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.
- sqlspec/__init__.py +7 -15
- sqlspec/_serialization.py +256 -24
- sqlspec/_typing.py +71 -52
- sqlspec/adapters/adbc/_types.py +1 -1
- sqlspec/adapters/adbc/adk/__init__.py +5 -0
- sqlspec/adapters/adbc/adk/store.py +870 -0
- sqlspec/adapters/adbc/config.py +69 -12
- sqlspec/adapters/adbc/data_dictionary.py +340 -0
- sqlspec/adapters/adbc/driver.py +266 -58
- sqlspec/adapters/adbc/litestar/__init__.py +5 -0
- sqlspec/adapters/adbc/litestar/store.py +504 -0
- sqlspec/adapters/adbc/type_converter.py +153 -0
- sqlspec/adapters/aiosqlite/_types.py +1 -1
- sqlspec/adapters/aiosqlite/adk/__init__.py +5 -0
- sqlspec/adapters/aiosqlite/adk/store.py +527 -0
- sqlspec/adapters/aiosqlite/config.py +88 -15
- sqlspec/adapters/aiosqlite/data_dictionary.py +149 -0
- sqlspec/adapters/aiosqlite/driver.py +143 -40
- sqlspec/adapters/aiosqlite/litestar/__init__.py +5 -0
- sqlspec/adapters/aiosqlite/litestar/store.py +281 -0
- sqlspec/adapters/aiosqlite/pool.py +7 -7
- sqlspec/adapters/asyncmy/__init__.py +7 -1
- sqlspec/adapters/asyncmy/_types.py +2 -2
- sqlspec/adapters/asyncmy/adk/__init__.py +5 -0
- sqlspec/adapters/asyncmy/adk/store.py +493 -0
- sqlspec/adapters/asyncmy/config.py +68 -23
- sqlspec/adapters/asyncmy/data_dictionary.py +161 -0
- sqlspec/adapters/asyncmy/driver.py +313 -58
- sqlspec/adapters/asyncmy/litestar/__init__.py +5 -0
- sqlspec/adapters/asyncmy/litestar/store.py +296 -0
- sqlspec/adapters/asyncpg/__init__.py +2 -1
- sqlspec/adapters/asyncpg/_type_handlers.py +71 -0
- sqlspec/adapters/asyncpg/_types.py +11 -7
- sqlspec/adapters/asyncpg/adk/__init__.py +5 -0
- sqlspec/adapters/asyncpg/adk/store.py +450 -0
- sqlspec/adapters/asyncpg/config.py +59 -35
- sqlspec/adapters/asyncpg/data_dictionary.py +173 -0
- sqlspec/adapters/asyncpg/driver.py +170 -25
- sqlspec/adapters/asyncpg/litestar/__init__.py +5 -0
- sqlspec/adapters/asyncpg/litestar/store.py +253 -0
- sqlspec/adapters/bigquery/_types.py +1 -1
- sqlspec/adapters/bigquery/adk/__init__.py +5 -0
- sqlspec/adapters/bigquery/adk/store.py +576 -0
- sqlspec/adapters/bigquery/config.py +27 -10
- sqlspec/adapters/bigquery/data_dictionary.py +149 -0
- sqlspec/adapters/bigquery/driver.py +368 -142
- sqlspec/adapters/bigquery/litestar/__init__.py +5 -0
- sqlspec/adapters/bigquery/litestar/store.py +327 -0
- sqlspec/adapters/bigquery/type_converter.py +125 -0
- sqlspec/adapters/duckdb/_types.py +1 -1
- sqlspec/adapters/duckdb/adk/__init__.py +14 -0
- sqlspec/adapters/duckdb/adk/store.py +553 -0
- sqlspec/adapters/duckdb/config.py +80 -20
- sqlspec/adapters/duckdb/data_dictionary.py +163 -0
- sqlspec/adapters/duckdb/driver.py +167 -45
- sqlspec/adapters/duckdb/litestar/__init__.py +5 -0
- sqlspec/adapters/duckdb/litestar/store.py +332 -0
- sqlspec/adapters/duckdb/pool.py +4 -4
- sqlspec/adapters/duckdb/type_converter.py +133 -0
- sqlspec/adapters/oracledb/_numpy_handlers.py +133 -0
- sqlspec/adapters/oracledb/_types.py +20 -2
- sqlspec/adapters/oracledb/adk/__init__.py +5 -0
- sqlspec/adapters/oracledb/adk/store.py +1745 -0
- sqlspec/adapters/oracledb/config.py +122 -32
- sqlspec/adapters/oracledb/data_dictionary.py +509 -0
- sqlspec/adapters/oracledb/driver.py +353 -91
- sqlspec/adapters/oracledb/litestar/__init__.py +5 -0
- sqlspec/adapters/oracledb/litestar/store.py +767 -0
- sqlspec/adapters/oracledb/migrations.py +348 -73
- sqlspec/adapters/oracledb/type_converter.py +207 -0
- sqlspec/adapters/psqlpy/_type_handlers.py +44 -0
- sqlspec/adapters/psqlpy/_types.py +2 -1
- sqlspec/adapters/psqlpy/adk/__init__.py +5 -0
- sqlspec/adapters/psqlpy/adk/store.py +482 -0
- sqlspec/adapters/psqlpy/config.py +46 -17
- sqlspec/adapters/psqlpy/data_dictionary.py +172 -0
- sqlspec/adapters/psqlpy/driver.py +123 -209
- sqlspec/adapters/psqlpy/litestar/__init__.py +5 -0
- sqlspec/adapters/psqlpy/litestar/store.py +272 -0
- sqlspec/adapters/psqlpy/type_converter.py +102 -0
- sqlspec/adapters/psycopg/_type_handlers.py +80 -0
- sqlspec/adapters/psycopg/_types.py +2 -1
- sqlspec/adapters/psycopg/adk/__init__.py +5 -0
- sqlspec/adapters/psycopg/adk/store.py +944 -0
- sqlspec/adapters/psycopg/config.py +69 -35
- sqlspec/adapters/psycopg/data_dictionary.py +331 -0
- sqlspec/adapters/psycopg/driver.py +238 -81
- sqlspec/adapters/psycopg/litestar/__init__.py +5 -0
- sqlspec/adapters/psycopg/litestar/store.py +554 -0
- sqlspec/adapters/sqlite/__init__.py +2 -1
- sqlspec/adapters/sqlite/_type_handlers.py +86 -0
- sqlspec/adapters/sqlite/_types.py +1 -1
- sqlspec/adapters/sqlite/adk/__init__.py +5 -0
- sqlspec/adapters/sqlite/adk/store.py +572 -0
- sqlspec/adapters/sqlite/config.py +87 -15
- sqlspec/adapters/sqlite/data_dictionary.py +149 -0
- sqlspec/adapters/sqlite/driver.py +137 -54
- sqlspec/adapters/sqlite/litestar/__init__.py +5 -0
- sqlspec/adapters/sqlite/litestar/store.py +318 -0
- sqlspec/adapters/sqlite/pool.py +18 -9
- sqlspec/base.py +45 -26
- sqlspec/builder/__init__.py +73 -4
- sqlspec/builder/_base.py +162 -89
- sqlspec/builder/_column.py +62 -29
- sqlspec/builder/_ddl.py +180 -121
- sqlspec/builder/_delete.py +5 -4
- sqlspec/builder/_dml.py +388 -0
- sqlspec/{_sql.py → builder/_factory.py} +53 -94
- sqlspec/builder/_insert.py +32 -131
- sqlspec/builder/_join.py +375 -0
- sqlspec/builder/_merge.py +446 -11
- sqlspec/builder/_parsing_utils.py +111 -17
- sqlspec/builder/_select.py +1457 -24
- sqlspec/builder/_update.py +11 -42
- sqlspec/cli.py +307 -194
- sqlspec/config.py +252 -67
- sqlspec/core/__init__.py +5 -4
- sqlspec/core/cache.py +17 -17
- sqlspec/core/compiler.py +62 -9
- sqlspec/core/filters.py +37 -37
- sqlspec/core/hashing.py +9 -9
- sqlspec/core/parameters.py +83 -48
- sqlspec/core/result.py +102 -46
- sqlspec/core/splitter.py +16 -17
- sqlspec/core/statement.py +36 -30
- sqlspec/core/type_conversion.py +235 -0
- sqlspec/driver/__init__.py +7 -6
- sqlspec/driver/_async.py +188 -151
- sqlspec/driver/_common.py +285 -80
- sqlspec/driver/_sync.py +188 -152
- sqlspec/driver/mixins/_result_tools.py +20 -236
- sqlspec/driver/mixins/_sql_translator.py +4 -4
- sqlspec/exceptions.py +75 -7
- sqlspec/extensions/adk/__init__.py +53 -0
- sqlspec/extensions/adk/_types.py +51 -0
- sqlspec/extensions/adk/converters.py +172 -0
- sqlspec/extensions/adk/migrations/0001_create_adk_tables.py +144 -0
- sqlspec/extensions/adk/migrations/__init__.py +0 -0
- sqlspec/extensions/adk/service.py +181 -0
- sqlspec/extensions/adk/store.py +536 -0
- sqlspec/extensions/aiosql/adapter.py +73 -53
- sqlspec/extensions/litestar/__init__.py +21 -4
- sqlspec/extensions/litestar/cli.py +54 -10
- sqlspec/extensions/litestar/config.py +59 -266
- sqlspec/extensions/litestar/handlers.py +46 -17
- sqlspec/extensions/litestar/migrations/0001_create_session_table.py +137 -0
- sqlspec/extensions/litestar/migrations/__init__.py +3 -0
- sqlspec/extensions/litestar/plugin.py +324 -223
- sqlspec/extensions/litestar/providers.py +25 -25
- sqlspec/extensions/litestar/store.py +265 -0
- sqlspec/loader.py +30 -49
- sqlspec/migrations/__init__.py +4 -3
- sqlspec/migrations/base.py +302 -39
- sqlspec/migrations/commands.py +611 -144
- sqlspec/migrations/context.py +142 -0
- sqlspec/migrations/fix.py +199 -0
- sqlspec/migrations/loaders.py +68 -23
- sqlspec/migrations/runner.py +543 -107
- sqlspec/migrations/tracker.py +237 -21
- sqlspec/migrations/utils.py +51 -3
- sqlspec/migrations/validation.py +177 -0
- sqlspec/protocols.py +66 -36
- sqlspec/storage/_utils.py +98 -0
- sqlspec/storage/backends/fsspec.py +134 -106
- sqlspec/storage/backends/local.py +78 -51
- sqlspec/storage/backends/obstore.py +278 -162
- sqlspec/storage/registry.py +75 -39
- sqlspec/typing.py +16 -84
- sqlspec/utils/config_resolver.py +153 -0
- sqlspec/utils/correlation.py +4 -5
- sqlspec/utils/data_transformation.py +3 -2
- sqlspec/utils/deprecation.py +9 -8
- sqlspec/utils/fixtures.py +4 -4
- sqlspec/utils/logging.py +46 -6
- sqlspec/utils/module_loader.py +2 -2
- sqlspec/utils/schema.py +288 -0
- sqlspec/utils/serializers.py +50 -2
- sqlspec/utils/sync_tools.py +21 -17
- sqlspec/utils/text.py +1 -2
- sqlspec/utils/type_guards.py +111 -20
- sqlspec/utils/version.py +433 -0
- {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/METADATA +40 -21
- sqlspec-0.27.0.dist-info/RECORD +207 -0
- sqlspec/builder/mixins/__init__.py +0 -55
- sqlspec/builder/mixins/_cte_and_set_ops.py +0 -254
- sqlspec/builder/mixins/_delete_operations.py +0 -50
- sqlspec/builder/mixins/_insert_operations.py +0 -282
- sqlspec/builder/mixins/_join_operations.py +0 -389
- sqlspec/builder/mixins/_merge_operations.py +0 -592
- sqlspec/builder/mixins/_order_limit_operations.py +0 -152
- sqlspec/builder/mixins/_pivot_operations.py +0 -157
- sqlspec/builder/mixins/_select_operations.py +0 -936
- sqlspec/builder/mixins/_update_operations.py +0 -218
- sqlspec/builder/mixins/_where_clause.py +0 -1304
- sqlspec-0.25.0.dist-info/RECORD +0 -139
- sqlspec-0.25.0.dist-info/licenses/NOTICE +0 -29
- {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/WHEEL +0 -0
- {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/entry_points.txt +0 -0
- {sqlspec-0.25.0.dist-info → sqlspec-0.27.0.dist-info}/licenses/LICENSE +0 -0
|
@@ -0,0 +1,944 @@
|
|
|
1
|
+
"""Psycopg ADK store for Google Agent Development Kit session/event storage."""
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, cast
|
|
4
|
+
|
|
5
|
+
from psycopg import errors
|
|
6
|
+
from psycopg import sql as pg_sql
|
|
7
|
+
from psycopg.types.json import Jsonb
|
|
8
|
+
|
|
9
|
+
from sqlspec.extensions.adk import BaseAsyncADKStore, BaseSyncADKStore, EventRecord, SessionRecord
|
|
10
|
+
from sqlspec.utils.logging import get_logger
|
|
11
|
+
|
|
12
|
+
if TYPE_CHECKING:
|
|
13
|
+
from datetime import datetime
|
|
14
|
+
|
|
15
|
+
from psycopg.abc import Query
|
|
16
|
+
|
|
17
|
+
from sqlspec.adapters.psycopg.config import PsycopgAsyncConfig, PsycopgSyncConfig
|
|
18
|
+
|
|
19
|
+
logger = get_logger("adapters.psycopg.adk.store")
|
|
20
|
+
|
|
21
|
+
__all__ = ("PsycopgAsyncADKStore", "PsycopgSyncADKStore")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PsycopgAsyncADKStore(BaseAsyncADKStore["PsycopgAsyncConfig"]):
|
|
25
|
+
"""PostgreSQL ADK store using Psycopg3 driver.
|
|
26
|
+
|
|
27
|
+
Implements session and event storage for Google Agent Development Kit
|
|
28
|
+
using PostgreSQL via psycopg3 with native async/await support.
|
|
29
|
+
|
|
30
|
+
Provides:
|
|
31
|
+
- Session state management with JSONB storage and merge operations
|
|
32
|
+
- Event history tracking with BYTEA-serialized actions
|
|
33
|
+
- Microsecond-precision timestamps with TIMESTAMPTZ
|
|
34
|
+
- Foreign key constraints with cascade delete
|
|
35
|
+
- Efficient upserts using ON CONFLICT
|
|
36
|
+
- GIN indexes for JSONB queries
|
|
37
|
+
- HOT updates with FILLFACTOR 80
|
|
38
|
+
|
|
39
|
+
Args:
|
|
40
|
+
config: PsycopgAsyncConfig with extension_config["adk"] settings.
|
|
41
|
+
|
|
42
|
+
Example:
|
|
43
|
+
from sqlspec.adapters.psycopg import PsycopgAsyncConfig
|
|
44
|
+
from sqlspec.adapters.psycopg.adk import PsycopgAsyncADKStore
|
|
45
|
+
|
|
46
|
+
config = PsycopgAsyncConfig(
|
|
47
|
+
pool_config={"conninfo": "postgresql://..."},
|
|
48
|
+
extension_config={
|
|
49
|
+
"adk": {
|
|
50
|
+
"session_table": "my_sessions",
|
|
51
|
+
"events_table": "my_events",
|
|
52
|
+
"owner_id_column": "tenant_id INTEGER NOT NULL REFERENCES tenants(id) ON DELETE CASCADE"
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
)
|
|
56
|
+
store = PsycopgAsyncADKStore(config)
|
|
57
|
+
await store.create_tables()
|
|
58
|
+
|
|
59
|
+
Notes:
|
|
60
|
+
- PostgreSQL JSONB type used for state (more efficient than JSON)
|
|
61
|
+
- Psycopg requires wrapping dicts with Jsonb() for type safety
|
|
62
|
+
- TIMESTAMPTZ provides timezone-aware microsecond precision
|
|
63
|
+
- State merging uses `state || $1::jsonb` operator for efficiency
|
|
64
|
+
- BYTEA for pre-serialized actions from Google ADK
|
|
65
|
+
- GIN index on state for JSONB queries (partial index)
|
|
66
|
+
- FILLFACTOR 80 leaves space for HOT updates
|
|
67
|
+
- Parameter style: $1, $2, $3 (PostgreSQL numeric placeholders)
|
|
68
|
+
- Configuration is read from config.extension_config["adk"]
|
|
69
|
+
"""
|
|
70
|
+
|
|
71
|
+
__slots__ = ()
|
|
72
|
+
|
|
73
|
+
def __init__(self, config: "PsycopgAsyncConfig") -> None:
|
|
74
|
+
"""Initialize Psycopg ADK store.
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
config: PsycopgAsyncConfig instance.
|
|
78
|
+
|
|
79
|
+
Notes:
|
|
80
|
+
Configuration is read from config.extension_config["adk"]:
|
|
81
|
+
- session_table: Sessions table name (default: "adk_sessions")
|
|
82
|
+
- events_table: Events table name (default: "adk_events")
|
|
83
|
+
- owner_id_column: Optional owner FK column DDL (default: None)
|
|
84
|
+
"""
|
|
85
|
+
super().__init__(config)
|
|
86
|
+
|
|
87
|
+
def _get_create_sessions_table_sql(self) -> str:
|
|
88
|
+
"""Get PostgreSQL CREATE TABLE SQL for sessions.
|
|
89
|
+
|
|
90
|
+
Returns:
|
|
91
|
+
SQL statement to create adk_sessions table with indexes.
|
|
92
|
+
|
|
93
|
+
Notes:
|
|
94
|
+
- VARCHAR(128) for IDs and names (sufficient for UUIDs and app names)
|
|
95
|
+
- JSONB type for state storage with default empty object
|
|
96
|
+
- TIMESTAMPTZ with microsecond precision
|
|
97
|
+
- FILLFACTOR 80 for HOT updates (reduces table bloat)
|
|
98
|
+
- Composite index on (app_name, user_id) for listing
|
|
99
|
+
- Index on update_time DESC for recent session queries
|
|
100
|
+
- Partial GIN index on state for JSONB queries (only non-empty)
|
|
101
|
+
- Optional owner ID column for multi-tenancy or user references
|
|
102
|
+
"""
|
|
103
|
+
owner_id_line = ""
|
|
104
|
+
if self._owner_id_column_ddl:
|
|
105
|
+
owner_id_line = f",\n {self._owner_id_column_ddl}"
|
|
106
|
+
|
|
107
|
+
return f"""
|
|
108
|
+
CREATE TABLE IF NOT EXISTS {self._session_table} (
|
|
109
|
+
id VARCHAR(128) PRIMARY KEY,
|
|
110
|
+
app_name VARCHAR(128) NOT NULL,
|
|
111
|
+
user_id VARCHAR(128) NOT NULL{owner_id_line},
|
|
112
|
+
state JSONB NOT NULL DEFAULT '{{}}'::jsonb,
|
|
113
|
+
create_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
114
|
+
update_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
115
|
+
) WITH (fillfactor = 80);
|
|
116
|
+
|
|
117
|
+
CREATE INDEX IF NOT EXISTS idx_{self._session_table}_app_user
|
|
118
|
+
ON {self._session_table}(app_name, user_id);
|
|
119
|
+
|
|
120
|
+
CREATE INDEX IF NOT EXISTS idx_{self._session_table}_update_time
|
|
121
|
+
ON {self._session_table}(update_time DESC);
|
|
122
|
+
|
|
123
|
+
CREATE INDEX IF NOT EXISTS idx_{self._session_table}_state
|
|
124
|
+
ON {self._session_table} USING GIN (state)
|
|
125
|
+
WHERE state != '{{}}'::jsonb;
|
|
126
|
+
"""
|
|
127
|
+
|
|
128
|
+
def _get_create_events_table_sql(self) -> str:
|
|
129
|
+
"""Get PostgreSQL CREATE TABLE SQL for events.
|
|
130
|
+
|
|
131
|
+
Returns:
|
|
132
|
+
SQL statement to create adk_events table with indexes.
|
|
133
|
+
|
|
134
|
+
Notes:
|
|
135
|
+
- VARCHAR sizes: id(128), session_id(128), invocation_id(256), author(256),
|
|
136
|
+
branch(256), error_code(256), error_message(1024)
|
|
137
|
+
- BYTEA for pickled actions (no size limit)
|
|
138
|
+
- JSONB for content, grounding_metadata, custom_metadata, long_running_tool_ids_json
|
|
139
|
+
- BOOLEAN for partial, turn_complete, interrupted
|
|
140
|
+
- Foreign key to sessions with CASCADE delete
|
|
141
|
+
- Index on (session_id, timestamp ASC) for ordered event retrieval
|
|
142
|
+
"""
|
|
143
|
+
return f"""
|
|
144
|
+
CREATE TABLE IF NOT EXISTS {self._events_table} (
|
|
145
|
+
id VARCHAR(128) PRIMARY KEY,
|
|
146
|
+
session_id VARCHAR(128) NOT NULL,
|
|
147
|
+
app_name VARCHAR(128) NOT NULL,
|
|
148
|
+
user_id VARCHAR(128) NOT NULL,
|
|
149
|
+
invocation_id VARCHAR(256),
|
|
150
|
+
author VARCHAR(256),
|
|
151
|
+
actions BYTEA,
|
|
152
|
+
long_running_tool_ids_json JSONB,
|
|
153
|
+
branch VARCHAR(256),
|
|
154
|
+
timestamp TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
155
|
+
content JSONB,
|
|
156
|
+
grounding_metadata JSONB,
|
|
157
|
+
custom_metadata JSONB,
|
|
158
|
+
partial BOOLEAN,
|
|
159
|
+
turn_complete BOOLEAN,
|
|
160
|
+
interrupted BOOLEAN,
|
|
161
|
+
error_code VARCHAR(256),
|
|
162
|
+
error_message VARCHAR(1024),
|
|
163
|
+
FOREIGN KEY (session_id) REFERENCES {self._session_table}(id) ON DELETE CASCADE
|
|
164
|
+
);
|
|
165
|
+
|
|
166
|
+
CREATE INDEX IF NOT EXISTS idx_{self._events_table}_session
|
|
167
|
+
ON {self._events_table}(session_id, timestamp ASC);
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
def _get_drop_tables_sql(self) -> "list[str]":
|
|
171
|
+
"""Get PostgreSQL DROP TABLE SQL statements.
|
|
172
|
+
|
|
173
|
+
Returns:
|
|
174
|
+
List of SQL statements to drop tables and indexes.
|
|
175
|
+
|
|
176
|
+
Notes:
|
|
177
|
+
Order matters: drop events table (child) before sessions (parent).
|
|
178
|
+
PostgreSQL automatically drops indexes when dropping tables.
|
|
179
|
+
"""
|
|
180
|
+
return [f"DROP TABLE IF EXISTS {self._events_table}", f"DROP TABLE IF EXISTS {self._session_table}"]
|
|
181
|
+
|
|
182
|
+
async def create_tables(self) -> None:
|
|
183
|
+
"""Create both sessions and events tables if they don't exist."""
|
|
184
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
185
|
+
await cur.execute(cast("Query", self._get_create_sessions_table_sql()))
|
|
186
|
+
await cur.execute(cast("Query", self._get_create_events_table_sql()))
|
|
187
|
+
logger.debug("Created ADK tables: %s, %s", self._session_table, self._events_table)
|
|
188
|
+
|
|
189
|
+
async def create_session(
|
|
190
|
+
self, session_id: str, app_name: str, user_id: str, state: "dict[str, Any]", owner_id: "Any | None" = None
|
|
191
|
+
) -> SessionRecord:
|
|
192
|
+
"""Create a new session.
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
session_id: Unique session identifier.
|
|
196
|
+
app_name: Application name.
|
|
197
|
+
user_id: User identifier.
|
|
198
|
+
state: Initial session state.
|
|
199
|
+
owner_id: Optional owner ID value for owner_id_column (if configured).
|
|
200
|
+
|
|
201
|
+
Returns:
|
|
202
|
+
Created session record.
|
|
203
|
+
|
|
204
|
+
Notes:
|
|
205
|
+
Uses CURRENT_TIMESTAMP for create_time and update_time.
|
|
206
|
+
State is wrapped with Jsonb() for PostgreSQL type safety.
|
|
207
|
+
If owner_id_column is configured, owner_id value must be provided.
|
|
208
|
+
"""
|
|
209
|
+
params: tuple[Any, ...]
|
|
210
|
+
if self._owner_id_column_name:
|
|
211
|
+
query = pg_sql.SQL("""
|
|
212
|
+
INSERT INTO {table} (id, app_name, user_id, {owner_id_col}, state, create_time, update_time)
|
|
213
|
+
VALUES (%s, %s, %s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
|
214
|
+
""").format(
|
|
215
|
+
table=pg_sql.Identifier(self._session_table), owner_id_col=pg_sql.Identifier(self._owner_id_column_name)
|
|
216
|
+
)
|
|
217
|
+
params = (session_id, app_name, user_id, owner_id, Jsonb(state))
|
|
218
|
+
else:
|
|
219
|
+
query = pg_sql.SQL("""
|
|
220
|
+
INSERT INTO {table} (id, app_name, user_id, state, create_time, update_time)
|
|
221
|
+
VALUES (%s, %s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
|
222
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
223
|
+
params = (session_id, app_name, user_id, Jsonb(state))
|
|
224
|
+
|
|
225
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
226
|
+
await cur.execute(query, params)
|
|
227
|
+
|
|
228
|
+
return await self.get_session(session_id) # type: ignore[return-value]
|
|
229
|
+
|
|
230
|
+
async def get_session(self, session_id: str) -> "SessionRecord | None":
|
|
231
|
+
"""Get session by ID.
|
|
232
|
+
|
|
233
|
+
Args:
|
|
234
|
+
session_id: Session identifier.
|
|
235
|
+
|
|
236
|
+
Returns:
|
|
237
|
+
Session record or None if not found.
|
|
238
|
+
|
|
239
|
+
Notes:
|
|
240
|
+
PostgreSQL returns datetime objects for TIMESTAMPTZ columns.
|
|
241
|
+
JSONB is automatically deserialized by psycopg to Python dict.
|
|
242
|
+
"""
|
|
243
|
+
query = pg_sql.SQL("""
|
|
244
|
+
SELECT id, app_name, user_id, state, create_time, update_time
|
|
245
|
+
FROM {table}
|
|
246
|
+
WHERE id = %s
|
|
247
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
248
|
+
|
|
249
|
+
try:
|
|
250
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
251
|
+
await cur.execute(query, (session_id,))
|
|
252
|
+
row = await cur.fetchone()
|
|
253
|
+
|
|
254
|
+
if row is None:
|
|
255
|
+
return None
|
|
256
|
+
|
|
257
|
+
return SessionRecord(
|
|
258
|
+
id=row["id"],
|
|
259
|
+
app_name=row["app_name"],
|
|
260
|
+
user_id=row["user_id"],
|
|
261
|
+
state=row["state"],
|
|
262
|
+
create_time=row["create_time"],
|
|
263
|
+
update_time=row["update_time"],
|
|
264
|
+
)
|
|
265
|
+
except errors.UndefinedTable:
|
|
266
|
+
return None
|
|
267
|
+
|
|
268
|
+
async def update_session_state(self, session_id: str, state: "dict[str, Any]") -> None:
|
|
269
|
+
"""Update session state.
|
|
270
|
+
|
|
271
|
+
Args:
|
|
272
|
+
session_id: Session identifier.
|
|
273
|
+
state: New state dictionary (replaces existing state).
|
|
274
|
+
|
|
275
|
+
Notes:
|
|
276
|
+
This replaces the entire state dictionary.
|
|
277
|
+
Uses CURRENT_TIMESTAMP for update_time.
|
|
278
|
+
State is wrapped with Jsonb() for PostgreSQL type safety.
|
|
279
|
+
"""
|
|
280
|
+
query = pg_sql.SQL("""
|
|
281
|
+
UPDATE {table}
|
|
282
|
+
SET state = %s, update_time = CURRENT_TIMESTAMP
|
|
283
|
+
WHERE id = %s
|
|
284
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
285
|
+
|
|
286
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
287
|
+
await cur.execute(query, (Jsonb(state), session_id))
|
|
288
|
+
|
|
289
|
+
async def delete_session(self, session_id: str) -> None:
|
|
290
|
+
"""Delete session and all associated events (cascade).
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
session_id: Session identifier.
|
|
294
|
+
|
|
295
|
+
Notes:
|
|
296
|
+
Foreign key constraint ensures events are cascade-deleted.
|
|
297
|
+
"""
|
|
298
|
+
query = pg_sql.SQL("DELETE FROM {table} WHERE id = %s").format(table=pg_sql.Identifier(self._session_table))
|
|
299
|
+
|
|
300
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
301
|
+
await cur.execute(query, (session_id,))
|
|
302
|
+
|
|
303
|
+
async def list_sessions(self, app_name: str, user_id: str) -> "list[SessionRecord]":
|
|
304
|
+
"""List all sessions for a user in an app.
|
|
305
|
+
|
|
306
|
+
Args:
|
|
307
|
+
app_name: Application name.
|
|
308
|
+
user_id: User identifier.
|
|
309
|
+
|
|
310
|
+
Returns:
|
|
311
|
+
List of session records ordered by update_time DESC.
|
|
312
|
+
|
|
313
|
+
Notes:
|
|
314
|
+
Uses composite index on (app_name, user_id).
|
|
315
|
+
"""
|
|
316
|
+
query = pg_sql.SQL("""
|
|
317
|
+
SELECT id, app_name, user_id, state, create_time, update_time
|
|
318
|
+
FROM {table}
|
|
319
|
+
WHERE app_name = %s AND user_id = %s
|
|
320
|
+
ORDER BY update_time DESC
|
|
321
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
322
|
+
|
|
323
|
+
try:
|
|
324
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
325
|
+
await cur.execute(query, (app_name, user_id))
|
|
326
|
+
rows = await cur.fetchall()
|
|
327
|
+
|
|
328
|
+
return [
|
|
329
|
+
SessionRecord(
|
|
330
|
+
id=row["id"],
|
|
331
|
+
app_name=row["app_name"],
|
|
332
|
+
user_id=row["user_id"],
|
|
333
|
+
state=row["state"],
|
|
334
|
+
create_time=row["create_time"],
|
|
335
|
+
update_time=row["update_time"],
|
|
336
|
+
)
|
|
337
|
+
for row in rows
|
|
338
|
+
]
|
|
339
|
+
except errors.UndefinedTable:
|
|
340
|
+
return []
|
|
341
|
+
|
|
342
|
+
async def append_event(self, event_record: EventRecord) -> None:
|
|
343
|
+
"""Append an event to a session.
|
|
344
|
+
|
|
345
|
+
Args:
|
|
346
|
+
event_record: Event record to store.
|
|
347
|
+
|
|
348
|
+
Notes:
|
|
349
|
+
Uses CURRENT_TIMESTAMP for timestamp if not provided.
|
|
350
|
+
JSONB fields are wrapped with Jsonb() for PostgreSQL type safety.
|
|
351
|
+
"""
|
|
352
|
+
content_json = event_record.get("content")
|
|
353
|
+
grounding_metadata_json = event_record.get("grounding_metadata")
|
|
354
|
+
custom_metadata_json = event_record.get("custom_metadata")
|
|
355
|
+
|
|
356
|
+
query = pg_sql.SQL("""
|
|
357
|
+
INSERT INTO {table} (
|
|
358
|
+
id, session_id, app_name, user_id, invocation_id, author, actions,
|
|
359
|
+
long_running_tool_ids_json, branch, timestamp, content,
|
|
360
|
+
grounding_metadata, custom_metadata, partial, turn_complete,
|
|
361
|
+
interrupted, error_code, error_message
|
|
362
|
+
) VALUES (
|
|
363
|
+
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s
|
|
364
|
+
)
|
|
365
|
+
""").format(table=pg_sql.Identifier(self._events_table))
|
|
366
|
+
|
|
367
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
368
|
+
await cur.execute(
|
|
369
|
+
query,
|
|
370
|
+
(
|
|
371
|
+
event_record["id"],
|
|
372
|
+
event_record["session_id"],
|
|
373
|
+
event_record["app_name"],
|
|
374
|
+
event_record["user_id"],
|
|
375
|
+
event_record.get("invocation_id"),
|
|
376
|
+
event_record.get("author"),
|
|
377
|
+
event_record.get("actions"),
|
|
378
|
+
event_record.get("long_running_tool_ids_json"),
|
|
379
|
+
event_record.get("branch"),
|
|
380
|
+
event_record["timestamp"],
|
|
381
|
+
Jsonb(content_json) if content_json is not None else None,
|
|
382
|
+
Jsonb(grounding_metadata_json) if grounding_metadata_json is not None else None,
|
|
383
|
+
Jsonb(custom_metadata_json) if custom_metadata_json is not None else None,
|
|
384
|
+
event_record.get("partial"),
|
|
385
|
+
event_record.get("turn_complete"),
|
|
386
|
+
event_record.get("interrupted"),
|
|
387
|
+
event_record.get("error_code"),
|
|
388
|
+
event_record.get("error_message"),
|
|
389
|
+
),
|
|
390
|
+
)
|
|
391
|
+
|
|
392
|
+
async def get_events(
|
|
393
|
+
self, session_id: str, after_timestamp: "datetime | None" = None, limit: "int | None" = None
|
|
394
|
+
) -> "list[EventRecord]":
|
|
395
|
+
"""Get events for a session.
|
|
396
|
+
|
|
397
|
+
Args:
|
|
398
|
+
session_id: Session identifier.
|
|
399
|
+
after_timestamp: Only return events after this time.
|
|
400
|
+
limit: Maximum number of events to return.
|
|
401
|
+
|
|
402
|
+
Returns:
|
|
403
|
+
List of event records ordered by timestamp ASC.
|
|
404
|
+
|
|
405
|
+
Notes:
|
|
406
|
+
Uses index on (session_id, timestamp ASC).
|
|
407
|
+
JSONB fields are automatically deserialized by psycopg.
|
|
408
|
+
BYTEA actions are converted to bytes.
|
|
409
|
+
"""
|
|
410
|
+
where_clauses = ["session_id = %s"]
|
|
411
|
+
params: list[Any] = [session_id]
|
|
412
|
+
|
|
413
|
+
if after_timestamp is not None:
|
|
414
|
+
where_clauses.append("timestamp > %s")
|
|
415
|
+
params.append(after_timestamp)
|
|
416
|
+
|
|
417
|
+
where_clause = " AND ".join(where_clauses)
|
|
418
|
+
if limit:
|
|
419
|
+
params.append(limit)
|
|
420
|
+
|
|
421
|
+
query = pg_sql.SQL(
|
|
422
|
+
"""
|
|
423
|
+
SELECT id, session_id, app_name, user_id, invocation_id, author, actions,
|
|
424
|
+
long_running_tool_ids_json, branch, timestamp, content,
|
|
425
|
+
grounding_metadata, custom_metadata, partial, turn_complete,
|
|
426
|
+
interrupted, error_code, error_message
|
|
427
|
+
FROM {table}
|
|
428
|
+
WHERE {where_clause}
|
|
429
|
+
ORDER BY timestamp ASC{limit_clause}
|
|
430
|
+
"""
|
|
431
|
+
).format(
|
|
432
|
+
table=pg_sql.Identifier(self._events_table),
|
|
433
|
+
where_clause=pg_sql.SQL(where_clause), # pyright: ignore[reportArgumentType]
|
|
434
|
+
limit_clause=pg_sql.SQL(" LIMIT %s" if limit else ""), # pyright: ignore[reportArgumentType]
|
|
435
|
+
)
|
|
436
|
+
|
|
437
|
+
try:
|
|
438
|
+
async with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
439
|
+
await cur.execute(query, tuple(params))
|
|
440
|
+
rows = await cur.fetchall()
|
|
441
|
+
|
|
442
|
+
return [
|
|
443
|
+
EventRecord(
|
|
444
|
+
id=row["id"],
|
|
445
|
+
session_id=row["session_id"],
|
|
446
|
+
app_name=row["app_name"],
|
|
447
|
+
user_id=row["user_id"],
|
|
448
|
+
invocation_id=row["invocation_id"],
|
|
449
|
+
author=row["author"],
|
|
450
|
+
actions=bytes(row["actions"]) if row["actions"] else b"",
|
|
451
|
+
long_running_tool_ids_json=row["long_running_tool_ids_json"],
|
|
452
|
+
branch=row["branch"],
|
|
453
|
+
timestamp=row["timestamp"],
|
|
454
|
+
content=row["content"],
|
|
455
|
+
grounding_metadata=row["grounding_metadata"],
|
|
456
|
+
custom_metadata=row["custom_metadata"],
|
|
457
|
+
partial=row["partial"],
|
|
458
|
+
turn_complete=row["turn_complete"],
|
|
459
|
+
interrupted=row["interrupted"],
|
|
460
|
+
error_code=row["error_code"],
|
|
461
|
+
error_message=row["error_message"],
|
|
462
|
+
)
|
|
463
|
+
for row in rows
|
|
464
|
+
]
|
|
465
|
+
except errors.UndefinedTable:
|
|
466
|
+
return []
|
|
467
|
+
|
|
468
|
+
|
|
469
|
+
class PsycopgSyncADKStore(BaseSyncADKStore["PsycopgSyncConfig"]):
|
|
470
|
+
"""PostgreSQL synchronous ADK store using Psycopg3 driver.
|
|
471
|
+
|
|
472
|
+
Implements session and event storage for Google Agent Development Kit
|
|
473
|
+
using PostgreSQL via psycopg3 with synchronous execution.
|
|
474
|
+
|
|
475
|
+
Provides:
|
|
476
|
+
- Session state management with JSONB storage and merge operations
|
|
477
|
+
- Event history tracking with BYTEA-serialized actions
|
|
478
|
+
- Microsecond-precision timestamps with TIMESTAMPTZ
|
|
479
|
+
- Foreign key constraints with cascade delete
|
|
480
|
+
- Efficient upserts using ON CONFLICT
|
|
481
|
+
- GIN indexes for JSONB queries
|
|
482
|
+
- HOT updates with FILLFACTOR 80
|
|
483
|
+
|
|
484
|
+
Args:
|
|
485
|
+
config: PsycopgSyncConfig with extension_config["adk"] settings.
|
|
486
|
+
|
|
487
|
+
Example:
|
|
488
|
+
from sqlspec.adapters.psycopg import PsycopgSyncConfig
|
|
489
|
+
from sqlspec.adapters.psycopg.adk import PsycopgSyncADKStore
|
|
490
|
+
|
|
491
|
+
config = PsycopgSyncConfig(
|
|
492
|
+
pool_config={"conninfo": "postgresql://..."},
|
|
493
|
+
extension_config={
|
|
494
|
+
"adk": {
|
|
495
|
+
"session_table": "my_sessions",
|
|
496
|
+
"events_table": "my_events",
|
|
497
|
+
"owner_id_column": "tenant_id INTEGER NOT NULL REFERENCES tenants(id) ON DELETE CASCADE"
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
)
|
|
501
|
+
store = PsycopgSyncADKStore(config)
|
|
502
|
+
store.create_tables()
|
|
503
|
+
|
|
504
|
+
Notes:
|
|
505
|
+
- PostgreSQL JSONB type used for state (more efficient than JSON)
|
|
506
|
+
- Psycopg requires wrapping dicts with Jsonb() for type safety
|
|
507
|
+
- TIMESTAMPTZ provides timezone-aware microsecond precision
|
|
508
|
+
- State merging uses `state || $1::jsonb` operator for efficiency
|
|
509
|
+
- BYTEA for pre-serialized actions from Google ADK
|
|
510
|
+
- GIN index on state for JSONB queries (partial index)
|
|
511
|
+
- FILLFACTOR 80 leaves space for HOT updates
|
|
512
|
+
- Parameter style: $1, $2, $3 (PostgreSQL numeric placeholders)
|
|
513
|
+
- Configuration is read from config.extension_config["adk"]
|
|
514
|
+
"""
|
|
515
|
+
|
|
516
|
+
__slots__ = ()
|
|
517
|
+
|
|
518
|
+
def __init__(self, config: "PsycopgSyncConfig") -> None:
|
|
519
|
+
"""Initialize Psycopg synchronous ADK store.
|
|
520
|
+
|
|
521
|
+
Args:
|
|
522
|
+
config: PsycopgSyncConfig instance.
|
|
523
|
+
|
|
524
|
+
Notes:
|
|
525
|
+
Configuration is read from config.extension_config["adk"]:
|
|
526
|
+
- session_table: Sessions table name (default: "adk_sessions")
|
|
527
|
+
- events_table: Events table name (default: "adk_events")
|
|
528
|
+
- owner_id_column: Optional owner FK column DDL (default: None)
|
|
529
|
+
"""
|
|
530
|
+
super().__init__(config)
|
|
531
|
+
|
|
532
|
+
def _get_create_sessions_table_sql(self) -> str:
|
|
533
|
+
"""Get PostgreSQL CREATE TABLE SQL for sessions.
|
|
534
|
+
|
|
535
|
+
Returns:
|
|
536
|
+
SQL statement to create adk_sessions table with indexes.
|
|
537
|
+
|
|
538
|
+
Notes:
|
|
539
|
+
- VARCHAR(128) for IDs and names (sufficient for UUIDs and app names)
|
|
540
|
+
- JSONB type for state storage with default empty object
|
|
541
|
+
- TIMESTAMPTZ with microsecond precision
|
|
542
|
+
- FILLFACTOR 80 for HOT updates (reduces table bloat)
|
|
543
|
+
- Composite index on (app_name, user_id) for listing
|
|
544
|
+
- Index on update_time DESC for recent session queries
|
|
545
|
+
- Partial GIN index on state for JSONB queries (only non-empty)
|
|
546
|
+
- Optional owner ID column for multi-tenancy or user references
|
|
547
|
+
"""
|
|
548
|
+
owner_id_line = ""
|
|
549
|
+
if self._owner_id_column_ddl:
|
|
550
|
+
owner_id_line = f",\n {self._owner_id_column_ddl}"
|
|
551
|
+
|
|
552
|
+
return f"""
|
|
553
|
+
CREATE TABLE IF NOT EXISTS {self._session_table} (
|
|
554
|
+
id VARCHAR(128) PRIMARY KEY,
|
|
555
|
+
app_name VARCHAR(128) NOT NULL,
|
|
556
|
+
user_id VARCHAR(128) NOT NULL{owner_id_line},
|
|
557
|
+
state JSONB NOT NULL DEFAULT '{{}}'::jsonb,
|
|
558
|
+
create_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
559
|
+
update_time TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP
|
|
560
|
+
) WITH (fillfactor = 80);
|
|
561
|
+
|
|
562
|
+
CREATE INDEX IF NOT EXISTS idx_{self._session_table}_app_user
|
|
563
|
+
ON {self._session_table}(app_name, user_id);
|
|
564
|
+
|
|
565
|
+
CREATE INDEX IF NOT EXISTS idx_{self._session_table}_update_time
|
|
566
|
+
ON {self._session_table}(update_time DESC);
|
|
567
|
+
|
|
568
|
+
CREATE INDEX IF NOT EXISTS idx_{self._session_table}_state
|
|
569
|
+
ON {self._session_table} USING GIN (state)
|
|
570
|
+
WHERE state != '{{}}'::jsonb;
|
|
571
|
+
"""
|
|
572
|
+
|
|
573
|
+
def _get_create_events_table_sql(self) -> str:
|
|
574
|
+
"""Get PostgreSQL CREATE TABLE SQL for events.
|
|
575
|
+
|
|
576
|
+
Returns:
|
|
577
|
+
SQL statement to create adk_events table with indexes.
|
|
578
|
+
|
|
579
|
+
Notes:
|
|
580
|
+
- VARCHAR sizes: id(128), session_id(128), invocation_id(256), author(256),
|
|
581
|
+
branch(256), error_code(256), error_message(1024)
|
|
582
|
+
- BYTEA for pickled actions (no size limit)
|
|
583
|
+
- JSONB for content, grounding_metadata, custom_metadata, long_running_tool_ids_json
|
|
584
|
+
- BOOLEAN for partial, turn_complete, interrupted
|
|
585
|
+
- Foreign key to sessions with CASCADE delete
|
|
586
|
+
- Index on (session_id, timestamp ASC) for ordered event retrieval
|
|
587
|
+
"""
|
|
588
|
+
return f"""
|
|
589
|
+
CREATE TABLE IF NOT EXISTS {self._events_table} (
|
|
590
|
+
id VARCHAR(128) PRIMARY KEY,
|
|
591
|
+
session_id VARCHAR(128) NOT NULL,
|
|
592
|
+
app_name VARCHAR(128) NOT NULL,
|
|
593
|
+
user_id VARCHAR(128) NOT NULL,
|
|
594
|
+
invocation_id VARCHAR(256),
|
|
595
|
+
author VARCHAR(256),
|
|
596
|
+
actions BYTEA,
|
|
597
|
+
long_running_tool_ids_json JSONB,
|
|
598
|
+
branch VARCHAR(256),
|
|
599
|
+
timestamp TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
600
|
+
content JSONB,
|
|
601
|
+
grounding_metadata JSONB,
|
|
602
|
+
custom_metadata JSONB,
|
|
603
|
+
partial BOOLEAN,
|
|
604
|
+
turn_complete BOOLEAN,
|
|
605
|
+
interrupted BOOLEAN,
|
|
606
|
+
error_code VARCHAR(256),
|
|
607
|
+
error_message VARCHAR(1024),
|
|
608
|
+
FOREIGN KEY (session_id) REFERENCES {self._session_table}(id) ON DELETE CASCADE
|
|
609
|
+
);
|
|
610
|
+
|
|
611
|
+
CREATE INDEX IF NOT EXISTS idx_{self._events_table}_session
|
|
612
|
+
ON {self._events_table}(session_id, timestamp ASC);
|
|
613
|
+
"""
|
|
614
|
+
|
|
615
|
+
def _get_drop_tables_sql(self) -> "list[str]":
|
|
616
|
+
"""Get PostgreSQL DROP TABLE SQL statements.
|
|
617
|
+
|
|
618
|
+
Returns:
|
|
619
|
+
List of SQL statements to drop tables and indexes.
|
|
620
|
+
|
|
621
|
+
Notes:
|
|
622
|
+
Order matters: drop events table (child) before sessions (parent).
|
|
623
|
+
PostgreSQL automatically drops indexes when dropping tables.
|
|
624
|
+
"""
|
|
625
|
+
return [f"DROP TABLE IF EXISTS {self._events_table}", f"DROP TABLE IF EXISTS {self._session_table}"]
|
|
626
|
+
|
|
627
|
+
def create_tables(self) -> None:
|
|
628
|
+
"""Create both sessions and events tables if they don't exist."""
|
|
629
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
630
|
+
cur.execute(cast("Query", self._get_create_sessions_table_sql()))
|
|
631
|
+
cur.execute(cast("Query", self._get_create_events_table_sql()))
|
|
632
|
+
logger.debug("Created ADK tables: %s, %s", self._session_table, self._events_table)
|
|
633
|
+
|
|
634
|
+
def create_session(
|
|
635
|
+
self, session_id: str, app_name: str, user_id: str, state: "dict[str, Any]", owner_id: "Any | None" = None
|
|
636
|
+
) -> SessionRecord:
|
|
637
|
+
"""Create a new session.
|
|
638
|
+
|
|
639
|
+
Args:
|
|
640
|
+
session_id: Unique session identifier.
|
|
641
|
+
app_name: Application name.
|
|
642
|
+
user_id: User identifier.
|
|
643
|
+
state: Initial session state.
|
|
644
|
+
owner_id: Optional owner ID value for owner_id_column (if configured).
|
|
645
|
+
|
|
646
|
+
Returns:
|
|
647
|
+
Created session record.
|
|
648
|
+
|
|
649
|
+
Notes:
|
|
650
|
+
Uses CURRENT_TIMESTAMP for create_time and update_time.
|
|
651
|
+
State is wrapped with Jsonb() for PostgreSQL type safety.
|
|
652
|
+
If owner_id_column is configured, owner_id value must be provided.
|
|
653
|
+
"""
|
|
654
|
+
params: tuple[Any, ...]
|
|
655
|
+
if self._owner_id_column_name:
|
|
656
|
+
query = pg_sql.SQL("""
|
|
657
|
+
INSERT INTO {table} (id, app_name, user_id, {owner_id_col}, state, create_time, update_time)
|
|
658
|
+
VALUES (%s, %s, %s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
|
659
|
+
""").format(
|
|
660
|
+
table=pg_sql.Identifier(self._session_table), owner_id_col=pg_sql.Identifier(self._owner_id_column_name)
|
|
661
|
+
)
|
|
662
|
+
params = (session_id, app_name, user_id, owner_id, Jsonb(state))
|
|
663
|
+
else:
|
|
664
|
+
query = pg_sql.SQL("""
|
|
665
|
+
INSERT INTO {table} (id, app_name, user_id, state, create_time, update_time)
|
|
666
|
+
VALUES (%s, %s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
|
|
667
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
668
|
+
params = (session_id, app_name, user_id, Jsonb(state))
|
|
669
|
+
|
|
670
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
671
|
+
cur.execute(query, params)
|
|
672
|
+
|
|
673
|
+
return self.get_session(session_id) # type: ignore[return-value]
|
|
674
|
+
|
|
675
|
+
def get_session(self, session_id: str) -> "SessionRecord | None":
|
|
676
|
+
"""Get session by ID.
|
|
677
|
+
|
|
678
|
+
Args:
|
|
679
|
+
session_id: Session identifier.
|
|
680
|
+
|
|
681
|
+
Returns:
|
|
682
|
+
Session record or None if not found.
|
|
683
|
+
|
|
684
|
+
Notes:
|
|
685
|
+
PostgreSQL returns datetime objects for TIMESTAMPTZ columns.
|
|
686
|
+
JSONB is automatically deserialized by psycopg to Python dict.
|
|
687
|
+
"""
|
|
688
|
+
query = pg_sql.SQL("""
|
|
689
|
+
SELECT id, app_name, user_id, state, create_time, update_time
|
|
690
|
+
FROM {table}
|
|
691
|
+
WHERE id = %s
|
|
692
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
693
|
+
|
|
694
|
+
try:
|
|
695
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
696
|
+
cur.execute(query, (session_id,))
|
|
697
|
+
row = cur.fetchone()
|
|
698
|
+
|
|
699
|
+
if row is None:
|
|
700
|
+
return None
|
|
701
|
+
|
|
702
|
+
return SessionRecord(
|
|
703
|
+
id=row["id"],
|
|
704
|
+
app_name=row["app_name"],
|
|
705
|
+
user_id=row["user_id"],
|
|
706
|
+
state=row["state"],
|
|
707
|
+
create_time=row["create_time"],
|
|
708
|
+
update_time=row["update_time"],
|
|
709
|
+
)
|
|
710
|
+
except errors.UndefinedTable:
|
|
711
|
+
return None
|
|
712
|
+
|
|
713
|
+
def update_session_state(self, session_id: str, state: "dict[str, Any]") -> None:
|
|
714
|
+
"""Update session state.
|
|
715
|
+
|
|
716
|
+
Args:
|
|
717
|
+
session_id: Session identifier.
|
|
718
|
+
state: New state dictionary (replaces existing state).
|
|
719
|
+
|
|
720
|
+
Notes:
|
|
721
|
+
This replaces the entire state dictionary.
|
|
722
|
+
Uses CURRENT_TIMESTAMP for update_time.
|
|
723
|
+
State is wrapped with Jsonb() for PostgreSQL type safety.
|
|
724
|
+
"""
|
|
725
|
+
query = pg_sql.SQL("""
|
|
726
|
+
UPDATE {table}
|
|
727
|
+
SET state = %s, update_time = CURRENT_TIMESTAMP
|
|
728
|
+
WHERE id = %s
|
|
729
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
730
|
+
|
|
731
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
732
|
+
cur.execute(query, (Jsonb(state), session_id))
|
|
733
|
+
|
|
734
|
+
def delete_session(self, session_id: str) -> None:
|
|
735
|
+
"""Delete session and all associated events (cascade).
|
|
736
|
+
|
|
737
|
+
Args:
|
|
738
|
+
session_id: Session identifier.
|
|
739
|
+
|
|
740
|
+
Notes:
|
|
741
|
+
Foreign key constraint ensures events are cascade-deleted.
|
|
742
|
+
"""
|
|
743
|
+
query = pg_sql.SQL("DELETE FROM {table} WHERE id = %s").format(table=pg_sql.Identifier(self._session_table))
|
|
744
|
+
|
|
745
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
746
|
+
cur.execute(query, (session_id,))
|
|
747
|
+
|
|
748
|
+
def list_sessions(self, app_name: str, user_id: str) -> "list[SessionRecord]":
|
|
749
|
+
"""List all sessions for a user in an app.
|
|
750
|
+
|
|
751
|
+
Args:
|
|
752
|
+
app_name: Application name.
|
|
753
|
+
user_id: User identifier.
|
|
754
|
+
|
|
755
|
+
Returns:
|
|
756
|
+
List of session records ordered by update_time DESC.
|
|
757
|
+
|
|
758
|
+
Notes:
|
|
759
|
+
Uses composite index on (app_name, user_id).
|
|
760
|
+
"""
|
|
761
|
+
query = pg_sql.SQL("""
|
|
762
|
+
SELECT id, app_name, user_id, state, create_time, update_time
|
|
763
|
+
FROM {table}
|
|
764
|
+
WHERE app_name = %s AND user_id = %s
|
|
765
|
+
ORDER BY update_time DESC
|
|
766
|
+
""").format(table=pg_sql.Identifier(self._session_table))
|
|
767
|
+
|
|
768
|
+
try:
|
|
769
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
770
|
+
cur.execute(query, (app_name, user_id))
|
|
771
|
+
rows = cur.fetchall()
|
|
772
|
+
|
|
773
|
+
return [
|
|
774
|
+
SessionRecord(
|
|
775
|
+
id=row["id"],
|
|
776
|
+
app_name=row["app_name"],
|
|
777
|
+
user_id=row["user_id"],
|
|
778
|
+
state=row["state"],
|
|
779
|
+
create_time=row["create_time"],
|
|
780
|
+
update_time=row["update_time"],
|
|
781
|
+
)
|
|
782
|
+
for row in rows
|
|
783
|
+
]
|
|
784
|
+
except errors.UndefinedTable:
|
|
785
|
+
return []
|
|
786
|
+
|
|
787
|
+
def create_event(
|
|
788
|
+
self,
|
|
789
|
+
event_id: str,
|
|
790
|
+
session_id: str,
|
|
791
|
+
app_name: str,
|
|
792
|
+
user_id: str,
|
|
793
|
+
author: "str | None" = None,
|
|
794
|
+
actions: "bytes | None" = None,
|
|
795
|
+
content: "dict[str, Any] | None" = None,
|
|
796
|
+
**kwargs: Any,
|
|
797
|
+
) -> EventRecord:
|
|
798
|
+
"""Create a new event.
|
|
799
|
+
|
|
800
|
+
Args:
|
|
801
|
+
event_id: Unique event identifier.
|
|
802
|
+
session_id: Session identifier.
|
|
803
|
+
app_name: Application name.
|
|
804
|
+
user_id: User identifier.
|
|
805
|
+
author: Event author (user/assistant/system).
|
|
806
|
+
actions: Pickled actions object.
|
|
807
|
+
content: Event content (JSONB).
|
|
808
|
+
**kwargs: Additional optional fields (invocation_id, branch, timestamp,
|
|
809
|
+
grounding_metadata, custom_metadata, partial, turn_complete,
|
|
810
|
+
interrupted, error_code, error_message, long_running_tool_ids_json).
|
|
811
|
+
|
|
812
|
+
Returns:
|
|
813
|
+
Created event record.
|
|
814
|
+
|
|
815
|
+
Notes:
|
|
816
|
+
Uses CURRENT_TIMESTAMP for timestamp if not provided in kwargs.
|
|
817
|
+
JSONB fields are wrapped with Jsonb() for PostgreSQL type safety.
|
|
818
|
+
"""
|
|
819
|
+
content_json = Jsonb(content) if content is not None else None
|
|
820
|
+
grounding_metadata = kwargs.get("grounding_metadata")
|
|
821
|
+
grounding_metadata_json = Jsonb(grounding_metadata) if grounding_metadata is not None else None
|
|
822
|
+
custom_metadata = kwargs.get("custom_metadata")
|
|
823
|
+
custom_metadata_json = Jsonb(custom_metadata) if custom_metadata is not None else None
|
|
824
|
+
|
|
825
|
+
query = pg_sql.SQL("""
|
|
826
|
+
INSERT INTO {table} (
|
|
827
|
+
id, session_id, app_name, user_id, invocation_id, author, actions,
|
|
828
|
+
long_running_tool_ids_json, branch, timestamp, content,
|
|
829
|
+
grounding_metadata, custom_metadata, partial, turn_complete,
|
|
830
|
+
interrupted, error_code, error_message
|
|
831
|
+
) VALUES (
|
|
832
|
+
%s, %s, %s, %s, %s, %s, %s, %s, %s, COALESCE(%s, CURRENT_TIMESTAMP), %s, %s, %s, %s, %s, %s, %s, %s
|
|
833
|
+
)
|
|
834
|
+
RETURNING id, session_id, app_name, user_id, invocation_id, author, actions,
|
|
835
|
+
long_running_tool_ids_json, branch, timestamp, content,
|
|
836
|
+
grounding_metadata, custom_metadata, partial, turn_complete,
|
|
837
|
+
interrupted, error_code, error_message
|
|
838
|
+
""").format(table=pg_sql.Identifier(self._events_table))
|
|
839
|
+
|
|
840
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
841
|
+
cur.execute(
|
|
842
|
+
query,
|
|
843
|
+
(
|
|
844
|
+
event_id,
|
|
845
|
+
session_id,
|
|
846
|
+
app_name,
|
|
847
|
+
user_id,
|
|
848
|
+
kwargs.get("invocation_id"),
|
|
849
|
+
author,
|
|
850
|
+
actions,
|
|
851
|
+
kwargs.get("long_running_tool_ids_json"),
|
|
852
|
+
kwargs.get("branch"),
|
|
853
|
+
kwargs.get("timestamp"),
|
|
854
|
+
content_json,
|
|
855
|
+
grounding_metadata_json,
|
|
856
|
+
custom_metadata_json,
|
|
857
|
+
kwargs.get("partial"),
|
|
858
|
+
kwargs.get("turn_complete"),
|
|
859
|
+
kwargs.get("interrupted"),
|
|
860
|
+
kwargs.get("error_code"),
|
|
861
|
+
kwargs.get("error_message"),
|
|
862
|
+
),
|
|
863
|
+
)
|
|
864
|
+
row = cur.fetchone()
|
|
865
|
+
|
|
866
|
+
if row is None:
|
|
867
|
+
msg = f"Failed to create event {event_id}"
|
|
868
|
+
raise RuntimeError(msg)
|
|
869
|
+
|
|
870
|
+
return EventRecord(
|
|
871
|
+
id=row["id"],
|
|
872
|
+
session_id=row["session_id"],
|
|
873
|
+
app_name=row["app_name"],
|
|
874
|
+
user_id=row["user_id"],
|
|
875
|
+
invocation_id=row["invocation_id"],
|
|
876
|
+
author=row["author"],
|
|
877
|
+
actions=bytes(row["actions"]) if row["actions"] else b"",
|
|
878
|
+
long_running_tool_ids_json=row["long_running_tool_ids_json"],
|
|
879
|
+
branch=row["branch"],
|
|
880
|
+
timestamp=row["timestamp"],
|
|
881
|
+
content=row["content"],
|
|
882
|
+
grounding_metadata=row["grounding_metadata"],
|
|
883
|
+
custom_metadata=row["custom_metadata"],
|
|
884
|
+
partial=row["partial"],
|
|
885
|
+
turn_complete=row["turn_complete"],
|
|
886
|
+
interrupted=row["interrupted"],
|
|
887
|
+
error_code=row["error_code"],
|
|
888
|
+
error_message=row["error_message"],
|
|
889
|
+
)
|
|
890
|
+
|
|
891
|
+
def list_events(self, session_id: str) -> "list[EventRecord]":
|
|
892
|
+
"""List events for a session ordered by timestamp.
|
|
893
|
+
|
|
894
|
+
Args:
|
|
895
|
+
session_id: Session identifier.
|
|
896
|
+
|
|
897
|
+
Returns:
|
|
898
|
+
List of event records ordered by timestamp ASC.
|
|
899
|
+
|
|
900
|
+
Notes:
|
|
901
|
+
Uses index on (session_id, timestamp ASC).
|
|
902
|
+
JSONB fields are automatically deserialized by psycopg.
|
|
903
|
+
BYTEA actions are converted to bytes.
|
|
904
|
+
"""
|
|
905
|
+
query = pg_sql.SQL("""
|
|
906
|
+
SELECT id, session_id, app_name, user_id, invocation_id, author, actions,
|
|
907
|
+
long_running_tool_ids_json, branch, timestamp, content,
|
|
908
|
+
grounding_metadata, custom_metadata, partial, turn_complete,
|
|
909
|
+
interrupted, error_code, error_message
|
|
910
|
+
FROM {table}
|
|
911
|
+
WHERE session_id = %s
|
|
912
|
+
ORDER BY timestamp ASC
|
|
913
|
+
""").format(table=pg_sql.Identifier(self._events_table))
|
|
914
|
+
|
|
915
|
+
try:
|
|
916
|
+
with self._config.provide_connection() as conn, conn.cursor() as cur:
|
|
917
|
+
cur.execute(query, (session_id,))
|
|
918
|
+
rows = cur.fetchall()
|
|
919
|
+
|
|
920
|
+
return [
|
|
921
|
+
EventRecord(
|
|
922
|
+
id=row["id"],
|
|
923
|
+
session_id=row["session_id"],
|
|
924
|
+
app_name=row["app_name"],
|
|
925
|
+
user_id=row["user_id"],
|
|
926
|
+
invocation_id=row["invocation_id"],
|
|
927
|
+
author=row["author"],
|
|
928
|
+
actions=bytes(row["actions"]) if row["actions"] else b"",
|
|
929
|
+
long_running_tool_ids_json=row["long_running_tool_ids_json"],
|
|
930
|
+
branch=row["branch"],
|
|
931
|
+
timestamp=row["timestamp"],
|
|
932
|
+
content=row["content"],
|
|
933
|
+
grounding_metadata=row["grounding_metadata"],
|
|
934
|
+
custom_metadata=row["custom_metadata"],
|
|
935
|
+
partial=row["partial"],
|
|
936
|
+
turn_complete=row["turn_complete"],
|
|
937
|
+
interrupted=row["interrupted"],
|
|
938
|
+
error_code=row["error_code"],
|
|
939
|
+
error_message=row["error_message"],
|
|
940
|
+
)
|
|
941
|
+
for row in rows
|
|
942
|
+
]
|
|
943
|
+
except errors.UndefinedTable:
|
|
944
|
+
return []
|