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,94 @@
1
+ """The ONE catalogue of `unsupported` warnings, shared by the three introspectors.
2
+
3
+ Every engine asks its own catalogue — `pg_catalog`, `information_schema`, `sqlite_master` — and that
4
+ difference is permanent and legitimate. What none of them does any more is WORD the answer: each
5
+ query tags every row with a kind and hands over the pieces, and the sentence is written here.
6
+
7
+ It used to be written inside each engine's SQL, and the three drifted exactly as one would expect
8
+ from three copies nothing compares. For the same finding Postgres emitted `columna de tipo no
9
+ representable: ` and MySQL `column of a type with no equivalent: `; where those two said
10
+ `trigger: {name} on {table}`, SQLite said `trigger not representable in the model: {name}` and never
11
+ named the table. One of the three was in Spanish, and it did not merely get printed: `cli/app.py`
12
+ writes these sentences as comments inside the `models.py` that `scaffold` generates and the user
13
+ commits into their own repository.
14
+
15
+ The sentence IS the product here. It is the only trace left of what the mirror does not cover, and
16
+ whoever reads the generated file has nothing else to tell them the database holds more than this.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ from collections.abc import Sequence
22
+ from enum import StrEnum
23
+
24
+
25
+ class SnakeUnsupportedKind(StrEnum):
26
+ """What an `unsupported` row describes. It travels as the row's FIRST column.
27
+
28
+ The engines agree on this vocabulary and disagree on which of these kinds they can detect, which
29
+ is a difference in what each catalogue is able to answer — not a difference in wording.
30
+ """
31
+
32
+ TRIGGER = "trigger"
33
+ ROUTINE = "routine"
34
+ EXPRESSION_INDEX = "expression_index"
35
+ UNREPRESENTABLE_COLUMN = "unrepresentable_column"
36
+ CHECK = "check"
37
+
38
+
39
+ def trigger_warning(name: str, table: str) -> str:
40
+ """A trigger: still there and still firing, and the model has no way to mention it."""
41
+ return f"trigger: {name} on {table}"
42
+
43
+
44
+ def check_warning(name: str, table: str, expression: str) -> str:
45
+ """A CHECK constraint: the database rejects rows the model believes are fine.
46
+
47
+ `snake_check` takes a `SnakeCondition`, never a string, so a mirror cannot declare one:
48
+ rebuilding the condition from the server's own text would be writing a SQL parser per engine.
49
+ The expression travels VERBATIM because it is the only thing that tells the reader what is
50
+ being enforced behind their model.
51
+ """
52
+ return f"check: {name} on {table} ({expression})"
53
+
54
+
55
+ def routine_warning(name: str) -> str:
56
+ """A stored routine (procedure or function): the metadata graph has no place for one."""
57
+ return f"routine: {name}"
58
+
59
+
60
+ def expression_index_warning(name: str) -> str:
61
+ """An index over an EXPRESSION: the graph indexes columns, never expressions."""
62
+ return f"expression index: {name}"
63
+
64
+
65
+ def unrepresentable_column_warning(table: str, column: str, sql_type: str) -> str:
66
+ """A column whose SQL type has no equivalent in a Python annotation."""
67
+ return f"column of a type with no equivalent: {table}.{column} ({sql_type})"
68
+
69
+
70
+ def warning_from_row(row: Sequence[object]) -> str:
71
+ """Word one `(kind, first, second, third)` row of an engine's unsupported query.
72
+
73
+ An unknown kind blows up instead of being skipped. Skipping would be the exact silence this
74
+ module exists to prevent: the engine bothered to report the object, and dropping it quietly is
75
+ what makes a mirror look complete when it is not.
76
+ """
77
+ kind = SnakeUnsupportedKind(str(row[0]))
78
+ first, second, third = ("" if piece is None else str(piece) for piece in row[1:4])
79
+ match kind:
80
+ case SnakeUnsupportedKind.TRIGGER:
81
+ return trigger_warning(first, second)
82
+ case SnakeUnsupportedKind.ROUTINE:
83
+ return routine_warning(first)
84
+ case SnakeUnsupportedKind.EXPRESSION_INDEX:
85
+ return expression_index_warning(first)
86
+ case SnakeUnsupportedKind.UNREPRESENTABLE_COLUMN:
87
+ return unrepresentable_column_warning(first, second, third)
88
+ case SnakeUnsupportedKind.CHECK:
89
+ return check_warning(first, second, third)
90
+
91
+
92
+ def warnings_from_rows(rows: Sequence[Sequence[object]]) -> list[str]:
93
+ """Word every row an engine's unsupported query returned, in the order it returned them."""
94
+ return [warning_from_row(row) for row in rows]
@@ -0,0 +1,3 @@
1
+ """SnakeORM's Linker: wires the relationships up at the end (Phase 2)."""
2
+
3
+ from snakeorm.linker.linker import snake_link as snake_link
@@ -0,0 +1,521 @@
1
+ """The Linker (Phase 2): resolves the relationships once every model is in place.
2
+
3
+ Register everything -> link at the end. The target comes out of the annotation; the FK pairs map
4
+ local columns to the target's PK by position. Two passes: to-one (FK) and then to-many (the
5
+ inverses), which read the child's already-resolved FK. Idempotent.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import dataclasses
11
+ import types
12
+ from typing import Any, Union, get_args, get_origin, get_type_hints
13
+
14
+ from snakeorm.core.exceptions import (
15
+ SnakeModelDefinitionError,
16
+ SnakeRegistryError,
17
+ SnakeUnknownRelationship,
18
+ )
19
+ from snakeorm.fields import SnakeToMany, SnakeToOne
20
+ from snakeorm.helpers.annotations import unwrap_optional
21
+ from snakeorm.helpers.inheritance import collect_inherited
22
+ from snakeorm.metadata import (
23
+ SnakeCheckInfo,
24
+ SnakeColumnInfo,
25
+ SnakeForeignKeyInfo,
26
+ SnakeIndexInfo,
27
+ SnakeRelationshipKind,
28
+ SnakeRelationshipInfo,
29
+ SnakeTableInfo,
30
+ SnakeThroughInfo,
31
+ )
32
+ from snakeorm.registry.by_module import resolve_in_module, type_checking_names
33
+ from snakeorm.registry import SnakeRegistry, registry
34
+
35
+
36
+ def _guard_same_database(
37
+ model: type,
38
+ attr: str,
39
+ target_cls: type,
40
+ source_table: SnakeTableInfo | None,
41
+ target_table: SnakeTableInfo,
42
+ ) -> None:
43
+ """Forbids a relationship whose target lives in ANOTHER database.
44
+
45
+ Neither an FK (a constraint does not cross databases) nor a JOIN (a SELECT lives inside a single
46
+ one) is possible. It is cut off at link time (at startup) instead of letting the `ALTER TABLE`
47
+ or a JOIN blow up in production.
48
+ """
49
+ if source_table is None or source_table.database == target_table.database:
50
+ return
51
+ raise SnakeModelDefinitionError(
52
+ f"Relationship {model.__name__}.{attr} crosses databases: {model.__name__} lives in "
53
+ f"'{source_table.database}' and {target_cls.__name__} in '{target_table.database}'. There is "
54
+ f"neither a foreign key nor a JOIN possible across connections. Move one of the two, or "
55
+ f"store the identifier as a plain column and resolve it yourself with two queries."
56
+ )
57
+
58
+
59
+ def _union_members(annotation: Any) -> tuple[Any, ...] | None:
60
+ """The members of a union annotation, or `None` when it is not a union.
61
+
62
+ Recognises both spellings, `Union[X, Y]` and PEP 604's `X | Y`, for the same reason
63
+ `unwrap_optional` does: a model file may use either.
64
+ """
65
+ if get_origin(annotation) in (Union, types.UnionType):
66
+ return get_args(annotation)
67
+ return None
68
+
69
+
70
+ def _name_of(annotation: Any) -> str:
71
+ """A readable name for an annotation member, for error messages only.
72
+
73
+ `getattr` and not `.__name__` because the thing being named is precisely what may NOT have one:
74
+ formatting a `types.UnionType` with `.__name__` is the crash this guard replaced.
75
+ """
76
+ if annotation is type(None):
77
+ return "None"
78
+ return getattr(annotation, "__name__", str(annotation))
79
+
80
+
81
+ def _guard_one_target_model(model: type, attr: str, annotation: Any) -> None:
82
+ """Forbids a to-one whose target is a union of MODELS (`SnakeToOne[Card | Transfer]`).
83
+
84
+ A relationship resolves to ONE target table: it is a single foreign key and a single JOIN.
85
+ A union names several, and there is no row shape that answers for all of them.
86
+
87
+ This guard is also what makes the typing of `SnakeToOne.__get__` sound, and that dependency runs
88
+ the other way from how it looks. The descriptor unwraps `| None` through an overload on the type
89
+ of `self`, and that overload has a hole exactly here: with two models plus `| None`, mypy infers
90
+ `type[Never]` — a type and not an error, so it goes green over a meaningless expression — while
91
+ pyright infers the union of the two. Refusing the shape makes the hole unreachable. See
92
+ `SnakeToOne.__get__`, whose docstring names this function.
93
+
94
+ It must be asked BEFORE `unwrap_optional`, which returns the first non-`None` member: given
95
+ `Card | Transfer | None` it hands back `Card` and drops `Transfer` without a word, so a guard
96
+ placed after it would be looking at a union that had already been silently resolved.
97
+ """
98
+ members = _union_members(annotation)
99
+ if members is None:
100
+ return
101
+ models = tuple(member for member in members if member is not type(None))
102
+ if len(models) < 2:
103
+ return
104
+ names = " | ".join(_name_of(member) for member in models)
105
+ raise SnakeRegistryError(
106
+ f"Relationship {model.__name__}.{attr} points at a union of models ({names}). A "
107
+ f"relationship points at one model: it is one foreign key and one JOIN, and a union names "
108
+ f"several tables with no single row shape between them. If these are one hierarchy, point "
109
+ f"at the BASE class they share instead of listing them — this ORM expresses polymorphism "
110
+ f"with single-table inheritance, so the concrete class is resolved from the discriminator "
111
+ f"when the rows are read."
112
+ )
113
+
114
+
115
+ def _guard_a_collection_is_never_optional(
116
+ model: type, attr: str, annotation: Any
117
+ ) -> None:
118
+ """Forbids `SnakeToMany[Child | None]`: a collection comes back EMPTY, never absent.
119
+
120
+ A to-one's `| None` states something true about the data — the foreign key may be NULL. A
121
+ to-many's states nothing: a parent with no children is handed `[]`. And because instance access
122
+ is typed `list[M]`, the annotation would additionally be promising a list that may contain
123
+ `None`s, which no path in the ORM can produce.
124
+
125
+ Refused rather than quietly unwrapped, because the annotation expresses a misunderstanding of
126
+ what a collection is and silently correcting it would leave that misunderstanding in the model
127
+ file. Before this, the to-many branch never called `unwrap_optional` at all and the annotation
128
+ fell over with the same `AttributeError` about `__name__`.
129
+ """
130
+ members = _union_members(annotation)
131
+ if members is None:
132
+ return
133
+ names = " | ".join(_name_of(member) for member in members)
134
+ raise SnakeRegistryError(
135
+ f"To-many relationship {model.__name__}.{attr} declares a union ({names}). A collection is "
136
+ f"not optional and does not hold optionals: a parent with no children gets an empty list, "
137
+ f"never `None`. Declare the child model on its own "
138
+ f"(SnakeToMany[{_name_of(members[0])}])."
139
+ )
140
+
141
+
142
+ def _validate_pairing(
143
+ model: type,
144
+ attr: str,
145
+ target_cls: type,
146
+ local: tuple[str, ...],
147
+ target_columns: tuple[SnakeColumnInfo, ...],
148
+ source_table: SnakeTableInfo | None,
149
+ ) -> None:
150
+ """Validates the POSITIONAL pairing source_column[i] <-> target_PK[i] before fixing the FK.
151
+
152
+ The mapping is by position, and a wrong order in `snake_to_one()` would silently cross columns
153
+ over. A loud catch: (1) the same number of local columns and of target PK columns; (2) Python
154
+ types that match pair by pair.
155
+ """
156
+ if len(local) != len(target_columns):
157
+ raise SnakeModelDefinitionError(
158
+ f"Relationship {model.__name__}.{attr} declares {len(local)} FK column(s) "
159
+ f"[{', '.join(local)}] but the PK of {target_cls.__name__} has "
160
+ f"{len(target_columns)} column(s) [{', '.join(c.name for c in target_columns)}]. "
161
+ f"snake_to_one() needs EXACTLY one local column per column of the target PK, "
162
+ f"in the same order."
163
+ )
164
+ if source_table is None:
165
+ return # with no local table the types cannot be read (hand-made info); only the count
166
+ for source_name, target_column in zip(local, target_columns, strict=True):
167
+ source_column = source_table.get_column(source_name)
168
+ if source_column is None:
169
+ continue # another validation (the compiler) covers the non-existent column
170
+ if source_column.python_type is not target_column.python_type:
171
+ raise SnakeModelDefinitionError(
172
+ f"Relationship {model.__name__}.{attr} pairs local column "
173
+ f"'{source_name}' ({source_column.python_type.__name__}) with remote column "
174
+ f"'{target_column.name}' ({target_column.python_type.__name__}) of the PK of "
175
+ f"{target_cls.__name__}, but their types do NOT match. The pairing is POSITIONAL: "
176
+ f"check the ORDER of the arguments of snake_to_one()."
177
+ )
178
+
179
+
180
+ def hints_of(model: type) -> dict[str, Any]:
181
+ """A model's resolved annotations, seeing what its module imports under `if TYPE_CHECKING:`.
182
+
183
+ `get_type_hints` evaluates against the module's RUNTIME globals, and a name imported only inside
184
+ the block is never there. That is not an edge case: it is the layout every project lands in the
185
+ moment its models span more than one file, because `accounts` needs `Note` and `notes` needs
186
+ `Account`, so one of the two imports HAS to go inside the block or the package stops importing
187
+ at all. Measured, with both at runtime:
188
+
189
+ ImportError: cannot import name 'Account' from partially initialized module
190
+
191
+ Without this, the linker dies on `NameError: name 'Note' is not defined`, a message naming
192
+ neither the relationship nor the model nor anything the user typed.
193
+
194
+ The block is read only AFTER `get_type_hints` has already failed. Reading it eagerly would put a
195
+ source parse and a set of imports in front of every model in every project, to serve the one
196
+ that needs it; and a module whose names are all in globals gets the same answer either way.
197
+
198
+ This is not a new mechanism: `through="Tagging"` already resolves by reading the very same
199
+ block.
200
+ """
201
+ try:
202
+ return get_type_hints(model)
203
+ except NameError:
204
+ return get_type_hints(model, localns=type_checking_names(model))
205
+
206
+
207
+ def _to_one_relationships(
208
+ model: type, reg: SnakeRegistry
209
+ ) -> tuple[SnakeRelationshipInfo, ...]:
210
+ """Resolves a model's to-one relationships by reading its SnakeToOne descriptors."""
211
+ hints = hints_of(model)
212
+ result: list[SnakeRelationshipInfo] = []
213
+ # Walks the MRO: it also resolves the to-one relationships INHERITED from an abstract base.
214
+ for attr, value in collect_inherited(model, SnakeToOne).items():
215
+ # `SnakeToOne[Brand | None]` is the way of saying "this relationship may have no partner".
216
+ # It is unwrapped just like on a column: the target is `Brand`, and the `| None` is what the
217
+ # checker will use to force the case to be handled.
218
+ declared = get_args(hints[attr])[0]
219
+ # BEFORE unwrapping: `unwrap_optional` collapses `Card | Transfer | None` to `Card` and
220
+ # drops the rest in silence, so asking afterwards would be asking about a union that no
221
+ # longer exists.
222
+ _guard_one_target_model(model, attr, declared)
223
+ target_cls, optional_relation = unwrap_optional(declared)
224
+ target_table = reg.table_of(target_cls)
225
+ if target_table is None:
226
+ raise SnakeRegistryError(
227
+ f"Relationship {model.__name__}.{attr} points at {target_cls.__name__}, "
228
+ f"which is not registered (did you import it?)."
229
+ )
230
+ value._target_table = target_table
231
+ source_table = reg.table_of(model)
232
+ _guard_same_database(model, attr, target_cls, source_table, target_table)
233
+ local = value.local_column_names()
234
+ _guard_nullability_parity(model, attr, local, source_table, optional_relation)
235
+ target_columns = target_table.primary_key.columns
236
+ _validate_pairing(model, attr, target_cls, local, target_columns, source_table)
237
+ remote = tuple(column.name for column in target_columns)
238
+ pairs = tuple(zip(local, remote, strict=True))
239
+ foreign_key = SnakeForeignKeyInfo(
240
+ target=target_cls.__name__,
241
+ pairs=pairs,
242
+ on_delete=value.on_delete,
243
+ on_update=value.on_update,
244
+ )
245
+ result.append(
246
+ SnakeRelationshipInfo(
247
+ name=attr,
248
+ target=target_cls.__name__,
249
+ kind=SnakeRelationshipKind.TO_ONE,
250
+ foreign_key=foreign_key,
251
+ # RESOLVED qualified target: reducing it to `__name__` threw the identity away and
252
+ # two apps each with their own `Customer` clobbered each other in the by-name index
253
+ # (a crossed FK).
254
+ target_table=f"{target_table.schema}.{target_table.name}",
255
+ )
256
+ )
257
+ return tuple(result)
258
+
259
+
260
+ def _guard_nullability_parity(
261
+ model: type,
262
+ attr: str,
263
+ local: tuple[str, ...],
264
+ source_table: SnakeTableInfo | None,
265
+ optional_relation: bool,
266
+ ) -> None:
267
+ """Demands that the relationship say the same thing as its foreign key about possibly not existing.
268
+
269
+ With an FK that accepts NULL, `include()` does a LEFT JOIN, finds no partner and the ORM hangs a
270
+ `None` off the relationship. If the type says `SnakeToOne[Brand]`, the checker approves
271
+ `car.brand.name` and in production out comes an `AttributeError`: a lie of a type, which is
272
+ the one thing this ORM does not allow itself.
273
+
274
+ It is demanded in BOTH directions. With a `NOT NULL` FK there is always a partner, so declaring
275
+ the relationship optional would force an impossible case to be handled — noise that hides the
276
+ `None`s that are real.
277
+
278
+ With a COMPOSITE key it is enough for ONE column to accept NULL: a key with a member at NULL
279
+ matches no row at all, so the relationship can come back empty just the same.
280
+ """
281
+ if (
282
+ source_table is None
283
+ ): # pragma: no cover - defensive: the model is registered before linking
284
+ return
285
+ by_name = {column.name: column for column in source_table.columns}
286
+ columns = [by_name[name] for name in local if name in by_name]
287
+ if not columns: # pragma: no cover - `_validate_pairing` already rejected it
288
+ return
289
+ fk_optional = any(column.nullable for column in columns)
290
+ if fk_optional == optional_relation:
291
+ return
292
+ names = ", ".join(local)
293
+ if fk_optional:
294
+ raise SnakeModelDefinitionError(
295
+ f"{model.__name__}.{attr} is declared WITHOUT `| None`, but its foreign key "
296
+ f"({names}) DOES accept NULL. When the key is NULL there is nothing to fetch and the "
297
+ f"relationship is `None`, so the type would be lying: declare it "
298
+ f"`SnakeToOne[... | None]` and the checker will force you to handle that case."
299
+ )
300
+ raise SnakeModelDefinitionError(
301
+ f"{model.__name__}.{attr} is declared with `| None`, but its foreign key ({names}) "
302
+ f"is NOT NULL, so there is always a partner and the relationship is never `None`. Drop the "
303
+ f"`| None`: forcing an impossible case to be handled hides the ones that are real."
304
+ )
305
+
306
+
307
+ def _to_many_relationships(
308
+ model: type, reg: SnakeRegistry
309
+ ) -> tuple[SnakeRelationshipInfo, ...]:
310
+ """Resolves the to-many (inverse) relationships: they read the child's resolved FK (pass 2)."""
311
+ hints = hints_of(model)
312
+ result: list[SnakeRelationshipInfo] = []
313
+ # Walks the MRO: it also resolves the to-many relationships INHERITED from an abstract base.
314
+ for attr, value in collect_inherited(model, SnakeToMany).items():
315
+ child_cls = get_args(hints[attr])[0]
316
+ _guard_a_collection_is_never_optional(model, attr, child_cls)
317
+ if value.through is not None:
318
+ result.append(_link_through(model, attr, value, child_cls, reg))
319
+ continue
320
+ child_table = reg.table_of(child_cls)
321
+ if child_table is None:
322
+ raise SnakeRegistryError(
323
+ f"To-many relationship {model.__name__}.{attr} points at "
324
+ f"{child_cls.__name__}, which is not registered (did you import it?)."
325
+ )
326
+ value._target_table = child_table
327
+ child_fk = next(
328
+ (rel for rel in child_table.relationships if rel.name == value.fk_name),
329
+ None,
330
+ )
331
+ if child_fk is None:
332
+ raise SnakeUnknownRelationship(
333
+ f"To-many relationship {model.__name__}.{attr} reverses "
334
+ f"'{value.fk_name}', which is not an FK relationship of {child_cls.__name__}."
335
+ )
336
+ result.append(
337
+ # Reuses the child's FK: its pairs (child_col -> parent_PK) serve for the select-in.
338
+ SnakeRelationshipInfo(
339
+ name=attr,
340
+ target=child_cls.__name__,
341
+ kind=SnakeRelationshipKind.TO_MANY,
342
+ foreign_key=child_fk.foreign_key,
343
+ target_table=f"{child_table.schema}.{child_table.name}",
344
+ )
345
+ )
346
+ return tuple(result)
347
+
348
+
349
+ def _link_through(
350
+ model: type,
351
+ attr: str,
352
+ value: SnakeToMany[Any],
353
+ target_cls: type,
354
+ reg: SnakeRegistry,
355
+ ) -> SnakeRelationshipInfo:
356
+ """Resolves a MANY-TO-MANY: the bridge's two hops, already turned into columns.
357
+
358
+ Here and not at query time because here the classes are right in front of us; storing names and
359
+ looking them up again produced bug #14 (an FK pointing at the table of a same-named model).
360
+ """
361
+ # A CLASS resolves directly; only a NAME has to be looked up. The docstring above says the
362
+ # classes are right in front of us, and that was true of the target and false of the bridge:
363
+ # `through=` only took a string, so it went through `model_by_name` — the index `register()`
364
+ # overwrites in silence, which is the index bug #14 was about. Worse than the query case,
365
+ # because the metadata is compiled ONCE: the wrong bridge ends up frozen in the
366
+ # `SnakeThroughInfo`, and the `via`/`to` pair usually matches on both homonyms, so the SELECT
367
+ # comes out valid and reads the table that is not.
368
+ named = value.through if isinstance(value.through, str) else None
369
+ # A NAME is resolved in the module that WROTE it, never through the registry's by-name index.
370
+ # That index is kept by whichever model registered last, and it does not fail loudly: with two
371
+ # apps declaring their own `Tagging`, the `via`/`to` pair matches on both, so the SELECT is
372
+ # valid and the `ALTER TABLE ... REFERENCES` applies without complaint, leaving referential
373
+ # integrity pointing at a stranger's table.
374
+ #
375
+ # The ANNOTATION of this very same declaration already resolves this way —`SnakeToOne["Post"]`
376
+ # goes through `get_type_hints`, which evaluates against the module's globals.
377
+ bridge_cls = resolve_in_module(model, named) if named is not None else value.through
378
+ bridge_table = reg.table_of(bridge_cls) if isinstance(bridge_cls, type) else None
379
+ if bridge_table is None:
380
+ # The message names what the USER wrote — the string they typed, or the class they passed —
381
+ # and not the table, which they never mentioned.
382
+ spelling = (
383
+ named
384
+ if named is not None
385
+ else getattr(value.through, "__name__", value.through)
386
+ )
387
+ raise SnakeRegistryError(
388
+ f"The many-to-many {model.__name__}.{attr} uses bridge '{spelling}', which is "
389
+ f"not registered. Did you import it? The bridge is a plain model with @snake_model."
390
+ )
391
+
392
+ def hop(name: str, role: str) -> tuple[tuple[str, str], ...]:
393
+ """The (bridge_column, endpoint_column) pairs of one of the bridge's relationships."""
394
+ relation = next(
395
+ (rel for rel in bridge_table.relationships if rel.name == name), None
396
+ )
397
+ if relation is None or relation.kind is not SnakeRelationshipKind.TO_ONE:
398
+ available = sorted(
399
+ rel.name
400
+ for rel in bridge_table.relationships
401
+ if rel.kind is SnakeRelationshipKind.TO_ONE
402
+ )
403
+ raise SnakeUnknownRelationship(
404
+ f"The many-to-many {model.__name__}.{attr} declares {role}='{name}', which is "
405
+ f"not a to-one relationship of '{value.through}'. The ones it has: "
406
+ f"{', '.join(available) or '(none)'}."
407
+ )
408
+ return relation.foreign_key.pairs
409
+
410
+ target_table = reg.table_of(target_cls)
411
+ if target_table is None:
412
+ raise SnakeRegistryError(
413
+ f"The many-to-many {model.__name__}.{attr} points at {target_cls.__name__}, which is "
414
+ f"not registered (did you import it?)."
415
+ )
416
+ value._target_table = target_table
417
+ to_parent = hop(value.via or "", "via")
418
+ to_target = hop(value.to or "", "to")
419
+ return SnakeRelationshipInfo(
420
+ name=attr,
421
+ target=target_cls.__name__,
422
+ kind=SnakeRelationshipKind.TO_MANY_THROUGH,
423
+ # The "main" FK is the bridge's one towards the PARENT: it is the one filtering the select-in.
424
+ foreign_key=SnakeForeignKeyInfo(target=model.__name__, pairs=to_parent),
425
+ through=SnakeThroughInfo(
426
+ table=f"{bridge_table.schema}.{bridge_table.name}",
427
+ to_parent=to_parent,
428
+ to_target=to_target,
429
+ ),
430
+ target_table=f"{target_table.schema}.{target_table.name}",
431
+ )
432
+
433
+
434
+ def _merge_polymorphic_columns(reg: SnakeRegistry) -> None:
435
+ """Lifts onto each polymorphic BASE the columns belonging to all of its children.
436
+
437
+ The physical table is ONE, so the base has to know its children's columns or the `CREATE TABLE`
438
+ would come out without them. It goes here and not in the decorator because when `Animal` is
439
+ decorated the children do not exist yet (resolving it earlier would depend on the import order).
440
+ """
441
+ contributed: dict[type, list[SnakeTableInfo]] = {}
442
+ for model in reg.models():
443
+ table = reg.table_of(model)
444
+ if table is None or not table.is_polymorphic_child:
445
+ continue
446
+ base = next(
447
+ (
448
+ ancestor
449
+ for ancestor in model.__mro__[1:]
450
+ if (ancestor_table := reg.table_of(ancestor)) is not None
451
+ and ancestor_table.polymorphic is not None
452
+ and ancestor_table.polymorphic.is_base
453
+ ),
454
+ None,
455
+ )
456
+ if base is not None:
457
+ contributed.setdefault(base, []).append(table)
458
+
459
+ for base, children in contributed.items():
460
+ table = reg.table_of(base)
461
+ if table is None: # pragma: no cover
462
+ continue
463
+ # Not just COLUMNS: also the indexes and CHECKs the child declared over them, or the base's
464
+ # `CREATE TABLE` silently comes out without a constraint. They are identified by their name
465
+ # resolved against the SAME physical table, so the discriminator's own one dedupes itself.
466
+ known = {column.name for column in table.columns}
467
+ known_indexes = {i.resolved_name(table.name) for i in table.indexes}
468
+ known_checks = {c.resolved_name(table.name) for c in table.checks}
469
+ new_columns: list[SnakeColumnInfo] = []
470
+ new_indexes: list[SnakeIndexInfo] = []
471
+ new_checks: list[SnakeCheckInfo] = []
472
+ for child in children:
473
+ for column in child.columns:
474
+ if column.name not in known:
475
+ known.add(column.name)
476
+ new_columns.append(column)
477
+ for index in child.indexes:
478
+ name = index.resolved_name(table.name)
479
+ if name not in known_indexes:
480
+ known_indexes.add(name)
481
+ new_indexes.append(index)
482
+ for check in child.checks:
483
+ name = check.resolved_name(table.name)
484
+ if name not in known_checks:
485
+ known_checks.add(name)
486
+ new_checks.append(check)
487
+ if new_columns or new_indexes or new_checks:
488
+ reg.register(
489
+ base,
490
+ dataclasses.replace(
491
+ table,
492
+ columns=(*table.columns, *new_columns),
493
+ indexes=(*table.indexes, *new_indexes),
494
+ checks=(*table.checks, *new_checks),
495
+ ),
496
+ )
497
+
498
+
499
+ def snake_link(reg: SnakeRegistry = registry) -> None:
500
+ """Links every model: pass 1 (to-one/FK), pass 2 (to-many/inverses)."""
501
+ _merge_polymorphic_columns(reg)
502
+ for model in reg.models():
503
+ table = reg.table_of(model)
504
+ if table is None:
505
+ continue
506
+ reg.register(
507
+ model,
508
+ dataclasses.replace(table, relationships=_to_one_relationships(model, reg)),
509
+ )
510
+ for model in reg.models():
511
+ table = reg.table_of(model)
512
+ if table is None:
513
+ continue
514
+ to_many = _to_many_relationships(model, reg)
515
+ if to_many:
516
+ reg.register(
517
+ model,
518
+ dataclasses.replace(
519
+ table, relationships=(*table.relationships, *to_many)
520
+ ),
521
+ )
@@ -0,0 +1,41 @@
1
+ """SnakeORM's immutable metadata graph.
2
+
3
+ Frozen structures the Model Compiler produces ONCE; the runtime never re-inspects the class.
4
+ Re-exported with a redundant alias (`X as X`) instead of a string `__all__`: these are
5
+ IDENTIFIERS, so a rename drags them along and the checkers recognise it as an explicit
6
+ re-export.
7
+ """
8
+
9
+ from snakeorm.metadata.check import SnakeCheckInfo as SnakeCheckInfo
10
+ from snakeorm.metadata.column import SnakeColumnInfo as SnakeColumnInfo
11
+ from snakeorm.metadata.enum_storage import SnakeEnumStorage as SnakeEnumStorage
12
+ from snakeorm.metadata.fk_action import SnakeFkAction as SnakeFkAction
13
+ from snakeorm.metadata.foreign_key import SnakeForeignKeyInfo as SnakeForeignKeyInfo
14
+ from snakeorm.metadata.index import SnakeIndexInfo as SnakeIndexInfo
15
+ from snakeorm.metadata.index_method import SnakeIndexMethod as SnakeIndexMethod
16
+ from snakeorm.metadata.int_size import SnakeIntSize as SnakeIntSize
17
+ from snakeorm.metadata.json_storage import SnakeJsonStorage as SnakeJsonStorage
18
+ from snakeorm.metadata.type_params import SnakeDateTimeParams as SnakeDateTimeParams
19
+ from snakeorm.metadata.type_params import SnakeFloatParams as SnakeFloatParams
20
+ from snakeorm.metadata.type_params import SnakeTimeParams as SnakeTimeParams
21
+ from snakeorm.metadata.type_params import SnakeDecimalParams as SnakeDecimalParams
22
+ from snakeorm.metadata.type_params import SnakeIntParams as SnakeIntParams
23
+ from snakeorm.metadata.type_params import SnakeJsonParams as SnakeJsonParams
24
+ from snakeorm.metadata.type_params import SnakeStrParams as SnakeStrParams
25
+ from snakeorm.metadata.type_params import SnakeTypeParams as SnakeTypeParams
26
+ from snakeorm.metadata.polymorphic import SnakePolymorphicInfo as SnakePolymorphicInfo
27
+ from snakeorm.metadata.primary_key import SnakePrimaryKeyInfo as SnakePrimaryKeyInfo
28
+ from snakeorm.metadata.relationship_kind import (
29
+ SnakeRelationshipKind as SnakeRelationshipKind,
30
+ )
31
+ from snakeorm.metadata.relationship import (
32
+ SnakeRelationshipInfo as SnakeRelationshipInfo,
33
+ )
34
+ from snakeorm.metadata.relationship import SnakeThroughInfo as SnakeThroughInfo
35
+ from snakeorm.metadata.routine import SnakeRoutineInfo as SnakeRoutineInfo
36
+ from snakeorm.metadata.server_default import SnakeServerDefault as SnakeServerDefault
37
+ from snakeorm.metadata.table import SnakeTableInfo as SnakeTableInfo
38
+ from snakeorm.metadata.table_kind import SnakeTableKind as SnakeTableKind
39
+ from snakeorm.metadata.trigger import SnakeTriggerEvent as SnakeTriggerEvent
40
+ from snakeorm.metadata.trigger import SnakeTriggerInfo as SnakeTriggerInfo
41
+ from snakeorm.metadata.trigger import SnakeTriggerTiming as SnakeTriggerTiming