Files
sqlmodel-pg-kit/examples/01_sync_crud.py
2025-08-17 22:18:45 +08:00

52 lines
1.2 KiB
Python

"""
Sync CRUD examples using SQLModel and the kit's generic Repository.
Prereq:
- Export SQL_*/PG* env vars to point at your Postgres
- Run this file: uv run python examples/01_sync_crud.py
"""
from typing import Optional, List
from sqlmodel import SQLModel, Field
from sqlmodel_pg_kit import create_all, Repository
from sqlmodel_pg_kit.db import get_session
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(index=True)
age: Optional[int] = None
def main():
# Ensure tables exist
create_all()
repo = Repository(Hero)
with get_session() as s:
# Create
h = repo.create(s, {"name": "Alice", "age": 20})
print("Created:", h)
# Read by id
h2 = repo.get(s, h.id)
print("Fetched by id:", h2)
# Update
h3 = repo.update(s, h.id, age=21)
print("Updated:", h3)
# List (pagination)
page = repo.list(s, page=1, size=5)
print("List page=1,size=5 ->", [x.name for x in page])
# Delete
ok = repo.delete(s, h.id)
print("Deleted?", ok)
if __name__ == "__main__":
main()