diff --git a/CHANGELOG.md b/CHANGELOG.md index 1fc422f..11bec8c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,53 @@ All notable changes to dbmazz will be documented here. ## [Unreleased] +## [2.4.0] - 2026-05-16 + +### Changed + +- **Sinks now dispatch on `DataType` (source-agnostic), not on + `pg_type_id`.** PostgreSQL `pg_type_id` is now an optional refinement + carried only by Postgres sources (`Option` on `SourceColumn`); + non-PG sources (MySQL today) populate `None`. The previous design used + a magic-zero `pg_type_id == 0` sentinel to detect non-PG sources, + which coupled every sink to PG OID semantics and silently broke + type-aware code paths for MySQL. +- Internal: `connectors::sinks::postgres::types::mysql_data_type_to_pg` + renamed to `data_type_to_pg` (it was never MySQL-specific; the name + was a relic of when it was first added). + +### Fixed + +- **MySQL → Snowflake** MERGE projection now produces correct casts for + every column type. Previously, the Snowflake sink dispatched on + `pg_type_id` and treated `0` (MySQL marker) as an unknown type, + defaulting every column to `VARCHAR` and silently breaking MERGE + fidelity. Now the sink dispatches primarily on `DataType` and falls + back to the OID only when the `DataType` is too coarse (PG arrays, + money) to disambiguate. +- **PostgreSQL sink** `Value::Timestamp` now serializes as an ISO-8601 + string (`YYYY-MM-DD HH:MM:SS.ffffff`) instead of a raw int64. Parity + with StarRocks/Snowflake sinks. Fixes a pre-existing bug that surfaced + when MySQL TIMESTAMP began landing as `Value::Timestamp(i64)` — the + raw int landed in the raw table's JSONB cell and the downstream MERGE + could not cast it. +- `pg_type_to_data_type` (PG→`DataType` boundary) now maps `1082` + (`date`), `1083` (`time`), and `1266` (`timetz`) to `DataType::Date` + and `DataType::Time` respectively, instead of collapsing them to + `DataType::String`. Sinks that dispatch on `DataType` (now the + primary axis) can produce accurate DDL without consulting the OID. + +### Migration + +- **`_dbmazz._schema_tracking` schema** auto-migrates from v1 to v2 on + first daemon start with v2.4.0+: adds nullable `data_type JSONB` + column, drops the `NOT NULL` on `pg_type_id`, and backfills + `data_type` for any pre-existing rows. The migration is idempotent; + re-running on v2 is a no-op. Old binaries remain forward-compatible + with the v2 schema (they will not write the new `data_type` column, + but reads tolerate NULL `data_type` with a fallback to + `pg_type_to_data_type(pg_type_id)`). + ## [2.3.0] - 2026-05-04 ### Added diff --git a/Cargo.lock b/Cargo.lock index 6afddc3..2687c58 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -913,7 +913,7 @@ dependencies = [ [[package]] name = "dbmazz" -version = "2.3.0" +version = "2.4.0" dependencies = [ "anyhow", "arrow", diff --git a/Cargo.toml b/Cargo.toml index 27834fb..4f111b2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "dbmazz" -version = "2.3.0" +version = "2.4.0" edition = "2021" license = "Elastic-2.0" # Minimum Supported Rust Version. diff --git a/docs/contributing-connectors.md b/docs/contributing-connectors.md index 1505ad2..b8dce92 100644 --- a/docs/contributing-connectors.md +++ b/docs/contributing-connectors.md @@ -550,6 +550,16 @@ impl Sink for MyNewSink { ### Step 4: Implement Type Mappings +> **Important — dispatch on `DataType`, never on `pg_type_id`.** +> `SourceColumn::pg_type_id: Option` is a Postgres-source-only +> refinement metadata field. Sink type mappers MUST take `&DataType` as +> the primary input. `pg_type_id` is consulted only as a refinement +> when the source is Postgres AND `DataType` is too coarse to express +> the precision the target type system needs (e.g., PG arrays collapse +> to `DataType::String` and require the OID to disambiguate). For all +> other cases, ignore `pg_type_id` — it will be `None` for non-PG +> sources (MySQL today, and any future source). + In `types.rs`, map `core::DataType` to sink-specific types: ```rust diff --git a/src/connectors/sinks/postgres/merge_generator.rs b/src/connectors/sinks/postgres/merge_generator.rs index c453af0..65f887b 100644 --- a/src/connectors/sinks/postgres/merge_generator.rs +++ b/src/connectors/sinks/postgres/merge_generator.rs @@ -206,13 +206,13 @@ mod tests { name: "id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, // integer + pg_type_id: Some(23), // integer }, SourceColumn { name: "name".to_string(), data_type: DataType::String, nullable: true, - pg_type_id: 25, // text + pg_type_id: Some(25), // text }, SourceColumn { name: "amount".to_string(), @@ -221,7 +221,7 @@ mod tests { scale: 9, }, nullable: true, - pg_type_id: 1700, // numeric + pg_type_id: Some(1700), // numeric }, ], primary_keys: vec!["id".to_string()], @@ -300,19 +300,19 @@ mod tests { name: "order_id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }, SourceColumn { name: "item_id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }, SourceColumn { name: "quantity".to_string(), data_type: DataType::Int32, nullable: true, - pg_type_id: 23, + pg_type_id: Some(23), }, ], primary_keys: vec!["order_id".to_string(), "item_id".to_string()], @@ -378,7 +378,7 @@ mod tests { name: "description".to_string(), data_type: DataType::String, nullable: true, - pg_type_id: 25, // text + pg_type_id: Some(25), // text }); let sql = generate_merge_range( diff --git a/src/connectors/sinks/postgres/raw_table.rs b/src/connectors/sinks/postgres/raw_table.rs index 60508ce..033e3dd 100644 --- a/src/connectors/sinks/postgres/raw_table.rs +++ b/src/connectors/sinks/postgres/raw_table.rs @@ -17,7 +17,7 @@ use tracing::info; use super::schema_tracking::{self, SchemaState}; use super::types; use crate::connectors::sinks::schema_evolution::compute_schema_evolution_plan; -use crate::core::record::{CdcRecord, ColumnValue, Value}; +use crate::core::record::{CdcRecord, ColumnValue, DataType, Value}; use crate::core::traits::SourceTableSchema; /// Metadata schema name @@ -62,9 +62,11 @@ pub async fn write_batch_to_raw( // is complete (Risk #6). A COPY failure rolls back the DDL too. for (table, diff) in &pending_diffs { for added in &diff.added { - let col_type = match added.pg_type_id { - Some(oid) => types::pg_oid_to_target_type(oid), - None => types::mysql_data_type_to_pg(&added.data_type), + // DataType-primary dispatch; OID is a PG-source refinement + // and only adds info when DataType collapses to String. + let col_type = match (&added.data_type, added.pg_type_id) { + (DataType::String | DataType::Text, Some(oid)) => types::pg_oid_to_target_type(oid), + _ => types::data_type_to_pg(&added.data_type), }; let sql = format!( r#"ALTER TABLE "{}"."{}" ADD COLUMN IF NOT EXISTS "{}" {}"#, @@ -342,7 +344,20 @@ fn value_to_json(value: &Value) -> serde_json::Value { // Parse the JSON string to embed it as a JSON value (not a string) serde_json::from_str(s).unwrap_or_else(|_| serde_json::json!(s)) } - Value::Timestamp(ts) => serde_json::json!(*ts), + Value::Timestamp(ts) => { + // Emit ISO-8601 string so the downstream MERGE can cast to + // PG timestamp directly. Mirrors the StarRocks/Snowflake + // sinks. Without this, MySQL TIMESTAMP→PG was unparseable + // because the raw int landed in a JSONB cell and MERGE + // could not cast it to timestamp. + let secs = ts / 1_000_000; + let nanos = ((ts % 1_000_000) * 1000) as u32; + if let Some(dt) = chrono::DateTime::from_timestamp(secs, nanos) { + serde_json::json!(dt.format("%Y-%m-%d %H:%M:%S%.6f").to_string()) + } else { + serde_json::Value::Null + } + } Value::Decimal(s) => serde_json::json!(s), Value::Uuid(s) => serde_json::json!(s), Value::Unchanged => serde_json::Value::Null, // should not reach here @@ -380,6 +395,25 @@ mod tests { assert!(parsed["deleted_at"].is_null()); } + #[test] + fn test_value_to_json_timestamp_iso8601() { + // 2024-01-15 10:50:00 UTC in microseconds since epoch + let ts: i64 = 1_705_315_800_000_000; + let json = value_to_json(&Value::Timestamp(ts)); + let s = json.as_str().expect("timestamp must serialize to string"); + assert_eq!(s, "2024-01-15 10:50:00.000000"); + } + + #[test] + fn test_value_to_json_timestamp_with_microseconds() { + // Timestamp with fractional microseconds — must round-trip + // through the format string with %.6f precision. + let ts: i64 = 1_705_315_800_123_456; + let json = value_to_json(&Value::Timestamp(ts)); + let s = json.as_str().unwrap(); + assert!(s.ends_with(".123456"), "expected microseconds in {s:?}"); + } + #[test] fn test_columns_to_json_skip_unchanged() { let cols = vec![ diff --git a/src/connectors/sinks/postgres/schema_tracking.rs b/src/connectors/sinks/postgres/schema_tracking.rs index 0fb9fd5..95a33e6 100644 --- a/src/connectors/sinks/postgres/schema_tracking.rs +++ b/src/connectors/sinks/postgres/schema_tracking.rs @@ -26,7 +26,7 @@ use tracing::{error, info, warn}; use crate::connectors::sinks::postgres::types::pg_oid_to_target_type; use crate::connectors::sinks::schema_evolution::AddedColumn; -use crate::core::record::TableRef; +use crate::core::record::{DataType, TableRef}; use crate::core::traits::{SourceColumn, SourceTableSchema}; use crate::source::converter::pg_type_to_data_type; @@ -56,19 +56,36 @@ pub const TRACKING_TABLE: &str = "_dbmazz._schema_tracking"; // DDL helpers // --------------------------------------------------------------------------- -/// Create `_dbmazz._schema_tracking` if it does not exist. +/// Create `_dbmazz._schema_tracking` if it does not exist, and migrate +/// any pre-existing legacy schema in place. +/// +/// Schema versions: +/// - **v1 (legacy)**: `pg_type_id OID NOT NULL`, no `data_type` column. +/// Works only for PG sources (which always carry an OID). +/// - **v2 (current)**: `pg_type_id OID NULL` + `data_type JSONB NULL`. +/// `data_type` is the authoritative type; `pg_type_id` is a PG-source +/// refinement. Reads tolerate NULL `data_type` and fall back to +/// `pg_type_to_data_type(pg_type_id)` to remain backward compatible +/// with rows written by v1 binaries. +/// +/// The migration is idempotent: re-running on a v2 table is a no-op. /// /// Pre: the `_dbmazz` schema already exists (created by `setup::run_setup`). -/// Post: the table exists with the schema described in solution doc §5.1. +/// Post: the table exists at v2. /// Errors: bubbles up any DDL error. Not transactional — standalone `batch_execute`. pub async fn create_tracking_table(client: &Client) -> Result<()> { - let ddl = format!( + // 1. Create with the v2 shape directly. CREATE TABLE IF NOT EXISTS + // is a no-op when the table already exists at any prior version, + // so we can't rely on it to add new columns — that's handled by + // the ALTERs below. + let create = format!( r#"CREATE TABLE IF NOT EXISTS {} ( job_name TEXT NOT NULL, src_schema TEXT NOT NULL, src_table TEXT NOT NULL, column_name TEXT NOT NULL, - pg_type_id OID NOT NULL, + pg_type_id OID, + data_type JSONB, ordinal INT NOT NULL, nullable BOOLEAN NOT NULL, added_at_lsn BIGINT NOT NULL DEFAULT 0, @@ -77,13 +94,87 @@ pub async fn create_tracking_table(client: &Client) -> Result<()> { )"#, TRACKING_TABLE ); - client - .batch_execute(&ddl) + .batch_execute(&create) .await .context("Failed to create _dbmazz._schema_tracking table")?; - info!(" [OK] Schema tracking table {} ready", TRACKING_TABLE); + // 2. v1 → v2 migration. Both ALTERs are conditional / idempotent. + // Order matters: drop NOT NULL on `pg_type_id` FIRST so subsequent + // inserts from non-PG sources can land NULLs, then add + // `data_type` for future writes. + let migrate = format!( + r#" + ALTER TABLE {table} ADD COLUMN IF NOT EXISTS data_type JSONB; + ALTER TABLE {table} ALTER COLUMN pg_type_id DROP NOT NULL; + "#, + table = TRACKING_TABLE + ); + client + .batch_execute(&migrate) + .await + .context("Failed to migrate _dbmazz._schema_tracking to v2")?; + + // 3. Backfill `data_type` for rows that pre-date the column. + // Bounded by `WHERE data_type IS NULL` so repeat invocations no-op. + let rows = client + .query( + &format!( + "SELECT src_schema, src_table, column_name, pg_type_id::int8 \ + FROM {} WHERE data_type IS NULL", + TRACKING_TABLE + ), + &[], + ) + .await + .context("Failed to scan _schema_tracking for legacy rows")?; + + if !rows.is_empty() { + info!( + " Migrating {} legacy tracking row(s) to v2 (backfill data_type)", + rows.len() + ); + for row in rows { + let src_schema: &str = row.get(0); + let src_table: &str = row.get(1); + let column_name: &str = row.get(2); + let pg_type_id_i64: Option = row.get(3); + // Without a pg_type_id we cannot infer DataType; fall back to + // String as the safest default and log so an operator can + // investigate. + let dt = match pg_type_id_i64 { + Some(oid_i64) => { + #[allow(clippy::cast_sign_loss)] + let oid = oid_i64 as u32; + pg_type_to_data_type(oid) + } + None => { + warn!( + table = %format!("{src_schema}.{src_table}"), + column = %column_name, + "schema_tracking v2 backfill: row has NULL pg_type_id; defaulting data_type to String" + ); + DataType::String + } + }; + let dt_json = + serde_json::to_value(&dt).context("Failed to encode DataType as JSONB")?; + client + .execute( + &format!( + "UPDATE {} SET data_type = $1 \ + WHERE src_schema = $2 AND src_table = $3 AND column_name = $4 \ + AND data_type IS NULL", + TRACKING_TABLE + ), + &[&dt_json, &src_schema, &src_table, &column_name], + ) + .await + .context("Failed to backfill data_type for tracking row")?; + } + } + + info!(" [OK] Schema tracking table {} ready (v2)", TRACKING_TABLE); Ok(()) } @@ -108,7 +199,7 @@ pub async fn load_tracking_state( let rows = client .query( &format!( - "SELECT src_schema, src_table, column_name, pg_type_id::int8, ordinal, nullable + "SELECT src_schema, src_table, column_name, pg_type_id::int8, data_type, ordinal, nullable FROM {} WHERE job_name = $1 ORDER BY src_schema, src_table, ordinal ASC", @@ -127,13 +218,48 @@ pub async fn load_tracking_state( let src_schema: &str = row.get(0); let src_table: &str = row.get(1); let column_name: &str = row.get(2); - // pg_type_id is stored as OID (which tokio-postgres maps to u32), but - // we cast it to int8 in the query to avoid OID-as-u32 codec issues. - let pg_type_id_i64: i64 = row.get(3); + // pg_type_id is stored as OID; we cast it to int8 in the query + // to avoid OID-as-u32 codec issues. v2 schema makes it NULL-able + // because non-PG sources can populate tracking rows without an + // OID. + let pg_type_id_i64: Option = row.get(3); #[allow(clippy::cast_sign_loss)] - let pg_type_id = pg_type_id_i64 as u32; - let _ordinal: i32 = row.get(4); - let nullable: bool = row.get(5); + let pg_type_id = pg_type_id_i64.map(|v| v as u32); + let data_type_json: Option = row.get(4); + let _ordinal: i32 = row.get(5); + let nullable: bool = row.get(6); + + // Prefer `data_type` (authoritative). Fall back to deriving it + // from `pg_type_id` only for legacy rows that pre-date the v2 + // migration backfill or were written by an even older binary + // mid-rollout (defensive — the migration in + // `create_tracking_table` already backfills all such rows). + let data_type: DataType = match data_type_json { + Some(j) => serde_json::from_value(j).with_context(|| { + format!( + "Corrupt data_type JSON in tracking row {}.{}.{}", + src_schema, src_table, column_name + ) + })?, + None => match pg_type_id { + Some(oid) => { + warn!( + table = %format!("{src_schema}.{src_table}"), + column = %column_name, + "tracking row missing data_type; deriving from pg_type_id (legacy compat)" + ); + pg_type_to_data_type(oid) + } + None => { + warn!( + table = %format!("{src_schema}.{src_table}"), + column = %column_name, + "tracking row missing both data_type and pg_type_id; defaulting to String" + ); + DataType::String + } + }, + }; let qn = format!("{}.{}", src_schema, src_table); let entry = table_columns @@ -142,7 +268,7 @@ pub async fn load_tracking_state( entry.2.push(SourceColumn { name: column_name.to_owned(), - data_type: pg_type_to_data_type(pg_type_id), + data_type, nullable, pg_type_id, }); @@ -194,22 +320,25 @@ pub async fn seed_initial_state( for (ordinal, col) in schema.columns.iter().enumerate() { #[allow(clippy::cast_possible_wrap)] let ordinal_i32 = ordinal as i32; + let data_type_json = serde_json::to_value(&col.data_type) + .context("Failed to encode SourceColumn data_type as JSONB")?; tx.execute( &format!( - "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, ordinal, nullable, added_at_lsn) - VALUES ($1, $2, $3, $4, $5, $6, $7, 0) + "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, data_type, ordinal, nullable, added_at_lsn) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0) ON CONFLICT DO NOTHING", TRACKING_TABLE ), - // pg_type_id is bound as &u32 — tokio-postgres maps u32 → OID - // natively. Do NOT bind as i64 (would send INT8 and PG won't - // implicitly cast BIGINT → OID). + // pg_type_id is bound as `&Option` — tokio-postgres + // serializes None as SQL NULL and Some(oid) as OID. Do + // NOT bind as i64 (PG won't implicitly cast BIGINT → OID). &[ &job_name, &schema.schema, &schema.name, &col.name, &col.pg_type_id, + &data_type_json, &ordinal_i32, &col.nullable, ], @@ -271,27 +400,25 @@ pub async fn insert_tracked_columns( let lsn_i64 = lsn as i64; for col in added { - // pg_type_id is `Option` on the shared `AddedColumn` (sink-agnostic). - // The PG source always populates it; `.expect()` makes the contract loud - // for any future non-PG source that wires SchemaChange events into - // this PG sink path (which would be a misconfiguration). - let pg_type_id = col - .pg_type_id - .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); + // `pg_type_id` is `Option` on the shared `AddedColumn` + // (sink-agnostic). The PG source always populates it; non-PG + // sources (MySQL) populate `None`. v2 schema accepts NULL. + let data_type_json = serde_json::to_value(&col.data_type) + .context("Failed to encode AddedColumn data_type as JSONB")?; tx.execute( &format!( - "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, ordinal, nullable, added_at_lsn) - VALUES ($1, $2, $3, $4, $5, $6, $7, $8) + "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, data_type, ordinal, nullable, added_at_lsn) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9) ON CONFLICT DO NOTHING", TRACKING_TABLE ), - // pg_type_id bound as &u32 → OID. See note in seed_initial_state. &[ &job_name, &src_schema, &table.name, &col.name, - &pg_type_id, + &col.pg_type_id, + &data_type_json, &col.ordinal, &col.nullable, &lsn_i64, @@ -373,7 +500,7 @@ pub async fn reconcile_on_startup( data_type: source_col.data_type.clone(), nullable: true, // always nullable on reconcile (Risk §5.7) ordinal: next_ordinal, - pg_type_id: Some(source_col.pg_type_id), + pg_type_id: source_col.pg_type_id, }; let sql = alter_add_column_sql(target_schema, &source.name, &added); @@ -384,20 +511,22 @@ pub async fn reconcile_on_startup( ) })?; + let data_type_json = serde_json::to_value(&source_col.data_type) + .context("Failed to encode source_col data_type as JSONB")?; tx.execute( &format!( - "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, ordinal, nullable, added_at_lsn) - VALUES ($1, $2, $3, $4, $5, $6, $7, 0) + "INSERT INTO {} (job_name, src_schema, src_table, column_name, pg_type_id, data_type, ordinal, nullable, added_at_lsn) + VALUES ($1, $2, $3, $4, $5, $6, $7, $8, 0) ON CONFLICT DO NOTHING", TRACKING_TABLE ), - // pg_type_id bound as &u32 → OID. See note in seed_initial_state. &[ &job_name, &source.schema, &source.name, &source_col.name, &source_col.pg_type_id, + &data_type_json, &added.ordinal, &added.nullable, ], @@ -461,14 +590,11 @@ pub async fn reconcile_on_startup( primary_keys: source.primary_keys.clone(), }); for added in newly_added { - let pg_type_id = added - .pg_type_id - .expect("PG sink: AddedColumn must carry pg_type_id (PG source contract)"); entry.columns.push(SourceColumn { name: added.name, - data_type: pg_type_to_data_type(pg_type_id), + data_type: added.data_type, nullable: added.nullable, - pg_type_id, + pg_type_id: added.pg_type_id, }); } } diff --git a/src/connectors/sinks/postgres/types.rs b/src/connectors/sinks/postgres/types.rs index c8356af..9d3cf55 100644 --- a/src/connectors/sinks/postgres/types.rs +++ b/src/connectors/sinks/postgres/types.rs @@ -10,20 +10,31 @@ use crate::core::record::DataType; use crate::core::traits::SourceColumn; /// Maps a SourceColumn's type info to the target PostgreSQL DDL type. -/// Uses mysql_data_type_to_pg for MySQL columns (pg_type_id == 0), -/// otherwise uses pg_oid_to_target_type for PG-to-PG identity mapping. +/// +/// Dispatch primary on `DataType` (source-agnostic). `pg_type_id` is +/// consulted only as a refinement when present (PG source) AND the +/// DataType is too coarse to disambiguate — currently only +/// `DataType::String` benefits from the OID for varchar(N) vs text +/// fidelity. Every other DataType has a precise PG mapping that does +/// not need OID help. pub fn column_type(col: &SourceColumn) -> &'static str { - if col.pg_type_id == 0 { - mysql_data_type_to_pg(&col.data_type) - } else { - pg_oid_to_target_type(col.pg_type_id) + // PG-source refinement: when DataType collapses to String, defer to + // the OID to recover varchar/inet/cidr/etc. fidelity. + if matches!(col.data_type, DataType::String | DataType::Text) { + if let Some(oid) = col.pg_type_id { + return pg_oid_to_target_type(oid); + } } + data_type_to_pg(&col.data_type) } -/// Map a MySQL DataType to the target PostgreSQL column type DDL string. -/// Used when the source is MySQL (pg_type_id is always 0). -/// Falls back to "text" for unknown types. -pub fn mysql_data_type_to_pg(dt: &DataType) -> &'static str { +/// Map a source-agnostic `DataType` to the target PostgreSQL column +/// type DDL string. Used for non-PG sources (MySQL today, and any +/// future source) AND as the PG-to-PG fallback when the OID does not +/// add fidelity beyond `DataType`. +/// +/// Falls back to "text" for `DataType::String` and unknown types. +pub fn data_type_to_pg(dt: &DataType) -> &'static str { match dt { DataType::Boolean => "boolean", DataType::Int16 => "smallint", diff --git a/src/connectors/sinks/schema_evolution.rs b/src/connectors/sinks/schema_evolution.rs index 678178c..959379e 100644 --- a/src/connectors/sinks/schema_evolution.rs +++ b/src/connectors/sinks/schema_evolution.rs @@ -171,7 +171,7 @@ pub fn diff_against_cache( // map to the same coarse DataType::Decimal bucket. let dt_changed = cached_col.data_type != col.data_type; let oid_changed = match (cached_col.pg_type_id, col.pg_type_id) { - (cached, Some(new)) if cached != 0 => cached != new, + (Some(cached), Some(new)) => cached != new, _ => false, }; if dt_changed || oid_changed { @@ -179,11 +179,7 @@ pub fn diff_against_cache( name: col.name.clone(), old_data_type: cached_col.data_type.clone(), new_data_type: col.data_type.clone(), - old_pg_type_id: if cached_col.pg_type_id == 0 { - None - } else { - Some(cached_col.pg_type_id) - }, + old_pg_type_id: cached_col.pg_type_id, new_pg_type_id: col.pg_type_id, }); } @@ -267,7 +263,7 @@ pub fn compute_schema_evolution_plan( name: added.name.clone(), data_type: added.data_type.clone(), nullable: added.nullable, - pg_type_id: added.pg_type_id.unwrap_or(0), + pg_type_id: added.pg_type_id, }); } @@ -300,7 +296,7 @@ mod tests { name: "id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }], primary_keys: vec!["id".to_string()], }, @@ -442,13 +438,13 @@ mod tests { name: "id".into(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }, SourceColumn { name: "name".into(), data_type: DataType::String, nullable: true, - pg_type_id: 25, + pg_type_id: Some(25), }, ], primary_keys: vec!["id".into()], diff --git a/src/connectors/sinks/snowflake/merge_generator.rs b/src/connectors/sinks/snowflake/merge_generator.rs index 9622368..a15da6b 100644 --- a/src/connectors/sinks/snowflake/merge_generator.rs +++ b/src/connectors/sinks/snowflake/merge_generator.rs @@ -50,7 +50,7 @@ pub fn generate_merge( .columns .iter() .map(|col| { - let expr = type_mapper.variant_extract_expr(&col.name, col.pg_type_id); + let expr = type_mapper.variant_extract_expr(&col.name, &col.data_type, col.pg_type_id); format!("{} AS \"{}\"", expr, col.name.to_uppercase()) }) .collect(); @@ -65,7 +65,7 @@ pub fn generate_merge( .iter() .find(|c| &c.name == pk) .expect("PK column must exist in schema"); - type_mapper.variant_extract_expr(&col.name, col.pg_type_id) + type_mapper.variant_extract_expr(&col.name, &col.data_type, col.pg_type_id) }) .collect(); @@ -269,13 +269,13 @@ mod tests { name: "id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }, SourceColumn { name: "name".to_string(), data_type: DataType::String, nullable: true, - pg_type_id: 25, + pg_type_id: Some(25), }, SourceColumn { name: "amount".to_string(), @@ -284,7 +284,7 @@ mod tests { scale: 9, }, nullable: true, - pg_type_id: 1700, + pg_type_id: Some(1700), }, ], primary_keys: vec!["id".to_string()], @@ -376,19 +376,19 @@ mod tests { name: "order_id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }, SourceColumn { name: "item_id".to_string(), data_type: DataType::Int32, nullable: false, - pg_type_id: 23, + pg_type_id: Some(23), }, SourceColumn { name: "quantity".to_string(), data_type: DataType::Int32, nullable: true, - pg_type_id: 23, + pg_type_id: Some(23), }, ], primary_keys: vec!["order_id".to_string(), "item_id".to_string()], diff --git a/src/connectors/sinks/snowflake/schema_evolution.rs b/src/connectors/sinks/snowflake/schema_evolution.rs index 193419e..3c95af8 100644 --- a/src/connectors/sinks/snowflake/schema_evolution.rs +++ b/src/connectors/sinks/snowflake/schema_evolution.rs @@ -123,7 +123,7 @@ impl SnowflakeSchemaEvolution { nullable: true, #[allow(clippy::cast_possible_wrap)] ordinal: i as i32, - pg_type_id: Some(src_col.pg_type_id), + pg_type_id: src_col.pg_type_id, }); } } diff --git a/src/connectors/sinks/snowflake/setup.rs b/src/connectors/sinks/snowflake/setup.rs index 34e529f..6547243 100644 --- a/src/connectors/sinks/snowflake/setup.rs +++ b/src/connectors/sinks/snowflake/setup.rs @@ -9,6 +9,7 @@ use tracing::{info, warn}; use super::client::SnowflakeClient; use super::types::TypeMapper; use crate::core::traits::SourceTableSchema; +use crate::core::DataType; /// Internal schema name in the target database (TRANSIENT, no fail-safe) const INTERNAL_SCHEMA: &str = "_DBMAZZ"; @@ -150,10 +151,21 @@ async fn create_target_table( // Build column definitions let mut col_defs: Vec = Vec::new(); for col in &source.columns { - let sf_type = if col.pg_type_id == 0 { - type_mapper.to_snowflake_type(&col.data_type) - } else { - type_mapper.pg_type_to_snowflake(col.pg_type_id).to_string() + // DataType is the primary axis. For PG sources, the OID is + // consulted ONLY when the DataType collapsed to a coarse default + // (`String` from arrays, money, etc) and the OID actually + // refines that — otherwise stick with DataType to keep + // non-PG sources first-class. + let sf_type = match (col.pg_type_id, &col.data_type) { + (Some(oid), DataType::String) => { + let refined = type_mapper.pg_type_to_snowflake(oid); + if refined == "VARCHAR" { + type_mapper.to_snowflake_type(&col.data_type) + } else { + refined.to_string() + } + } + _ => type_mapper.to_snowflake_type(&col.data_type), }; let nullable = if col.nullable { "" } else { " NOT NULL" }; col_defs.push(format!( diff --git a/src/connectors/sinks/snowflake/types.rs b/src/connectors/sinks/snowflake/types.rs index 02be27e..14b9c8e 100644 --- a/src/connectors/sinks/snowflake/types.rs +++ b/src/connectors/sinks/snowflake/types.rs @@ -18,7 +18,11 @@ impl TypeMapper { } /// Converts a CDC `DataType` to a Snowflake SQL type string. - #[allow(dead_code)] + /// + /// This is the primary type dispatcher. Sinks should use this against + /// `SourceColumn::data_type`; `pg_type_id` is only consulted as a + /// refinement when present (PG-source-only) AND the DataType is too + /// coarse to disambiguate. pub fn to_snowflake_type(&self, data_type: &DataType) -> String { match data_type { DataType::Boolean => "BOOLEAN".to_string(), @@ -43,7 +47,11 @@ impl TypeMapper { } } - /// Converts a PostgreSQL type OID to a Snowflake SQL type string. + /// PG-source-only refinement: when the OID gives information beyond + /// `DataType` (arrays, money, inet/cidr, interval), return the + /// refined Snowflake type. Sinks should call this only when + /// `SourceColumn::pg_type_id.is_some()` AND the dispatch on + /// `DataType` produced a default like `VARCHAR`. pub fn pg_type_to_snowflake(&self, pg_type_id: u32) -> &'static str { match pg_type_id { 16 => "BOOLEAN", // bool @@ -101,27 +109,53 @@ impl TypeMapper { /// Returns the VARIANT extraction expression for a column in MERGE SQL. /// - /// Used in FLATTENED CTE: `_DATA:col_name::SNOWFLAKE_TYPE AS "COL_NAME"` - pub fn variant_extract_expr(&self, col_name: &str, pg_type_id: u32) -> String { - let sf_type = self.pg_type_to_snowflake(pg_type_id); - match pg_type_id { - // Binary: base64 decode - 17 => format!("BASE64_DECODE_BINARY(_DATA:\"{}\")", col_name), - // JSON/JSONB: parse to VARIANT - 114 | 3802 => { - format!("TRY_PARSE_JSON(CAST(_DATA:\"{}\" AS VARCHAR))", col_name) + /// Used in FLATTENED CTE: `_DATA:col_name::SNOWFLAKE_TYPE AS "COL_NAME"`. + /// + /// Dispatches primarily on `data_type` (source-agnostic). When + /// `pg_type_id` is present (PG source), it is consulted only as + /// refinement for cases the `DataType` is too coarse to express — + /// PG arrays, money, inet/cidr, interval — all of which currently + /// collapse to `DataType::String` at the PG boundary. + pub fn variant_extract_expr( + &self, + col_name: &str, + data_type: &DataType, + pg_type_id: Option, + ) -> String { + // 1. Cases where DataType alone is sufficient and unambiguous. + match data_type { + DataType::Bytes => return format!("BASE64_DECODE_BINARY(_DATA:\"{}\")", col_name), + DataType::Json | DataType::Jsonb => { + return format!("TRY_PARSE_JSON(CAST(_DATA:\"{}\" AS VARCHAR))", col_name); } - // Numeric with precision: use TRY_CAST to avoid breaking batch - 1700 | 790 => { - format!("TRY_CAST((_DATA:\"{}\")::VARCHAR AS {})", col_name, sf_type) + DataType::Decimal { .. } => { + let sf_type = self.to_snowflake_type(data_type); + return format!("TRY_CAST((_DATA:\"{}\")::VARCHAR AS {})", col_name, sf_type); } - // Arrays - 1005 | 1007 | 1016 | 1021 | 1022 | 1009 | 1015 => { - format!("TRY_PARSE_JSON(CAST(_DATA:\"{}\" AS VARCHAR))", col_name) + _ => {} + } + + // 2. PG-source-only refinement for DataType::String cases the + // PG→DataType boundary cannot disambiguate (arrays, money, + // inet/cidr, interval). + if let Some(oid) = pg_type_id { + match oid { + 1005 | 1007 | 1016 | 1021 | 1022 | 1009 | 1015 => { + return format!("TRY_PARSE_JSON(CAST(_DATA:\"{}\" AS VARCHAR))", col_name); + } + 790 => { + return format!( + "TRY_CAST((_DATA:\"{}\")::VARCHAR AS NUMBER(19,4))", + col_name + ); + } + _ => {} } - // Default: direct cast - _ => format!("_DATA:\"{}\"::{}", col_name, sf_type), } + + // 3. Default: direct cast using DataType. + let sf_type = self.to_snowflake_type(data_type); + format!("_DATA:\"{}\"::{}", col_name, sf_type) } } @@ -246,30 +280,123 @@ mod tests { } #[test] - fn test_variant_extract_expr() { + fn test_variant_extract_expr_datatype_path() { let mapper = TypeMapper::new(); - // Default: direct cast + // Every DataType variant must produce a correct expression + // without any OID (non-PG sources, e.g., MySQL). + assert_eq!( + mapper.variant_extract_expr("flag", &DataType::Boolean, None), + r#"_DATA:"flag"::BOOLEAN"# + ); + assert_eq!( + mapper.variant_extract_expr("n", &DataType::Int32, None), + r#"_DATA:"n"::INT"# + ); assert_eq!( - mapper.variant_extract_expr("name", 25), + mapper.variant_extract_expr("n", &DataType::Int64, None), + r#"_DATA:"n"::BIGINT"# + ); + assert_eq!( + mapper.variant_extract_expr("amount", &DataType::Float64, None), + r#"_DATA:"amount"::DOUBLE"# + ); + assert_eq!( + mapper.variant_extract_expr("name", &DataType::String, None), + r#"_DATA:"name"::VARCHAR"# + ); + assert_eq!( + mapper.variant_extract_expr("name", &DataType::Text, None), r#"_DATA:"name"::VARCHAR"# ); + assert_eq!( + mapper.variant_extract_expr("id", &DataType::Uuid, None), + r#"_DATA:"id"::VARCHAR(36)"# + ); + assert_eq!( + mapper.variant_extract_expr("d", &DataType::Date, None), + r#"_DATA:"d"::DATE"# + ); + assert_eq!( + mapper.variant_extract_expr("t", &DataType::Time, None), + r#"_DATA:"t"::TIME"# + ); + assert_eq!( + mapper.variant_extract_expr("ts", &DataType::Timestamp, None), + r#"_DATA:"ts"::TIMESTAMP_NTZ"# + ); + assert_eq!( + mapper.variant_extract_expr("ts", &DataType::TimestampTz, None), + r#"_DATA:"ts"::TIMESTAMP_TZ"# + ); - // Binary: base64 decode + // Bytes always uses BASE64_DECODE_BINARY regardless of source. assert_eq!( - mapper.variant_extract_expr("avatar", 17), + mapper.variant_extract_expr("avatar", &DataType::Bytes, None), r#"BASE64_DECODE_BINARY(_DATA:"avatar")"# ); - // JSON: parse + // JSON / JSONB always uses TRY_PARSE_JSON. + assert_eq!( + mapper.variant_extract_expr("md", &DataType::Json, None), + r#"TRY_PARSE_JSON(CAST(_DATA:"md" AS VARCHAR))"# + ); + assert_eq!( + mapper.variant_extract_expr("md", &DataType::Jsonb, None), + r#"TRY_PARSE_JSON(CAST(_DATA:"md" AS VARCHAR))"# + ); + + // Decimal uses TRY_CAST with full precision. + assert_eq!( + mapper.variant_extract_expr( + "amount", + &DataType::Decimal { + precision: 38, + scale: 9, + }, + None, + ), + r#"TRY_CAST((_DATA:"amount")::VARCHAR AS NUMBER(38,9))"# + ); + } + + #[test] + fn test_variant_extract_expr_pg_refinement() { + let mapper = TypeMapper::new(); + + // PG arrays collapse to DataType::String — OID refines to ARRAY. assert_eq!( - mapper.variant_extract_expr("metadata", 3802), - r#"TRY_PARSE_JSON(CAST(_DATA:"metadata" AS VARCHAR))"# + mapper.variant_extract_expr("tags", &DataType::String, Some(1009)), + r#"TRY_PARSE_JSON(CAST(_DATA:"tags" AS VARCHAR))"# + ); + assert_eq!( + mapper.variant_extract_expr("ids", &DataType::String, Some(1007)), + r#"TRY_PARSE_JSON(CAST(_DATA:"ids" AS VARCHAR))"# + ); + + // PG money OID refines to NUMBER(19,4) TRY_CAST. + assert_eq!( + mapper.variant_extract_expr("price", &DataType::String, Some(790)), + r#"TRY_CAST((_DATA:"price")::VARCHAR AS NUMBER(19,4))"# + ); + + // PG text OID (25) — no refinement, falls through to DataType. + assert_eq!( + mapper.variant_extract_expr("name", &DataType::String, Some(25)), + r#"_DATA:"name"::VARCHAR"# ); - // Numeric: TRY_CAST + // Decimal with PG numeric OID — DataType wins (refinement path + // is bypassed because the DataType is already precise). assert_eq!( - mapper.variant_extract_expr("amount", 1700), + mapper.variant_extract_expr( + "amount", + &DataType::Decimal { + precision: 38, + scale: 9, + }, + Some(1700), + ), r#"TRY_CAST((_DATA:"amount")::VARCHAR AS NUMBER(38,9))"# ); } diff --git a/src/connectors/sinks/starrocks/schema_evolution.rs b/src/connectors/sinks/starrocks/schema_evolution.rs index f7cf76d..4facd15 100644 --- a/src/connectors/sinks/starrocks/schema_evolution.rs +++ b/src/connectors/sinks/starrocks/schema_evolution.rs @@ -234,7 +234,7 @@ impl StarRocksSchemaEvolution { nullable: true, #[allow(clippy::cast_possible_wrap)] ordinal: i as i32, - pg_type_id: Some(src_col.pg_type_id), + pg_type_id: src_col.pg_type_id, }); } } diff --git a/src/connectors/sinks/starrocks/types.rs b/src/connectors/sinks/starrocks/types.rs index 6edfc06..492300d 100644 --- a/src/connectors/sinks/starrocks/types.rs +++ b/src/connectors/sinks/starrocks/types.rs @@ -7,7 +7,15 @@ //! This module provides mappings between: //! - `core::DataType` (database-agnostic) -> StarRocks column types //! - `core::Value` -> JSON values for Stream Load -//! - PostgreSQL type OIDs -> StarRocks types (legacy support) +//! +//! ## Sink dispatch axis +//! +//! Runtime and DDL dispatch is on `DataType` only (`to_starrocks_type` +//! and `value_to_json`). The legacy `pg_type_to_starrocks` and +//! `pg_text_to_json` helpers exist for source-side refinement / future +//! use; sinks MUST NOT branch on `pg_type_id` as a discriminator. See +//! `openspec/changes/decouple-sinks-from-pg-source-types/` for the +//! architectural intent. //! //! ## StarRocks Type System //! @@ -86,7 +94,10 @@ impl TypeMapper { /// Converts a PostgreSQL type OID to a StarRocks type string. /// - /// This is provided for backward compatibility with the legacy sink. + /// **PG-source-only refinement.** The runtime path uses + /// `to_starrocks_type(&DataType)`; this helper is kept for future + /// fine-grained refinement (e.g., `varchar(N)` length) and is not + /// currently wired into the schema-evolution or DDL code paths. /// /// # Arguments /// diff --git a/src/core/traits.rs b/src/core/traits.rs index f182d09..e625206 100644 --- a/src/core/traits.rs +++ b/src/core/traits.rs @@ -68,15 +68,26 @@ pub struct SourceTableSchema { pub primary_keys: Vec, } -/// A single column in a source table schema +/// A single column in a source table schema. +/// +/// `data_type` is the authoritative, source-agnostic type info that sinks +/// dispatch on for DDL generation, MERGE projection casts, and runtime +/// value conversion. `pg_type_id` is an OPTIONAL refinement carried only +/// by Postgres sources — sinks consult it as a fallback when `DataType` +/// is too coarse to disambiguate (e.g., `varchar(N)` vs `text` both +/// collapse to `DataType::String`). Non-PG sources (MySQL, and any +/// future source) populate `None`. +/// +/// **Sinks MUST NOT use the presence/absence of `pg_type_id` as a +/// source-type discriminator.** The intent is purely refinement, not +/// branching. #[derive(Debug, Clone)] #[allow(dead_code)] pub struct SourceColumn { pub name: String, pub data_type: DataType, pub nullable: bool, - /// Original PostgreSQL type OID (useful for PG-to-PG sinks) - pub pg_type_id: u32, + pub pg_type_id: Option, } /// Generic replication stream — replaces PG-specific CopyBothDuplex diff --git a/src/engine/snapshot/mysql.rs b/src/engine/snapshot/mysql.rs index 043122f..1dab51d 100644 --- a/src/engine/snapshot/mysql.rs +++ b/src/engine/snapshot/mysql.rs @@ -1103,19 +1103,19 @@ mod tests { name: pk_name.to_string(), data_type: pk_type, nullable: false, - pg_type_id: 0, + pg_type_id: None, }, SourceColumn { name: "name".to_string(), data_type: DataType::String, nullable: true, - pg_type_id: 0, + pg_type_id: None, }, SourceColumn { name: "amount".to_string(), data_type: DataType::Float64, nullable: true, - pg_type_id: 0, + pg_type_id: None, }, ], primary_keys: vec![pk_name.to_string()], @@ -1177,7 +1177,7 @@ mod tests { name: "uuid".to_string(), data_type: DataType::String, nullable: false, - pg_type_id: 0, + pg_type_id: None, }], primary_keys: vec!["uuid".to_string()], }; @@ -1194,7 +1194,7 @@ mod tests { name: "id".to_string(), data_type: DataType::Int64, nullable: false, - pg_type_id: 0, + pg_type_id: None, }], primary_keys: vec![], }; diff --git a/src/source/converter.rs b/src/source/converter.rs index c92c9dc..d42904b 100644 --- a/src/source/converter.rs +++ b/src/source/converter.rs @@ -175,7 +175,13 @@ fn convert_pg_value(text: &str, pg_type_id: u32) -> Value { } } -/// Convert PostgreSQL type OID to generic DataType +/// Convert PostgreSQL type OID to generic DataType. +/// +/// This is the boundary where PG-specific OIDs become source-agnostic +/// `DataType`. Keep it as faithful as possible so sinks can dispatch on +/// `DataType` without needing the OID — anything that collapses to +/// `DataType::String` here forces sinks into OID-based refinement and +/// re-couples them to PG. pub fn pg_type_to_data_type(pg_type_id: u32) -> DataType { match pg_type_id { 16 => DataType::Boolean, @@ -188,6 +194,8 @@ pub fn pg_type_to_data_type(pg_type_id: u32) -> DataType { precision: 38, scale: 9, }, + 1082 => DataType::Date, + 1083 | 1266 => DataType::Time, 1114 => DataType::Timestamp, 1184 => DataType::TimestampTz, 25 | 1043 | 1042 => DataType::String, diff --git a/src/source/mysql/schema.rs b/src/source/mysql/schema.rs index f20eaf3..350b3d6 100644 --- a/src/source/mysql/schema.rs +++ b/src/source/mysql/schema.rs @@ -111,7 +111,7 @@ async fn introspect_columns( name, data_type: mysql_type_to_data_type(&data_type), nullable: nullable.to_uppercase() == "YES", - pg_type_id: 0, + pg_type_id: None, }) .collect(); Ok(columns) diff --git a/src/source/postgres.rs b/src/source/postgres.rs index e676c1a..a2158a0 100644 --- a/src/source/postgres.rs +++ b/src/source/postgres.rs @@ -95,7 +95,7 @@ pub async fn introspect_schemas( name, data_type: pg_type_to_data_type(type_oid as u32), nullable: !not_null, - pg_type_id: type_oid as u32, + pg_type_id: Some(type_oid as u32), } }) .collect();