Automated Database Schema Migrations with Alembic & TimescaleDB

Note

  • Published: December 2, 2026

  • Authors: Written by Gemini 3.8 Flash, Co-Authored & Reviewed by Carlos Santos (@carlkidcrypto)

  • Estimated Reading Time: 7 minutes

  • Tags: PurpleAir • Alembic • TimescaleDB • PostgreSQL • Migrations • Python

When purpleair_data_logger (published on PyPI as purpleair-data-logger) first initializes your PostgreSQL database, PurpleAirPSQLDataLogger automatically provisions tables, TimescaleDB hypertables, compression policies, and continuous aggregates.

Over months of production operation, however, environmental telemetry requirements evolve. You might need to add new columns (such as VOC index or PM4.0 channels), add composite indexes for Grafana, or adjust chunk compression settings—all without dropping historical data or halting active edge sensor ingestion.

Running ad-hoc ALTER TABLE statements manually across staging and production databases invites schema drift. Alembic brings version-controlled, repeatable database migrations to Python pipelines and works cleanly alongside pg8000 and TimescaleDB hypertables when configured carefully.

In this tutorial, we will configure Alembic with the postgresql+pg8000 driver, author safe non-blocking migrations for compressed TimescaleDB hypertables, and automate pre-flight schema upgrades in CI/CD.

Configuring Alembic for pg8000 & TimescaleDB

Because purpleair_data_logger uses pg8000 as its pure-Python PostgreSQL driver, configure Alembic’s sqlalchemy.url in alembic.ini or env.py to use the postgresql+pg8000:// dialect:

pip install alembic sqlalchemy pg8000
alembic init migrations

In migrations/env.py, read database credentials from environment variables rather than hardcoding secrets in alembic.ini:

import os
from alembic import context
from sqlalchemy import engine_from_config, pool

config = context.config

db_url = (
    f"postgresql+pg8000://{os.environ['DB_USER']}:"
    f"{os.environ['DB_PASSWORD']}@"
    f"{os.environ.get('DB_HOST', 'localhost')}:"
    f"{os.environ.get('DB_PORT', '5432')}/"
    f"{os.environ.get('DB_NAME', 'airquality')}"
)
config.set_main_option("sqlalchemy.url", db_url)

📥 Download this script: 01_configuring_alembic_for_pg8000_timescale.py

Writing Safe Hypertable Migrations

Standard PostgreSQL ALTER TABLE ... ADD COLUMN (with a NULL default or constant non-volatile default in PostgreSQL 11+) is metadata-only and instantaneous on ordinary tables. On compressed TimescaleDB hypertables, however, you must follow specific ordering rules so compressed chunks remain consistent.

Adding Columns & Indexes Without Downtime

  1. Use ``IF NOT EXISTS`` and Non-Blocking Index Creation:

    • Creating a standard index acquires a SHARE lock that blocks INSERT batches from active purpleair_data_logger workers.

    • Use autocommit_block() inside Alembic to run CREATE INDEX CONCURRENTLY on standard PostgreSQL tables without blocking ingestion (for large multi-chunk TimescaleDB hypertables, use WITH (timescaledb.transaction_per_chunk) so each chunk builds its index in an independent transaction).

  2. Avoid Expensive Table Rewrites:

    • Adding a nullable REAL column (such as voc_index) propagates cleanly across hypertable chunks without decompressing old segments.

Here is an example Alembic revision adding a voc_index column and a concurrent index:

'''add voc_index and sensor confidence index'''

from alembic import op
import sqlalchemy as sa

revision = "20261202_01"
down_revision = "20261101_01"
branch_labels = None
depends_on = None

def upgrade() -> None:
    op.execute(
        '''
        ALTER TABLE purpleair_sensor_data
        ADD COLUMN IF NOT EXISTS voc_index REAL;
        '''
    )
    # Build index without blocking concurrent sensor inserts
    with op.get_context().autocommit_block():
        op.execute(
            '''
            CREATE INDEX CONCURRENTLY IF NOT EXISTS
            idx_purpleair_conf_time
            ON purpleair_sensor_data (confidence, time_stamp DESC);
            '''
        )

def downgrade() -> None:
    with op.get_context().autocommit_block():
        op.execute(
            "DROP INDEX CONCURRENTLY IF EXISTS idx_purpleair_conf_time;"
        )
    op.execute(
        '''
        ALTER TABLE purpleair_sensor_data
        DROP COLUMN IF EXISTS voc_index;
        '''
    )

📥 Download this script: 02_downgrade.py

Updating Continuous Aggregates Safely

TimescaleDB continuous aggregates do not support in-place ALTER VIEW for adding new aggregate columns. When adding a new metric to an existing summary view:

  1. Create the new materialized view version (e.g. purpleair_hourly_summary_v2) with its refresh policy.

  2. Backfill the new view using CALL refresh_continuous_aggregate(...).

  3. Switch Grafana dashboards or application queries to _v2 before dropping the legacy view in a subsequent migration.

Automating Migrations in Docker Entrypoints

When deploying containerized purpleair_data_logger collectors, run alembic upgrade head as a dedicated init step or pre-start hook before launching the polling loop:

#!/usr/bin/env bash
set -euo pipefail

echo "[*] Applying pending database migrations..."
alembic upgrade head

echo "[*] Starting purpleair_data_logger collector..."
exec purpleair_data_logger --config /config/settings.json

Summary & What’s Next

Pairing Alembic with postgresql+pg8000 and lock-safe CONCURRENTLY patterns keeps your purpleair_data_logger TimescaleDB schema versioned, auditable, and upgradeable with zero ingestion downtime.

In our next blog post, we will rotate to purpleair-matterbridge, exploring automated CI/CD testing and Matter controller mock validation for Matterbridge plugins in GitHub Actions.


Warning

AI-generated content may contain misinformation or mistakes. A human does review this, but we are only human.