|
| 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 | + """ |
| 19 | + A method to create a connection with MariaDB database. |
| 20 | +
|
| 21 | + Parameters: |
| 22 | + url (str): The URL in the format mariadb://username:password@host:port/database_name |
| 23 | + **kwargs: Additional keyword arguments for the connection. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + any: The connection object. |
| 27 | + """ |
| 28 | + url = urlparse(url) |
| 29 | + try: |
| 30 | + # Use official MariaDB connector |
| 31 | + connection_params = { |
| 32 | + 'host': url.hostname, |
| 33 | + 'port': url.port or int(kwargs.get('port', 3306)), |
| 34 | + 'user': url.username, |
| 35 | + 'password': url.password, |
| 36 | + 'database': url.path.lstrip('/') if url.path else None, |
| 37 | + 'autocommit': True, |
| 38 | + } |
| 39 | + |
| 40 | + # Remove None values and add any additional kwargs |
| 41 | + connection_params = {k: v for k, v in connection_params.items() if v is not None} |
| 42 | + connection_params.update({k: v for k, v in kwargs.items() if k not in ['port']}) |
| 43 | + |
| 44 | + conn = mariadb.connect(**connection_params) |
| 45 | + |
| 46 | + log.info(SUCCESSFULLY_CONNECTED_TO_DB_CONSTANT.format("MariaDB")) |
| 47 | + return conn |
| 48 | + |
| 49 | + except mariadb.Error as e: |
| 50 | + error_msg = str(e) |
| 51 | + log.info(ERROR_CONNECTING_TO_DB_CONSTANT.format("MariaDB", error_msg)) |
| 52 | + return None |
| 53 | + |
| 54 | + def validate_connection(self, connection: any) -> None: |
| 55 | + """ |
| 56 | + A function that validates if the provided connection is a MariaDB connection. |
| 57 | +
|
| 58 | + Parameters: |
| 59 | + connection: The connection object for accessing the database. |
| 60 | +
|
| 61 | + Raises: |
| 62 | + ValueError: If the provided connection is not a MariaDB connection. |
| 63 | +
|
| 64 | + Returns: |
| 65 | + None |
| 66 | + """ |
| 67 | + if connection is None: |
| 68 | + raise ValueError(CONNECTION_ESTABLISH_ERROR_CONSTANT) |
| 69 | + |
| 70 | + # MariaDB connection validation (using PyMySQL connection) |
| 71 | + if not hasattr(connection, 'cursor'): |
| 72 | + raise ValueError(INVALID_DB_CONNECTION_OBJECT.format("MariaDB")) |
| 73 | + |
| 74 | + def execute_sql(self, connection, sql: str) -> pd.DataFrame: |
| 75 | + """ |
| 76 | + A method to execute SQL on the database. |
| 77 | +
|
| 78 | + Parameters: |
| 79 | + connection (any): The connection object. |
| 80 | + sql (str): The SQL to be executed. |
| 81 | +
|
| 82 | + Returns: |
| 83 | + pd.DataFrame: The result of the SQL query. |
| 84 | + """ |
| 85 | + try: |
| 86 | + self.validate_connection(connection) |
| 87 | + cursor = connection.cursor() |
| 88 | + cursor.execute(sql) |
| 89 | + |
| 90 | + # For DDL/DML statements (CREATE, INSERT, UPDATE, DELETE), commit and return empty DataFrame |
| 91 | + if sql.strip().upper().startswith(('CREATE', 'INSERT', 'UPDATE', 'DELETE', 'DROP', 'ALTER')): |
| 92 | + connection.commit() |
| 93 | + cursor.close() |
| 94 | + return pd.DataFrame() |
| 95 | + |
| 96 | + # For SELECT statements, fetch results |
| 97 | + results = cursor.fetchall() |
| 98 | + if cursor.description: |
| 99 | + column_names = [i[0] for i in cursor.description] |
| 100 | + df = pd.DataFrame(results, columns=column_names) |
| 101 | + else: |
| 102 | + df = pd.DataFrame() |
| 103 | + cursor.close() |
| 104 | + return df |
| 105 | + except mariadb.Error as e: |
| 106 | + log.info(ERROR_WHILE_RUNNING_QUERY.format(e)) |
| 107 | + return pd.DataFrame() |
| 108 | + |
| 109 | + def get_databases(self, connection) -> List[str]: |
| 110 | + """ |
| 111 | + Get a list of databases from the given connection and SQL query. |
| 112 | +
|
| 113 | + Parameters: |
| 114 | + connection (object): The connection object for the database. |
| 115 | +
|
| 116 | + Returns: |
| 117 | + List[str]: A list of unique database names. |
| 118 | + """ |
| 119 | + try: |
| 120 | + self.validate_connection(connection) |
| 121 | + df_databases = self.execute_sql(connection=connection, sql=MARIADB_SHOW_DATABASE_QUERY) |
| 122 | + except Exception as e: |
| 123 | + log.info(e) |
| 124 | + return [] |
| 125 | + |
| 126 | + return df_databases["Database"].unique().tolist() |
| 127 | + |
| 128 | + def get_table_names(self, connection, database: str) -> pd.DataFrame: |
| 129 | + """ |
| 130 | + Retrieves the tables from the information schema for the specified database. |
| 131 | +
|
| 132 | + Parameters: |
| 133 | + connection: The database connection object. |
| 134 | + database (str): The name of the database. |
| 135 | +
|
| 136 | + Returns: |
| 137 | + DataFrame: A pandas DataFrame containing the table names from the information schema. |
| 138 | + """ |
| 139 | + self.validate_connection(connection) |
| 140 | + df_tables = self.execute_sql(connection, MARIADB_DB_TABLES_INFO_SCHEMA_QUERY.format(database)) |
| 141 | + return df_tables |
| 142 | + |
| 143 | + def get_all_ddls(self, connection, database: str) -> pd.DataFrame: |
| 144 | + """ |
| 145 | + Get all DDLs from the specified database using the provided connection object. |
| 146 | +
|
| 147 | + Parameters: |
| 148 | + connection (any): The connection object. |
| 149 | + database (str): The name of the database. |
| 150 | +
|
| 151 | + Returns: |
| 152 | + pd.DataFrame: A pandas DataFrame containing the DDLs for each table in the specified database. |
| 153 | + """ |
| 154 | + self.validate_connection(connection) |
| 155 | + df_tables = self.get_table_names(connection, database) |
| 156 | + df_ddl = pd.DataFrame(columns=['Table', 'DDL']) |
| 157 | + for index, row in df_tables.iterrows(): |
| 158 | + # Handle both uppercase and lowercase column names |
| 159 | + table_name = row.get('TABLE_NAME') or row.get('table_name') |
| 160 | + if table_name: |
| 161 | + ddl_df = self.get_ddl(connection, table_name) |
| 162 | + df_ddl = df_ddl._append({'Table': table_name, 'DDL': ddl_df}, ignore_index=True) |
| 163 | + return df_ddl |
| 164 | + |
| 165 | + def get_ddl(self, connection: any, table_name: str, **kwargs) -> str: |
| 166 | + """ |
| 167 | + A method to get the DDL for the table. |
| 168 | +
|
| 169 | + Parameters: |
| 170 | + connection (any): The connection object. |
| 171 | + table_name (str): The name of the table. |
| 172 | + **kwargs: Additional keyword arguments. |
| 173 | +
|
| 174 | + Returns: |
| 175 | + str: The DDL for the table. |
| 176 | + """ |
| 177 | + ddl_df = self.execute_sql(connection, MARIADB_SHOW_CREATE_TABLE_QUERY.format(table_name)) |
| 178 | + return ddl_df["Create Table"].iloc[0] |
| 179 | + |
| 180 | + def get_dialect(self) -> str: |
| 181 | + """ |
| 182 | + A method to get the dialect of the database. |
| 183 | +
|
| 184 | + Returns: |
| 185 | + str: The dialect of the database. |
| 186 | + """ |
| 187 | + return 'mysql' |
0 commit comments