thoth-dbmanager 0.5.0__py3-none-any.whl → 0.5.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,165 +0,0 @@
1
- """
2
- MySQL adapter for Thoth SQL Database Manager.
3
- """
4
-
5
- from typing import Any, Dict, List, Optional, Union
6
- from sqlalchemy import create_engine, text
7
- from sqlalchemy.engine import Engine
8
- from sqlalchemy.exc import SQLAlchemyError
9
-
10
- from ..core.interfaces import DbAdapter
11
-
12
-
13
- class MySQLAdapter(DbAdapter):
14
- """MySQL database adapter."""
15
-
16
- def __init__(self, connection_string: str, **kwargs: Any) -> None:
17
- """
18
- Initialize MySQL adapter.
19
-
20
- Args:
21
- connection_string: MySQL connection string
22
- **kwargs: Additional connection parameters
23
- """
24
- self.connection_string = connection_string
25
- self.engine = None
26
- self.connection_params = kwargs
27
-
28
- def connect(self) -> None:
29
- """Establish database connection."""
30
- try:
31
- self.engine = create_engine(
32
- self.connection_string,
33
- pool_pre_ping=True,
34
- **self.connection_params
35
- )
36
- except Exception as e:
37
- raise ConnectionError(f"Failed to connect to MySQL: {e}")
38
-
39
- def disconnect(self) -> None:
40
- """Close database connection."""
41
- if self.engine:
42
- self.engine.dispose()
43
- self.engine = None
44
-
45
- def execute_query(self, query: str, params: Optional[Dict[str, Any]] = None) -> List[Dict[str, Any]]:
46
- """Execute a query and return results."""
47
- if not self.engine:
48
- self.connect()
49
-
50
- try:
51
- with self.engine.connect() as conn:
52
- result = conn.execute(text(query), params or {})
53
- return [dict(row._mapping) for row in result]
54
- except SQLAlchemyError as e:
55
- raise RuntimeError(f"MySQL query failed: {e}")
56
-
57
- def execute_update(self, query: str, params: Optional[Dict[str, Any]] = None) -> int:
58
- """Execute an update query and return affected row count."""
59
- if not self.engine:
60
- self.connect()
61
-
62
- try:
63
- with self.engine.connect() as conn:
64
- result = conn.execute(text(query), params or {})
65
- conn.commit()
66
- return result.rowcount
67
- except SQLAlchemyError as e:
68
- raise RuntimeError(f"MySQL update failed: {e}")
69
-
70
- def get_tables(self) -> List[str]:
71
- """Get list of tables in the database."""
72
- query = "SHOW TABLES"
73
- result = self.execute_query(query)
74
- return [list(row.values())[0] for row in result]
75
-
76
- def get_table_schema(self, table_name: str) -> Dict[str, Any]:
77
- """Get schema information for a specific table."""
78
- query = f"DESCRIBE {table_name}"
79
- columns = self.execute_query(query)
80
-
81
- schema = {
82
- 'table_name': table_name,
83
- 'columns': []
84
- }
85
-
86
- for col in columns:
87
- schema['columns'].append({
88
- 'name': col['Field'],
89
- 'type': col['Type'],
90
- 'nullable': col['Null'] == 'YES',
91
- 'default': col['Default'],
92
- 'primary_key': col['Key'] == 'PRI'
93
- })
94
-
95
- return schema
96
-
97
- def get_indexes(self, table_name: str) -> List[Dict[str, Any]]:
98
- """Get index information for a table."""
99
- query = f"SHOW INDEX FROM {table_name}"
100
- indexes = self.execute_query(query)
101
-
102
- result = []
103
- for idx in indexes:
104
- result.append({
105
- 'name': idx['Key_name'],
106
- 'column': idx['Column_name'],
107
- 'unique': not idx['Non_unique'],
108
- 'type': idx['Index_type']
109
- })
110
-
111
- return result
112
-
113
- def get_foreign_keys(self, table_name: str) -> List[Dict[str, Any]]:
114
- """Get foreign key information for a table."""
115
- query = f"""
116
- SELECT
117
- CONSTRAINT_NAME as name,
118
- COLUMN_NAME as column_name,
119
- REFERENCED_TABLE_NAME as referenced_table,
120
- REFERENCED_COLUMN_NAME as referenced_column
121
- FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE
122
- WHERE TABLE_NAME = '{table_name}'
123
- AND REFERENCED_TABLE_NAME IS NOT NULL
124
- """
125
-
126
- return self.execute_query(query)
127
-
128
- def create_table(self, table_name: str, schema: Dict[str, Any]) -> None:
129
- """Create a new table with the given schema."""
130
- columns = []
131
- for col in schema.get('columns', []):
132
- col_def = f"{col['name']} {col['type']}"
133
- if not col.get('nullable', True):
134
- col_def += " NOT NULL"
135
- if col.get('default') is not None:
136
- col_def += f" DEFAULT {col['default']}"
137
- if col.get('primary_key'):
138
- col_def += " PRIMARY KEY"
139
- columns.append(col_def)
140
-
141
- query = f"CREATE TABLE {table_name} ({', '.join(columns)})"
142
- self.execute_update(query)
143
-
144
- def drop_table(self, table_name: str) -> None:
145
- """Drop a table."""
146
- query = f"DROP TABLE IF EXISTS {table_name}"
147
- self.execute_update(query)
148
-
149
- def table_exists(self, table_name: str) -> bool:
150
- """Check if a table exists."""
151
- query = f"""
152
- SELECT COUNT(*) as count
153
- FROM INFORMATION_SCHEMA.TABLES
154
- WHERE TABLE_NAME = '{table_name}'
155
- """
156
- result = self.execute_query(query)
157
- return result[0]['count'] > 0
158
-
159
- def get_connection_info(self) -> Dict[str, Any]:
160
- """Get connection information."""
161
- return {
162
- 'type': 'mysql',
163
- 'connection_string': self.connection_string,
164
- 'connected': self.engine is not None
165
- }