asqueel-migration 0.1.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.
- asqueel_migration/__init__.py +81 -0
- asqueel_migration/adapters/__init__.py +26 -0
- asqueel_migration/adapters/mssql_adapter.py +277 -0
- asqueel_migration/adapters/mysql_adapter.py +283 -0
- asqueel_migration/adapters/pg_adapter.py +244 -0
- asqueel_migration/adapters/sqlite_adapter.py +333 -0
- asqueel_migration/app.py +229 -0
- asqueel_migration/cli.py +136 -0
- asqueel_migration/command_builder.py +1018 -0
- asqueel_migration/database.py +196 -0
- asqueel_migration/diff_engine.py +220 -0
- asqueel_migration/editor_service.py +65 -0
- asqueel_migration/exceptions.py +63 -0
- asqueel_migration/executor.py +364 -0
- asqueel_migration/json_producer.py +177 -0
- asqueel_migration/migrator.py +321 -0
- asqueel_migration/py.typed +0 -0
- asqueel_migration/readers/__init__.py +34 -0
- asqueel_migration/readers/base_reader.py +299 -0
- asqueel_migration/readers/mssql_reader.py +457 -0
- asqueel_migration/readers/mysql_reader.py +372 -0
- asqueel_migration/readers/pg_reader.py +442 -0
- asqueel_migration/readers/sqlite_reader.py +319 -0
- asqueel_migration/schemas/sql_model-1.0.xsd +210 -0
- asqueel_migration/schemas/structure-1.0.json +239 -0
- asqueel_migration/structures.py +459 -0
- asqueel_migration/validation.py +275 -0
- asqueel_migration/writers/__init__.py +32 -0
- asqueel_migration/writers/base_writer.py +353 -0
- asqueel_migration/writers/mssql_writer.py +323 -0
- asqueel_migration/writers/mysql_writer.py +411 -0
- asqueel_migration/writers/pg_writer.py +525 -0
- asqueel_migration/writers/sqlite_writer.py +234 -0
- asqueel_migration/xml_producer.py +356 -0
- asqueel_migration-0.1.2.dist-info/METADATA +274 -0
- asqueel_migration-0.1.2.dist-info/RECORD +40 -0
- asqueel_migration-0.1.2.dist-info/WHEEL +4 -0
- asqueel_migration-0.1.2.dist-info/entry_points.txt +2 -0
- asqueel_migration-0.1.2.dist-info/licenses/LICENSE +201 -0
- asqueel_migration-0.1.2.dist-info/licenses/NOTICE +11 -0
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# Copyright (c) 2025 Softwell Srl, Milano, Italy
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
asqueel-migration: Database schema migration engine.
|
|
6
|
+
|
|
7
|
+
Compares a desired database structure (from any ORM or schema definition)
|
|
8
|
+
with the actual database structure (from PostgreSQL, SQLite, etc.)
|
|
9
|
+
and generates the SQL commands needed to align them.
|
|
10
|
+
|
|
11
|
+
The engine is ORM-agnostic: any framework can use it by providing
|
|
12
|
+
its schema in the normalized JSON format defined in :mod:`structures`.
|
|
13
|
+
|
|
14
|
+
Main components:
|
|
15
|
+
|
|
16
|
+
- :class:`SqlMigrator`: Orchestrator that coordinates the full migration flow.
|
|
17
|
+
- :mod:`readers`: Database-specific introspection (read actual DB structure).
|
|
18
|
+
- :mod:`writers`: Database-specific SQL generation (write migration commands).
|
|
19
|
+
- :mod:`adapters`: Concrete Database/BaseAdapter pairs per dialect.
|
|
20
|
+
- :mod:`structures`: Normalized JSON format (the contract between components).
|
|
21
|
+
- :mod:`diff_engine`: Structure comparison using dictdiffer.
|
|
22
|
+
- :mod:`command_builder`: SQL command generation from diff events.
|
|
23
|
+
- :mod:`executor`: SQL assembly and execution.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
from asqueel_migration.adapters import (
|
|
27
|
+
MssqlAdapter,
|
|
28
|
+
MssqlDatabase,
|
|
29
|
+
MysqlAdapter,
|
|
30
|
+
MysqlDatabase,
|
|
31
|
+
PgAdapter,
|
|
32
|
+
PgDatabase,
|
|
33
|
+
SqliteAdapter,
|
|
34
|
+
SqliteDatabase,
|
|
35
|
+
)
|
|
36
|
+
from asqueel_migration.exceptions import MigrationExecutionError
|
|
37
|
+
from asqueel_migration.json_producer import JsonStructureProducer
|
|
38
|
+
from asqueel_migration.migrator import SqlMigrator
|
|
39
|
+
from asqueel_migration.structures import (
|
|
40
|
+
FORMAT_VERSION,
|
|
41
|
+
new_column_item,
|
|
42
|
+
new_constraint_item,
|
|
43
|
+
new_event_trigger_item,
|
|
44
|
+
new_extension_item,
|
|
45
|
+
new_index_item,
|
|
46
|
+
new_relation_item,
|
|
47
|
+
new_schema_item,
|
|
48
|
+
new_structure_root,
|
|
49
|
+
new_table_item,
|
|
50
|
+
)
|
|
51
|
+
from asqueel_migration.validation import StructureValidator
|
|
52
|
+
from asqueel_migration.xml_producer import XmlStructureProducer, struct_to_xml
|
|
53
|
+
|
|
54
|
+
__version__ = "0.1.2"
|
|
55
|
+
|
|
56
|
+
__all__ = [
|
|
57
|
+
"FORMAT_VERSION",
|
|
58
|
+
"JsonStructureProducer",
|
|
59
|
+
"MssqlAdapter",
|
|
60
|
+
"MssqlDatabase",
|
|
61
|
+
"MigrationExecutionError",
|
|
62
|
+
"MysqlAdapter",
|
|
63
|
+
"MysqlDatabase",
|
|
64
|
+
"PgAdapter",
|
|
65
|
+
"PgDatabase",
|
|
66
|
+
"SqliteAdapter",
|
|
67
|
+
"SqliteDatabase",
|
|
68
|
+
"SqlMigrator",
|
|
69
|
+
"StructureValidator",
|
|
70
|
+
"XmlStructureProducer",
|
|
71
|
+
"new_column_item",
|
|
72
|
+
"new_constraint_item",
|
|
73
|
+
"new_event_trigger_item",
|
|
74
|
+
"new_extension_item",
|
|
75
|
+
"new_index_item",
|
|
76
|
+
"new_relation_item",
|
|
77
|
+
"new_schema_item",
|
|
78
|
+
"new_structure_root",
|
|
79
|
+
"new_table_item",
|
|
80
|
+
"struct_to_xml",
|
|
81
|
+
]
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
# Copyright (c) 2025 Softwell Srl, Milano, Italy
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
adapters - Concrete Database/BaseAdapter pairs per dialect
|
|
6
|
+
===========================================================
|
|
7
|
+
|
|
8
|
+
Each dialect contributes one module: PostgreSQL, SQLite, MySQL,
|
|
9
|
+
Microsoft SQL Server.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from asqueel_migration.adapters.mssql_adapter import MssqlAdapter, MssqlDatabase
|
|
13
|
+
from asqueel_migration.adapters.mysql_adapter import MysqlAdapter, MysqlDatabase
|
|
14
|
+
from asqueel_migration.adapters.pg_adapter import PgAdapter, PgDatabase
|
|
15
|
+
from asqueel_migration.adapters.sqlite_adapter import SqliteAdapter, SqliteDatabase
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"MssqlAdapter",
|
|
19
|
+
"MssqlDatabase",
|
|
20
|
+
"MysqlAdapter",
|
|
21
|
+
"MysqlDatabase",
|
|
22
|
+
"PgAdapter",
|
|
23
|
+
"PgDatabase",
|
|
24
|
+
"SqliteAdapter",
|
|
25
|
+
"SqliteDatabase",
|
|
26
|
+
]
|
|
@@ -0,0 +1,277 @@
|
|
|
1
|
+
# Copyright (c) 2025 Softwell Srl, Milano, Italy
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
mssql_adapter.py - Concrete Microsoft SQL Server adapter/database pair
|
|
6
|
+
=======================================================================
|
|
7
|
+
|
|
8
|
+
``MssqlAdapter`` wires DDL generation to :class:`MssqlWriter` and
|
|
9
|
+
introspection to :class:`MssqlReader`; ``MssqlDatabase`` is the
|
|
10
|
+
:class:`Database` facade consumers instantiate. pymssql is required at
|
|
11
|
+
connection time only (optional ``mssql`` extra).
|
|
12
|
+
|
|
13
|
+
``execute`` splits the incoming SQL script into individual statements and
|
|
14
|
+
runs them one by one on a single connection: this satisfies the T-SQL
|
|
15
|
+
rule that ``CREATE SCHEMA`` must be alone in its batch while retaining one
|
|
16
|
+
transaction for the complete migration DDL unit.
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from asqueel_migration.database import BaseAdapter, Database
|
|
20
|
+
from asqueel_migration.exceptions import (
|
|
21
|
+
NonExistingDbException,
|
|
22
|
+
SqlConnectionException,
|
|
23
|
+
SqlMigrationError,
|
|
24
|
+
)
|
|
25
|
+
from asqueel_migration.readers import MssqlReader
|
|
26
|
+
from asqueel_migration.writers import MssqlWriter
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class MssqlAdapter(BaseAdapter):
|
|
30
|
+
"""SQL Server adapter: MssqlWriter for DDL, MssqlReader for introspection, pymssql for execution."""
|
|
31
|
+
|
|
32
|
+
TYPE_CONVERSIONS = MssqlWriter.TYPE_CONVERSIONS
|
|
33
|
+
supports_atomic_ddl = True
|
|
34
|
+
|
|
35
|
+
def __init__(self, database):
|
|
36
|
+
self.database = database
|
|
37
|
+
self.writer = MssqlWriter()
|
|
38
|
+
self._reader = None
|
|
39
|
+
|
|
40
|
+
# -- Connections ---------------------------------------------------------
|
|
41
|
+
|
|
42
|
+
def connect(self, manager=False, autocommit=False):
|
|
43
|
+
"""Open a pymssql connection with the #655 error taxonomy.
|
|
44
|
+
|
|
45
|
+
A missing database (message contains "Cannot open database") raises
|
|
46
|
+
:class:`NonExistingDbException`; any other failure raises
|
|
47
|
+
:class:`SqlConnectionException`. ``SET QUOTED_IDENTIFIER ON`` is
|
|
48
|
+
issued so double-quoted identifiers parse consistently.
|
|
49
|
+
"""
|
|
50
|
+
import pymssql # optional dependency (mssql extra)
|
|
51
|
+
params = dict(self.database.connection_params(manager=manager))
|
|
52
|
+
dbname = params.pop('dbname', None)
|
|
53
|
+
if dbname is not None:
|
|
54
|
+
params['database'] = dbname
|
|
55
|
+
try:
|
|
56
|
+
connection = pymssql.connect(autocommit=autocommit, **params)
|
|
57
|
+
except pymssql.OperationalError as error:
|
|
58
|
+
if 'cannot open database' in str(error).lower():
|
|
59
|
+
raise NonExistingDbException(self.database.get_dbname()) from error
|
|
60
|
+
raise SqlConnectionException(
|
|
61
|
+
self.database.get_dbname(), original_error=error
|
|
62
|
+
) from error
|
|
63
|
+
with connection.cursor() as cursor:
|
|
64
|
+
cursor.execute('SET QUOTED_IDENTIFIER ON')
|
|
65
|
+
return connection
|
|
66
|
+
|
|
67
|
+
def split_statements(self, sql):
|
|
68
|
+
"""Split a SQL script into individual statements.
|
|
69
|
+
|
|
70
|
+
Statements are separated by a ``;`` at end of line; empty fragments
|
|
71
|
+
are ignored. T-SQL cannot batch several DDL statements (e.g.
|
|
72
|
+
``CREATE SCHEMA``) together, so each is executed on its own.
|
|
73
|
+
"""
|
|
74
|
+
statements = []
|
|
75
|
+
for chunk in sql.split(';\n'):
|
|
76
|
+
statement = chunk.strip().rstrip(';').strip()
|
|
77
|
+
if statement:
|
|
78
|
+
statements.append(statement)
|
|
79
|
+
return statements
|
|
80
|
+
|
|
81
|
+
def execute(self, sql, autoCommit=False, manager=False):
|
|
82
|
+
"""Run a (possibly multi-statement) SQL script on a fresh connection.
|
|
83
|
+
|
|
84
|
+
The script is split into individual statements executed one by one;
|
|
85
|
+
manager connections use autocommit (CREATE DATABASE cannot run in a
|
|
86
|
+
transaction).
|
|
87
|
+
"""
|
|
88
|
+
autocommit = autoCommit or manager
|
|
89
|
+
connection = self.connect(manager=manager, autocommit=autocommit)
|
|
90
|
+
try:
|
|
91
|
+
with connection.cursor() as cursor:
|
|
92
|
+
for statement in self.split_statements(sql):
|
|
93
|
+
cursor.execute(statement)
|
|
94
|
+
if not autocommit:
|
|
95
|
+
connection.commit()
|
|
96
|
+
except Exception:
|
|
97
|
+
if not autocommit:
|
|
98
|
+
connection.rollback()
|
|
99
|
+
raise
|
|
100
|
+
finally:
|
|
101
|
+
connection.close()
|
|
102
|
+
|
|
103
|
+
# -- Introspection (delegated to MssqlReader) -----------------------------
|
|
104
|
+
|
|
105
|
+
@property
|
|
106
|
+
def reader(self):
|
|
107
|
+
"""Lazily build the MssqlReader bound to this database's connection params."""
|
|
108
|
+
if self._reader is None:
|
|
109
|
+
self._reader = MssqlReader(self.database.connection_params())
|
|
110
|
+
return self._reader
|
|
111
|
+
|
|
112
|
+
@property
|
|
113
|
+
def capabilities(self):
|
|
114
|
+
"""Dialect capability set, declared by the writer."""
|
|
115
|
+
return self.writer.CAPABILITIES
|
|
116
|
+
|
|
117
|
+
# -- SQL generation (delegated to MssqlWriter) ----------------------------
|
|
118
|
+
|
|
119
|
+
def createDbSql(self, dbname, encoding='UNICODE'):
|
|
120
|
+
return self.writer.create_db_sql(dbname, encoding=encoding)
|
|
121
|
+
|
|
122
|
+
def createSchemaSql(self, schema_name):
|
|
123
|
+
return self.writer.create_schema_sql(schema_name)
|
|
124
|
+
|
|
125
|
+
def columnSqlType(self, dtype, size=None):
|
|
126
|
+
return self.writer.column_sql_type(dtype, size=size)
|
|
127
|
+
|
|
128
|
+
def columnSqlDefinition(self, column_name, dtype, size=None,
|
|
129
|
+
notnull=False, default=None,
|
|
130
|
+
extra_sql=None, generated_expression=None):
|
|
131
|
+
return self.writer.column_sql_definition(
|
|
132
|
+
column_name, dtype, size=size, notnull=notnull, default=default,
|
|
133
|
+
extra_sql=extra_sql, generated_expression=generated_expression
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
def adaptSqlName(self, name):
|
|
137
|
+
return f'"{name}"'
|
|
138
|
+
|
|
139
|
+
def struct_constraint_sql(self, constraint_name, constraint_type,
|
|
140
|
+
columns=None, check_clause=None, **kwargs):
|
|
141
|
+
return self.writer.constraint_sql(
|
|
142
|
+
constraint_name, constraint_type,
|
|
143
|
+
columns=columns, check_clause=check_clause
|
|
144
|
+
)
|
|
145
|
+
|
|
146
|
+
def struct_foreign_key_sql(self, fk_name, columns, related_table,
|
|
147
|
+
related_schema, related_columns,
|
|
148
|
+
on_delete=None, on_update=None,
|
|
149
|
+
deferrable=False, initially_deferred=False):
|
|
150
|
+
return self.writer.foreign_key_sql(
|
|
151
|
+
fk_name, columns, related_table, related_schema, related_columns,
|
|
152
|
+
on_delete=on_delete, on_update=on_update,
|
|
153
|
+
deferrable=deferrable, initially_deferred=initially_deferred
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
def struct_create_index_sql(self, schema_name, table_name, columns,
|
|
157
|
+
index_name=None, unique=False, method=None,
|
|
158
|
+
with_options=None, tablespace=None,
|
|
159
|
+
where=None):
|
|
160
|
+
return self.writer.create_index_sql(
|
|
161
|
+
schema_name, table_name, columns,
|
|
162
|
+
index_name=index_name, unique=unique, method=method,
|
|
163
|
+
with_options=with_options, tablespace=tablespace, where=where
|
|
164
|
+
)
|
|
165
|
+
|
|
166
|
+
def struct_create_extension_sql(self, extension_name):
|
|
167
|
+
return self.writer.create_extension_sql(extension_name)
|
|
168
|
+
|
|
169
|
+
def struct_comment_on_column_sql(self, schema_name, table_name,
|
|
170
|
+
column_name, comment):
|
|
171
|
+
return self.writer.comment_on_column_sql(
|
|
172
|
+
schema_name, table_name, column_name, comment
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
def struct_comment_on_table_sql(self, schema_name, table_name, comment):
|
|
176
|
+
return self.writer.comment_on_table_sql(schema_name, table_name, comment)
|
|
177
|
+
|
|
178
|
+
def struct_drop_table_pkey_sql(self, schema_name, table_name):
|
|
179
|
+
return self.writer.drop_table_pkey_sql(schema_name, table_name)
|
|
180
|
+
|
|
181
|
+
def struct_add_table_pkey_sql(self, schema_name, table_name, pkeys):
|
|
182
|
+
return self.writer.add_table_pkey_sql(schema_name, table_name, pkeys)
|
|
183
|
+
|
|
184
|
+
def struct_alter_column_sql(self, column_name, new_sql_type, **kwargs):
|
|
185
|
+
return self.writer.alter_column_sql(column_name, new_sql_type)
|
|
186
|
+
|
|
187
|
+
def struct_alter_column_with_conversion_sql(self, column_name,
|
|
188
|
+
new_sql_type,
|
|
189
|
+
conversion_expression,
|
|
190
|
+
**kwargs):
|
|
191
|
+
return self.writer.alter_column_with_conversion_sql(
|
|
192
|
+
column_name, new_sql_type, conversion_expression
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
def struct_add_not_null_sql(self, column_name, **kwargs):
|
|
196
|
+
return self.writer.add_not_null_sql(column_name)
|
|
197
|
+
|
|
198
|
+
def struct_drop_not_null_sql(self, column_name, **kwargs):
|
|
199
|
+
return self.writer.drop_not_null_sql(column_name)
|
|
200
|
+
|
|
201
|
+
def struct_drop_constraint_sql(self, constraint_name, **kwargs):
|
|
202
|
+
return self.writer.drop_constraint_sql(constraint_name)
|
|
203
|
+
|
|
204
|
+
def struct_add_column_sql(self, column_definition):
|
|
205
|
+
return self.writer.add_column_sql(column_definition)
|
|
206
|
+
|
|
207
|
+
def struct_alter_table_commands(self, schema_name, table_name,
|
|
208
|
+
column_fragments):
|
|
209
|
+
return self.writer.alter_table_commands(
|
|
210
|
+
schema_name, table_name, column_fragments
|
|
211
|
+
)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class MssqlDatabase(Database):
|
|
215
|
+
"""Production Microsoft SQL Server database facade.
|
|
216
|
+
|
|
217
|
+
Consumers pass pymssql connection kwargs (``dbname`` required) and the
|
|
218
|
+
schema lists; the migrator reads schemas through the getter methods.
|
|
219
|
+
"""
|
|
220
|
+
|
|
221
|
+
def __init__(self, connection_params, application_schemas=None,
|
|
222
|
+
read_only_schemas=None, tenant_schemas=None):
|
|
223
|
+
self._connection_params = dict(connection_params)
|
|
224
|
+
if 'dbname' not in self._connection_params:
|
|
225
|
+
raise SqlMigrationError("connection_params must include 'dbname'")
|
|
226
|
+
self._application_schemas = list(application_schemas or [])
|
|
227
|
+
self._read_only_schemas = list(read_only_schemas or [])
|
|
228
|
+
self._tenant_schemas = list(tenant_schemas or [])
|
|
229
|
+
self._adapter = MssqlAdapter(self)
|
|
230
|
+
self._connection = None
|
|
231
|
+
|
|
232
|
+
@property
|
|
233
|
+
def adapter(self):
|
|
234
|
+
return self._adapter
|
|
235
|
+
|
|
236
|
+
def get_dbname(self):
|
|
237
|
+
return self._connection_params['dbname']
|
|
238
|
+
|
|
239
|
+
def connection_params(self, manager=False):
|
|
240
|
+
"""pymssql connection kwargs; ``manager`` targets the ``master`` DB."""
|
|
241
|
+
params = dict(self._connection_params)
|
|
242
|
+
if manager:
|
|
243
|
+
params['dbname'] = 'master'
|
|
244
|
+
return params
|
|
245
|
+
|
|
246
|
+
# -- Schemas seen by the migrator -----------------------------------------
|
|
247
|
+
|
|
248
|
+
def getApplicationSchemas(self):
|
|
249
|
+
return self._application_schemas
|
|
250
|
+
|
|
251
|
+
def readOnlySchemas(self):
|
|
252
|
+
return self._read_only_schemas
|
|
253
|
+
|
|
254
|
+
def getTenantSchemas(self):
|
|
255
|
+
return self._tenant_schemas
|
|
256
|
+
|
|
257
|
+
# -- Persistent connection ------------------------------------------------
|
|
258
|
+
|
|
259
|
+
def startup(self):
|
|
260
|
+
"""Open the persistent connection lazily (legacy ``db.startup()``)."""
|
|
261
|
+
if self._connection is None:
|
|
262
|
+
self._connection = self._adapter.connect()
|
|
263
|
+
|
|
264
|
+
def execute(self, sql):
|
|
265
|
+
self.startup()
|
|
266
|
+
cursor = self._connection.cursor()
|
|
267
|
+
cursor.execute(sql)
|
|
268
|
+
return cursor
|
|
269
|
+
|
|
270
|
+
def commit(self):
|
|
271
|
+
if self._connection is not None:
|
|
272
|
+
self._connection.commit()
|
|
273
|
+
|
|
274
|
+
def closeConnection(self):
|
|
275
|
+
if self._connection is not None:
|
|
276
|
+
self._connection.close()
|
|
277
|
+
self._connection = None
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
# Copyright (c) 2025 Softwell Srl, Milano, Italy
|
|
2
|
+
# SPDX-License-Identifier: Apache-2.0
|
|
3
|
+
|
|
4
|
+
"""
|
|
5
|
+
mysql_adapter.py - Concrete MySQL adapter/database pair
|
|
6
|
+
========================================================
|
|
7
|
+
|
|
8
|
+
``MysqlAdapter`` wires DDL generation to :class:`MysqlWriter` and
|
|
9
|
+
introspection to :class:`MysqlReader`; ``MysqlDatabase`` is the
|
|
10
|
+
:class:`Database` facade consumers instantiate. pymysql is required at
|
|
11
|
+
connection time only (optional ``mysql`` extra).
|
|
12
|
+
|
|
13
|
+
Model: SCHEMA and DATABASE are synonyms in MySQL. Application schemas are
|
|
14
|
+
MySQL databases; the manager connection targets the same server without
|
|
15
|
+
selecting a database. Every connection runs in ``ANSI_QUOTES`` mode so
|
|
16
|
+
the double-quoted identifiers emitted by the writer are valid.
|
|
17
|
+
|
|
18
|
+
``execute`` splits a multi-statement SQL script into individual
|
|
19
|
+
statements and runs them one by one on a single connection (pymysql
|
|
20
|
+
executes only one statement per ``cursor.execute`` call), preserving the
|
|
21
|
+
legacy per-statement autocommit stance.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
from asqueel_migration.database import BaseAdapter, Database
|
|
25
|
+
from asqueel_migration.exceptions import (
|
|
26
|
+
NonExistingDbException,
|
|
27
|
+
SqlConnectionException,
|
|
28
|
+
SqlMigrationError,
|
|
29
|
+
)
|
|
30
|
+
from asqueel_migration.readers import MysqlReader
|
|
31
|
+
from asqueel_migration.writers import MysqlWriter
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class MysqlAdapter(BaseAdapter):
|
|
35
|
+
"""MySQL adapter: MysqlWriter for DDL, MysqlReader for introspection, pymysql for execution."""
|
|
36
|
+
|
|
37
|
+
TYPE_CONVERSIONS = MysqlWriter.TYPE_CONVERSIONS
|
|
38
|
+
|
|
39
|
+
def __init__(self, database):
|
|
40
|
+
self.database = database
|
|
41
|
+
self.writer = MysqlWriter()
|
|
42
|
+
self._reader = None
|
|
43
|
+
|
|
44
|
+
# -- Connections ---------------------------------------------------------
|
|
45
|
+
|
|
46
|
+
def connect(self, manager=False, autocommit=False):
|
|
47
|
+
"""Open a pymysql connection with the #655 error taxonomy.
|
|
48
|
+
|
|
49
|
+
Applies ANSI_QUOTES and the autocommit flag. Unknown database
|
|
50
|
+
(errno 1049) raises :class:`NonExistingDbException`; any other
|
|
51
|
+
operational error raises :class:`SqlConnectionException`.
|
|
52
|
+
"""
|
|
53
|
+
import pymysql # optional dependency (mysql extra)
|
|
54
|
+
params = self.database.connection_params(manager=manager)
|
|
55
|
+
params = self._pymysql_params(params)
|
|
56
|
+
try:
|
|
57
|
+
connection = pymysql.connect(**params, autocommit=autocommit)
|
|
58
|
+
except pymysql.err.OperationalError as error:
|
|
59
|
+
if error.args and error.args[0] == 1049:
|
|
60
|
+
raise NonExistingDbException(self.database.get_dbname()) from error
|
|
61
|
+
raise SqlConnectionException(
|
|
62
|
+
self.database.get_dbname(), original_error=error
|
|
63
|
+
) from error
|
|
64
|
+
with connection.cursor() as cursor:
|
|
65
|
+
cursor.execute("SET SESSION sql_mode = CONCAT(@@sql_mode, ',ANSI_QUOTES')")
|
|
66
|
+
return connection
|
|
67
|
+
|
|
68
|
+
def _pymysql_params(self, params):
|
|
69
|
+
"""Translate the ``dbname`` key into pymysql's ``database`` kwarg."""
|
|
70
|
+
params = dict(params)
|
|
71
|
+
dbname = params.pop('dbname', None)
|
|
72
|
+
if dbname is not None:
|
|
73
|
+
params['database'] = dbname
|
|
74
|
+
return params
|
|
75
|
+
|
|
76
|
+
def _split_statements(self, sql):
|
|
77
|
+
"""Split a SQL script into individual statements.
|
|
78
|
+
|
|
79
|
+
Splits on ``;`` at end-of-line (the shape the executor emits) and
|
|
80
|
+
drops empty fragments.
|
|
81
|
+
"""
|
|
82
|
+
statements = []
|
|
83
|
+
for chunk in sql.split(';\n'):
|
|
84
|
+
statement = chunk.strip().rstrip(';').strip()
|
|
85
|
+
if statement:
|
|
86
|
+
statements.append(statement)
|
|
87
|
+
return statements
|
|
88
|
+
|
|
89
|
+
def execute(self, sql, autoCommit=False, manager=False):
|
|
90
|
+
"""Run a (possibly multi-statement) SQL string on a fresh connection.
|
|
91
|
+
|
|
92
|
+
pymysql runs one statement per ``execute`` call, so the script is
|
|
93
|
+
split and the statements run sequentially on one connection.
|
|
94
|
+
"""
|
|
95
|
+
connection = self.connect(manager=manager, autocommit=autoCommit or manager)
|
|
96
|
+
try:
|
|
97
|
+
with connection.cursor() as cursor:
|
|
98
|
+
for statement in self._split_statements(sql):
|
|
99
|
+
cursor.execute(statement)
|
|
100
|
+
if not (autoCommit or manager):
|
|
101
|
+
connection.commit()
|
|
102
|
+
finally:
|
|
103
|
+
connection.close()
|
|
104
|
+
|
|
105
|
+
# -- Introspection (delegated to MysqlReader) -----------------------------
|
|
106
|
+
|
|
107
|
+
@property
|
|
108
|
+
def reader(self):
|
|
109
|
+
"""Lazily build the MysqlReader bound to this database's connection params."""
|
|
110
|
+
if self._reader is None:
|
|
111
|
+
self._reader = MysqlReader(self.database.connection_params())
|
|
112
|
+
return self._reader
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def capabilities(self):
|
|
116
|
+
"""Dialect capability set, declared by the writer."""
|
|
117
|
+
return self.writer.CAPABILITIES
|
|
118
|
+
|
|
119
|
+
# -- SQL generation (delegated to MysqlWriter) ----------------------------
|
|
120
|
+
|
|
121
|
+
def createDbSql(self, dbname, encoding='UNICODE'):
|
|
122
|
+
return self.writer.create_db_sql(dbname, encoding=encoding)
|
|
123
|
+
|
|
124
|
+
def createSchemaSql(self, schema_name):
|
|
125
|
+
return self.writer.create_schema_sql(schema_name)
|
|
126
|
+
|
|
127
|
+
def columnSqlType(self, dtype, size=None):
|
|
128
|
+
return self.writer.column_sql_type(dtype, size=size)
|
|
129
|
+
|
|
130
|
+
def columnSqlDefinition(self, column_name, dtype, size=None,
|
|
131
|
+
notnull=False, default=None,
|
|
132
|
+
extra_sql=None, generated_expression=None):
|
|
133
|
+
return self.writer.column_sql_definition(
|
|
134
|
+
column_name, dtype, size=size, notnull=notnull, default=default,
|
|
135
|
+
extra_sql=extra_sql, generated_expression=generated_expression
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
def adaptSqlName(self, name):
|
|
139
|
+
return f'"{name}"'
|
|
140
|
+
|
|
141
|
+
def struct_constraint_sql(self, constraint_name, constraint_type,
|
|
142
|
+
columns=None, check_clause=None, **kwargs):
|
|
143
|
+
return self.writer.constraint_sql(
|
|
144
|
+
constraint_name, constraint_type,
|
|
145
|
+
columns=columns, check_clause=check_clause
|
|
146
|
+
)
|
|
147
|
+
|
|
148
|
+
def struct_foreign_key_sql(self, fk_name, columns, related_table,
|
|
149
|
+
related_schema, related_columns,
|
|
150
|
+
on_delete=None, on_update=None,
|
|
151
|
+
deferrable=False, initially_deferred=False):
|
|
152
|
+
return self.writer.foreign_key_sql(
|
|
153
|
+
fk_name, columns, related_table, related_schema, related_columns,
|
|
154
|
+
on_delete=on_delete, on_update=on_update,
|
|
155
|
+
deferrable=deferrable, initially_deferred=initially_deferred
|
|
156
|
+
)
|
|
157
|
+
|
|
158
|
+
def struct_create_index_sql(self, schema_name, table_name, columns,
|
|
159
|
+
index_name=None, unique=False, method=None,
|
|
160
|
+
with_options=None, tablespace=None,
|
|
161
|
+
where=None):
|
|
162
|
+
return self.writer.create_index_sql(
|
|
163
|
+
schema_name, table_name, columns,
|
|
164
|
+
index_name=index_name, unique=unique, method=method,
|
|
165
|
+
with_options=with_options, tablespace=tablespace, where=where
|
|
166
|
+
)
|
|
167
|
+
|
|
168
|
+
def struct_create_extension_sql(self, extension_name):
|
|
169
|
+
return self.writer.create_extension_sql(extension_name)
|
|
170
|
+
|
|
171
|
+
def struct_comment_on_column_sql(self, schema_name, table_name,
|
|
172
|
+
column_name, comment):
|
|
173
|
+
return self.writer.comment_on_column_sql(
|
|
174
|
+
schema_name, table_name, column_name, comment
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def struct_comment_on_table_sql(self, schema_name, table_name, comment):
|
|
178
|
+
return self.writer.comment_on_table_sql(schema_name, table_name, comment)
|
|
179
|
+
|
|
180
|
+
def struct_drop_table_pkey_sql(self, schema_name, table_name):
|
|
181
|
+
return self.writer.drop_table_pkey_sql(schema_name, table_name)
|
|
182
|
+
|
|
183
|
+
def struct_add_table_pkey_sql(self, schema_name, table_name, pkeys):
|
|
184
|
+
return self.writer.add_table_pkey_sql(schema_name, table_name, pkeys)
|
|
185
|
+
|
|
186
|
+
def struct_alter_column_sql(self, column_name, new_sql_type, **kwargs):
|
|
187
|
+
return self.writer.alter_column_sql(column_name, new_sql_type)
|
|
188
|
+
|
|
189
|
+
def struct_alter_column_with_conversion_sql(self, column_name,
|
|
190
|
+
new_sql_type,
|
|
191
|
+
conversion_expression,
|
|
192
|
+
**kwargs):
|
|
193
|
+
return self.writer.alter_column_with_conversion_sql(
|
|
194
|
+
column_name, new_sql_type, conversion_expression
|
|
195
|
+
)
|
|
196
|
+
|
|
197
|
+
def struct_add_not_null_sql(self, column_name, **kwargs):
|
|
198
|
+
return self.writer.add_not_null_sql(column_name)
|
|
199
|
+
|
|
200
|
+
def struct_drop_not_null_sql(self, column_name, **kwargs):
|
|
201
|
+
return self.writer.drop_not_null_sql(column_name)
|
|
202
|
+
|
|
203
|
+
def struct_drop_constraint_sql(self, constraint_name, **kwargs):
|
|
204
|
+
return self.writer.drop_constraint_sql(constraint_name)
|
|
205
|
+
|
|
206
|
+
def struct_add_column_sql(self, column_definition):
|
|
207
|
+
return self.writer.add_column_sql(column_definition)
|
|
208
|
+
|
|
209
|
+
def struct_alter_table_commands(self, schema_name, table_name,
|
|
210
|
+
column_fragments):
|
|
211
|
+
return self.writer.alter_table_commands(
|
|
212
|
+
schema_name, table_name, column_fragments
|
|
213
|
+
)
|
|
214
|
+
|
|
215
|
+
|
|
216
|
+
class MysqlDatabase(Database):
|
|
217
|
+
"""Production MySQL database facade.
|
|
218
|
+
|
|
219
|
+
Consumers pass pymysql connection kwargs (``dbname`` required) and the
|
|
220
|
+
schema lists; the migrator reads schemas through the getter methods.
|
|
221
|
+
"""
|
|
222
|
+
|
|
223
|
+
def __init__(self, connection_params, application_schemas=None,
|
|
224
|
+
read_only_schemas=None, tenant_schemas=None):
|
|
225
|
+
self._connection_params = dict(connection_params)
|
|
226
|
+
if 'dbname' not in self._connection_params:
|
|
227
|
+
raise SqlMigrationError("connection_params must include 'dbname'")
|
|
228
|
+
self._application_schemas = list(application_schemas or [])
|
|
229
|
+
self._read_only_schemas = list(read_only_schemas or [])
|
|
230
|
+
self._tenant_schemas = list(tenant_schemas or [])
|
|
231
|
+
self._adapter = MysqlAdapter(self)
|
|
232
|
+
self._connection = None
|
|
233
|
+
|
|
234
|
+
@property
|
|
235
|
+
def adapter(self):
|
|
236
|
+
return self._adapter
|
|
237
|
+
|
|
238
|
+
def get_dbname(self):
|
|
239
|
+
return self._connection_params['dbname']
|
|
240
|
+
|
|
241
|
+
def connection_params(self, manager=False):
|
|
242
|
+
"""pymysql connection kwargs; ``manager`` drops the database selection.
|
|
243
|
+
|
|
244
|
+
The manager connection targets the same server without selecting a
|
|
245
|
+
database (schema == database in MySQL), so CREATE DATABASE can run.
|
|
246
|
+
"""
|
|
247
|
+
params = dict(self._connection_params)
|
|
248
|
+
if manager:
|
|
249
|
+
params.pop('dbname', None)
|
|
250
|
+
return params
|
|
251
|
+
|
|
252
|
+
# -- Schemas seen by the migrator -----------------------------------------
|
|
253
|
+
|
|
254
|
+
def getApplicationSchemas(self):
|
|
255
|
+
return self._application_schemas
|
|
256
|
+
|
|
257
|
+
def readOnlySchemas(self):
|
|
258
|
+
return self._read_only_schemas
|
|
259
|
+
|
|
260
|
+
def getTenantSchemas(self):
|
|
261
|
+
return self._tenant_schemas
|
|
262
|
+
|
|
263
|
+
# -- Persistent connection ------------------------------------------------
|
|
264
|
+
|
|
265
|
+
def startup(self):
|
|
266
|
+
"""Open the persistent connection lazily (legacy ``db.startup()``)."""
|
|
267
|
+
if self._connection is None or not self._connection.open:
|
|
268
|
+
self._connection = self._adapter.connect()
|
|
269
|
+
|
|
270
|
+
def execute(self, sql):
|
|
271
|
+
self.startup()
|
|
272
|
+
cursor = self._connection.cursor()
|
|
273
|
+
cursor.execute(sql)
|
|
274
|
+
return cursor
|
|
275
|
+
|
|
276
|
+
def commit(self):
|
|
277
|
+
if self._connection and self._connection.open:
|
|
278
|
+
self._connection.commit()
|
|
279
|
+
|
|
280
|
+
def closeConnection(self):
|
|
281
|
+
if self._connection and self._connection.open:
|
|
282
|
+
self._connection.close()
|
|
283
|
+
self._connection = None
|