rivet-cli 0.24.1

Rivet: PostgreSQL/MySQL/SQL Server/MongoDB → Parquet/CSV (local, S3, GCS, Azure). Crate name rivet-cli; binary rivet.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
//! Snowflake loader.
//!
//! Loads Rivet Parquet from GCS into a native-typed Snowflake table via a
//! `COPY INTO` off an external stage (a GCS `STORAGE INTEGRATION`). Unlike
//! BigQuery — where `LOAD DATA` with a declared schema coerces the Parquet for
//! free — Snowflake:
//!   * bills warehouse compute for the `COPY` (there is no free load), and
//!   * does NOT parse a Parquet JSON string into a navigable `VARIANT`: a plain
//!     `COPY` lands it as a `VARIANT`-wrapped string (`meta:key` → NULL). So a
//!     `VARIANT` column is loaded through a `PARSE_JSON($1:col)` transform in
//!     the same `COPY` (one billed pass), which yields a navigable `OBJECT`.
//!
//! Both facts were verified live before this was written.
//!
//! Cost attribution rides a `QUERY_TAG` (Snowflake's analogue of BigQuery job
//! labels): the tag shows up in `ACCOUNT_USAGE.QUERY_HISTORY`, so per-`rivet_op`
//! warehouse credits can be summed after the fact.

use super::TargetLoader;
use crate::types::target::TargetColumnSpec;
use anyhow::{Context, Result, bail};
use std::process::Command;

/// Loads Rivet Parquet from GCS into Snowflake.
#[derive(Debug, Default, Clone)]
pub struct SnowflakeLoader {
    /// The `snow` CLI connection name (e.g. `rivet`).
    pub connection: String,
    pub warehouse: String,
    pub database: String,
    pub schema: String,
    /// A pre-created GCS `STORAGE INTEGRATION` (grants Snowflake read on the
    /// bucket). The external stage is created per-load using it.
    pub storage_integration: String,
    /// `gcs://bucket/prefix/` — the external stage's URL (Snowflake wants the
    /// `gcs://` scheme, not `gs://`).
    pub gcs_url: String,
    /// Clustering key — column(s)/expression(s) for `CLUSTER BY`, enabling
    /// background auto-clustering. Empty = no clustering key. Applies only at
    /// table creation.
    pub cluster_by: Vec<String>,
    /// Absolute path to the connection's private key. The `snow` CLI does not
    /// expand `~`, so a `~`-relative `private_key_path` in the connection file
    /// must be overridden with an absolute path via env.
    pub private_key_path: Option<String>,
    /// Load-run correlation id, emitted in the `QUERY_TAG` JSON as `rivet_run`
    /// so every statement of one `rivet load` invocation shares a run key —
    /// cost slices per run (across tables) as well as per table. `None` omits it.
    pub run_id: Option<String>,
}

impl SnowflakeLoader {
    pub fn new(connection: impl Into<String>) -> Self {
        Self {
            connection: connection.into(),
            ..Default::default()
        }
    }

    /// Fully-qualified `db.schema.table`. Identifiers are passed **unquoted**:
    /// the warehouse/database/schema are pre-existing objects, and quoting a
    /// lowercase name would miss an unquoted-created (upper-cased) object. The
    /// tradeoff is that a reserved-word / special-char column is not handled —
    /// a hardening TODO once a real source needs it.
    fn fqtn(&self, table: &str) -> String {
        format!("{}.{}.{}", self.database, self.schema, table)
    }

    /// `  id NUMBER(38,0),\n  meta VARIANT` — the native column DDL.
    fn build_schema_ddl(specs: &[TargetColumnSpec]) -> String {
        specs
            .iter()
            .map(|s| format!("  {} {}", s.column_name, s.target_type))
            .collect::<Vec<_>>()
            .join(",\n")
    }

    /// The `COPY` transform projection: a `VARIANT` column is parsed with
    /// `PARSE_JSON` (a plain `COPY` would leave it a string), everything else is
    /// passed through `$1:col` (the path key preserves the Parquet field case)
    /// and coerced by the target column's type.
    fn build_copy_select(specs: &[TargetColumnSpec]) -> String {
        specs
            .iter()
            .map(|s| {
                let path = format!("$1:{}", s.column_name);
                if needs_parse_json(s) {
                    format!("PARSE_JSON({path})")
                } else {
                    path
                }
            })
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// `id, meta` — the explicit column list the transform loads into.
    fn build_column_list(specs: &[TargetColumnSpec]) -> String {
        specs
            .iter()
            .map(|s| s.column_name.clone())
            .collect::<Vec<_>>()
            .join(", ")
    }

    /// ` CLUSTER BY (created, region)` — the clustering-key clause (empty when
    /// no key). Snowflake wraps the key in parentheses (unlike BigQuery).
    fn cluster_clause(cluster_by: &[String]) -> String {
        if cluster_by.is_empty() {
            String::new()
        } else {
            format!(" CLUSTER BY ({})", cluster_by.join(", "))
        }
    }

    /// A JSON query tag for post-hoc cost attribution in `QUERY_HISTORY`.
    /// Carries `rivet_run` too when a load-run id is set, so credits summed from
    /// `QUERY_ATTRIBUTION_HISTORY` slice per run as well as per table.
    fn query_tag(&self, table: &str) -> String {
        let run = self
            .run_id
            .as_deref()
            .map(|r| format!(r#","rivet_run":"{}""#, sanitize_tag(r)))
            .unwrap_or_default();
        format!(
            r#"{{"managed_by":"rivet","rivet_op":"load","rivet_table":"{}"{run}}}"#,
            sanitize_tag(table)
        )
    }

    /// Run a SQL script through `snow sql`, returning parsed JSON blocks.
    fn run_snow(&self, sql: &str) -> Result<serde_json::Value> {
        let mut cmd = Command::new("snow");
        cmd.args(["sql", "-c", &self.connection, "--format", "json", "-q", sql]);
        if let Some(key) = &self.private_key_path {
            // snow reads SNOWFLAKE_CONNECTIONS_<CONN>_PRIVATE_KEY_PATH.
            let env_key = format!(
                "SNOWFLAKE_CONNECTIONS_{}_PRIVATE_KEY_PATH",
                self.connection.to_uppercase()
            );
            cmd.env(env_key, key);
        }
        let out = cmd
            .output()
            .context("running `snow sql` — is the Snowflake CLI installed?")?;
        if !out.status.success() {
            bail!(
                "snow sql failed: {}",
                String::from_utf8_lossy(&out.stderr).trim()
            );
        }
        serde_json::from_slice(&out.stdout).with_context(|| {
            format!(
                "parsing snow sql JSON output: {}",
                String::from_utf8_lossy(&out.stdout)
            )
        })
    }
}

impl TargetLoader for SnowflakeLoader {
    fn fqtn(&self, table: &str) -> String {
        format!("{}.{}.{}", self.database, self.schema, table)
    }

    fn materialize(&self, table: &str, specs: &[TargetColumnSpec], uris: &[String]) -> Result<u64> {
        let fqtn = self.fqtn(table);
        let ddl = Self::build_schema_ddl(specs);
        let select = Self::build_copy_select(specs);
        let columns = Self::build_column_list(specs);
        // A per-load external stage over the export's GCS prefix; the COPY loads
        // exactly the driver-selected files (`FILES=(…)`), NOT every Parquet under
        // the prefix — so the mode-aware/ledger per-run selection is honored (a
        // `PATTERN` over the prefix would load stale runs and fail the count gate).
        let stage = format!("rivet_stage_{}", sanitize_tag(table));
        let files = copy_files_clause(&self.gcs_url, uris)?;
        let cluster = Self::cluster_clause(&self.cluster_by);

        // `CREATE OR REPLACE` (overwrite): storage is the source of truth. Pin
        // the session to UTC before the COPY — Snowflake otherwise stamps a
        // Parquet timestamp with the session offset, shifting a `timestamptz`.
        let sql = format!(
            "ALTER SESSION SET QUERY_TAG = '{tag}';\n\
             ALTER SESSION SET TIMEZONE = 'UTC';\n\
             USE WAREHOUSE {wh};\n\
             USE SCHEMA {db}.{sc};\n\
             CREATE FILE FORMAT IF NOT EXISTS rivet_pq TYPE=PARQUET BINARY_AS_TEXT=FALSE;\n\
             CREATE OR REPLACE STAGE {stage} URL='{url}' STORAGE_INTEGRATION={si} FILE_FORMAT=rivet_pq;\n\
             CREATE OR REPLACE TABLE {fqtn} (\n{ddl}\n){cluster};\n\
             COPY INTO {fqtn} ({columns})\n\
             \x20 FROM (SELECT {select} FROM @{stage})\n\
             \x20 FILE_FORMAT=(FORMAT_NAME=rivet_pq) {files};\n\
             SELECT COUNT(*) AS ROWS_ FROM {fqtn};",
            tag = self.query_tag(table),
            wh = self.warehouse,
            db = self.database,
            sc = self.schema,
            si = self.storage_integration,
            url = self.gcs_url,
        );

        let result = self.run_snow(&sql)?;
        // ponytail: rows via COUNT(*); can become the COPY's `rows_loaded`
        // (metadata) behind this seam, no driver change.
        extract_count(&result)
            .context("COPY ran but the row count could not be read from snow output")
    }

    fn append_changelog(
        &self,
        table: &str,
        specs: &[TargetColumnSpec],
        uris: &[String],
        pk: &[String],
    ) -> Result<u64> {
        let sql = self.build_append_changelog_sql(table, specs, uris, pk)?;
        let result = self.run_snow(&sql)?;
        let before = extract_named(&result, "BEFORE_")
            .context("CDC load ran but the pre-append count (BEFORE_) could not be read")?;
        let after = extract_named(&result, "AFTER_")
            .context("CDC load ran but the post-append count (AFTER_) could not be read")?;
        Ok(after.saturating_sub(before))
    }

    fn warehouse(&self) -> crate::load::cdc::Warehouse {
        crate::load::cdc::Warehouse::Snowflake
    }

    fn create_view(&self, table: &str, view_sql: &str) -> Result<()> {
        // Fully-qualified DDL; a QUERY_TAG keeps it cost-attributable. CREATE VIEW
        // is metadata — no warehouse compute needed.
        let sql = format!(
            "ALTER SESSION SET QUERY_TAG = '{tag}';\n{view_sql}",
            tag = self.query_tag(table),
        );
        self.run_snow(&sql)?;
        Ok(())
    }
}

impl SnowflakeLoader {
    /// The append script for one CDC load, separated from its EXECUTION so the
    /// schema-reconciliation step can be asserted without a Snowflake account.
    /// The reconciling `ALTER` shipped on BigQuery only, so "the builder exists"
    /// is not evidence that this adapter calls it — that is what the test pins.
    fn build_append_changelog_sql(
        &self,
        table: &str,
        specs: &[TargetColumnSpec],
        uris: &[String],
        pk: &[String],
    ) -> Result<String> {
        use crate::load::cdc::Warehouse;
        // Full change-log schema: rivet's `__op`/`__pos`/`__seq` meta columns
        // (not reported by `rivet check`) ahead of the resolved data columns.
        let mut full = crate::load::cdc::meta_column_specs(Warehouse::Snowflake);
        full.extend(
            specs
                .iter()
                .filter(|s| !is_meta_column(&s.column_name))
                .cloned(),
        );

        let changes = format!("{table}__changes");
        let changes_fqtn = self.fqtn(&changes);
        let ddl = Self::build_schema_ddl(&full);
        let select = Self::build_copy_select(&full);
        let columns = Self::build_column_list(&full);
        let cluster = Self::cluster_clause(pk);
        let stage = format!("rivet_stage_{}", sanitize_tag(&changes));
        let files = copy_files_clause(&self.gcs_url, uris)?;

        // Ensure the log exists (clustered on PK), COUNT before, append via COPY,
        // COUNT after — the delta is what THIS load added; the driver gates it.
        let sql = format!(
            "ALTER SESSION SET QUERY_TAG = '{tag}';\n\
             ALTER SESSION SET TIMEZONE = 'UTC';\n\
             USE WAREHOUSE {wh};\n\
             USE SCHEMA {db}.{sc};\n\
             CREATE FILE FORMAT IF NOT EXISTS rivet_pq TYPE=PARQUET BINARY_AS_TEXT=FALSE;\n\
             CREATE OR REPLACE STAGE {stage} URL='{url}' STORAGE_INTEGRATION={si} FILE_FORMAT=rivet_pq;\n\
             CREATE TABLE IF NOT EXISTS {changes_fqtn} (\n{ddl}\n){cluster};\n\
             {alter}\
             SELECT COUNT(*) AS BEFORE_ FROM {changes_fqtn};\n\
             COPY INTO {changes_fqtn} ({columns})\n\
             \x20 FROM (SELECT {select} FROM @{stage})\n\
             \x20 FILE_FORMAT=(FORMAT_NAME=rivet_pq) FORCE=TRUE {files};\n\
             SELECT COUNT(*) AS AFTER_ FROM {changes_fqtn};",
            tag = self.query_tag(&changes),
            wh = self.warehouse,
            db = self.database,
            sc = self.schema,
            si = self.storage_integration,
            url = self.gcs_url,
            alter = build_alter_add_columns_sql(&changes_fqtn, &full),
        );
        Ok(sql)
    }
}

/// Whether a column name is one of rivet's CDC meta columns.
fn is_meta_column(name: &str) -> bool {
    crate::load::cdc::is_meta_column(name)
}

/// Bring an EXISTING change log's schema up to the declared one by ADDING what
/// is missing — never by replacing the table, which would impose rivet's schema
/// on history rivet does not own.
///
/// `CREATE TABLE IF NOT EXISTS` is a no-op on a table that already exists, so a
/// log rivet did not create — one an operator pointed rivet at — keeps whatever shape its previous
/// owner gave it, and a log that predates a new column keeps the old one. The
/// `COPY INTO … (<declared columns>)` below then names a column the table lacks
/// and Snowflake fails the whole load with `invalid identifier` — after the
/// extract has already been paid for. `_rivet_row_hash` made that concrete: it
/// is written at extraction and gained a load spec, so every pre-existing log
/// was suddenly one column short.
///
/// `ADD COLUMN IF NOT EXISTS` is the only safe verb: additive, idempotent,
/// metadata-only, and existing rows read NULL for the new column. Trailing
/// newline (not `Option`) so the caller interpolates it unconditionally; an
/// empty spec list yields an empty string rather than a bare `ALTER TABLE t ;`.
fn build_alter_add_columns_sql(fqtn: &str, specs: &[TargetColumnSpec]) -> String {
    if specs.is_empty() {
        return String::new();
    }
    let adds = specs
        .iter()
        // Bare identifiers, matching `build_schema_ddl` / `build_column_list`:
        // this loader creates its columns unquoted (Snowflake upper-cases them),
        // so a quoted `"col"` here would ADD a second, case-sensitive column
        // instead of matching the one the COPY names.
        .map(|s| {
            format!(
                "ADD COLUMN IF NOT EXISTS {} {}",
                s.column_name, s.target_type
            )
        })
        .collect::<Vec<_>>()
        .join(",\n  ");
    format!("ALTER TABLE {fqtn}\n  {adds};\n")
}

/// A column is loaded through `PARSE_JSON` iff its native type is `VARIANT`
/// (Rivet's Snowflake resolver maps JSON → `VARIANT`); a plain `COPY` would
/// leave it a string.
fn needs_parse_json(spec: &TargetColumnSpec) -> bool {
    spec.target_type.eq_ignore_ascii_case("VARIANT")
}

/// Keep a table name safe for a stage name / query tag (alnum + underscore).
fn sanitize_tag(s: &str) -> String {
    s.chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect()
}

/// Strip either GCS URI scheme — `gcs://` (Snowflake's stage scheme) or `gs://`
/// (what the load driver hands us) — so a stage URL and a driver-selected URI
/// compare on bucket/key alone, not scheme. Without this the two never matched.
fn strip_gcs_scheme(s: &str) -> &str {
    s.strip_prefix("gcs://")
        .or_else(|| s.strip_prefix("gs://"))
        .unwrap_or(s)
}

/// Build the COPY `FILES=('a.parquet', 'b/c.parquet', …)` clause from the
/// driver-selected `uris`, each made relative to the stage URL (`gcs_url`). This
/// is what makes Snowflake honor the mode-aware/ledger per-run selection instead
/// of loading every Parquet under the prefix — a `PATTERN` over the prefix would
/// re-load stale/already-loaded runs and fail the count gate.
fn copy_files_clause(gcs_url: &str, uris: &[String]) -> Result<String> {
    if uris.is_empty() {
        bail!("Snowflake COPY: no Parquet URIs selected to load");
    }
    // Snowflake caps an explicit FILES=() list at 1000 entries; a normal run is a
    // handful. Batching past that is a follow-up — fail loud rather than silently
    // fall back to a whole-prefix PATTERN (the bug this fix closes).
    if uris.len() > 1000 {
        bail!(
            "Snowflake COPY FILES=() caps at 1000 files, got {} — batch the load or reduce parallelism",
            uris.len()
        );
    }
    // Scheme-blind: the stage URL is `gcs://` (Snowflake's scheme) but the driver
    // hands `gs://` uris. Strip both before matching so FILES entries come out
    // stage-RELATIVE — else strip_prefix never matches, the FULL uri leaks into
    // FILES=(), and Snowflake resolves it relative to the stage → a doubled
    // `gcs://…/gs://…` path (the live-caught "file not found" bug).
    let base = strip_gcs_scheme(gcs_url).trim_end_matches('/');
    let files = uris
        .iter()
        .map(|u| {
            let stripped = strip_gcs_scheme(u);
            let rel = stripped
                .strip_prefix(base)
                .unwrap_or(stripped)
                .trim_start_matches('/');
            format!("'{rel}'")
        })
        .collect::<Vec<_>>()
        .join(", ");
    Ok(format!("FILES=({files})"))
}

/// Pull the `ROWS_` count out of snow's JSON (array of statement result blocks).
fn extract_count(value: &serde_json::Value) -> Option<u64> {
    extract_named(value, "ROWS_")
}

/// Pull a named integer column (e.g. `BEFORE_` / `AFTER_` / `ROWS_`) out of
/// snow's JSON — an array of statement result blocks, each an array of row
/// objects. Returns the first block carrying the key.
fn extract_named(value: &serde_json::Value, key: &str) -> Option<u64> {
    let blocks = value.as_array()?;
    for block in blocks {
        if let Some(rows) = block.as_array() {
            for row in rows {
                if let Some(n) = row.get(key).and_then(|v| v.as_u64()) {
                    return Some(n);
                }
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::target::TargetStatus;

    fn spec(name: &str, ty: &str) -> TargetColumnSpec {
        TargetColumnSpec {
            column_name: name.to_string(),
            target_type: ty.to_string(),
            autoload_type: String::new(),
            status: TargetStatus::Ok,
            note: None,
            cast_sql: None,
        }
    }

    #[test]
    fn copy_files_clause_lists_the_selected_files_relative_to_the_stage() {
        // PRODUCTION REALITY: the stage URL is `gcs://` (Snowflake's scheme) while
        // the driver hands `gs://` uris. FILES must still come out stage-RELATIVE
        // across the scheme gap — a scheme-blind strip_prefix leaks the FULL uri,
        // which Snowflake resolves relative to the stage → a doubled
        // `gcs://…/gs://…` path ("file not found", caught live). This test now
        // mixes the schemes so it reproduces that bug.
        let clause = copy_files_clause(
            "gcs://bucket/exports/orders/",
            &[
                "gs://bucket/exports/orders/part-0.parquet".to_string(),
                "gs://bucket/exports/orders/snapshot/part-1.parquet".to_string(),
            ],
        )
        .unwrap();
        assert_eq!(
            clause, "FILES=('part-0.parquet', 'snapshot/part-1.parquet')",
            "each uri stripped to a stage-relative path across schemes; no PATTERN"
        );
        assert!(!clause.contains("PATTERN"));
        assert!(
            !clause.contains("gs://") && !clause.contains("gcs://"),
            "no absolute URI may leak into FILES=() — that doubles the stage prefix"
        );
        // A `gcs://` stage URL without a trailing slash still strips a `gs://` uri.
        assert_eq!(
            copy_files_clause("gcs://b/p", &["gs://b/p/f.parquet".to_string()]).unwrap(),
            "FILES=('f.parquet')"
        );
        // Empty selection and the 1000-file cap both bail (never a silent
        // whole-prefix fallback).
        assert!(copy_files_clause("gcs://b/p/", &[]).is_err());
        let many: Vec<String> = (0..1001)
            .map(|i| format!("gs://b/p/f{i}.parquet"))
            .collect();
        assert!(copy_files_clause("gcs://b/p/", &many).is_err());
    }

    #[test]
    fn variant_columns_are_parsed_scalars_pass_through() {
        let specs = [
            spec("id", "NUMBER(38,0)"),
            spec("meta", "VARIANT"),
            spec("created", "DATE"),
        ];
        let sel = SnowflakeLoader::build_copy_select(&specs);
        assert_eq!(sel, "$1:id, PARSE_JSON($1:meta), $1:created");
    }

    #[test]
    fn schema_ddl_and_column_list_are_unquoted() {
        let specs = [spec("id", "NUMBER(38,0)"), spec("meta", "VARIANT")];
        assert_eq!(
            SnowflakeLoader::build_schema_ddl(&specs),
            "  id NUMBER(38,0),\n  meta VARIANT"
        );
        assert_eq!(SnowflakeLoader::build_column_list(&specs), "id, meta");
    }

    #[test]
    fn cluster_clause_wraps_key_in_parens_and_is_empty_when_unset() {
        assert_eq!(SnowflakeLoader::cluster_clause(&[]), "");
        assert_eq!(
            SnowflakeLoader::cluster_clause(&["created".to_string(), "customer".to_string()]),
            " CLUSTER BY (created, customer)"
        );
    }

    /// An existing change log must be reconciled by ADDING what it lacks, never
    /// by a replace. `CREATE TABLE IF NOT EXISTS` is a no-op on a table that
    /// already exists, so without this the `COPY INTO … (<declared columns>)`
    /// names a column the table does not have and Snowflake fails the load with
    /// `invalid identifier` — after the extract was already paid for. This is
    /// the Snowflake twin of bigquery.rs's `build_alter_add_columns_sql`; the
    /// reconciliation lives in each adapter, so one adapter having it proves
    /// nothing about the other (it shipped on BigQuery alone).
    #[test]
    fn alter_add_columns_reconciles_an_existing_log_and_never_replaces_it() {
        let specs = vec![
            spec("__op", "VARCHAR"),
            spec(crate::enrich::COL_ROW_HASH, "NUMBER(38,0)"),
        ];
        let sql = build_alter_add_columns_sql("DB.SC.t__changes", &specs);
        assert!(
            sql.starts_with("ALTER TABLE DB.SC.t__changes"),
            "must ALTER the log in place; got: {sql}"
        );
        assert!(
            sql.contains("ADD COLUMN IF NOT EXISTS __op VARCHAR")
                && sql.contains("ADD COLUMN IF NOT EXISTS _rivet_row_hash NUMBER(38,0)"),
            "every declared column is added idempotently; got: {sql}"
        );
        assert!(
            !sql.to_uppercase().contains("REPLACE") && !sql.to_uppercase().contains("DROP"),
            "reconciliation must never replace or drop — the log holds history \
             rivet does not own; got: {sql}"
        );
        // Bare identifiers: the loader creates its columns unquoted, so a quoted
        // name would add a SECOND case-sensitive column the COPY never names.
        assert!(!sql.contains('"'), "identifiers stay bare; got: {sql}");
        // Empty spec list ⇒ no statement at all, not a bare `ALTER TABLE t ;`.
        assert_eq!(build_alter_add_columns_sql("DB.SC.t", &[]), "");
    }

    /// The reconciliation must actually be IN the append script — a correct
    /// builder that no caller invokes is the bug this release shipped on
    /// Snowflake. Asserted on the emitted SQL's ORDER: the ALTER has to sit
    /// after the CREATE (which is the no-op on an existing table) and before
    /// the COPY that names the columns.
    #[test]
    fn the_append_script_alters_between_the_create_and_the_copy() {
        let specs = vec![spec("id", "NUMBER"), spec("__op", "VARCHAR")];
        let mut l = SnowflakeLoader::new("c");
        l.database = "DB".into();
        l.schema = "SC".into();
        let sql = l
            .build_append_changelog_sql(
                "t",
                &specs,
                &["gs://b/p/part-0.parquet".to_string()],
                &["id".to_string()],
            )
            .unwrap();
        let create = sql
            .find("CREATE TABLE IF NOT EXISTS")
            .expect("create present");
        let alter = sql.find("ALTER TABLE DB.SC.t__changes").expect(
            "the append script must reconcile an existing log — without this the COPY \
             names columns the table lacks and the load fails after the extract",
        );
        let copy = sql.find("COPY INTO").expect("copy present");
        assert!(
            create < alter && alter < copy,
            "order must be CREATE → ALTER → COPY; got:\n{sql}"
        );
    }

    #[test]
    fn is_meta_column_matches_only_cdc_meta() {
        assert!(is_meta_column("__op"));
        assert!(is_meta_column("__pos"));
        assert!(is_meta_column("__seq"));
        assert!(!is_meta_column("id"));
        assert!(!is_meta_column("__other"));
    }

    #[test]
    fn fqtn_qualifies_database_schema_table() {
        let mut l = SnowflakeLoader::new("c");
        l.database = "DB".into();
        l.schema = "SC".into();
        assert_eq!(l.fqtn("orders"), "DB.SC.orders");
    }

    #[test]
    fn query_tag_carries_run_id_when_set_and_omits_it_otherwise() {
        let mut l = SnowflakeLoader::new("c");
        assert_eq!(
            l.query_tag("Orders"),
            r#"{"managed_by":"rivet","rivet_op":"load","rivet_table":"Orders"}"#
        );
        // Non-alphanumerics in the id are coerced to `_` so QUERY_TAG stays
        // valid JSON. The generated run id is pure hex, so this only bites a
        // user-supplied `--run-id` with punctuation.
        l.run_id = Some("r-7".to_string());
        assert_eq!(
            l.query_tag("Orders"),
            r#"{"managed_by":"rivet","rivet_op":"load","rivet_table":"Orders","rivet_run":"r_7"}"#
        );
    }

    #[test]
    fn count_is_extracted_from_snow_json() {
        let v = serde_json::json!([
            [{"status": "ok"}],
            [{"ROWS_": 50}]
        ]);
        assert_eq!(extract_count(&v), Some(50));
    }

    #[test]
    fn cdc_before_and_after_counts_are_extracted_by_name() {
        // The CDC script emits BEFORE_ and AFTER_ counts in separate blocks.
        let v = serde_json::json!([
            [{"status": "Statement executed successfully."}],
            [{"BEFORE_": 10}],
            [{"status": "rows loaded"}],
            [{"AFTER_": 35}]
        ]);
        assert_eq!(extract_named(&v, "BEFORE_"), Some(10));
        assert_eq!(extract_named(&v, "AFTER_"), Some(35));
        assert_eq!(extract_named(&v, "MISSING_"), None);
    }
}