sqlspec 0.26.0__py3-none-any.whl → 0.27.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.

Potentially problematic release.


This version of sqlspec might be problematic. Click here for more details.

Files changed (197) hide show
  1. sqlspec/__init__.py +7 -15
  2. sqlspec/_serialization.py +55 -25
  3. sqlspec/_typing.py +62 -52
  4. sqlspec/adapters/adbc/_types.py +1 -1
  5. sqlspec/adapters/adbc/adk/__init__.py +5 -0
  6. sqlspec/adapters/adbc/adk/store.py +870 -0
  7. sqlspec/adapters/adbc/config.py +62 -12
  8. sqlspec/adapters/adbc/data_dictionary.py +52 -2
  9. sqlspec/adapters/adbc/driver.py +144 -45
  10. sqlspec/adapters/adbc/litestar/__init__.py +5 -0
  11. sqlspec/adapters/adbc/litestar/store.py +504 -0
  12. sqlspec/adapters/adbc/type_converter.py +44 -50
  13. sqlspec/adapters/aiosqlite/_types.py +1 -1
  14. sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
  15. sqlspec/adapters/aiosqlite/adk/store.py +527 -0
  16. sqlspec/adapters/aiosqlite/config.py +86 -16
  17. sqlspec/adapters/aiosqlite/data_dictionary.py +34 -2
  18. sqlspec/adapters/aiosqlite/driver.py +127 -38
  19. sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
  20. sqlspec/adapters/aiosqlite/litestar/store.py +281 -0
  21. sqlspec/adapters/aiosqlite/pool.py +7 -7
  22. sqlspec/adapters/asyncmy/__init__.py +7 -1
  23. sqlspec/adapters/asyncmy/_types.py +1 -1
  24. sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
  25. sqlspec/adapters/asyncmy/adk/store.py +493 -0
  26. sqlspec/adapters/asyncmy/config.py +59 -17
  27. sqlspec/adapters/asyncmy/data_dictionary.py +41 -2
  28. sqlspec/adapters/asyncmy/driver.py +293 -62
  29. sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
  30. sqlspec/adapters/asyncmy/litestar/store.py +296 -0
  31. sqlspec/adapters/asyncpg/__init__.py +2 -1
  32. sqlspec/adapters/asyncpg/_type_handlers.py +71 -0
  33. sqlspec/adapters/asyncpg/_types.py +11 -7
  34. sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
  35. sqlspec/adapters/asyncpg/adk/store.py +450 -0
  36. sqlspec/adapters/asyncpg/config.py +57 -36
  37. sqlspec/adapters/asyncpg/data_dictionary.py +41 -2
  38. sqlspec/adapters/asyncpg/driver.py +153 -23
  39. sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
  40. sqlspec/adapters/asyncpg/litestar/store.py +253 -0
  41. sqlspec/adapters/bigquery/_types.py +1 -1
  42. sqlspec/adapters/bigquery/adk/__init__.py +5 -0
  43. sqlspec/adapters/bigquery/adk/store.py +576 -0
  44. sqlspec/adapters/bigquery/config.py +25 -11
  45. sqlspec/adapters/bigquery/data_dictionary.py +42 -2
  46. sqlspec/adapters/bigquery/driver.py +352 -144
  47. sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
  48. sqlspec/adapters/bigquery/litestar/store.py +327 -0
  49. sqlspec/adapters/bigquery/type_converter.py +55 -23
  50. sqlspec/adapters/duckdb/_types.py +2 -2
  51. sqlspec/adapters/duckdb/adk/__init__.py +14 -0
  52. sqlspec/adapters/duckdb/adk/store.py +553 -0
  53. sqlspec/adapters/duckdb/config.py +79 -21
  54. sqlspec/adapters/duckdb/data_dictionary.py +41 -2
  55. sqlspec/adapters/duckdb/driver.py +138 -43
  56. sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
  57. sqlspec/adapters/duckdb/litestar/store.py +332 -0
  58. sqlspec/adapters/duckdb/pool.py +5 -5
  59. sqlspec/adapters/duckdb/type_converter.py +51 -21
  60. sqlspec/adapters/oracledb/_numpy_handlers.py +133 -0
  61. sqlspec/adapters/oracledb/_types.py +20 -2
  62. sqlspec/adapters/oracledb/adk/__init__.py +5 -0
  63. sqlspec/adapters/oracledb/adk/store.py +1745 -0
  64. sqlspec/adapters/oracledb/config.py +120 -36
  65. sqlspec/adapters/oracledb/data_dictionary.py +87 -20
  66. sqlspec/adapters/oracledb/driver.py +292 -84
  67. sqlspec/adapters/oracledb/litestar/__init__.py +5 -0
  68. sqlspec/adapters/oracledb/litestar/store.py +767 -0
  69. sqlspec/adapters/oracledb/migrations.py +316 -25
  70. sqlspec/adapters/oracledb/type_converter.py +91 -16
  71. sqlspec/adapters/psqlpy/_type_handlers.py +44 -0
  72. sqlspec/adapters/psqlpy/_types.py +2 -1
  73. sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
  74. sqlspec/adapters/psqlpy/adk/store.py +482 -0
  75. sqlspec/adapters/psqlpy/config.py +45 -19
  76. sqlspec/adapters/psqlpy/data_dictionary.py +41 -2
  77. sqlspec/adapters/psqlpy/driver.py +101 -31
  78. sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
  79. sqlspec/adapters/psqlpy/litestar/store.py +272 -0
  80. sqlspec/adapters/psqlpy/type_converter.py +40 -11
  81. sqlspec/adapters/psycopg/_type_handlers.py +80 -0
  82. sqlspec/adapters/psycopg/_types.py +2 -1
  83. sqlspec/adapters/psycopg/adk/__init__.py +5 -0
  84. sqlspec/adapters/psycopg/adk/store.py +944 -0
  85. sqlspec/adapters/psycopg/config.py +65 -37
  86. sqlspec/adapters/psycopg/data_dictionary.py +77 -3
  87. sqlspec/adapters/psycopg/driver.py +200 -78
  88. sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
  89. sqlspec/adapters/psycopg/litestar/store.py +554 -0
  90. sqlspec/adapters/sqlite/__init__.py +2 -1
  91. sqlspec/adapters/sqlite/_type_handlers.py +86 -0
  92. sqlspec/adapters/sqlite/_types.py +1 -1
  93. sqlspec/adapters/sqlite/adk/__init__.py +5 -0
  94. sqlspec/adapters/sqlite/adk/store.py +572 -0
  95. sqlspec/adapters/sqlite/config.py +85 -16
  96. sqlspec/adapters/sqlite/data_dictionary.py +34 -2
  97. sqlspec/adapters/sqlite/driver.py +120 -52
  98. sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
  99. sqlspec/adapters/sqlite/litestar/store.py +318 -0
  100. sqlspec/adapters/sqlite/pool.py +5 -5
  101. sqlspec/base.py +45 -26
  102. sqlspec/builder/__init__.py +73 -4
  103. sqlspec/builder/_base.py +91 -58
  104. sqlspec/builder/_column.py +5 -5
  105. sqlspec/builder/_ddl.py +98 -89
  106. sqlspec/builder/_delete.py +5 -4
  107. sqlspec/builder/_dml.py +388 -0
  108. sqlspec/{_sql.py → builder/_factory.py} +41 -44
  109. sqlspec/builder/_insert.py +5 -82
  110. sqlspec/builder/{mixins/_join_operations.py → _join.py} +145 -143
  111. sqlspec/builder/_merge.py +446 -11
  112. sqlspec/builder/_parsing_utils.py +9 -11
  113. sqlspec/builder/_select.py +1313 -25
  114. sqlspec/builder/_update.py +11 -42
  115. sqlspec/cli.py +76 -69
  116. sqlspec/config.py +231 -60
  117. sqlspec/core/__init__.py +5 -4
  118. sqlspec/core/cache.py +18 -18
  119. sqlspec/core/compiler.py +6 -8
  120. sqlspec/core/filters.py +37 -37
  121. sqlspec/core/hashing.py +9 -9
  122. sqlspec/core/parameters.py +76 -45
  123. sqlspec/core/result.py +102 -46
  124. sqlspec/core/splitter.py +16 -17
  125. sqlspec/core/statement.py +32 -31
  126. sqlspec/core/type_conversion.py +3 -2
  127. sqlspec/driver/__init__.py +1 -3
  128. sqlspec/driver/_async.py +95 -161
  129. sqlspec/driver/_common.py +133 -80
  130. sqlspec/driver/_sync.py +95 -162
  131. sqlspec/driver/mixins/_result_tools.py +20 -236
  132. sqlspec/driver/mixins/_sql_translator.py +4 -4
  133. sqlspec/exceptions.py +70 -7
  134. sqlspec/extensions/adk/__init__.py +53 -0
  135. sqlspec/extensions/adk/_types.py +51 -0
  136. sqlspec/extensions/adk/converters.py +172 -0
  137. sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +144 -0
  138. sqlspec/extensions/adk/migrations/__init__.py +0 -0
  139. sqlspec/extensions/adk/service.py +181 -0
  140. sqlspec/extensions/adk/store.py +536 -0
  141. sqlspec/extensions/aiosql/adapter.py +73 -53
  142. sqlspec/extensions/litestar/__init__.py +21 -4
  143. sqlspec/extensions/litestar/cli.py +54 -10
  144. sqlspec/extensions/litestar/config.py +59 -266
  145. sqlspec/extensions/litestar/handlers.py +46 -17
  146. sqlspec/extensions/litestar/migrations/0001_create_session_table.py +137 -0
  147. sqlspec/extensions/litestar/migrations/__init__.py +3 -0
  148. sqlspec/extensions/litestar/plugin.py +324 -223
  149. sqlspec/extensions/litestar/providers.py +25 -25
  150. sqlspec/extensions/litestar/store.py +265 -0
  151. sqlspec/loader.py +30 -49
  152. sqlspec/migrations/base.py +200 -76
  153. sqlspec/migrations/commands.py +591 -62
  154. sqlspec/migrations/context.py +6 -9
  155. sqlspec/migrations/fix.py +199 -0
  156. sqlspec/migrations/loaders.py +47 -19
  157. sqlspec/migrations/runner.py +241 -75
  158. sqlspec/migrations/tracker.py +237 -21
  159. sqlspec/migrations/utils.py +51 -3
  160. sqlspec/migrations/validation.py +177 -0
  161. sqlspec/protocols.py +66 -36
  162. sqlspec/storage/_utils.py +98 -0
  163. sqlspec/storage/backends/fsspec.py +134 -106
  164. sqlspec/storage/backends/local.py +78 -51
  165. sqlspec/storage/backends/obstore.py +278 -162
  166. sqlspec/storage/registry.py +75 -39
  167. sqlspec/typing.py +14 -84
  168. sqlspec/utils/config_resolver.py +6 -6
  169. sqlspec/utils/correlation.py +4 -5
  170. sqlspec/utils/data_transformation.py +3 -2
  171. sqlspec/utils/deprecation.py +9 -8
  172. sqlspec/utils/fixtures.py +4 -4
  173. sqlspec/utils/logging.py +46 -6
  174. sqlspec/utils/module_loader.py +2 -2
  175. sqlspec/utils/schema.py +288 -0
  176. sqlspec/utils/serializers.py +3 -3
  177. sqlspec/utils/sync_tools.py +21 -17
  178. sqlspec/utils/text.py +1 -2
  179. sqlspec/utils/type_guards.py +111 -20
  180. sqlspec/utils/version.py +433 -0
  181. {sqlspec-0.26.0.dist-info → sqlspec-0.27.0.dist-info}/METADATA +40 -21
  182. sqlspec-0.27.0.dist-info/RECORD +207 -0
  183. sqlspec/builder/mixins/__init__.py +0 -55
  184. sqlspec/builder/mixins/_cte_and_set_ops.py +0 -253
  185. sqlspec/builder/mixins/_delete_operations.py +0 -50
  186. sqlspec/builder/mixins/_insert_operations.py +0 -282
  187. sqlspec/builder/mixins/_merge_operations.py +0 -698
  188. sqlspec/builder/mixins/_order_limit_operations.py +0 -145
  189. sqlspec/builder/mixins/_pivot_operations.py +0 -157
  190. sqlspec/builder/mixins/_select_operations.py +0 -930
  191. sqlspec/builder/mixins/_update_operations.py +0 -199
  192. sqlspec/builder/mixins/_where_clause.py +0 -1298
  193. sqlspec-0.26.0.dist-info/RECORD +0 -157
  194. sqlspec-0.26.0.dist-info/licenses/NOTICE +0 -29
  195. {sqlspec-0.26.0.dist-info → sqlspec-0.27.0.dist-info}/WHEEL +0 -0
  196. {sqlspec-0.26.0.dist-info → sqlspec-0.27.0.dist-info}/entry_points.txt +0 -0
  197. {sqlspec-0.26.0.dist-info → sqlspec-0.27.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,554 @@
1
+ """Psycopg session stores for Litestar integration.
2
+
3
+ Provides both async and sync PostgreSQL session stores using psycopg3.
4
+ """
5
+
6
+ from datetime import datetime, timedelta, timezone
7
+ from typing import TYPE_CHECKING
8
+
9
+ from sqlspec.extensions.litestar.store import BaseSQLSpecStore
10
+ from sqlspec.utils.logging import get_logger
11
+ from sqlspec.utils.sync_tools import async_
12
+
13
+ if TYPE_CHECKING:
14
+ from sqlspec.adapters.psycopg.config import PsycopgAsyncConfig, PsycopgSyncConfig
15
+
16
+ logger = get_logger("adapters.psycopg.litestar.store")
17
+
18
+ __all__ = ("PsycopgAsyncStore", "PsycopgSyncStore")
19
+
20
+
21
+ class PsycopgAsyncStore(BaseSQLSpecStore["PsycopgAsyncConfig"]):
22
+ """PostgreSQL session store using Psycopg async driver.
23
+
24
+ Implements server-side session storage for Litestar using PostgreSQL
25
+ via the Psycopg (psycopg3) async driver. Provides efficient session
26
+ management with:
27
+ - Native async PostgreSQL operations
28
+ - UPSERT support using ON CONFLICT
29
+ - Automatic expiration handling
30
+ - Efficient cleanup of expired sessions
31
+
32
+ Args:
33
+ config: PsycopgAsyncConfig instance.
34
+
35
+ Example:
36
+ from sqlspec.adapters.psycopg import PsycopgAsyncConfig
37
+ from sqlspec.adapters.psycopg.litestar.store import PsycopgAsyncStore
38
+
39
+ config = PsycopgAsyncConfig(pool_config={"conninfo": "postgresql://..."})
40
+ store = PsycopgAsyncStore(config)
41
+ await store.create_table()
42
+ """
43
+
44
+ __slots__ = ()
45
+
46
+ def __init__(self, config: "PsycopgAsyncConfig") -> None:
47
+ """Initialize Psycopg async session store.
48
+
49
+ Args:
50
+ config: PsycopgAsyncConfig instance.
51
+
52
+ Notes:
53
+ Table name is read from config.extension_config["litestar"]["session_table"].
54
+ """
55
+ super().__init__(config)
56
+
57
+ def _get_create_table_sql(self) -> str:
58
+ """Get PostgreSQL CREATE TABLE SQL with optimized schema.
59
+
60
+ Returns:
61
+ SQL statement to create the sessions table with proper indexes.
62
+
63
+ Notes:
64
+ - Uses TIMESTAMPTZ for timezone-aware expiration timestamps
65
+ - Partial index WHERE expires_at IS NOT NULL reduces index size/maintenance
66
+ - FILLFACTOR 80 leaves space for HOT updates, reducing table bloat
67
+ - Audit columns (created_at, updated_at) help with debugging
68
+ - Table name is internally controlled, not user input (S608 suppressed)
69
+ """
70
+ return f"""
71
+ CREATE TABLE IF NOT EXISTS {self._table_name} (
72
+ session_id TEXT PRIMARY KEY,
73
+ data BYTEA NOT NULL,
74
+ expires_at TIMESTAMPTZ,
75
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
76
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
77
+ ) WITH (fillfactor = 80);
78
+
79
+ CREATE INDEX IF NOT EXISTS idx_{self._table_name}_expires_at
80
+ ON {self._table_name}(expires_at) WHERE expires_at IS NOT NULL;
81
+
82
+ ALTER TABLE {self._table_name} SET (
83
+ autovacuum_vacuum_scale_factor = 0.05,
84
+ autovacuum_analyze_scale_factor = 0.02
85
+ );
86
+ """
87
+
88
+ def _get_drop_table_sql(self) -> "list[str]":
89
+ """Get PostgreSQL DROP TABLE SQL statements.
90
+
91
+ Returns:
92
+ List of SQL statements to drop indexes and table.
93
+ """
94
+ return [f"DROP INDEX IF EXISTS idx_{self._table_name}_expires_at", f"DROP TABLE IF EXISTS {self._table_name}"]
95
+
96
+ async def create_table(self) -> None:
97
+ """Create the session table if it doesn't exist."""
98
+ sql = self._get_create_table_sql()
99
+ async with self._config.provide_session() as driver:
100
+ await driver.execute_script(sql)
101
+ await driver.commit()
102
+ logger.debug("Created session table: %s", self._table_name)
103
+
104
+ async def get(self, key: str, renew_for: "int | timedelta | None" = None) -> "bytes | None":
105
+ """Get a session value by key.
106
+
107
+ Args:
108
+ key: Session ID to retrieve.
109
+ renew_for: If given, renew the expiry time for this duration.
110
+
111
+ Returns:
112
+ Session data as bytes if found and not expired, None otherwise.
113
+
114
+ Notes:
115
+ Uses CURRENT_TIMESTAMP instead of NOW() for SQL standard compliance.
116
+ The query planner can use the partial index for expires_at > CURRENT_TIMESTAMP.
117
+ """
118
+ sql = f"""
119
+ SELECT data, expires_at FROM {self._table_name}
120
+ WHERE session_id = %s
121
+ AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
122
+ """
123
+
124
+ conn_context = self._config.provide_connection()
125
+ async with conn_context as conn:
126
+ async with conn.cursor() as cur:
127
+ await cur.execute(sql.encode(), (key,))
128
+ row = await cur.fetchone()
129
+
130
+ if row is None:
131
+ return None
132
+
133
+ if renew_for is not None and row["expires_at"] is not None:
134
+ new_expires_at = self._calculate_expires_at(renew_for)
135
+ if new_expires_at is not None:
136
+ update_sql = f"""
137
+ UPDATE {self._table_name}
138
+ SET expires_at = %s, updated_at = CURRENT_TIMESTAMP
139
+ WHERE session_id = %s
140
+ """
141
+ await conn.execute(update_sql.encode(), (new_expires_at, key))
142
+ await conn.commit()
143
+
144
+ return bytes(row["data"])
145
+
146
+ async def set(self, key: str, value: "str | bytes", expires_in: "int | timedelta | None" = None) -> None:
147
+ """Store a session value.
148
+
149
+ Args:
150
+ key: Session ID.
151
+ value: Session data.
152
+ expires_in: Time until expiration.
153
+
154
+ Notes:
155
+ Uses EXCLUDED to reference the proposed insert values in ON CONFLICT.
156
+ Updates updated_at timestamp on every write for audit trail.
157
+ """
158
+ data = self._value_to_bytes(value)
159
+ expires_at = self._calculate_expires_at(expires_in)
160
+
161
+ sql = f"""
162
+ INSERT INTO {self._table_name} (session_id, data, expires_at)
163
+ VALUES (%s, %s, %s)
164
+ ON CONFLICT (session_id)
165
+ DO UPDATE SET
166
+ data = EXCLUDED.data,
167
+ expires_at = EXCLUDED.expires_at,
168
+ updated_at = CURRENT_TIMESTAMP
169
+ """
170
+
171
+ conn_context = self._config.provide_connection()
172
+ async with conn_context as conn:
173
+ await conn.execute(sql.encode(), (key, data, expires_at))
174
+ await conn.commit()
175
+
176
+ async def delete(self, key: str) -> None:
177
+ """Delete a session by key.
178
+
179
+ Args:
180
+ key: Session ID to delete.
181
+ """
182
+ sql = f"DELETE FROM {self._table_name} WHERE session_id = %s"
183
+
184
+ conn_context = self._config.provide_connection()
185
+ async with conn_context as conn:
186
+ await conn.execute(sql.encode(), (key,))
187
+ await conn.commit()
188
+
189
+ async def delete_all(self) -> None:
190
+ """Delete all sessions from the store."""
191
+ sql = f"DELETE FROM {self._table_name}"
192
+
193
+ conn_context = self._config.provide_connection()
194
+ async with conn_context as conn:
195
+ await conn.execute(sql.encode())
196
+ await conn.commit()
197
+ logger.debug("Deleted all sessions from table: %s", self._table_name)
198
+
199
+ async def exists(self, key: str) -> bool:
200
+ """Check if a session key exists and is not expired.
201
+
202
+ Args:
203
+ key: Session ID to check.
204
+
205
+ Returns:
206
+ True if the session exists and is not expired.
207
+
208
+ Notes:
209
+ Uses CURRENT_TIMESTAMP for consistency with get() method.
210
+ """
211
+ sql = f"""
212
+ SELECT 1 FROM {self._table_name}
213
+ WHERE session_id = %s
214
+ AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
215
+ """
216
+
217
+ conn_context = self._config.provide_connection()
218
+ async with conn_context as conn, conn.cursor() as cur:
219
+ await cur.execute(sql.encode(), (key,))
220
+ result = await cur.fetchone()
221
+ return result is not None
222
+
223
+ async def expires_in(self, key: str) -> "int | None":
224
+ """Get the time in seconds until the session expires.
225
+
226
+ Args:
227
+ key: Session ID to check.
228
+
229
+ Returns:
230
+ Seconds until expiration, or None if no expiry or key doesn't exist.
231
+ """
232
+ sql = f"""
233
+ SELECT expires_at FROM {self._table_name}
234
+ WHERE session_id = %s
235
+ """
236
+
237
+ conn_context = self._config.provide_connection()
238
+ async with conn_context as conn:
239
+ async with conn.cursor() as cur:
240
+ await cur.execute(sql.encode(), (key,))
241
+ row = await cur.fetchone()
242
+
243
+ if row is None or row["expires_at"] is None:
244
+ return None
245
+
246
+ expires_at = row["expires_at"]
247
+ now = datetime.now(timezone.utc)
248
+ if expires_at <= now:
249
+ return 0
250
+
251
+ delta = expires_at - now
252
+ return int(delta.total_seconds())
253
+
254
+ async def delete_expired(self) -> int:
255
+ """Delete all expired sessions.
256
+
257
+ Returns:
258
+ Number of sessions deleted.
259
+
260
+ Notes:
261
+ Uses CURRENT_TIMESTAMP for consistency.
262
+ For very large tables (10M+ rows), consider batching deletes
263
+ to avoid holding locks too long.
264
+ """
265
+ sql = f"DELETE FROM {self._table_name} WHERE expires_at <= CURRENT_TIMESTAMP"
266
+
267
+ conn_context = self._config.provide_connection()
268
+ async with conn_context as conn, conn.cursor() as cur:
269
+ await cur.execute(sql.encode())
270
+ await conn.commit()
271
+ count = cur.rowcount if cur.rowcount and cur.rowcount > 0 else 0
272
+ if count > 0:
273
+ logger.debug("Cleaned up %d expired sessions", count)
274
+ return count
275
+
276
+
277
+ class PsycopgSyncStore(BaseSQLSpecStore["PsycopgSyncConfig"]):
278
+ """PostgreSQL session store using Psycopg sync driver.
279
+
280
+ Implements server-side session storage for Litestar using PostgreSQL
281
+ via the synchronous Psycopg (psycopg3) driver. Uses Litestar's sync_to_thread
282
+ utility to provide an async interface compatible with the Store protocol.
283
+
284
+ Provides efficient session management with:
285
+ - Sync operations wrapped for async compatibility
286
+ - UPSERT support using ON CONFLICT
287
+ - Automatic expiration handling
288
+ - Efficient cleanup of expired sessions
289
+
290
+ Note:
291
+ For high-concurrency applications, consider using PsycopgAsyncStore instead,
292
+ as it provides native async operations without threading overhead.
293
+
294
+ Args:
295
+ config: PsycopgSyncConfig instance.
296
+
297
+ Example:
298
+ from sqlspec.adapters.psycopg import PsycopgSyncConfig
299
+ from sqlspec.adapters.psycopg.litestar.store import PsycopgSyncStore
300
+
301
+ config = PsycopgSyncConfig(pool_config={"conninfo": "postgresql://..."})
302
+ store = PsycopgSyncStore(config)
303
+ await store.create_table()
304
+ """
305
+
306
+ __slots__ = ()
307
+
308
+ def __init__(self, config: "PsycopgSyncConfig") -> None:
309
+ """Initialize Psycopg sync session store.
310
+
311
+ Args:
312
+ config: PsycopgSyncConfig instance.
313
+
314
+ Notes:
315
+ Table name is read from config.extension_config["litestar"]["session_table"].
316
+ """
317
+ super().__init__(config)
318
+
319
+ def _get_create_table_sql(self) -> str:
320
+ """Get PostgreSQL CREATE TABLE SQL with optimized schema.
321
+
322
+ Returns:
323
+ SQL statement to create the sessions table with proper indexes.
324
+
325
+ Notes:
326
+ - Uses TIMESTAMPTZ for timezone-aware expiration timestamps
327
+ - Partial index WHERE expires_at IS NOT NULL reduces index size/maintenance
328
+ - FILLFACTOR 80 leaves space for HOT updates, reducing table bloat
329
+ - Audit columns (created_at, updated_at) help with debugging
330
+ - Table name is internally controlled, not user input (S608 suppressed)
331
+ """
332
+ return f"""
333
+ CREATE TABLE IF NOT EXISTS {self._table_name} (
334
+ session_id TEXT PRIMARY KEY,
335
+ data BYTEA NOT NULL,
336
+ expires_at TIMESTAMPTZ,
337
+ created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
338
+ updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
339
+ ) WITH (fillfactor = 80);
340
+
341
+ CREATE INDEX IF NOT EXISTS idx_{self._table_name}_expires_at
342
+ ON {self._table_name}(expires_at) WHERE expires_at IS NOT NULL;
343
+
344
+ ALTER TABLE {self._table_name} SET (
345
+ autovacuum_vacuum_scale_factor = 0.05,
346
+ autovacuum_analyze_scale_factor = 0.02
347
+ );
348
+ """
349
+
350
+ def _get_drop_table_sql(self) -> "list[str]":
351
+ """Get PostgreSQL DROP TABLE SQL statements.
352
+
353
+ Returns:
354
+ List of SQL statements to drop indexes and table.
355
+ """
356
+ return [f"DROP INDEX IF EXISTS idx_{self._table_name}_expires_at", f"DROP TABLE IF EXISTS {self._table_name}"]
357
+
358
+ def _create_table(self) -> None:
359
+ """Synchronous implementation of create_table."""
360
+ sql = self._get_create_table_sql()
361
+ with self._config.provide_session() as driver:
362
+ driver.execute_script(sql)
363
+ driver.commit()
364
+ logger.debug("Created session table: %s", self._table_name)
365
+
366
+ async def create_table(self) -> None:
367
+ """Create the session table if it doesn't exist."""
368
+ await async_(self._create_table)()
369
+
370
+ def _get(self, key: str, renew_for: "int | timedelta | None" = None) -> "bytes | None":
371
+ """Synchronous implementation of get.
372
+
373
+ Notes:
374
+ Uses CURRENT_TIMESTAMP for SQL standard compliance.
375
+ """
376
+ sql = f"""
377
+ SELECT data, expires_at FROM {self._table_name}
378
+ WHERE session_id = %s
379
+ AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
380
+ """
381
+
382
+ with self._config.provide_connection() as conn:
383
+ with conn.cursor() as cur:
384
+ cur.execute(sql.encode(), (key,))
385
+ row = cur.fetchone()
386
+
387
+ if row is None:
388
+ return None
389
+
390
+ if renew_for is not None and row["expires_at"] is not None:
391
+ new_expires_at = self._calculate_expires_at(renew_for)
392
+ if new_expires_at is not None:
393
+ update_sql = f"""
394
+ UPDATE {self._table_name}
395
+ SET expires_at = %s, updated_at = CURRENT_TIMESTAMP
396
+ WHERE session_id = %s
397
+ """
398
+ conn.execute(update_sql.encode(), (new_expires_at, key))
399
+ conn.commit()
400
+
401
+ return bytes(row["data"])
402
+
403
+ async def get(self, key: str, renew_for: "int | timedelta | None" = None) -> "bytes | None":
404
+ """Get a session value by key.
405
+
406
+ Args:
407
+ key: Session ID to retrieve.
408
+ renew_for: If given, renew the expiry time for this duration.
409
+
410
+ Returns:
411
+ Session data as bytes if found and not expired, None otherwise.
412
+ """
413
+ return await async_(self._get)(key, renew_for)
414
+
415
+ def _set(self, key: str, value: "str | bytes", expires_in: "int | timedelta | None" = None) -> None:
416
+ """Synchronous implementation of set.
417
+
418
+ Notes:
419
+ Uses EXCLUDED to reference the proposed insert values in ON CONFLICT.
420
+ """
421
+ data = self._value_to_bytes(value)
422
+ expires_at = self._calculate_expires_at(expires_in)
423
+
424
+ sql = f"""
425
+ INSERT INTO {self._table_name} (session_id, data, expires_at)
426
+ VALUES (%s, %s, %s)
427
+ ON CONFLICT (session_id)
428
+ DO UPDATE SET
429
+ data = EXCLUDED.data,
430
+ expires_at = EXCLUDED.expires_at,
431
+ updated_at = CURRENT_TIMESTAMP
432
+ """
433
+
434
+ with self._config.provide_connection() as conn:
435
+ conn.execute(sql.encode(), (key, data, expires_at))
436
+ conn.commit()
437
+
438
+ async def set(self, key: str, value: "str | bytes", expires_in: "int | timedelta | None" = None) -> None:
439
+ """Store a session value.
440
+
441
+ Args:
442
+ key: Session ID.
443
+ value: Session data.
444
+ expires_in: Time until expiration.
445
+ """
446
+ await async_(self._set)(key, value, expires_in)
447
+
448
+ def _delete(self, key: str) -> None:
449
+ """Synchronous implementation of delete."""
450
+ sql = f"DELETE FROM {self._table_name} WHERE session_id = %s"
451
+
452
+ with self._config.provide_connection() as conn:
453
+ conn.execute(sql.encode(), (key,))
454
+ conn.commit()
455
+
456
+ async def delete(self, key: str) -> None:
457
+ """Delete a session by key.
458
+
459
+ Args:
460
+ key: Session ID to delete.
461
+ """
462
+ await async_(self._delete)(key)
463
+
464
+ def _delete_all(self) -> None:
465
+ """Synchronous implementation of delete_all."""
466
+ sql = f"DELETE FROM {self._table_name}"
467
+
468
+ with self._config.provide_connection() as conn:
469
+ conn.execute(sql.encode())
470
+ conn.commit()
471
+ logger.debug("Deleted all sessions from table: %s", self._table_name)
472
+
473
+ async def delete_all(self) -> None:
474
+ """Delete all sessions from the store."""
475
+ await async_(self._delete_all)()
476
+
477
+ def _exists(self, key: str) -> bool:
478
+ """Synchronous implementation of exists."""
479
+ sql = f"""
480
+ SELECT 1 FROM {self._table_name}
481
+ WHERE session_id = %s
482
+ AND (expires_at IS NULL OR expires_at > CURRENT_TIMESTAMP)
483
+ """
484
+
485
+ with self._config.provide_connection() as conn, conn.cursor() as cur:
486
+ cur.execute(sql.encode(), (key,))
487
+ result = cur.fetchone()
488
+ return result is not None
489
+
490
+ async def exists(self, key: str) -> bool:
491
+ """Check if a session key exists and is not expired.
492
+
493
+ Args:
494
+ key: Session ID to check.
495
+
496
+ Returns:
497
+ True if the session exists and is not expired.
498
+ """
499
+ return await async_(self._exists)(key)
500
+
501
+ def _expires_in(self, key: str) -> "int | None":
502
+ """Synchronous implementation of expires_in."""
503
+ sql = f"""
504
+ SELECT expires_at FROM {self._table_name}
505
+ WHERE session_id = %s
506
+ """
507
+
508
+ with self._config.provide_connection() as conn:
509
+ with conn.cursor() as cur:
510
+ cur.execute(sql.encode(), (key,))
511
+ row = cur.fetchone()
512
+
513
+ if row is None or row["expires_at"] is None:
514
+ return None
515
+
516
+ expires_at = row["expires_at"]
517
+ now = datetime.now(timezone.utc)
518
+
519
+ if expires_at <= now:
520
+ return 0
521
+
522
+ delta = expires_at - now
523
+ return int(delta.total_seconds())
524
+
525
+ async def expires_in(self, key: str) -> "int | None":
526
+ """Get the time in seconds until the session expires.
527
+
528
+ Args:
529
+ key: Session ID to check.
530
+
531
+ Returns:
532
+ Seconds until expiration, or None if no expiry or key doesn't exist.
533
+ """
534
+ return await async_(self._expires_in)(key)
535
+
536
+ def _delete_expired(self) -> int:
537
+ """Synchronous implementation of delete_expired."""
538
+ sql = f"DELETE FROM {self._table_name} WHERE expires_at <= CURRENT_TIMESTAMP"
539
+
540
+ with self._config.provide_connection() as conn, conn.cursor() as cur:
541
+ cur.execute(sql.encode())
542
+ conn.commit()
543
+ count = cur.rowcount if cur.rowcount and cur.rowcount > 0 else 0
544
+ if count > 0:
545
+ logger.debug("Cleaned up %d expired sessions", count)
546
+ return count
547
+
548
+ async def delete_expired(self) -> int:
549
+ """Delete all expired sessions.
550
+
551
+ Returns:
552
+ Number of sessions deleted.
553
+ """
554
+ return await async_(self._delete_expired)()
@@ -1,7 +1,7 @@
1
1
  """SQLite adapter for SQLSpec."""
2
2
 
3
3
  from sqlspec.adapters.sqlite._types import SqliteConnection
4
- from sqlspec.adapters.sqlite.config import SqliteConfig, SqliteConnectionParams
4
+ from sqlspec.adapters.sqlite.config import SqliteConfig, SqliteConnectionParams, SqliteDriverFeatures
5
5
  from sqlspec.adapters.sqlite.driver import SqliteCursor, SqliteDriver, SqliteExceptionHandler, sqlite_statement_config
6
6
  from sqlspec.adapters.sqlite.pool import SqliteConnectionPool
7
7
 
@@ -12,6 +12,7 @@ __all__ = (
12
12
  "SqliteConnectionPool",
13
13
  "SqliteCursor",
14
14
  "SqliteDriver",
15
+ "SqliteDriverFeatures",
15
16
  "SqliteExceptionHandler",
16
17
  "sqlite_statement_config",
17
18
  )
@@ -0,0 +1,86 @@
1
+ """SQLite custom type handlers for optional JSON and type conversion support.
2
+
3
+ Provides registration functions for SQLite's adapter/converter system to enable
4
+ custom type handling. All handlers are optional and must be explicitly enabled
5
+ via SqliteDriverFeatures configuration.
6
+ """
7
+
8
+ import logging
9
+ import sqlite3
10
+ from typing import TYPE_CHECKING, Any
11
+
12
+ if TYPE_CHECKING:
13
+ from collections.abc import Callable
14
+
15
+ __all__ = ("json_adapter", "json_converter", "register_type_handlers", "unregister_type_handlers")
16
+
17
+ logger = logging.getLogger(__name__)
18
+
19
+ DEFAULT_JSON_TYPE = "JSON"
20
+
21
+
22
+ def json_adapter(value: Any, serializer: "Callable[[Any], str] | None" = None) -> str:
23
+ """Convert Python dict/list to JSON string for SQLite storage.
24
+
25
+ Args:
26
+ value: Python dict or list to serialize.
27
+ serializer: Optional JSON serializer callable. Defaults to standard json.dumps.
28
+
29
+ Returns:
30
+ JSON string representation.
31
+ """
32
+ if serializer is None:
33
+ import json
34
+
35
+ return json.dumps(value, ensure_ascii=False)
36
+ return serializer(value)
37
+
38
+
39
+ def json_converter(value: bytes, deserializer: "Callable[[str], Any] | None" = None) -> Any:
40
+ """Convert JSON string from SQLite to Python dict/list.
41
+
42
+ Args:
43
+ value: UTF-8 encoded JSON bytes from SQLite.
44
+ deserializer: Optional JSON deserializer callable. Defaults to standard json.loads.
45
+
46
+ Returns:
47
+ Deserialized Python object (dict or list).
48
+ """
49
+ if deserializer is None:
50
+ import json
51
+
52
+ return json.loads(value.decode("utf-8"))
53
+ return deserializer(value.decode("utf-8"))
54
+
55
+
56
+ def register_type_handlers(
57
+ json_serializer: "Callable[[Any], str] | None" = None, json_deserializer: "Callable[[str], Any] | None" = None
58
+ ) -> None:
59
+ """Register custom type adapters and converters with sqlite3 module.
60
+
61
+ This function registers handlers globally for the sqlite3 module. It should be
62
+ called once during application initialization if custom type handling is needed.
63
+
64
+ Args:
65
+ json_serializer: Optional custom JSON serializer (e.g., orjson.dumps).
66
+ json_deserializer: Optional custom JSON deserializer (e.g., orjson.loads).
67
+ """
68
+ try:
69
+ sqlite3.register_adapter(dict, lambda v: json_adapter(v, json_serializer))
70
+ sqlite3.register_adapter(list, lambda v: json_adapter(v, json_serializer))
71
+
72
+ sqlite3.register_converter(DEFAULT_JSON_TYPE, lambda v: json_converter(v, json_deserializer))
73
+
74
+ logger.debug("Registered SQLite custom type handlers (JSON dict/list adapters)")
75
+ except Exception:
76
+ logger.exception("Failed to register SQLite type handlers")
77
+ raise
78
+
79
+
80
+ def unregister_type_handlers() -> None:
81
+ """Unregister custom type handlers from sqlite3 module.
82
+
83
+ Note: sqlite3 module does not provide an official unregister API, so this
84
+ function is a no-op placeholder for API consistency with other adapters.
85
+ """
86
+ logger.debug("SQLite type handler unregistration requested (no-op - not supported by sqlite3)")
@@ -2,7 +2,7 @@ import sqlite3
2
2
  from typing import TYPE_CHECKING
3
3
 
4
4
  if TYPE_CHECKING:
5
- from typing_extensions import TypeAlias
5
+ from typing import TypeAlias
6
6
 
7
7
  SqliteConnection: TypeAlias = sqlite3.Connection
8
8
  else:
@@ -0,0 +1,5 @@
1
+ """SQLite ADK integration for Google Agent Development Kit."""
2
+
3
+ from sqlspec.adapters.sqlite.adk.store import SqliteADKStore
4
+
5
+ __all__ = ("SqliteADKStore",)