File size: 2,206 Bytes
e391a84 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 | """
infrastructure/database/models/base.py
βββββββββββββββββββββββββββββββββββββββ
Shared SQLAlchemy declarative base β Supabase / PostgreSQL ready.
All ORM models inherit from ``Base``, which automatically provides:
β’ ``id`` β native UUID primary key (PostgreSQL UUID type, auto-generated)
β’ ``created_at`` β UTC timestamp set by the DB on INSERT
β’ ``updated_at`` β UTC timestamp updated by the DB on every UPDATE
DRY: defined once here, inherited by every model.
Supabase note:
PostgreSQL's native UUID type is used instead of VARCHAR(36) for better
index performance and storage efficiency. The ``server_default`` for UUIDs
uses gen_random_uuid() which is natively available on PostgreSQL β₯ 13
(Supabase uses PostgreSQL 15).
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import DateTime, func, text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
class Base(DeclarativeBase):
"""
Declarative base for all SQLAlchemy ORM models.
Shared columns (auto-injected into every subclass):
id: UUID primary key β generated by PostgreSQL gen_random_uuid().
created_at: TIMESTAMP WITH TIME ZONE β set by the DB on INSERT.
updated_at: TIMESTAMP WITH TIME ZONE β updated by the DB on every UPDATE.
"""
id: Mapped[str] = mapped_column(
UUID(as_uuid=False), # Store as str; no Python uuid.UUID coercion needed
primary_key=True,
server_default=text("gen_random_uuid()"),
comment="UUID primary key β generated by PostgreSQL",
)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
nullable=False,
comment="UTC timestamp of record creation (set by DB)",
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
server_default=func.now(),
onupdate=func.now(),
nullable=False,
comment="UTC timestamp of last update (maintained by DB)",
)
|