|
| 1 | +import sys |
| 2 | +import re |
| 3 | +import os |
| 4 | +import logging |
| 5 | + |
| 6 | +os.environ["LOG_LEVEL"] = logging.getLevelName(logging.INFO) |
| 7 | + |
| 8 | +if __package__: |
| 9 | + current_path = os.path.abspath(os.path.dirname(__file__)).replace('/' + str(__package__), '', 1) |
| 10 | +else: |
| 11 | + current_path = os.path.abspath(os.path.dirname(__file__)) |
| 12 | + |
| 13 | +if not current_path[-1] == '/': |
| 14 | + current_path += '/' |
| 15 | + |
| 16 | +ROOT_DIR = current_path.replace('scripts/migrations/mysql/', '') |
| 17 | + |
| 18 | +_REGISTERED_PATHS = False |
| 19 | + |
| 20 | + |
| 21 | +def register_paths(): |
| 22 | + global _REGISTERED_PATHS |
| 23 | + if not _REGISTERED_PATHS: |
| 24 | + # path fixes, define the priority of the modules search |
| 25 | + sys.path.insert(0, ROOT_DIR) |
| 26 | + sys.path.insert(0, ROOT_DIR + 'venv/') |
| 27 | + sys.path.insert(1, ROOT_DIR + 'chalicelib/') |
| 28 | + sys.path.insert(1, ROOT_DIR + 'flask_app/') |
| 29 | + sys.path.insert(1, ROOT_DIR + 'lambda_app/') |
| 30 | + sys.path.insert(2, ROOT_DIR + 'vendor/') |
| 31 | + _REGISTERED_PATHS = True |
| 32 | + pass |
| 33 | + |
| 34 | + |
| 35 | +# register the paths |
| 36 | +register_paths() |
| 37 | + |
| 38 | +from lambda_app.logging import get_logger |
| 39 | +from lambda_app.boot import reset, load_dot_env, load_env |
| 40 | +from lambda_app.config import reset as reset_config, get_config |
| 41 | +from lambda_app.database.mysql import get_connection |
| 42 | + |
| 43 | +logger = get_logger() |
| 44 | +logger.info("ROOT_DIR " + ROOT_DIR) |
| 45 | + |
| 46 | + |
| 47 | +if __package__: |
| 48 | + current_path = os.path.abspath(os.path.dirname(__file__)).replace('/' + str(__package__), '', 1) |
| 49 | +else: |
| 50 | + current_path = os.path.abspath(os.path.dirname(__file__)) |
| 51 | + |
| 52 | +if not current_path[-1] == '/': |
| 53 | + current_path += '/' |
| 54 | + |
| 55 | + |
| 56 | +class ConnectionHelper: |
| 57 | + @staticmethod |
| 58 | + def get_mysql_local_connection(): |
| 59 | + return get_connection() |
| 60 | + |
| 61 | + |
| 62 | +class MySQLHelper: |
| 63 | + |
| 64 | + @staticmethod |
| 65 | + def get_connection(): |
| 66 | + """ |
| 67 | + :return: |
| 68 | + """ |
| 69 | + return ConnectionHelper.get_mysql_local_connection() |
| 70 | + |
| 71 | + @staticmethod |
| 72 | + def drop_table(connection, table_name): |
| 73 | + result = True |
| 74 | + try: |
| 75 | + # connection = MySQLHelper.get_connection() |
| 76 | + connection.connect() |
| 77 | + |
| 78 | + content = "DROP TABLE IF EXISTS " + table_name |
| 79 | + print(f"Deleting {table_name}...") |
| 80 | + with connection.cursor() as cursor: |
| 81 | + cursor.execute(content) |
| 82 | + print(f"{table_name} deleted") |
| 83 | + |
| 84 | + except Exception as err: |
| 85 | + print(f"{table_name} not exists") |
| 86 | + try: |
| 87 | + connection.close() |
| 88 | + except Exception as err: |
| 89 | + pass |
| 90 | + return result |
| 91 | + |
| 92 | + @staticmethod |
| 93 | + def sow_table(connection, table_name, file_name): |
| 94 | + result = False |
| 95 | + cnt = 0 |
| 96 | + seeder_file = None |
| 97 | + try: |
| 98 | + connection.connect() |
| 99 | + seeder_file = open(file_name, 'r') |
| 100 | + line = seeder_file.readline().strip().replace(';', '') |
| 101 | + cnt = 0 |
| 102 | + try: |
| 103 | + while line: |
| 104 | + cnt += 1 |
| 105 | + with connection.cursor() as cursor: |
| 106 | + if line != '': |
| 107 | + cursor.execute(line,) |
| 108 | + line = seeder_file.readline().strip().replace(';', '') |
| 109 | + |
| 110 | + connection.commit() |
| 111 | + result = True |
| 112 | + except Exception as ex: |
| 113 | + result = False |
| 114 | + connection.rollback() |
| 115 | + print(ex) |
| 116 | + except Exception as ex: |
| 117 | + result = False |
| 118 | + print(ex) |
| 119 | + finally: |
| 120 | + if seeder_file is not None: |
| 121 | + seeder_file.close() |
| 122 | + |
| 123 | + print("Total of rows affected: %d" % cnt) |
| 124 | + try: |
| 125 | + connection.close() |
| 126 | + except Exception as err: |
| 127 | + pass |
| 128 | + return result |
| 129 | + |
| 130 | + @staticmethod |
| 131 | + def create_table(connection, table_name, file_name): |
| 132 | + result = False |
| 133 | + |
| 134 | + connection.connect() |
| 135 | + try: |
| 136 | + sql = 'SELECT table_name FROM information_schema.tables WHERE table_schema = %s' |
| 137 | + with connection.cursor() as cursor: |
| 138 | + cursor.execute(sql, (table_name,)) |
| 139 | + table_exists = cursor.fetchone() |
| 140 | + except Exception as err: |
| 141 | + table_exists = False |
| 142 | + |
| 143 | + if not table_exists: |
| 144 | + sql_file = open(file_name, 'r') |
| 145 | + create_table = sql_file.read() |
| 146 | + sql_file.close() |
| 147 | + |
| 148 | + try: |
| 149 | + with connection.cursor() as cursor: |
| 150 | + result = cursor.execute(create_table) |
| 151 | + print(f"Creating {table_name}...") |
| 152 | + except Exception as err: |
| 153 | + result = False |
| 154 | + print(f"Not created {table_name}...") |
| 155 | + else: |
| 156 | + print(f'Table {table_name} already exists') |
| 157 | + try: |
| 158 | + connection.close() |
| 159 | + except Exception as err: |
| 160 | + pass |
| 161 | + return result |
| 162 | + |
| 163 | + |
| 164 | +command = None |
| 165 | +sql_file = None |
| 166 | +try: |
| 167 | + sql_file = sys.argv[1] |
| 168 | +except IndexError as err: |
| 169 | + logger.error(err) |
| 170 | + exit('Filename required') |
| 171 | + |
| 172 | +try: |
| 173 | + logger.info("Load configuration") |
| 174 | + # reset config and env |
| 175 | + reset() |
| 176 | + reset_config() |
| 177 | + # load integration |
| 178 | + APP_TYPE = os.environ['APP_TYPE'] |
| 179 | + if APP_TYPE == 'Flask': |
| 180 | + load_dot_env() |
| 181 | + else: |
| 182 | + load_env() |
| 183 | + config = get_config() |
| 184 | +except IndexError as err: |
| 185 | + logger.error(err) |
| 186 | + exit('Filename required') |
| 187 | + |
| 188 | + |
| 189 | +class Command: |
| 190 | + CREATE_TABLE = 'CREATE_TABLE' |
| 191 | + INSERT_INTO = 'INSERT_INTO' |
| 192 | + |
| 193 | + |
| 194 | +def get_commnad(line): |
| 195 | + command = None |
| 196 | + if "CREATE TABLE" in line: |
| 197 | + command = Command.CREATE_TABLE |
| 198 | + if "INSERT INTO" in line: |
| 199 | + command = Command.INSERT_INTO |
| 200 | + return command |
| 201 | + |
| 202 | + |
| 203 | +def get_table_name(content, only_table=False): |
| 204 | + table_name = None |
| 205 | + rx = re.search("CREATE TABLE (IF NOT EXISTS )?([\w.]+)", content) |
| 206 | + if not rx: |
| 207 | + rx = re.search("INSERT INTO ([\w.]+)", content) |
| 208 | + if rx: |
| 209 | + groups = rx.groups() |
| 210 | + if len(groups) > 0: |
| 211 | + table_name = groups[len(groups)-1] |
| 212 | + |
| 213 | + if table_name and only_table: |
| 214 | + table_name_parts = table_name.split('.') |
| 215 | + table_name = table_name_parts[len(table_name_parts)-1] |
| 216 | + return table_name |
| 217 | + |
| 218 | + |
| 219 | +try: |
| 220 | + connection = MySQLHelper.get_connection() |
| 221 | + with open(ROOT_DIR + sql_file, 'r') as f: |
| 222 | + content = f.read() |
| 223 | + f.close() |
| 224 | + |
| 225 | + command = get_commnad(content) |
| 226 | + file_name = ROOT_DIR + sql_file |
| 227 | + if command == Command.CREATE_TABLE: |
| 228 | + table_name = get_table_name(content) |
| 229 | + created = MySQLHelper.create_table(connection, table_name, file_name) |
| 230 | + if created is not False: |
| 231 | + logger.info("Table created") |
| 232 | + if command == Command.INSERT_INTO: |
| 233 | + table_name = get_table_name(content) |
| 234 | + sow = MySQLHelper.sow_table(connection, table_name, file_name) |
| 235 | + if sow is not False: |
| 236 | + logger.info("Table sow") |
| 237 | + |
| 238 | + |
| 239 | +except Exception as err: |
| 240 | + logger.error(err) |
| 241 | + exit('File not found') |
0 commit comments