Server: basic implementation. Not tested => no python installed; bugfix in ESP (uvicorn on port 8090)

This commit is contained in:
Thomas Karner committed 2026-09-20 23:49:40 +02:00
1 parent 3694cdf207
commit 8a51e3d95e
38 files changed
+2442 -21

No files matched your search

+29
View File
@@ -0,0 +1,29 @@
"""All models, imported here so ``Base.metadata`` is complete.
Alembic's env.py and the drift test both rely on importing this one module.
"""
from .base import Base
from .captures import Capture, Observation, Tag, Taxon, capture_tags
from .devices import Device, DeviceCommand, DeviceStatus, Firmware
from .ops import AuditLog, BackupRun, Job, Setting
from .users import Session, User
__all__ = [
"AuditLog",
"BackupRun",
"Base",
"Capture",
"Device",
"DeviceCommand",
"DeviceStatus",
"Firmware",
"Job",
"Observation",
"Session",
"Setting",
"Tag",
"Taxon",
"User",
"capture_tags",
]
+19
View File
@@ -0,0 +1,19 @@
from __future__ import annotations
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase
# Explicit names for every constraint. Without this, Alembic autogenerate
# cannot drop or alter constraints Postgres named for itself, and migrations
# start needing hand-written DDL.
NAMING_CONVENTION = {
"ix": "ix_%(table_name)s_%(column_0_N_name)s",
"uq": "uq_%(table_name)s_%(column_0_N_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=NAMING_CONVENTION)
+190
View File
@@ -0,0 +1,190 @@
"""Captures, observations, taxonomy and tags.
Two structural decisions from SPEC 3, both load-bearing:
1. ``captures`` 1--n ``observations``. One photo can hold two species, and can
legitimately hold none (a false trigger, an empty frame). A single
``species`` column on the image would have to be undone later.
2. Human labels and model predictions share one table, separated by
``source``. The edit UI is therefore already the training-data pipeline for
any future detection model, with no migration when that day comes.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
Index,
Integer,
String,
Table,
Text,
Column,
Uuid,
func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
# API.md sends 'radar'; SPEC 3 predates the LD2410 decision and says 'pir'.
TRIGGERS = ("radar", "manual", "timer", "stream_grab")
class Capture(Base):
__tablename__ = "captures"
__table_args__ = (
CheckConstraint("trigger IN " + str(TRIGGERS), name="trigger_valid"),
Index("ix_captures_device_received", "device_id", "received_at"),
Index("ix_captures_burst", "burst_id", "burst_index"),
Index("ix_captures_triage", "kept", "reviewed", "received_at"),
)
# UUID rather than a serial, because it is also the filename:
# /srv/poorbird/images/2026/09/08/<uuid>.jpg (SPEC 3.3).
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
path: Mapped[str] = mapped_column(Text)
thumb_path: Mapped[str | None] = mapped_column(Text)
sha256: Mapped[str] = mapped_column(String(64), index=True)
width: Mapped[int | None] = mapped_column(Integer)
height: Mapped[int | None] = mapped_column(Integer)
bytes: Mapped[int] = mapped_column(BigInteger)
# NULL when the device clock was unsynced. X-Captured-At: 0 means unsynced,
# NOT 1970 -- never store an epoch date for it (API.md).
captured_at_device: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
# SPEC C7: authoritative, always.
received_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
trigger: Mapped[str] = mapped_column(String(16))
burst_id: Mapped[str | None] = mapped_column(String(64))
burst_index: Mapped[int | None] = mapped_column(Integer)
burst_count: Mapped[int | None] = mapped_column(Integer)
# SPEC 0 / API.md: this frame was captured BEFORE the trigger fired, out of
# the PSRAM ring. Usually the good ones -- the bird is still arriving.
pre_trigger: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
frame_seq: Mapped[int | None] = mapped_column(Integer)
radar_state: Mapped[int | None] = mapped_column(Integer) # 0 none 1 moving 2 stationary 3 both
radar_distance_cm: Mapped[int | None] = mapped_column(Integer)
radar_energy: Mapped[int | None] = mapped_column(Integer)
battery_mv: Mapped[int | None] = mapped_column(Integer)
rssi: Mapped[int | None] = mapped_column(Integer)
temp_c: Mapped[float | None] = mapped_column(Float)
reviewed: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
# Soft reject. Drives retention -- see TODO Phase 5 and open question 8.
kept: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
observations: Mapped[list[Observation]] = relationship(
back_populates="capture", cascade="all, delete-orphan"
)
tags: Mapped[list[Tag]] = relationship(secondary="capture_tags", back_populates="captures")
class Observation(Base):
__tablename__ = "observations"
__table_args__ = (
CheckConstraint("age IN ('adult', 'juvenile', 'unknown')", name="age_valid"),
CheckConstraint("sex IN ('male', 'female', 'unknown')", name="sex_valid"),
CheckConstraint(
"behaviour IN ('feeding', 'bathing', 'perching', 'nesting', 'fighting', 'other')",
name="behaviour_valid",
),
CheckConstraint(
"certainty IN ('certain', 'probable', 'uncertain')", name="certainty_valid"
),
CheckConstraint("source IN ('human', 'model')", name="source_valid"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
capture_id: Mapped[uuid.UUID] = mapped_column(
ForeignKey("captures.id", ondelete="CASCADE"), index=True
)
taxon_id: Mapped[int | None] = mapped_column(ForeignKey("taxa.id", ondelete="RESTRICT"))
individuals: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
age: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
sex: Mapped[str] = mapped_column(String(16), default="unknown", server_default="'unknown'")
behaviour: Mapped[str | None] = mapped_column(String(16))
certainty: Mapped[str] = mapped_column(
String(16), default="certain", server_default="'certain'"
)
notes: Mapped[str | None] = mapped_column(Text)
source: Mapped[str] = mapped_column(String(8), default="human", server_default="'human'")
# Populated only when source = 'model'. Schema is ready; the pipeline is
# explicitly not built (SPEC Option C).
model_version: Mapped[str | None] = mapped_column(String(64))
confidence: Mapped[float | None] = mapped_column(Float)
bbox: Mapped[dict | None] = mapped_column(JSONB)
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
)
capture: Mapped[Capture] = relationship(back_populates="observations")
taxon: Mapped[Taxon | None] = relationship()
class Taxon(Base):
"""Seeded, never free text.
This is what makes "species, biologically" real rather than a string
column that accumulates Kohlmeise, kohlmeise, Parus major and Kohlmeise?
as four distinct species (SPEC 3.2).
"""
__tablename__ = "taxa"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
gbif_key: Mapped[int | None] = mapped_column(BigInteger, unique=True)
scientific_name: Mapped[str] = mapped_column(String(128), unique=True)
name_de: Mapped[str | None] = mapped_column(String(128), index=True)
name_en: Mapped[str | None] = mapped_column(String(128), index=True)
family: Mapped[str | None] = mapped_column(String(64))
# "order" is reserved in SQL; SQLAlchemy quotes it.
order: Mapped[str | None] = mapped_column("order", String(64))
iucn_status: Mapped[str | None] = mapped_column(String(8))
# Ranks the autocomplete. The local garden list comes first.
is_local_common: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
class Tag(Base):
__tablename__ = "tags"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
label: Mapped[str] = mapped_column(String(64), unique=True)
colour: Mapped[str | None] = mapped_column(String(16))
captures: Mapped[list[Capture]] = relationship(secondary="capture_tags", back_populates="tags")
capture_tags = Table(
"capture_tags",
Base.metadata,
Column("capture_id", ForeignKey("captures.id", ondelete="CASCADE"), primary_key=True),
Column("tag_id", ForeignKey("tags.id", ondelete="CASCADE"), primary_key=True),
)
+227
View File
@@ -0,0 +1,227 @@
"""Devices, their command queue, their telemetry and the firmware images.
Field names follow firmware/API.md, which is the contract the firmware
actually implements. Where SPEC.md 3 and API.md disagree, API.md wins and the
difference is noted inline.
"""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import (
BigInteger,
Boolean,
CheckConstraint,
DateTime,
Float,
ForeignKey,
Index,
Integer,
String,
Text,
func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column, relationship
from .base import Base
COMMAND_TYPES = (
"apply_config",
"capture_now",
"report_status",
"wake_and_hold",
"sleep_now",
"stream_start",
"stream_stop",
"ota_update",
"reboot",
)
STATUS_REASONS = (
"heartbeat",
"periodic",
"after_event",
"before_sleep",
"before_night_sleep",
"on_request",
)
class Device(Base):
__tablename__ = "devices"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
# eFuse MAC in hex. Survives reflashing, which is what makes it an
# identity rather than a name (API.md, Enrollment).
device_uid: Mapped[str] = mapped_column(String(32), unique=True, index=True)
name: Mapped[str] = mapped_column(String(64))
mac: Mapped[str | None] = mapped_column(String(32))
hw_revision: Mapped[str | None] = mapped_column(String(64))
fw_version: Mapped[str | None] = mapped_column(String(32))
# Only the hash is stored. The token is high-entropy, so a fast hash is
# defensible here (API.md).
token_hash: Mapped[str | None] = mapped_column(String(128))
# Per-device re-enrollment credential, so a rotated token cannot strand a
# camera that has no USB access once mounted (SPEC 0).
reenroll_secret_hash: Mapped[str | None] = mapped_column(String(128))
# --- last-known conditions, denormalised from device_status for the list view
last_seen_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
battery_mv: Mapped[int | None] = mapped_column(Integer)
battery_pct: Mapped[int | None] = mapped_column(Integer)
# false means NOT MEASURED, not empty. No divider is wired by default.
# Render as an em dash, never as a low-battery alarm (API.md, SPEC 0).
battery_valid: Mapped[bool] = mapped_column(Boolean, default=False)
rssi: Mapped[int | None] = mapped_column(Integer)
temp_c: Mapped[float | None] = mapped_column(Float)
# Reported every heartbeat so the UI can show command latency honestly (SPEC 0).
awake: Mapped[bool] = mapped_column(Boolean, default=True)
# --- settings surface
# One JSONB document rather than forty columns. This mirrors GET /config
# exactly: every key is optional and the device merges and clamps partial
# documents, so a strict column-per-key schema would be a migration every
# time the firmware gains a tunable. The UI edits it as a form; validation
# lives in a Pydantic model, not in the DDL.
config: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
# The only thing the device compares. Bump on every config change.
config_version: Mapped[int] = mapped_column(Integer, default=1, server_default="1")
heartbeat_interval_s: Mapped[int] = mapped_column(Integer, default=300, server_default="300")
status_interval_s: Mapped[int] = mapped_column(Integer, default=900, server_default="900")
responsive_mode: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
enabled: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
commands: Mapped[list[DeviceCommand]] = relationship(
back_populates="device", cascade="all, delete-orphan"
)
class DeviceCommand(Base):
"""SPEC C1: the device is never pushed to, it drains this queue.
Commands ride along on the /ingest and /heartbeat response, so a capture
that was going to happen anyway also delivers the queue at no extra cost.
/status deliberately returns nothing actionable (API.md).
"""
__tablename__ = "device_commands"
__table_args__ = (
CheckConstraint(
"type IN " + str(COMMAND_TYPES),
name="type_valid",
),
CheckConstraint(
"ack_status IS NULL OR ack_status IN ('done', 'failed', 'rejected')",
name="ack_status_valid",
),
Index("ix_device_commands_pending", "device_id", "created_at"),
)
id: Mapped[int] = mapped_column(Integer, primary_key=True)
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
type: Mapped[str] = mapped_column(String(32))
payload: Mapped[dict | None] = mapped_column(JSONB)
created_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
acked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
ack_status: Mapped[str | None] = mapped_column(String(16))
result: Mapped[str | None] = mapped_column(Text)
expires_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
device: Mapped[Device] = relationship(back_populates="commands")
class Firmware(Base):
__tablename__ = "firmware"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
version: Mapped[str] = mapped_column(String(32), unique=True)
semver: Mapped[str | None] = mapped_column(String(32))
file_path: Mapped[str] = mapped_column(Text)
sha256: Mapped[str] = mapped_column(String(64))
size_bytes: Mapped[int] = mapped_column(BigInteger)
release_notes: Mapped[str | None] = mapped_column(Text)
# SPEC C6 / API.md: the device refuses to flash below this.
min_battery_pct: Mapped[int] = mapped_column(Integer, default=50, server_default="50")
uploaded_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
uploaded_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
is_target: Mapped[bool] = mapped_column(Boolean, default=False, server_default="false")
class DeviceStatus(Base):
"""Time series, one row per conditions report (SPEC 0).
The flat columns are the ones worth querying and charting. ``raw`` keeps
the whole posted body so nothing is lost when the firmware grows a field
before the server learns about it.
"""
__tablename__ = "device_status"
__table_args__ = (
CheckConstraint("reason IN " + str(STATUS_REASONS), name="reason_valid"),
Index("ix_device_status_device_at", "device_id", "at"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"))
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
reason: Mapped[str] = mapped_column(String(32))
battery_mv: Mapped[int | None] = mapped_column(Integer)
battery_pct: Mapped[int | None] = mapped_column(Integer)
battery_valid: Mapped[bool | None] = mapped_column(Boolean)
awake_ms: Mapped[int | None] = mapped_column(BigInteger)
boot_count: Mapped[int | None] = mapped_column(Integer)
wake_cause: Mapped[str | None] = mapped_column(String(16))
last_sleep_s: Mapped[int | None] = mapped_column(Integer)
total_sleep_s: Mapped[int | None] = mapped_column(BigInteger)
# The device's opinion, not the truth: these live in RTC memory and reset
# on power loss. `captures` is authoritative. Their real value is the GAP
# between captured and delivered, which is an upload-health signal.
captured_today: Mapped[int | None] = mapped_column(Integer)
delivered_today: Mapped[int | None] = mapped_column(Integer)
failed_today: Mapped[int | None] = mapped_column(Integer)
events_today: Mapped[int | None] = mapped_column(Integer)
# Days since epoch, local time; stays 0 until the clock syncs, so the
# pre-sync bucket is a phantom day. Do not chart it (API.md).
day_index: Mapped[int | None] = mapped_column(Integer)
is_night: Mapped[bool | None] = mapped_column(Boolean)
nightlight_on: Mapped[bool | None] = mapped_column(Boolean)
cam_profile: Mapped[str | None] = mapped_column(String(16))
# 0 here means no valid frame was decoded at any rate: wiring or a dead
# module, and worth an alert (API.md).
radar_baud: Mapped[int | None] = mapped_column(Integer)
radar_uart_ok: Mapped[bool | None] = mapped_column(Boolean)
stream_active: Mapped[bool | None] = mapped_column(Boolean)
rssi: Mapped[int | None] = mapped_column(Integer)
ip: Mapped[str | None] = mapped_column(String(45))
free_heap: Mapped[int | None] = mapped_column(BigInteger)
free_psram: Mapped[int | None] = mapped_column(BigInteger)
ring_depth: Mapped[int | None] = mapped_column(Integer)
time_synced: Mapped[bool | None] = mapped_column(Boolean)
device_time: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
fw_version: Mapped[str | None] = mapped_column(String(32))
config_version: Mapped[int | None] = mapped_column(Integer)
raw: Mapped[dict | None] = mapped_column(JSONB)
+112
View File
@@ -0,0 +1,112 @@
"""Operational tables: settings, audit log, backup runs, and the job queue."""
from __future__ import annotations
from datetime import datetime
from sqlalchemy import (
BigInteger,
CheckConstraint,
DateTime,
ForeignKey,
Index,
Integer,
String,
Text,
func,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
JOB_STATUSES = ("queued", "running", "done", "failed")
class Setting(Base):
"""SPEC 3.4. "Fully configurable" needs a boundary or it never finishes.
Server scope: retention policy, thumbnail size, backup schedule + target,
alarm thresholds and channels, default theme, default locale, session
lifetime. Anything not on that list is a code change, deliberately.
Backup schedule lives here rather than in a systemd timer, which is why
scheduling runs in the worker (TODO Phase 1.2).
"""
__tablename__ = "settings"
__table_args__ = (CheckConstraint("scope IN ('server', 'device')", name="scope_valid"),)
key: Mapped[str] = mapped_column(String(64), primary_key=True)
value: Mapped[str | None] = mapped_column(Text)
value_type: Mapped[str] = mapped_column(String(16), default="str", server_default="'str'")
scope: Mapped[str] = mapped_column(String(16), default="server", server_default="'server'")
updated_by: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now(), onupdate=func.now()
)
class AuditLog(Base):
__tablename__ = "audit_log"
__table_args__ = (Index("ix_audit_log_entity", "entity", "entity_id", "at"),)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
user_id: Mapped[int | None] = mapped_column(ForeignKey("users.id", ondelete="SET NULL"))
action: Mapped[str] = mapped_column(String(64))
entity: Mapped[str] = mapped_column(String(64))
entity_id: Mapped[str | None] = mapped_column(String(64))
before: Mapped[dict | None] = mapped_column(JSONB)
after: Mapped[dict | None] = mapped_column(JSONB)
ip: Mapped[str | None] = mapped_column(String(45))
class BackupRun(Base):
__tablename__ = "backup_runs"
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
started_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
status: Mapped[str] = mapped_column(String(16), default="running")
bytes: Mapped[int | None] = mapped_column(BigInteger)
snapshot_id: Mapped[str | None] = mapped_column(String(64))
# A backup you have never restored is a hypothesis: set by the monthly
# restore test (TODO Phase 5).
restore_tested_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
error: Mapped[str | None] = mapped_column(Text)
class Job(Base):
"""Postgres-backed queue, claimed with FOR UPDATE SKIP LOCKED. No Redis.
This second writer is the concrete reason SPEC C8 pushed past SQLite.
"""
__tablename__ = "jobs"
__table_args__ = (
CheckConstraint("status IN " + str(JOB_STATUSES), name="status_valid"),
# The claim query's covering index.
Index("ix_jobs_claimable", "status", "run_at", "priority"),
)
id: Mapped[int] = mapped_column(BigInteger, primary_key=True)
kind: Mapped[str] = mapped_column(String(64))
payload: Mapped[dict] = mapped_column(JSONB, default=dict, server_default="{}")
status: Mapped[str] = mapped_column(String(16), default="queued", server_default="'queued'")
priority: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
run_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), server_default=func.now())
attempts: Mapped[int] = mapped_column(Integer, default=0, server_default="0")
max_attempts: Mapped[int] = mapped_column(Integer, default=3, server_default="3")
locked_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
locked_by: Mapped[str | None] = mapped_column(String(128))
last_error: Mapped[str | None] = mapped_column(Text)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
+65
View File
@@ -0,0 +1,65 @@
"""Users and sessions.
Devices are NOT users (SPEC 3.1). A device authenticates with a bearer token
scoped to /ingest, /heartbeat, /status, /config, /commands/*/ack, /firmware/*
and /stream/*. It can never read the gallery.
"""
from __future__ import annotations
import uuid
from datetime import datetime
from sqlalchemy import (
Boolean,
CheckConstraint,
DateTime,
ForeignKey,
String,
Uuid,
func,
)
from sqlalchemy.orm import Mapped, mapped_column
from .base import Base
ROLES = ("admin", "editor", "viewer")
THEMES = ("light", "dark", "blue")
class User(Base):
__tablename__ = "users"
__table_args__ = (
CheckConstraint("role IN " + str(ROLES), name="role_valid"),
CheckConstraint("theme IN " + str(THEMES), name="theme_valid"),
)
id: Mapped[int] = mapped_column(primary_key=True)
username: Mapped[str] = mapped_column(String(64), unique=True)
email: Mapped[str | None] = mapped_column(String(255))
# Argon2id. Populated in Phase 3; nothing writes it yet.
password_hash: Mapped[str | None] = mapped_column(String(255))
role: Mapped[str] = mapped_column(String(16), default="viewer", server_default="'viewer'")
totp_secret: Mapped[str | None] = mapped_column(String(64))
is_active: Mapped[bool] = mapped_column(Boolean, default=True, server_default="true")
theme: Mapped[str] = mapped_column(String(16), default="light", server_default="'light'")
locale: Mapped[str] = mapped_column(String(8), default="de", server_default="'de'")
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
last_login_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True))
class Session(Base):
__tablename__ = "sessions"
id: Mapped[uuid.UUID] = mapped_column(Uuid(as_uuid=True), primary_key=True, default=uuid.uuid4)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True)
created_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True), server_default=func.now()
)
expires_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), index=True)
ip: Mapped[str | None] = mapped_column(String(45))
user_agent: Mapped[str | None] = mapped_column(String(255))