"""presence hypertable Revision ID: e5c1f0a72b9d Revises: d4b9f2e6a1c7 Create Date: 2026-05-29 21:00:00.000000 """ from collections.abc import Sequence import sqlalchemy as sa from alembic import op from sqlalchemy.dialects import postgresql revision: str = "e5c1f0a72b9d" down_revision: str | None = "d4b9f2e6a1c7" branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None def upgrade() -> None: op.create_table( "presence", sa.Column("account_id", sa.Integer(), nullable=False), sa.Column("peer_id", sa.BigInteger(), nullable=False), sa.Column("ts", sa.DateTime(timezone=True), nullable=False), sa.Column("status", sa.String(), nullable=False), sa.Column("last_online_date", sa.DateTime(timezone=True), nullable=True), sa.Column("next_offline_date", sa.DateTime(timezone=True), nullable=True), sa.Column("raw", postgresql.JSONB(astext_type=sa.Text()), nullable=False), sa.PrimaryKeyConstraint("account_id", "peer_id", "ts"), ) op.execute( "SELECT create_hypertable('presence', by_range('ts', INTERVAL '1 week'))" ) op.execute( "ALTER TABLE presence SET (" "timescaledb.enable_columnstore = true, " "timescaledb.segmentby = 'peer_id', " "timescaledb.orderby = 'ts DESC')" ) op.execute("CALL add_columnstore_policy('presence', after => INTERVAL '30 days')") op.execute( "CREATE MATERIALIZED VIEW presence_hourly " "WITH (timescaledb.continuous) AS " "SELECT time_bucket('1 hour', ts) AS bucket, " "account_id, peer_id, " "count(*) AS samples, " "count(*) FILTER (WHERE status = 'online') AS online_samples, " "max(ts) AS last_seen " "FROM presence " "GROUP BY bucket, account_id, peer_id " "WITH NO DATA" ) op.execute( "SELECT add_continuous_aggregate_policy('presence_hourly', " "start_offset => INTERVAL '3 hours', " "end_offset => INTERVAL '1 hour', " "schedule_interval => INTERVAL '1 hour')" ) def downgrade() -> None: op.execute("DROP MATERIALIZED VIEW IF EXISTS presence_hourly") op.drop_table("presence")