Skip to content

storage

Class info

Re-exported classes

Class Module Description
ModelStore schemez.storage.model_store Type-safe async SQLite storage for Pydantic models.

🛈 DocStrings

Storage module for persisting Pydantic models to SQLite.

ModelStore

Type-safe async SQLite storage for Pydantic models.

Can be initialized with a model type, or opened from an existing database that has the schema stored.

Example
class User(BaseModel):
    name: str
    age: int
    email: str | None = None

# Create new database with known type
async with ModelStore(User, "users.db") as store:
    user_id = await store.insert(User(name="Alice", age=30))
    user = await store.get(user_id)
    all_users = await store.all()

# Open existing database, reconstruct type from stored schema
async with await ModelStore.open("users.db") as store:
    users = await store.all()  # Returns reconstructed model instances
Source code in src/schemez/storage/model_store.py
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
class ModelStore[T: BaseModel]:
    """Type-safe async SQLite storage for Pydantic models.

    Can be initialized with a model type, or opened from an existing database
    that has the schema stored.

    Example:
        ```python
        class User(BaseModel):
            name: str
            age: int
            email: str | None = None

        # Create new database with known type
        async with ModelStore(User, "users.db") as store:
            user_id = await store.insert(User(name="Alice", age=30))
            user = await store.get(user_id)
            all_users = await store.all()

        # Open existing database, reconstruct type from stored schema
        async with await ModelStore.open("users.db") as store:
            users = await store.all()  # Returns reconstructed model instances
        ```
    """

    def __init__(
        self,
        model_type: type[T] | None = None,
        path: str | Path = ":memory:",
        table_name: str | None = None,
    ) -> None:
        """Initialize the model store.

        Args:
            model_type: The Pydantic model class to store (required for new DBs)
            path: SQLite database path (":memory:" for in-memory)
            table_name: Custom table name (defaults to lowercase model name)

        Raises:
            ValueError: If model_type is None and path doesn't exist or is :memory:
        """
        self._path = str(path)
        self._connection: aiosqlite.Connection | None = None
        self._model_type: type[T] | None = model_type
        self._table_name = table_name
        self._columns: list[tuple[str, str, bool, Any]] | None = None
        self._import_path: str | None = None

        # Validate: can't create new DB without model_type
        if model_type is None:
            if self._path == ":memory:":
                msg = "model_type is required for in-memory databases"
                raise ValueError(msg)
            if not Path(self._path).exists():
                msg = f"model_type is required when database doesn't exist: {self._path}"
                raise ValueError(msg)
        else:
            self._table_name = table_name or model_type.__name__.lower()
            self._columns = self._build_column_definitions()
            module = model_type.__module__
            if module != "__main__":
                self._import_path = f"{module}.{model_type.__name__}"

    @classmethod
    async def open(cls, path: str | Path) -> ModelStore[BaseModel]:
        """Open an existing database and reconstruct the model from stored schema.

        Args:
            path: Path to existing SQLite database

        Returns:
            ModelStore with reconstructed model type

        Raises:
            FileNotFoundError: If database doesn't exist
            ValueError: If database has no stored schema
        """
        path = Path(path)
        if not path.exists():
            msg = f"Database not found: {path}"
            raise FileNotFoundError(msg)

        return cls(model_type=None, path=path)  # ty: ignore[invalid-explicit-return]

    @property
    def model_type(self) -> type[T]:
        """The model class (original or reconstructed)."""
        if self._model_type is None:
            msg = "Model type not yet available. Use async context manager first."
            raise RuntimeError(msg)
        return self._model_type

    @property
    def json_schema(self) -> dict[str, Any]:
        """Get the JSON schema for the stored model."""
        return self.model_type.model_json_schema()

    @property
    def import_path(self) -> str | None:
        """Get the import path for the stored model, if available."""
        return self._import_path

    def _build_column_definitions(self) -> list[tuple[str, str, bool, Any]]:
        """Build column definitions from model fields.

        Returns:
            List of (name, sqlite_type, is_nullable, annotation) tuples
        """
        if self._model_type is None:
            msg = "Cannot build columns without model_type"
            raise RuntimeError(msg)

        columns: list[tuple[str, str, bool, Any]] = []
        for name, field_info in self._model_type.model_fields.items():
            annotation = field_info.annotation
            sqlite_type, is_nullable = _get_sqlite_type(annotation)
            # Fields with a default may still default to None
            if not field_info.is_required() and field_info.default is None:
                is_nullable = True
            columns.append((name, sqlite_type, is_nullable, annotation))
        return columns

    def _create_table_sql(self) -> str:
        """Generate CREATE TABLE SQL statement."""
        if self._columns is None:
            msg = "Columns not initialized"
            raise RuntimeError(msg)

        column_defs = ["id INTEGER PRIMARY KEY AUTOINCREMENT"]
        for name, sqlite_type, is_nullable, _ in self._columns:
            null_clause = "" if is_nullable else " NOT NULL"
            column_defs.append(f"{_quote(name)} {sqlite_type}{null_clause}")
        columns_sql = ", ".join(column_defs)
        return f"CREATE TABLE IF NOT EXISTS {self._quoted_table} ({columns_sql})"

    def _create_meta_table_sql(self) -> str:
        """Generate CREATE TABLE SQL for metadata."""
        return f"""
            CREATE TABLE IF NOT EXISTS {META_TABLE} (
                key TEXT PRIMARY KEY,
                value TEXT NOT NULL
            )
        """

    async def _store_schema(self, conn: aiosqlite.Connection) -> None:
        """Store the model's JSON schema in the metadata table."""
        if self._model_type is None:
            return

        schema = self._model_type.model_json_schema()
        model_name = self._model_type.__name__
        module = self._model_type.__module__
        import_path = f"{module}.{model_name}" if module != "__main__" else None

        await conn.execute(
            f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
            ("schema", json.dumps(schema)),
        )
        await conn.execute(
            f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
            ("model_name", model_name),
        )
        await conn.execute(
            f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
            ("table_name", self._table_name),
        )
        if import_path:
            await conn.execute(
                f"INSERT OR REPLACE INTO {META_TABLE} (key, value) VALUES (?, ?)",
                ("import_path", import_path),
            )

    async def _load_schema(self, conn: aiosqlite.Connection) -> None:
        """Load and reconstruct model from stored schema."""
        from schemez.schema_to_type import json_schema_to_pydantic_class

        # Check if meta table exists
        cursor = await conn.execute(
            "SELECT name FROM sqlite_master WHERE type='table' AND name=?",
            (META_TABLE,),
        )
        if await cursor.fetchone() is None:
            msg = "Database has no metadata table. Cannot reconstruct model."
            raise ValueError(msg)

        # Load schema and model name
        cursor = await conn.execute(
            f"SELECT key, value FROM {META_TABLE} WHERE key IN (?, ?, ?, ?)",
            ("schema", "model_name", "table_name", "import_path"),
        )
        rows = await cursor.fetchall()
        meta = {row[0]: row[1] for row in rows}

        if "schema" not in meta:
            msg = "No schema found in database metadata"
            raise ValueError(msg)

        schema = json.loads(meta["schema"])
        model_name = meta.get("model_name", "DynamicModel")
        self._table_name = meta.get("table_name", model_name.lower())
        self._import_path = meta.get("import_path")

        # Reconstruct the model class
        self._model_type = json_schema_to_pydantic_class(schema, class_name=model_name)  # ty: ignore[invalid-assignment]
        self._columns = self._build_column_definitions()

    async def __aenter__(self) -> Self:
        """Open connection and create/load table."""
        import aiosqlite

        conn = await aiosqlite.connect(self._path)
        conn.row_factory = aiosqlite.Row
        try:
            if self._model_type is None:
                # Opening existing DB - reconstruct model from schema
                await self._load_schema(conn)
            else:
                # Creating new or opening with known type
                await conn.execute(self._create_meta_table_sql())
                await conn.execute(self._create_table_sql())
                await self._store_schema(conn)
                await conn.commit()
        except BaseException:
            # __aexit__ won't run; an open connection's worker thread blocks exit
            await conn.close()
            raise
        self._connection = conn
        return self

    async def __aexit__(
        self,
        exc_type: type[BaseException] | None,
        exc_val: BaseException | None,
        exc_tb: object,
    ) -> None:
        """Close connection."""
        if self._connection:
            await self._connection.close()
            self._connection = None

    @property
    def _quoted_table(self) -> str:
        if self._table_name is None:
            msg = "Table name not initialized"
            raise RuntimeError(msg)
        return _quote(self._table_name)

    def _ensure_connected(self) -> aiosqlite.Connection:
        """Ensure we have an active connection."""
        if self._connection is None:
            msg = "ModelStore must be used as async context manager"
            raise RuntimeError(msg)
        return self._connection

    def _instance_to_row(self, instance: T) -> dict[str, Any]:
        """Convert model instance to row dict with serialized values."""
        if self._columns is None:
            msg = "Columns not initialized"
            raise RuntimeError(msg)

        row = {}
        for name, _, _, annotation in self._columns:
            value = getattr(instance, name)
            row[name] = _serialize_value(value, annotation)
        return row

    def _row_to_instance(self, row: aiosqlite.Row) -> T:
        """Convert database row to model instance."""
        if self._columns is None or self._model_type is None:
            msg = "Model not initialized"
            raise RuntimeError(msg)

        data = {}
        for name, _, _, annotation in self._columns:
            value = row[name]
            data[name] = _deserialize_value(value, annotation)
        return self._model_type.model_validate(data)

    async def insert(self, instance: T) -> int:
        """Insert a model instance.

        Args:
            instance: The model instance to insert

        Returns:
            The inserted row's id
        """
        conn = self._ensure_connected()
        row_id = await self._insert_row(conn, instance)
        await conn.commit()
        return row_id

    async def _insert_row(self, conn: aiosqlite.Connection, instance: T) -> int:
        row = self._instance_to_row(instance)
        columns = ", ".join(_quote(name) for name in row)
        placeholders = ", ".join("?" for _ in row)
        sql = f"INSERT INTO {self._quoted_table} ({columns}) VALUES ({placeholders})"
        cursor = await conn.execute(sql, list(row.values()))
        row_id = cursor.lastrowid
        assert row_id is not None  # always set after a successful INSERT
        return row_id

    async def insert_many(self, instances: Sequence[T]) -> list[int]:
        """Insert multiple model instances.

        Args:
            instances: The model instances to insert

        Returns:
            List of inserted row ids
        """
        conn = self._ensure_connected()
        try:  # one transaction for all rows
            ids = [await self._insert_row(conn, instance) for instance in instances]
        except BaseException:
            await conn.rollback()
            raise
        await conn.commit()
        return ids

    async def get(self, row_id: int) -> T | None:
        """Fetch a model instance by id.

        Args:
            row_id: The row id to fetch

        Returns:
            The model instance, or None if not found
        """
        conn = self._ensure_connected()
        sql = f"SELECT * FROM {self._quoted_table} WHERE id = ?"
        cursor = await conn.execute(sql, (row_id,))
        row = await cursor.fetchone()
        if row is None:
            return None
        return self._row_to_instance(row)

    async def all(self) -> list[T]:
        """Fetch all model instances.

        Returns:
            List of all model instances
        """
        conn = self._ensure_connected()
        sql = f"SELECT * FROM {self._quoted_table}"
        cursor = await conn.execute(sql)
        rows = await cursor.fetchall()
        return [self._row_to_instance(row) for row in rows]

    async def delete(self, row_id: int) -> bool:
        """Delete a model instance by id.

        Args:
            row_id: The row id to delete

        Returns:
            True if a row was deleted, False otherwise
        """
        conn = self._ensure_connected()
        sql = f"DELETE FROM {self._quoted_table} WHERE id = ?"
        cursor = await conn.execute(sql, (row_id,))
        await conn.commit()
        return cursor.rowcount > 0

    async def count(self) -> int:
        """Count total rows in the table.

        Returns:
            Number of rows
        """
        conn = self._ensure_connected()
        sql = f"SELECT COUNT(*) FROM {self._quoted_table}"
        cursor = await conn.execute(sql)
        row = await cursor.fetchone()
        return row[0] if row else 0

    async def query(self, **filters: Any) -> list[T]:
        """Query instances with simple equality filters.

        Args:
            **filters: Field-value pairs for WHERE clause (equality only)

        Returns:
            List of matching model instances

        Example:
            ```python
            users = await store.query(age=30, name="Alice")
            ```
        """
        conn = self._ensure_connected()

        if not filters:
            return await self.all()

        if self._columns is None:
            msg = "Columns not initialized"
            raise RuntimeError(msg)

        # Build WHERE clause
        conditions = []
        values = []
        annotations = {name: ann for name, _, _, ann in self._columns}

        for field, value in filters.items():
            if field not in annotations:
                msg = f"Unknown field: {field}"
                raise ValueError(msg)
            if value is None:
                conditions.append(f"{_quote(field)} IS NULL")
                continue
            conditions.append(f"{_quote(field)} = ?")
            values.append(_serialize_value(value, annotations[field]))

        where_clause = " AND ".join(conditions)
        sql = f"SELECT * FROM {self._quoted_table} WHERE {where_clause}"
        cursor = await conn.execute(sql, values)
        rows = await cursor.fetchall()
        return [self._row_to_instance(row) for row in rows]

import_path property

import_path: str | None

Get the import path for the stored model, if available.

json_schema property

json_schema: dict[str, Any]

Get the JSON schema for the stored model.

model_type property

model_type: type[T]

The model class (original or reconstructed).

__aenter__ async

__aenter__() -> Self

Open connection and create/load table.

Source code in src/schemez/storage/model_store.py
async def __aenter__(self) -> Self:
    """Open connection and create/load table."""
    import aiosqlite

    conn = await aiosqlite.connect(self._path)
    conn.row_factory = aiosqlite.Row
    try:
        if self._model_type is None:
            # Opening existing DB - reconstruct model from schema
            await self._load_schema(conn)
        else:
            # Creating new or opening with known type
            await conn.execute(self._create_meta_table_sql())
            await conn.execute(self._create_table_sql())
            await self._store_schema(conn)
            await conn.commit()
    except BaseException:
        # __aexit__ won't run; an open connection's worker thread blocks exit
        await conn.close()
        raise
    self._connection = conn
    return self

__aexit__ async

__aexit__(
    exc_type: type[BaseException] | None, exc_val: BaseException | None, exc_tb: object
) -> None

Close connection.

Source code in src/schemez/storage/model_store.py
async def __aexit__(
    self,
    exc_type: type[BaseException] | None,
    exc_val: BaseException | None,
    exc_tb: object,
) -> None:
    """Close connection."""
    if self._connection:
        await self._connection.close()
        self._connection = None

__init__

__init__(
    model_type: type[T] | None = None,
    path: str | Path = ":memory:",
    table_name: str | None = None,
) -> None

Initialize the model store.

Parameters:

Name Type Description Default
model_type type[T] | None

The Pydantic model class to store (required for new DBs)

None
path str | Path

SQLite database path (":memory:" for in-memory)

':memory:'
table_name str | None

Custom table name (defaults to lowercase model name)

None

Raises:

Type Description
ValueError

If model_type is None and path doesn't exist or is :memory:

Source code in src/schemez/storage/model_store.py
def __init__(
    self,
    model_type: type[T] | None = None,
    path: str | Path = ":memory:",
    table_name: str | None = None,
) -> None:
    """Initialize the model store.

    Args:
        model_type: The Pydantic model class to store (required for new DBs)
        path: SQLite database path (":memory:" for in-memory)
        table_name: Custom table name (defaults to lowercase model name)

    Raises:
        ValueError: If model_type is None and path doesn't exist or is :memory:
    """
    self._path = str(path)
    self._connection: aiosqlite.Connection | None = None
    self._model_type: type[T] | None = model_type
    self._table_name = table_name
    self._columns: list[tuple[str, str, bool, Any]] | None = None
    self._import_path: str | None = None

    # Validate: can't create new DB without model_type
    if model_type is None:
        if self._path == ":memory:":
            msg = "model_type is required for in-memory databases"
            raise ValueError(msg)
        if not Path(self._path).exists():
            msg = f"model_type is required when database doesn't exist: {self._path}"
            raise ValueError(msg)
    else:
        self._table_name = table_name or model_type.__name__.lower()
        self._columns = self._build_column_definitions()
        module = model_type.__module__
        if module != "__main__":
            self._import_path = f"{module}.{model_type.__name__}"

all async

all() -> list[T]

Fetch all model instances.

Returns:

Type Description
list[T]

List of all model instances

Source code in src/schemez/storage/model_store.py
async def all(self) -> list[T]:
    """Fetch all model instances.

    Returns:
        List of all model instances
    """
    conn = self._ensure_connected()
    sql = f"SELECT * FROM {self._quoted_table}"
    cursor = await conn.execute(sql)
    rows = await cursor.fetchall()
    return [self._row_to_instance(row) for row in rows]

count async

count() -> int

Count total rows in the table.

Returns:

Type Description
int

Number of rows

Source code in src/schemez/storage/model_store.py
async def count(self) -> int:
    """Count total rows in the table.

    Returns:
        Number of rows
    """
    conn = self._ensure_connected()
    sql = f"SELECT COUNT(*) FROM {self._quoted_table}"
    cursor = await conn.execute(sql)
    row = await cursor.fetchone()
    return row[0] if row else 0

delete async

delete(row_id: int) -> bool

Delete a model instance by id.

Parameters:

Name Type Description Default
row_id int

The row id to delete

required

Returns:

Type Description
bool

True if a row was deleted, False otherwise

Source code in src/schemez/storage/model_store.py
async def delete(self, row_id: int) -> bool:
    """Delete a model instance by id.

    Args:
        row_id: The row id to delete

    Returns:
        True if a row was deleted, False otherwise
    """
    conn = self._ensure_connected()
    sql = f"DELETE FROM {self._quoted_table} WHERE id = ?"
    cursor = await conn.execute(sql, (row_id,))
    await conn.commit()
    return cursor.rowcount > 0

get async

get(row_id: int) -> T | None

Fetch a model instance by id.

Parameters:

Name Type Description Default
row_id int

The row id to fetch

required

Returns:

Type Description
T | None

The model instance, or None if not found

Source code in src/schemez/storage/model_store.py
async def get(self, row_id: int) -> T | None:
    """Fetch a model instance by id.

    Args:
        row_id: The row id to fetch

    Returns:
        The model instance, or None if not found
    """
    conn = self._ensure_connected()
    sql = f"SELECT * FROM {self._quoted_table} WHERE id = ?"
    cursor = await conn.execute(sql, (row_id,))
    row = await cursor.fetchone()
    if row is None:
        return None
    return self._row_to_instance(row)

insert async

insert(instance: T) -> int

Insert a model instance.

Parameters:

Name Type Description Default
instance T

The model instance to insert

required

Returns:

Type Description
int

The inserted row's id

Source code in src/schemez/storage/model_store.py
async def insert(self, instance: T) -> int:
    """Insert a model instance.

    Args:
        instance: The model instance to insert

    Returns:
        The inserted row's id
    """
    conn = self._ensure_connected()
    row_id = await self._insert_row(conn, instance)
    await conn.commit()
    return row_id

insert_many async

insert_many(instances: Sequence[T]) -> list[int]

Insert multiple model instances.

Parameters:

Name Type Description Default
instances Sequence[T]

The model instances to insert

required

Returns:

Type Description
list[int]

List of inserted row ids

Source code in src/schemez/storage/model_store.py
async def insert_many(self, instances: Sequence[T]) -> list[int]:
    """Insert multiple model instances.

    Args:
        instances: The model instances to insert

    Returns:
        List of inserted row ids
    """
    conn = self._ensure_connected()
    try:  # one transaction for all rows
        ids = [await self._insert_row(conn, instance) for instance in instances]
    except BaseException:
        await conn.rollback()
        raise
    await conn.commit()
    return ids

open async classmethod

open(path: str | Path) -> ModelStore[BaseModel]

Open an existing database and reconstruct the model from stored schema.

Parameters:

Name Type Description Default
path str | Path

Path to existing SQLite database

required

Returns:

Type Description
ModelStore[BaseModel]

ModelStore with reconstructed model type

Raises:

Type Description
FileNotFoundError

If database doesn't exist

ValueError

If database has no stored schema

Source code in src/schemez/storage/model_store.py
@classmethod
async def open(cls, path: str | Path) -> ModelStore[BaseModel]:
    """Open an existing database and reconstruct the model from stored schema.

    Args:
        path: Path to existing SQLite database

    Returns:
        ModelStore with reconstructed model type

    Raises:
        FileNotFoundError: If database doesn't exist
        ValueError: If database has no stored schema
    """
    path = Path(path)
    if not path.exists():
        msg = f"Database not found: {path}"
        raise FileNotFoundError(msg)

    return cls(model_type=None, path=path)  # ty: ignore[invalid-explicit-return]

query async

query(**filters: Any) -> list[T]

Query instances with simple equality filters.

Parameters:

Name Type Description Default
**filters Any

Field-value pairs for WHERE clause (equality only)

{}

Returns:

Type Description
list[T]

List of matching model instances

Example
users = await store.query(age=30, name="Alice")
Source code in src/schemez/storage/model_store.py
async def query(self, **filters: Any) -> list[T]:
    """Query instances with simple equality filters.

    Args:
        **filters: Field-value pairs for WHERE clause (equality only)

    Returns:
        List of matching model instances

    Example:
        ```python
        users = await store.query(age=30, name="Alice")
        ```
    """
    conn = self._ensure_connected()

    if not filters:
        return await self.all()

    if self._columns is None:
        msg = "Columns not initialized"
        raise RuntimeError(msg)

    # Build WHERE clause
    conditions = []
    values = []
    annotations = {name: ann for name, _, _, ann in self._columns}

    for field, value in filters.items():
        if field not in annotations:
            msg = f"Unknown field: {field}"
            raise ValueError(msg)
        if value is None:
            conditions.append(f"{_quote(field)} IS NULL")
            continue
        conditions.append(f"{_quote(field)} = ?")
        values.append(_serialize_value(value, annotations[field]))

    where_clause = " AND ".join(conditions)
    sql = f"SELECT * FROM {self._quoted_table} WHERE {where_clause}"
    cursor = await conn.execute(sql, values)
    rows = await cursor.fetchall()
    return [self._row_to_instance(row) for row in rows]