snake-orm 0.1.0b1__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 (198) hide show
  1. snake_orm-0.1.0b1.dist-info/METADATA +366 -0
  2. snake_orm-0.1.0b1.dist-info/RECORD +198 -0
  3. snake_orm-0.1.0b1.dist-info/WHEEL +4 -0
  4. snake_orm-0.1.0b1.dist-info/entry_points.txt +2 -0
  5. snake_orm-0.1.0b1.dist-info/licenses/LICENSE +21 -0
  6. snakeorm/__init__.py +214 -0
  7. snakeorm/advisor.py +109 -0
  8. snakeorm/cli/__init__.py +3 -0
  9. snakeorm/cli/app.py +992 -0
  10. snakeorm/cli/discovery.py +179 -0
  11. snakeorm/cli/hooks.py +86 -0
  12. snakeorm/compiler/__init__.py +3 -0
  13. snakeorm/compiler/compiler.py +330 -0
  14. snakeorm/connection.py +228 -0
  15. snakeorm/contrib/__init__.py +17 -0
  16. snakeorm/contrib/asgi.py +192 -0
  17. snakeorm/contrib/config.py +264 -0
  18. snakeorm/contrib/deliver.py +256 -0
  19. snakeorm/contrib/django.py +245 -0
  20. snakeorm/contrib/sidecar.py +44 -0
  21. snakeorm/contrib/wsgi.py +176 -0
  22. snakeorm/core/__init__.py +1 -0
  23. snakeorm/core/config.py +173 -0
  24. snakeorm/core/converters.py +172 -0
  25. snakeorm/core/exceptions.py +175 -0
  26. snakeorm/core/placement.py +15 -0
  27. snakeorm/core/sentinels.py +37 -0
  28. snakeorm/core/signals.py +114 -0
  29. snakeorm/debug/__init__.py +42 -0
  30. snakeorm/debug/assets/css/panel.css +616 -0
  31. snakeorm/debug/assets/css/snake_orm_app.css +293 -0
  32. snakeorm/debug/assets/img/icon.svg +5 -0
  33. snakeorm/debug/assets/js/history.js +425 -0
  34. snakeorm/debug/assets/js/language.js +283 -0
  35. snakeorm/debug/assets/js/panel.js +241 -0
  36. snakeorm/debug/assets/js/snake_orm_app.js +82 -0
  37. snakeorm/debug/assets/pages/cli.html +28 -0
  38. snakeorm/debug/assets/pages/config.html +34 -0
  39. snakeorm/debug/assets/pages/database_first.html +29 -0
  40. snakeorm/debug/assets/pages/help.html +21 -0
  41. snakeorm/debug/assets/pages/history.html +27 -0
  42. snakeorm/debug/capture.py +234 -0
  43. snakeorm/debug/channel.py +131 -0
  44. snakeorm/debug/collector.py +144 -0
  45. snakeorm/debug/config.py +149 -0
  46. snakeorm/debug/html.py +578 -0
  47. snakeorm/debug/matrix.py +60 -0
  48. snakeorm/debug/origin.py +42 -0
  49. snakeorm/debug/otel/__init__.py +68 -0
  50. snakeorm/debug/otel/context.py +43 -0
  51. snakeorm/debug/otel/exporter.py +277 -0
  52. snakeorm/debug/otel/payload.py +97 -0
  53. snakeorm/debug/otel/report.py +29 -0
  54. snakeorm/debug/otel/spans.py +393 -0
  55. snakeorm/debug/otel/summary.py +59 -0
  56. snakeorm/debug/record.py +54 -0
  57. snakeorm/debug/report.py +311 -0
  58. snakeorm/debug/testing.py +23 -0
  59. snakeorm/decorators/__init__.py +13 -0
  60. snakeorm/decorators/abstract.py +26 -0
  61. snakeorm/decorators/db_first.py +104 -0
  62. snakeorm/decorators/function.py +28 -0
  63. snakeorm/decorators/model.py +268 -0
  64. snakeorm/decorators/polymorphic.py +140 -0
  65. snakeorm/decorators/result.py +167 -0
  66. snakeorm/decorators/row.py +90 -0
  67. snakeorm/decorators/trigger.py +47 -0
  68. snakeorm/decorators/view.py +149 -0
  69. snakeorm/dialects/__init__.py +6 -0
  70. snakeorm/dialects/base.py +373 -0
  71. snakeorm/dialects/capabilities.py +571 -0
  72. snakeorm/dialects/literals.py +46 -0
  73. snakeorm/dialects/matrix.py +384 -0
  74. snakeorm/dialects/mysql.py +519 -0
  75. snakeorm/dialects/postgres.py +504 -0
  76. snakeorm/dialects/sqlite.py +417 -0
  77. snakeorm/drivers/__init__.py +18 -0
  78. snakeorm/drivers/asyncbase.py +73 -0
  79. snakeorm/drivers/asyncdecorators.py +244 -0
  80. snakeorm/drivers/asyncpool.py +228 -0
  81. snakeorm/drivers/asyncpsycopg.py +124 -0
  82. snakeorm/drivers/asyncpymysql.py +50 -0
  83. snakeorm/drivers/asyncsqlite.py +30 -0
  84. snakeorm/drivers/base.py +76 -0
  85. snakeorm/drivers/failures.py +181 -0
  86. snakeorm/drivers/logging.py +167 -0
  87. snakeorm/drivers/pool.py +352 -0
  88. snakeorm/drivers/psycopg.py +188 -0
  89. snakeorm/drivers/pymysql.py +176 -0
  90. snakeorm/drivers/savepoints.py +46 -0
  91. snakeorm/drivers/sqlite.py +170 -0
  92. snakeorm/drivers/threaded.py +143 -0
  93. snakeorm/drivers/timeout.py +87 -0
  94. snakeorm/dto/__init__.py +55 -0
  95. snakeorm/dto/read.py +231 -0
  96. snakeorm/dto/region.py +326 -0
  97. snakeorm/dto/resolve.py +354 -0
  98. snakeorm/dto/spec.py +201 -0
  99. snakeorm/expressions/__init__.py +88 -0
  100. snakeorm/expressions/conditional.py +178 -0
  101. snakeorm/expressions/expression.py +810 -0
  102. snakeorm/expressions/functions.py +71 -0
  103. snakeorm/expressions/keys.py +299 -0
  104. snakeorm/expressions/paths.py +43 -0
  105. snakeorm/expressions/scalar.py +293 -0
  106. snakeorm/expressions/window.py +248 -0
  107. snakeorm/fields/__init__.py +68 -0
  108. snakeorm/fields/check.py +79 -0
  109. snakeorm/fields/column.py +316 -0
  110. snakeorm/fields/enum.py +64 -0
  111. snakeorm/fields/index.py +46 -0
  112. snakeorm/fields/relationship.py +738 -0
  113. snakeorm/fields/typed.py +736 -0
  114. snakeorm/helpers/__init__.py +1 -0
  115. snakeorm/helpers/annotations.py +21 -0
  116. snakeorm/helpers/inheritance.py +41 -0
  117. snakeorm/helpers/pyliteral.py +52 -0
  118. snakeorm/helpers/pytype.py +50 -0
  119. snakeorm/introspection/__init__.py +13 -0
  120. snakeorm/introspection/base.py +30 -0
  121. snakeorm/introspection/drift.py +78 -0
  122. snakeorm/introspection/models.py +633 -0
  123. snakeorm/introspection/mysql.py +367 -0
  124. snakeorm/introspection/postgres.py +397 -0
  125. snakeorm/introspection/sqlite.py +217 -0
  126. snakeorm/introspection/unsupported.py +94 -0
  127. snakeorm/linker/__init__.py +3 -0
  128. snakeorm/linker/linker.py +521 -0
  129. snakeorm/metadata/__init__.py +41 -0
  130. snakeorm/metadata/check.py +37 -0
  131. snakeorm/metadata/column.py +201 -0
  132. snakeorm/metadata/enum_storage.py +33 -0
  133. snakeorm/metadata/fk_action.py +19 -0
  134. snakeorm/metadata/foreign_key.py +26 -0
  135. snakeorm/metadata/index.py +43 -0
  136. snakeorm/metadata/index_method.py +19 -0
  137. snakeorm/metadata/int_size.py +20 -0
  138. snakeorm/metadata/json_storage.py +21 -0
  139. snakeorm/metadata/polymorphic.py +30 -0
  140. snakeorm/metadata/primary_key.py +23 -0
  141. snakeorm/metadata/relationship.py +60 -0
  142. snakeorm/metadata/relationship_kind.py +43 -0
  143. snakeorm/metadata/routine.py +26 -0
  144. snakeorm/metadata/server_default.py +20 -0
  145. snakeorm/metadata/table.py +97 -0
  146. snakeorm/metadata/table_kind.py +23 -0
  147. snakeorm/metadata/trigger.py +62 -0
  148. snakeorm/metadata/type_params.py +348 -0
  149. snakeorm/migration/__init__.py +88 -0
  150. snakeorm/migration/asyncrunner.py +168 -0
  151. snakeorm/migration/autodetect.py +96 -0
  152. snakeorm/migration/ddl.py +1172 -0
  153. snakeorm/migration/diff.py +701 -0
  154. snakeorm/migration/loader.py +77 -0
  155. snakeorm/migration/operations.py +952 -0
  156. snakeorm/migration/planner.py +78 -0
  157. snakeorm/migration/realize.py +420 -0
  158. snakeorm/migration/renames.py +153 -0
  159. snakeorm/migration/render.py +1095 -0
  160. snakeorm/migration/runner.py +314 -0
  161. snakeorm/migration/squash.py +60 -0
  162. snakeorm/migration/state.py +107 -0
  163. snakeorm/model.py +162 -0
  164. snakeorm/py.typed +0 -0
  165. snakeorm/query/__init__.py +9 -0
  166. snakeorm/query/compound.py +288 -0
  167. snakeorm/query/join_kind.py +19 -0
  168. snakeorm/query/joined.py +143 -0
  169. snakeorm/query/query.py +1001 -0
  170. snakeorm/query/recursive.py +244 -0
  171. snakeorm/registry/__init__.py +5 -0
  172. snakeorm/registry/by_module.py +163 -0
  173. snakeorm/registry/registry.py +166 -0
  174. snakeorm/session/__init__.py +8 -0
  175. snakeorm/session/asyncsession.py +638 -0
  176. snakeorm/session/coercion.py +306 -0
  177. snakeorm/session/factory.py +29 -0
  178. snakeorm/session/guards.py +269 -0
  179. snakeorm/session/isolation.py +23 -0
  180. snakeorm/session/mapper.py +213 -0
  181. snakeorm/session/planning.py +815 -0
  182. snakeorm/session/retry.py +96 -0
  183. snakeorm/session/session.py +871 -0
  184. snakeorm/session/shared.py +355 -0
  185. snakeorm/sql/__init__.py +18 -0
  186. snakeorm/sql/adapt.py +104 -0
  187. snakeorm/sql/aggregate.py +232 -0
  188. snakeorm/sql/condition.py +359 -0
  189. snakeorm/sql/delete.py +46 -0
  190. snakeorm/sql/insert.py +149 -0
  191. snakeorm/sql/joins.py +158 -0
  192. snakeorm/sql/pk_subquery.py +54 -0
  193. snakeorm/sql/refs.py +19 -0
  194. snakeorm/sql/resolver.py +28 -0
  195. snakeorm/sql/select.py +175 -0
  196. snakeorm/sql/update.py +82 -0
  197. snakeorm/sql/value.py +552 -0
  198. snakeorm/times.py +276 -0
@@ -0,0 +1,571 @@
1
+ """The BASE catalogue of capabilities: everything any engine can do, and what each one answers.
2
+
3
+ Three pieces and not one flat `bool` per capability, because a `bool` cannot do two things:
4
+
5
+ - **Be walked.** Warning at startup about everything the user's engine does not give them means
6
+ ITERATING the capabilities.
7
+ - **Say "halfway".** SQLite stores a `Decimal` and returns it exact, but it sorts it as TEXT
8
+ (`'9.99' > '10.00'`). Neither absent nor full.
9
+
10
+ Hence `Cap` (the catalogue), `Support` (tri-state with a reason) and `SnakeCapabilities`, which
11
+ forces every engine to answer the WHOLE catalogue — unlike a `frozenset` of supported capabilities,
12
+ where the one you forgot to declare is simply not there, and "not there" reads as "not supported".
13
+ A silent default, in the ORM that shouts. Here one goes missing and it does not start.
14
+
15
+ Mind the boundary: this is what the engine KNOWS HOW TO DO. The SHAPE of the statement
16
+ (`DROP INDEX x` vs `DROP INDEX x ON t`) is not a capability —both engines drop indexes— and lives in
17
+ `SnakeSyntax`, which is translated in the emitter and never stops the plan.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ from collections.abc import Mapping
23
+ from dataclasses import dataclass, field
24
+ from enum import Enum, auto
25
+ from types import MappingProxyType
26
+
27
+ from snakeorm.core.exceptions import SnakeDialectError
28
+
29
+
30
+ class Cap(Enum):
31
+ """Everything an engine CAN do. Adding a member forces all three dialects to answer.
32
+
33
+ Two families, and the distinction matters because the plan treats them differently:
34
+
35
+ - The **structural** ones decide whether an operation can be executed. If they are missing, the
36
+ ORM stops and shouts.
37
+ - The **type-fidelity** ones never stop anything: the type is stored all the same (falling back
38
+ to TEXT if it has to) and the value comes back exact. What gets degraded is the SQL SEMANTICS
39
+ —sorting, comparing, operating— and startup warns about that.
40
+ """
41
+
42
+ # --- Structural: if they are missing, the operation cannot be executed ---
43
+ RETURNING = auto()
44
+ ROW_CONSTRUCTOR = auto()
45
+ TRANSACTIONAL_DDL = auto()
46
+ UPSERT = auto()
47
+ # Two, and not one, because SQLite 3.53 accepted the CHECK and kept refusing the other three.
48
+ CHECK_CONSTRAINT_DDL = auto()
49
+ ADD_CONSTRAINT = auto() # the rest: FOREIGN KEY, UNIQUE, PRIMARY KEY
50
+ ALTER_COLUMN = auto()
51
+ SCHEMAS = auto()
52
+ STORED_FUNCTIONS = auto()
53
+ ROW_LOCKING = auto()
54
+ SET_ISOLATION = auto()
55
+ TEXT_IN_PRIMARY_KEY = auto()
56
+ COMMENTS = auto()
57
+ REPLACE_VIEW = auto()
58
+ PARENTHESISED_COMPOUND = auto()
59
+ # A `WITH [RECURSIVE] ...` used as a BRANCH of a UNION/EXCEPT/INTERSECT. It is STRUCTURAL and it
60
+ # is NOT the same question as `PARENTHESISED_COMPOUND`: MySQL parenthesises branches perfectly
61
+ # well and still answers 1064 to a CTE inside one, so the two flags part company on the middle
62
+ # engine — which is exactly the shape of thing that cannot be inferred from the other.
63
+ CTE_IN_COMPOUND_BRANCH = auto()
64
+ ILIKE = auto()
65
+ INDEX_METHODS = auto()
66
+ # `CREATE INDEX ... WHERE`: the index that only covers the rows matching a condition, which is
67
+ # what makes soft-delete and multi-tenancy affordable. It is STRUCTURAL and not advisory,
68
+ # because it does both things this family does: it changes the SQL that gets written (the
69
+ # `WHERE` is dropped where it does not exist) and it stops the plan when dropping it would
70
+ # change the meaning — a partial UNIQUE widened into a full one forbids rows the domain allows.
71
+ PARTIAL_INDEXES = auto()
72
+ # `ALTER TABLE ... DROP COLUMN` over a column a FOREIGN KEY still holds. It is STRUCTURAL and it
73
+ # is not the same question as `ADD_CONSTRAINT`: MySQL adds and drops constraints perfectly well
74
+ # and still refuses this, because InnoDB needs the index the key sits on (error 1553). Measured
75
+ # on all three, and only ONE says yes — which is why it could never be inferred from how
76
+ # complete an engine looks.
77
+ DROP_COLUMN_CASCADES_FK = auto()
78
+
79
+ # --- Type fidelity: they never stop the plan, they only warn about what is lost ---
80
+ DECIMAL_ORDERING = auto()
81
+ TIMESTAMPTZ = auto()
82
+ INTERVAL = auto()
83
+ JSON = auto()
84
+ UUID = auto()
85
+ BOOLEAN = auto()
86
+ INT_WIDTHS = auto()
87
+ ARRAYS = auto()
88
+ FLOAT_SPECIALS = auto()
89
+ # Adding MONTHS or YEARS to a date, which is the only part of date arithmetic a calendar has to
90
+ # interpret. Days, hours, minutes and seconds are a fixed span and the three engines agree on
91
+ # them exactly; the end of a month is where they part. It sits in this family and not the
92
+ # structural one because nothing is refused — the date is computed and comes back, and what
93
+ # differs is WHICH date, which is precisely a semantics warning.
94
+ CALENDAR_INTERVAL = auto()
95
+ # ILIKE is in this family and not among the structural ones, and it was the case that made the
96
+ # distinction worth writing down. Every engine matches without regard to case: what changes is
97
+ # the SPELLING (`syntax.has_ilike`) and how much the folding covers. Declared `Nope` here, it
98
+ # said the engine could not do something it does in fact do — and the reason text gave it away
99
+ # by explaining the fallback.
100
+
101
+
102
+ PLAN_CAPS: frozenset[Cap] = frozenset(
103
+ {
104
+ Cap.RETURNING,
105
+ Cap.ROW_CONSTRUCTOR,
106
+ Cap.TRANSACTIONAL_DDL,
107
+ Cap.UPSERT,
108
+ Cap.CHECK_CONSTRAINT_DDL,
109
+ Cap.ADD_CONSTRAINT,
110
+ Cap.ALTER_COLUMN,
111
+ Cap.SCHEMAS,
112
+ Cap.STORED_FUNCTIONS,
113
+ Cap.ROW_LOCKING,
114
+ Cap.SET_ISOLATION,
115
+ Cap.TEXT_IN_PRIMARY_KEY,
116
+ Cap.COMMENTS,
117
+ Cap.REPLACE_VIEW,
118
+ Cap.PARENTHESISED_COMPOUND,
119
+ Cap.CTE_IN_COMPOUND_BRANCH,
120
+ Cap.PARTIAL_INDEXES,
121
+ Cap.DROP_COLUMN_CASCADES_FK,
122
+ }
123
+ )
124
+ """The capabilities SOMEBODY reads to decide: they stop an operation or change the shape of the SQL.
125
+
126
+ The distinction is not documentation, it is what makes the catalogue checkable. A capability in this
127
+ list that nobody reads is dead metadata —the ORM would claim to take it into account and would not—,
128
+ and that has already happened twice in this project: `db_comment` was stored without anything
129
+ emitting a `COMMENT ON`, and `supports_add_constraint` was declared in all three dialects without a
130
+ single reader, while foreign keys simply did not exist on SQLite.
131
+ `test_every_plan_capability_has_a_consumer` checks it mechanically, which is the only way that has
132
+ worked here.
133
+ """
134
+
135
+ ADVISORY_CAPS: frozenset[Cap] = frozenset(Cap) - PLAN_CAPS
136
+ """The ones that do NOT change the plan: they are declared in order to WARN.
137
+
138
+ The type-fidelity ones land here because the model works just the same (the value goes in and comes
139
+ out exact) and what is lost is the SQL semantics. And `INDEX_METHODS` too, even though it is not a
140
+ type one: the thing that enforces it is the dialect's own `index_method()`, which rejects the method
141
+ it does not know instead of emitting a plain index and lying. It is here so that the startup warning
142
+ counts it.
143
+ """
144
+
145
+
146
+ @dataclass(frozen=True, slots=True)
147
+ class Full:
148
+ """The engine does it, and does it properly. There is nothing to tell the user."""
149
+
150
+
151
+ @dataclass(frozen=True, slots=True)
152
+ class Degraded:
153
+ """The engine does it, but lying about something. It WORKS: the plan does not stop, the user
154
+ finds out.
155
+
156
+ It is the state of almost everything that falls back to TEXT on SQLite: the value goes in and
157
+ comes out exact, and what is lost is that the engine does not treat it as what it is when
158
+ sorting, comparing or operating.
159
+ """
160
+
161
+ reason: str
162
+
163
+ def __post_init__(self) -> None:
164
+ """The reason is MANDATORY: it is the text the user reads at startup, not a comment."""
165
+ _demand_reason(self.reason, "Degraded")
166
+
167
+
168
+ @dataclass(frozen=True, slots=True)
169
+ class Nope:
170
+ """The engine does not do it. Any operation that needs it stops and the ORM explains why."""
171
+
172
+ reason: str
173
+
174
+ def __post_init__(self) -> None:
175
+ """Same as in `Degraded`: with no reason, the error would say "cannot be done" and leave you just as lost."""
176
+ _demand_reason(self.reason, "Nope")
177
+
178
+
179
+ @dataclass(frozen=True, slots=True)
180
+ class Since:
181
+ """The capability ARRIVES with a version of the engine. A declaration, not a fourth state.
182
+
183
+ It collapses into `below` or `Full` when the capabilities are built, so nothing downstream ever
184
+ sees a `Since`.
185
+
186
+ `below` is written out because only the capability knows what its absence MEANS: a missing CHECK
187
+ stops the operation (`Nope`), a missing native type only warns (`Degraded`). Resolving to a
188
+ fixed state turned the first into the second and let the plan emit SQL the engine refuses.
189
+ """
190
+
191
+ version: tuple[int, ...]
192
+ sentence: str
193
+ below: Degraded | Nope
194
+
195
+ def resolve(self, engine_version: tuple[int, ...] | None) -> Full | Degraded | Nope:
196
+ """`Full` if the engine reaches it; otherwise `below`, with BOTH versions in the reason."""
197
+ if engine_version is not None and tuple(engine_version) >= self.version:
198
+ return Full()
199
+ seen = ".".join(str(n) for n in engine_version) if engine_version else "unknown"
200
+ want = ".".join(str(n) for n in self.version)
201
+ said = f"{self.below.reason} (this engine is {seen}; `{self.sentence}` exists from {want})"
202
+ return type(self.below)(said)
203
+
204
+
205
+ Support = Full | Degraded | Nope
206
+ """What an engine answers about a capability. The union (and not a bool plus a string) is what makes
207
+ it possible to derive both the plan's decision and the warning from it, with no way for them to
208
+ contradict each other."""
209
+
210
+
211
+ def _demand_reason(reason: str, kind: str) -> None:
212
+ """Demands a non-empty reason. It lives on its own so `Degraded` and `Nope` cannot diverge."""
213
+ if not reason.strip():
214
+ raise SnakeDialectError(
215
+ f"{kind}() demands a reason: it is the text shown to the user when the session opens. "
216
+ f"Without it, the warning says that something cannot be done and does not say what to "
217
+ f"do about it."
218
+ )
219
+
220
+
221
+ @dataclass(frozen=True, slots=True)
222
+ class SnakeCapabilities:
223
+ """What ONE engine answers to the whole catalogue. Incomplete, it does not get built.
224
+
225
+ Exhaustiveness is checked at construction time —that is, when the dialect is imported—, which
226
+ for practical purposes is the same moment a type-checker would fail, and in exchange it allows
227
+ iteration.
228
+ """
229
+
230
+ declared: Mapping[Cap, Support | Since]
231
+ """What the dialect WROTE, `Since` included, so it can still be read as it was declared."""
232
+ engine_version: tuple[int, ...] | None = None
233
+ """The engine version, when it can be known without a connection (SQLite reads it from its
234
+ module). `Since` resolves against it; every other state ignores it."""
235
+ resolved: Mapping[Cap, Support] = field(init=False)
236
+ """What the engine ANSWERS: the same map with every `Since` collapsed. Everything reads here,
237
+ which is why no caller ever has to know a version was involved."""
238
+
239
+ def __post_init__(self) -> None:
240
+ """Checks that they are ALL there and freezes the map. Without this, a missing one would read
241
+ as absent.
242
+
243
+ No number: it said "all 22" and there were already 23. A count written by hand in prose is a
244
+ copy of the catalogue that nobody updates, and in a module whose job is precisely to stop
245
+ something from going undeclared, it is especially ugly. `Cap` does the counting.
246
+ """
247
+ missing = [cap.name for cap in Cap if cap not in self.declared]
248
+ if missing:
249
+ raise SnakeDialectError(
250
+ f"This dialect does not answer {len(missing)} capability(ies) of the catalogue: "
251
+ f"{', '.join(missing)}. Every engine declares them ALL: an undeclared capability "
252
+ f"would read as unsupported without anyone having decided so."
253
+ )
254
+ # A `Since` is resolved HERE, against the engine version, so that `declared` only ever holds
255
+ # the three states. Everything downstream — `can()`, `caveats()`, the plan — keeps reading
256
+ # what it always read and never learns that a version was involved.
257
+ answers = {
258
+ cap: support.resolve(self.engine_version)
259
+ if isinstance(support, Since)
260
+ else support
261
+ for cap, support in self.declared.items()
262
+ }
263
+ object.__setattr__(self, "declared", MappingProxyType(dict(self.declared)))
264
+ object.__setattr__(self, "resolved", MappingProxyType(answers))
265
+
266
+ def support_for(self, cap: Cap) -> Support:
267
+ """What this engine answers about a capability. Never `None`: the catalogue is complete."""
268
+ return self.resolved[cap]
269
+
270
+ def can(self, cap: Cap) -> bool:
271
+ """Whether the engine can, even if badly. `Degraded` is a YES: the model works.
272
+
273
+ Treating it as a no would forbid a `Decimal` on SQLite, which stores and returns the exact value.
274
+ """
275
+ return not isinstance(self.resolved[cap], Nope)
276
+
277
+ def caveats(self) -> tuple[tuple[Cap, str], ...]:
278
+ """What the user has to be told: (capability, reason) for everything that is not full.
279
+
280
+ In catalogue order, which is stable, so the warning does not dance between runs.
281
+ """
282
+ return tuple(
283
+ (cap, support.reason)
284
+ for cap in Cap
285
+ if isinstance(support := self.resolved[cap], (Degraded, Nope))
286
+ )
287
+
288
+
289
+ class EmptyInsertStyle(Enum):
290
+ """How an INSERT with NO values is written, that is, a row that is all defaults.
291
+
292
+ It is not a laboratory case: any join or event table whose only field of its own is the
293
+ autoincrement id triggers it. `DEFAULT VALUES` is the standard and MySQL does not have it, so
294
+ until this existed the ORM was writing MySQL something it rejects — and it only showed up when
295
+ seeding against a real server.
296
+ """
297
+
298
+ DEFAULT_VALUES = auto()
299
+ """`INSERT INTO t DEFAULT VALUES` (Postgres, SQLite)."""
300
+ EMPTY_ROW = auto()
301
+ """`INSERT INTO t () VALUES ()` (MySQL): empty column list and empty row."""
302
+
303
+
304
+ class AlterColumnStyle(Enum):
305
+ """The SHAPE of an `ALTER TABLE ... ALTER COLUMN`. It is not a capability: it is grammar.
306
+
307
+ Postgres and MySQL both change a column's type; they write the statement differently. Filing
308
+ this under capabilities is what left `emit_alter_column` hard-wired to Postgres's shape.
309
+ """
310
+
311
+ POSTGRES_TYPE_USING = auto()
312
+ """`ALTER COLUMN c TYPE t USING c::t`, with `SET`/`DROP NOT NULL` in separate statements."""
313
+ MYSQL_MODIFY = auto()
314
+ """`MODIFY COLUMN c t NOT NULL`: a single clause that rewrites the whole definition."""
315
+ UNSUPPORTED = auto()
316
+ """The engine cannot (SQLite: it would require rebuilding the table). The plan stops before emitting."""
317
+
318
+
319
+ class CommentStyle(Enum):
320
+ """How a comment is SPELLED. It is grammar, not capability — the same split as `AlterColumnStyle`.
321
+
322
+ Filing it under capabilities is what kept `Cap.COMMENTS` answering `Nope` on MySQL for an engine
323
+ that stores comments perfectly well: the dialect's own reason said "it has no COMMENT ON: MySQL
324
+ comments INLINE", which is a sentence about SYNTAX used to justify a claim about the ENGINE. A
325
+ `db_comment` was dropped on a server that would have kept it, and `AlterTableComment` was refused
326
+ with "there is no comment to change". Spelling one intention differently on each engine is
327
+ literally a dialect's job.
328
+ """
329
+
330
+ COMMENT_ON = auto()
331
+ """`COMMENT ON TABLE t IS 'x'` (Postgres): a statement of its own, and `IS NULL` removes it."""
332
+ INLINE = auto()
333
+ """MySQL: a CLAUSE, never a statement. `CREATE TABLE ... COMMENT = 'x'` for a new table,
334
+ `ALTER TABLE t COMMENT = 'x'` to change one, and a COLUMN comment only inside the column's own
335
+ definition — which is why changing one alone costs a whole `MODIFY COLUMN`."""
336
+ UNSUPPORTED = auto()
337
+ """The engine stores none (SQLite). `Cap.COMMENTS` is `Nope`, so the plan stops before the
338
+ emitter runs and whatever shape it would have written never reaches a server."""
339
+
340
+
341
+ @dataclass(frozen=True, slots=True)
342
+ class SnakeSyntax:
343
+ """SHAPE differences between engines. They are TRANSLATED in the emitter; they never stop the plan.
344
+
345
+ Kept apart from the capabilities on purpose. When `triggers_are_table_scoped` lived among the
346
+ `supports_*` it looked like a rare, lonely case, and its sibling for indexes was never written:
347
+ `emit_drop_index` emitted Postgres's shape and broke the rollback of any migration with an index
348
+ on MySQL. With the family declared, the gap is visible.
349
+ """
350
+
351
+ triggers_are_table_scoped: bool
352
+ """`DROP TRIGGER x ON t` (Postgres) versus `DROP TRIGGER x` (MySQL and SQLite, without the table).
353
+
354
+ It used to put MySQL in the first group while `mysql.py` itself declares it `False`, with a
355
+ comment right next to it saying the opposite. The code was right; the prose explaining it was
356
+ lying, which is the worst combination: whoever reads the attribute in order to write a new
357
+ dialect trusts what is here.
358
+ """
359
+ indexes_are_table_scoped: bool
360
+ """`DROP INDEX x ON t` (MySQL) versus `DROP INDEX x` (Postgres, SQLite)."""
361
+ alter_column_style: AlterColumnStyle
362
+ """How the change of an existing column is written."""
363
+ empty_insert_style: EmptyInsertStyle
364
+ """How an INSERT of a row that is all default values is written."""
365
+ comment_style: CommentStyle
366
+ """How a table's and a column's comment are spelled: a statement of their own, or a clause."""
367
+ defer_constraints_statement: str | None = None
368
+ """How this engine is told to postpone foreign key checking until the COMMIT, or `None`.
369
+
370
+ Only an engine that has to REMAKE a table to change a constraint needs it: mid-rebuild the old
371
+ table is dropped, and any key pointing at it is violated at that instant even though the table
372
+ comes back three statements later. Deferring moves the verdict to the COMMIT, where it is the
373
+ ENGINE that answers — so nothing is switched off and nothing is checked by a statement whose
374
+ rows nobody reads.
375
+
376
+ `None` on Postgres and MySQL, and not because they lack the feature: they can change a
377
+ constraint in place, so there is no window to hold open. Declaring it here rather than writing
378
+ the pragma into the emitter is what keeps a second engine without `ADD CONSTRAINT` from
379
+ inheriting SQLite's spelling.
380
+ """
381
+ has_nulls_ordering: bool = False
382
+ """Whether the engine spells `ORDER BY x ASC NULLS LAST`, or needs the portable form.
383
+
384
+ A SHAPE difference, and it belongs here for the same reason `has_ilike` does: all three engines
385
+ ORDER nulls, and what changes is how you ask. Filing it in the catalogue would say an engine
386
+ cannot do something it does — the mistake `Cap.ILIKE` was written to record.
387
+
388
+ Measured on both servers this dialect family serves, because `mysql.py` exists partly because it
389
+ "cannot promise what only one of them does": MariaDB 11.8.8 and MySQL 8.4.11 both answer
390
+ `ERROR 1064` to `NULLS LAST`, and both accept `ORDER BY (x IS NULL) ASC, x ASC` — inside a
391
+ UNION as well. So the two agree and the fallback covers them.
392
+
393
+ Defaults to `False` so an engine that says nothing gets the portable form that works everywhere,
394
+ rather than a keyword it may not have. Same default, same reason, as its neighbour.
395
+ """
396
+ has_ilike: bool = False
397
+ """Whether the engine spells a case-insensitive match `ILIKE`, or needs the portable fallback.
398
+
399
+ A SHAPE difference and it belongs here, not in the catalogue. All three engines DO match without
400
+ regard to case: Postgres with the keyword, the other two through `LOWER(a) LIKE LOWER(b)`, which
401
+ the emitter writes. Nothing is refused and no plan stops.
402
+
403
+ It used to be read off `Cap.ILIKE`, and that is what made `Nope` mean two things — see the note
404
+ on `Cap.ILIKE` itself. Defaults to `False` so an engine that says nothing gets the fallback that
405
+ works everywhere, rather than a keyword it may not have.
406
+ """
407
+ round_casts_first_argument_to: str | None = None
408
+ """What `ROUND(x, digits)` has to cast its value to on this engine, or `None` for no cast.
409
+
410
+ Postgres has `ROUND(double precision)` and `ROUND(numeric, int)` and NO
411
+ `ROUND(double precision, int)`, so asking a float for decimal places reached the server as
412
+ `function round(double precision, integer) does not exist` — the driver explaining a decision
413
+ this ORM made, which is what the project refuses everywhere else. It was bug #34's open half.
414
+
415
+ A SHAPE difference and not a capability, which is why it lives here: all three engines round to
416
+ a digit count, they just do not all spell it the same way. Declaring the target type rather than
417
+ a boolean is what stops the emitter from holding a Postgres spelling for everybody.
418
+
419
+ Applied unconditionally when there is a digit count, because the emitter cannot see the
420
+ argument's Python type —`SnakeFuncCall[T]` erases it— and does not need to: on Postgres the cast
421
+ is a no-op for a `numeric` and correct for a `float` or an `int`.
422
+ """
423
+
424
+
425
+ @dataclass(frozen=True, slots=True)
426
+ class SnakeLimits:
427
+ """The engine's NUMERIC ceilings. `None` is not "no ceiling": it is "it ignores the declared parameter".
428
+
429
+ It is SQLite's answer, which has a per-column affinity and nothing else. Any number would assert
430
+ a limit that does not exist, and a small one would reject models this engine stores just fine.
431
+ """
432
+
433
+ bind_params: int
434
+ """Placeholders per statement. The bulk INSERT slices into batches with this. Postgres: 65535."""
435
+ numeric_precision: int | None
436
+ """TOTAL digits of a NUMERIC/DECIMAL. Postgres 1000, MySQL 65."""
437
+ numeric_scale: int | None
438
+ """Decimal places. NOT the same number as the precision: MySQL stops at 30 with a precision of 65."""
439
+ fractional_seconds: int | None
440
+ """Fractional-second digits of a date. Postgres and MySQL 6 (Python's `datetime`)."""
441
+
442
+
443
+ class DerivedFlags:
444
+ """BRIDGE: the same old `supports_*`/`max_*`, derived from the catalogue. It is temporary, on purpose.
445
+
446
+ The three objects above are the source of truth, but some forty reads spread over fifteen
447
+ modules are still written as `dialect.supports_upsert`. Migrating them ALL in the same move that
448
+ introduces the catalogue would be a big change where the failure is, on top of that, silent: two
449
+ tables resolve the flag by STRING (`getattr`), so a name that stopped existing would not break
450
+ compilation, only behaviour.
451
+
452
+ With this bridge, the catalogue comes in without touching a single one of those reads, and they
453
+ migrate one at a time afterwards. When none are left, this class gets deleted and the dialects
454
+ stop inheriting anything.
455
+ """
456
+
457
+ capabilities: SnakeCapabilities
458
+ syntax: SnakeSyntax
459
+ limits: SnakeLimits
460
+
461
+ @property
462
+ def supports_returning(self) -> bool:
463
+ """Whether it can return the rows it wrote (`INSERT ... RETURNING`)."""
464
+ return self.capabilities.can(Cap.RETURNING)
465
+
466
+ @property
467
+ def supports_row_constructor(self) -> bool:
468
+ """Whether it understands `(a, b) IN ((...), (...))`; if not, the emitter uses the OR-of-ANDs."""
469
+ return self.capabilities.can(Cap.ROW_CONSTRUCTOR)
470
+
471
+ @property
472
+ def supports_transactional_ddl(self) -> bool:
473
+ """Whether DDL goes inside the transaction: with it, an N-step migration is all-or-nothing."""
474
+ return self.capabilities.can(Cap.TRANSACTIONAL_DDL)
475
+
476
+ @property
477
+ def supports_upsert(self) -> bool:
478
+ """Whether it can do an INSERT that is idempotent on conflict. Without it, `upsert()` raises: emulating it is a race."""
479
+ return self.capabilities.can(Cap.UPSERT)
480
+
481
+ @property
482
+ def supports_add_constraint(self) -> bool:
483
+ """Whether it accepts `ALTER TABLE ... ADD CONSTRAINT`. It decides the SHAPE of the migration plan."""
484
+ return self.capabilities.can(Cap.ADD_CONSTRAINT)
485
+
486
+ @property
487
+ def supports_alter_column(self) -> bool:
488
+ """Whether it can change the type or nullability of an existing column."""
489
+ return self.capabilities.can(Cap.ALTER_COLUMN)
490
+
491
+ @property
492
+ def supports_schemas(self) -> bool:
493
+ """Whether it has named schemas (`CREATE SCHEMA`)."""
494
+ return self.capabilities.can(Cap.SCHEMAS)
495
+
496
+ @property
497
+ def supports_stored_functions(self) -> bool:
498
+ """Whether it stores named functions/procedures.
499
+
500
+ It is a capability of its OWN, and it was not before: the plan used to ask about
501
+ `supports_schemas` to decide whether it could create a function. It matched on all three
502
+ engines and that is why nobody noticed, but they are different things and the catalogue puts
503
+ it out in the open.
504
+ """
505
+ return self.capabilities.can(Cap.STORED_FUNCTIONS)
506
+
507
+ @property
508
+ def supports_row_locking(self) -> bool:
509
+ """Whether it can lock ROWS (`SELECT ... FOR UPDATE`)."""
510
+ return self.capabilities.can(Cap.ROW_LOCKING)
511
+
512
+ @property
513
+ def supports_comments(self) -> bool:
514
+ """Whether it STORES table and column comments — not whether it spells them `COMMENT ON`.
515
+
516
+ The distinction is the bug this property was read through: MySQL has no `COMMENT ON` and
517
+ keeps comments perfectly well, and answering `False` here dropped a `db_comment` on a server
518
+ that stores it. The spelling is `syntax.comment_style`.
519
+ """
520
+ return self.capabilities.can(Cap.COMMENTS)
521
+
522
+ @property
523
+ def supports_replace_view(self) -> bool:
524
+ """Whether it can do `CREATE OR REPLACE VIEW`. Without it, altering a view is drop+create."""
525
+ return self.capabilities.can(Cap.REPLACE_VIEW)
526
+
527
+ @property
528
+ def supports_parenthesised_compound(self) -> bool:
529
+ """Whether the branches of a UNION/EXCEPT/INTERSECT accept parentheses (which make the LIMIT belong to the branch)."""
530
+ return self.capabilities.can(Cap.PARENTHESISED_COMPOUND)
531
+
532
+ @property
533
+ def supports_cte_in_compound_branch(self) -> bool:
534
+ """Whether a `WITH RECURSIVE` may be a BRANCH of a UNION/EXCEPT/INTERSECT. Only Postgres."""
535
+ return self.capabilities.can(Cap.CTE_IN_COMPOUND_BRANCH)
536
+
537
+ @property
538
+ def supports_ilike(self) -> bool:
539
+ """Whether it spells the case-insensitive match `ILIKE`, or needs `LOWER(a) LIKE LOWER(b)`.
540
+
541
+ Read off the SYNTAX and no longer off `Cap.ILIKE`, which is the whole of that fix: what the
542
+ emitter needs here is which SHAPE to write, and the catalogue answers a different question —
543
+ how good the result is. Reading one for the other is what let a `Nope` sit on something that
544
+ works.
545
+ """
546
+ return self.syntax.has_ilike
547
+
548
+ @property
549
+ def triggers_are_table_scoped(self) -> bool:
550
+ """`DROP TRIGGER x ON t` versus `DROP TRIGGER x`. Grammar, not capability."""
551
+ return self.syntax.triggers_are_table_scoped
552
+
553
+ @property
554
+ def max_bind_params(self) -> int:
555
+ """Ceiling of placeholders per statement."""
556
+ return self.limits.bind_params
557
+
558
+ @property
559
+ def max_numeric_precision(self) -> int | None:
560
+ """Total digits of a NUMERIC/DECIMAL, or `None` if the engine ignores the parameter."""
561
+ return self.limits.numeric_precision
562
+
563
+ @property
564
+ def max_numeric_scale(self) -> int | None:
565
+ """Decimal places of a NUMERIC/DECIMAL, or `None`."""
566
+ return self.limits.numeric_scale
567
+
568
+ @property
569
+ def max_fractional_seconds(self) -> int | None:
570
+ """Fractional-second digits of a date, or `None`."""
571
+ return self.limits.fractional_seconds
@@ -0,0 +1,46 @@
1
+ """How a NUMBER is written as a SQL literal, in one place for the three dialects.
2
+
3
+ The DDL door: where a value cannot be a placeholder — a `DEFAULT`, a `CHECK`, the `WHERE` of a
4
+ partial index. Everything else goes out parametrised, which is why this file is small and why what
5
+ it gets wrong is expensive.
6
+
7
+ It used to be `str(value)`, so `float('inf')` came out as bare `inf` — an IDENTIFIER. Postgres reads
8
+ `DEFAULT inf` as a column reference; SQLite creates the table and hands back `('inf', 'text')` from
9
+ a `REAL NOT NULL`.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ import math
15
+ from decimal import Decimal
16
+
17
+ from snakeorm.core.exceptions import SnakeDialectError
18
+
19
+
20
+ def numeric_literal(value: int | float | Decimal, dialect_name: str) -> str:
21
+ """The SQL literal of a number, or a refusal if it has no literal to be written as.
22
+
23
+ `int` returns FIRST because `math.isfinite` on a big one raises `OverflowError`, which would
24
+ kill a `NUMERIC` default the engine stores happily.
25
+
26
+ The refusal spans the three engines instead of splitting per engine, and `NaN` is why: the
27
+ infinities have per-engine literals, but SQLite loses a `NaN` and Postgres does not — so the
28
+ rule would have to split by VALUE as well, inside the half of `literal()` that has no engine in
29
+ it. It is a formatter failure, not a capability one: `Cap.FLOAT_SPECIALS` exists and Postgres
30
+ answers `Full()` to it.
31
+ """
32
+ if isinstance(value, int):
33
+ return str(value)
34
+ # `Decimal` asks ITSELF, because `math.isfinite` cannot look at all of them:
35
+ # `math.isfinite(Decimal('sNaN'))` raises `ValueError: cannot convert signaling NaN to float`,
36
+ # so the guard would blow up with the wrong exception on the one value most likely to have got
37
+ # there by accident.
38
+ finite = value.is_finite() if isinstance(value, Decimal) else math.isfinite(value)
39
+ if not finite:
40
+ raise SnakeDialectError(
41
+ f"{dialect_name} has no SQL literal for {value!r}: a DDL literal has to be finite. "
42
+ f"`str()` of it is a bareword —`inf`, `NaN`— which an engine reads as an identifier, "
43
+ f"not as a value, and SQLite accepts it into a REAL column as text without complaining. "
44
+ f"Store it through a parametrised write instead, where the driver types it properly."
45
+ )
46
+ return str(value)