:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(data-warehouse): apply warehouse sources queue migrations one statement at a time (#70472)
posthog[bot]074f706562e3
diff --git a/products/warehouse_sources_queue/backend/migrations/0001_initial.py b/products/warehouse_sources_queue/backend/migrations/0001_initial.pyindex 2c278263898f..10bb16914f85 100644--- a/products/warehouse_sources_queue/backend/migrations/0001_initial.py+++ b/products/warehouse_sources_queue/backend/migrations/0001_initial.py@@ -1,5 +1,7 @@# Generated by Django 4.2.29 on 2026-04-28+import datetime+import django.db.models.deletionfrom django.db import migrations, models@@ -9,7 +11,31 @@ from posthog.models.utils import uuid7PARTITIONS_AHEAD = 7+def _precreate_daily_partitions(schema_editor, parent_table):+ """Pre-create one daily range partition per day for today + next N days.++ Emitted as individual ``CREATE TABLE ... PARTITION OF`` statements from+ Python rather than a server-side ``DO`` block, so it applies against+ Postgres-wire targets that don't implement PL/pgSQL, ``generate_series``,+ or ``EXECUTE format(...)``.+ """+ today = datetime.date.today()+ for offset in range(PARTITIONS_AHEAD + 1):+ day = today + datetime.timedelta(days=offset)+ next_day = day + datetime.timedelta(days=1)+ suffix = day.strftime("%Y%m%d")+ schema_editor.execute(+ f"CREATE TABLE IF NOT EXISTS {parent_table}_{suffix} "+ f"PARTITION OF {parent_table} "+ f"FOR VALUES FROM ('{day.isoformat()}') TO ('{next_day.isoformat()}')"+ )++def _create_partitioned_tables(apps, schema_editor):+ # One statement per execute(): psycopg3 sends DDL over the extended query+ # protocol, which parses a single statement at a time. Multiple statements+ # crammed into one execute() fail against targets that reject trailing+ # tokens after the first statement.schema_editor.execute("""CREATE TABLE sourcebatch (id UUID NOT NULL DEFAULT gen_random_uuid(),@@ -33,13 +59,11 @@ def _create_partitioned_tables(apps, schema_editor):metadata JSONB NOT NULL DEFAULT '{}'::jsonb,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (id, created_at)- ) PARTITION BY RANGE (created_at);-- CREATE INDEX sb_team_schema_idx ON sourcebatch (team_id, schema_id);- CREATE INDEX sb_run_uuid_idx ON sourcebatch (run_uuid);-- CREATE TABLE sourcebatch_default PARTITION OF sourcebatch DEFAULT;+ ) PARTITION BY RANGE (created_at)""")+ schema_editor.execute("CREATE INDEX sb_team_schema_idx ON sourcebatch (team_id, schema_id)")+ schema_editor.execute("CREATE INDEX sb_run_uuid_idx ON sourcebatch (run_uuid)")+ schema_editor.execute("CREATE TABLE sourcebatch_default PARTITION OF sourcebatch DEFAULT")schema_editor.execute("""CREATE TABLE sourcebatchstatus (@@ -51,41 +75,15 @@ def _create_partitioned_tables(apps, schema_editor):error_response JSONB,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (id, created_at)- ) PARTITION BY RANGE (created_at);-- CREATE INDEX sbs_batch_id_desc_state_idx- ON sourcebatchstatus (batch_id, created_at DESC, id DESC, job_state);-- CREATE TABLE sourcebatchstatus_default PARTITION OF sourcebatchstatus DEFAULT;+ ) PARTITION BY RANGE (created_at)""")+ schema_editor.execute(+ "CREATE INDEX sbs_batch_id_desc_state_idx ON sourcebatchstatus (batch_id, created_at DESC, id DESC, job_state)"+ )+ schema_editor.execute("CREATE TABLE sourcebatchstatus_default PARTITION OF sourcebatchstatus DEFAULT")- # Pre-create daily partitions for today + next N days.- schema_editor.execute(f"""- DO $$- DECLARE- d DATE;- BEGIN- FOR d IN SELECT generate_series(- CURRENT_DATE,- CURRENT_DATE + {PARTITIONS_AHEAD},- '1 day'::interval- )::date- LOOP- EXECUTE format(- 'CREATE TABLE IF NOT EXISTS sourcebatch_%%s '- 'PARTITION OF sourcebatch '- 'FOR VALUES FROM (%%L) TO (%%L)',- to_char(d, 'YYYYMMDD'), d, d + 1- );- EXECUTE format(- 'CREATE TABLE IF NOT EXISTS sourcebatchstatus_%%s '- 'PARTITION OF sourcebatchstatus '- 'FOR VALUES FROM (%%L) TO (%%L)',- to_char(d, 'YYYYMMDD'), d, d + 1- );- END LOOP;- END $$;- """)+ _precreate_daily_partitions(schema_editor, "sourcebatch")+ _precreate_daily_partitions(schema_editor, "sourcebatchstatus")def _create_latest_status_view(apps, schema_editor):diff --git a/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.py b/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.pyindex 1e84109f8978..dfa993886322 100644--- a/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.py+++ b/products/warehouse_sources_queue/backend/migrations/0003_duckgres_sink.py@@ -1,3 +1,5 @@+import datetime+import django.db.models.managerimport django.db.models.deletionfrom django.db import migrations, models@@ -7,7 +9,31 @@ from posthog.models.utils import uuid7PARTITIONS_AHEAD = 7+def _precreate_daily_partitions(schema_editor, parent_table):+ """Pre-create one daily range partition per day for today + next N days.++ Emitted as individual ``CREATE TABLE ... PARTITION OF`` statements from+ Python rather than a server-side ``DO`` block, so it applies against+ Postgres-wire targets that don't implement PL/pgSQL, ``generate_series``,+ or ``EXECUTE format(...)``.+ """+ today = datetime.date.today()+ for offset in range(PARTITIONS_AHEAD + 1):+ day = today + datetime.timedelta(days=offset)+ next_day = day + datetime.timedelta(days=1)+ suffix = day.strftime("%Y%m%d")+ schema_editor.execute(+ f"CREATE TABLE IF NOT EXISTS {parent_table}_{suffix} "+ f"PARTITION OF {parent_table} "+ f"FOR VALUES FROM ('{day.isoformat()}') TO ('{next_day.isoformat()}')"+ )++def _create_duckgres_tables(apps, schema_editor):+ # One statement per execute(): psycopg3 sends DDL over the extended query+ # protocol, which parses a single statement at a time. Multiple statements+ # crammed into one execute() fail against targets that reject trailing+ # tokens after the first statement.schema_editor.execute("""CREATE TABLE sourcebatchduckgresstatus (id UUID NOT NULL DEFAULT gen_random_uuid(),@@ -18,13 +44,15 @@ def _create_duckgres_tables(apps, schema_editor):error_response JSONB,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),PRIMARY KEY (id, created_at)- ) PARTITION BY RANGE (created_at);-- CREATE INDEX sbdgs_batch_desc_state_idx- ON sourcebatchduckgresstatus (batch_id, created_at DESC, id DESC, job_state);-- CREATE TABLE sourcebatchduckgresstatus_default PARTITION OF sourcebatchduckgresstatus DEFAULT;+ ) PARTITION BY RANGE (created_at)""")+ schema_editor.execute(+ "CREATE INDEX sbdgs_batch_desc_state_idx "+ "ON sourcebatchduckgresstatus (batch_id, created_at DESC, id DESC, job_state)"+ )+ schema_editor.execute(+ "CREATE TABLE sourcebatchduckgresstatus_default PARTITION OF sourcebatchduckgresstatus DEFAULT"+ )schema_editor.execute("""CREATE TABLE sourcebatchduckgresapply (@@ -37,35 +65,12 @@ def _create_duckgres_tables(apps, schema_editor):row_count INT NOT NULL,created_at TIMESTAMPTZ NOT NULL DEFAULT now(),CONSTRAINT sbdga_unique_batch_apply UNIQUE (team_id, schema_id, run_uuid, batch_index)- );-- CREATE INDEX sbdga_run_idx- ON sourcebatchduckgresapply (team_id, schema_id, run_uuid);-- CREATE INDEX sbdga_team_id_idx- ON sourcebatchduckgresapply (team_id);+ )""")+ schema_editor.execute("CREATE INDEX sbdga_run_idx ON sourcebatchduckgresapply (team_id, schema_id, run_uuid)")+ schema_editor.execute("CREATE INDEX sbdga_team_id_idx ON sourcebatchduckgresapply (team_id)")- schema_editor.execute(f"""- DO $$- DECLARE- d DATE;- BEGIN- FOR d IN SELECT generate_series(- CURRENT_DATE,- CURRENT_DATE + {PARTITIONS_AHEAD},- '1 day'::interval- )::date- LOOP- EXECUTE format(- 'CREATE TABLE IF NOT EXISTS sourcebatchduckgresstatus_%%s '- 'PARTITION OF sourcebatchduckgresstatus '- 'FOR VALUES FROM (%%L) TO (%%L)',- to_char(d, 'YYYYMMDD'), d, d + 1- );- END LOOP;- END $$;- """)+ _precreate_daily_partitions(schema_editor, "sourcebatchduckgresstatus")def _create_latest_duckgres_status_view(apps, schema_editor):