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