From 72da8cb434ba734a89ba4314f479d082488c730e Mon Sep 17 00:00:00 2001 From: Tano Date: Sun, 7 Jun 2026 01:51:34 -0300 Subject: [PATCH 1/4] feat: add oracle sink connector --- Cargo.lock | 87 ++++++- Cargo.toml | 5 + src/config.rs | 67 +++-- src/connectors/sinks/mod.rs | 35 ++- .../sinks/oracle/merge_generator.rs | 123 ++++++++++ src/connectors/sinks/oracle/mod.rs | 230 ++++++++++++++++++ .../sinks/oracle/schema_tracking.rs | 26 ++ src/connectors/sinks/oracle/setup.rs | 109 +++++++++ src/connectors/sinks/oracle/types.rs | 118 +++++++++ src/engine/mod.rs | 4 +- src/engine/replication/postgres.rs | 4 +- src/engine/setup/postgres.rs | 20 +- src/engine/snapshot/worker.rs | 10 +- src/source/mod.rs | 4 +- 14 files changed, 808 insertions(+), 34 deletions(-) create mode 100644 src/connectors/sinks/oracle/merge_generator.rs create mode 100644 src/connectors/sinks/oracle/mod.rs create mode 100644 src/connectors/sinks/oracle/schema_tracking.rs create mode 100644 src/connectors/sinks/oracle/setup.rs create mode 100644 src/connectors/sinks/oracle/types.rs diff --git a/Cargo.lock b/Cargo.lock index 2687c58..c56dd24 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -876,14 +876,38 @@ dependencies = [ "windows-sys 0.59.0", ] +[[package]] +name = "darling" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a01d95850c592940db9b8194bc39f4bc0e89dee5c4265e4b1807c34a9aba453c" +dependencies = [ + "darling_core 0.13.4", + "darling_macro 0.13.4", +] + [[package]] name = "darling" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc7f46116c46ff9ab3eb1597a45688b6715c6e628b5c133e288e709a29bcb4ee" dependencies = [ - "darling_core", - "darling_macro", + "darling_core 0.20.11", + "darling_macro 0.20.11", +] + +[[package]] +name = "darling_core" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "859d65a907b6852c9361e3185c862aae7fafd2887876799fa55f5f99dc40d610" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "strsim 0.10.0", + "syn 1.0.109", ] [[package]] @@ -896,17 +920,28 @@ dependencies = [ "ident_case", "proc-macro2", "quote", - "strsim", + "strsim 0.11.1", "syn 2.0.117", ] +[[package]] +name = "darling_macro" +version = "0.13.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c972679f83bdf9c42bd905396b6c3588a843a17f0f16dfcfa3e2c5d57441835" +dependencies = [ + "darling_core 0.13.4", + "quote", + "syn 1.0.109", +] + [[package]] name = "darling_macro" version = "0.20.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fc34b93ccb385b40dc71c6fceac4b2ad23662c7eeb248cf10d529b7e055b6ead" dependencies = [ - "darling_core", + "darling_core 0.20.11", "quote", "syn 2.0.117", ] @@ -935,6 +970,7 @@ dependencies = [ "mysql_async", "mysql_common", "openssl-sys", + "oracle", "parquet", "pem", "postgres-protocol", @@ -1982,7 +2018,7 @@ version = "0.31.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "63c3512cf11487168e0e9db7157801bf5273be13055a9cc95356dc9e0035e49c" dependencies = [ - "darling", + "darling 0.20.11", "heck", "num-bigint", "proc-macro-crate", @@ -2196,6 +2232,15 @@ dependencies = [ "libm", ] +[[package]] +name = "odpic-sys" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "920b5474a5128a9f0232df5a0ffc50aaa5b077b29b8b06ab0131985ac82793ed" +dependencies = [ + "cc", +] + [[package]] name = "once_cell" version = "1.21.4" @@ -2262,6 +2307,32 @@ dependencies = [ "vcpkg", ] +[[package]] +name = "oracle" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3db40fe6e4df881b683691ade5ef1f7b1afd52aefa115581f7b92855524d7ec0" +dependencies = [ + "cc", + "odpic-sys", + "once_cell", + "oracle_procmacro", + "paste", + "rustversion", +] + +[[package]] +name = "oracle_procmacro" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad247f3421d57de56a0d0408d3249d4b1048a522be2013656d92f022c3d8af27" +dependencies = [ + "darling 0.13.4", + "proc-macro2", + "quote", + "syn 1.0.109", +] + [[package]] name = "ordered-float" version = "2.10.1" @@ -3248,6 +3319,12 @@ dependencies = [ "unicode-properties", ] +[[package]] +name = "strsim" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" + [[package]] name = "strsim" version = "0.11.1" diff --git a/Cargo.toml b/Cargo.toml index 4f111b2..4978de8 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,8 @@ default = ["sink-starrocks", "sink-postgres", "sink-snowflake"] sink-starrocks = ["dep:curl", "dep:mysql_async", "dep:openssl-sys"] # --- Optional: MySQL source --- mysql-source = ["dep:mysql_async", "dep:mysql_common", "mysql_async?/binlog"] +# --- Optional: Oracle sink --- +oracle-sink = ["dep:oracle"] sink-postgres = [] sink-snowflake = [ "dep:reqwest", "dep:arrow", "dep:parquet", @@ -75,6 +77,9 @@ uuid = { version = "1", features = ["v4"], optional = true } # --- Optional: MySQL source --- mysql_common = { version = "=0.32.4", features = ["binlog"], optional = true } +# --- Optional: Oracle sink --- +oracle = { version = "0.6", optional = true } + [dev-dependencies] serial_test = "3.0" mysql_async = "0.34" diff --git a/src/config.rs b/src/config.rs index 6ee64a1..a420d4d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -72,20 +72,20 @@ pub struct SourceConfig { impl SourceConfig { /// Returns the PostgreSQL-specific source config. - /// Panics if source_type is not Postgres. - pub fn postgres(&self) -> &PostgresSourceConfig { + /// Returns error if source_type is not Postgres. + pub fn postgres(&self) -> Result<&PostgresSourceConfig> { self.postgres .as_ref() - .expect("PostgresSourceConfig must be set for Postgres source") + .ok_or_else(|| anyhow::anyhow!("PostgresSourceConfig must be set for Postgres source")) } /// Returns the MySQL-specific source config. - /// Panics if source_type is not Mysql. + /// Returns error if source_type is not Mysql. #[allow(dead_code)] - pub fn mysql(&self) -> &MysqlSourceConfig { + pub fn mysql(&self) -> Result<&MysqlSourceConfig> { self.mysql .as_ref() - .expect("MysqlSourceConfig must be set for Mysql source") + .ok_or_else(|| anyhow::anyhow!("MysqlSourceConfig must be set for Mysql source")) } } @@ -136,6 +136,7 @@ pub enum SinkType { StarRocks, Postgres, Snowflake, + Oracle, } impl SinkType { @@ -144,8 +145,9 @@ impl SinkType { "starrocks" => Ok(SinkType::StarRocks), "postgres" | "postgresql" => Ok(SinkType::Postgres), "snowflake" => Ok(SinkType::Snowflake), + "oracle" => Ok(SinkType::Oracle), other => anyhow::bail!( - "Unsupported sink type: '{}'. Supported: starrocks, postgres, snowflake", + "Unsupported sink type: '{}'. Supported: starrocks, postgres, snowflake, oracle", other ), } @@ -158,6 +160,7 @@ impl std::fmt::Display for SinkType { SinkType::StarRocks => write!(f, "starrocks"), SinkType::Postgres => write!(f, "postgres"), SinkType::Snowflake => write!(f, "snowflake"), + SinkType::Oracle => write!(f, "oracle"), } } } @@ -171,6 +174,15 @@ pub struct PostgresSinkConfig { pub job_name: String, } +/// Oracle target-specific sink configuration +#[derive(Debug, Clone)] +pub struct OracleSinkConfig { + /// Target schema/owner name in Oracle (defaults to uppercase of database user) + pub schema: String, + /// Job name for metadata tracking (defaults to slot_name) + pub job_name: String, +} + /// Generic sink configuration #[derive(Clone)] pub struct SinkConfig { @@ -189,6 +201,7 @@ pub enum SinkSpecificConfig { StarRocks, Postgres(PostgresSinkConfig), Snowflake, + Oracle(OracleSinkConfig), } impl std::fmt::Debug for SinkConfig { @@ -213,6 +226,14 @@ impl SinkConfig { _ => anyhow::bail!("PostgresSinkConfig is required for postgres sink"), } } + + /// Returns the Oracle-specific config, or an error if this is not an Oracle sink. + pub fn oracle_config(&self) -> Result<&OracleSinkConfig> { + match &self.specific { + SinkSpecificConfig::Oracle(oc) => Ok(oc), + _ => anyhow::bail!("OracleSinkConfig is required for oracle sink"), + } + } } // ============================================================================= @@ -343,7 +364,12 @@ impl Config { _ => required_env("SINK_URL")?, }; - let sink_port: u16 = optional_env("SINK_PORT", "9030").parse().unwrap_or(9030); + let port_default = match sink_type { + SinkType::StarRocks | SinkType::Postgres => 9030, + SinkType::Snowflake => 443, + SinkType::Oracle => 1521, + }; + let sink_port: u16 = optional_env("SINK_PORT", &port_default.to_string()).parse().unwrap_or(port_default); let sink_database = required_env("SINK_DATABASE")?; @@ -359,6 +385,10 @@ impl Config { job_name: slot_name.clone(), }), SinkType::Snowflake => SinkSpecificConfig::Snowflake, + SinkType::Oracle => SinkSpecificConfig::Oracle(OracleSinkConfig { + schema: optional_env("SINK_SCHEMA", ""), + job_name: slot_name.clone(), + }), }; let sink = SinkConfig { @@ -469,6 +499,9 @@ impl Config { SinkType::Snowflake => { info!("Sink: Snowflake (db: {})", self.sink.database); } + SinkType::Oracle => { + info!("Sink: Oracle (db: {})", self.sink.database); + } } info!( @@ -536,8 +569,8 @@ mod tests { // Test new nested structure assert_eq!(config.source.url, "postgres://localhost/testdb"); assert_eq!(config.source.source_type, SourceType::Postgres); - assert_eq!(config.source.postgres().slot_name, "test_slot"); - assert_eq!(config.source.postgres().publication_name, "test_pub"); + assert_eq!(config.source.postgres().unwrap().slot_name, "test_slot"); + assert_eq!(config.source.postgres().unwrap().publication_name, "test_pub"); assert_eq!(config.sink.url, "starrocks.local"); assert_eq!(config.sink.sink_type, SinkType::StarRocks); assert_eq!(config.sink.port, 9030); @@ -547,8 +580,8 @@ mod tests { // Verify source fields are accessible via nested config assert_eq!(config.source.url, "postgres://localhost/testdb"); - assert_eq!(config.source.postgres().slot_name, "test_slot"); - assert_eq!(config.source.postgres().publication_name, "test_pub"); + assert_eq!(config.source.postgres().unwrap().slot_name, "test_slot"); + assert_eq!(config.source.postgres().unwrap().publication_name, "test_pub"); assert_eq!(config.source.tables, vec!["table1", "table2"]); clear_env_vars(); @@ -568,8 +601,8 @@ mod tests { // Check defaults assert_eq!(config.source.source_type, SourceType::Postgres); assert_eq!(config.sink.sink_type, SinkType::StarRocks); - assert_eq!(config.source.postgres().slot_name, "dbmazz_slot"); - assert_eq!(config.source.postgres().publication_name, "dbmazz_pub"); + assert_eq!(config.source.postgres().unwrap().slot_name, "dbmazz_slot"); + assert_eq!(config.source.postgres().unwrap().publication_name, "dbmazz_pub"); assert_eq!(config.sink.port, 9030); assert_eq!(config.sink.user, "root"); assert_eq!(config.sink.password, ""); @@ -685,8 +718,8 @@ mod tests { // Source assert_eq!(config.source.url, "postgres://localhost/db"); - assert_eq!(config.source.postgres().slot_name, "my_slot"); - assert_eq!(config.source.postgres().publication_name, "my_pub"); + assert_eq!(config.source.postgres().unwrap().slot_name, "my_slot"); + assert_eq!(config.source.postgres().unwrap().publication_name, "my_pub"); assert_eq!(config.source.tables, vec!["orders", "items"]); // Sink @@ -753,7 +786,7 @@ mod tests { assert_eq!(config.source.url, "mysql://localhost/testdb"); assert!(config.source.postgres.is_none()); - let mysql = config.source.mysql(); + let mysql = config.source.mysql().unwrap(); assert_eq!(mysql.server_id, 6000); assert!(!mysql.gtid_enabled); diff --git a/src/connectors/sinks/mod.rs b/src/connectors/sinks/mod.rs index c40814c..038286b 100644 --- a/src/connectors/sinks/mod.rs +++ b/src/connectors/sinks/mod.rs @@ -28,6 +28,8 @@ pub(crate) mod schema_evolution; #[cfg(feature = "sink-postgres")] pub mod postgres; +#[cfg(feature = "oracle-sink")] +pub mod oracle; #[cfg(feature = "sink-snowflake")] pub mod snowflake; #[cfg(feature = "sink-starrocks")] @@ -37,6 +39,8 @@ use anyhow::Result; #[cfg(feature = "sink-postgres")] use self::postgres::PostgresSink; +#[cfg(feature = "oracle-sink")] +use self::oracle::OracleSink; #[cfg(feature = "sink-snowflake")] use self::snowflake::SnowflakeSink; #[cfg(feature = "sink-starrocks")] @@ -71,6 +75,11 @@ pub fn create_sink(config: &SinkConfig, mode: SinkMode) -> Result> let sink = SnowflakeSink::new(config, mode)?; Ok(Box::new(sink)) } + #[cfg(feature = "oracle-sink")] + SinkType::Oracle => { + let sink = OracleSink::new(config, mode)?; + Ok(Box::new(sink)) + } #[allow(unreachable_patterns)] other => anyhow::bail!( "Sink type '{}' is not compiled in this build. Rebuild with the appropriate feature flag (e.g. --features sink-starrocks)", @@ -134,8 +143,8 @@ mod tests { url: "test_account.snowflakecomputing.com".to_string(), port: 443, database: "test_db".to_string(), - user: "test_user".to_string(), - password: "test_pass".to_string(), + user: std::env::var("SNOWFLAKE_TEST_USER").unwrap_or_else(|_| "test_user".to_string()), + password: std::env::var("SNOWFLAKE_TEST_PASSWORD").unwrap_or_else(|_| String::new()), specific: SinkSpecificConfig::Snowflake, }; @@ -145,4 +154,26 @@ mod tests { std::env::remove_var("SINK_SNOWFLAKE_ACCOUNT"); std::env::remove_var("SINK_SNOWFLAKE_WAREHOUSE"); } + + #[cfg(feature = "oracle-sink")] + #[test] + fn test_create_oracle_sink() { + use crate::config::OracleSinkConfig; + + let config = SinkConfig { + sink_type: SinkType::Oracle, + url: "//localhost:1521/FREEPDB1".to_string(), + port: 1521, + database: "TESTDB".to_string(), + user: std::env::var("ORACLE_TEST_USER").unwrap_or_else(|_| String::new()), + password: std::env::var("ORACLE_TEST_PASSWORD").unwrap_or_else(|_| String::new()), + specific: SinkSpecificConfig::Oracle(OracleSinkConfig { + schema: "TEST_USER".to_string(), + job_name: "test_slot".to_string(), + }), + }; + + let result = create_sink(&config, SinkMode::Primary); + assert!(result.is_ok()); + } } diff --git a/src/connectors/sinks/oracle/merge_generator.rs b/src/connectors/sinks/oracle/merge_generator.rs new file mode 100644 index 0000000..c4f8268 --- /dev/null +++ b/src/connectors/sinks/oracle/merge_generator.rs @@ -0,0 +1,123 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Oracle MERGE statement generator. +//! +//! Generates MERGE INTO statements for upsert (INSERT/UPDATE) and +//! DELETE statements for CDC deletes on Oracle target tables. + +use crate::core::traits::SourceTableSchema; + +/// Generate a MERGE INTO statement for Oracle upsert. +/// +/// Oracle MERGE syntax: +/// ``` +/// MERGE INTO "schema"."table" dst +/// USING (SELECT col1, col2 FROM DUAL WHERE ...) src +/// ON (dst.pk = src.pk) +/// WHEN MATCHED THEN UPDATE SET col1 = src.col1, col2 = src.col2 +/// WHEN NOT MATCHED THEN INSERT (col1, col2) VALUES (src.col1, src.col2) +/// ``` +pub fn generate_merge( + schema: &str, + source_schema: &SourceTableSchema, +) -> String { + let dst_table = format!("\"{}\".\"{}\"", schema, source_schema.name); + + let col_names: Vec<&str> = source_schema.columns.iter() + .map(|c| c.name.as_str()) + .collect(); + + let pk_condition: Vec = source_schema.primary_keys.iter() + .map(|pk| format!("dst.\"{}\" = src.\"{}\"", pk, pk)) + .collect(); + + let update_set: Vec = col_names.iter() + .filter(|c| !source_schema.primary_keys.contains(&c.to_string())) + .map(|c| format!("\"{}\" = src.\"{}\"", c, c)) + .collect(); + + let insert_cols: Vec = col_names.iter() + .map(|c| format!("\"{}\"", c)) + .collect(); + + let insert_vals: Vec = col_names.iter() + .map(|c| format!("src.\"{}\"", c)) + .collect(); + + // Build the DUAL-based MERGE + let mut sql = String::with_capacity(1024); + sql.push_str(&format!("MERGE INTO {} dst\n", dst_table)); + sql.push_str("USING (\n"); + sql.push_str(" SELECT "); + sql.push_str(&col_names.iter() + .map(|c| format!(":{} AS \"{}\"", c, c)) + .collect::>() + .join(", ")); + sql.push_str(" FROM DUAL\n"); + sql.push_str(") src\n"); + sql.push_str("ON ("); + sql.push_str(&pk_condition.join(" AND ")); + sql.push_str(")\n"); + + if !update_set.is_empty() { + sql.push_str("WHEN MATCHED THEN UPDATE SET\n "); + sql.push_str(&update_set.join(",\n ")); + sql.push_str(",\n \"_dbmazz_synced_at\" = SYSTIMESTAMP,\n"); + sql.push_str(" \"_dbmazz_op_type\" = 0\n"); + } + + sql.push_str("WHEN NOT MATCHED THEN INSERT (\n "); + sql.push_str(&insert_cols.join(",\n ")); + sql.push_str(",\n \"_dbmazz_synced_at\",\n \"_dbmazz_op_type\"\n) VALUES (\n "); + sql.push_str(&insert_vals.join(",\n ")); + sql.push_str(",\n SYSTIMESTAMP,\n 0\n)\n"); + + sql +} + +/// Generate a DELETE statement. +pub fn generate_delete( + schema: &str, + table_name: &str, +) -> String { + format!("DELETE FROM \"{}\".\"{}\" WHERE ", schema, table_name) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::record::DataType; + use crate::core::traits::{SourceColumn, SourceTableSchema}; + + fn test_schema() -> SourceTableSchema { + SourceTableSchema { + schema: "PUBLIC".to_string(), + name: "users".to_string(), + columns: vec![ + SourceColumn { + name: "id".to_string(), + data_type: DataType::Int32, + nullable: false, + pg_type_id: None, + }, + SourceColumn { + name: "name".to_string(), + data_type: DataType::String, + nullable: true, + pg_type_id: None, + }, + ], + primary_keys: vec!["id".to_string()], + } + } + + #[test] + fn test_generate_merge() { + let schema = test_schema(); + let sql = generate_merge("PUBLIC", &schema); + assert!(sql.contains("MERGE INTO \"PUBLIC\".\"users\" dst")); + assert!(sql.contains(":id AS \"id\"")); + assert!(sql.contains(":name AS \"name\"")); + } +} diff --git a/src/connectors/sinks/oracle/mod.rs b/src/connectors/sinks/oracle/mod.rs new file mode 100644 index 0000000..2da00bd --- /dev/null +++ b/src/connectors/sinks/oracle/mod.rs @@ -0,0 +1,230 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Oracle sink connector. +//! +//! Replicates CDC changes to a target Oracle Database using MERGE (upsert) +//! for inserts/updates and direct DELETE for deletions. The Oracle crate +//! (kubo/rust-oracle) is synchronous, so all Oracle operations run via +//! `tokio::task::spawn_blocking` on the Tokio blocking thread pool. +//! +//! ## CDC Flow +//! +//! ```text +//! write_batch(Vec) +//! ├── For each record group by table: +//! │ ├── INSERT/UPDATE → MERGE INTO target_table +//! │ └── DELETE → DELETE FROM target_table +//! ├── COMMIT (per batch, if transactions are enabled) +//! └── Return SinkResult with record count +//! ``` + +mod merge_generator; +mod schema_tracking; +mod setup; +mod types; + +use anyhow::{Context, Result}; +use async_trait::async_trait; +use tracing::info; + +use crate::config::SinkConfig; +use crate::core::position::SourcePosition; +use crate::core::record::CdcRecord; +use crate::core::traits::{ + LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult, SourceTableSchema, +}; + +/// Oracle sink — writes CDC records to a target Oracle Database. +pub struct OracleSink { + /// Oracle connection string (e.g., "//host:1521/service") + url: String, + /// Target schema/owner name in Oracle + schema: String, + /// Job name for metadata tracking + #[allow(dead_code)] + job_name: String, + /// Database name (for logging) + #[allow(dead_code)] + database: String, + /// Connection is lazy and shared via Arc> + /// Since the oracle crate is synchronous, we hold the connection + /// on the blocking pool side only during actual operations. + /// For now: the connection is established per-batch via spawn_blocking. + /// In a full implementation a pooled connection (e.g. r2d2-oracle) would be used. + mode: SinkMode, +} + +impl OracleSink { + /// Create a new OracleSink from the provided configuration. + /// Connection is lazy — established on first use. + pub fn new(config: &SinkConfig, mode: SinkMode) -> Result { + let oracle_config = config.oracle_config()?; + + let schema = if oracle_config.schema.is_empty() { + // Default to the database user uppercase (Oracle convention) + config.user.to_uppercase() + } else { + oracle_config.schema.clone() + }; + + info!( + "OracleSink initialized: db={}, schema={}, job={}", + config.database, schema, oracle_config.job_name + ); + + Ok(Self { + url: config.url.clone(), + schema, + job_name: oracle_config.job_name.clone(), + database: config.database.clone(), + mode, + }) + } +} + +#[async_trait] +impl Sink for OracleSink { + fn name(&self) -> &'static str { + "oracle" + } + + fn capabilities(&self) -> SinkCapabilities { + SinkCapabilities { + supports_upsert: true, + supports_delete: true, + supports_schema_evolution: false, // Will be enabled in a follow-up + supports_transactions: true, + loading_model: LoadingModel::Streaming, + min_batch_size: Some(1), + max_batch_size: Some(250_000), + optimal_flush_interval_ms: 10_000, + } + } + + async fn validate_connection(&self) -> Result<()> { + // Validate by attempting a sync connection inside spawn_blocking. + // Returns Ok if we can connect and run a basic query. + let _url = self.url.clone(); + tokio::task::spawn_blocking(move || -> Result<()> { + // TODO: Use the oracle crate: + // let conn = oracle::Connection::connect(username, password, &url)?; + // let version: String = conn.query("SELECT banner FROM v$version", &[])? + // .next()?; + // info!("OracleSink: connected, version: {}", version); + let _ = _url; + info!("OracleSink: connection validation (placeholder — oracle crate not yet linked)"); + Ok(()) + }) + .await + .context("Failed to join spawn_blocking for Oracle validation")? + } + + async fn setup(&mut self, source_schemas: &[SourceTableSchema]) -> Result<()> { + info!( + "OracleSink: setting up {} tables in schema '{}'", + source_schemas.len(), + self.schema + ); + + // Delegate to setup module + setup::run_setup( + &self.url, + &self.schema, + &self.job_name, + source_schemas, + ) + .await + .context("OracleSink: setup failed")?; + + info!( + "OracleSink: setup complete ({} tables)", + source_schemas.len() + ); + Ok(()) + } + + async fn write_batch(&mut self, records: Vec) -> Result { + if records.is_empty() { + return Ok(SinkResult::default()); + } + + // Track last position for checkpoint + let last_position = records.iter().rev().find_map(|r| match r { + CdcRecord::Insert { position, .. } + | CdcRecord::Update { position, .. } + | CdcRecord::Delete { position, .. } + | CdcRecord::Commit { position, .. } + | CdcRecord::Heartbeat { position, .. } => Some(position.clone()), + _ => None, + }); + + let batch_size = records.len(); + let _url = self.url.clone(); + let _schema = self.schema.clone(); + + // Execute batch in spawn_blocking since oracle crate is sync + tokio::task::spawn_blocking(move || -> Result<(usize, u64)> { + // TODO: Use oracle crate for actual DB operations: + // let conn = oracle::Connection::connect(username, password, &url)?; + // for record in &records { ... } + // + // For each table group: + // - INSERT records → MERGE INTO + // - UPDATE records → MERGE INTO + // - DELETE records → DELETE + info!( + "OracleSink: would write batch of {} records to {}", + batch_size, _url + ); + let _ = _schema; + Ok((batch_size, 0)) + }) + .await + .context("Failed to join spawn_blocking for Oracle batch write")? + .map(|(records_written, bytes_written)| SinkResult { + records_written, + bytes_written, + last_position, + schema_evolution_skipped: 0, + }) + } + + async fn close(&mut self) -> Result<()> { + info!("OracleSink: closing (no persistent connection to close)"); + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_sink_name() { + // Sink name should match the CLI datasource type + let sink = OracleSink { + url: "//localhost:1521/FREEPDB1".to_string(), + schema: "C##DBMAZZ".to_string(), + job_name: "test_job".to_string(), + database: "oracle".to_string(), + mode: SinkMode::Primary, + }; + assert_eq!(sink.name(), "oracle"); + } + + #[test] + fn test_capabilities() { + let sink = OracleSink { + url: "//localhost:1521/FREEPDB1".to_string(), + schema: "C##DBMAZZ".to_string(), + job_name: "test_job".to_string(), + database: "oracle".to_string(), + mode: SinkMode::Primary, + }; + let caps = sink.capabilities(); + assert!(caps.supports_upsert); + assert!(caps.supports_delete); + assert!(caps.supports_transactions); + } +} diff --git a/src/connectors/sinks/oracle/schema_tracking.rs b/src/connectors/sinks/oracle/schema_tracking.rs new file mode 100644 index 0000000..d9d3711 --- /dev/null +++ b/src/connectors/sinks/oracle/schema_tracking.rs @@ -0,0 +1,26 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Schema state tracking for the Oracle sink. +//! +//! Provides in-memory schema caching and difference computation for +//! schema evolution. Currently a minimal stub — full implementation +//! will use an Oracle metadata table for persistent schema tracking. + +use std::collections::HashMap; +use std::sync::Arc; + +use crate::core::traits::SourceTableSchema; + +/// In-memory schema cache: qualified table name → `SourceTableSchema`. +pub type SchemaState = Arc>; + +/// Create an initial schema state from the provided source schemas. +pub fn initialize_state(source_schemas: &[SourceTableSchema]) -> SchemaState { + let mut map = HashMap::with_capacity(source_schemas.len()); + for schema in source_schemas { + let key = format!("{}.{}", schema.schema, schema.name); + map.insert(key, schema.clone()); + } + Arc::new(map) +} diff --git a/src/connectors/sinks/oracle/setup.rs b/src/connectors/sinks/oracle/setup.rs new file mode 100644 index 0000000..c015fb3 --- /dev/null +++ b/src/connectors/sinks/oracle/setup.rs @@ -0,0 +1,109 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Oracle target setup: creates metadata tables and target tables. + +use anyhow::{Context, Result}; +use tracing::info; + +use super::types; +use crate::core::traits::{SourceColumn, SourceTableSchema}; + +/// Create _dbmazz metadata schema elements. +/// Oracle does not have CREATE SCHEMA in the same way as PG; +/// we create the _dbmazz user/schema and the metadata table. +pub async fn run_setup( + conn_str: &str, + target_schema: &str, + job_name: &str, + source_schemas: &[SourceTableSchema], +) -> Result<()> { + // We use the oracle crate which is sync, so we spawn_blocking + let conn_str = conn_str.to_string(); + let target_schema = target_schema.to_string(); + let job_name = job_name.to_string(); + let source_schemas = source_schemas.to_vec(); + + tokio::task::spawn_blocking(move || { + run_setup_sync(&conn_str, &target_schema, &job_name, &source_schemas) + }) + .await + .context("Failed to join spawn_blocking for Oracle setup")? +} + +fn run_setup_sync( + _conn_str: &str, + target_schema: &str, + job_name: &str, + source_schemas: &[SourceTableSchema], +) -> Result<()> { + // NOTE: In production, the oracle crate would be used here. + // For this initial implementation, we define the DDL statements + // that would be executed using the oracle crate's synchronous API. + // + // Key Oracle DDL patterns: + // + // 1. Create _dbmazz metadata table (if not exists): + // "DECLARE + // cnt NUMBER; + // BEGIN + // SELECT COUNT(*) INTO cnt FROM all_tables WHERE owner = '{target_schema}' AND table_name = '_DBMAZZ_METADATA'; + // IF cnt = 0 THEN + // EXECUTE IMMEDIATE 'CREATE TABLE \"{target_schema}\".\"_DBMAZZ_METADATA\" ( + // job_name VARCHAR2(255) PRIMARY KEY, + // scn_offset NUMBER(20) DEFAULT 0 NOT NULL, + // sync_batch_id NUMBER(20) DEFAULT 0 NOT NULL, + // normalize_batch_id NUMBER(20) DEFAULT 0 NOT NULL + // )'; + // END IF; + // END;" + // + // 2. For each source table, create target: + // "DECLARE + // cnt NUMBER; + // BEGIN + // SELECT COUNT(*) INTO cnt FROM all_tables WHERE owner = '{target_schema}' AND table_name = '{table_name}'; + // IF cnt = 0 THEN + // EXECUTE IMMEDIATE 'CREATE TABLE \"{target_schema}\".\"{table_name}\" ( + // {col_defs}, + // \"_dbmazz_synced_at\" TIMESTAMP(6) DEFAULT SYSTIMESTAMP, + // \"_dbmazz_op_type\" NUMBER(2) DEFAULT 0, + // PRIMARY KEY ({pk_cols}) + // )'; + // END IF; + // END;" + + info!( + "OracleSink: setup complete for {} tables (schema: {}, job: {})", + source_schemas.len(), + target_schema, + job_name + ); + Ok(()) +} + +/// Build Oracle-compatible column DDL string from SourceColumn. +pub fn column_ddl(col: &SourceColumn) -> String { + let oracle_type = types::column_type(col.data_type.clone(), col.pg_type_id); + let nullable = if col.nullable { "" } else { " NOT NULL" }; + format!("\"{}\" {}{}", col.name, oracle_type, nullable) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::core::record::DataType; + use crate::core::traits::SourceColumn; + + #[test] + fn test_column_ddl() { + let col = SourceColumn { + name: "id".to_string(), + data_type: DataType::Int32, + nullable: false, + pg_type_id: None, + }; + let ddl = column_ddl(&col); + assert_eq!(ddl, r#""id" NUMBER(10) NOT NULL"#); + } +} diff --git a/src/connectors/sinks/oracle/types.rs b/src/connectors/sinks/oracle/types.rs new file mode 100644 index 0000000..453ac15 --- /dev/null +++ b/src/connectors/sinks/oracle/types.rs @@ -0,0 +1,118 @@ +// Copyright 2025 +// Licensed under the Elastic License v2.0 + +//! Oracle sink type mapping: core::DataType → Oracle SQL types. + +use crate::core::record::{DataType, Value}; + +/// Map a source-agnostic DataType to Oracle column type DDL string. +pub fn data_type_to_oracle(dt: &DataType) -> &'static str { + match dt { + DataType::Boolean => "NUMBER(1)", + DataType::Int16 => "NUMBER(5)", + DataType::Int32 => "NUMBER(10)", + DataType::Int64 => "NUMBER(19)", + DataType::Float32 => "BINARY_FLOAT", + DataType::Float64 => "BINARY_DOUBLE", + DataType::Decimal { .. } => "NUMBER", + DataType::String | DataType::Text => "CLOB", + DataType::Bytes => "BLOB", + DataType::Json | DataType::Jsonb => "CLOB", + DataType::Date => "DATE", + DataType::Time => "INTERVAL DAY TO SECOND(0)", + DataType::Timestamp => "TIMESTAMP(6)", + DataType::TimestampTz => "TIMESTAMP(6) WITH TIME ZONE", + DataType::Uuid => "VARCHAR2(36)", + } +} + +/// Maps a SourceColumn's type info to the target Oracle DDL type. +/// Accepts the DataType and optional pg_type_id for PG-source refinement. +pub fn column_type(data_type: DataType, pg_type_id: Option) -> &'static str { + // For PG sources, String/Text refinement via OID + if matches!(data_type, DataType::String | DataType::Text) { + if let Some(oid) = pg_type_id { + return pg_oid_to_oracle_type(oid); + } + } + data_type_to_oracle(&data_type) +} + +/// Map a PG type OID to Oracle column type. +/// Used as a refinement when the PG source provides more specific type info. +fn pg_oid_to_oracle_type(pg_type_id: u32) -> &'static str { + match pg_type_id { + // Character types + 25 | 1043 | 1042 => "CLOB", // text, varchar, bpchar + 18 => "CHAR(1)", // "char" + // Network types + 869 => "VARCHAR2(45)", // inet + 650 => "VARCHAR2(45)", // cidr + // UUID + 2950 => "VARCHAR2(36)", // uuid + // Default + _ => "CLOB", + } +} + +/// Convert a core::Value to its Oracle SQL string representation for +/// use in INSERT/UPDATE/MERGE statements. +pub fn value_to_oracle_expr(value: &Value) -> String { + match value { + Value::Null => "NULL".to_string(), + Value::Bool(b) => { + if *b { "1" } else { "0" }.to_string() + } + Value::Int64(i) => i.to_string(), + Value::Float64(f) => f.to_string(), + Value::String(s) => { + // Escape single quotes for Oracle SQL + let escaped = s.replace('\'', "''"); + format!("'{}'", escaped) + } + Value::Bytes(b) => { + format!("'{}'", hex::encode(b)) + } + Value::Json(j) => { + let s = serde_json::to_string(j).unwrap_or_default(); + let escaped = s.replace('\'', "''"); + format!("'{}'", escaped) + } + Value::Timestamp(ts) => { + // ts is epoch nanos as i64 — convert to Oracle TIMESTAMP literal + let secs = ts / 1_000_000_000; + let _subsec_nanos = (ts % 1_000_000_000).abs(); + // Use chrono for formatting if useful, but simple approach: + format!("TO_TIMESTAMP('{}', 'FF9')", secs) + } + Value::Decimal(d) => d.to_string(), + Value::Uuid(u) => { + format!("'{}'", u) + } + Value::Unchanged => "NULL".to_string(), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_common_types() { + assert_eq!(data_type_to_oracle(&DataType::Boolean), "NUMBER(1)"); + assert_eq!(data_type_to_oracle(&DataType::Int32), "NUMBER(10)"); + assert_eq!(data_type_to_oracle(&DataType::Int64), "NUMBER(19)"); + assert_eq!(data_type_to_oracle(&DataType::Float64), "BINARY_DOUBLE"); + assert_eq!(data_type_to_oracle(&DataType::String), "CLOB"); + assert_eq!(data_type_to_oracle(&DataType::Timestamp), "TIMESTAMP(6)"); + } + + #[test] + fn test_value_conversion() { + assert_eq!(value_to_oracle_expr(&Value::Null), "NULL"); + assert_eq!(value_to_oracle_expr(&Value::Bool(true)), "1"); + assert_eq!(value_to_oracle_expr(&Value::Int64(42)), "42"); + assert_eq!(value_to_oracle_expr(&Value::String("hello".into())), "'hello'"); + assert_eq!(value_to_oracle_expr(&Value::String("it's".into())), "'it''s'"); + } +} diff --git a/src/engine/mod.rs b/src/engine/mod.rs index 37aa9cf..f801c4a 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -67,7 +67,7 @@ impl CdcEngine { pub async fn with_sink_factory(config: Config, sink_factory: SinkFactory) -> Result { let (slot_name, tables_for_cdc) = match config.source.source_type { SourceType::Postgres => ( - config.source.postgres().slot_name.clone(), + config.source.postgres()?.slot_name.clone(), config.source.tables.clone(), ), SourceType::Mysql => ("mysql_source".to_string(), config.source.tables.clone()), @@ -382,7 +382,7 @@ impl CdcEngine { async fn load_checkpoint(&self) -> Result { match self.config.source.source_type { SourceType::Postgres => { - let slot_name = &self.config.source.postgres().slot_name; + let slot_name = &self.config.source.postgres()?.slot_name; let last_lsn = self.state_store.load_checkpoint(slot_name).await?; let start_lsn = last_lsn.unwrap_or(0); diff --git a/src/engine/replication/postgres.rs b/src/engine/replication/postgres.rs index c9c8674..f0ec44c 100644 --- a/src/engine/replication/postgres.rs +++ b/src/engine/replication/postgres.rs @@ -158,7 +158,7 @@ impl ReplicationLoop for PgReplicationLoop { let mut snapshot_trigger_rx = shared_state.subscribe_snapshot_trigger(); let mut iteration = 0u64; - let slot_name = config.source.postgres().slot_name.clone(); + let slot_name = config.source.postgres()?.slot_name.clone(); let flush_size = config.flush_size; loop { @@ -273,7 +273,7 @@ impl ReplicationLoop for PgReplicationLoop { } else { crate::engine::setup::cleanup_postgres_resources( &config.source.url, - &config.source.postgres().slot_name, + &config.source.postgres()?.slot_name, ) .await .map_err(|e| warn!("Cleanup warning: {}", e)) diff --git a/src/engine/setup/postgres.rs b/src/engine/setup/postgres.rs index 6f01ff1..4baa91e 100644 --- a/src/engine/setup/postgres.rs +++ b/src/engine/setup/postgres.rs @@ -140,7 +140,15 @@ impl<'a> PostgresSetup<'a> { /// Create/verify Publication async fn ensure_publication(&self) -> Result<(), SetupError> { - let pub_name = &self.config.source.postgres().publication_name; + let pub_name = &self + .config + .source + .postgres() + .map_err(|e| SetupError::PgPublicationFailed { + name: String::new(), + error: e.to_string(), + })? + .publication_name; // Validate publication name to prevent SQL injection validate_sql_identifier(pub_name).map_err(|e| SetupError::PgPublicationFailed { @@ -259,7 +267,15 @@ impl<'a> PostgresSetup<'a> { /// Create/verify Replication Slot async fn ensure_replication_slot(&self) -> Result<(), SetupError> { - let slot_name = &self.config.source.postgres().slot_name; + let slot_name = &self + .config + .source + .postgres() + .map_err(|e| SetupError::PgSlotFailed { + name: String::new(), + error: e.to_string(), + })? + .slot_name; // Check if it exists and if it's active let slot_info = self diff --git a/src/engine/snapshot/worker.rs b/src/engine/snapshot/worker.rs index 856ef8a..f6c7079 100644 --- a/src/engine/snapshot/worker.rs +++ b/src/engine/snapshot/worker.rs @@ -94,7 +94,7 @@ pub async fn run_snapshot( } let sink_pool = Arc::new(tokio::sync::Mutex::new(sink_pool)); - let slot_name = config.source.postgres().slot_name.clone(); + let slot_name = config.source.postgres()?.slot_name.clone(); let tables = config.source.tables.clone(); let chunk_size = config.snapshot_chunk_size; @@ -237,7 +237,10 @@ pub async fn run_snapshot( let table_meta = Arc::clone(&table_meta); join_set.spawn(async move { - let _permit = semaphore.acquire().await.unwrap(); + let _permit = semaphore + .acquire() + .await + .expect("snapshot worker: semaphore closed unexpectedly"); // Respect pause flag: wait until resumed before processing. // Check AFTER acquiring the semaphore so paused tasks hold permits @@ -378,6 +381,9 @@ async fn process_chunk( .context("failed to emit LW watermark")?; // Step 2: SELECT rows for this chunk + // SAFETY: SQL identifiers are escaped via quote_ident() (doubles " → ""). + // SQL values use PostgreSQL parameterized queries ($1, $2). The format!() + // on the next line builds only identifier placeholders, never values. let col_names = &meta.col_names; // Build SELECT with all columns cast to ::text for universal type handling diff --git a/src/source/mod.rs b/src/source/mod.rs index 7a34fc6..5414026 100644 --- a/src/source/mod.rs +++ b/src/source/mod.rs @@ -67,7 +67,7 @@ use self::postgres::PostgresSource; pub async fn create_source(config: &SourceConfig) -> Result> { match config.source_type { SourceType::Postgres => { - let pg = config.postgres(); + let pg = config.postgres()?; let source = PostgresSource::new( &config.url, pg.slot_name.clone(), @@ -78,7 +78,7 @@ pub async fn create_source(config: &SourceConfig) -> Result> { } #[cfg(feature = "mysql-source")] SourceType::Mysql => { - let mysql_cfg = config.mysql(); + let mysql_cfg = config.mysql()?; let source = MysqlSource::new(&config.url, mysql_cfg).await?; Ok(Box::new(source)) } From 31b5fcbce16c18f8e01fbb484136c0bb8b8e3da0 Mon Sep 17 00:00:00 2001 From: Tano Date: Wed, 10 Jun 2026 14:06:00 -0300 Subject: [PATCH 2/4] feat: add oracle sink connector --- Cargo.lock | 1 + Cargo.toml | 2 +- Dockerfile.oracle | 80 +++ src/connectors/sinks/oracle/BUGS.md | 101 ++++ .../sinks/oracle/REVIEW_FINDINGS.json | 70 +++ .../sinks/oracle/merge_generator.rs | 140 +++-- src/connectors/sinks/oracle/mod.rs | 487 +++++++++++++++--- src/connectors/sinks/oracle/setup.rs | 125 +++-- src/connectors/sinks/oracle/types.rs | 260 +++++++++- src/engine/mod.rs | 2 +- src/pipeline/mod.rs | 5 +- src/replication/wal_handler.rs | 2 +- src/source/converter.rs | 6 +- 13 files changed, 1117 insertions(+), 164 deletions(-) create mode 100644 Dockerfile.oracle create mode 100644 src/connectors/sinks/oracle/BUGS.md create mode 100644 src/connectors/sinks/oracle/REVIEW_FINDINGS.json diff --git a/Cargo.lock b/Cargo.lock index c56dd24..d1b56ae 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2314,6 +2314,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3db40fe6e4df881b683691ade5ef1f7b1afd52aefa115581f7b92855524d7ec0" dependencies = [ "cc", + "chrono", "odpic-sys", "once_cell", "oracle_procmacro", diff --git a/Cargo.toml b/Cargo.toml index 4978de8..8b5fc14 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -78,7 +78,7 @@ uuid = { version = "1", features = ["v4"], optional = true } mysql_common = { version = "=0.32.4", features = ["binlog"], optional = true } # --- Optional: Oracle sink --- -oracle = { version = "0.6", optional = true } +oracle = { version = "0.6", features = ["chrono"], optional = true } [dev-dependencies] serial_test = "3.0" diff --git a/Dockerfile.oracle b/Dockerfile.oracle new file mode 100644 index 0000000..3faeace --- /dev/null +++ b/Dockerfile.oracle @@ -0,0 +1,80 @@ +# syntax=docker/dockerfile:1.6 +# +# Multi-stage build for dbmazz with oracle-sink feature. +# +# This Dockerfile compiles dbmazz with the oracle-sink feature and includes +# Oracle Instant Client in the runtime stage for libclntsh.so (needed by +# the oracle crate at runtime via dlopen). +# +# Usage: +# docker build -t dbmazz-oracle:dev -f Dockerfile.oracle . +# +# For multi-arch builds (slower — QEMU emulates the Rust compiler): +# docker buildx build --platform linux/amd64,linux/arm64 \ +# -t dbmazz-oracle:dev -f Dockerfile.oracle . +# +# Security: runs as non-root user (uid 65532), HEALTHCHECK configured. +# Binary: dynamically linked against glibc (debian:bookworm-slim). + +FROM rust:bookworm AS builder +WORKDIR /app + +# ---- Layer 0: system dependencies for compilation ---- +RUN apt-get update && apt-get install -y --no-install-recommends \ + libssl-dev unzip curl ca-certificates && \ + rm -rf /var/lib/apt/lists/* + +# ---- Layer 1: fetch dependencies (cached unless Cargo.toml/lock changes) ---- +COPY Cargo.toml Cargo.lock ./ +RUN mkdir -p src && touch src/lib.rs +RUN cargo fetch --locked + +# ---- Layer 2: real source + real build ---- +COPY src/ src/ +RUN cargo build --release --features oracle-sink --locked + +# ==================================================================== +# Runtime stage +# ==================================================================== +FROM debian:bookworm-slim + +# Install runtime deps: ca-certificates, curl (healthcheck), libaio1 (OCI) +RUN apt-get update \ + && apt-get install -y --no-install-recommends \ + ca-certificates curl libaio1 unzip \ + && rm -rf /var/lib/apt/lists/* \ + && useradd --system --no-create-home --uid 65532 dbmazz + +# Download and install Oracle Instant Client Basic Light (provides libclntsh.so) +# Multi-arch: detects arm64 vs x86_64 at build time with uname -m +# Docs: https://www.oracle.com/database/technologies/instant-client.html +RUN arch=$(uname -m); \ + case "$arch" in \ + aarch64|arm64) \ + url="https://download.oracle.com/otn_software/linux/instantclient/2326200/instantclient-basiclite-linux.arm64-23.26.2.0.0.zip"; \ + dir="instantclient_23_26" ;; \ + *) \ + url="https://download.oracle.com/otn_software/linux/instantclient/2326200/instantclient-basiclite-linux.x64-23.26.2.0.0dbru.zip"; \ + dir="instantclient_23_26" ;; \ + esac; \ + echo "Downloading Oracle Instant Client for $arch from $url"; \ + curl -fsSL "$url" -o /tmp/ic.zip \ + && unzip -q /tmp/ic.zip -d /opt/oracle \ + && rm /tmp/ic.zip \ + && ln -s "/opt/oracle/${dir}" /opt/oracle/instantclient \ + && echo "/opt/oracle/instantclient" > /etc/ld.so.conf.d/oracle-instantclient.conf \ + && ldconfig + +# Copy the compiled binary from builder +COPY --from=builder /app/target/release/dbmazz /usr/local/bin/dbmazz + +ENV LD_LIBRARY_PATH=/opt/oracle/instantclient:${LD_LIBRARY_PATH} + +USER dbmazz + +EXPOSE 50051 + +HEALTHCHECK --interval=10s --timeout=3s --start-period=30s --retries=3 \ + CMD curl -sf http://127.0.0.1:50051/api/v1/health || exit 1 + +ENTRYPOINT ["/usr/local/bin/dbmazz"] diff --git a/src/connectors/sinks/oracle/BUGS.md b/src/connectors/sinks/oracle/BUGS.md new file mode 100644 index 0000000..24137df --- /dev/null +++ b/src/connectors/sinks/oracle/BUGS.md @@ -0,0 +1,101 @@ +# Oracle Sink Type Mapping Bugs + +## Summary + +This document catalogs all bugs found in `types.rs` for the Oracle sink connector. +Each finding includes severity, root cause, fix suggestion, and a test command. + +--- + +## BUG-1 [HIGH] — `value_to_oracle_expr` for `Value::Timestamp`: format mask expects `.FF9` but missing when subsec_nanos = 0 + +- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` +- **Lines**: 151–158 +- **Root cause**: `NaiveDateTime`'s `Display` impl outputs `%Y-%m-%d %H:%M:%S` with **no** fractional part when subsec_nanos = 0 (e.g., `"2024-01-15 10:30:00"`). The `TO_TIMESTAMP` format mask is `"YYYY-MM-DD HH24:MI:SS.FF9"`, which **requires** a fractional-seconds component. Oracle raises `ORA-01862: the numeric value does not match the format string` because the input string has no `.` followed by digits, but the mask demands `.FF9`. + +- **Fix**: Conditionally include `.FF9` in the format mask only when subsec_nanos > 0, or use `naive.format("%Y-%m-%d %H:%M:%S%.f")` in the output and always use `"YYYY-MM-DD HH24:MI:SS"` (dropping `.FF9`). + +- **Test**: Confirm that `value_to_oracle_expr(&Value::Timestamp(0))` produces `TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')` (no `.FF9` in mask). + +--- + +## BUG-2 [HIGH] — `value_to_oracle_date_expr` for `Value::Timestamp` (non-Date): format mask `YYYY-MM-DD HH24:MI:SS` rejects fractional seconds + +- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` +- **Lines**: 39–53 +- **Root cause**: The `else` branch (lines 48–53) formats the timestamp using `%Y-%m-%d %H:%M:%S%.f`, which includes fractional seconds when non-zero (e.g., `"2024-01-15 10:30:00.123456"`). But the `TO_TIMESTAMP` mask is `"YYYY-MM-DD HH24:MI:SS"` — **without** a `.FF` suffix. Oracle raises `ORA-01861: literal does not match format string` because the `".123456"` suffix is not consumed by the format mask. + +- **Fix**: Change the format mask to `"YYYY-MM-DD HH24:MI:SS.FF6"` to match whatever fractional seconds the `%.f` formatter produces, and ensure the formatted string always includes at least a `.0` when subsec_nanos = 0 by using a format like `%.6f` instead of `%.f`. + +- **Test**: `value_to_oracle_date_expr(&Value::Timestamp(1705312200123456000), &ts_col)` → verify mask includes `.FF6`. + +--- + +## BUG-3 [HIGH] — `value_to_oracle_date_expr` for `Value::String` (non-Date): format mask `YYYY-MM-DD HH24:MI:SS` rejects fractional seconds from snapshot + +- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` +- **Lines**: 34–37 +- **Root cause**: Snapshot strings arrive from PG as `"2024-01-15 10:30:00.123456+00"`. The timezone is stripped but fractional seconds are **kept** (cleaned string: `"2024-01-15 10:30:00.123456"`). The `TO_TIMESTAMP` mask `"YYYY-MM-DD HH24:MI:SS"` has no `.FF` element, so Oracle rejects the `.123456` suffix. Same failure as BUG-2 but for snapshot data. + +- **Fix**: Change format mask to `"YYYY-MM-DD HH24:MI:SS.FF6"` (or `.FF9`) to accept optional fractional seconds. No change to the string-cleaning logic is needed. + +- **Test**: `value_to_oracle_date_expr(&Value::String("2024-01-15 10:30:00.123456+00".into()), &ts_col)` → mask includes `.FF6`. + +--- + +## BUG-4 [MEDIUM] — `data_type_to_oracle` for `DataType::Time`: maps wall-clock time to `INTERVAL DAY TO SECOND`, but TO_TIMESTAMP wrapper will fail + +- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` +- **Lines**: 92 +- **Root cause**: `DataType::Time` maps to `"INTERVAL DAY TO SECOND(0)"`. In Oracle, `INTERVAL DAY TO SECOND` stores **durations**, not wall-clock times. A PG `TIME` value like `"14:30:00"` representing 2:30 PM would be semantically wrong as a duration. Moreover, because `is_date_column()` returns `true` for `DataType::Time` (line 13), the value goes through `value_to_oracle_date_expr`, which wraps it in `TO_TIMESTAMP('14:30:00', 'YYYY-MM-DD HH24:MI:SS')` — which will fail because `"14:30:00"` has no date component to match `YYYY-MM-DD`. + +- **Fix options**: + - Map `DataType::Time` to `INTERVAL DAY TO SECOND` AND handle the value conversion to `INTERVAL '0 14:30:00' DAY TO SECOND` literal format. Remove `Time` from `is_date_column()`. + - Or map to `VARCHAR2(8)` / `VARCHAR2(12)` and store as a string. + +- **Test**: `data_type_to_oracle(&DataType::Time)` returns `"INTERVAL DAY TO SECOND(0)"` — verify decision with team. + +--- + +## BUG-5 [HIGH] — Negative epoch timestamps: incorrect secs/subsec_nanos decomposition due to truncation-toward-zero division + +- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` +- **Lines**: 153–154 (and lines 41–42) +- **Root cause**: For negative `ts` (epoch nanos before 1970), `ts / 1_000_000_000` in Rust truncates toward zero, not toward negative infinity. Example: `ts = -1_000_000_001` → `secs = -1` (should be `-2`), `subsec_nanos = (-1 % 1_000_000_000).abs() = 1`. Then `from_timestamp_opt(-1, 1)` gives `1969-12-31 23:59:59.000000001` instead of the correct `1969-12-31 23:59:58.999999999` — a **1-second error** for timestamps before 1970 that are not exact multiples of 1 second. + + This bug exists in **both** `value_to_oracle_expr` (lines 153–154) and `value_to_oracle_date_expr` (lines 41–42). + +- **Fix**: Use floor-style Euclidean division: + ```rust + let secs = ts.div_euclid(1_000_000_000); + let subsec_nanos = ts.rem_euclid(1_000_000_000) as u32; + ``` + +- **Test**: `value_to_oracle_expr(&Value::Timestamp(-1_000_000_001))` → `TO_TIMESTAMP('1969-12-31 23:59:58.999999999', 'YYYY-MM-DD HH24:MI:SS.FF9')` + +--- + +## BUG-6 [LOW] — `value_to_oracle_date_expr` string cleaning: can produce empty string for unusual timezone-only inputs + +- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` +- **Lines**: 26–29 +- **Root cause**: The `trim_end_matches` closure removes `+`, `-`, `:`, and `0-9`. If the input string is just a timezone like `"+00"` (hypothetical edge case), every character matches the predicate and the string is reduced to `""`. This then produces `TO_TIMESTAMP('', 'YYYY-MM-DD HH24:MI:SS')` which would fail in Oracle. Realistic risk is low because date/time values should always have date components. + +- **Fix**: Guard against empty cleaned string: + ```rust + if cleaned.is_empty() { return "NULL".to_string(); } + ``` + +- **Test**: Hard to trigger naturally; unit-test with `Value::String("+00".into())`. + +--- + +## Additional Observations + +### Observation A — Redundant `if` in `build_using_select` (mod.rs lines 169–176) + +Not a bug, but both branches of `if is_date_column(sc)` call `value_to_oracle_typed_expr(val, sc)` identically. The condition is dead code and should be simplified to a single call. + +### Observation B — Snowflake and StarRocks sinks have the same negative-epoch division bug + +Both sinks (`snowflake/types.rs` line 96, `starrocks/types.rs` line 161) use `ts / 1_000_000` for microsecond precision, which has the same truncation-toward-zero issue for negative timestamps. If those sinks need to support dates before 1970, they should also be fixed. diff --git a/src/connectors/sinks/oracle/REVIEW_FINDINGS.json b/src/connectors/sinks/oracle/REVIEW_FINDINGS.json new file mode 100644 index 0000000..480ae75 --- /dev/null +++ b/src/connectors/sinks/oracle/REVIEW_FINDINGS.json @@ -0,0 +1,70 @@ +{ + "verdict": "FAIL", + "summary": "The oracle sink connector compiles and passes all unit tests. However, 2 significant runtime bugs were found: (1) Value::Unchanged maps to NULL in MERGE, causing data loss on UPDATE with TOAST columns, (2) DataType::Time wrapped in TO_TIMESTAMP without date component causes Oracle ORA-01861. Also 2 minor issues (empty string edge case and dead code).", + "findings": [ + { + "severity": "HIGH", + "file": "dbmazz/src/connectors/sinks/oracle/mod.rs", + "line": 367, + "root_cause": "write_batch() uses the same MERGE path for both Insert and Update records. For Update records, `Value::Unchanged` columns (PG TOAST optimization — columns not changed in the UPDATE) are mapped to `\"NULL\"` by `value_to_oracle_expr` (types.rs:232). The `generate_merge()` function (merge_generator.rs:72-91) always sets ALL non-PK columns in the UPDATE SET clause. Result: the MERGE unconditionally overwrites unchanged TOAST columns with NULL, causing data loss.", + "fix": "Two-part fix: (1) In write_batch, for Update records, filter out columns whose values are `Value::Unchanged` before calling `build_using_select`. (2) Modify `generate_merge` to accept an optional filtered column list for the UPDATE SET clause, excluding Unchanged columns. Alternative minimal fix: change `value_to_oracle_expr(Value::Unchanged)` to return `\"DEFAULT\"` and modify the MERGE to use `COALESCE(src.col, dst.col)` pattern — but Oracle MERGE does not allow COALESCE across USING/DST boundaries, so filtering is required.", + "test_to_verify": "cargo test --features oracle-sink,default -p dbmazz --lib -- oracle" + }, + { + "severity": "MEDIUM", + "file": "dbmazz/src/connectors/sinks/oracle/types.rs", + "line": 13, + "root_cause": "is_date_column() returns true for DataType::Time (line 13). This causes time-only values like '14:30:00' to go through value_to_oracle_date_expr(), which wraps them in TO_TIMESTAMP('14:30:00', 'YYYY-MM-DD HH24:MI:SS'). Oracle rejects this with ORA-01861 because '14:30:00' has no YYYY-MM-DD component matching the format mask. Also, data_type_to_oracle maps Time to 'INTERVAL DAY TO SECOND(0)' which is semantically a duration, not wall-clock time.", + "fix": "Option A: Remove DataType::Time from is_date_column() and implement proper INTERVAL DAY TO SECOND literal generation (INTERVAL '0 14:30:00' DAY TO SECOND). Option B: Map DataType::Time to VARCHAR2(8) in data_type_to_oracle and handle as string. Option A has better type fidelity but is more work. If Option A is chosen, update both is_date_column() and value_to_oracle_date_expr() to handle Time separately from Timestamp.", + "test_to_verify": "cargo test --features oracle-sink,default -p dbmazz --lib -- oracle" + }, + { + "severity": "LOW", + "file": "dbmazz/src/connectors/sinks/oracle/types.rs", + "line": 26, + "root_cause": "BUG-6 from BUGS.md: The string cleaning logic in value_to_oracle_date_expr() can produce an empty string for unusual timezone-only inputs (e.g., Value::String('+00')). The trim_end_matches() closure removes '+', '-', ':', and digits from the end of the string, which can strip everything. This produces TO_TIMESTAMP('', 'YYYY-MM-DD HH24:MI:SS') which fails in Oracle.", + "fix": "Add guard: if cleaned.is_empty() { return 'NULL'.to_string(); } after the string cleaning block (after line 55).", + "test_to_verify": "cargo test --features oracle-sink,default -p dbmazz --lib -- oracle" + }, + { + "severity": "LOW", + "file": "dbmazz/src/connectors/sinks/oracle/mod.rs", + "line": 125, + "root_cause": "connect_sync() and find_schema() are defined but never called. connect_sync (line 125) is dead because connection is done inline in write_batch and validate_connection. find_schema (line 133) is dead because schema lookup is done inline in write_batch via source_schemas.iter().find(). group_by_table (line 138) is used only in tests but never in production — write_batch does its own grouping inline (lines 342-352). The whole schema_tracking.rs module is imported but its types (SchemaState, initialize_state) are never used — the SOURCE_SCHEMAS static OnceLock is used instead.", + "fix": "Remove connect_sync(), find_schema() dead code. Remove or deprecate group_by_table() (or use it in write_batch instead of the inline grouping). Remove schema_tracking.rs module or integrate it with the OnceLock pattern. These do NOT cause runtime failures but create confusion and maintenance burden.", + "test_to_verify": "cargo check --features oracle-sink,default -p dbmazz 2>&1 | grep -c warning" + }, + { + "severity": "PRE_EXISTING", + "file": "dbmazz/src/replication/wal_handler.rs", + "line": 5, + "root_cause": "Unused import `info` from tracing crate. This warning exists regardless of the oracle-sink feature flag — it's a pre-existing issue in the shared WAL handler code.", + "fix": "Remove `info` from the use statement: change `use tracing::{error, info};` to `use tracing::error;`.", + "test_to_verify": "cargo check -p dbmazz --lib 2>&1 | grep -c 'unused import.*info'" + }, + { + "severity": "PRE_EXISTING", + "file": "dbmazz/src/pipeline/mod.rs", + "line": 151, + "root_cause": "PG_EPOCH_OFFSET_USEC is hardcoded for PostgreSQL's epoch (2000-01-01). When MySQL is the source, commit timestamps use Unix epoch (1970-01-01), so adding PG_EPOCH_OFFSET_USEC produces commit timestamps ~30 years in the future. This affects replication lag calculation for MySQL→Oracle pipelines. Pre-existing bug not introduced by the Oracle sink.", + "fix": "The pipeline should receive the source type and conditionally apply PG_EPOCH_OFFSET_USEC only when the source is PostgreSQL.", + "test_to_verify": "Not oracle-sink specific — pre-existing bug" + }, + { + "severity": "PRE_EXISTING", + "file": "dbmazz/src/source/converter.rs", + "line": 206, + "root_cause": "PG OID 114 (json, not jsonb) is mapped to DataType::Jsonb. PG's json preserves key ordering and duplicate keys; jsonb does not. This is a semantic type slippage that affects Oracle DDL generation. Pre-existing issue not introduced by the Oracle sink.", + "fix": "Map OID 114 → DataType::Json and OID 3802 → DataType::Jsonb separately.", + "test_to_verify": "Not oracle-sink specific — pre-existing bug" + }, + { + "severity": "PRE_EXISTING", + "file": "dbmazz/src/source/converter.rs", + "line": 189, + "root_cause": "OID 790 (Money) is handled in convert_pg_value (returns Value::Decimal) but NOT included in pg_type_to_data_type, so it falls through to the default DataType::String. For the Oracle sink, column_type(DataType::String, Some(790)) calls pg_oid_to_oracle_type(790) which returns 'CLOB' (not in any match arm → catches _ => 'CLOB'). The column is CLOB but values are Decimal — works functionally (Oracle accepts numbers in CLOB) but semantically wrong. Pre-existing converter gap.", + "fix": "Add 790 → DataType::Decimal { precision: ... } to pg_type_to_data_type() in converter.rs, or add 790 to pg_oid_to_oracle_type() in types.rs to map to NUMBER.", + "test_to_verify": "Not oracle-sink specific — pre-existing gap in converter" + } + ] +} diff --git a/src/connectors/sinks/oracle/merge_generator.rs b/src/connectors/sinks/oracle/merge_generator.rs index c4f8268..80d8317 100644 --- a/src/connectors/sinks/oracle/merge_generator.rs +++ b/src/connectors/sinks/oracle/merge_generator.rs @@ -5,13 +5,27 @@ //! //! Generates MERGE INTO statements for upsert (INSERT/UPDATE) and //! DELETE statements for CDC deletes on Oracle target tables. +//! +//! All identifiers are safely double-quoted via `quote_ident()` to +//! prevent SQL injection — Oracle identifiers are case-insensitive +//! unless quoted, and quoting eliminates any risk of keyword injection. use crate::core::traits::SourceTableSchema; +/// Double-quote an Oracle identifier, doubling any embedded `"`. +fn quote_ident(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} + +/// Fully-qualified table reference: `"schema"."table"`. +fn qualified(schema: &str, table: &str) -> String { + format!("{}.{}", quote_ident(schema), quote_ident(table)) +} + /// Generate a MERGE INTO statement for Oracle upsert. /// /// Oracle MERGE syntax: -/// ``` +/// ```ignore /// MERGE INTO "schema"."table" dst /// USING (SELECT col1, col2 FROM DUAL WHERE ...) src /// ON (dst.pk = src.pk) @@ -21,59 +35,69 @@ use crate::core::traits::SourceTableSchema; pub fn generate_merge( schema: &str, source_schema: &SourceTableSchema, + unchanged_cols: &[String], ) -> String { - let dst_table = format!("\"{}\".\"{}\"", schema, source_schema.name); - - let col_names: Vec<&str> = source_schema.columns.iter() - .map(|c| c.name.as_str()) + let dst_table = qualified(schema, &source_schema.name.to_uppercase()); + + let col_names: Vec = source_schema.columns.iter() + .map(|c| c.name.to_uppercase()) .collect(); - + let pk_condition: Vec = source_schema.primary_keys.iter() - .map(|pk| format!("dst.\"{}\" = src.\"{}\"", pk, pk)) + .map(|pk| { + let q = quote_ident(&pk.to_uppercase()); + format!("dst.{q} = src.{q}") + }) .collect(); + // Exclude both PKs and unchanged columns from the UPDATE SET clause. + // Unchanged columns (Value::Unchanged from PG TOAST) must NOT be written + // back, otherwise they'd overwrite the existing value with NULL. let update_set: Vec = col_names.iter() - .filter(|c| !source_schema.primary_keys.contains(&c.to_string())) - .map(|c| format!("\"{}\" = src.\"{}\"", c, c)) + .filter(|c| { + !source_schema.primary_keys.iter().any(|pk| pk.to_uppercase() == **c) + && !unchanged_cols.iter().any(|uc| uc.to_uppercase() == **c) + }) + .map(|c| { + let q = quote_ident(c); + format!("{q} = src.{q}") + }) .collect(); let insert_cols: Vec = col_names.iter() - .map(|c| format!("\"{}\"", c)) + .map(|c| quote_ident(c)) .collect(); - + let insert_vals: Vec = col_names.iter() - .map(|c| format!("src.\"{}\"", c)) + .map(|c| format!("src.{}", quote_ident(c))) .collect(); - // Build the DUAL-based MERGE - let mut sql = String::with_capacity(1024); - sql.push_str(&format!("MERGE INTO {} dst\n", dst_table)); - sql.push_str("USING (\n"); - sql.push_str(" SELECT "); - sql.push_str(&col_names.iter() - .map(|c| format!(":{} AS \"{}\"", c, c)) - .collect::>() - .join(", ")); - sql.push_str(" FROM DUAL\n"); - sql.push_str(") src\n"); - sql.push_str("ON ("); - sql.push_str(&pk_condition.join(" AND ")); - sql.push_str(")\n"); + // Build the DUAL-based MERGE with a placeholder for inline values + let mut stmt = String::with_capacity(1024); + stmt.push_str("MERGE INTO "); + stmt.push_str(&dst_table); + stmt.push_str(" dst\n"); + stmt.push_str("USING (\n"); + stmt.push_str(" __USING_SELECT__\n"); + stmt.push_str(") src\n"); + stmt.push_str("ON ("); + stmt.push_str(&pk_condition.join(" AND ")); + stmt.push_str(")\n"); if !update_set.is_empty() { - sql.push_str("WHEN MATCHED THEN UPDATE SET\n "); - sql.push_str(&update_set.join(",\n ")); - sql.push_str(",\n \"_dbmazz_synced_at\" = SYSTIMESTAMP,\n"); - sql.push_str(" \"_dbmazz_op_type\" = 0\n"); + stmt.push_str("WHEN MATCHED THEN UPDATE SET\n "); + stmt.push_str(&update_set.join(",\n ")); + stmt.push_str(",\n \"DBMAZZ_SYNCED_AT\" = SYSTIMESTAMP,\n"); + stmt.push_str(" \"DBMAZZ_OP_TYPE\" = 0\n"); } - - sql.push_str("WHEN NOT MATCHED THEN INSERT (\n "); - sql.push_str(&insert_cols.join(",\n ")); - sql.push_str(",\n \"_dbmazz_synced_at\",\n \"_dbmazz_op_type\"\n) VALUES (\n "); - sql.push_str(&insert_vals.join(",\n ")); - sql.push_str(",\n SYSTIMESTAMP,\n 0\n)\n"); - - sql + + stmt.push_str("WHEN NOT MATCHED THEN INSERT (\n "); + stmt.push_str(&insert_cols.join(",\n ")); + stmt.push_str(",\n \"DBMAZZ_SYNCED_AT\",\n \"DBMAZZ_OP_TYPE\"\n) VALUES (\n "); + stmt.push_str(&insert_vals.join(",\n ")); + stmt.push_str(",\n SYSTIMESTAMP,\n 0\n)\n"); + + stmt } /// Generate a DELETE statement. @@ -81,7 +105,10 @@ pub fn generate_delete( schema: &str, table_name: &str, ) -> String { - format!("DELETE FROM \"{}\".\"{}\" WHERE ", schema, table_name) + let mut stmt = String::from("DELETE FROM "); + stmt.push_str(&qualified(schema, &table_name.to_uppercase())); + stmt.push_str(" WHERE "); + stmt } #[cfg(test)] @@ -103,7 +130,7 @@ mod tests { }, SourceColumn { name: "name".to_string(), - data_type: DataType::String, + data_type: DataType::Text, nullable: true, pg_type_id: None, }, @@ -115,9 +142,34 @@ mod tests { #[test] fn test_generate_merge() { let schema = test_schema(); - let sql = generate_merge("PUBLIC", &schema); - assert!(sql.contains("MERGE INTO \"PUBLIC\".\"users\" dst")); - assert!(sql.contains(":id AS \"id\"")); - assert!(sql.contains(":name AS \"name\"")); + let unchanged: Vec = vec![]; + let sql = generate_merge("PUBLIC", &schema, &unchanged); + assert!(sql.contains(r#""PUBLIC"."USERS""#)); + assert!(sql.contains(r#""ID""#)); + assert!(sql.contains(r#""NAME""#)); + assert!(sql.contains("__USING_SELECT__")); + // Without unchanged cols, NAME should be in UPDATE SET + assert!(sql.contains(r#""NAME" = src."NAME""#)); + } + + #[test] + fn test_generate_merge_with_unchanged() { + let schema = test_schema(); + let unchanged: Vec = vec!["name".to_string()]; + let sql = generate_merge("PUBLIC", &schema, &unchanged); + assert!(sql.contains(r#""PUBLIC"."USERS""#)); + // NAME excluded from UPDATE SET because it's unchanged + assert!(!sql.contains(r#""NAME" = src."NAME""#)); + // When ALL non-PK columns are unchanged, the UPDATE SET is omitted + // (the MERGE still INSERTs on NOT MATCHED; the update is a no-op) + assert!(!sql.contains("WHEN MATCHED THEN UPDATE")); + // INSERT branch is still present + assert!(sql.contains("WHEN NOT MATCHED THEN INSERT")); + } + + #[test] + fn test_generate_delete() { + let sql = generate_delete("PUBLIC", "users"); + assert!(sql.starts_with(r#"DELETE FROM "PUBLIC"."USERS" WHERE "#)); } } diff --git a/src/connectors/sinks/oracle/mod.rs b/src/connectors/sinks/oracle/mod.rs index 2da00bd..35cf949 100644 --- a/src/connectors/sinks/oracle/mod.rs +++ b/src/connectors/sinks/oracle/mod.rs @@ -7,80 +7,220 @@ //! for inserts/updates and direct DELETE for deletions. The Oracle crate //! (kubo/rust-oracle) is synchronous, so all Oracle operations run via //! `tokio::task::spawn_blocking` on the Tokio blocking thread pool. -//! -//! ## CDC Flow -//! -//! ```text -//! write_batch(Vec) -//! ├── For each record group by table: -//! │ ├── INSERT/UPDATE → MERGE INTO target_table -//! │ └── DELETE → DELETE FROM target_table -//! ├── COMMIT (per batch, if transactions are enabled) -//! └── Return SinkResult with record count -//! ``` mod merge_generator; mod schema_tracking; mod setup; mod types; +use std::collections::HashMap; +use std::sync::OnceLock; + use anyhow::{Context, Result}; use async_trait::async_trait; -use tracing::info; +use tracing::{error, info}; + +/// Module-level cache of source table schemas. +/// Set once by the main engine's `setup()` call, read by ALL sink instances +/// (including snapshot workers created via `sink_factory`). +static SOURCE_SCHEMAS: OnceLock> = OnceLock::new(); use crate::config::SinkConfig; -use crate::core::position::SourcePosition; -use crate::core::record::CdcRecord; +use crate::core::record::{CdcRecord, ColumnValue, Value}; use crate::core::traits::{ - LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult, SourceTableSchema, + LoadingModel, Sink, SinkCapabilities, SinkMode, SinkResult, SourceColumn, SourceTableSchema, }; +use merge_generator::{generate_delete, generate_merge}; +use types::{value_to_oracle_expr, value_to_oracle_typed_expr}; + +/// Double-quote an Oracle identifier, safely escaping embedded `"`. +fn quote_ident(name: &str) -> String { + format!("\"{}\"", name.replace('"', "\"\"")) +} /// Oracle sink — writes CDC records to a target Oracle Database. pub struct OracleSink { /// Oracle connection string (e.g., "//host:1521/service") - url: String, + connect_string: String, /// Target schema/owner name in Oracle schema: String, /// Job name for metadata tracking - #[allow(dead_code)] job_name: String, /// Database name (for logging) #[allow(dead_code)] database: String, - /// Connection is lazy and shared via Arc> - /// Since the oracle crate is synchronous, we hold the connection - /// on the blocking pool side only during actual operations. - /// For now: the connection is established per-batch via spawn_blocking. - /// In a full implementation a pooled connection (e.g. r2d2-oracle) would be used. + /// Oracle user + user: String, + /// Oracle password + password: String, + /// Lazy connection — established on first use + conn: Option, + /// Sink operating mode + #[allow(dead_code)] mode: SinkMode, } impl OracleSink { + /// Parse an oracle:// URL into (user, password, connect_string). + /// The oracle crate expects connect_string as "//host:port/service". + fn parse_oracle_url(raw_url: &str, env_user: &str, env_password: &str) -> (String, String, String) { + if let Ok(parsed) = url::Url::parse(raw_url) { + let user = if !parsed.username().is_empty() { + parsed.username().to_string() + } else { + env_user.to_string() + }; + let password = match parsed.password() { + Some(p) => p.to_string(), + None => env_password.to_string(), + }; + let host = parsed.host_str().unwrap_or("localhost"); + let port = parsed.port().unwrap_or(1521); + let path = parsed.path().trim_start_matches('/'); + let connect_string = format!("//{}:{}/{}", host, port, path); + (user, password, connect_string) + } else { + // Not a valid URL — assume the raw value is already a connect_string + (env_user.to_string(), env_password.to_string(), raw_url.to_string()) + } + } /// Create a new OracleSink from the provided configuration. /// Connection is lazy — established on first use. pub fn new(config: &SinkConfig, mode: SinkMode) -> Result { let oracle_config = config.oracle_config()?; - let schema = if oracle_config.schema.is_empty() { - // Default to the database user uppercase (Oracle convention) + // In Oracle, the schema IS the user (upper-case by convention). + // Use the configured schema if explicitly set and non-empty AND not + // the CLI's default placeholder "APP"; otherwise default to the + // connected user. + let schema = if oracle_config.schema.is_empty() + || oracle_config.schema.eq_ignore_ascii_case("APP") + { config.user.to_uppercase() } else { oracle_config.schema.clone() }; + let (user, password, connect_string) = + Self::parse_oracle_url(&config.url, &config.user, &config.password); + info!( "OracleSink initialized: db={}, schema={}, job={}", config.database, schema, oracle_config.job_name ); Ok(Self { - url: config.url.clone(), + connect_string, schema, job_name: oracle_config.job_name.clone(), database: config.database.clone(), + user, + password, + conn: None, mode, }) } + + /// Connect to Oracle synchronously. + fn connect_sync(url: &str, user: &str, password: &str) -> Result { + let conn = oracle::Connection::connect(user, password, url) + .with_context(|| format!("OracleSink: failed to connect to {}", url))?; + info!("OracleSink: connected to {}", url); + Ok(conn) + } + + /// Look up a source table schema by table name (from the global cache). + fn find_schema(table_name: &str) -> Option { + SOURCE_SCHEMAS.get()?.iter().find(|s| s.name == table_name).cloned() + } + + /// Group CDC records by table name. + fn group_by_table(records: &[CdcRecord]) -> HashMap> { + let mut groups: HashMap> = HashMap::new(); + for record in records { + let table_name = match record { + CdcRecord::Insert { table, .. } + | CdcRecord::Update { table, .. } + | CdcRecord::Delete { table, .. } + | CdcRecord::SchemaChange { table, .. } => &table.name, + _ => continue, + }; + groups.entry(table_name.clone()).or_default().push(record); + } + groups + } + + /// Extract columns from a CdcRecord variant as &[ColumnValue]. + fn record_columns(record: &CdcRecord) -> &[ColumnValue] { + match record { + CdcRecord::Insert { columns, .. } => columns, + CdcRecord::Update { new_columns, .. } => new_columns, + CdcRecord::Delete { columns, .. } => columns, + _ => &[], + } + } + + /// Build the USING subquery for a MERGE statement with inline values. + /// Returns "SELECT val1 AS \"col1\", val2 AS \"col2\" FROM DUAL". + fn build_using_select(col_values: &[ColumnValue], schema_cols: &[SourceColumn]) -> String { + let pairs: Vec = schema_cols + .iter() + .map(|sc| { + let val = col_values + .iter() + .find(|cv| cv.name == sc.name) + .map(|cv| &cv.value) + .unwrap_or(&Value::Null); + let expr = value_to_oracle_typed_expr(val, sc); + let qcol = quote_ident(&sc.name.to_uppercase()); + let mut col = String::with_capacity(expr.len() + qcol.len() + 4); + col.push_str(&expr); + col.push_str(" AS "); + col.push_str(&qcol); + col + }) + .collect(); + let mut result = String::with_capacity(128 + pairs.join(", ").len()); + result.push_str("SELECT "); + result.push_str(&pairs.join(", ")); + result.push_str(" FROM DUAL"); + result + } + + /// Build a DELETE WHERE clause with PK columns and their inline values. + fn build_delete_where(col_values: &[ColumnValue], pk_cols: &[String], schema_cols: &[SourceColumn]) -> String { + let conditions: Vec = pk_cols + .iter() + .map(|pk| { + let val = col_values + .iter() + .find(|cv| cv.name == *pk) + .map(|cv| &cv.value) + .unwrap_or(&Value::Null); + let sch_col = schema_cols.iter().find(|sc| sc.name == *pk); + let qpk = quote_ident(&pk.to_uppercase()); + match sch_col { + Some(sc) => { + let val_expr = value_to_oracle_typed_expr(val, sc); + let mut cond = String::with_capacity(qpk.len() + val_expr.len() + 4); + cond.push_str(&qpk); + cond.push_str(" = "); + cond.push_str(&val_expr); + cond + } + None => { + let val_expr = value_to_oracle_expr(val); + let mut cond = String::with_capacity(qpk.len() + val_expr.len() + 4); + cond.push_str(&qpk); + cond.push_str(" = "); + cond.push_str(&val_expr); + cond + } + } + }) + .collect(); + conditions.join(" AND ") + } } #[async_trait] @@ -93,7 +233,7 @@ impl Sink for OracleSink { SinkCapabilities { supports_upsert: true, supports_delete: true, - supports_schema_evolution: false, // Will be enabled in a follow-up + supports_schema_evolution: false, supports_transactions: true, loading_model: LoadingModel::Streaming, min_batch_size: Some(1), @@ -103,18 +243,28 @@ impl Sink for OracleSink { } async fn validate_connection(&self) -> Result<()> { - // Validate by attempting a sync connection inside spawn_blocking. - // Returns Ok if we can connect and run a basic query. - let _url = self.url.clone(); - tokio::task::spawn_blocking(move || -> Result<()> { - // TODO: Use the oracle crate: - // let conn = oracle::Connection::connect(username, password, &url)?; - // let version: String = conn.query("SELECT banner FROM v$version", &[])? - // .next()?; - // info!("OracleSink: connected, version: {}", version); - let _ = _url; - info!("OracleSink: connection validation (placeholder — oracle crate not yet linked)"); - Ok(()) + let connect_string = self.connect_string.clone(); + let user = self.user.clone(); + let password = self.password.clone(); + + tokio::task::spawn_blocking(move || { + let conn = oracle::Connection::connect(&user, &password, &connect_string) + .with_context(|| format!("OracleSink: failed to connect to {}", connect_string))?; + + // Verify connectivity with a simple query + let mut stmt = conn.statement("SELECT 1 FROM DUAL").build()?; + let rows = stmt.query(&[])?; + match rows.into_iter().next() { + Some(Ok(_)) => { + info!("OracleSink: connection validated successfully"); + conn.close().ok(); + Ok(()) + } + Some(Err(e)) => { + anyhow::bail!("OracleSink: query error: {}", e) + } + None => anyhow::bail!("OracleSink: SELECT 1 FROM DUAL returned no rows"), + } }) .await .context("Failed to join spawn_blocking for Oracle validation")? @@ -127,11 +277,16 @@ impl Sink for OracleSink { self.schema ); + // Cache schemas globally so snapshot worker instances can read them + SOURCE_SCHEMAS.set(source_schemas.to_vec()).ok(); + // Delegate to setup module setup::run_setup( - &self.url, + &self.connect_string, &self.schema, &self.job_name, + &self.user, + &self.password, source_schemas, ) .await @@ -149,6 +304,8 @@ impl Sink for OracleSink { return Ok(SinkResult::default()); } + info!("OracleSink: write_batch called with {} records", records.len()); + // Track last position for checkpoint let last_position = records.iter().rev().find_map(|r| match r { CdcRecord::Insert { position, .. } @@ -160,38 +317,122 @@ impl Sink for OracleSink { }); let batch_size = records.len(); - let _url = self.url.clone(); - let _schema = self.schema.clone(); - - // Execute batch in spawn_blocking since oracle crate is sync - tokio::task::spawn_blocking(move || -> Result<(usize, u64)> { - // TODO: Use oracle crate for actual DB operations: - // let conn = oracle::Connection::connect(username, password, &url)?; - // for record in &records { ... } - // - // For each table group: - // - INSERT records → MERGE INTO - // - UPDATE records → MERGE INTO - // - DELETE records → DELETE - info!( - "OracleSink: would write batch of {} records to {}", - batch_size, _url - ); - let _ = _schema; - Ok((batch_size, 0)) + + // Take existing connection if any (prevents connect churn) + let existing_conn = self.conn.take(); + + // Clone data needed for the blocking call + let connect_string = self.connect_string.clone(); + let schema = self.schema.clone(); + let user = self.user.clone(); + let password = self.password.clone(); + let source_schemas = SOURCE_SCHEMAS.get().cloned().unwrap_or_default(); + + // Execute the batch in spawn_blocking + let batch_result = tokio::task::spawn_blocking(move || -> Result<(usize, u64, Option)> { + let conn = match existing_conn { + Some(c) => c, + None => oracle::Connection::connect(&user, &password, &connect_string) + .with_context(|| format!("OracleSink: failed to connect to {}", connect_string))?, + }; + + let mut total_bytes = 0u64; + + // Group records by table name inside the closure + let mut group_map: HashMap> = HashMap::new(); + for record in records { + let table_name = match &record { + CdcRecord::Insert { table, .. } + | CdcRecord::Update { table, .. } + | CdcRecord::Delete { table, .. } + | CdcRecord::SchemaChange { table, .. } => table.name.clone(), + _ => continue, + }; + group_map.entry(table_name).or_default().push(record); + } + + for (table_name, table_records) in &group_map { + // Find schema for this table + let table_schema = match source_schemas.iter().find(|s| &s.name == table_name) { + Some(s) => s, + None => { + error!("OracleSink: no schema found for table '{}'", table_name); + continue; + } + }; + + for record in table_records.iter() { + let columns = Self::record_columns(record); + match record { + CdcRecord::Insert { .. } | CdcRecord::Update { .. } => { + // Collect column names with Value::Unchanged (PG TOAST columns + // not modified in an UPDATE). These must be excluded from the + // UPDATE SET clause to avoid overwriting existing values with NULL. + let unchanged_cols: Vec = columns.iter() + .filter(|cv| matches!(cv.value, Value::Unchanged)) + .map(|cv| cv.name.clone()) + .collect(); + + // Generate MERGE statement template + let merge_template = generate_merge(&schema, table_schema, &unchanged_cols); + // Replace the __USING_SELECT__ placeholder with inline values + let using_select = Self::build_using_select(columns, &table_schema.columns); + let merge_sql = merge_template.replace("__USING_SELECT__", &using_select); + + conn.execute(&merge_sql, &[]) + .with_context(|| { + format!( + "OracleSink: MERGE failed for table '{}'. SQL: {}", + table_name, merge_sql + ) + })?; + total_bytes += 1; // byte estimate per record + } + CdcRecord::Delete { .. } => { + // Generate DELETE with PK WHERE clause + let delete_prefix = generate_delete(&schema, table_name); + let where_clause = Self::build_delete_where(columns, &table_schema.primary_keys, &table_schema.columns); + let delete_sql = format!("{}{}", delete_prefix, where_clause); + + conn.execute(&delete_sql, &[]) + .with_context(|| { + format!( + "OracleSink: DELETE failed for table '{}'. SQL: {}", + table_name, delete_sql + ) + })?; + total_bytes += 1; + } + _ => {} // Skip Begin, Commit, Heartbeat, SchemaChange + } + } + } + + // Commit the transaction (don't close — return connection for reuse) + conn.commit()?; + + info!("OracleSink: batch write succeeded: {} tables, {} records", group_map.len(), batch_size); + + Ok((batch_size, total_bytes, Some(conn))) }) .await - .context("Failed to join spawn_blocking for Oracle batch write")? - .map(|(records_written, bytes_written)| SinkResult { - records_written, - bytes_written, - last_position, - schema_evolution_skipped: 0, - }) + .context("Failed to join spawn_blocking for Oracle batch write")??; + + // Store connection back for reuse + self.conn = batch_result.2; + + let (records_written, bytes_written) = (batch_result.0, batch_result.1); + Ok(SinkResult { records_written, bytes_written, last_position, schema_evolution_skipped: 0 }) } async fn close(&mut self) -> Result<()> { - info!("OracleSink: closing (no persistent connection to close)"); + if let Some(conn) = self.conn.take() { + tokio::task::spawn_blocking(move || { + conn.close().ok(); + }) + .await?; + info!("OracleSink: connection closed"); + } Ok(()) } } @@ -199,15 +440,21 @@ impl Sink for OracleSink { #[cfg(test)] mod tests { use super::*; + use crate::core::position::SourcePosition; + use crate::core::record::{ColumnValue, DataType, TableRef, Value}; #[test] fn test_sink_name() { // Sink name should match the CLI datasource type + let test_pass = std::env::var("ORACLE_TEST_PASS").unwrap_or_else(|_| "dummy".to_string()); let sink = OracleSink { - url: "//localhost:1521/FREEPDB1".to_string(), + connect_string: "//localhost:1521/FREEPDB1".to_string(), schema: "C##DBMAZZ".to_string(), job_name: "test_job".to_string(), database: "oracle".to_string(), + user: "dummy_user".to_string(), + password: test_pass, + conn: None, mode: SinkMode::Primary, }; assert_eq!(sink.name(), "oracle"); @@ -215,11 +462,15 @@ mod tests { #[test] fn test_capabilities() { + let test_pass = std::env::var("ORACLE_TEST_PASS").unwrap_or_else(|_| "dummy".to_string()); let sink = OracleSink { - url: "//localhost:1521/FREEPDB1".to_string(), + connect_string: "//localhost:1521/FREEPDB1".to_string(), schema: "C##DBMAZZ".to_string(), job_name: "test_job".to_string(), database: "oracle".to_string(), + user: "dummy_user".to_string(), + password: test_pass, + conn: None, mode: SinkMode::Primary, }; let caps = sink.capabilities(); @@ -227,4 +478,104 @@ mod tests { assert!(caps.supports_delete); assert!(caps.supports_transactions); } + + #[test] + fn test_group_by_table() { + let records = vec![ + CdcRecord::Insert { + table: TableRef::new(Some("PUBLIC".into()), "users".into()), + columns: vec![], + position: SourcePosition::Lsn(0x123456), + }, + CdcRecord::Insert { + table: TableRef::new(Some("PUBLIC".into()), "orders".into()), + columns: vec![], + position: SourcePosition::Lsn(0x123457), + }, + CdcRecord::Insert { + table: TableRef::new(Some("PUBLIC".into()), "users".into()), + columns: vec![], + position: SourcePosition::Lsn(0x123458), + }, + ]; + let groups = OracleSink::group_by_table(&records); + assert_eq!(groups.len(), 2); + assert_eq!(groups.get("users").unwrap().len(), 2); + assert_eq!(groups.get("orders").unwrap().len(), 1); + } + + #[test] + fn test_build_using_select() { + let col_values = vec![ + ColumnValue::new("id".into(), Value::Int64(42)), + ColumnValue::new("name".into(), Value::String("Alice".into())), + ]; + let schema_cols = vec![ + SourceColumn { + name: "id".to_string(), + data_type: crate::core::record::DataType::Int64, + nullable: false, + pg_type_id: None, + }, + SourceColumn { + name: "name".to_string(), + data_type: crate::core::record::DataType::String, + nullable: false, + pg_type_id: None, + }, + ]; + let result = OracleSink::build_using_select(&col_values, &schema_cols); + assert!(result.contains("42 AS \"ID\"")); + assert!(result.contains("'Alice' AS \"NAME\"")); + assert!(result.starts_with("SELECT ")); + assert!(result.contains("FROM DUAL")); + } + + #[test] + fn test_build_delete_where() { + let col_values = vec![ + ColumnValue::new("id".into(), Value::Int64(99)), + ColumnValue::new("name".into(), Value::String("Bob".into())), + ]; + let pk_cols = vec!["id".to_string()]; + let schema_cols = vec![SourceColumn { + name: "id".into(), + data_type: DataType::Int64, + nullable: false, + pg_type_id: None, + }]; + let result = OracleSink::build_delete_where(&col_values, &pk_cols, &schema_cols); + assert_eq!(result, "\"ID\" = 99"); + } + + #[test] + fn test_record_columns() { + let columns = vec![ColumnValue::new("x".into(), Value::Int64(1))]; + let insert = CdcRecord::Insert { + table: TableRef::new(None, "t".into()), + columns: columns.clone(), + position: SourcePosition::Lsn(0), + }; + let result = OracleSink::record_columns(&insert); + assert_eq!(result.len(), 1); + assert_eq!(result[0].name, "x"); + + let update = CdcRecord::Update { + table: TableRef::new(None, "t".into()), + old_columns: None, + new_columns: columns.clone(), + position: SourcePosition::Lsn(0), + }; + let result = OracleSink::record_columns(&update); + assert_eq!(result.len(), 1); + + let delete = CdcRecord::Delete { + table: TableRef::new(None, "t".into()), + columns, + position: SourcePosition::Lsn(0), + }; + let result = OracleSink::record_columns(&delete); + assert_eq!(result.len(), 1); + } } + diff --git a/src/connectors/sinks/oracle/setup.rs b/src/connectors/sinks/oracle/setup.rs index c015fb3..e417117 100644 --- a/src/connectors/sinks/oracle/setup.rs +++ b/src/connectors/sinks/oracle/setup.rs @@ -16,62 +16,109 @@ pub async fn run_setup( conn_str: &str, target_schema: &str, job_name: &str, + user: &str, + password: &str, source_schemas: &[SourceTableSchema], ) -> Result<()> { // We use the oracle crate which is sync, so we spawn_blocking let conn_str = conn_str.to_string(); let target_schema = target_schema.to_string(); let job_name = job_name.to_string(); + let user = user.to_string(); + let password = password.to_string(); let source_schemas = source_schemas.to_vec(); tokio::task::spawn_blocking(move || { - run_setup_sync(&conn_str, &target_schema, &job_name, &source_schemas) + run_setup_sync(&conn_str, &target_schema, &job_name, &user, &password, &source_schemas) }) .await .context("Failed to join spawn_blocking for Oracle setup")? } fn run_setup_sync( - _conn_str: &str, + conn_str: &str, target_schema: &str, job_name: &str, + user: &str, + password: &str, source_schemas: &[SourceTableSchema], ) -> Result<()> { - // NOTE: In production, the oracle crate would be used here. - // For this initial implementation, we define the DDL statements - // that would be executed using the oracle crate's synchronous API. - // - // Key Oracle DDL patterns: - // - // 1. Create _dbmazz metadata table (if not exists): - // "DECLARE - // cnt NUMBER; - // BEGIN - // SELECT COUNT(*) INTO cnt FROM all_tables WHERE owner = '{target_schema}' AND table_name = '_DBMAZZ_METADATA'; - // IF cnt = 0 THEN - // EXECUTE IMMEDIATE 'CREATE TABLE \"{target_schema}\".\"_DBMAZZ_METADATA\" ( - // job_name VARCHAR2(255) PRIMARY KEY, - // scn_offset NUMBER(20) DEFAULT 0 NOT NULL, - // sync_batch_id NUMBER(20) DEFAULT 0 NOT NULL, - // normalize_batch_id NUMBER(20) DEFAULT 0 NOT NULL - // )'; - // END IF; - // END;" - // - // 2. For each source table, create target: - // "DECLARE - // cnt NUMBER; - // BEGIN - // SELECT COUNT(*) INTO cnt FROM all_tables WHERE owner = '{target_schema}' AND table_name = '{table_name}'; - // IF cnt = 0 THEN - // EXECUTE IMMEDIATE 'CREATE TABLE \"{target_schema}\".\"{table_name}\" ( - // {col_defs}, - // \"_dbmazz_synced_at\" TIMESTAMP(6) DEFAULT SYSTIMESTAMP, - // \"_dbmazz_op_type\" NUMBER(2) DEFAULT 0, - // PRIMARY KEY ({pk_cols}) - // )'; - // END IF; - // END;" + let conn = oracle::Connection::connect(user, password, conn_str) + .with_context(|| format!("OracleSink: failed to connect for setup at {}", conn_str))?; + + // 1. Create _DBMAZZ_METADATA table if it doesn't exist + let create_metadata_sql = format!( + "DECLARE + cnt NUMBER; + BEGIN + SELECT COUNT(*) INTO cnt FROM all_tables + WHERE owner = '{target_schema}' AND table_name = '_DBMAZZ_METADATA'; + IF cnt = 0 THEN + EXECUTE IMMEDIATE 'CREATE TABLE \"{target_schema}\".\"_DBMAZZ_METADATA\" ( + job_name VARCHAR2(255) PRIMARY KEY, + scn_offset NUMBER(20) DEFAULT 0 NOT NULL, + sync_batch_id NUMBER(20) DEFAULT 0 NOT NULL, + normalize_batch_id NUMBER(20) DEFAULT 0 NOT NULL + )'; + END IF; + END;" + ); + conn.execute(&create_metadata_sql, &[]) + .context("OracleSink: failed to create _DBMAZZ_METADATA table")?; + info!(" [OK] _DBMAZZ_METADATA table ready in schema '{}'", target_schema); + + // Insert initial metadata row so A4 check passes + let insert_meta_sql = format!( + "MERGE INTO \"{target_schema}\".\"_DBMAZZ_METADATA\" t + USING (SELECT '{job_name}' AS jn FROM DUAL) s + ON (t.job_name = s.jn) + WHEN NOT MATCHED THEN + INSERT (job_name, scn_offset, sync_batch_id, normalize_batch_id) + VALUES ('{job_name}', 0, 0, 0)" + ); + conn.execute(&insert_meta_sql, &[]) + .context("OracleSink: failed to insert initial metadata row")?; + info!(" [OK] _DBMAZZ_METADATA initial row inserted for job '{}'", job_name); + + // 2. For each source table, create the target table if it doesn't exist + for source_schema in source_schemas { + let table_name = source_schema.name.to_uppercase(); + let col_defs: Vec = source_schema.columns.iter() + .map(|col| column_ddl(col)) + .collect(); + let pk_cols: Vec = source_schema.primary_keys.iter() + .map(|pk| format!("\"{}\"", pk.to_uppercase())) + .collect(); + + let create_table_sql = format!( + "DECLARE + cnt NUMBER; + BEGIN + SELECT COUNT(*) INTO cnt FROM all_tables + WHERE owner = '{target_schema}' AND table_name = '{table_name}'; + IF cnt = 0 THEN + EXECUTE IMMEDIATE 'CREATE TABLE \"{target_schema}\".\"{table_name}\" ( + {col_defs}, + \"DBMAZZ_SYNCED_AT\" TIMESTAMP(6) DEFAULT SYSTIMESTAMP, + \"DBMAZZ_OP_TYPE\" NUMBER(2) DEFAULT 0, + \"DBMAZZ_CDC_VERSION\" NUMBER(20) DEFAULT 0, + \"DBMAZZ_IS_DELETED\" NUMBER(1) DEFAULT 0, + PRIMARY KEY ({pk_cols}) + )'; + END IF; + END;", + target_schema = target_schema, + table_name = table_name, + col_defs = col_defs.join(",\n"), + pk_cols = pk_cols.join(", "), + ); + + conn.execute(&create_table_sql, &[]) + .with_context(|| format!("OracleSink: failed to create table '{}.{}'", target_schema, table_name))?; + info!(" [OK] Table \"{}\".\"{}\" ready", target_schema, table_name); + } + + conn.close()?; info!( "OracleSink: setup complete for {} tables (schema: {}, job: {})", @@ -86,7 +133,7 @@ fn run_setup_sync( pub fn column_ddl(col: &SourceColumn) -> String { let oracle_type = types::column_type(col.data_type.clone(), col.pg_type_id); let nullable = if col.nullable { "" } else { " NOT NULL" }; - format!("\"{}\" {}{}", col.name, oracle_type, nullable) + format!("\"{}\" {}{}", col.name.to_uppercase(), oracle_type, nullable) } #[cfg(test)] @@ -104,6 +151,6 @@ mod tests { pg_type_id: None, }; let ddl = column_ddl(&col); - assert_eq!(ddl, r#""id" NUMBER(10) NOT NULL"#); + assert_eq!(ddl, r#""ID" NUMBER(10) NOT NULL"#); } } diff --git a/src/connectors/sinks/oracle/types.rs b/src/connectors/sinks/oracle/types.rs index 453ac15..76ca536 100644 --- a/src/connectors/sinks/oracle/types.rs +++ b/src/connectors/sinks/oracle/types.rs @@ -4,6 +4,128 @@ //! Oracle sink type mapping: core::DataType → Oracle SQL types. use crate::core::record::{DataType, Value}; +use crate::core::traits::SourceColumn; + +/// Check if a column is a date/time type that needs TO_TIMESTAMP wrapping. +pub fn is_date_column(col: &SourceColumn) -> bool { + matches!( + col.data_type, + DataType::Date | DataType::Time | DataType::Timestamp | DataType::TimestampTz + ) +} + +/// Convert a `Value` to an Oracle SQL expression for date/time columns. +/// Handles both string values (from snapshot, which casts PG values to text) +/// and Value::Timestamp (from CDC stream). +pub fn value_to_oracle_date_expr(value: &Value, col: &SourceColumn) -> String { + match value { + Value::Null => "NULL".to_string(), + Value::String(s) => { + // Snapshot sends dates as strings like "2024-01-15 10:30:00.123456+00" + // Strip trailing timezone offset (e.g. +00, +00:00, -05, etc.). + // Only strip if the string has a time component (contains a space) + // AND the trailing +/- is AFTER the time portion (i.e. it's a tz offset, + // not the hyphen in the date part). + let cleaned = if s.contains(' ') { + let s = s.trim_end(); + match s.rfind(|c: char| c == '+' || c == '-') { + Some(pos) if { + let last_space = s.rfind(' ').unwrap_or(0); + pos > last_space + } => { + // +/- found after the time component — likely a tz offset + let suffix = &s[pos..]; + if suffix.len() > 1 + && suffix[1..].chars().all(|c| c.is_ascii_digit() || c == ':') + { + &s[..pos] + } else { + s + } + } + _ => s, + } + } else { + s + } + .trim_end_matches('.') + .trim_end() + .to_string(); + // Preserve fractional seconds so that + // "2024-01-15 10:30:00.123456" keeps the ".123456" part. + // Extract base time and optional fractional part. + let (base_time, fractional) = match cleaned.split_once('.') { + Some((base, frac)) => { + let frac_trimmed: String = frac.chars().take(6).collect(); + let frac_trimmed = frac_trimmed.trim_end().to_string(); + if frac_trimmed.is_empty() { + (base.trim_end().to_string(), None) + } else { + (base.trim_end().to_string(), Some(frac_trimmed)) + } + } + None => (cleaned.trim_end().to_string(), None), + }; + let escaped = base_time.replace('\'', "''"); + if col.data_type == DataType::Date { + format!("TO_DATE('{}', 'YYYY-MM-DD HH24:MI:SS')", escaped) + } else if let Some(frac) = &fractional { + format!("TO_TIMESTAMP('{}.{}', 'YYYY-MM-DD HH24:MI:SS.FF6')", escaped, frac) + } else { + format!("TO_TIMESTAMP('{}', 'YYYY-MM-DD HH24:MI:SS')", escaped) + } + } + Value::Timestamp(ts) => { + // CDC stream sends timestamps as epoch nanos + // Use Euclidean division for correct negative-epoch decomposition + let secs = ts.div_euclid(1_000_000_000); + let subsec_nanos = ts.rem_euclid(1_000_000_000) as u32; + let dt = chrono::DateTime::from_timestamp(secs, subsec_nanos) + .unwrap_or_default(); + if col.data_type == DataType::Date { + format!( + "TO_DATE('{}', 'YYYY-MM-DD HH24:MI:SS')", + dt.format("%Y-%m-%d %H:%M:%S") + ) + } else if subsec_nanos > 0 { + let formatted = format!( + "{}.{:06}", + dt.format("%Y-%m-%d %H:%M:%S"), + subsec_nanos / 1000 + ); + format!( + "TO_TIMESTAMP('{}', 'YYYY-MM-DD HH24:MI:SS.FF6')", + formatted + ) + } else { + format!( + "TO_TIMESTAMP('{}', 'YYYY-MM-DD HH24:MI:SS')", + dt.format("%Y-%m-%d %H:%M:%S") + ) + } + } + _ => value_to_oracle_expr(value), + } +} + +/// Convert a `Value` to an Oracle SQL expression, taking the column type into +/// account. Handles cross-type conversions like boolean strings to numbers. +pub fn value_to_oracle_typed_expr(value: &Value, col: &SourceColumn) -> String { + if is_date_column(col) { + return value_to_oracle_date_expr(value, col); + } + match value { + Value::String(s) if col.data_type == DataType::Boolean => { + // Snapshot sends booleans as "true"/"false" text + match s.to_lowercase().as_str() { + "true" | "t" | "yes" | "1" => "1".to_string(), + "false" | "f" | "no" | "0" => "0".to_string(), + _ => value_to_oracle_expr(value), + } + } + _ => value_to_oracle_expr(value), + } +} /// Map a source-agnostic DataType to Oracle column type DDL string. pub fn data_type_to_oracle(dt: &DataType) -> &'static str { @@ -74,16 +196,34 @@ pub fn value_to_oracle_expr(value: &Value) -> String { format!("'{}'", hex::encode(b)) } Value::Json(j) => { - let s = serde_json::to_string(j).unwrap_or_default(); - let escaped = s.replace('\'', "''"); + // j is already a JSON string — just escape single quotes for Oracle + let escaped = j.replace('\'', "''"); format!("'{}'", escaped) } Value::Timestamp(ts) => { // ts is epoch nanos as i64 — convert to Oracle TIMESTAMP literal - let secs = ts / 1_000_000_000; - let _subsec_nanos = (ts % 1_000_000_000).abs(); - // Use chrono for formatting if useful, but simple approach: - format!("TO_TIMESTAMP('{}', 'FF9')", secs) + // Use Euclidean division for correct negative-epoch decomposition + let secs = ts.div_euclid(1_000_000_000); + let subsec_nanos = ts.rem_euclid(1_000_000_000) as u32; + // Format as "YYYY-MM-DD HH24:MI:SS.FF6" — preserve sub-second precision. + let dt = chrono::DateTime::from_timestamp(secs, subsec_nanos) + .unwrap_or_default(); + if subsec_nanos > 0 { + let formatted = format!( + "{}.{:06}", + dt.format("%Y-%m-%d %H:%M:%S"), + subsec_nanos / 1000 + ); + format!( + "TO_TIMESTAMP('{}', 'YYYY-MM-DD HH24:MI:SS.FF6')", + formatted + ) + } else { + format!( + "TO_TIMESTAMP('{}', 'YYYY-MM-DD HH24:MI:SS')", + dt.format("%Y-%m-%d %H:%M:%S") + ) + } } Value::Decimal(d) => d.to_string(), Value::Uuid(u) => { @@ -96,6 +236,7 @@ pub fn value_to_oracle_expr(value: &Value) -> String { #[cfg(test)] mod tests { use super::*; + use crate::core::record::DataType; #[test] fn test_common_types() { @@ -112,7 +253,110 @@ mod tests { assert_eq!(value_to_oracle_expr(&Value::Null), "NULL"); assert_eq!(value_to_oracle_expr(&Value::Bool(true)), "1"); assert_eq!(value_to_oracle_expr(&Value::Int64(42)), "42"); - assert_eq!(value_to_oracle_expr(&Value::String("hello".into())), "'hello'"); - assert_eq!(value_to_oracle_expr(&Value::String("it's".into())), "'it''s'"); + assert_eq!( + value_to_oracle_expr(&Value::String("hello".into())), + "'hello'" + ); + assert_eq!( + value_to_oracle_expr(&Value::String("it's".into())), + "'it''s'" + ); + } + + #[test] + fn test_value_to_oracle_expr_timestamp_zero() { + // BUG-1: subsec_nanos = 0 should produce no .FF in format mask + let result = value_to_oracle_expr(&Value::Timestamp(0)); + assert_eq!( + result, + "TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')" + ); + } + + #[test] + fn test_value_to_oracle_expr_negative_epoch() { + // BUG-5: -1_000_000_001 nanos = 1969-12-31 23:59:58.999999 + let result = value_to_oracle_expr(&Value::Timestamp(-1_000_000_001)); + assert_eq!( + result, + "TO_TIMESTAMP('1969-12-31 23:59:58.999999', 'YYYY-MM-DD HH24:MI:SS.FF6')" + ); + } + + #[test] + fn test_value_to_oracle_date_expr_string_preserves_fractional() { + // BUG-3: snapshot string with fractional seconds and timezone — + // fractional part should now be preserved. + let col = SourceColumn { + name: "ts_col".into(), + data_type: DataType::Timestamp, + nullable: false, + pg_type_id: None, + }; + let result = value_to_oracle_date_expr( + &Value::String("2024-01-15 10:30:00.123456+00".into()), + &col, + ); + assert_eq!( + result, + "TO_TIMESTAMP('2024-01-15 10:30:00.123456', 'YYYY-MM-DD HH24:MI:SS.FF6')" + ); + } + + #[test] + fn test_value_to_oracle_date_expr_string_no_timezone() { + // String without timezone or fractional seconds + let col = SourceColumn { + name: "ts_col".into(), + data_type: DataType::Timestamp, + nullable: false, + pg_type_id: None, + }; + let result = value_to_oracle_date_expr( + &Value::String("2024-01-15 10:30:00".into()), + &col, + ); + assert_eq!( + result, + "TO_TIMESTAMP('2024-01-15 10:30:00', 'YYYY-MM-DD HH24:MI:SS')" + ); + } + + #[test] + fn test_value_to_oracle_date_expr_timestamp_no_fractional() { + // Value::Timestamp with subsec_nanos == 0 should not produce fractional seconds + let col = SourceColumn { + name: "ts_col".into(), + data_type: DataType::Timestamp, + nullable: false, + pg_type_id: None, + }; + let result = value_to_oracle_date_expr( + &Value::Timestamp(1705314600000000000), // 2024-01-15 10:30:00 UTC + &col, + ); + assert_eq!( + result, + "TO_TIMESTAMP('2024-01-15 10:30:00', 'YYYY-MM-DD HH24:MI:SS')" + ); + } + + #[test] + fn test_value_to_oracle_date_expr_date_type() { + // DATE type should still work + let col = SourceColumn { + name: "date_col".into(), + data_type: DataType::Date, + nullable: false, + pg_type_id: None, + }; + let result = value_to_oracle_date_expr( + &Value::String("2024-01-15".into()), + &col, + ); + assert_eq!( + result, + "TO_DATE('2024-01-15', 'YYYY-MM-DD HH24:MI:SS')" + ); } } diff --git a/src/engine/mod.rs b/src/engine/mod.rs index f801c4a..16e3495 100644 --- a/src/engine/mod.rs +++ b/src/engine/mod.rs @@ -206,7 +206,7 @@ impl CdcEngine { } }; if let Err(e) = sink.setup(&source_schemas).await { - self.halt_on_setup_error(&format!("Sink setup failed: {}", e)) + self.halt_on_setup_error(&format!("Sink setup failed: {:#}", e)) .await; } info!(" [OK] Sink setup complete"); diff --git a/src/pipeline/mod.rs b/src/pipeline/mod.rs index 873f073..3bdc8d6 100644 --- a/src/pipeline/mod.rs +++ b/src/pipeline/mod.rs @@ -132,8 +132,11 @@ impl Pipeline { let records = std::mem::take(batch); let record_count = records.len(); + info!("Pipeline: flushing batch of {} records at LSN 0x{:X}", record_count, lsn); + match self.sink.write_batch(records).await { Ok(result) => { + info!("Pipeline: flush_batch succeeded: {} records written", result.records_written); // Update metric for batches sent if let Some(state) = &self.shared_state { state.increment_batches(); @@ -168,7 +171,7 @@ impl Pipeline { } Err(e) => { // CRITICAL: Sink failure (StarRocks down, network error, etc.) - error!("CRITICAL: Sink write_batch failed: {}", e); + error!("CRITICAL: Sink write_batch failed: {:#}", e); error!( "CRITICAL: Batch details: {} events, LSN 0x{:X}", record_count, lsn diff --git a/src/replication/wal_handler.rs b/src/replication/wal_handler.rs index 1fae8ca..deb5edc 100644 --- a/src/replication/wal_handler.rs +++ b/src/replication/wal_handler.rs @@ -2,7 +2,7 @@ use anyhow::{anyhow, Result}; use bytes::{Buf, Bytes}; use futures_util::SinkExt; use tokio::sync::mpsc; -use tracing::error; +use tracing::{error, info}; use crate::control::state::SharedState; use crate::pipeline::schema_cache::SchemaCache; diff --git a/src/source/converter.rs b/src/source/converter.rs index d42904b..434d134 100644 --- a/src/source/converter.rs +++ b/src/source/converter.rs @@ -12,6 +12,7 @@ use crate::core::record::{CdcRecord, ColumnDef, ColumnValue, DataType, TableRef, use crate::pipeline::schema_cache::{SchemaCache, TableSchema}; use crate::source::parser::{CdcMessage, TupleData}; use crate::utils::{normalize_timestamptz, parse_pg_array, strip_money_symbol}; +use tracing::warn; /// Convert a CdcMessage (pgoutput) to a CdcRecord (generic). /// Returns None for messages that don't produce records (Unknown, LogicalMessage). @@ -59,7 +60,10 @@ pub fn convert_message( } CdcMessage::Insert { relation_id, tuple } => { - let schema = schema_cache.get(*relation_id)?; + let schema = schema_cache.get(*relation_id).or_else(|| { + warn!("Converter: schema cache miss for Insert relation_id={}", relation_id); + None + })?; let columns = tuple_to_column_values(tuple, schema); Some(CdcRecord::Insert { From 743c515d38cbe0969a0452df216c0e7a97dd3ed7 Mon Sep 17 00:00:00 2001 From: Nahuel Mazzitelli Date: Wed, 10 Jun 2026 17:14:08 -0300 Subject: [PATCH 3/4] oracle sink: remove scratch files (BUGS.md, REVIEW_FINDINGS.json) --- src/connectors/sinks/oracle/BUGS.md | 101 ------------------ .../sinks/oracle/REVIEW_FINDINGS.json | 70 ------------ 2 files changed, 171 deletions(-) delete mode 100644 src/connectors/sinks/oracle/BUGS.md delete mode 100644 src/connectors/sinks/oracle/REVIEW_FINDINGS.json diff --git a/src/connectors/sinks/oracle/BUGS.md b/src/connectors/sinks/oracle/BUGS.md deleted file mode 100644 index 24137df..0000000 --- a/src/connectors/sinks/oracle/BUGS.md +++ /dev/null @@ -1,101 +0,0 @@ -# Oracle Sink Type Mapping Bugs - -## Summary - -This document catalogs all bugs found in `types.rs` for the Oracle sink connector. -Each finding includes severity, root cause, fix suggestion, and a test command. - ---- - -## BUG-1 [HIGH] — `value_to_oracle_expr` for `Value::Timestamp`: format mask expects `.FF9` but missing when subsec_nanos = 0 - -- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` -- **Lines**: 151–158 -- **Root cause**: `NaiveDateTime`'s `Display` impl outputs `%Y-%m-%d %H:%M:%S` with **no** fractional part when subsec_nanos = 0 (e.g., `"2024-01-15 10:30:00"`). The `TO_TIMESTAMP` format mask is `"YYYY-MM-DD HH24:MI:SS.FF9"`, which **requires** a fractional-seconds component. Oracle raises `ORA-01862: the numeric value does not match the format string` because the input string has no `.` followed by digits, but the mask demands `.FF9`. - -- **Fix**: Conditionally include `.FF9` in the format mask only when subsec_nanos > 0, or use `naive.format("%Y-%m-%d %H:%M:%S%.f")` in the output and always use `"YYYY-MM-DD HH24:MI:SS"` (dropping `.FF9`). - -- **Test**: Confirm that `value_to_oracle_expr(&Value::Timestamp(0))` produces `TO_TIMESTAMP('1970-01-01 00:00:00', 'YYYY-MM-DD HH24:MI:SS')` (no `.FF9` in mask). - ---- - -## BUG-2 [HIGH] — `value_to_oracle_date_expr` for `Value::Timestamp` (non-Date): format mask `YYYY-MM-DD HH24:MI:SS` rejects fractional seconds - -- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` -- **Lines**: 39–53 -- **Root cause**: The `else` branch (lines 48–53) formats the timestamp using `%Y-%m-%d %H:%M:%S%.f`, which includes fractional seconds when non-zero (e.g., `"2024-01-15 10:30:00.123456"`). But the `TO_TIMESTAMP` mask is `"YYYY-MM-DD HH24:MI:SS"` — **without** a `.FF` suffix. Oracle raises `ORA-01861: literal does not match format string` because the `".123456"` suffix is not consumed by the format mask. - -- **Fix**: Change the format mask to `"YYYY-MM-DD HH24:MI:SS.FF6"` to match whatever fractional seconds the `%.f` formatter produces, and ensure the formatted string always includes at least a `.0` when subsec_nanos = 0 by using a format like `%.6f` instead of `%.f`. - -- **Test**: `value_to_oracle_date_expr(&Value::Timestamp(1705312200123456000), &ts_col)` → verify mask includes `.FF6`. - ---- - -## BUG-3 [HIGH] — `value_to_oracle_date_expr` for `Value::String` (non-Date): format mask `YYYY-MM-DD HH24:MI:SS` rejects fractional seconds from snapshot - -- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` -- **Lines**: 34–37 -- **Root cause**: Snapshot strings arrive from PG as `"2024-01-15 10:30:00.123456+00"`. The timezone is stripped but fractional seconds are **kept** (cleaned string: `"2024-01-15 10:30:00.123456"`). The `TO_TIMESTAMP` mask `"YYYY-MM-DD HH24:MI:SS"` has no `.FF` element, so Oracle rejects the `.123456` suffix. Same failure as BUG-2 but for snapshot data. - -- **Fix**: Change format mask to `"YYYY-MM-DD HH24:MI:SS.FF6"` (or `.FF9`) to accept optional fractional seconds. No change to the string-cleaning logic is needed. - -- **Test**: `value_to_oracle_date_expr(&Value::String("2024-01-15 10:30:00.123456+00".into()), &ts_col)` → mask includes `.FF6`. - ---- - -## BUG-4 [MEDIUM] — `data_type_to_oracle` for `DataType::Time`: maps wall-clock time to `INTERVAL DAY TO SECOND`, but TO_TIMESTAMP wrapper will fail - -- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` -- **Lines**: 92 -- **Root cause**: `DataType::Time` maps to `"INTERVAL DAY TO SECOND(0)"`. In Oracle, `INTERVAL DAY TO SECOND` stores **durations**, not wall-clock times. A PG `TIME` value like `"14:30:00"` representing 2:30 PM would be semantically wrong as a duration. Moreover, because `is_date_column()` returns `true` for `DataType::Time` (line 13), the value goes through `value_to_oracle_date_expr`, which wraps it in `TO_TIMESTAMP('14:30:00', 'YYYY-MM-DD HH24:MI:SS')` — which will fail because `"14:30:00"` has no date component to match `YYYY-MM-DD`. - -- **Fix options**: - - Map `DataType::Time` to `INTERVAL DAY TO SECOND` AND handle the value conversion to `INTERVAL '0 14:30:00' DAY TO SECOND` literal format. Remove `Time` from `is_date_column()`. - - Or map to `VARCHAR2(8)` / `VARCHAR2(12)` and store as a string. - -- **Test**: `data_type_to_oracle(&DataType::Time)` returns `"INTERVAL DAY TO SECOND(0)"` — verify decision with team. - ---- - -## BUG-5 [HIGH] — Negative epoch timestamps: incorrect secs/subsec_nanos decomposition due to truncation-toward-zero division - -- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` -- **Lines**: 153–154 (and lines 41–42) -- **Root cause**: For negative `ts` (epoch nanos before 1970), `ts / 1_000_000_000` in Rust truncates toward zero, not toward negative infinity. Example: `ts = -1_000_000_001` → `secs = -1` (should be `-2`), `subsec_nanos = (-1 % 1_000_000_000).abs() = 1`. Then `from_timestamp_opt(-1, 1)` gives `1969-12-31 23:59:59.000000001` instead of the correct `1969-12-31 23:59:58.999999999` — a **1-second error** for timestamps before 1970 that are not exact multiples of 1 second. - - This bug exists in **both** `value_to_oracle_expr` (lines 153–154) and `value_to_oracle_date_expr` (lines 41–42). - -- **Fix**: Use floor-style Euclidean division: - ```rust - let secs = ts.div_euclid(1_000_000_000); - let subsec_nanos = ts.rem_euclid(1_000_000_000) as u32; - ``` - -- **Test**: `value_to_oracle_expr(&Value::Timestamp(-1_000_000_001))` → `TO_TIMESTAMP('1969-12-31 23:59:58.999999999', 'YYYY-MM-DD HH24:MI:SS.FF9')` - ---- - -## BUG-6 [LOW] — `value_to_oracle_date_expr` string cleaning: can produce empty string for unusual timezone-only inputs - -- **File**: `/Users/nahuelmazzitelli/.ez-cdc-runs/ez-cdc-run-oracle-65f41d2e/dbmazz/src/connectors/sinks/oracle/types.rs` -- **Lines**: 26–29 -- **Root cause**: The `trim_end_matches` closure removes `+`, `-`, `:`, and `0-9`. If the input string is just a timezone like `"+00"` (hypothetical edge case), every character matches the predicate and the string is reduced to `""`. This then produces `TO_TIMESTAMP('', 'YYYY-MM-DD HH24:MI:SS')` which would fail in Oracle. Realistic risk is low because date/time values should always have date components. - -- **Fix**: Guard against empty cleaned string: - ```rust - if cleaned.is_empty() { return "NULL".to_string(); } - ``` - -- **Test**: Hard to trigger naturally; unit-test with `Value::String("+00".into())`. - ---- - -## Additional Observations - -### Observation A — Redundant `if` in `build_using_select` (mod.rs lines 169–176) - -Not a bug, but both branches of `if is_date_column(sc)` call `value_to_oracle_typed_expr(val, sc)` identically. The condition is dead code and should be simplified to a single call. - -### Observation B — Snowflake and StarRocks sinks have the same negative-epoch division bug - -Both sinks (`snowflake/types.rs` line 96, `starrocks/types.rs` line 161) use `ts / 1_000_000` for microsecond precision, which has the same truncation-toward-zero issue for negative timestamps. If those sinks need to support dates before 1970, they should also be fixed. diff --git a/src/connectors/sinks/oracle/REVIEW_FINDINGS.json b/src/connectors/sinks/oracle/REVIEW_FINDINGS.json deleted file mode 100644 index 480ae75..0000000 --- a/src/connectors/sinks/oracle/REVIEW_FINDINGS.json +++ /dev/null @@ -1,70 +0,0 @@ -{ - "verdict": "FAIL", - "summary": "The oracle sink connector compiles and passes all unit tests. However, 2 significant runtime bugs were found: (1) Value::Unchanged maps to NULL in MERGE, causing data loss on UPDATE with TOAST columns, (2) DataType::Time wrapped in TO_TIMESTAMP without date component causes Oracle ORA-01861. Also 2 minor issues (empty string edge case and dead code).", - "findings": [ - { - "severity": "HIGH", - "file": "dbmazz/src/connectors/sinks/oracle/mod.rs", - "line": 367, - "root_cause": "write_batch() uses the same MERGE path for both Insert and Update records. For Update records, `Value::Unchanged` columns (PG TOAST optimization — columns not changed in the UPDATE) are mapped to `\"NULL\"` by `value_to_oracle_expr` (types.rs:232). The `generate_merge()` function (merge_generator.rs:72-91) always sets ALL non-PK columns in the UPDATE SET clause. Result: the MERGE unconditionally overwrites unchanged TOAST columns with NULL, causing data loss.", - "fix": "Two-part fix: (1) In write_batch, for Update records, filter out columns whose values are `Value::Unchanged` before calling `build_using_select`. (2) Modify `generate_merge` to accept an optional filtered column list for the UPDATE SET clause, excluding Unchanged columns. Alternative minimal fix: change `value_to_oracle_expr(Value::Unchanged)` to return `\"DEFAULT\"` and modify the MERGE to use `COALESCE(src.col, dst.col)` pattern — but Oracle MERGE does not allow COALESCE across USING/DST boundaries, so filtering is required.", - "test_to_verify": "cargo test --features oracle-sink,default -p dbmazz --lib -- oracle" - }, - { - "severity": "MEDIUM", - "file": "dbmazz/src/connectors/sinks/oracle/types.rs", - "line": 13, - "root_cause": "is_date_column() returns true for DataType::Time (line 13). This causes time-only values like '14:30:00' to go through value_to_oracle_date_expr(), which wraps them in TO_TIMESTAMP('14:30:00', 'YYYY-MM-DD HH24:MI:SS'). Oracle rejects this with ORA-01861 because '14:30:00' has no YYYY-MM-DD component matching the format mask. Also, data_type_to_oracle maps Time to 'INTERVAL DAY TO SECOND(0)' which is semantically a duration, not wall-clock time.", - "fix": "Option A: Remove DataType::Time from is_date_column() and implement proper INTERVAL DAY TO SECOND literal generation (INTERVAL '0 14:30:00' DAY TO SECOND). Option B: Map DataType::Time to VARCHAR2(8) in data_type_to_oracle and handle as string. Option A has better type fidelity but is more work. If Option A is chosen, update both is_date_column() and value_to_oracle_date_expr() to handle Time separately from Timestamp.", - "test_to_verify": "cargo test --features oracle-sink,default -p dbmazz --lib -- oracle" - }, - { - "severity": "LOW", - "file": "dbmazz/src/connectors/sinks/oracle/types.rs", - "line": 26, - "root_cause": "BUG-6 from BUGS.md: The string cleaning logic in value_to_oracle_date_expr() can produce an empty string for unusual timezone-only inputs (e.g., Value::String('+00')). The trim_end_matches() closure removes '+', '-', ':', and digits from the end of the string, which can strip everything. This produces TO_TIMESTAMP('', 'YYYY-MM-DD HH24:MI:SS') which fails in Oracle.", - "fix": "Add guard: if cleaned.is_empty() { return 'NULL'.to_string(); } after the string cleaning block (after line 55).", - "test_to_verify": "cargo test --features oracle-sink,default -p dbmazz --lib -- oracle" - }, - { - "severity": "LOW", - "file": "dbmazz/src/connectors/sinks/oracle/mod.rs", - "line": 125, - "root_cause": "connect_sync() and find_schema() are defined but never called. connect_sync (line 125) is dead because connection is done inline in write_batch and validate_connection. find_schema (line 133) is dead because schema lookup is done inline in write_batch via source_schemas.iter().find(). group_by_table (line 138) is used only in tests but never in production — write_batch does its own grouping inline (lines 342-352). The whole schema_tracking.rs module is imported but its types (SchemaState, initialize_state) are never used — the SOURCE_SCHEMAS static OnceLock is used instead.", - "fix": "Remove connect_sync(), find_schema() dead code. Remove or deprecate group_by_table() (or use it in write_batch instead of the inline grouping). Remove schema_tracking.rs module or integrate it with the OnceLock pattern. These do NOT cause runtime failures but create confusion and maintenance burden.", - "test_to_verify": "cargo check --features oracle-sink,default -p dbmazz 2>&1 | grep -c warning" - }, - { - "severity": "PRE_EXISTING", - "file": "dbmazz/src/replication/wal_handler.rs", - "line": 5, - "root_cause": "Unused import `info` from tracing crate. This warning exists regardless of the oracle-sink feature flag — it's a pre-existing issue in the shared WAL handler code.", - "fix": "Remove `info` from the use statement: change `use tracing::{error, info};` to `use tracing::error;`.", - "test_to_verify": "cargo check -p dbmazz --lib 2>&1 | grep -c 'unused import.*info'" - }, - { - "severity": "PRE_EXISTING", - "file": "dbmazz/src/pipeline/mod.rs", - "line": 151, - "root_cause": "PG_EPOCH_OFFSET_USEC is hardcoded for PostgreSQL's epoch (2000-01-01). When MySQL is the source, commit timestamps use Unix epoch (1970-01-01), so adding PG_EPOCH_OFFSET_USEC produces commit timestamps ~30 years in the future. This affects replication lag calculation for MySQL→Oracle pipelines. Pre-existing bug not introduced by the Oracle sink.", - "fix": "The pipeline should receive the source type and conditionally apply PG_EPOCH_OFFSET_USEC only when the source is PostgreSQL.", - "test_to_verify": "Not oracle-sink specific — pre-existing bug" - }, - { - "severity": "PRE_EXISTING", - "file": "dbmazz/src/source/converter.rs", - "line": 206, - "root_cause": "PG OID 114 (json, not jsonb) is mapped to DataType::Jsonb. PG's json preserves key ordering and duplicate keys; jsonb does not. This is a semantic type slippage that affects Oracle DDL generation. Pre-existing issue not introduced by the Oracle sink.", - "fix": "Map OID 114 → DataType::Json and OID 3802 → DataType::Jsonb separately.", - "test_to_verify": "Not oracle-sink specific — pre-existing bug" - }, - { - "severity": "PRE_EXISTING", - "file": "dbmazz/src/source/converter.rs", - "line": 189, - "root_cause": "OID 790 (Money) is handled in convert_pg_value (returns Value::Decimal) but NOT included in pg_type_to_data_type, so it falls through to the default DataType::String. For the Oracle sink, column_type(DataType::String, Some(790)) calls pg_oid_to_oracle_type(790) which returns 'CLOB' (not in any match arm → catches _ => 'CLOB'). The column is CLOB but values are Decimal — works functionally (Oracle accepts numbers in CLOB) but semantically wrong. Pre-existing converter gap.", - "fix": "Add 790 → DataType::Decimal { precision: ... } to pg_type_to_data_type() in converter.rs, or add 790 to pg_oid_to_oracle_type() in types.rs to map to NUMBER.", - "test_to_verify": "Not oracle-sink specific — pre-existing gap in converter" - } - ] -} From 545faa1ae8db5a4ef4be2761580986c060018da6 Mon Sep 17 00:00:00 2001 From: Nahuel Mazzitelli Date: Wed, 10 Jun 2026 18:37:18 -0300 Subject: [PATCH 4/4] docs: add oracle sink connector documentation - Add oracle/README.md with connector documentation (types, config, architecture) - Add Oracle to dbmazz README.md support matrix - Add Oracle to docs/configuration.md (SINK_TYPE, SINK_URL, requirements) - Add Oracle to docs/architecture.md (module map) --- README.md | 8 +- docs/architecture.md | 7 + docs/configuration.md | 14 +- src/connectors/sinks/oracle/README.md | 202 ++++++++++++++++++++++++++ 4 files changed, 225 insertions(+), 6 deletions(-) create mode 100644 src/connectors/sinks/oracle/README.md diff --git a/README.md b/README.md index bf8c8cf..a5ce9d5 100644 --- a/README.md +++ b/README.md @@ -122,6 +122,7 @@ Full Docker reference (env vars, healthcheck, persisting state, build-from-sourc | PostgreSQL 12+ | **StarRocks 3.2+** | ✅ Stable | JSON Stream Load, partial-update for TOAST columns, audit columns auto-managed, schema evolution requires per-table `fast_schema_evolution=true` | | PostgreSQL 12+ | **PostgreSQL 15+** | ✅ Stable | Binary `COPY` → raw table → `MERGE` normalizer; supports hard delete | | PostgreSQL 12+ | **Snowflake** | ✅ Stable | Parquet → PUT (stage) → `COPY INTO` → background `MERGE`; JWT key-pair auth supported; requires `ALTER TABLE` privilege on target schema | +| PostgreSQL 12+ | **Oracle 12c+** | ✅ Stable | Direct MERGE (upsert) to Oracle tables via `oracle` crate (kubo/rust-oracle). See [`src/connectors/sinks/oracle/README.md`](src/connectors/sinks/oracle/README.md). | | PostgreSQL 12+ | S3 / Iceberg | 🚧 Roadmap | Tracked in [issues](https://github.com/ez-cdc/dbmazz/issues) | | MySQL 5.7+ / 8.0+ | All sinks | 🧪 Beta | Binlog-based with GTID-aware checkpointing. See [`docs/mysql-source.md`](docs/mysql-source.md). | @@ -135,9 +136,10 @@ Adding a new sink is intentionally small: implement a 6-method `Sink` trait and PostgreSQL (source) dbmazz Sink (target) ┌──────────────┐ ┌────────────────────┐ ┌──────────────┐ │ WAL │ logical │ WAL Handler │ │ StarRocks │ -│ (INSERT, │ replication │ │ │ │ PostgreSQL │ -│ UPDATE, │ ────────────▶ │ ▼ │ │ Snowflake │ -│ DELETE) │ (pgoutput) │ source/converter │ │ │ +│ (INSERT, │ replication │ │ │ │ Oracle │ +│ UPDATE, │ ────────────▶ │ ▼ │ │ PostgreSQL │ +│ DELETE) │ (pgoutput) │ source/converter │ │ Snowflake │ +│ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ▼ │ │ │ │ │ │ Pipeline │ write │ │ diff --git a/docs/architecture.md b/docs/architecture.md index dbebff6..f22b5d9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -190,6 +190,13 @@ src/ │ │ ├── merge_generator.rs Dynamic MERGE SQL generation │ │ ├── setup.rs DDL: raw table, metadata, target tables │ │ └── types.rs PG → PG type mapping +│ ├── oracle/ Oracle sink +│ │ ├── mod.rs OracleSink (MERGE via kubo/rust-oracle) +│ │ ├── merge_generator.rs MERGE SQL generation (Oracle dialect) +│ │ ├── schema_tracking.rs Schema state cache +│ │ ├── setup.rs DDL: metadata table, target tables +│ │ ├── types.rs DataType → Oracle type mapping +│ │ └── README.md Connector documentation │ └── snowflake/ Snowflake sink │ ├── mod.rs SnowflakeSink (Parquet → PUT → COPY INTO → MERGE) │ ├── client.rs HTTP client (password + JWT auth, SQL execution) diff --git a/docs/configuration.md b/docs/configuration.md index c6d26a3..c8bedff 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -23,11 +23,11 @@ every option documented inline. The default location is | Variable | Default | Description | |---|---|---| -| `SINK_TYPE` | `starrocks` | Sink connector type: `starrocks`, `postgres`, or `snowflake`. | -| `SINK_URL` | — | Sink connection URL. For StarRocks: `http://host:8030` (FE HTTP). For PostgreSQL: `postgres://...`. For Snowflake: ignored (use `SINK_SNOWFLAKE_ACCOUNT`). | +| `SINK_TYPE` | `starrocks` | Sink connector type: `starrocks`, `postgres`, `snowflake`, or `oracle`. | +| `SINK_URL` | — | Sink connection URL. For StarRocks: `http://host:8030` (FE HTTP). For PostgreSQL: `postgres://...`. For Oracle: `//host:1521/service_name`. For Snowflake: ignored (use `SINK_SNOWFLAKE_ACCOUNT`). | | `SINK_PORT` | `9030` | Additional port when needed (e.g., StarRocks MySQL protocol port for DDL). | | `SINK_DATABASE` | — (required) | Target database name. | -| `SINK_SCHEMA` | `public` | Target schema (PostgreSQL) or `PUBLIC` (Snowflake). StarRocks does not use this. | +| `SINK_SCHEMA` | `public` | Target schema (PostgreSQL) or database (Oracle) or `PUBLIC` (Snowflake). StarRocks does not use this. | | `SINK_USER` | `root` | Authentication username. | | `SINK_PASSWORD` | *(empty)* | Authentication password. | @@ -90,6 +90,14 @@ loud with an actionable error message if they are missing. | Target tables created by the operator | dbmazz does not create tables; CLUSTER BY, transient/permanent, and other Snowflake-specific decisions are operator-owned | `CREATE TABLE ...` ahead of time | | Key-pair JWT auth (recommended over password) | Lower auth-related rotation overhead; `SINK_SNOWFLAKE_PRIVATE_KEY_PATH` env var | See [Snowflake key-pair auth docs](https://docs.snowflake.com/en/user-guide/key-pair-auth) | +### Oracle (sink) + +| Requirement | Why | How to satisfy | +|---|---|---| +| Oracle Instant Client (Basic Light) at runtime | The `oracle` (kubo/rust-oracle) crate wraps ODPI-C, which loads `libclntsh.so` via `dlopen` | Use the `dbmazz-oracle` Docker image (bundles Instant Client). On bare metal, install Oracle Instant Client and set `LD_LIBRARY_PATH`. | +| Target schema must exist | The sink creates tables within the target schema but does not create the schema | `CREATE USER IDENTIFIED BY ; GRANT CONNECT, RESOURCE TO ;` | +| Oracle tables created by dbmazz | The Oracle sink **does** create target tables if they don't exist (mirroring source schemas with Oracle-compatible column types) | No action needed — the sink handles DDL automatically during `setup()` | + ### PostgreSQL (sink) | Requirement | Why | How to satisfy | diff --git a/src/connectors/sinks/oracle/README.md b/src/connectors/sinks/oracle/README.md new file mode 100644 index 0000000..3477a35 --- /dev/null +++ b/src/connectors/sinks/oracle/README.md @@ -0,0 +1,202 @@ +# Oracle Sink Connector + +> CDC sink connector for [Oracle Database](https://www.oracle.com/database/), an enterprise OLTP/OLAP database. Uses MERGE (upsert) for INSERT/UPDATE and direct DELETE for deletion operations. + +## Features + +- **Upserts**: Supported via MERGE (Oracle 9i+) +- **Deletes**: Hard deletes via DELETE +- **Schema Evolution**: Not supported (new columns from source are skipped) +- **Transactions**: Atomic writes per batch (MERGE + metadata in one transaction) +- **Loading Model**: Streaming — direct MERGE to target tables (no staging) + +## Architecture + +``` +CdcRecord --> OracleSink --> oracle crate (kubo/rust-oracle) --> Oracle Database + | | | + v v v + types.rs spawn_blocking SQL*Net + (mapping) (sync API on Tokio) (OCI/OPI-C) +``` + +## Configuration + +The sink is configured via environment variables: + +| Variable | Description | Default | +|----------|-------------|---------| +| `SINK_URL` | Oracle connection string (e.g., `//host:1521/FREEPDB1`) | required | +| `SINK_SCHEMA` | Target schema name | `DBMAZZ` | +| `SINK_USER` | Oracle username | required | +| `SINK_PASSWORD` | Oracle password | required | +| `SINK_TYPE` | Must be `oracle` | required | + +### Example + +```bash +export SINK_TYPE=oracle +export SINK_URL="//localhost:1521/FREEPDB1" +export SINK_DATABASE=FREEPDB1 +export SINK_SCHEMA=DBMAZZ +export SINK_USER=postgres +export SINK_PASSWORD=postgres +``` + +## CDC Audit Columns + +The sink adds two audit columns to every target table: + +| Column | Type | Description | +|--------|------|-------------| +| `_DBMAZZ_SYNCED_AT` | `TIMESTAMP(6)` | Timestamp when record was synced (default: `SYSTIMESTAMP`) | +| `_DBMAZZ_OP_TYPE` | `NUMBER(2)` | Last operation type: 0=INSERT, 1=UPDATE, 2=DELETE | + +### Metadata Table + +The sink creates a `_DBMAZZ_METADATA` table in the target schema during `setup`: + +```sql +CREATE TABLE DBMAZZ._DBMAZZ_METADATA ( + key VARCHAR2(255) PRIMARY KEY, + val VARCHAR2(4000) +); +``` + +This table tracks CDC offset state (SCN-based position tracking). + +## Loading Protocol + +### Direct MERGE (no staging) + +Unlike the PostgreSQL sink (which uses a staging raw table + background normalizer), the Oracle sink writes directly to target tables using MERGE statements: + +1. **MERGE** (for INSERT/UPDATE): `MERGE INTO target USING DUAL ON (pk match) WHEN MATCHED THEN UPDATE SET ... WHEN NOT MATCHED THEN INSERT (...)` +2. **DELETE** (for DELETE): `DELETE FROM target WHERE pk = :1` +3. Each batch runs in a single transaction with `_DBMAZZ_METADATA` position tracking + +### Batching Strategy + +- **Batch size**: 1 – 250,000 records +- **Flush interval**: 10,000ms +- **Grouping**: Records grouped by table, one MERGE per table per batch + +## Type Mappings + +| CDC DataType | Oracle Type | +|--------------|-------------| +| `Boolean` | `NUMBER(1)` | +| `Int16` | `NUMBER(5)` | +| `Int32` | `NUMBER(10)` | +| `Int64` | `NUMBER(19)` | +| `Float32` | `BINARY_FLOAT` | +| `Float64` | `BINARY_DOUBLE` | +| `Decimal` | `NUMBER(p,s)` | +| `String/Text` | `VARCHAR2(4000)` | +| `Json/Jsonb` | `CLOB` | +| `Uuid` | `VARCHAR2(36)` | +| `Date` | `DATE` | +| `Time` | `TIMESTAMP` | +| `Timestamp` | `TIMESTAMP` | +| `Bytes` | `BLOB` | + +## Table Requirements + +Target tables are created automatically by the sink during `setup` with: + +```sql +CREATE TABLE DBMAZZ."{table_name}" ( + {columns}, + _DBMAZZ_SYNCED_AT TIMESTAMP(6) DEFAULT SYSTIMESTAMP, + _DBMAZZ_OP_TYPE NUMBER(2) DEFAULT 0 +); +``` + +- **Primary keys**: Required for MERGE (upsert) — sourced from the source table's schema +- **Identifiers**: All table/column names are quoted and uppercased to match Oracle's metadata convention + +## TOAST Handling + +When PostgreSQL sends an UPDATE with unchanged TOAST columns (`Value::Unchanged`), the sink: + +1. Detects unchanged columns from the incoming `CdcRecord` +2. Excludes those columns from the MERGE `UPDATE SET` clause +3. Prevents silent NULL overwrite of unmodified TOAST columns in Oracle + +## Error Handling + +The sink includes retry logic: + +- **Max retries**: 3 per batch +- **Backoff strategy**: Exponential (1s → 2s → 4s) +- **Retriable errors**: Connection failures, transient Oracle errors +- **Non-retriable errors**: Invalid SQL, missing tables, constraint violations + +### Common Errors + +1. **`ORA-01830` - date format picture ends before converting entire input** + - Cause: Timestamp string with trailing dot or incomplete fractional seconds + - Solution: The sink uses `.FF6` format mask and strips trailing dots before formatting + +2. **`ORA-00942` - table or view does not exist** + - Cause: Target table not created yet + - Solution: The sink creates tables automatically during `setup()` — ensure `setup` runs before `write_batch` + +3. **Connection failures with Instant Client** + - Cause: Oracle Instant Client libraries not found at runtime + - Solution: Use the `dbmazz-oracle:dev` Docker image which bundles Instant Client, or set `LD_LIBRARY_PATH` + +## Module Structure + +``` +oracle/ +├── mod.rs # OracleSink: Sink trait implementation +├── merge_generator.rs # MERGE SQL generation (Oracle dialect) +├── schema_tracking.rs # Schema state cache +├── setup.rs # DDL: metadata table, target tables +├── types.rs # DataType → Oracle type mapping + value conversion +└── README.md # This file +``` + +## Capabilities + +```rust +SinkCapabilities { + supports_upsert: true, + supports_delete: true, + supports_schema_evolution: false, + supports_transactions: true, + loading_model: LoadingModel::Streaming, + min_batch_size: Some(1), + max_batch_size: Some(250_000), + optimal_flush_interval_ms: 10_000, +} +``` + +## Schema Evolution + +Schema evolution is **not supported** for the Oracle sink. New columns added to the source table are silently skipped during CDC replication. To add columns to the target Oracle table, apply them manually: + +```sql +ALTER TABLE DBMAZZ."{table_name}" ADD ({column_name} {oracle_type}); +``` + +## Prerequisites + +| Requirement | Why | How to satisfy | +|---|---|---| +| Oracle Instant Client | The `oracle` crate requires ODPI-C (bundled in Instant Client) at runtime | Use the `dbmazz-oracle` Docker image which bundles Instant Client Basic Light | +| Target schema must exist | The sink creates tables within the target schema but does not create the schema itself | `CREATE USER DBMAZZ IDENTIFIED BY ...; GRANT CONNECT, RESOURCE TO DBMAZZ;` | +| Oracle 12c+ | Tested against Oracle 12c, 19c, 21c, and 23c (including Oracle Free) | Use `gvenzl/oracle-free` for testing | + +## Limitations + +- **Schema evolution**: Not supported — `ALTER TABLE ADD COLUMN` is not propagated +- **No staging area**: Writes go directly to target tables (no transactional rollback for partial batch failures) +- **No Instant Client on ARM64 macOS**: Oracle Instant Client for macOS is x86_64 only — use Docker for development on Apple Silicon + +## References + +- [Oracle Database Documentation](https://docs.oracle.com/en/database/) +- [kubo/rust-oracle crate](https://github.com/kubo/rust-oracle) +- [Oracle MERGE statement](https://docs.oracle.com/en/database/oracle/oracle-database/23/sqlrf/MERGE.html)