|
| 1 | +from typing import List |
| 2 | +from urllib.parse import urlparse |
| 3 | + |
| 4 | +import mariadb |
| 5 | +import pandas as pd |
| 6 | + |
| 7 | +from .._utils import logger |
| 8 | +from .._utils.constants import SUCCESSFULLY_CONNECTED_TO_DB_CONSTANT, ERROR_CONNECTING_TO_DB_CONSTANT, \ |
| 9 | + INVALID_DB_CONNECTION_OBJECT, ERROR_WHILE_RUNNING_QUERY, MARIADB_DB_TABLES_INFO_SCHEMA_QUERY, \ |
| 10 | + MARIADB_SHOW_DATABASE_QUERY, MARIADB_SHOW_CREATE_TABLE_QUERY, CONNECTION_ESTABLISH_ERROR_CONSTANT |
| 11 | +from . import IDatabase |
| 12 | + |
| 13 | +log = logger.init_loggers("MariaDB") |
| 14 | + |
| 15 | + |
| 16 | +class MariaDB(IDatabase): |
| 17 | + def create_connection(self, url: str, **kwargs) -> any: |
| 18 | + url = urlparse(url) |
| 19 | + try: |
| 20 | + connection_params = { |
| 21 | + 'host': url.hostname, |
| 22 | + 'port': url.port or int(kwargs.get('port', 3306)), |
| 23 | + 'user': url.username, |
| 24 | + 'password': url.password, |
| 25 | + 'database': url.path.lstrip('/') if url.path else None, |
| 26 | + 'autocommit': True, |
| 27 | + } |
| 28 | + |
| 29 | + connection_params = {k: v for k, v in connection_params.items() if v is not None} |
| 30 | + connection_params.update({k: v for k, v in kwargs.items() if k not in ['port']}) |
| 31 | + |
| 32 | + conn = mariadb.connect(**connection_params) |
| 33 | + log.info(SUCCESSFULLY_CONNECTED_TO_DB_CONSTANT.format("MariaDB")) |
| 34 | + return conn |
| 35 | + |
| 36 | + except mariadb.Error as e: |
| 37 | + log.info(ERROR_CONNECTING_TO_DB_CONSTANT.format("MariaDB", str(e))) |
| 38 | + return None |
| 39 | + |
| 40 | + def validate_connection(self, connection: any) -> None: |
| 41 | + if connection is None: |
| 42 | + raise ValueError(CONNECTION_ESTABLISH_ERROR_CONSTANT) |
| 43 | + if not hasattr(connection, 'cursor'): |
| 44 | + raise ValueError(INVALID_DB_CONNECTION_OBJECT.format("MariaDB")) |
| 45 | + |
| 46 | + def execute_sql(self, connection, sql: str) -> pd.DataFrame: |
| 47 | + try: |
| 48 | + self.validate_connection(connection) |
| 49 | + cursor = connection.cursor() |
| 50 | + cursor.execute(sql) |
| 51 | + |
| 52 | + if sql.strip().upper().startswith(('CREATE', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER')): |
| 53 | + connection.commit() |
| 54 | + cursor.close() |
| 55 | + return pd.DataFrame() |
| 56 | + |
| 57 | + results = cursor.fetchall() |
| 58 | + if cursor.description: |
| 59 | + column_names = [i[0] for i in cursor.description] |
| 60 | + df = pd.DataFrame(results, columns=column_names) |
| 61 | + else: |
| 62 | + df = pd.DataFrame() |
| 63 | + cursor.close() |
| 64 | + return df |
| 65 | + except mariadb.Error as e: |
| 66 | + log.info(ERROR_WHILE_RUNNING_QUERY.format(e)) |
| 67 | + return pd.DataFrame() |
| 68 | + |
| 69 | + def get_databases(self, connection) -> List[str]: |
| 70 | + try: |
| 71 | + self.validate_connection(connection) |
| 72 | + df_databases = self.execute_sql(connection=connection, sql=MARIADB_SHOW_DATABASE_QUERY) |
| 73 | + except Exception as e: |
| 74 | + log.info(e) |
| 75 | + return [] |
| 76 | + return df_databases["Database"].unique().tolist() |
| 77 | + |
| 78 | + def get_table_names(self, connection, database: str) -> pd.DataFrame: |
| 79 | + self.validate_connection(connection) |
| 80 | + df_tables = self.execute_sql(connection, MARIADB_DB_TABLES_INFO_SCHEMA_QUERY.format(database)) |
| 81 | + return df_tables |
| 82 | + |
| 83 | + def get_all_ddls(self, connection, database: str) -> pd.DataFrame: |
| 84 | + self.validate_connection(connection) |
| 85 | + df_tables = self.get_table_names(connection, database) |
| 86 | + df_ddl = pd.DataFrame(columns=['Table', 'DDL']) |
| 87 | + for index, row in df_tables.iterrows(): |
| 88 | + table_name = row.get('TABLE_NAME') or row.get('table_name') |
| 89 | + if table_name: |
| 90 | + ddl_df = self.get_ddl(connection, table_name) |
| 91 | + df_ddl = df_ddl._append({'Table': table_name, 'DDL': ddl_df}, ignore_index=True) |
| 92 | + return df_ddl |
| 93 | + |
| 94 | + def get_ddl(self, connection: any, table_name: str, **kwargs) -> str: |
| 95 | + ddl_df = self.execute_sql(connection, MARIADB_SHOW_CREATE_TABLE_QUERY.format(table_name)) |
| 96 | + return ddl_df["Create Table"].iloc[0] |
| 97 | + |
| 98 | + def get_dialect(self) -> str: |
| 99 | + return 'mysql' |
0 commit comments