sqlspec 0.32.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 (262) hide show
  1. sqlspec/__init__.py +104 -0
  2. sqlspec/__main__.py +12 -0
  3. sqlspec/__metadata__.py +14 -0
  4. sqlspec/_serialization.py +312 -0
  5. sqlspec/_typing.py +784 -0
  6. sqlspec/adapters/__init__.py +0 -0
  7. sqlspec/adapters/adbc/__init__.py +5 -0
  8. sqlspec/adapters/adbc/_types.py +12 -0
  9. sqlspec/adapters/adbc/adk/__init__.py +5 -0
  10. sqlspec/adapters/adbc/adk/store.py +880 -0
  11. sqlspec/adapters/adbc/config.py +436 -0
  12. sqlspec/adapters/adbc/data_dictionary.py +537 -0
  13. sqlspec/adapters/adbc/driver.py +841 -0
  14. sqlspec/adapters/adbc/litestar/__init__.py +5 -0
  15. sqlspec/adapters/adbc/litestar/store.py +504 -0
  16. sqlspec/adapters/adbc/type_converter.py +153 -0
  17. sqlspec/adapters/aiosqlite/__init__.py +29 -0
  18. sqlspec/adapters/aiosqlite/_types.py +13 -0
  19. sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
  20. sqlspec/adapters/aiosqlite/adk/store.py +536 -0
  21. sqlspec/adapters/aiosqlite/config.py +310 -0
  22. sqlspec/adapters/aiosqlite/data_dictionary.py +260 -0
  23. sqlspec/adapters/aiosqlite/driver.py +463 -0
  24. sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
  25. sqlspec/adapters/aiosqlite/litestar/store.py +281 -0
  26. sqlspec/adapters/aiosqlite/pool.py +500 -0
  27. sqlspec/adapters/asyncmy/__init__.py +25 -0
  28. sqlspec/adapters/asyncmy/_types.py +12 -0
  29. sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
  30. sqlspec/adapters/asyncmy/adk/store.py +503 -0
  31. sqlspec/adapters/asyncmy/config.py +246 -0
  32. sqlspec/adapters/asyncmy/data_dictionary.py +241 -0
  33. sqlspec/adapters/asyncmy/driver.py +632 -0
  34. sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
  35. sqlspec/adapters/asyncmy/litestar/store.py +296 -0
  36. sqlspec/adapters/asyncpg/__init__.py +23 -0
  37. sqlspec/adapters/asyncpg/_type_handlers.py +76 -0
  38. sqlspec/adapters/asyncpg/_types.py +23 -0
  39. sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
  40. sqlspec/adapters/asyncpg/adk/store.py +460 -0
  41. sqlspec/adapters/asyncpg/config.py +464 -0
  42. sqlspec/adapters/asyncpg/data_dictionary.py +321 -0
  43. sqlspec/adapters/asyncpg/driver.py +720 -0
  44. sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
  45. sqlspec/adapters/asyncpg/litestar/store.py +253 -0
  46. sqlspec/adapters/bigquery/__init__.py +18 -0
  47. sqlspec/adapters/bigquery/_types.py +12 -0
  48. sqlspec/adapters/bigquery/adk/__init__.py +5 -0
  49. sqlspec/adapters/bigquery/adk/store.py +585 -0
  50. sqlspec/adapters/bigquery/config.py +298 -0
  51. sqlspec/adapters/bigquery/data_dictionary.py +256 -0
  52. sqlspec/adapters/bigquery/driver.py +1073 -0
  53. sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
  54. sqlspec/adapters/bigquery/litestar/store.py +327 -0
  55. sqlspec/adapters/bigquery/type_converter.py +125 -0
  56. sqlspec/adapters/duckdb/__init__.py +24 -0
  57. sqlspec/adapters/duckdb/_types.py +12 -0
  58. sqlspec/adapters/duckdb/adk/__init__.py +14 -0
  59. sqlspec/adapters/duckdb/adk/store.py +563 -0
  60. sqlspec/adapters/duckdb/config.py +396 -0
  61. sqlspec/adapters/duckdb/data_dictionary.py +264 -0
  62. sqlspec/adapters/duckdb/driver.py +604 -0
  63. sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
  64. sqlspec/adapters/duckdb/litestar/store.py +332 -0
  65. sqlspec/adapters/duckdb/pool.py +273 -0
  66. sqlspec/adapters/duckdb/type_converter.py +133 -0
  67. sqlspec/adapters/oracledb/__init__.py +32 -0
  68. sqlspec/adapters/oracledb/_numpy_handlers.py +133 -0
  69. sqlspec/adapters/oracledb/_types.py +39 -0
  70. sqlspec/adapters/oracledb/_uuid_handlers.py +130 -0
  71. sqlspec/adapters/oracledb/adk/__init__.py +5 -0
  72. sqlspec/adapters/oracledb/adk/store.py +1632 -0
  73. sqlspec/adapters/oracledb/config.py +469 -0
  74. sqlspec/adapters/oracledb/data_dictionary.py +717 -0
  75. sqlspec/adapters/oracledb/driver.py +1493 -0
  76. sqlspec/adapters/oracledb/litestar/__init__.py +5 -0
  77. sqlspec/adapters/oracledb/litestar/store.py +765 -0
  78. sqlspec/adapters/oracledb/migrations.py +532 -0
  79. sqlspec/adapters/oracledb/type_converter.py +207 -0
  80. sqlspec/adapters/psqlpy/__init__.py +16 -0
  81. sqlspec/adapters/psqlpy/_type_handlers.py +44 -0
  82. sqlspec/adapters/psqlpy/_types.py +12 -0
  83. sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
  84. sqlspec/adapters/psqlpy/adk/store.py +483 -0
  85. sqlspec/adapters/psqlpy/config.py +271 -0
  86. sqlspec/adapters/psqlpy/data_dictionary.py +179 -0
  87. sqlspec/adapters/psqlpy/driver.py +892 -0
  88. sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
  89. sqlspec/adapters/psqlpy/litestar/store.py +272 -0
  90. sqlspec/adapters/psqlpy/type_converter.py +102 -0
  91. sqlspec/adapters/psycopg/__init__.py +32 -0
  92. sqlspec/adapters/psycopg/_type_handlers.py +90 -0
  93. sqlspec/adapters/psycopg/_types.py +18 -0
  94. sqlspec/adapters/psycopg/adk/__init__.py +5 -0
  95. sqlspec/adapters/psycopg/adk/store.py +962 -0
  96. sqlspec/adapters/psycopg/config.py +487 -0
  97. sqlspec/adapters/psycopg/data_dictionary.py +630 -0
  98. sqlspec/adapters/psycopg/driver.py +1336 -0
  99. sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
  100. sqlspec/adapters/psycopg/litestar/store.py +554 -0
  101. sqlspec/adapters/spanner/__init__.py +38 -0
  102. sqlspec/adapters/spanner/_type_handlers.py +186 -0
  103. sqlspec/adapters/spanner/_types.py +12 -0
  104. sqlspec/adapters/spanner/adk/__init__.py +5 -0
  105. sqlspec/adapters/spanner/adk/store.py +435 -0
  106. sqlspec/adapters/spanner/config.py +241 -0
  107. sqlspec/adapters/spanner/data_dictionary.py +95 -0
  108. sqlspec/adapters/spanner/dialect/__init__.py +6 -0
  109. sqlspec/adapters/spanner/dialect/_spangres.py +52 -0
  110. sqlspec/adapters/spanner/dialect/_spanner.py +123 -0
  111. sqlspec/adapters/spanner/driver.py +366 -0
  112. sqlspec/adapters/spanner/litestar/__init__.py +5 -0
  113. sqlspec/adapters/spanner/litestar/store.py +266 -0
  114. sqlspec/adapters/spanner/type_converter.py +46 -0
  115. sqlspec/adapters/sqlite/__init__.py +18 -0
  116. sqlspec/adapters/sqlite/_type_handlers.py +86 -0
  117. sqlspec/adapters/sqlite/_types.py +11 -0
  118. sqlspec/adapters/sqlite/adk/__init__.py +5 -0
  119. sqlspec/adapters/sqlite/adk/store.py +582 -0
  120. sqlspec/adapters/sqlite/config.py +221 -0
  121. sqlspec/adapters/sqlite/data_dictionary.py +256 -0
  122. sqlspec/adapters/sqlite/driver.py +527 -0
  123. sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
  124. sqlspec/adapters/sqlite/litestar/store.py +318 -0
  125. sqlspec/adapters/sqlite/pool.py +140 -0
  126. sqlspec/base.py +811 -0
  127. sqlspec/builder/__init__.py +146 -0
  128. sqlspec/builder/_base.py +900 -0
  129. sqlspec/builder/_column.py +517 -0
  130. sqlspec/builder/_ddl.py +1642 -0
  131. sqlspec/builder/_delete.py +84 -0
  132. sqlspec/builder/_dml.py +381 -0
  133. sqlspec/builder/_expression_wrappers.py +46 -0
  134. sqlspec/builder/_factory.py +1537 -0
  135. sqlspec/builder/_insert.py +315 -0
  136. sqlspec/builder/_join.py +375 -0
  137. sqlspec/builder/_merge.py +848 -0
  138. sqlspec/builder/_parsing_utils.py +297 -0
  139. sqlspec/builder/_select.py +1615 -0
  140. sqlspec/builder/_update.py +161 -0
  141. sqlspec/builder/_vector_expressions.py +259 -0
  142. sqlspec/cli.py +764 -0
  143. sqlspec/config.py +1540 -0
  144. sqlspec/core/__init__.py +305 -0
  145. sqlspec/core/cache.py +785 -0
  146. sqlspec/core/compiler.py +603 -0
  147. sqlspec/core/filters.py +872 -0
  148. sqlspec/core/hashing.py +274 -0
  149. sqlspec/core/metrics.py +83 -0
  150. sqlspec/core/parameters/__init__.py +64 -0
  151. sqlspec/core/parameters/_alignment.py +266 -0
  152. sqlspec/core/parameters/_converter.py +413 -0
  153. sqlspec/core/parameters/_processor.py +341 -0
  154. sqlspec/core/parameters/_registry.py +201 -0
  155. sqlspec/core/parameters/_transformers.py +226 -0
  156. sqlspec/core/parameters/_types.py +430 -0
  157. sqlspec/core/parameters/_validator.py +123 -0
  158. sqlspec/core/pipeline.py +187 -0
  159. sqlspec/core/result.py +1124 -0
  160. sqlspec/core/splitter.py +940 -0
  161. sqlspec/core/stack.py +163 -0
  162. sqlspec/core/statement.py +835 -0
  163. sqlspec/core/type_conversion.py +235 -0
  164. sqlspec/driver/__init__.py +36 -0
  165. sqlspec/driver/_async.py +1027 -0
  166. sqlspec/driver/_common.py +1236 -0
  167. sqlspec/driver/_sync.py +1025 -0
  168. sqlspec/driver/mixins/__init__.py +7 -0
  169. sqlspec/driver/mixins/_result_tools.py +61 -0
  170. sqlspec/driver/mixins/_sql_translator.py +122 -0
  171. sqlspec/driver/mixins/_storage.py +311 -0
  172. sqlspec/exceptions.py +321 -0
  173. sqlspec/extensions/__init__.py +0 -0
  174. sqlspec/extensions/adk/__init__.py +53 -0
  175. sqlspec/extensions/adk/_types.py +51 -0
  176. sqlspec/extensions/adk/converters.py +172 -0
  177. sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +144 -0
  178. sqlspec/extensions/adk/migrations/__init__.py +0 -0
  179. sqlspec/extensions/adk/service.py +181 -0
  180. sqlspec/extensions/adk/store.py +536 -0
  181. sqlspec/extensions/aiosql/__init__.py +10 -0
  182. sqlspec/extensions/aiosql/adapter.py +471 -0
  183. sqlspec/extensions/fastapi/__init__.py +19 -0
  184. sqlspec/extensions/fastapi/extension.py +341 -0
  185. sqlspec/extensions/fastapi/providers.py +543 -0
  186. sqlspec/extensions/flask/__init__.py +36 -0
  187. sqlspec/extensions/flask/_state.py +72 -0
  188. sqlspec/extensions/flask/_utils.py +40 -0
  189. sqlspec/extensions/flask/extension.py +402 -0
  190. sqlspec/extensions/litestar/__init__.py +23 -0
  191. sqlspec/extensions/litestar/_utils.py +52 -0
  192. sqlspec/extensions/litestar/cli.py +92 -0
  193. sqlspec/extensions/litestar/config.py +90 -0
  194. sqlspec/extensions/litestar/handlers.py +316 -0
  195. sqlspec/extensions/litestar/migrations/0001_create_session_table.py +137 -0
  196. sqlspec/extensions/litestar/migrations/__init__.py +3 -0
  197. sqlspec/extensions/litestar/plugin.py +638 -0
  198. sqlspec/extensions/litestar/providers.py +454 -0
  199. sqlspec/extensions/litestar/store.py +265 -0
  200. sqlspec/extensions/otel/__init__.py +58 -0
  201. sqlspec/extensions/prometheus/__init__.py +107 -0
  202. sqlspec/extensions/starlette/__init__.py +10 -0
  203. sqlspec/extensions/starlette/_state.py +26 -0
  204. sqlspec/extensions/starlette/_utils.py +52 -0
  205. sqlspec/extensions/starlette/extension.py +257 -0
  206. sqlspec/extensions/starlette/middleware.py +154 -0
  207. sqlspec/loader.py +716 -0
  208. sqlspec/migrations/__init__.py +36 -0
  209. sqlspec/migrations/base.py +728 -0
  210. sqlspec/migrations/commands.py +1140 -0
  211. sqlspec/migrations/context.py +142 -0
  212. sqlspec/migrations/fix.py +203 -0
  213. sqlspec/migrations/loaders.py +450 -0
  214. sqlspec/migrations/runner.py +1024 -0
  215. sqlspec/migrations/templates.py +234 -0
  216. sqlspec/migrations/tracker.py +403 -0
  217. sqlspec/migrations/utils.py +256 -0
  218. sqlspec/migrations/validation.py +203 -0
  219. sqlspec/observability/__init__.py +22 -0
  220. sqlspec/observability/_config.py +228 -0
  221. sqlspec/observability/_diagnostics.py +67 -0
  222. sqlspec/observability/_dispatcher.py +151 -0
  223. sqlspec/observability/_observer.py +180 -0
  224. sqlspec/observability/_runtime.py +381 -0
  225. sqlspec/observability/_spans.py +158 -0
  226. sqlspec/protocols.py +530 -0
  227. sqlspec/py.typed +0 -0
  228. sqlspec/storage/__init__.py +46 -0
  229. sqlspec/storage/_utils.py +104 -0
  230. sqlspec/storage/backends/__init__.py +1 -0
  231. sqlspec/storage/backends/base.py +163 -0
  232. sqlspec/storage/backends/fsspec.py +398 -0
  233. sqlspec/storage/backends/local.py +377 -0
  234. sqlspec/storage/backends/obstore.py +580 -0
  235. sqlspec/storage/errors.py +104 -0
  236. sqlspec/storage/pipeline.py +604 -0
  237. sqlspec/storage/registry.py +289 -0
  238. sqlspec/typing.py +219 -0
  239. sqlspec/utils/__init__.py +31 -0
  240. sqlspec/utils/arrow_helpers.py +95 -0
  241. sqlspec/utils/config_resolver.py +153 -0
  242. sqlspec/utils/correlation.py +132 -0
  243. sqlspec/utils/data_transformation.py +114 -0
  244. sqlspec/utils/dependencies.py +79 -0
  245. sqlspec/utils/deprecation.py +113 -0
  246. sqlspec/utils/fixtures.py +250 -0
  247. sqlspec/utils/logging.py +172 -0
  248. sqlspec/utils/module_loader.py +273 -0
  249. sqlspec/utils/portal.py +325 -0
  250. sqlspec/utils/schema.py +288 -0
  251. sqlspec/utils/serializers.py +396 -0
  252. sqlspec/utils/singleton.py +41 -0
  253. sqlspec/utils/sync_tools.py +277 -0
  254. sqlspec/utils/text.py +108 -0
  255. sqlspec/utils/type_converters.py +99 -0
  256. sqlspec/utils/type_guards.py +1324 -0
  257. sqlspec/utils/version.py +444 -0
  258. sqlspec-0.32.0.dist-info/METADATA +202 -0
  259. sqlspec-0.32.0.dist-info/RECORD +262 -0
  260. sqlspec-0.32.0.dist-info/WHEEL +4 -0
  261. sqlspec-0.32.0.dist-info/entry_points.txt +2 -0
  262. sqlspec-0.32.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,318 @@
1
+ """SQLite sync session store for Litestar integration."""
2
+
3
+ from datetime import datetime, timedelta, timezone
4
+ from typing import TYPE_CHECKING
5
+
6
+ from sqlspec.extensions.litestar.store import BaseSQLSpecStore
7
+ from sqlspec.utils.logging import get_logger
8
+ from sqlspec.utils.sync_tools import async_
9
+
10
+ if TYPE_CHECKING:
11
+ from sqlspec.adapters.sqlite.config import SqliteConfig
12
+
13
+ logger = get_logger("adapters.sqlite.litestar.store")
14
+
15
+ SECONDS_PER_DAY = 86400.0
16
+ JULIAN_EPOCH = 2440587.5
17
+
18
+ __all__ = ("SQLiteStore",)
19
+
20
+
21
+ class SQLiteStore(BaseSQLSpecStore["SqliteConfig"]):
22
+ """SQLite session store using synchronous SQLite driver.
23
+
24
+ Implements server-side session storage for Litestar using SQLite
25
+ via the synchronous sqlite3 driver. Uses Litestar's sync_to_thread
26
+ utility to provide an async interface compatible with the Store protocol.
27
+
28
+ Provides efficient session management with:
29
+ - Sync operations wrapped for async compatibility
30
+ - INSERT OR REPLACE for UPSERT functionality
31
+ - Automatic expiration handling
32
+ - Efficient cleanup of expired sessions
33
+
34
+ Args:
35
+ config: SqliteConfig instance.
36
+
37
+ Example:
38
+ from sqlspec.adapters.sqlite import SqliteConfig
39
+ from sqlspec.adapters.sqlite.litestar.store import SQLiteStore
40
+
41
+ config = SqliteConfig(database=":memory:")
42
+ store = SQLiteStore(config)
43
+ await store.create_table()
44
+ """
45
+
46
+ __slots__ = ()
47
+
48
+ def __init__(self, config: "SqliteConfig") -> None:
49
+ """Initialize SQLite session store.
50
+
51
+ Args:
52
+ config: SqliteConfig instance.
53
+
54
+ Notes:
55
+ Table name is read from config.extension_config["litestar"]["session_table"].
56
+ """
57
+ super().__init__(config)
58
+
59
+ def _get_create_table_sql(self) -> str:
60
+ """Get SQLite CREATE TABLE SQL.
61
+
62
+ Returns:
63
+ SQL statement to create the sessions table with proper indexes.
64
+
65
+ Notes:
66
+ - Uses REAL type for expires_at (stores Julian Day number)
67
+ - Julian Day enables direct comparison with julianday('now')
68
+ - Partial index WHERE expires_at IS NOT NULL reduces index size
69
+ - This approach ensures the index is actually used by query optimizer
70
+ """
71
+ return f"""
72
+ CREATE TABLE IF NOT EXISTS {self._table_name} (
73
+ session_id TEXT PRIMARY KEY,
74
+ data BLOB NOT NULL,
75
+ expires_at REAL
76
+ );
77
+ CREATE INDEX IF NOT EXISTS idx_{self._table_name}_expires_at
78
+ ON {self._table_name}(expires_at) WHERE expires_at IS NOT NULL;
79
+ """
80
+
81
+ def _get_drop_table_sql(self) -> "list[str]":
82
+ """Get SQLite DROP TABLE SQL statements.
83
+
84
+ Returns:
85
+ List of SQL statements to drop indexes and table.
86
+ """
87
+ return [f"DROP INDEX IF EXISTS idx_{self._table_name}_expires_at", f"DROP TABLE IF EXISTS {self._table_name}"]
88
+
89
+ def _datetime_to_julian(self, dt: "datetime | None") -> "float | None":
90
+ """Convert datetime to Julian Day number for SQLite storage.
91
+
92
+ Args:
93
+ dt: Datetime to convert (must be UTC-aware).
94
+
95
+ Returns:
96
+ Julian Day number as REAL, or None if dt is None.
97
+
98
+ Notes:
99
+ Julian Day number is days since November 24, 4714 BCE (proleptic Gregorian).
100
+ This enables direct comparison with julianday('now') in SQL queries.
101
+ """
102
+ if dt is None:
103
+ return None
104
+
105
+ epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
106
+ delta_days = (dt - epoch).total_seconds() / SECONDS_PER_DAY
107
+ return JULIAN_EPOCH + delta_days
108
+
109
+ def _julian_to_datetime(self, julian: "float | None") -> "datetime | None":
110
+ """Convert Julian Day number back to datetime.
111
+
112
+ Args:
113
+ julian: Julian Day number.
114
+
115
+ Returns:
116
+ UTC-aware datetime, or None if julian is None.
117
+ """
118
+ if julian is None:
119
+ return None
120
+
121
+ days_since_epoch = julian - JULIAN_EPOCH
122
+ timestamp = days_since_epoch * SECONDS_PER_DAY
123
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc)
124
+
125
+ def _create_table(self) -> None:
126
+ """Synchronous implementation of create_table."""
127
+ sql = self._get_create_table_sql()
128
+ with self._config.provide_session() as driver:
129
+ driver.execute_script(sql)
130
+ logger.debug("Created session table: %s", self._table_name)
131
+
132
+ async def create_table(self) -> None:
133
+ """Create the session table if it doesn't exist."""
134
+ await async_(self._create_table)()
135
+
136
+ def _get(self, key: str, renew_for: "int | timedelta | None" = None) -> "bytes | None":
137
+ """Synchronous implementation of get."""
138
+ sql = f"""
139
+ SELECT data, expires_at FROM {self._table_name}
140
+ WHERE session_id = ?
141
+ AND (expires_at IS NULL OR julianday(expires_at) > julianday('now'))
142
+ """
143
+
144
+ with self._config.provide_connection() as conn:
145
+ cursor = conn.execute(sql, (key,))
146
+ row = cursor.fetchone()
147
+
148
+ if row is None:
149
+ return None
150
+
151
+ data, expires_at_julian = row
152
+
153
+ if renew_for is not None and expires_at_julian is not None:
154
+ new_expires_at = self._calculate_expires_at(renew_for)
155
+ new_expires_at_julian = self._datetime_to_julian(new_expires_at)
156
+ if new_expires_at_julian is not None:
157
+ update_sql = f"""
158
+ UPDATE {self._table_name}
159
+ SET expires_at = ?
160
+ WHERE session_id = ?
161
+ """
162
+ conn.execute(update_sql, (new_expires_at_julian, key))
163
+ conn.commit()
164
+
165
+ return bytes(data)
166
+
167
+ async def get(self, key: str, renew_for: "int | timedelta | None" = None) -> "bytes | None":
168
+ """Get a session value by key.
169
+
170
+ Args:
171
+ key: Session ID to retrieve.
172
+ renew_for: If given, renew the expiry time for this duration.
173
+
174
+ Returns:
175
+ Session data as bytes if found and not expired, None otherwise.
176
+ """
177
+ return await async_(self._get)(key, renew_for)
178
+
179
+ def _set(self, key: str, value: "str | bytes", expires_in: "int | timedelta | None" = None) -> None:
180
+ """Synchronous implementation of set.
181
+
182
+ Notes:
183
+ Stores expires_at as Julian Day number (REAL) for optimal index usage.
184
+ """
185
+ data = self._value_to_bytes(value)
186
+ expires_at = self._calculate_expires_at(expires_in)
187
+ expires_at_julian = self._datetime_to_julian(expires_at)
188
+
189
+ sql = f"""
190
+ INSERT OR REPLACE INTO {self._table_name} (session_id, data, expires_at)
191
+ VALUES (?, ?, ?)
192
+ """
193
+
194
+ with self._config.provide_connection() as conn:
195
+ conn.execute(sql, (key, data, expires_at_julian))
196
+ conn.commit()
197
+
198
+ async def set(self, key: str, value: "str | bytes", expires_in: "int | timedelta | None" = None) -> None:
199
+ """Store a session value.
200
+
201
+ Args:
202
+ key: Session ID.
203
+ value: Session data.
204
+ expires_in: Time until expiration.
205
+ """
206
+ await async_(self._set)(key, value, expires_in)
207
+
208
+ def _delete(self, key: str) -> None:
209
+ """Synchronous implementation of delete."""
210
+ sql = f"DELETE FROM {self._table_name} WHERE session_id = ?"
211
+
212
+ with self._config.provide_connection() as conn:
213
+ conn.execute(sql, (key,))
214
+ conn.commit()
215
+
216
+ async def delete(self, key: str) -> None:
217
+ """Delete a session by key.
218
+
219
+ Args:
220
+ key: Session ID to delete.
221
+ """
222
+ await async_(self._delete)(key)
223
+
224
+ def _delete_all(self) -> None:
225
+ """Synchronous implementation of delete_all."""
226
+ sql = f"DELETE FROM {self._table_name}"
227
+
228
+ with self._config.provide_connection() as conn:
229
+ conn.execute(sql)
230
+ conn.commit()
231
+ logger.debug("Deleted all sessions from table: %s", self._table_name)
232
+
233
+ async def delete_all(self) -> None:
234
+ """Delete all sessions from the store."""
235
+ await async_(self._delete_all)()
236
+
237
+ def _exists(self, key: str) -> bool:
238
+ """Synchronous implementation of exists."""
239
+ sql = f"""
240
+ SELECT 1 FROM {self._table_name}
241
+ WHERE session_id = ?
242
+ AND (expires_at IS NULL OR julianday(expires_at) > julianday('now'))
243
+ """
244
+
245
+ with self._config.provide_connection() as conn:
246
+ cursor = conn.execute(sql, (key,))
247
+ result = cursor.fetchone()
248
+ return result is not None
249
+
250
+ async def exists(self, key: str) -> bool:
251
+ """Check if a session key exists and is not expired.
252
+
253
+ Args:
254
+ key: Session ID to check.
255
+
256
+ Returns:
257
+ True if the session exists and is not expired.
258
+ """
259
+ return await async_(self._exists)(key)
260
+
261
+ def _expires_in(self, key: str) -> "int | None":
262
+ """Synchronous implementation of expires_in."""
263
+ sql = f"""
264
+ SELECT expires_at FROM {self._table_name}
265
+ WHERE session_id = ?
266
+ """
267
+
268
+ with self._config.provide_connection() as conn:
269
+ cursor = conn.execute(sql, (key,))
270
+ row = cursor.fetchone()
271
+
272
+ if row is None or row[0] is None:
273
+ return None
274
+
275
+ expires_at_julian = row[0]
276
+ expires_at = self._julian_to_datetime(expires_at_julian)
277
+
278
+ if expires_at is None:
279
+ return None
280
+
281
+ now = datetime.now(timezone.utc)
282
+
283
+ if expires_at <= now:
284
+ return 0
285
+
286
+ delta = expires_at - now
287
+ return int(delta.total_seconds())
288
+
289
+ async def expires_in(self, key: str) -> "int | None":
290
+ """Get the time in seconds until the session expires.
291
+
292
+ Args:
293
+ key: Session ID to check.
294
+
295
+ Returns:
296
+ Seconds until expiration, or None if no expiry or key doesn't exist.
297
+ """
298
+ return await async_(self._expires_in)(key)
299
+
300
+ def _delete_expired(self) -> int:
301
+ """Synchronous implementation of delete_expired."""
302
+ sql = f"DELETE FROM {self._table_name} WHERE julianday(expires_at) <= julianday('now')"
303
+
304
+ with self._config.provide_connection() as conn:
305
+ cursor = conn.execute(sql)
306
+ conn.commit()
307
+ count = cursor.rowcount
308
+ if count > 0:
309
+ logger.debug("Cleaned up %d expired sessions", count)
310
+ return count
311
+
312
+ async def delete_expired(self) -> int:
313
+ """Delete all expired sessions.
314
+
315
+ Returns:
316
+ Number of sessions deleted.
317
+ """
318
+ return await async_(self._delete_expired)()
@@ -0,0 +1,140 @@
1
+ """SQLite database configuration with thread-local connections."""
2
+
3
+ import contextlib
4
+ import sqlite3
5
+ import threading
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING, Any, TypedDict, cast
8
+
9
+ from typing_extensions import NotRequired
10
+
11
+ from sqlspec.adapters.sqlite._types import SqliteConnection
12
+
13
+ if TYPE_CHECKING:
14
+ from collections.abc import Generator
15
+
16
+
17
+ class SqliteConnectionParams(TypedDict):
18
+ """SQLite connection parameters."""
19
+
20
+ database: NotRequired[str]
21
+ timeout: NotRequired[float]
22
+ detect_types: NotRequired[int]
23
+ isolation_level: "NotRequired[str | None]"
24
+ check_same_thread: NotRequired[bool]
25
+ factory: "NotRequired[type[SqliteConnection] | None]"
26
+ cached_statements: NotRequired[int]
27
+ uri: NotRequired[bool]
28
+
29
+
30
+ __all__ = ("SqliteConnectionPool",)
31
+
32
+
33
+ class SqliteConnectionPool:
34
+ """Thread-local connection manager for SQLite.
35
+
36
+ SQLite connections aren't thread-safe, so we use thread-local storage
37
+ to ensure each thread has its own connection. This is simpler and more
38
+ efficient than a traditional pool for SQLite's constraints.
39
+ """
40
+
41
+ __slots__ = ("_connection_parameters", "_enable_optimizations", "_thread_local")
42
+
43
+ def __init__(
44
+ self, connection_parameters: "dict[str, Any]", enable_optimizations: bool = True, **kwargs: Any
45
+ ) -> None:
46
+ """Initialize the thread-local connection manager.
47
+
48
+ Args:
49
+ connection_parameters: SQLite connection parameters
50
+ enable_optimizations: Whether to apply performance PRAGMAs
51
+ **kwargs: Ignored pool parameters for compatibility
52
+ """
53
+ if "check_same_thread" not in connection_parameters:
54
+ connection_parameters = {**connection_parameters, "check_same_thread": False}
55
+ self._connection_parameters = connection_parameters
56
+ self._thread_local = threading.local()
57
+ self._enable_optimizations = enable_optimizations
58
+
59
+ def _create_connection(self) -> SqliteConnection:
60
+ """Create a new SQLite connection with optimizations."""
61
+ connection = sqlite3.connect(**self._connection_parameters)
62
+
63
+ if self._enable_optimizations:
64
+ database = self._connection_parameters.get("database", ":memory:")
65
+ is_memory = database == ":memory:" or "mode=memory" in database
66
+
67
+ if not is_memory:
68
+ connection.execute("PRAGMA journal_mode = DELETE")
69
+ connection.execute("PRAGMA busy_timeout = 5000")
70
+ connection.execute("PRAGMA optimize")
71
+
72
+ connection.execute("PRAGMA foreign_keys = ON")
73
+ connection.execute("PRAGMA synchronous = NORMAL")
74
+
75
+ return connection # type: ignore[no-any-return]
76
+
77
+ def _get_thread_connection(self) -> SqliteConnection:
78
+ """Get or create a connection for the current thread."""
79
+ try:
80
+ return cast("SqliteConnection", self._thread_local.connection)
81
+ except AttributeError:
82
+ connection = self._create_connection()
83
+ self._thread_local.connection = connection
84
+ return connection
85
+
86
+ def _close_thread_connection(self) -> None:
87
+ """Close the connection for the current thread."""
88
+ try:
89
+ connection = self._thread_local.connection
90
+ connection.close()
91
+ del self._thread_local.connection
92
+ except AttributeError:
93
+ pass
94
+
95
+ @contextmanager
96
+ def get_connection(self) -> "Generator[SqliteConnection, None, None]":
97
+ """Get a thread-local connection.
98
+
99
+ Yields:
100
+ SqliteConnection: A thread-local connection.
101
+ """
102
+ connection = self._get_thread_connection()
103
+ try:
104
+ yield connection
105
+ finally:
106
+ with contextlib.suppress(Exception):
107
+ if connection.in_transaction:
108
+ connection.commit()
109
+
110
+ def close(self) -> None:
111
+ """Close the thread-local connection if it exists."""
112
+ self._close_thread_connection()
113
+
114
+ def acquire(self) -> SqliteConnection:
115
+ """Acquire a thread-local connection.
116
+
117
+ Returns:
118
+ SqliteConnection: A thread-local connection
119
+ """
120
+ return self._get_thread_connection()
121
+
122
+ def release(self, connection: SqliteConnection) -> None:
123
+ """Release a connection (no-op for thread-local connections).
124
+
125
+ Args:
126
+ connection: The connection to release (ignored)
127
+ """
128
+
129
+ def size(self) -> int:
130
+ """Get pool size (always 1 for thread-local)."""
131
+ try:
132
+ _ = self._thread_local.connection
133
+ except AttributeError:
134
+ return 0
135
+ else:
136
+ return 1
137
+
138
+ def checked_out(self) -> int:
139
+ """Get number of checked out connections (always 0)."""
140
+ return 0