"""Database tables. profile ─┐ one row: baby name, birth date, timezone, display prefs event_kinds ─┬─ buttons what each of the 8 buttons means (editable) └─ events the log the parent sees and edits devices ─┬─ presses raw button presses exactly as the device sent them └─ device_reports one row per sync: battery, signal, clock skew... Presses are the device's append-only record (used to drop duplicate uploads); events are derived from them (or typed in by hand) and can be edited. A sleep start and stop are two presses but one event with started_at/ended_at. After changing anything here, create a migration: alembic revision --autogenerate -m "describe the change" """ from datetime import date, datetime, timedelta, timezone from typing import Any from sqlalchemy import ( JSON, Boolean, Date, DateTime, ForeignKey, Index, Integer, MetaData, SmallInteger, String, Text, UniqueConstraint, ) from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship from sqlalchemy.types import TypeDecorator def utcnow() -> datetime: return datetime.now(timezone.utc) class UTCDateTime(TypeDecorator): """Timezone-aware UTC datetimes on both Postgres and SQLite. SQLite has no timezone support, so values are stored as naive UTC there and turned back into aware datetimes on the way out. """ impl = DateTime(timezone=True) cache_ok = True def process_bind_param(self, value: datetime | None, dialect): # noqa: ANN001 if value is None: return None if value.tzinfo is None: raise ValueError("naive datetime given to a UTCDateTime column; attach a timezone") value = value.astimezone(timezone.utc) return value.replace(tzinfo=None) if dialect.name == "sqlite" else value def process_result_value(self, value: datetime | None, dialect): # noqa: ANN001 if value is None: return None if value.tzinfo is None: return value.replace(tzinfo=timezone.utc) return value.astimezone(timezone.utc) def alembic_render_item(type_, obj, autogen_context): # noqa: ANN001, ANN201 """Write UTCDateTime into migration files as a plain timestamp column, so migrations don't depend on app code that may change later.""" if type_ == "type" and isinstance(obj, UTCDateTime): return "sa.DateTime(timezone=True)" return False def alembic_compare_type(context, inspected_column, metadata_column, inspected_type, metadata_type): # noqa: ANN001, ANN201 if isinstance(metadata_type, UTCDateTime) and isinstance(inspected_type, DateTime): return False return None class Base(DeclarativeBase): # Predictable constraint names make migrations (and SQLite batch mode) reliable. metadata = MetaData( naming_convention={ "ix": "ix_%(column_0_label)s", "uq": "uq_%(table_name)s_%(column_0_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 Profile(Base): """The baby and the family's display preferences. Always exactly one row (id=1).""" __tablename__ = "profile" id: Mapped[int] = mapped_column(Integer, primary_key=True) baby_name: Mapped[str] = mapped_column(String(80), default="Baby") birth_date: Mapped[date | None] = mapped_column(Date) timezone: Mapped[str] = mapped_column(String(64), default="UTC") clock_24h: Mapped[bool] = mapped_column(Boolean, default=False) # How often the device should sync, sent to it in every sync response. sync_interval_min: Mapped[int] = mapped_column(Integer, default=60) updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, onupdate=utcnow) class Kind(Base): """A type of event: "Wet diaper", "Sleep"... Kinds are never deleted, only hidden.""" __tablename__ = "event_kinds" slug: Mapped[str] = mapped_column(String(32), primary_key=True) label: Mapped[str] = mapped_column(String(40)) # Up to 10 characters, for the device's 200x200 e-paper. short: Mapped[str] = mapped_column(String(12)) emoji: Mapped[str] = mapped_column(String(16), default="") # sleep | feeding | diaper | pump | health | activity | other (see catalog.py) category: Mapped[str] = mapped_column(String(16)) # "instant": one press = one event. # "duration": first press starts it, next press ends it (sleep, tummy time). mode: Mapped[str] = mapped_column(String(10), default="instant") # For duration kinds: a start older than this is treated as forgotten, so the # next press starts a new session instead of ending a 2-day "nap". max_minutes: Mapped[int | None] = mapped_column(Integer) sort_order: Mapped[int] = mapped_column(Integer, default=0) active: Mapped[bool] = mapped_column(Boolean, default=True) @property def is_duration(self) -> bool: return self.mode == "duration" @property def max_duration(self) -> timedelta | None: return timedelta(minutes=self.max_minutes) if self.max_minutes else None class ButtonMap(Base): """Which kind each physical button (1-8) logs.""" __tablename__ = "buttons" button: Mapped[int] = mapped_column(SmallInteger, primary_key=True, autoincrement=False) kind_slug: Mapped[str | None] = mapped_column( ForeignKey("event_kinds.slug", ondelete="SET NULL", onupdate="CASCADE") ) kind: Mapped[Kind | None] = relationship(lazy="joined") class Device(Base): __tablename__ = "devices" id: Mapped[int] = mapped_column(Integer, primary_key=True) name: Mapped[str] = mapped_column(String(80)) # SHA-256 of the device's API token. The token itself is never stored. token_hash: Mapped[str] = mapped_column(String(64), unique=True) token_hint: Mapped[str] = mapped_column(String(12), default="") created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) revoked_at: Mapped[datetime | None] = mapped_column(UTCDateTime) # Latest state, copied from the most recent sync. last_seen_at: Mapped[datetime | None] = mapped_column(UTCDateTime) firmware: Mapped[str | None] = mapped_column(String(32)) battery_mv: Mapped[int | None] = mapped_column(Integer) charging: Mapped[bool | None] = mapped_column(Boolean) rssi: Mapped[int | None] = mapped_column(SmallInteger) clock_skew_s: Mapped[int | None] = mapped_column(Integer) boot_count: Mapped[int | None] = mapped_column(Integer) @property def active(self) -> bool: return self.revoked_at is None class DeviceReport(Base): """One row per sync. Battery voltage over weeks shows real battery life.""" __tablename__ = "device_reports" id: Mapped[int] = mapped_column(Integer, primary_key=True) device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE"), index=True) received_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, index=True) firmware: Mapped[str | None] = mapped_column(String(32)) battery_mv: Mapped[int | None] = mapped_column(Integer) charging: Mapped[bool | None] = mapped_column(Boolean) rssi: Mapped[int | None] = mapped_column(SmallInteger) clock_skew_s: Mapped[int | None] = mapped_column(Integer) boot_count: Mapped[int | None] = mapped_column(Integer) queue_len: Mapped[int | None] = mapped_column(Integer) events_received: Mapped[int] = mapped_column(Integer, default=0) events_new: Mapped[int] = mapped_column(Integer, default=0) duration_ms: Mapped[int | None] = mapped_column(Integer) extra: Mapped[dict[str, Any] | None] = mapped_column(JSON) class Event(Base): """One thing that happened to the baby. Duration kinds have an end time.""" __tablename__ = "events" __table_args__ = (Index("ix_events_kind_open", "kind_slug", "ended_at"),) id: Mapped[int] = mapped_column(Integer, primary_key=True) kind_slug: Mapped[str] = mapped_column( ForeignKey("event_kinds.slug", onupdate="CASCADE"), index=True ) started_at: Mapped[datetime] = mapped_column(UTCDateTime, index=True) ended_at: Mapped[datetime | None] = mapped_column(UTCDateTime) note: Mapped[str | None] = mapped_column(Text) source: Mapped[str] = mapped_column(String(8), default="manual") # device | manual device_id: Mapped[int | None] = mapped_column(ForeignKey("devices.id", ondelete="SET NULL")) button: Mapped[int | None] = mapped_column(SmallInteger) # True when the device's clock was wrong and the server shifted the time. clock_corrected: Mapped[bool] = mapped_column(Boolean, default=False) created_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) updated_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow, onupdate=utcnow) # Soft delete, so "Undo" works and nothing is lost to a mis-tap at 3 a.m. deleted_at: Mapped[datetime | None] = mapped_column(UTCDateTime, index=True) kind: Mapped[Kind] = relationship(lazy="joined") @property def is_open(self) -> bool: return self.kind.is_duration and self.ended_at is None @property def duration(self) -> timedelta | None: if self.ended_at is None: return None return self.ended_at - self.started_at class Press(Base): """A button press exactly as uploaded. Append-only. (device_id, seq, device_time) identifies a press: a retried upload repeats all three and is ignored. The time is part of the key so a device whose sequence counter restarts at 1 (reflash, erased flash) isn't mistaken for a replay of old presses. """ __tablename__ = "presses" __table_args__ = ( UniqueConstraint("device_id", "seq", "device_time", name="uq_presses_identity"), ) id: Mapped[int] = mapped_column(Integer, primary_key=True) device_id: Mapped[int] = mapped_column(ForeignKey("devices.id", ondelete="CASCADE")) seq: Mapped[int] = mapped_column(Integer) button: Mapped[int] = mapped_column(SmallInteger) device_time: Mapped[datetime] = mapped_column(UTCDateTime) # as the device's RTC said occurred_at: Mapped[datetime] = mapped_column(UTCDateTime) # after clock correction received_at: Mapped[datetime] = mapped_column(UTCDateTime, default=utcnow) clock_corrected: Mapped[bool] = mapped_column(Boolean, default=False) # instant | start | end: what this press did to the event log. role: Mapped[str] = mapped_column(String(8), default="instant") event_id: Mapped[int | None] = mapped_column(ForeignKey("events.id", ondelete="SET NULL"))