rakko-orm 1.0.0a0__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.
Files changed (143) hide show
  1. rakko/__init__.py +613 -0
  2. rakko/__main__.py +10 -0
  3. rakko/apps.py +356 -0
  4. rakko/backends/__init__.py +4 -0
  5. rakko/backends/asyncpg/__init__.py +7 -0
  6. rakko/backends/asyncpg/client.py +223 -0
  7. rakko/backends/asyncpg/executor.py +20 -0
  8. rakko/backends/asyncpg/schema_generator.py +17 -0
  9. rakko/backends/base/__init__.py +4 -0
  10. rakko/backends/base/client.py +438 -0
  11. rakko/backends/base/config_generator.py +249 -0
  12. rakko/backends/base/executor.py +764 -0
  13. rakko/backends/base/schema_generator.py +580 -0
  14. rakko/backends/base_postgres/__init__.py +4 -0
  15. rakko/backends/base_postgres/client.py +170 -0
  16. rakko/backends/base_postgres/executor.py +149 -0
  17. rakko/backends/base_postgres/schema_generator.py +84 -0
  18. rakko/backends/mssql/__init__.py +7 -0
  19. rakko/backends/mssql/client.py +127 -0
  20. rakko/backends/mssql/executor.py +17 -0
  21. rakko/backends/mssql/schema_generator.py +125 -0
  22. rakko/backends/mysql/__init__.py +7 -0
  23. rakko/backends/mysql/client.py +312 -0
  24. rakko/backends/mysql/executor.py +154 -0
  25. rakko/backends/mysql/schema_generator.py +101 -0
  26. rakko/backends/odbc/__init__.py +4 -0
  27. rakko/backends/odbc/client.py +221 -0
  28. rakko/backends/odbc/executor.py +20 -0
  29. rakko/backends/oracle/__init__.py +7 -0
  30. rakko/backends/oracle/client.py +136 -0
  31. rakko/backends/oracle/executor.py +27 -0
  32. rakko/backends/oracle/schema_generator.py +120 -0
  33. rakko/backends/psycopg/__init__.py +7 -0
  34. rakko/backends/psycopg/client.py +288 -0
  35. rakko/backends/psycopg/executor.py +14 -0
  36. rakko/backends/psycopg/schema_generator.py +17 -0
  37. rakko/backends/sqlite/__init__.py +14 -0
  38. rakko/backends/sqlite/client.py +299 -0
  39. rakko/backends/sqlite/executor.py +88 -0
  40. rakko/backends/sqlite/schema_generator.py +32 -0
  41. rakko/cli/__init__.py +13 -0
  42. rakko/cli/cli.py +878 -0
  43. rakko/cli/utils.py +181 -0
  44. rakko/config.py +315 -0
  45. rakko/connection.py +345 -0
  46. rakko/context.py +571 -0
  47. rakko/contrib/__init__.py +4 -0
  48. rakko/contrib/aiohttp/__init__.py +99 -0
  49. rakko/contrib/blacksheep/__init__.py +121 -0
  50. rakko/contrib/fastapi/__init__.py +301 -0
  51. rakko/contrib/mysql/__init__.py +4 -0
  52. rakko/contrib/mysql/fields.py +63 -0
  53. rakko/contrib/mysql/functions.py +19 -0
  54. rakko/contrib/mysql/indexes.py +28 -0
  55. rakko/contrib/mysql/json_functions.py +80 -0
  56. rakko/contrib/mysql/search.py +49 -0
  57. rakko/contrib/postgres/__init__.py +4 -0
  58. rakko/contrib/postgres/array_functions.py +35 -0
  59. rakko/contrib/postgres/fields.py +105 -0
  60. rakko/contrib/postgres/functions.py +43 -0
  61. rakko/contrib/postgres/indexes.py +33 -0
  62. rakko/contrib/postgres/json_functions.py +113 -0
  63. rakko/contrib/postgres/regex.py +31 -0
  64. rakko/contrib/postgres/search.py +483 -0
  65. rakko/contrib/pydantic/__init__.py +16 -0
  66. rakko/contrib/pydantic/base.py +147 -0
  67. rakko/contrib/pydantic/creator.py +681 -0
  68. rakko/contrib/pydantic/descriptions.py +207 -0
  69. rakko/contrib/pydantic/utils.py +38 -0
  70. rakko/contrib/pylint/__init__.py +158 -0
  71. rakko/contrib/quart/__init__.py +117 -0
  72. rakko/contrib/sanic/__init__.py +116 -0
  73. rakko/contrib/sqlite/__init__.py +4 -0
  74. rakko/contrib/sqlite/functions.py +16 -0
  75. rakko/contrib/sqlite/regex.py +46 -0
  76. rakko/contrib/starlette/__init__.py +180 -0
  77. rakko/contrib/test/__init__.py +336 -0
  78. rakko/contrib/test/condition.py +42 -0
  79. rakko/converters.py +160 -0
  80. rakko/exceptions.py +130 -0
  81. rakko/expressions.py +962 -0
  82. rakko/fields/__init__.py +111 -0
  83. rakko/fields/base.py +685 -0
  84. rakko/fields/data.py +1308 -0
  85. rakko/fields/db_defaults.py +105 -0
  86. rakko/fields/relational.py +703 -0
  87. rakko/filters.py +639 -0
  88. rakko/functions.py +142 -0
  89. rakko/indexes.py +165 -0
  90. rakko/log.py +8 -0
  91. rakko/manager.py +29 -0
  92. rakko/migrations/__init__.py +41 -0
  93. rakko/migrations/api/__init__.py +16 -0
  94. rakko/migrations/api/migrate.py +77 -0
  95. rakko/migrations/api/plan.py +76 -0
  96. rakko/migrations/api/sqlmigrate.py +69 -0
  97. rakko/migrations/autodetector.py +203 -0
  98. rakko/migrations/constraints.py +31 -0
  99. rakko/migrations/exceptions.py +10 -0
  100. rakko/migrations/executor.py +368 -0
  101. rakko/migrations/expressions.py +13 -0
  102. rakko/migrations/graph.py +158 -0
  103. rakko/migrations/loader.py +127 -0
  104. rakko/migrations/migration.py +189 -0
  105. rakko/migrations/operations.py +1288 -0
  106. rakko/migrations/recorder.py +104 -0
  107. rakko/migrations/schema_editor/__init__.py +25 -0
  108. rakko/migrations/schema_editor/asyncpg.py +11 -0
  109. rakko/migrations/schema_editor/base.py +945 -0
  110. rakko/migrations/schema_editor/base_postgres.py +171 -0
  111. rakko/migrations/schema_editor/data.py +18 -0
  112. rakko/migrations/schema_editor/mssql.py +339 -0
  113. rakko/migrations/schema_editor/mysql.py +408 -0
  114. rakko/migrations/schema_editor/oracle.py +259 -0
  115. rakko/migrations/schema_editor/psycopg.py +11 -0
  116. rakko/migrations/schema_editor/sqlite.py +424 -0
  117. rakko/migrations/schema_generator/__init__.py +5 -0
  118. rakko/migrations/schema_generator/operation_generator.py +163 -0
  119. rakko/migrations/schema_generator/state.py +224 -0
  120. rakko/migrations/schema_generator/state_apps.py +165 -0
  121. rakko/migrations/schema_generator/state_diff.py +419 -0
  122. rakko/migrations/writer.py +515 -0
  123. rakko/models.py +1854 -0
  124. rakko/py.typed +0 -0
  125. rakko/query_api.py +134 -0
  126. rakko/query_utils.py +238 -0
  127. rakko/queryset.py +2743 -0
  128. rakko/relations.py +85 -0
  129. rakko/router.py +55 -0
  130. rakko/schema_quoting.py +62 -0
  131. rakko/signals.py +73 -0
  132. rakko/timezone.py +173 -0
  133. rakko/transactions.py +69 -0
  134. rakko/utils.py +50 -0
  135. rakko/validators.py +412 -0
  136. rakko/warnings.py +22 -0
  137. rakko_orm-1.0.0a0.dist-info/METADATA +114 -0
  138. rakko_orm-1.0.0a0.dist-info/RECORD +143 -0
  139. rakko_orm-1.0.0a0.dist-info/WHEEL +4 -0
  140. rakko_orm-1.0.0a0.dist-info/entry_points.txt +5 -0
  141. rakko_orm-1.0.0a0.dist-info/licenses/CONTRIBUTORS.rst +86 -0
  142. rakko_orm-1.0.0a0.dist-info/licenses/LICENSE.txt +201 -0
  143. rakko_orm-1.0.0a0.dist-info/licenses/NOTICE.txt +22 -0
@@ -0,0 +1,312 @@
1
+ # Copyright (c) 2026 ropmyung (Rakko ORM modifications and additions).
2
+ # Derived from Tortoise ORM; maintained and modified for Rakko ORM.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from __future__ import annotations
6
+
7
+ import asyncio
8
+ from collections.abc import Callable
9
+ from functools import wraps
10
+ from itertools import count
11
+ from types import CoroutineType
12
+ from typing import Any, SupportsInt
13
+
14
+ try:
15
+ import asyncmy as mysql # type: ignore[import-not-found]
16
+ from asyncmy import errors # type: ignore[import-not-found]
17
+ from asyncmy.charset import charset_by_name # type: ignore[import-not-found]
18
+ from asyncmy.constants import COMMAND # type: ignore[import-not-found]
19
+ except ImportError:
20
+ import aiomysql as mysql
21
+ from pymysql import err as errors
22
+ from pymysql.charset import charset_by_name
23
+ from pymysql.constants import COMMAND
24
+
25
+ from pypika_tortoise import MySQLQuery
26
+
27
+ from rakko.backends.base.client import (
28
+ BaseDBAsyncClient,
29
+ Capabilities,
30
+ ConnectionWrapper,
31
+ NestedTransactionContext,
32
+ PoolConnectionWrapper,
33
+ TransactionalDBClient,
34
+ TransactionContext,
35
+ TransactionContextPooled,
36
+ )
37
+ from rakko.backends.mysql.executor import MySQLExecutor
38
+ from rakko.backends.mysql.schema_generator import MySQLSchemaGenerator
39
+ from rakko.exceptions import (
40
+ DBConnectionError,
41
+ IntegrityError,
42
+ OperationalError,
43
+ TransactionManagementError,
44
+ )
45
+ from rakko.timezone import get_default_timezone, get_use_tz
46
+
47
+ type FuncType[**P, R] = Callable[P, CoroutineType[Any, Any, R]]
48
+
49
+
50
+ def translate_exceptions[**P, R](func: FuncType[P, R]) -> FuncType[P, R]:
51
+ @wraps(func)
52
+ async def translate_exceptions_(*args: P.args, **kwargs: P.kwargs) -> R:
53
+ try:
54
+ return await func(*args, **kwargs)
55
+ except (
56
+ errors.OperationalError,
57
+ errors.ProgrammingError,
58
+ errors.DataError,
59
+ errors.InternalError,
60
+ errors.NotSupportedError,
61
+ ) as exc:
62
+ raise OperationalError(exc)
63
+ except errors.IntegrityError as exc:
64
+ raise IntegrityError(exc)
65
+
66
+ return translate_exceptions_
67
+
68
+
69
+ class MySQLClient(BaseDBAsyncClient):
70
+ query_class = MySQLQuery
71
+ executor_class = MySQLExecutor
72
+ schema_generator = MySQLSchemaGenerator
73
+ capabilities = Capabilities(
74
+ "mysql",
75
+ requires_limit=True,
76
+ inline_comment=True,
77
+ support_index_hint=True,
78
+ support_for_posix_regex_queries=True,
79
+ support_json_attributes=True,
80
+ )
81
+
82
+ def __init__(
83
+ self,
84
+ *,
85
+ user: str,
86
+ password: str,
87
+ database: str,
88
+ host: str,
89
+ port: SupportsInt,
90
+ **kwargs: Any,
91
+ ) -> None:
92
+ super().__init__(**kwargs)
93
+
94
+ self.user = user
95
+ self.password = password
96
+ self.database = database
97
+ self.host = host
98
+ self.port = int(port) # make sure port is int type
99
+ self.extra = kwargs.copy()
100
+ self.storage_engine = self.extra.pop("storage_engine", "")
101
+ self.extra.pop("connection_name", None)
102
+ self.extra.pop("fetch_inserted", None)
103
+ self.extra.pop("db", None)
104
+ self.extra.pop("autocommit", None)
105
+ self.extra.setdefault("sql_mode", "STRICT_TRANS_TABLES")
106
+ self.charset = self.extra.pop("charset", "utf8mb4")
107
+ self.pool_minsize = int(self.extra.pop("minsize", 1))
108
+ self.pool_maxsize = int(self.extra.pop("maxsize", 5))
109
+
110
+ self._template: dict = {}
111
+ self._pool: mysql.Pool | None = None
112
+ self._connection = None
113
+ self._pool_init_lock = asyncio.Lock()
114
+
115
+ async def create_connection(self, with_db: bool) -> None:
116
+ if charset_by_name(self.charset) is None:
117
+ raise DBConnectionError(f"Unknown charset {self.charset}")
118
+ self._template = {
119
+ "host": self.host,
120
+ "port": self.port,
121
+ "user": self.user,
122
+ "db": self.database if with_db else None,
123
+ "autocommit": True,
124
+ "charset": self.charset,
125
+ "minsize": self.pool_minsize,
126
+ "maxsize": self.pool_maxsize,
127
+ **self.extra,
128
+ }
129
+ try:
130
+ self._pool = await mysql.create_pool(password=self.password, **self._template)
131
+
132
+ if isinstance(self._pool, mysql.Pool):
133
+ async with self.acquire_connection() as connection:
134
+ async with connection.cursor() as cursor:
135
+ if self.storage_engine:
136
+ await cursor.execute(
137
+ f"SET default_storage_engine='{self.storage_engine}';"
138
+ )
139
+ if self.storage_engine.lower() != "innodb": # pragma: nobranch
140
+ self.capabilities.__dict__["supports_transactions"] = False
141
+ # Only set session timezone when use_tz=True
142
+ if get_use_tz():
143
+ from datetime import datetime as _datetime
144
+
145
+ offset = _datetime.now(tz=get_default_timezone()).utcoffset()
146
+ total_seconds = int(offset.total_seconds()) # type: ignore
147
+ hours = total_seconds // 3600
148
+ minutes = abs(total_seconds) % 3600 // 60
149
+ tz = f"{hours:+d}:{minutes:02d}"
150
+ await cursor.execute(f"SET time_zone='{tz}';")
151
+ await self._post_connect()
152
+ self.log.debug("Created connection %s pool with params: %s", self._pool, self._template)
153
+ except errors.OperationalError:
154
+ raise DBConnectionError(f"Can't connect to MySQL server: {self._template}")
155
+
156
+ async def _expire_connections(self) -> None:
157
+ if self._pool: # pragma: nobranch
158
+ for conn in self._pool._free:
159
+ conn._reader.set_exception(EOFError("EOF"))
160
+
161
+ async def _close(self) -> None:
162
+ if self._pool: # pragma: nobranch
163
+ self._pool.close()
164
+ await self._pool.wait_closed()
165
+ self.log.debug("Closed connection %s with params: %s", self._connection, self._template)
166
+ self._pool = None
167
+
168
+ async def close(self) -> None:
169
+ await self._close()
170
+ self._template.clear()
171
+
172
+ async def db_create(self) -> None:
173
+ await self.create_connection(with_db=False)
174
+ await self.execute_script(f"CREATE DATABASE {self.database}")
175
+ await self.close()
176
+
177
+ async def db_delete(self) -> None:
178
+ await self.create_connection(with_db=False)
179
+ try:
180
+ await self.execute_script(f"DROP DATABASE {self.database}")
181
+ except errors.DatabaseError: # pragma: nocoverage
182
+ pass
183
+ await self.close()
184
+
185
+ def acquire_connection(self) -> ConnectionWrapper | PoolConnectionWrapper:
186
+ return PoolConnectionWrapper(self, self._pool_init_lock)
187
+
188
+ def _in_transaction(self) -> TransactionContext:
189
+ return TransactionContextPooled(TransactionWrapper(self), self._pool_init_lock)
190
+
191
+ @translate_exceptions
192
+ async def execute_insert(self, query: str, values: list) -> int:
193
+ async with self.acquire_connection() as connection:
194
+ self.log.debug("%s: %s", query, values)
195
+ async with connection.cursor() as cursor:
196
+ await cursor.execute(query, values)
197
+ return cursor.lastrowid # return auto-generated id
198
+
199
+ @translate_exceptions
200
+ async def execute_many(self, query: str, values: list) -> None:
201
+ async with self.acquire_connection() as connection:
202
+ self.log.debug("%s: %s", query, values)
203
+ async with connection.cursor() as cursor:
204
+ if self.capabilities.supports_transactions:
205
+ await connection.begin()
206
+ try:
207
+ await cursor.executemany(query, values)
208
+ except Exception:
209
+ await connection.rollback()
210
+ raise
211
+ else:
212
+ await connection.commit()
213
+ else:
214
+ await cursor.executemany(query, values)
215
+
216
+ @translate_exceptions
217
+ async def execute_query(self, query: str, values: list | None = None) -> tuple[int, list[dict]]:
218
+ async with self.acquire_connection() as connection:
219
+ self.log.debug("%s: %s", query, values)
220
+ async with connection.cursor() as cursor:
221
+ await cursor.execute(query, values)
222
+ rows = await cursor.fetchall()
223
+ if rows:
224
+ fields = [f.name for f in cursor._result.fields]
225
+ return cursor.rowcount, [dict(zip(fields, row)) for row in rows]
226
+ return cursor.rowcount, []
227
+
228
+ async def execute_query_dict(self, query: str, values: list | None = None) -> list[dict]:
229
+ return (await self.execute_query(query, values))[1]
230
+
231
+ @translate_exceptions
232
+ async def execute_script(self, query: str) -> None:
233
+ async with self.acquire_connection() as connection:
234
+ self.log.debug(query)
235
+ async with connection.cursor() as cursor:
236
+ await cursor.execute(query)
237
+
238
+
239
+ class TransactionWrapper(MySQLClient, TransactionalDBClient):
240
+ def __init__(self, connection: MySQLClient) -> None:
241
+ self.connection_name = connection.connection_name
242
+ self._connection: mysql.Connection = connection._connection
243
+ self._lock = asyncio.Lock()
244
+ self._savepoint: str | None = None
245
+ self.log = connection.log
246
+ self._finalized: bool = False
247
+ self.fetch_inserted = connection.fetch_inserted
248
+ self._parent = connection
249
+
250
+ def _in_transaction(self) -> TransactionContext:
251
+ return NestedTransactionContext(TransactionWrapper(self))
252
+
253
+ def acquire_connection(self) -> ConnectionWrapper[mysql.Connection]:
254
+ return ConnectionWrapper(self._lock, self)
255
+
256
+ @translate_exceptions
257
+ async def execute_many(self, query: str, values: list) -> None:
258
+ async with self.acquire_connection() as connection:
259
+ self.log.debug("%s: %s", query, values)
260
+ async with connection.cursor() as cursor:
261
+ await cursor.executemany(query, values)
262
+
263
+ @translate_exceptions
264
+ async def begin(self) -> None:
265
+ await self._connection.begin()
266
+ self._finalized = False
267
+
268
+ async def commit(self) -> None:
269
+ if self._finalized:
270
+ raise TransactionManagementError("Transaction already finalised")
271
+ await self._connection.commit()
272
+ self._finalized = True
273
+
274
+ @translate_exceptions
275
+ async def savepoint(self) -> None:
276
+ self._savepoint = _gen_savepoint_name()
277
+ await self._connection._execute_command(COMMAND.COM_QUERY, f"SAVEPOINT {self._savepoint}")
278
+ await self._connection._read_ok_packet()
279
+
280
+ async def rollback(self) -> None:
281
+ if self._finalized:
282
+ raise TransactionManagementError("Transaction already finalised")
283
+ await self._connection.rollback()
284
+ self._finalized = True
285
+
286
+ async def savepoint_rollback(self) -> None:
287
+ if self._finalized:
288
+ raise TransactionManagementError("Transaction already finalised")
289
+ if self._savepoint is None:
290
+ raise TransactionManagementError("No savepoint to rollback to")
291
+ await self._connection._execute_command(
292
+ COMMAND.COM_QUERY, f"ROLLBACK TO SAVEPOINT {self._savepoint}"
293
+ )
294
+ await self._connection._read_ok_packet()
295
+ self._savepoint = None
296
+ self._finalized = True
297
+
298
+ async def release_savepoint(self) -> None:
299
+ if self._finalized:
300
+ raise TransactionManagementError("Transaction already finalised")
301
+ if self._savepoint is None:
302
+ raise TransactionManagementError("No savepoint to release")
303
+ await self._connection._execute_command(
304
+ COMMAND.COM_QUERY, f"RELEASE SAVEPOINT {self._savepoint}"
305
+ )
306
+ await self._connection._read_ok_packet()
307
+ self._savepoint = None
308
+ self._finalized = True
309
+
310
+
311
+ def _gen_savepoint_name(_c=count()) -> str:
312
+ return f"tortoise_savepoint_{next(_c)}"
@@ -0,0 +1,154 @@
1
+ # Copyright (c) 2026 ropmyung (Rakko ORM modifications and additions).
2
+ # Derived from Tortoise ORM; maintained and modified for Rakko ORM.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ import enum
6
+ from typing import Any
7
+
8
+ from pypika_tortoise import SqlContext
9
+ from pypika_tortoise.enums import SqlTypes
10
+ from pypika_tortoise.functions import Cast, Coalesce, Upper
11
+ from pypika_tortoise.terms import BasicCriterion, Criterion, Term, ValueWrapper
12
+ from pypika_tortoise.utils import format_quotes
13
+
14
+ from rakko import Model
15
+ from rakko.backends.base.executor import BaseExecutor
16
+ from rakko.contrib.mysql.json_functions import (
17
+ mysql_json_contained_by,
18
+ mysql_json_contains,
19
+ mysql_json_filter,
20
+ )
21
+ from rakko.contrib.mysql.search import SearchCriterion
22
+ from rakko.exceptions import UnSupportedError
23
+ from rakko.fields import BigIntField, IntField, SmallIntField
24
+ from rakko.filters import (
25
+ Like,
26
+ contains,
27
+ ends_with,
28
+ insensitive_contains,
29
+ insensitive_ends_with,
30
+ insensitive_exact,
31
+ insensitive_starts_with,
32
+ json_contained_by,
33
+ json_contains,
34
+ json_filter,
35
+ posix_regex,
36
+ search,
37
+ starts_with,
38
+ )
39
+
40
+
41
+ class MySQLRegexpComparators(enum.Enum):
42
+ REGEXP = " REGEXP "
43
+
44
+
45
+ class StrWrapper(ValueWrapper):
46
+ """
47
+ Naive str wrapper that doesn't use the monkey-patched pypika ValueWrapper for MySQL
48
+ """
49
+
50
+ def get_value_sql(self, ctx: SqlContext) -> str:
51
+ quote_char = ctx.secondary_quote_char or ""
52
+ value = self.value.replace(quote_char, quote_char * 2)
53
+ return format_quotes(value, quote_char)
54
+
55
+
56
+ def escape_like(val: str) -> str:
57
+ return val.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
58
+
59
+
60
+ def _mysql_like(field: Term, pattern: str) -> Criterion:
61
+ return Like(Cast(field, SqlTypes.CHAR), StrWrapper(pattern), escape="")
62
+
63
+
64
+ def _mysql_upper_like(field: Term, pattern: str) -> Criterion:
65
+ return Like(Upper(Cast(field, SqlTypes.CHAR)), Upper(StrWrapper(pattern)), escape="")
66
+
67
+
68
+ def mysql_contains(field: Term, value: str) -> Criterion:
69
+ return _mysql_like(field, f"%{escape_like(value)}%")
70
+
71
+
72
+ def mysql_starts_with(field: Term, value: str) -> Criterion:
73
+ return _mysql_like(field, f"{escape_like(value)}%")
74
+
75
+
76
+ def mysql_ends_with(field: Term, value: str) -> Criterion:
77
+ return _mysql_like(field, f"%{escape_like(value)}")
78
+
79
+
80
+ def mysql_insensitive_exact(field: Term, value: str) -> Criterion:
81
+ return Upper(Cast(field, SqlTypes.CHAR)).eq(Upper(str(value)))
82
+
83
+
84
+ def mysql_insensitive_contains(field: Term, value: str) -> Criterion:
85
+ return _mysql_upper_like(field, f"%{escape_like(value)}%")
86
+
87
+
88
+ def mysql_insensitive_starts_with(field: Term, value: str) -> Criterion:
89
+ return _mysql_upper_like(field, f"{escape_like(value)}%")
90
+
91
+
92
+ def mysql_insensitive_ends_with(field: Term, value: str) -> Criterion:
93
+ return _mysql_upper_like(field, f"%{escape_like(value)}")
94
+
95
+
96
+ def mysql_search(field: Term, value: str) -> SearchCriterion:
97
+ return SearchCriterion(field, expr=StrWrapper(value))
98
+
99
+
100
+ def mysql_posix_regex(field: Term, value: str) -> BasicCriterion:
101
+ return BasicCriterion(
102
+ MySQLRegexpComparators.REGEXP, Coalesce(Cast(field, SqlTypes.CHAR)), StrWrapper(value)
103
+ )
104
+
105
+
106
+ class MySQLExecutor(BaseExecutor):
107
+ FILTER_FUNC_OVERRIDE = {
108
+ contains: mysql_contains,
109
+ starts_with: mysql_starts_with,
110
+ ends_with: mysql_ends_with,
111
+ insensitive_exact: mysql_insensitive_exact,
112
+ insensitive_contains: mysql_insensitive_contains,
113
+ insensitive_starts_with: mysql_insensitive_starts_with,
114
+ insensitive_ends_with: mysql_insensitive_ends_with,
115
+ search: mysql_search,
116
+ json_contains: mysql_json_contains,
117
+ json_contained_by: mysql_json_contained_by,
118
+ json_filter: mysql_json_filter,
119
+ posix_regex: mysql_posix_regex,
120
+ }
121
+ EXPLAIN_SUPPORTED_FORMATS = ["JSON", "TRADITIONAL", "TREE"]
122
+
123
+ async def execute_explain(
124
+ self, sql: str, output_fmt: str | None = None, **options: bool
125
+ ) -> Any:
126
+ output_fmt = output_fmt or "JSON"
127
+ if output_fmt.upper() not in self.EXPLAIN_SUPPORTED_FORMATS:
128
+ raise UnSupportedError(f"Unsupported explain format: {output_fmt}")
129
+
130
+ if options and not all(k == "analyze" for k in options):
131
+ unsupported = [k for k in options if k != "analyze"]
132
+ raise UnSupportedError(f"Unsupported options: {set(unsupported)}")
133
+
134
+ explain_parts = []
135
+ if options.get("analyze"):
136
+ explain_parts.append("ANALYZE")
137
+ explain_parts.append(f"FORMAT={output_fmt.upper()}")
138
+
139
+ explain_statement = "EXPLAIN " + " ".join(explain_parts)
140
+ return (await self.db.execute_query(f"{explain_statement} {sql}"))[1]
141
+
142
+ async def _process_insert_result(self, instance: Model, results: int) -> None:
143
+ pk_field_object = self.model._meta.pk
144
+ if (
145
+ isinstance(pk_field_object, (SmallIntField, IntField, BigIntField))
146
+ and pk_field_object.generated
147
+ and not instance._custom_generated_pk
148
+ ):
149
+ instance.pk = results
150
+ if self.model._meta.db_default_db_columns:
151
+ await self._fetch_db_defaults_after_insert(instance)
152
+
153
+ # MySQL can only generate a single ROWID
154
+ # so if any other primary key, it won't generate what we want.
@@ -0,0 +1,101 @@
1
+ # Copyright (c) 2026 ropmyung (Rakko ORM modifications and additions).
2
+ # Derived from Tortoise ORM; maintained and modified for Rakko ORM.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+
5
+ from __future__ import annotations
6
+
7
+ from collections.abc import Sequence
8
+ from typing import TYPE_CHECKING, Any
9
+
10
+ from rakko.backends.base.schema_generator import BaseSchemaGenerator
11
+ from rakko.converters import encoders
12
+ from rakko.schema_quoting import MySQLQuotingMixin
13
+
14
+ if TYPE_CHECKING: # pragma: nocoverage
15
+ from rakko.backends.mysql.client import MySQLClient
16
+ from rakko.models import Model
17
+
18
+
19
+ class MySQLSchemaGenerator(MySQLQuotingMixin, BaseSchemaGenerator): # type: ignore[override]
20
+ DIALECT = "mysql"
21
+ TABLE_CREATE_TEMPLATE = "CREATE TABLE {exists}{table_name} ({fields}){extra}{comment};"
22
+ INDEX_CREATE_TEMPLATE = "{index_type}KEY `{index_name}` ({fields}){extra}"
23
+ UNIQUE_CONSTRAINT_CREATE_TEMPLATE = "UNIQUE KEY `{index_name}` ({fields})"
24
+ UNIQUE_INDEX_CREATE_TEMPLATE = UNIQUE_CONSTRAINT_CREATE_TEMPLATE
25
+ FIELD_TEMPLATE = "`{name}` {type}{nullable}{unique}{primary}{comment}{default}"
26
+ GENERATED_PK_TEMPLATE = "`{field_name}` {generated_sql}{comment}"
27
+ FK_TEMPLATE = (
28
+ "{constraint}FOREIGN KEY (`{db_column}`)"
29
+ " REFERENCES {table} (`{field}`) ON DELETE {on_delete}"
30
+ )
31
+ M2M_TABLE_TEMPLATE = (
32
+ "CREATE TABLE {exists}{table_name} (\n"
33
+ " `{backward_key}` {backward_type} NOT NULL,\n"
34
+ " `{forward_key}` {forward_type} NOT NULL,\n"
35
+ " {backward_fk},\n"
36
+ " {forward_fk}\n"
37
+ "){extra}{comment};"
38
+ )
39
+
40
+ def __init__(self, client: MySQLClient) -> None:
41
+ super().__init__(client)
42
+ self._field_indexes = [] # type: list[str]
43
+ self._foreign_keys = [] # type: list[str]
44
+
45
+ def _table_generate_extra(self, table: str) -> str:
46
+ return (
47
+ f" CHARACTER SET {self.client.charset}" if self.client.charset else "" # type: ignore
48
+ )
49
+
50
+ def _table_comment_generator(self, table: str, comment: str) -> str:
51
+ return f" COMMENT='{self._escape_comment(comment)}'"
52
+
53
+ def _column_comment_generator(self, table: str, column: str, comment: str) -> str:
54
+ return f" COMMENT '{self._escape_comment(comment)}'"
55
+
56
+ def _escape_default_value(self, default: Any):
57
+ return encoders.get(type(default))(default) # type: ignore
58
+
59
+ def _get_index_sql(
60
+ self,
61
+ model: type[Model],
62
+ field_names: Sequence[str],
63
+ safe: bool,
64
+ index_name: str | None = None,
65
+ index_type: str | None = None,
66
+ extra: str | None = None,
67
+ ) -> str:
68
+ """Get index SQLs, but keep them for ourselves"""
69
+ index_create_sql = super()._get_index_sql(
70
+ model, field_names, safe, index_name=index_name, index_type=index_type, extra=extra
71
+ )
72
+ self._field_indexes.append(index_create_sql)
73
+ return ""
74
+
75
+ def _create_fk_string(
76
+ self,
77
+ constraint_name: str,
78
+ db_column: str,
79
+ table: str,
80
+ field: str,
81
+ on_delete: str,
82
+ comment: str,
83
+ ) -> str:
84
+ constraint = f"CONSTRAINT `{constraint_name}` " if constraint_name else ""
85
+ fk = self.FK_TEMPLATE.format(
86
+ constraint=constraint,
87
+ db_column=db_column,
88
+ table=table,
89
+ field=field,
90
+ on_delete=on_delete,
91
+ )
92
+ if constraint_name:
93
+ self._foreign_keys.append(fk)
94
+ return comment
95
+ return fk
96
+
97
+ def _get_inner_statements(self) -> list[str]:
98
+ extra = self._foreign_keys + list(dict.fromkeys(self._field_indexes))
99
+ self._field_indexes.clear()
100
+ self._foreign_keys.clear()
101
+ return extra
@@ -0,0 +1,4 @@
1
+ # Copyright (c) 2026 ropmyung (Rakko ORM modifications and additions).
2
+ # Derived from Tortoise ORM; maintained and modified for Rakko ORM.
3
+ # SPDX-License-Identifier: Apache-2.0
4
+