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,397 @@
1
+ """PostgreSQL introspector: it reads `information_schema`/`pg_catalog` and returns the graph."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import date, datetime, time, timedelta
6
+ from decimal import Decimal
7
+ from uuid import UUID
8
+
9
+ from snakeorm.core.exceptions import SnakeMigrationError, SnakeModelDefinitionError
10
+ from snakeorm.core.placement import DEFAULT_SCHEMA
11
+ from snakeorm.drivers import SnakeDriver
12
+ from snakeorm.introspection.unsupported import (
13
+ SnakeUnsupportedKind,
14
+ warnings_from_rows,
15
+ )
16
+ from snakeorm.times import SnakeUtc
17
+ from snakeorm.metadata import (
18
+ SnakeColumnInfo,
19
+ SnakeDateTimeParams,
20
+ SnakeDecimalParams,
21
+ SnakeForeignKeyInfo,
22
+ SnakeIndexInfo,
23
+ SnakeIntParams,
24
+ SnakeIntSize,
25
+ SnakeJsonParams,
26
+ SnakeJsonStorage,
27
+ SnakePrimaryKeyInfo,
28
+ SnakeRelationshipKind,
29
+ SnakeRelationshipInfo,
30
+ SnakeStrParams,
31
+ SnakeTableInfo,
32
+ SnakeTypeParams,
33
+ )
34
+
35
+ # The INVERSE Postgres → Python mapping. It is not the exact inverse of `_POSTGRES_TYPES`: several
36
+ # SQL types collapse onto the same Python one (`text`/`varchar`/`char` → `str`). Introspection is
37
+ # not bijective.
38
+ _PYTHON_TYPES: dict[str, type] = {
39
+ "integer": int,
40
+ "bigint": int,
41
+ "smallint": int,
42
+ "text": str,
43
+ "character varying": str,
44
+ "character": str,
45
+ "boolean": bool,
46
+ "double precision": float,
47
+ "real": float,
48
+ "numeric": Decimal,
49
+ "bytea": bytes,
50
+ "date": date,
51
+ # Postgres's TWO date types are different and the mirror has to tell them apart: the first
52
+ # stores an INSTANT (and in Python that is `SnakeUtc`), the second a WALL-CLOCK TIME.
53
+ # Collapsing them into `datetime` meant scaffolding a TIMESTAMPTZ produced a model that says
54
+ # TIMESTAMP — without blowing up, and without anybody noticing until the next `drift`.
55
+ "timestamp with time zone": SnakeUtc,
56
+ "timestamp without time zone": datetime,
57
+ "time without time zone": time,
58
+ "interval": timedelta,
59
+ "uuid": UUID,
60
+ "jsonb": dict,
61
+ "json": dict,
62
+ }
63
+
64
+ # The width of the integer read → its `int_size`, so scaffolding re-emits the SAME type. Without
65
+ # this a legacy `INTEGER` would come back with the default `BIGINT` and the generated file would
66
+ # widen it in silence.
67
+ _INT_SIZES: dict[str, SnakeIntSize] = {
68
+ "smallint": SnakeIntSize.SMALLINT,
69
+ "integer": SnakeIntSize.INTEGER,
70
+ "bigint": SnakeIntSize.BIGINT,
71
+ }
72
+
73
+ # Postgres's two date types -> whether the column carries a time zone. The mirror has to tell them
74
+ # apart: they are DIFFERENT types in the database, and each has its own declarator.
75
+ _TIMESTAMP_TZ: dict[str, bool] = {
76
+ "timestamp with time zone": True,
77
+ "timestamp without time zone": False,
78
+ }
79
+
80
+ # The backing of the JSON read from the database → its knob, so scaffolding does not drift (a legacy
81
+ # `json` is not re-emitted as `jsonb`, which would normalise it).
82
+ _JSON_STORAGES: dict[str, SnakeJsonStorage] = {
83
+ "jsonb": SnakeJsonStorage.JSONB,
84
+ "json": SnakeJsonStorage.JSON,
85
+ }
86
+
87
+
88
+ def _type_params(
89
+ data_type: str, max_length: int | None, precision: int | None, scale: int | None
90
+ ) -> SnakeTypeParams | None:
91
+ """The parameters of the family the type read from the database really belongs to.
92
+
93
+ All FIVE knobs used to be fired at every column, so an `integer` came back carrying a
94
+ `json_storage=JSONB` and a `max_length=None` that meant nothing. With one object per family you
95
+ have to CHOOSE one, and choosing forces you to look at the type — which is the right thing.
96
+
97
+ `None` for whatever has no parameters, including a `numeric` WITHOUT precision: Postgres allows
98
+ the unconstrained NUMERIC and the mirror must be able to reproduce it as it is.
99
+
100
+ The parameters validate their own range, and here nobody writes the values: the database brings
101
+ them. A `NUMERIC` with a negative scale —a Postgres 15 extension, which the ORM does not model—
102
+ would trip that guard with a message telling the user about what they "declared", when they
103
+ declared nothing. It is translated into an INTROSPECTION error, which is what really happened.
104
+ """
105
+ if data_type == "numeric":
106
+ if precision is None:
107
+ return None
108
+ try:
109
+ return SnakeDecimalParams(precision, scale)
110
+ except SnakeModelDefinitionError as error:
111
+ raise SnakeMigrationError(
112
+ f"The database has a NUMERIC({precision},{scale}) this ORM cannot declare: "
113
+ f"{error} If it comes from a Postgres 15 extension (negative scales, or scales "
114
+ f"larger than the precision), the mirror cannot reproduce it: exclude that column "
115
+ f"or redeclare it in the database."
116
+ ) from error
117
+ if data_type in _TIMESTAMP_TZ:
118
+ # The time zone HAS to travel in the parameters, not be deduced from the Python type later:
119
+ # the generator picks the declarator by reading `with_timezone`, and without these
120
+ # parameters it read the default (`False`) and emitted `snake_datetime()` over a
121
+ # `SnakeColumn[SnakeUtc]` — a contradiction its own guard rejects. Scaffolding a
122
+ # TIMESTAMPTZ produced a file that does not import.
123
+ return SnakeDateTimeParams(tz=_TIMESTAMP_TZ[data_type])
124
+ if data_type in _INT_SIZES:
125
+ return SnakeIntParams(size=_INT_SIZES[data_type])
126
+ if data_type in _JSON_STORAGES:
127
+ return SnakeJsonParams(storage=_JSON_STORAGES[data_type])
128
+ if max_length is not None:
129
+ return SnakeStrParams(max_length=max_length)
130
+ return None
131
+
132
+
133
+ _UNSUPPORTED_QUERY = f"""
134
+ SELECT '{SnakeUnsupportedKind.TRIGGER.value}',
135
+ t.tgname::text, c.relname::text, NULL
136
+ FROM pg_trigger t JOIN pg_class c ON c.oid = t.tgrelid
137
+ JOIN pg_namespace n ON n.oid = c.relnamespace
138
+ WHERE NOT t.tgisinternal AND n.nspname = %s
139
+ UNION ALL
140
+ SELECT '{SnakeUnsupportedKind.EXPRESSION_INDEX.value}',
141
+ i.relname::text, NULL, NULL
142
+ FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid
143
+ JOIN pg_class c ON c.oid = x.indrelid
144
+ JOIN pg_namespace n ON n.oid = c.relnamespace
145
+ WHERE n.nspname = %s AND x.indexprs IS NOT NULL
146
+ UNION ALL
147
+ SELECT '{SnakeUnsupportedKind.UNREPRESENTABLE_COLUMN.value}',
148
+ c.relname::text, a.attname::text, format_type(a.atttypid, a.atttypmod)
149
+ FROM pg_attribute a JOIN pg_class c ON c.oid = a.attrelid
150
+ JOIN pg_namespace n ON n.oid = c.relnamespace
151
+ WHERE n.nspname = %s AND c.relkind = 'r' AND a.attnum > 0 AND NOT a.attisdropped
152
+ AND format_type(a.atttypid, NULL) NOT IN (
153
+ 'integer','bigint','smallint','text','character varying','character','boolean',
154
+ 'double precision','real','numeric','bytea','date','timestamp with time zone',
155
+ 'timestamp without time zone','time without time zone','interval','uuid','jsonb','json')
156
+ UNION ALL
157
+ SELECT '{SnakeUnsupportedKind.CHECK.value}',
158
+ k.conname::text, c.relname::text, pg_get_constraintdef(k.oid)
159
+ FROM pg_constraint k JOIN pg_class c ON c.oid = k.conrelid
160
+ JOIN pg_namespace n ON n.oid = c.relnamespace
161
+ WHERE k.contype = 'c' AND n.nspname = %s
162
+ ORDER BY 1, 2, 3
163
+ """
164
+ """What the graph cannot represent, TAGGED but not worded.
165
+
166
+ The three engines used to compose the sentence inside their own SQL and drifted apart doing it — one
167
+ of them into Spanish. Here the query only says WHAT it found and hands over the pieces;
168
+ `introspection.unsupported` writes the sentence for all three. The kinds are interpolated from that
169
+ same enum rather than retyped, so a rename cannot leave this query behind quietly.
170
+
171
+ The literals interpolated here are this module's own constants, never a value from the database: the
172
+ parameters are still the three `%s`, which is where anything from outside travels.
173
+ """
174
+
175
+
176
+ class PostgresIntrospector:
177
+ """Reads Postgres's real schema. Implements the `SnakeIntrospector` Protocol."""
178
+
179
+ def __init__(self, driver: SnakeDriver) -> None:
180
+ self._driver = driver
181
+
182
+ def tables(self, schema: str = DEFAULT_SCHEMA) -> list[SnakeTableInfo]:
183
+ """Reads the schema's tables with everything the graph knows how to represent."""
184
+ names = [
185
+ str(row[0])
186
+ for row in self._driver.fetch_all(
187
+ "SELECT table_name FROM information_schema.tables "
188
+ "WHERE table_schema = %s AND table_type = 'BASE TABLE' "
189
+ "AND table_name <> 'snake_migrations' ORDER BY table_name",
190
+ (schema,),
191
+ )
192
+ ]
193
+ return [self._table(schema, name) for name in names]
194
+
195
+ def _table(self, schema: str, name: str) -> SnakeTableInfo:
196
+ """Builds the `SnakeTableInfo` of one specific table."""
197
+ primary_key_columns = self._primary_key_columns(schema, name)
198
+ unique_columns = self._unique_columns(schema, name)
199
+ comments = self._column_comments(schema, name)
200
+ columns = [
201
+ self._column(row, unique_columns, comments)
202
+ for row in self._driver.fetch_all(
203
+ "SELECT column_name, data_type, is_nullable, column_default, "
204
+ "character_maximum_length, numeric_precision, numeric_scale "
205
+ "FROM information_schema.columns "
206
+ "WHERE table_schema = %s AND table_name = %s ORDER BY ordinal_position",
207
+ (schema, name),
208
+ )
209
+ ]
210
+ by_name = {column.name: column for column in columns}
211
+ return SnakeTableInfo(
212
+ name=name,
213
+ columns=tuple(columns),
214
+ primary_key=SnakePrimaryKeyInfo(
215
+ columns=tuple(
216
+ by_name[column]
217
+ for column in primary_key_columns
218
+ if column in by_name
219
+ )
220
+ ),
221
+ relationships=self._relationships(schema, name),
222
+ schema=schema,
223
+ db_comment=self._table_comment(schema, name),
224
+ indexes=self._indexes(schema, name),
225
+ )
226
+
227
+ def _column(
228
+ self,
229
+ row: tuple[object, ...],
230
+ unique_columns: set[str],
231
+ comments: dict[str, str],
232
+ ) -> SnakeColumnInfo:
233
+ """Translates a row of `information_schema.columns` into column metadata."""
234
+ name, data_type, nullable, default = (
235
+ str(row[0]),
236
+ str(row[1]),
237
+ str(row[2]),
238
+ row[3],
239
+ )
240
+ # `nextval(...)` is how Postgres represents a SERIAL: it is recognised by the default, not
241
+ # by the type, because the type is still `integer`.
242
+ autoincrement = isinstance(default, str) and default.startswith("nextval(")
243
+ # `character_maximum_length` only comes on VARCHAR(n)/CHAR(n); on TEXT it is NULL. That way
244
+ # a faithful scaffolding re-emits the original VARCHAR(n) instead of widening it to TEXT.
245
+ max_length = row[4] if isinstance(row[4], int) else None
246
+ # precision/scale ONLY for NUMERIC: an `integer` also brings a numeric_precision (32), but
247
+ # there it means nothing. Without this, `NUMERIC(10,2)` came back as a bare `NUMERIC`.
248
+ is_numeric = data_type == "numeric"
249
+ precision = row[5] if is_numeric and isinstance(row[5], int) else None
250
+ scale = row[6] if is_numeric and isinstance(row[6], int) else None
251
+ # The DEFAULT is a SQL expression (`now()`, `'x'::text`), not a literal: it is preserved as
252
+ # `server_default_sql`. The SERIAL's nextval is already captured by `autoincrement`, it is
253
+ # not duplicated.
254
+ server_default_sql = (
255
+ default if isinstance(default, str) and not autoincrement else None
256
+ )
257
+ return SnakeColumnInfo(
258
+ name=name,
259
+ python_type=_PYTHON_TYPES.get(data_type, str),
260
+ nullable=nullable == "YES",
261
+ unique=name in unique_columns,
262
+ attr_name=name,
263
+ autoincrement=autoincrement,
264
+ db_comment=comments.get(name),
265
+ server_default_sql=server_default_sql,
266
+ type_params=_type_params(data_type, max_length, precision, scale),
267
+ )
268
+
269
+ def _primary_key_columns(self, schema: str, name: str) -> list[str]:
270
+ """The PK's columns, IN ORDER (it matters for a composite PK)."""
271
+ rows = self._driver.fetch_all(
272
+ "SELECT a.attname FROM pg_index x "
273
+ "JOIN pg_class c ON c.oid = x.indrelid "
274
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
275
+ "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(x.indkey) "
276
+ "WHERE x.indisprimary AND n.nspname = %s AND c.relname = %s "
277
+ "ORDER BY array_position(x.indkey, a.attnum)",
278
+ (schema, name),
279
+ )
280
+ return [str(row[0]) for row in rows]
281
+
282
+ def _unique_columns(self, schema: str, name: str) -> set[str]:
283
+ """Columns with a UNIQUE constraint over a SINGLE column."""
284
+ rows = self._driver.fetch_all(
285
+ "SELECT a.attname FROM pg_constraint k "
286
+ "JOIN pg_class c ON c.oid = k.conrelid "
287
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
288
+ "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(k.conkey) "
289
+ "WHERE k.contype = 'u' AND array_length(k.conkey, 1) = 1 "
290
+ "AND n.nspname = %s AND c.relname = %s",
291
+ (schema, name),
292
+ )
293
+ return {str(row[0]) for row in rows}
294
+
295
+ def _indexes(self, schema: str, name: str) -> tuple[SnakeIndexInfo, ...]:
296
+ """NON-unique indexes not derived from a constraint (those already come out as uniqueness)."""
297
+ rows = self._driver.fetch_all(
298
+ "SELECT i.relname, array_agg(a.attname ORDER BY a.attnum) "
299
+ "FROM pg_index x JOIN pg_class i ON i.oid = x.indexrelid "
300
+ "JOIN pg_class c ON c.oid = x.indrelid "
301
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
302
+ "JOIN pg_attribute a ON a.attrelid = c.oid AND a.attnum = ANY(x.indkey) "
303
+ "WHERE n.nspname = %s AND c.relname = %s "
304
+ "AND NOT x.indisprimary AND NOT x.indisunique AND x.indexprs IS NULL "
305
+ "GROUP BY i.relname ORDER BY i.relname",
306
+ (schema, name),
307
+ )
308
+ return tuple(
309
+ SnakeIndexInfo(
310
+ columns=tuple(
311
+ str(column)
312
+ for column in (row[1] if isinstance(row[1], list) else [])
313
+ ),
314
+ name=str(row[0]),
315
+ )
316
+ for row in rows
317
+ )
318
+
319
+ def _relationships(
320
+ self, schema: str, name: str
321
+ ) -> tuple[SnakeRelationshipInfo, ...]:
322
+ """The table's foreign keys, with their pairs (local column → remote column)."""
323
+ rows = self._driver.fetch_all(
324
+ # `unnest(conkey, confkey) WITH ORDINALITY` walks the two key arrays TOGETHER, one
325
+ # position at a time. Joining `pg_attribute` twice with `= ANY(...)` instead — which is
326
+ # what this did — is a CARTESIAN PRODUCT: a two-column key matched 2 local rows by 2
327
+ # remote ones and aggregated FOUR, each name twice. One column is 1x1, so it looked
328
+ # right for every single-column key in the suite.
329
+ #
330
+ # The ordering was the second half of the same bug: `ORDER BY attnum` is the order the
331
+ # columns were DECLARED in the table, not their position in the key, so a composite key
332
+ # whose columns are not in declaration order paired the wrong ones together.
333
+ "SELECT k.conname, tc.relname, "
334
+ " array_agg(la.attname ORDER BY u.ord), "
335
+ " array_agg(ra.attname ORDER BY u.ord) "
336
+ "FROM pg_constraint k "
337
+ "JOIN pg_class c ON c.oid = k.conrelid "
338
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
339
+ "JOIN pg_class tc ON tc.oid = k.confrelid "
340
+ "JOIN LATERAL unnest(k.conkey, k.confkey) WITH ORDINALITY AS u(lnum, rnum, ord) "
341
+ " ON TRUE "
342
+ "JOIN pg_attribute la ON la.attrelid = c.oid AND la.attnum = u.lnum "
343
+ "JOIN pg_attribute ra ON ra.attrelid = tc.oid AND ra.attnum = u.rnum "
344
+ "WHERE k.contype = 'f' AND n.nspname = %s AND c.relname = %s "
345
+ "GROUP BY k.conname, tc.relname ORDER BY k.conname",
346
+ (schema, name),
347
+ )
348
+ return tuple(self._relationship(row) for row in rows)
349
+
350
+ def _relationship(self, row: tuple[object, ...]) -> SnakeRelationshipInfo:
351
+ """Translates an FK row into relationship metadata.
352
+
353
+ The `array_agg`s arrive as `object` from the driver (which promises tuples of `object`, not
354
+ of lists), so they are narrowed with `isinstance` instead of being annotated: `object`,
355
+ never `Any`, which is the discipline of the rest of the project.
356
+ """
357
+ target = str(row[1])
358
+ local = row[2] if isinstance(row[2], list) else []
359
+ remote = row[3] if isinstance(row[3], list) else []
360
+ pairs = tuple(
361
+ (str(source_column), str(target_column))
362
+ for source_column, target_column in zip(local, remote, strict=False)
363
+ )
364
+ return SnakeRelationshipInfo(
365
+ name=target,
366
+ target=target,
367
+ kind=SnakeRelationshipKind.TO_ONE,
368
+ foreign_key=SnakeForeignKeyInfo(target=target, pairs=pairs),
369
+ )
370
+
371
+ def _table_comment(self, schema: str, name: str) -> str | None:
372
+ """The table's comment, if it has one."""
373
+ rows = self._driver.fetch_all(
374
+ "SELECT obj_description(c.oid) FROM pg_class c "
375
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
376
+ "WHERE n.nspname = %s AND c.relname = %s",
377
+ (schema, name),
378
+ )
379
+ return str(rows[0][0]) if rows and rows[0][0] is not None else None
380
+
381
+ def _column_comments(self, schema: str, name: str) -> dict[str, str]:
382
+ """Comments per column."""
383
+ rows = self._driver.fetch_all(
384
+ "SELECT a.attname, col_description(c.oid, a.attnum) FROM pg_attribute a "
385
+ "JOIN pg_class c ON c.oid = a.attrelid "
386
+ "JOIN pg_namespace n ON n.oid = c.relnamespace "
387
+ "WHERE n.nspname = %s AND c.relname = %s AND a.attnum > 0 AND NOT a.attisdropped",
388
+ (schema, name),
389
+ )
390
+ return {str(row[0]): str(row[1]) for row in rows if row[1] is not None}
391
+
392
+ def unsupported(self, schema: str = DEFAULT_SCHEMA) -> list[str]:
393
+ """Objects the ORM cannot represent, described so it can WARN (never dropped in silence)."""
394
+ rows = self._driver.fetch_all(
395
+ _UNSUPPORTED_QUERY, (schema, schema, schema, schema)
396
+ )
397
+ return warnings_from_rows(rows)
@@ -0,0 +1,217 @@
1
+ """How SQLite's schema is READ (the second engine). It has no `information_schema`: you ask with PRAGMAs.
2
+
3
+ The translation into `SnakeTableInfo` is the same as on Postgres, so drift and scaffolding work without being touched. It is not bijective: `VARCHAR(50)`/`TEXT`/`CHAR(10)` are the same affinity, reading back does not reproduce the original.
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from datetime import datetime
9
+ from decimal import Decimal
10
+ from typing import Any
11
+
12
+ from snakeorm.core.placement import DEFAULT_SCHEMA
13
+ from snakeorm.introspection.unsupported import (
14
+ SnakeUnsupportedKind,
15
+ warnings_from_rows,
16
+ )
17
+ from snakeorm.metadata import (
18
+ SnakeColumnInfo,
19
+ SnakeForeignKeyInfo,
20
+ SnakeIndexInfo,
21
+ SnakePrimaryKeyInfo,
22
+ SnakeRelationshipKind,
23
+ SnakeRelationshipInfo,
24
+ SnakeTableInfo,
25
+ )
26
+
27
+ _UNSUPPORTED_QUERY = f"""
28
+ SELECT '{SnakeUnsupportedKind.TRIGGER.value}', name, tbl_name, NULL
29
+ FROM sqlite_master WHERE type = 'trigger'
30
+ UNION ALL
31
+ SELECT '{SnakeUnsupportedKind.EXPRESSION_INDEX.value}', name, NULL, NULL
32
+ FROM sqlite_master WHERE type = 'index' AND sql LIKE '%(%(%'
33
+ ORDER BY 1, 2
34
+ """
35
+ """What is in the database and the graph cannot express, TAGGED but not worded.
36
+
37
+ Same shape as the other two engines: the query says what it found, and
38
+ `introspection.unsupported` writes the one sentence the three share. SQLite has no
39
+ `information_schema`, but `sqlite_master` answers both questions in one pass.
40
+ """
41
+
42
+ _AFFINITIES: dict[str, type] = {
43
+ # SQLite declares types by AFFINITY (substring rules over the DDL text). What the ORM emits is
44
+ # covered here; everything else falls to `str`, which is what the driver will return anyway.
45
+ "INTEGER": int,
46
+ "INT": int,
47
+ "REAL": float,
48
+ "FLOAT": float,
49
+ "DOUBLE": float,
50
+ "NUMERIC": Decimal,
51
+ "DECIMAL": Decimal,
52
+ "BLOB": bytes,
53
+ "TEXT": str,
54
+ "VARCHAR": str,
55
+ "CHAR": str,
56
+ "DATETIME": datetime,
57
+ "BOOLEAN": bool,
58
+ }
59
+
60
+
61
+ def _python_type(declared: str) -> type:
62
+ """Translates the type DECLARED in the DDL into Python, by affinity (prefix: SQLite keeps the text as it is).
63
+
64
+ Anything unknown falls to `str`, which is what the driver will hand over anyway.
65
+ """
66
+ normalized = declared.upper().split("(")[0].strip()
67
+ return _AFFINITIES.get(normalized, str)
68
+
69
+
70
+ class SQLiteIntrospector:
71
+ """Reads a SQLite database's schema and returns it as the SAME metadata graph."""
72
+
73
+ def __init__(self, driver: Any) -> None:
74
+ self._driver = driver
75
+
76
+ def tables(self, schema: str = DEFAULT_SCHEMA) -> list[SnakeTableInfo]:
77
+ """Every user table with its columns, PK, uniqueness, indexes and FKs.
78
+
79
+ `schema` is accepted because of the Protocol and is IGNORED: SQLite has no named schemas, and the calling code is the same for both engines.
80
+ """
81
+ names = [
82
+ str(row[0])
83
+ for row in self._driver.fetch_all(
84
+ "SELECT name FROM sqlite_master WHERE type = 'table' "
85
+ "AND name NOT LIKE 'sqlite_%' ORDER BY name",
86
+ (),
87
+ )
88
+ ]
89
+ return [self._table(name) for name in names]
90
+
91
+ def _table(self, name: str) -> SnakeTableInfo:
92
+ """Builds a table's `SnakeTableInfo` out of its PRAGMAs."""
93
+ unique_names = self._unique_columns(name)
94
+ columns: list[SnakeColumnInfo] = []
95
+ pk: list[SnakeColumnInfo] = []
96
+ for _, col, declared, notnull, _default, pk_pos in self._driver.fetch_all(
97
+ f"PRAGMA table_info({self._quote(name)})", ()
98
+ ):
99
+ kind = _python_type(str(declared))
100
+ column = SnakeColumnInfo(
101
+ name=str(col),
102
+ python_type=kind,
103
+ nullable=not int(notnull) and not int(pk_pos),
104
+ unique=str(col) in unique_names,
105
+ # On SQLite the autoincrement is an `INTEGER PRIMARY KEY`: an alias of the ROWID.
106
+ autoincrement=bool(int(pk_pos)) and kind is int,
107
+ attr_name=str(col),
108
+ )
109
+ columns.append(column)
110
+ if int(pk_pos):
111
+ pk.append(column)
112
+ return SnakeTableInfo(
113
+ name=name,
114
+ columns=tuple(columns),
115
+ primary_key=SnakePrimaryKeyInfo(columns=tuple(pk)),
116
+ indexes=self._indexes(name),
117
+ relationships=self._relations(name),
118
+ )
119
+
120
+ def _unique_columns(self, table: str) -> set[str]:
121
+ """Columns with a unique index over a SINGLE column (the uniqueness the ORM declares)."""
122
+ unique_names: set[str] = set()
123
+ for _, index, is_unique, *_rest in self._driver.fetch_all(
124
+ f"PRAGMA index_list({self._quote(table)})", ()
125
+ ):
126
+ if not int(is_unique):
127
+ continue
128
+ columns = [
129
+ str(row[2])
130
+ for row in self._driver.fetch_all(
131
+ f"PRAGMA index_info({self._quote(str(index))})", ()
132
+ )
133
+ ]
134
+ if len(columns) == 1:
135
+ unique_names.add(columns[0])
136
+ return unique_names
137
+
138
+ def _indexes(self, table: str) -> tuple[SnakeIndexInfo, ...]:
139
+ """NON-implicit indexes (`origin` == `c`): nobody declared the ones backing a UNIQUE or a PK, and `check` would see them as drift on a schema the ORM has just created."""
140
+ output: list[SnakeIndexInfo] = []
141
+ for _, index, is_unique, source, _partial in self._driver.fetch_all(
142
+ f"PRAGMA index_list({self._quote(table)})", ()
143
+ ):
144
+ if str(source) != "c":
145
+ continue
146
+ columns = tuple(
147
+ str(row[2])
148
+ for row in self._driver.fetch_all(
149
+ f"PRAGMA index_info({self._quote(str(index))})", ()
150
+ )
151
+ )
152
+ output.append(
153
+ SnakeIndexInfo(
154
+ columns=columns, name=str(index), unique=bool(int(is_unique))
155
+ )
156
+ )
157
+ return tuple(sorted(output, key=lambda index: index.name or ""))
158
+
159
+ def _relations(self, table: str) -> tuple[SnakeRelationshipInfo, ...]:
160
+ """The table's foreign keys, grouped by `id` (a composite FK is several rows)."""
161
+ by_fk: dict[int, list[tuple[str, str, str]]] = {}
162
+ targets: dict[int, str] = {}
163
+ for (
164
+ fk_id,
165
+ _seq,
166
+ target,
167
+ source,
168
+ target_column,
169
+ _upd,
170
+ _del,
171
+ _match,
172
+ ) in self._driver.fetch_all(
173
+ f"PRAGMA foreign_key_list({self._quote(table)})", ()
174
+ ):
175
+ by_fk.setdefault(int(fk_id), []).append(
176
+ (str(source), str(target_column), str(target))
177
+ )
178
+ targets[int(fk_id)] = str(target)
179
+
180
+ output: list[SnakeRelationshipInfo] = []
181
+ for fk_id, pairs in sorted(by_fk.items()):
182
+ target = targets[fk_id]
183
+ output.append(
184
+ SnakeRelationshipInfo(
185
+ name=f"fk_{table}_{fk_id}",
186
+ target=target,
187
+ kind=SnakeRelationshipKind.TO_ONE,
188
+ foreign_key=SnakeForeignKeyInfo(
189
+ target=target,
190
+ pairs=tuple(
191
+ (source, target_column)
192
+ for source, target_column, _ in pairs
193
+ ),
194
+ ),
195
+ )
196
+ )
197
+ return tuple(output)
198
+
199
+ def unsupported(self, schema: str = DEFAULT_SCHEMA) -> list[str]:
200
+ """What is in the database and the ORM cannot express (TRIGGERS and views above all), so it can be warned about instead of dropped in silence.
201
+
202
+ ONE query, tagged by kind, like the other two engines: it used to be two queries whose
203
+ sentences were written right here, and one of them —the trigger— did not name the table the
204
+ other engines named, while the Postgres wording of the other had drifted into Spanish.
205
+ `tbl_name` was in `sqlite_master` all along; nobody was asking for it.
206
+ """
207
+ rows = self._driver.fetch_all(_UNSUPPORTED_QUERY, ())
208
+ return warnings_from_rows(rows)
209
+
210
+ @staticmethod
211
+ def _quote(name: str) -> str:
212
+ """Quotes an identifier for a PRAGMA (it takes no parameters).
213
+
214
+ The names come from `sqlite_master`, but they are quoted anyway: a table can be named after a reserved word, and trusting the source is how injections start.
215
+ """
216
+ escaped = name.replace('"', '""')
217
+ return f'"{escaped}"'