sqlspec 0.25.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 (199) hide show
  1. sqlspec/__init__.py +7 -15
  2. sqlspec/_serialization.py +256 -24
  3. sqlspec/_typing.py +71 -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 +69 -12
  8. sqlspec/adapters/adbc/data_dictionary.py +340 -0
  9. sqlspec/adapters/adbc/driver.py +266 -58
  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 +153 -0
  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 +88 -15
  17. sqlspec/adapters/aiosqlite/data_dictionary.py +149 -0
  18. sqlspec/adapters/aiosqlite/driver.py +143 -40
  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 +2 -2
  24. sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
  25. sqlspec/adapters/asyncmy/adk/store.py +493 -0
  26. sqlspec/adapters/asyncmy/config.py +68 -23
  27. sqlspec/adapters/asyncmy/data_dictionary.py +161 -0
  28. sqlspec/adapters/asyncmy/driver.py +313 -58
  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 +59 -35
  37. sqlspec/adapters/asyncpg/data_dictionary.py +173 -0
  38. sqlspec/adapters/asyncpg/driver.py +170 -25
  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 +27 -10
  45. sqlspec/adapters/bigquery/data_dictionary.py +149 -0
  46. sqlspec/adapters/bigquery/driver.py +368 -142
  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 +125 -0
  50. sqlspec/adapters/duckdb/_types.py +1 -1
  51. sqlspec/adapters/duckdb/adk/__init__.py +14 -0
  52. sqlspec/adapters/duckdb/adk/store.py +553 -0
  53. sqlspec/adapters/duckdb/config.py +80 -20
  54. sqlspec/adapters/duckdb/data_dictionary.py +163 -0
  55. sqlspec/adapters/duckdb/driver.py +167 -45
  56. sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
  57. sqlspec/adapters/duckdb/litestar/store.py +332 -0
  58. sqlspec/adapters/duckdb/pool.py +4 -4
  59. sqlspec/adapters/duckdb/type_converter.py +133 -0
  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 +122 -32
  65. sqlspec/adapters/oracledb/data_dictionary.py +509 -0
  66. sqlspec/adapters/oracledb/driver.py +353 -91
  67. sqlspec/adapters/oracledb/litestar/__init__.py +5 -0
  68. sqlspec/adapters/oracledb/litestar/store.py +767 -0
  69. sqlspec/adapters/oracledb/migrations.py +348 -73
  70. sqlspec/adapters/oracledb/type_converter.py +207 -0
  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 +46 -17
  76. sqlspec/adapters/psqlpy/data_dictionary.py +172 -0
  77. sqlspec/adapters/psqlpy/driver.py +123 -209
  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 +102 -0
  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 +69 -35
  86. sqlspec/adapters/psycopg/data_dictionary.py +331 -0
  87. sqlspec/adapters/psycopg/driver.py +238 -81
  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 +87 -15
  96. sqlspec/adapters/sqlite/data_dictionary.py +149 -0
  97. sqlspec/adapters/sqlite/driver.py +137 -54
  98. sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
  99. sqlspec/adapters/sqlite/litestar/store.py +318 -0
  100. sqlspec/adapters/sqlite/pool.py +18 -9
  101. sqlspec/base.py +45 -26
  102. sqlspec/builder/__init__.py +73 -4
  103. sqlspec/builder/_base.py +162 -89
  104. sqlspec/builder/_column.py +62 -29
  105. sqlspec/builder/_ddl.py +180 -121
  106. sqlspec/builder/_delete.py +5 -4
  107. sqlspec/builder/_dml.py +388 -0
  108. sqlspec/{_sql.py → builder/_factory.py} +53 -94
  109. sqlspec/builder/_insert.py +32 -131
  110. sqlspec/builder/_join.py +375 -0
  111. sqlspec/builder/_merge.py +446 -11
  112. sqlspec/builder/_parsing_utils.py +111 -17
  113. sqlspec/builder/_select.py +1457 -24
  114. sqlspec/builder/_update.py +11 -42
  115. sqlspec/cli.py +307 -194
  116. sqlspec/config.py +252 -67
  117. sqlspec/core/__init__.py +5 -4
  118. sqlspec/core/cache.py +17 -17
  119. sqlspec/core/compiler.py +62 -9
  120. sqlspec/core/filters.py +37 -37
  121. sqlspec/core/hashing.py +9 -9
  122. sqlspec/core/parameters.py +83 -48
  123. sqlspec/core/result.py +102 -46
  124. sqlspec/core/splitter.py +16 -17
  125. sqlspec/core/statement.py +36 -30
  126. sqlspec/core/type_conversion.py +235 -0
  127. sqlspec/driver/__init__.py +7 -6
  128. sqlspec/driver/_async.py +188 -151
  129. sqlspec/driver/_common.py +285 -80
  130. sqlspec/driver/_sync.py +188 -152
  131. sqlspec/driver/mixins/_result_tools.py +20 -236
  132. sqlspec/driver/mixins/_sql_translator.py +4 -4
  133. sqlspec/exceptions.py +75 -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/__init__.py +4 -3
  153. sqlspec/migrations/base.py +302 -39
  154. sqlspec/migrations/commands.py +611 -144
  155. sqlspec/migrations/context.py +142 -0
  156. sqlspec/migrations/fix.py +199 -0
  157. sqlspec/migrations/loaders.py +68 -23
  158. sqlspec/migrations/runner.py +543 -107
  159. sqlspec/migrations/tracker.py +237 -21
  160. sqlspec/migrations/utils.py +51 -3
  161. sqlspec/migrations/validation.py +177 -0
  162. sqlspec/protocols.py +66 -36
  163. sqlspec/storage/_utils.py +98 -0
  164. sqlspec/storage/backends/fsspec.py +134 -106
  165. sqlspec/storage/backends/local.py +78 -51
  166. sqlspec/storage/backends/obstore.py +278 -162
  167. sqlspec/storage/registry.py +75 -39
  168. sqlspec/typing.py +16 -84
  169. sqlspec/utils/config_resolver.py +153 -0
  170. sqlspec/utils/correlation.py +4 -5
  171. sqlspec/utils/data_transformation.py +3 -2
  172. sqlspec/utils/deprecation.py +9 -8
  173. sqlspec/utils/fixtures.py +4 -4
  174. sqlspec/utils/logging.py +46 -6
  175. sqlspec/utils/module_loader.py +2 -2
  176. sqlspec/utils/schema.py +288 -0
  177. sqlspec/utils/serializers.py +50 -2
  178. sqlspec/utils/sync_tools.py +21 -17
  179. sqlspec/utils/text.py +1 -2
  180. sqlspec/utils/type_guards.py +111 -20
  181. sqlspec/utils/version.py +433 -0
  182. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/METADATA +40 -21
  183. sqlspec-0.27.0.dist-info/RECORD +207 -0
  184. sqlspec/builder/mixins/__init__.py +0 -55
  185. sqlspec/builder/mixins/_cte_and_set_ops.py +0 -254
  186. sqlspec/builder/mixins/_delete_operations.py +0 -50
  187. sqlspec/builder/mixins/_insert_operations.py +0 -282
  188. sqlspec/builder/mixins/_join_operations.py +0 -389
  189. sqlspec/builder/mixins/_merge_operations.py +0 -592
  190. sqlspec/builder/mixins/_order_limit_operations.py +0 -152
  191. sqlspec/builder/mixins/_pivot_operations.py +0 -157
  192. sqlspec/builder/mixins/_select_operations.py +0 -936
  193. sqlspec/builder/mixins/_update_operations.py +0 -218
  194. sqlspec/builder/mixins/_where_clause.py +0 -1304
  195. sqlspec-0.25.0.dist-info/RECORD +0 -139
  196. sqlspec-0.25.0.dist-info/licenses/NOTICE +0 -29
  197. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/WHEEL +0 -0
  198. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/entry_points.txt +0 -0
  199. {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,527 @@
1
+ """Aiosqlite async ADK store for Google Agent Development Kit session/event storage."""
2
+
3
+ from datetime import datetime, timezone
4
+ from typing import TYPE_CHECKING, Any
5
+
6
+ from sqlspec.extensions.adk import BaseAsyncADKStore, EventRecord, SessionRecord
7
+ from sqlspec.utils.logging import get_logger
8
+ from sqlspec.utils.serializers import from_json, to_json
9
+
10
+ if TYPE_CHECKING:
11
+ from sqlspec.adapters.aiosqlite.config import AiosqliteConfig
12
+
13
+ logger = get_logger("adapters.aiosqlite.adk.store")
14
+
15
+ SECONDS_PER_DAY = 86400.0
16
+ JULIAN_EPOCH = 2440587.5
17
+
18
+ __all__ = ("AiosqliteADKStore",)
19
+
20
+
21
+ def _datetime_to_julian(dt: datetime) -> float:
22
+ """Convert datetime to Julian Day number for SQLite storage.
23
+
24
+ Args:
25
+ dt: Datetime to convert (must be UTC-aware).
26
+
27
+ Returns:
28
+ Julian Day number as REAL.
29
+
30
+ Notes:
31
+ Julian Day number is days since November 24, 4714 BCE (proleptic Gregorian).
32
+ This enables direct comparison with julianday('now') in SQL queries.
33
+ """
34
+ if dt.tzinfo is None:
35
+ dt = dt.replace(tzinfo=timezone.utc)
36
+ epoch = datetime(1970, 1, 1, tzinfo=timezone.utc)
37
+ delta_days = (dt - epoch).total_seconds() / SECONDS_PER_DAY
38
+ return JULIAN_EPOCH + delta_days
39
+
40
+
41
+ def _julian_to_datetime(julian: float) -> datetime:
42
+ """Convert Julian Day number back to datetime.
43
+
44
+ Args:
45
+ julian: Julian Day number.
46
+
47
+ Returns:
48
+ UTC-aware datetime.
49
+ """
50
+ days_since_epoch = julian - JULIAN_EPOCH
51
+ timestamp = days_since_epoch * SECONDS_PER_DAY
52
+ return datetime.fromtimestamp(timestamp, tz=timezone.utc)
53
+
54
+
55
+ def _to_sqlite_bool(value: "bool | None") -> "int | None":
56
+ """Convert Python bool to SQLite INTEGER.
57
+
58
+ Args:
59
+ value: Boolean value or None.
60
+
61
+ Returns:
62
+ 1 for True, 0 for False, None for None.
63
+ """
64
+ if value is None:
65
+ return None
66
+ return 1 if value else 0
67
+
68
+
69
+ def _from_sqlite_bool(value: "int | None") -> "bool | None":
70
+ """Convert SQLite INTEGER to Python bool.
71
+
72
+ Args:
73
+ value: Integer value (0/1) or None.
74
+
75
+ Returns:
76
+ True for 1, False for 0, None for None.
77
+ """
78
+ if value is None:
79
+ return None
80
+ return bool(value)
81
+
82
+
83
+ class AiosqliteADKStore(BaseAsyncADKStore["AiosqliteConfig"]):
84
+ """Aiosqlite ADK store using asynchronous SQLite driver.
85
+
86
+ Implements session and event storage for Google Agent Development Kit
87
+ using SQLite via the asynchronous aiosqlite driver.
88
+
89
+ Provides:
90
+ - Session state management with JSON storage (as TEXT)
91
+ - Event history tracking with BLOB-serialized actions
92
+ - Julian Day timestamps (REAL) for efficient date operations
93
+ - Foreign key constraints with cascade delete
94
+ - Efficient upserts using INSERT OR REPLACE
95
+
96
+ Args:
97
+ config: AiosqliteConfig with extension_config["adk"] settings.
98
+
99
+ Example:
100
+ from sqlspec.adapters.aiosqlite import AiosqliteConfig
101
+ from sqlspec.adapters.aiosqlite.adk import AiosqliteADKStore
102
+
103
+ config = AiosqliteConfig(
104
+ pool_config={"database": ":memory:"},
105
+ extension_config={
106
+ "adk": {
107
+ "session_table": "my_sessions",
108
+ "events_table": "my_events"
109
+ }
110
+ }
111
+ )
112
+ store = AiosqliteADKStore(config)
113
+ await store.create_tables()
114
+
115
+ Notes:
116
+ - JSON stored as TEXT with SQLSpec serializers (msgspec/orjson/stdlib)
117
+ - BOOLEAN as INTEGER (0/1, with None for NULL)
118
+ - Timestamps as REAL (Julian day: julianday('now'))
119
+ - BLOB for pre-serialized actions from Google ADK
120
+ - PRAGMA foreign_keys = ON (enable per connection)
121
+ - Configuration is read from config.extension_config["adk"]
122
+ """
123
+
124
+ __slots__ = ()
125
+
126
+ def __init__(self, config: "AiosqliteConfig") -> None:
127
+ """Initialize Aiosqlite ADK store.
128
+
129
+ Args:
130
+ config: AiosqliteConfig instance.
131
+
132
+ Notes:
133
+ Configuration is read from config.extension_config["adk"]:
134
+ - session_table: Sessions table name (default: "adk_sessions")
135
+ - events_table: Events table name (default: "adk_events")
136
+ """
137
+ super().__init__(config)
138
+
139
+ def _get_create_sessions_table_sql(self) -> str:
140
+ """Get SQLite CREATE TABLE SQL for sessions.
141
+
142
+ Returns:
143
+ SQL statement to create adk_sessions table with indexes.
144
+
145
+ Notes:
146
+ - TEXT for IDs, names, and JSON state
147
+ - REAL for Julian Day timestamps
148
+ - Composite index on (app_name, user_id)
149
+ - Index on update_time DESC for recent session queries
150
+ """
151
+ return f"""
152
+ CREATE TABLE IF NOT EXISTS {self._session_table} (
153
+ id TEXT PRIMARY KEY,
154
+ app_name TEXT NOT NULL,
155
+ user_id TEXT NOT NULL,
156
+ state TEXT NOT NULL DEFAULT '{{}}',
157
+ create_time REAL NOT NULL,
158
+ update_time REAL NOT NULL
159
+ );
160
+ CREATE INDEX IF NOT EXISTS idx_{self._session_table}_app_user
161
+ ON {self._session_table}(app_name, user_id);
162
+ CREATE INDEX IF NOT EXISTS idx_{self._session_table}_update_time
163
+ ON {self._session_table}(update_time DESC);
164
+ """
165
+
166
+ def _get_create_events_table_sql(self) -> str:
167
+ """Get SQLite CREATE TABLE SQL for events.
168
+
169
+ Returns:
170
+ SQL statement to create adk_events table with indexes.
171
+
172
+ Notes:
173
+ - TEXT for IDs, strings, and JSON content
174
+ - BLOB for pickled actions
175
+ - INTEGER for booleans (0/1/NULL)
176
+ - REAL for Julian Day timestamps
177
+ - Foreign key to sessions with CASCADE delete
178
+ - Index on (session_id, timestamp ASC)
179
+ """
180
+ return f"""
181
+ CREATE TABLE IF NOT EXISTS {self._events_table} (
182
+ id TEXT PRIMARY KEY,
183
+ session_id TEXT NOT NULL,
184
+ app_name TEXT NOT NULL,
185
+ user_id TEXT NOT NULL,
186
+ invocation_id TEXT NOT NULL,
187
+ author TEXT NOT NULL,
188
+ actions BLOB NOT NULL,
189
+ long_running_tool_ids_json TEXT,
190
+ branch TEXT,
191
+ timestamp REAL NOT NULL,
192
+ content TEXT,
193
+ grounding_metadata TEXT,
194
+ custom_metadata TEXT,
195
+ partial INTEGER,
196
+ turn_complete INTEGER,
197
+ interrupted INTEGER,
198
+ error_code TEXT,
199
+ error_message TEXT,
200
+ FOREIGN KEY (session_id) REFERENCES {self._session_table}(id) ON DELETE CASCADE
201
+ );
202
+ CREATE INDEX IF NOT EXISTS idx_{self._events_table}_session
203
+ ON {self._events_table}(session_id, timestamp ASC);
204
+ """
205
+
206
+ def _get_drop_tables_sql(self) -> "list[str]":
207
+ """Get SQLite DROP TABLE SQL statements.
208
+
209
+ Returns:
210
+ List of SQL statements to drop tables and indexes.
211
+
212
+ Notes:
213
+ Order matters: drop events table (child) before sessions (parent).
214
+ SQLite automatically drops indexes when dropping tables.
215
+ """
216
+ return [f"DROP TABLE IF EXISTS {self._events_table}", f"DROP TABLE IF EXISTS {self._session_table}"]
217
+
218
+ async def _enable_foreign_keys(self, connection: Any) -> None:
219
+ """Enable foreign key constraints for this connection.
220
+
221
+ Args:
222
+ connection: Aiosqlite connection.
223
+
224
+ Notes:
225
+ SQLite requires PRAGMA foreign_keys = ON per connection.
226
+ """
227
+ await connection.execute("PRAGMA foreign_keys = ON")
228
+
229
+ async def create_tables(self) -> None:
230
+ """Create both sessions and events tables if they don't exist."""
231
+ async with self._config.provide_connection() as conn:
232
+ await self._enable_foreign_keys(conn)
233
+ await conn.executescript(self._get_create_sessions_table_sql())
234
+ await conn.executescript(self._get_create_events_table_sql())
235
+ await conn.commit()
236
+ logger.debug("Created ADK tables: %s, %s", self._session_table, self._events_table)
237
+
238
+ async def create_session(
239
+ self, session_id: str, app_name: str, user_id: str, state: "dict[str, Any]", owner_id: "Any | None" = None
240
+ ) -> SessionRecord:
241
+ """Create a new session.
242
+
243
+ Args:
244
+ session_id: Unique session identifier.
245
+ app_name: Application name.
246
+ user_id: User identifier.
247
+ state: Initial session state.
248
+ owner_id: Optional owner ID value for owner_id_column.
249
+
250
+ Returns:
251
+ Created session record.
252
+
253
+ Notes:
254
+ Uses Julian Day for create_time and update_time.
255
+ State is JSON-serialized before insertion.
256
+ """
257
+ now = datetime.now(timezone.utc)
258
+ now_julian = _datetime_to_julian(now)
259
+ state_json = to_json(state) if state else None
260
+
261
+ params: tuple[Any, ...]
262
+ if self._owner_id_column_name:
263
+ sql = f"""
264
+ INSERT INTO {self._session_table}
265
+ (id, app_name, user_id, {self._owner_id_column_name}, state, create_time, update_time)
266
+ VALUES (?, ?, ?, ?, ?, ?, ?)
267
+ """
268
+ params = (session_id, app_name, user_id, owner_id, state_json, now_julian, now_julian)
269
+ else:
270
+ sql = f"""
271
+ INSERT INTO {self._session_table} (id, app_name, user_id, state, create_time, update_time)
272
+ VALUES (?, ?, ?, ?, ?, ?)
273
+ """
274
+ params = (session_id, app_name, user_id, state_json, now_julian, now_julian)
275
+
276
+ async with self._config.provide_connection() as conn:
277
+ await self._enable_foreign_keys(conn)
278
+ await conn.execute(sql, params)
279
+ await conn.commit()
280
+
281
+ return SessionRecord(
282
+ id=session_id, app_name=app_name, user_id=user_id, state=state, create_time=now, update_time=now
283
+ )
284
+
285
+ async def get_session(self, session_id: str) -> "SessionRecord | None":
286
+ """Get session by ID.
287
+
288
+ Args:
289
+ session_id: Session identifier.
290
+
291
+ Returns:
292
+ Session record or None if not found.
293
+
294
+ Notes:
295
+ SQLite returns Julian Day (REAL) for timestamps.
296
+ JSON is parsed from TEXT storage.
297
+ """
298
+ sql = f"""
299
+ SELECT id, app_name, user_id, state, create_time, update_time
300
+ FROM {self._session_table}
301
+ WHERE id = ?
302
+ """
303
+
304
+ async with self._config.provide_connection() as conn:
305
+ await self._enable_foreign_keys(conn)
306
+ cursor = await conn.execute(sql, (session_id,))
307
+ row = await cursor.fetchone()
308
+
309
+ if row is None:
310
+ return None
311
+
312
+ return SessionRecord(
313
+ id=row[0],
314
+ app_name=row[1],
315
+ user_id=row[2],
316
+ state=from_json(row[3]) if row[3] else {},
317
+ create_time=_julian_to_datetime(row[4]),
318
+ update_time=_julian_to_datetime(row[5]),
319
+ )
320
+
321
+ async def update_session_state(self, session_id: str, state: "dict[str, Any]") -> None:
322
+ """Update session state.
323
+
324
+ Args:
325
+ session_id: Session identifier.
326
+ state: New state dictionary (replaces existing state).
327
+
328
+ Notes:
329
+ This replaces the entire state dictionary.
330
+ Updates update_time to current Julian Day.
331
+ """
332
+ now_julian = _datetime_to_julian(datetime.now(timezone.utc))
333
+ state_json = to_json(state) if state else None
334
+
335
+ sql = f"""
336
+ UPDATE {self._session_table}
337
+ SET state = ?, update_time = ?
338
+ WHERE id = ?
339
+ """
340
+
341
+ async with self._config.provide_connection() as conn:
342
+ await self._enable_foreign_keys(conn)
343
+ await conn.execute(sql, (state_json, now_julian, session_id))
344
+ await conn.commit()
345
+
346
+ async def list_sessions(self, app_name: str, user_id: str) -> "list[SessionRecord]":
347
+ """List all sessions for a user in an app.
348
+
349
+ Args:
350
+ app_name: Application name.
351
+ user_id: User identifier.
352
+
353
+ Returns:
354
+ List of session records ordered by update_time DESC.
355
+
356
+ Notes:
357
+ Uses composite index on (app_name, user_id).
358
+ """
359
+ sql = f"""
360
+ SELECT id, app_name, user_id, state, create_time, update_time
361
+ FROM {self._session_table}
362
+ WHERE app_name = ? AND user_id = ?
363
+ ORDER BY update_time DESC
364
+ """
365
+
366
+ async with self._config.provide_connection() as conn:
367
+ await self._enable_foreign_keys(conn)
368
+ cursor = await conn.execute(sql, (app_name, user_id))
369
+ rows = await cursor.fetchall()
370
+
371
+ return [
372
+ SessionRecord(
373
+ id=row[0],
374
+ app_name=row[1],
375
+ user_id=row[2],
376
+ state=from_json(row[3]) if row[3] else {},
377
+ create_time=_julian_to_datetime(row[4]),
378
+ update_time=_julian_to_datetime(row[5]),
379
+ )
380
+ for row in rows
381
+ ]
382
+
383
+ async def delete_session(self, session_id: str) -> None:
384
+ """Delete session and all associated events (cascade).
385
+
386
+ Args:
387
+ session_id: Session identifier.
388
+
389
+ Notes:
390
+ Foreign key constraint ensures events are cascade-deleted.
391
+ """
392
+ sql = f"DELETE FROM {self._session_table} WHERE id = ?"
393
+
394
+ async with self._config.provide_connection() as conn:
395
+ await self._enable_foreign_keys(conn)
396
+ await conn.execute(sql, (session_id,))
397
+ await conn.commit()
398
+
399
+ async def append_event(self, event_record: EventRecord) -> None:
400
+ """Append an event to a session.
401
+
402
+ Args:
403
+ event_record: Event record to store.
404
+
405
+ Notes:
406
+ Uses Julian Day for timestamp.
407
+ JSON fields are serialized to TEXT.
408
+ Boolean fields converted to INTEGER (0/1/NULL).
409
+ """
410
+ timestamp_julian = _datetime_to_julian(event_record["timestamp"])
411
+
412
+ content_json = to_json(event_record.get("content")) if event_record.get("content") else None
413
+ grounding_metadata_json = (
414
+ to_json(event_record.get("grounding_metadata")) if event_record.get("grounding_metadata") else None
415
+ )
416
+ custom_metadata_json = (
417
+ to_json(event_record.get("custom_metadata")) if event_record.get("custom_metadata") else None
418
+ )
419
+
420
+ partial_int = _to_sqlite_bool(event_record.get("partial"))
421
+ turn_complete_int = _to_sqlite_bool(event_record.get("turn_complete"))
422
+ interrupted_int = _to_sqlite_bool(event_record.get("interrupted"))
423
+
424
+ sql = f"""
425
+ INSERT INTO {self._events_table} (
426
+ id, session_id, app_name, user_id, invocation_id, author, actions,
427
+ long_running_tool_ids_json, branch, timestamp, content,
428
+ grounding_metadata, custom_metadata, partial, turn_complete,
429
+ interrupted, error_code, error_message
430
+ ) VALUES (
431
+ ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?
432
+ )
433
+ """
434
+
435
+ async with self._config.provide_connection() as conn:
436
+ await self._enable_foreign_keys(conn)
437
+ await conn.execute(
438
+ sql,
439
+ (
440
+ event_record["id"],
441
+ event_record["session_id"],
442
+ event_record["app_name"],
443
+ event_record["user_id"],
444
+ event_record["invocation_id"],
445
+ event_record["author"],
446
+ event_record["actions"],
447
+ event_record.get("long_running_tool_ids_json"),
448
+ event_record.get("branch"),
449
+ timestamp_julian,
450
+ content_json,
451
+ grounding_metadata_json,
452
+ custom_metadata_json,
453
+ partial_int,
454
+ turn_complete_int,
455
+ interrupted_int,
456
+ event_record.get("error_code"),
457
+ event_record.get("error_message"),
458
+ ),
459
+ )
460
+ await conn.commit()
461
+
462
+ async def get_events(
463
+ self, session_id: str, after_timestamp: "datetime | None" = None, limit: "int | None" = None
464
+ ) -> "list[EventRecord]":
465
+ """Get events for a session.
466
+
467
+ Args:
468
+ session_id: Session identifier.
469
+ after_timestamp: Only return events after this time.
470
+ limit: Maximum number of events to return.
471
+
472
+ Returns:
473
+ List of event records ordered by timestamp ASC.
474
+
475
+ Notes:
476
+ Uses index on (session_id, timestamp ASC).
477
+ Parses JSON fields and converts BLOB actions to bytes.
478
+ Converts INTEGER booleans back to bool/None.
479
+ """
480
+ where_clauses = ["session_id = ?"]
481
+ params: list[Any] = [session_id]
482
+
483
+ if after_timestamp is not None:
484
+ where_clauses.append("timestamp > ?")
485
+ params.append(_datetime_to_julian(after_timestamp))
486
+
487
+ where_clause = " AND ".join(where_clauses)
488
+ limit_clause = f" LIMIT {limit}" if limit else ""
489
+
490
+ sql = f"""
491
+ SELECT id, session_id, app_name, user_id, invocation_id, author, actions,
492
+ long_running_tool_ids_json, branch, timestamp, content,
493
+ grounding_metadata, custom_metadata, partial, turn_complete,
494
+ interrupted, error_code, error_message
495
+ FROM {self._events_table}
496
+ WHERE {where_clause}
497
+ ORDER BY timestamp ASC{limit_clause}
498
+ """
499
+
500
+ async with self._config.provide_connection() as conn:
501
+ await self._enable_foreign_keys(conn)
502
+ cursor = await conn.execute(sql, params)
503
+ rows = await cursor.fetchall()
504
+
505
+ return [
506
+ EventRecord(
507
+ id=row[0],
508
+ session_id=row[1],
509
+ app_name=row[2],
510
+ user_id=row[3],
511
+ invocation_id=row[4],
512
+ author=row[5],
513
+ actions=bytes(row[6]),
514
+ long_running_tool_ids_json=row[7],
515
+ branch=row[8],
516
+ timestamp=_julian_to_datetime(row[9]),
517
+ content=from_json(row[10]) if row[10] else None,
518
+ grounding_metadata=from_json(row[11]) if row[11] else None,
519
+ custom_metadata=from_json(row[12]) if row[12] else None,
520
+ partial=_from_sqlite_bool(row[13]),
521
+ turn_complete=_from_sqlite_bool(row[14]),
522
+ interrupted=_from_sqlite_bool(row[15]),
523
+ error_code=row[16],
524
+ error_message=row[17],
525
+ )
526
+ for row in rows
527
+ ]