sqlspec 0.72.2__py3-none-any.whl → 0.74.0__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 (92) hide show
  1. sqlspec/adapters/aiomysql/core.py +8 -4
  2. sqlspec/adapters/aiosqlite/core.py +72 -79
  3. sqlspec/adapters/aiosqlite/data_dictionary.py +9 -292
  4. sqlspec/adapters/aiosqlite/driver.py +4 -6
  5. sqlspec/adapters/asyncmy/core.py +8 -4
  6. sqlspec/adapters/asyncpg/config.py +141 -18
  7. sqlspec/adapters/asyncpg/core.py +277 -2
  8. sqlspec/adapters/asyncpg/data_dictionary.py +6 -407
  9. sqlspec/adapters/bigquery/adk/store.py +8 -3
  10. sqlspec/adapters/bigquery/core.py +0 -15
  11. sqlspec/adapters/bigquery/data_dictionary.py +3 -489
  12. sqlspec/adapters/cockroach_asyncpg/data_dictionary.py +3 -358
  13. sqlspec/adapters/cockroach_asyncpg/driver.py +2 -2
  14. sqlspec/adapters/cockroach_psycopg/data_dictionary.py +4 -603
  15. sqlspec/adapters/db2/data_dictionary.py +20 -474
  16. sqlspec/adapters/duckdb/data_dictionary.py +3 -540
  17. sqlspec/adapters/mssql_python/data_dictionary.py +4 -405
  18. sqlspec/adapters/mysqlconnector/core.py +13 -5
  19. sqlspec/adapters/oracledb/core.py +37 -60
  20. sqlspec/adapters/oracledb/data_dictionary.py +10 -1231
  21. sqlspec/adapters/oracledb/driver.py +63 -21
  22. sqlspec/adapters/psqlpy/data_dictionary.py +4 -387
  23. sqlspec/adapters/psycopg/data_dictionary.py +6 -684
  24. sqlspec/adapters/pymssql/data_dictionary.py +4 -405
  25. sqlspec/adapters/pymssql/driver.py +19 -0
  26. sqlspec/adapters/pymysql/config.py +68 -1
  27. sqlspec/adapters/pymysql/core.py +268 -4
  28. sqlspec/adapters/snowflake/core.py +1 -34
  29. sqlspec/adapters/snowflake/data_dictionary.py +5 -344
  30. sqlspec/adapters/spanner/data_dictionary.py +7 -690
  31. sqlspec/adapters/sqlanywhere/data_dictionary.py +9 -256
  32. sqlspec/adapters/sqlite/core.py +2 -2
  33. sqlspec/adapters/sqlite/data_dictionary.py +3 -314
  34. sqlspec/adapters/sybase/data_dictionary.py +9 -332
  35. sqlspec/adapters/sybase/driver.py +19 -0
  36. sqlspec/adapters/teradata/data_dictionary.py +9 -290
  37. sqlspec/cli.py +2 -2
  38. sqlspec/core/result/_base.py +21 -1
  39. sqlspec/data_dictionary/dialects/bigquery/__init__.py +31 -0
  40. sqlspec/data_dictionary/dialects/bigquery/dictionary.py +499 -0
  41. sqlspec/data_dictionary/dialects/cockroachdb/__init__.py +37 -0
  42. sqlspec/data_dictionary/dialects/cockroachdb/dictionary.py +614 -0
  43. sqlspec/data_dictionary/dialects/db2/__init__.py +43 -0
  44. sqlspec/data_dictionary/dialects/db2/dictionary.py +492 -0
  45. sqlspec/data_dictionary/dialects/duckdb/__init__.py +26 -1
  46. sqlspec/data_dictionary/dialects/duckdb/dictionary.py +555 -0
  47. sqlspec/data_dictionary/dialects/mariadb/__init__.py +30 -1
  48. sqlspec/data_dictionary/dialects/mariadb/dictionary.py +23 -0
  49. sqlspec/data_dictionary/dialects/mssql/__init__.py +26 -0
  50. sqlspec/data_dictionary/dialects/mssql/dictionary.py +402 -0
  51. sqlspec/data_dictionary/dialects/mysql/__init__.py +26 -1
  52. sqlspec/data_dictionary/dialects/mysql/config.py +6 -3
  53. sqlspec/data_dictionary/dialects/mysql/dictionary.py +6 -4
  54. sqlspec/data_dictionary/dialects/oracle/__init__.py +46 -0
  55. sqlspec/data_dictionary/dialects/oracle/config.py +62 -1
  56. sqlspec/data_dictionary/dialects/oracle/dictionary.py +1248 -0
  57. sqlspec/data_dictionary/dialects/postgres/__init__.py +37 -0
  58. sqlspec/data_dictionary/dialects/postgres/dictionary.py +699 -0
  59. sqlspec/data_dictionary/dialects/snowflake/__init__.py +31 -0
  60. sqlspec/data_dictionary/dialects/snowflake/config.py +53 -19
  61. sqlspec/data_dictionary/dialects/snowflake/dictionary.py +355 -0
  62. sqlspec/data_dictionary/dialects/spanner/__init__.py +30 -1
  63. sqlspec/data_dictionary/dialects/spanner/dictionary.py +705 -0
  64. sqlspec/data_dictionary/dialects/sqlanywhere/__init__.py +49 -0
  65. sqlspec/data_dictionary/dialects/sqlanywhere/dictionary.py +276 -0
  66. sqlspec/data_dictionary/dialects/sqlite/__init__.py +28 -0
  67. sqlspec/data_dictionary/dialects/sqlite/dictionary.py +567 -0
  68. sqlspec/data_dictionary/dialects/sybase/__init__.py +40 -0
  69. sqlspec/data_dictionary/dialects/sybase/dictionary.py +348 -0
  70. sqlspec/data_dictionary/dialects/teradata/__init__.py +46 -0
  71. sqlspec/data_dictionary/dialects/teradata/dictionary.py +310 -0
  72. sqlspec/driver/__init__.py +6 -0
  73. sqlspec/driver/_async.py +55 -2
  74. sqlspec/driver/_common.py +102 -6
  75. sqlspec/driver/_sync.py +54 -2
  76. sqlspec/extensions/adk/__init__.py +26 -0
  77. sqlspec/extensions/adk/_config_utils.py +224 -78
  78. sqlspec/extensions/adk/maintenance.py +3 -3
  79. sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +9 -9
  80. sqlspec/extensions/adk/migrations/0002_create_mssql_python_memory.py +2 -2
  81. sqlspec/extensions/adk/migrations/reconcile.py +99 -148
  82. sqlspec/extensions/events/__init__.py +3 -0
  83. sqlspec/extensions/events/_channel.py +50 -37
  84. sqlspec/extensions/events/migrations/reconcile.py +40 -40
  85. sqlspec/storage/__init__.py +3 -1
  86. sqlspec/storage/_utils.py +0 -4
  87. sqlspec/storage/registry.py +457 -60
  88. {sqlspec-0.72.2.dist-info → sqlspec-0.74.0.dist-info}/METADATA +1 -1
  89. {sqlspec-0.72.2.dist-info → sqlspec-0.74.0.dist-info}/RECORD +92 -78
  90. {sqlspec-0.72.2.dist-info → sqlspec-0.74.0.dist-info}/WHEEL +0 -0
  91. {sqlspec-0.72.2.dist-info → sqlspec-0.74.0.dist-info}/entry_points.txt +0 -0
  92. {sqlspec-0.72.2.dist-info → sqlspec-0.74.0.dist-info}/licenses/LICENSE +0 -0
@@ -454,7 +454,7 @@ def resolve_rowcount(cursor: Any) -> int:
454
454
  if not has_rowcount(cursor):
455
455
  return 0
456
456
  rowcount = cursor.rowcount
457
- if isinstance(rowcount, int) and rowcount >= 0:
457
+ if isinstance(rowcount, int) and not isinstance(rowcount, bool) and rowcount >= 0:
458
458
  return rowcount
459
459
  return 0
460
460
 
@@ -476,12 +476,12 @@ def normalize_lastrowid(cursor: Any) -> int | None:
476
476
  if not has_rowcount(cursor):
477
477
  return None
478
478
  rowcount = cursor.rowcount
479
- if not isinstance(rowcount, int) or rowcount <= 0:
479
+ if isinstance(rowcount, bool) or not isinstance(rowcount, int) or rowcount <= 0:
480
480
  return None
481
481
  if not has_lastrowid(cursor):
482
482
  return None
483
483
  last_id = cursor.lastrowid
484
- return last_id if isinstance(last_id, int) else None
484
+ return last_id if isinstance(last_id, int) and not isinstance(last_id, bool) else None
485
485
 
486
486
 
487
487
  async def execute_cache_hit(
@@ -526,7 +526,11 @@ async def execute_cache_hit(
526
526
  else:
527
527
  await cursor.execute(compiled_sql)
528
528
  if not cached.operation_profile.returns_rows:
529
- result = DMLResult(cached.operation_type, resolve_rowcount(cursor))
529
+ affected_rows = resolve_rowcount(cursor)
530
+ last_inserted_id = (
531
+ normalize_lastrowid(cursor) if cached.operation_type == "INSERT" and affected_rows > 0 else None
532
+ )
533
+ result = DMLResult(cached.operation_type, affected_rows, last_inserted_id)
530
534
  else:
531
535
  fetched_data = await cursor.fetchall()
532
536
  rows, column_names, _row_format = collect_rows(
@@ -39,7 +39,7 @@ from sqlspec.exceptions import (
39
39
  from sqlspec.utils.serializers._json import from_json, to_json
40
40
  from sqlspec.utils.text import quote_identifier, split_qualified_identifier
41
41
  from sqlspec.utils.type_converters import build_decimal_converter, build_uuid_coercions, time_iso_convert
42
- from sqlspec.utils.type_guards import has_lastrowid, has_rowcount, has_sqlite_error, resolve_row_format
42
+ from sqlspec.utils.type_guards import has_rowcount, has_sqlite_error, resolve_row_format
43
43
 
44
44
  if TYPE_CHECKING:
45
45
  from collections.abc import Awaitable, Callable, Sequence
@@ -223,11 +223,74 @@ async def run_on_worker_thread(
223
223
  return await execute(function, *args, **kwargs)
224
224
 
225
225
 
226
+ def execute_fetchall_with_metadata(
227
+ connection: "AiosqliteConnection",
228
+ sql: str,
229
+ parameters: Any,
230
+ operation_type: "OperationType",
231
+ expression: Any,
232
+ eligibility_cache: "dict[Any, bool]",
233
+ cache_key: "str | None" = None,
234
+ ) -> "tuple[list[Any], Any, int, int | None]":
235
+ """Execute a query and return rows plus execution metadata on the worker thread."""
236
+ raw_connection = connection._conn
237
+ cursor = cast("Any", raw_connection.execute(sql, normalize_execute_parameters(parameters)))
238
+ try:
239
+ fetched_data = cursor.fetchall()
240
+ rowcount = cursor.rowcount if isinstance(cursor.rowcount, int) and cursor.rowcount > 0 else 0
241
+ effective_rowcount = rowcount or (len(fetched_data) if operation_type == "INSERT" else 0)
242
+ last_inserted_id = resolve_lastrowid(
243
+ raw_connection, cursor, operation_type, effective_rowcount, expression, eligibility_cache, cache_key
244
+ )
245
+ return fetched_data, cursor.description, rowcount, last_inserted_id
246
+ finally:
247
+ with contextlib.suppress(Exception):
248
+ cursor.close()
249
+
250
+
251
+ def execute_and_resolve_metadata(
252
+ connection: "AiosqliteConnection",
253
+ sql: str,
254
+ parameters: Any,
255
+ operation_type: "OperationType",
256
+ expression: Any,
257
+ eligibility_cache: "dict[Any, bool]",
258
+ cache_key: "str | None" = None,
259
+ ) -> "tuple[int, int | None]":
260
+ """Execute a statement and resolve rowcount and lastrowid on the worker thread."""
261
+ raw_connection = connection._conn
262
+ cursor = raw_connection.execute(sql, normalize_execute_parameters(parameters))
263
+ try:
264
+ rowcount = (
265
+ cursor.rowcount if has_rowcount(cursor) and isinstance(cursor.rowcount, int) and cursor.rowcount > 0 else 0
266
+ )
267
+ return rowcount, resolve_lastrowid(
268
+ raw_connection, cursor, operation_type, rowcount, expression, eligibility_cache, cache_key
269
+ )
270
+ finally:
271
+ with contextlib.suppress(Exception):
272
+ cast("Any", cursor).close()
273
+
274
+
275
+ def execute_many_on_worker_thread(connection: "AiosqliteConnection", sql: str, parameters: Any) -> int:
276
+ """Execute SQL with multiple parameter sets on the worker thread."""
277
+ raw_connection = connection._conn
278
+ cursor = raw_connection.cursor()
279
+ try:
280
+ cursor.executemany(sql, normalize_execute_many_parameters(parameters))
281
+ return (
282
+ cursor.rowcount if has_rowcount(cursor) and isinstance(cursor.rowcount, int) and cursor.rowcount > 0 else 0
283
+ )
284
+ finally:
285
+ with contextlib.suppress(Exception):
286
+ cast("Any", cursor).close()
287
+
288
+
226
289
  def execute_fetchall_with_description(
227
290
  connection: "AiosqliteConnection", sql: str, parameters: Any
228
291
  ) -> "tuple[list[Any], Any]":
229
292
  """Execute a query and return raw rows plus description on the worker thread."""
230
- fetched_data, description, _rowcount, _last_inserted_id = _execute_fetchall_with_metadata(
293
+ fetched_data, description, _rowcount, _last_inserted_id = execute_fetchall_with_metadata(
231
294
  connection, sql, parameters, "SELECT", None, {}
232
295
  )
233
296
  return fetched_data, description
@@ -235,7 +298,7 @@ def execute_fetchall_with_description(
235
298
 
236
299
  def execute_and_resolve_rowcount(connection: "AiosqliteConnection", sql: str, parameters: Any) -> int:
237
300
  """Execute a statement and resolve rowcount on the worker thread."""
238
- rowcount, _last_inserted_id = _execute_and_resolve_metadata(connection, sql, parameters, "COMMAND", None, {})
301
+ rowcount, _last_inserted_id = execute_and_resolve_metadata(connection, sql, parameters, "COMMAND", None, {})
239
302
  return rowcount
240
303
 
241
304
 
@@ -270,7 +333,7 @@ async def execute_cache_hit(
270
333
  if not cached.operation_profile.returns_rows:
271
334
  affected_rows, dml_last_inserted_id = await run_on_worker_thread(
272
335
  connection,
273
- _execute_and_resolve_metadata,
336
+ execute_and_resolve_metadata,
274
337
  connection,
275
338
  cached.compiled_sql,
276
339
  params,
@@ -282,7 +345,7 @@ async def execute_cache_hit(
282
345
  return DMLResult(operation_type, affected_rows, dml_last_inserted_id)
283
346
  fetched_data, description, _affected_rows, last_inserted_id = await run_on_worker_thread(
284
347
  connection,
285
- _execute_fetchall_with_metadata,
348
+ execute_fetchall_with_metadata,
286
349
  connection,
287
350
  cached.compiled_sql,
288
351
  params,
@@ -319,12 +382,12 @@ def normalize_lastrowid(cursor: Any, operation_type: "OperationType", rowcount:
319
382
  rowcount: Normalized affected-row count.
320
383
 
321
384
  Returns:
322
- Integer lastrowid, or None for non-INSERT or unsuccessful operations.
385
+ Integer lastrowid (excluding ``bool``), or None for non-INSERT or unsuccessful operations.
323
386
  """
324
- if operation_type != "INSERT" or rowcount <= 0 or not has_lastrowid(cursor):
387
+ if operation_type != "INSERT" or rowcount <= 0:
325
388
  return None
326
- lastrowid = cursor.lastrowid
327
- return lastrowid if isinstance(lastrowid, int) else None
389
+ lastrowid = getattr(cursor, "lastrowid", None)
390
+ return lastrowid if isinstance(lastrowid, int) and not isinstance(lastrowid, bool) else None
328
391
 
329
392
 
330
393
  def resolve_lastrowid(
@@ -852,76 +915,6 @@ def _read_transaction_state_on_worker(raw_conn: Any) -> "tuple[bool, bool]":
852
915
  return False, False
853
916
 
854
917
 
855
- def _execute_fetchall_with_metadata(
856
- connection: "AiosqliteConnection",
857
- sql: str,
858
- parameters: Any,
859
- operation_type: "OperationType",
860
- expression: Any,
861
- eligibility_cache: "dict[Any, bool]",
862
- cache_key: "str | None" = None,
863
- ) -> "tuple[list[Any], Any, int, int | None]":
864
- """Execute a query and return rows plus execution metadata on the worker thread."""
865
- raw_connection = connection._conn
866
- cursor = cast("Any", raw_connection.execute(sql, normalize_execute_parameters(parameters)))
867
- try:
868
- fetched_data = cursor.fetchall()
869
- rowcount = cursor.rowcount if isinstance(cursor.rowcount, int) and cursor.rowcount > 0 else 0
870
- effective_rowcount = rowcount or (len(fetched_data) if operation_type == "INSERT" else 0)
871
- last_inserted_id = resolve_lastrowid(
872
- raw_connection, cursor, operation_type, effective_rowcount, expression, eligibility_cache, cache_key
873
- )
874
- return fetched_data, cursor.description, rowcount, last_inserted_id
875
- finally:
876
- with contextlib.suppress(Exception):
877
- cursor.close()
878
-
879
-
880
- def _execute_and_resolve_metadata(
881
- connection: "AiosqliteConnection",
882
- sql: str,
883
- parameters: Any,
884
- operation_type: "OperationType",
885
- expression: Any,
886
- eligibility_cache: "dict[Any, bool]",
887
- cache_key: "str | None" = None,
888
- ) -> "tuple[int, int | None]":
889
- """Execute a statement and resolve rowcount and lastrowid on the worker thread."""
890
- raw_connection = connection._conn
891
- cursor = raw_connection.execute(sql, normalize_execute_parameters(parameters))
892
- try:
893
- rowcount = (
894
- cursor.rowcount if has_rowcount(cursor) and isinstance(cursor.rowcount, int) and cursor.rowcount > 0 else 0
895
- )
896
- return rowcount, resolve_lastrowid(
897
- raw_connection, cursor, operation_type, rowcount, expression, eligibility_cache, cache_key
898
- )
899
- finally:
900
- with contextlib.suppress(Exception):
901
- cast("Any", cursor).close()
902
-
903
-
904
- def _execute_many_on_worker_thread(connection: "AiosqliteConnection", sql: str, parameters: Any) -> int:
905
- """Execute SQL with multiple parameter sets on the worker thread."""
906
- raw_connection = connection._conn
907
- cursor = raw_connection.cursor()
908
- try:
909
- cursor.executemany(sql, normalize_execute_many_parameters(parameters))
910
- return (
911
- cursor.rowcount if has_rowcount(cursor) and isinstance(cursor.rowcount, int) and cursor.rowcount > 0 else 0
912
- )
913
- finally:
914
- with contextlib.suppress(Exception):
915
- cast("Any", cursor).close()
916
-
917
-
918
- execute_and_resolve_metadata = _execute_and_resolve_metadata
919
-
920
- execute_fetchall_with_metadata = _execute_fetchall_with_metadata
921
-
922
- execute_many_on_worker_thread = _execute_many_on_worker_thread
923
-
924
-
925
918
  def _normalize_metadata_row(row: Any) -> Any:
926
919
  if isinstance(row, dict):
927
920
  return tuple(row.values())
@@ -1,70 +1,32 @@
1
1
  """SQLite-specific data dictionary for metadata queries via aiosqlite."""
2
2
 
3
- from typing import TYPE_CHECKING, Any, ClassVar, cast
3
+ from typing import TYPE_CHECKING, ClassVar
4
4
 
5
5
  from mypy_extensions import mypyc_attr
6
6
 
7
7
  from sqlspec.adapters.aiosqlite._typing import aiosqlite_sqlite_module as sqlite3
8
- from sqlspec.data_dictionary import (
9
- ColumnMetadata,
10
- DDLResult,
11
- ForeignKeyMetadata,
12
- IndexMetadata,
13
- MetadataResult,
14
- TableMetadata,
15
- VersionInfo,
16
- get_data_dictionary_loader,
17
- get_dialect_config,
18
- )
19
- from sqlspec.data_dictionary.dialects.sqlite import list_sqlite_available_features, resolve_sqlite_json_type
20
- from sqlspec.data_dictionary.dialects.sqlite.config import (
21
- format_sqlite_schema_prefix,
22
- normalize_sqlite_schema_name,
23
- sqlite_check_constraints,
24
- sqlite_constraint_metadata,
25
- sqlite_generated_expressions,
26
- sqlite_object_ddl_result,
27
- sqlite_schema_ddl_results,
28
- )
29
- from sqlspec.driver import AsyncDataDictionaryBase
30
- from sqlspec.exceptions import SQLFileNotFoundError
8
+ from sqlspec.data_dictionary.dialects.sqlite import SqliteAsyncDataDictionary
31
9
 
32
10
  if TYPE_CHECKING:
33
- from sqlspec.adapters.aiosqlite.driver import AiosqliteDriver
34
- from sqlspec.data_dictionary import DialectConfig
11
+ from sqlspec.data_dictionary import VersionInfo
12
+ from sqlspec.driver import AsyncDriverAdapterBase
35
13
 
36
14
  __all__ = ("AiosqliteDataDictionary",)
37
15
 
38
- SQLITE_INDEX_EXPRESSION_COLUMN_ID = -2
39
-
40
16
 
41
17
  @mypyc_attr(allow_interpreted_subclasses=True, native_class=False)
42
- class AiosqliteDataDictionary(AsyncDataDictionaryBase):
18
+ class AiosqliteDataDictionary(SqliteAsyncDataDictionary):
43
19
  """SQLite-specific async data dictionary."""
44
20
 
45
21
  dialect: ClassVar[str] = "sqlite"
46
22
  _shared_version_info: ClassVar["VersionInfo | None"] = None
47
23
 
48
- def __init__(self) -> None:
49
- super().__init__()
50
-
51
- def get_dialect_config(self) -> "DialectConfig":
52
- """Return the dialect configuration for this data dictionary."""
53
- return get_dialect_config(type(self).dialect)
54
-
55
- def resolve_schema(self, schema: "str | None") -> "str | None":
56
- """Return a validated schema name using dialect defaults when missing."""
57
- if schema is not None:
58
- return normalize_sqlite_schema_name(schema)
59
- return self.get_dialect_config().default_schema
60
-
61
- def list_available_features(self) -> "list[str]":
62
- """List available feature flags for this dialect."""
63
- return list_sqlite_available_features()
64
-
65
- async def get_version(self, driver: "AiosqliteDriver") -> "VersionInfo | None":
24
+ async def get_version(self, driver: "AsyncDriverAdapterBase") -> "VersionInfo | None":
66
25
  """Get SQLite database version information.
67
26
 
27
+ Checks the shared in-process cache and local ``sqlite3.sqlite_version``
28
+ before falling back to querying the database driver.
29
+
68
30
  Args:
69
31
  driver: Async database driver instance.
70
32
 
@@ -96,248 +58,3 @@ class AiosqliteDataDictionary(AsyncDataDictionaryBase):
96
58
  self.cache_version(driver_id, version_info)
97
59
  AiosqliteDataDictionary._shared_version_info = version_info
98
60
  return version_info
99
-
100
- async def get_feature_flag(self, driver: "AiosqliteDriver", feature: str) -> bool:
101
- """Check if SQLite database supports a specific feature.
102
-
103
- Args:
104
- driver: Async database driver instance.
105
- feature: Feature name to check.
106
-
107
- Returns:
108
- True if feature is supported, False otherwise.
109
- """
110
- version_info = await self.get_version(driver)
111
- return self.resolve_feature_flag(feature, version_info)
112
-
113
- async def get_optimal_type(self, driver: "AiosqliteDriver", type_category: str) -> str:
114
- """Get optimal SQLite type for a category.
115
-
116
- Args:
117
- driver: Async database driver instance.
118
- type_category: Type category.
119
-
120
- Returns:
121
- SQLite-specific type name.
122
- """
123
- config = self.get_dialect_config()
124
- version_info = await self.get_version(driver)
125
-
126
- if type_category == "json":
127
- return resolve_sqlite_json_type(version_info)
128
-
129
- return config.get_optimal_type(type_category)
130
-
131
- async def get_tables(self, driver: "AiosqliteDriver", schema: "str | None" = None) -> "list[TableMetadata]":
132
- """Get tables sorted by topological dependency order using SQLite catalog."""
133
- schema_name = self.resolve_schema(schema)
134
- self._log_schema_introspect(driver, schema_name=schema_name, table_name=None, operation="tables")
135
- query_text = self._get_domain_query_text("tables", "by_schema")
136
- return await driver.select(query_text, schema_name=schema_name, schema_type=TableMetadata)
137
-
138
- async def get_columns(
139
- self, driver: "AiosqliteDriver", table: "str | None" = None, schema: "str | None" = None
140
- ) -> "list[ColumnMetadata]":
141
- """Get column information for a table or schema, including generated-column expressions."""
142
- schema_name = self.resolve_schema(schema)
143
- schema_prefix = format_sqlite_schema_prefix(schema_name)
144
- if table is None:
145
- self._log_schema_introspect(driver, schema_name=schema_name, table_name=None, operation="columns")
146
- query_text = self._get_domain_query_text("columns", "by_schema").format(schema_prefix=schema_prefix)
147
- rows = await driver.select(query_text, schema_name=schema_name)
148
- else:
149
- self._log_table_describe(driver, schema_name=schema_name, table_name=table, operation="columns")
150
- query_text = self._get_domain_query_text("columns", "by_table").format(schema_prefix=schema_prefix)
151
- rows = await driver.select(query_text, table_name=table, schema_name=schema_name)
152
- if any(str(row.get("extra") or "").endswith("generated") for row in rows):
153
- table_sql = await self._get_table_sql(driver, schema_name, table)
154
- parsed_expressions: dict[str, dict[str, str]] = {}
155
- for row in rows:
156
- if str(row.get("extra") or "").endswith("generated"):
157
- table_name_str = str(row.get("table_name"))
158
- if table_name_str not in parsed_expressions:
159
- parsed_expressions[table_name_str] = sqlite_generated_expressions(table_sql.get(table_name_str))
160
- expression = parsed_expressions[table_name_str].get(str(row.get("column_name")))
161
- if expression is not None:
162
- row["generation_expression"] = expression
163
- return cast("list[ColumnMetadata]", rows)
164
-
165
- async def get_indexes(
166
- self, driver: "AiosqliteDriver", table: "str | None" = None, schema: "str | None" = None
167
- ) -> "list[IndexMetadata]":
168
- """Get index metadata for a table or schema."""
169
- schema_name = self.resolve_schema(schema)
170
- schema_prefix = format_sqlite_schema_prefix(schema_name)
171
- if table is None:
172
- self._log_schema_introspect(driver, schema_name=schema_name, table_name=None, operation="indexes")
173
- query_text = self._get_domain_query_text("indexes", "by_schema").format(schema_prefix=schema_prefix)
174
- rows = await driver.select(query_text, schema_name=schema_name)
175
- return _sqlite_index_rows_to_metadata(rows, schema_name)
176
-
177
- self._log_table_describe(driver, schema_name=schema_name, table_name=table, operation="indexes")
178
- query_text = self._get_domain_query_text("indexes", "by_table").format(schema_prefix=schema_prefix)
179
- rows = await driver.select(query_text, table_name=table, schema_name=schema_name)
180
- return _sqlite_index_rows_to_metadata(rows, schema_name)
181
-
182
- async def get_foreign_keys(
183
- self, driver: "AiosqliteDriver", table: "str | None" = None, schema: "str | None" = None
184
- ) -> "list[ForeignKeyMetadata]":
185
- """Get foreign key metadata, including ON DELETE / ON UPDATE actions."""
186
- schema_name = self.resolve_schema(schema)
187
- if table is None:
188
- self._log_schema_introspect(driver, schema_name=schema_name, table_name=None, operation="foreign_keys")
189
- rows = await driver.select(
190
- self._get_domain_query_text("foreign_keys", "by_schema"), schema_name=schema_name
191
- )
192
- else:
193
- self._log_table_describe(driver, schema_name=schema_name, table_name=table, operation="foreign_keys")
194
- rows = await driver.select(
195
- self._get_domain_query_text("foreign_keys", "by_table"), table_name=table, schema_name=schema_name
196
- )
197
- return [ForeignKeyMetadata.from_row(row) for row in rows]
198
-
199
- async def get_constraints(
200
- self, driver: "AiosqliteDriver", table: "str | None" = None, schema: "str | None" = None
201
- ) -> "MetadataResult":
202
- """Get PRIMARY KEY, UNIQUE, and CHECK constraint metadata.
203
-
204
- PRIMARY KEY and UNIQUE come from index pragmas; CHECK constraints are parsed from the
205
- stored CREATE TABLE statement because SQLite exposes them nowhere else.
206
- """
207
- schema_name = self.resolve_schema(schema)
208
- if table is None:
209
- rows = await driver.select(
210
- self._get_domain_query_text("constraints", "by_schema"), schema_name=schema_name, table_name=None
211
- )
212
- else:
213
- rows = await driver.select(
214
- self._get_domain_query_text("constraints", "by_table"), schema_name=schema_name, table_name=table
215
- )
216
- items: list[dict[str, Any]] = sqlite_constraint_metadata(rows)
217
- warnings: list[str] = []
218
- for table_name, create_sql in (await self._get_table_sql(driver, schema_name, table)).items():
219
- checks, check_warnings = sqlite_check_constraints(table_name, create_sql, schema_name=schema_name)
220
- items.extend(checks)
221
- warnings.extend(check_warnings)
222
- return MetadataResult("constraints", items=tuple(items), warnings=tuple(warnings))
223
-
224
- async def get_views(self, driver: "AiosqliteDriver", schema: "str | None" = None) -> "MetadataResult":
225
- """Get view metadata including the stored CREATE VIEW statement."""
226
- schema_name = self.resolve_schema(schema)
227
- schema_prefix = format_sqlite_schema_prefix(schema_name)
228
- query_text = self._get_domain_query_text("views", "by_schema").format(schema_prefix=schema_prefix)
229
- return MetadataResult("views", items=tuple(await driver.select(query_text, schema_name=schema_name)))
230
-
231
- async def get_sequences(self, driver: "AiosqliteDriver", schema: "str | None" = None) -> "MetadataResult":
232
- """Return an empty sequence result because SQLite has no sequence objects."""
233
- _ = driver, schema
234
- return MetadataResult("sequences", items=())
235
-
236
- async def get_types(self, driver: "AiosqliteDriver", schema: "str | None" = None) -> "MetadataResult":
237
- """Return an empty type result because SQLite has no user-defined types."""
238
- _ = driver, schema
239
- return MetadataResult("types", items=())
240
-
241
- async def _get_native_object_ddl(
242
- self,
243
- driver: "AiosqliteDriver",
244
- object_name: str,
245
- *,
246
- schema: "str | None",
247
- object_type: str,
248
- include_dependencies: bool,
249
- redact: bool,
250
- ) -> "DDLResult | None":
251
- """Return the stored SQL for an object from sqlite_schema."""
252
- _ = include_dependencies, redact
253
- schema_name = self.resolve_schema(schema)
254
- schema_prefix = format_sqlite_schema_prefix(schema_name)
255
- query_text = self._get_domain_query_text("ddl", "by_object").format(schema_prefix=schema_prefix)
256
- rows = await driver.select(
257
- query_text, schema_name=schema_name, object_name=object_name, object_type=object_type
258
- )
259
- return sqlite_object_ddl_result(rows, object_name=object_name, object_type=object_type, schema=schema_name)
260
-
261
- async def _get_native_schema_ddl(
262
- self, driver: "AiosqliteDriver", schema: "str | None", *, include_dependencies: bool, redact: bool
263
- ) -> "list[DDLResult] | None":
264
- """Return the stored SQL for every sqlite_schema object."""
265
- _ = include_dependencies, redact
266
- schema_name = self.resolve_schema(schema)
267
- schema_prefix = format_sqlite_schema_prefix(schema_name)
268
- query_text = self._get_domain_query_text("ddl", "by_schema").format(schema_prefix=schema_prefix)
269
- return sqlite_schema_ddl_results(await driver.select(query_text, schema_name=schema_name), schema=schema_name)
270
-
271
- async def _get_table_sql(
272
- self, driver: "AiosqliteDriver", schema_name: "str | None", table: "str | None"
273
- ) -> "dict[str, str]":
274
- """Return stored CREATE TABLE statements keyed by table name for one table or the whole schema."""
275
- schema_prefix = format_sqlite_schema_prefix(schema_name)
276
- if table is None:
277
- query_text = self._get_domain_query_text("ddl", "by_schema").format(schema_prefix=schema_prefix)
278
- rows = await driver.select(query_text, schema_name=schema_name)
279
- else:
280
- query_text = self._get_domain_query_text("ddl", "by_object").format(schema_prefix=schema_prefix)
281
- rows = await driver.select(query_text, schema_name=schema_name, object_name=table, object_type="table")
282
- return {
283
- str(row["object_name"]): str(row["ddl"])
284
- for row in rows
285
- if str(row.get("object_type") or "").lower() == "table" and row.get("ddl") is not None
286
- }
287
-
288
- def _get_domain_query_text(self, domain: str, query_name: str) -> str:
289
- """Return a required direct-domain query for SQLite."""
290
- query_text = get_data_dictionary_loader().get_domain_query_text(type(self).dialect, domain, query_name)
291
- if query_text is None:
292
- msg = f"Missing SQLite data-dictionary query: {domain}/{query_name}"
293
- raise SQLFileNotFoundError(msg)
294
- return query_text
295
-
296
-
297
- def _sqlite_index_rows_to_metadata(rows: "list[dict[str, Any]]", schema_name: "str | None") -> "list[IndexMetadata]":
298
- """Group SQLite index_xinfo rows into the public index metadata shape."""
299
- if not rows:
300
- return []
301
- first_row = rows[0]
302
- if "columns" in first_row:
303
- return cast("list[IndexMetadata]", rows)
304
-
305
- grouped: dict[tuple[str | None, str, str], dict[str, Any]] = {}
306
- for row in rows:
307
- table_name_value = row.get("table_name")
308
- index_name_value = row.get("index_name")
309
- if table_name_value is None or index_name_value is None:
310
- continue
311
- row_schema = cast("str | None", row.get("schema_name", schema_name))
312
- table_name = str(table_name_value)
313
- index_name = str(index_name_value)
314
- key = (row_schema, table_name, index_name)
315
- index_metadata = grouped.get(key)
316
- if index_metadata is None:
317
- index_metadata = {
318
- "index_name": index_name,
319
- "table_name": table_name,
320
- "columns": [],
321
- "is_primary": bool(row.get("is_primary")),
322
- }
323
- if row_schema is not None:
324
- index_metadata["schema_name"] = row_schema
325
- unique_value = row.get("is_unique")
326
- if unique_value is not None:
327
- index_metadata["is_unique"] = unique_value
328
- if row.get("is_partial") is not None:
329
- index_metadata["is_partial"] = row.get("is_partial")
330
- if row.get("index_sql") is not None:
331
- index_metadata["native_sql"] = row.get("index_sql")
332
- grouped[key] = index_metadata
333
-
334
- if row.get("is_key_column") in (0, False):
335
- continue
336
- columns = cast("list[str]", index_metadata["columns"])
337
- column_name = row.get("column_name")
338
- if column_name is not None:
339
- columns.append(str(column_name))
340
- elif row.get("column_id") == SQLITE_INDEX_EXPRESSION_COLUMN_ID:
341
- columns.append("<expression>")
342
-
343
- return [cast("IndexMetadata", metadata) for metadata in grouped.values()]
@@ -62,8 +62,6 @@ __all__ = (
62
62
  "AiosqliteSessionContext",
63
63
  )
64
64
 
65
- _execute_and_resolve_metadata = execute_and_resolve_metadata
66
- _execute_fetchall_with_metadata = execute_fetchall_with_metadata
67
65
  random = secrets.SystemRandom()
68
66
  _NO_CURSOR: Any = None
69
67
  _DISPATCH_HOOKS: Final[tuple[str, ...]] = (
@@ -141,7 +139,7 @@ class AiosqliteDriver(AsyncDriverAdapterBase):
141
139
  if statement.returns_rows():
142
140
  fetched_data, description, _affected_rows, last_inserted_id = await run_on_worker_thread(
143
141
  self.connection,
144
- _execute_fetchall_with_metadata,
142
+ execute_fetchall_with_metadata,
145
143
  self.connection,
146
144
  sql,
147
145
  normalized_parameters,
@@ -165,7 +163,7 @@ class AiosqliteDriver(AsyncDriverAdapterBase):
165
163
 
166
164
  affected_rows, last_inserted_id = await run_on_worker_thread(
167
165
  self.connection,
168
- _execute_and_resolve_metadata,
166
+ execute_and_resolve_metadata,
169
167
  self.connection,
170
168
  sql,
171
169
  normalized_parameters,
@@ -385,7 +383,7 @@ class AiosqliteDriver(AsyncDriverAdapterBase):
385
383
  if cached.operation_profile.returns_rows:
386
384
  fetched_data, description, _affected_rows, last_inserted_id = await run_on_worker_thread(
387
385
  self.connection,
388
- _execute_fetchall_with_metadata,
386
+ execute_fetchall_with_metadata,
389
387
  self.connection,
390
388
  wire_sql,
391
389
  normalized_parameters,
@@ -408,7 +406,7 @@ class AiosqliteDriver(AsyncDriverAdapterBase):
408
406
  )
409
407
  affected_rows, last_inserted_id = await run_on_worker_thread(
410
408
  self.connection,
411
- _execute_and_resolve_metadata,
409
+ execute_and_resolve_metadata,
412
410
  self.connection,
413
411
  wire_sql,
414
412
  normalized_parameters,
@@ -453,7 +453,7 @@ def resolve_rowcount(cursor: Any) -> int:
453
453
  if not has_rowcount(cursor):
454
454
  return 0
455
455
  rowcount = cursor.rowcount
456
- if isinstance(rowcount, int) and rowcount >= 0:
456
+ if isinstance(rowcount, int) and not isinstance(rowcount, bool) and rowcount >= 0:
457
457
  return rowcount
458
458
  return 0
459
459
 
@@ -475,12 +475,12 @@ def normalize_lastrowid(cursor: Any) -> int | None:
475
475
  if not has_rowcount(cursor):
476
476
  return None
477
477
  rowcount = cursor.rowcount
478
- if not isinstance(rowcount, int) or rowcount <= 0:
478
+ if isinstance(rowcount, bool) or not isinstance(rowcount, int) or rowcount <= 0:
479
479
  return None
480
480
  if not has_lastrowid(cursor):
481
481
  return None
482
482
  last_id = cursor.lastrowid
483
- return last_id if isinstance(last_id, int) else None
483
+ return last_id if isinstance(last_id, int) and not isinstance(last_id, bool) else None
484
484
 
485
485
 
486
486
  async def execute_cache_hit(
@@ -525,7 +525,11 @@ async def execute_cache_hit(
525
525
  else:
526
526
  await cursor.execute(compiled_sql)
527
527
  if not cached.operation_profile.returns_rows:
528
- result = DMLResult(cached.operation_type, resolve_rowcount(cursor))
528
+ affected_rows = resolve_rowcount(cursor)
529
+ last_inserted_id = (
530
+ normalize_lastrowid(cursor) if cached.operation_type == "INSERT" and affected_rows > 0 else None
531
+ )
532
+ result = DMLResult(cached.operation_type, affected_rows, last_inserted_id)
529
533
  else:
530
534
  fetched_data = await cursor.fetchall()
531
535
  rows, column_names, _row_format = collect_rows(