Here’s a SwiftData-inspired Python API built on top of SQLite, mimicking SwiftData’s declarative @Model approach while keeping it lightweight. This example uses Python’s sqlite3 and dataclasses for simplicity.
SwiftData-like Python SQLite API
import sqlite3
from dataclasses import dataclass, field
from typing import List, Type, TypeVar, Any
import inspect
T = TypeVar('T')
# --- SwiftData-like Decorators ---
def Model(cls: Type[T]) -> Type[T]:
"""Decorator to mark a class as a persistable model (like @Model in SwiftData)."""
if not hasattr(cls, '__annotations__'):
raise ValueError(f"Class {cls.__name__} must use type annotations for fields.")
# Convert class to a dataclass (for easy field access)
cls = dataclass(cls)
# Register the model with the database
Database.register_model(cls)
return cls
# --- Database Core (Simplified SwiftData Container) ---
class Database:
_models: List[Type[Any]] = []
_connection: sqlite3.Connection = None
@classmethod
def register_model(cls, model: Type[Any]):
"""Register a model class and create its SQLite table."""
cls._models.append(model)
if cls._connection is None:
cls._connection = sqlite3.connect(":memory:") # Or a file path
# Generate SQL schema from the model's fields
fields = inspect.get_annotations(model)
columns = [f"{name} {_pytype_to_sqlite(type_)}" for name, type_ in fields.items()]
schema = f"CREATE TABLE IF NOT EXISTS {model.__name__} (id INTEGER PRIMARY KEY, {', '.join(columns)})"
cls._connection.execute(schema)
cls._connection.commit()
@classmethod
def context(cls):
"""Simulate SwiftData's modelContext for CRUD operations."""
return DatabaseContext(cls._connection)
# --- Context for Queries (Like SwiftData's modelContext) ---
class DatabaseContext:
def __init__(self, connection: sqlite3.Connection):
self.connection = connection
def insert(self, instance: Any):
"""Insert a model instance into SQLite."""
fields = inspect.get_annotations(type(instance))
columns = list(fields.keys())
values = [getattr(instance, col) for col in columns]
placeholders = ", ".join(["?"] * len(values))
query = f"INSERT INTO {type(instance).__name__} ({', '.join(columns)}) VALUES ({placeholders})"
self.connection.execute(query, values)
self.connection.commit()
def fetch_all(self, model: Type[T]) -> List[T]:
"""Fetch all rows for a model (simplified)."""
cursor = self.connection.execute(f"SELECT * FROM {model.__name__}")
rows = cursor.fetchall()
return [model(**dict(zip(inspect.get_annotations(model), row[1:]))) for row in rows]
# --- Helper ---
def _pytype_to_sqlite(pytype: type) -> str:
"""Map Python types to SQLite column types."""
if pytype == int:
return "INTEGER"
elif pytype == float:
return "REAL"
elif pytype == str:
return "TEXT"
elif pytype == bool:
return "INTEGER" # SQLite has no native BOOL
else:
return "TEXT" # Fallback