Skip to main content

micromegas_analytics/lakehouse/
migration.rs

1use crate::arrow_utils::parse_parquet_metadata;
2use crate::lakehouse::log_stats_view::{log_stats_ddl_text, log_stats_view_definition};
3use anyhow::{Context, Result};
4use micromegas_ingestion::remote_data_lake::acquire_lock;
5use micromegas_tracing::prelude::*;
6use sqlx::Executor;
7use sqlx::Row;
8
9pub const LATEST_LAKEHOUSE_SCHEMA_VERSION: i32 = 12;
10
11async fn read_lakehouse_schema_version(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> i32 {
12    match sqlx::query(
13        "SELECT version
14         FROM lakehouse_migration;",
15    )
16    .fetch_one(&mut **tr)
17    .await
18    {
19        Ok(row) => row.get("version"),
20        Err(e) => {
21            info!(
22                "Error reading data lake schema version, assuming version 0: {}",
23                e
24            );
25            0
26        }
27    }
28}
29
30/// Migrates the lakehouse schema to the latest version.
31pub async fn migrate_lakehouse(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
32    let mut tr = pool.begin().await?;
33    let mut current_version = read_lakehouse_schema_version(&mut tr).await;
34    drop(tr);
35    info!("current lakehouse schema: {}", current_version);
36    if current_version != LATEST_LAKEHOUSE_SCHEMA_VERSION {
37        let mut tr = pool.begin().await?;
38        acquire_lock(&mut tr, 1).await?;
39        current_version = read_lakehouse_schema_version(&mut pool.begin().await?).await;
40        if LATEST_LAKEHOUSE_SCHEMA_VERSION == current_version {
41            return Ok(());
42        }
43        if let Err(e) = execute_lakehouse_migration(pool.clone()).await {
44            error!("Error migrating database: {}", e);
45            return Err(e);
46        }
47        current_version = read_lakehouse_schema_version(&mut tr).await;
48    }
49    assert_eq!(current_version, LATEST_LAKEHOUSE_SCHEMA_VERSION);
50    Ok(())
51}
52
53/// Executes the lakehouse migration steps.
54async fn execute_lakehouse_migration(pool: sqlx::Pool<sqlx::Postgres>) -> Result<()> {
55    let mut current_version = read_lakehouse_schema_version(&mut pool.begin().await?).await;
56    if 0 == current_version {
57        info!("creating v1 lakehouse_schema");
58        let mut tr = pool.begin().await?;
59        create_tables(&mut tr).await?;
60        current_version = read_lakehouse_schema_version(&mut tr).await;
61        tr.commit().await?;
62    }
63    if 1 == current_version {
64        info!("upgrade lakehouse schema to v2");
65        let mut tr = pool.begin().await?;
66        upgrade_v1_to_v2(&mut tr).await?;
67        current_version = read_lakehouse_schema_version(&mut tr).await;
68        tr.commit().await?;
69    }
70    if 2 == current_version {
71        info!("upgrade lakehouse schema to v3");
72        let mut tr = pool.begin().await?;
73        upgrade_v2_to_v3(&mut tr).await?;
74        current_version = read_lakehouse_schema_version(&mut tr).await;
75        tr.commit().await?;
76    }
77    if 3 == current_version {
78        info!("upgrade lakehouse schema to v4");
79        let mut tr = pool.begin().await?;
80        upgrade_v3_to_v4(&mut tr).await?;
81        current_version = read_lakehouse_schema_version(&mut tr).await;
82        tr.commit().await?;
83    }
84    if 4 == current_version {
85        info!("upgrade lakehouse schema to v5");
86        let mut tr = pool.begin().await?;
87        upgrade_v4_to_v5(&mut tr).await?;
88        current_version = read_lakehouse_schema_version(&mut tr).await;
89        tr.commit().await?;
90    }
91    if 5 == current_version {
92        info!("upgrade lakehouse schema to v6");
93        let mut tr = pool.begin().await?;
94        upgrade_v5_to_v6(&mut tr).await?;
95        current_version = read_lakehouse_schema_version(&mut tr).await;
96        tr.commit().await?;
97    }
98    if 6 == current_version {
99        info!("upgrade lakehouse schema to v7");
100        let mut tr = pool.begin().await?;
101        upgrade_v6_to_v7(&mut tr).await?;
102        current_version = read_lakehouse_schema_version(&mut tr).await;
103        tr.commit().await?;
104    }
105    if 7 == current_version {
106        info!("upgrade lakehouse schema to v8");
107        let mut tr = pool.begin().await?;
108        upgrade_v7_to_v8(&mut tr).await?;
109        current_version = read_lakehouse_schema_version(&mut tr).await;
110        tr.commit().await?;
111    }
112    if 8 == current_version {
113        info!("upgrade lakehouse schema to v9");
114        let mut tr = pool.begin().await?;
115        upgrade_v8_to_v9(&mut tr).await?;
116        current_version = read_lakehouse_schema_version(&mut tr).await;
117        tr.commit().await?;
118    }
119    if 9 == current_version {
120        info!("upgrade lakehouse schema to v10");
121        let mut tr = pool.begin().await?;
122        upgrade_v9_to_v10(&mut tr).await?;
123        current_version = read_lakehouse_schema_version(&mut tr).await;
124        tr.commit().await?;
125    }
126    if 10 == current_version {
127        info!("upgrade lakehouse schema to v11");
128        let mut tr = pool.begin().await?;
129        upgrade_v10_to_v11(&mut tr).await?;
130        current_version = read_lakehouse_schema_version(&mut tr).await;
131        tr.commit().await?;
132    }
133    if 11 == current_version {
134        info!("upgrade lakehouse schema to v12");
135        let mut tr = pool.begin().await?;
136        upgrade_v11_to_v12(&mut tr).await?;
137        current_version = read_lakehouse_schema_version(&mut tr).await;
138        tr.commit().await?;
139    }
140    assert_eq!(current_version, LATEST_LAKEHOUSE_SCHEMA_VERSION);
141    Ok(())
142}
143
144async fn create_partitions_table(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
145    // Every table in the set shares the same schema - that schema can change over time, in which case the partition has to be rebuilt.
146    // The instance id is a unique key to the table within the table set.
147    //    * Example 1: if there is a process_log table for each process, the instance id could be the process_id.
148    //      It would not clash with an instance of process_metrics table for the same process.
149    //    * Example 2:  if there is a table instance for each metric, the view_instance_id could be the name of the metric.
150
151    // source_data_hash can be used to detect that the partition is out of date (sha1 of the block_ids, for example)
152    tr.execute("
153         CREATE TABLE lakehouse_partitions(
154                  view_set_name VARCHAR(255),
155                  view_instance_id VARCHAR(255),
156                  begin_insert_time TIMESTAMPTZ,
157                  end_insert_time TIMESTAMPTZ,
158                  min_event_time TIMESTAMPTZ,
159                  max_event_time TIMESTAMPTZ,
160                  updated TIMESTAMPTZ,
161                  file_path VARCHAR(2047),
162                  file_size BIGINT,
163                  file_schema_hash bytea,
164                  source_data_hash bytea
165                  );
166         CREATE INDEX lh_part_begin_insert on lakehouse_partitions(view_set_name, view_instance_id, begin_insert_time);
167         CREATE INDEX lh_part_end_insert on lakehouse_partitions(view_set_name, view_instance_id, end_insert_time);
168         CREATE INDEX lh_part_min_time on lakehouse_partitions(view_set_name, view_instance_id, min_event_time);
169         CREATE INDEX lh_part_max_time on lakehouse_partitions(view_set_name, view_instance_id, max_event_time);
170")
171        .await
172        .with_context(|| "Creating table blocks and its indices")?;
173    Ok(())
174}
175
176async fn create_temp_files_table(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
177    // partitions that are out of date can still be referenced until they expire
178    tr.execute(
179        "
180         CREATE TABLE temporary_files(
181                  file_path VARCHAR(2047),
182                  file_size BIGINT,
183                  expiration TIMESTAMPTZ );
184         CREATE INDEX temporary_files_expiration on temporary_files(expiration);
185",
186    )
187    .await
188    .with_context(|| "Creating temporary_files table")?;
189    Ok(())
190}
191
192async fn create_migration_table(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
193    sqlx::query("CREATE table lakehouse_migration(version integer);")
194        .execute(&mut **tr)
195        .await
196        .with_context(|| "Creating table lakehouse_migration")?;
197    sqlx::query("INSERT INTO lakehouse_migration VALUES(1);")
198        .execute(&mut **tr)
199        .await
200        .with_context(|| "Recording the initial lakehouse schema version")?;
201    Ok(())
202}
203
204async fn create_tables(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
205    create_partitions_table(tr).await?;
206    create_temp_files_table(tr).await?;
207    create_migration_table(tr).await?;
208    Ok(())
209}
210
211async fn upgrade_v1_to_v2(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
212    // file_metadata is meant to be the serialized ParquetMetaData
213    // which can be found in the footer of the file
214    tr.execute("ALTER TABLE lakehouse_partitions ADD file_metadata bytea;")
215        .await
216        .with_context(|| "adding column file_metadata to lakehouse_partitions table")?;
217    tr.execute("UPDATE lakehouse_migration SET version=2;")
218        .await
219        .with_context(|| "Updating lakehouse schema version to 2")?;
220    Ok(())
221}
222
223async fn upgrade_v2_to_v3(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
224    // Add num_rows column to store row count separately from file_metadata
225    tr.execute("ALTER TABLE lakehouse_partitions ADD num_rows BIGINT;")
226        .await
227        .with_context(|| "adding column num_rows to lakehouse_partitions table")?;
228
229    // Add index on file_path for efficient on-demand metadata loading
230    tr.execute("CREATE INDEX lakehouse_partitions_file_path ON lakehouse_partitions(file_path);")
231        .await
232        .with_context(|| "creating index on file_path")?;
233
234    // Populate num_rows column for existing partitions
235    populate_num_rows_column(tr)
236        .await
237        .with_context(|| "populating num_rows column")?;
238
239    // Make num_rows NOT NULL after populating existing data
240    tr.execute("ALTER TABLE lakehouse_partitions ALTER COLUMN num_rows SET NOT NULL;")
241        .await
242        .with_context(|| "setting num_rows column to NOT NULL")?;
243
244    tr.execute("UPDATE lakehouse_migration SET version=3;")
245        .await
246        .with_context(|| "Updating lakehouse schema version to 3")?;
247    Ok(())
248}
249
250async fn populate_num_rows_column(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
251    info!("populating num_rows column for existing partitions");
252
253    let mut total_count = 0;
254    let batch_size = 1000;
255
256    loop {
257        // Fetch partitions in batches to avoid loading all metadata into memory
258        let rows = sqlx::query("SELECT file_path, file_metadata FROM lakehouse_partitions WHERE file_metadata IS NOT NULL AND num_rows IS NULL LIMIT $1")
259            .bind(batch_size)
260            .fetch_all(&mut **tr)
261            .await?;
262
263        if rows.is_empty() {
264            break;
265        }
266
267        let mut batch_count = 0;
268        for row in rows {
269            let file_path: String = row.try_get("file_path")?;
270            let file_metadata_buffer: Vec<u8> = row.try_get("file_metadata")?;
271
272            // Parse metadata only for this partition
273            match parse_parquet_metadata(&file_metadata_buffer.into()) {
274                Ok(file_metadata) => {
275                    let num_rows = file_metadata.file_metadata().num_rows();
276
277                    // Update just this partition
278                    if let Err(e) = sqlx::query(
279                        "UPDATE lakehouse_partitions SET num_rows = $1 WHERE file_path = $2",
280                    )
281                    .bind(num_rows)
282                    .bind(&file_path)
283                    .execute(&mut **tr)
284                    .await
285                    {
286                        error!(
287                            "failed to update num_rows for partition {}: {}",
288                            file_path, e
289                        );
290                        continue;
291                    }
292
293                    batch_count += 1;
294                }
295                Err(e) => {
296                    error!(
297                        "failed to parse metadata for partition {}: {}",
298                        file_path, e
299                    );
300                    // For partitions with unparseable metadata, set num_rows to 0 as a fallback
301                    if let Err(e2) = sqlx::query(
302                        "UPDATE lakehouse_partitions SET num_rows = 0 WHERE file_path = $1",
303                    )
304                    .bind(&file_path)
305                    .execute(&mut **tr)
306                    .await
307                    {
308                        error!(
309                            "failed to set fallback num_rows for partition {}: {}",
310                            file_path, e2
311                        );
312                    }
313                }
314            }
315        }
316
317        total_count += batch_count;
318        info!(
319            "populated num_rows for {} partitions (total: {})",
320            batch_count, total_count
321        );
322    }
323
324    info!("populated num_rows for {} total partitions", total_count);
325    Ok(())
326}
327
328async fn upgrade_v3_to_v4(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
329    // Create dedicated partition_metadata table
330    tr.execute(
331        "CREATE TABLE partition_metadata(
332            file_path VARCHAR(2047) PRIMARY KEY,
333            metadata bytea NOT NULL,
334            insert_time TIMESTAMPTZ NOT NULL
335        );",
336    )
337    .await
338    .with_context(|| "creating partition_metadata table")?;
339
340    // Migrate existing metadata from lakehouse_partitions to partition_metadata
341    migrate_metadata_to_new_table(tr)
342        .await
343        .with_context(|| "migrating metadata to partition_metadata table")?;
344
345    // Drop the file_metadata column from lakehouse_partitions after successful migration
346    tr.execute("ALTER TABLE lakehouse_partitions DROP COLUMN file_metadata;")
347        .await
348        .with_context(|| "dropping file_metadata column from lakehouse_partitions")?;
349
350    tr.execute("UPDATE lakehouse_migration SET version=4;")
351        .await
352        .with_context(|| "Updating lakehouse schema version to 4")?;
353    Ok(())
354}
355
356async fn migrate_metadata_to_new_table(
357    tr: &mut sqlx::Transaction<'_, sqlx::Postgres>,
358) -> Result<()> {
359    info!("migrating metadata to partition_metadata table");
360
361    // First, get all file paths that have metadata (small data)
362    let file_paths: Vec<String> = sqlx::query_scalar(
363        "SELECT file_path 
364         FROM lakehouse_partitions 
365         WHERE file_metadata IS NOT NULL
366         ORDER BY file_path",
367    )
368    .fetch_all(&mut **tr)
369    .await?;
370
371    let total_to_migrate = file_paths.len();
372    info!(
373        "found {} partitions with metadata to migrate",
374        total_to_migrate
375    );
376
377    let mut total_count = 0;
378    let batch_size = 10; // Small batch size since metadata can be large
379
380    // Process in batches to avoid loading too much metadata at once
381    for chunk in file_paths.chunks(batch_size) {
382        // Build a query to fetch just this batch
383        let placeholders: Vec<String> = (1..=chunk.len()).map(|i| format!("${}", i)).collect();
384        let query_str = format!(
385            "SELECT file_path, file_metadata, updated 
386             FROM lakehouse_partitions 
387             WHERE file_path IN ({})",
388            placeholders.join(", ")
389        );
390
391        let mut query = sqlx::query(&query_str);
392        for path in chunk {
393            query = query.bind(path);
394        }
395
396        let rows = query.fetch_all(&mut **tr).await?;
397
398        for row in rows {
399            let file_path: String = row.try_get("file_path")?;
400            let file_metadata: Vec<u8> = row.try_get("file_metadata")?;
401            let updated: chrono::DateTime<chrono::Utc> = row.try_get("updated")?;
402
403            // Insert into new partition_metadata table (with ON CONFLICT for migration safety)
404            if let Err(e) = sqlx::query(
405                "INSERT INTO partition_metadata (file_path, metadata, insert_time) 
406                 VALUES ($1, $2, $3)
407                 ON CONFLICT (file_path) DO NOTHING",
408            )
409            .bind(&file_path)
410            .bind(&file_metadata)
411            .bind(updated)
412            .execute(&mut **tr)
413            .await
414            {
415                error!(
416                    "failed to migrate metadata for partition {}: {}",
417                    file_path, e
418                );
419                continue;
420            }
421
422            total_count += 1;
423        }
424
425        if total_count % 100 == 0 || total_count == total_to_migrate {
426            info!(
427                "migrated {}/{} partition metadata entries",
428                total_count, total_to_migrate
429            );
430        }
431    }
432
433    info!("migrated metadata for {} total partitions", total_count);
434    Ok(())
435}
436
437async fn upgrade_v4_to_v5(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
438    // Add partition_format_version column to lakehouse_partitions
439    // Default to 1 for existing partitions (Arrow 56.0 format)
440    tr.execute(
441        "ALTER TABLE lakehouse_partitions
442         ADD COLUMN partition_format_version INTEGER NOT NULL DEFAULT 1;",
443    )
444    .await
445    .with_context(|| "adding partition_format_version to lakehouse_partitions")?;
446    // Add partition_format_version column to partition_metadata
447    // Default to 1 for existing metadata (Arrow 56.0 format)
448    tr.execute(
449        "ALTER TABLE partition_metadata
450         ADD COLUMN partition_format_version INTEGER NOT NULL DEFAULT 1;",
451    )
452    .await
453    .with_context(|| "adding partition_format_version to partition_metadata")?;
454    tr.execute("UPDATE lakehouse_migration SET version=5;")
455        .await
456        .with_context(|| "Updating lakehouse schema version to 5")?;
457    info!("added partition_format_version columns to both tables");
458    Ok(())
459}
460
461async fn upgrade_v5_to_v6(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
462    tr.execute("DROP TABLE partition_metadata;")
463        .await
464        .with_context(|| "dropping partition_metadata table")?;
465    tr.execute("UPDATE lakehouse_migration SET version=6;")
466        .await
467        .with_context(|| "Updating lakehouse schema version to 6")?;
468    Ok(())
469}
470
471async fn upgrade_v6_to_v7(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
472    // Nullable, no backfill needed: NULL means "no ordering guarantee", which is automatically
473    // correct for every partition written before this column existed.
474    tr.execute("ALTER TABLE lakehouse_partitions ADD COLUMN sort_order TEXT[];")
475        .await
476        .with_context(|| "adding sort_order column to lakehouse_partitions")?;
477    tr.execute("CREATE EXTENSION IF NOT EXISTS btree_gist;")
478        .await
479        .with_context(|| "creating btree_gist extension (required by the partition overlap exclusion constraint); on PostgreSQL <= 12, or if this role lacks CREATE on the database, a superuser must run CREATE EXTENSION btree_gist once")?;
480    // Detect-then-fail: the exclusion constraint below cannot be added NOT VALID, so if legacy
481    // overlapping partitions exist, surface exactly which rows conflict instead of failing with a
482    // raw constraint error. Zero-width ranges are excluded to match tstzrange semantics (an empty
483    // range never overlaps anything). Scoped to same-schema pairs, matching the constraint: a
484    // cross-schema overlap is the legal schema-rollout coexistence state, not a conflict.
485    let conflicts = sqlx::query(
486        "SELECT a.view_set_name, a.view_instance_id,
487                a.file_path AS file_path_a, b.file_path AS file_path_b,
488                a.begin_insert_time AS begin_a, a.end_insert_time AS end_a,
489                b.begin_insert_time AS begin_b, b.end_insert_time AS end_b
490         FROM lakehouse_partitions a
491         JOIN lakehouse_partitions b
492           ON a.view_set_name = b.view_set_name
493          AND a.view_instance_id = b.view_instance_id
494          AND a.file_schema_hash = b.file_schema_hash
495          AND a.ctid < b.ctid
496          AND a.begin_insert_time < b.end_insert_time
497          AND a.end_insert_time > b.begin_insert_time
498          AND a.begin_insert_time < a.end_insert_time
499          AND b.begin_insert_time < b.end_insert_time
500         LIMIT 20;",
501    )
502    .fetch_all(&mut **tr)
503    .await
504    .with_context(|| "detecting overlapping partitions before adding exclusion constraint")?;
505    if !conflicts.is_empty() {
506        let mut msg = String::from(
507            "lakehouse_partitions contains partitions with overlapping insert-time ranges; \
508             retire them (e.g. retire_partition_by_metadata) and restart to complete the \
509             migration. Conflicting pairs (first 20):",
510        );
511        for row in &conflicts {
512            let view_set_name: String = row.try_get("view_set_name")?;
513            let view_instance_id: String = row.try_get("view_instance_id")?;
514            let file_path_a: Option<String> = row.try_get("file_path_a")?;
515            let file_path_b: Option<String> = row.try_get("file_path_b")?;
516            let begin_a: chrono::DateTime<chrono::Utc> = row.try_get("begin_a")?;
517            let end_a: chrono::DateTime<chrono::Utc> = row.try_get("end_a")?;
518            let begin_b: chrono::DateTime<chrono::Utc> = row.try_get("begin_b")?;
519            let end_b: chrono::DateTime<chrono::Utc> = row.try_get("end_b")?;
520            msg.push_str(&format!(
521                "\n  {view_set_name}/{view_instance_id}: {file_path_a:?} [{begin_a}, {end_a}] overlaps {file_path_b:?} [{begin_b}, {end_b}]"
522            ));
523        }
524        anyhow::bail!(msg);
525    }
526    // Enforced by the index even across concurrent transactions (the second conflicting writer
527    // blocks, then errors) -- closes the race a SELECT-based check under READ COMMITTED cannot:
528    // two concurrent writers whose snapshots don't see each other's uncommitted partitions.
529    // tstzrange is '[)' so adjacent partitions sharing a boundary do not conflict, and the write
530    // path's retire+insert runs in one transaction so replacing a partition never self-conflicts.
531    // Scoped by file_schema_hash (btree_gist supports bytea equality): after a schema-hash bump,
532    // old-schema partitions legally coexist with overlapping new-schema writes until
533    // retire_incompatible_partitions cleans them up -- e.g. an old-schema daily merged partition
534    // vs a new hourly write that overlaps it without containing it, which the insert path's
535    // containment-based retire cannot remove. Queries filter partitions by schema hash, so
536    // cross-schema overlap never yields duplicate rows; only same-schema overlap is a bug.
537    tr.execute(
538        "ALTER TABLE lakehouse_partitions ADD CONSTRAINT lakehouse_partitions_no_overlap
539         EXCLUDE USING gist (
540             view_set_name WITH =,
541             view_instance_id WITH =,
542             file_schema_hash WITH =,
543             tstzrange(begin_insert_time, end_insert_time) WITH &&
544         );",
545    )
546    .await
547    .with_context(|| "adding partition overlap exclusion constraint")?;
548    tr.execute("UPDATE lakehouse_migration SET version=7;")
549        .await
550        .with_context(|| "Updating lakehouse schema version to 7")?;
551    Ok(())
552}
553
554async fn upgrade_v7_to_v8(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
555    // Nullable, no backfill: NULL means "not recorded" -- either the partition was written
556    // before this column existed, or its view never declares a `Concatenated` event-time
557    // ordering. This is the same nullable/no-backfill shape as upgrade_v6_to_v7's sort_order
558    // column; unlike that migration, this one adds no constraint.
559    tr.execute("ALTER TABLE lakehouse_partitions ADD COLUMN max_sort_key_time TIMESTAMPTZ;")
560        .await
561        .with_context(|| "adding max_sort_key_time column to lakehouse_partitions")?;
562    tr.execute("UPDATE lakehouse_migration SET version=8;")
563        .await
564        .with_context(|| "Updating lakehouse schema version to 8")?;
565    Ok(())
566}
567
568async fn upgrade_v8_to_v9(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
569    // Admin-managed query deny list. One `match_expr` column,
570    // not a column per matcher. No index: the table holds at most
571    // `MICROMEGAS_QUERY_DENY_MAX_RULES` rows and every replica reads all of it on each refresh
572    // tick. No `SCHEMA_VERSION` (partition file-schema) change -- no partition content is affected.
573    tr.execute(
574        "CREATE TABLE query_deny_list(
575             rule_id      UUID PRIMARY KEY,
576             created_at   TIMESTAMPTZ  NOT NULL,
577             created_by   VARCHAR(255) NOT NULL,
578             reason       TEXT         NOT NULL,
579             match_expr   TEXT         NOT NULL,
580             last_hit_at  TIMESTAMPTZ
581         );",
582    )
583    .await
584    .with_context(|| "creating query_deny_list table")?;
585    tr.execute("UPDATE lakehouse_migration SET version=9;")
586        .await
587        .with_context(|| "Updating lakehouse schema version to 9")?;
588    Ok(())
589}
590
591async fn upgrade_v9_to_v10(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
592    // DDL-defined eagerly materialized views: persistence for `CREATE [OR REPLACE]
593    // MATERIALIZED VIEW` / `DROP MATERIALIZED VIEW`. `view_options` is TEXT (serde_json), not
594    // JSONB -- the column is always read back as a whole and round-tripped, so JSONB's indexing
595    // buys nothing. No SCHEMA_VERSION (partition file-schema) change -- no partition content is
596    // affected by this migration.
597    tr.execute(
598        "CREATE TABLE lakehouse_view_set_definitions(
599             view_set_name          VARCHAR(255) PRIMARY KEY,
600             definition_sql         TEXT NOT NULL,
601             extract_query          TEXT NOT NULL,
602             count_src_query        TEXT NOT NULL,
603             merge_partitions_query TEXT NOT NULL,
604             update_group           INTEGER NOT NULL,
605             view_options           TEXT NOT NULL DEFAULT '{}',
606             created_at             TIMESTAMPTZ NOT NULL DEFAULT now(),
607             updated_at             TIMESTAMPTZ NOT NULL DEFAULT now(),
608             updated_by             TEXT
609         );",
610    )
611    .await
612    .with_context(|| "creating lakehouse_view_set_definitions table")?;
613
614    // `log_stats` becomes data: its only distinction from a DDL-defined view was that its SQL
615    // lived in Rust. Seeded here, from the same `ViewDefinition` `view_factory.rs` used to build
616    // it in code (see `log_stats_view.rs`), so this is a pure data move -- its `file_schema_hash`
617    // cannot change, and existing partitions survive the upgrade unaffected.
618    // `ON CONFLICT DO NOTHING` keeps this idempotent and freezes the seeded text at this version:
619    // a later release changing `log_stats`'s shipped SQL must ship its own migration step that
620    // upserts the row, not just edit `log_stats_view.rs`'s consts.
621    let def = log_stats_view_definition();
622    let view_options = serde_json::to_string(&def.options)
623        .with_context(|| "serializing log_stats's seeded view_options")?;
624    sqlx::query(
625        "INSERT INTO lakehouse_view_set_definitions
626             (view_set_name, definition_sql, extract_query, count_src_query,
627              merge_partitions_query, update_group, view_options, updated_by)
628         VALUES ($1, $2, $3, $4, $5, $6, $7, 'migration')
629         ON CONFLICT (view_set_name) DO NOTHING;",
630    )
631    .bind(&def.view_set_name)
632    .bind(log_stats_ddl_text())
633    .bind(&def.extract_query)
634    .bind(&def.count_src_query)
635    .bind(&def.merge_partitions_query)
636    .bind(def.update_group)
637    .bind(view_options)
638    .execute(&mut **tr)
639    .await
640    .with_context(|| "seeding log_stats into lakehouse_view_set_definitions")?;
641
642    tr.execute("UPDATE lakehouse_migration SET version=10;")
643        .await
644        .with_context(|| "Updating lakehouse schema version to 10")?;
645    Ok(())
646}
647
648async fn upgrade_v10_to_v11(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
649    // Gives the seeded `log_stats` row its shipped description. A row an admin has redefined
650    // (`updated_by` no longer 'migration') keeps its own text. No partition content is affected.
651    let def = log_stats_view_definition();
652    let view_options = serde_json::to_string(&def.options)
653        .with_context(|| "serializing log_stats's view_options")?;
654    sqlx::query(
655        "UPDATE lakehouse_view_set_definitions
656         SET definition_sql = $1, view_options = $2, updated_at = now()
657         WHERE view_set_name = 'log_stats' AND updated_by = 'migration';",
658    )
659    .bind(log_stats_ddl_text())
660    .bind(view_options)
661    .execute(&mut **tr)
662    .await
663    .with_context(|| "adding log_stats's description")?;
664    tr.execute("UPDATE lakehouse_migration SET version=11;")
665        .await
666        .with_context(|| "Updating lakehouse schema version to 11")?;
667    Ok(())
668}
669
670async fn upgrade_v11_to_v12(tr: &mut sqlx::Transaction<'_, sqlx::Postgres>) -> Result<()> {
671    // A NULL `update_group` marks an on-demand view. Existing rows keep their groups.
672    tr.execute(
673        "ALTER TABLE lakehouse_view_set_definitions ALTER COLUMN update_group DROP NOT NULL;",
674    )
675    .await
676    .with_context(|| "dropping NOT NULL on lakehouse_view_set_definitions.update_group")?;
677    tr.execute("UPDATE lakehouse_migration SET version=12;")
678        .await
679        .with_context(|| "Updating lakehouse schema version to 12")?;
680    Ok(())
681}