25 MB lightweight cross-platform database client for 100+ databases, including MySQL, PostgreSQL, SQLite, Redis, MongoDB, DuckDB, SQL Server, and Dameng. Built-in AI, MCP Server, CLI, desktop and Docker. | 轻量级跨平台数据库管理工具,支持 MySQL、PostgreSQL、SQLite、Redis、MongoDB、达梦等 100+ 数据库,提供桌面端、Docker、CLI、内置 AI 助手和 MCP。
TypeScript aicliclickhousedatabasedatabase-clientdatabase-managementdockerguimcpmongodbmysqlpostgresqlredisrustsql-serversqlitetaurivue
feat(schema-diff): preserve dialect-specific DDL semantics
dbin0123002a2c85c02a
diff --git a/Cargo.lock b/Cargo.lockindex a383ed13ae..2192825017 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -41,9 +41,9 @@ dependencies = [[[package]]name = "aes"-version = "0.9.0"+version = "0.9.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "66bd29a732b644c0431c6140f370d097879203d79b80c94a6747ba0872adaef8"+checksum = "f1fc76eaeac4c9164506c466d4ffdd8ec9d0c5bf57ee97177c4d8eceb3a0e138"dependencies = ["cipher 0.5.2","cpubits",@@ -71,7 +71,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e22c0c90bbe8d4f77c3ca9ddabe41a1f8382d6fc1f7cea89459d0f320371f972"dependencies = ["aead 0.6.0-rc.10",- "aes 0.9.0",+ "aes 0.9.1","cipher 0.5.2","ctr 0.10.1","ghash 0.6.0",@@ -120,9 +120,9 @@ checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3"[[package]]name = "alloc-stdlib"-version = "0.2.2"+version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "94fb8275041c72129eb51b7d0322c29b8387a0386127718b096429201a5d6ece"+checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195"dependencies = ["alloc-no-stdlib",]@@ -161,15 +161,15 @@ dependencies = [[[package]]name = "anyhow"-version = "1.0.102"+version = "1.0.104"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"[[package]]name = "ar_archive_writer"-version = "0.5.1"+version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7eb93bbb63b9c227414f6eb3a0adfddca591a8ce1e9b60661bb08969b87e340b"+checksum = "4087686b4b0a3427190bae57a1d9a478dbb2d40c5dc1bd6e2b6d797913bdd348"dependencies = ["object",]@@ -204,6 +204,15 @@ dependencies = ["x11rb",]+[[package]]+name = "arc-swap"+version = "1.9.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c049c0be4daef0b145cb3555416b3b8ef5b7888a38aea1a3a155801fe7b0810b"+dependencies = [+ "rustversion",+]+[[package]]name = "argon2"version = "0.5.3"@@ -218,15 +227,15 @@ dependencies = [[[package]]name = "arrayvec"-version = "0.7.6"+version = "0.7.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56"[[package]]name = "arrow"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "378530e55cd479eda3c14eb345310799717e6f76d0c332041e8487022166b471"+checksum = "6cfdd0833e32a9874d2b55089333ad310c0be208aafa277385ce2461dec90be3"dependencies = ["arrow-arith","arrow-array",@@ -242,9 +251,9 @@ dependencies = [[[package]]name = "arrow-arith"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a0ab212d2c1886e802f51c5212d78ebbcbb0bec980fff9dadc1eb8d45cd0b738"+checksum = "0a41203398f0eaa6f7ec8e62c0da742a21abf282c148fc157f6c35c90e29981a"dependencies = ["arrow-array","arrow-buffer",@@ -256,9 +265,9 @@ dependencies = [[[package]]name = "arrow-array"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfd33d3e92f207444098c75b42de99d329562be0cf686b307b097cc52b4e999e"+checksum = "ae33dad492b7df00a217563a7b0ef2874df68a0deea1b1a3acf628152f7f7a69"dependencies = ["ahash 0.8.12","arrow-buffer",@@ -274,9 +283,9 @@ dependencies = [[[package]]name = "arrow-buffer"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c6cd424c2693bcdbc150d843dc9d4d137dd2de4782ce6df491ad11a3a0416c0"+checksum = "b9552f96391c005e6ab449fa941420935e7e062489b12b8b1b08879b2163f5b5"dependencies = ["bytes","half",@@ -286,9 +295,9 @@ dependencies = [[[package]]name = "arrow-cast"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4c5aefb56a2c02e9e2b30746241058b85f8983f0fcff2ba0c6d09006e1cded7f"+checksum = "3a8a327c9649f30d8406995f27642b68df354713cca3baaaf100f076f18d5f34"dependencies = ["arrow-array","arrow-buffer",@@ -308,9 +317,9 @@ dependencies = [[[package]]name = "arrow-data"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3c88210023a2bfee1896af366309a3028fc3bcbd6515fa29a7990ee1baa08ee0"+checksum = "2b24852db04738907e06c04ea61e42fe7fda962a34513022dc0d0e754fb7976b"dependencies = ["arrow-buffer","arrow-schema",@@ -321,9 +330,9 @@ dependencies = [[[package]]name = "arrow-ord"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1bffd8fd2579286a5d63bac898159873e5094a79009940bcb42bbfce4f19f1d0"+checksum = "63a083ec750f5c043f02946b4baf05fcdbb55f4560a3277055caca5cc99f3eb0"dependencies = ["arrow-array","arrow-buffer",@@ -334,9 +343,9 @@ dependencies = [[[package]]name = "arrow-row"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bab5994731204603c73ba69267616c50f80780774c6bb0476f1f830625115e0c"+checksum = "514ba0ef0d4c5896202dae736251ce415abb43a950bed570fb7981b8716c0e4c"dependencies = ["arrow-array","arrow-buffer",@@ -347,18 +356,18 @@ dependencies = [[[package]]name = "arrow-schema"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f633dbfdf39c039ada1bf9e34c694816eb71fbb7dc78f613993b7245e078a1ed"+checksum = "21ca356ad6425cecb6eb7b28e4f659f1ee7880fbb1a16127de7dd62901efee9e"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1",][[package]]name = "arrow-select"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8cd065c54172ac787cf3f2f8d4107e0d3fdc26edba76fdf4f4cc170258942222"+checksum = "c58da39eb3d8350ad4a549e5c2bc49284dac554016c69829310350f1731b0aad"dependencies = ["ahash 0.8.12","arrow-array",@@ -370,9 +379,9 @@ dependencies = [[[package]]name = "arrow-string"-version = "58.3.0"+version = "58.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "29dd7cda3ab9692f43a2e4acc444d760cc17b12bb6d8232ddf64e9bab7c06b42"+checksum = "b6789b388467525e3271326b6b4915666ecfdf5142aef09779445c954b67543c"dependencies = ["arrow-array","arrow-buffer",@@ -490,7 +499,7 @@ checksum = "3b43422f69d8ff38f95f1b2bb76517c91589a924d1559a0e935d7c8ce0274c11"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -530,7 +539,7 @@ checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -541,13 +550,13 @@ checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de"[[package]]name = "async-trait"-version = "0.1.89"+version = "0.1.91"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"+checksum = "ae36dc4177970ef04fde5178d3e2429882def40e57a451f919c098f72baa6cec"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]@@ -618,9 +627,9 @@ checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"[[package]]name = "aws-lc-rs"-version = "1.17.0"+version = "1.17.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00"+checksum = "00bdb5da18dac48ca2cc7cd4a98e533e8635a58e2361d13a1a4ee3888e0d72f1"dependencies = ["aws-lc-sys","untrusted 0.7.1",@@ -629,14 +638,15 @@ dependencies = [[[package]]name = "aws-lc-sys"-version = "0.41.0"+version = "0.43.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4"+checksum = "43103168cc76fe62678a375e722fc9cb3a0146159ac5828bc4f0dfd755c2224c"dependencies = ["cc","cmake","dunce","fs_extra",+ "pkg-config",][[package]]@@ -666,7 +676,7 @@ dependencies = ["serde_json","serde_path_to_error","serde_urlencoded",- "sha1 0.10.6",+ "sha1 0.10.7","sync_wrapper","tokio","tokio-tungstenite",@@ -753,18 +763,18 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"[[package]]name = "bitflags"-version = "2.11.1"+version = "2.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"+checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da"dependencies = ["serde_core",][[package]]name = "bitvec"-version = "1.0.1"+version = "1.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1bc2832c24239b0141d5674bb9174f9d68a8b5b3f2753311927c172ca46f7e9c"+checksum = "ddcec3d12c579d40898fe0a9a358a803c23e9c52ca3c425707f81c9436211837"dependencies = ["funty","radium",@@ -792,9 +802,9 @@ dependencies = [[[package]]name = "block-buffer"-version = "0.12.0"+version = "0.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"dependencies = ["hybrid-array",]@@ -851,9 +861,9 @@ dependencies = [[[package]]name = "borsh"-version = "1.6.1"+version = "1.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cfd1e3f8955a5d7de9fab72fc8373fade9fb8a703968cb200ae3dc6cf08e185a"+checksum = "a88b7ea17d208c4193f2c1e6de3c35fe71f98c96982d5ced308bdcc749ff6e1f"dependencies = ["borsh-derive","bytes",@@ -862,22 +872,22 @@ dependencies = [[[package]]name = "borsh-derive"-version = "1.6.1"+version = "1.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bfcfdc083699101d5a7965e49925975f2f55060f94f9a05e7187be95d530ca59"+checksum = "d8f347189c62a579b8cd5f80714efa178f52e461dc2e6d701d264f5ff22e566c"dependencies = ["once_cell","proc-macro-crate 3.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "brotli"-version = "8.0.2"+version = "8.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4bd8b9603c7aa97359dbd97ecf258968c95f3adddd6db2f7e7a5bef101c84560"+checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3"dependencies = ["alloc-no-stdlib","alloc-stdlib",@@ -886,9 +896,9 @@ dependencies = [[[package]]name = "brotli-decompressor"-version = "5.0.0"+version = "5.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "874bb8112abecc98cbd6d81ea4fa7e94fb9449648c93cc89aa40c81c24d7de03"+checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583"dependencies = ["alloc-no-stdlib","alloc-stdlib",@@ -918,7 +928,7 @@ dependencies = ["indexmap 2.14.0","js-sys","once_cell",- "rand 0.9.4",+ "rand 0.9.5","serde","serde_bytes","serde_json",@@ -926,6 +936,16 @@ dependencies = ["uuid",]+[[package]]+name = "bstr"+version = "1.13.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1f7dc094d718f2e1c1559ad110e27eeaae14a5465d3d56dd6dbd793079fbd530"+dependencies = [+ "memchr",+ "serde_core",+]+[[package]]name = "btoi"version = "0.5.0"@@ -941,18 +961,6 @@ version = "3.20.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"-[[package]]-name = "byte-unit"-version = "5.2.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8c6d47a4e2961fb8721bcfc54feae6455f2f64e7054f9bc67e875f0e77f4c58d"-dependencies = [- "rust_decimal",- "schemars 1.2.1",- "serde",- "utf8-width",-]-[[package]]name = "bytecheck"version = "0.6.12"@@ -977,9 +985,9 @@ dependencies = [[[package]]name = "bytemuck"-version = "1.25.0"+version = "1.25.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec"+checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797"[[package]]name = "byteorder"@@ -995,9 +1003,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495"[[package]]name = "bytes"-version = "1.11.1"+version = "1.12.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"dependencies = ["serde",]@@ -1017,7 +1025,7 @@ version = "0.18.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","cairo-sys-rs","glib","libc",@@ -1056,9 +1064,9 @@ dependencies = [[[package]]name = "camino"-version = "1.2.2"+version = "1.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e629a66d692cb9ff1a1c664e41771b3dcaf961985a9774c0eb0bd1b51cf60a48"+checksum = "5f2d30e4173c4026932d51d31d6b0613b1fd3014bf3f9f8943d4ba139c437ba0"dependencies = ["serde_core",]@@ -1083,7 +1091,7 @@ dependencies = ["semver","serde","serde_json",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]@@ -1122,9 +1130,9 @@ dependencies = [[[package]]name = "cc"-version = "1.2.62"+version = "1.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98"+checksum = "5add81bb678e6cb321aff7fa0dc7689ad82b112dbc032cea19f91d6b8e3582b9"dependencies = ["find-msvc-tools","jobserver",@@ -1167,9 +1175,9 @@ checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"[[package]]name = "cfg_aliases"-version = "0.2.1"+version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"+checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527"[[package]]name = "chacha20"@@ -1184,9 +1192,9 @@ dependencies = [[[package]]name = "chacha20"-version = "0.10.0"+version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"dependencies = ["cfg-if","cpufeatures 0.3.0",@@ -1195,9 +1203,9 @@ dependencies = [[[package]]name = "chrono"-version = "0.4.44"+version = "0.4.45"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c673075a2e0e5f4a1dde27ce9dee1ea4558c7ffe648f576438a20ca1d2acc4b0"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"dependencies = ["iana-time-zone","js-sys",@@ -1223,7 +1231,7 @@ version = "0.5.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"dependencies = [- "block-buffer 0.12.0",+ "block-buffer 0.12.1","crypto-common 0.2.2","inout 0.2.2",]@@ -1248,9 +1256,9 @@ dependencies = [[[package]]name = "cmov"-version = "0.5.3"+version = "0.5.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3f88a43d011fc4a6876cb7344703e297c71dda42494fee094d5f7c76bf13f746"+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"[[package]]name = "codepage"@@ -1318,6 +1326,17 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "510ca239cf13b7f8d16a2b48f263de7b4f8c566f0af58d901031473c76afb1e3"+[[package]]+name = "console"+version = "0.16.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4fe5f465a4f6fee88fad41b85d990f84c835335e85b5d9e6e63e0d06d28cba7c"+dependencies = [+ "encode_unicode",+ "libc",+ "windows-sys 0.61.2",+]+[[package]]name = "const-oid"version = "0.9.6"@@ -1420,7 +1439,7 @@ version = "0.25.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","core-foundation 0.10.1","core-graphics-types 0.2.0","foreign-types 0.5.0",@@ -1444,7 +1463,7 @@ version = "0.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","core-foundation 0.10.1","libc",]@@ -1508,18 +1527,18 @@ checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b"[[package]]name = "crossbeam-channel"-version = "0.5.15"+version = "0.5.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2"+checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e"dependencies = ["crossbeam-utils",][[package]]name = "crossbeam-deque"-version = "0.8.6"+version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51"+checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb"dependencies = ["crossbeam-epoch","crossbeam-utils",@@ -1527,27 +1546,27 @@ dependencies = [[[package]]name = "crossbeam-epoch"-version = "0.9.18"+version = "0.9.20"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e"+checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f"dependencies = ["crossbeam-utils",][[package]]name = "crossbeam-queue"-version = "0.3.12"+version = "0.3.13"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115"+checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26"dependencies = ["crossbeam-utils",][[package]]name = "crossbeam-utils"-version = "0.8.21"+version = "0.8.22"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"+checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17"[[package]]name = "crossterm"@@ -1555,7 +1574,7 @@ version = "0.28.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "829d955a0bb380ef178a640b91779e3987da38c9aea133b20614cfed8cdea9c6"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","crossterm_winapi","parking_lot","rustix 0.38.44",@@ -1585,7 +1604,7 @@ checksum = "96dacf199529fb801ae62a9aafdc01b189e9504c0d1ee1512a4c16bcd8666a93"dependencies = ["cpubits","ctutils",- "getrandom 0.4.2",+ "getrandom 0.4.3","hybrid-array","num-traits","rand_core 0.10.1",@@ -1611,7 +1630,7 @@ version = "0.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"dependencies = [- "getrandom 0.4.2",+ "getrandom 0.4.3","hybrid-array","rand_core 0.10.1",]@@ -1647,7 +1666,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331"dependencies = ["quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -1752,7 +1771,7 @@ checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -1775,7 +1794,7 @@ dependencies = ["proc-macro2","quote","strsim",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -1786,7 +1805,7 @@ checksum = "ac3984ec7bd6cfa798e62b4a642426a5be0e68f9401cfc2a01e3fa9ea2fcdb8d"dependencies = ["darling_core","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -1797,9 +1816,9 @@ checksum = "a4ae5f15dda3c708c0ade84bfee31ccab44a3da4f88015ed22f63732abe300c8"[[package]]name = "dbus"-version = "0.9.11"+version = "0.9.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b942602992bb7acfd1f51c49811c58a610ef9181b6e66f3e519d79b540a3bf73"+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"dependencies = ["libc","libdbus-sys",@@ -1834,7 +1853,7 @@ dependencies = ["reqwest 0.12.28","russh","rust_decimal",- "rustls 0.23.40",+ "rustls 0.23.42","semver","serde","serde_json",@@ -1880,6 +1899,7 @@ dependencies = ["aes 0.8.4","aes-gcm 0.10.3","anyhow",+ "arc-swap","argon2","async-trait","base64 0.22.1",@@ -1895,11 +1915,14 @@ dependencies = ["font-kit","futures","iana-time-zone",+ "insta","json5","jsonwebtoken","log",+ "minijinja","mongodb","mysql_async",+ "notify","pageant","percent-encoding","portpicker",@@ -1912,10 +1935,11 @@ dependencies = ["rusqlite","russh","rust_decimal",- "rustls 0.23.40",+ "rustls 0.23.42","rustls-pemfile 2.2.0","serde","serde_json",+ "serde_yaml","serde_yaml_ng","sha2 0.10.9","sqlparser",@@ -1934,7 +1958,7 @@ dependencies = ["utoipa","uuid","webpki-roots 0.26.11",- "winnow 1.0.3",+ "winnow 1.0.4","zip 4.6.1",]@@ -1971,7 +1995,7 @@ dependencies = ["pbkdf2 0.12.2","redis","reqwest 0.12.28",- "rustls 0.23.40",+ "rustls 0.23.42","serde","serde_json","sha2 0.10.9",@@ -2039,7 +2063,7 @@ checksum = "780eb241654bf097afb00fc5f054a09b687dad862e485fdcf8399bb056565370"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2056,9 +2080,9 @@ dependencies = [[[package]]name = "der"-version = "0.8.0"+version = "0.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "71fd89660b2dc699704064e59e9dba0147b903e85319429e131620d022be411b"+checksum = "a69dedd701da44b0536442edf09c81a64b0ab97a7a4a5e3d1971f00027cbc63d"dependencies = ["const-oid 0.10.2","pem-rfc7468 1.0.0",@@ -2073,7 +2097,7 @@ checksum = "8034092389675178f570469e6c3b0465d3d30b4505c294a6550db47f3c17ad18"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2082,7 +2106,6 @@ version = "0.5.8"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"dependencies = [- "powerfmt","serde_core",]@@ -2094,7 +2117,7 @@ checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2105,7 +2128,7 @@ checksum = "d08b3a0bcc0d079199cd476b2cae8435016ec11d1c0986c6901c5ac223041534"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2116,7 +2139,7 @@ checksum = "1e567bd82dcff979e4b03460c307b3cdc9e96fde3d73bed1496d2bc75d9dd62a"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2138,7 +2161,7 @@ dependencies = ["proc-macro2","quote","rustc_version",- "syn 2.0.117",+ "syn 2.0.119","unicode-xid",]@@ -2160,7 +2183,7 @@ version = "0.11.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"dependencies = [- "block-buffer 0.12.0",+ "block-buffer 0.12.1","const-oid 0.10.2","crypto-common 0.2.2","ctutils",@@ -2193,7 +2216,7 @@ version = "0.3.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","block2","libc","objc2",@@ -2201,13 +2224,13 @@ dependencies = [[[package]]name = "displaydoc"-version = "0.2.5"+version = "0.2.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0"+checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2239,7 +2262,7 @@ checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2313,9 +2336,9 @@ checksum = "f678cf4a922c215c63e0de95eb1ff08a958a81d47e485cf9da1e27bf6305cfa5"[[package]]name = "duckdb"-version = "1.10503.1"+version = "1.10505.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0cb42b21e3be42ef14acda15ce8dc99c125ce5376b87c8016a432cf14ae65de1"+checksum = "970e05eedd3f55c435194d9104f90a9b4a79a80d6e73251bc9ff43e178130c4e"dependencies = ["arrow","cast",@@ -2325,7 +2348,6 @@ dependencies = ["hashlink 0.10.0","libduckdb-sys","num-integer",- "rust_decimal","strum",]@@ -2359,7 +2381,7 @@ version = "0.17.0-rc.16"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "91bbdd377139884fafcad8dc43a760a3e1e681aa26db910257fa6535b70e1829"dependencies = [- "der 0.8.0",+ "der 0.8.1","digest 0.11.3","elliptic-curve","rfc6979",@@ -2396,9 +2418,9 @@ dependencies = [[[package]]name = "either"-version = "1.16.0"+version = "1.17.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"+checksum = "9e5e8f6c15a24b9a3ee5efec809ccd006d3b30e8b3bb63c39af737c7f87daa1d"[[package]]name = "elliptic-curve"@@ -2425,14 +2447,14 @@ dependencies = [[[package]]name = "embed-resource"-version = "3.0.9"+version = "3.0.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c31a88c8d26de40ed18fe748c547845aa39de1db3afd958f8cb91579f3644bcb"+checksum = "fbfdaacccebec3b28e4866b8973543c7647797db5ada1bdab552e48fe665fbbd"dependencies = ["cc","memchr","rustc_version",- "toml 1.1.2+spec-1.1.0",+ "toml 1.1.3+spec-1.1.0","vswhom","winreg",]@@ -2443,6 +2465,12 @@ version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"+[[package]]+name = "encode_unicode"+version = "1.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0"+[[package]]name = "encoding_rs"version = "0.8.35"@@ -2467,7 +2495,7 @@ dependencies = ["once_cell","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2488,7 +2516,7 @@ checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -2581,9 +2609,9 @@ checksum = "f8eb564c5c7423d25c886fb561d1e4ee69f72354d16918afa32c08811f6b6a55"[[package]]name = "fastrand"-version = "2.4.1"+version = "2.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"[[package]]name = "fax"@@ -2700,7 +2728,7 @@ version = "0.14.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2c7e611d49285d4c4b2e1727b72cf05353558885cc5252f93707b845dfcaf3d3"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","byteorder","core-foundation 0.9.4","core-graphics 0.23.2",@@ -2740,13 +2768,13 @@ dependencies = [[[package]]name = "foreign-types-macros"-version = "0.2.3"+version = "0.2.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a5c6c585bc94aaf2c7b51dd4c2ba22680844aba4c687be581871a6f518c5742"+checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]@@ -2795,9 +2823,9 @@ checksum = "e6d5a32815ae3f33302d95fdcb2ce17862f8c65363dcfd29360480ba1001fc9c"[[package]]name = "futures"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8b147ee9d1f6d097cef9ce628cd2ee62288d963e16fb287bd9286455b241382d"+checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218"dependencies = ["futures-channel","futures-core",@@ -2810,9 +2838,9 @@ dependencies = [[[package]]name = "futures-channel"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"+checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"dependencies = ["futures-core","futures-sink",@@ -2820,15 +2848,15 @@ dependencies = [[[package]]name = "futures-core"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"+checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"[[package]]name = "futures-executor"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "baf29c38818342a3b26b5b923639e7b1f4a61fc5e76102d4b1981c6dc7a7579d"+checksum = "6754879cc9f2c66f88c6e5c35344bb0bdb0708b0352b1201815667c7eabc7458"dependencies = ["futures-core","futures-task",@@ -2837,9 +2865,9 @@ dependencies = [[[package]]name = "futures-io"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"+checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"[[package]]name = "futures-lite"@@ -2856,32 +2884,32 @@ dependencies = [[[package]]name = "futures-macro"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b"+checksum = "2d6d3cde68c518367be28956066ddfef33813991b77a55005a69dae04bf3b10b"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "futures-sink"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"+checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307"[[package]]name = "futures-task"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"+checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"[[package]]name = "futures-util"-version = "0.3.32"+version = "0.3.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"+checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"dependencies = ["futures-channel","futures-core",@@ -3005,9 +3033,9 @@ dependencies = [[[package]]name = "generic-array"-version = "1.4.1"+version = "1.4.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dab9e9188e97a93276e1fe7b56401b851e2b45a46d045ca658100c1303ada649"+checksum = "ab4e5aa225bc56696909483320f0ff9b600f1a971b52e07a17d70f3d9b43254b"dependencies = ["generic-array 0.14.7","rustversion",@@ -3053,16 +3081,16 @@ dependencies = [[[package]]name = "getrandom"-version = "0.4.2"+version = "0.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"dependencies = ["cfg-if",+ "js-sys","libc","r-efi 6.0.0","rand_core 0.10.1",- "wasip2",- "wasip3",+ "wasm-bindgen",][[package]]@@ -3081,7 +3109,7 @@ version = "0.6.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2eecf2d5dc9b66b732b97707a0210906b1d30523eb773193ab777c0c84b3e8d5"dependencies = [- "polyval 0.7.1",+ "polyval 0.7.3",][[package]]@@ -3122,7 +3150,7 @@ version = "0.18.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","futures-channel","futures-core","futures-executor",@@ -3150,7 +3178,7 @@ dependencies = ["proc-macro-error","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -3165,9 +3193,22 @@ dependencies = [[[package]]name = "glob"-version = "0.3.3"+version = "0.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"++[[package]]+name = "globset"+version = "0.4.19"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e47d37d2ae4464254884b60ab7071be2b876a9c35b696bd018ddcc76847309cd"+dependencies = [+ "aho-corasick",+ "bstr",+ "log",+ "regex-automata",+ "regex-syntax",+][[package]]name = "gobject-sys"@@ -3229,14 +3270,14 @@ dependencies = ["proc-macro-error","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "h2"-version = "0.4.14"+version = "0.4.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "171fefbc92fe4a4de27e0698d6a5b392d6a0e333506bc49133760b3bcf948733"+checksum = "6cb093c84e8bd9b188d4c4a8cb6579fc016968d14c99882163cd3ff402a4f155"dependencies = ["atomic-waker","bytes",@@ -3376,8 +3417,8 @@ dependencies = ["idna","ipnet","jni 0.22.4",- "rand 0.10.1",- "thiserror 2.0.18",+ "rand 0.10.2",+ "thiserror 2.0.19","tinyvec","tokio","tracing",@@ -3396,9 +3437,9 @@ dependencies = ["jni 0.22.4","once_cell","prefix-trie",- "rand 0.10.1",+ "rand 0.10.2","ring",- "thiserror 2.0.18",+ "thiserror 2.0.19","tinyvec","tracing","url",@@ -3421,11 +3462,11 @@ dependencies = ["ndk-context","once_cell","parking_lot",- "rand 0.10.1",+ "rand 0.10.2","resolv-conf","smallvec","system-configuration",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","tracing",]@@ -3469,9 +3510,9 @@ dependencies = [[[package]]name = "http"-version = "1.4.0"+version = "1.4.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e3ba2a386d7f85a81f119ad7498ebe444d2e22c2af0b86b069416ace48b3311a"+checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"dependencies = ["bytes","itoa",@@ -3479,9 +3520,9 @@ dependencies = [[[package]]name = "http-body"-version = "1.0.1"+version = "1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"+checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c"dependencies = ["bytes","http",@@ -3489,9 +3530,9 @@ dependencies = [[[package]]name = "http-body-util"-version = "0.1.3"+version = "0.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"+checksum = "e9f41fd6a08e4d4ec69df65976da761afd5ad5e58a9d4acb46bd1c953a9e3ff2"dependencies = ["bytes","futures-core",@@ -3520,9 +3561,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"[[package]]name = "hybrid-array"-version = "0.4.12"+version = "0.4.13"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"+checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"dependencies = ["ctutils","subtle",@@ -3532,9 +3573,9 @@ dependencies = [[[package]]name = "hyper"-version = "1.9.0"+version = "1.11.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6299f016b246a94207e63da54dbe807655bf9e00044f73ded42c3ac5305fbcca"+checksum = "d22053281f852e11534f5198498373cbb59295120a20771d90f7ed1897490a72"dependencies = ["atomic-waker","bytes",@@ -3561,11 +3602,11 @@ dependencies = ["http","hyper","hyper-util",- "rustls 0.23.40",+ "rustls 0.23.42","tokio","tokio-rustls 0.26.4","tower-service",- "webpki-roots 1.0.7",+ "webpki-roots 1.0.9",][[package]]@@ -3725,12 +3766,6 @@ dependencies = ["zerovec",]-[[package]]-name = "id-arena"-version = "2.3.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"-[[package]]name = "ident_case"version = "1.0.1"@@ -3804,6 +3839,26 @@ dependencies = ["cfb",]+[[package]]+name = "inotify"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fdd168d97690d0b8c412d6b6c10360277f4d7ee495c5d0d5d5fe0854923255cc"+dependencies = [+ "bitflags 1.3.2",+ "inotify-sys",+ "libc",+]++[[package]]+name = "inotify-sys"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c033f80b2c113cdf91ab7a33faa9cbc014726dcad99880c8609af2a370edf37d"+dependencies = [+ "libc",+]+[[package]]name = "inout"version = "0.1.4"@@ -3824,6 +3879,30 @@ dependencies = ["hybrid-array",]+[[package]]+name = "insta"+version = "1.48.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "86f0f8fee8c926415c58d6ae43a08523a26faccb2323f5e6b644fe7dd4ef6b82"+dependencies = [+ "console",+ "globset",+ "once_cell",+ "serde",+ "similar",+ "tempfile",+ "walkdir",+]++[[package]]+name = "instant"+version = "0.1.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e0242819d153cba4b4b05a5a8f2a7e9bbf97b6055b2a002b395c96b5ff3c0222"+dependencies = [+ "cfg-if",+]+[[package]]name = "internal-russh-forked-ssh-key"version = "0.6.18+upstream-0.6.7"@@ -3861,7 +3940,7 @@ checksum = "ae8e22120c32fb4d19ec55fba35015f57095cd95a2e3b732e44457f5915b2ee8"dependencies = ["num-integer","num-traits",- "rand 0.10.1",+ "rand 0.10.2","rand_core 0.10.1",]@@ -3972,7 +4051,7 @@ dependencies = ["jni-sys 0.4.1","log","simd_cesu8",- "thiserror 2.0.18",+ "thiserror 2.0.19","walkdir","windows-link 0.2.1",]@@ -3987,7 +4066,7 @@ dependencies = ["quote","rustc_version","simd_cesu8",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4015,28 +4094,27 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264"dependencies = ["quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "jobserver"-version = "0.1.34"+version = "0.1.35"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9afb3de4395d6b3e67a780b6de64b51c978ecf11cb9a462c66be7d4ca9039d33"+checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3"dependencies = [- "getrandom 0.3.4",+ "getrandom 0.4.3","libc",][[package]]name = "js-sys"-version = "0.3.99"+version = "0.3.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "142bc4740e452c1e57ade0cbc129f139c9093e354346f0872ef985f4f5cf5f11"+checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"dependencies = ["cfg-if","futures-util",- "once_cell","wasm-bindgen",]@@ -4114,7 +4192,7 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","serde","unicode-segmentation",]@@ -4128,6 +4206,26 @@ dependencies = ["indexmap 2.14.0",]+[[package]]+name = "kqueue"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "273c0752728918e0ac4976f2b275b6fefb9ecd400585dec929419f3844cd87b5"+dependencies = [+ "kqueue-sys",+ "libc",+]++[[package]]+name = "kqueue-sys"+version = "1.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "07293a4e297ac234359b510362495713f75ea345d5307140414f20c69ffeb087"+dependencies = [+ "bitflags 2.13.1",+ "libc",+]+[[package]]name = "lazy_static"version = "1.5.0"@@ -4137,12 +4235,6 @@ dependencies = ["spin",]-[[package]]-name = "leb128fmt"-version = "0.1.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"-[[package]]name = "lexical-core"version = "1.0.6"@@ -4232,9 +4324,9 @@ checksum = "34b357333733e8260735ba5894eb928c02ecc69c78715f01a8019e7fa7f2db4c"[[package]]name = "libc"-version = "0.2.186"+version = "0.2.189"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"[[package]]name = "libdbus-sys"@@ -4247,17 +4339,17 @@ dependencies = [[[package]]name = "libduckdb-sys"-version = "1.10503.1"+version = "1.10505.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c9a4389c243e7afa0fbc8d8471031335ddc8a2dac4534f3290c9c2ba3edabab5"+checksum = "6cb514dab5e271e849235c1cb98bd65a2ae107fbd619a6740219319c54a71d95"dependencies = ["cc","flate2","pkg-config",- "reqwest 0.12.28","serde","serde_json","tar",+ "ureq","vcpkg","zip 6.0.0",]@@ -4284,18 +4376,18 @@ dependencies = [[[package]]name = "liblzma"-version = "0.4.6"+version = "0.4.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b6033b77c21d1f56deeae8014eb9fbe7bdf1765185a6c508b5ca82eeaed7f899"+checksum = "45aec2360b3933207e27908049d8e4df4e476b58180afb1e56b2a4fb72efe4ba"dependencies = ["liblzma-sys",][[package]]name = "liblzma-sys"-version = "0.4.6"+version = "0.4.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1a60851d15cd8c5346eca4ab8babff585be2ae4bc8097c067291d3ffe2add3b6"+checksum = "a046c7f353ba30f810545151e04f63545833803f5b86ee3ddf1517247fe560a5"dependencies = ["cc","libc",@@ -4310,9 +4402,9 @@ checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981"[[package]]name = "libredox"-version = "0.1.16"+version = "0.1.18"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e02f3bb43d335493c96bf3fd3a321600bf6bd07ed34bc64118e9293bdffea46c"+checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"dependencies = ["libc",]@@ -4358,12 +4450,9 @@ dependencies = [[[package]]name = "log"-version = "0.4.30"+version = "0.4.33"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "616ec5685824bcc94416c6d4a7a446eea774a31efd7062c8480ba6fd06d7a6e5"-dependencies = [- "value-bag",-]+checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"[[package]]name = "lru"@@ -4398,7 +4487,7 @@ dependencies = ["macro_magic_core","macro_magic_macros","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4412,7 +4501,7 @@ dependencies = ["macro_magic_core_macros","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4423,7 +4512,7 @@ checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4434,7 +4523,7 @@ checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869"dependencies = ["macro_magic_core","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4446,7 +4535,7 @@ dependencies = ["manyhow-macros","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4486,16 +4575,6 @@ version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"-[[package]]-name = "md-5"-version = "0.10.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"-dependencies = [- "cfg-if",- "digest 0.10.7",-]-[[package]]name = "md-5"version = "0.11.0"@@ -4514,9 +4593,15 @@ checksum = "490cc448043f947bae3cbee9c203358d62dbee0db12107a74be5c30ccfd09771"[[package]]name = "memchr"-version = "2.8.0"+version = "2.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[package]]+name = "memo-map"+version = "0.3.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "38d1115007560874e373613744c6fba374c17688327a71c1476d1a5954cc857b"[[package]]name = "memoffset"@@ -4543,6 +4628,16 @@ dependencies = ["unicase",]+[[package]]+name = "minijinja"+version = "2.21.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb3d648e68cea56d9858d535ee28f9538404e2dd8cb08ed0bd05dca379477f39"+dependencies = [+ "memo-map",+ "serde",+]+[[package]]name = "minisign-verify"version = "0.2.5"@@ -4561,11 +4656,12 @@ dependencies = [[[package]]name = "mio"-version = "1.2.0"+version = "1.2.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "50b7e5b27aa02a74bac8c3f23f448f8d87ff11f92d3aac1a6ed369ee08cc56c1"+checksum = "30d65c71f1ce40ab09135ce117d742b9f8a19ff91a41a8b57ed50bc2de59c427"dependencies = ["libc",+ "log","wasi 0.11.1+wasi-snapshot-preview1","windows-sys 0.61.2",]@@ -4613,9 +4709,9 @@ dependencies = [[[package]]name = "mongocrypt"-version = "0.3.2"+version = "0.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8da0cd419a51a5fb44819e290fbdb0665a54f21dead8923446a799c7f4d26ad9"+checksum = "8426a875ded61430d4a811dbfda7633b6b8af0225c547fc6c28b8b0aa7d79a13"dependencies = ["bson","mongocrypt-sys",@@ -4625,18 +4721,18 @@ dependencies = [[[package]]name = "mongocrypt-sys"-version = "0.1.5+1.15.1"+version = "0.1.6+1.18.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "224484c5d09285a7b8cb0a0c117e847ebd14cb6e4470ecf68cdb89c503b0edb9"+checksum = "851fac73f7fe22f6a3ab87f720ce509cae7c9fd08e7dd27866cc232dee07ccf4"[[package]]name = "mongodb"-version = "3.7.0"+version = "3.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "276ba0cd571553d1f6936c6f180964776ece6ab7507dc8765f8a9c9c49d8cd00"+checksum = "b814038f367d212f55de0a630cb35102a9b8ca23785a86955d62c0087c93846d"dependencies = ["base64 0.22.1",- "bitflags 2.11.1",+ "bitflags 2.13.1","bson","derive-where","derive_more",@@ -4647,44 +4743,44 @@ dependencies = ["hickory-net","hickory-proto","hickory-resolver",- "hmac 0.12.1",+ "hmac 0.13.0","macro_magic",- "md-5 0.10.6",+ "md-5","mongocrypt","mongodb-internal-macros",- "pbkdf2 0.12.2",+ "pbkdf2 0.13.0","percent-encoding",- "rand 0.9.4",+ "rand 0.9.5","rustc_version_runtime",- "rustls 0.23.40",+ "rustls 0.23.42","serde","serde_bytes","serde_with",- "sha1 0.10.6",- "sha2 0.10.9",+ "sha1 0.11.0",+ "sha2 0.11.0","socket2","stringprep","strsim","take_mut",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","tokio-rustls 0.26.4","tokio-util","typed-builder","uuid",- "webpki-roots 1.0.7",+ "webpki-roots 1.0.9",][[package]]name = "mongodb-internal-macros"-version = "3.7.0"+version = "3.8.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "99ceb1a9a1018e470077ec94cf3a8c2d0e6da542b2c05ea95a59a0a627147375"+checksum = "f736d2fbc56e0011a341fbb9172bd822fda75c5f93b82fae1c7aab1e2613c810"dependencies = ["macro_magic","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -4699,9 +4795,9 @@ dependencies = [[[package]]name = "muda"-version = "0.19.2"+version = "0.19.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "47a2e3dff89cd322c66647942668faee0a2b1f88ea6cbb4d374b4a8d7e92528c"+checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878"dependencies = ["crossbeam-channel","dpi",@@ -4714,7 +4810,7 @@ dependencies = ["once_cell","png 0.18.1","serde",- "thiserror 2.0.18",+ "thiserror 2.0.19","windows-sys 0.61.2",]@@ -4747,9 +4843,9 @@ dependencies = ["proc-macro-crate 3.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","termcolor",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]@@ -4768,17 +4864,17 @@ dependencies = ["lru 0.18.1","mysql_common","percent-encoding",- "rand 0.10.1",- "rustls 0.23.40",+ "rand 0.10.2",+ "rustls 0.23.42","serde","socket2",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","tokio-rustls 0.26.4","tokio-util","twox-hash","url",- "webpki-roots 1.0.7",+ "webpki-roots 1.0.9",][[package]]@@ -4787,7 +4883,7 @@ version = "0.38.0"source = "git+https://github.com/t8y2/rust_mysql_common.git?rev=77085e91e5081309d585153e3b656ce33bc1fe74#77085e91e5081309d585153e3b656ce33bc1fe74"dependencies = ["base64 0.22.1",- "bitflags 2.11.1",+ "bitflags 2.13.1","btoi","byteorder","bytes",@@ -4805,9 +4901,9 @@ dependencies = ["saturating","serde","serde_json",- "sha1 0.10.6",+ "sha1 0.10.7","sha2 0.10.9",- "thiserror 2.0.18",+ "thiserror 2.0.19","uuid",]@@ -4834,7 +4930,7 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","jni-sys 0.3.1","log","ndk-sys",@@ -4870,7 +4966,7 @@ version = "0.31.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","cfg-if","cfg_aliases","libc",@@ -4885,6 +4981,33 @@ dependencies = ["memchr",]+[[package]]+name = "notify"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c533b4c39709f9ba5005d8002048266593c1cfaf3c5f0739d5b8ab0c6c504009"+dependencies = [+ "bitflags 2.13.1",+ "filetime",+ "inotify",+ "kqueue",+ "libc",+ "log",+ "mio",+ "notify-types",+ "walkdir",+ "windows-sys 0.52.0",+]++[[package]]+name = "notify-types"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "585d3cb5e12e01aed9e8a1f70d5c6b5e86fe2a6e48fc8cd0b3e0b8df6f6eb174"+dependencies = [+ "instant",+]+[[package]]name = "ntapi"version = "0.4.3"@@ -4905,9 +5028,9 @@ dependencies = [[[package]]name = "num-bigint"-version = "0.4.6"+version = "0.4.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9"+checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367"dependencies = ["num-integer","num-traits",@@ -4924,7 +5047,7 @@ dependencies = ["num-integer","num-iter","num-traits",- "rand 0.8.6",+ "rand 0.8.7","serde","smallvec",]@@ -4955,11 +5078,10 @@ dependencies = [[[package]]name = "num-iter"-version = "0.1.45"+version = "0.1.46"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf"+checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b"dependencies = [- "autocfg","num-integer","num-traits",]@@ -5003,7 +5125,7 @@ dependencies = ["proc-macro-crate 3.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -5031,7 +5153,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","block2","objc2","objc2-core-foundation",@@ -5045,7 +5167,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","objc2","objc2-foundation",]@@ -5066,7 +5188,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","dispatch2","objc2",]@@ -5077,7 +5199,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","dispatch2","objc2","objc2-core-foundation",@@ -5110,7 +5232,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","objc2","objc2-core-foundation","objc2-core-graphics",@@ -5137,7 +5259,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","block2","libc","objc2",@@ -5150,7 +5272,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","objc2","objc2-core-foundation",]@@ -5161,7 +5283,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "f112d1746737b0da274ef79a23aac283376f335f4095a083a267a082f21db0c0"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","objc2","objc2-app-kit","objc2-foundation",@@ -5173,7 +5295,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","objc2","objc2-core-foundation","objc2-foundation",@@ -5194,7 +5316,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","block2","objc2","objc2-cloud-kit",@@ -5225,7 +5347,7 @@ version = "0.3.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","block2","objc2","objc2-app-kit",@@ -5260,23 +5382,22 @@ checksum = "c08d65885ee38876c4f86fa503fb49d7b507c2b62552df7c70b2fce627e06381"[[package]]name = "open"-version = "5.3.5"+version = "5.4.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2fbaa89d2ddc8473c78a3adf69eea8cffa28c483b8e02a971ef31527cd0fc92c"+checksum = "a0b3d059e795d52b8a72fef45658620edd4d9c359b338564aa14391ffa511ed5"dependencies = ["dunce","is-wsl","libc",- "pathdiff",][[package]]name = "openssl"-version = "0.10.80"+version = "0.10.81"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "a45fa2aa886c42762255da344f0a0d313e254066c46aad76f300c3d3da62d967"+checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","cfg-if","foreign-types 0.3.2","libc",@@ -5292,7 +5413,7 @@ checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -5318,9 +5439,9 @@ dependencies = [[[package]]name = "openssl-sys"-version = "0.9.116"+version = "0.9.117"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f28a22dc7140cda5f096e5e7724a6962ca81a7f8bfd2979f9b18c11af56318c4"+checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695"dependencies = ["cc","libc",@@ -5376,7 +5497,7 @@ dependencies = ["objc2-osa-kit","serde","serde_json",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]@@ -5432,9 +5553,9 @@ dependencies = ["delegate","futures","log",- "rand 0.10.1",+ "rand 0.10.2","sha2 0.11.0",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","windows 0.62.2","windows-strings 0.5.1",@@ -5511,12 +5632,6 @@ version = "0.2.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4"-[[package]]-name = "pathdiff"-version = "0.2.3"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "df94ce210e5bc13cb6651479fa48d14f601d9858cfe0467f43ae157023b938d3"-[[package]]name = "pathfinder_geometry"version = "0.5.1"@@ -5592,9 +5707,9 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"[[package]]name = "pest"-version = "2.8.7"+version = "2.8.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "47627dd7305c6a2d6c8c6bcd24c5a4c17dbbf425f4f9c5313e724b38fc9782e9"+checksum = "7df728be843c7070fab6ab7c328c4e9e9d78e23bf749c0669c86ee7ebfa050a2"dependencies = ["memchr","ucd-trie",@@ -5602,9 +5717,9 @@ dependencies = [[[package]]name = "pest_derive"-version = "2.8.7"+version = "2.8.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4b4254325ecad416ab689e27ba51da03ba01a9632bc6e108f5fe7c3c4ad29d58"+checksum = "9e2dd6fc3b26b3462ee188aac870f5a41d398f1cd5e2408d16531bd71c9591fd"dependencies = ["pest","pest_generator",@@ -5612,22 +5727,22 @@ dependencies = [[[package]]name = "pest_generator"-version = "2.8.7"+version = "2.8.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6c4c0e91ead7a8f7acecbca6f003fc2e8282b1dbe2dd9c9d2f16aba42995e0a7"+checksum = "6a7a9205cfb6f596a9e8b689c0a15f9ceb7a1aafae7aaf788150ac65b29975b6"dependencies = ["pest","pest_meta","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "pest_meta"-version = "2.8.7"+version = "2.8.8"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f9744bc48116fee06334924bb5f2bad41eed5e89bd26e29b0b799f9a3f82c210"+checksum = "85abd351c0de1e8384fc791a0737111a350394937e92b956b743dac12429f57c"dependencies = ["pest",]@@ -5684,7 +5799,7 @@ dependencies = ["phf_shared","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -5719,7 +5834,7 @@ version = "0.8.0-rc.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "986d2e952779af96ea048f160fd9194e1751b4faea78bcf3ceb456efe008088e"dependencies = [- "der 0.8.0",+ "der 0.8.1","spki 0.8.0-rc.4",]@@ -5729,10 +5844,10 @@ version = "0.8.0-rc.13"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c5a777c6e26664bc9504b3ce3f6133f8f20d9071f130a4f9fcbd3186959d8dd6"dependencies = [- "aes 0.9.0",+ "aes 0.9.1","aes-gcm 0.11.0-rc.3","cbc 0.2.1",- "der 0.8.0",+ "der 0.8.1","pbkdf2 0.13.0","rand_core 0.10.1","scrypt",@@ -5746,7 +5861,7 @@ version = "0.11.0-rc.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "12922b6296c06eb741b02d7b5161e3aaa22864af38dfa025a1a3ba3f68c84577"dependencies = [- "der 0.8.0",+ "der 0.8.1","pkcs5","rand_core 0.10.1","spki 0.8.0-rc.4",@@ -5760,13 +5875,13 @@ checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e"[[package]]name = "plist"-version = "1.9.0"+version = "1.10.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "092791278e026273c1b65bbdcfbba3a300f2994c896bd01ab01da613c29c46f1"+checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85"dependencies = ["base64 0.22.1","indexmap 2.14.0",- "quick-xml 0.39.4",+ "quick-xml 0.41.0","serde","time",]@@ -5790,7 +5905,7 @@ version = "0.18.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","crc32fast","fdeflate","flate2",@@ -5836,9 +5951,9 @@ dependencies = [[[package]]name = "polyval"-version = "0.7.1"+version = "0.7.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7dfc63250416fea14f5749b90725916a6c903f599d51cb635aa7a52bfd03eede"+checksum = "f0fa31d631f2b2cb2a544d0aa321ce847a94764d701ca2becc411138b93d49cd"dependencies = ["cpubits","cpufeatures 0.3.0",@@ -5847,9 +5962,9 @@ dependencies = [[[package]]name = "portable-atomic"-version = "1.13.1"+version = "1.14.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49"+checksum = "3d20d5497ef88037a52ff98267d066e7f11fcc5e99bbfbd58a42336193aacec3"[[package]]name = "portpicker"@@ -5857,32 +5972,30 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "be97d76faf1bfab666e1375477b23fde79eccf0276e9b63b92a39d676a889ba9"dependencies = [- "rand 0.8.6",+ "rand 0.8.7",][[package]]name = "postgres-protocol"-version = "0.6.11"-source = "git+https://github.com/t8y2/tokio-postgres-gaussdb.git?branch=master#8d50befeee7cdeb8ecdb97c7b790c91010971063"+version = "0.6.12"+source = "git+https://github.com/t8y2/tokio-postgres-gaussdb.git?branch=master#6bf367c3ac9552f5fcba95659b6ffc1a8a35f494"dependencies = ["base64 0.22.1","byteorder","bytes","fallible-iterator 0.2.0","hmac 0.13.0",- "md-5 0.11.0",+ "md-5","memchr",- "pbkdf2 0.12.2",- "rand 0.10.1",- "sha1 0.10.6",+ "rand 0.10.2","sha2 0.11.0","stringprep",][[package]]name = "postgres-types"-version = "0.2.13"-source = "git+https://github.com/t8y2/tokio-postgres-gaussdb.git?branch=master#8d50befeee7cdeb8ecdb97c7b790c91010971063"+version = "0.2.14"+source = "git+https://github.com/t8y2/tokio-postgres-gaussdb.git?branch=master#6bf367c3ac9552f5fcba95659b6ffc1a8a35f494"dependencies = ["bytes","chrono",@@ -5946,16 +6059,6 @@ version = "0.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c6fa0831dd7cc608c38a5e323422a0077678fa5744aa2be4ad91c4ece8eec8d5"-[[package]]-name = "prettyplease"-version = "0.2.37"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"-dependencies = [- "proc-macro2",- "syn 2.0.117",-]-[[package]]name = "primefield"version = "0.14.0-rc.7"@@ -6005,7 +6108,7 @@ version = "3.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f"dependencies = [- "toml_edit 0.25.11+spec-1.1.0",+ "toml_edit 0.25.13+spec-1.1.0",][[package]]@@ -6045,9 +6148,9 @@ dependencies = [[[package]]name = "proc-macro2"-version = "1.0.106"+version = "1.0.107"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"dependencies = ["unicode-ident",]@@ -6096,9 +6199,9 @@ dependencies = [[[package]]name = "pxfm"-version = "0.1.29"+version = "0.1.30"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f"+checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea"[[package]]name = "quick-error"@@ -6118,18 +6221,18 @@ dependencies = [[[package]]name = "quick-xml"-version = "0.39.4"+version = "0.41.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e"+checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1"dependencies = ["memchr",][[package]]name = "quinn"-version = "0.11.9"+version = "0.11.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20"+checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"dependencies = ["bytes","cfg_aliases",@@ -6137,9 +6240,9 @@ dependencies = ["quinn-proto","quinn-udp","rustc-hash",- "rustls 0.23.40",+ "rustls 0.23.42","socket2",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","tracing","web-time",@@ -6147,20 +6250,21 @@ dependencies = [[[package]]name = "quinn-proto"-version = "0.11.14"+version = "0.11.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098"+checksum = "2f4bfc015262b9df63c8845072ce59068853ff5872180c2ce2f13038b970e560"dependencies = ["bytes",- "getrandom 0.3.4",+ "getrandom 0.4.3","lru-slab",- "rand 0.9.4",+ "rand 0.10.2",+ "rand_pcg","ring","rustc-hash",- "rustls 0.23.40",+ "rustls 0.23.42","rustls-pki-types","slab",- "thiserror 2.0.18",+ "thiserror 2.0.19","tinyvec","tracing","web-time",@@ -6168,23 +6272,23 @@ dependencies = [[[package]]name = "quinn-udp"-version = "0.5.14"+version = "0.5.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"+checksum = "35a133f956daabe89a61a685c2649f13d82d5aa4bd5d12d1277e1072a21c0694"dependencies = ["cfg_aliases","libc","once_cell","socket2","tracing",- "windows-sys 0.60.2",+ "windows-sys 0.61.2",][[package]]name = "quote"-version = "1.0.45"+version = "1.0.47"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"+checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"dependencies = ["proc-macro2",]@@ -6209,9 +6313,9 @@ checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09"[[package]]name = "rand"-version = "0.8.6"+version = "0.8.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"+checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a"dependencies = ["libc","rand_chacha 0.3.1",@@ -6220,9 +6324,9 @@ dependencies = [[[package]]name = "rand"-version = "0.9.4"+version = "0.9.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"+checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41"dependencies = ["rand_chacha 0.9.0","rand_core 0.9.5",@@ -6230,12 +6334,12 @@ dependencies = [[[package]]name = "rand"-version = "0.10.1"+version = "0.10.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"+checksum = "c7f5fa3a058cd35567ef9bfa5e75732bee0f9e4c55fa90477bef2dfcdbc4be80"dependencies = [- "chacha20 0.10.0",- "getrandom 0.4.2",+ "chacha20 0.10.1",+ "getrandom 0.4.3","rand_core 0.10.1",]@@ -6283,6 +6387,15 @@ version = "0.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"+[[package]]+name = "rand_pcg"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "caa0f4137e1c0a72f4c651489402276c8e8e1cf081f3b0ba156d2cbeef09e86a"+dependencies = [+ "rand_core 0.10.1",+]+[[package]]name = "raw-window-handle"version = "0.6.2"@@ -6326,7 +6439,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "76009fbe0614077fc1a2ce255e3a1881a2e3a3527097d5dc6d8212c585e7e38b"dependencies = ["quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -6346,9 +6459,9 @@ dependencies = ["num-bigint","percent-encoding","pin-project-lite",- "rand 0.9.4",- "rustls 0.23.40",- "rustls-native-certs 0.8.3",+ "rand 0.9.5",+ "rustls 0.23.42",+ "rustls-native-certs 0.8.4","ryu","sha1_smol","socket2",@@ -6364,7 +6477,7 @@ version = "0.5.18"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1",][[package]]@@ -6375,34 +6488,34 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac"dependencies = ["getrandom 0.2.17","libredox",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]name = "ref-cast"-version = "1.0.25"+version = "1.0.26"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f354300ae66f76f1c85c5f84693f0ce81d747e2c3f21a45fef496d89c960bf7d"+checksum = "216e8f773d7923bcba9ceb86a86c93cabb3903a11872fc3f138c49630e50b96d"dependencies = ["ref-cast-impl",][[package]]name = "ref-cast-impl"-version = "1.0.25"+version = "1.0.26"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b7186006dcb21920990093f30e3dea63b7d6e977bf1256be20c3563a5db070da"+checksum = "2c9283685feec7d69af75fb0e858d5e7378f33fe4fc699383b2916ab9273e03c"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]name = "regex"-version = "1.12.3"+version = "1.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"dependencies = ["aho-corasick","memchr",@@ -6412,9 +6525,9 @@ dependencies = [[[package]]name = "regex-automata"-version = "0.4.14"+version = "0.4.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+checksum = "8fcfdb36bda0c880c5931cdc7a2bcdc8ba4556847b9d912bca70bc94708711ad"dependencies = ["aho-corasick","memchr",@@ -6423,9 +6536,9 @@ dependencies = [[[package]]name = "regex-syntax"-version = "0.8.10"+version = "0.8.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"[[package]]name = "rend"@@ -6445,7 +6558,6 @@ dependencies = ["base64 0.22.1","bytes","encoding_rs",- "futures-channel","futures-core","futures-util","h2",@@ -6463,7 +6575,7 @@ dependencies = ["percent-encoding","pin-project-lite","quinn",- "rustls 0.23.40",+ "rustls 0.23.42","rustls-pki-types","serde","serde_json",@@ -6481,14 +6593,14 @@ dependencies = ["wasm-bindgen-futures","wasm-streams 0.4.2","web-sys",- "webpki-roots 1.0.7",+ "webpki-roots 1.0.9",][[package]]name = "reqwest"-version = "0.13.3"+version = "0.13.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "62e0021ea2c22aed41653bc7e1419abb2c97e038ff2c33d0e1309e49a97deec0"+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"dependencies = ["base64 0.22.1","bytes",@@ -6504,7 +6616,7 @@ dependencies = ["log","percent-encoding","pin-project-lite",- "rustls 0.23.40",+ "rustls 0.23.42","rustls-pki-types","rustls-platform-verifier","serde",@@ -6622,7 +6734,7 @@ dependencies = ["schemars 1.2.1","serde","serde_json",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","tokio-stream","tokio-util",@@ -6639,7 +6751,7 @@ dependencies = ["proc-macro2","quote","serde_json",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -6667,7 +6779,7 @@ version = "0.32.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7753b721174eb8ff87a9a0e799e2d7bc3749323e773db92e0984debb00019d6e"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","fallible-iterator 0.3.0","fallible-streaming-iterator","hashlink 0.9.1",@@ -6683,10 +6795,10 @@ checksum = "324b92f459d3e42da294e14e8eb150d2215fcfb7c966838bc1127cd68bc05a0d"dependencies = ["aead 0.6.0-rc.10","aes 0.8.4",- "aes 0.9.0",+ "aes 0.9.1","aes-gcm 0.11.0-rc.3","aws-lc-rs",- "bitflags 2.11.1",+ "bitflags 2.13.1","block-padding 0.3.3","byteorder","bytes",@@ -6699,7 +6811,7 @@ dependencies = ["curve25519-dalek 5.0.0-pre.6","data-encoding","delegate",- "der 0.8.0",+ "der 0.8.1","digest 0.10.7","ecdsa","ed25519-dalek",@@ -6707,7 +6819,7 @@ dependencies = ["enum_dispatch","flate2","futures",- "generic-array 1.4.1",+ "generic-array 1.4.4","getrandom 0.2.17","ghash 0.6.0","hex-literal",@@ -6732,8 +6844,8 @@ dependencies = ["pkcs1","pkcs5","pkcs8",- "polyval 0.7.1",- "rand 0.10.1",+ "polyval 0.7.3",+ "rand 0.10.2","rand_core 0.10.1","rsa","russh-cryptovec",@@ -6741,7 +6853,7 @@ dependencies = ["salsa20","scrypt","sec1",- "sha1 0.10.6",+ "sha1 0.10.7","sha1 0.11.0","sha2 0.10.9","sha2 0.11.0",@@ -6750,7 +6862,7 @@ dependencies = ["spki 0.8.0-rc.4","ssh-encoding","subtle",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","typenum","universal-hash 0.6.1",@@ -6793,16 +6905,16 @@ dependencies = [[[package]]name = "rust_decimal"-version = "1.42.0"+version = "1.42.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c5108e3d4d903e21aac27f12ba5377b6b34f9f44b325e4894c7924169d06995"+checksum = "be2a24f50780bc85f09cc6ac299bdf1424302742d77221106859c9d8b102126a"dependencies = ["arrayvec","borsh","bytes","num-traits","postgres-types",- "rand 0.8.6",+ "rand 0.8.7","rkyv","serde","serde_json",@@ -6811,9 +6923,9 @@ dependencies = [[[package]]name = "rustc-hash"-version = "2.1.2"+version = "2.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"+checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d"[[package]]name = "rustc_version"@@ -6861,7 +6973,7 @@ version = "0.38.44"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","errno","libc","linux-raw-sys 0.4.15",@@ -6874,7 +6986,7 @@ version = "1.1.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","errno","libc","linux-raw-sys 0.12.1",@@ -6895,9 +7007,9 @@ dependencies = [[[package]]name = "rustls"-version = "0.23.40"+version = "0.23.42"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b"+checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"dependencies = ["aws-lc-rs","log",@@ -6923,9 +7035,9 @@ dependencies = [[[package]]name = "rustls-native-certs"-version = "0.8.3"+version = "0.8.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "612460d5f7bea540c490b2b6395d8e34a953e52b491accd6c86c8164c5932a63"+checksum = "dab5152771c58876a2146916e53e35057e1a4dfa2b9df0f0305b07f611fdea4d"dependencies = ["openssl-probe 0.2.1","rustls-pki-types",@@ -6953,9 +7065,9 @@ dependencies = [[[package]]name = "rustls-pki-types"-version = "1.14.1"+version = "1.15.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9"+checksum = "2f4925028c7eb5d1fcdaf196971378ed9d2c1c4efc7dc5d011256f76c99c0a96"dependencies = ["web-time","zeroize",@@ -6972,8 +7084,8 @@ dependencies = ["jni 0.22.4","log","once_cell",- "rustls 0.23.40",- "rustls-native-certs 0.8.3",+ "rustls 0.23.42",+ "rustls-native-certs 0.8.4","rustls-platform-verifier-android","rustls-webpki 0.103.13","security-framework 3.7.0",@@ -7012,9 +7124,9 @@ dependencies = [[[package]]name = "rustversion"-version = "1.0.22"+version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"[[package]]name = "ryu"@@ -7106,7 +7218,7 @@ dependencies = ["proc-macro2","quote","serde_derive_internals",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -7118,7 +7230,7 @@ dependencies = ["proc-macro2","quote","serde_derive_internals",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -7163,7 +7275,7 @@ checksum = "d56d437c2f19203ce5f7122e507831de96f3d2d4d3be5af44a0b0a09d8a80e4d"dependencies = ["base16ct","ctutils",- "der 0.8.0",+ "der 0.8.1","hybrid-array","subtle","zeroize",@@ -7175,7 +7287,7 @@ version = "2.11.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","core-foundation 0.9.4","core-foundation-sys","libc",@@ -7188,7 +7300,7 @@ version = "3.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","core-foundation 0.10.1","core-foundation-sys","libc",@@ -7211,7 +7323,7 @@ version = "0.36.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "c5d9c0c92a92d33f08817311cf3f2c29a3538a8240e94a6a3c622ce652d7e00c"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","cssparser","derive_more","log",@@ -7236,9 +7348,9 @@ dependencies = [[[package]]name = "serde"-version = "1.0.228"+version = "1.0.229"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"+checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba"dependencies = ["serde_core","serde_derive",@@ -7268,22 +7380,22 @@ dependencies = [[[package]]name = "serde_core"-version = "1.0.228"+version = "1.0.229"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"+checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48"dependencies = ["serde_derive",][[package]]name = "serde_derive"-version = "1.0.228"+version = "1.0.229"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"+checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]@@ -7294,14 +7406,14 @@ checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "serde_json"-version = "1.0.150"+version = "1.0.151"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"+checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14"dependencies = ["indexmap 2.14.0","itoa",@@ -7324,13 +7436,13 @@ dependencies = [[[package]]name = "serde_repr"-version = "0.1.20"+version = "0.1.21"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "175ee3e80ae9982737ca543e96133087cbd9a485eecc3bc4de9c1a37b47ea59c"+checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]@@ -7365,9 +7477,9 @@ dependencies = [[[package]]name = "serde_with"-version = "3.20.0"+version = "3.21.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e72c1c2cb7b223fafb600a619537a871c2818583d619401b785e7c0b746ccde2"+checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"dependencies = ["base64 0.22.1","bs58",@@ -7385,14 +7497,27 @@ dependencies = [[[package]]name = "serde_with_macros"-version = "3.20.0"+version = "3.21.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b90c488738ecb4fb0262f41f43bc40efc5868d9fb744319ddf5f5317f417bfac"+checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"dependencies = ["darling","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",+]++[[package]]+name = "serde_yaml"+version = "0.9.34+deprecated"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47"+dependencies = [+ "indexmap 2.14.0",+ "itoa",+ "ryu",+ "serde",+ "unsafe-libyaml",][[package]]@@ -7437,7 +7562,7 @@ checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -7451,9 +7576,9 @@ dependencies = [[[package]]name = "sha1"-version = "0.10.6"+version = "0.10.7"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba"+checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8"dependencies = ["cfg-if","cpufeatures 0.2.17",@@ -7531,9 +7656,9 @@ dependencies = [[[package]]name = "shlex"-version = "1.3.0"+version = "2.0.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"[[package]]name = "sigchld"@@ -7578,15 +7703,15 @@ dependencies = [[[package]]name = "simd-adler32"-version = "0.3.9"+version = "0.3.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "703d5c7ef118737c72f1af64ad2f6f8c5e1921f818cdcb97b8fe6fc69bf66214"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"[[package]]name = "simd_cesu8"-version = "1.1.1"+version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "94f90157bb87cddf702797c5dadfa0be7d266cdf49e22da2fcaa32eff75b2c33"+checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520"dependencies = ["rustc_version","simdutf8",@@ -7598,6 +7723,12 @@ version = "0.1.5"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e"+[[package]]+name = "similar"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"+[[package]]name = "simple_asn1"version = "0.6.4"@@ -7606,7 +7737,7 @@ checksum = "0d585997b0ac10be3c5ee635f1bab02d512760d14b7c468801ac8a01d9ae5f1d"dependencies = ["num-bigint","num-traits",- "thiserror 2.0.18",+ "thiserror 2.0.19","time",]@@ -7624,15 +7755,15 @@ checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"[[package]]name = "smallvec"-version = "1.15.1"+version = "1.15.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"+checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"[[package]]name = "socket2"-version = "0.6.3"+version = "0.6.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3a766e1110788c36f4fa1c2b71b387a7815aa65f88ce0229841826633d93723e"+checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4"dependencies = ["libc","windows-sys 0.61.2",@@ -7688,9 +7819,9 @@ dependencies = [[[package]]name = "spin"-version = "0.9.8"+version = "0.9.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67"+checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e"[[package]]name = "spki"@@ -7709,7 +7840,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8baeff88f34ed0691978ec34440140e1572b68c7dd4a495fd14a3dc1944daa80"dependencies = ["base64ct",- "der 0.8.0",+ "der 0.8.1",][[package]]@@ -7731,7 +7862,7 @@ checksum = "a6dd45d8fc1c79299bfbb7190e42ccbbdf6a5f52e4a6ad98d92357ea965bd289"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -7741,7 +7872,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8cafd85a137485737308ec6b94c19639833ca96bb83cbad2bc94a0e0eb763410"dependencies = ["lru 0.16.4",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]@@ -7851,7 +7982,7 @@ dependencies = ["heck 0.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -7884,9 +8015,20 @@ dependencies = [[[package]]name = "syn"-version = "2.0.117"+version = "2.0.119"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"+dependencies = [+ "proc-macro2",+ "quote",+ "unicode-ident",+]++[[package]]+name = "syn"+version = "3.0.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"+checksum = "53e9bae58849f64dfa4f5d5ae372c8341f7305f82a3868709269343628b659a3"dependencies = ["proc-macro2","quote",@@ -7910,7 +8052,7 @@ checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -7942,7 +8084,7 @@ version = "0.7.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a13f3d0daba03132c0aa9767f98351b3488edc2c100cda2d2ec2b04f3d8d3c8b"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","core-foundation 0.9.4","system-configuration-sys",]@@ -7988,7 +8130,7 @@ version = "0.35.3"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d1c93047acf68669466a34690ac58cca7010bd1b201e1ec86f1fd0a75d3dd4a9"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","block2","core-foundation 0.10.1","core-graphics 0.25.0",@@ -8030,7 +8172,7 @@ checksum = "f4e16beb8b2ac17db28eab8bca40e62dbfbb34c0fcdc6d9826b11b7b5d047dfd"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -8058,9 +8200,9 @@ checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"[[package]]name = "tauri"-version = "2.11.2"+version = "2.11.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "437404997acf375d85f1177afa7e11bb971f274ed6a7b83a2a3e339015f4cc28"+checksum = "667b20e2726d572dea2de7370da16e188eb06008faf9a92fab7cdc46791190b5"dependencies = ["anyhow","bytes",@@ -8086,7 +8228,7 @@ dependencies = ["percent-encoding","plist","raw-window-handle",- "reqwest 0.13.3",+ "reqwest 0.13.4","serde","serde_json","serde_repr",@@ -8097,7 +8239,7 @@ dependencies = ["tauri-runtime","tauri-runtime-wry","tauri-utils",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio","tray-icon","url",@@ -8109,9 +8251,9 @@ dependencies = [[[package]]name = "tauri-build"-version = "2.6.2"+version = "2.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4aa1f9055fc23919a54e4e125052bed16ed04aef0487086e758fe01a67b451c7"+checksum = "bc9ce40b16101cb6ea63d3e221567affd1c3a9205f95d7bc574941a10636b632"dependencies = ["anyhow","cargo_toml",@@ -8130,9 +8272,9 @@ dependencies = [[[package]]name = "tauri-codegen"-version = "2.6.2"+version = "2.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e4a0319528a025a38c4078e7dae2c446f4e63620ddb0659a643ede1cb38f90e9"+checksum = "08279169ff42f8fc45a1dbc9dcae888893ba95288142e5880c59b93a26d2cfc5"dependencies = ["base64 0.22.1","brotli",@@ -8146,9 +8288,9 @@ dependencies = ["serde","serde_json","sha2 0.10.9",- "syn 2.0.117",+ "syn 2.0.119","tauri-utils",- "thiserror 2.0.18",+ "thiserror 2.0.19","time","url","uuid",@@ -8157,23 +8299,23 @@ dependencies = [[[package]]name = "tauri-macros"-version = "2.6.2"+version = "2.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ae6cb4e3896c21d2f6da5b31251d2faea0153bba56ed0e970f918115dbee4924"+checksum = "e8b394794f399a421811d06966343e7933fcae92d59f5180b9388d1174497a45"dependencies = ["heck 0.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","tauri-codegen","tauri-utils",][[package]]name = "tauri-plugin"-version = "2.6.2"+version = "2.6.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "e126abc9e84e35cdfd01596140a73a1850cdb0df0a23acf0185776c30b469a6e"+checksum = "74be5dd4bed9afbd145e5716b5fa2ec28cbc29c34ffa61c258c9273d896c8020"dependencies = ["anyhow","glob",@@ -8197,7 +8339,7 @@ dependencies = ["serde_json","tauri","tauri-plugin",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]@@ -8214,7 +8356,7 @@ dependencies = ["tauri","tauri-plugin","tauri-utils",- "thiserror 2.0.18",+ "thiserror 2.0.19","tracing","url","windows-registry 0.5.3",@@ -8223,9 +8365,9 @@ dependencies = [[[package]]name = "tauri-plugin-dialog"-version = "2.7.1"+version = "2.7.2"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "65981abb771e74e571a38196c3baa11c459379164791eba0e67abc1a5fac9884"+checksum = "b2d3c1dbe38037e7f590cdf2492594d5ceebe031e7bc7e827509b22a999d2940"dependencies = ["log","raw-window-handle",@@ -8235,7 +8377,7 @@ dependencies = ["tauri","tauri-plugin","tauri-plugin-fs",- "thiserror 2.0.18",+ "thiserror 2.0.19","url",]@@ -8258,19 +8400,18 @@ dependencies = ["tauri","tauri-plugin","tauri-utils",- "thiserror 2.0.18",- "toml 1.1.2+spec-1.1.0",+ "thiserror 2.0.19",+ "toml 1.1.3+spec-1.1.0","url",][[package]]name = "tauri-plugin-log"-version = "2.8.0"+version = "2.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7545bd67f070a4500432c826e2e0682146a1d6712aee22a2786490156b574d93"+checksum = "6792296e6f389268016c77db21ebae1fc0568f2fccf88b1ec7e2ea71330afb4c"dependencies = ["android_logger",- "byte-unit","fern","log","objc2",@@ -8281,7 +8422,7 @@ dependencies = ["swift-rs","tauri","tauri-plugin",- "thiserror 2.0.18",+ "thiserror 2.0.19","time",]@@ -8312,20 +8453,21 @@ dependencies = ["shared_child","tauri","tauri-plugin",- "thiserror 2.0.18",+ "thiserror 2.0.19","tokio",][[package]]name = "tauri-plugin-single-instance"-version = "2.4.2"+version = "2.4.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5c8f29386f5e9fdc699182388a33ee80a56de436d91b67459e86afef426282af"+checksum = "b3214becf9ef5783c0ae99a3bb25adf5353a7a16ebf53e74b909e29205735c6c"dependencies = ["serde","serde_json","tauri",- "thiserror 2.0.18",+ "thiserror 2.0.19",+ "tokio","tracing","windows-sys 0.60.2","zbus",@@ -8347,8 +8489,8 @@ dependencies = ["minisign-verify","osakit","percent-encoding",- "reqwest 0.13.3",- "rustls 0.23.40",+ "reqwest 0.13.4",+ "rustls 0.23.42","semver","serde","serde_json",@@ -8356,7 +8498,7 @@ dependencies = ["tauri","tauri-plugin","tempfile",- "thiserror 2.0.18",+ "thiserror 2.0.19","time","tokio","url",@@ -8370,20 +8512,20 @@ version = "2.4.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "73736611e14142408d15353e21e3cca2f12a3cfb523ad0ce85999b6d2ef1a704"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","log","serde","serde_json","tauri","tauri-plugin",- "thiserror 2.0.18",+ "thiserror 2.0.19",][[package]]name = "tauri-runtime"-version = "2.11.2"+version = "2.11.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "48222d7116c8807eaa6fe2f372e023fae125084e61e6eca6d70b7961cdf129ef"+checksum = "b0b4bc95aed361b0019067d189a1174a603d460d0f6c72606512d59fc9c12ec8"dependencies = ["cookie","dpi",@@ -8397,7 +8539,7 @@ dependencies = ["serde","serde_json","tauri-utils",- "thiserror 2.0.18",+ "thiserror 2.0.19","url","webkit2gtk","webview2-com",@@ -8406,9 +8548,9 @@ dependencies = [[[package]]name = "tauri-runtime-wry"-version = "2.11.2"+version = "2.11.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b83849ee63ecb27a8e8d0fe51915ca215076914aca43f96db1179f0f415f6cd9"+checksum = "4e6fac707727b7a2f48e4ded90976324267371073edbb415ffb73bb0458d203f"dependencies = ["gtk","http",@@ -8432,9 +8574,9 @@ dependencies = [[[package]]name = "tauri-utils"-version = "2.9.2"+version = "2.9.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "092379df9a707631978e6c56b1bc2401d387f01e2d4a3c123360d167bbb9aa95"+checksum = "3e176a18e67764923c4f1ce66f25ae4abe5f688384d5eb1a0fa6c77f3d90f887"dependencies = ["anyhow","brotli",@@ -8460,8 +8602,8 @@ dependencies = ["serde_json","serde_with","swift-rs",- "thiserror 2.0.18",- "toml 1.1.2+spec-1.1.0",+ "thiserror 2.0.19",+ "toml 1.1.3+spec-1.1.0","url","urlpattern","uuid",@@ -8476,7 +8618,7 @@ checksum = "cc65d45c68858bfe420dd29e834b5d15dbecf8a07a8a16cf4d532c7b1f69d4b6"dependencies = ["dunce","embed-resource",- "toml 1.1.2+spec-1.1.0",+ "toml 1.1.3+spec-1.1.0",][[package]]@@ -8486,7 +8628,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"dependencies = ["fastrand",- "getrandom 0.4.2",+ "getrandom 0.4.3","once_cell","rustix 1.1.4","windows-sys 0.61.2",@@ -8494,12 +8636,11 @@ dependencies = [[[package]]name = "tendril"-version = "0.5.0"+version = "0.5.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c4790fc369d5a530f4b544b094e31388b9b3a37c0f4652ade4505945f5660d24"+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"dependencies = ["new_debug_unreachable",- "utf-8",][[package]]@@ -8522,11 +8663,11 @@ dependencies = [[[package]]name = "thiserror"-version = "2.0.18"+version = "2.0.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"+checksum = "09a43598840e33d5b0331f38c5e30d13bb11c11210a4b58f0d9b18a5a5eefcd9"dependencies = [- "thiserror-impl 2.0.18",+ "thiserror-impl 2.0.19",][[package]]@@ -8537,25 +8678,25 @@ checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "thiserror-impl"-version = "2.0.18"+version = "2.0.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"+checksum = "43cbfe0cf76104d42a574802844187e84a305e531ed54455f11fbde0f10541cd"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 3.0.3",][[package]]name = "thread_local"-version = "1.1.9"+version = "1.1.10"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185"+checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070"dependencies = ["cfg-if",]@@ -8606,12 +8747,11 @@ dependencies = [[[package]]name = "time"-version = "0.3.47"+version = "0.3.54"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "743bd48c283afc0388f9b8827b976905fb217ad9e647fae3a379a9283c4def2c"+checksum = "3e1d5e639ff6bab73cb6885cc7e7b1de96c3f32c68ec55f3952614bec1092244"dependencies = ["deranged",- "itoa","libc","num-conv","num_threads",@@ -8623,15 +8763,15 @@ dependencies = [[[package]]name = "time-core"-version = "0.1.8"+version = "0.1.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7694e1cfe791f8d31026952abf09c69ca6f6fa4e1a1229e18988f06a04a12dca"+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"[[package]]name = "time-macros"-version = "0.2.27"+version = "0.2.32"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2e70e4c5a0e0a8a4823ad65dfe1a6930e4f4d756dcd9dd7939022b5e8c501215"+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"dependencies = ["num-conv","time-core",@@ -8658,9 +8798,9 @@ dependencies = [[[package]]name = "tinyvec"-version = "1.11.0"+version = "1.12.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"+checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"dependencies = ["tinyvec_macros",]@@ -8689,14 +8829,14 @@ checksum = "2d2e76690929402faae40aebdda620a2c0e25dd6d3b9afe48867dfd95991f4bd"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "tokio"-version = "1.52.3"+version = "1.53.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"+checksum = "202caea871b69668250d242070849eb495be178ed697a3e98aebce5bc81a0bed"dependencies = ["bytes","libc",@@ -8711,13 +8851,13 @@ dependencies = [[[package]]name = "tokio-macros"-version = "2.7.0"+version = "2.7.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"+checksum = "6328af13490e73a9b4694030fafd93f8c8c6a9dede33e821c3fc63eddf8042ba"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -8732,8 +8872,8 @@ dependencies = [[[package]]name = "tokio-postgres"-version = "0.7.17"-source = "git+https://github.com/t8y2/tokio-postgres-gaussdb.git?branch=master#8d50befeee7cdeb8ecdb97c7b790c91010971063"+version = "0.7.18"+source = "git+https://github.com/t8y2/tokio-postgres-gaussdb.git?branch=master#6bf367c3ac9552f5fcba95659b6ffc1a8a35f494"dependencies = ["async-trait","byteorder",@@ -8748,7 +8888,7 @@ dependencies = ["pin-project-lite","postgres-protocol","postgres-types",- "rand 0.10.1",+ "rand 0.10.2","socket2","tokio","tokio-util",@@ -8763,7 +8903,7 @@ checksum = "27d684bad428a0f2481f42241f821db42c54e2dc81d8c00db8536c506b0a0144"dependencies = ["const-oid 0.9.6","ring",- "rustls 0.23.40",+ "rustls 0.23.42","tokio","tokio-postgres","tokio-rustls 0.26.4",@@ -8786,15 +8926,15 @@ version = "0.26.4"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"dependencies = [- "rustls 0.23.40",+ "rustls 0.23.42","tokio",][[package]]name = "tokio-stream"-version = "0.1.18"+version = "0.1.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"+checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b"dependencies = ["futures-core","pin-project-lite",@@ -8815,15 +8955,16 @@ dependencies = [[[package]]name = "tokio-util"-version = "0.7.18"+version = "0.7.19"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098"+checksum = "494815d09bf52b5548659851081238f0ca39ff638363907596da739561c62c52"dependencies = ["bytes","futures-core","futures-io","futures-sink","futures-util",+ "libc","pin-project-lite","tokio",]@@ -8857,9 +8998,9 @@ dependencies = [[[package]]name = "toml"-version = "1.1.2+spec-1.1.0"+version = "1.1.3+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "81f3d15e84cbcd896376e6730314d59fb5a87f31e4b038454184435cd57defee"+checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"dependencies = ["indexmap 2.14.0","serde_core",@@ -8867,7 +9008,7 @@ dependencies = ["toml_datetime 1.1.1+spec-1.1.0","toml_parser","toml_writer",- "winnow 1.0.3",+ "winnow 1.0.4",][[package]]@@ -8923,14 +9064,14 @@ dependencies = [[[package]]name = "toml_edit"-version = "0.25.11+spec-1.1.0"+version = "0.25.13+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0b59c4d22ed448339746c59b905d24568fcbb3ab65a500494f7b8c3e97739f2b"+checksum = "6975367e4d2ef766d86af01ffad14b622fecc8d4357a998fbc4deb6e9bacaf9b"dependencies = ["indexmap 2.14.0","toml_datetime 1.1.1+spec-1.1.0","toml_parser",- "winnow 1.0.3",+ "winnow 1.0.4",][[package]]@@ -8939,14 +9080,14 @@ version = "1.1.2+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"dependencies = [- "winnow 1.0.3",+ "winnow 1.0.4",][[package]]name = "toml_writer"-version = "1.1.1+spec-1.1.0"+version = "1.1.2+spec-1.1.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db"+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"[[package]]name = "tower"@@ -8971,7 +9112,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"dependencies = ["async-compression",- "bitflags 2.11.1",+ "bitflags 2.13.1","bytes","futures-core","futures-util",@@ -9025,7 +9166,7 @@ checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -9069,9 +9210,9 @@ dependencies = [[[package]]name = "tray-icon"-version = "0.23.1"+version = "0.24.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "15edbb0d80583e85ee8df283410038e17314df5cba30da2087a54a85216c0773"+checksum = "65ba1e5f6b9ef9fd87e21b9c6f351554dbd717960089168fcfdef854686961dc"dependencies = ["crossbeam-channel","dirs",@@ -9085,7 +9226,7 @@ dependencies = ["once_cell","png 0.18.1","serde",- "thiserror 2.0.18",+ "thiserror 2.0.19","windows-sys 0.61.2",]@@ -9117,16 +9258,16 @@ dependencies = ["http","httparse","log",- "rand 0.9.4",- "sha1 0.10.6",- "thiserror 2.0.18",+ "rand 0.9.5",+ "sha1 0.10.7",+ "thiserror 2.0.19",][[package]]name = "twox-hash"-version = "2.1.2"+version = "2.1.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9ea3136b675547379c4bd395ca6b938e5ad3c3d20fad76e7fe85f9e0d011419c"+checksum = "8464ec13c3691491391d9fce00f6416c9a48e46972f72d7865688be2080192c9"[[package]]name = "typed-builder"@@ -9145,7 +9286,7 @@ checksum = "0e48cea23f68d1f78eb7bc092881b6bb88d3d6b5b7e6234f6f9c911da1ffb221"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -9156,9 +9297,9 @@ checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"[[package]]name = "typenum"-version = "1.20.0"+version = "1.20.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"[[package]]name = "ucd-trie"@@ -9253,9 +9394,9 @@ checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"[[package]]name = "unicode-segmentation"-version = "1.13.2"+version = "1.13.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9629274872b2bfaf8d66f5f15725007f635594914870f65218920345aa11aa8c"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"[[package]]name = "unicode-width"@@ -9307,6 +9448,34 @@ version = "0.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"+[[package]]+name = "ureq"+version = "3.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0"+dependencies = [+ "base64 0.22.1",+ "log",+ "percent-encoding",+ "rustls 0.23.42",+ "rustls-pki-types",+ "ureq-proto",+ "utf8-zero",+ "webpki-roots 1.0.9",+]++[[package]]+name = "ureq-proto"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c"+dependencies = [+ "base64 0.22.1",+ "http",+ "httparse",+ "log",+]+[[package]]name = "url"version = "2.5.8"@@ -9333,16 +9502,10 @@ dependencies = [][[package]]-name = "utf-8"-version = "0.7.6"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9"--[[package]]-name = "utf8-width"-version = "0.1.8"+name = "utf8-zero"+version = "0.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1292c0d970b54115d14f2492fe0170adf21d68a1de108eebc51c1df4f346a091"+checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e"[[package]]name = "utf8_iter"@@ -9371,16 +9534,16 @@ dependencies = ["proc-macro2","quote","regex",- "syn 2.0.117",+ "syn 2.0.119",][[package]]name = "uuid"-version = "1.23.1"+version = "1.24.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ddd74a9687298c6858e9b88ec8935ec45d22e8fd5e6394fa1bd4e99a87789c76"+checksum = "bf3923a6f5c4c6382e0b653c4117f48d631ea17f38ed86e2a828e6f7412f5239"dependencies = [- "getrandom 0.4.2",+ "getrandom 0.4.3","js-sys","serde_core","wasm-bindgen",@@ -9392,12 +9555,6 @@ version = "0.1.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65"-[[package]]-name = "value-bag"-version = "1.12.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0"-[[package]]name = "vcpkg"version = "0.2.15"@@ -9472,20 +9629,11 @@ dependencies = [[[package]]name = "wasip2"-version = "1.0.3+wasi-0.2.9"+version = "1.0.4+wasi-0.2.12"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "20064672db26d7cdc89c7798c48a0fdfac8213434a1186e5ef29fd560ae223d6"+checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"dependencies = [- "wit-bindgen 0.57.1",-]--[[package]]-name = "wasip3"-version = "0.4.0+wasi-0.3.0-rc-2026-01-06"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"-dependencies = [- "wit-bindgen 0.51.0",+ "wit-bindgen",][[package]]@@ -9499,9 +9647,9 @@ dependencies = [[[package]]name = "wasm-bindgen"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3ed04576f974d2b2fba0f38c51dbc5518011e38c36bf1143164be765528fd409"+checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"dependencies = ["cfg-if","once_cell",@@ -9513,9 +9661,9 @@ dependencies = [[[package]]name = "wasm-bindgen-futures"-version = "0.4.72"+version = "0.4.76"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9473dbd2991ae90b6291c3c32c30c6187ac49aa32f9905d1cce280ec1e110b0f"+checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"dependencies = ["js-sys","wasm-bindgen",@@ -9523,9 +9671,9 @@ dependencies = [[[package]]name = "wasm-bindgen-macro"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "916151b09da36bd82f6615cbf3a419e2f0ba23a03c6160e8e92eb6bd4aa1dec6"+checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"dependencies = ["quote","wasm-bindgen-macro-support",@@ -9533,48 +9681,26 @@ dependencies = [[[package]]name = "wasm-bindgen-macro-support"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "299047362ccbfce148b67ab7e73349f77748e00c8296f9542adfad2ad82c5c5e"+checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"dependencies = ["bumpalo","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","wasm-bindgen-shared",][[package]]name = "wasm-bindgen-shared"-version = "0.2.122"+version = "0.2.126"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9a929b2c61f11ba3e9bc35b50c1f25cb38e0e892c0c231ae2b8cf78d5dad4437"+checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"dependencies = ["unicode-ident",]-[[package]]-name = "wasm-encoder"-version = "0.244.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"-dependencies = [- "leb128fmt",- "wasmparser",-]--[[package]]-name = "wasm-metadata"-version = "0.244.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"-dependencies = [- "anyhow",- "indexmap 2.14.0",- "wasm-encoder",- "wasmparser",-]-[[package]]name = "wasm-streams"version = "0.4.2"@@ -9601,23 +9727,11 @@ dependencies = ["web-sys",]-[[package]]-name = "wasmparser"-version = "0.244.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"-dependencies = [- "bitflags 2.11.1",- "hashbrown 0.15.5",- "indexmap 2.14.0",- "semver",-]-[[package]]name = "wayland-backend"-version = "0.3.15"+version = "0.3.16"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "2857dd20b54e916ec7253b3d6b4d5c4d7d4ca2c33c2e11c6c76a99bd8744755d"+checksum = "016ccf01d1c58b6f8999612813e17c9b2390f7d70671428869913310f83f54b8"dependencies = ["cc","downcast-rs",@@ -9628,11 +9742,11 @@ dependencies = [[[package]]name = "wayland-client"-version = "0.31.14"+version = "0.31.15"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "645c7c96bb74690c3189b5c9cb4ca1627062bb23693a4fad9d8c3de958260144"+checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","rustix 1.1.4","wayland-backend","wayland-scanner",@@ -9640,11 +9754,11 @@ dependencies = [[[package]]name = "wayland-protocols"-version = "0.32.12"+version = "0.32.13"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "563a85523cade2429938e790815fd7319062103b9f4a2dc806e9b53b95982d8f"+checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","wayland-backend","wayland-client","wayland-scanner",@@ -9656,7 +9770,7 @@ version = "0.3.12"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234"dependencies = [- "bitflags 2.11.1",+ "bitflags 2.13.1","wayland-backend","wayland-client","wayland-protocols",@@ -9665,12 +9779,12 @@ dependencies = [[[package]]name = "wayland-scanner"-version = "0.31.10"+version = "0.31.11"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9c324a910fd86ebdc364a3e61ec1f11737d3b1d6c273c0239ee8ff4bc0d24b4a"+checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0"dependencies = ["proc-macro2",- "quick-xml 0.39.4",+ "quick-xml 0.41.0","quote",]@@ -9685,9 +9799,9 @@ dependencies = [[[package]]name = "web-sys"-version = "0.3.99"+version = "0.3.103"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6d621441cfc37b84979402712047321980c178f299193a3589d05b99e8763436"+checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"dependencies = ["js-sys","wasm-bindgen",@@ -9705,9 +9819,9 @@ dependencies = [[[package]]name = "web_atoms"-version = "0.2.4"+version = "0.2.5"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d7cff6eef815df1834fd250e3a2ff436044d82a9f1bc1980ca1dbdf07effc538"+checksum = "075474b12bcb3d2e3d4546580e9de478eeeead668a1761e2a8860c836b7ef297"dependencies = ["phf","phf_codegen",@@ -9761,9 +9875,9 @@ dependencies = [[[package]]name = "webpki-root-certs"-version = "1.0.7"+version = "1.0.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c"+checksum = "b96554aa2acc8ccdb7e1c9a58a7a68dd5d13bccc69cd124cb09406db612a1c9b"dependencies = ["rustls-pki-types",]@@ -9774,14 +9888,14 @@ version = "0.26.11"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"dependencies = [- "webpki-roots 1.0.7",+ "webpki-roots 1.0.9",][[package]]name = "webpki-roots"-version = "1.0.7"+version = "1.0.9"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d"+checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"dependencies = ["rustls-pki-types",]@@ -9808,7 +9922,7 @@ checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -9817,7 +9931,7 @@ version = "0.38.2"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"dependencies = [- "thiserror 2.0.18",+ "thiserror 2.0.19","windows 0.61.3","windows-core 0.61.2",]@@ -10014,7 +10128,7 @@ checksum = "9107ddc059d5b6fbfbffdfa7a7fe3e22a226def0b2608f72e9d552763d3e1ad7"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10025,7 +10139,7 @@ checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10036,7 +10150,7 @@ checksum = "29bee4b38ea3cde66011baa44dba677c432a78593e202392d1e9070cf2a7fca7"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10047,7 +10161,7 @@ checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10424,9 +10538,9 @@ checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945"[[package]]name = "winnow"-version = "1.0.3"+version = "1.0.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1"+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"dependencies = ["memchr",]@@ -10450,100 +10564,12 @@ dependencies = ["winapi",]-[[package]]-name = "wit-bindgen"-version = "0.51.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"-dependencies = [- "wit-bindgen-rust-macro",-]-[[package]]name = "wit-bindgen"version = "0.57.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"-[[package]]-name = "wit-bindgen-core"-version = "0.51.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"-dependencies = [- "anyhow",- "heck 0.5.0",- "wit-parser",-]--[[package]]-name = "wit-bindgen-rust"-version = "0.51.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"-dependencies = [- "anyhow",- "heck 0.5.0",- "indexmap 2.14.0",- "prettyplease",- "syn 2.0.117",- "wasm-metadata",- "wit-bindgen-core",- "wit-component",-]--[[package]]-name = "wit-bindgen-rust-macro"-version = "0.51.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"-dependencies = [- "anyhow",- "prettyplease",- "proc-macro2",- "quote",- "syn 2.0.117",- "wit-bindgen-core",- "wit-bindgen-rust",-]--[[package]]-name = "wit-component"-version = "0.244.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"-dependencies = [- "anyhow",- "bitflags 2.11.1",- "indexmap 2.14.0",- "log",- "serde",- "serde_derive",- "serde_json",- "wasm-encoder",- "wasm-metadata",- "wasmparser",- "wit-parser",-]--[[package]]-name = "wit-parser"-version = "0.244.0"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"-dependencies = [- "anyhow",- "id-arena",- "indexmap 2.14.0",- "log",- "semver",- "serde",- "serde_derive",- "serde_json",- "unicode-xid",- "wasmparser",-]-[[package]]name = "wl-clipboard-rs"version = "0.9.3"@@ -10554,7 +10580,7 @@ dependencies = ["log","os_pipe","rustix 1.1.4",- "thiserror 2.0.18",+ "thiserror 2.0.19","tree_magic_mini","wayland-backend","wayland-client",@@ -10601,7 +10627,7 @@ dependencies = ["sha2 0.10.9","soup3","tao-macros",- "thiserror 2.0.18",+ "thiserror 2.0.19","url","webkit2gtk","webkit2gtk-sys",@@ -10694,9 +10720,9 @@ dependencies = [[[package]]name = "yoke"-version = "0.8.2"+version = "0.8.3"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "abe8c5fda708d9ca3df187cae8bfb9ceda00dd96231bed36e445a1a48e66f9ca"+checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"dependencies = ["stable_deref_trait","yoke-derive",@@ -10711,15 +10737,15 @@ checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","synstructure",][[package]]name = "zbus"-version = "5.15.0"+version = "5.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c3bcbf15c8708d7fc1be0c993622e0a5cbd5e8b52bfa40afa4c3e0cd8d724ac1"+checksum = "fe18fb60dc696039e738717b76eaea21e7a4489bbb1885020b43c94236d7e98a"dependencies = ["async-broadcast","async-executor",@@ -10744,7 +10770,7 @@ dependencies = ["uds_windows","uuid","windows-sys 0.61.2",- "winnow 1.0.3",+ "winnow 1.0.4","zbus_macros","zbus_names","zvariant",@@ -10752,14 +10778,14 @@ dependencies = [[[package]]name = "zbus_macros"-version = "5.15.0"+version = "5.18.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "51fa5406ad9175a8c825a931f8cf347116b531b3634fcb0b627c290f1f2516ff"+checksum = "fe96480bed92df2b442a1a30df364e12d08eed03aeb061f2b8dc6afb2be91119"dependencies = ["proc-macro-crate 3.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","zbus_names","zvariant","zvariant_utils",@@ -10767,33 +10793,33 @@ dependencies = [[[package]]name = "zbus_names"-version = "4.3.2"+version = "4.3.4"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "7074f3e50b894eac91750142016d30d0a89be8e67dbfd9704fb875825760e52d"+checksum = "d8bf88b4a3ff53e883001e0e0115b297a9d53c31b9c1edd2bfdd853e3428624e"dependencies = ["serde",- "winnow 1.0.3",+ "winnow 1.0.4","zvariant",][[package]]name = "zerocopy"-version = "0.8.48"+version = "0.8.55"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "eed437bf9d6692032087e337407a86f04cd8d6a16a37199ed57949d415bd68e9"+checksum = "b5a105cd7b140f6eeec8acff2ea38135d3cab283ada58540f629fe51e46696eb"dependencies = ["zerocopy-derive",][[package]]name = "zerocopy-derive"-version = "0.8.48"+version = "0.8.55"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "70e3cd084b1788766f53af483dd21f93881ff30d7320490ec3ef7526d203bad4"+checksum = "0fe976fb70c78cd64cccfe3a6fc142244e8a77b70959b30faf9d0ac37ee228eb"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10813,28 +10839,28 @@ checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","synstructure",][[package]]name = "zeroize"-version = "1.8.2"+version = "1.9.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"dependencies = ["zeroize_derive",][[package]]name = "zeroize_derive"-version = "1.4.3"+version = "1.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "85a5b4158499876c763cb03bc4e49185d3cccbabb15b33c627f7884f43db852e"+checksum = "3c50655cbb0fe3fc43170059e702f1ce5e19b84cec58dc87b037a09935c2f328"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10867,7 +10893,7 @@ checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"dependencies = ["proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119",][[package]]@@ -10890,7 +10916,7 @@ dependencies = ["memchr","pbkdf2 0.12.2","ppmd-rust",- "sha1 0.10.6",+ "sha1 0.10.7","time","zeroize","zopfli",@@ -10913,15 +10939,15 @@ dependencies = [[[package]]name = "zlib-rs"-version = "0.6.3"+version = "0.6.6"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "3be3d40e40a133f9c916ee3f9f4fa2d9d63435b5fbe1bfc6d9dae0aa0ada1513"+checksum = "b142a20ec14a91d5bc708c1dc21b080c550113d8aa77afa29635673a65dd02c5"[[package]]name = "zmij"-version = "1.0.21"+version = "1.0.23"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"[[package]]name = "zopfli"@@ -10980,40 +11006,40 @@ dependencies = [[[package]]name = "zvariant"-version = "5.11.0"+version = "5.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "1c1567a6ec68df868cbbfde844cfc6d81649fe5109a62b116b19fabd53e618ee"+checksum = "bee2a0bcd2a907786a456fff45aaaaf54c9ba5f50b71ae9ec1a4edd200c94911"dependencies = ["endi","enumflags2","serde",- "winnow 1.0.3",+ "winnow 1.0.4","zvariant_derive","zvariant_utils",][[package]]name = "zvariant_derive"-version = "5.11.0"+version = "5.13.1"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "c7d5b780599bbde114e39d9a0799577fad1ced5105d38515745f7b3099d8ceda"+checksum = "38a708216a18780796770bfe3f4739c7c83a3e8f789b755534bbbc06e4e23e12"dependencies = ["proc-macro-crate 3.5.0","proc-macro2","quote",- "syn 2.0.117",+ "syn 2.0.119","zvariant_utils",][[package]]name = "zvariant_utils"-version = "3.3.1"+version = "3.5.0"source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "6d464f5733ffa07a3164d656f18533caace9d0638596721355d73256a410d691"+checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7"dependencies = ["proc-macro2","quote","serde",- "syn 2.0.117",- "winnow 1.0.3",+ "syn 2.0.119",+ "winnow 1.0.4",]diff --git a/apps/desktop/src/components/config/ConfigDriftPanel.vue b/apps/desktop/src/components/config/ConfigDriftPanel.vuenew file mode 100644index 0000000000..b6abef4336--- /dev/null+++ b/apps/desktop/src/components/config/ConfigDriftPanel.vue@@ -0,0 +1,144 @@+<script setup lang="ts">+import { computed, ref } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { AlertTriangle, Check, ChevronDown, ChevronRight, RefreshCw } from "@lucide/vue";+import type { DriftAlert } from "@/types/governance";++interface DriftSummary {+ sourceEnv: string;+ targetEnv: string;+ driftCount: number;+ lastDetectedAt: string;+ hasUnacknowledged: boolean;+}++const props = defineProps<{+ drifts: DriftSummary[];+ alerts: DriftAlert[];+}>();++const emit = defineEmits<{+ acknowledge: [alertId: string];+ refresh: [];+}>();++const { t } = useI18n();+const expandedKeys = ref<Set<string>>(new Set());++const totalDriftCount = computed(() => props.drifts.reduce((sum, d) => sum + d.driftCount, 0));++function toggleKey(key: string) {+ const next = new Set(expandedKeys.value);+ if (next.has(key)) {+ next.delete(key);+ } else {+ next.add(key);+ }+ expandedKeys.value = next;+}++function alertsForDrift(summary: DriftSummary): DriftAlert[] {+ return props.alerts.filter((a) => a.sourceEnv === summary.sourceEnv && a.targetEnv === summary.targetEnv);+}++function formatDate(iso: string): string {+ try {+ return new Intl.DateTimeFormat(undefined, {+ dateStyle: "medium",+ timeStyle: "short",+ }).format(new Date(iso));+ } catch {+ return iso;+ }+}+</script>++<template>+ <div class="rounded-md border bg-card">+ <div class="flex items-center justify-between border-b px-4 py-3">+ <h3 class="text-sm font-medium">{{ t("configDrift.title") }}</h3>+ <Button size="sm" variant="ghost" class="h-7 gap-1 text-xs" @click="emit('refresh')">+ <RefreshCw class="h-3 w-3" />+ </Button>+ </div>++ <div class="border-b px-4 py-2 text-xs">+ <template v-if="totalDriftCount > 0">+ <span class="text-muted-foreground">{{ t("configDrift.driftFound", { count: totalDriftCount }) }}</span>+ </template>+ <template v-else>+ <span class="text-muted-foreground">{{ t("configDrift.noDrift") }}</span>+ </template>+ </div>++ <div v-if="drifts.length > 0" class="overflow-x-auto">+ <table class="w-full text-xs">+ <thead>+ <tr class="border-b bg-muted/30 text-muted-foreground">+ <th class="px-4 py-2 text-left font-medium">{{ t("configDrift.sourceEnv") }}</th>+ <th class="px-4 py-2 text-left font-medium">{{ t("configDrift.targetEnv") }}</th>+ <th class="px-4 py-2 text-left font-medium">{{ t("configDrift.driftCount") }}</th>+ <th class="px-4 py-2 text-left font-medium">{{ t("configDrift.lastDetected") }}</th>+ <th class="px-4 py-2 text-left font-medium">{{ t("configDrift.configKey") }}</th>+ </tr>+ </thead>+ <tbody>+ <template v-for="drift in drifts" :key="`${drift.sourceEnv}-${drift.targetEnv}`">+ <tr class="border-b last:border-b-0 hover:bg-accent/50">+ <td class="px-4 py-2.5 font-medium">{{ drift.sourceEnv }}</td>+ <td class="px-4 py-2.5">{{ drift.targetEnv }}</td>+ <td class="px-4 py-2.5">{{ drift.driftCount }}</td>+ <td class="px-4 py-2.5 text-muted-foreground">{{ formatDate(drift.lastDetectedAt) }}</td>+ <td class="px-4 py-2.5">+ <span v-if="!drift.hasUnacknowledged" class="text-green-600 dark:text-green-400">{{ t("configDrift.acknowledged") }}</span>+ <Badge v-else variant="outline" class="text-xs">{{ t("configDrift.unacknowledged") }}</Badge>+ </td>+ </tr>++ <tr v-for="alert in alertsForDrift(drift)" :key="alert.id" class="border-b bg-muted/20">+ <td colspan="5" class="px-4 py-1.5">+ <div class="flex items-center justify-between">+ <button class="flex items-center gap-1.5 text-left text-xs" @click="toggleKey(alert.id)">+ <ChevronRight v-if="!expandedKeys.has(alert.id)" class="h-3 w-3 shrink-0 text-muted-foreground" />+ <ChevronDown v-else class="h-3 w-3 shrink-0 text-muted-foreground" />+ <code class="rounded bg-muted px-1 py-0.5 font-mono text-xs">{{ alert.configKey }}</code>+ <span v-if="alert.acknowledged" class="text-green-600 dark:text-green-400">{{ t("configDrift.acknowledged") }}</span>+ </button>+ <Button v-if="!alert.acknowledged" size="sm" variant="outline" class="h-7 gap-1 text-xs" @click="emit('acknowledge', alert.id)">+ <Check class="h-3 w-3" />+ {{ t("configDrift.acknowledge") }}+ </Button>+ </div>+ <div v-if="expandedKeys.has(alert.id)" class="mt-2 space-y-1.5 pl-5">+ <div class="grid grid-cols-2 gap-3 text-xs">+ <div>+ <span class="text-muted-foreground">{{ t("configDrift.checksum") }} (expected)</span>+ <code class="ml-2 rounded bg-muted px-1 py-0.5 font-mono text-[10px]">{{ alert.expectedChecksum }}</code>+ </div>+ <div>+ <span class="text-muted-foreground">{{ t("configDrift.checksum") }} (actual)</span>+ <code class="ml-2 rounded bg-muted px-1 py-0.5 font-mono text-[10px]">{{ alert.actualChecksum }}</code>+ </div>+ </div>+ <div v-if="alert.detailsJson" class="text-xs">+ <span class="text-muted-foreground">{{ t("configDrift.mismatchedFields") }}</span>+ <pre class="mt-0.5 max-h-32 overflow-auto rounded bg-muted/50 p-2 font-mono text-[10px] whitespace-pre-wrap">{{ typeof alert.detailsJson === "string" ? alert.detailsJson : JSON.stringify(alert.detailsJson, null, 2) }}</pre>+ </div>+ </div>+ </td>+ </tr>+ </template>+ </tbody>+ </table>+ </div>++ <div v-if="drifts.length === 0" class="flex items-center justify-center px-4 py-10 text-xs text-muted-foreground">+ <AlertTriangle class="mr-2 h-4 w-4" />+ {{ t("configDrift.noDrift") }}+ </div>+ </div>+</template>++<style scoped></style>diff --git a/apps/desktop/src/components/config/ConfigHotReloadIndicator.vue b/apps/desktop/src/components/config/ConfigHotReloadIndicator.vuenew file mode 100644index 0000000000..a111ef32b9--- /dev/null+++ b/apps/desktop/src/components/config/ConfigHotReloadIndicator.vue@@ -0,0 +1,52 @@+<script setup lang="ts">+import { useI18n } from "vue-i18n";+import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";+import { Button } from "@/components/ui/button";+import { Loader2 } from "@lucide/vue";++const props = defineProps<{+ lastReloadedAt: string | null;+ reloadCount: number;+ reloading: boolean;+}>();++const emit = defineEmits<{+ apply: [];+ dismiss: [];+}>();++const { t } = useI18n();++function formatTimestamp(iso: string): string {+ try {+ return new Intl.DateTimeFormat(undefined, {+ dateStyle: "medium",+ timeStyle: "medium",+ }).format(new Date(iso));+ } catch {+ return iso;+ }+}+</script>++<template>+ <div v-if="lastReloadedAt || reloadCount > 0" class="fixed bottom-4 right-4 z-50">+ <Tooltip>+ <TooltipTrigger as-child>+ <div class="flex items-center gap-2 rounded-lg border bg-card p-3 shadow-lg">+ <Loader2 v-if="reloading" class="h-4 w-4 animate-spin text-muted-foreground" />+ <span class="text-xs font-medium">{{ t("toolbar.configChanged") }}</span>+ <Button size="sm" variant="default" class="h-6 text-xs px-2" @click="emit('apply')">+ {{ t("toolbar.applyConfig") }}+ </Button>+ <Button size="sm" variant="ghost" class="h-6 text-xs px-2" @click="emit('dismiss')">+ {{ t("toolbar.dismiss") }}+ </Button>+ </div>+ </TooltipTrigger>+ <TooltipContent side="top" class="text-xs">+ {{ lastReloadedAt ? formatTimestamp(lastReloadedAt) : "" }}+ </TooltipContent>+ </Tooltip>+ </div>+</template>diff --git a/apps/desktop/src/components/config/TagManagementPanel.vue b/apps/desktop/src/components/config/TagManagementPanel.vuenew file mode 100644index 0000000000..8fdec7d2bf--- /dev/null+++ b/apps/desktop/src/components/config/TagManagementPanel.vue@@ -0,0 +1,681 @@+<script setup lang="ts">+import { computed, ref } from "vue";+import { useI18n } from "vue-i18n";+import { Download, Edit3, FileJson, Lock, Plus, Search, Trash2, X } from "@lucide/vue";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { Input } from "@/components/ui/input";+import { Label } from "@/components/ui/label";+import { Switch } from "@/components/ui/switch";+import { Separator } from "@/components/ui/separator";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from "@/components/ui/dialog";+import { cn } from "@/lib/common/utils";++interface BusinessTag {+ key: string;+ value: string;+ description: string;+ immutable: boolean;+}++interface TagFilter {+ search: string;+ showExpired: boolean;+ environment: string;+}++const props = defineProps<{+ tags: BusinessTag[];+ whitelist: string[];+}>();++const emit = defineEmits<{+ save: [tag: BusinessTag];+ delete: [key: string];+ import: [tags: BusinessTag[]];+ updateWhitelist: [keys: string[]];+}>();++const { t } = useI18n();++const filter = ref<TagFilter>({+ search: "",+ showExpired: false,+ environment: "",+});++const showAddDialog = ref(false);+const showImportDialog = ref(false);+const showWhitelistSection = ref(false);+const editingTag = ref<BusinessTag | null>(null);+const confirmDeleteKey = ref<string | null>(null);+const importData = ref("");+const importPreview = ref<BusinessTag[]>([]);+const whitelistInput = ref("");++const environments = ["", "development", "staging", "production"];++const filteredTags = computed(() => {+ return props.tags.filter((tag) => {+ if (filter.value.search) {+ const q = filter.value.search.toLowerCase();+ if (!tag.key.toLowerCase().includes(q) && !tag.value.toLowerCase().includes(q) && !tag.description.toLowerCase().includes(q)) {+ return false;+ }+ }+ return true;+ });+});++function resetEditingTag() {+ editingTag.value = { key: "", value: "", description: "", immutable: false };+}++function openAddDialog() {+ resetEditingTag();+ showAddDialog.value = true;+}++function openEditDialog(tag: BusinessTag) {+ editingTag.value = { ...tag };+ showAddDialog.value = true;+}++function handleSave() {+ if (!editingTag.value) return;+ emit("save", { ...editingTag.value });+ showAddDialog.value = false;+ editingTag.value = null;+}++function handleDelete(key: string) {+ emit("delete", key);+ confirmDeleteKey.value = null;+}++function parseImport() {+ try {+ const parsed: BusinessTag[] = JSON.parse(importData.value);+ importPreview.value = parsed.filter((item): item is BusinessTag => typeof item.key === "string" && typeof item.value === "string" && typeof item.description === "string" && typeof item.immutable === "boolean");+ } catch {+ const lines = importData.value.split("\n").filter(Boolean);+ const parsed: BusinessTag[] = lines.map((line) => {+ const parts = line.split(",");+ return {+ key: parts[0]?.trim() ?? "",+ value: parts[1]?.trim() ?? "",+ description: parts[2]?.trim() ?? "",+ immutable: parts[3]?.trim() === "true",+ };+ });+ importPreview.value = parsed.filter((item) => item.key);+ }+}++function handleImport() {+ if (importPreview.value.length === 0) return;+ emit("import", importPreview.value);+ importPreview.value = [];+ importData.value = "";+ showImportDialog.value = false;+}++function addWhitelistKey() {+ const key = whitelistInput.value.trim();+ if (!key || props.whitelist.includes(key)) return;+ emit("updateWhitelist", [...props.whitelist, key]);+ whitelistInput.value = "";+}++function removeWhitelistKey(key: string) {+ emit(+ "updateWhitelist",+ props.whitelist.filter((k) => k !== key),+ );+}++function handleExport() {+ const blob = new Blob([JSON.stringify(props.tags, null, 2)], {+ type: "application/json",+ });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = "tags.json";+ a.click();+ URL.revokeObjectURL(url);+}+</script>++<template>+ <div class="tag-management-panel">+ <div class="panel-header">+ <h2 class="panel-title">{{ t("tag.management") }}</h2>+ <div class="panel-actions">+ <Button variant="outline" size="sm" @click="showImportDialog = true">+ <FileJson class="h-4 w-4" />+ {{ t("tag.importTags") }}+ </Button>+ <Button variant="outline" size="sm" @click="handleExport">+ <Download class="h-4 w-4" />+ {{ t("tag.exportTags") }}+ </Button>+ <Button size="sm" @click="openAddDialog">+ <Plus class="h-4 w-4" />+ {{ t("common.add") }}+ </Button>+ </div>+ </div>++ <div class="filter-bar">+ <div class="search-wrapper">+ <Search class="search-icon" />+ <Input v-model="filter.search" :placeholder="t('common.search')" />+ </div>+ <div class="filter-controls">+ <Select v-model="filter.environment">+ <SelectTrigger class="w-[160px]">+ <SelectValue :placeholder="t('tag.environment')" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="">+ {{ t("common.all") }}+ </SelectItem>+ <SelectItem v-for="env in environments.filter(Boolean)" :key="env" :value="env">+ {{ env }}+ </SelectItem>+ </SelectContent>+ </Select>+ <label class="expired-toggle">+ <Switch v-model="filter.showExpired" size="sm" />+ <span>{{ t("tag.expired") }}</span>+ </label>+ </div>+ </div>++ <div class="table-container">+ <table class="tag-table">+ <thead>+ <tr>+ <th>{{ t("tag.key") }}</th>+ <th>{{ t("tag.value") }}</th>+ <th>{{ t("tag.description") }}</th>+ <th>{{ t("tag.immutable") }}</th>+ <th class="actions-cell">{{ t("common.actions") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-if="filteredTags.length === 0">+ <td colspan="5" class="empty-state">+ {{ t("tag.noTags") }}+ </td>+ </tr>+ <tr v-for="tag in filteredTags" :key="tag.key">+ <td class="cell-key">{{ tag.key }}</td>+ <td>{{ tag.value }}</td>+ <td class="cell-desc">{{ tag.description }}</td>+ <td>+ <Badge v-if="tag.immutable" variant="secondary" class="immutable-badge">+ <Lock class="h-3 w-3" />+ {{ t("tag.immutable") }}+ </Badge>+ <span v-else class="text-muted-foreground text-xs">—</span>+ </td>+ <td class="actions-cell">+ <div class="row-actions">+ <Button variant="ghost" size="icon-sm" @click="openEditDialog(tag)">+ <Edit3 class="h-4 w-4" />+ </Button>+ <Button variant="ghost" size="icon-sm" :disabled="tag.immutable" @click="confirmDeleteKey = tag.key">+ <Trash2 class="h-4 w-4" />+ </Button>+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>++ <Separator class="my-2" />++ <div class="whitelist-section">+ <button class="whitelist-toggle" @click="showWhitelistSection = !showWhitelistSection">+ <span>{{ t("tag.whitelist") }}</span>+ <span class="whitelist-count">{{ props.whitelist.length }}</span>+ <svg :class="cn('chevron', showWhitelistSection && 'open')" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">+ <polyline points="9 18 15 12 9 6" />+ </svg>+ </button>+ <div v-if="showWhitelistSection" class="whitelist-content">+ <div class="whitelist-chips">+ <span v-for="key in props.whitelist" :key="key" class="whitelist-chip">+ {{ key }}+ <button class="chip-remove" @click="removeWhitelistKey(key)">+ <X class="h-3 w-3" />+ </button>+ </span>+ </div>+ <div class="whitelist-add-row">+ <Input v-model="whitelistInput" :placeholder="t('tag.key')" @keydown.enter="addWhitelistKey" />+ <Button variant="outline" size="sm" @click="addWhitelistKey">+ {{ t("common.add") }}+ </Button>+ </div>+ </div>+ </div>+ </div>++ <Dialog v-model:open="showAddDialog">+ <DialogContent class="sm:max-w-[500px]">+ <DialogHeader>+ <DialogTitle>+ {{ editingTag?.key && !editingTag?.key.startsWith("_new") ? t("common.edit") : t("common.add") }}+ {{ t("tag.management") }}+ </DialogTitle>+ </DialogHeader>+ <div class="grid gap-4 py-4">+ <div class="form-field">+ <Label>{{ t("tag.key") }}</Label>+ <Input v-model="editingTag!.key" />+ </div>+ <div class="form-field">+ <Label>{{ t("tag.value") }}</Label>+ <Input v-model="editingTag!.value" />+ </div>+ <div class="form-field">+ <Label>{{ t("tag.description") }}</Label>+ <textarea v-model="editingTag!.description" class="desc-textarea" rows="3" />+ </div>+ <label class="immutable-field">+ <Switch v-model="editingTag!.immutable" size="sm" />+ <span>{{ t("tag.immutable") }}</span>+ </label>+ </div>+ <DialogFooter>+ <Button variant="outline" @click="showAddDialog = false">+ {{ t("common.cancel") }}+ </Button>+ <Button @click="handleSave">+ {{ t("common.save") }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog v-model:open="showImportDialog">+ <DialogContent class="sm:max-w-[600px]">+ <DialogHeader>+ <DialogTitle>+ {{ t("tag.batchImport") }}+ </DialogTitle>+ </DialogHeader>+ <div class="grid gap-4 py-4">+ <textarea v-model="importData" class="import-textarea" rows="6" :placeholder="t('tag.batchImport')" />+ <div v-if="importPreview.length > 0" class="import-preview">+ <p class="preview-count">{{ importPreview.length }} {{ t("common.rows") }}</p>+ <table class="preview-table">+ <thead>+ <tr>+ <th>{{ t("tag.key") }}</th>+ <th>{{ t("tag.value") }}</th>+ <th>{{ t("tag.description") }}</th>+ <th>{{ t("tag.immutable") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(item, idx) in importPreview.slice(0, 10)" :key="idx">+ <td>{{ item.key }}</td>+ <td>{{ item.value }}</td>+ <td>{{ item.description }}</td>+ <td>{{ item.immutable }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ <DialogFooter>+ <Button variant="outline" @click="showImportDialog = false">+ {{ t("common.cancel") }}+ </Button>+ <Button variant="secondary" :disabled="!importData" @click="parseImport">+ {{ t("common.parse") }}+ </Button>+ <Button :disabled="importPreview.length === 0" @click="handleImport">+ {{ t("common.import") }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>++ <Dialog+ v-model:open="confirmDeleteKey !== null"+ @update:open="+ (v) => {+ if (!v) confirmDeleteKey = null;+ }+ "+ >+ <DialogContent class="sm:max-w-[400px]">+ <DialogHeader>+ <DialogTitle>+ {{ t("common.confirm") }}+ </DialogTitle>+ </DialogHeader>+ <p class="py-4 text-sm">+ {{ t("tag.confirmDelete", { key: confirmDeleteKey }) }}+ </p>+ <DialogFooter>+ <Button variant="outline" @click="confirmDeleteKey = null">+ {{ t("common.cancel") }}+ </Button>+ <Button variant="destructive" @click="confirmDeleteKey && handleDelete(confirmDeleteKey)">+ {{ t("common.delete") }}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+</template>++<style scoped>+.tag-management-panel {+ display: flex;+ flex-direction: column;+ gap: 16px;+}++.panel-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+}++.panel-title {+ font-size: 18px;+ font-weight: 600;+ margin: 0;+}++.panel-actions {+ display: flex;+ align-items: center;+ gap: 8px;+}++.filter-bar {+ display: flex;+ align-items: center;+ gap: 12px;+ flex-wrap: wrap;+}++.search-wrapper {+ position: relative;+ flex: 1;+ min-width: 200px;+}++.search-icon {+ position: absolute;+ left: 8px;+ top: 50%;+ transform: translateY(-50%);+ width: 16px;+ height: 16px;+ color: var(--muted-foreground);+ pointer-events: none;+}++.search-wrapper :deep(input) {+ padding-left: 32px;+}++.filter-controls {+ display: flex;+ align-items: center;+ gap: 12px;+}++.expired-toggle {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 13px;+ cursor: pointer;+ white-space: nowrap;+}++.table-container {+ overflow-x: auto;+ border: 1px solid var(--border);+ border-radius: 8px;+}++.tag-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 13px;+}++.tag-table th {+ text-align: left;+ padding: 10px 12px;+ font-weight: 500;+ color: var(--muted-foreground);+ border-bottom: 1px solid var(--border);+ background: var(--bg-secondary);+ white-space: nowrap;+}++.tag-table td {+ padding: 10px 12px;+ border-bottom: 1px solid var(--border);+ vertical-align: middle;+}++.tag-table tr:last-child td {+ border-bottom: none;+}++.tag-table tbody tr:hover {+ background: var(--accent);+}++.empty-state {+ text-align: center;+ color: var(--muted-foreground);+ padding: 32px 12px !important;+}++.cell-key {+ font-family: var(--font-mono, monospace);+ font-size: 12px;+ font-weight: 500;+}++.cell-desc {+ max-width: 240px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+ color: var(--muted-foreground);+}++.actions-cell {+ width: 100px;+ text-align: right;+}++.row-actions {+ display: flex;+ align-items: center;+ justify-content: flex-end;+ gap: 4px;+}++.immutable-badge {+ display: inline-flex;+ align-items: center;+ gap: 4px;+}++.whitelist-section {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.whitelist-toggle {+ display: flex;+ align-items: center;+ gap: 8px;+ background: none;+ border: none;+ cursor: pointer;+ font-size: 14px;+ font-weight: 500;+ padding: 4px 0;+ color: inherit;+}++.whitelist-count {+ display: inline-flex;+ align-items: center;+ justify-content: center;+ min-width: 20px;+ height: 20px;+ border-radius: 10px;+ font-size: 11px;+ font-weight: 600;+ background: var(--bg-secondary);+ padding: 0 6px;+}++.chevron {+ transition: transform 0.2s;+}++.chevron.open {+ transform: rotate(90deg);+}++.whitelist-content {+ display: flex;+ flex-direction: column;+ gap: 8px;+}++.whitelist-chips {+ display: flex;+ flex-wrap: wrap;+ gap: 6px;+}++.whitelist-chip {+ display: inline-flex;+ align-items: center;+ gap: 4px;+ padding: 2px 10px;+ font-size: 12px;+ border-radius: 12px;+ border: 1px solid var(--border);+ background: var(--bg-secondary);+}++.chip-remove {+ display: inline-flex;+ align-items: center;+ background: none;+ border: none;+ cursor: pointer;+ padding: 0;+ color: var(--muted-foreground);+}++.whitelist-add-row {+ display: flex;+ align-items: center;+ gap: 8px;+}++.form-field {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.desc-textarea {+ width: 100%;+ padding: 8px 10px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: transparent;+ color: inherit;+ font-size: 13px;+ font-family: inherit;+ resize: vertical;+ outline: none;+}++.desc-textarea:focus {+ border-color: var(--ring);+ box-shadow: 0 0 0 2px var(--ring);+}++.immutable-field {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 13px;+ cursor: pointer;+}++.import-textarea {+ width: 100%;+ padding: 10px;+ border: 1px solid var(--border);+ border-radius: 6px;+ background: transparent;+ color: inherit;+ font-size: 12px;+ font-family: var(--font-mono, monospace);+ resize: vertical;+ outline: none;+}++.import-textarea:focus {+ border-color: var(--ring);+ box-shadow: 0 0 0 2px var(--ring);+}++.import-preview {+ display: flex;+ flex-direction: column;+ gap: 6px;+}++.preview-count {+ font-size: 13px;+ font-weight: 500;+ margin: 0;+}++.preview-table {+ width: 100%;+ border-collapse: collapse;+ font-size: 12px;+}++.preview-table th {+ text-align: left;+ padding: 6px 8px;+ font-weight: 500;+ color: var(--muted-foreground);+ border-bottom: 1px solid var(--border);+}++.preview-table td {+ padding: 6px 8px;+ border-bottom: 1px solid var(--border);+}+</style>diff --git a/apps/desktop/src/components/diff/ConflictMatrix.vue b/apps/desktop/src/components/diff/ConflictMatrix.vuenew file mode 100644index 0000000000..880a6682b4--- /dev/null+++ b/apps/desktop/src/components/diff/ConflictMatrix.vue@@ -0,0 +1,80 @@+<script setup lang="ts">+import { useI18n } from "vue-i18n";+import { CheckCircle2, XCircle, GitMerge } from "@lucide/vue";++const { t } = useI18n();++interface ConflictItem {+ objectName: string;+ conflictType: string;+ sourceValue: string;+ targetValue: string;+ autoResolvable: boolean;+}++const props = defineProps<{+ conflicts: ConflictItem[];+}>();++const emit = defineEmits<{+ resolveWithSource: [objectName: string];+ resolveWithTarget: [objectName: string];+}>();+</script>++<template>+ <div class="border rounded-md bg-card">+ <div class="flex items-center gap-2 px-3 py-2 border-b">+ <GitMerge class="w-4 h-4 text-primary" />+ <h3 class="text-sm font-medium">{{ t("conflictMatrix.title") }}</h3>+ </div>++ <div v-if="conflicts.length === 0" class="flex items-center justify-center py-8 text-sm text-muted-foreground">+ {{ t("conflictMatrix.noConflicts") }}+ </div>++ <div v-else class="p-3">+ <div class="border rounded overflow-hidden">+ <table class="w-full text-xs">+ <thead>+ <tr class="bg-muted/30">+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("conflictMatrix.objectName") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("conflictMatrix.conflictType") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("conflictMatrix.sourceValue") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("conflictMatrix.targetValue") }}</th>+ <th class="text-center px-2 py-1.5 font-medium text-muted-foreground">{{ t("conflictMatrix.autoResolvable") }}</th>+ <th class="text-right px-2 py-1.5 font-medium text-muted-foreground">{{ t("common.actions") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="c in conflicts" :key="c.objectName" class="border-t" :class="c.autoResolvable ? 'bg-emerald-500/5' : 'bg-red-500/5'">+ <td class="px-2 py-1.5 font-mono">{{ c.objectName }}</td>+ <td class="px-2 py-1.5">{{ c.conflictType }}</td>+ <td class="px-2 py-1.5 font-mono max-w-[200px] truncate" :title="c.sourceValue">{{ c.sourceValue }}</td>+ <td class="px-2 py-1.5 font-mono max-w-[200px] truncate" :title="c.targetValue">{{ c.targetValue }}</td>+ <td class="px-2 py-1.5 text-center">+ <CheckCircle2 v-if="c.autoResolvable" class="w-4 h-4 text-green-500 inline-block" />+ <XCircle v-else class="w-4 h-4 text-red-500 inline-block" />+ </td>+ <td class="px-2 py-1.5 text-right">+ <div v-if="!c.autoResolvable" class="flex items-center justify-end gap-1">+ <button class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary/10 text-primary hover:bg-primary/20 transition-colors" @click="emit('resolveWithSource', c.objectName)">+ {{ t("conflictMatrix.resolveWithSource") }}+ </button>+ <button class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-muted/40 text-muted-foreground hover:bg-muted/60 transition-colors" @click="emit('resolveWithTarget', c.objectName)">+ {{ t("conflictMatrix.resolveWithTarget") }}+ </button>+ </div>+ <span v-else class="text-[10px] text-green-600 dark:text-green-400 font-medium">+ {{ t("conflictMatrix.resolved") }}+ </span>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ </div>+</template>++<style scoped></style>diff --git a/apps/desktop/src/components/diff/FieldMappingDialog.vue b/apps/desktop/src/components/diff/FieldMappingDialog.vuenew file mode 100644index 0000000000..b017f54316--- /dev/null+++ b/apps/desktop/src/components/diff/FieldMappingDialog.vue@@ -0,0 +1,205 @@+<script setup lang="ts">+import { ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Download, Upload, Check, X, Trash2 } from "@lucide/vue";+import FieldMappingPanel from "@/components/diff/FieldMappingPanel.vue";+import type { FieldMappingEntry } from "@/types/schemaDiff";+import { useToast } from "@/composables/useToast";++const props = defineProps<{+ open: boolean;+ mappings: FieldMappingEntry[];+ sourceDbType: string;+ targetDbType: string;+ sourceConnectionId?: string;+ sourceDatabase?: string;+ targetConnectionId?: string;+ targetDatabase?: string;+}>();++const emit = defineEmits<{+ (e: "update:open", value: boolean): void;+ (e: "save", value: FieldMappingEntry[]): void;+}>();++const { t } = useI18n();+const { toast } = useToast();++const editingMappings = ref<FieldMappingEntry[]>([]);+const fileInputRef = ref<HTMLInputElement | null>(null);++// 打开时深拷贝当前映射为本地副本(单向数据流,取消不写回)+watch(+ () => props.open,+ (isOpen) => {+ if (isOpen) {+ editingMappings.value = props.mappings.map((m) => ({ ...m }));+ }+ },+ { immediate: true },+);++function handleUpdateMappings(v: FieldMappingEntry[]) {+ editingMappings.value = v;+}++function handleExport() {+ const payload = {+ sourceDbType: props.sourceDbType,+ targetDbType: props.targetDbType,+ mappings: editingMappings.value,+ };+ const content = JSON.stringify(payload, null, 2);+ // Use File System Access API (modern Chromium) for a native Save As dialog,+ // fallback to Blob download for other browsers.+ if ("showSaveFilePicker" in window) {+ (window as any)+ .showSaveFilePicker({+ suggestedName: "field-mappings.json",+ types: [{ description: "JSON", accept: { "application/json": [".json"] } }],+ })+ .then((handle: FileSystemFileHandle) => {+ return handle.createWritable().then((writable: FileSystemWritableFileStream) => {+ writable.write(content);+ return writable.close();+ });+ })+ .catch(() => {+ // User cancelled or API failed — fallback to Blob download+ fallbackDownload(content);+ });+ } else {+ fallbackDownload(content);+ }+}++function handleClear() {+ editingMappings.value = [];+}++function fallbackDownload(content: string) {+ const blob = new Blob([content], { type: "application/json" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = "field-mappings.json";+ a.click();+ URL.revokeObjectURL(url);+}++function handleImportClick() {+ fileInputRef.value?.click();+}++function onFileSelected(event: Event) {+ const input = event.target as HTMLInputElement;+ const file = input.files?.[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = () => {+ try {+ const parsed = JSON.parse(String(reader.result)) as any;++ // Support both new format { sourceDbType, targetDbType, mappings }+ // and legacy flat format FieldMappingEntry[]+ let mappings: any[];+ let fileSourceDbType: string | undefined;+ let fileTargetDbType: string | undefined;++ if (Array.isArray(parsed)) {+ mappings = parsed;+ } else if (parsed?.mappings && Array.isArray(parsed.mappings)) {+ mappings = parsed.mappings;+ fileSourceDbType = parsed.sourceDbType;+ fileTargetDbType = parsed.targetDbType;+ } else {+ throw new Error("invalid structure");+ }++ const normalized: FieldMappingEntry[] = mappings.map((item: any) => ({+ sourceType: String(item.sourceType ?? ""),+ targetType: String(item.targetType ?? ""),+ paramStrategy: item.paramStrategy === "strip" || item.paramStrategy === "custom" ? item.paramStrategy : "preserve",+ customParams: item.customParams ? String(item.customParams) : undefined,+ }));+ if (normalized.some((m) => !m.sourceType || !m.targetType)) {+ throw new Error("missing sourceType/targetType");+ }++ // Warn if exported source/target types differ from current+ if (fileSourceDbType && fileTargetDbType && (fileSourceDbType !== props.sourceDbType || fileTargetDbType !== props.targetDbType)) {+ toast(t("diff.fieldMapping.importTypeMismatch", { src: fileSourceDbType, tgt: fileTargetDbType }), 5000);+ }++ editingMappings.value = normalized;+ toast(t("diff.fieldMapping.importSuccess"), 2000);+ } catch {+ toast(t("diff.fieldMapping.importError"), 3000);+ } finally {+ input.value = "";+ }+ };+ reader.onerror = () => toast(t("diff.fieldMapping.importError"), 3000);+ reader.readAsText(file);+}++function handleDone() {+ emit(+ "save",+ editingMappings.value.map((m) => ({ ...m })),+ );+ emit("update:open", false);+}++function handleClose() {+ emit("update:open", false);+}+</script>++<template>+ <div v-if="open" class="absolute inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center" @click.self="handleClose">+ <div class="bg-card border rounded-lg shadow-lg w-[760px] max-w-[calc(100vw-2rem)] max-h-[80vh] overflow-auto p-4">+ <div class="flex items-center justify-between mb-4">+ <h3 class="text-sm font-medium">{{ t("diff.fieldMapping.title") }}</h3>+ <Button variant="ghost" size="sm" @click="handleClose">+ <X class="w-3.5 h-3.5" />+ </Button>+ </div>++ <FieldMappingPanel+ :mappings="editingMappings"+ :source-db-type="sourceDbType"+ :target-db-type="targetDbType"+ :source-connection-id="sourceConnectionId"+ :source-database="sourceDatabase"+ :target-connection-id="targetConnectionId"+ :target-database="targetDatabase"+ @update:mappings="handleUpdateMappings"+ />++ <div class="flex items-center justify-between mt-4 pt-3 border-t">+ <div class="flex items-center gap-2">+ <Button variant="outline" size="sm" @click="handleClear" :disabled="editingMappings.length === 0">+ <Trash2 class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.clearMappings") }}+ </Button>+ <Button variant="outline" size="sm" @click="handleImportClick">+ <Upload class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.import") }}+ </Button>+ <Button variant="outline" size="sm" @click="handleExport">+ <Download class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.export") }}+ </Button>+ </div>+ <Button size="sm" @click="handleDone">+ <Check class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.done") }}+ </Button>+ </div>++ <input ref="fileInputRef" type="file" accept=".json,application/json" class="hidden" @change="onFileSelected" />+ </div>+ </div>+</template>diff --git a/apps/desktop/src/components/diff/FieldMappingPanel.vue b/apps/desktop/src/components/diff/FieldMappingPanel.vuenew file mode 100644index 0000000000..936cbe8bb1--- /dev/null+++ b/apps/desktop/src/components/diff/FieldMappingPanel.vue@@ -0,0 +1,286 @@+<script setup lang="ts">+import { computed, ref, watch, onMounted } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";+import { Plus, Trash2, ArrowRight, Wand2 } from "@lucide/vue";+import SearchableSelect from "@/components/ui/searchable-select/SearchableSelect.vue";+import { getDataTypeOptions } from "@/lib/table/tableStructureEditorState";+import * as api from "@/lib/backend/api";+import { useConnectionStore } from "@/stores/connectionStore";+import { findPreset } from "@/lib/fieldMappingPresets";+import type { FieldMappingEntry, FieldMappingParamStrategy } from "@/types/schemaDiff";+import type { DatabaseType } from "@/types/database";++const { t } = useI18n();+const store = useConnectionStore();++const props = defineProps<{+ mappings: FieldMappingEntry[];+ sourceDbType: string;+ targetDbType: string;+ /** Same source as table structure editor: live types via listDataTypes(connection, database). */+ sourceConnectionId?: string;+ sourceDatabase?: string;+ targetConnectionId?: string;+ targetDatabase?: string;+}>();++const emit = defineEmits<{+ (e: "update:mappings", value: FieldMappingEntry[]): void;+}>();++const sameType = computed(() => props.sourceDbType === props.targetDbType);++const sourceTypeOptions = ref<string[]>([]);+const targetTypeOptions = ref<string[]>([]);+const selectedPresetId = ref<string>("");++const availablePresets = computed(() => {+ const preset = findPreset(props.sourceDbType, props.targetDbType);+ return preset ? [preset] : [];+});++/** Same merge semantics as TableStructureEditor (local copy; do not touch structure editor code). */+function mergeDataTypeOptions(primary: readonly string[], fallback: readonly string[]): string[] {+ const seen = new Set<string>();+ const result: string[] = [];+ for (const option of [...primary, ...fallback]) {+ const trimmed = option.trim();+ if (!trimmed) continue;+ const key = trimmed.toLowerCase();+ if (seen.has(key)) continue;+ seen.add(key);+ result.push(trimmed);+ }+ return result;+}++/** Match TableStructureEditor: listDataTypes(connection, database) + getDataTypeOptions(dbType). */+async function loadTypeOptions(dbType: string, connectionId?: string, database?: string): Promise<string[]> {+ const fallback = getDataTypeOptions((dbType || undefined) as DatabaseType | undefined);+ if (!connectionId || !database) {+ return fallback;+ }+ try {+ await store.ensureConnected(connectionId);+ const live = await api.listDataTypes(connectionId, database);+ return mergeDataTypeOptions(live, fallback);+ } catch {+ return fallback;+ }+}++function levenshtein(a: string, b: string): number {+ const m = a.length,+ n = b.length;+ let prev = Array.from({ length: n + 1 }, (_, i) => i);+ for (let i = 1; i <= m; i++) {+ const curr = [i];+ for (let j = 1; j <= n; j++) {+ curr[j] = a[i - 1].toLowerCase() === b[j - 1].toLowerCase() ? prev[j - 1] : Math.min(prev[j], curr[j - 1], prev[j - 1]) + 1;+ }+ prev = curr;+ }+ return prev[n];+}++function nameSimilarity(a: string, b: string): number {+ const maxLen = Math.max(a.length, b.length);+ if (maxLen === 0) return 1;+ return 1 - levenshtein(a, b) / maxLen;+}++function autoGenerateMappings() {+ const srcTypes = sourceTypeOptions.value;+ const tgtTypes = targetTypeOptions.value;+ if (srcTypes.length === 0 || tgtTypes.length === 0) return;++ const used = new Set<string>();+ const result: FieldMappingEntry[] = [];++ for (const src of srcTypes) {+ let bestTarget = "";+ let bestSim = 0;+ for (const tgt of tgtTypes) {+ if (used.has(tgt)) continue;+ const sim = nameSimilarity(src, tgt);+ if (sim > bestSim) {+ bestSim = sim;+ bestTarget = tgt;+ }+ }+ if (bestTarget && bestSim >= 0.3) {+ result.push({ sourceType: src, targetType: bestTarget, paramStrategy: "preserve" });+ used.add(bestTarget);+ }+ }++ if (result.length > 0) {+ emit("update:mappings", result);+ }+}++async function loadSourceTypes() {+ sourceTypeOptions.value = await loadTypeOptions(props.sourceDbType, props.sourceConnectionId, props.sourceDatabase);+}++async function loadTargetTypes() {+ targetTypeOptions.value = await loadTypeOptions(props.targetDbType, props.targetConnectionId, props.targetDatabase);+}++function addMapping() {+ emit("update:mappings", [...props.mappings, { sourceType: "", targetType: "", paramStrategy: "preserve" as FieldMappingParamStrategy }]);+}++function removeMapping(index: number) {+ const next = props.mappings.filter((_, i) => i !== index);+ emit("update:mappings", next);+}++function updateMapping(index: number, field: keyof FieldMappingEntry, value: any) {+ const next = props.mappings.map((m, i) => (i === index ? { ...m, [field]: value } : m));+ emit("update:mappings", next);+}++function applyPreset(presetId: string) {+ selectedPresetId.value = presetId;+ const preset = findPreset(props.sourceDbType, props.targetDbType);+ if (preset) {+ emit("update:mappings", [...preset.mappings]);+ }+}++watch(+ () => [props.sourceDbType, props.sourceConnectionId, props.sourceDatabase] as const,+ () => {+ void loadSourceTypes();+ },+);+watch(+ () => [props.targetDbType, props.targetConnectionId, props.targetDatabase] as const,+ () => {+ void loadTargetTypes();+ },+);++// Auto-generate mappings when both type lists are ready, no preset exists, and no mappings yet+watch([sourceTypeOptions, targetTypeOptions, availablePresets], ([src, tgt, presets]) => {+ if (src.length > 0 && tgt.length > 0 && props.mappings.length === 0 && presets.length === 0 && !sameType.value) {+ autoGenerateMappings();+ }+});++onMounted(() => {+ void loadSourceTypes();+ void loadTargetTypes();+});+</script>++<template>+ <div class="border rounded-lg bg-card">+ <div class="flex items-center gap-2 px-3 py-2 border-b">+ <span class="text-xs font-medium">{{ t("diff.fieldMapping.title") }}</span>+ <span v-if="!sameType" class="flex items-center gap-1 ml-1">+ <span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-300">{{ sourceDbType }}</span>+ <ArrowRight class="w-3 h-3 text-muted-foreground" />+ <span class="px-1.5 py-0.5 rounded text-[10px] font-mono bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300">{{ targetDbType }}</span>+ </span>+ </div>++ <div v-if="sameType" class="px-3 py-4 text-xs text-muted-foreground text-center">+ {{ t("diff.fieldMapping.sameTypeHint") }}+ </div>++ <div v-else class="p-3 max-h-[42vh] overflow-auto">+ <div v-if="availablePresets.length > 0" class="mb-3">+ <label class="text-[10px] font-medium text-muted-foreground mb-1 block">+ {{ t("diff.fieldMapping.preset") }}+ </label>+ <Select :model-value="selectedPresetId" @update:model-value="(v: any) => applyPreset(v)">+ <SelectTrigger class="h-8 w-full text-xs">+ <SelectValue :placeholder="t('diff.fieldMapping.selectPreset')" />+ </SelectTrigger>+ <SelectContent>+ <SelectItem v-for="p in availablePresets" :key="p.id" :value="p.id">{{ p.label }}</SelectItem>+ </SelectContent>+ </Select>+ </div>++ <div v-if="mappings.length === 0" class="flex flex-col items-center justify-center py-6 gap-3">+ <p class="text-xs text-muted-foreground">{{ t("diff.fieldMapping.noMappings") }}</p>+ <Button v-if="availablePresets.length === 0" variant="outline" size="sm" class="h-7 text-xs gap-1" @click="autoGenerateMappings" :disabled="sameType || sourceTypeOptions.length === 0 || targetTypeOptions.length === 0">+ <Wand2 class="w-3.5 h-3.5" />+ {{ t("diff.fieldMapping.autoGenerate") }}+ </Button>+ </div>++ <div v-else class="space-y-3">+ <div class="grid grid-cols-[1fr_auto_1fr_100px_auto] gap-2 items-center px-1">+ <span class="text-[10px] font-medium text-muted-foreground">{{ t("diff.fieldMapping.sourceType") }}</span>+ <div />+ <span class="text-[10px] font-medium text-muted-foreground">{{ t("diff.fieldMapping.targetType") }}</span>+ <span class="text-[10px] font-medium text-muted-foreground">{{ t("diff.fieldMapping.paramStrategy") }}</span>+ <div />+ </div>+ <div v-for="(mapping, i) in mappings" :key="i" class="space-y-1">+ <div class="grid grid-cols-[1fr_auto_1fr_100px_auto] gap-2 items-center">+ <SearchableSelect+ :model-value="mapping.sourceType"+ @update:model-value="(v: string) => updateMapping(i, 'sourceType', v)"+ :options="sourceTypeOptions"+ :placeholder="t('diff.fieldMapping.sourceType')"+ :search-placeholder="t('diff.fieldMapping.sourceType')"+ :empty-text="t('common.noResults')"+ trigger-variant="outline"+ trigger-class="h-8 w-full justify-between text-xs font-mono"+ content-class="w-[var(--reka-popover-trigger-width)]"+ allow-custom+ />+ <ArrowRight class="w-3.5 h-3.5 text-muted-foreground shrink-0" />+ <SearchableSelect+ :model-value="mapping.targetType"+ @update:model-value="(v: string) => updateMapping(i, 'targetType', v)"+ :options="targetTypeOptions"+ :placeholder="t('diff.fieldMapping.targetType')"+ :search-placeholder="t('diff.fieldMapping.targetType')"+ :empty-text="t('common.noResults')"+ trigger-variant="outline"+ trigger-class="h-8 w-full justify-between text-xs font-mono"+ content-class="w-[var(--reka-popover-trigger-width)]"+ allow-custom+ />+ <Select :model-value="mapping.paramStrategy" @update:model-value="(v: any) => updateMapping(i, 'paramStrategy', v)">+ <SelectTrigger class="h-8 w-full text-xs">+ <SelectValue />+ </SelectTrigger>+ <SelectContent>+ <SelectItem value="preserve">{{ t("diff.fieldMapping.strategyPreserve") }}</SelectItem>+ <SelectItem value="strip">{{ t("diff.fieldMapping.strategyStrip") }}</SelectItem>+ <SelectItem value="custom">{{ t("diff.fieldMapping.strategyCustom") }}</SelectItem>+ </SelectContent>+ </Select>+ <Button variant="ghost" size="icon-sm" class="h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive" @click="removeMapping(i)">+ <Trash2 class="w-3.5 h-3.5" />+ </Button>+ </div>+ <div v-if="mapping.paramStrategy === 'custom'" class="flex items-center gap-2 pl-1">+ <input+ :value="mapping.customParams || ''"+ @input="(e: any) => updateMapping(i, 'customParams', (e.target as HTMLInputElement).value)"+ class="h-7 w-32 rounded border border-input bg-background px-2 text-xs font-mono outline-none focus:ring-1 focus:ring-ring"+ :placeholder="t('diff.fieldMapping.customParamsPlaceholder')"+ />+ </div>+ </div>+ </div>++ <div class="mt-3">+ <Button variant="outline" size="sm" class="h-7 text-xs gap-1" @click="addMapping">+ <Plus class="w-3.5 h-3.5" />+ {{ t("diff.fieldMapping.addMapping") }}+ </Button>+ </div>+ </div>+ </div>+</template>diff --git a/apps/desktop/src/components/diff/ImpactReportPanel.vue b/apps/desktop/src/components/diff/ImpactReportPanel.vuenew file mode 100644index 0000000000..e0f2fd42e4--- /dev/null+++ b/apps/desktop/src/components/diff/ImpactReportPanel.vue@@ -0,0 +1,162 @@+<script setup lang="ts">+import { computed } from "vue";+import { useI18n } from "vue-i18n";+import { AlertTriangle, Clock, WifiOff, Zap, Layers, CheckCircle2, XCircle } from "@lucide/vue";++const { t } = useI18n();++interface ImpactReport {+ overallRisk: "safe" | "caution" | "dangerous" | "blocked";+ ddlRiskLevel: "safe" | "caution" | "dangerous" | "blocked";+ estimatedLocks: Array<{ lockType: string; objects: string[]; duration: string }>;+ estimatedTotalDuration: string;+ recommendedStrategy: "online" | "lazy" | "offline" | "batch";+ warnings: string[];+ requiresMaintenanceWindow: boolean;+ isReversible: boolean;+}++const props = defineProps<{+ report: ImpactReport | null;+}>();++const riskColors: Record<string, string> = {+ safe: "#22c55e",+ caution: "#eab308",+ dangerous: "#f97316",+ blocked: "#ef4444",+};++const riskLabels: Record<string, string> = {+ safe: t("impact.riskSafe"),+ caution: t("impact.riskCaution"),+ dangerous: t("impact.riskDangerous"),+ blocked: t("impact.riskBlocked"),+};++const strategyIcons: Record<string, any> = {+ online: Zap,+ lazy: Clock,+ offline: WifiOff,+ batch: Layers,+};++const strategyLabels: Record<string, string> = {+ online: t("impact.strategyOnline"),+ lazy: t("impact.strategyLazy"),+ offline: t("impact.strategyOffline"),+ batch: t("impact.strategyBatch"),+};++const strategyIcon = computed(() => (props.report ? strategyIcons[props.report.recommendedStrategy] : null));+const strategyLabel = computed(() => (props.report ? strategyLabels[props.report.recommendedStrategy] : ""));+</script>++<template>+ <div class="border rounded-md bg-card">+ <!-- Header -->+ <div class="px-3 py-2 border-b">+ <h3 class="text-sm font-medium">{{ t("impact.title") }}</h3>+ </div>++ <!-- No report state -->+ <div v-if="!report" class="flex items-center justify-center py-8 text-sm text-muted-foreground">+ {{ t("impact.noReport") }}+ </div>++ <!-- Report content -->+ <div v-else class="p-3 space-y-4">+ <!-- Risk Summary -->+ <div class="flex items-center gap-4">+ <div class="flex items-center gap-2">+ <span class="text-xs text-muted-foreground">{{ t("impact.overallRisk") }}:</span>+ <span class="px-2 py-0.5 rounded text-[11px] font-semibold text-white" :style="{ backgroundColor: riskColors[report.overallRisk] }">+ {{ riskLabels[report.overallRisk] }}+ </span>+ </div>+ <div class="flex items-center gap-2">+ <span class="text-xs text-muted-foreground">{{ t("impact.ddlRisk") }}:</span>+ <span class="px-2 py-0.5 rounded text-[11px] font-semibold text-white" :style="{ backgroundColor: riskColors[report.ddlRiskLevel] }">+ {{ riskLabels[report.ddlRiskLevel] }}+ </span>+ </div>+ </div>++ <!-- Strategy & Impact Grid -->+ <div class="grid grid-cols-2 gap-3">+ <div class="flex items-center gap-2 p-2 rounded border bg-muted/20">+ <component :is="strategyIcon" class="w-4 h-4 text-primary shrink-0" />+ <div class="min-w-0">+ <div class="text-[10px] text-muted-foreground">{{ t("impact.recommendedStrategy") }}</div>+ <div class="text-xs font-medium truncate">{{ strategyLabel }}</div>+ </div>+ </div>+ <div class="flex items-center gap-2 p-2 rounded border bg-muted/20">+ <Clock class="w-4 h-4 text-muted-foreground shrink-0" />+ <div class="min-w-0">+ <div class="text-[10px] text-muted-foreground">{{ t("impact.estimatedDuration") }}</div>+ <div class="text-xs font-medium truncate">{{ report.estimatedTotalDuration }}</div>+ </div>+ </div>+ <div class="flex items-center gap-2 p-2 rounded border bg-muted/20">+ <component :is="report.requiresMaintenanceWindow ? AlertTriangle : CheckCircle2" class="w-4 h-4 shrink-0" :class="report.requiresMaintenanceWindow ? 'text-amber-500' : 'text-green-500'" />+ <div class="min-w-0">+ <div class="text-[10px] text-muted-foreground">{{ t("impact.maintenanceWindow") }}</div>+ <span class="inline-block px-1.5 py-0.5 rounded text-[10px] font-medium" :class="report.requiresMaintenanceWindow ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300' : 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300'">+ {{ report.requiresMaintenanceWindow ? t("impact.yes") : t("impact.no") }}+ </span>+ </div>+ </div>+ <div class="flex items-center gap-2 p-2 rounded border bg-muted/20">+ <component :is="report.isReversible ? CheckCircle2 : XCircle" class="w-4 h-4 shrink-0" :class="report.isReversible ? 'text-green-500' : 'text-red-500'" />+ <div class="min-w-0">+ <div class="text-[10px] text-muted-foreground">{{ t("impact.reversible") }}</div>+ <span class="inline-block px-1.5 py-0.5 rounded text-[10px] font-medium" :class="report.isReversible ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'">+ {{ report.isReversible ? t("impact.yes") : t("impact.no") }}+ </span>+ </div>+ </div>+ </div>++ <!-- Lock Analysis -->+ <div v-if="report.estimatedLocks.length > 0">+ <h4 class="text-xs font-medium mb-2">{{ t("impact.lockAnalysis") }}</h4>+ <div class="border rounded overflow-hidden">+ <table class="w-full text-xs">+ <thead>+ <tr class="bg-muted/30">+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("impact.lockType") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("impact.lockObjects") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("impact.lockDuration") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(lock, i) in report.estimatedLocks" :key="i" class="border-t">+ <td class="px-2 py-1.5 font-mono">{{ lock.lockType }}</td>+ <td class="px-2 py-1.5">+ <span v-for="(obj, j) in lock.objects" :key="j" class="inline-block mr-1 mb-0.5 px-1.5 py-0.5 rounded bg-muted/40 text-[10px] font-mono">+ {{ obj }}+ </span>+ </td>+ <td class="px-2 py-1.5 text-muted-foreground">{{ lock.duration }}</td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>++ <!-- Warnings -->+ <div v-if="report.warnings.length > 0">+ <h4 class="text-xs font-medium mb-2">{{ t("impact.warnings") }}</h4>+ <div class="space-y-1">+ <div v-for="(warning, i) in report.warnings" :key="i" class="flex items-start gap-2 px-2 py-1.5 rounded text-xs bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-900/30">+ <AlertTriangle class="w-3.5 h-3.5 text-amber-500 shrink-0 mt-0.5" />+ <span>{{ warning }}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<style scoped></style>diff --git a/apps/desktop/src/components/diff/OscStatusPanel.vue b/apps/desktop/src/components/diff/OscStatusPanel.vuenew file mode 100644index 0000000000..028c60d043--- /dev/null+++ b/apps/desktop/src/components/diff/OscStatusPanel.vue@@ -0,0 +1,126 @@+<script setup lang="ts">+import { useI18n } from "vue-i18n";+import { Badge } from "@/components/ui/badge";+import { AlertTriangle, CheckCircle, Clock, Hourglass, Loader2, XCircle } from "@lucide/vue";++type OscExecutionStatus = "preparing" | "copying" | "cut_over" | "completed" | "failed" | "postponed";++interface OscOperation {+ toolType: "gh-ost" | "pt-osc";+ tableName: string;+ status: OscExecutionStatus;+ progressPercent: number;+ estimatedRemainingSecs?: number;+ error?: string;+}++const props = defineProps<{+ operations: OscOperation[];+}>();++const { t } = useI18n();++const statusConfig: Record<OscExecutionStatus, { labelKey: string; icon: any; badgeClass: string; barClass: string }> = {+ preparing: {+ labelKey: "osc.preparing",+ icon: Hourglass,+ badgeClass: "bg-yellow-100 text-yellow-700 dark:bg-yellow-900/30 dark:text-yellow-400",+ barClass: "bg-yellow-500",+ },+ copying: {+ labelKey: "osc.copying",+ icon: Loader2,+ badgeClass: "bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400",+ barClass: "bg-blue-500",+ },+ cut_over: {+ labelKey: "osc.cutOver",+ icon: Clock,+ badgeClass: "bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400",+ barClass: "bg-purple-500",+ },+ completed: {+ labelKey: "osc.completed",+ icon: CheckCircle,+ badgeClass: "bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400",+ barClass: "bg-green-500",+ },+ failed: {+ labelKey: "osc.failed",+ icon: XCircle,+ badgeClass: "bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-400",+ barClass: "bg-red-500",+ },+ postponed: {+ labelKey: "osc.postponed",+ icon: AlertTriangle,+ badgeClass: "bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400",+ barClass: "bg-orange-500",+ },+};++function formatRemaining(seconds?: number): string {+ if (seconds == null) return "-";+ if (seconds < 60) return `${seconds}s`;+ if (seconds < 3600) return `${Math.floor(seconds / 60)}m ${seconds % 60}s`;+ const h = Math.floor(seconds / 3600);+ const m = Math.floor((seconds % 3600) / 60);+ return `${h}h ${m}m`;+}++const toolTypeLabelKey: Record<string, string> = {+ "gh-ost": "osc.ghost",+ "pt-osc": "osc.ptosc",+};+</script>++<template>+ <div class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <h3 class="text-sm font-medium">{{ t("osc.title") }}</h3>+ </div>++ <div v-if="operations.length === 0" class="flex items-center justify-center px-4 py-12 text-xs text-muted-foreground">+ {{ t("osc.noActiveOsc") }}+ </div>++ <div v-else class="divide-y">+ <div v-for="op in operations" :key="`${op.toolType}-${op.tableName}`" class="px-4 py-3">+ <div class="mb-2 flex items-center justify-between">+ <div class="flex items-center gap-2">+ <component :is="statusConfig[op.status].icon" class="h-4 w-4" :class="{ 'animate-spin': op.status === 'copying' }" />+ <span class="text-xs font-medium">{{ op.tableName }}</span>+ <Badge variant="outline" class="text-[10px]">{{ t(toolTypeLabelKey[op.toolType] || op.toolType) }}</Badge>+ </div>+ <span class="inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-medium" :class="statusConfig[op.status].badgeClass">+ <component :is="statusConfig[op.status].icon" class="h-3 w-3" />+ {{ t(statusConfig[op.status].labelKey) }}+ </span>+ </div>++ <div class="mb-1.5 flex items-center gap-3">+ <div class="h-2 flex-1 overflow-hidden rounded-full bg-muted">+ <div class="h-full rounded-full transition-all duration-500" :class="statusConfig[op.status].barClass" :style="{ width: `${Math.min(op.progressPercent, 100)}%` }" />+ </div>+ <span class="w-10 text-right text-[10px] tabular-nums text-muted-foreground">{{ Math.min(op.progressPercent, 100) }}%</span>+ </div>++ <div class="flex items-center justify-between text-[10px] text-muted-foreground">+ <div class="flex items-center gap-1">+ <Clock class="h-3 w-3" />+ <span>{{ t("osc.estimatedRemaining") }}: {{ formatRemaining(op.estimatedRemainingSecs) }}</span>+ </div>+ </div>++ <div v-if="op.status === 'failed' && op.error" class="mt-2 rounded-md bg-destructive/10 px-2.5 py-1.5 text-[10px] text-destructive">+ <div class="flex items-start gap-1.5">+ <AlertTriangle class="mt-0.5 h-3 w-3 shrink-0" />+ <span>{{ op.error }}</span>+ </div>+ </div>+ </div>+ </div>+ </div>+</template>++<style scoped></style>diff --git a/apps/desktop/src/components/diff/RebasePanel.vue b/apps/desktop/src/components/diff/RebasePanel.vuenew file mode 100644index 0000000000..690b73b0a2--- /dev/null+++ b/apps/desktop/src/components/diff/RebasePanel.vue@@ -0,0 +1,144 @@+<script setup lang="ts">+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Badge } from "@/components/ui/badge";+import { AlertTriangle, Check, Clock, Layers, SkipForward } from "@lucide/vue";++interface ConflictItem {+ objectName: string;+ conflictType: string;+ sourceValue: string;+ targetValue: string;+ autoResolvable: boolean;+}++interface RebaseInfo {+ id: string;+ baselineId: string;+ totalObjects: number;+ autoResolvedCount: number;+ conflictCount: number;+ conflicts: ConflictItem[];+ createdAt: string;+}++const props = defineProps<{+ rebaseInfo: RebaseInfo | null;+}>();++const emit = defineEmits<{+ overwriteBaseline: [];+ skipObject: [objectName: string];+}>();++const { t } = useI18n();++function formatDate(iso: string): string {+ try {+ return new Intl.DateTimeFormat(undefined, {+ dateStyle: "medium",+ timeStyle: "short",+ }).format(new Date(iso));+ } catch {+ return iso;+ }+}+</script>++<template>+ <div class="rounded-md border bg-card">+ <div class="border-b px-4 py-3">+ <h3 class="text-sm font-medium">{{ t("rebase.title") }}</h3>+ </div>++ <div v-if="!rebaseInfo" class="flex items-center justify-center px-4 py-12 text-xs text-muted-foreground">+ {{ t("rebase.notes") }}+ </div>++ <template v-else>+ <div class="grid grid-cols-4 gap-4 border-b px-4 py-3">+ <div class="space-y-1">+ <div class="text-xs text-muted-foreground">{{ t("rebase.objectCount") }}</div>+ <div class="text-sm font-medium">{{ rebaseInfo.totalObjects }}</div>+ </div>+ <div class="space-y-1">+ <div class="text-xs text-muted-foreground">{{ t("rebase.autoResolved") }}</div>+ <div class="text-sm font-medium text-green-600 dark:text-green-400">{{ rebaseInfo.autoResolvedCount }}</div>+ </div>+ <div class="space-y-1">+ <div class="text-xs text-muted-foreground">{{ t("rebase.conflictCount") }}</div>+ <div class="text-sm font-medium" :class="rebaseInfo.conflictCount > 0 ? 'text-destructive' : ''">{{ rebaseInfo.conflictCount }}</div>+ </div>+ <div class="space-y-1">+ <div class="text-xs text-muted-foreground">{{ t("rebase.notes") }}</div>+ <div class="flex items-center gap-1.5 text-xs text-muted-foreground">+ <Clock class="h-3 w-3" />+ {{ formatDate(rebaseInfo.createdAt) }}+ </div>+ </div>+ </div>++ <div class="border-b px-4 py-3">+ <div class="mb-2 flex items-center gap-2">+ <Layers class="h-4 w-4 text-muted-foreground" />+ <span class="text-xs font-medium text-muted-foreground">{{ t("rebase.driftReport") }}</span>+ </div>+ <div class="grid grid-cols-2 gap-x-6 gap-y-2 text-xs">+ <div class="flex items-center justify-between">+ <span class="text-muted-foreground">{{ t("rebase.currentBaseline") }}</span>+ <code class="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{{ rebaseInfo.baselineId }}</code>+ </div>+ <div class="flex items-center justify-between">+ <span class="text-muted-foreground">{{ t("rebase.newBaseline") }}</span>+ <code class="rounded bg-muted px-1.5 py-0.5 font-mono text-xs">{{ rebaseInfo.id }}</code>+ </div>+ </div>+ </div>++ <div v-if="rebaseInfo.conflicts.length > 0" class="border-b px-4 py-3">+ <div class="mb-2 flex items-center gap-2">+ <AlertTriangle class="h-4 w-4 text-amber-500" />+ <span class="text-xs font-medium text-muted-foreground">{{ t("rebase.conflicts") }}</span>+ <Badge variant="destructive" class="ml-auto text-xs">{{ rebaseInfo.conflictCount }}</Badge>+ </div>+ <div class="space-y-2">+ <div v-for="(conflict, index) in rebaseInfo.conflicts" :key="conflict.objectName" class="rounded-md border px-3 py-2 text-xs">+ <div class="flex items-center justify-between">+ <div class="flex items-center gap-2">+ <div class="flex h-5 w-5 items-center justify-center rounded-full text-[10px] font-medium" :class="conflict.autoResolvable ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400'">+ {{ index + 1 }}+ </div>+ <span class="font-medium">{{ conflict.objectName }}</span>+ <Badge variant="outline" class="text-[10px]">{{ conflict.conflictType }}</Badge>+ <Badge v-if="conflict.autoResolvable" variant="secondary" class="text-[10px]"> auto </Badge>+ </div>+ <Button size="sm" variant="ghost" class="h-7 gap-1 text-xs" @click="emit('skipObject', conflict.objectName)">+ <SkipForward class="h-3 w-3" />+ {{ t("rebase.skipObject") }}+ </Button>+ </div>+ <div class="mt-1.5 grid grid-cols-2 gap-3">+ <div>+ <div class="text-[10px] text-muted-foreground">Source</div>+ <code class="mt-0.5 block truncate rounded bg-muted/50 px-1 py-0.5 font-mono">{{ conflict.sourceValue }}</code>+ </div>+ <div>+ <div class="text-[10px] text-muted-foreground">Target</div>+ <code class="mt-0.5 block truncate rounded bg-muted/50 px-1 py-0.5 font-mono">{{ conflict.targetValue }}</code>+ </div>+ </div>+ </div>+ </div>+ </div>++ <div class="flex items-center justify-end gap-2 px-4 py-3">+ <Button size="sm" class="gap-1.5 text-xs" @click="emit('overwriteBaseline')">+ <Check class="h-3.5 w-3.5" />+ {{ t("rebase.overwriteBaseline") }}+ </Button>+ </div>+ </template>+ </div>+</template>++<style scoped></style>diff --git a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vueindex c47db733b3..73a8d31e8d 100644--- a/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue+++ b/apps/desktop/src/components/diff/SchemaDiffConfigStep.vue@@ -11,7 +11,7 @@ import DatabaseIcon from "@/components/icons/DatabaseIcon.vue";import * as api from "@/lib/backend/api";import { isSchemaAware } from "@/lib/database/databaseCapabilities";import { ArrowLeftRight, GitCompareArrows, Save, FolderOpen, Settings, X } from "@lucide/vue";-import type { SchemaDiffConfig, SchemaDiffCompareOptions } from "@/types/schemaDiff";+import type { SchemaDiffConfig, SchemaDiffCompareOptions, FieldMappingEntry } from "@/types/schemaDiff";const { t } = useI18n();const store = useConnectionStore();@@ -39,6 +39,8 @@ const emit = defineEmits<{(e: "update:targetDatabase", value: string): void;(e: "update:targetSchema", value: string): void;(e: "update:ignoreComments", value: boolean): void;+ (e: "update:fieldMappings", value: FieldMappingEntry[]): void;+ (e: "open-field-mapping"): void;(e: "compare"): void;(e: "saveConfig"): void;(e: "loadConfig"): void;@@ -60,6 +62,11 @@ const sqlConnections = computed(() => store.connections.filter((c: any) => !["moconst sourceConfig = computed(() => store.getConfig(props.sourceConnectionId));const targetConfig = computed(() => store.getConfig(props.targetConnectionId));+const sourceDbType = computed(() => sourceConfig.value?.db_type || "");+const targetDbType = computed(() => targetConfig.value?.db_type || "");+const showFieldMapping = computed(() => sourceDbType.value && targetDbType.value && sourceDbType.value !== targetDbType.value);+const activeFieldMappings = computed(() => props.options?.fieldMappings ?? []);+const canCompare = computed(() => {return props.sourceConnectionId && props.targetConnectionId && props.sourceDatabase && props.targetDatabase && (!isSchemaAware(sourceConfig.value?.db_type) || props.sourceSchema) && (!isSchemaAware(targetConfig.value?.db_type) || props.targetSchema);});@@ -473,6 +480,11 @@ async function fetchDbVersion(connectionId: string, database: string, schema: st<Settings class="w-3.5 h-3.5 mr-1" />{{ t("diff.options") }}</Button>+ <Button v-if="showFieldMapping" variant="outline" size="sm" @click="$emit('open-field-mapping')">+ <ArrowLeftRight class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.openFieldMapping") }}+ <span v-if="activeFieldMappings.length > 0" class="ml-1 inline-flex items-center justify-center rounded-full bg-primary/10 px-1.5 py-0.5 text-[10px] font-medium text-primary">{{ activeFieldMappings.length }}</span>+ </Button></div><Button size="sm" :disabled="!canCompare || loading" @click="$emit('compare')"><GitCompareArrows class="w-3.5 h-3.5 mr-1" />diff --git a/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue b/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vueindex 894c486aea..1673a436a5 100644--- a/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue@@ -9,10 +9,10 @@ import { DEFAULT_CUSTOM_THEME_DDL_COLORS } from "@/stores/settingsStore";import { useDiffScrollSync } from "@/composables/useDiffScrollSync";import { buildHunks, type DiffLine } from "@/components/diff/DiffHunkBuilder";import DiffSvgConnector from "@/components/diff/DiffSvgConnector.vue";-import { FileCode, ScrollText, Copy, Play } from "@lucide/vue";+import { FileCode, ScrollText, Copy, Play, FileDiff } from "@lucide/vue";import { Splitpanes, Pane } from "splitpanes";import "splitpanes/dist/splitpanes.css";-import type { SchemaDiffObject } from "@/lib/schema/schemaDiff";+import type { SchemaDiffObject, CompatibilityWarning, DependencyGraph, PermissionDiff, MissingRollbackObject, RollbackCompleteness } from "@/lib/schema/schemaDiff";const { t } = useI18n();const { toast } = useToast();@@ -36,19 +36,39 @@ const props = defineProps<{selectedObject: SchemaDiffObject | null;deploySql: string;deploySqlAll: string;+ compatibilityWarnings?: CompatibilityWarning[];+ rollbackSql?: string;+ deploySqlMode?: "forward" | "rollback";+ dependencyGraph?: DependencyGraph | null;+ permissionDiffs?: PermissionDiff[];+ rollbackCompleteness?: RollbackCompleteness;+ missingRollbackObjects?: MissingRollbackObject[];+ canExecute?: boolean;}>();const emit = defineEmits<{executeScript: [];+ "update:deploySqlMode": [mode: "forward" | "rollback"];}>();-const activeTab = ref<"ddl" | "script" | "scriptAll">("ddl");+const activeTab = ref<"ddl" | "script" | "scriptAll" | "warnings" | "depGraph" | "permissions" | "rollbackCompare">("ddl");const diffContainerRef = ref<HTMLDivElement>();const leftPaneRef = ref<HTMLDivElement>();const rightPaneRef = ref<HTMLDivElement>();const containerSize = ref({ width: 0, height: 0 });const connectorKey = ref(0);+const rollbackDiffContainerRef = ref<HTMLDivElement>();+const rollbackLeftPaneRef = ref<HTMLDivElement>();+const rollbackRightPaneRef = ref<HTMLDivElement>();+const rollbackContainerSize = ref({ width: 0, height: 0 });+const rollbackConnectorKey = ref(0);++const rollbackHunks = computed(() => {+ if (!props.rollbackSql) return [];+ return buildHunks(props.deploySql, props.rollbackSql);+});+const hunks = computed(() => {if (!props.selectedObject?.sourceDdl && !props.selectedObject?.targetDdl) return [];return buildHunks(props.selectedObject?.sourceDdl || "", props.selectedObject?.targetDdl || "");@@ -61,6 +81,13 @@ const { syncScroll, measureHunks } = useDiffScrollSync({hunks,});+const { syncScroll: rollbackSyncScroll, measureHunks: rollbackMeasureHunks } = useDiffScrollSync({+ container: rollbackDiffContainerRef,+ leftPane: rollbackLeftPaneRef,+ rightPane: rollbackRightPaneRef,+ hunks: rollbackHunks,+});+// Cache char-level diff segments so we don't recompute on every renderconst modifySegments = computed(() => {const map = new Map<string, { leftSegments: Segment[]; rightSegments: Segment[] }>();@@ -77,6 +104,21 @@ const modifySegments = computed(() => {return map;});+const rollbackModifySegments = computed(() => {+ const map = new Map<string, { leftSegments: Segment[]; rightSegments: Segment[] }>();+ for (const hunk of rollbackHunks.value) {+ if (hunk.type !== "modify") continue;+ for (let i = 0; i < hunk.leftLines.length; i++) {+ const left = hunk.leftLines[i];+ const right = hunk.rightLines[i];+ if (left.isPadding || right.isPadding) continue;+ const key = `${hunk.id}:${i}`;+ map.set(key, renderModifyLine(left, right));+ }+ }+ return map;+});+let measureRaf: number | null = null;let measureTimeout: ReturnType<typeof setTimeout> | null = null;@@ -101,6 +143,37 @@ function handleScroll(from: "left" | "right") {requestMeasureDebounced();}+let rollbackMeasureRaf: number | null = null;+let rollbackMeasureTimeout: ReturnType<typeof setTimeout> | null = null;++function rollbackRequestMeasure() {+ if (rollbackMeasureRaf) return;+ rollbackMeasureRaf = requestAnimationFrame(() => {+ rollbackMeasureRaf = null;+ rollbackMeasureHunks();+ rollbackConnectorKey.value++;+ });+}++function rollbackRequestMeasureDebounced() {+ if (rollbackMeasureTimeout) clearTimeout(rollbackMeasureTimeout);+ rollbackMeasureTimeout = setTimeout(() => {+ rollbackRequestMeasure();+ }, 100);+}++function rollbackHandleScroll(from: "left" | "right") {+ rollbackSyncScroll(from);+ rollbackRequestMeasureDebounced();+}++function rollbackUpdateContainerSize() {+ const el = rollbackDiffContainerRef.value;+ if (!el) return;+ const rect = el.getBoundingClientRect();+ rollbackContainerSize.value = { width: rect.width, height: rect.height };+}+watch(() => props.selectedObject?.id,async () => {@@ -122,6 +195,11 @@ function onSplitpanesResized() {requestMeasure();}+function rollbackOnSplitpanesResized() {+ rollbackUpdateContainerSize();+ rollbackRequestMeasure();+}+function lineBackground(line: DiffLine): string | undefined {if (line.isPadding) return undefined;if (line.type === "delete") {@@ -232,6 +310,19 @@ function copyDeploySqlAll() {<template><div class="border rounded-md flex flex-col h-full">+ <!-- Forward / Rollback SQL mode toggle -->+ <div v-if="rollbackSql" class="flex items-center gap-1 px-3 py-1 border-b bg-muted/20 shrink-0">+ <span class="text-[11px] text-muted-foreground mr-2">{{ t("diff.deployMode") }}:</span>+ <button class="text-xs px-2 py-1 rounded transition-colors" :class="deploySqlMode === 'forward' ? 'bg-primary text-primary-foreground' : 'hover:bg-accent'" @click="$emit('update:deploySqlMode', 'forward')">{{ t("diff.forwardSql") }}</button>+ <button class="text-xs px-2 py-1 rounded transition-colors" :class="deploySqlMode === 'rollback' ? 'bg-destructive text-destructive-foreground' : 'hover:bg-accent'" @click="$emit('update:deploySqlMode', 'rollback')">{{ t("diff.rollbackSql") }}</button>+ </div>++ <div v-if="rollbackCompleteness === 'incomplete'" class="px-3 py-1.5 border-b bg-amber-50 dark:bg-amber-950/30 text-xs text-amber-800 dark:text-amber-200 shrink-0">+ {{ t("diff.rollbackIncompleteBanner") }}+ <ul v-if="missingRollbackObjects?.length" class="mt-1 list-disc pl-4">+ <li v-for="(m, i) in missingRollbackObjects" :key="i">{{ m.kind }} {{ m.name }}{{ m.table ? ` @ ${m.table}` : "" }} — {{ m.reason }}</li>+ </ul>+ </div><!-- Tabs --><div class="flex border-b shrink-0"><button class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'ddl' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'ddl'">@@ -246,6 +337,29 @@ function copyDeploySqlAll() {<ScrollText class="w-3.5 h-3.5" />{{ t("diff.deployScriptAll") }}</button>+ <button v-if="rollbackSql" class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'rollbackCompare' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'rollbackCompare'">+ <FileDiff class="w-3.5 h-3.5" />+ {{ t("rollbackComparison.title") }}+ </button>+ <button+ v-if="compatibilityWarnings && compatibilityWarnings.length > 0"+ class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors relative"+ :class="activeTab === 'warnings' ? 'bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-300 border-b-2 border-amber-500' : 'hover:bg-muted/50'"+ @click="activeTab = 'warnings'"+ >+ <span class="w-2 h-2 rounded-full bg-amber-500 shrink-0" />+ {{ t("diff.compatibilityWarnings") }}+ <span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] bg-amber-500 text-white font-bold">{{ compatibilityWarnings.length }}</span>+ </button>+ <button v-if="dependencyGraph && dependencyGraph.nodes.length > 0" class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'depGraph' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'depGraph'">+ <span class="w-2 h-2 rounded-full bg-blue-500 shrink-0" />+ {{ t("diff.dependencyGraph") }}+ </button>+ <button v-if="permissionDiffs && permissionDiffs.length > 0" class="px-3 py-1.5 text-xs font-medium flex items-center gap-1 transition-colors" :class="activeTab === 'permissions' ? 'bg-primary/10 text-primary border-b-2 border-primary' : 'hover:bg-muted/50'" @click="activeTab = 'permissions'">+ <span class="w-2 h-2 rounded-full bg-purple-500 shrink-0" />+ {{ t("diff.operation") }}+ <span class="ml-1 px-1.5 py-0.5 rounded-full text-[10px] bg-purple-500 text-white font-bold">{{ permissionDiffs.length }}</span>+ </button></div><!-- DDL Compare -->@@ -335,6 +449,82 @@ function copyDeploySqlAll() {</div></div>+ <!-- Rollback Comparison -->+ <div v-else-if="activeTab === 'rollbackCompare'" class="flex-1 overflow-hidden relative">+ <div v-if="!rollbackSql" class="absolute inset-0 flex items-center justify-center text-sm text-muted-foreground">+ {{ t("diff.noDdlAvailable") }}+ </div>+ <div v-else ref="rollbackDiffContainerRef" class="absolute inset-0 font-mono text-xs leading-relaxed">+ <Splitpanes class="h-full" @resized="rollbackOnSplitpanesResized">+ <Pane min-size="20">+ <div ref="rollbackLeftPaneRef" class="h-full overflow-y-auto border-r" @scroll="rollbackHandleScroll('left')">+ <div class="sticky top-0 bg-muted/50 px-3 py-1.5 text-xs font-medium border-b z-10">+ {{ t("rollbackComparison.forwardSql") }}+ </div>+ <div v-for="hunk in rollbackHunks" :key="`left-${hunk.id}`" :data-hunk-id="hunk.id">+ <div+ v-for="(line, idx) in hunk.leftLines"+ :key="`l-${hunk.id}-${idx}`"+ class="flex min-h-[1.5em]"+ :class="{+ 'border-l border-r border-yellow-500/40': hunk.type === 'modify',+ 'border-t rounded-t-sm': hunk.type === 'modify' && idx === 0,+ 'border-b rounded-b-sm': hunk.type === 'modify' && idx === hunk.leftLines.length - 1,+ }"+ :style="{ backgroundColor: lineBackground(line) }"+ >+ <span class="text-muted-foreground w-8 text-right pr-2 select-none shrink-0">+ {{ line.lineNumber ?? "" }}+ </span>+ <span class="flex-1 px-1 whitespace-pre" :class="lineTextClass(line)">+ <template v-if="line.type === 'modify' && !line.isPadding">+ <template v-for="(segment, si) in rollbackModifySegments.get(`${hunk.id}:${idx}`)?.leftSegments ?? []" :key="`ls-${si}`">+ <span :style="segment.changed ? { backgroundColor: toRgba(ddlColors.modifiedCharBg, ddlColors.modifiedCharBgAlpha) } : undefined">{{ segment.text }}</span>+ </template>+ </template>+ <span v-else>{{ line.isPadding ? "\u00A0" : line.content }}</span>+ </span>+ </div>+ </div>+ </div>+ </Pane>+ <Pane min-size="20">+ <div ref="rollbackRightPaneRef" class="h-full overflow-y-auto" @scroll="rollbackHandleScroll('right')">+ <div class="sticky top-0 bg-muted/50 px-3 py-1.5 text-xs font-medium border-b z-10">+ {{ t("rollbackComparison.rollbackSql") }}+ </div>+ <div v-for="hunk in rollbackHunks" :key="`right-${hunk.id}`" :data-hunk-id="hunk.id">+ <div+ v-for="(line, idx) in hunk.rightLines"+ :key="`r-${hunk.id}-${idx}`"+ class="flex min-h-[1.5em]"+ :class="{+ 'border-l border-r border-yellow-500/40': hunk.type === 'modify',+ 'border-t rounded-t-sm': hunk.type === 'modify' && idx === 0,+ 'border-b rounded-b-sm': hunk.type === 'modify' && idx === hunk.rightLines.length - 1,+ }"+ :style="{ backgroundColor: lineBackground(line) }"+ >+ <span class="text-muted-foreground w-8 text-right pr-2 select-none shrink-0">+ {{ line.lineNumber ?? "" }}+ </span>+ <span class="flex-1 px-1 whitespace-pre" :class="lineTextClass(line)">+ <template v-if="line.type === 'modify' && !line.isPadding">+ <template v-for="(segment, si) in rollbackModifySegments.get(`${hunk.id}:${idx}`)?.rightSegments ?? []" :key="`rs-${si}`">+ <span :style="segment.changed ? { backgroundColor: toRgba(ddlColors.modifiedCharBg, ddlColors.modifiedCharBgAlpha) } : undefined">{{ segment.text }}</span>+ </template>+ </template>+ <span v-else>{{ line.isPadding ? "\u00A0" : line.content }}</span>+ </span>+ </div>+ </div>+ </div>+ </Pane>+ </Splitpanes>+ <DiffSvgConnector :key="rollbackConnectorKey" :hunks="rollbackHunks" :container-width="rollbackContainerSize.width" :container-height="rollbackContainerSize.height" />+ </div>+ </div>+<!-- Deploy Script --><div v-else-if="activeTab === 'script'" class="flex-1 flex flex-col overflow-hidden"><div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0">@@ -344,7 +534,7 @@ function copyDeploySqlAll() {<Copy class="w-3 h-3" />{{ t("diff.copy") }}</Button>- <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" @click="$emit('executeScript')">+ <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" :disabled="canExecute === false" @click="$emit('executeScript')"><Play class="w-3 h-3" />{{ t("diff.execute") }}</Button>@@ -355,6 +545,63 @@ function copyDeploySqlAll() {</div></div>+ <!-- Compatibility Warnings -->+ <div v-else-if="activeTab === 'warnings'" class="flex-1 flex flex-col overflow-hidden p-3">+ <div v-if="compatibilityWarnings && compatibilityWarnings.length > 0" class="space-y-2">+ <div v-for="(w, i) in compatibilityWarnings" :key="i" class="flex items-start gap-2 p-2 rounded border bg-amber-50 dark:bg-amber-950/20 text-xs">+ <span class="shrink-0 w-2 h-2 rounded-full mt-0.5" :class="w.risk === 'high' ? 'bg-red-500' : w.risk === 'medium' ? 'bg-amber-500' : 'bg-yellow-400'" />+ <div class="min-w-0">+ <span class="font-medium">{{ w.table }}.{{ w.column }}</span+ >:+ <span class="text-muted-foreground">{{ w.sourceType }} → {{ w.targetType }}</span>+ <p class="text-muted-foreground mt-0.5">{{ w.message }}</p>+ </div>+ </div>+ </div>+ <div v-else class="flex-1 flex items-center justify-center text-sm text-muted-foreground">+ {{ t("diff.noDifferences") }}+ </div>+ </div>++ <!-- Dependency Graph -->+ <div v-else-if="activeTab === 'depGraph'" class="flex-1 flex flex-col overflow-hidden p-3">+ <div v-if="dependencyGraph && dependencyGraph.nodes.length > 0" class="space-y-1">+ <div v-for="node in dependencyGraph.nodes" :key="node.tableName" class="py-1 text-xs">+ <span class="font-mono font-medium">{{ node.tableName }}</span>+ <span v-if="node.dependsOn.length > 0" class="text-muted-foreground ml-2">+ → {{ t("diff.dependsOn") }}: <span class="font-mono">{{ node.dependsOn.join(", ") }}</span>+ </span>+ <span v-if="node.dependedBy.length > 0" class="text-muted-foreground ml-2">+ ← {{ t("diff.dependedBy") }}: <span class="font-mono">{{ node.dependedBy.join(", ") }}</span>+ </span>+ </div>+ </div>+ <div v-else class="flex-1 flex items-center justify-center text-sm text-muted-foreground">+ {{ t("diff.noDifferences") }}+ </div>+ </div>++ <!-- Permissions -->+ <div v-else-if="activeTab === 'permissions'" class="flex-1 flex flex-col overflow-hidden p-3">+ <div v-if="permissionDiffs && permissionDiffs.length > 0" class="space-y-2">+ <div v-for="(pd, i) in permissionDiffs" :key="i" class="flex items-start gap-2 p-2 rounded border text-xs">+ <span class="shrink-0 w-2 h-2 rounded-full mt-0.5 bg-purple-500" />+ <div class="min-w-0">+ <span class="font-medium">{{ pd.objectName }}</span>+ <span class="text-muted-foreground"> — {{ pd.permissionType }}</span>+ <div class="mt-0.5">+ <span v-if="pd.sourcePermission" class="text-green-600 dark:text-green-400">{{ t("diff.source") }}: {{ pd.sourcePermission }}</span>+ <span v-if="pd.sourcePermission && pd.targetPermission" class="text-muted-foreground mx-1">→</span>+ <span v-if="pd.targetPermission" class="text-red-600 dark:text-red-400">{{ t("diff.target") }}: {{ pd.targetPermission }}</span>+ </div>+ </div>+ </div>+ </div>+ <div v-else class="flex-1 flex items-center justify-center text-sm text-muted-foreground">+ {{ t("diff.noDifferences") }}+ </div>+ </div>+<!-- Deploy Script All --><div v-else-if="activeTab === 'scriptAll'" class="flex-1 flex flex-col overflow-hidden"><div class="flex items-center justify-between px-3 py-1.5 border-b shrink-0">@@ -364,7 +611,7 @@ function copyDeploySqlAll() {<Copy class="w-3 h-3" />{{ t("diff.copy") }}</Button>- <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" @click="$emit('executeScript')">+ <Button variant="ghost" size="sm" class="h-6 px-2 text-xs gap-1" :disabled="canExecute === false" @click="$emit('executeScript')"><Play class="w-3 h-3" />{{ t("diff.executeAll") }}</Button>diff --git a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vueindex 50405bb143..1d92f7bd13 100644--- a/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDeployStep.vue@@ -9,13 +9,15 @@ import { useTheme } from "@/composables/useTheme";import { loadEditorTheme, editorFontTheme } from "@/lib/editor/editorThemes";import { createDbxCodeMirrorSqlDialect } from "@/lib/editor/codemirrorSqlDialect";import { Splitpanes, Pane } from "splitpanes";-import type { SchemaDiffObject, DiffOperationType, DiffObjectKind } from "@/lib/schema/schemaDiff";-import { ArrowLeft, Copy, Download, Play, Loader2, PlusCircle, XCircle, ArrowRightLeft, Table, Eye, FunctionSquare, ListOrdered, ScrollText, UserCog, ListTree, Link2, Zap } from "@lucide/vue";+import type { SchemaDiffObject, DiffOperationType, DiffObjectKind, CompatibilityWarning, RenameCandidate, MissingRollbackObject, RollbackCompleteness } from "@/lib/schema/schemaDiff";+import ImpactReportPanel from "@/components/diff/ImpactReportPanel.vue";+import type { ImpactReport } from "@/types/governance";+import { ArrowLeft, Copy, Download, Play, Loader2, PlusCircle, XCircle, ArrowRightLeft, Table, Eye, FunctionSquare, ListOrdered, ScrollText, UserCog, ListTree, Link2, Zap, AlertTriangle, ShieldCheck } from "@lucide/vue";const { t } = useI18n();const { toast } = useToast();const settingsStore = useSettingsStore();-const { isDark, themePalette } = useTheme();+const { isDark } = useTheme();const props = defineProps<{deploySql: string;@@ -24,10 +26,19 @@ const props = defineProps<{targetDatabase: string;targetSchema: string;executing: boolean;+ rollbackSql?: string;+ deploySqlMode?: "forward" | "rollback";+ compatibilityWarnings?: CompatibilityWarning[];+ renameCandidates?: RenameCandidate[];+ impactReport?: ImpactReport | null;+ rollbackCompleteness?: RollbackCompleteness;+ missingRollbackObjects?: MissingRollbackObject[];+ canExecute?: boolean;}>();const emit = defineEmits<{"update:deploySql": [sql: string];+ "update:deploySqlMode": [mode: "forward" | "rollback"];back: [];deploy: [];}>();@@ -92,6 +103,24 @@ const operationCounts = computed(() => {return counts;});+const riskLevel = computed(() => {+ const count = props.compatibilityWarnings?.length ?? 0;+ if (count === 0) return "safe";+ if (count <= 3) return "caution";+ return "dangerous";+});++const renameCount = computed(() => props.renameCandidates?.length ?? 0);++const showImpactReport = ref(false);++const effectiveSql = computed(() => {+ if (props.deploySqlMode === "rollback" && props.rollbackSql) {+ return props.rollbackSql;+ }+ return props.deploySql;+});+const operationIcons: Record<DiffOperationType, any> = {modify: ArrowRightLeft,create: PlusCircle,@@ -120,13 +149,13 @@ async function initEditor() {const fontSize = settingsStore.editorSettings.fontSize;const fontFamily = settingsStore.editorSettings.fontFamily;- const themeExt = await loadEditorTheme(editorTheme, appAppearance, undefined, themePalette.value);+ const themeExt = await loadEditorTheme(editorTheme, appAppearance);const fontExt = editorFontTheme(EditorView, fontSize, fontFamily, { fixedHeight: true, scrollable: true });const dialect = createDbxCodeMirrorSqlDialect(langSql, "postgres");const state = EditorState.create({- doc: props.deploySql,+ doc: effectiveSql.value,extensions: [basicSetup,langSql.sql({ dialect }),@@ -144,9 +173,9 @@ async function initEditor() {isEditorReady.value = true;}-// Watch for external deploySql changes+// Watch for external deploySql changes (including mode switch)watch(- () => props.deploySql,+ () => effectiveSql.value,(newVal) => {if (editorView.value && editorView.value.state.doc.toString() !== newVal) {editorView.value.dispatch({@@ -271,14 +300,38 @@ function getObjectIconColor(kind: DiffObjectKind): string {</Button><span class="text-sm font-medium">{{ t("diff.deployReview") }}</span><span class="text-xs text-muted-foreground"> ({{ t("diff.selectedCount", { selected: topLevelObjects.length, total: topLevelObjects.length }) }}) </span>+ <!-- Risk level badge -->+ <span v-if="riskLevel !== 'safe'" class="flex items-center gap-1 px-2 py-0.5 rounded text-[10px] font-medium" :class="riskLevel === 'dangerous' ? 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300' : 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300'">+ <AlertTriangle class="w-3 h-3" />+ {{ riskLevel === "dangerous" ? t("diff.riskLevel.dangerous", { count: compatibilityWarnings?.length ?? 0 }) : t("diff.riskLevel.caution", { count: compatibilityWarnings?.length ?? 0 }) }}+ </span></div><div class="flex items-center gap-3 text-xs"><span class="text-green-500">{{ t("diff.create") }}: {{ operationCounts.create }}</span><span class="text-blue-500">{{ t("diff.modify") }}: {{ operationCounts.modify }}</span><span class="text-red-500">{{ t("diff.delete") }}: {{ operationCounts.delete }}</span>+ <span v-if="renameCount > 0" class="text-purple-500">{{ t("diff.renameCount", { count: renameCount }) }}</span>+ </div>+ </div>++ <!-- Impact Report toggle -->+ <div v-if="impactReport" class="border-b shrink-0">+ <button class="flex items-center gap-2 w-full px-3 py-1.5 text-xs hover:bg-accent/50 transition-colors" @click="showImpactReport = !showImpactReport">+ <ShieldCheck class="w-3.5 h-3.5" :class="impactReport.overallRisk === 'safe' ? 'text-green-500' : impactReport.overallRisk === 'caution' ? 'text-yellow-500' : impactReport.overallRisk === 'dangerous' ? 'text-orange-500' : 'text-red-500'" />+ <span class="font-medium">{{ t("impact.title") }}</span>+ <span class="ml-auto text-muted-foreground">{{ showImpactReport ? "▲" : "▼" }}</span>+ </button>+ <div v-if="showImpactReport" class="border-t">+ <ImpactReportPanel :report="impactReport" /></div></div>+ <div v-if="rollbackCompleteness === 'incomplete' && deploySqlMode === 'rollback'" class="px-3 py-1.5 border-b bg-amber-50 dark:bg-amber-950/30 text-xs text-amber-800 dark:text-amber-200 shrink-0">+ {{ t("diff.rollbackIncompleteBanner") }}+ <ul v-if="missingRollbackObjects?.length" class="mt-1 list-disc pl-4">+ <li v-for="(m, i) in missingRollbackObjects" :key="i">{{ m.kind }} {{ m.name }}{{ m.table ? ` @ ${m.table}` : "" }} — {{ m.reason }}</li>+ </ul>+ </div><!-- Content --><Splitpanes class="flex-1 min-h-0"><Pane size="30" min-size="20">@@ -305,6 +358,11 @@ function getObjectIconColor(kind: DiffObjectKind): string {<!-- Footer --><div class="flex items-center justify-between px-3 py-2 border-t shrink-0 gap-2"><div class="flex items-center gap-2">+ <!-- SQL mode toggle -->+ <div v-if="props.rollbackSql" class="flex items-center gap-1 mr-2 border rounded">+ <button class="text-xs px-2 py-1 rounded transition-colors" :class="props.deploySqlMode === 'forward' ? 'bg-primary text-primary-foreground' : 'hover:bg-accent'" @click="$emit('update:deploySqlMode', 'forward')">{{ t("diff.deployMode") }}</button>+ <button class="text-xs px-2 py-1 rounded transition-colors" :class="props.deploySqlMode === 'rollback' ? 'bg-destructive text-destructive-foreground' : 'hover:bg-accent'" @click="$emit('update:deploySqlMode', 'rollback')">{{ t("diff.rollbackMode") }}</button>+ </div><Button variant="outline" size="sm" class="h-7 text-xs gap-1" @click="handleCopy"><Copy class="w-3.5 h-3.5" />{{ t("diff.copyScript") }}@@ -322,7 +380,7 @@ function getObjectIconColor(kind: DiffObjectKind): string {<Button variant="ghost" size="sm" class="h-7 text-xs" @click="$emit('back')">{{ t("diff.cancel") }}</Button>- <Button size="sm" class="h-7 text-xs gap-1" :disabled="topLevelObjects.length === 0 || executing" @click="handleDeploy">+ <Button size="sm" class="h-7 text-xs gap-1" :disabled="topLevelObjects.length === 0 || executing || canExecute === false" @click="handleDeploy"><Loader2 v-if="executing" class="w-3.5 h-3.5 animate-spin" /><Play v-else class="w-3.5 h-3.5" />{{ t("diff.deployToServer") }}diff --git a/apps/desktop/src/components/diff/SchemaDiffDialog.vue b/apps/desktop/src/components/diff/SchemaDiffDialog.vueindex 79d8725049..d71898c7b7 100644--- a/apps/desktop/src/components/diff/SchemaDiffDialog.vue+++ b/apps/desktop/src/components/diff/SchemaDiffDialog.vue@@ -5,22 +5,44 @@ import { Dialog, DialogHeader, DialogTitle, DialogFooter, DialogContent } from "import { Button } from "@/components/ui/button";import { useConnectionStore } from "@/stores/connectionStore";import { useToast } from "@/composables/useToast";-import { GitCompareArrows, ArrowLeft, Play, Loader2, Maximize2, Minimize2, AlertTriangle, CircleCheck } from "@lucide/vue";+import { GitCompareArrows, ArrowLeft, Play, Loader2, Maximize2, Minimize2, AlertTriangle, CircleCheck, ChevronDown, ChevronRight } from "@lucide/vue";import * as api from "@/lib/backend/api";import { executeWithProductionSqlGuard } from "@/lib/database/productionExecutionGuard";import { useSchemaDiffConfig } from "@/composables/useSchemaDiffConfig";import SchemaDiffConfigStep from "@/components/diff/SchemaDiffConfigStep.vue";+import FieldMappingDialog from "@/components/diff/FieldMappingDialog.vue";import SchemaDiffObjectTree from "@/components/diff/SchemaDiffObjectTree.vue";import SchemaDiffDdlPanel from "@/components/diff/SchemaDiffDdlPanel.vue";import SchemaDiffDeployStep from "@/components/diff/SchemaDiffDeployStep.vue";import SchemaDiffOptionsPanel from "@/components/diff/SchemaDiffOptionsPanel.vue";import { getSchemaDiffOptionsForDbType } from "@/lib/schema/schemaDiffOptions";+import { buildDeployTxResult } from "@/lib/schema/deployTxResult";import { createConcurrencyLimiter, mapWithConcurrency, schemaDiffMetadataConcurrency, shouldFetchSchemaDiffDdl } from "@/lib/schema/schemaDiffMetadataLoad";import { normalizeSchemaDiffCompareOptions } from "@/types/schemaDiff";-import type { SchemaDiffCompareOptions, SchemaDiffConfig } from "@/types/schemaDiff";+import type { SchemaDiffCompareOptions, SchemaDiffConfig, FieldMappingEntry } from "@/types/schemaDiff";import type { ObjectSourceKind, TableInfo } from "@/types/database";-import { buildDeploySqlForObjects, convertToSchemaDiffObjects, groupDiffObjects, schemaDiffDeployTargetSchema, type OperationGroup, type SchemaDiffObject, type DiffOperationType, type DiffObjectKind, type SchemaDiffPreparation, type TableSchemaDetail } from "@/lib/schema/schemaDiff";+import {+ buildDeploySqlForObjects,+ convertToSchemaDiffObjects,+ groupDiffObjects,+ injectColumnRenameSql,+ schemaDiffDeployTargetSchema,+ databaseTypeToDialectKind,+ normalizeDialectKind,+ type OperationGroup,+ type SchemaDiffObject,+ type DiffOperationType,+ type DiffObjectKind,+ type SchemaDiffPreparation,+ type MissingRollbackObject,+ type RollbackCompleteness,+ type TableSchemaDetail,+ type RenameCandidate,+ type CompatibilityWarning,+ type PermissionDiff,+ type DependencyGraph,+} from "@/lib/schema/schemaDiff";import { compileSchemaDiffTableFilter, filterSchemaDiffTables } from "@/lib/schema/schemaDiffTableFilter";import { Splitpanes, Pane } from "splitpanes";import "splitpanes/dist/splitpanes.css";@@ -53,6 +75,16 @@ const ignoreComments = ref(false);// Options panelconst showOptionsPanel = ref(false);+const showFieldMappingDialog = ref(false);+const sourceDbType = computed(() => store.getConfig(sourceConnectionId.value)?.db_type ?? "");+const targetDbType = computed(() => store.getConfig(targetConnectionId.value)?.db_type ?? "");++// Clear stale field mappings when source and target are the same type+watch([sourceDbType, targetDbType], ([src, tgt]) => {+ if (src && src === tgt && activeConfig.value?.options.fieldMappings?.length) {+ handleFieldMappingsUpdate([]);+ }+});const optionTree = computed(() => {const targetConfig = store.getConfig(targetConnectionId.value);const dbType = targetConfig?.db_type || "postgres";@@ -70,7 +102,22 @@ const executing = ref(false);const lastDiffResult = ref<SchemaDiffPreparation | null>(null);const targetDbVersion = ref<string | null>(null);const showResultDialog = ref(false);-const deployResult = ref<{ success: boolean; message: string; affectedRows?: number } | null>(null);+const deployResult = ref<{ success: boolean; status?: string; message: string; affectedRows?: number; error?: string } | null>(null);++// Phase 4 result fields+const rollbackSql = ref("");+const rollbackCompleteness = ref<RollbackCompleteness>("complete");+const missingRollbackObjects = ref<MissingRollbackObject[]>([]);+const renameCandidates = ref<RenameCandidate[]>([]);+const compatibilityWarnings = ref<CompatibilityWarning[]>([]);+const permissionDiffs = ref<PermissionDiff[]>([]);+const dependencyGraph = ref<DependencyGraph | null>(null);++// Rename candidates panel+const showRenamePanel = ref(true);++// Rollback / forward SQL mode in deploy step+const deploySqlMode = ref<"forward" | "rollback">("forward");// Dialog size memory (width + height + splitpanes ratio)const DIALOG_SIZE_KEY = "dbx-schema-diff-size";@@ -274,6 +321,13 @@ function handleOptionsUpdate(options: SchemaDiffCompareOptions) {}}+function handleFieldMappingsUpdate(mappings: FieldMappingEntry[]) {+ if (activeConfig.value) {+ const updated = { ...activeConfig.value.options, fieldMappings: mappings };+ updateActiveConfigOptions(normalizeSchemaDiffCompareOptions(updated, getDbType()));+ }+}+/** Map a JDBC table_type to an ObjectSourceKind for getTableDdl routing.* Views and materialized views need the object_type parameter so the* backend can call DBMS_METADATA.GET_DDL with the correct type. */@@ -324,6 +378,15 @@ async function handleCompare() {loading.value = true;step.value = "compare";+ // Reset Phase 4 state to prevent stale data from previous compares+ rollbackSql.value = "";+ rollbackCompleteness.value = "complete";+ missingRollbackObjects.value = [];+ renameCandidates.value = [];+ compatibilityWarnings.value = [];+ permissionDiffs.value = [];+ dependencyGraph.value = null;+try {const sourceConfig = store.getConfig(sourceConnectionId.value);const targetConfig = store.getConfig(targetConnectionId.value);@@ -404,17 +467,53 @@ async function handleCompare() {ignoreComments: ignoreComments.value,cascadeDelete: opts?.cascadeDelete ?? false,compareColumnOrder: opts.compareColumnOrder,+ detectRenames: opts?.detectRenames ?? false,+ detectTableRenames: opts?.detectTableRenames ?? false,+ renameThreshold: opts?.renameThreshold ?? 0.5,+ enableRollback: opts?.enableRollback ?? false,+ batchPatterns: opts?.batchPatterns+ ? opts.batchPatterns+ .split(",")+ .map((s: string) => s.trim())+ .filter(Boolean)+ : undefined,+ sourceDialect: opts?.sourceDialect ? normalizeDialectKind(opts.sourceDialect) : sourceConfig?.db_type ? databaseTypeToDialectKind(sourceConfig.db_type) : undefined,+ targetDialect: opts?.targetDialect ? normalizeDialectKind(opts.targetDialect) : targetConfig?.db_type ? databaseTypeToDialectKind(targetConfig.db_type) : undefined,+ compatibilityThreshold: opts?.compatibilityThreshold ?? 0.5,+ fieldMappings:+ opts?.fieldMappings?.map((m: FieldMappingEntry) => ({+ sourceType: m.sourceType,+ targetType: m.targetType,+ paramStrategy: m.paramStrategy ?? "preserve",+ customParams: m.customParams,+ })) || [],});+ // Extract new result fields+ rollbackSql.value = result.rollbackSyncSql ?? "";+ rollbackCompleteness.value = result.rollbackCompleteness ?? "complete";+ missingRollbackObjects.value = result.missingRollbackObjects ?? [];+ renameCandidates.value = result.renameCandidates ?? [];+ compatibilityWarnings.value = result.compatibilityWarnings ?? [];+ permissionDiffs.value = result.permissionDiffs ?? [];+ dependencyGraph.value = result.dependencyGraph ?? null;+// Convert to unified objects- diffObjects.value = convertToSchemaDiffObjects(result.diffs, result.functionDiffs, result.sequenceDiffs, result.ruleDiffs, result.ownerDiffs);+ diffObjects.value = convertToSchemaDiffObjects(result.diffs, result.functionDiffs, result.sequenceDiffs, result.ruleDiffs, result.ownerDiffs, result.renameCandidates);// Group by operation type and object kinddiffGroups.value = groupDiffObjects(diffObjects.value);- // Save full result and generate deploy SQL+ // Save full result and apply column rename detection to SQLlastDiffResult.value = result;deploySqlAll.value = result.syncSql;+ if (opts?.detectRenames && opts.renameThreshold) {+ deploySqlAll.value = injectColumnRenameSql(deploySqlAll.value, result.diffs, opts.renameThreshold);+ if (rollbackSql.value) {+ rollbackSql.value = injectColumnRenameSql(rollbackSql.value, result.diffs, opts.renameThreshold, true);+ }+ }+ deploySqlMode.value = "forward";regenerateDeploySql();step.value = "result";@@ -498,29 +597,112 @@ function regenerateDeploySql() {deploySql.value = buildDeploySqlForObjects(diffObjects.value);}+function switchDeploySqlMode(mode: "forward" | "rollback") {+ if (mode === "rollback" && rollbackCompleteness.value === "incomplete") {+ toast(t("diff.rollbackIncompleteBlocked"), 4000);+ return;+ }+ deploySqlMode.value = mode;+ if (mode === "rollback" && rollbackSql.value) {+ deploySql.value = rollbackSql.value;+ } else {+ regenerateDeploySql();+ }+}++const canExecuteDeploy = computed(() => {+ if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {+ return false;+ }+ return true;+});++function applyRename(rc: RenameCandidate) {+ let found = false;+ for (const obj of diffObjects.value) {+ // Backend-detected renamed diff (diff_type = "renamed")+ if (obj.renameMetadata?.sourceName === rc.sourceName && obj.renameMetadata?.targetName === rc.targetName) {+ obj.renameMetadata.confirmed = true;+ obj.selected = true;+ found = true;+ }+ // Legacy delete+create pair+ if (obj.operationType === "delete" && obj.name === rc.sourceName) {+ obj.deploySql = `-- Renamed to ${rc.targetName}\n${obj.deploySql ?? ""}`;+ obj.renameMetadata = { confirmed: true, targetName: rc.targetName, score: rc.score };+ found = true;+ }+ if (obj.operationType === "create" && obj.name === rc.targetName) {+ obj.deploySql = `-- Renamed from ${rc.sourceName}\n${obj.deploySql ?? ""}`;+ obj.sourceName = rc.sourceName;+ obj.renameMetadata = { confirmed: true, sourceName: rc.sourceName, score: rc.score };+ found = true;+ }+ }+ if (found) {+ regenerateDeploySql();+ toast(t("diff.renameApplied"), 2000);+ }+}++function ignoreRename(index: number) {+ const rc = renameCandidates.value[index];+ if (rc) {+ for (const obj of diffObjects.value) {+ if (obj.renameMetadata?.sourceName === rc.sourceName && obj.renameMetadata?.targetName === rc.targetName) {+ obj.renameMetadata.confirmed = false;+ obj.selected = false;+ }+ }+ }+ renameCandidates.value.splice(index, 1);+ regenerateDeploySql();+}+async function handleExecuteScript() {if (!deploySql.value || deploySql.value.startsWith("-- ")) {toast(t("diff.noObjectsSelected"), 3000);return;}+ if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {+ toast(t("diff.rollbackIncompleteBlocked"), 5000);+ return;+ }+ await executeDeploySql();+}++async function executeDeploySql() {executing.value = true;try {- const result = await executeWithProductionSqlGuard({- connection: store.getConfig(targetConnectionId.value),+ const targetConnection = store.getConfig(targetConnectionId.value);+ const failed = await executeWithProductionSqlGuard({+ connection: targetConnection,database: targetDatabase.value,sql: deploySql.value,source: t("production.sourceSchemaDiff"),- execute: () => api.executeScript(targetConnectionId.value, targetDatabase.value, deploySql.value, targetSchema.value),+ execute: async () => {+ const txLog = await api.executeScriptWith2pc(targetConnectionId.value, targetDatabase.value, [deploySql.value], targetSchema.value);+ return txLog;+ },});- if (!result) return;- toast(t("diff.executeSuccess"), 3000);+ if (failed === undefined) return;+ showDeployTxResult(failed);} catch (e: any) {- toast(e?.message || String(e), 5000);+ deployResult.value = {+ success: false,+ message: e?.message || String(e),+ };+ showResultDialog.value = true;} finally {executing.value = false;}}++function showDeployTxResult(txLog: any) {+ deployResult.value = buildDeployTxResult(txLog, t);+ showResultDialog.value = true;+}async function handleSelectObject(obj: SchemaDiffObject) {selectedObjectId.value = obj.id;@@ -575,9 +757,9 @@ function handleLoadHistoryConfig(config: SchemaDiffConfig) {function handleSaveConfig() {if (activeConfig.value) {- const name = window.prompt(t("diff.saveConfigPrompt") || "Please enter config name:", activeConfig.value.name || "Default");+ const name = window.prompt(t("diff.saveConfigPrompt"), activeConfig.value.name || t("diff.defaultConfigName"));if (name === null) return; // User cancelled- const configToSave = { ...activeConfig.value, name: name.trim() || "Default" };+ const configToSave = { ...activeConfig.value, name: name.trim() || t("diff.defaultConfigName") };saveToHistory(configToSave);toast(t("diff.configSaved"), 2000);}@@ -631,36 +813,21 @@ function handleDeployReview() {}async function handleDeploy() {+ if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {+ toast(t("diff.rollbackIncompleteBlocked"), 5000);+ return;+ }showConfirmDialog.value = true;}async function onConfirmDeploy() {showConfirmDialog.value = false;- executing.value = true;- try {- const result = await executeWithProductionSqlGuard({- connection: store.getConfig(targetConnectionId.value),- database: targetDatabase.value,- sql: deploySql.value,- source: t("production.sourceSchemaDiff"),- execute: () => api.executeScript(targetConnectionId.value, targetDatabase.value, deploySql.value, targetSchema.value),- });- if (!result) return;- deployResult.value = {- success: true,- message: t("diff.deploySuccess"),- affectedRows: result.affected_rows,- };- showResultDialog.value = true;- } catch (e: any) {- deployResult.value = {- success: false,- message: e?.message || String(e),- };- showResultDialog.value = true;- } finally {- executing.value = false;+ if (deploySqlMode.value === "rollback" && rollbackCompleteness.value === "incomplete") {+ toast(t("diff.rollbackIncompleteBlocked"), 5000);+ return;}++ await executeDeploySql();}const deployStats = computed(() => {@@ -724,6 +891,8 @@ const targetConnectionInfo = computed(() => {@save-config="handleSaveConfig"@load-history-config="handleLoadHistoryConfig"@delete-history-config="handleDeleteHistoryConfig"+ @update:field-mappings="handleFieldMappingsUpdate"+ @open-field-mapping="showFieldMappingDialog = true"/><!-- Compare Loading -->@@ -734,6 +903,49 @@ const targetConnectionInfo = computed(() => {<!-- Result Step --><template v-else-if="step === 'result'">+ <!-- Rename Candidates Panel -->+ <div v-if="renameCandidates.length > 0" class="border-b bg-amber-50 dark:bg-amber-950/20 shrink-0 overflow-hidden">+ <button class="flex items-center gap-2 px-3 py-1.5 w-full text-left text-xs font-medium hover:bg-amber-100/50 dark:hover:bg-amber-900/30 transition-colors" @click="showRenamePanel = !showRenamePanel">+ <ChevronDown v-if="showRenamePanel" class="w-3 h-3" />+ <ChevronRight v-else class="w-3 h-3" />+ {{ t("diff.renameCandidates") }}+ <span class="ml-auto text-muted-foreground font-normal">{{ renameCandidates.length }} candidate(s)</span>+ </button>+ <div v-if="showRenamePanel" class="px-3 pb-2 text-xs">+ <table class="w-full">+ <thead>+ <tr class="text-muted-foreground border-b">+ <th class="text-left py-1 pr-4">{{ t("diff.sourceTable") }}</th>+ <th class="text-left py-1 pr-4">{{ t("diff.targetTable") }}</th>+ <th class="text-left py-1 pr-4">{{ t("diff.similarity") }}</th>+ <th class="text-left py-1">{{ t("common.action") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="(rc, i) in renameCandidates" :key="i" class="border-b border-amber-200/50 dark:border-amber-800/30">+ <td class="py-1 pr-4 font-mono">{{ rc.sourceName }}</td>+ <td class="py-1 pr-4 font-mono">{{ rc.targetName }}</td>+ <td class="py-1 pr-4">+ <span+ class="px-1.5 py-0.5 rounded text-[10px] font-medium"+ :class="rc.score >= 0.8 ? 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-300' : rc.score >= 0.5 ? 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-300' : 'bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300'"+ >{{ (rc.score * 100).toFixed(0) }}%</span+ >+ </td>+ <td class="py-1">+ <button class="text-xs px-2 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20 transition-colors mr-1" @click="applyRename(rc)">+ {{ t("diff.confirmRename") }}+ </button>+ <button class="text-xs px-2 py-0.5 rounded bg-muted hover:bg-muted/80 transition-colors" @click="ignoreRename(i)">+ {{ t("diff.ignore") }}+ </button>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+<Splitpanes horizontal class="flex-1 min-h-0" @resized="handleSplitpanesResized"><Pane :size="splitpanesSize" min-size="20"><div class="h-full overflow-auto">@@ -750,14 +962,45 @@ const targetConnectionInfo = computed(() => {</div></Pane><Pane :size="100 - splitpanesSize" min-size="20">- <SchemaDiffDdlPanel :selected-object="selectedObject" :deploy-sql="deploySql" :deploy-sql-all="deploySqlAll" @execute-script="handleExecuteScript" />+ <SchemaDiffDdlPanel+ :selected-object="selectedObject"+ :deploy-sql="deploySql"+ :deploy-sql-all="deploySqlAll"+ :compatibility-warnings="compatibilityWarnings"+ :rollback-sql="rollbackSql"+ :deploy-sql-mode="deploySqlMode"+ :dependency-graph="dependencyGraph"+ :permission-diffs="permissionDiffs"+ :rollback-completeness="rollbackCompleteness"+ :missing-rollback-objects="missingRollbackObjects"+ :can-execute="canExecuteDeploy"+ @update:deploy-sql-mode="switchDeploySqlMode"+ @execute-script="handleExecuteScript"+ /></Pane></Splitpanes></template><!-- Deploy Review Step --><template v-else-if="step === 'deploy-review'">- <SchemaDiffDeployStep v-model:deploy-sql="deploySql" :selected-objects="diffObjects" :target-connection-id="targetConnectionId" :target-database="targetDatabase" :target-schema="targetSchema" :executing="executing" @back="step = 'result'" @deploy="handleDeploy" />+ <SchemaDiffDeployStep+ v-model:deploy-sql="deploySql"+ :selected-objects="diffObjects"+ :target-connection-id="targetConnectionId"+ :target-database="targetDatabase"+ :target-schema="targetSchema"+ :executing="executing"+ :rollback-sql="rollbackSql"+ :deploy-sql-mode="deploySqlMode"+ :compatibility-warnings="compatibilityWarnings"+ :rename-candidates="renameCandidates"+ :rollback-completeness="rollbackCompleteness"+ :missing-rollback-objects="missingRollbackObjects"+ :can-execute="canExecuteDeploy"+ @update:deploy-sql-mode="switchDeploySqlMode"+ @back="step = 'result'"+ @deploy="handleDeploy"+ /></template></div>@@ -837,12 +1080,23 @@ const targetConnectionInfo = computed(() => {<DialogTitle class="flex items-center gap-2" :class="deployResult?.success ? 'text-green-500' : 'text-destructive'"><AlertTriangle v-if="!deployResult?.success" class="h-5 w-5" /><CircleCheck v-else class="h-5 w-5" />- {{ deployResult?.success ? t("diff.deploySuccess") : t("diff.deployFailed") }}+ <template v-if="deployResult?.status === 'mixed'">{{ t("diff.deployMixedTitle") }}</template>+ <template v-else-if="deployResult?.status === 'rolled_back'">{{ t("diff.deployRolledBackTitle") }}</template>+ <template v-else>{{ deployResult?.success ? t("diff.deploySuccess") : t("diff.deployFailed") }}</template></DialogTitle></DialogHeader><div class="py-2">- <div v-if="deployResult?.success" class="space-y-2">+ <div v-if="deployResult?.status === 'mixed'" class="space-y-2">+ <p class="text-sm text-destructive-foreground">{{ deployResult.message }}</p>+ <div class="bg-yellow-50 border border-yellow-300 p-3 rounded text-xs text-yellow-800">+ {{ t("diff.deployMixedWarning") }}+ </div>+ </div>+ <div v-else-if="deployResult?.status === 'rolled_back'" class="space-y-2">+ <p class="text-sm text-destructive-foreground">{{ deployResult.message }}</p>+ </div>+ <div v-else-if="deployResult?.success" class="space-y-2"><p class="text-sm text-muted-foreground">{{ t("diff.deploySuccessMessage") }}</p><div class="bg-muted p-3 rounded text-xs font-mono"><div>{{ t("diff.affectedRows") }}: {{ deployResult.affectedRows ?? 0 }}</div>@@ -875,11 +1129,25 @@ const targetConnectionInfo = computed(() => {<div class="bg-card border rounded-lg shadow-lg w-[760px] max-w-[calc(100vw-2rem)] max-h-[80vh] overflow-auto p-4"><div class="flex items-center justify-between mb-4"><h3 class="text-sm font-medium">{{ t("schemaDiff.optionsTitle") }}</h3>- <Button variant="ghost" size="sm" @click="showOptionsPanel = false">✕</Button>+ <Button variant="ghost" size="sm" @click="showOptionsPanel = false" :aria-label="t('common.close')">✕</Button></div><SchemaDiffOptionsPanel :options="schemaDiffPanelOptions" :option-tree="optionTree" @update:options="handleOptionsUpdate" @close="showOptionsPanel = false" /></div></div>++ <!-- Field Mapping Dialog Overlay -->+ <FieldMappingDialog+ :open="showFieldMappingDialog"+ :mappings="activeConfig?.options.fieldMappings ?? []"+ :source-db-type="sourceDbType"+ :target-db-type="targetDbType"+ :source-connection-id="sourceConnectionId"+ :source-database="sourceDatabase"+ :target-connection-id="targetConnectionId"+ :target-database="targetDatabase"+ @update:open="showFieldMappingDialog = $event"+ @save="handleFieldMappingsUpdate"+ /></DialogContent></Dialog></template>diff --git a/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vue b/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vueindex 8c82e10c76..ca2f830945 100644--- a/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vue+++ b/apps/desktop/src/components/diff/SchemaDiffOptionsPanel.vue@@ -147,6 +147,36 @@ function getItemClasses(state: "checked" | "unchecked" | "indeterminate"): strin</SelectContent></Select></div>++ <!-- Advanced options -->+ <div class="col-span-2 pt-3 pb-1 text-xs font-medium text-muted-foreground border-t mt-2">{{ t("schemaDiff.options.advancedSection") }}</div>++ <label class="pt-2 text-xs font-medium text-muted-foreground" for="schema-diff-rename-threshold">{{ t("schemaDiff.options.renameThreshold") }}</label>+ <div v-if="localOptions.detectRenames || localOptions.detectTableRenames" class="flex items-center gap-2 pt-1">+ <input id="schema-diff-rename-threshold" type="range" min="0" max="1" step="0.05" v-model.number="localOptions.renameThreshold" class="flex-1 h-1.5 accent-primary cursor-pointer" />+ <span class="text-xs font-mono w-10 text-right">{{ localOptions.renameThreshold.toFixed(2) }}</span>+ </div>+ <div v-else class="pt-1 text-xs text-muted-foreground italic">+ {{ t("schemaDiff.options.detectRenames") }}+ </div>++ <label class="pt-2 text-xs font-medium text-muted-foreground" for="schema-diff-compat-threshold">{{ t("schemaDiff.options.compatibilityThreshold") }}</label>+ <div class="flex items-center gap-2 pt-1">+ <input id="schema-diff-compat-threshold" type="range" min="0" max="1" step="0.05" v-model.number="localOptions.compatibilityThreshold" class="flex-1 h-1.5 accent-primary cursor-pointer" />+ <span class="text-xs font-mono w-10 text-right">{{ localOptions.compatibilityThreshold.toFixed(2) }}</span>+ </div>++ <label class="pt-2 text-xs font-medium text-muted-foreground" for="schema-diff-source-dialect">{{ t("schemaDiff.options.sourceDialect") }}</label>+ <input id="schema-diff-source-dialect" v-model="localOptions.sourceDialect" class="h-8 w-full rounded-md border border-input bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring" :placeholder="t('schemaDiff.options.dialectAuto')" />++ <label class="pt-2 text-xs font-medium text-muted-foreground" for="schema-diff-target-dialect">{{ t("schemaDiff.options.targetDialect") }}</label>+ <input id="schema-diff-target-dialect" v-model="localOptions.targetDialect" class="h-8 w-full rounded-md border border-input bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring" :placeholder="t('schemaDiff.options.dialectAuto')" />++ <div class="col-span-2 pt-3 pb-1 text-xs font-medium text-muted-foreground border-t mt-2">{{ t("schemaDiff.options.batchSection") }}</div>++ <div class="flex items-center gap-2 col-span-2 pt-1">+ <input id="schema-diff-batch-patterns" v-model="localOptions.batchPatterns" class="h-8 w-full rounded-md border border-input bg-background px-2 text-xs outline-none focus:ring-1 focus:ring-ring" :placeholder="t('schemaDiff.options.batchPatterns')" />+ </div></div></div>diff --git a/apps/desktop/src/components/diff/StrictTagAlertPanel.vue b/apps/desktop/src/components/diff/StrictTagAlertPanel.vuenew file mode 100644index 0000000000..a66eef464c--- /dev/null+++ b/apps/desktop/src/components/diff/StrictTagAlertPanel.vue@@ -0,0 +1,87 @@+<script setup lang="ts">+import { useI18n } from "vue-i18n";+import { AlertTriangle, ShieldAlert } from "@lucide/vue";++const { t } = useI18n();++interface TagViolation {+ fileName: string;+ lineNumber: number;+ tagName: string;+ suggestion: string;+}++const props = defineProps<{+ violations: TagViolation[];+ blocking: boolean;+}>();++const emit = defineEmits<{+ registerTag: [tagName: string];+ removeTag: [tagName: string];+ ignore: [tagName: string];+}>();+</script>++<template>+ <div class="border rounded-md bg-card">+ <div class="flex items-center gap-2 px-3 py-2 border-b">+ <ShieldAlert class="w-4 h-4 text-amber-500" />+ <h3 class="text-sm font-medium">{{ t("strictTag.title") }}</h3>+ </div>++ <div v-if="blocking" class="mx-3 mt-3 flex items-center gap-2 px-3 py-2 rounded text-xs font-medium bg-red-100 text-red-700 dark:bg-red-900/30 dark:text-red-300 border border-red-200 dark:border-red-900/30">+ <AlertTriangle class="w-3.5 h-3.5 shrink-0" />+ <span>{{ t("strictTag.blockingExecution") }}</span>+ </div>++ <div v-if="violations.length === 0" class="flex items-center justify-center py-8 text-sm text-muted-foreground">+ {{ t("strictTag.noViolations") }}+ </div>++ <template v-else>+ <div class="px-3 pt-3 pb-1 text-xs text-muted-foreground">+ {{ t("strictTag.violationsFound", { count: violations.length }) }}+ </div>++ <div class="p-3">+ <div class="border rounded overflow-hidden">+ <table class="w-full text-xs">+ <thead>+ <tr class="bg-muted/30">+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("strictTag.fileName") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("strictTag.lineNumber") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("strictTag.tagName") }}</th>+ <th class="text-left px-2 py-1.5 font-medium text-muted-foreground">{{ t("strictTag.suggestion") }}</th>+ <th class="text-right px-2 py-1.5 font-medium text-muted-foreground">{{ t("common.actions") }}</th>+ </tr>+ </thead>+ <tbody>+ <tr v-for="v in violations" :key="`${v.fileName}:${v.lineNumber}:${v.tagName}`" class="border-t">+ <td class="px-2 py-1.5 font-mono">{{ v.fileName }}</td>+ <td class="px-2 py-1.5">{{ v.lineNumber }}</td>+ <td class="px-2 py-1.5 font-mono">{{ v.tagName }}</td>+ <td class="px-2 py-1.5 text-muted-foreground">{{ v.suggestion }}</td>+ <td class="px-2 py-1.5 text-right">+ <div class="flex items-center justify-end gap-1">+ <button class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-primary/10 text-primary hover:bg-primary/20 transition-colors" @click="emit('registerTag', v.tagName)">+ {{ t("strictTag.registerTag") }}+ </button>+ <button class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-destructive/10 text-destructive hover:bg-destructive/20 transition-colors" @click="emit('removeTag', v.tagName)">+ {{ t("strictTag.removeTag") }}+ </button>+ <button class="px-1.5 py-0.5 rounded text-[10px] font-medium bg-muted/40 text-muted-foreground hover:bg-muted/60 transition-colors" @click="emit('ignore', v.tagName)">+ {{ t("strictTag.ignore") }}+ </button>+ </div>+ </td>+ </tr>+ </tbody>+ </table>+ </div>+ </div>+ </template>+ </div>+</template>++<style scoped></style>diff --git a/apps/desktop/src/i18n/locales/en.ts b/apps/desktop/src/i18n/locales/en.tsindex ad49b62dfc..b583d6168e 100644--- a/apps/desktop/src/i18n/locales/en.ts+++ b/apps/desktop/src/i18n/locales/en.ts@@ -4000,10 +4000,54 @@ export default {port: "Port",copied: "Copied to clipboard",saveConfigPrompt: "Please enter config name:",+ defaultConfigName: "Default",+ dependsOn: "depends on",+ dependedBy: "depended by",close: "Close",searchConnection: "Search connections...",searchDatabase: "Search databases...",searchSchema: "Search schemas...",+ openFieldMapping: "Field Mapping",+ fieldMapping: {+ title: "Field Type Mapping",+ sameTypeHint: "Source and target are the same database type. Field mapping is only needed when comparing across different database types.",+ preset: "Built-in Preset",+ selectPreset: "Select a preset...",+ noMappings: "No field mappings defined",+ sourceType: "Source Type",+ targetType: "Target Type",+ paramStrategy: "Param Strategy",+ strategyPreserve: "Preserve",+ strategyStrip: "Strip",+ strategyCustom: "Custom",+ customParamsPlaceholder: "e.g. (100)",+ addMapping: "Add Mapping",+ autoGenerate: "Auto-Generate",+ import: "Import",+ export: "Export",+ done: "Done",+ importTypeMismatch: "The imported mappings were exported for {src} → {tgt}, but the current comparison is {curSrc} → {curTgt}. The type mappings may not be accurate. Continue anyway?",+ importSuccess: "Field mappings imported successfully",+ importError: "Failed to import field mappings. Please check the JSON format.",+ clearMappings: "Clear",+ staleMappingWarning: "The database type has changed from {prevSrc} → {prevTgt} to {curSrc} → {curTgt}. Existing field mappings may no longer be valid. Clear them?",+ },+ deployMode: "Deploy",+ forwardSql: "Forward SQL",+ rollbackSql: "Rollback SQL",+ rollbackMode: "Rollback",+ deployMixed: "Deployment partially completed. Some statements may already be applied ({executedCount}/{statementCount}). DDL may not be transactional.",+ deployRolledBack: "All changes have been rolled back.",+ rollbackIncompleteBlocked: "Rollback SQL is incomplete (missing objects). Execution is blocked.",+ rollbackIncompleteBanner: "Rollback is incomplete — missing trigger/table DDL. Fix missing objects before executing.",+ deployMixedTitle: "Partially Deployed",+ deployRolledBackTitle: "Rolled Back",+ deployMixedWarning: "Some statements may already be applied while others failed. The database may be in an inconsistent state. Review the transaction log and take manual corrective action before retrying.",+ },+ rollbackComparison: {+ title: "Rollback Comparison",+ forwardSql: "Forward SQL",+ rollbackSql: "Rollback SQL",},schemaDiff: {optionsTitle: "Compare Options",@@ -4052,6 +4096,17 @@ export default {cascadeDelete: "Use CASCADE delete",sequenceLastValues: "Compare sequence last values",compareColumnOrder: "Compare column order",+ detectRenames: "Detect renames",+ detectTableRenames: "Detect table renames",+ enableRollback: "Enable rollback",+ advancedSection: "Advanced",+ renameThreshold: "Rename threshold",+ compatibilityThreshold: "Compatibility threshold",+ sourceDialect: "Source dialect",+ targetDialect: "Target dialect",+ batchSection: "Batch",+ batchPatterns: "Table patterns (comma-separated)",+ dialectAuto: "auto",},},dataCompare: {diff --git a/apps/desktop/src/i18n/locales/es.ts b/apps/desktop/src/i18n/locales/es.tsindex b6422561c4..26e1cbb2b6 100644--- a/apps/desktop/src/i18n/locales/es.ts+++ b/apps/desktop/src/i18n/locales/es.ts@@ -3785,6 +3785,50 @@ export default withEnglishFallback({searchConnection: "Buscar conexiones...",searchDatabase: "Buscar bases de datos...",searchSchema: "Buscar esquemas...",+ defaultConfigName: "Predeterminado",+ dependsOn: "depende de",+ dependedBy: "dependido por",+ openFieldMapping: "Mapeo de Campos",+ fieldMapping: {+ title: "Mapeo de Tipos de Campo",+ sameTypeHint: "Origen y destino son del mismo tipo de base de datos. El mapeo de campos solo es necesario al comparar entre diferentes tipos de bases de datos.",+ preset: "Preajuste Integrado",+ selectPreset: "Seleccionar un preajuste...",+ noMappings: "No hay mapeos de campos definidos",+ sourceType: "Tipo de Origen",+ targetType: "Tipo de Destino",+ paramStrategy: "Estrategia de Parámetros",+ strategyPreserve: "Preservar",+ strategyStrip: "Eliminar",+ strategyCustom: "Personalizado",+ customParamsPlaceholder: "ej. (100)",+ addMapping: "Agregar Mapeo",+ autoGenerate: "Auto-Generar",+ import: "Importar",+ export: "Exportar",+ done: "Listo",+ importTypeMismatch: "Los mapeos importados se exportaron para {src} → {tgt}, pero la comparación actual es {curSrc} → {curTgt}. Los mapeos de tipos pueden no ser precisos. ¿Continuar de todos modos?",+ importSuccess: "Mapeos de campos importados correctamente",+ importError: "Error al importar mapeos de campos. Verifique el formato JSON.",+ clearMappings: "Limpiar",+ staleMappingWarning: "El tipo de base de datos ha cambiado de {prevSrc} → {prevTgt} a {curSrc} → {curTgt}. Los mapeos de campos existentes pueden no ser válidos. ¿Limpiarlos?",+ },+ deployMode: "Desplegar",+ forwardSql: "SQL Directo",+ rollbackSql: "SQL de Reversión",+ rollbackMode: "Reversión",+ deployMixed: "Despliegue parcialmente completado. Algunas declaraciones pueden haberse aplicado ya ({executedCount}/{statementCount}). El DDL puede no ser transaccional.",+ deployRolledBack: "Todos los cambios han sido revertidos.",+ rollbackIncompleteBlocked: "Rollback incomplete (missing objects). Execution blocked.",+ rollbackIncompleteBanner: "Rollback incomplete — missing trigger/table DDL.",+ deployMixedTitle: "Parcialmente Desplegado",+ deployRolledBackTitle: "Revertido",+ deployMixedWarning: "Algunas declaraciones pueden haberse aplicado mientras que otras fallaron. La base de datos puede estar en un estado inconsistente. Revise el registro de transacciones y tome medidas correctivas manuales antes de reintentar.",+ },+ rollbackComparison: {+ title: "Comparación de Reversión",+ forwardSql: "SQL Directo",+ rollbackSql: "SQL de Reversión",},schemaDiff: {optionsTitle: "Opciones de comparación",@@ -3833,6 +3877,17 @@ export default withEnglishFallback({cascadeDelete: "Use CASCADE delete",sequenceLastValues: "Compare sequence last values",compareColumnOrder: "Compare column order",+ detectRenames: "Detectar renombrados",+ detectTableRenames: "Detectar renombrados de tabla",+ enableRollback: "Habilitar reversión",+ advancedSection: "Avanzado",+ renameThreshold: "Umbral de renombrado",+ compatibilityThreshold: "Umbral de compatibilidad",+ sourceDialect: "Dialecto de origen",+ targetDialect: "Dialecto de destino",+ batchSection: "Lote",+ batchPatterns: "Patrones de tabla (separados por comas)",+ dialectAuto: "automático",},},dataCompare: {diff --git a/apps/desktop/src/i18n/locales/it.ts b/apps/desktop/src/i18n/locales/it.tsindex 4d46d441e8..b7e34dd5c1 100644--- a/apps/desktop/src/i18n/locales/it.ts+++ b/apps/desktop/src/i18n/locales/it.ts@@ -3783,6 +3783,50 @@ export default withEnglishFallback({searchConnection: "Cerca connessioni...",searchDatabase: "Cerca database...",searchSchema: "Cerca schemi...",+ defaultConfigName: "Predefinito",+ dependsOn: "dipende da",+ dependedBy: "dipendente da",+ openFieldMapping: "Mappatura Campi",+ fieldMapping: {+ title: "Mappatura Tipi di Campo",+ sameTypeHint: "Origine e destinazione sono lo stesso tipo di database. La mappatura dei campi è necessaria solo quando si confrontano tipi di database diversi.",+ preset: "Preimpostazione Integrata",+ selectPreset: "Seleziona una preimpostazione...",+ noMappings: "Nessuna mappatura di campi definita",+ sourceType: "Tipo Origine",+ targetType: "Tipo Destinazione",+ paramStrategy: "Strategia Parametri",+ strategyPreserve: "Preserva",+ strategyStrip: "Rimuovi",+ strategyCustom: "Personalizzato",+ customParamsPlaceholder: "es. (100)",+ addMapping: "Aggiungi Mappatura",+ autoGenerate: "Genera Automaticamente",+ import: "Importa",+ export: "Esporta",+ done: "Fatto",+ importTypeMismatch: "Le mappature importate sono state esportate per {src} → {tgt}, ma il confronto corrente è {curSrc} → {curTgt}. Le mappature dei tipi potrebbero non essere accurate. Continuare comunque?",+ importSuccess: "Mappature dei campi importate con successo",+ importError: "Importazione mappature campi non riuscita. Verificare il formato JSON.",+ clearMappings: "Cancella",+ staleMappingWarning: "Il tipo di database è cambiato da {prevSrc} → {prevTgt} a {curSrc} → {curTgt}. Le mappature dei campi esistenti potrebbero non essere più valide. Cancellarle?",+ },+ deployMode: "Distribuisci",+ forwardSql: "SQL Diretto",+ rollbackSql: "SQL di Rollback",+ rollbackMode: "Rollback",+ deployMixed: "Distribuzione parzialmente completata. Alcune istruzioni potrebbero essere già applicate ({executedCount}/{statementCount}). Il DDL potrebbe non essere transazionale.",+ deployRolledBack: "Tutte le modifiche sono state annullate.",+ rollbackIncompleteBlocked: "Rollback incomplete (missing objects). Execution blocked.",+ rollbackIncompleteBanner: "Rollback incomplete — missing trigger/table DDL.",+ deployMixedTitle: "Parzialmente Distribuito",+ deployRolledBackTitle: "Annullato",+ deployMixedWarning: "Alcune istruzioni potrebbero essere già applicate mentre altre sono fallite. Il database potrebbe trovarsi in uno stato inconsistente. Controllare il log delle transazioni e intervenire manualmente prima di riprovare.",+ },+ rollbackComparison: {+ title: "Confronto Rollback",+ forwardSql: "SQL Diretto",+ rollbackSql: "SQL di Rollback",},schemaDiff: {optionsTitle: "Opzioni di Confronto",@@ -3831,6 +3875,17 @@ export default withEnglishFallback({cascadeDelete: "Usa CASCADE delete",sequenceLastValues: "Confronta ultimi valori sequenza",compareColumnOrder: "Confronta ordine colonne",+ detectRenames: "Rileva ridenominazioni",+ detectTableRenames: "Rileva ridenominazioni tabelle",+ enableRollback: "Abilita rollback",+ advancedSection: "Avanzate",+ renameThreshold: "Soglia ridenominazione",+ compatibilityThreshold: "Soglia compatibilità",+ sourceDialect: "Dialetto origine",+ targetDialect: "Dialetto destinazione",+ batchSection: "Batch",+ batchPatterns: "Pattern tabella (separati da virgola)",+ dialectAuto: "auto",},},dataCompare: {diff --git a/apps/desktop/src/i18n/locales/ja.ts b/apps/desktop/src/i18n/locales/ja.tsindex dee28013b1..4ce56b0fb1 100644--- a/apps/desktop/src/i18n/locales/ja.ts+++ b/apps/desktop/src/i18n/locales/ja.ts@@ -3784,6 +3784,50 @@ export default withEnglishFallback({searchConnection: "接続を検索...",searchDatabase: "データベースを検索...",searchSchema: "スキーマを検索...",+ defaultConfigName: "デフォルト",+ dependsOn: "に依存",+ dependedBy: "から依存される",+ openFieldMapping: "フィールドマッピング",+ fieldMapping: {+ title: "フィールド型マッピング",+ sameTypeHint: "ソースとターゲットが同じデータベースタイプです。フィールドマッピングは異なるデータベースタイプ間での比較時のみ必要です。",+ preset: "組み込みプリセット",+ selectPreset: "プリセットを選択...",+ noMappings: "フィールドマッピングが定義されていません",+ sourceType: "ソース型",+ targetType: "ターゲット型",+ paramStrategy: "パラメータ戦略",+ strategyPreserve: "保持",+ strategyStrip: "除去",+ strategyCustom: "カスタム",+ customParamsPlaceholder: "例: (100)",+ addMapping: "マッピングを追加",+ autoGenerate: "自動生成",+ import: "インポート",+ export: "エクスポート",+ done: "完了",+ importTypeMismatch: "インポートされたマッピングは {src} → {tgt} 用にエクスポートされましたが、現在の比較は {curSrc} → {curTgt} です。型マッピングが正確でない可能性があります。続行しますか?",+ importSuccess: "フィールドマッピングが正常にインポートされました",+ importError: "フィールドマッピングのインポートに失敗しました。JSON形式を確認してください。",+ clearMappings: "クリア",+ staleMappingWarning: "データベースタイプが {prevSrc} → {prevTgt} から {curSrc} → {curTgt} に変更されました。既存のフィールドマッピングは有効でない可能性があります。クリアしますか?",+ },+ deployMode: "デプロイ",+ forwardSql: "フォワードSQL",+ rollbackSql: "ロールバックSQL",+ rollbackMode: "ロールバック",+ deployMixed: "デプロイが部分的に完了しました。一部のステートメントは既に適用済みの可能性があります({executedCount}/{statementCount})。DDL はトランザクション対象外の場合があります。",+ deployRolledBack: "すべての変更がロールバックされました。",+ rollbackIncompleteBlocked: "Rollback incomplete (missing objects). Execution blocked.",+ rollbackIncompleteBanner: "Rollback incomplete — missing trigger/table DDL.",+ deployMixedTitle: "部分的にデプロイ",+ deployRolledBackTitle: "ロールバック済み",+ deployMixedWarning: "一部のステートメントは既に適用済みで、他のステートメントは失敗した可能性があります。データベースが不整合な状態にある可能性があります。再試行前にトランザクションログを確認し、手動で修正してください。",+ },+ rollbackComparison: {+ title: "ロールバック比較",+ forwardSql: "フォワードSQL",+ rollbackSql: "ロールバックSQL",},schemaDiff: {optionsTitle: "比較オプション",@@ -3832,6 +3876,17 @@ export default withEnglishFallback({cascadeDelete: "CASCADE削除を使用",sequenceLastValues: "シーケンス最終値を比較",compareColumnOrder: "列順序を比較",+ detectRenames: "名前変更を検出",+ detectTableRenames: "テーブル名変更を検出",+ enableRollback: "ロールバックを有効化",+ advancedSection: "詳細設定",+ renameThreshold: "名前変更しきい値",+ compatibilityThreshold: "互換性しきい値",+ sourceDialect: "ソース方言",+ targetDialect: "ターゲット方言",+ batchSection: "バッチ",+ batchPatterns: "テーブルパターン(カンマ区切り)",+ dialectAuto: "自動",},},dataCompare: {diff --git a/apps/desktop/src/i18n/locales/pt-BR.ts b/apps/desktop/src/i18n/locales/pt-BR.tsindex 1a2411e9a6..7874025c33 100644--- a/apps/desktop/src/i18n/locales/pt-BR.ts+++ b/apps/desktop/src/i18n/locales/pt-BR.ts@@ -3785,6 +3785,50 @@ export default withEnglishFallback({searchConnection: "Pesquisar conexões...",searchDatabase: "Pesquisar bancos de dados...",searchSchema: "Pesquisar schemas...",+ defaultConfigName: "Padrão",+ dependsOn: "depende de",+ dependedBy: "dependido por",+ openFieldMapping: "Mapeamento de Campos",+ fieldMapping: {+ title: "Mapeamento de Tipos de Campo",+ sameTypeHint: "Origem e destino são do mesmo tipo de banco de dados. O mapeamento de campos só é necessário ao comparar entre tipos de banco de dados diferentes.",+ preset: "Predefinição Integrada",+ selectPreset: "Selecionar uma predefinição...",+ noMappings: "Nenhum mapeamento de campos definido",+ sourceType: "Tipo de Origem",+ targetType: "Tipo de Destino",+ paramStrategy: "Estratégia de Parâmetros",+ strategyPreserve: "Preservar",+ strategyStrip: "Remover",+ strategyCustom: "Personalizado",+ customParamsPlaceholder: "ex.: (100)",+ addMapping: "Adicionar Mapeamento",+ autoGenerate: "Auto-Gerar",+ import: "Importar",+ export: "Exportar",+ done: "Concluído",+ importTypeMismatch: "Os mapeamentos importados foram exportados para {src} → {tgt}, mas a comparação atual é {curSrc} → {curTgt}. Os mapeamentos de tipo podem não ser precisos. Continuar mesmo assim?",+ importSuccess: "Mapeamentos de campos importados com sucesso",+ importError: "Falha ao importar mapeamentos de campos. Verifique o formato JSON.",+ clearMappings: "Limpar",+ staleMappingWarning: "O tipo de banco de dados mudou de {prevSrc} → {prevTgt} para {curSrc} → {curTgt}. Os mapeamentos de campos existentes podem não ser mais válidos. Limpá-los?",+ },+ deployMode: "Implantar",+ forwardSql: "SQL Direto",+ rollbackSql: "SQL de Reversão",+ rollbackMode: "Reversão",+ deployMixed: "Implantação parcialmente concluída. Algumas instruções podem já ter sido aplicadas ({executedCount}/{statementCount}). DDL pode não ser transacional.",+ deployRolledBack: "Todas as alterações foram revertidas.",+ rollbackIncompleteBlocked: "Rollback incomplete (missing objects). Execution blocked.",+ rollbackIncompleteBanner: "Rollback incomplete — missing trigger/table DDL.",+ deployMixedTitle: "Parcialmente Implantado",+ deployRolledBackTitle: "Revertido",+ deployMixedWarning: "Algumas instruções podem já ter sido aplicadas enquanto outras falharam. O banco de dados pode estar em um estado inconsistente. Revise o log de transações e tome ação corretiva manual antes de tentar novamente.",+ },+ rollbackComparison: {+ title: "Comparação de Reversão",+ forwardSql: "SQL Direto",+ rollbackSql: "SQL de Reversão",},schemaDiff: {optionsTitle: "Opções de Comparação",@@ -3833,6 +3877,17 @@ export default withEnglishFallback({cascadeDelete: "Usar CASCADE delete",sequenceLastValues: "Comparar últimos valores de sequência",compareColumnOrder: "Comparar ordem das colunas",+ detectRenames: "Detectar renomeações",+ detectTableRenames: "Detectar renomeações de tabela",+ enableRollback: "Habilitar rollback",+ advancedSection: "Avançado",+ renameThreshold: "Limiar de renomeação",+ compatibilityThreshold: "Limiar de compatibilidade",+ sourceDialect: "Dialeto de origem",+ targetDialect: "Dialeto de destino",+ batchSection: "Lote",+ batchPatterns: "Padrões de tabela (separados por vírgula)",+ dialectAuto: "automático",},},dataCompare: {diff --git a/apps/desktop/src/i18n/locales/zh-CN.ts b/apps/desktop/src/i18n/locales/zh-CN.tsindex 4c097b5953..2be5a72fca 100644--- a/apps/desktop/src/i18n/locales/zh-CN.ts+++ b/apps/desktop/src/i18n/locales/zh-CN.ts@@ -4001,9 +4001,53 @@ export default withEnglishFallback({configDeleted: "配置已删除",noDeployScriptAll: "暂无所选对象的部署脚本",saveConfigPrompt: "请输入配置名称:",+ defaultConfigName: "默认",+ dependsOn: "依赖于",+ dependedBy: "被依赖",searchConnection: "搜索连接...",searchDatabase: "搜索数据库...",searchSchema: "搜索模式...",+ openFieldMapping: "字段映射",+ fieldMapping: {+ title: "字段类型映射",+ sameTypeHint: "源和目标数据库类型相同,仅在不同类型数据库之间比较时才需要字段映射。",+ preset: "内置预设",+ selectPreset: "选择预设...",+ noMappings: "暂无字段映射",+ sourceType: "源类型",+ targetType: "目标类型",+ paramStrategy: "参数策略",+ strategyPreserve: "保留",+ strategyStrip: "去除",+ strategyCustom: "自定义",+ customParamsPlaceholder: "如 (100)",+ addMapping: "添加映射",+ autoGenerate: "自动生成",+ import: "导入",+ export: "导出",+ done: "完成",+ importTypeMismatch: "导入的映射文件是 {src} → {tgt} 的,但当前比较是 {curSrc} → {curTgt}。类型映射可能不准确。是否继续?",+ importSuccess: "字段映射导入成功",+ importError: "字段映射导入失败,请检查 JSON 格式。",+ clearMappings: "清空",+ staleMappingWarning: "数据库类型已从 {prevSrc} → {prevTgt} 变更为 {curSrc} → {curTgt},现有字段映射可能不再有效。是否清除?",+ },+ deployMode: "部署",+ forwardSql: "正向 SQL",+ rollbackSql: "回滚 SQL",+ rollbackMode: "回滚",+ deployMixed: "部署部分完成,部分语句可能已生效({executedCount}/{statementCount})。DDL 可能不支持事务。",+ deployRolledBack: "所有变更已回滚。",+ rollbackIncompleteBlocked: "回滚 SQL 不完整(存在缺失对象),已禁止执行。",+ rollbackIncompleteBanner: "回滚不完整 — 缺少触发器/表 DDL。请先补全缺失对象再执行。",+ deployMixedTitle: "部分已部署",+ deployRolledBackTitle: "已回滚",+ deployMixedWarning: "部分语句可能已生效,其余语句失败。数据库可能处于不一致状态,请在重试前检查事务日志并手动处理。",+ },+ rollbackComparison: {+ title: "回滚对比",+ forwardSql: "正向 SQL",+ rollbackSql: "回滚 SQL",},schemaDiff: {optionsTitle: "比较选项",@@ -4052,6 +4096,17 @@ export default withEnglishFallback({cascadeDelete: "使用级联删除",sequenceLastValues: "比较序列最后值",compareColumnOrder: "比较字段顺序",+ detectRenames: "检测重命名",+ detectTableRenames: "检测表重命名",+ enableRollback: "启用回滚",+ advancedSection: "高级选项",+ renameThreshold: "重命名阈值",+ compatibilityThreshold: "兼容性阈值",+ sourceDialect: "源数据库方言",+ targetDialect: "目标数据库方言",+ batchSection: "批次模式",+ batchPatterns: "表名模式(逗号分隔)",+ dialectAuto: "自动",},},dataCompare: {diff --git a/apps/desktop/src/i18n/locales/zh-TW.ts b/apps/desktop/src/i18n/locales/zh-TW.tsindex 934078c17f..bcecba7779 100644--- a/apps/desktop/src/i18n/locales/zh-TW.ts+++ b/apps/desktop/src/i18n/locales/zh-TW.ts@@ -3456,6 +3456,50 @@ export default withEnglishFallback({searchConnection: "搜尋連線...",searchDatabase: "搜尋資料庫...",searchSchema: "搜尋結構描述...",+ defaultConfigName: "預設",+ dependsOn: "依賴於",+ dependedBy: "被依賴",+ openFieldMapping: "欄位映射",+ fieldMapping: {+ title: "欄位類型映射",+ sameTypeHint: "來源與目標資料庫類型相同,僅在不同類型資料庫之間比較時才需要欄位映射。",+ preset: "內建預設",+ selectPreset: "選擇預設...",+ noMappings: "暫無欄位映射",+ sourceType: "來源類型",+ targetType: "目標類型",+ paramStrategy: "參數策略",+ strategyPreserve: "保留",+ strategyStrip: "去除",+ strategyCustom: "自訂",+ customParamsPlaceholder: "如 (100)",+ addMapping: "新增映射",+ autoGenerate: "自動生成",+ import: "匯入",+ export: "匯出",+ done: "完成",+ importTypeMismatch: "匯入的映射檔案是 {src} → {tgt} 的,但目前比較是 {curSrc} → {curTgt}。類型映射可能不準確。是否繼續?",+ importSuccess: "欄位映射匯入成功",+ importError: "欄位映射匯入失敗,請檢查 JSON 格式。",+ clearMappings: "清空",+ staleMappingWarning: "資料庫類型已從 {prevSrc} → {prevTgt} 變更為 {curSrc} → {curTgt},現有欄位映射可能不再有效。是否清除?",+ },+ deployMode: "部署",+ forwardSql: "正向 SQL",+ rollbackSql: "回溯 SQL",+ rollbackMode: "回溯",+ deployMixed: "部署部分完成,部分語句可能已生效({executedCount}/{statementCount})。DDL 可能不支援交易。",+ deployRolledBack: "所有變更已回溯。",+ rollbackIncompleteBlocked: "Rollback SQL is incomplete (missing objects). Execution is blocked.",+ rollbackIncompleteBanner: "Rollback is incomplete — missing trigger/table DDL. Fix missing objects before executing.",+ deployMixedTitle: "部分已部署",+ deployRolledBackTitle: "已回溯",+ deployMixedWarning: "部分語句可能已生效,其餘語句失敗。資料庫可能處於不一致狀態,請在重試前檢查交易日誌並手動處理。",+ },+ rollbackComparison: {+ title: "回溯對比",+ forwardSql: "正向 SQL",+ rollbackSql: "回溯 SQL",},schemaDiff: {optionsTitle: "比較選項",@@ -3504,6 +3548,17 @@ export default withEnglishFallback({cascadeDelete: "使用級聯刪除",sequenceLastValues: "比較序列最後值",compareColumnOrder: "比較欄位順序",+ detectRenames: "檢測重新命名",+ detectTableRenames: "檢測表重新命名",+ enableRollback: "啟用回溯",+ advancedSection: "進階選項",+ renameThreshold: "重新命名閾值",+ compatibilityThreshold: "相容性閾值",+ sourceDialect: "來源資料庫方言",+ targetDialect: "目標資料庫方言",+ batchSection: "批次模式",+ batchPatterns: "資料表模式(逗號分隔)",+ dialectAuto: "自動",},},dataCompare: {diff --git a/apps/desktop/src/lib/backend/__tests__/listDialectDataTypes.spec.ts b/apps/desktop/src/lib/backend/__tests__/listDialectDataTypes.spec.tsnew file mode 100644index 0000000000..bca2ee17a4--- /dev/null+++ b/apps/desktop/src/lib/backend/__tests__/listDialectDataTypes.spec.ts@@ -0,0 +1,40 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mocks = vi.hoisted(() => ({+ invoke: vi.fn(),+}));++vi.mock("@tauri-apps/api/core", () => ({+ invoke: mocks.invoke,+}));++vi.mock("@tauri-apps/api/event", () => ({+ listen: vi.fn(),+}));++describe("listDialectDataTypes backend adapters", () => {+ beforeEach(() => {+ vi.clearAllMocks();+ vi.unstubAllGlobals();+ });++ it("uses the Tauri dialect command", async () => {+ mocks.invoke.mockResolvedValue(["INTEGER", "TEXT"]);+ const { listDialectDataTypes } = await import("@/lib/backend/tauri");++ await expect(listDialectDataTypes("PostgreSQL")).resolves.toEqual(["INTEGER", "TEXT"]);+ expect(mocks.invoke).toHaveBeenCalledWith("list_dialect_data_types", { dialectName: "PostgreSQL" });+ });++ it("uses the matching Web dialect route", async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ json: vi.fn().mockResolvedValue(["INTEGER", "TEXT"]),+ });+ vi.stubGlobal("fetch", fetchMock);+ const { listDialectDataTypes } = await import("@/lib/backend/http");++ await expect(listDialectDataTypes("PostgreSQL")).resolves.toEqual(["INTEGER", "TEXT"]);+ expect(fetchMock).toHaveBeenCalledWith("/api/dialect/data-types?dialect_name=PostgreSQL");+ });+});diff --git a/apps/desktop/src/lib/backend/api.ts b/apps/desktop/src/lib/backend/api.tsindex e088ee18a9..5342f16df1 100644--- a/apps/desktop/src/lib/backend/api.ts+++ b/apps/desktop/src/lib/backend/api.ts@@ -175,6 +175,7 @@ export const listExtensions = forward("listExtensions");export const listAvailableExtensions = forward("listAvailableExtensions");export const prepareSchemaDiff = forward("prepareSchemaDiff");export const generateSchemaSyncSql = forward("generateSchemaSyncSql");+export const listDialectDataTypes = forward("listDialectDataTypes");// Queryexport const executeQuery = forward("executeQuery");@@ -182,6 +183,7 @@ export const executeMulti = forward("executeMulti");export const executeMultiWithProgress = forward("executeMultiWithProgress");export const executeBatch = forward("executeBatch");export const executeScript = forward("executeScript");+export const executeScriptWith2pc = forward("executeScriptWith2pc");export const executeInTransaction = forward("executeInTransaction");export const beginManualTransaction = forward("beginManualTransaction");export const executeInManualTransaction = forward("executeInManualTransaction");diff --git a/apps/desktop/src/lib/backend/http.ts b/apps/desktop/src/lib/backend/http.tsindex 9cdb4322aa..eb880bb0f2 100644--- a/apps/desktop/src/lib/backend/http.ts+++ b/apps/desktop/src/lib/backend/http.ts@@ -776,6 +776,10 @@ export async function listAvailableExtensions(connectionId: string, database: streturn get(`/api/schema/available-extensions?${qs({ connection_id: connectionId, database })}`);}+export async function listDialectDataTypes(dialectName: string): Promise<string[]> {+ return get(`/api/dialect/data-types?${qs({ dialect_name: dialectName })}`);+}+// ---------------------------------------------------------------------------// Query// ---------------------------------------------------------------------------@@ -867,6 +871,10 @@ export async function executeScript(connectionId: string, database: string, sql:return post("/api/query/execute-script", { connectionId, database, sql, schema });}+export async function executeScriptWith2pc(connectionId: string, database: string, statements: string[], schema?: string): Promise<any> {+ return post("/api/query/execute-script-2pc", { connectionId, database, statements, schema });+}+export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string): Promise<QueryResult> {return post("/api/query/execute-in-transaction", { connectionId, database, statements, schema });}diff --git a/apps/desktop/src/lib/backend/tauri.ts b/apps/desktop/src/lib/backend/tauri.tsindex 945bdbab31..4da46fa26e 100644--- a/apps/desktop/src/lib/backend/tauri.ts+++ b/apps/desktop/src/lib/backend/tauri.ts@@ -44,6 +44,7 @@ import type {SavedSqlLibrary,SshConfigHostEntry,TunnelProfile,+ TransactionLog,} from "@/types/database";import { isTauriCommandUnavailable, normalizeConnectionTestResult } from "@/lib/connection/connectionDatabaseInfo";import type { CollectionInfo } from "@/types/database";@@ -999,6 +1000,10 @@ export async function executeScript(connectionId: string, database: string, sql:return invoke("execute_script", { connectionId, database, sql, schema });}+export async function executeScriptWith2pc(connectionId: string, database: string, statements: string[], schema?: string): Promise<TransactionLog> {+ return invoke("execute_script_with_2pc", { connectionId, database, statements, schema });+}+export async function executeInTransaction(connectionId: string, database: string, statements: string[], schema?: string): Promise<QueryResult> {return invoke("execute_in_transaction", { connectionId, database, statements, schema });}@@ -1284,6 +1289,10 @@ export async function prepareSchemaDiff(options: SchemaDiffPreparationOptions):return invoke("prepare_schema_diff", { options });}+export async function listDialectDataTypes(dialectName: string): Promise<string[]> {+ return invoke("list_dialect_data_types", { dialectName });+}+export async function generateSchemaSyncSql(diffs: TableDiff[], databaseType: DatabaseType, targetSchema?: string, functionDiffs?: FunctionDiff[], sequenceDiffs?: SequenceDiff[], ruleDiffs?: RuleDiff[], ownerDiffs?: OwnerDiff[], cascadeDelete?: boolean): Promise<string> {return invoke("generate_schema_sync_sql", {diffs,diff --git a/apps/desktop/src/lib/dataGrid/dataCompare.ts b/apps/desktop/src/lib/dataGrid/dataCompare.tsindex 4cfdb6ac17..24d66b9406 100644--- a/apps/desktop/src/lib/dataGrid/dataCompare.ts+++ b/apps/desktop/src/lib/dataGrid/dataCompare.ts@@ -2,6 +2,15 @@ import type { ColumnInfo, DatabaseType, QueryResult } from "@/types/database";export type DataCompareCellValue = QueryResult["rows"][number][number];+export type SamplingStrategy = "Random" | "ExtremeValues" | "Hybrid";++export interface DegradationThreshold {+ fullCompareMaxRows: number;+ sampleMaxRows: number;+ sampleSize: number;+ extremeSampleCount: number;+}+export interface DataCompareChangedCell {column: string;source: DataCompareCellValue;@@ -57,6 +66,9 @@ export interface DataCompareFromTablesOptions {columns: string[];keyColumns: string[];fetchBatchSize?: number;+ degradationThreshold?: DegradationThreshold;+ samplingStrategy?: SamplingStrategy;+ enableChecksum?: boolean;}export interface DataCompareMissingTargetOptions {@@ -70,6 +82,9 @@ export interface DataCompareMissingTargetOptions {targetTable: string;keyColumns: string[];fetchBatchSize?: number;+ degradationThreshold?: DegradationThreshold;+ samplingStrategy?: SamplingStrategy;+ enableChecksum?: boolean;}export interface DataCompareFromTablesPreparation extends DataComparePreparation {diff --git a/apps/desktop/src/lib/fieldMappingPresets.ts b/apps/desktop/src/lib/fieldMappingPresets.tsnew file mode 100644index 0000000000..9199c26909--- /dev/null+++ b/apps/desktop/src/lib/fieldMappingPresets.ts@@ -0,0 +1,112 @@+import type { FieldMappingEntry } from "@/types/schemaDiff";++export interface FieldMappingPreset {+ id: string;+ label: string;+ sourceDialect: string;+ targetDialect: string;+ mappings: FieldMappingEntry[];+}++export const FIELD_MAPPING_PRESETS: FieldMappingPreset[] = [+ {+ id: "mysql-to-dameng",+ label: "MySQL → 达梦 (DM)",+ sourceDialect: "mysql",+ targetDialect: "dameng",+ mappings: [+ { sourceType: "VARCHAR", targetType: "VARCHAR", paramStrategy: "preserve" },+ { sourceType: "CHAR", targetType: "CHAR", paramStrategy: "preserve" },+ { sourceType: "TEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "TINYTEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "MEDIUMTEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "LONGTEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "INT", targetType: "INT", paramStrategy: "preserve" },+ { sourceType: "BIGINT", targetType: "BIGINT", paramStrategy: "preserve" },+ { sourceType: "DECIMAL", targetType: "NUMERIC", paramStrategy: "preserve" },+ { sourceType: "FLOAT", targetType: "FLOAT", paramStrategy: "preserve" },+ { sourceType: "DOUBLE", targetType: "DOUBLE", paramStrategy: "preserve" },+ { sourceType: "DATE", targetType: "DATE", paramStrategy: "preserve" },+ { sourceType: "DATETIME", targetType: "TIMESTAMP", paramStrategy: "preserve" },+ { sourceType: "TIMESTAMP", targetType: "TIMESTAMP", paramStrategy: "preserve" },+ { sourceType: "BLOB", targetType: "BLOB", paramStrategy: "strip" },+ { sourceType: "JSON", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "TINYINT", targetType: "TINYINT", paramStrategy: "preserve" },+ { sourceType: "SMALLINT", targetType: "SMALLINT", paramStrategy: "preserve" },+ { sourceType: "BOOLEAN", targetType: "BOOLEAN", paramStrategy: "preserve" },+ ],+ },+ {+ id: "mysql-to-postgresql",+ label: "MySQL → PostgreSQL",+ sourceDialect: "mysql",+ targetDialect: "postgresql",+ mappings: [+ { sourceType: "VARCHAR", targetType: "VARCHAR", paramStrategy: "preserve" },+ { sourceType: "CHAR", targetType: "CHAR", paramStrategy: "preserve" },+ { sourceType: "TEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "TINYTEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "MEDIUMTEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "LONGTEXT", targetType: "TEXT", paramStrategy: "strip" },+ { sourceType: "INT", targetType: "INTEGER", paramStrategy: "preserve" },+ { sourceType: "BIGINT", targetType: "BIGINT", paramStrategy: "preserve" },+ { sourceType: "DECIMAL", targetType: "NUMERIC", paramStrategy: "preserve" },+ { sourceType: "FLOAT", targetType: "REAL", paramStrategy: "preserve" },+ { sourceType: "DOUBLE", targetType: "DOUBLE PRECISION", paramStrategy: "preserve" },+ { sourceType: "DATETIME", targetType: "TIMESTAMP", paramStrategy: "preserve" },+ { sourceType: "TIMESTAMP", targetType: "TIMESTAMP", paramStrategy: "preserve" },+ { sourceType: "BLOB", targetType: "BYTEA", paramStrategy: "strip" },+ { sourceType: "JSON", targetType: "JSONB", paramStrategy: "preserve" },+ { sourceType: "TINYINT", targetType: "SMALLINT", paramStrategy: "preserve" },+ { sourceType: "BOOLEAN", targetType: "BOOLEAN", paramStrategy: "preserve" },+ ],+ },+ {+ id: "mysql-to-oracle",+ label: "MySQL → Oracle",+ sourceDialect: "mysql",+ targetDialect: "oracle",+ mappings: [+ { sourceType: "VARCHAR", targetType: "VARCHAR2", paramStrategy: "preserve" },+ { sourceType: "CHAR", targetType: "CHAR", paramStrategy: "preserve" },+ { sourceType: "TEXT", targetType: "CLOB", paramStrategy: "strip" },+ { sourceType: "TINYTEXT", targetType: "CLOB", paramStrategy: "strip" },+ { sourceType: "MEDIUMTEXT", targetType: "CLOB", paramStrategy: "strip" },+ { sourceType: "LONGTEXT", targetType: "CLOB", paramStrategy: "strip" },+ { sourceType: "INT", targetType: "NUMBER", paramStrategy: "preserve" },+ { sourceType: "BIGINT", targetType: "NUMBER", paramStrategy: "preserve" },+ { sourceType: "DECIMAL", targetType: "NUMBER", paramStrategy: "preserve" },+ { sourceType: "FLOAT", targetType: "BINARY_FLOAT", paramStrategy: "preserve" },+ { sourceType: "DOUBLE", targetType: "BINARY_DOUBLE", paramStrategy: "preserve" },+ { sourceType: "DATETIME", targetType: "TIMESTAMP", paramStrategy: "preserve" },+ { sourceType: "TIMESTAMP", targetType: "TIMESTAMP", paramStrategy: "preserve" },+ { sourceType: "BLOB", targetType: "BLOB", paramStrategy: "strip" },+ { sourceType: "JSON", targetType: "CLOB", paramStrategy: "strip" },+ { sourceType: "BOOLEAN", targetType: "NUMBER(1)", paramStrategy: "custom", customParams: "(1)" },+ ],+ },+];++export function findPreset(sourceDialect: string, targetDialect: string): FieldMappingPreset | undefined {+ // Look for exact forward match+ const forward = FIELD_MAPPING_PRESETS.find((p) => p.sourceDialect === sourceDialect && p.targetDialect === targetDialect);+ if (forward) return forward;++ // Look for reverse match and auto-generate bidirectional preset+ const reverse = FIELD_MAPPING_PRESETS.find((p) => p.sourceDialect === targetDialect && p.targetDialect === sourceDialect);+ if (reverse) {+ return {+ id: `${reverse.id}-reverse`,+ label: `${reverse.label.split(" → ").reverse().join(" → ")}`,+ sourceDialect,+ targetDialect,+ mappings: reverse.mappings.map((m) => ({+ sourceType: m.targetType,+ targetType: m.sourceType,+ paramStrategy: m.paramStrategy === "custom" ? "strip" : m.paramStrategy,+ })),+ };+ }++ return undefined;+}diff --git a/apps/desktop/src/lib/schema/__tests__/deployTxResult.spec.ts b/apps/desktop/src/lib/schema/__tests__/deployTxResult.spec.tsnew file mode 100644index 0000000000..8c9bd410a2--- /dev/null+++ b/apps/desktop/src/lib/schema/__tests__/deployTxResult.spec.ts@@ -0,0 +1,89 @@+import { describe, expect, it } from "vitest";+import { buildDeployTxResult } from "@/lib/schema/deployTxResult";++const t = (key: string, params?: Record<string, any>) => {+ const fallback: Record<string, string> = {+ "diff.executeSuccess": "Executed successfully",+ "diff.deployMixed": "Deployment partially completed. Some statements may already be applied ({executedCount}/{statementCount}). DDL may not be transactional.",+ "diff.deployRolledBack": "All changes have been rolled back.",+ "diff.deployFailed": "Deployment failed: {status}",+ };+ let msg = fallback[key] || key;+ if (params) {+ for (const [k, v] of Object.entries(params)) {+ msg = msg.replace(`{${k}}`, String(v));+ }+ }+ return msg;+};++describe("buildDeployTxResult", () => {+ it("returns success for committed transaction", () => {+ const result = buildDeployTxResult({ status: "committed", transaction_id: "tx1", executedCount: 2 }, t);+ expect(result.success).toBe(true);+ expect(result.status).toBe("committed");+ expect(result.message).toBe("Executed successfully");+ expect(result.executedCount).toBe(2);+ });++ it("returns failure with mixed status for partially committed", () => {+ const result = buildDeployTxResult(+ {+ status: "mixed",+ participants: [{ id: "1" }, { id: "2" }],+ executedCount: 1,+ statementCount: 2,+ },+ t,+ );+ expect(result.success).toBe(false);+ expect(result.status).toBe("mixed");+ expect(result.message).toContain("partially completed");+ expect(result.message).toContain("1/2");+ expect(result.message).toContain("may not be transactional");+ expect(result.executedCount).toBe(1);+ expect(result.statementCount).toBe(2);+ });++ it("returns failure with rolled_back status and error detail", () => {+ const result = buildDeployTxResult({ status: "rolled_back", error: "syntax error near SELECT", executedCount: 0, statementCount: 2 }, t);+ expect(result.success).toBe(false);+ expect(result.status).toBe("rolled_back");+ expect(result.message).toContain("rolled back");+ expect(result.message).toContain("syntax error");+ expect(result.executedCount).toBe(0);+ expect(result.statementCount).toBe(2);+ });++ it("returns failure for unknown status", () => {+ const result = buildDeployTxResult({ status: "unknown" }, t);+ expect(result.success).toBe(false);+ expect(result.status).toBe("unknown");+ expect(result.message).toContain("unknown");+ });++ it("returns failure for null/undefined txLog", () => {+ const result = buildDeployTxResult(null, t);+ expect(result.success).toBe(false);+ expect(result.status).toBe("unknown");+ });++ it("maps MySQL-style partial DDL failure (1 of 2 applied) for UI", () => {+ const result = buildDeployTxResult(+ {+ status: "mixed",+ executedCount: 1,+ statementCount: 2,+ error: "Statement 2 failed: table already exists",+ metadata: { atomicity: "partial_effects_possible", ddl_atomic: false },+ },+ t,+ );+ expect(result.success).toBe(false);+ expect(result.status).toBe("mixed");+ expect(result.executedCount).toBe(1);+ expect(result.statementCount).toBe(2);+ expect(result.message).toContain("1/2");+ expect(result.message).toMatch(/may already be applied|may not be transactional/i);+ });+});diff --git a/apps/desktop/src/lib/schema/deployTxResult.ts b/apps/desktop/src/lib/schema/deployTxResult.tsnew file mode 100644index 0000000000..b17cbed53d--- /dev/null+++ b/apps/desktop/src/lib/schema/deployTxResult.ts@@ -0,0 +1,61 @@+export interface DeployTxResult {+ success: boolean;+ status?: string;+ message: string;+ affectedRows?: number;+ error?: string;+ executedCount?: number;+ statementCount?: number;+}++export function buildDeployTxResult(txLog: any, t: (key: string, params?: Record<string, any>) => string): DeployTxResult {+ const status = txLog?.status;+ const error = txLog?.error ?? txLog?.metadata?.error;+ const executedCount = txLog?.executedCount ?? txLog?.executed_count;+ const statementCount = txLog?.statementCount ?? txLog?.statement_count;+ const affectedRows = txLog?.metadata?.affected_rows ?? txLog?.affectedRows;++ if (status === "committed") {+ return {+ success: true,+ status,+ message: t("diff.executeSuccess"),+ affectedRows,+ executedCount,+ statementCount,+ };+ }+ if (status === "mixed") {+ return {+ success: false,+ status,+ message: t("diff.deployMixed", {+ participants: txLog?.participants?.length ?? 0,+ executedCount: executedCount ?? 0,+ statementCount: statementCount ?? 0,+ }),+ error,+ executedCount,+ statementCount,+ };+ }+ if (status === "rolled_back") {+ const detail = error ? `: ${error}` : "";+ return {+ success: false,+ status,+ message: `${t("diff.deployRolledBack")}${detail}`,+ error,+ executedCount: executedCount ?? 0,+ statementCount,+ };+ }+ return {+ success: false,+ status: status || "unknown",+ message: t("diff.deployFailed", { status: status || "unknown" }),+ error,+ executedCount,+ statementCount,+ };+}diff --git a/apps/desktop/src/lib/schema/schemaDiff.ts b/apps/desktop/src/lib/schema/schemaDiff.tsindex 2bd7f7b070..50db448700 100644--- a/apps/desktop/src/lib/schema/schemaDiff.ts+++ b/apps/desktop/src/lib/schema/schemaDiff.ts@@ -1,5 +1,111 @@import type { ColumnInfo, IndexInfo, ForeignKeyInfo, TriggerInfo, FunctionInfo, SequenceInfo, RuleInfo, OwnerInfo, DatabaseType, TableInfo } from "@/types/database";+const DIALECT_KIND_MAP: Record<string, string> = {+ mysql: "mysql",+ doris: "mysql",+ starrocks: "mysql",+ goldendb: "mysql",+ sundb: "mysql",+ databend: "mysql",+ gbase: "mysql",+ postgres: "postgres",+ gaussdb: "postgres",+ kwdb: "postgres",+ opengauss: "postgres",+ highgo: "postgres",+ vastbase: "postgres",+ kingbase: "postgres",+ firebird: "postgres",+ redshift: "postgres",+ vertica: "postgres",+ exasol: "postgres",+ sqlite: "sqlite",+ rqlite: "sqlite",+ turso: "sqlite",+ duckdb: "duckdb",+ sqlserver: "sql_server",+ access: "sql_server",+ oracle: "oracle",+ dameng: "oracle",+ "oceanbase-oracle": "oracle",+ iris: "oracle",+ yashandb: "oracle",+ xugu: "oracle",+ h2: "h2",+ clickhouse: "click_house",+ manticoresearch: "manticore_search",+ informix: "informix",+ questdb: "questdb",+};++export function databaseTypeToDialectKind(dbType: DatabaseType): string {+ return DIALECT_KIND_MAP[dbType] ?? "unsupported";+}++const DIALECT_ALIAS_MAP: Record<string, string> = {+ access: "sql_server",+ mssql: "sql_server",+ "sql server": "sql_server",+ postgresql: "postgres",+ sqlite3: "sqlite",+ "oceanbase-oracle": "oracle",+ oceanbase: "oracle",+ dameng: "oracle",+ iris: "oracle",+ yashandb: "oracle",+ xugu: "oracle",+ gaussdb: "postgres",+ kwdb: "postgres",+ opengauss: "postgres",+ highgo: "postgres",+ vastbase: "postgres",+ kingbase: "postgres",+ firebird: "postgres",+ redshift: "postgres",+ vertica: "postgres",+ exasol: "postgres",+ doris: "mysql",+ starrocks: "mysql",+ goldendb: "mysql",+ sundb: "mysql",+ databend: "mysql",+ gbase: "mysql",+ rqlite: "sqlite",+ turso: "sqlite",+ manticore: "manticore_search",+ questdb: "questdb",+ clickhouse: "click_house",+};++export function normalizeDialectKind(input: string): string {+ const lower = input.trim().toLowerCase();+ if (DIALECT_KIND_MAP[lower]) return DIALECT_KIND_MAP[lower];+ if (DIALECT_ALIAS_MAP[lower]) return DIALECT_ALIAS_MAP[lower];+ return lower;+}++function levenshteinDistance(a: string, b: string): number {+ const m = a.length;+ const n = b.length;+ if (m === 0) return n;+ if (n === 0) return m;+ let prev = Array.from({ length: n + 1 }, (_, i) => i);+ for (let i = 1; i <= m; i++) {+ const curr = [i];+ for (let j = 1; j <= n; j++) {+ curr[j] = a[i - 1] === b[j - 1] ? prev[j - 1] : Math.min(prev[j], curr[j - 1], prev[j - 1]) + 1;+ }+ prev = curr;+ }+ return prev[n];+}++function nameSimilarity(a: string, b: string): number {+ const maxLen = Math.max(a.length, b.length);+ if (maxLen === 0) return 1;+ return 1 - levenshteinDistance(a, b) / maxLen;+}+export interface ColumnDiff {type: "added" | "removed" | "modified";name: string;@@ -65,7 +171,7 @@ export interface OwnerDiff {}export interface TableDiff {- type: "added" | "removed" | "modified";+ type: "added" | "removed" | "modified" | "renamed";objectType?: "table" | "view";name: string;columns?: ColumnDiff[];@@ -88,6 +194,11 @@ export interface TableSchemaDetail {ddl?: string;}+export interface FieldMappingEntry {+ sourceType: string;+ targetType: string;+}+export interface SchemaDiffPreparationOptions {sourceTables: TableInfo[];targetTables: TableInfo[];@@ -106,8 +217,58 @@ export interface SchemaDiffPreparationOptions {ignoreComments?: boolean;cascadeDelete?: boolean;compareColumnOrder?: boolean;+ detectRenames?: boolean;+ detectTableRenames?: boolean;+ renameThreshold?: number;+ enableRollback?: boolean;+ batchPatterns?: string[];+ sourceDialect?: string;+ targetDialect?: string;+ compatibilityThreshold?: number;+ fieldMappings?: FieldMappingEntry[];+}++export interface RenameCandidate {+ sourceName: string;+ targetName: string;+ score: number;}+export interface CompatibilityWarning {+ table: string;+ column: string;+ sourceType: string;+ targetType: string;+ risk: string;+ message: string;+}++export interface PermissionDiff {+ objectName: string;+ permissionType: string;+ sourcePermission: string | null;+ targetPermission: string | null;+}++export interface DependencyNode {+ tableName: string;+ dependsOn: string[];+ dependedBy: string[];+}++export interface DependencyGraph {+ nodes: DependencyNode[];+}++export interface MissingRollbackObject {+ kind: string;+ name: string;+ table?: string;+ reason: string;+}++export type RollbackCompleteness = "complete" | "incomplete";+export interface SchemaDiffPreparation {diffs: TableDiff[];functionDiffs?: FunctionDiff[];@@ -115,6 +276,15 @@ export interface SchemaDiffPreparation {ruleDiffs?: RuleDiff[];ownerDiffs?: OwnerDiff[];syncSql: string;+ rollbackSyncSql?: string;+ rollbackCompleteness?: RollbackCompleteness;+ missingRollbackObjects?: MissingRollbackObject[];+ renameCandidates?: RenameCandidate[];+ rollbackGraph?: unknown;+ compatibilityWarnings?: CompatibilityWarning[];+ permissionDiffs?: PermissionDiff[];+ permissionSyncSql?: string;+ dependencyGraph?: DependencyGraph;}const MYSQL_LIKE_SCHEMA_DIFF_TARGET_TYPES = new Set<DatabaseType>(["mysql", "doris", "starrocks", "goldendb", "sundb", "databend", "gbase"]);@@ -146,10 +316,17 @@ export interface SchemaDiffObject {sourceDdl?: string;targetDdl?: string;deploySql?: string;+ rollbackDdl?: string;changes?: string[];children?: SchemaDiffObject[];/** Function arguments signature (for PostgreSQL overloaded functions) */arguments?: string;+ renameMetadata?: {+ confirmed: boolean;+ sourceName?: string;+ targetName?: string;+ score?: number;+ };}export interface SchemaDiffGroup {@@ -164,6 +341,7 @@ export interface SchemaDiffGroup {export function getOperationType(diffType: string): DiffOperationType {switch (diffType) {case "modified":+ case "renamed":return "modify";case "added":return "create";@@ -203,23 +381,27 @@ function buildSequenceDdl(seq: SequenceInfo): string {return parts.join("\n");}-export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiffs: FunctionDiff[] = [], sequenceDiffs: SequenceDiff[] = [], ruleDiffs: RuleDiff[] = [], ownerDiffs: OwnerDiff[] = []): SchemaDiffObject[] {+export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiffs: FunctionDiff[] = [], sequenceDiffs: SequenceDiff[] = [], ruleDiffs: RuleDiff[] = [], ownerDiffs: OwnerDiff[] = [], renameCandidates?: RenameCandidate[]): SchemaDiffObject[] {const objects: SchemaDiffObject[] = [];for (const diff of tableDiffs) {const opType = getOperationType(diff.type);+ const isRenamed = diff.type === "renamed";+ const newName = isRenamed && renameCandidates ? (renameCandidates.find((rc) => rc.sourceName === diff.name)?.targetName ?? diff.name) : undefined;+const obj: SchemaDiffObject = {id: `table-${diff.name}`,operationType: opType,objectKind: diff.objectType === "view" ? "view" : "table",name: diff.name,sourceName: diff.type === "added" ? undefined : diff.name,- targetName: diff.type === "removed" ? undefined : diff.name,+ targetName: diff.type === "removed" ? undefined : isRenamed ? newName : diff.name,selected: opType !== "none",sourceDdl: diff.ddl,targetDdl: diff.targetDdl,- deploySql: diff.syncSql,+ deploySql: isRenamed && newName ? (diff.objectType === "view" ? `ALTER VIEW ${diff.name} RENAME TO ${newName};` : `RENAME TABLE ${diff.name} TO ${newName};`) : diff.syncSql,changes: diff.columns?.flatMap((c) => c.changes || []),+ renameMetadata: isRenamed && newName ? { confirmed: true, sourceName: diff.name, targetName: newName, score: renameCandidates?.find((rc) => rc.sourceName === diff.name)?.score } : undefined,children: [...(diff.columns?.map((c) => ({id: `col-${diff.name}-${c.name}`,@@ -324,6 +506,24 @@ export function convertToSchemaDiffObjects(tableDiffs: TableDiff[], functionDiff});}+ // Pre-mark rename candidates on diff objects (for UI display before user confirms)+ if (renameCandidates && renameCandidates.length > 0) {+ for (const rc of renameCandidates) {+ for (const obj of objects) {+ // Backend-detected renames: diff_type = "renamed", already has metadata set above+ if (obj.renameMetadata) continue;+ // Legacy: mark rename candidates on delete+create pairs (fallback for older backends)+ if (obj.operationType === "delete" && obj.name === rc.sourceName) {+ obj.renameMetadata = { confirmed: false, targetName: rc.targetName, score: rc.score };+ }+ if (obj.operationType === "create" && obj.name === rc.targetName) {+ obj.renameMetadata = { confirmed: false, sourceName: rc.sourceName, score: rc.score };+ obj.sourceName = rc.sourceName;+ }+ }+ }+ }+return objects;}@@ -382,6 +582,133 @@ function generateDropSql(obj: SchemaDiffObject): string {return `DROP ${sqlType} IF EXISTS ${obj.name};`;}+/** Detect column renames in raw SQL and replace DROP+ADD with RENAME COLUMN. */+export function injectColumnRenameSql(sql: string, diffs: TableDiff[], threshold: number, reverse = false): string {+ if (!sql || !threshold) return sql;++ // Build rename pairs: for each table, match removed columns with added columns by similarity+ const replacements: { table: string; oldName: string; newName: string }[] = [];+ for (const diff of diffs) {+ if (!diff.columns || diff.type !== "modified") continue;+ const removedCols = diff.columns.filter((c) => c.type === "removed");+ const addedCols = diff.columns.filter((c) => c.type === "added");+ if (removedCols.length === 0 || addedCols.length === 0) continue;++ const used = new Set<string>();+ for (const rc of removedCols) {+ let best: (typeof addedCols)[0] | null = null;+ let bestSim = 0;+ for (const ac of addedCols) {+ if (used.has(ac.name)) continue;+ const sim = nameSimilarity(rc.name, ac.name);+ if (sim > bestSim) {+ bestSim = sim;+ best = ac;+ }+ }+ if (best && bestSim >= threshold) {+ // rc = removed column (exists in source, NOT in target → needs to be ADDED to target)+ // best = added column (exists in target, NOT in source → needs to be DROPPED from target)+ // To sync target → source: rename target's "best.name" to source's "rc.name"+ replacements.push({ table: diff.name, oldName: best.name, newName: rc.name });+ used.add(best.name);+ }+ }+ }++ if (replacements.length === 0) return sql;++ // Process each ALTER TABLE block+ const lines = sql.split("\n");+ const out: string[] = [];+ let currentTable = "";+ let inAlter = false;+ let alterStart = -1;+ const tableRenames = new Map<string, typeof replacements>();++ for (const r of replacements) {+ const list = tableRenames.get(r.table) || [];+ list.push(r);+ tableRenames.set(r.table, list);+ }++ for (let i = 0; i < lines.length; i++) {+ const line = lines[i];+ const trimmed = line.trim();++ // Detect ALTER TABLE <table>+ const alterMatch = trimmed.match(/^ALTER\s+TABLE\s+(?:`[^`]+`\.)?`?(\w+)`?/i);+ if (alterMatch && !inAlter) {+ currentTable = alterMatch[1];+ const renames = tableRenames.get(currentTable);+ if (renames) {+ inAlter = true;+ alterStart = i;+ continue; // skip current ALTER TABLE line, we'll rebuild it+ }+ }++ if (!inAlter) {+ out.push(line);+ continue;+ }++ // Inside an ALTER TABLE block being rewritten+ const endOfAlter = trimmed === ";" || trimmed.endsWith(";") || (i + 1 < lines.length && lines[i + 1].trim().toUpperCase().startsWith("ALTER")) || i === lines.length - 1;++ if (endOfAlter) {+ const renames = tableRenames.get(currentTable)!;+ // Emit RENAME COLUMN statements+ out.push(`-- Alter table: ${currentTable} (column renames detected)`);+ for (const r of renames) {+ const fromName = reverse ? r.newName : r.oldName;+ const toName = reverse ? r.oldName : r.newName;+ out.push(`ALTER TABLE ${currentTable} RENAME COLUMN ${fromName} TO ${toName};`);+ }+ // Collect remaining ALTER clauses (non-renamed columns)+ const remaining: string[] = [];+ for (let j = alterStart + 1; j <= i; j++) {+ const l = lines[j].trim();+ if (!l || l === ";") continue;+ // Forward: ADD for newName, DROP for oldName. Reverse: ADD for oldName, DROP for newName.+ const isAddRename = l.toUpperCase().startsWith("ADD COLUMN") && renames.some((r) => l.includes(reverse ? r.oldName : r.newName));+ const isDropRename = l.toUpperCase().startsWith("DROP COLUMN") && renames.some((r) => l.includes(reverse ? r.newName : r.oldName));+ if (isAddRename || isDropRename) continue;+ // Clean trailing comma if next line is removed+ let cleaned = l;+ let nextIdx = j + 1;+ while (nextIdx <= i) {+ const nextLine = lines[nextIdx].trim();+ if (!nextLine) {+ nextIdx++;+ continue;+ }+ const nextIsAddRename = nextLine.toUpperCase().startsWith("ADD COLUMN") && renames.some((r) => nextLine.includes(reverse ? r.oldName : r.newName));+ const nextIsDropRename = nextLine.toUpperCase().startsWith("DROP COLUMN") && renames.some((r) => nextLine.includes(reverse ? r.newName : r.oldName));+ if (nextIsAddRename || nextIsDropRename) {+ cleaned = cleaned.replace(/,\s*$/, "");+ }+ break;+ }+ remaining.push(cleaned);+ }+ if (remaining.length > 0) {+ const last = remaining[remaining.length - 1].replace(/,\s*$/, "").replace(/;\s*$/, "");+ remaining[remaining.length - 1] = last;+ out.push(`ALTER TABLE ${currentTable}`);+ for (const r of remaining) {+ out.push(` ${r}`);+ }+ out.push(";");+ }+ inAlter = false;+ currentTable = "";+ }+ }++ return out.join("\n").trim();+}+export interface ObjectTypeGroup {kind: DiffObjectKind;label: string;diff --git a/apps/desktop/src/lib/schema/schemaDiffOptions.ts b/apps/desktop/src/lib/schema/schemaDiffOptions.tsindex 45cd1156e9..07847bafad 100644--- a/apps/desktop/src/lib/schema/schemaDiffOptions.ts+++ b/apps/desktop/src/lib/schema/schemaDiffOptions.ts@@ -23,6 +23,9 @@ export const POSTGRES_SCHEMA_DIFF_OPTIONS: SchemaDiffOptionItem[] = [{ id: "cascadeDelete", labelKey: "schemaDiff.options.cascadeDelete", defaultChecked: false },{ id: "sequenceLastValues", labelKey: "schemaDiff.options.sequenceLastValues", defaultChecked: true },{ id: "compareColumnOrder", labelKey: "schemaDiff.options.compareColumnOrder", defaultChecked: false },+ { id: "detectRenames", labelKey: "schemaDiff.options.detectRenames", defaultChecked: false },+ { id: "detectTableRenames", labelKey: "schemaDiff.options.detectTableRenames", defaultChecked: false },+ { id: "enableRollback", labelKey: "schemaDiff.options.enableRollback", defaultChecked: false },];export const SCHEMA_DIFF_OPTIONS_BY_DB_TYPE: Record<string, SchemaDiffOptionItem[]> = {diff --git a/apps/desktop/src/types/database.ts b/apps/desktop/src/types/database.tsindex aca7f33e02..6dc9910d84 100644--- a/apps/desktop/src/types/database.ts+++ b/apps/desktop/src/types/database.ts@@ -640,6 +640,26 @@ export interface QueryResultRun {tableMeta?: QueryTab["tableMeta"];}+export interface ParticipantInfo {+ id: string;+ name: string;+ role: string;+}++export interface TransactionLog {+ transaction_id: string;+ status: string;+ participants: ParticipantInfo[];+ created_at: string;+ updated_at: string;+ metadata: unknown;+ /** camelCase fields from SchemaDiffDeployResult */+ transactionId?: string;+ executedCount?: number;+ statementCount?: number;+ error?: string;+}+export interface SqlTextSpan {start_line: number;start_column: number;diff --git a/apps/desktop/src/types/governance.ts b/apps/desktop/src/types/governance.tsnew file mode 100644index 0000000000..9a6e8e9554--- /dev/null+++ b/apps/desktop/src/types/governance.ts@@ -0,0 +1,135 @@+export interface ConfigAuditEntry {+ id: string;+ timestamp: string;+ operator: string;+ reason: string;+ keyPath: string;+ changeDiff: unknown;+ configSnapshot: unknown;+}++export interface ConfigVersionSnapshot {+ id: string;+ keyPath: string;+ version: number;+ snapshotJson: unknown;+ checksum: string;+ createdAt: string;+}++export interface AuditQuery {+ keyPath?: string;+ operator?: string;+ limit?: number;+ offset?: number;+}++export interface AuditSummary {+ totalEntries: number;+ entries: ConfigAuditEntry[];+}++export type ApprovalStatus = "draft" | "pending_approval" | "approved" | "rejected";++export interface ApprovalRecord {+ id: string;+ configDomain: string;+ changeDescription: string;+ status: ApprovalStatus;+ requester: string;+ reviewer?: string;+ reviewedAt?: string;+ webhookUrl?: string;+ draftConfigJson: unknown;+ createdAt: string;+ updatedAt: string;+}++export interface DriftAlert {+ id: string;+ sourceEnv: string;+ targetEnv: string;+ configKey: string;+ expectedChecksum: string;+ actualChecksum: string;+ detailsJson: unknown;+ detectedAt: string;+ acknowledged: boolean;+}++export interface DriftReport {+ sourceEnv: string;+ targetEnv: string;+ keyPath: string;+ sourceChecksum: string;+ targetChecksum: string;+ mismatchedFields: string[];+ sourceChangedAt?: string;+ detectedAt: string;+}++export type DdlRiskLevel = "safe" | "caution" | "dangerous" | "blocked";++export type ExecStrategy = "online" | "lazy" | "offline" | "batch";++export interface LockInfo {+ lockType: string;+ objects: string[];+ duration: string;+}++export interface ImpactReport {+ overallRisk: DdlRiskLevel;+ ddlRiskLevel: DdlRiskLevel;+ estimatedLocks: LockInfo[];+ estimatedTotalDuration: string;+ recommendedStrategy: ExecStrategy;+ warnings: string[];+ requiresMaintenanceWindow: boolean;+ isReversible: boolean;+}++export type OscExecutionStatus = "preparing" | "copying" | "cut_over" | "completed" | "failed" | "postponed";++export interface OscStatus {+ toolType: "gh-ost" | "pt-osc";+ tableName: string;+ status: OscExecutionStatus;+ progressPercent: number;+ estimatedRemainingSecs?: number;+ error?: string;+}++export type DegradationLevel = "full" | "sample" | "skip_with_risk";++export interface BusinessTag {+ key: string;+ value: string;+ description: string;+ immutable: boolean;+}++export interface ConflictItem {+ objectName: string;+ conflictType: string;+ sourceValue: string;+ targetValue: string;+ autoResolvable: boolean;+}++export interface RebasePlan {+ id: string;+ baselineId: string;+ conflicts: ConflictItem[];+ totalObjects: number;+ autoResolvedCount: number;+ createdAt: string;+}++export interface ConfigDriftSummary {+ sourceEnv: string;+ targetEnv: string;+ driftCount: number;+ lastDetectedAt: string;+ hasUnacknowledged: boolean;+}diff --git a/apps/desktop/src/types/schemaDiff.ts b/apps/desktop/src/types/schemaDiff.tsindex 4a3444ab91..4de47387d1 100644--- a/apps/desktop/src/types/schemaDiff.ts+++ b/apps/desktop/src/types/schemaDiff.ts@@ -20,6 +20,24 @@ export interface SchemaDiffCompareOptions {tableIncludePattern: string;tableExcludePattern: string;tableFilterPriority: SchemaDiffTableFilterPriority;+ detectRenames: boolean;+ renameThreshold: number;+ detectTableRenames: boolean;+ enableRollback: boolean;+ batchPatterns: string;+ sourceDialect: string;+ targetDialect: string;+ compatibilityThreshold: number;+ fieldMappings: FieldMappingEntry[];+}++export type FieldMappingParamStrategy = "preserve" | "strip" | "custom";++export interface FieldMappingEntry {+ sourceType: string;+ targetType: string;+ paramStrategy: FieldMappingParamStrategy;+ customParams?: string;}export interface SchemaDiffConfig {@@ -69,6 +87,15 @@ export const DEFAULT_POSTGRES_OPTIONS: SchemaDiffCompareOptions = {tableIncludePattern: "",tableExcludePattern: "",tableFilterPriority: "exclude",+ detectRenames: false,+ renameThreshold: 0.5,+ detectTableRenames: false,+ enableRollback: false,+ batchPatterns: "",+ sourceDialect: "",+ targetDialect: "",+ compatibilityThreshold: 0.5,+ fieldMappings: [],};export const DEFAULT_MYSQL_OPTIONS: SchemaDiffCompareOptions = {@@ -91,6 +118,15 @@ export const DEFAULT_MYSQL_OPTIONS: SchemaDiffCompareOptions = {tableIncludePattern: "",tableExcludePattern: "",tableFilterPriority: "exclude",+ detectRenames: false,+ renameThreshold: 0.5,+ detectTableRenames: false,+ enableRollback: false,+ batchPatterns: "",+ sourceDialect: "",+ targetDialect: "",+ compatibilityThreshold: 0.5,+ fieldMappings: [],};export function getDefaultOptionsForDbType(dbType: string): SchemaDiffCompareOptions {diff --git a/crates/dbx-core/Cargo.toml b/crates/dbx-core/Cargo.tomlindex 2f2320d467..cbd616e6a5 100644--- a/crates/dbx-core/Cargo.toml+++ b/crates/dbx-core/Cargo.toml@@ -98,4 +98,9 @@ zip = { version = "4", default-features = false, features = ["deflate"] }flate2 = "1"tar = "0.4"sysinfo = { version = "0.32", features = ["system"] }+serde_yaml = "0.9"+minijinja = "2"+notify = { version = "7", default-features = false, features = ["macos_kqueue"] }+arc-swap = "1"+insta = { version = "1", features = ["json", "glob"] }tempfile = "3"diff --git a/crates/dbx-core/build.rs b/crates/dbx-core/build.rsnew file mode 100644index 0000000000..3f8e5da0a8--- /dev/null+++ b/crates/dbx-core/build.rs@@ -0,0 +1,51 @@+use std::env;+use std::path::Path;++fn main() {+ let cargo_manifest_dir_str = env::var("CARGO_MANIFEST_DIR").unwrap();+ let cargo_manifest_dir = Path::new(&cargo_manifest_dir_str);+ let dialects_dir = cargo_manifest_dir.join("..").join("..").join("plugins").join("dialects");+ let dialects_dir = std::fs::canonicalize(&dialects_dir).unwrap_or(dialects_dir);++ let out_dir_str = env::var("OUT_DIR").unwrap();+ let dest_path = Path::new(&out_dir_str).join("core_dialects.rs");++ let mut entries: Vec<_> = std::fs::read_dir(&dialects_dir)+ .expect("Cannot read plugins/dialects directory")+ .filter_map(|e| e.ok())+ .filter(|e| e.path().extension().is_some_and(|ext| ext == "yaml" || ext == "yml"))+ .collect();+ entries.sort_by_key(|e| e.file_name());++ // Watch the directory itself so additions/removals of dialect files trigger a rebuild.+ println!("cargo::rerun-if-changed={}", dialects_dir.to_str().unwrap());++ let mut code = String::from("{\n");++ for entry in &entries {+ let path = entry.path();+ let canonical = std::fs::canonicalize(&path).unwrap_or_else(|_| path.clone());+ let file_name = path.file_stem().unwrap().to_str().unwrap();+ let path_str = canonical.to_str().unwrap();++ // Watch each dialect file individually. Editing a single YAML must invalidate+ // the embedded `core_dialects.rs`, otherwise the compiled binary keeps a stale+ // type catalog (e.g. old type names) and silently misbehaves (see field mapping).+ println!("cargo::rerun-if-changed={}", path_str);++ code.push_str("match crate::sql_dialect::dialect_loader::DialectPluginLoader::load_from_string(\n");+ code.push_str(&format!(" include_str!(\"{}\"),\n", path_str.replace('\\', "\\\\")));+ code.push_str(" None,\n");+ code.push_str(") {\n");+ code.push_str(" Ok((_kind, yaml, descriptor)) => {\n");+ code.push_str(" let name = yaml.dialect.name.clone();\n");+ code.push_str(" registry.register_descriptor(&name, descriptor, yaml);\n");+ code.push_str(" }\n");+ code.push_str(&format!(" Err(e) => log::warn!(\"Failed to load core dialect '{}': {{e}}\"),\n", file_name));+ code.push_str("};\n");+ }++ code.push_str("}\n");++ std::fs::write(&dest_path, code).expect("Failed to write core_dialects.rs");+}diff --git a/crates/dbx-core/src/config/expression.rs b/crates/dbx-core/src/config/expression.rsnew file mode 100644index 0000000000..ed2011e64c--- /dev/null+++ b/crates/dbx-core/src/config/expression.rs@@ -0,0 +1,307 @@+use serde::{Deserialize, Serialize};+use std::collections::HashMap;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+pub enum Expression {+ EnvVar(String),+ Ref(String),+ Eval(String),+ Literal(String),+}++pub fn parse_expression(input: &str) -> Expression {+ let trimmed = input.trim();+ if trimmed.starts_with("${env:") && trimmed.ends_with('}') {+ let inner = &trimmed[6..trimmed.len() - 1];+ Expression::EnvVar(inner.to_string())+ } else if trimmed.starts_with("${ref:") && trimmed.ends_with('}') {+ let inner = &trimmed[6..trimmed.len() - 1];+ Expression::Ref(inner.to_string())+ } else if trimmed.starts_with("${eval:") && trimmed.ends_with('}') {+ let inner = &trimmed[7..trimmed.len() - 1];+ Expression::Eval(inner.to_string())+ } else {+ Expression::Literal(input.to_string())+ }+}++pub fn resolve_env_var(name: &str) -> Result<String, String> {+ std::env::var(name).map_err(|_| format!("Environment variable '${name}' not set"))+}++pub fn resolve_ref(path: &str, merged: &HashMap<String, serde_json::Value>) -> Result<serde_json::Value, String> {+ let parts: Vec<&str> = path.split('.').collect();+ let key = parts[0];+ let value = merged.get(key).ok_or_else(|| format!("Config reference '${path}' not found in merged config"))?;++ if parts.len() == 1 {+ return Ok(value.clone());+ }++ let mut current = value;+ for part in &parts[1..] {+ match current {+ serde_json::Value::Object(map) => {+ current =+ map.get(*part).ok_or_else(|| format!("Config reference '${path}': key '{part}' not found"))?;+ }+ _ => {+ return Err(format!("Config reference '${path}': intermediate value is not an object"));+ }+ }+ }+ Ok(current.clone())+}++/// Parses JSON literals only (numbers, booleans, null, quoted strings).+/// Does NOT support arithmetic, operators, or function calls.+fn eval_simple(expr: &str) -> Result<serde_json::Value, String> {+ let expr = expr.trim();++ if let Ok(v) = expr.parse::<i64>() {+ return Ok(serde_json::Value::Number(v.into()));+ }++ if let Ok(v) = expr.parse::<f64>() {+ if let Some(n) = serde_json::Number::from_f64(v) {+ return Ok(serde_json::Value::Number(n));+ }+ }++ if expr == "true" {+ return Ok(serde_json::Value::Bool(true));+ }+ if expr == "false" {+ return Ok(serde_json::Value::Bool(false));+ }+ if expr == "null" {+ return Ok(serde_json::Value::Null);+ }++ if expr.starts_with('"') && expr.ends_with('"') && expr.len() >= 2 {+ return Ok(serde_json::Value::String(expr[1..expr.len() - 1].to_string()));+ }++ Err(format!("Cannot evaluate expression: '{expr}'"))+}++pub fn resolve_expression(+ expression: &Expression,+ merged: &HashMap<String, serde_json::Value>,+) -> Result<serde_json::Value, String> {+ match expression {+ Expression::EnvVar(name) => {+ let val = resolve_env_var(name)?;+ Ok(serde_json::Value::String(val))+ }+ Expression::Ref(path) => resolve_ref(path, merged),+ Expression::Eval(expr) => eval_simple(expr),+ Expression::Literal(val) => Ok(serde_json::Value::String(val.clone())),+ }+}++pub fn resolve_all_expressions_in_value(+ value: &serde_json::Value,+ merged: &HashMap<String, serde_json::Value>,+) -> Result<serde_json::Value, String> {+ match value {+ serde_json::Value::String(s) => {+ let expr = parse_expression(s);+ resolve_expression(&expr, merged)+ }+ serde_json::Value::Object(map) => {+ let mut resolved = serde_json::Map::new();+ for (k, v) in map {+ resolved.insert(k.clone(), resolve_all_expressions_in_value(v, merged)?);+ }+ Ok(serde_json::Value::Object(resolved))+ }+ serde_json::Value::Array(arr) => {+ let mut resolved = Vec::new();+ for v in arr {+ resolved.push(resolve_all_expressions_in_value(v, merged)?);+ }+ Ok(serde_json::Value::Array(resolved))+ }+ other => Ok(other.clone()),+ }+}++pub fn apply_expression_resolution(+ config: &mut HashMap<String, serde_json::Value>,+ merged: &HashMap<String, serde_json::Value>,+) -> Result<(), String> {+ let mut resolved = HashMap::new();+ for (k, v) in config.iter() {+ resolved.insert(k.clone(), resolve_all_expressions_in_value(v, merged)?);+ }+ config.extend(resolved);+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_parse_env_var_expression() {+ assert_eq!(parse_expression("${env:HOME}"), Expression::EnvVar("HOME".to_string()));+ }++ #[test]+ fn test_parse_ref_expression() {+ assert_eq!(parse_expression("${ref:database.host}"), Expression::Ref("database.host".to_string()));+ }++ #[test]+ fn test_parse_eval_expression() {+ assert_eq!(parse_expression("${eval:42}"), Expression::Eval("42".to_string()));+ }++ #[test]+ fn test_parse_literal() {+ assert_eq!(parse_expression("hello"), Expression::Literal("hello".to_string()));+ assert_eq!(parse_expression("${not-an-expr}"), Expression::Literal("${not-an-expr}".to_string()));+ }++ #[test]+ fn test_resolve_env_var() {+ std::env::set_var("DBX_TEST_VAR", "test_value");+ let result = resolve_env_var("DBX_TEST_VAR");+ assert_eq!(result.unwrap(), "test_value");+ std::env::remove_var("DBX_TEST_VAR");+ }++ #[test]+ fn test_resolve_env_var_missing() {+ let result = resolve_env_var("DBX_NONEXISTENT_VAR_12345");+ assert!(result.is_err());+ }++ #[test]+ fn test_resolve_ref_simple() {+ let mut merged = HashMap::new();+ merged.insert("host".to_string(), serde_json::Value::String("localhost".to_string()));++ let result = resolve_ref("host", &merged).unwrap();+ assert_eq!(result, serde_json::Value::String("localhost".to_string()));+ }++ #[test]+ fn test_resolve_ref_nested() {+ let mut merged = HashMap::new();+ let mut db = serde_json::Map::new();+ db.insert("host".to_string(), serde_json::Value::String("pg.example.com".to_string()));+ db.insert("port".to_string(), serde_json::Value::Number(serde_json::Number::from(5432)));+ merged.insert("database".to_string(), serde_json::Value::Object(db));++ let host = resolve_ref("database.host", &merged).unwrap();+ assert_eq!(host, serde_json::Value::String("pg.example.com".to_string()));++ let port = resolve_ref("database.port", &merged).unwrap();+ assert_eq!(port, serde_json::Value::Number(serde_json::Number::from(5432)));+ }++ #[test]+ fn test_resolve_ref_missing() {+ let merged = HashMap::new();+ let result = resolve_ref("nonexistent", &merged);+ assert!(result.is_err());+ }++ #[test]+ fn test_eval_simple_integer() {+ let result = eval_simple("42").unwrap();+ assert_eq!(result, serde_json::Value::Number(serde_json::Number::from(42)));+ }++ #[test]+ fn test_eval_simple_bool() {+ assert_eq!(eval_simple("true").unwrap(), serde_json::Value::Bool(true));+ assert_eq!(eval_simple("false").unwrap(), serde_json::Value::Bool(false));+ }++ #[test]+ fn test_eval_simple_null() {+ assert_eq!(eval_simple("null").unwrap(), serde_json::Value::Null);+ }++ #[test]+ fn test_eval_simple_string() {+ let result = eval_simple(r#""hello world""#).unwrap();+ assert_eq!(result, serde_json::Value::String("hello world".to_string()));+ }++ #[test]+ fn test_eval_simple_invalid() {+ assert!(eval_simple("some_random_text").is_err());+ }++ #[test]+ fn test_resolve_expression_env_var() {+ std::env::set_var("DBX_TEST_PORT", "8080");+ let expr = Expression::EnvVar("DBX_TEST_PORT".to_string());+ let merged = HashMap::new();+ let result = resolve_expression(&expr, &merged).unwrap();+ assert_eq!(result, serde_json::Value::String("8080".to_string()));+ std::env::remove_var("DBX_TEST_PORT");+ }++ #[test]+ fn test_resolve_expression_ref() {+ let mut merged = HashMap::new();+ merged.insert("host".to_string(), serde_json::Value::String("db.local".to_string()));+ let expr = Expression::Ref("host".to_string());+ let result = resolve_expression(&expr, &merged).unwrap();+ assert_eq!(result, serde_json::Value::String("db.local".to_string()));+ }++ #[test]+ fn test_resolve_expression_eval() {+ let expr = Expression::Eval("true".to_string());+ let merged = HashMap::new();+ let result = resolve_expression(&expr, &merged).unwrap();+ assert_eq!(result, serde_json::Value::Bool(true));+ }++ #[test]+ fn test_resolve_expression_literal() {+ let expr = Expression::Literal("hello".to_string());+ let merged = HashMap::new();+ let result = resolve_expression(&expr, &merged).unwrap();+ assert_eq!(result, serde_json::Value::String("hello".to_string()));+ }++ #[test]+ fn test_resolve_all_in_nested_object() {+ let mut merged = HashMap::new();+ merged.insert("default_host".to_string(), serde_json::Value::String("pg.example.com".to_string()));++ let mut obj = serde_json::Map::new();+ obj.insert("host".to_string(), serde_json::Value::String("${ref:default_host}".to_string()));+ obj.insert("port".to_string(), serde_json::Value::Number(serde_json::Number::from(5432)));+ obj.insert("debug".to_string(), serde_json::Value::String("${eval:true}".to_string()));++ let input = serde_json::Value::Object(obj);+ let result = resolve_all_expressions_in_value(&input, &merged).unwrap();++ let obj = result.as_object().unwrap();+ assert_eq!(obj.get("host").unwrap(), &serde_json::Value::String("pg.example.com".to_string()));+ assert_eq!(obj.get("port").unwrap(), &serde_json::Value::Number(serde_json::Number::from(5432)));+ assert_eq!(obj.get("debug").unwrap(), &serde_json::Value::Bool(true));+ }++ #[test]+ fn test_apply_expression_resolution() {+ let mut merged = HashMap::new();+ merged.insert("base_url".to_string(), serde_json::Value::String("https://api.example.com".to_string()));++ let mut config = HashMap::new();+ config.insert("url".to_string(), serde_json::Value::String("${ref:base_url}".to_string()));+ config.insert("timeout".to_string(), serde_json::Value::String("${eval:30}".to_string()));++ apply_expression_resolution(&mut config, &merged).unwrap();+ assert_eq!(config.get("url").unwrap(), &serde_json::Value::String("https://api.example.com".to_string()));+ assert_eq!(config.get("timeout").unwrap(), &serde_json::Value::Number(serde_json::Number::from(30)));+ }+}diff --git a/crates/dbx-core/src/config/governance.rs b/crates/dbx-core/src/config/governance.rsnew file mode 100644index 0000000000..afc336cc99--- /dev/null+++ b/crates/dbx-core/src/config/governance.rs@@ -0,0 +1,979 @@+use arc_swap::ArcSwap;+use chrono::Utc;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use std::collections::HashMap;+use std::sync::Arc;++use crate::config::layer::ConfigTree;+#[cfg(test)]+use crate::config::layer::LayerConfig;+use crate::storage::Storage;++fn hex_encode(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++// ---------------------------------------------------------------------------+// 16.1 — Config Change Audit & Version Management+// ---------------------------------------------------------------------------++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ConfigAuditEntry {+ pub id: String,+ pub timestamp: String,+ pub operator: String,+ pub reason: String,+ pub key_path: String,+ pub change_diff: serde_json::Value,+ pub config_snapshot: serde_json::Value,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ConfigVersionSnapshot {+ pub id: String,+ pub key_path: String,+ pub version: u64,+ pub snapshot_json: serde_json::Value,+ pub checksum: String,+ pub created_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AuditQuery {+ pub key_path: Option<String>,+ pub operator: Option<String>,+ pub limit: Option<usize>,+ pub offset: Option<usize>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AuditSummary {+ pub total_entries: usize,+ pub entries: Vec<ConfigAuditEntry>,+}++pub struct ConfigAuditor {+ storage: Arc<Storage>,+}++impl ConfigAuditor {+ pub fn new(storage: Arc<Storage>) -> Self {+ Self { storage }+ }++ pub async fn record_change(+ &self,+ operator: &str,+ reason: &str,+ key_path: &str,+ change_diff: serde_json::Value,+ config_snapshot: serde_json::Value,+ ) -> Result<ConfigAuditEntry, String> {+ let entry = ConfigAuditEntry {+ id: uuid::Uuid::new_v4().to_string(),+ timestamp: Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),+ operator: operator.to_string(),+ reason: reason.to_string(),+ key_path: key_path.to_string(),+ change_diff,+ config_snapshot,+ };+ self.storage.save_audit_entry(&entry).await?;+ Ok(entry)+ }++ pub async fn query_history(&self, query: &AuditQuery) -> Result<AuditSummary, String> {+ self.storage.query_audit_entries(query).await+ }++ pub async fn save_snapshot(&self, key_path: &str, tree: &ConfigTree) -> Result<ConfigVersionSnapshot, String> {+ let snapshot_json = serde_json::to_value(tree).map_err(|e| format!("serialize config tree: {e}"))?;+ let json_bytes = serde_json::to_vec(&snapshot_json).map_err(|e| format!("json bytes: {e}"))?;+ let checksum = hex_encode(&Sha256::digest(&json_bytes));+ let version = self.storage.next_config_version(key_path).await?;++ let snap = ConfigVersionSnapshot {+ id: uuid::Uuid::new_v4().to_string(),+ key_path: key_path.to_string(),+ version,+ snapshot_json: snapshot_json.clone(),+ checksum,+ created_at: Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),+ };+ self.storage.save_config_snapshot(&snap).await?;+ Ok(snap)+ }++ pub async fn get_snapshot(&self, key_path: &str, version: u64) -> Result<Option<ConfigVersionSnapshot>, String> {+ self.storage.load_config_snapshot(key_path, version).await+ }++ pub async fn list_versions(&self, key_path: &str) -> Result<Vec<ConfigVersionSnapshot>, String> {+ self.storage.list_config_snapshots(key_path).await+ }++ pub async fn rollback(+ &self,+ key_path: &str,+ version: u64,+ operator: &str,+ reason: &str,+ ) -> Result<ConfigTree, String> {+ let snap = self+ .get_snapshot(key_path, version)+ .await?+ .ok_or_else(|| format!("version {version} not found for key_path '{key_path}'"))?;++ let tree: ConfigTree =+ serde_json::from_value(snap.snapshot_json.clone()).map_err(|e| format!("deserialize config tree: {e}"))?;++ let current_json = serde_json::to_value(&tree).map_err(|e| format!("serialize current: {e}"))?;+ self.record_change(+ operator,+ &format!("rollback: {reason}"),+ key_path,+ serde_json::json!({ "rollback_to_version": version }),+ current_json,+ )+ .await?;++ Ok(tree)+ }+}++// ---------------------------------------------------------------------------+// 16.2 — Approval Workflow Integration+// ---------------------------------------------------------------------------++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum ApprovalStatus {+ Draft,+ PendingApproval,+ Approved,+ Rejected,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ApprovalRecord {+ pub id: String,+ pub config_domain: String,+ pub change_description: String,+ pub status: ApprovalStatus,+ pub requester: String,+ pub reviewer: Option<String>,+ pub reviewed_at: Option<String>,+ pub webhook_url: Option<String>,+ pub draft_config_json: serde_json::Value,+ pub created_at: String,+ pub updated_at: String,+}++const SENSITIVE_DOMAINS: &[&str] = &["mapping_rules", "allow_destructive", "dangerous_ddl_policy"];++pub fn is_sensitive_domain(domain: &str) -> bool {+ SENSITIVE_DOMAINS.contains(&domain)+}++pub fn requires_approval_for_change(domain: &str, current_status: ApprovalStatus) -> bool {+ if !is_sensitive_domain(domain) {+ return false;+ }+ matches!(current_status, ApprovalStatus::Draft | ApprovalStatus::Rejected)+}++pub struct ConfigApproval {+ storage: Arc<Storage>,+}++impl ConfigApproval {+ pub fn new(storage: Arc<Storage>) -> Self {+ Self { storage }+ }++ pub async fn submit_change(+ &self,+ domain: &str,+ description: &str,+ requester: &str,+ draft_config: serde_json::Value,+ webhook_url: Option<&str>,+ ) -> Result<ApprovalRecord, String> {+ let now = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();+ let record = ApprovalRecord {+ id: uuid::Uuid::new_v4().to_string(),+ config_domain: domain.to_string(),+ change_description: description.to_string(),+ status: if is_sensitive_domain(domain) {+ ApprovalStatus::PendingApproval+ } else {+ ApprovalStatus::Approved+ },+ requester: requester.to_string(),+ reviewer: None,+ reviewed_at: None,+ webhook_url: webhook_url.map(String::from),+ draft_config_json: draft_config,+ created_at: now.clone(),+ updated_at: now,+ };+ self.storage.save_approval_record(&record).await?;+ Ok(record)+ }++ pub async fn approve(&self, id: &str, reviewer: &str) -> Result<ApprovalRecord, String> {+ let mut record =+ self.storage.load_approval_record(id).await?.ok_or_else(|| format!("approval record {id} not found"))?;+ if record.status != ApprovalStatus::PendingApproval {+ return Err(format!("record {id} is not in PendingApproval state (current: {:?})", record.status));+ }+ record.status = ApprovalStatus::Approved;+ record.reviewer = Some(reviewer.to_string());+ record.reviewed_at = Some(Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string());+ record.updated_at = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();+ self.storage.save_approval_record(&record).await?;+ Ok(record)+ }++ pub async fn reject(&self, id: &str, reviewer: &str) -> Result<ApprovalRecord, String> {+ let mut record =+ self.storage.load_approval_record(id).await?.ok_or_else(|| format!("approval record {id} not found"))?;+ if record.status != ApprovalStatus::PendingApproval {+ return Err(format!("record {id} is not in PendingApproval state"));+ }+ record.status = ApprovalStatus::Rejected;+ record.reviewer = Some(reviewer.to_string());+ record.reviewed_at = Some(Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string());+ record.updated_at = Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string();+ self.storage.save_approval_record(&record).await?;+ Ok(record)+ }++ pub async fn list_pending(&self) -> Result<Vec<ApprovalRecord>, String> {+ self.storage.query_approval_records(Some(ApprovalStatus::PendingApproval)).await+ }++ pub async fn check_effective(&self, domain: &str) -> Result<bool, String> {+ if !is_sensitive_domain(domain) {+ return Ok(true);+ }+ let records = self.storage.query_approval_records_by_domain(domain).await?;+ let latest = records.into_iter().last();+ match latest {+ Some(r) => Ok(r.status == ApprovalStatus::Approved),+ None => Ok(false),+ }+ }+}++// ---------------------------------------------------------------------------+// 16.3 — Cross-Environment Config Drift Detection+// ---------------------------------------------------------------------------++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ConfigChecksum {+ pub env: String,+ pub key_path: String,+ pub checksum: String,+ pub computed_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DriftReport {+ pub source_env: String,+ pub target_env: String,+ pub key_path: String,+ pub source_checksum: String,+ pub target_checksum: String,+ pub mismatched_fields: Vec<String>,+ pub source_changed_at: Option<String>,+ pub detected_at: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DriftAlert {+ pub id: String,+ pub source_env: String,+ pub target_env: String,+ pub config_key: String,+ pub expected_checksum: String,+ pub actual_checksum: String,+ pub details_json: serde_json::Value,+ pub detected_at: String,+ pub acknowledged: bool,+}++pub fn compute_config_checksum(tree: &ConfigTree) -> String {+ let json = serde_json::to_vec(tree).unwrap_or_default();+ hex_encode(&Sha256::digest(&json))+}++pub fn compute_config_checksum_for_layer(tree: &ConfigTree, key_path: &str) -> Option<String> {+ let merged = tree.merge().ok()?;+ let relevant: HashMap<String, serde_json::Value> =+ merged.values.into_iter().filter(|(k, _)| k.starts_with(key_path)).collect();+ if relevant.is_empty() {+ return None;+ }+ let json = serde_json::to_vec(&relevant).ok()?;+ Some(hex_encode(&Sha256::digest(&json)))+}++pub fn detect_drift(source: &ConfigTree, target: &ConfigTree, key_path: &str) -> Option<DriftReport> {+ let source_merged = source.merge().ok()?;+ let target_merged = target.merge().ok()?;++ let source_vals: HashMap<&String, &serde_json::Value> =+ source_merged.values.iter().filter(|(k, _)| k.starts_with(key_path)).collect();+ let target_vals: HashMap<&String, &serde_json::Value> =+ target_merged.values.iter().filter(|(k, _)| k.starts_with(key_path)).collect();++ let all_keys: std::collections::BTreeSet<&String> = source_vals.keys().chain(target_vals.keys()).copied().collect();++ let mismatched: Vec<String> = all_keys+ .into_iter()+ .filter(|k| match (source_vals.get(k), target_vals.get(k)) {+ (Some(sv), Some(tv)) => sv != tv,+ _ => true,+ })+ .map(|k| {+ let s = source_vals.get(k).map(|v| v.to_string()).unwrap_or_default();+ let t = target_vals.get(k).map(|v| v.to_string()).unwrap_or_default();+ format!("{k}: source={s}, target={t}")+ })+ .collect();++ if mismatched.is_empty() {+ return None;+ }++ let source_ck = compute_config_checksum_for_layer(source, key_path).unwrap_or_default();+ let target_ck = compute_config_checksum_for_layer(target, key_path).unwrap_or_default();++ Some(DriftReport {+ source_env: String::new(),+ target_env: String::new(),+ key_path: key_path.to_string(),+ source_checksum: source_ck,+ target_checksum: target_ck,+ mismatched_fields: mismatched,+ source_changed_at: None,+ detected_at: Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),+ })+}++pub struct DriftDetector {+ storage: Arc<Storage>,+}++impl DriftDetector {+ pub fn new(storage: Arc<Storage>) -> Self {+ Self { storage }+ }++ pub fn compare_envs(+ &self,+ source_env: &str,+ target_env: &str,+ source_tree: &ConfigTree,+ target_tree: &ConfigTree,+ key_path: &str,+ ) -> Option<DriftReport> {+ let mut report = detect_drift(source_tree, target_tree, key_path)?;+ report.source_env = source_env.to_string();+ report.target_env = target_env.to_string();+ Some(report)+ }++ pub async fn record_alert(&self, alert: &DriftAlert) -> Result<(), String> {+ self.storage.save_drift_alert(alert).await+ }++ pub async fn acknowledge_alert(&self, id: &str) -> Result<(), String> {+ self.storage.acknowledge_drift_alert(id).await+ }++ pub async fn list_alerts(&self, acknowledged: Option<bool>) -> Result<Vec<DriftAlert>, String> {+ self.storage.query_drift_alerts(acknowledged).await+ }+}++// ---------------------------------------------------------------------------+// 16.4 — COW Snapshot (ArcSwap-based hot-reload)+// ---------------------------------------------------------------------------++pub struct ConfigSnapshot {+ inner: ArcSwap<ConfigTree>,+ key_path: String,+ auditor: Arc<ConfigAuditor>,+}++impl ConfigSnapshot {+ pub fn new(tree: ConfigTree, key_path: &str, auditor: Arc<ConfigAuditor>) -> Self {+ Self { inner: ArcSwap::new(Arc::new(tree)), key_path: key_path.to_string(), auditor }+ }++ pub fn load(&self) -> Arc<ConfigTree> {+ self.inner.load_full()+ }++ pub fn apply(+ &self,+ operator: &str,+ reason: &str,+ f: impl FnOnce(&mut ConfigTree),+ ) -> Result<Arc<ConfigTree>, String>+ where+ Self: Sized,+ {+ let prev = self.inner.load_full();+ let mut new_tree = (*prev).clone();+ f(&mut new_tree);++ let prev_json = serde_json::to_value(&*prev).map_err(|e| format!("serialize prev: {e}"))?;+ let new_json = serde_json::to_value(&new_tree).map_err(|e| format!("serialize new: {e}"))?;++ let diff = serde_json::json!({+ "prev": prev_json,+ "new": new_json,+ });++ let new_arc = Arc::new(new_tree);+ self.inner.store(new_arc.clone());++ let auditor = self.auditor.clone();+ let key_path = self.key_path.clone();+ let operator = operator.to_string();+ let reason = reason.to_string();+ tokio::spawn(async move {+ let _ = auditor.record_change(&operator, &reason, &key_path, diff, new_json).await;+ });++ Ok(new_arc)+ }++ pub fn apply_silent(&self, f: impl FnOnce(&mut ConfigTree)) -> Arc<ConfigTree> {+ let prev = self.inner.load_full();+ let mut new_tree = (*prev).clone();+ f(&mut new_tree);+ let new_arc = Arc::new(new_tree);+ self.inner.store(new_arc.clone());+ new_arc+ }+}++// ---------------------------------------------------------------------------+// Tests+// ---------------------------------------------------------------------------++#[cfg(test)]+mod tests {+ use super::*;+ use crate::config::layer::ConfigLayer;+ use std::sync::Arc;++ async fn make_test_storage() -> Arc<Storage> {+ let tmp = std::env::temp_dir().join(uuid::Uuid::new_v4().to_string());+ std::fs::create_dir_all(&tmp).unwrap();+ let db_path = tmp.join("test_governance.db");+ let storage = Arc::new(Storage::open(&db_path).await.unwrap());+ std::mem::forget(tmp);+ storage+ }++ fn make_test_tree() -> ConfigTree {+ let mut tree = ConfigTree::new();+ tree.add_layer(LayerConfig {+ layer: ConfigLayer::Global,+ name: "test".to_string(),+ values: HashMap::from([+ ("host".to_string(), serde_json::Value::String("db.example.com".to_string())),+ ("port".to_string(), serde_json::json!(5432)),+ ]),+ enabled: true,+ ..Default::default()+ });+ tree+ }++ // ---- 16.1 Audit Tests ----++ #[tokio::test]+ async fn test_audit_record_and_query() {+ let storage = make_test_storage().await;+ let auditor = ConfigAuditor::new(storage.clone());++ auditor+ .record_change(+ "alice",+ "update host",+ "database.host",+ serde_json::json!({"old": "old.host.com", "new": "new.host.com"}),+ serde_json::json!({"host": "new.host.com"}),+ )+ .await+ .unwrap();++ let summary = auditor+ .query_history(&AuditQuery { key_path: None, operator: None, limit: None, offset: None })+ .await+ .unwrap();+ assert_eq!(summary.total_entries, 1);+ assert_eq!(summary.entries[0].operator, "alice");+ assert_eq!(summary.entries[0].key_path, "database.host");++ let filtered = auditor+ .query_history(&AuditQuery {+ key_path: Some("database.host".into()),+ operator: Some("alice".into()),+ limit: Some(10),+ offset: Some(0),+ })+ .await+ .unwrap();+ assert_eq!(filtered.total_entries, 1);++ let empty = auditor+ .query_history(&AuditQuery {+ key_path: Some("other.key".into()),+ operator: None,+ limit: None,+ offset: None,+ })+ .await+ .unwrap();+ assert_eq!(empty.total_entries, 0);+ }++ #[tokio::test]+ async fn test_audit_multiple_entries() {+ let storage = make_test_storage().await;+ let auditor = ConfigAuditor::new(storage.clone());++ for i in 0..3 {+ auditor+ .record_change(+ &format!("user{i}"),+ &format!("change {i}"),+ "app.config",+ serde_json::json!({"index": i}),+ serde_json::json!({"version": i}),+ )+ .await+ .unwrap();+ }++ let summary = auditor+ .query_history(&AuditQuery { key_path: None, operator: None, limit: Some(2), offset: None })+ .await+ .unwrap();+ assert_eq!(summary.total_entries, 3);+ assert_eq!(summary.entries.len(), 2);+ }++ // ---- 16.1 Snapshot Tests ----++ #[tokio::test]+ async fn test_snapshot_save_and_rollback() {+ let storage = make_test_storage().await;+ let auditor = ConfigAuditor::new(storage.clone());+ let tree = make_test_tree();++ let snap = auditor.save_snapshot("app.config", &tree).await.unwrap();+ assert_eq!(snap.version, 1);+ assert!(!snap.checksum.is_empty());++ let loaded = auditor.get_snapshot("app.config", 1).await.unwrap().unwrap();+ assert_eq!(loaded.checksum, snap.checksum);++ let versions = auditor.list_versions("app.config").await.unwrap();+ assert_eq!(versions.len(), 1);+ }++ #[tokio::test]+ async fn test_snapshot_version_increment() {+ let storage = make_test_storage().await;+ let auditor = ConfigAuditor::new(storage.clone());++ let tree = make_test_tree();+ let v1 = auditor.save_snapshot("app.config", &tree).await.unwrap();+ assert_eq!(v1.version, 1);++ let v2 = auditor.save_snapshot("app.config", &tree).await.unwrap();+ assert_eq!(v2.version, 2);++ let versions = auditor.list_versions("app.config").await.unwrap();+ assert_eq!(versions.len(), 2);+ }++ #[tokio::test]+ async fn test_rollback_restores_snapshot() {+ let storage = make_test_storage().await;+ let auditor = ConfigAuditor::new(storage.clone());++ let mut tree = make_test_tree();+ let snap1 = auditor.save_snapshot("app.config", &tree).await.unwrap();++ tree.add_layer(LayerConfig {+ layer: ConfigLayer::Task,+ name: "override".to_string(),+ values: HashMap::from([("host".to_string(), serde_json::Value::String("override.host.com".to_string()))]),+ enabled: true,+ ..Default::default()+ });+ auditor.save_snapshot("app.config", &tree).await.unwrap();++ let rolled = auditor.rollback("app.config", 1, "bob", "bad override").await.unwrap();+ let merged = rolled.merge().unwrap();+ assert_eq!(merged.values.get("host").unwrap(), &serde_json::Value::String("db.example.com".to_string()));++ let history = auditor+ .query_history(&AuditQuery {+ key_path: Some("app.config".into()),+ operator: None,+ limit: None,+ offset: None,+ })+ .await+ .unwrap();+ let rollback_entries: Vec<_> = history.entries.iter().filter(|e| e.reason.contains("rollback")).collect();+ assert_eq!(rollback_entries.len(), 1);+ }++ #[tokio::test]+ async fn test_rollback_nonexistent_version() {+ let storage = make_test_storage().await;+ let auditor = ConfigAuditor::new(storage.clone());+ let result = auditor.rollback("app.config", 99, "alice", "test").await;+ assert!(result.is_err());+ }++ // ---- 16.2 Approval Tests ----++ #[test]+ fn test_sensitive_domain_check() {+ assert!(is_sensitive_domain("mapping_rules"));+ assert!(is_sensitive_domain("allow_destructive"));+ assert!(is_sensitive_domain("dangerous_ddl_policy"));+ assert!(!is_sensitive_domain("theme"));+ assert!(!is_sensitive_domain("log_level"));+ }++ #[test]+ fn test_requires_approval_logic() {+ assert!(requires_approval_for_change("mapping_rules", ApprovalStatus::Draft));+ assert!(requires_approval_for_change("allow_destructive", ApprovalStatus::Rejected));+ assert!(!requires_approval_for_change("allow_destructive", ApprovalStatus::Approved));+ assert!(!requires_approval_for_change("theme", ApprovalStatus::Draft));+ }++ #[tokio::test]+ async fn test_submit_change_sensitive_domain() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ let record = approval+ .submit_change(+ "allow_destructive",+ "enable drop table",+ "alice",+ serde_json::json!({"enabled": true}),+ None,+ )+ .await+ .unwrap();+ assert_eq!(record.status, ApprovalStatus::PendingApproval);+ assert_eq!(record.requester, "alice");+ }++ #[tokio::test]+ async fn test_submit_change_non_sensitive_domain() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ let record = approval+ .submit_change("theme", "set dark mode", "alice", serde_json::json!({"theme": "dark"}), None)+ .await+ .unwrap();+ assert_eq!(record.status, ApprovalStatus::Approved);+ }++ #[tokio::test]+ async fn test_approve_workflow() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ let record = approval+ .submit_change(+ "mapping_rules",+ "add mysql mapping",+ "alice",+ serde_json::json!({"rule": "varchar->text"}),+ None,+ )+ .await+ .unwrap();++ let approved = approval.approve(&record.id, "bob").await.unwrap();+ assert_eq!(approved.status, ApprovalStatus::Approved);+ assert_eq!(approved.reviewer.as_deref(), Some("bob"));+ }++ #[tokio::test]+ async fn test_reject_workflow() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ let record = approval+ .submit_change(+ "dangerous_ddl_policy",+ "allow drop database",+ "alice",+ serde_json::json!({"allow": true}),+ None,+ )+ .await+ .unwrap();++ let rejected = approval.reject(&record.id, "bob").await.unwrap();+ assert_eq!(rejected.status, ApprovalStatus::Rejected);+ }++ #[tokio::test]+ async fn test_approve_invalid_state() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ let record = approval+ .submit_change("theme", "dark mode", "alice", serde_json::json!({"theme": "dark"}), None)+ .await+ .unwrap();+ assert!(record.status == ApprovalStatus::Approved);++ let result = approval.approve(&record.id, "bob").await;+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn test_check_effective() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ assert!(!approval.check_effective("allow_destructive").await.unwrap());++ let record = approval+ .submit_change("allow_destructive", "enable", "alice", serde_json::json!({"enabled": true}), None)+ .await+ .unwrap();+ assert!(!approval.check_effective("allow_destructive").await.unwrap());++ approval.approve(&record.id, "bob").await.unwrap();+ assert!(approval.check_effective("allow_destructive").await.unwrap());++ assert!(approval.check_effective("theme").await.unwrap());+ }++ #[tokio::test]+ async fn test_list_pending() {+ let storage = make_test_storage().await;+ let approval = ConfigApproval::new(storage.clone());++ approval.submit_change("mapping_rules", "rule1", "alice", serde_json::json!({"r": 1}), None).await.unwrap();+ approval.submit_change("allow_destructive", "rule2", "bob", serde_json::json!({"r": 2}), None).await.unwrap();++ let pending = approval.list_pending().await.unwrap();+ assert_eq!(pending.len(), 2);+ }++ // ---- 16.3 Drift Detection Tests ----++ #[test]+ fn test_checksum_computation() {+ let tree = make_test_tree();+ let ck = compute_config_checksum(&tree);+ assert_eq!(ck.len(), 64);+ assert!(ck.chars().all(|c| c.is_ascii_hexdigit()));+ }++ #[test]+ fn test_checksum_deterministic() {+ let tree = make_test_tree();+ let ck1 = compute_config_checksum(&tree);+ let ck2 = compute_config_checksum(&tree);+ assert_eq!(ck1, ck2);+ }++ #[test]+ fn test_checksum_differs_on_change() {+ let mut tree1 = make_test_tree();+ let mut tree2 = make_test_tree();+ tree2.add_layer(LayerConfig {+ layer: ConfigLayer::Task,+ name: "override".to_string(),+ values: HashMap::from([("host".to_string(), serde_json::Value::String("other.com".to_string()))]),+ enabled: true,+ ..Default::default()+ });+ assert_ne!(compute_config_checksum(&tree1), compute_config_checksum(&tree2));+ }++ #[test]+ fn test_layer_checksum() {+ let tree = make_test_tree();+ let ck = compute_config_checksum_for_layer(&tree, "host").unwrap();+ assert_eq!(ck.len(), 64);++ let none = compute_config_checksum_for_layer(&tree, "nonexistent");+ assert!(none.is_none());+ }++ #[test]+ fn test_detect_drift_no_drift() {+ let tree1 = make_test_tree();+ let tree2 = make_test_tree();+ assert!(detect_drift(&tree1, &tree2, "host").is_none());+ }++ #[test]+ fn test_detect_drift_with_drift() {+ let tree1 = make_test_tree();+ let mut tree2 = make_test_tree();+ tree2.add_layer(LayerConfig {+ layer: ConfigLayer::Task,+ name: "override".to_string(),+ values: HashMap::from([("host".to_string(), serde_json::Value::String("other.com".to_string()))]),+ enabled: true,+ ..Default::default()+ });++ let report = detect_drift(&tree1, &tree2, "host").unwrap();+ assert_eq!(report.key_path, "host");+ assert!(!report.mismatched_fields.is_empty());+ }++ #[test]+ fn test_detect_drift_partial_keys() {+ let tree1 = make_test_tree();+ let tree2 = make_test_tree();+ let report = detect_drift(&tree1, &tree2, "port");+ assert!(report.is_none());+ }++ #[tokio::test]+ async fn test_drift_alert_persistence() {+ let storage = make_test_storage().await;+ let detector = DriftDetector::new(storage.clone());++ let alert = DriftAlert {+ id: uuid::Uuid::new_v4().to_string(),+ source_env: "prod".to_string(),+ target_env: "staging".to_string(),+ config_key: "database.host".to_string(),+ expected_checksum: "abc".to_string(),+ actual_checksum: "def".to_string(),+ details_json: serde_json::json!({"field": "host", "expected": "prod-host", "actual": "staging-host"}),+ detected_at: Utc::now().format("%Y-%m-%dT%H:%M:%S%.3fZ").to_string(),+ acknowledged: false,+ };+ detector.record_alert(&alert).await.unwrap();++ let unacked = detector.list_alerts(Some(false)).await.unwrap();+ assert_eq!(unacked.len(), 1);++ detector.acknowledge_alert(&alert.id).await.unwrap();+ let still_unacked = detector.list_alerts(Some(false)).await.unwrap();+ assert_eq!(still_unacked.len(), 0);+ let acked = detector.list_alerts(Some(true)).await.unwrap();+ assert_eq!(acked.len(), 1);+ }++ // ---- 16.4 COW Snapshot Tests ----++ #[test]+ fn test_config_snapshot_load() {+ let storage = make_test_storage_for_snapshot();+ let auditor = Arc::new(ConfigAuditor::new(storage));+ let tree = make_test_tree();+ let snapshot = ConfigSnapshot::new(tree, "app.config", auditor);++ let loaded = snapshot.load();+ let merged = loaded.merge().unwrap();+ assert_eq!(merged.values.get("host").unwrap(), &serde_json::Value::String("db.example.com".to_string()));+ }++ #[tokio::test]+ async fn test_config_snapshot_apply_modification() {+ let storage = make_test_storage().await;+ let auditor = Arc::new(ConfigAuditor::new(storage));+ let tree = make_test_tree();+ let snapshot = ConfigSnapshot::new(tree, "app.config", auditor);++ snapshot+ .apply("alice", "update port", |t| {+ for layer in &mut t.layers {+ if layer.name == "test" {+ layer.values.insert("port".to_string(), serde_json::json!(3306));+ }+ }+ })+ .unwrap();++ let loaded = snapshot.load();+ let merged = loaded.merge().unwrap();+ assert_eq!(merged.values.get("port").unwrap(), &serde_json::json!(3306));+ }++ #[test]+ fn test_config_snapshot_apply_silent_no_audit() {+ let storage = make_test_storage_for_snapshot();+ let auditor = Arc::new(ConfigAuditor::new(storage.clone()));+ let tree = make_test_tree();+ let snapshot = ConfigSnapshot::new(tree, "app.config", auditor);++ snapshot.apply_silent(|t| {+ for layer in &mut t.layers {+ if layer.name == "test" {+ layer.values.insert("host".to_string(), serde_json::Value::String("silent.host.com".to_string()));+ }+ }+ });++ let loaded = snapshot.load();+ let merged = loaded.merge().unwrap();+ assert_eq!(merged.values.get("host").unwrap(), &serde_json::Value::String("silent.host.com".to_string()));+ }++ #[test]+ fn test_config_snapshot_concurrent_reads() {+ use std::thread;+ let storage = make_test_storage_for_snapshot();+ let auditor = Arc::new(ConfigAuditor::new(storage));+ let tree = make_test_tree();+ let snapshot = Arc::new(ConfigSnapshot::new(tree, "app.config", auditor));++ let mut handles = Vec::new();+ for i in 0..10 {+ let snap = snapshot.clone();+ handles.push(thread::spawn(move || {+ let loaded = snap.load();+ let merged = loaded.merge().unwrap();+ let port = merged.values.get("port").and_then(|v| v.as_i64()).unwrap_or(0);+ assert_eq!(port, 5432);+ }));+ }+ for h in handles {+ h.join().unwrap();+ }+ }++ fn make_test_storage_for_snapshot() -> Arc<Storage> {+ let tmp = std::env::temp_dir().join(uuid::Uuid::new_v4().to_string());+ std::fs::create_dir_all(&tmp).unwrap();+ let db_path = tmp.join("test_snapshot.db");+ let rt = tokio::runtime::Runtime::new().unwrap();+ let storage = Arc::new(rt.block_on(Storage::open(&db_path)).unwrap());+ std::mem::forget(tmp);+ storage+ }+}diff --git a/crates/dbx-core/src/config/layer.rs b/crates/dbx-core/src/config/layer.rsnew file mode 100644index 0000000000..7e5084125c--- /dev/null+++ b/crates/dbx-core/src/config/layer.rs@@ -0,0 +1,308 @@+use serde::{Deserialize, Serialize};+use std::collections::HashMap;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Hash)]+#[serde(rename_all = "snake_case")]+pub enum ConfigLayer {+ Global = 0,+ Team = 1,+ Project = 2,+ Env = 3,+ Task = 4,+}++impl ConfigLayer {+ pub fn priority(&self) -> u8 {+ *self as u8+ }++ pub fn label(&self) -> &'static str {+ match self {+ ConfigLayer::Global => "global",+ ConfigLayer::Team => "team",+ ConfigLayer::Project => "project",+ ConfigLayer::Env => "env",+ ConfigLayer::Task => "task",+ }+ }++ pub fn all() -> &'static [ConfigLayer] {+ &[ConfigLayer::Global, ConfigLayer::Team, ConfigLayer::Project, ConfigLayer::Env, ConfigLayer::Task]+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct LayerConfig {+ pub layer: ConfigLayer,+ pub name: String,++ #[serde(default)]+ pub description: String,++ #[serde(default)]+ pub values: HashMap<String, serde_json::Value>,++ #[serde(default)]+ pub tags: HashMap<String, String>,++ #[serde(default)]+ pub enabled: bool,++ #[serde(default = "default_priority")]+ pub priority_override: Option<u8>,++ #[serde(default)]+ pub metadata: HashMap<String, String>,+}++impl Default for LayerConfig {+ fn default() -> Self {+ Self {+ layer: ConfigLayer::Global,+ name: String::new(),+ description: String::new(),+ values: HashMap::new(),+ tags: HashMap::new(),+ enabled: true,+ priority_override: None,+ metadata: HashMap::new(),+ }+ }+}++fn default_priority() -> Option<u8> {+ None+}++impl LayerConfig {+ pub fn effective_priority(&self) -> u8 {+ self.priority_override.unwrap_or_else(|| self.layer.priority())+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MergedConfig {+ pub values: HashMap<String, serde_json::Value>,+ pub tags: HashMap<String, String>,+ pub provenance: HashMap<String, ConfigLayer>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ConfigTree {+ pub layers: Vec<LayerConfig>,+}++impl Default for ConfigTree {+ fn default() -> Self {+ Self::new()+ }+}++impl ConfigTree {+ pub fn new() -> Self {+ Self { layers: Vec::new() }+ }++ pub fn add_layer(&mut self, config: LayerConfig) {+ self.layers.push(config);+ }++ pub fn merge(&self) -> Result<MergedConfig, String> {+ let mut sorted: Vec<&LayerConfig> = self.layers.iter().filter(|l| l.enabled).collect();+ sorted.sort_by_key(|l| l.effective_priority());++ let mut values: HashMap<String, serde_json::Value> = HashMap::new();+ let mut tags: HashMap<String, String> = HashMap::new();+ let mut provenance: HashMap<String, ConfigLayer> = HashMap::new();++ for layer_config in &sorted {+ for (k, v) in &layer_config.values {+ values.insert(k.clone(), v.clone());+ provenance.insert(k.clone(), layer_config.layer);+ }+ for (k, v) in &layer_config.tags {+ tags.insert(k.clone(), v.clone());+ }+ }++ Ok(MergedConfig { values, tags, provenance })+ }++ pub fn merge_with_guard(&self, tag_guard: &crate::config::tag::TagGuard) -> Result<MergedConfig, String> {+ let merged = self.merge()?;+ let tags: Vec<crate::config::tag::BusinessTag> = merged+ .tags+ .iter()+ .map(|(k, v)| crate::config::tag::BusinessTag {+ key: k.clone(),+ value: v.clone(),+ description: String::new(),+ immutable: false,+ })+ .collect();+ let base_tags: HashMap<String, String> = HashMap::new();+ let result = tag_guard.validate_and_collect(&tags, &base_tags);+ if tag_guard.validator.has_blocking_violations(&result) {+ let (blocked, violations, _total) = tag_guard.blocking_summary();+ return Err(format!("Tag guard blocked config merge: {blocked} tags blocked, {violations} violations"));+ }+ Ok(merged)+ }++ pub fn validate(&self) -> Result<(), Vec<String>> {+ let mut errors = Vec::new();+ let mut seen_keys: HashMap<&str, usize> = HashMap::new();++ for (i, layer) in self.layers.iter().enumerate() {+ if layer.name.is_empty() {+ errors.push(format!("Layer at index {i} has empty name"));+ }+ if layer.values.is_empty() && layer.tags.is_empty() {+ errors.push(format!("Layer '{}' ({}) has no values or tags", layer.name, layer.layer.label()));+ }+ for key in layer.values.keys() {+ if let Some(prev) = seen_keys.get(key.as_str()) {+ errors.push(format!("Key '{}' defined in multiple layers (index {prev} and {i})", key));+ }+ seen_keys.entry(key.as_str()).or_insert(i);+ }+ }++ if errors.is_empty() {+ Ok(())+ } else {+ Err(errors)+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn make_layer(layer: ConfigLayer, name: &str, key: &str, value: &str) -> LayerConfig {+ let mut values = HashMap::new();+ values.insert(key.to_string(), serde_json::Value::String(value.to_string()));+ LayerConfig { layer, name: name.to_string(), values, enabled: true, ..Default::default() }+ }++ #[test]+ fn test_layer_priority_order() {+ assert!(ConfigLayer::Global.priority() < ConfigLayer::Team.priority());+ assert!(ConfigLayer::Team.priority() < ConfigLayer::Project.priority());+ assert!(ConfigLayer::Project.priority() < ConfigLayer::Env.priority());+ assert!(ConfigLayer::Env.priority() < ConfigLayer::Task.priority());+ }++ #[test]+ fn test_layer_label() {+ assert_eq!(ConfigLayer::Global.label(), "global");+ assert_eq!(ConfigLayer::Task.label(), "task");+ }++ #[test]+ fn test_config_tree_merge_basic() {+ let mut tree = ConfigTree::new();+ tree.add_layer(make_layer(ConfigLayer::Global, "global-cfg", "host", "db-global"));+ tree.add_layer(make_layer(ConfigLayer::Project, "proj-cfg", "host", "db-proj"));++ let merged = tree.merge().unwrap();+ assert_eq!(merged.values.get("host").unwrap(), &serde_json::Value::String("db-proj".to_string()));+ assert_eq!(*merged.provenance.get("host").unwrap(), ConfigLayer::Project);+ }++ #[test]+ fn test_config_tree_merge_lower_priority_does_not_override() {+ let mut tree = ConfigTree::new();+ tree.add_layer(make_layer(ConfigLayer::Project, "proj-cfg", "port", "5432"));+ tree.add_layer(make_layer(ConfigLayer::Global, "global-cfg", "port", "3306"));++ let merged = tree.merge().unwrap();+ assert_eq!(merged.values.get("port").unwrap(), &serde_json::Value::String("5432".to_string()));+ assert_eq!(*merged.provenance.get("port").unwrap(), ConfigLayer::Project);+ }++ #[test]+ fn test_config_tree_merge_disabled_layer_ignored() {+ let mut tree = ConfigTree::new();+ let mut global = make_layer(ConfigLayer::Global, "global-cfg", "host", "db-global");+ global.enabled = false;+ tree.add_layer(global);+ tree.add_layer(make_layer(ConfigLayer::Task, "task-cfg", "host", "db-task"));++ let merged = tree.merge().unwrap();+ assert_eq!(merged.values.get("host").unwrap(), &serde_json::Value::String("db-task".to_string()));+ }++ #[test]+ fn test_config_tree_merge_distinct_keys() {+ let mut tree = ConfigTree::new();+ tree.add_layer(make_layer(ConfigLayer::Global, "g", "host", "g-host"));+ tree.add_layer(make_layer(ConfigLayer::Team, "t", "port", "t-port"));++ let merged = tree.merge().unwrap();+ assert_eq!(merged.values.len(), 2);+ assert!(merged.values.contains_key("host"));+ assert!(merged.values.contains_key("port"));+ }++ #[test]+ fn test_priority_override() {+ let mut tree = ConfigTree::new();+ let mut global = make_layer(ConfigLayer::Global, "override-cfg", "key", "val");+ global.priority_override = Some(255);+ tree.add_layer(global);+ tree.add_layer(make_layer(ConfigLayer::Task, "task-cfg", "key", "task-val"));++ let merged = tree.merge().unwrap();+ assert_eq!(merged.values.get("key").unwrap(), &serde_json::Value::String("val".to_string()));+ }++ #[test]+ fn test_validate_empty_name() {+ let tree = ConfigTree {+ layers: vec![LayerConfig {+ layer: ConfigLayer::Global,+ name: String::new(),+ values: HashMap::from([("k".to_string(), serde_json::Value::String("v".to_string()))]),+ ..Default::default()+ }],+ };+ assert!(tree.validate().is_err());+ }++ #[test]+ fn test_validate_empty_values_and_tags() {+ let layer = LayerConfig {+ layer: ConfigLayer::Global,+ name: "empty".to_string(),+ values: HashMap::new(),+ tags: HashMap::new(),+ ..Default::default()+ };+ let tree = ConfigTree { layers: vec![layer] };+ let errs = tree.validate().unwrap_err();+ assert!(errs.iter().any(|e| e.contains("empty")));+ }++ #[test]+ fn test_effective_priority_default() {+ let l = make_layer(ConfigLayer::Env, "env", "k", "v");+ assert_eq!(l.effective_priority(), ConfigLayer::Env.priority());+ }++ #[test]+ fn test_effective_priority_override() {+ let mut l = make_layer(ConfigLayer::Global, "g", "k", "v");+ l.priority_override = Some(100);+ assert_eq!(l.effective_priority(), 100);+ }++ #[test]+ fn test_all_layers() {+ let all = ConfigLayer::all();+ assert_eq!(all.len(), 5);+ assert_eq!(all[0], ConfigLayer::Global);+ assert_eq!(all[4], ConfigLayer::Task);+ }+}diff --git a/crates/dbx-core/src/config/mod.rs b/crates/dbx-core/src/config/mod.rsnew file mode 100644index 0000000000..d3e58fb183--- /dev/null+++ b/crates/dbx-core/src/config/mod.rs@@ -0,0 +1,160 @@+pub mod expression;+// governance disabled — storage methods not available at HEAD after main merge+// pub mod governance;+pub mod layer;+pub mod tag;+pub mod trace;++pub use expression::{parse_expression, resolve_all_expressions_in_value, resolve_expression, Expression};+// pub use governance::{ ... };+pub use layer::{ConfigLayer, ConfigTree, LayerConfig, MergedConfig};+pub use tag::{+ BlockStats, BusinessTag, TagGuard, TagInheritanceWhitelist, TagPolicy, TagValidationResult, TagValidator,+};+pub use trace::{TraceEntry, TraceRingBuffer, TraceStats};++#[cfg(test)]+mod integration_tests {+ use crate::config::*;+ use crate::models::connection::DatabaseType;+ use crate::schema_diff::SchemaDiffPreparationOptions;+ use std::collections::HashMap;++ #[test]+ fn test_config_tree_with_schema_diff_options() {+ let mut tree = ConfigTree::new();++ let mut global_vals = HashMap::new();+ global_vals.insert("target_schema".to_string(), serde_json::Value::String("public".to_string()));+ global_vals.insert("ignore_comments".to_string(), serde_json::Value::Bool(true));+ global_vals.insert("db_type".to_string(), serde_json::Value::String("postgres".to_string()));++ tree.add_layer(LayerConfig {+ layer: ConfigLayer::Global,+ name: "defaults".to_string(),+ values: global_vals,+ tags: HashMap::from([("env".to_string(), "prod".to_string())]),+ enabled: true,+ ..Default::default()+ });++ tree.add_layer(LayerConfig {+ layer: ConfigLayer::Task,+ name: "task-override".to_string(),+ values: HashMap::from([+ ("cascade_delete".to_string(), serde_json::Value::Bool(true)),+ ("compare_column_order".to_string(), serde_json::Value::String("${eval:true}".to_string())),+ ]),+ tags: HashMap::new(),+ enabled: true,+ ..Default::default()+ });++ let mut merged = tree.merge().unwrap();+ let merged_snapshot = merged.clone();++ let resolved: HashMap<_, _> = merged+ .values+ .iter()+ .map(|(k, v)| {+ let resolved = resolve_all_expressions_in_value(v, &merged.values)+ .unwrap_or_else(|e| panic!("Failed to resolve expression for key '{k}': {e}"));+ (k.clone(), resolved)+ })+ .collect();+ merged.values.extend(resolved);++ let db_val = merged.values.get("db_type").and_then(|v| v.as_str()).unwrap_or("mysql");+ let database_type: DatabaseType = serde_json::from_str(&format!("\"{db_val}\"")).unwrap_or(DatabaseType::Mysql);++ let opts = SchemaDiffPreparationOptions {+ source_tables: vec![],+ target_tables: vec![],+ source_details: vec![],+ target_details: vec![],+ source_functions: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type,+ target_schema: merged.values.get("target_schema").and_then(|v| v.as_str()).map(String::from),+ ignore_comments: merged.values.get("ignore_comments").and_then(|v| v.as_bool()).unwrap_or(false),+ cascade_delete: merged.values.get("cascade_delete").and_then(|v| v.as_bool()).unwrap_or(false),+ compare_column_order: merged.values.get("compare_column_order").and_then(|v| v.as_bool()).unwrap_or(false),+ ..Default::default()+ };++ assert_eq!(opts.database_type, DatabaseType::Postgres);+ assert_eq!(opts.target_schema.as_deref(), Some("public"));+ assert!(opts.ignore_comments);+ assert!(opts.cascade_delete);+ assert!(opts.compare_column_order);++ let whitelist = TagInheritanceWhitelist::new(vec!["env".to_string()], TagPolicy::Strict);+ let validator = TagValidator::new(whitelist, true);+ let tags: Vec<BusinessTag> = merged_snapshot+ .tags+ .iter()+ .map(|(k, v)| BusinessTag {+ key: k.clone(),+ value: v.clone(),+ description: String::new(),+ immutable: false,+ })+ .collect();+ let result = validator.validate_tags(&tags, &HashMap::new());+ assert_eq!(result.allowed.len(), 1);+ assert_eq!(result.blocked.len(), 0);++ let mut trace = TraceRingBuffer::new(100);+ trace.record(ConfigLayer::Global, "target_schema", "read", "used for SchemaDiffPreparationOptions");+ trace.record(ConfigLayer::Global, "db_type", "read", "used for DatabaseType");+ trace.record(ConfigLayer::Task, "cascade_delete", "read", "overridden from task layer");+ assert_eq!(trace.len(), 3);+ }++ #[test]+ fn test_config_expression_with_value_injection() {+ let mut tree = ConfigTree::new();++ let mut global = HashMap::new();+ global.insert("base_host".to_string(), serde_json::Value::String("db.example.com".to_string()));+ global.insert("base_port".to_string(), serde_json::Value::Number(serde_json::Number::from(5432)));++ tree.add_layer(LayerConfig {+ layer: ConfigLayer::Global,+ name: "global".to_string(),+ values: global,+ ..Default::default()+ });++ tree.add_layer(LayerConfig {+ layer: ConfigLayer::Project,+ name: "project".to_string(),+ values: HashMap::from([+ ("jdbc_url".to_string(), serde_json::Value::String("${eval:\"jdbc:postgresql://\"}".to_string())),+ ("host".to_string(), serde_json::Value::String("${ref:base_host}".to_string())),+ ]),+ ..Default::default()+ });++ let merged = tree.merge().unwrap();+ let scope = merged.values.clone();++ let url_resolved = resolve_all_expressions_in_value(+ &serde_json::Value::String("${eval:\"jdbc:postgresql://\"}".to_string()),+ &scope,+ )+ .unwrap();+ assert_eq!(url_resolved, serde_json::Value::String("jdbc:postgresql://".to_string()));++ let host_resolved =+ resolve_all_expressions_in_value(&serde_json::Value::String("${ref:base_host}".to_string()), &scope)+ .unwrap();+ assert_eq!(host_resolved, serde_json::Value::String("db.example.com".to_string()));+ }+}diff --git a/crates/dbx-core/src/config/tag.rs b/crates/dbx-core/src/config/tag.rsnew file mode 100644index 0000000000..390fea5e75--- /dev/null+++ b/crates/dbx-core/src/config/tag.rs@@ -0,0 +1,441 @@+use serde::{Deserialize, Serialize};+use std::collections::{HashMap, HashSet};++/// Controls how `TagInheritanceWhitelist` handles unlisted tags.+///+/// - `Allow` — all tags pass through by default; the whitelist is purely informational.+/// - `Block` — only tags whose keys appear in `allowed_keys` pass through; unlisted tags+/// are collected in `TagValidationResult::blocked` and count as blocking violations.+/// - `Strict` — same key filtering as `Block`, but additionally checks that tag *values*+/// match the base-layer values. Any value mismatch (or blocked key) is reported as a+/// violation, and **all** violations (including value mismatches) count as blocking.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum TagPolicy {+ #[default]+ Allow,+ Block,+ Strict,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BusinessTag {+ pub key: String,+ pub value: String,++ #[serde(default)]+ pub description: String,++ #[serde(default)]+ pub immutable: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TagInheritanceWhitelist {+ #[serde(default)]+ pub allowed_keys: HashSet<String>,++ #[serde(default = "default_policy")]+ pub default_policy: TagPolicy,+}++fn default_policy() -> TagPolicy {+ TagPolicy::Block+}++impl Default for TagInheritanceWhitelist {+ fn default() -> Self {+ Self { allowed_keys: HashSet::new(), default_policy: TagPolicy::Block }+ }+}++impl TagInheritanceWhitelist {+ pub fn new(allowed: Vec<String>, policy: TagPolicy) -> Self {+ Self { allowed_keys: allowed.into_iter().collect(), default_policy: policy }+ }++ pub fn is_allowed(&self, key: &str) -> bool {+ match self.default_policy {+ TagPolicy::Allow => true,+ TagPolicy::Block => self.allowed_keys.contains(key),+ TagPolicy::Strict => self.allowed_keys.contains(key),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TagValidationResult {+ pub allowed: Vec<BusinessTag>,+ pub blocked: Vec<BusinessTag>,+ pub violations: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct TagValidator {+ pub whitelist: TagInheritanceWhitelist,+ #[serde(default)]+ pub strict_mode: bool,+}++impl TagValidator {+ pub fn new(whitelist: TagInheritanceWhitelist, strict_mode: bool) -> Self {+ Self { whitelist, strict_mode }+ }++ pub fn validate_tags(&self, tags: &[BusinessTag], base_tags: &HashMap<String, String>) -> TagValidationResult {+ let mut allowed = Vec::new();+ let mut blocked = Vec::new();+ let mut violations = Vec::new();++ for tag in tags {+ if !self.whitelist.is_allowed(&tag.key) {+ blocked.push(tag.clone());+ let msg = if self.strict_mode {+ format!("BLOCKED: Tag '{}'='{}' is not in whitelist (strict mode)", tag.key, tag.value)+ } else {+ format!("BLOCKED: Tag '{}'='{}' is not in whitelist", tag.key, tag.value)+ };+ violations.push(msg);+ continue;+ }++ if let Some(base_val) = base_tags.get(&tag.key) {+ if tag.value != *base_val && self.strict_mode {+ violations.push(format!(+ "STRICT VIOLATION: Tag '{}'='{}' differs from base value '{}'",+ tag.key, tag.value, base_val+ ));+ }+ }++ allowed.push(tag.clone());+ }++ TagValidationResult { allowed, blocked, violations }+ }++ pub fn has_blocking_violations(&self, result: &TagValidationResult) -> bool {+ if self.strict_mode {+ !result.violations.is_empty()+ } else {+ !result.blocked.is_empty()+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BlockStats {+ pub total_tags: usize,+ pub blocked_count: usize,+ pub violation_count: usize,+ pub by_key: HashMap<String, usize>,+ pub strict_mode: bool,+}++impl BlockStats {+ pub fn from_validation(result: &TagValidationResult, strict_mode: bool) -> Self {+ let mut by_key = HashMap::new();+ for tag in &result.blocked {+ *by_key.entry(tag.key.clone()).or_insert(0) += 1;+ }+ Self {+ total_tags: result.allowed.len() + result.blocked.len(),+ blocked_count: result.blocked.len(),+ violation_count: result.violations.len(),+ by_key,+ strict_mode,+ }+ }+}++pub struct TagGuard {+ pub validator: TagValidator,+ pub stats: std::sync::Mutex<Vec<BlockStats>>,+}++impl TagGuard {+ pub fn new(validator: TagValidator) -> Self {+ Self { validator, stats: std::sync::Mutex::new(Vec::new()) }+ }++ pub fn validate_and_collect(+ &self,+ tags: &[BusinessTag],+ base_tags: &HashMap<String, String>,+ ) -> TagValidationResult {+ let result = self.validator.validate_tags(tags, base_tags);+ let stats = BlockStats::from_validation(&result, self.validator.strict_mode);+ if let Ok(mut guard) = self.stats.lock() {+ guard.push(stats);+ }+ result+ }++ pub fn accumulated_stats(&self) -> Vec<BlockStats> {+ self.stats.lock().map(|g| g.clone()).unwrap_or_default()+ }++ pub fn blocking_summary(&self) -> (usize, usize, usize) {+ let stats = self.accumulated_stats();+ let total_blocked = stats.iter().map(|s| s.blocked_count).sum();+ let total_violations = stats.iter().map(|s| s.violation_count).sum();+ let total_tags = stats.iter().map(|s| s.total_tags).sum();+ (total_blocked, total_violations, total_tags)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn test_allow_policy_allows_all() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Allow);+ assert!(whitelist.is_allowed("anything"));+ }++ #[test]+ fn test_block_policy_blocks_unlisted() {+ let whitelist = TagInheritanceWhitelist::new(vec!["allowed_key".to_string()], TagPolicy::Block);+ assert!(whitelist.is_allowed("allowed_key"));+ assert!(!whitelist.is_allowed("blocked_key"));+ }++ #[test]+ fn test_strict_policy_blocks_unlisted() {+ let whitelist = TagInheritanceWhitelist::new(vec!["safe".to_string()], TagPolicy::Strict);+ assert!(whitelist.is_allowed("safe"));+ assert!(!whitelist.is_allowed("unsafe"));+ }++ #[test]+ fn test_validator_allows_all_with_allow_policy() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Allow);+ let validator = TagValidator::new(whitelist, false);++ let tags = vec![BusinessTag {+ key: "env".to_string(),+ value: "prod".to_string(),+ description: String::new(),+ immutable: false,+ }];+ let base = HashMap::new();+ let result = validator.validate_tags(&tags, &base);+ assert_eq!(result.allowed.len(), 1);+ assert_eq!(result.blocked.len(), 0);+ }++ #[test]+ fn test_validator_blocks_unlisted_in_block_mode() {+ let whitelist = TagInheritanceWhitelist::new(vec!["allowed".to_string()], TagPolicy::Block);+ let validator = TagValidator::new(whitelist, false);++ let tags = vec![+ BusinessTag {+ key: "allowed".to_string(),+ value: "yes".to_string(),+ description: String::new(),+ immutable: false,+ },+ BusinessTag {+ key: "blocked".to_string(),+ value: "no".to_string(),+ description: String::new(),+ immutable: false,+ },+ ];+ let base = HashMap::new();+ let result = validator.validate_tags(&tags, &base);+ assert_eq!(result.allowed.len(), 1);+ assert_eq!(result.blocked.len(), 1);+ assert_eq!(result.blocked[0].key, "blocked");+ }++ #[test]+ fn test_strict_mode_reports_value_mismatch() {+ let whitelist = TagInheritanceWhitelist::new(vec!["env".to_string()], TagPolicy::Strict);+ let validator = TagValidator::new(whitelist, true);++ let tags = vec![BusinessTag {+ key: "env".to_string(),+ value: "staging".to_string(),+ description: String::new(),+ immutable: false,+ }];+ let mut base = HashMap::new();+ base.insert("env".to_string(), "prod".to_string());+ let result = validator.validate_tags(&tags, &base);+ assert_eq!(result.violations.len(), 1);+ assert!(result.violations[0].contains("STRICT VIOLATION"));+ }++ #[test]+ fn test_has_blocking_violations_standard_mode() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Block);+ let validator = TagValidator::new(whitelist, false);++ let result = TagValidationResult {+ allowed: vec![],+ blocked: vec![BusinessTag {+ key: "x".to_string(),+ value: "y".to_string(),+ description: String::new(),+ immutable: false,+ }],+ violations: vec![],+ };+ assert!(validator.has_blocking_violations(&result));+ }++ #[test]+ fn test_has_blocking_violations_strict_mode() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Strict);+ let validator = TagValidator::new(whitelist, true);++ let result =+ TagValidationResult { allowed: vec![], blocked: vec![], violations: vec!["STRICT VIOLATION".to_string()] };+ assert!(validator.has_blocking_violations(&result));+ }++ #[test]+ fn test_has_blocking_violations_no_violations() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Allow);+ let validator = TagValidator::new(whitelist, false);++ let result = TagValidationResult { allowed: vec![], blocked: vec![], violations: vec![] };+ assert!(!validator.has_blocking_violations(&result));+ }++ #[test]+ fn test_immutable_tag_field() {+ let tag = BusinessTag {+ key: "env".to_string(),+ value: "prod".to_string(),+ description: "Environment".to_string(),+ immutable: true,+ };+ assert!(tag.immutable);+ }++ #[test]+ fn block_stats_from_validation() {+ let whitelist = TagInheritanceWhitelist::new(vec!["allowed".to_string()], TagPolicy::Block);+ let validator = TagValidator::new(whitelist, false);++ let tags = vec![+ BusinessTag {+ key: "allowed".to_string(),+ value: "yes".to_string(),+ description: String::new(),+ immutable: false,+ },+ BusinessTag {+ key: "blocked1".to_string(),+ value: "no".to_string(),+ description: String::new(),+ immutable: false,+ },+ BusinessTag {+ key: "blocked2".to_string(),+ value: "no".to_string(),+ description: String::new(),+ immutable: false,+ },+ ];+ let base = HashMap::new();+ let result = validator.validate_tags(&tags, &base);+ let stats = BlockStats::from_validation(&result, false);+ assert_eq!(stats.total_tags, 3);+ assert_eq!(stats.blocked_count, 2);+ assert_eq!(stats.violation_count, 2);+ assert_eq!(stats.by_key.get("blocked1"), Some(&1usize));+ assert_eq!(stats.by_key.get("blocked2"), Some(&1usize));+ assert!(!stats.strict_mode);+ }++ #[test]+ fn block_stats_with_strict_mode_violations() {+ let whitelist = TagInheritanceWhitelist::new(vec!["env".to_string()], TagPolicy::Strict);+ let validator = TagValidator::new(whitelist, true);++ let tags = vec![BusinessTag {+ key: "env".to_string(),+ value: "dev".to_string(),+ description: String::new(),+ immutable: false,+ }];+ let mut base = HashMap::new();+ base.insert("env".to_string(), "prod".to_string());+ let result = validator.validate_tags(&tags, &base);+ let stats = BlockStats::from_validation(&result, true);+ assert_eq!(stats.blocked_count, 0);+ assert_eq!(stats.violation_count, 1);+ assert!(stats.strict_mode);+ }++ #[test]+ fn tag_guard_collects_multiple_validations() {+ let whitelist = TagInheritanceWhitelist::new(vec!["env".to_string()], TagPolicy::Strict);+ let validator = TagValidator::new(whitelist, true);+ let guard = TagGuard::new(validator);++ let tags1 = vec![BusinessTag {+ key: "env".to_string(),+ value: "staging".to_string(),+ description: String::new(),+ immutable: false,+ }];+ let mut base1 = HashMap::new();+ base1.insert("env".to_string(), "prod".to_string());++ let tags2 = vec![BusinessTag {+ key: "blocked".to_string(),+ value: "x".to_string(),+ description: String::new(),+ immutable: false,+ }];++ guard.validate_and_collect(&tags1, &base1);+ guard.validate_and_collect(&tags2, &HashMap::new());++ let stats = guard.accumulated_stats();+ assert_eq!(stats.len(), 2);+ assert_eq!(stats[0].violation_count, 1);+ assert_eq!(stats[1].blocked_count, 1);++ let (blocked, violations, total) = guard.blocking_summary();+ assert_eq!(blocked, 1);+ assert_eq!(violations, 2);+ assert_eq!(total, 2);+ }++ #[test]+ fn tag_guard_empty_stats() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Allow);+ let validator = TagValidator::new(whitelist, false);+ let guard = TagGuard::new(validator);++ assert!(guard.accumulated_stats().is_empty());+ let (blocked, violations, total) = guard.blocking_summary();+ assert_eq!(blocked, 0);+ assert_eq!(violations, 0);+ assert_eq!(total, 0);+ }++ #[test]+ fn tag_guard_blocking_with_strict_mode() {+ let whitelist = TagInheritanceWhitelist::new(vec![], TagPolicy::Strict);+ let validator = TagValidator::new(whitelist, true);+ let guard = TagGuard::new(validator);++ let tags = vec![BusinessTag {+ key: "env".to_string(),+ value: "dev".to_string(),+ description: String::new(),+ immutable: false,+ }];+ let result = guard.validate_and_collect(&tags, &HashMap::new());+ assert_eq!(result.blocked.len(), 1);+ assert!(guard.validator.has_blocking_violations(&result));+ }+}diff --git a/crates/dbx-core/src/config/trace.rs b/crates/dbx-core/src/config/trace.rsnew file mode 100644index 0000000000..755ea49da4--- /dev/null+++ b/crates/dbx-core/src/config/trace.rs@@ -0,0 +1,273 @@+use chrono::{DateTime, Utc};+use serde::{Deserialize, Serialize};+use std::collections::VecDeque;++use super::ConfigLayer;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TraceEntry {+ pub timestamp: DateTime<Utc>,+ pub layer: ConfigLayer,+ pub key: String,+ pub action: String,+ pub detail: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TraceRingBuffer {+ capacity: usize,+ entries: VecDeque<TraceEntry>,+}++impl TraceRingBuffer {+ pub fn new(capacity: usize) -> Self {+ Self { capacity, entries: VecDeque::with_capacity(capacity) }+ }++ pub fn push(&mut self, entry: TraceEntry) {+ if self.entries.len() >= self.capacity {+ self.entries.pop_front();+ }+ self.entries.push_back(entry);+ }++ pub fn record(&mut self, layer: ConfigLayer, key: &str, action: &str, detail: &str) {+ self.push(TraceEntry {+ timestamp: Utc::now(),+ layer,+ key: key.to_string(),+ action: action.to_string(),+ detail: detail.to_string(),+ });+ }++ pub fn entries(&self) -> impl Iterator<Item = &TraceEntry> {+ self.entries.iter()+ }++ pub fn len(&self) -> usize {+ self.entries.len()+ }++ pub fn is_empty(&self) -> bool {+ self.entries.is_empty()+ }++ pub fn capacity(&self) -> usize {+ self.capacity+ }++ pub fn clear(&mut self) {+ self.entries.clear();+ }++ pub fn filter_by_layer(&self, layer: ConfigLayer) -> Vec<&TraceEntry> {+ self.entries.iter().filter(|e| e.layer == layer).collect()+ }++ pub fn filter_by_action(&self, action: &str) -> Vec<&TraceEntry> {+ self.entries.iter().filter(|e| e.action == action).collect()+ }++ pub fn export_json(&self) -> Result<String, String> {+ serde_json::to_string_pretty(&self.entries)+ .map_err(|e| format!("Failed to serialize {} trace entries: {e}", self.entries.len()))+ }++ pub fn recent(&self, n: usize) -> Vec<&TraceEntry> {+ let n = n.min(self.entries.len());+ self.entries.iter().rev().take(n).collect()+ }++ pub fn stats(&self) -> TraceStats {+ let mut action_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();+ let mut layer_counts: std::collections::HashMap<String, usize> = std::collections::HashMap::new();++ for entry in &self.entries {+ *action_counts.entry(entry.action.clone()).or_insert(0) += 1;+ *layer_counts.entry(entry.layer.label().to_string()).or_insert(0) += 1;+ }++ TraceStats { total_entries: self.entries.len(), capacity: self.capacity, action_counts, layer_counts }+ }+}++impl Default for TraceRingBuffer {+ fn default() -> Self {+ Self::new(1000)+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TraceStats {+ pub total_entries: usize,+ pub capacity: usize,+ pub action_counts: std::collections::HashMap<String, usize>,+ pub layer_counts: std::collections::HashMap<String, usize>,+}++#[cfg(test)]+mod tests {+ use super::*;+ use chrono::TimeZone;++ fn sample_entry() -> TraceEntry {+ TraceEntry {+ timestamp: Utc.with_ymd_and_hms(2026, 1, 1, 0, 0, 0).unwrap(),+ layer: ConfigLayer::Global,+ key: "host".to_string(),+ action: "read".to_string(),+ detail: "value resolved".to_string(),+ }+ }++ #[test]+ fn test_new_buffer_is_empty() {+ let buf = TraceRingBuffer::new(10);+ assert!(buf.is_empty());+ assert_eq!(buf.len(), 0);+ }++ #[test]+ fn test_push_adds_entry() {+ let mut buf = TraceRingBuffer::new(10);+ buf.push(sample_entry());+ assert_eq!(buf.len(), 1);+ }++ #[test]+ fn test_push_evicts_oldest_when_full() {+ let mut buf = TraceRingBuffer::new(3);+ for i in 0..5 {+ buf.push(TraceEntry {+ timestamp: Utc::now(),+ layer: ConfigLayer::Task,+ key: format!("key{i}"),+ action: "write".to_string(),+ detail: String::new(),+ });+ }+ assert_eq!(buf.len(), 3);+ let entries: Vec<&TraceEntry> = buf.entries().collect();+ assert_eq!(entries[0].key, "key2");+ assert_eq!(entries[2].key, "key4");+ }++ #[test]+ fn test_record_convenience() {+ let mut buf = TraceRingBuffer::new(10);+ buf.record(ConfigLayer::Global, "host", "read", "localhost");+ assert_eq!(buf.len(), 1);+ let entry = buf.entries().next().unwrap();+ assert_eq!(entry.layer, ConfigLayer::Global);+ assert_eq!(entry.key, "host");+ assert_eq!(entry.action, "read");+ }++ #[test]+ fn test_filter_by_layer() {+ let mut buf = TraceRingBuffer::new(10);+ buf.record(ConfigLayer::Global, "host", "read", "");+ buf.record(ConfigLayer::Project, "port", "write", "");+ buf.record(ConfigLayer::Global, "user", "read", "");++ let global_entries = buf.filter_by_layer(ConfigLayer::Global);+ assert_eq!(global_entries.len(), 2);++ let project_entries = buf.filter_by_layer(ConfigLayer::Project);+ assert_eq!(project_entries.len(), 1);++ let task_entries = buf.filter_by_layer(ConfigLayer::Task);+ assert_eq!(task_entries.len(), 0);+ }++ #[test]+ fn test_filter_by_action() {+ let mut buf = TraceRingBuffer::new(10);+ buf.record(ConfigLayer::Global, "host", "read", "");+ buf.record(ConfigLayer::Global, "port", "write", "");+ buf.record(ConfigLayer::Global, "user", "read", "");++ let reads = buf.filter_by_action("read");+ assert_eq!(reads.len(), 2);++ let writes = buf.filter_by_action("write");+ assert_eq!(writes.len(), 1);+ }++ #[test]+ fn test_export_json() {+ let mut buf = TraceRingBuffer::new(10);+ buf.push(sample_entry());+ let json = buf.export_json().unwrap();+ assert!(json.contains("host"));+ assert!(json.contains("read"));+ }++ #[test]+ fn test_recent() {+ let mut buf = TraceRingBuffer::new(10);+ for i in 0..5 {+ buf.record(ConfigLayer::Task, &format!("key{i}"), "write", "");+ }+ let recent = buf.recent(3);+ assert_eq!(recent.len(), 3);+ assert_eq!(recent[0].key, "key4");+ assert_eq!(recent[2].key, "key2");+ }++ #[test]+ fn test_recent_less_than_n() {+ let mut buf = TraceRingBuffer::new(10);+ buf.record(ConfigLayer::Task, "k1", "read", "");+ let recent = buf.recent(10);+ assert_eq!(recent.len(), 1);+ }++ #[test]+ fn test_clear() {+ let mut buf = TraceRingBuffer::new(10);+ buf.record(ConfigLayer::Task, "k1", "read", "");+ buf.record(ConfigLayer::Task, "k2", "write", "");+ assert_eq!(buf.len(), 2);+ buf.clear();+ assert!(buf.is_empty());+ }++ #[test]+ fn test_stats() {+ let mut buf = TraceRingBuffer::new(100);+ buf.record(ConfigLayer::Global, "host", "read", "");+ buf.record(ConfigLayer::Global, "port", "read", "");+ buf.record(ConfigLayer::Project, "config", "write", "");++ let stats = buf.stats();+ assert_eq!(stats.total_entries, 3);+ assert_eq!(*stats.action_counts.get("read").unwrap(), 2);+ assert_eq!(*stats.action_counts.get("write").unwrap(), 1);+ assert_eq!(*stats.layer_counts.get("global").unwrap(), 2);+ assert_eq!(*stats.layer_counts.get("project").unwrap(), 1);+ }++ #[test]+ fn test_default_capacity() {+ let buf = TraceRingBuffer::default();+ assert_eq!(buf.capacity(), 1000);+ }++ #[test]+ fn test_capacity_set_correctly() {+ let buf = TraceRingBuffer::new(500);+ assert_eq!(buf.capacity(), 500);+ }++ #[test]+ fn test_entry_timestamp_is_set() {+ let mut buf = TraceRingBuffer::new(10);+ buf.record(ConfigLayer::Task, "k", "read", "detail");+ let entry = buf.entries().next().unwrap();+ let now = Utc::now();+ let diff = now - entry.timestamp;+ assert!(diff.num_seconds() < 5);+ }+}diff --git a/crates/dbx-core/src/correction.rs b/crates/dbx-core/src/correction.rsnew file mode 100644index 0000000000..17497ace01--- /dev/null+++ b/crates/dbx-core/src/correction.rs@@ -0,0 +1,659 @@+use serde::{Deserialize, Serialize};++use crate::data_compare::{DataCompareFromTablesPreparation, DataCompareResult};+use crate::schema_diff::SchemaDiffPreparation;++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub enum CorrectionStepType {+ SchemaCreate,+ SchemaAlter,+ SchemaDrop,+ DataInsert,+ DataUpdate,+ DataDelete,+ SchemaPostSync,+ Checkpoint,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CorrectionStep {+ pub step_type: CorrectionStepType,+ pub table_name: Option<String>,+ pub sql: String,+ pub rollback_sql: Option<String>,+ pub description: String,+ pub risk_level: CorrectionRiskLevel,+ #[serde(default)]+ pub depends_on: Vec<usize>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]+#[serde(rename_all = "camelCase")]+pub enum CorrectionRiskLevel {+ Safe,+ #[default]+ Caution,+ Dangerous,+ Blocked,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub enum CorrectionStrategy {+ StructureFirst,+ DataFirst,+ Interleaved,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct JointCorrectionPlan {+ pub strategy: CorrectionStrategy,+ pub steps: Vec<CorrectionStep>,+ pub schema_diff_count: usize,+ pub data_diff_count: usize,+ pub total_estimated_duration_secs: Option<u64>,+ #[serde(default)]+ pub rollback_steps: Vec<CorrectionStep>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct JointCorrectionOptions {+ pub strategy: CorrectionStrategy,+ #[serde(default)]+ pub include_checkpoints: bool,+ #[serde(default)]+ pub include_rollback: bool,+}++impl Default for JointCorrectionOptions {+ fn default() -> Self {+ Self { strategy: CorrectionStrategy::StructureFirst, include_checkpoints: true, include_rollback: true }+ }+}++/// Build a joint correction plan from schema diff and data compare results.+///+/// Orchestrates schema + data changes according to `CorrectionStrategy`:+/// - `StructureFirst`: schema → data → post-sync checks+/// - `DataFirst`: data → schema+/// - `Interleaved`: per-table schema + data interleaved+///+/// # Limitations+/// - `Interleaved` uses placeholder SQL rather than actual per-table DDL slices.+/// - Table name matching uses substring checks (`line.contains(&name)`), which can+/// produce false positives when one table name is a prefix of another.+pub fn build_joint_correction_plan(+ schema_diff: Option<&SchemaDiffPreparation>,+ data_compare: Option<&DataCompareFromTablesPreparation>,+ options: JointCorrectionOptions,+) -> JointCorrectionPlan {+ let mut steps = Vec::new();+ let mut rollback_steps = Vec::new();+ let mut step_index = 0usize;++ match options.strategy {+ CorrectionStrategy::StructureFirst => {+ step_index = append_schema_steps(schema_diff, &mut steps, &mut rollback_steps, &options, step_index);+ let _ = append_data_steps(data_compare, &mut steps, &mut rollback_steps, &options, step_index);+ }+ CorrectionStrategy::DataFirst => {+ step_index = append_data_steps(data_compare, &mut steps, &mut rollback_steps, &options, step_index);+ let _ = append_schema_steps(schema_diff, &mut steps, &mut rollback_steps, &options, step_index);+ }+ CorrectionStrategy::Interleaved => {+ if let Some(schema) = schema_diff {+ let table_diffs: Vec<_> = schema.diffs.iter().filter(|d| d.diff_type != "unchanged").collect();++ for table_diff in &table_diffs {+ let tbl_name = &table_diff.name;++ if let Some(dc) = data_compare {+ if contains_table(&dc.sync_sql, tbl_name) {+ step_index = append_table_data_step(+ &dc.result,+ tbl_name,+ &mut steps,+ &mut rollback_steps,+ &options,+ step_index,+ );+ }+ }++ step_index = append_table_schema_step(+ table_diff,+ tbl_name,+ &mut steps,+ &mut rollback_steps,+ &options,+ step_index,+ );+ }+ } else if let Some(dc) = data_compare {+ let _ = append_data_steps(Some(dc), &mut steps, &mut rollback_steps, &options, step_index);+ }+ }+ }++ let schema_diff_count = steps+ .iter()+ .filter(|s| {+ matches!(+ s.step_type,+ CorrectionStepType::SchemaCreate+ | CorrectionStepType::SchemaAlter+ | CorrectionStepType::SchemaDrop+ | CorrectionStepType::SchemaPostSync+ )+ })+ .count();+ let data_diff_count = steps+ .iter()+ .filter(|s| {+ matches!(+ s.step_type,+ CorrectionStepType::DataInsert | CorrectionStepType::DataUpdate | CorrectionStepType::DataDelete+ )+ })+ .count();++ JointCorrectionPlan {+ strategy: options.strategy,+ steps,+ schema_diff_count,+ data_diff_count,+ total_estimated_duration_secs: None,+ rollback_steps,+ }+}++fn append_schema_steps(+ schema_diff: Option<&SchemaDiffPreparation>,+ steps: &mut Vec<CorrectionStep>,+ _rollback_steps: &mut Vec<CorrectionStep>,+ options: &JointCorrectionOptions,+ mut step_index: usize,+) -> usize {+ let Some(schema) = schema_diff else {+ return step_index;+ };++ if schema.sync_sql.is_empty() {+ return step_index;+ }++ if options.include_checkpoints {+ steps.push(CorrectionStep {+ step_type: CorrectionStepType::Checkpoint,+ table_name: None,+ sql: String::new(),+ rollback_sql: None,+ description: "Schema correction checkpoint".to_string(),+ risk_level: CorrectionRiskLevel::Safe,+ depends_on: Vec::new(),+ });+ step_index += 1;+ }++ let table_diffs: Vec<_> = schema.diffs.iter().filter(|d| d.diff_type != "unchanged").collect();++ for table_diff in &table_diffs {+ let tbl_name = &table_diff.name;+ step_index = append_table_schema_step(table_diff, tbl_name, steps, _rollback_steps, options, step_index);+ }++ step_index+}++fn append_table_schema_step(+ table_diff: &crate::schema_diff::TableDiff,+ tbl_name: &str,+ steps: &mut Vec<CorrectionStep>,+ rollback_steps: &mut Vec<CorrectionStep>,+ options: &JointCorrectionOptions,+ mut step_index: usize,+) -> usize {+ let step_type = match table_diff.diff_type.as_str() {+ "added" => CorrectionStepType::SchemaCreate,+ "removed" => CorrectionStepType::SchemaDrop,+ _ => CorrectionStepType::SchemaAlter,+ };++ let risk_level = match table_diff.diff_type.as_str() {+ "removed" => CorrectionRiskLevel::Dangerous,+ "modified" => CorrectionRiskLevel::Caution,+ _ => CorrectionRiskLevel::Safe,+ };++ let has_incomplete_triggers = table_diff+ .triggers+ .as_ref()+ .is_some_and(|triggers| triggers.iter().any(|t| t.source.as_ref().is_some_and(|s| s.statement.is_none())));++ let rollback_sql = if options.include_rollback {+ match table_diff.diff_type.as_str() {+ "added" => Some(format!("DROP TABLE IF EXISTS {};", tbl_name)),+ "removed" => {+ table_diff.target_ddl.as_ref().map(|ddl| {+ if has_incomplete_triggers {+ format!(+ "-- WARNING: Rollback DDL is INCOMPLETE — trigger bodies could not be reconstructed.\n-- Manual review required. Original DDL:\n{}",+ ddl+ )+ } else {+ ddl.clone()+ }+ }).or_else(|| {+ if has_incomplete_triggers {+ Some(format!(+ "-- WARNING: Rollback is INCOMPLETE — table '{}' had triggers that cannot be reconstructed.\n-- Manual intervention required before executing.",+ tbl_name+ ))+ } else {+ Some(format!(+ "-- Manual rollback required: recreate table {} with original DDL",+ tbl_name+ ))+ }+ })+ }+ "modified" => table_diff.sync_sql.as_ref().map(|s| format!("-- Rollback: {}", s)),+ _ => None,+ }+ } else {+ None+ };++ let rollback_risk = if has_incomplete_triggers { CorrectionRiskLevel::Blocked } else { risk_level.clone() };++ let rollback_desc = if has_incomplete_triggers {+ format!(+ "INCOMPLETE Rollback for schema {} on table: {tbl_name} — trigger bodies cannot be reconstructed",+ table_diff.diff_type+ )+ } else {+ format!("Rollback for schema {} on table: {tbl_name}", table_diff.diff_type)+ };++ let sql = table_diff.sync_sql.clone().unwrap_or_else(|| format!("-- Schema change for table: {tbl_name}"));++ steps.push(CorrectionStep {+ step_type,+ table_name: Some(tbl_name.to_string()),+ sql,+ rollback_sql: rollback_sql.clone(),+ description: format!("Schema {} for table: {tbl_name}", table_diff.diff_type),+ risk_level,+ depends_on: Vec::new(),+ });++ if let Some(rollback) = rollback_sql {+ rollback_steps.push(CorrectionStep {+ step_type: match table_diff.diff_type.as_str() {+ "added" => CorrectionStepType::SchemaDrop,+ "removed" => CorrectionStepType::SchemaCreate,+ _ => CorrectionStepType::SchemaAlter,+ },+ table_name: Some(tbl_name.to_string()),+ sql: rollback,+ rollback_sql: None,+ description: rollback_desc,+ risk_level: rollback_risk,+ depends_on: Vec::new(),+ });+ }++ step_index += 1;++ step_index+}++fn append_data_steps(+ data_compare: Option<&DataCompareFromTablesPreparation>,+ steps: &mut Vec<CorrectionStep>,+ _rollback_steps: &mut Vec<CorrectionStep>,+ options: &JointCorrectionOptions,+ mut step_index: usize,+) -> usize {+ let Some(dc) = data_compare else {+ return step_index;+ };++ if dc.result.added.is_empty() && dc.result.removed.is_empty() && dc.result.modified.is_empty() {+ return step_index;+ }++ if options.include_checkpoints {+ steps.push(CorrectionStep {+ step_type: CorrectionStepType::Checkpoint,+ table_name: None,+ sql: String::new(),+ rollback_sql: None,+ description: "Data correction checkpoint".to_string(),+ risk_level: CorrectionRiskLevel::Safe,+ depends_on: Vec::new(),+ });+ step_index += 1;+ }++ for statement in &dc.sync_statements {+ let (step_type, description) = if statement.to_uppercase().starts_with("INSERT") {+ (CorrectionStepType::DataInsert, format!("Insert data: {}", summary(statement, 80)))+ } else if statement.to_uppercase().starts_with("UPDATE") {+ (CorrectionStepType::DataUpdate, format!("Update data: {}", summary(statement, 80)))+ } else if statement.to_uppercase().starts_with("DELETE") {+ (CorrectionStepType::DataDelete, format!("Delete data: {}", summary(statement, 80)))+ } else {+ (CorrectionStepType::SchemaPostSync, format!("Pre-sync: {}", summary(statement, 80)))+ };++ let rollback_sql = if options.include_rollback {+ if statement.to_uppercase().starts_with("INSERT") {+ Some(format!("-- Rollback: DELETE matching rows; manual review needed: {}", summary(statement, 60)))+ } else if statement.to_uppercase().starts_with("DELETE") {+ Some(format!("-- Rollback: INSERT deleted rows; manual review needed: {}", summary(statement, 60)))+ } else if statement.to_uppercase().starts_with("UPDATE") {+ Some(format!("-- Rollback: reverse UPDATE; manual review needed: {}", summary(statement, 60)))+ } else {+ None+ }+ } else {+ None+ };++ steps.push(CorrectionStep {+ step_type,+ table_name: None,+ sql: statement.clone(),+ rollback_sql,+ description,+ risk_level: CorrectionRiskLevel::Caution,+ depends_on: Vec::new(),+ });+ step_index += 1;+ }++ step_index+}++fn append_table_data_step(+ data_prep: &DataCompareResult,+ tbl_name: &str,+ steps: &mut Vec<CorrectionStep>,+ _rollback_steps: &mut Vec<CorrectionStep>,+ _options: &JointCorrectionOptions,+ mut step_index: usize,+) -> usize {+ let total = data_prep.added.len() + data_prep.modified.len() + data_prep.removed.len();+ if total == 0 {+ return step_index;+ }++ steps.push(CorrectionStep {+ step_type: CorrectionStepType::DataInsert,+ table_name: Some(tbl_name.to_string()),+ sql: format!(+ "-- Data sync for table: {tbl_name} ({} added, {} modified, {} removed)",+ data_prep.added.len(),+ data_prep.modified.len(),+ data_prep.removed.len()+ ),+ rollback_sql: None,+ description: format!(+ "Data sync for table: {tbl_name} ({} added, {} modified, {} removed)",+ data_prep.added.len(),+ data_prep.modified.len(),+ data_prep.removed.len()+ ),+ risk_level: CorrectionRiskLevel::Caution,+ depends_on: Vec::new(),+ });+ step_index += 1;++ step_index+}++fn contains_table(sync_sql: &str, table_name: &str) -> bool {+ sync_sql.contains(table_name)+}++fn summary(text: &str, max_len: usize) -> String {+ let cleaned = text.replace('\n', " ");+ if cleaned.len() <= max_len {+ cleaned+ } else {+ format!("{}...", &cleaned[..max_len.min(cleaned.len())])+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::data_compare::{+ DataCompareChangedCell, DataCompareFromTablesPreparation, DataCompareModifiedRow, DataCompareResult,+ DataCompareRow,+ };+ use crate::schema_diff::{SchemaDiffPreparation, TableDiff};+ use serde_json::json;+ use std::collections::HashMap;++ fn sample_table_diff(diff_type: &str, name: &str) -> TableDiff {+ TableDiff {+ diff_type: diff_type.to_string(),+ object_type: Some("table".to_string()),+ name: name.to_string(),+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: Some(format!("-- SQL for {name}")),+ }+ }++ fn sample_schema_preparation() -> SchemaDiffPreparation {+ SchemaDiffPreparation {+ diffs: vec![sample_table_diff("added", "users"), sample_table_diff("modified", "orders")],+ sync_sql: "-- Schema sync SQL for users\n-- Schema sync SQL for orders".to_string(),+ function_diffs: Vec::new(),+ sequence_diffs: Vec::new(),+ rule_diffs: Vec::new(),+ owner_diffs: Vec::new(),+ rollback_sync_sql: Some("-- Rollback SQL".to_string()),+ rollback_completeness: crate::schema_diff::RollbackCompleteness::Complete,+ missing_rollback_objects: Vec::new(),+ rename_candidates: Vec::new(),+ rollback_graph: None,+ compatibility_warnings: Vec::new(),+ permission_diffs: Vec::new(),+ permission_sync_sql: None,+ dependency_graph: None,+ }+ }++ fn sample_data_preparation() -> DataCompareFromTablesPreparation {+ DataCompareFromTablesPreparation {+ result: DataCompareResult {+ added: vec![DataCompareRow {+ key: "1".to_string(),+ key_values: HashMap::from([("id".to_string(), json!(1))]),+ values: HashMap::from([("id".to_string(), json!(1)), ("name".to_string(), json!("Ada"))]),+ }],+ removed: vec![],+ modified: vec![DataCompareModifiedRow {+ key: "2".to_string(),+ key_values: HashMap::from([("id".to_string(), json!(2))]),+ source_values: HashMap::new(),+ target_values: HashMap::new(),+ changes: vec![DataCompareChangedCell {+ column: "name".to_string(),+ source: json!("Bob"),+ target: json!("Bobby"),+ }],+ }],+ },+ sync_statements: vec![+ "INSERT INTO \"public\".\"users\" (\"id\", \"name\") VALUES (1, 'Ada');".to_string(),+ "UPDATE \"public\".\"users\" SET \"name\" = 'Bob' WHERE \"id\" = 2;".to_string(),+ ],+ sync_sql: "INSERT INTO \"public\".\"users\" (\"id\", \"name\") VALUES (1, 'Ada');\n\+ UPDATE \"public\".\"users\" SET \"name\" = 'Bob' WHERE \"id\" = 2;"+ .to_string(),+ pre_sync_statements: vec![],+ source_row_count: 2,+ target_row_count: 2,+ source_truncated: false,+ target_truncated: false,+ degradation_level: Some("full".to_string()),+ sampling_rate: Some(1.0),+ confidence_score: Some(1.0),+ verification_method: Some("full_compare".to_string()),+ source_checksums: None,+ target_checksums: None,+ }+ }++ #[test]+ fn builds_structure_first_correction_plan() {+ let schema = sample_schema_preparation();+ let data = sample_data_preparation();+ let plan = build_joint_correction_plan(+ Some(&schema),+ Some(&data),+ JointCorrectionOptions {+ strategy: CorrectionStrategy::StructureFirst,+ include_checkpoints: true,+ include_rollback: true,+ },+ );++ assert_eq!(plan.strategy, CorrectionStrategy::StructureFirst);+ assert!(plan.schema_diff_count > 0);+ assert!(plan.data_diff_count > 0);++ let first_data_idx = plan.steps.iter().position(|s| {+ matches!(+ s.step_type,+ CorrectionStepType::DataInsert | CorrectionStepType::DataUpdate | CorrectionStepType::DataDelete+ )+ });++ let last_schema_idx = plan.steps.iter().rposition(|s| {+ matches!(+ s.step_type,+ CorrectionStepType::SchemaCreate | CorrectionStepType::SchemaAlter | CorrectionStepType::SchemaDrop+ )+ });++ if let (Some(si), Some(di)) = (last_schema_idx, first_data_idx) {+ assert!(si < di, "Schema steps should come before data steps in StructureFirst strategy");+ }+ }++ #[test]+ fn builds_data_first_correction_plan() {+ let schema = sample_schema_preparation();+ let data = sample_data_preparation();+ let plan = build_joint_correction_plan(+ Some(&schema),+ Some(&data),+ JointCorrectionOptions {+ strategy: CorrectionStrategy::DataFirst,+ include_checkpoints: true,+ include_rollback: true,+ },+ );++ assert_eq!(plan.strategy, CorrectionStrategy::DataFirst);+ assert!(plan+ .steps+ .iter()+ .any(|s| matches!(s.step_type, CorrectionStepType::DataInsert | CorrectionStepType::DataUpdate)));+ assert!(plan+ .steps+ .iter()+ .any(|s| matches!(s.step_type, CorrectionStepType::SchemaCreate | CorrectionStepType::SchemaAlter)));+ }++ #[test]+ fn builds_interleaved_correction_plan() {+ let schema = sample_schema_preparation();+ let data = sample_data_preparation();+ let plan = build_joint_correction_plan(+ Some(&schema),+ Some(&data),+ JointCorrectionOptions {+ strategy: CorrectionStrategy::Interleaved,+ include_checkpoints: true,+ include_rollback: true,+ },+ );++ assert_eq!(plan.strategy, CorrectionStrategy::Interleaved);+ assert!(!plan.steps.is_empty());+ }++ #[test]+ fn handles_missing_schema_diff() {+ let data = sample_data_preparation();+ let plan = build_joint_correction_plan(None, Some(&data), JointCorrectionOptions::default());++ assert_eq!(plan.schema_diff_count, 0);+ assert!(plan.data_diff_count > 0);+ }++ #[test]+ fn handles_missing_data_compare() {+ let schema = sample_schema_preparation();+ let plan = build_joint_correction_plan(Some(&schema), None, JointCorrectionOptions::default());++ assert!(plan.schema_diff_count > 0);+ assert_eq!(plan.data_diff_count, 0);+ }++ #[test]+ fn handles_empty_input() {+ let plan = build_joint_correction_plan(None, None, JointCorrectionOptions::default());++ assert_eq!(plan.steps.len(), 0);+ assert_eq!(plan.schema_diff_count, 0);+ assert_eq!(plan.data_diff_count, 0);+ }++ #[test]+ fn correction_step_serialization() {+ let step = CorrectionStep {+ step_type: CorrectionStepType::SchemaCreate,+ table_name: Some("public.users".to_string()),+ sql: "CREATE TABLE ...".to_string(),+ rollback_sql: Some("DROP TABLE ...".to_string()),+ description: "Create users table".to_string(),+ risk_level: CorrectionRiskLevel::Safe,+ depends_on: vec![0],+ };++ let json = serde_json::to_string(&step).expect("serialization should succeed");+ let deserialized: CorrectionStep = serde_json::from_str(&json).expect("deserialization should succeed");++ assert_eq!(deserialized.step_type, CorrectionStepType::SchemaCreate);+ assert_eq!(deserialized.table_name, Some("public.users".to_string()));+ assert_eq!(deserialized.risk_level, CorrectionRiskLevel::Safe);+ }++ #[test]+ fn joint_correction_plan_serialization() {+ let schema = sample_schema_preparation();+ let data = sample_data_preparation();+ let plan = build_joint_correction_plan(Some(&schema), Some(&data), JointCorrectionOptions::default());++ let json = serde_json::to_string(&plan).expect("serialization should succeed");+ assert!(json.contains("structureFirst") || json.contains("StructureFirst"));+ }+}diff --git a/crates/dbx-core/src/data_compare.rs b/crates/dbx-core/src/data_compare.rsindex 6170ede424..5b627e9dd8 100644--- a/crates/dbx-core/src/data_compare.rs+++ b/crates/dbx-core/src/data_compare.rs@@ -3,6 +3,7 @@ use std::collections::{HashMap, HashSet};use rayon::prelude::*;use serde::{Deserialize, Serialize};use serde_json::Value;+use sha2::{Digest, Sha256};use crate::connection::AppState;use crate::data_grid_sql::{format_grid_sql_literal as format_data_grid_sql_literal, DataGridColumnInfo};@@ -62,6 +63,12 @@ pub struct DataCompareFromTablesOptions {pub key_columns: Vec<String>,#[serde(default, skip_serializing_if = "Option::is_none")]pub fetch_batch_size: Option<usize>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub degradation_threshold: Option<DegradationThreshold>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sampling_strategy: Option<SamplingStrategy>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub enable_checksum: Option<bool>,}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -170,6 +177,112 @@ pub struct DataCompareFromTablesPreparation {pub target_row_count: u64,pub source_truncated: bool,pub target_truncated: bool,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub degradation_level: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sampling_rate: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub confidence_score: Option<f64>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub verification_method: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_checksums: Option<HashMap<String, String>>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub target_checksums: Option<HashMap<String, String>>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub enum DegradationLevel {+ Full,+ Sample,+ SkipWithRisk,+}++impl std::fmt::Display for DegradationLevel {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ match self {+ DegradationLevel::Full => write!(f, "full"),+ DegradationLevel::Sample => write!(f, "sample"),+ DegradationLevel::SkipWithRisk => write!(f, "skip_with_risk"),+ }+ }+}++impl TryFrom<&str> for DegradationLevel {+ type Error = String;+ fn try_from(s: &str) -> Result<Self, Self::Error> {+ match s {+ "full" => Ok(DegradationLevel::Full),+ "sample" => Ok(DegradationLevel::Sample),+ "skip_with_risk" => Ok(DegradationLevel::SkipWithRisk),+ _ => Err(format!("Unknown degradation level: {s}")),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]+#[serde(rename_all = "camelCase")]+pub enum SamplingStrategy {+ Random,+ ExtremeValues,+ Hybrid,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DegradationThreshold {+ pub full_compare_max_rows: u64,+ pub sample_max_rows: u64,+ pub sample_size: usize,+ pub extreme_sample_count: usize,+}++impl Default for DegradationThreshold {+ fn default() -> Self {+ Self {+ full_compare_max_rows: 100_000,+ sample_max_rows: 10_000_000,+ sample_size: 10_000,+ extreme_sample_count: 500,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct VerifyDataOptions {+ pub source_connection_id: String,+ pub source_database: String,+ pub source_schema: String,+ pub source_table: String,+ pub target_connection_id: String,+ pub target_database: String,+ pub target_schema: String,+ pub target_table: String,+ pub columns: Vec<String>,+ pub key_columns: Vec<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub fetch_batch_size: Option<usize>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub degradation_threshold: Option<DegradationThreshold>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub sampling_strategy: Option<SamplingStrategy>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub enable_checksum: Option<bool>,+}++/// Result of a full verification pass including statistical metadata.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct VerifyDataResult {+ pub preparation: DataCompareFromTablesPreparation,+ pub degradation_level: DegradationLevel,+ pub sampling_rate: f64,+ pub confidence_score: f64,+ pub row_count_match: bool,+ pub checksums_match: Option<bool>,+ pub verification_method: String,}pub fn prepare_data_compare(options: DataComparePreparationOptions) -> Result<DataComparePreparation, String> {@@ -238,30 +351,74 @@ pub async fn prepare_data_compare_from_tables(let source_row_count = first_count(&source_count_result.rows)?;let target_row_count = first_count(&target_count_result.rows)?;- let (source_rows, target_rows) = tokio::try_join!(- fetch_compare_rows(- state,- &options.source_connection_id,- &options.source_database,- &options.source_schema,- &options.source_table,- &options.columns,- &options.key_columns,- source_database_type,- fetch_batch_size,- ),- fetch_compare_rows(- state,- &options.target_connection_id,- &options.target_database,- &options.target_schema,- &options.target_table,- &options.columns,- &options.key_columns,- target_database_type,- fetch_batch_size,- )- )?;+ let threshold = options.degradation_threshold.clone().unwrap_or_default();+ let degradation_level = should_degrade(source_row_count, target_row_count, &threshold);+ let sampling_strategy = options.sampling_strategy.clone().unwrap_or(SamplingStrategy::Hybrid);+ let enable_checksum = options.enable_checksum.unwrap_or(true);++ let (source_rows, target_rows, sampling_rate, verification_method) = match °radation_level {+ DegradationLevel::Full => {+ let (src, tgt) = tokio::try_join!(+ fetch_compare_rows(+ state,+ &options.source_connection_id,+ &options.source_database,+ &options.source_schema,+ &options.source_table,+ &options.columns,+ &options.key_columns,+ source_database_type,+ fetch_batch_size,+ ),+ fetch_compare_rows(+ state,+ &options.target_connection_id,+ &options.target_database,+ &options.target_schema,+ &options.target_table,+ &options.columns,+ &options.key_columns,+ target_database_type,+ fetch_batch_size,+ )+ )?;+ (src, tgt, 1.0, "full_compare".to_string())+ }+ DegradationLevel::Sample => {+ let (src, tgt) = tokio::try_join!(+ fetch_sampled_compare_rows(+ state,+ &options.source_connection_id,+ &options.source_database,+ &options.source_schema,+ &options.source_table,+ &options.columns,+ &options.key_columns,+ source_database_type,+ &sampling_strategy,+ threshold.sample_size,+ ),+ fetch_sampled_compare_rows(+ state,+ &options.target_connection_id,+ &options.target_database,+ &options.target_schema,+ &options.target_table,+ &options.columns,+ &options.key_columns,+ target_database_type,+ &sampling_strategy,+ threshold.sample_size,+ )+ )?;+ let max_count = source_row_count.max(target_row_count);+ let sample_rate = if max_count > 0 { threshold.sample_size as f64 / max_count as f64 } else { 1.0 };+ let method = "sampled".to_string();+ (src, tgt, sample_rate.min(1.0), method)+ }+ DegradationLevel::SkipWithRisk => (Vec::new(), Vec::new(), 0.0, "skipped".to_string()),+ };+let target_columns = get_columns_core(state,&options.target_connection_id,@@ -271,6 +428,21 @@ pub async fn prepare_data_compare_from_tables().await?;+ let source_checksums = if enable_checksum && !source_rows.is_empty() {+ Some(compute_column_checksums(&options.columns, &source_rows))+ } else {+ None+ };+ let target_checksums = if enable_checksum && !target_rows.is_empty() {+ Some(compute_column_checksums(&options.columns, &target_rows))+ } else {+ None+ };++ let row_count_match = source_row_count == target_row_count;+ let confidence_score =+ compute_confidence(sampling_rate, °radation_level, row_count_match, source_row_count, target_row_count);+let preparation = prepare_data_compare(DataComparePreparationOptions {table_name: options.target_table,schema: Some(options.target_schema),@@ -291,6 +463,12 @@ pub async fn prepare_data_compare_from_tables(target_row_count,source_truncated: false,target_truncated: false,+ degradation_level: Some(degradation_level.to_string()),+ sampling_rate: Some(sampling_rate),+ confidence_score: Some(confidence_score),+ verification_method: Some(verification_method),+ source_checksums,+ target_checksums,})}@@ -383,6 +561,12 @@ pub async fn prepare_data_compare_missing_target(target_row_count: 0,source_truncated: false,target_truncated: false,+ degradation_level: Some("full".to_string()),+ sampling_rate: Some(1.0),+ confidence_score: Some(1.0),+ verification_method: Some("missing_target_full".to_string()),+ source_checksums: None,+ target_checksums: None,})}@@ -1066,6 +1250,421 @@ fn data_grid_column_info(column: crate::types::ColumnInfo) -> DataGridColumnInfo}}+fn should_degrade(source_row_count: u64, target_row_count: u64, threshold: &DegradationThreshold) -> DegradationLevel {+ let max_count = source_row_count.max(target_row_count);+ if max_count <= threshold.full_compare_max_rows {+ DegradationLevel::Full+ } else if max_count <= threshold.sample_max_rows {+ DegradationLevel::Sample+ } else {+ DegradationLevel::SkipWithRisk+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DegradationEvent {+ pub source_row_count: u64,+ pub target_row_count: u64,+ pub decided_level: String,+ pub sample_rate: f64,+ pub confidence: f64,+ pub auto_decision: String,+ pub timestamp: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DegradationChain {+ pub threshold: DegradationThreshold,+ pub events: Vec<DegradationEvent>,+ pub auto_upgrade_enabled: bool,+ pub auto_downgrade_enabled: bool,+}++impl DegradationChain {+ pub fn new(threshold: DegradationThreshold) -> Self {+ Self { threshold, events: Vec::new(), auto_upgrade_enabled: true, auto_downgrade_enabled: true }+ }++ pub fn decide(+ &mut self,+ source_row_count: u64,+ target_row_count: u64,+ metrics: Option<&crate::risk_metrics::DegradationMetrics>,+ ) -> DegradationLevel {+ let max_count = source_row_count.max(target_row_count);+ let new_level = if max_count <= self.threshold.full_compare_max_rows {+ DegradationLevel::Full+ } else if max_count <= self.threshold.sample_max_rows {+ DegradationLevel::Sample+ } else {+ DegradationLevel::SkipWithRisk+ };++ let (sample_rate, confidence) = match &new_level {+ DegradationLevel::Full => (1.0, 1.0),+ DegradationLevel::Sample => {+ let rate = self.threshold.sample_size as f64 / max_count as f64;+ let conf = 0.95 * rate;+ (rate, conf.clamp(0.5, 0.95))+ }+ DegradationLevel::SkipWithRisk => (0.0, 0.0),+ };++ if self.auto_upgrade_enabled {+ if let Some(last) = self.events.last() {+ let auto_upgrade = matches!(+ (last.decided_level.as_str(), &new_level),+ ("skip_with_risk", DegradationLevel::Sample) | ("sample", DegradationLevel::Full)+ );+ if auto_upgrade {+ if let Some(m) = metrics {+ m.record_auto_upgrade();+ }+ }+ }+ }++ if self.auto_downgrade_enabled {+ if let Some(last) = self.events.last() {+ let auto_downgrade = matches!(+ (last.decided_level.as_str(), &new_level),+ ("full", DegradationLevel::Sample | DegradationLevel::SkipWithRisk)+ | ("sample", DegradationLevel::SkipWithRisk)+ );+ if auto_downgrade {+ if let Some(m) = metrics {+ m.record_auto_downgrade();+ }+ }+ }+ }++ if let Some(m) = metrics {+ m.record_degradation(&new_level.to_string(), sample_rate, confidence);+ }++ let auto_decision = if new_level == DegradationLevel::Full {+ "auto".to_string()+ } else if new_level == DegradationLevel::Sample {+ "auto_degraded".to_string()+ } else {+ "auto_skipped".to_string()+ };++ self.events.push(DegradationEvent {+ source_row_count,+ target_row_count,+ decided_level: new_level.to_string(),+ sample_rate,+ confidence,+ auto_decision,+ timestamp: chrono::Utc::now().to_rfc3339(),+ });++ new_level+ }++ pub fn event_count(&self) -> usize {+ self.events.len()+ }++ pub fn last_event(&self) -> Option<&DegradationEvent> {+ self.events.last()+ }+}++impl Default for DegradationChain {+ fn default() -> Self {+ Self::new(DegradationThreshold::default())+ }+}++fn build_sampling_select_sql(+ database_type: DatabaseType,+ schema: &str,+ table_name: &str,+ columns: &[String],+ key_columns: &[String],+ strategy: &SamplingStrategy,+ sample_size: usize,+) -> String {+ let table = qualified_table_name(Some(database_type), Some(schema), table_name);+ let select_columns = if columns.is_empty() {+ "*".to_string()+ } else {+ columns.iter().map(|column| quote_table_identifier(Some(database_type), column)).collect::<Vec<_>>().join(", ")+ };++ match strategy {+ SamplingStrategy::Random => match database_type {+ DatabaseType::Postgres | DatabaseType::Redshift | DatabaseType::DuckDb | DatabaseType::Databricks => {+ format!("SELECT {select_columns} FROM {table} TABLESAMPLE SYSTEM (1) LIMIT {sample_size}")+ }+ DatabaseType::SqlServer => {+ format!("SELECT TOP ({sample_size}) {select_columns} FROM {table} TABLESAMPLE ({sample_size} ROWS)")+ }+ DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks | DatabaseType::Goldendb => {+ format!("SELECT {select_columns} FROM {table} ORDER BY RAND() LIMIT {sample_size}")+ }+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => {+ format!("SELECT {select_columns} FROM {table} ORDER BY RANDOM() LIMIT {sample_size}")+ }+ DatabaseType::ClickHouse => {+ format!("SELECT {select_columns} FROM {table} ORDER BY rand() LIMIT {sample_size}")+ }+ DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng => {+ format!("SELECT {select_columns} FROM (SELECT {select_columns} FROM {table} ORDER BY DBMS_RANDOM.VALUE) WHERE ROWNUM <= {sample_size}")+ }+ DatabaseType::Iris => {+ format!("SELECT TOP {sample_size} {select_columns} FROM {table} ORDER BY RAND()")+ }+ DatabaseType::Questdb => {+ format!("SELECT {select_columns} FROM {table} ORDER BY RAND() LIMIT {sample_size}")+ }+ DatabaseType::Informix => {+ format!("SELECT FIRST {sample_size} {select_columns} FROM {table} ORDER BY RAND()")+ }+ _ => {+ if key_columns.is_empty() {+ format!("SELECT {select_columns} FROM {table} LIMIT {sample_size}")+ } else {+ let order_by = key_columns+ .iter()+ .map(|column| format!("{} ASC", quote_table_identifier(Some(database_type), column)))+ .collect::<Vec<_>>()+ .join(", ");+ format!("SELECT {select_columns} FROM {table} ORDER BY {order_by} LIMIT {sample_size}")+ }+ }+ },+ SamplingStrategy::ExtremeValues => {+ if key_columns.is_empty() {+ return format!("SELECT {select_columns} FROM {table} LIMIT {sample_size}");+ }+ let order_keys = key_columns+ .iter()+ .map(|column| format!("{} ASC", quote_table_identifier(Some(database_type), column)))+ .collect::<Vec<_>>();+ let asc_order = order_keys.join(", ");+ let desc_order = key_columns+ .iter()+ .map(|column| format!("{} DESC", quote_table_identifier(Some(database_type), column)))+ .collect::<Vec<_>>()+ .join(", ");++ let head_count = sample_size / 2;+ let tail_count = sample_size - head_count;++ format!(+ "SELECT {select_columns} FROM ( \+ (SELECT {select_columns} FROM {table} ORDER BY {asc_order} LIMIT {head_count}) \+ UNION ALL \+ (SELECT {select_columns} FROM {table} ORDER BY {desc_order} LIMIT {tail_count}) \+ ) AS _extreme_sample"+ )+ }+ SamplingStrategy::Hybrid => {+ if key_columns.is_empty() {+ return format!("SELECT {select_columns} FROM {table} LIMIT {sample_size}");+ }+ let order_keys = key_columns+ .iter()+ .map(|column| format!("{} ASC", quote_table_identifier(Some(database_type), column)))+ .collect::<Vec<_>>();+ let asc_order = order_keys.join(", ");+ let desc_order = key_columns+ .iter()+ .map(|column| format!("{} DESC", quote_table_identifier(Some(database_type), column)))+ .collect::<Vec<_>>()+ .join(", ");++ let random_count = sample_size / 2;+ let head_count = (sample_size - random_count) / 2;+ let tail_count = sample_size - random_count - head_count;++ let random_part = match database_type {+ DatabaseType::Postgres | DatabaseType::Redshift | DatabaseType::DuckDb | DatabaseType::Databricks => {+ format!("(SELECT {select_columns} FROM {table} TABLESAMPLE SYSTEM (1) LIMIT {random_count})")+ }+ DatabaseType::SqlServer => {+ format!(+ "(SELECT TOP ({random_count}) {select_columns} FROM {table} TABLESAMPLE ({random_count} ROWS))"+ )+ }+ DatabaseType::Mysql | DatabaseType::Doris | DatabaseType::StarRocks | DatabaseType::Goldendb => {+ format!("(SELECT {select_columns} FROM {table} ORDER BY RAND() LIMIT {random_count})")+ }+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => {+ format!("(SELECT {select_columns} FROM {table} ORDER BY RANDOM() LIMIT {random_count})")+ }+ DatabaseType::ClickHouse => {+ format!("(SELECT {select_columns} FROM {table} ORDER BY rand() LIMIT {random_count})")+ }+ DatabaseType::Oracle | DatabaseType::OceanbaseOracle | DatabaseType::Dameng => {+ format!("(SELECT {select_columns} FROM (SELECT {select_columns} FROM {table} ORDER BY DBMS_RANDOM.VALUE) WHERE ROWNUM <= {random_count})")+ }+ DatabaseType::Iris => {+ format!("(SELECT TOP {random_count} {select_columns} FROM {table} ORDER BY RAND())")+ }+ DatabaseType::Questdb => {+ format!("(SELECT {select_columns} FROM {table} ORDER BY RAND() LIMIT {random_count})")+ }+ DatabaseType::Informix => {+ format!("(SELECT FIRST {random_count} {select_columns} FROM {table} ORDER BY RAND())")+ }+ _ => {+ format!("(SELECT {select_columns} FROM {table} LIMIT {random_count})")+ }+ };++ format!(+ "SELECT {select_columns} FROM ( \+ {random_part} \+ UNION ALL \+ (SELECT {select_columns} FROM {table} ORDER BY {asc_order} LIMIT {head_count}) \+ UNION ALL \+ (SELECT {select_columns} FROM {table} ORDER BY {desc_order} LIMIT {tail_count}) \+ ) AS _hybrid_sample"+ )+ }+ }+}++#[allow(clippy::too_many_arguments)]+async fn fetch_sampled_compare_rows(+ state: &AppState,+ connection_id: &str,+ database: &str,+ schema: &str,+ table_name: &str,+ columns: &[String],+ key_columns: &[String],+ database_type: DatabaseType,+ strategy: &SamplingStrategy,+ sample_size: usize,+) -> Result<Vec<Vec<Value>>, String> {+ if sample_size == 0 {+ return Ok(Vec::new());+ }++ let sql = build_sampling_select_sql(database_type, schema, table_name, columns, key_columns, strategy, sample_size);++ let result = execute_sql_statement_with_options(+ state,+ connection_id,+ database,+ &sql,+ Some(schema),+ None,+ QueryExecutionOptions { max_rows: Some(sample_size), ..Default::default() },+ )+ .await?;++ Ok(result.rows)+}++fn compute_column_checksums(columns: &[String], rows: &[Vec<Value>]) -> HashMap<String, String> {+ let mut column_hashers: HashMap<String, Sha256> = columns.iter().map(|col| (col.clone(), Sha256::new())).collect();++ let column_indexes = column_index_map(columns);++ for row in rows {+ for (column_name, index) in &column_indexes {+ if let Some(hasher) = column_hashers.get_mut(*column_name) {+ let value_str = json_stringify(row_value(row, *index));+ hasher.update(value_str.as_bytes());+ hasher.update(b"\n");+ }+ }+ }++ column_hashers+ .into_iter()+ .map(|(name, hasher)| {+ let hash = format!("{:x}", hasher.finalize());+ (name, hash)+ })+ .collect()+}++fn compute_confidence(+ sampling_rate: f64,+ degradation_level: &DegradationLevel,+ row_count_match: bool,+ source_row_count: u64,+ target_row_count: u64,+) -> f64 {+ match degradation_level {+ DegradationLevel::Full => {+ if row_count_match {+ 1.0+ } else {+ 0.99+ }+ }+ DegradationLevel::Sample => {+ let count_ratio =+ source_row_count.min(target_row_count) as f64 / source_row_count.max(target_row_count).max(1) as f64;+ let base = if row_count_match { 0.95 } else { 0.85 };+ let adjusted = base * sampling_rate * count_ratio.sqrt();+ adjusted.clamp(0.5, 0.95)+ }+ DegradationLevel::SkipWithRisk => 0.0,+ }+}++pub async fn verify_data(state: &AppState, options: VerifyDataOptions) -> Result<VerifyDataResult, String> {+ let degradation_threshold = options.degradation_threshold.unwrap_or_default();+ let sampling_strategy = options.sampling_strategy.unwrap_or(SamplingStrategy::Hybrid);+ let enable_checksum = options.enable_checksum.unwrap_or(true);++ let from_tables_options = DataCompareFromTablesOptions {+ source_connection_id: options.source_connection_id,+ source_database: options.source_database,+ source_schema: options.source_schema,+ source_table: options.source_table,+ target_connection_id: options.target_connection_id,+ target_database: options.target_database,+ target_schema: options.target_schema,+ target_table: options.target_table,+ columns: options.columns,+ key_columns: options.key_columns,+ fetch_batch_size: options.fetch_batch_size,+ degradation_threshold: Some(degradation_threshold),+ sampling_strategy: Some(sampling_strategy),+ enable_checksum: Some(enable_checksum),+ };++ let preparation = prepare_data_compare_from_tables(state, from_tables_options).await?;++ let degradation_level = preparation+ .degradation_level+ .as_deref()+ .and_then(|s| DegradationLevel::try_from(s).ok())+ .unwrap_or(DegradationLevel::SkipWithRisk);+ let sampling_rate = preparation.sampling_rate.unwrap_or(1.0);+ let confidence_score = preparation.confidence_score.unwrap_or(0.0);+ let row_count_match = preparation.source_row_count == preparation.target_row_count;++ let checksums_match = match (&preparation.source_checksums, &preparation.target_checksums) {+ (Some(src), Some(tgt)) => Some(src == tgt),+ _ => None,+ };+ let verification_method = preparation.verification_method.clone().unwrap_or_else(|| "unknown".to_string());++ Ok(VerifyDataResult {+ preparation,+ degradation_level,+ sampling_rate,+ confidence_score,+ row_count_match,+ checksums_match,+ verification_method,+ })+}+#[cfg(test)]mod tests {use super::*;@@ -1792,4 +2391,80 @@ mod tests {"SELECT \"ID\", \"NAME\" FROM \"APP\".\"EVENTS\" ORDER BY \"ID\" ASC FETCH FIRST 25 ROWS ONLY");}++ #[test]+ fn degradation_chain_full_for_small_table() {+ let threshold = DegradationThreshold::default();+ let mut chain = DegradationChain::new(threshold);+ let level = chain.decide(1000, 1000, None);+ assert_eq!(level, DegradationLevel::Full);+ assert_eq!(chain.event_count(), 1);+ let last = chain.last_event().unwrap();+ assert_eq!(last.decided_level, "full");+ assert!((last.sample_rate - 1.0).abs() < f64::EPSILON);+ assert!((last.confidence - 1.0).abs() < f64::EPSILON);+ }++ #[test]+ fn degradation_chain_sample_for_large_table() {+ let threshold = DegradationThreshold::default();+ let mut chain = DegradationChain::new(threshold);+ let level = chain.decide(500_000, 500_000, None);+ assert_eq!(level, DegradationLevel::Sample);+ let last = chain.last_event().unwrap();+ assert_eq!(last.decided_level, "sample");+ assert!(last.sample_rate < 1.0);+ assert!(last.confidence >= 0.5);+ }++ #[test]+ fn degradation_chain_skip_for_huge_table() {+ let threshold = DegradationThreshold::default();+ let mut chain = DegradationChain::new(threshold);+ let level = chain.decide(20_000_000, 20_000_000, None);+ assert_eq!(level, DegradationLevel::SkipWithRisk);+ let last = chain.last_event().unwrap();+ assert_eq!(last.decided_level, "skip_with_risk");+ assert!((last.sample_rate - 0.0).abs() < f64::EPSILON);+ assert!((last.confidence - 0.0).abs() < f64::EPSILON);+ }++ #[test]+ fn degradation_chain_records_multiple_events() {+ let threshold = DegradationThreshold::default();+ let mut chain = DegradationChain::new(threshold);+ chain.decide(1000, 1000, None);+ chain.decide(500_000, 500_000, None);+ chain.decide(20_000_000, 20_000_000, None);+ assert_eq!(chain.event_count(), 3);+ }++ #[test]+ fn degradation_chain_with_metrics_integration() {+ let threshold = DegradationThreshold::default();+ let mut chain = DegradationChain::new(threshold);+ let metrics = crate::risk_metrics::DegradationMetrics::new();++ chain.decide(1000, 1000, Some(&metrics));+ chain.decide(500_000, 500_000, Some(&metrics));+ chain.decide(20_000_000, 20_000_000, Some(&metrics));++ let snapshot = metrics.snapshot();+ let total = snapshot.iter().find(|e| e.name == "dbx_degradation_total").unwrap();+ assert_eq!(total.value, crate::risk_metrics::MetricValue::Counter(3));+ }++ #[test]+ fn degradation_chain_auto_chain_detection() {+ let threshold = DegradationThreshold::default();+ let mut chain = DegradationChain::new(threshold);+ let metrics = crate::risk_metrics::DegradationMetrics::new();++ chain.decide(20_000_000, 20_000_000, Some(&metrics));+ chain.decide(500_000, 500_000, Some(&metrics));++ let snapshot = metrics.snapshot();+ let up = snapshot.iter().find(|e| e.name == "dbx_auto_upgrade_total").unwrap();+ assert_eq!(up.value, crate::risk_metrics::MetricValue::Counter(1));+ }}diff --git a/crates/dbx-core/src/db/agent_driver.rs b/crates/dbx-core/src/db/agent_driver.rsindex b17f141645..13a6e56665 100644--- a/crates/dbx-core/src/db/agent_driver.rs+++ b/crates/dbx-core/src/db/agent_driver.rs@@ -2255,6 +2255,8 @@ mod tests {let stderr_tail = Arc::new(Mutex::new(StderrTail::default()));start_stderr_collector(child.stderr.take().expect("stderr should be piped"), Arc::clone(&stderr_tail));+ std::thread::sleep(Duration::from_millis(200));+let message = format_agent_startup_error("Failed to read startup line from agent: end of stream",&mut child,diff --git a/crates/dbx-core/src/db/sqlite.rs b/crates/dbx-core/src/db/sqlite.rsindex 02f1c00341..16b5e277a5 100644--- a/crates/dbx-core/src/db/sqlite.rs+++ b/crates/dbx-core/src/db/sqlite.rs@@ -2133,10 +2133,13 @@ pub async fn list_indexes(pool: &SqliteHandle, schema: &str, table: &str) -> Res)).map_err(|e| e.to_string())?;let columns = col_stmt- .query_map([], |row| row.get::<_, String>("name"))+ .query_map([], |row| row.get::<_, Option<String>>("name")).map_err(|e| e.to_string())?.collect::<Result<Vec<_>, _>>()- .map_err(|e| e.to_string())?;+ .map_err(|e| e.to_string())?+ .into_iter()+ .flatten()+ .collect::<Vec<_>>();indexes.push(IndexInfo {name,diff --git a/crates/dbx-core/src/db/ssh_tunnel.rs b/crates/dbx-core/src/db/ssh_tunnel.rsindex 0ccb8675ad..643c0c2e73 100644--- a/crates/dbx-core/src/db/ssh_tunnel.rs+++ b/crates/dbx-core/src/db/ssh_tunnel.rs@@ -367,11 +367,11 @@ async fn connect_and_authenticate(async fn try_authenticate_with_agent(session: &mut Handle<SshClient>,ssh_user: &str,- _ssh_agent_sock_path: &str,+ #[cfg_attr(not(unix), allow(unused_variables))] ssh_agent_sock_path: &str,connect_timeout: &Duration,) -> Result<(), String> {#[cfg(unix)]- let mut agent = if _ssh_agent_sock_path.is_empty() {+ let mut agent = if ssh_agent_sock_path.is_empty() {match AgentClient::connect_env().await {Ok(a) => a,Err(e) => {@@ -379,12 +379,12 @@ async fn try_authenticate_with_agent(}}} else {- match AgentClient::connect_uds(_ssh_agent_sock_path).await {+ match AgentClient::connect_uds(ssh_agent_sock_path).await {Ok(a) => a,Err(e) => {return Err(format!("No SSH password or key provided, and ssh-agent at '{}' is unavailable: {e}",- _ssh_agent_sock_path+ ssh_agent_sock_path));}}diff --git a/crates/dbx-core/src/dml_binding.rs b/crates/dbx-core/src/dml_binding.rsnew file mode 100644index 0000000000..ce46d56d1e--- /dev/null+++ b/crates/dbx-core/src/dml_binding.rs@@ -0,0 +1,409 @@+use std::collections::HashMap;+use std::path::{Path, PathBuf};+use std::sync::RwLock;++use serde::{Deserialize, Serialize};++use crate::sql_dialect::descriptor::DialectKind;+use crate::sql_dialect::dialect_yaml::DialectYaml;+use crate::sql_dialect::inference::{ColumnType, DefaultTypeInferenceEngine, TypeInferenceEngine};++// ============================================================================+// DML Clean Rules — lossy type mapping → pre-transform DML template+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DmlCleanRulesFile {+ pub rules: Vec<DmlCleanRule>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DmlCleanRule {+ pub name: String,+ pub source_type: String,+ pub target_type: String,+ pub max_fidelity: f64,+ #[serde(default)]+ pub pre_transform_sql: Option<String>,+ #[serde(default)]+ pub description: Option<String>,+}++impl DmlCleanRule {+ pub fn transform_sql(&self, table: &str, column: &str) -> Option<String> {+ self.pre_transform_sql.as_ref().map(|tmpl| tmpl.replace("{table}", table).replace("{column}", column))+ }++ /// Check if this rule matches the source → target type pair.+ pub fn matches(&self, source_type: &str, target_type: &str) -> bool {+ let src_norm = normalize_type(source_type);+ let tgt_norm = normalize_type(target_type);+ let rule_src = normalize_type(&self.source_type);+ let rule_tgt = normalize_type(&self.target_type);+ src_norm == rule_src && tgt_norm == rule_tgt+ }++ fn applies(&self, source_type: &str, target_type: &str, fidelity: f64) -> bool {+ self.matches(source_type, target_type) && fidelity < self.max_fidelity+ }+}++fn normalize_type(t: &str) -> String {+ t.trim().to_ascii_uppercase().split('(').next().unwrap_or("").to_string()+}++// ============================================================================+// DmlCleanRuleRegistry — global singleton, loads from YAML+// ============================================================================++pub struct DmlCleanRuleRegistry {+ pub(crate) rules: Vec<DmlCleanRule>,+}++impl DmlCleanRuleRegistry {+ pub fn new() -> Self {+ Self { rules: Vec::new() }+ }++ pub fn global() -> &'static RwLock<Self> {+ use std::sync::OnceLock;+ static INSTANCE: OnceLock<RwLock<DmlCleanRuleRegistry>> = OnceLock::new();+ INSTANCE.get_or_init(|| RwLock::new(Self::new()))+ }++ pub fn load(path: &Path) -> Result<Vec<DmlCleanRule>, String> {+ let content = std::fs::read_to_string(path).map_err(|e| format!("Cannot read {}: {e}", path.display()))?;+ let parsed: DmlCleanRulesFile =+ serde_yaml::from_str(&content).map_err(|e| format!("YAML parse error in {}: {e}", path.display()))?;+ Ok(parsed.rules)+ }++ pub fn load_default() -> Result<(), String> {+ let paths = [+ "plugins/mappings/rules/dml_clean_rules.yaml",+ "../plugins/mappings/rules/dml_clean_rules.yaml",+ "../../plugins/mappings/rules/dml_clean_rules.yaml",+ ];+ for path in &paths {+ let p = Path::new(path);+ if p.exists() {+ let rules = Self::load(p)?;+ if let Ok(mut registry) = Self::global().write() {+ registry.rules = rules;+ }+ return Ok(());+ }+ }+ Ok(())+ }++ pub fn find_rule(&self, source_type: &str, target_type: &str) -> Option<&DmlCleanRule> {+ self.rules.iter().find(|r| r.matches(source_type, target_type))+ }++ pub fn all_rules(&self) -> &[DmlCleanRule] {+ &self.rules+ }+}++impl Default for DmlCleanRuleRegistry {+ fn default() -> Self {+ Self::new()+ }+}++// ============================================================================+// BindingEngine — auto-binds DML clean SQL to lossy type mappings+// ============================================================================++pub struct BindingEngine;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BindingResult {+ pub source_type: String,+ pub target_type: String,+ pub fidelity: f64,+ pub pre_transform_sql: Option<String>,+ pub rule_name: Option<String>,+}++impl BindingEngine {+ /// Compute fidelity for a single type mapping and auto-bind DML if lossy.+ pub fn bind(source_type: &str, target_type: &str, table: &str, column: &str, threshold: f64) -> BindingResult {+ let engine = DefaultTypeInferenceEngine;+ let src_parsed = ColumnType::parse(source_type);+ let tgt_parsed = ColumnType::parse(target_type);+ let fidelity = engine.type_compatibility_score(&src_parsed, &tgt_parsed);++ if let Ok(registry) = DmlCleanRuleRegistry::global().read() {+ if let Some(rule) = registry.find_rule(source_type, target_type) {+ // A pair-specific rule owns its fidelity boundary; the caller+ // threshold remains the fallback for mappings without a rule.+ if rule.applies(source_type, target_type, fidelity) {+ return BindingResult {+ source_type: source_type.to_string(),+ target_type: target_type.to_string(),+ fidelity,+ pre_transform_sql: rule.transform_sql(table, column),+ rule_name: Some(rule.name.clone()),+ };+ }+ }+ }++ if fidelity >= threshold {+ return BindingResult {+ source_type: source_type.to_string(),+ target_type: target_type.to_string(),+ fidelity,+ pre_transform_sql: None,+ rule_name: None,+ };+ }++ BindingResult {+ source_type: source_type.to_string(),+ target_type: target_type.to_string(),+ fidelity,+ pre_transform_sql: None,+ rule_name: None,+ }+ }++ /// Bind for a full set of column mappings.+ pub fn bind_columns(+ source_types: &[(String, String)], // (col_name, type)+ target_types: &[(String, String)],+ table: &str,+ threshold: f64,+ ) -> Vec<BindingResult> {+ let source_map: HashMap<&str, &str> = source_types.iter().map(|(n, t)| (n.as_str(), t.as_str())).collect();++ target_types+ .iter()+ .map(|(col_name, target_type)| {+ let source_type = source_map.get(col_name.as_str()).copied().unwrap_or(target_type);+ Self::bind(source_type, target_type, table, col_name, threshold)+ })+ .collect()+ }+}++// ============================================================================+// MappingCache — cache derivation results to plugins/mappings/base/+// ============================================================================++const MAPPING_BASE_DIR: &str = "plugins/mappings/base";+const MAPPING_CUSTOM_DIR: &str = "plugins/mappings/custom";++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MappingCacheFile {+ pub status: String, // "UNVERIFIED" | "VERIFIED" | "REJECTED"+ pub generated_at: String,+ pub derived_from: MappingDerivationInfo,+ pub transformations: Vec<CachedTransformation>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MappingDerivationInfo {+ pub source_dialect: String,+ pub target_dialect: String,+ pub source_type_count: usize,+ pub target_type_count: usize,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct CachedTransformation {+ pub source_type: String,+ pub target_type: String,+ pub fidelity: f64,+ pub pre_transform_sql: Option<String>,+ pub rule_name: Option<String>,+}++impl MappingCacheFile {+ pub fn cache_path(source: DialectKind, target: DialectKind) -> PathBuf {+ let dir = Path::new(MAPPING_BASE_DIR);+ let name = format!("{}_to_{}.base.yaml", source.label(), target.label());+ dir.join(name)+ }++ pub fn custom_path(source: DialectKind, target: DialectKind, env: &str) -> PathBuf {+ let dir = Path::new(MAPPING_CUSTOM_DIR);+ let name = format!("{}_to_{}.{}.yaml", source.label(), target.label(), env);+ dir.join(name)+ }++ /// Load from cache if exists. Checks custom override first, then base cache.+ pub fn load(source: DialectKind, target: DialectKind, env: &str) -> Option<Self> {+ let custom = Self::custom_path(source, target, env);+ if custom.exists() {+ let content = std::fs::read_to_string(&custom).ok()?;+ return serde_yaml::from_str(&content).ok();+ }++ let base = Self::cache_path(source, target);+ if base.exists() {+ let content = std::fs::read_to_string(&base).ok()?;+ return serde_yaml::from_str(&content).ok();+ }++ None+ }++ /// Save derivation result to base cache (UNVERIFIED).+ pub fn save(source: DialectKind, target: DialectKind, bindings: &[BindingResult]) -> Result<(), String> {+ let dir = Path::new(MAPPING_BASE_DIR);+ std::fs::create_dir_all(dir).map_err(|e| format!("Cannot create mappings dir: {e}"))?;++ let source_yaml = DialectYaml::from_descriptor(source);+ let target_yaml = DialectYaml::from_descriptor(target);++ let cache = MappingCacheFile {+ status: "UNVERIFIED".to_string(),+ generated_at: chrono::Utc::now().to_rfc3339(),+ derived_from: MappingDerivationInfo {+ source_dialect: source.label().to_string(),+ target_dialect: target.label().to_string(),+ source_type_count: source_yaml.types.len(),+ target_type_count: target_yaml.types.len(),+ },+ transformations: bindings+ .iter()+ .map(|b| CachedTransformation {+ source_type: b.source_type.clone(),+ target_type: b.target_type.clone(),+ fidelity: b.fidelity,+ pre_transform_sql: b.pre_transform_sql.clone(),+ rule_name: b.rule_name.clone(),+ })+ .collect(),+ };++ let path = Self::cache_path(source, target);+ let yaml_str = serde_yaml::to_string(&cache).map_err(|e| format!("YAML serialize: {e}"))?;+ std::fs::write(&path, &yaml_str).map_err(|e| format!("Write cache {}: {e}", path.display()))?;+ Ok(())+ }+}++// ============================================================================+// Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rule_matches_exact() {+ let rule = DmlCleanRule {+ name: "test".to_string(),+ source_type: "BIGINT".to_string(),+ target_type: "INT".to_string(),+ max_fidelity: 0.8,+ pre_transform_sql: Some("UPDATE {table} SET {column} = NULL".to_string()),+ description: None,+ };+ assert!(rule.matches("BIGINT", "INT"));+ assert!(!rule.matches("INT", "BIGINT"));+ }++ #[test]+ fn rule_matches_normalized() {+ let rule = DmlCleanRule {+ name: "test".to_string(),+ source_type: "BIGINT".to_string(),+ target_type: "INT".to_string(),+ max_fidelity: 0.8,+ pre_transform_sql: None,+ description: None,+ };+ assert!(rule.matches("BIGINT(20)", "INT"));+ assert!(rule.matches("bigint", "int"));+ }++ #[test]+ fn rule_transform_sql() {+ let rule = DmlCleanRule {+ name: "test".to_string(),+ source_type: "BIGINT".to_string(),+ target_type: "INT".to_string(),+ max_fidelity: 0.8,+ pre_transform_sql: Some("UPDATE {table} SET {column} = NULL WHERE {column} > 2147483647".to_string()),+ description: None,+ };+ let sql = rule.transform_sql("users", "age").unwrap();+ assert_eq!(sql, "UPDATE users SET age = NULL WHERE age > 2147483647");+ }++ #[test]+ fn binding_engine_high_fidelity_no_dml() {+ let result = BindingEngine::bind("INT", "INTEGER", "t", "c", 0.7);+ assert!(result.pre_transform_sql.is_none());+ assert!((result.fidelity - 0.9).abs() < 0.01);+ }++ #[test]+ fn binding_engine_low_fidelity_with_dml() {+ let _registry = DmlCleanRuleRegistry::new();+ if let Ok(mut reg) = DmlCleanRuleRegistry::global().write() {+ reg.rules = vec![DmlCleanRule {+ name: "bigint_to_int".to_string(),+ source_type: "BIGINT".to_string(),+ target_type: "INT".to_string(),+ max_fidelity: 0.9,+ pre_transform_sql: Some("UPDATE {table} SET {column} = NULL WHERE {column} > 2147483647".to_string()),+ description: None,+ }];+ }++ let result = BindingEngine::bind("BIGINT", "INT", "users", "id", 0.4);+ assert!(result.pre_transform_sql.is_some());+ assert!(result.pre_transform_sql.unwrap().contains("2147483647"));+ }++ #[test]+ fn rule_max_fidelity_boundary_is_exclusive() {+ let rule = DmlCleanRule {+ name: "boundary".to_string(),+ source_type: "BIGINT".to_string(),+ target_type: "INT".to_string(),+ max_fidelity: 0.5,+ pre_transform_sql: Some("SELECT 1".to_string()),+ description: None,+ };++ assert!(rule.applies("BIGINT", "INT", 0.49));+ assert!(!rule.applies("BIGINT", "INT", 0.5));+ }++ #[test]+ fn default_rules_honor_configured_max_fidelity() {+ let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("../../plugins/mappings/rules/dml_clean_rules.yaml");+ let rules = DmlCleanRuleRegistry::load(&path).unwrap();+ let rule = rules.iter().find(|rule| rule.matches("BIGINT", "INT")).unwrap();++ assert!(rule.applies("BIGINT", "INT", rule.max_fidelity - f64::EPSILON));+ assert!(!rule.applies("BIGINT", "INT", rule.max_fidelity));+ }++ #[test]+ fn binding_engine_no_rule_found() {+ let result = BindingEngine::bind("GEOGRAPHY", "INT", "t", "c", 0.5);+ assert!(result.pre_transform_sql.is_none());+ assert!((result.fidelity - 0.3).abs() < 0.01);+ }++ #[test]+ fn mapping_cache_path() {+ let path = MappingCacheFile::cache_path(DialectKind::Mysql, DialectKind::Postgres);+ assert!(path.to_string_lossy().contains("mysql_to_postgres"));+ let custom = MappingCacheFile::custom_path(DialectKind::Mysql, DialectKind::Postgres, "prod");+ assert!(custom.to_string_lossy().contains("prod"));+ }+}diff --git a/crates/dbx-core/src/lib.rs b/crates/dbx-core/src/lib.rsindex 9eeb866c82..f49b441a20 100644--- a/crates/dbx-core/src/lib.rs+++ b/crates/dbx-core/src/lib.rs@@ -17,8 +17,10 @@ mod ai_model_filter;pub mod ai_pi_agent_cli;pub mod changelog;pub mod cloud_sync;+pub mod config;pub mod connection;pub mod connection_secrets;+pub mod correction;pub mod csv_export;pub mod data_compare;pub mod data_grid_extractors;@@ -28,6 +30,7 @@ pub mod database_export;pub mod database_search_sql;pub mod db;pub mod db_admin_sql;+pub mod dml_binding;pub mod document_ops;pub mod driver_runtime;pub mod external;@@ -53,19 +56,23 @@ pub mod query_execution_sql;pub mod query_result_export;pub mod query_result_sql;pub mod redis_ops;+pub mod risk_metrics;pub mod saved_sql;pub mod schema;pub mod schema_diff;+pub mod script_generator;pub mod sql;pub mod sql_analysis;pub mod sql_diagnostics;pub mod sql_dialect;pub mod sql_editability;pub mod sql_file_import;+pub mod sql_parser;pub mod sql_risk;pub mod sqlite_backup;pub(crate) mod sqlserver_temporal;pub mod ssh_config;+pub mod state_persistence;pub mod storage;pub mod table_export;pub mod table_import;@@ -75,6 +82,7 @@ pub mod temporal_format;pub mod text_export;pub mod token_usage;pub mod transfer;+pub mod two_phase_commit;pub mod types;pub mod update;pub mod xlsx_export;diff --git a/crates/dbx-core/src/osc_probe.rs b/crates/dbx-core/src/osc_probe.rsnew file mode 100644index 0000000000..3b20bc00aa--- /dev/null+++ b/crates/dbx-core/src/osc_probe.rs@@ -0,0 +1,427 @@+use serde::{Deserialize, Serialize};+use std::sync::Arc;++use crate::state_persistence::StateMachine;++// ============================================================================+// 15.1 & 15.2: External OSC Tool Status+// ============================================================================++/// Status of an external online schema change tool execution.+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum OscExecutionStatus {+ Preparing,+ Copying { progress_pct: f64, rows_copied: u64, rows_total: u64 },+ CutOver,+ Postponed,+ Completed,+ Failed(String),+}++/// Type of OSC tool+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum OscToolKind {+ GhOst,+ PtOsc,+}++impl OscToolKind {+ pub fn name(&self) -> &'static str {+ match self {+ Self::GhOst => "gh-ost",+ Self::PtOsc => "pt-osc",+ }+ }+}++// ============================================================================+// 15.1: gh-ost Probe+// ============================================================================++pub struct GhOstProbe {+ progress_history: Vec<(String, f64)>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct GhOstProgress {+ pub status: OscExecutionStatus,+ pub ghost_table_exists: bool,+ pub changelog_table_exists: bool,+ pub rows_copied: u64,+ pub rows_total: u64,+ pub progress_pct: f64,+}++impl GhOstProbe {+ pub fn new() -> Self {+ Self { progress_history: Vec::new() }+ }++ pub fn probe(&mut self, _database: &str, _table: &str, _has_connection: bool) -> GhOstProgress {+ let ghost_table = format!("{_table}_gho");+ let changelog_table = format!("{_table}_ghc");+ if !_has_connection {+ return GhOstProgress {+ status: OscExecutionStatus::Copying { progress_pct: 0.0, rows_copied: 0, rows_total: 0 },+ ghost_table_exists: false,+ changelog_table_exists: false,+ rows_copied: 0,+ rows_total: 0,+ progress_pct: 0.0,+ };+ }+ GhOstProgress {+ status: OscExecutionStatus::Copying { progress_pct: 0.0, rows_copied: 0, rows_total: 0 },+ ghost_table_exists: false,+ changelog_table_exists: false,+ rows_copied: 0,+ rows_total: 0,+ progress_pct: 0.0,+ }+ }++ /// Parse gh-ost log line: "Copying rows: 12345/67890 (18.2%)"+ pub fn parse_log_line(line: &str) -> Option<GhOstProgress> {+ let upper = line.to_uppercase();+ if !upper.contains("COPYING ROWS") {+ return None;+ }+ let re = regex::Regex::new(r"(\d+)\s*/\s*(\d+)\s*\((\d+\.?\d*)%\)").ok()?;+ if let Some(caps) = re.captures(line) {+ let rows_copied: u64 = caps.get(1)?.as_str().parse().ok()?;+ let rows_total: u64 = caps.get(2)?.as_str().parse().ok()?;+ let progress_pct: f64 = caps.get(3)?.as_str().parse().ok()?;+ let status = if progress_pct >= 99.0 {+ OscExecutionStatus::CutOver+ } else {+ OscExecutionStatus::Copying { progress_pct, rows_copied, rows_total }+ };+ return Some(GhOstProgress {+ status,+ ghost_table_exists: true,+ changelog_table_exists: true,+ rows_copied,+ rows_total,+ progress_pct,+ });+ }+ None+ }++ pub fn record_sample(&mut self, progress_pct: f64, label: &str) {+ self.progress_history.push((label.to_string(), progress_pct));+ if self.progress_history.len() > 1000 {+ self.progress_history.remove(0);+ }+ }++ pub fn estimated_remaining_seconds(&self, current_pct: f64) -> Option<f64> {+ if self.progress_history.len() < 2 || current_pct <= 0.0 {+ return None;+ }+ let first = self.progress_history.first()?;+ let total_pct = current_pct - first.1;+ if total_pct <= 0.0 {+ return None;+ }+ let rate = total_pct / 1.0;+ if rate <= 0.0 {+ return None;+ }+ Some((100.0 - current_pct) / rate)+ }+}++impl Default for GhOstProbe {+ fn default() -> Self {+ Self::new()+ }+}++// ============================================================================+// 15.2: pt-osc Probe+// ============================================================================++pub struct PtOscProbe;++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PtOscProgress {+ pub status: OscExecutionStatus,+ pub new_table_exists: bool,+ pub old_table_exists: bool,+ pub triggers_active: u32,+ pub rows_copied: u64,+ pub rows_total: u64,+ pub progress_pct: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PtOscNames {+ pub new_table: String,+ pub old_table: String,+ pub del_trigger: String,+ pub ins_trigger: String,+ pub upd_trigger: String,+}++impl PtOscProbe {+ pub fn new() -> Self {+ Self+ }++ pub fn object_names(table: &str) -> PtOscNames {+ PtOscNames {+ new_table: format!("_{table}_new"),+ old_table: format!("_{table}_old"),+ del_trigger: format!("pt_osc_{table}_del"),+ ins_trigger: format!("pt_osc_{table}_ins"),+ upd_trigger: format!("pt_osc_{table}_upd"),+ }+ }++ pub fn parse_progress_line(line: &str) -> Option<f64> {+ let re = regex::Regex::new(r"(\d+)%\s").ok()?;+ if let Some(caps) = re.captures(line) {+ return caps.get(1)?.as_str().parse().ok();+ }+ None+ }+}++impl Default for PtOscProbe {+ fn default() -> Self {+ Self::new()+ }+}++// ============================================================================+// 15.3: OscStateBridge — map external status to StateMachine+// ============================================================================++pub struct OscStateBridge {+ state_machine: Arc<StateMachine>,+}++impl OscStateBridge {+ pub fn new(state_machine: Arc<StateMachine>) -> Self {+ Self { state_machine }+ }++ pub async fn bridge(&self, state_key: &str, external_status: &OscExecutionStatus) -> Result<String, String> {+ match external_status {+ OscExecutionStatus::Preparing | OscExecutionStatus::Copying { .. } | OscExecutionStatus::Postponed => {+ Ok("osc_syncing")+ }+ OscExecutionStatus::CutOver | OscExecutionStatus::Completed => {+ let new_state = crate::state_persistence::StateTransition::Completed;+ self.state_machine.transition(state_key, new_state).await?;+ Ok("completed")+ }+ OscExecutionStatus::Failed(_) => {+ let new_state = crate::state_persistence::StateTransition::Failed;+ self.state_machine.transition(state_key, new_state).await?;+ Err(format!("OSC failed: {external_status:?}"))+ }+ }+ .map(|s| s.to_string())+ }+}++// ============================================================================+// 15.6: dbdiff_lock — database-level distributed lock+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DbDiffLock {+ pub lock_id: String,+ pub instance_id: String,+ pub acquired_at: String,+ pub expires_at: String,+}++impl DbDiffLock {+ pub fn create_table_sql() -> &'static str {+ "CREATE TABLE IF NOT EXISTS dbdiff_lock (+ lock_id TEXT PRIMARY KEY,+ instance_id TEXT NOT NULL,+ acquired_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,+ expires_at TIMESTAMP NOT NULL+ )"+ }++ pub fn acquire_sql(lock_id: &str, instance_id: &str, ttl_seconds: u64) -> String {+ format!(+ "INSERT INTO dbdiff_lock (lock_id, instance_id, expires_at) \+ VALUES ('{lock_id}', '{instance_id}', DATEADD('SECOND', {ttl_seconds}, CURRENT_TIMESTAMP))"+ )+ }++ pub fn check_sql(lock_id: &str) -> String {+ format!(+ "SELECT instance_id, acquired_at, expires_at FROM dbdiff_lock \+ WHERE lock_id = '{lock_id}' AND expires_at > CURRENT_TIMESTAMP"+ )+ }++ pub fn release_sql(lock_id: &str, instance_id: &str) -> String {+ format!("DELETE FROM dbdiff_lock WHERE lock_id = '{lock_id}' AND instance_id = '{instance_id}'")+ }++ pub fn cleanup_expired_sql() -> &'static str {+ "DELETE FROM dbdiff_lock WHERE expires_at <= CURRENT_TIMESTAMP"+ }++ pub fn extend_sql(lock_id: &str, instance_id: &str, ttl_seconds: u64) -> String {+ format!(+ "UPDATE dbdiff_lock SET expires_at = DATEADD('SECOND', {ttl_seconds}, CURRENT_TIMESTAMP) \+ WHERE lock_id = '{lock_id}' AND instance_id = '{instance_id}'"+ )+ }+}++// ============================================================================+// Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;++ // --- gh-ost log parsing ---++ #[test]+ fn gh_ost_parse_log_copying() {+ let line = "Copying rows: 12345/67890 (18.2%)";+ let result = GhOstProbe::parse_log_line(line).unwrap();+ assert_eq!(result.rows_copied, 12345);+ assert_eq!(result.rows_total, 67890);+ assert!((result.progress_pct - 18.2).abs() < 0.01);+ match result.status {+ OscExecutionStatus::Copying { .. } => {}+ _ => panic!("should be Copying"),+ }+ }++ #[test]+ fn gh_ost_parse_log_cutover() {+ let line = "Copying rows: 67889/67890 (100.0%)";+ let result = GhOstProbe::parse_log_line(line).unwrap();+ match result.status {+ OscExecutionStatus::CutOver => {}+ _ => panic!("should be CutOver at 100%"),+ }+ }++ #[test]+ fn gh_ost_parse_non_copying_line() {+ let line = "2024/01/01 12:00:00 Starting gh-ost...";+ assert!(GhOstProbe::parse_log_line(line).is_none());+ }++ // --- pt-osc ---++ #[test]+ fn pt_osc_get_object_names() {+ let names = PtOscProbe::object_names("users");+ assert_eq!(names.new_table, "_users_new");+ assert_eq!(names.del_trigger, "pt_osc_users_del");+ }++ #[test]+ fn pt_osc_parse_progress() {+ let line = "Copying `mydb`.`users`: 45% 00:30 remaining";+ let pct = PtOscProbe::parse_progress_line(line).unwrap();+ assert!((pct - 45.0).abs() < 0.01);+ }++ // --- OSC status serialization ---++ #[test]+ fn osc_status_serialization() {+ let status = OscExecutionStatus::Copying { progress_pct: 45.5, rows_copied: 100, rows_total: 200 };+ let json = serde_json::to_string(&status).unwrap();+ assert!(json.contains("45.5"));+ let deserialized: OscExecutionStatus = serde_json::from_str(&json).unwrap();+ assert_eq!(status, deserialized);+ }++ // --- dbdiff_lock ---++ #[test]+ fn dbdiff_lock_acquire_sql() {+ let sql = DbDiffLock::acquire_sql("mig-001", "node-1", 300);+ assert!(sql.contains("INSERT INTO dbdiff_lock"));+ assert!(sql.contains("mig-001"));+ }++ #[test]+ fn dbdiff_lock_release_sql() {+ let sql = DbDiffLock::release_sql("mig-001", "node-1");+ assert!(sql.contains("DELETE FROM dbdiff_lock"));+ }++ #[test]+ fn dbdiff_lock_check_sql() {+ let sql = DbDiffLock::check_sql("mig-001");+ assert!(sql.contains("expires_at > CURRENT_TIMESTAMP"));+ }++ #[test]+ fn dbdiff_lock_create_table_sql() {+ let sql = DbDiffLock::create_table_sql();+ assert!(sql.contains("CREATE TABLE IF NOT EXISTS dbdiff_lock"));+ }++ // --- State machine extended transition tests ---++ #[test]+ fn state_machine_new_transitions_valid() {+ use crate::state_persistence::{is_valid_transition, StateTransition};+ assert!(is_valid_transition(&StateTransition::Running, &StateTransition::OscSyncing));+ assert!(is_valid_transition(&StateTransition::OscSyncing, &StateTransition::Completed));+ assert!(is_valid_transition(&StateTransition::OscSyncing, &StateTransition::Failed));+ assert!(is_valid_transition(&StateTransition::Failed, &StateTransition::RollingBack));+ assert!(is_valid_transition(&StateTransition::RollingBack, &StateTransition::FullyRolledBack));+ assert!(is_valid_transition(&StateTransition::RollingBack, &StateTransition::PartiallyRolledBack));+ assert!(is_valid_transition(&StateTransition::PartiallyRolledBack, &StateTransition::RecoveryRequired));+ }++ #[test]+ fn state_machine_new_transitions_invalid() {+ use crate::state_persistence::{is_valid_transition, StateTransition};+ assert!(!is_valid_transition(&StateTransition::Created, &StateTransition::OscSyncing));+ assert!(!is_valid_transition(&StateTransition::OscSyncing, &StateTransition::Running));+ assert!(!is_valid_transition(&StateTransition::FullyRolledBack, &StateTransition::Running));+ }++ #[test]+ fn state_machine_full_lifecycle_with_osc() {+ use crate::state_persistence::{is_valid_transition, StateTransition};+ let lifecycle = ["created", "running", "osc_syncing", "completed"];+ // Validate each step+ let states = [+ StateTransition::Created,+ StateTransition::Running,+ StateTransition::OscSyncing,+ StateTransition::Completed,+ ];+ for i in 0..states.len() - 1 {+ assert!(is_valid_transition(&states[i], &states[i + 1]));+ }+ }++ #[test]+ fn state_machine_rollback_scenarios() {+ use crate::state_persistence::{is_valid_transition, StateTransition};+ // Failed → RollingBack → FullyRolledBack+ assert!(is_valid_transition(&StateTransition::Failed, &StateTransition::RollingBack));+ assert!(is_valid_transition(&StateTransition::RollingBack, &StateTransition::FullyRolledBack));+ // Failed → RollingBack → PartiallyRolledBack → RecoveryRequired+ assert!(is_valid_transition(&StateTransition::RollingBack, &StateTransition::PartiallyRolledBack));+ assert!(is_valid_transition(&StateTransition::PartiallyRolledBack, &StateTransition::RecoveryRequired));+ // Failed → RecoveryRequired (direct)+ assert!(is_valid_transition(&StateTransition::Failed, &StateTransition::RecoveryRequired));+ }+}diff --git a/crates/dbx-core/src/query.rs b/crates/dbx-core/src/query.rsindex 1da9195602..e3c59c856d 100644--- a/crates/dbx-core/src/query.rs+++ b/crates/dbx-core/src/query.rs@@ -33,6 +33,8 @@ use crate::query_execution_sql::is_write_sql;#[cfg(feature = "duckdb-bundled")]use crate::sql::starts_with_duckdb_result_sql_keyword;use crate::sql::{split_sql_batches, split_sql_statements, starts_with_executable_sql_keyword};+use crate::sql_dialect::{resolve_for_db, CAP_TRANSACTIONAL_DDL};+use crate::sql_risk::{classify_sql_risk_for_database, SqlRisk};pub const QUERY_TIMEOUT: Duration = Duration::from_secs(30);pub const MAX_ROWS: usize = 10000;@@ -475,6 +477,7 @@ fn duckdb_value_to_json(row: &duckdb::Row<'_>, idx: usize) -> serde_json::Value| ValueRef::Map(..)| ValueRef::Enum(..)| ValueRef::Union(..) => duckdb_owned_value_to_json(&value_ref.to_owned()),+ _ => duckdb_owned_value_to_json(&value_ref.to_owned()),}}@@ -534,6 +537,7 @@ fn duckdb_owned_value_to_json(value: &Value) -> serde_json::Value {.collect(),),Value::Union(value) => duckdb_owned_value_to_json(value),+ _ => serde_json::Value::Null,}}@@ -2587,6 +2591,254 @@ fn is_agent_execute_batch_unsupported(error: &str) -> bool {lower.contains("execute_batch") && (lower.contains("unknown method") || lower.contains("method not found"))}+/// Deploy result for Schema Diff: single-connection transactional execution.+/// On statement failure the transaction is rolled back by the underlying path.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SchemaDiffDeployResult {+ pub transaction_id: String,+ pub status: String,+ pub participants: Vec<crate::two_phase_commit::ParticipantInfo>,+ pub created_at: String,+ pub updated_at: String,+ pub executed_count: usize,+ pub statement_count: usize,+ pub error: Option<String>,+ pub metadata: serde_json::Value,+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum SchemaDiffAtomicity {+ GuaranteedRollback,+ PartialEffectsPossible,+}++impl SchemaDiffAtomicity {+ fn ddl_atomic(self) -> bool {+ matches!(self, Self::GuaranteedRollback)+ }+}++fn database_supports_transactional_ddl(db_type: DatabaseType) -> bool {+ if resolve_for_db(db_type).has_capability(CAP_TRANSACTIONAL_DDL) {+ return true;+ }+ // SQLite-family DDL is transactional even when dialect registry omits the flag.+ matches!(db_type, DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso | DatabaseType::CloudflareD1)+}++fn classify_schema_diff_atomicity(+ db_type: Option<DatabaseType>,+ statements: &[String],+ has_transactional_path: bool,+) -> SchemaDiffAtomicity {+ if !has_transactional_path {+ return SchemaDiffAtomicity::PartialEffectsPossible;+ }++ let mut contains_ddl = false;+ for statement in statements {+ let risk = match db_type {+ Some(db_type) => classify_sql_risk_for_database(statement, db_type).ok(),+ None => None,+ };++ match risk {+ Some(SqlRisk::Ddl) => {+ contains_ddl = true;+ }+ Some(SqlRisk::Write | SqlRisk::ReadOnly) => {}+ Some(SqlRisk::Transaction) | None => {+ return SchemaDiffAtomicity::PartialEffectsPossible;+ }+ }+ }++ if !contains_ddl {+ return SchemaDiffAtomicity::GuaranteedRollback;+ }++ match db_type {+ Some(db_type) if database_supports_transactional_ddl(db_type) => SchemaDiffAtomicity::GuaranteedRollback,+ _ => SchemaDiffAtomicity::PartialEffectsPossible,+ }+}++fn executed_count_before_error(error: &str, statement_count: usize) -> usize {+ let Some(rest) = error.strip_prefix("Statement ") else {+ return statement_count;+ };+ let digits: String = rest.chars().take_while(|ch| ch.is_ascii_digit()).collect();+ let Ok(statement_number) = digits.parse::<usize>() else {+ return statement_count;+ };+ statement_number.saturating_sub(1).min(statement_count)+}++/// Pure failure mapping used by deploy and unit tests.+fn schema_diff_failure_outcome(+ atomicity: SchemaDiffAtomicity,+ error: &str,+ statement_count: usize,+) -> (crate::two_phase_commit::TransactionStatus, usize) {+ if atomicity.ddl_atomic() {+ (crate::two_phase_commit::TransactionStatus::RolledBack, 0)+ } else {+ (crate::two_phase_commit::TransactionStatus::Mixed, executed_count_before_error(error, statement_count))+ }+}++fn pool_kind_has_transactional_path(pool: &PoolKind) -> bool {+ // DuckDb variants always exist (unit stubs when duckdb-bundled is off).+ match pool {+ PoolKind::Postgres(_)+ | PoolKind::Mysql(_, _)+ | PoolKind::Sqlite(_)+ | PoolKind::CloudflareD1(_)+ | PoolKind::ClickHouse(_)+ | PoolKind::Rqlite(_)+ | PoolKind::Turso(_)+ | PoolKind::SqlServer(_)+ | PoolKind::Agent(_) => true,+ PoolKind::MessageQueue+ | PoolKind::Nacos+ | PoolKind::HBase(_)+ | PoolKind::DuckDb(_)+ | PoolKind::DuckDbWorker(_)+ | PoolKind::Redis(_)+ | PoolKind::MongoDb(_)+ | PoolKind::Elasticsearch(_)+ | PoolKind::VectorDb(_)+ | PoolKind::InfluxDb(_)+ | PoolKind::ExternalTabular(_)+ | PoolKind::ExternalDriver { .. } => false,+ }+}++/// Execute Schema Diff deploy SQL as one real single-connection transaction.+///+/// - Uses [`execute_statements_in_transaction`] so partial success rolls back.+/// - Returns a structured result (never re-executes statements to probe status).+/// - Comment-only / empty scripts succeed as `committed` with zero statements.+/// - When the target path cannot guarantee DDL atomicity (MySQL/Oracle DDL+/// auto-commit, `TxPath::None`, etc.), a failure reports `mixed` and+/// `executed_count` reflects the statements that were issued before the+/// error, so the caller can warn the user that partial effects may persist.+pub async fn execute_schema_diff_deploy(+ state: &AppState,+ connection_id: &str,+ database: &str,+ statements: &[String],+ schema: Option<&str>,+) -> SchemaDiffDeployResult {+ let tx_id = format!("deploy_{}", uuid::Uuid::new_v4());+ let now = chrono::Utc::now().to_rfc3339();+ let db_type = connection_database_type(state, connection_id).await;++ let parsed: Vec<String> = statements+ .iter()+ .flat_map(|s| {+ db_type.map_or_else(|| split_sql_statements(s), |dt| crate::sql::split_sql_statements_for_database(s, dt))+ })+ .map(|s| s.trim().to_string())+ .filter(|s| {+ !s.is_empty()+ && !s.lines().all(|line| {+ let t = line.trim();+ t.is_empty() || t.starts_with("--")+ })+ })+ .collect();++ let participant = crate::two_phase_commit::ParticipantInfo {+ id: "connection".to_string(),+ name: format!("{connection_id}/{database}"),+ role: "database".to_string(),+ };++ if parsed.is_empty() {+ return SchemaDiffDeployResult {+ transaction_id: tx_id,+ status: crate::two_phase_commit::TransactionStatus::Committed.as_str().to_string(),+ participants: vec![participant],+ created_at: now.clone(),+ updated_at: now,+ executed_count: 0,+ statement_count: 0,+ error: None,+ metadata: serde_json::json!({"source": "schema_diff_deploy", "mode": "single_connection_tx"}),+ };+ }++ let pool_key = if database.is_empty() {+ connection_id.to_string()+ } else {+ match state.get_or_create_pool(connection_id, Some(database)).await {+ Ok(key) => key,+ Err(_) => {+ return SchemaDiffDeployResult {+ transaction_id: tx_id.clone(),+ status: crate::two_phase_commit::TransactionStatus::RolledBack.as_str().to_string(),+ participants: vec![participant],+ created_at: now.clone(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ executed_count: 0,+ statement_count: parsed.len(),+ error: Some("Connection not available for deploy".to_string()),+ metadata: serde_json::json!({"source": "schema_diff_deploy", "mode": "single_connection_tx"}),+ };+ }+ }+ };+ let has_transactional_path = {+ let conns = state.connections.read().await;+ conns.get(&pool_key).is_some_and(pool_kind_has_transactional_path)+ };+ let atomicity = classify_schema_diff_atomicity(db_type, &parsed, has_transactional_path);++ match execute_statements_in_transaction_on_pool(state, &pool_key, connection_id, database, &parsed, schema).await {+ Ok(result) => SchemaDiffDeployResult {+ transaction_id: tx_id,+ status: crate::two_phase_commit::TransactionStatus::Committed.as_str().to_string(),+ participants: vec![participant],+ created_at: now.clone(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ executed_count: parsed.len(),+ statement_count: parsed.len(),+ error: None,+ metadata: serde_json::json!({+ "source": "schema_diff_deploy",+ "mode": "single_connection_tx",+ "affected_rows": result.affected_rows,+ "execution_time_ms": result.execution_time_ms,+ }),+ },+ Err(e) => {+ let (status, executed_count) = schema_diff_failure_outcome(atomicity, &e, parsed.len());+ SchemaDiffDeployResult {+ transaction_id: tx_id,+ status: status.as_str().to_string(),+ participants: vec![participant],+ created_at: now.clone(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ executed_count,+ statement_count: parsed.len(),+ error: Some(e.clone()),+ metadata: serde_json::json!({+ "source": "schema_diff_deploy",+ "mode": "single_connection_tx",+ "ddl_atomic": atomicity.ddl_atomic(),+ "atomicity": match atomicity {+ SchemaDiffAtomicity::GuaranteedRollback => "guaranteed_rollback",+ SchemaDiffAtomicity::PartialEffectsPossible => "partial_effects_possible",+ },+ "error": e,+ }),+ }+ }+ }+}+/// Execute multiple SQL statements within a single transaction./// For pooled drivers (Postgres/MySQL), uses the driver transaction API./// For SQLite and already-single-connection drivers (ClickHouse/SqlServer/Agent),@@ -3637,6 +3889,132 @@ mod tests {};use crate::storage::Storage;+ #[test]+ fn schema_diff_atomicity_marks_mysql_ddl_as_partial() {+ let atomicity = classify_schema_diff_atomicity(+ Some(DatabaseType::Mysql),+ &["CREATE TABLE users (id INT)".to_string(), "ALTER TABLE users ADD COLUMN name VARCHAR(32)".to_string()],+ true,+ );++ assert_eq!(atomicity, SchemaDiffAtomicity::PartialEffectsPossible);+ }++ #[test]+ fn schema_diff_atomicity_marks_oracle_ddl_as_partial() {+ let atomicity = classify_schema_diff_atomicity(+ Some(DatabaseType::Oracle),+ &["CREATE TABLE users (id INT)".to_string(), "ALTER TABLE users ADD name VARCHAR2(32)".to_string()],+ true,+ );++ assert_eq!(atomicity, SchemaDiffAtomicity::PartialEffectsPossible);+ }++ #[test]+ fn schema_diff_atomicity_keeps_postgres_ddl_atomic() {+ let atomicity = classify_schema_diff_atomicity(+ Some(DatabaseType::Postgres),+ &["CREATE TABLE users (id INT)".to_string(), "ALTER TABLE users ADD COLUMN name VARCHAR(32)".to_string()],+ true,+ );++ assert_eq!(atomicity, SchemaDiffAtomicity::GuaranteedRollback);+ }++ #[test]+ fn schema_diff_atomicity_keeps_dml_atomic_when_tx_path_exists() {+ let atomicity = classify_schema_diff_atomicity(+ Some(DatabaseType::Mysql),+ &["INSERT INTO users VALUES (1)".to_string(), "UPDATE users SET active = 1 WHERE id = 1".to_string()],+ true,+ );++ assert_eq!(atomicity, SchemaDiffAtomicity::GuaranteedRollback);+ }++ #[test]+ fn schema_diff_atomicity_marks_missing_transaction_path_as_partial() {+ let atomicity = classify_schema_diff_atomicity(+ Some(DatabaseType::Postgres),+ &["CREATE TABLE users (id INT)".to_string()],+ false,+ );++ assert_eq!(atomicity, SchemaDiffAtomicity::PartialEffectsPossible);+ }++ #[test]+ fn executed_count_before_error_uses_failing_statement_index() {+ assert_eq!(executed_count_before_error("Statement 1 failed: syntax error", 3), 0);+ assert_eq!(executed_count_before_error("Statement 2 failed: syntax error", 3), 1);+ assert_eq!(executed_count_before_error("Statement 3 failed: syntax error", 3), 2);+ }++ #[test]+ fn schema_diff_failure_outcome_rolls_back_when_atomic() {+ let (status, executed) =+ schema_diff_failure_outcome(SchemaDiffAtomicity::GuaranteedRollback, "Statement 2 failed: syntax error", 3);+ assert_eq!(status, crate::two_phase_commit::TransactionStatus::RolledBack);+ assert_eq!(executed, 0);+ }++ #[test]+ fn schema_diff_failure_outcome_reports_mixed_with_partial_count() {+ let (status, executed) = schema_diff_failure_outcome(+ SchemaDiffAtomicity::PartialEffectsPossible,+ "Statement 2 failed: syntax error",+ 3,+ );+ assert_eq!(status, crate::two_phase_commit::TransactionStatus::Mixed);+ assert_eq!(executed, 1);+ }++ #[test]+ fn schema_diff_atomicity_keeps_sqlite_ddl_atomic() {+ let atomicity = classify_schema_diff_atomicity(+ Some(DatabaseType::Sqlite),+ &["CREATE TABLE users (id INTEGER)".to_string()],+ true,+ );+ assert_eq!(atomicity, SchemaDiffAtomicity::GuaranteedRollback);+ }++ /// MySQL: first DDL may already commit; second fails → mixed + executed_count = 1.+ #[test]+ fn mysql_second_ddl_failure_maps_to_mixed_with_partial_executed_count() {+ let stmts = ["CREATE TABLE t1 (id INT)".to_string(), "CREATE TABLE t2 (id INT)".to_string()];+ let atomicity = classify_schema_diff_atomicity(Some(DatabaseType::Mysql), &stmts, true);+ assert_eq!(atomicity, SchemaDiffAtomicity::PartialEffectsPossible);+ let (status, executed) =+ schema_diff_failure_outcome(atomicity, "Statement 2 failed: table already exists", stmts.len());+ assert_eq!(status, crate::two_phase_commit::TransactionStatus::Mixed);+ assert_eq!(executed, 1);+ }++ /// Oracle: same non-transactional DDL semantics as MySQL for deploy status.+ #[test]+ fn oracle_second_ddl_failure_maps_to_mixed_with_partial_executed_count() {+ let stmts = ["CREATE TABLE t1 (id NUMBER)".to_string(), "ALTER TABLE t1 ADD name VARCHAR2(32)".to_string()];+ let atomicity = classify_schema_diff_atomicity(Some(DatabaseType::Oracle), &stmts, true);+ assert_eq!(atomicity, SchemaDiffAtomicity::PartialEffectsPossible);+ let (status, executed) = schema_diff_failure_outcome(atomicity, "Statement 2 failed: ORA-00942", stmts.len());+ assert_eq!(status, crate::two_phase_commit::TransactionStatus::Mixed);+ assert_eq!(executed, 1);+ }++ /// Postgres transactional DDL: second fails → rolled_back + executed_count = 0.+ #[test]+ fn postgres_second_ddl_failure_maps_to_rolled_back_zero_executed() {+ let stmts = ["CREATE TABLE t1 (id INT)".to_string(), "CREATE TABLE t2 (id INT)".to_string()];+ let atomicity = classify_schema_diff_atomicity(Some(DatabaseType::Postgres), &stmts, true);+ assert_eq!(atomicity, SchemaDiffAtomicity::GuaranteedRollback);+ let (status, executed) =+ schema_diff_failure_outcome(atomicity, "Statement 2 failed: relation already exists", stmts.len());+ assert_eq!(status, crate::two_phase_commit::TransactionStatus::RolledBack);+ assert_eq!(executed, 0);+ }+#[test]fn query_execution_mode_deserializes_simple_client_value() {let mode: QueryExecutionMode = serde_json::from_str("\"simple\"").unwrap();diff --git a/crates/dbx-core/src/risk_metrics.rs b/crates/dbx-core/src/risk_metrics.rsnew file mode 100644index 0000000000..5eb48b02c6--- /dev/null+++ b/crates/dbx-core/src/risk_metrics.rs@@ -0,0 +1,376 @@+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::sync::atomic::{AtomicU64, Ordering};+use std::sync::Mutex;++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum MetricType {+ Counter,+ Gauge,+ Histogram,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MetricEntry {+ pub name: String,+ pub metric_type: MetricType,+ pub description: String,+ pub labels: HashMap<String, String>,+ pub value: MetricValue,+}++#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]+#[serde(untagged)]+pub enum MetricValue {+ Counter(u64),+ Gauge(f64),+ Histogram(Vec<(f64, u64)>),+}++pub struct DegradationMetrics {+ degradation_total: AtomicU64,+ degradation_level_full: AtomicU64,+ degradation_level_sample: AtomicU64,+ degradation_level_skip: AtomicU64,+ sample_rate_histogram: Mutex<Vec<(f64, u64)>>,+ confidence_gauge: Mutex<f64>,+ auto_upgrade_total: AtomicU64,+ auto_downgrade_total: AtomicU64,+ // Phase 15.5: OSC and rollback metrics+ osc_probe_latency: Mutex<Vec<f64>>,+ osc_execution_gauge: Mutex<f64>,+ rollback_trigger_count: AtomicU64,+ tag_block_count: AtomicU64,+ trace_dropped_count: AtomicU64,+}++impl DegradationMetrics {+ pub fn new() -> Self {+ Self {+ degradation_total: AtomicU64::new(0),+ degradation_level_full: AtomicU64::new(0),+ degradation_level_sample: AtomicU64::new(0),+ degradation_level_skip: AtomicU64::new(0),+ sample_rate_histogram: Mutex::new(Vec::new()),+ confidence_gauge: Mutex::new(0.0),+ auto_upgrade_total: AtomicU64::new(0),+ auto_downgrade_total: AtomicU64::new(0),+ osc_probe_latency: Mutex::new(Vec::new()),+ osc_execution_gauge: Mutex::new(0.0),+ rollback_trigger_count: AtomicU64::new(0),+ tag_block_count: AtomicU64::new(0),+ trace_dropped_count: AtomicU64::new(0),+ }+ }++ pub fn record_degradation(&self, level: &str, sample_rate: f64, confidence: f64) {+ self.degradation_total.fetch_add(1, Ordering::Relaxed);+ match level {+ "full" => {+ self.degradation_level_full.fetch_add(1, Ordering::Relaxed);+ }+ "sample" => {+ self.degradation_level_sample.fetch_add(1, Ordering::Relaxed);+ }+ "skip_with_risk" => {+ self.degradation_level_skip.fetch_add(1, Ordering::Relaxed);+ }+ _ => {}+ }+ if let Ok(mut h) = self.sample_rate_histogram.lock() {+ h.push((sample_rate, 1));+ }+ if let Ok(mut g) = self.confidence_gauge.lock() {+ *g = confidence;+ }+ }++ pub fn record_auto_upgrade(&self) {+ self.auto_upgrade_total.fetch_add(1, Ordering::Relaxed);+ }++ pub fn record_auto_downgrade(&self) {+ self.auto_downgrade_total.fetch_add(1, Ordering::Relaxed);+ }++ // --- Phase 15.5: OSC & rollback metrics ---++ pub fn record_osc_probe_latency(&self, latency_ms: f64) {+ if let Ok(mut h) = self.osc_probe_latency.lock() {+ h.push(latency_ms);+ if h.len() > 1000 {+ h.remove(0);+ }+ }+ }++ pub fn set_osc_execution_status(&self, status: f64) {+ if let Ok(mut g) = self.osc_execution_gauge.lock() {+ *g = status;+ }+ }++ pub fn record_rollback_trigger(&self) {+ self.rollback_trigger_count.fetch_add(1, Ordering::Relaxed);+ }++ pub fn record_tag_block(&self) {+ self.tag_block_count.fetch_add(1, Ordering::Relaxed);+ }++ pub fn record_trace_dropped(&self) {+ self.trace_dropped_count.fetch_add(1, Ordering::Relaxed);+ }++ pub fn snapshot(&self) -> Vec<MetricEntry> {+ let mut entries = vec![+ MetricEntry {+ name: "dbx_degradation_total".to_string(),+ metric_type: MetricType::Counter,+ description: "Total number of degradation decisions".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.degradation_total.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_degradation_level_full".to_string(),+ metric_type: MetricType::Counter,+ description: "Number of full compare decisions".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.degradation_level_full.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_degradation_level_sample".to_string(),+ metric_type: MetricType::Counter,+ description: "Number of sample compare decisions".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.degradation_level_sample.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_degradation_level_skip".to_string(),+ metric_type: MetricType::Counter,+ description: "Number of skip-with-risk decisions".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.degradation_level_skip.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_auto_upgrade_total".to_string(),+ metric_type: MetricType::Counter,+ description: "Number of automatic upgrades in degradation chain".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.auto_upgrade_total.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_auto_downgrade_total".to_string(),+ metric_type: MetricType::Counter,+ description: "Number of automatic downgrades in degradation chain".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.auto_downgrade_total.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_confidence_gauge".to_string(),+ metric_type: MetricType::Gauge,+ description: "Current confidence score".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Gauge(*self.confidence_gauge.lock().unwrap_or_else(|e| e.into_inner())),+ },+ ];++ // Phase 15.5: OSC and rollback metrics+ if let Ok(h) = self.osc_probe_latency.lock() {+ if !h.is_empty() {+ entries.push(MetricEntry {+ name: "dbx_osc_probe_latency".to_string(),+ metric_type: MetricType::Histogram,+ description: "Distribution of OSC probe latency in milliseconds".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Histogram(h.iter().map(|&v| (v, 1u64)).collect()),+ });+ }+ }+ entries.extend(vec![+ MetricEntry {+ name: "dbx_osc_execution_status".to_string(),+ metric_type: MetricType::Gauge,+ description: "Current OSC execution status (0=idle, 1=running, 2=completed, -1=error)".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Gauge(*self.osc_execution_gauge.lock().unwrap_or_else(|e| e.into_inner())),+ },+ MetricEntry {+ name: "dbx_rollback_trigger_total".to_string(),+ metric_type: MetricType::Counter,+ description: "Total number of rollback triggers".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.rollback_trigger_count.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_tag_block_total".to_string(),+ metric_type: MetricType::Counter,+ description: "Total number of tag policy blocks".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.tag_block_count.load(Ordering::Relaxed)),+ },+ MetricEntry {+ name: "dbx_trace_dropped_total".to_string(),+ metric_type: MetricType::Counter,+ description: "Total number of dropped trace entries".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Counter(self.trace_dropped_count.load(Ordering::Relaxed)),+ },+ ]);++ if let Ok(h) = self.sample_rate_histogram.lock() {+ entries.push(MetricEntry {+ name: "dbx_sample_rate_histogram".to_string(),+ metric_type: MetricType::Histogram,+ description: "Distribution of sampling rates used".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Histogram(h.clone()),+ });+ }++ entries+ }+}++impl Default for DegradationMetrics {+ fn default() -> Self {+ Self::new()+ }+}++pub fn export_prometheus(metrics: &[MetricEntry]) -> String {+ let mut out = String::new();+ for entry in metrics {+ let name = &entry.name;+ let desc = &entry.description;+ let labels = if entry.labels.is_empty() {+ String::new()+ } else {+ let pairs: Vec<String> = entry.labels.iter().map(|(k, v)| format!("{k}=\"{v}\"")).collect();+ format!("{{{}}}", pairs.join(","))+ };++ out.push_str(&format!("# HELP {name} {desc}\n"));+ match &entry.metric_type {+ MetricType::Counter => {+ out.push_str(&format!("# TYPE {name} counter\n"));+ if let MetricValue::Counter(v) = &entry.value {+ out.push_str(&format!("{name}{labels} {v}\n"));+ }+ }+ MetricType::Gauge => {+ out.push_str(&format!("# TYPE {name} gauge\n"));+ if let MetricValue::Gauge(v) = &entry.value {+ out.push_str(&format!("{name}{labels} {v}\n"));+ }+ }+ MetricType::Histogram => {+ out.push_str(&format!("# TYPE {name} histogram\n"));+ if let MetricValue::Histogram(buckets) = &entry.value {+ for (le, count) in buckets {+ out.push_str(&format!("{name}_bucket{{le=\"{le}\"}} {count}\n"));+ }+ let total: u64 = buckets.iter().map(|(_, c)| c).sum();+ out.push_str(&format!("{name}_count{labels} {total}\n"));+ }+ }+ }+ }+ out+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn degradation_metrics_records_levels() {+ let metrics = DegradationMetrics::new();+ metrics.record_degradation("full", 1.0, 1.0);+ metrics.record_degradation("sample", 0.1, 0.8);+ metrics.record_degradation("skip_with_risk", 0.0, 0.0);++ let snapshot = metrics.snapshot();+ let total = snapshot.iter().find(|e| e.name == "dbx_degradation_total").unwrap();+ assert_eq!(total.value, MetricValue::Counter(3));+ let full = snapshot.iter().find(|e| e.name == "dbx_degradation_level_full").unwrap();+ assert_eq!(full.value, MetricValue::Counter(1));+ let sample = snapshot.iter().find(|e| e.name == "dbx_degradation_level_sample").unwrap();+ assert_eq!(sample.value, MetricValue::Counter(1));+ let skip = snapshot.iter().find(|e| e.name == "dbx_degradation_level_skip").unwrap();+ assert_eq!(skip.value, MetricValue::Counter(1));+ }++ #[test]+ fn degradation_metrics_auto_chain_events() {+ let metrics = DegradationMetrics::new();+ metrics.record_auto_upgrade();+ metrics.record_auto_upgrade();+ metrics.record_auto_downgrade();++ let snapshot = metrics.snapshot();+ let up = snapshot.iter().find(|e| e.name == "dbx_auto_upgrade_total").unwrap();+ assert_eq!(up.value, MetricValue::Counter(2));+ let down = snapshot.iter().find(|e| e.name == "dbx_auto_downgrade_total").unwrap();+ assert_eq!(down.value, MetricValue::Counter(1));+ }++ #[test]+ fn degradation_metrics_confidence_gauge() {+ let metrics = DegradationMetrics::new();+ metrics.record_degradation("sample", 0.05, 0.85);++ let snapshot = metrics.snapshot();+ let gauge = snapshot.iter().find(|e| e.name == "dbx_confidence_gauge").unwrap();+ assert_eq!(gauge.value, MetricValue::Gauge(0.85));+ }++ #[test]+ fn export_prometheus_counter() {+ let mut labels = HashMap::new();+ labels.insert("level".to_string(), "full".to_string());+ let entries = vec![MetricEntry {+ name: "test_counter".to_string(),+ metric_type: MetricType::Counter,+ description: "A test counter".to_string(),+ labels,+ value: MetricValue::Counter(42),+ }];+ let output = export_prometheus(&entries);+ assert!(output.contains("# HELP test_counter A test counter"));+ assert!(output.contains("# TYPE test_counter counter"));+ assert!(output.contains("test_counter{level=\"full\"} 42"));+ }++ #[test]+ fn export_prometheus_gauge() {+ let entries = vec![MetricEntry {+ name: "test_gauge".to_string(),+ metric_type: MetricType::Gauge,+ description: "A test gauge".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Gauge(3.125),+ }];+ let output = export_prometheus(&entries);+ assert!(output.contains("# TYPE test_gauge gauge"));+ assert!(output.contains("test_gauge 3.125"));+ }++ #[test]+ fn export_prometheus_histogram() {+ let buckets = vec![(0.5, 10u64), (1.0, 5u64), (1.5, 2u64)];+ let entries = vec![MetricEntry {+ name: "test_histogram".to_string(),+ metric_type: MetricType::Histogram,+ description: "A test histogram".to_string(),+ labels: HashMap::new(),+ value: MetricValue::Histogram(buckets),+ }];+ let output = export_prometheus(&entries);+ assert!(output.contains("# TYPE test_histogram histogram"));+ assert!(output.contains("test_histogram_bucket{le=\"0.5\"} 10"));+ assert!(output.contains("test_histogram_bucket{le=\"1\"} 5"));+ assert!(output.contains("test_histogram_count 17"));+ }+}diff --git a/crates/dbx-core/src/safety_report.rs b/crates/dbx-core/src/safety_report.rsnew file mode 100644index 0000000000..e5adfc782d--- /dev/null+++ b/crates/dbx-core/src/safety_report.rs@@ -0,0 +1,53 @@+use crate::sql_risk::ImpactReport;++/// Generate a human-readable safety check report string.+pub fn generate_safety_report(report: &ImpactReport) -> String {+ let mut lines = Vec::new();++ lines.push("=== SQL Safety Check Report ===".to_string());+ lines.push(format!("Overall Risk: {}", report.overall_risk));++ if let Some(drl) = &report.ddl_risk_level {+ lines.push(format!("DDL Risk Level: {}", drl));+ } else {+ lines.push("DDL Risk Level: N/A (no DDL statements)".to_string());+ }++ lines.push(format!("Statement Count: {}", report.statement_count));+ lines.push(format!("Recommended Strategy: {}", report.recommended_strategy));+ lines.push(format!("Estimated Duration: {}", report.estimated_total_duration));+ lines.push(format!("Maintenance Window Required: {}", report.requires_maintenance_window));+ lines.push(format!("Reversible: {}", report.is_reversible));++ if !report.ddl_details.is_empty() {+ lines.push("\n--- DDL Details ---".to_string());+ for (i, detail) in report.ddl_details.iter().enumerate() {+ lines.push(format!(+ " {}. [{}] {} — affects: {}",+ i + 1,+ detail.ddl_risk,+ detail.summary,+ detail.affected_objects.join(", ")+ ));+ }+ }++ if !report.estimated_locks.is_empty() {+ lines.push("\n--- Estimated Locks ---".to_string());+ for lock in &report.estimated_locks {+ lines.push(format!(+ " {}: {} lock ({}) — {}",+ lock.object, lock.lock_type, lock.scope, lock.estimated_duration+ ));+ }+ }++ if !report.warnings.is_empty() {+ lines.push("\n--- Warnings ---".to_string());+ for w in &report.warnings {+ lines.push(format!(" ! {}", w));+ }+ }++ lines.join("\n")+}diff --git a/crates/dbx-core/src/schema_diff.rs b/crates/dbx-core/src/schema_diff.rsindex 143c60c972..5f2f2f2b3d 100644--- a/crates/dbx-core/src/schema_diff.rs+++ b/crates/dbx-core/src/schema_diff.rs@@ -1,8 +1,18 @@-use std::collections::{HashMap, HashSet};+use std::collections::{HashMap, HashSet, VecDeque};+use log;+use rayon::prelude::*;+use regex::Regex;use serde::{Deserialize, Serialize};use crate::models::connection::DatabaseType;+use crate::sql_dialect::ddl_profile::{profile_for, DdlDialectProfile};+use crate::sql_dialect::descriptor::DialectKind;+use crate::sql_dialect::inference::{ColumnType, DefaultTypeInferenceEngine, TypeInferenceEngine};+use crate::sql_dialect::type_rewrite::{+ apply_auto_inc_to_column_def, rewrite_column_type, type_looks_integer, AutoIncColumnBuild,+};+use crate::sql_parser::ast_filter::AstTransmitFilter;use crate::types::{ColumnInfo, ForeignKeyInfo, FunctionInfo, IndexInfo, OwnerInfo, RuleInfo, SequenceInfo, TableInfo, TriggerInfo,};@@ -119,7 +129,7 @@ pub struct OwnerDiff {pub changes: Vec<String>,}-#[derive(Debug, Clone, Serialize, Deserialize)]+#[derive(Debug, Clone, Serialize, Deserialize, Default)]#[serde(rename_all = "camelCase")]pub struct TableDiff {#[serde(rename = "type")]@@ -163,6 +173,95 @@ pub struct TableSchemaDetail {pub ddl: Option<String>,}+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum ParamStrategy {+ Preserve,+ Strip,+ Custom,+}++fn default_param_strategy() -> ParamStrategy {+ ParamStrategy::Preserve+}++/// A custom field type mapping override: source_type → target_type.+/// Used when source and target database types differ.+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct FieldMapping {+ pub source_type: String,+ pub target_type: String,+ #[serde(default = "default_param_strategy")]+ pub param_strategy: ParamStrategy,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub custom_params: Option<String>,+}++impl FieldMapping {+ pub fn apply<'a>(mappings: &'a [FieldMapping], source_type: &str) -> Option<&'a str> {+ let base_type = source_type.split('(').next().unwrap_or(source_type).trim();+ mappings.iter().find(|m| m.source_type.eq_ignore_ascii_case(base_type)).map(|m| m.target_type.as_str())+ }++ pub fn apply_with_params(mappings: &[FieldMapping], source_type: &str, target_kind: DialectKind) -> Option<String> {+ let trimmed = source_type.trim();+ let base_type = trimmed.split('(').next().unwrap_or(trimmed);+ let source_params = &trimmed[base_type.len()..];+ let matched = mappings.iter().find(|m| m.source_type.eq_ignore_ascii_case(base_type))?;++ let result = match matched.param_strategy {+ ParamStrategy::Strip => Some(matched.target_type.clone()),+ ParamStrategy::Custom => match &matched.custom_params {+ Some(params) if !params.is_empty() => {+ let p = params.trim();+ // Normalize: wrap bare params (e.g. "100") in parentheses so the+ // generated type becomes e.g. `character(100)` rather than `character100`.+ let formatted = if p.starts_with('(') { p.to_string() } else { format!("({})", p) };+ Some(format!("{}{}", matched.target_type, formatted))+ }+ _ => Some(matched.target_type.clone()),+ },+ ParamStrategy::Preserve => {+ let supports = type_supports_params(target_kind, &matched.target_type);+ let has_params = !source_params.is_empty();+ if has_params && supports {+ Some(format!("{}{}", matched.target_type, source_params))+ } else {+ log::info!(+ "apply_with_params[Preserve] source={} target={} strategy={:?} has_params={} supports_params={} -> bare {}",+ source_type, matched.target_type, matched.param_strategy, has_params, supports, matched.target_type+ );+ Some(matched.target_type.clone())+ }+ }+ };+ log::info!(+ "apply_with_params source={} target_type={} strategy={:?} result={:?}",+ source_type,+ matched.target_type,+ matched.param_strategy,+ result+ );+ result+ }+}++fn type_supports_params(kind: DialectKind, type_name: &str) -> bool {+ crate::sql_dialect::dialect_loader::register_core_dialects();+ let registry = crate::sql_dialect::dialect_loader::DialectRegistry::global();+ let all = registry.get_all_by_kind(kind);+ if all.is_empty() {+ return true;+ }+ all.iter().any(|loaded| {+ loaded.yaml.types.iter().any(|t| {+ (t.name.eq_ignore_ascii_case(type_name) || t.aliases.iter().any(|a| a.eq_ignore_ascii_case(type_name)))+ && (t.has_length || t.has_precision || t.max_precision.is_some())+ })+ })+}+#[derive(Debug, Clone, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SchemaDiffPreparationOptions {@@ -199,6 +298,59 @@ pub struct SchemaDiffPreparationOptions {pub cascade_delete: bool,#[serde(default)]pub compare_column_order: bool,+ #[serde(default)]+ pub detect_renames: bool,+ #[serde(default)]+ pub detect_table_renames: bool,+ #[serde(default)]+ pub rename_threshold: f64,+ #[serde(default)]+ pub enable_rollback: bool,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub batch_patterns: Vec<BatchPattern>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub source_dialect: Option<DialectKind>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub target_dialect: Option<DialectKind>,+ #[serde(default)]+ pub compatibility_threshold: f64,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub source_permissions: Vec<PermissionInfo>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub target_permissions: Vec<PermissionInfo>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub shard_strategy: Option<ShardStrategy>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub resource_constraint: Option<ResourceConstraint>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub field_mappings: Vec<FieldMapping>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub struct MissingRollbackObject {+ pub kind: String,+ pub name: String,+ pub table: Option<String>,+ pub reason: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum RollbackCompleteness {+ #[serde(rename = "complete")]+ Complete,+ #[serde(rename = "incomplete")]+ Incomplete,+}++impl RollbackCompleteness {+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Complete => "complete",+ Self::Incomplete => "incomplete",+ }+ }}#[derive(Debug, Clone, Serialize, Deserialize)]@@ -214,733 +366,1120 @@ pub struct SchemaDiffPreparation {#[serde(default, skip_serializing_if = "Vec::is_empty")]pub owner_diffs: Vec<OwnerDiff>,pub sync_sql: String,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub rollback_sync_sql: Option<String>,+ /// Whether rollback SQL is complete enough to execute safely.+ #[serde(default = "default_rollback_complete")]+ pub rollback_completeness: RollbackCompleteness,+ /// Objects that could not be reconstructed for rollback (e.g. triggers without body).+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub missing_rollback_objects: Vec<MissingRollbackObject>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub rename_candidates: Vec<RenameCandidate>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub rollback_graph: Option<RollbackGraph>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub compatibility_warnings: Vec<ColumnCompatibilityWarning>,+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub permission_diffs: Vec<PermissionDiff>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub permission_sync_sql: Option<String>,+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub dependency_graph: Option<DependencyGraph>,}-pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffPreparation {- let mut diffs = diff_schema(&options);- let function_diffs = diff_functions(&options.source_functions, &options.target_functions);- let sequence_diffs = diff_sequences(&options.source_sequences, &options.target_sequences);- let rule_diffs = diff_rules(&options.source_rules, &options.target_rules);- let owner_diffs = diff_owners(&options.source_owners, &options.target_owners);- for diff in &mut diffs {- let sync_sql = generate_schema_sync_sql(- std::slice::from_ref(diff),- &[],- &[],- &[],- &[],- options.database_type,- options.target_schema.as_deref(),- options.cascade_delete,- );- if !sync_sql.is_empty() {- diff.sync_sql = Some(sync_sql);+fn default_rollback_complete() -> RollbackCompleteness {+ RollbackCompleteness::Complete+}++// ============================================================================+// Phase 4.1: Dependency Graph & Rename Detection+// ============================================================================++/// Regex-based text scanning for table references in SQL/DDL text.+/// Used as fallback when no live DB query (YAML metadata_queries.dependencies) is available.+fn extract_ddl_references(sql: &str, known_tables: &HashSet<&str>) -> Vec<String> {+ let upper = sql.to_uppercase();+ let mut refs: Vec<String> = Vec::new();++ for table in known_tables {+ let table_up = table.to_uppercase();+ // Match after SQL keywords that indicate table references+ let patterns = [+ format!(" FROM {table_up}"),+ format!(" JOIN {table_up}"),+ format!(" INTO {table_up}"),+ format!(" TABLE {table_up}"),+ format!(" REFERENCES {table_up}"),+ format!(" UPDATE {table_up}"),+ format!("DELETE FROM {table_up}"),+ format!("FROM {table_up} ("),+ format!(" {table_up}."),+ ];+ if patterns.iter().any(|p| upper.contains(p.as_str())) {+ refs.push(table.to_string());}}- let sync_sql = generate_schema_sync_sql(- &diffs,- &function_diffs,- &sequence_diffs,- &rule_diffs,- &owner_diffs,- options.database_type,- options.target_schema.as_deref(),- options.cascade_delete,- );- SchemaDiffPreparation { diffs, function_diffs, sequence_diffs, rule_diffs, owner_diffs, sync_sql }++ refs}-fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {- let source_details: HashMap<&str, &TableSchemaDetail> =- options.source_details.iter().map(|detail| (detail.name.as_str(), detail)).collect();- let target_details: HashMap<&str, &TableSchemaDetail> =- options.target_details.iter().map(|detail| (detail.name.as_str(), detail)).collect();- let source_table_comments: HashMap<&str, Option<String>> =- options.source_tables.iter().map(|table| (table.name.as_str(), table.comment.clone())).collect();- let target_table_comments: HashMap<&str, Option<String>> =- options.target_tables.iter().map(|table| (table.name.as_str(), table.comment.clone())).collect();+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DependencyNode {+ pub table_name: String,+ pub depends_on: Vec<String>,+ pub depended_by: Vec<String>,+}- let source_table_names: Vec<String> = options- .source_tables- .iter()- .filter(|table| !table.table_type.contains("VIEW"))- .map(|table| table.name.clone())- .collect();- let target_table_names: Vec<String> = options- .target_tables- .iter()- .filter(|table| !table.table_type.contains("VIEW"))- .map(|table| table.name.clone())- .collect();- let source_view_names: Vec<String> = options- .source_tables- .iter()- .filter(|table| table.table_type.contains("VIEW"))- .map(|table| table.name.clone())- .collect();- let target_view_names: Vec<String> = options- .target_tables- .iter()- .filter(|table| table.table_type.contains("VIEW"))- .map(|table| table.name.clone())- .collect();+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DependencyGraph {+ pub nodes: HashMap<String, DependencyNode>,+ pub topological_order: Vec<String>,+}- let (added, removed, common) = diff_names(&source_table_names, &target_table_names);- let (added_views, removed_views, _) = diff_names(&source_view_names, &target_view_names);- let mut result = Vec::new();+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct CoverageReport {+ pub level1_score: f64,+ pub level2_score: f64,+ pub composite_score: f64,+ pub level1_covered: u64,+ pub level1_total: u64,+ pub level2_covered: u64,+ pub level2_total: u64,+ pub uncovered_edges: Vec<UncoveredEdge>,+}- for name in added {- result.push(TableDiff {- diff_type: "added".to_string(),- object_type: Some("table".to_string()),- ddl: source_details.get(name.as_str()).and_then(|detail| detail.ddl.clone()),- target_ddl: None,- name,- columns: None,- indexes: None,- foreign_keys: None,- triggers: None,- source_table_comment: None,- target_table_comment: None,- sync_sql: None,- });+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct UncoveredEdge {+ pub from_table: String,+ pub to_table: String,+ pub level: u32,+}++impl DependencyGraph {+ pub fn build(details: &[TableSchemaDetail], tables: &[TableInfo]) -> Self {+ Self::build_with_functions(details, tables, &[], &[])}- for name in removed {- let name_clone = name.clone();- result.push(TableDiff {- diff_type: "removed".to_string(),- object_type: Some("table".to_string()),- name,- columns: None,- indexes: None,- foreign_keys: None,- triggers: None,- ddl: None,- target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),- source_table_comment: None,- target_table_comment: None,- sync_sql: None,- });+ /// Extended build: also extracts dependencies from view DDLs, triggers, and function/sequence definitions.+ /// Falls back to regex-based text scanning when no live DB query is available.+ pub fn build_with_functions(+ details: &[TableSchemaDetail],+ tables: &[TableInfo],+ functions: &[FunctionInfo],+ _sequences: &[SequenceInfo],+ ) -> Self {+ let table_names: HashSet<&str> =+ tables.iter().filter(|t| !t.table_type.contains("VIEW")).map(|t| t.name.as_str()).collect();+ let view_names: HashSet<&str> =+ tables.iter().filter(|t| t.table_type.contains("VIEW")).map(|t| t.name.as_str()).collect();+ let all_names: HashSet<&str> = tables.iter().map(|t| t.name.as_str()).collect();++ let mut nodes: HashMap<String, DependencyNode> = all_names+ .iter()+ .map(|name| {+ (+ name.to_string(),+ DependencyNode { table_name: name.to_string(), depends_on: Vec::new(), depended_by: Vec::new() },+ )+ })+ .collect();++ let detail_map: HashMap<&str, &TableSchemaDetail> = details.iter().map(|d| (d.name.as_str(), d)).collect();+ let function_by_name: HashMap<&str, &FunctionInfo> = functions.iter().map(|f| (f.name.as_str(), f)).collect();++ // Phase 1: FK-based dependencies (existing logic)+ for table_name in &table_names {+ if let Some(detail) = detail_map.get(table_name) {+ for fk in &detail.foreign_keys {+ if table_names.contains(fk.ref_table.as_str()) {+ if let Some(node) = nodes.get_mut(*table_name) {+ if !node.depends_on.contains(&fk.ref_table) {+ node.depends_on.push(fk.ref_table.clone());+ }+ }+ if let Some(ref_node) = nodes.get_mut(&fk.ref_table) {+ if !ref_node.depended_by.iter().any(|d| d == *table_name) {+ ref_node.depended_by.push((*table_name).to_string());+ }+ }+ }+ }+ }+ }++ // Phase 2: View DDL text scanning+ for view_name in &view_names {+ if let Some(detail) = detail_map.get(view_name) {+ if let Some(ddl) = &detail.ddl {+ let refs = extract_ddl_references(ddl, &table_names);+ for ref_table in refs {+ if let Some(node) = nodes.get_mut(*view_name) {+ if !node.depends_on.contains(&ref_table) {+ node.depends_on.push(ref_table.clone());+ }+ }+ if let Some(ref_node) = nodes.get_mut(&ref_table) {+ if !ref_node.depended_by.iter().any(|d| d == *view_name) {+ ref_node.depended_by.push((*view_name).to_string());+ }+ }+ }+ }+ }+ }++ // Phase 3: Trigger statement text scanning+ for table_name in &all_names {+ if let Some(detail) = detail_map.get(table_name) {+ for trigger in &detail.triggers {+ if let Some(stmt) = &trigger.statement {+ let refs = extract_ddl_references(stmt, &table_names);+ for ref_table in refs {+ if let Some(node) = nodes.get_mut(*table_name) {+ if !node.depends_on.contains(&ref_table) {+ node.depends_on.push(ref_table.clone());+ }+ }+ if let Some(ref_node) = nodes.get_mut(&ref_table) {+ if !ref_node.depended_by.iter().any(|d| d == *table_name) {+ ref_node.depended_by.push((*table_name).to_string());+ }+ }+ }+ }+ }+ }+ }++ // Phase 4: Function definition text scanning+ for (_func_name, func) in &function_by_name {+ let refs = extract_ddl_references(&func.definition, &table_names);+ for ref_table in &refs {+ if let Some(ref_node) = nodes.get_mut(ref_table) {+ if !ref_node.depended_by.iter().any(|d| d == _func_name) {+ ref_node.depended_by.push(_func_name.to_string());+ }+ }+ }+ }++ let topological_order = Self::topological_sort(&nodes);+ DependencyGraph { nodes, topological_order }}- for name in added_views {- let name_clone = name.clone();- result.push(TableDiff {- diff_type: "added".to_string(),- object_type: Some("view".to_string()),- name,- columns: None,- indexes: None,- foreign_keys: None,- triggers: None,- ddl: source_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),- target_ddl: None,- source_table_comment: None,- target_table_comment: None,- sync_sql: None,- });+ fn topological_sort(nodes: &HashMap<String, DependencyNode>) -> Vec<String> {+ let mut in_degree: HashMap<&str, usize> = nodes.keys().map(|k| (k.as_str(), 0usize)).collect();+ for node in nodes.values() {+ in_degree.entry(node.table_name.as_str()).or_insert(0);+ for _dep in &node.depends_on {+ *in_degree.entry(node.table_name.as_str()).or_insert(0) += 1;+ }+ }++ let mut queue: VecDeque<&str> = in_degree.iter().filter(|(_, °)| deg == 0).map(|(&name, _)| name).collect();++ let mut result = Vec::new();+ while let Some(name) = queue.pop_front() {+ result.push(name.to_string());+ if let Some(node) = nodes.get(name) {+ for dependent in &node.depended_by {+ if let Some(deg) = in_degree.get_mut(dependent.as_str()) {+ *deg -= 1;+ if *deg == 0 {+ queue.push_back(dependent.as_str());+ }+ }+ }+ }+ }++ if result.len() != nodes.len() {+ let remaining: Vec<String> = nodes.keys().filter(|k| !result.contains(k)).cloned().collect();+ result.extend(remaining);+ }++ result}- for name in removed_views {- let name_clone = name.clone();- result.push(TableDiff {- diff_type: "removed".to_string(),- object_type: Some("view".to_string()),- name,- columns: None,- indexes: None,- foreign_keys: None,- triggers: None,- ddl: None,- target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),- source_table_comment: None,- target_table_comment: None,- sync_sql: None,- });+ pub fn build_order(&self) -> Vec<String> {+ self.topological_order.clone()}- for name in common {- let Some(source) = source_details.get(name.as_str()) else { continue };- let Some(target) = target_details.get(name.as_str()) else { continue };- let column_diffs = diff_columns_with_options(- &source.columns,- &target.columns,- ColumnDiffOptions {- ignore_comments: options.ignore_comments,- compare_column_order: options.compare_column_order,- case_insensitive_names: column_names_are_case_insensitive(options.database_type),- },- );- let index_diffs = diff_indexes(&source.indexes, &target.indexes);- let foreign_key_diffs = diff_foreign_keys(&source.foreign_keys, &target.foreign_keys);- let trigger_diffs = diff_triggers(&source.triggers, &target.triggers);- let source_comment = source_table_comments.get(name.as_str()).cloned().unwrap_or(None);- let target_comment = target_table_comments.get(name.as_str()).cloned().unwrap_or(None);- let comment_changed = !options.ignore_comments- && source_comment.clone().unwrap_or_default() != target_comment.clone().unwrap_or_default();-- let has_diff = !column_diffs.is_empty()- || !index_diffs.is_empty()- || !foreign_key_diffs.is_empty()- || !trigger_diffs.is_empty()- || comment_changed;-- let name_clone = name.clone();- result.push(TableDiff {- diff_type: if has_diff { "modified".to_string() } else { "none".to_string() },- object_type: Some("table".to_string()),- name,- columns: if has_diff { (!column_diffs.is_empty()).then_some(column_diffs) } else { None },- indexes: if has_diff { (!index_diffs.is_empty()).then_some(index_diffs) } else { None },- foreign_keys: if has_diff { (!foreign_key_diffs.is_empty()).then_some(foreign_key_diffs) } else { None },- triggers: if has_diff { (!trigger_diffs.is_empty()).then_some(trigger_diffs) } else { None },- ddl: source_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),- target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),- source_table_comment: if has_diff { comment_changed.then_some(source_comment) } else { None },- target_table_comment: if has_diff { comment_changed.then_some(target_comment) } else { None },- sync_sql: None,- });+ pub fn drop_order(&self) -> Vec<String> {+ let mut order = self.topological_order.clone();+ order.reverse();+ order}- result.retain(|diff| diff.diff_type != "none");- result-}+ pub fn coverage_score(&self, diffed_tables: &[String]) -> f64 {+ self.coverage_score_level1(diffed_tables)+ }-fn diff_names(source: &[String], target: &[String]) -> (Vec<String>, Vec<String>, Vec<String>) {- let source_set: HashSet<&str> = source.iter().map(String::as_str).collect();- let target_set: HashSet<&str> = target.iter().map(String::as_str).collect();- (- source.iter().filter(|name| !target_set.contains(name.as_str())).cloned().collect(),- target.iter().filter(|name| !source_set.contains(name.as_str())).cloned().collect(),- source.iter().filter(|name| target_set.contains(name.as_str())).cloned().collect(),- )-}+ pub fn coverage_score_level1(&self, diffed_tables: &[String]) -> f64 {+ if self.nodes.is_empty() {+ return 1.0;+ }+ let diffed_set: HashSet<&str> = diffed_tables.iter().map(|s| s.as_str()).collect();+ let mut covered_edges = 0u64;+ let mut total_edges = 0u64;++ for node in self.nodes.values() {+ for dep in &node.depends_on {+ total_edges += 1;+ if diffed_set.contains(node.table_name.as_str()) && diffed_set.contains(dep.as_str()) {+ covered_edges += 1;+ }+ }+ }-pub fn diff_columns(source: &[ColumnInfo], target: &[ColumnInfo]) -> Vec<ColumnDiff> {- diff_columns_with_options(source, target, ColumnDiffOptions::default())-}+ if total_edges == 0 {+ 1.0+ } else {+ covered_edges as f64 / total_edges as f64+ }+ }-#[derive(Debug, Clone, Copy, Default)]-struct ColumnDiffOptions {- ignore_comments: bool,- compare_column_order: bool,- case_insensitive_names: bool,-}+ pub fn coverage_score_level2(&self, diffed_tables: &[String]) -> f64 {+ if self.nodes.is_empty() {+ return 1.0;+ }+ let diffed_set: HashSet<&str> = diffed_tables.iter().map(|s| s.as_str()).collect();-fn diff_columns_with_options(- source: &[ColumnInfo],- target: &[ColumnInfo],- options: ColumnDiffOptions,-) -> Vec<ColumnDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<String, &ColumnInfo> = target- .iter()- .map(|column| (column_name_match_key(&column.name, options.case_insensitive_names), column))- .collect();- let source_map: HashMap<String, &ColumnInfo> = source- .iter()- .map(|column| (column_name_match_key(&column.name, options.case_insensitive_names), column))- .collect();- let target_position_map: HashMap<&str, usize> =- target.iter().enumerate().map(|(index, column)| (column.name.as_str(), index)).collect();- let target_normalized_position_map: HashMap<String, usize> = target- .iter()- .enumerate()- .map(|(index, column)| (column_name_match_key(&column.name, options.case_insensitive_names), index))- .collect();- let can_compare_order = options.compare_column_order- && source.len() == target.len()- && source.iter().all(|column| {- target_map.contains_key(&column_name_match_key(&column.name, options.case_insensitive_names))- });+ let mut transitive_edges = 0u64;+ let mut covered_transitive = 0u64;- for (source_index, source_column) in source.iter().enumerate() {- let source_name_key = column_name_match_key(&source_column.name, options.case_insensitive_names);- if let Some(target_column) = target_map.get(&source_name_key) {- let mut changes = Vec::new();- if options.case_insensitive_names && source_column.name != target_column.name {- changes.push(format!("name: {} → {}", target_column.name, source_column.name));- }- if source_column.data_type.to_lowercase() != target_column.data_type.to_lowercase() {- changes.push(format!("type: {} → {}", target_column.data_type, source_column.data_type));+ for node in self.nodes.values() {+ let table_name = node.table_name.as_str();+ if !diffed_set.contains(table_name) {+ continue;}- if source_column.is_nullable != target_column.is_nullable {- changes.push(format!(- "nullable: {} → {}",- if target_column.is_nullable { "YES" } else { "NO" },- if source_column.is_nullable { "YES" } else { "NO" }- ));+ for indirect in &node.depends_on {+ if let Some(inner) = self.nodes.get(indirect) {+ for grand in &inner.depends_on {+ transitive_edges += 1;+ if diffed_set.contains(table_name) && diffed_set.contains(grand.as_str()) {+ covered_transitive += 1;+ }+ }+ }}- if source_column.column_default.as_deref().unwrap_or_default()- != target_column.column_default.as_deref().unwrap_or_default()- {- changes.push(format!(- "default: {} → {}",- target_column.column_default.as_deref().unwrap_or("NULL"),- source_column.column_default.as_deref().unwrap_or("NULL")- ));+ }++ if transitive_edges == 0 {+ 1.0+ } else {+ covered_transitive as f64 / transitive_edges as f64+ }+ }++ pub fn composite_coverage_score(&self, diffed_tables: &[String]) -> CoverageReport {+ let diffed_set: HashSet<&str> = diffed_tables.iter().map(|s| s.as_str()).collect();++ let (l1_covered, l1_total) = self.count_edges(diffed_tables, &diffed_set, 1);+ let (l2_covered, l2_total) = self.count_transitive_edges(diffed_tables, &diffed_set);++ let l1_score = if l1_total == 0 { 1.0 } else { l1_covered as f64 / l1_total as f64 };+ let l2_score = if l2_total == 0 { 1.0 } else { l2_covered as f64 / l2_total as f64 };++ let composite_score = 0.6 * l1_score + 0.4 * l2_score;++ let uncovered = self.collect_uncovered_edges(diffed_tables, &diffed_set);++ CoverageReport {+ level1_score: l1_score,+ level2_score: l2_score,+ composite_score,+ level1_covered: l1_covered,+ level1_total: l1_total,+ level2_covered: l2_covered,+ level2_total: l2_total,+ uncovered_edges: uncovered,+ }+ }++ fn count_edges(&self, _diffed_tables: &[String], diffed_set: &HashSet<&str>, _level: u32) -> (u64, u64) {+ let mut covered = 0u64;+ let mut total = 0u64;+ for node in self.nodes.values() {+ for dep in &node.depends_on {+ total += 1;+ if diffed_set.contains(node.table_name.as_str()) && diffed_set.contains(dep.as_str()) {+ covered += 1;+ }}- if !options.ignore_comments- && source_column.comment.as_deref().unwrap_or_default()- != target_column.comment.as_deref().unwrap_or_default()- {- changes.push(format!(- "comment: {} → {}",- target_column.comment.as_deref().unwrap_or_default(),- source_column.comment.as_deref().unwrap_or_default()- ));+ }+ (covered, total)+ }++ fn count_transitive_edges(&self, _diffed_tables: &[String], diffed_set: &HashSet<&str>) -> (u64, u64) {+ let mut covered = 0u64;+ let mut total = 0u64;+ for node in self.nodes.values() {+ let table_name = node.table_name.as_str();+ if !diffed_set.contains(table_name) {+ continue;}- if can_compare_order {- let target_index = if options.case_insensitive_names {- target_normalized_position_map.get(&source_name_key)- } else {- target_position_map.get(source_column.name.as_str())- };- if let Some(target_index) = target_index {- if source_index != *target_index {- changes.push(format!("order: {} → {}", *target_index + 1, source_index + 1));+ for indirect in &node.depends_on {+ if let Some(inner) = self.nodes.get(indirect) {+ for grand in &inner.depends_on {+ total += 1;+ if diffed_set.contains(table_name) && diffed_set.contains(grand.as_str()) {+ covered += 1;+ }}}}- if !changes.is_empty() {- diffs.push(ColumnDiff {- diff_type: "modified".to_string(),- name: source_column.name.clone(),- source: Some(source_column.clone()),- target: Some((*target_column).clone()),- changes,- });- }- } else {- diffs.push(ColumnDiff {- diff_type: "added".to_string(),- name: source_column.name.clone(),- source: Some(source_column.clone()),- target: None,- changes: Vec::new(),- });}+ (covered, total)}- for target_column in target {- if !source_map.contains_key(&column_name_match_key(&target_column.name, options.case_insensitive_names)) {- diffs.push(ColumnDiff {- diff_type: "removed".to_string(),- name: target_column.name.clone(),- source: None,- target: Some(target_column.clone()),- changes: Vec::new(),- });+ fn collect_uncovered_edges(&self, _diffed_tables: &[String], diffed_set: &HashSet<&str>) -> Vec<UncoveredEdge> {+ let mut uncovered = Vec::new();+ for node in self.nodes.values() {+ for dep in &node.depends_on {+ let both_covered = diffed_set.contains(node.table_name.as_str()) && diffed_set.contains(dep.as_str());+ if !both_covered {+ uncovered.push(UncoveredEdge {+ from_table: node.table_name.clone(),+ to_table: dep.clone(),+ level: 1,+ });+ }+ }+ for indirect in &node.depends_on {+ if let Some(inner) = self.nodes.get(indirect) {+ for grand in &inner.depends_on {+ let all_covered =+ diffed_set.contains(node.table_name.as_str()) && diffed_set.contains(grand.as_str());+ if !all_covered {+ uncovered.push(UncoveredEdge {+ from_table: node.table_name.clone(),+ to_table: grand.clone(),+ level: 2,+ });+ }+ }+ }+ }}+ uncovered}+}- diffs+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RenameCandidate {+ pub source_name: String,+ pub target_name: String,+ pub score: f64,+ pub column_jaccard: f64,+ pub type_similarity: f64,}-fn column_name_match_key(name: &str, case_insensitive: bool) -> String {- if case_insensitive {- name.to_ascii_lowercase()+fn jaccard_similarity(a: &HashSet<String>, b: &HashSet<String>) -> f64 {+ if a.is_empty() && b.is_empty() {+ return 1.0;+ }+ let intersection = a.intersection(b).count();+ let union = a.union(b).count();+ if union == 0 {+ 1.0} else {- name.to_string()+ intersection as f64 / union as f64}}-fn column_names_are_case_insensitive(db_type: DatabaseType) -> bool {- // MySQL documents column identifiers as case-insensitive on every platform; exact matching would turn- // a case-only rename into a destructive add/drop plan.- matches!(db_type, DatabaseType::Mysql)+fn column_type_similarity(source_cols: &[ColumnInfo], target_cols: &[ColumnInfo]) -> f64 {+ if source_cols.is_empty() || target_cols.is_empty() {+ return 0.0;+ }+ let engine = DefaultTypeInferenceEngine;+ let source_map: HashMap<&str, &ColumnInfo> = source_cols.iter().map(|c| (c.name.as_str(), c)).collect();+ let target_map: HashMap<&str, &ColumnInfo> = target_cols.iter().map(|c| (c.name.as_str(), c)).collect();+ let common_names: HashSet<&str> = source_map.keys().filter(|k| target_map.contains_key(**k)).copied().collect();++ if common_names.is_empty() {+ return 0.0;+ }++ let total: f64 = common_names+ .iter()+ .map(|name| {+ let s = ColumnType::parse(&source_map[name].data_type);+ let t = ColumnType::parse(&target_map[name].data_type);+ engine.type_compatibility_score(&s, &t)+ })+ .sum();+ total / common_names.len() as f64}-pub fn diff_indexes(source: &[IndexInfo], target: &[IndexInfo]) -> Vec<IndexDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<&str, &IndexInfo> = target.iter().map(|index| (index.name.as_str(), index)).collect();- let source_map: HashMap<&str, &IndexInfo> = source.iter().map(|index| (index.name.as_str(), index)).collect();+pub fn detect_renames(+ removed: &[String],+ added: &[String],+ source_details: &[TableSchemaDetail],+ target_details: &[TableSchemaDetail],+ threshold: f64,+) -> Vec<RenameCandidate> {+ let source_detail_map: HashMap<&str, &TableSchemaDetail> =+ source_details.iter().map(|d| (d.name.as_str(), d)).collect();+ let target_detail_map: HashMap<&str, &TableSchemaDetail> =+ target_details.iter().map(|d| (d.name.as_str(), d)).collect();++ let mut candidates = Vec::new();+ for target_name in removed {+ let Some(target_detail) = target_detail_map.get(target_name.as_str()) else { continue };+ for source_name in added {+ let Some(source_detail) = source_detail_map.get(source_name.as_str()) else { continue };++ let col_names_source: HashSet<String> = source_detail.columns.iter().map(|c| c.name.clone()).collect();+ let col_names_target: HashSet<String> = target_detail.columns.iter().map(|c| c.name.clone()).collect();+ let column_jaccard = jaccard_similarity(&col_names_target, &col_names_source);++ if column_jaccard < threshold {+ continue;+ }- for source_index in source {- if source_index.is_primary {- continue;- }- let Some(target_index) = target_map.get(source_index.name.as_str()) else {- diffs.push(IndexDiff {- diff_type: "added".to_string(),- name: source_index.name.clone(),- source: Some(source_index.clone()),- target: None,- changes: Vec::new(),- });- continue;- };+ let type_sim = column_type_similarity(&target_detail.columns, &source_detail.columns);- let mut changes = Vec::new();- if source_index.is_unique != target_index.is_unique {- changes.push(format!(- "unique: {} → {}",- if target_index.is_unique { "YES" } else { "NO" },- if source_index.is_unique { "YES" } else { "NO" }- ));- }- if source_index.columns.join(",") != target_index.columns.join(",") {- changes.push(format!("columns: {} → {}", target_index.columns.join(", "), source_index.columns.join(", ")));- }- if source_index.index_type.as_deref().unwrap_or_default()- != target_index.index_type.as_deref().unwrap_or_default()- {- changes.push(format!(- "type: {} → {}",- target_index.index_type.as_deref().unwrap_or("default"),- source_index.index_type.as_deref().unwrap_or("default")- ));- }- if source_index.filter.as_deref().unwrap_or_default() != target_index.filter.as_deref().unwrap_or_default() {- changes.push(format!(- "filter: {} → {}",- target_index.filter.as_deref().unwrap_or("none"),- source_index.filter.as_deref().unwrap_or("none")- ));- }- let source_included = source_index.included_columns.clone().unwrap_or_default();- let target_included = target_index.included_columns.clone().unwrap_or_default();- if source_included.join(",") != target_included.join(",") {- changes.push(format!(- "include: {} → {}",- if target_included.is_empty() { "none".to_string() } else { target_included.join(", ") },- if source_included.is_empty() { "none".to_string() } else { source_included.join(", ") }- ));- }- if !changes.is_empty() {- diffs.push(IndexDiff {- diff_type: "modified".to_string(),- name: source_index.name.clone(),- source: Some(source_index.clone()),- target: Some((*target_index).clone()),- changes,- });+ let score = column_jaccard * 0.6 + type_sim * 0.4;++ if score >= threshold {+ candidates.push(RenameCandidate {+ source_name: source_name.clone(),+ target_name: target_name.clone(),+ score,+ column_jaccard,+ type_similarity: type_sim,+ });+ }}}- for target_index in target {- if target_index.is_primary {- continue;- }- if !source_map.contains_key(target_index.name.as_str()) {- diffs.push(IndexDiff {- diff_type: "removed".to_string(),- name: target_index.name.clone(),- source: None,- target: Some(target_index.clone()),- changes: Vec::new(),- });+ candidates.sort_by(|a, b| b.score.partial_cmp(&a.score).unwrap_or(std::cmp::Ordering::Equal));++ let mut final_candidates = Vec::new();+ let mut used_target: HashSet<String> = HashSet::new();+ let mut used_source: HashSet<String> = HashSet::new();++ for c in &candidates {+ if !used_target.contains(&c.target_name) && !used_source.contains(&c.source_name) {+ final_candidates.push(c.clone());+ used_target.insert(c.target_name.clone());+ used_source.insert(c.source_name.clone());}}- diffs+ final_candidates}-pub fn diff_foreign_keys(source: &[ForeignKeyInfo], target: &[ForeignKeyInfo]) -> Vec<ForeignKeyDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<&str, &ForeignKeyInfo> = target.iter().map(|fk| (fk.name.as_str(), fk)).collect();- let source_map: HashMap<&str, &ForeignKeyInfo> = source.iter().map(|fk| (fk.name.as_str(), fk)).collect();+// ============================================================================+// Phase 4.2: Batch Naming Pattern Recognition+// ============================================================================- for source_fk in source {- let Some(target_fk) = target_map.get(source_fk.name.as_str()) else {- diffs.push(ForeignKeyDiff {- diff_type: "added".to_string(),- name: source_fk.name.clone(),- source: Some(source_fk.clone()),- target: None,- changes: Vec::new(),- });- continue;- };+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct BatchPattern {+ pub pattern: String,+ pub is_regex: bool,+ pub description: String,+}- let mut changes = Vec::new();- if source_fk.column != target_fk.column {- changes.push(format!("column: {} → {}", target_fk.column, source_fk.column));- }- if source_fk.ref_table != target_fk.ref_table {- changes.push(format!("ref table: {} → {}", target_fk.ref_table, source_fk.ref_table));- }- if source_fk.ref_schema != target_fk.ref_schema {- changes.push(format!(- "ref schema: {} → {}",- target_fk.ref_schema.as_deref().unwrap_or(""),- source_fk.ref_schema.as_deref().unwrap_or("")- ));- }- if source_fk.ref_column != target_fk.ref_column {- changes.push(format!("ref column: {} → {}", target_fk.ref_column, source_fk.ref_column));+pub fn diff_names_with_patterns(+ source: &[String],+ target: &[String],+ patterns: &[BatchPattern],+) -> (Vec<String>, Vec<String>, Vec<String>, Vec<Vec<String>>) {+ let (added, removed, common) = diff_names(source, target);++ let mut pattern_matches: Vec<Vec<String>> = Vec::new();+ for pattern in patterns {+ let mut matches = Vec::new();+ if pattern.is_regex {+ if let Ok(re) = Regex::new(&pattern.pattern) {+ for name in source {+ if re.is_match(name) {+ matches.push(name.clone());+ }+ }+ }+ } else {+ let glob_pattern = pattern.pattern.replace('*', ".*").replace('?', ".");+ if let Ok(re) = Regex::new(&format!("^{}$", glob_pattern)) {+ for name in source {+ if re.is_match(name) {+ matches.push(name.clone());+ }+ }+ }}- if !changes.is_empty() {- diffs.push(ForeignKeyDiff {- diff_type: "modified".to_string(),- name: source_fk.name.clone(),- source: Some(source_fk.clone()),- target: Some((*target_fk).clone()),- changes,- });+ if !matches.is_empty() {+ pattern_matches.push(matches);}}- for target_fk in target {- if !source_map.contains_key(target_fk.name.as_str()) {- diffs.push(ForeignKeyDiff {- diff_type: "removed".to_string(),- name: target_fk.name.clone(),- source: None,- target: Some(target_fk.clone()),- changes: Vec::new(),- });+ (added, removed, common, pattern_matches)+}++pub fn detect_pattern_conflicts(patterns: &[BatchPattern], names: &[String]) -> Vec<Vec<String>> {+ let mut conflicts = Vec::new();+ for i in 0..patterns.len() {+ for j in (i + 1)..patterns.len() {+ let pi = &patterns[i];+ let pj = &patterns[j];+ let pattern_i =+ if pi.is_regex { pi.pattern.clone() } else { pi.pattern.replace('*', ".*").replace('?', ".") };+ let pattern_j =+ if pj.is_regex { pj.pattern.clone() } else { pj.pattern.replace('*', ".*").replace('?', ".") };++ let re_i = Regex::new(&format!("^{}$", pattern_i));+ let re_j = Regex::new(&format!("^{}$", pattern_j));+ if let (Ok(ri), Ok(rj)) = (re_i, re_j) {+ for name in names {+ if ri.is_match(name) && rj.is_match(name) {+ conflicts.push(vec![pi.description.clone(), pj.description.clone()]);+ break;+ }+ }+ }}}-- diffs+ conflicts}-pub fn diff_triggers(source: &[TriggerInfo], target: &[TriggerInfo]) -> Vec<TriggerDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<&str, &TriggerInfo> =- target.iter().map(|trigger| (trigger.name.as_str(), trigger)).collect();- let source_map: HashMap<&str, &TriggerInfo> =- source.iter().map(|trigger| (trigger.name.as_str(), trigger)).collect();+// ============================================================================+// Phase 4.3: Dialect-Aware Type Compatibility Scoring+// ============================================================================- for source_trigger in source {- let Some(target_trigger) = target_map.get(source_trigger.name.as_str()) else {- diffs.push(TriggerDiff {- diff_type: "added".to_string(),- name: source_trigger.name.clone(),- source: Some(source_trigger.clone()),- target: None,- changes: Vec::new(),- });- continue;- };+pub fn diff_columns_with_compatibility(+ source: &[ColumnInfo],+ target: &[ColumnInfo],+ ignore_comments: bool,+ compare_column_order: bool,+ source_dialect: DialectKind,+ target_dialect: DialectKind,+ compatibility_threshold: f64,+ field_mappings: &[FieldMapping],+) -> (Vec<ColumnDiff>, Vec<ColumnCompatibilityWarning>) {+ use crate::sql_dialect::descriptor::TypeMappingMatrix;++ let matrix = TypeMappingMatrix::for_dialects(source_dialect, target_dialect);+ let engine = DefaultTypeInferenceEngine;++ let basic_diffs = diff_columns_with_options(source, target, ignore_comments, compare_column_order, false, 0.5);++ let mut warnings = Vec::new();+ let mut enhanced_diffs = Vec::new();++ for diff in basic_diffs {+ let mut warning = None;++ if diff.diff_type == "modified" {+ if let (Some(src), Some(tgt)) = (&diff.source, &diff.target) {+ let src_parsed = ColumnType::parse(&src.data_type);+ let tgt_parsed = ColumnType::parse(&tgt.data_type);+ let compatibility = engine.type_compatibility_score(&src_parsed, &tgt_parsed);++ let (mapped_type, requires_cast) = if let Some(user_target) =+ FieldMapping::apply_with_params(field_mappings, &src.data_type, target_dialect)+ {+ (user_target, false)+ } else {+ matrix.convert_type(&tgt.data_type)+ };- let mut changes = Vec::new();- if source_trigger.event != target_trigger.event {- changes.push(format!("event: {} → {}", target_trigger.event, source_trigger.event));- }- if source_trigger.timing != target_trigger.timing {- changes.push(format!("timing: {} → {}", target_trigger.timing, source_trigger.timing));- }- if !changes.is_empty() {- diffs.push(TriggerDiff {- diff_type: "modified".to_string(),- name: source_trigger.name.clone(),- source: Some(source_trigger.clone()),- target: Some((*target_trigger).clone()),- changes,- });+ let risk = if compatibility >= 0.9 {+ ColumnConversionRisk::None+ } else if compatibility >= 0.7 {+ ColumnConversionRisk::Low+ } else if compatibility >= 0.5 {+ ColumnConversionRisk::Medium+ } else {+ ColumnConversionRisk::High+ };++ if compatibility < compatibility_threshold {+ warning = Some(ColumnCompatibilityWarning {+ column_name: diff.name.clone(),+ source_type: src.data_type.clone(),+ target_type: tgt.data_type.clone(),+ compatibility_score: compatibility,+ suggested_mapping: mapped_type,+ requires_cast,+ risk,+ });+ }+ }}- }- for target_trigger in target {- if !source_map.contains_key(target_trigger.name.as_str()) {- diffs.push(TriggerDiff {- diff_type: "removed".to_string(),- name: target_trigger.name.clone(),- source: None,- target: Some(target_trigger.clone()),- changes: Vec::new(),- });+ enhanced_diffs.push(diff);+ if let Some(w) = warning {+ warnings.push(w);}}- diffs+ (enhanced_diffs, warnings)}-fn is_mysql_like(db_type: DatabaseType) -> bool {- matches!(- db_type,- DatabaseType::Mysql- | DatabaseType::Doris- | DatabaseType::StarRocks- | DatabaseType::Goldendb- | DatabaseType::Sundb- | DatabaseType::Databend- | DatabaseType::Gbase- )+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ColumnCompatibilityWarning {+ pub column_name: String,+ pub source_type: String,+ pub target_type: String,+ pub compatibility_score: f64,+ pub suggested_mapping: String,+ pub requires_cast: bool,+ pub risk: ColumnConversionRisk,}-/// Normalize a function definition for comparison by:-/// - Converting CRLF to LF-/// - Collapsing all whitespace (tabs, multiple spaces) to single spaces-/// - Trimming each line and rejoining-fn normalize_definition(def: &str) -> String {- def.replace("\r\n", "\n")- .split('\n')- .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))- .collect::<Vec<_>>()- .join("\n")+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum ColumnConversionRisk {+ None,+ Low,+ Medium,+ High,}-pub fn diff_functions(source: &[FunctionInfo], target: &[FunctionInfo]) -> Vec<FunctionDiff> {- let mut diffs = Vec::new();- // Use (name, arguments) as key to support PostgreSQL function overloading- let target_map: HashMap<(&str, &str), &FunctionInfo> =- target.iter().map(|f| ((f.name.as_str(), f.arguments.as_str()), f)).collect();- let source_map: HashMap<(&str, &str), &FunctionInfo> =- source.iter().map(|f| ((f.name.as_str(), f.arguments.as_str()), f)).collect();+// ============================================================================+// Phase 4.4: Bidirectional Diff & Rollback Graph+// ============================================================================- for source_fn in source {- let key = (source_fn.name.as_str(), source_fn.arguments.as_str());- let Some(target_fn) = target_map.get(&key) else {- diffs.push(FunctionDiff {- diff_type: "added".to_string(),- name: source_fn.name.clone(),- source: Some(source_fn.clone()),- target: None,- changes: Vec::new(),+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DiffNode {+ pub table_diff: TableDiff,+ pub direction: DiffDirection,+ pub dependency_order: usize,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rename_source: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rename_target: Option<String>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub rename_score: Option<f64>,+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "camelCase")]+pub enum DiffDirection {+ Forward,+ Rollback,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RollbackGraph {+ pub forward_nodes: Vec<DiffNode>,+ pub rollback_nodes: Vec<DiffNode>,+ pub is_consistent: bool,+ pub consistency_issues: Vec<String>,+}++impl RollbackGraph {+ pub fn from_forward_diffs(+ forward_diffs: &[TableDiff],+ renames: &[RenameCandidate],+ dep_graph: &DependencyGraph,+ ) -> Self {+ let mut forward_nodes = Vec::new();+ let mut rollback_nodes = Vec::new();+ let consistency_issues = Vec::new();++ let rename_map: HashMap<&str, &RenameCandidate> = renames.iter().map(|r| (r.target_name.as_str(), r)).collect();+ let rename_reverse: HashMap<&str, &str> =+ renames.iter().map(|r| (r.source_name.as_str(), r.target_name.as_str())).collect();++ let order_map: HashMap<&str, usize> =+ dep_graph.topological_order.iter().enumerate().map(|(i, name)| (name.as_str(), i)).collect();++ for diff in forward_diffs {+ let order = order_map.get(diff.name.as_str()).copied().unwrap_or(usize::MAX);++ let (rename_source, rename_target, rename_score) = if diff.diff_type == "added" {+ if let Some(rc) = rename_reverse.get(diff.name.as_str()) {+ (Some(rc.to_string()), Some(diff.name.clone()), None)+ } else {+ (None, None, None)+ }+ } else if diff.diff_type == "removed" {+ if let Some(rc) = rename_map.get(diff.name.as_str()) {+ (Some(diff.name.clone()), Some(rc.source_name.clone()), Some(rc.score))+ } else {+ (None, None, None)+ }+ } else {+ (None, None, None)+ };++ forward_nodes.push(DiffNode {+ table_diff: diff.clone(),+ direction: DiffDirection::Forward,+ dependency_order: order,+ rename_source,+ rename_target,+ rename_score,});- continue;- };- let mut changes = Vec::new();- if source_fn.function_type != target_fn.function_type {- changes.push(format!("type: {} → {}", target_fn.function_type, source_fn.function_type));+ let rollback_diff = Self::invert_diff(diff);+ rollback_nodes.push(DiffNode {+ table_diff: rollback_diff,+ direction: DiffDirection::Rollback,+ dependency_order: order,+ rename_source: None,+ rename_target: None,+ rename_score: None,+ });}- if source_fn.data_type != target_fn.data_type {- changes.push(format!("return type: {} → {}", target_fn.data_type, source_fn.data_type));++ RollbackGraph { forward_nodes, rollback_nodes, is_consistent: false, consistency_issues }+ }++ fn invert_diff_type(dt: &str) -> &str {+ match dt {+ "added" => "removed",+ "removed" => "added",+ "renamed" => "renamed",+ _ => "modified",}- if normalize_definition(&source_fn.definition) != normalize_definition(&target_fn.definition) {- changes.push("definition changed".to_string());+ }++ fn invert_change_string(ch: &str) -> String {+ if let Some(_pos) = ch.find(" → ") {+ let parts: Vec<&str> = ch.split(" → ").collect();+ if parts.len() == 2 {+ format!("{} → {}", parts[1], parts[0])+ } else {+ ch.to_string()+ }+ } else {+ ch.to_string()}- if !changes.is_empty() {- diffs.push(FunctionDiff {- diff_type: "modified".to_string(),- name: source_fn.name.clone(),- source: Some(source_fn.clone()),- target: Some((*target_fn).clone()),- changes,- });+ }++ fn invert_columns(cols: &[ColumnDiff]) -> Vec<ColumnDiff> {+ cols.iter()+ .map(|c| {+ let inverted_name = if c.diff_type == "renamed" {+ c.target.as_ref().map(|t| t.name.clone()).unwrap_or_else(|| c.name.clone())+ } else {+ c.name.clone()+ };+ ColumnDiff {+ diff_type: Self::invert_diff_type(&c.diff_type).to_string(),+ name: inverted_name,+ source: c.target.clone(),+ target: c.source.clone(),+ changes: c.changes.iter().map(|ch| Self::invert_change_string(ch)).collect(),+ }+ })+ .collect()+ }++ fn invert_indexes(idxs: &[IndexDiff]) -> Vec<IndexDiff> {+ idxs.iter()+ .map(|i| IndexDiff {+ diff_type: Self::invert_diff_type(&i.diff_type).to_string(),+ name: i.name.clone(),+ source: i.target.clone(),+ target: i.source.clone(),+ changes: i.changes.clone(),+ })+ .collect()+ }++ fn invert_fks(fks: &[ForeignKeyDiff]) -> Vec<ForeignKeyDiff> {+ fks.iter()+ .map(|fk| ForeignKeyDiff {+ diff_type: Self::invert_diff_type(&fk.diff_type).to_string(),+ name: fk.name.clone(),+ source: fk.target.clone(),+ target: fk.source.clone(),+ changes: fk.changes.clone(),+ })+ .collect()+ }++ fn invert_triggers(trgs: &[TriggerDiff]) -> Vec<TriggerDiff> {+ trgs.iter()+ .map(|t| TriggerDiff {+ diff_type: Self::invert_diff_type(&t.diff_type).to_string(),+ name: t.name.clone(),+ source: t.target.clone(),+ target: t.source.clone(),+ changes: t.changes.clone(),+ })+ .collect()+ }++ fn invert_diff(diff: &TableDiff) -> TableDiff {+ let inverted_type = Self::invert_diff_type(&diff.diff_type).to_string();++ let inverted_columns = diff.columns.as_ref().map(|cols| Self::invert_columns(cols));+ let inverted_indexes = diff.indexes.as_ref().map(|idxs| Self::invert_indexes(idxs));+ let inverted_fks = diff.foreign_keys.as_ref().map(|fks| Self::invert_fks(fks));+ let inverted_triggers = diff.triggers.as_ref().map(|trgs| Self::invert_triggers(trgs));++ let (source_comment, target_comment) = match inverted_type.as_str() {+ "added" => (diff.target_table_comment.clone(), diff.source_table_comment.clone()),+ "removed" => (diff.source_table_comment.clone(), diff.target_table_comment.clone()),+ _ => (diff.target_table_comment.clone(), diff.source_table_comment.clone()),+ };+ let recreates_removed_table =+ diff.diff_type == "removed" && inverted_type == "added" && diff.object_type.as_deref() == Some("table");++ TableDiff {+ diff_type: inverted_type,+ object_type: diff.object_type.clone(),+ name: diff.name.clone(),+ columns: inverted_columns,+ indexes: inverted_indexes,+ foreign_keys: inverted_fks,+ triggers: inverted_triggers,+ // Rollback recreation must use the structured snapshot first. Keep+ // native target DDL isolated as a same-target-dialect fallback.+ ddl: if recreates_removed_table { None } else { diff.target_ddl.clone() },+ target_ddl: if recreates_removed_table { diff.target_ddl.clone() } else { diff.ddl.clone() },+ source_table_comment: source_comment,+ target_table_comment: target_comment,+ sync_sql: None,}}- for target_fn in target {- let key = (target_fn.name.as_str(), target_fn.arguments.as_str());- if !source_map.contains_key(&key) {- diffs.push(FunctionDiff {- diff_type: "removed".to_string(),- name: target_fn.name.clone(),- source: None,- target: Some(target_fn.clone()),- changes: Vec::new(),+ pub fn validate_consistency(&mut self) -> bool {+ self.consistency_issues.clear();++ for fwd in &self.forward_nodes {+ let has_rollback = self.rollback_nodes.iter().any(|rbk| {+ rbk.table_diff.name == fwd.table_diff.name+ && matches!(+ (fwd.table_diff.diff_type.as_str(), rbk.table_diff.diff_type.as_str()),+ ("added", "removed") | ("removed", "added") | ("modified", "modified") | ("none", "none")+ )});++ if !has_rollback {+ self.consistency_issues.push(format!(+ "No rollback entry for forward {}: {}",+ fwd.table_diff.diff_type, fwd.table_diff.name+ ));+ }++ let rollback_of_rollback: Vec<_> = self+ .rollback_nodes+ .iter()+ .filter(|rbk| rbk.table_diff.name == fwd.table_diff.name)+ .map(|rbk| Self::invert_diff(&rbk.table_diff))+ .collect();++ for ror in &rollback_of_rollback {+ if ror.diff_type != fwd.table_diff.diff_type {+ self.consistency_issues.push(format!(+ "Forward∘Rollback mismatch for {}: forward={}, rollback∘rollback={}",+ fwd.table_diff.name, fwd.table_diff.diff_type, ror.diff_type+ ));+ }+ }}++ self.is_consistent = self.consistency_issues.is_empty();+ self.is_consistent}+}- diffs+pub fn generate_rollback_sync_sql(+ rollback_graph: &RollbackGraph,+ db_type: DatabaseType,+ schema: Option<&str>,+ cascade_delete: bool,+) -> String {+ generate_rollback_sync_sql_with_missing(rollback_graph, db_type, schema, cascade_delete).0}-pub fn diff_sequences(source: &[SequenceInfo], target: &[SequenceInfo]) -> Vec<SequenceDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<&str, &SequenceInfo> = target.iter().map(|s| (s.name.as_str(), s)).collect();- let source_map: HashMap<&str, &SequenceInfo> = source.iter().map(|s| (s.name.as_str(), s)).collect();+pub fn generate_rollback_sync_sql_with_missing(+ rollback_graph: &RollbackGraph,+ db_type: DatabaseType,+ schema: Option<&str>,+ cascade_delete: bool,+) -> (String, Vec<MissingRollbackObject>) {+ let rollback_diffs: Vec<TableDiff> = rollback_graph.rollback_nodes.iter().map(|n| n.table_diff.clone()).collect();+ generate_schema_sync_sql_inner(&rollback_diffs, &[], &[], &[], &[], db_type, schema, cascade_delete, None, &[])+}- for source_seq in source {- let Some(target_seq) = target_map.get(source_seq.name.as_str()) else {- diffs.push(SequenceDiff {- diff_type: "added".to_string(),- name: source_seq.name.clone(),- source: Some(source_seq.clone()),- target: None,- changes: Vec::new(),- });- continue;- };+// ============================================================================+// Phase 4.5: Shard-Parallel Comparison+// ============================================================================- let mut changes = Vec::new();- if source_seq.data_type != target_seq.data_type {- changes.push(format!("data_type: {} → {}", target_seq.data_type, source_seq.data_type));- }- if source_seq.start_value != target_seq.start_value {- changes.push(format!("start: {} → {}", target_seq.start_value, source_seq.start_value));- }- if source_seq.min_value != target_seq.min_value {- changes.push(format!("min: {} → {}", target_seq.min_value, source_seq.min_value));- }- if source_seq.max_value != target_seq.max_value {- changes.push(format!("max: {} → {}", target_seq.max_value, source_seq.max_value));- }- if source_seq.increment != target_seq.increment {- changes.push(format!("increment: {} → {}", target_seq.increment, source_seq.increment));- }- if source_seq.cycle != target_seq.cycle {- changes.push(format!("cycle: {} → {}", target_seq.cycle, source_seq.cycle));- }- // Only compare last_value when both sides successfully retrieved it.- // Avoid false positives when one side lacks permission (returns None).- if let (Some(s), Some(t)) = (&source_seq.last_value, &target_seq.last_value) {- if s != t {- changes.push(format!("last_value: {} → {}", t, s));+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ShardStrategy {+ pub shard_count: usize,+ pub shard_by: ShardBy,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub enum ShardBy {+ Table,+ Schema,+ RoundRobin,+}++pub fn shard_diff(options: &SchemaDiffPreparationOptions, shard_strategy: &ShardStrategy) -> Vec<TableDiff> {+ let table_count = options.source_tables.len().max(options.target_tables.len());+ let shard_count = shard_strategy.shard_count.min(table_count.max(1));++ if shard_count <= 1 {+ return diff_schema(options);+ }++ let source_table_names: Vec<&str> =+ options.source_tables.iter().filter(|t| !t.table_type.contains("VIEW")).map(|t| t.name.as_str()).collect();+ let source_view_names: Vec<&str> =+ options.source_tables.iter().filter(|t| t.table_type.contains("VIEW")).map(|t| t.name.as_str()).collect();+ let _target_table_names: Vec<&str> =+ options.target_tables.iter().filter(|t| !t.table_type.contains("VIEW")).map(|t| t.name.as_str()).collect();+ let _target_view_names: Vec<&str> =+ options.target_tables.iter().filter(|t| t.table_type.contains("VIEW")).map(|t| t.name.as_str()).collect();++ let source_all: Vec<&str> = source_table_names.iter().chain(source_view_names.iter()).copied().collect();+ let shards: Vec<Vec<&str>> = match &shard_strategy.shard_by {+ ShardBy::Table | ShardBy::RoundRobin => {+ let mut s: Vec<Vec<&str>> = vec![Vec::new(); shard_count];+ for (i, name) in source_all.iter().enumerate() {+ s[i % shard_count].push(*name);}+ s}- if !changes.is_empty() {- diffs.push(SequenceDiff {- diff_type: "modified".to_string(),- name: source_seq.name.clone(),- source: Some(source_seq.clone()),- target: Some((*target_seq).clone()),- changes,- });+ ShardBy::Schema => {+ let mut schema_groups: HashMap<&str, Vec<&str>> = HashMap::new();+ for table in &options.source_tables {+ let schema = table.parent_schema.as_deref().unwrap_or("default");+ schema_groups.entry(schema).or_default().push(table.name.as_str());+ }+ let mut s: Vec<Vec<&str>> = vec![Vec::new(); shard_count];+ for (i, (_schema, names)) in schema_groups.iter().enumerate() {+ s[i % shard_count].extend(names);+ }+ s}- }+ };- for target_seq in target {- if !source_map.contains_key(target_seq.name.as_str()) {- diffs.push(SequenceDiff {- diff_type: "removed".to_string(),- name: target_seq.name.clone(),- source: None,- target: Some(target_seq.clone()),- changes: Vec::new(),- });- }+ let shard_results: Vec<Vec<TableDiff>> = shards+ .par_iter()+ .filter(|shard| !shard.is_empty())+ .map(|shard| {+ let shard_set: HashSet<&str> = shard.iter().copied().collect();+ let shard_options = SchemaDiffPreparationOptions {+ source_tables: options+ .source_tables+ .iter()+ .filter(|t| shard_set.contains(t.name.as_str()))+ .cloned()+ .collect(),+ target_tables: options+ .target_tables+ .iter()+ .filter(|t| shard_set.contains(t.name.as_str()))+ .cloned()+ .collect(),+ source_details: options+ .source_details+ .iter()+ .filter(|d| shard_set.contains(d.name.as_str()))+ .cloned()+ .collect(),+ target_details: options+ .target_details+ .iter()+ .filter(|d| shard_set.contains(d.name.as_str()))+ .cloned()+ .collect(),+ source_functions: options.source_functions.clone(),+ target_functions: options.target_functions.clone(),+ source_sequences: options.source_sequences.clone(),+ target_sequences: options.target_sequences.clone(),+ source_rules: options.source_rules.clone(),+ target_rules: options.target_rules.clone(),+ source_owners: options.source_owners.clone(),+ target_owners: options.target_owners.clone(),+ database_type: options.database_type,+ target_schema: options.target_schema.clone(),+ ignore_comments: options.ignore_comments,+ cascade_delete: options.cascade_delete,+ compare_column_order: options.compare_column_order,+ ..Default::default()+ };+ diff_schema(&shard_options)+ })+ .collect();++ let mut merged: Vec<TableDiff> = Vec::new();+ for shard_result in shard_results {+ merged.extend(shard_result);}- diffs+ merged.sort_by(|a, b| a.name.cmp(&b.name));+ merged.dedup_by(|a, b| a.name == b.name && a.diff_type == b.diff_type);+ merged}-pub fn diff_rules(source: &[RuleInfo], target: &[RuleInfo]) -> Vec<RuleDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<&str, &RuleInfo> = target.iter().map(|r| (r.name.as_str(), r)).collect();- let source_map: HashMap<&str, &RuleInfo> = source.iter().map(|r| (r.name.as_str(), r)).collect();+// ============================================================================+// Phase 4.6: Permission & Role-Aware Sync+// ============================================================================- for source_rule in source {- let Some(target_rule) = target_map.get(source_rule.name.as_str()) else {- diffs.push(RuleDiff {+#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionInfo {+ pub grantee: String,+ pub object_type: String,+ pub object_name: String,+ pub privilege: String,+ pub is_grantable: bool,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct PermissionDiff {+ #[serde(rename = "type")]+ pub diff_type: String,+ pub grantee: String,+ pub object_name: String,+ pub privilege: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub source: Option<PermissionInfo>,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub target: Option<PermissionInfo>,+}++pub fn diff_permissions(source: &[PermissionInfo], target: &[PermissionInfo]) -> Vec<PermissionDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<(&str, &str, &str), &PermissionInfo> =+ target.iter().map(|p| ((p.grantee.as_str(), p.object_name.as_str(), p.privilege.as_str()), p)).collect();+ let source_map: HashMap<(&str, &str, &str), &PermissionInfo> =+ source.iter().map(|p| ((p.grantee.as_str(), p.object_name.as_str(), p.privilege.as_str()), p)).collect();++ for sp in source {+ let key = (sp.grantee.as_str(), sp.object_name.as_str(), sp.privilege.as_str());+ if !target_map.contains_key(&key) {+ diffs.push(PermissionDiff {diff_type: "added".to_string(),- name: source_rule.name.clone(),- source: Some(source_rule.clone()),+ grantee: sp.grantee.clone(),+ object_name: sp.object_name.clone(),+ privilege: sp.privilege.clone(),+ source: Some(sp.clone()),target: None,- changes: Vec::new(),- });- continue;- };-- let mut changes = Vec::new();- if source_rule.definition != target_rule.definition {- changes.push("definition changed".to_string());- }- if !changes.is_empty() {- diffs.push(RuleDiff {- diff_type: "modified".to_string(),- name: source_rule.name.clone(),- source: Some(source_rule.clone()),- target: Some((*target_rule).clone()),- changes,});}}- for target_rule in target {- if !source_map.contains_key(target_rule.name.as_str()) {- diffs.push(RuleDiff {+ for tp in target {+ let key = (tp.grantee.as_str(), tp.object_name.as_str(), tp.privilege.as_str());+ if !source_map.contains_key(&key) {+ diffs.push(PermissionDiff {diff_type: "removed".to_string(),- name: target_rule.name.clone(),+ grantee: tp.grantee.clone(),+ object_name: tp.object_name.clone(),+ privilege: tp.privilege.clone(),source: None,- target: Some(target_rule.clone()),- changes: Vec::new(),+ target: Some(tp.clone()),});}}@@ -948,1057 +1487,6733 @@ pub fn diff_rules(source: &[RuleInfo], target: &[RuleInfo]) -> Vec<RuleDiff> {diffs}-pub fn diff_owners(source: &[OwnerInfo], target: &[OwnerInfo]) -> Vec<OwnerDiff> {- let mut diffs = Vec::new();- let target_map: HashMap<&str, &OwnerInfo> = target.iter().map(|o| (o.object_name.as_str(), o)).collect();- let _source_map: HashMap<&str, &OwnerInfo> = source.iter().map(|o| (o.object_name.as_str(), o)).collect();-- for source_owner in source {- let Some(target_owner) = target_map.get(source_owner.object_name.as_str()) else {- continue; // skip added/removed objects, only compare owners for common objects- };+pub fn generate_permission_sync_sql(diffs: &[PermissionDiff], db_type: DatabaseType, schema: Option<&str>) -> String {+ let mut lines: Vec<String> = Vec::new();+ let profile = profile_for(db_type);- let mut changes = Vec::new();- if source_owner.owner != target_owner.owner {- changes.push(format!("owner: {} → {}", target_owner.owner, source_owner.owner));- }- if !changes.is_empty() {- diffs.push(OwnerDiff {- diff_type: "modified".to_string(),- object_name: source_owner.object_name.clone(),- source: Some(source_owner.clone()),- target: Some((*target_owner).clone()),- changes,- });+ for diff in diffs {+ match diff.diff_type.as_str() {+ "added" => {+ if let Some(source) = &diff.source {+ if profile.grant_uses_mysql_user_syntax {+ let object_path = if let Some(sch) = schema {+ format!("`{}`.`{}`", sch.replace('`', "``"), source.object_name.replace('`', "``"))+ } else {+ format!("`{}`", source.object_name.replace('`', "``"))+ };+ let with_grant = if source.is_grantable { " WITH GRANT OPTION" } else { "" };+ let grantee_escaped = source.grantee.replace('\'', "''");+ lines.push(format!(+ "GRANT {} ON {} TO '{}'{};",+ source.privilege, object_path, grantee_escaped, with_grant+ ));+ } else {+ let obj_escaped = source.object_name.replace('"', "\"\"");+ let object_path = if let Some(sch) = schema {+ format!("{} \"{}\".\"{}\"", source.object_type, sch, obj_escaped)+ } else {+ format!("{} \"{}\"", source.object_type, obj_escaped)+ };+ let with_grant = if source.is_grantable { " WITH GRANT OPTION" } else { "" };+ let grantee_escaped = source.grantee.replace('"', "\"\"");+ lines.push(format!(+ "GRANT {} ON {} TO \"{}\"{};",+ source.privilege, object_path, grantee_escaped, with_grant+ ));+ }+ }+ }+ "removed" => {+ if let Some(target) = &diff.target {+ if profile.grant_uses_mysql_user_syntax {+ let object_path = if let Some(sch) = schema {+ format!("`{}`.`{}`", sch.replace('`', "``"), target.object_name.replace('`', "``"))+ } else {+ format!("`{}`", target.object_name.replace('`', "``"))+ };+ let grantee_escaped = target.grantee.replace('\'', "''");+ lines.push(format!(+ "REVOKE {} ON {} FROM '{}';",+ target.privilege, object_path, grantee_escaped+ ));+ } else {+ let obj_escaped = target.object_name.replace('"', "\"\"");+ let object_path = if let Some(sch) = schema {+ format!("{} \"{}\".\"{}\"", target.object_type, sch, obj_escaped)+ } else {+ format!("{} \"{}\"", target.object_type, obj_escaped)+ };+ let grantee_escaped = target.grantee.replace('"', "\"\"");+ lines.push(format!(+ "REVOKE {} ON {} FROM \"{}\";",+ target.privilege, object_path, grantee_escaped+ ));+ }+ }+ }+ _ => {}}}- diffs+ lines.join("\n")}-fn quote_id(name: &str, db_type: DatabaseType) -> String {- if is_mysql_like(db_type) {- format!("`{}`", name.replace('`', "``"))- } else {- format!("\"{}\"", name.replace('"', "\"\""))+// ============================================================================+// Phase 4.7: Metadata Resource-Aware Scheduling+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ResourceConstraint {+ pub max_concurrent_connections: usize,+ pub max_memory_mb: u64,+ pub max_tables_per_batch: usize,+ pub throttle_delay_ms: u64,+}++impl Default for ResourceConstraint {+ fn default() -> Self {+ Self { max_concurrent_connections: 4, max_memory_mb: 512, max_tables_per_batch: 50, throttle_delay_ms: 100 }}}-fn mysql_default_value(default: &str, data_type: &str) -> String {- let trimmed = default.trim();- if is_mysql_default_expression(trimmed) || !is_mysql_string_literal_type(data_type) {- return default.to_string();+#[derive(Debug, Clone)]+pub struct AdaptiveScheduler {+ pub constraint: ResourceConstraint,+ pub current_connections: usize,+ pub estimated_table_count: usize,+}++impl AdaptiveScheduler {+ pub fn new(constraint: ResourceConstraint, table_count: usize) -> Self {+ Self { constraint, current_connections: 0, estimated_table_count: table_count }}- // MySQL metadata returns string defaults as values rather than reusable DDL tokens.- let literal = format!("'{}'", default.replace('\'', "''"));- if mysql_default_requires_expression(data_type) {- format!("({literal})")- } else {- literal+ pub fn optimal_batch_size(&self) -> usize {+ let conn_limit = self.constraint.max_concurrent_connections;+ let mem_limit = self.constraint.max_memory_mb as usize * 50;+ let table_limit = self.constraint.max_tables_per_batch;++ let batches = self.estimated_table_count.max(1);+ let per_batch = (self.estimated_table_count / conn_limit).max(1);++ per_batch.min(mem_limit / batches).min(table_limit)}-}-fn is_mysql_default_expression(default: &str) -> bool {- let upper = default.to_ascii_uppercase();- (default.starts_with('(') && default.ends_with(')'))- || (default.starts_with('\'') && default.ends_with('\''))- || (default.starts_with('"') && default.ends_with('"'))- || upper == "NULL"- || upper == "CURRENT_TIMESTAMP"- || upper.strip_prefix("CURRENT_TIMESTAMP(").is_some_and(|precision| {- precision.ends_with(')') && precision[..precision.len() - 1].chars().all(|c| c.is_ascii_digit())- })- || matches!(upper.as_bytes(), [b'B' | b'X', b'\'', .., b'\''])-}--fn is_mysql_string_literal_type(data_type: &str) -> bool {- let base_type = mysql_base_type(data_type);- matches!(- base_type.as_str(),- "char"- | "varchar"- | "tinytext"- | "text"- | "mediumtext"- | "longtext"- | "tinyblob"- | "blob"- | "mediumblob"- | "longblob"- | "binary"- | "varbinary"- | "enum"- | "set"- | "date"- | "datetime"- | "timestamp"- | "time"- | "year"- | "json"- | "geometry"- | "point"- | "linestring"- | "polygon"- | "multipoint"- | "multilinestring"- | "multipolygon"- | "geometrycollection"- )-}+ pub fn recommended_shard_count(&self) -> usize {+ let per_batch = self.optimal_batch_size();+ let count = (self.estimated_table_count as f64 / per_batch as f64).ceil() as usize;+ count.min(self.constraint.max_concurrent_connections).max(1)+ }-fn mysql_default_requires_expression(data_type: &str) -> bool {- let base_type = mysql_base_type(data_type);- matches!(- base_type.as_str(),- "tinytext"- | "text"- | "mediumtext"- | "longtext"- | "tinyblob"- | "blob"- | "mediumblob"- | "longblob"- | "json"- | "geometry"- | "point"- | "linestring"- | "polygon"- | "multipoint"- | "multilinestring"- | "multipolygon"- | "geometrycollection"- )+ pub fn throttle_delay_ms(&self) -> u64 {+ self.constraint.throttle_delay_ms+ }}-fn mysql_base_type(data_type: &str) -> String {- data_type- .trim_start()- .split(|c: char| c == '(' || c.is_ascii_whitespace())- .next()- .unwrap_or_default()- .to_ascii_lowercase()+// ============================================================================+// Phase 4: Extended SchemaDiffPreparationOptions & SchemaDiffPreparation+// ============================================================================++impl Default for SchemaDiffPreparationOptions {+ fn default() -> Self {+ Self {+ source_tables: Vec::new(),+ target_tables: Vec::new(),+ source_details: Vec::new(),+ target_details: Vec::new(),+ source_functions: Vec::new(),+ target_functions: Vec::new(),+ source_sequences: Vec::new(),+ target_sequences: Vec::new(),+ source_rules: Vec::new(),+ target_rules: Vec::new(),+ source_owners: Vec::new(),+ target_owners: Vec::new(),+ database_type: DatabaseType::Sqlite,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ detect_renames: false,+ detect_table_renames: false,+ rename_threshold: 0.5,+ enable_rollback: false,+ batch_patterns: Vec::new(),+ source_dialect: None,+ target_dialect: None,+ compatibility_threshold: 0.5,+ source_permissions: Vec::new(),+ target_permissions: Vec::new(),+ shard_strategy: None,+ resource_constraint: None,+ field_mappings: Vec::new(),+ }+ }}-fn column_def(col: &ColumnInfo, db_type: DatabaseType) -> String {- let mut definition = format!("{} {}", quote_id(&col.name, db_type), col.data_type);- if !col.is_nullable {- definition.push_str(" NOT NULL");+// Add new optional fields to SchemaDiffPreparationOptions+// These are added as separate impl blocks to avoid breaking existing construction sites+impl SchemaDiffPreparationOptions {+ pub fn with_rename_detection(mut self, detect: bool, threshold: f64) -> Self {+ self.detect_renames = detect;+ self.rename_threshold = threshold;+ self}- if let Some(default) = &col.column_default {- let default =- if db_type == DatabaseType::Mysql { mysql_default_value(default, &col.data_type) } else { default.clone() };- definition.push_str(&format!(" DEFAULT {default}"));++ pub fn with_rollback(mut self, enable: bool) -> Self {+ self.enable_rollback = enable;+ self}- if is_mysql_like(db_type) {- if let Some(comment) = &col.comment {- definition.push_str(&format!(" COMMENT {}", comment_literal(comment)));- }++ pub fn with_batch_patterns(mut self, patterns: Vec<BatchPattern>) -> Self {+ self.batch_patterns = patterns;+ self}- definition-}-fn qualified_name(name: &str, db_type: DatabaseType, schema: Option<&str>) -> String {- schema- .map(str::trim)- .filter(|schema| !schema.is_empty())- .map(|schema| format!("{}.{}", quote_id(schema, db_type), quote_id(name, db_type)))- .unwrap_or_else(|| quote_id(name, db_type))-}+ pub fn with_dialects(mut self, source: Option<DialectKind>, target: Option<DialectKind>) -> Self {+ self.source_dialect = source;+ self.target_dialect = target;+ self+ }-fn drop_index_sql(table_name: &str, index_name: &str, db_type: DatabaseType, schema: Option<&str>) -> String {- let table = qualified_name(table_name, db_type, schema);- let index = qualified_name(index_name, db_type, schema);- if is_mysql_like(db_type) {- format!("DROP INDEX {} ON {table};", quote_id(index_name, db_type))- } else {- format!("DROP INDEX IF EXISTS {index};")+ pub fn with_compatibility_threshold(mut self, threshold: f64) -> Self {+ self.compatibility_threshold = threshold;+ self}-}-fn mysql_index_column_sql(column: &str) -> String {- let trimmed = column.trim();- // MySQL metadata represents a functional key part as an expression wrapped for CREATE INDEX.- if trimmed.starts_with("((") && trimmed.ends_with("))") {- trimmed.to_string()- } else {- quote_id(column, DatabaseType::Mysql)+ pub fn with_permissions(mut self, source: Vec<PermissionInfo>, target: Vec<PermissionInfo>) -> Self {+ self.source_permissions = source;+ self.target_permissions = target;+ self}-}-fn create_index_sql(table_name: &str, index: &IndexInfo, db_type: DatabaseType, schema: Option<&str>) -> String {- let table = qualified_name(table_name, db_type, schema);- let columns =- index- .columns- .iter()- .map(|column| {- if db_type == DatabaseType::Mysql {- mysql_index_column_sql(column)- } else {- quote_id(column, db_type)- }- })- .collect::<Vec<_>>()- .join(", ");- let unique = if index.is_unique { "UNIQUE " } else { "" };- let index_type = index.index_type.as_deref().unwrap_or_default();- let using_clause = if !index_type.is_empty() && db_type == DatabaseType::Postgres {- format!(" USING {index_type}")- } else {- String::new()- };- let type_prefix = if !index_type.is_empty() && db_type == DatabaseType::SqlServer {- format!("{index_type} ")- } else {- String::new()- };- let mysql_using =- if !index_type.is_empty() && is_mysql_like(db_type) { format!(" USING {index_type}") } else { String::new() };- let included_columns = index.included_columns.clone().unwrap_or_default();- let include_clause =- if !included_columns.is_empty() && matches!(db_type, DatabaseType::Postgres | DatabaseType::SqlServer) {- format!(- " INCLUDE ({})",- included_columns.iter().map(|column| quote_id(column, db_type)).collect::<Vec<_>>().join(", ")- )- } else {- String::new()- };- let supports_where = matches!(db_type, DatabaseType::Postgres | DatabaseType::SqlServer | DatabaseType::Sqlite);- let filter = if supports_where { index.filter.as_deref().unwrap_or_default() } else { "" };- let filter_clause = if filter.is_empty() { String::new() } else { format!(" WHERE {filter}") };- let comment = index.comment.as_deref().unwrap_or("");- let comment_clause = if !comment.trim().is_empty() && is_mysql_like(db_type) {- format!(" COMMENT {}", comment_literal(comment))- } else {- String::new()- };- if is_mysql_like(db_type) {- format!(- "CREATE {unique}{type_prefix}INDEX {}{mysql_using} ON {table} ({columns}){comment_clause};",- quote_id(&index.name, db_type)- )- } else {- format!(- "CREATE {unique}{type_prefix}INDEX {} ON {table}{using_clause} ({columns}){include_clause}{filter_clause};",- quote_id(&index.name, db_type)- )+ pub fn with_shard_strategy(mut self, strategy: ShardStrategy) -> Self {+ self.shard_strategy = Some(strategy);+ self}-}-fn drop_foreign_key_sql(table_name: &str, fk_name: &str, db_type: DatabaseType, schema: Option<&str>) -> String {- let table = qualified_name(table_name, db_type, schema);- let fk = quote_id(fk_name, db_type);- if is_mysql_like(db_type) {- format!("ALTER TABLE {table} DROP FOREIGN KEY {fk};")- } else {- format!("ALTER TABLE {table} DROP CONSTRAINT {fk};")+ pub fn with_resource_constraint(mut self, constraint: ResourceConstraint) -> Self {+ self.resource_constraint = Some(constraint);+ self+ }++ pub fn with_field_mappings(mut self, mappings: Vec<FieldMapping>) -> Self {+ self.field_mappings = mappings;+ self}}-fn add_foreign_key_sql(table_name: &str, fk: &ForeignKeyInfo, db_type: DatabaseType, schema: Option<&str>) -> String {- let table = qualified_name(table_name, db_type, schema);- format!(- "ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({});",- quote_id(&fk.name, db_type),- quote_id(&fk.column, db_type),- quote_id(&fk.ref_table, db_type),- quote_id(&fk.ref_column, db_type)- )-}--fn drop_object_sql(diff: &TableDiff, db_type: DatabaseType, schema: Option<&str>, cascade: &str) -> String {- let object_type = if diff.object_type.as_deref() == Some("view") { "VIEW" } else { "TABLE" };- format!("DROP {object_type} IF EXISTS {}{cascade};", qualified_name(&diff.name, db_type, schema))-}--fn comment_literal(comment: &str) -> String {- format!("'{}'", comment.replace('\'', "''"))-}--fn column_comment_sql(- table_name: &str,- column_name: &str,- comment: &str,- db_type: DatabaseType,- schema: Option<&str>,-) -> String {- if is_mysql_like(db_type) {- return format!(- "-- Column comment for {column_name}: use ALTER TABLE ... MODIFY COLUMN to set comment in MySQL"- );+pub fn prepare_schema_diff(options: SchemaDiffPreparationOptions) -> SchemaDiffPreparation {+ if !options.field_mappings.is_empty() {+ log::info!("prepare_schema_diff field_mappings:");+ for m in &options.field_mappings {+ log::info!(+ " {} -> {} (strategy={:?}, custom={:?})",+ m.source_type,+ m.target_type,+ m.param_strategy,+ m.custom_params+ );+ }+ log::info!(" source_dialect={:?} target_dialect={:?}", options.source_dialect, options.target_dialect);}- let table = qualified_name(table_name, db_type, schema);- format!("COMMENT ON COLUMN {table}.{} IS {};", quote_id(column_name, db_type), comment_literal(comment))-}-fn table_comment_sql(table_name: &str, comment: &str, db_type: DatabaseType, schema: Option<&str>) -> String {- let table = qualified_name(table_name, db_type, schema);- if is_mysql_like(db_type) {- format!("ALTER TABLE {table} COMMENT = {};", comment_literal(comment))- } else {- format!("COMMENT ON TABLE {table} IS {};", comment_literal(comment))- }-}+ let dialect_str = options.source_dialect.map(|d| d.label().to_string()).unwrap_or_else(|| "generic".to_string());+ let options = AstTransmitFilter::filter_diff_preparation_options(options, &dialect_str);-#[allow(clippy::too_many_arguments)]-pub fn generate_schema_sync_sql(- diffs: &[TableDiff],- function_diffs: &[FunctionDiff],- sequence_diffs: &[SequenceDiff],- rule_diffs: &[RuleDiff],- owner_diffs: &[OwnerDiff],- db_type: DatabaseType,- schema: Option<&str>,- cascade_delete: bool,-) -> String {- let mut lines = Vec::new();- let is_mysql = is_mysql_like(db_type);- let cascade = if cascade_delete { " CASCADE" } else { "" };+ let dep_graph = DependencyGraph::build(&options.source_details, &options.source_tables);- for diff in diffs {- let table = qualified_name(&diff.name, db_type, schema);+ let mut diffs = if let Some(ref strategy) = options.shard_strategy {+ shard_diff(&options, strategy)+ } else {+ diff_schema(&options)+ };- if diff.diff_type == "added" && diff.ddl.is_some() {- lines.push(format!("-- Create {}: {}", diff.object_type.as_deref().unwrap_or("table"), diff.name));- lines.push(format!("{};", diff.ddl.as_deref().unwrap_or_default()));- lines.push(String::new());- continue;- }+ let rename_candidates = if options.detect_renames && options.detect_table_renames {+ let removed: Vec<String> = diffs.iter().filter(|d| d.diff_type == "removed").map(|d| d.name.clone()).collect();+ let added: Vec<String> = diffs.iter().filter(|d| d.diff_type == "added").map(|d| d.name.clone()).collect();+ let candidates = detect_renames(+ &removed,+ &added,+ &options.source_details,+ &options.target_details,+ options.rename_threshold,+ );- if diff.diff_type == "added" && diff.object_type.as_deref() == Some("view") {- lines.push(format!("-- View exists only in source: {}", diff.name));- lines.push("-- Source view definition is not available from this driver yet.".to_string());- lines.push(String::new());- continue;- }+ let target_renamed: HashSet<&str> = candidates.iter().map(|r| r.target_name.as_str()).collect();+ let source_renamed: HashSet<&str> = candidates.iter().map(|r| r.source_name.as_str()).collect();- if diff.diff_type == "removed" {- lines.push(format!("-- Drop {}: {}", diff.object_type.as_deref().unwrap_or("table"), diff.name));- lines.push(drop_object_sql(diff, db_type, schema, cascade));- lines.push(String::new());- continue;- }+ diffs.retain(|d| {+ !((d.diff_type == "removed" && target_renamed.contains(d.name.as_str()))+ || (d.diff_type == "added" && source_renamed.contains(d.name.as_str())))+ });- if diff.diff_type != "modified" {- continue;+ for c in &candidates {+ let source_detail = options.source_details.iter().find(|d| d.name == c.source_name);+ let target_detail = options.target_details.iter().find(|d| d.name == c.target_name);+ diffs.push(TableDiff {+ diff_type: "renamed".to_string(),+ object_type: Some("table".to_string()),+ name: c.source_name.clone(),+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: source_detail.and_then(|d| d.ddl.clone()),+ target_ddl: target_detail.and_then(|d| d.ddl.clone()),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ });}- let mut parts = Vec::new();- if let Some(foreign_keys) = &diff.foreign_keys {- for fk in foreign_keys {- if fk.diff_type == "removed" || fk.diff_type == "modified" {- lines.push(drop_foreign_key_sql(&diff.name, &fk.name, db_type, schema));- }- }- }+ candidates+ } else {+ Vec::new()+ };- if let Some(columns) = &diff.columns {- for column in columns {- match column.diff_type.as_str() {- "added" => {- if let Some(source) = &column.source {- parts.push(format!(" ADD COLUMN {}", column_def(source, db_type)));- }- }- "removed" => {- parts.push(format!(" DROP COLUMN {}", quote_id(&column.name, db_type)));- }- "modified" => {- if let Some(source) = &column.source {- if is_mysql {- let renames_column = column.changes.iter().any(|change| change.starts_with("name:"));- if renames_column {- if let Some(target) = &column.target {- parts.push(format!(- " CHANGE COLUMN {} {}",- quote_id(&target.name, db_type),- column_def(source, db_type)- ));- }- } else if column.changes.iter().any(|change| !change.starts_with("order:")) {- parts.push(format!(" MODIFY COLUMN {}", column_def(source, db_type)));- }- } else {- let name = quote_id(&column.name, db_type);- if column.changes.iter().any(|change| change.starts_with("type:")) {- parts.push(format!(" ALTER COLUMN {name} TYPE {}", source.data_type));- }- if column.changes.iter().any(|change| change.starts_with("nullable:")) {- parts.push(if source.is_nullable {- format!(" ALTER COLUMN {name} DROP NOT NULL")- } else {- format!(" ALTER COLUMN {name} SET NOT NULL")- });- }- if column.changes.iter().any(|change| change.starts_with("default:")) {- parts.push(if let Some(default) = &source.column_default {- format!(" ALTER COLUMN {name} SET DEFAULT {default}")- } else {- format!(" ALTER COLUMN {name} DROP DEFAULT")- });- }- }- }+ let compatibility_warnings = if options.source_dialect.is_some() || options.target_dialect.is_some() {+ let src_dialect = options.source_dialect.unwrap_or(DialectKind::Mysql);+ let tgt_dialect = options.target_dialect.unwrap_or(DialectKind::Mysql);+ let mut all_warnings = Vec::new();+ for diff in &diffs {+ if diff.diff_type == "modified" {+ if let Some(source_detail) = options.source_details.iter().find(|d| d.name == diff.name) {+ if let Some(target_detail) = options.target_details.iter().find(|d| d.name == diff.name) {+ let (_, warnings) = diff_columns_with_compatibility(+ &source_detail.columns,+ &target_detail.columns,+ options.ignore_comments,+ options.compare_column_order,+ src_dialect,+ tgt_dialect,+ options.compatibility_threshold,+ &options.field_mappings,+ );+ all_warnings.extend(warnings);}- _ => {}}}}+ all_warnings+ } else {+ Vec::new()+ };- if !parts.is_empty() {- lines.push(format!("-- Alter table: {}", diff.name));- if is_mysql {- lines.push(format!("ALTER TABLE {table}"));- lines.push(format!("{};", parts.join(",\n")));- } else {- for part in parts {- lines.push(format!("ALTER TABLE {table}{part};"));- }- }- lines.push(String::new());- }+ let rollback_graph = if options.enable_rollback {+ let mut graph = RollbackGraph::from_forward_diffs(&diffs, &rename_candidates, &dep_graph);+ let _ = graph.validate_consistency();+ Some(graph)+ } else {+ None+ };- if !is_mysql {- if let Some(columns) = &diff.columns {- for column in columns {- if let Some(source) = &column.source {- if column.changes.iter().any(|change| change.starts_with("comment:")) {- lines.push(column_comment_sql(- &diff.name,- &column.name,- source.comment.as_deref().unwrap_or_default(),- db_type,- schema,- ));- }- if column.diff_type == "added" {- if let Some(comment) = &source.comment {- lines.push(column_comment_sql(&diff.name, &column.name, comment, db_type, schema));- }- }- }- }- }- }+ let function_diffs = diff_functions(&options.source_functions, &options.target_functions);+ let sequence_diffs = diff_sequences(&options.source_sequences, &options.target_sequences);+ let rule_diffs = diff_rules(&options.source_rules, &options.target_rules);+ let owner_diffs = diff_owners(&options.source_owners, &options.target_owners);- if diff.source_table_comment.is_some() && diff.source_table_comment != diff.target_table_comment {- let comment = diff.source_table_comment.as_ref().and_then(|comment| comment.as_deref()).unwrap_or_default();- lines.push(table_comment_sql(&diff.name, comment, db_type, schema));+ for diff in &mut diffs {+ let (sync_sql, _) = generate_schema_sync_sql_inner(+ std::slice::from_ref(diff),+ &[],+ &[],+ &[],+ &[],+ options.database_type,+ options.target_schema.as_deref(),+ options.cascade_delete,+ options.source_dialect,+ &options.field_mappings,+ );+ if !sync_sql.is_empty() {+ diff.sync_sql = Some(sync_sql);}+ }- if let Some(indexes) = &diff.indexes {- for index in indexes {- match index.diff_type.as_str() {- "added" => {- if let Some(source) = &index.source {- lines.push(create_index_sql(&diff.name, source, db_type, schema));- }- }- "removed" => lines.push(drop_index_sql(&diff.name, &index.name, db_type, schema)),- "modified" => {- if let Some(source) = &index.source {- lines.push(drop_index_sql(&diff.name, &index.name, db_type, schema));- lines.push(create_index_sql(&diff.name, source, db_type, schema));- }- }- _ => {}- }- }- }+ let (sync_sql, _) = generate_schema_sync_sql_inner(+ &diffs,+ &function_diffs,+ &sequence_diffs,+ &rule_diffs,+ &owner_diffs,+ options.database_type,+ options.target_schema.as_deref(),+ options.cascade_delete,+ options.source_dialect,+ &options.field_mappings,+ );- if let Some(foreign_keys) = &diff.foreign_keys {- for fk in foreign_keys {- if fk.diff_type == "added" || fk.diff_type == "modified" {- if let Some(source) = &fk.source {- lines.push(add_foreign_key_sql(&diff.name, source, db_type, schema));- }- }- }+ let (rollback_sync_sql, missing_rollback_objects) = match &rollback_graph {+ Some(graph) => {+ let (sql, missing) = generate_rollback_sync_sql_with_missing(+ graph,+ options.database_type,+ options.target_schema.as_deref(),+ options.cascade_delete,+ );+ (Some(sql), missing)}+ None => (None, Vec::new()),+ };+ let rollback_completeness = if missing_rollback_objects.is_empty() {+ RollbackCompleteness::Complete+ } else {+ RollbackCompleteness::Incomplete+ };- if let Some(triggers) = &diff.triggers {- for trigger in triggers {- lines.push(format!(- "-- Trigger {}: {} on {}; review trigger definition manually.",- trigger.diff_type, trigger.name, diff.name- ));- }- }+ let permission_diffs = if !options.source_permissions.is_empty() || !options.target_permissions.is_empty() {+ diff_permissions(&options.source_permissions, &options.target_permissions)+ } else {+ Vec::new()+ };- if diff.indexes.as_ref().is_some_and(|indexes| !indexes.is_empty())- || diff.foreign_keys.as_ref().is_some_and(|foreign_keys| !foreign_keys.is_empty())- || diff.triggers.as_ref().is_some_and(|triggers| !triggers.is_empty())- {- lines.push(String::new());- }+ let permission_sync_sql = if !permission_diffs.is_empty() {+ Some(generate_permission_sync_sql(&permission_diffs, options.database_type, options.target_schema.as_deref()))+ } else {+ None+ };- if db_type == DatabaseType::Sqlite- && diff.foreign_keys.as_ref().is_some_and(|foreign_keys| !foreign_keys.is_empty())- {- lines.push(format!("-- SQLite foreign key synchronization may require table rebuild for: {}", diff.name));- lines.push(String::new());- }+ SchemaDiffPreparation {+ diffs,+ function_diffs,+ sequence_diffs,+ rule_diffs,+ owner_diffs,+ sync_sql,+ rollback_sync_sql,+ rollback_completeness,+ missing_rollback_objects,+ rename_candidates,+ rollback_graph,+ compatibility_warnings,+ permission_diffs,+ permission_sync_sql,+ dependency_graph: Some(dep_graph),}+}- // Function diffs- if !function_diffs.is_empty() {- lines.push(String::new());- lines.push("-- Functions".to_string());- for diff in function_diffs {- match diff.diff_type.as_str() {- "added" => {- if let Some(source) = &diff.source {- lines.push(format!("-- Create function: {}", diff.name));- lines.push(format!(- "CREATE OR REPLACE FUNCTION {} {};",- qualified_name(&diff.name, db_type, schema),- source.definition- ));- }- }- "removed" => {- lines.push(format!("-- Drop function: {}", diff.name));- lines.push(format!(- "DROP FUNCTION IF EXISTS {}{cascade};",- qualified_name(&diff.name, db_type, schema)- ));- }- "modified" => {- if let Some(source) = &diff.source {- lines.push(format!("-- Alter function: {}", diff.name));- lines.push(format!(- "CREATE OR REPLACE FUNCTION {} {};",- qualified_name(&diff.name, db_type, schema),- source.definition- ));- }+fn diff_schema(options: &SchemaDiffPreparationOptions) -> Vec<TableDiff> {+ let source_details: HashMap<&str, &TableSchemaDetail> =+ options.source_details.iter().map(|detail| (detail.name.as_str(), detail)).collect();+ let target_details: HashMap<&str, &TableSchemaDetail> =+ options.target_details.iter().map(|detail| (detail.name.as_str(), detail)).collect();+ let source_table_comments: HashMap<&str, Option<String>> =+ options.source_tables.iter().map(|table| (table.name.as_str(), table.comment.clone())).collect();+ let target_table_comments: HashMap<&str, Option<String>> =+ options.target_tables.iter().map(|table| (table.name.as_str(), table.comment.clone())).collect();++ let source_table_names: Vec<String> = options+ .source_tables+ .iter()+ .filter(|table| !table.table_type.contains("VIEW"))+ .map(|table| table.name.clone())+ .collect();+ let target_table_names: Vec<String> = options+ .target_tables+ .iter()+ .filter(|table| !table.table_type.contains("VIEW"))+ .map(|table| table.name.clone())+ .collect();+ let source_view_names: Vec<String> = options+ .source_tables+ .iter()+ .filter(|table| table.table_type.contains("VIEW"))+ .map(|table| table.name.clone())+ .collect();+ let target_view_names: Vec<String> = options+ .target_tables+ .iter()+ .filter(|table| table.table_type.contains("VIEW"))+ .map(|table| table.name.clone())+ .collect();++ let (added, removed, common) = diff_names(&source_table_names, &target_table_names);+ let (added_views, removed_views, _) = diff_names(&source_view_names, &target_view_names);+ let mut result = Vec::new();++ for name in added {+ let source_detail = source_details.get(name.as_str());+ result.push(TableDiff {+ diff_type: "added".to_string(),+ object_type: Some("table".to_string()),+ name,+ ddl: source_detail.and_then(|detail| detail.ddl.clone()),+ target_ddl: None,+ columns: source_detail.map(|detail| {+ detail+ .columns+ .iter()+ .map(|c| ColumnDiff {+ diff_type: "added".to_string(),+ name: c.name.clone(),+ source: Some(c.clone()),+ target: None,+ changes: vec![],+ })+ .collect()+ }),+ indexes: source_detail.map(|detail| {+ detail+ .indexes+ .iter()+ .map(|i| IndexDiff {+ diff_type: "added".to_string(),+ name: i.name.clone(),+ source: Some(i.clone()),+ target: None,+ changes: vec![],+ })+ .collect()+ }),+ foreign_keys: source_detail.map(|detail| {+ detail+ .foreign_keys+ .iter()+ .map(|fk| ForeignKeyDiff {+ diff_type: "added".to_string(),+ name: fk.name.clone(),+ source: Some(fk.clone()),+ target: None,+ changes: vec![],+ })+ .collect()+ }),+ triggers: source_detail.and_then(|detail| {+ if detail.triggers.is_empty() {+ None+ } else {+ Some(+ detail+ .triggers+ .iter()+ .map(|t| TriggerDiff {+ diff_type: "added".to_string(),+ name: t.name.clone(),+ source: Some(t.clone()),+ target: None,+ changes: vec![],+ })+ .collect(),+ )}- _ => {}- }- }+ }),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ });}- // Sequence diffs- if !sequence_diffs.is_empty() {- lines.push(String::new());- lines.push("-- Sequences".to_string());- for diff in sequence_diffs {- match diff.diff_type.as_str() {- "added" => {- if let Some(source) = &diff.source {- lines.push(format!("-- Create sequence: {}", diff.name));- lines.push(format!(- "CREATE SEQUENCE {} AS {} START WITH {} INCREMENT BY {} MINVALUE {} MAXVALUE {} {};",- qualified_name(&diff.name, db_type, schema),- source.data_type,- source.start_value,- source.increment,- source.min_value,- source.max_value,- if source.cycle { "CYCLE" } else { "NO CYCLE" }- ));- }- }- "removed" => {- lines.push(format!("-- Drop sequence: {}", diff.name));- lines.push(format!("DROP SEQUENCE {}{cascade};", qualified_name(&diff.name, db_type, schema)));- }- "modified" => {- if let Some(source) = &diff.source {- lines.push(format!("-- Alter sequence: {}", diff.name));- lines.push(format!(- "ALTER SEQUENCE {} AS {} START WITH {} INCREMENT BY {} MINVALUE {} MAXVALUE {} {};",- qualified_name(&diff.name, db_type, schema),- source.data_type,- source.start_value,- source.increment,- source.min_value,- source.max_value,- if source.cycle { "CYCLE" } else { "NO CYCLE" }- ));- }- }- _ => {}- }- }+ for name in removed {+ let name_clone = name.clone();+ let target_detail = target_details.get(name_clone.as_str()).copied();+ result.push(TableDiff {+ diff_type: "removed".to_string(),+ object_type: Some("table".to_string()),+ name,+ columns: target_detail.map(|detail| {+ detail+ .columns+ .iter()+ .map(|column| ColumnDiff {+ diff_type: "removed".to_string(),+ name: column.name.clone(),+ source: None,+ target: Some(column.clone()),+ changes: vec![],+ })+ .collect()+ }),+ indexes: target_detail.map(|detail| {+ detail+ .indexes+ .iter()+ .map(|index| IndexDiff {+ diff_type: "removed".to_string(),+ name: index.name.clone(),+ source: None,+ target: Some(index.clone()),+ changes: vec![],+ })+ .collect()+ }),+ foreign_keys: target_detail.map(|detail| {+ detail+ .foreign_keys+ .iter()+ .map(|foreign_key| ForeignKeyDiff {+ diff_type: "removed".to_string(),+ name: foreign_key.name.clone(),+ source: None,+ target: Some(foreign_key.clone()),+ changes: vec![],+ })+ .collect()+ }),+ triggers: target_detail.map(|detail| {+ detail+ .triggers+ .iter()+ .map(|trigger| TriggerDiff {+ diff_type: "removed".to_string(),+ name: trigger.name.clone(),+ source: None,+ target: Some(trigger.clone()),+ changes: vec![],+ })+ .collect()+ }),+ ddl: None,+ target_ddl: target_detail.and_then(|detail| detail.ddl.clone()),+ source_table_comment: None,+ target_table_comment: target_table_comments.get(name_clone.as_str()).cloned(),+ sync_sql: None,+ });}- // Rule diffs- if !rule_diffs.is_empty() {- lines.push(String::new());- lines.push("-- Rules".to_string());- for diff in rule_diffs {- match diff.diff_type.as_str() {- "added" => {- if let Some(source) = &diff.source {- lines.push(format!("-- Create rule: {}", diff.name));- lines.push(source.definition.clone());- }- }- "removed" => {- lines.push(format!("-- Drop rule: {}", diff.name));- if let Some(source) = &diff.source {- lines.push(format!(- "DROP RULE IF EXISTS {} ON {};",- diff.name,- qualified_name(&source.table_name, db_type, schema)- ));- }- }- "modified" => {- if let Some(source) = &diff.source {- lines.push(format!("-- Alter rule: {}", diff.name));- lines.push(format!(- "DROP RULE IF EXISTS {} ON {};",- diff.name,- qualified_name(&source.table_name, db_type, schema)- ));- lines.push(source.definition.clone());- }- }- _ => {}- }- }+ for name in added_views {+ let name_clone = name.clone();+ result.push(TableDiff {+ diff_type: "added".to_string(),+ object_type: Some("view".to_string()),+ name,+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: source_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ });}- // Owner diffs- if !owner_diffs.is_empty() {- lines.push(String::new());- lines.push("-- Owners".to_string());- for diff in owner_diffs {- if let (Some(source), Some(_target)) = (&diff.source, &diff.target) {- let object_type = match source.object_type.as_str() {- "TABLE" => "TABLE",- "VIEW" => "VIEW",- "SEQUENCE" => "SEQUENCE",- _ => "TABLE",- };- lines.push(format!(- "ALTER {object_type} {} OWNER TO {};",- qualified_name(&diff.object_name, db_type, schema),- source.owner+ for name in removed_views {+ let name_clone = name.clone();+ result.push(TableDiff {+ diff_type: "removed".to_string(),+ object_type: Some("view".to_string()),+ name,+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ });+ }++ for name in common {+ let Some(source) = source_details.get(name.as_str()) else { continue };+ let Some(target) = target_details.get(name.as_str()) else { continue };+ let column_diffs = diff_columns_with_options(+ &source.columns,+ &target.columns,+ options.ignore_comments,+ options.compare_column_order,+ options.detect_renames,+ options.rename_threshold,+ );+ let index_diffs = diff_indexes(&source.indexes, &target.indexes);+ let foreign_key_diffs = diff_foreign_keys(&source.foreign_keys, &target.foreign_keys);+ let trigger_diffs = diff_triggers(&source.triggers, &target.triggers);+ let source_comment = source_table_comments.get(name.as_str()).cloned().unwrap_or(None);+ let target_comment = target_table_comments.get(name.as_str()).cloned().unwrap_or(None);+ let comment_changed = !options.ignore_comments+ && source_comment.clone().unwrap_or_default() != target_comment.clone().unwrap_or_default();++ let has_diff = !column_diffs.is_empty()+ || !index_diffs.is_empty()+ || !foreign_key_diffs.is_empty()+ || !trigger_diffs.is_empty()+ || comment_changed;++ let name_clone = name.clone();+ result.push(TableDiff {+ diff_type: if has_diff { "modified".to_string() } else { "none".to_string() },+ object_type: Some("table".to_string()),+ name,+ columns: if has_diff { (!column_diffs.is_empty()).then_some(column_diffs) } else { None },+ indexes: if has_diff { (!index_diffs.is_empty()).then_some(index_diffs) } else { None },+ foreign_keys: if has_diff { (!foreign_key_diffs.is_empty()).then_some(foreign_key_diffs) } else { None },+ triggers: if has_diff { (!trigger_diffs.is_empty()).then_some(trigger_diffs) } else { None },+ ddl: source_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),+ target_ddl: target_details.get(name_clone.as_str()).and_then(|detail| detail.ddl.clone()),+ source_table_comment: if has_diff { comment_changed.then_some(source_comment) } else { None },+ target_table_comment: if has_diff { comment_changed.then_some(target_comment) } else { None },+ sync_sql: None,+ });+ }++ result.retain(|diff| diff.diff_type != "none");+ result+}++fn diff_names(source: &[String], target: &[String]) -> (Vec<String>, Vec<String>, Vec<String>) {+ let source_set: HashSet<&str> = source.iter().map(String::as_str).collect();+ let target_set: HashSet<&str> = target.iter().map(String::as_str).collect();+ (+ source.iter().filter(|name| !target_set.contains(name.as_str())).cloned().collect(),+ target.iter().filter(|name| !source_set.contains(name.as_str())).cloned().collect(),+ source.iter().filter(|name| target_set.contains(name.as_str())).cloned().collect(),+ )+}++pub fn diff_columns(source: &[ColumnInfo], target: &[ColumnInfo]) -> Vec<ColumnDiff> {+ diff_columns_with_options(source, target, false, false, false, 0.5)+}++fn column_type_similarity_score(source_type: &str, target_type: &str) -> f64 {+ let s = ColumnType::parse(source_type).base_type.to_ascii_lowercase();+ let t = ColumnType::parse(target_type).base_type.to_ascii_lowercase();+ if s == t {+ return 1.0;+ }+ let exact_matches = [+ ("int", "integer"),+ ("integer", "int"),+ ("float", "real"),+ ("real", "float"),+ ("double", "double precision"),+ ("double precision", "double"),+ ("bool", "boolean"),+ ("boolean", "bool"),+ ("timestamp", "datetime"),+ ("datetime", "timestamp"),+ ];+ if exact_matches.contains(&(s.as_str(), t.as_str())) {+ return 1.0;+ }+ let integer_family = ["tinyint", "smallint", "mediumint", "int", "integer", "bigint", "serial", "bigserial"];+ let text_family = ["char", "varchar", "text", "tinytext", "mediumtext", "longtext", "clob", "nclob"];+ if integer_family.contains(&s.as_str()) && integer_family.contains(&t.as_str()) {+ return 0.8;+ }+ if text_family.contains(&s.as_str()) && text_family.contains(&t.as_str()) {+ return 0.8;+ }+ 0.0+}++fn diff_columns_with_options(+ source: &[ColumnInfo],+ target: &[ColumnInfo],+ ignore_comments: bool,+ compare_column_order: bool,+ detect_renames: bool,+ rename_threshold: f64,+) -> Vec<ColumnDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &ColumnInfo> = target.iter().map(|column| (column.name.as_str(), column)).collect();+ let source_map: HashMap<&str, &ColumnInfo> = source.iter().map(|column| (column.name.as_str(), column)).collect();+ let target_position_map: HashMap<&str, usize> =+ target.iter().enumerate().map(|(index, column)| (column.name.as_str(), index)).collect();+ let can_compare_order = compare_column_order+ && source.len() == target.len()+ && source.iter().all(|column| target_map.contains_key(column.name.as_str()));++ for (source_index, source_column) in source.iter().enumerate() {+ if let Some(target_column) = target_map.get(source_column.name.as_str()) {+ let mut changes = Vec::new();+ if source_column.data_type.to_lowercase() != target_column.data_type.to_lowercase() {+ changes.push(format!("type: {} → {}", target_column.data_type, source_column.data_type));+ }+ if source_column.is_nullable != target_column.is_nullable {+ changes.push(format!(+ "nullable: {} → {}",+ if target_column.is_nullable { "YES" } else { "NO" },+ if source_column.is_nullable { "YES" } else { "NO" }));}- }+ if source_column.column_default.as_deref().unwrap_or_default()+ != target_column.column_default.as_deref().unwrap_or_default()+ {+ changes.push(format!(+ "default: {} → {}",+ target_column.column_default.as_deref().unwrap_or("NULL"),+ source_column.column_default.as_deref().unwrap_or("NULL")+ ));+ }+ if !ignore_comments+ && source_column.comment.as_deref().unwrap_or_default()+ != target_column.comment.as_deref().unwrap_or_default()+ {+ changes.push(format!(+ "comment: {} → {}",+ target_column.comment.as_deref().unwrap_or_default(),+ source_column.comment.as_deref().unwrap_or_default()+ ));+ }+ if can_compare_order {+ if let Some(target_index) = target_position_map.get(source_column.name.as_str()) {+ if source_index != *target_index {+ changes.push(format!("order: {} → {}", *target_index + 1, source_index + 1));+ }+ }+ }+ if !changes.is_empty() {+ diffs.push(ColumnDiff {+ diff_type: "modified".to_string(),+ name: source_column.name.clone(),+ source: Some(source_column.clone()),+ target: Some((*target_column).clone()),+ changes,+ });+ }+ } else {+ diffs.push(ColumnDiff {+ diff_type: "added".to_string(),+ name: source_column.name.clone(),+ source: Some(source_column.clone()),+ target: None,+ changes: Vec::new(),+ });+ }+ }++ for target_column in target {+ if !source_map.contains_key(target_column.name.as_str()) {+ diffs.push(ColumnDiff {+ diff_type: "removed".to_string(),+ name: target_column.name.clone(),+ source: None,+ target: Some(target_column.clone()),+ changes: Vec::new(),+ });+ }+ }++ if detect_renames && rename_threshold > 0.0 {+ let removed_indices: Vec<usize> =+ diffs.iter().enumerate().filter(|(_, d)| d.diff_type == "removed").map(|(i, _)| i).collect();+ let added_indices: Vec<usize> =+ diffs.iter().enumerate().filter(|(_, d)| d.diff_type == "added").map(|(i, _)| i).collect();++ let mut matched_added: HashSet<usize> = HashSet::new();+ let mut matched_removed: HashSet<usize> = HashSet::new();+ let mut rename_pairs: Vec<(usize, usize, f64)> = Vec::new();++ for &ri in &removed_indices {+ if let Some(removed_col) = &diffs[ri].target {+ let mut best_score = 0.0_f64;+ let mut best_ai = None;+ for &ai in &added_indices {+ if matched_added.contains(&ai) {+ continue;+ }+ if let Some(added_col) = &diffs[ai].source {+ let type_score = column_type_similarity_score(&removed_col.data_type, &added_col.data_type);+ if type_score < rename_threshold {+ continue;+ }+ let mut score = type_score;+ if removed_col.is_nullable == added_col.is_nullable {+ score *= 1.0;+ } else {+ score *= 0.8;+ }+ if score > best_score {+ best_score = score;+ best_ai = Some(ai);+ }+ }+ }+ if let Some(ai) = best_ai {+ rename_pairs.push((ri, ai, best_score));+ matched_removed.insert(ri);+ matched_added.insert(ai);+ }+ }+ }++ for (ri, ai, _score) in &rename_pairs {+ let old_name = diffs[*ri].name.clone();+ let old_col = diffs[*ri].target.clone().unwrap();+ let new_col = diffs[*ai].source.clone().unwrap();+ let new_name = new_col.name.clone();++ diffs[*ri] = ColumnDiff {+ diff_type: "renamed".to_string(),+ name: new_name.clone(),+ source: Some(new_col),+ target: Some(old_col),+ changes: vec![format!("{} → {}", old_name, new_name)],+ };+ diffs[*ai] = ColumnDiff {+ diff_type: "_matched_rename".to_string(),+ name: String::new(),+ source: None,+ target: None,+ changes: Vec::new(),+ };+ }++ diffs.retain(|d| d.diff_type != "_matched_rename");+ }++ diffs+}++pub fn diff_indexes(source: &[IndexInfo], target: &[IndexInfo]) -> Vec<IndexDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &IndexInfo> = target.iter().map(|index| (index.name.as_str(), index)).collect();+ let source_map: HashMap<&str, &IndexInfo> = source.iter().map(|index| (index.name.as_str(), index)).collect();++ for source_index in source {+ if source_index.is_primary {+ continue;+ }+ let Some(target_index) = target_map.get(source_index.name.as_str()) else {+ diffs.push(IndexDiff {+ diff_type: "added".to_string(),+ name: source_index.name.clone(),+ source: Some(source_index.clone()),+ target: None,+ changes: Vec::new(),+ });+ continue;+ };++ let mut changes = Vec::new();+ if source_index.is_unique != target_index.is_unique {+ changes.push(format!(+ "unique: {} → {}",+ if target_index.is_unique { "YES" } else { "NO" },+ if source_index.is_unique { "YES" } else { "NO" }+ ));+ }+ if source_index.columns.join(",") != target_index.columns.join(",") {+ changes.push(format!("columns: {} → {}", target_index.columns.join(", "), source_index.columns.join(", ")));+ }+ if source_index.index_type.as_deref().unwrap_or_default()+ != target_index.index_type.as_deref().unwrap_or_default()+ {+ changes.push(format!(+ "type: {} → {}",+ target_index.index_type.as_deref().unwrap_or("default"),+ source_index.index_type.as_deref().unwrap_or("default")+ ));+ }+ if source_index.filter.as_deref().unwrap_or_default() != target_index.filter.as_deref().unwrap_or_default() {+ changes.push(format!(+ "filter: {} → {}",+ target_index.filter.as_deref().unwrap_or("none"),+ source_index.filter.as_deref().unwrap_or("none")+ ));+ }+ let source_included = source_index.included_columns.clone().unwrap_or_default();+ let target_included = target_index.included_columns.clone().unwrap_or_default();+ if source_included.join(",") != target_included.join(",") {+ changes.push(format!(+ "include: {} → {}",+ if target_included.is_empty() { "none".to_string() } else { target_included.join(", ") },+ if source_included.is_empty() { "none".to_string() } else { source_included.join(", ") }+ ));+ }+ if !changes.is_empty() {+ diffs.push(IndexDiff {+ diff_type: "modified".to_string(),+ name: source_index.name.clone(),+ source: Some(source_index.clone()),+ target: Some((*target_index).clone()),+ changes,+ });+ }+ }++ for target_index in target {+ if target_index.is_primary {+ continue;+ }+ if !source_map.contains_key(target_index.name.as_str()) {+ diffs.push(IndexDiff {+ diff_type: "removed".to_string(),+ name: target_index.name.clone(),+ source: None,+ target: Some(target_index.clone()),+ changes: Vec::new(),+ });+ }+ }++ diffs+}++fn normalized_foreign_key_action(action: Option<&str>) -> Option<String> {+ action+ .map(|value| value.split_whitespace().collect::<Vec<_>>().join(" ").to_ascii_uppercase())+ .filter(|value| !value.is_empty())+}++pub fn diff_foreign_keys(source: &[ForeignKeyInfo], target: &[ForeignKeyInfo]) -> Vec<ForeignKeyDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &ForeignKeyInfo> = target.iter().map(|fk| (fk.name.as_str(), fk)).collect();+ let source_map: HashMap<&str, &ForeignKeyInfo> = source.iter().map(|fk| (fk.name.as_str(), fk)).collect();++ for source_fk in source {+ let Some(target_fk) = target_map.get(source_fk.name.as_str()) else {+ diffs.push(ForeignKeyDiff {+ diff_type: "added".to_string(),+ name: source_fk.name.clone(),+ source: Some(source_fk.clone()),+ target: None,+ changes: Vec::new(),+ });+ continue;+ };++ let mut changes = Vec::new();+ if source_fk.column != target_fk.column {+ changes.push(format!("column: {} → {}", target_fk.column, source_fk.column));+ }+ if source_fk.ref_table != target_fk.ref_table {+ changes.push(format!("ref table: {} → {}", target_fk.ref_table, source_fk.ref_table));+ }+ if source_fk.ref_schema != target_fk.ref_schema {+ changes.push(format!(+ "ref schema: {} → {}",+ target_fk.ref_schema.as_deref().unwrap_or(""),+ source_fk.ref_schema.as_deref().unwrap_or("")+ ));+ }+ if source_fk.ref_column != target_fk.ref_column {+ changes.push(format!("ref column: {} → {}", target_fk.ref_column, source_fk.ref_column));+ }+ let source_on_delete = normalized_foreign_key_action(source_fk.on_delete.as_deref());+ let target_on_delete = normalized_foreign_key_action(target_fk.on_delete.as_deref());+ if source_on_delete != target_on_delete {+ changes.push(format!(+ "delete: {} → {}",+ target_on_delete.as_deref().unwrap_or(""),+ source_on_delete.as_deref().unwrap_or("")+ ));+ }+ let source_on_update = normalized_foreign_key_action(source_fk.on_update.as_deref());+ let target_on_update = normalized_foreign_key_action(target_fk.on_update.as_deref());+ if source_on_update != target_on_update {+ changes.push(format!(+ "update: {} → {}",+ target_on_update.as_deref().unwrap_or(""),+ source_on_update.as_deref().unwrap_or("")+ ));+ }+ if !changes.is_empty() {+ diffs.push(ForeignKeyDiff {+ diff_type: "modified".to_string(),+ name: source_fk.name.clone(),+ source: Some(source_fk.clone()),+ target: Some((*target_fk).clone()),+ changes,+ });+ }+ }++ for target_fk in target {+ if !source_map.contains_key(target_fk.name.as_str()) {+ diffs.push(ForeignKeyDiff {+ diff_type: "removed".to_string(),+ name: target_fk.name.clone(),+ source: None,+ target: Some(target_fk.clone()),+ changes: Vec::new(),+ });+ }+ }++ diffs+}++pub fn diff_triggers(source: &[TriggerInfo], target: &[TriggerInfo]) -> Vec<TriggerDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &TriggerInfo> =+ target.iter().map(|trigger| (trigger.name.as_str(), trigger)).collect();+ let source_map: HashMap<&str, &TriggerInfo> =+ source.iter().map(|trigger| (trigger.name.as_str(), trigger)).collect();++ for source_trigger in source {+ let Some(target_trigger) = target_map.get(source_trigger.name.as_str()) else {+ diffs.push(TriggerDiff {+ diff_type: "added".to_string(),+ name: source_trigger.name.clone(),+ source: Some(source_trigger.clone()),+ target: None,+ changes: Vec::new(),+ });+ continue;+ };++ let mut changes = Vec::new();+ if source_trigger.event != target_trigger.event {+ changes.push(format!("event: {} → {}", target_trigger.event, source_trigger.event));+ }+ if source_trigger.timing != target_trigger.timing {+ changes.push(format!("timing: {} → {}", target_trigger.timing, source_trigger.timing));+ }+ if !changes.is_empty() {+ diffs.push(TriggerDiff {+ diff_type: "modified".to_string(),+ name: source_trigger.name.clone(),+ source: Some(source_trigger.clone()),+ target: Some((*target_trigger).clone()),+ changes,+ });+ }+ }++ for target_trigger in target {+ if !source_map.contains_key(target_trigger.name.as_str()) {+ diffs.push(TriggerDiff {+ diff_type: "removed".to_string(),+ name: target_trigger.name.clone(),+ source: None,+ target: Some(target_trigger.clone()),+ changes: Vec::new(),+ });+ }+ }++ diffs+}++/// Normalize a function definition for comparison by:+/// - Converting CRLF to LF+/// - Collapsing all whitespace (tabs, multiple spaces) to single spaces+/// - Trimming each line and rejoining+pub(crate) fn normalize_definition(def: &str) -> String {+ def.replace("\r\n", "\n")+ .split('\n')+ .map(|line| line.split_whitespace().collect::<Vec<_>>().join(" "))+ .collect::<Vec<_>>()+ .join("\n")+}++pub fn diff_functions(source: &[FunctionInfo], target: &[FunctionInfo]) -> Vec<FunctionDiff> {+ let mut diffs = Vec::new();+ // Use (name, arguments) as key to support PostgreSQL function overloading+ let target_map: HashMap<(&str, &str), &FunctionInfo> =+ target.iter().map(|f| ((f.name.as_str(), f.arguments.as_str()), f)).collect();+ let source_map: HashMap<(&str, &str), &FunctionInfo> =+ source.iter().map(|f| ((f.name.as_str(), f.arguments.as_str()), f)).collect();++ for source_fn in source {+ let key = (source_fn.name.as_str(), source_fn.arguments.as_str());+ let Some(target_fn) = target_map.get(&key) else {+ diffs.push(FunctionDiff {+ diff_type: "added".to_string(),+ name: source_fn.name.clone(),+ source: Some(source_fn.clone()),+ target: None,+ changes: Vec::new(),+ });+ continue;+ };++ let mut changes = Vec::new();+ if source_fn.function_type != target_fn.function_type {+ changes.push(format!("type: {} → {}", target_fn.function_type, source_fn.function_type));+ }+ if source_fn.data_type != target_fn.data_type {+ changes.push(format!("return type: {} → {}", target_fn.data_type, source_fn.data_type));+ }+ if normalize_definition(&source_fn.definition) != normalize_definition(&target_fn.definition) {+ changes.push("definition changed".to_string());+ }+ if !changes.is_empty() {+ diffs.push(FunctionDiff {+ diff_type: "modified".to_string(),+ name: source_fn.name.clone(),+ source: Some(source_fn.clone()),+ target: Some((*target_fn).clone()),+ changes,+ });+ }+ }++ for target_fn in target {+ let key = (target_fn.name.as_str(), target_fn.arguments.as_str());+ if !source_map.contains_key(&key) {+ diffs.push(FunctionDiff {+ diff_type: "removed".to_string(),+ name: target_fn.name.clone(),+ source: None,+ target: Some(target_fn.clone()),+ changes: Vec::new(),+ });+ }+ }++ diffs+}++pub fn diff_sequences(source: &[SequenceInfo], target: &[SequenceInfo]) -> Vec<SequenceDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &SequenceInfo> = target.iter().map(|s| (s.name.as_str(), s)).collect();+ let source_map: HashMap<&str, &SequenceInfo> = source.iter().map(|s| (s.name.as_str(), s)).collect();++ for source_seq in source {+ let Some(target_seq) = target_map.get(source_seq.name.as_str()) else {+ diffs.push(SequenceDiff {+ diff_type: "added".to_string(),+ name: source_seq.name.clone(),+ source: Some(source_seq.clone()),+ target: None,+ changes: Vec::new(),+ });+ continue;+ };++ let mut changes = Vec::new();+ if source_seq.data_type != target_seq.data_type {+ changes.push(format!("data_type: {} → {}", target_seq.data_type, source_seq.data_type));+ }+ if source_seq.start_value != target_seq.start_value {+ changes.push(format!("start: {} → {}", target_seq.start_value, source_seq.start_value));+ }+ if source_seq.min_value != target_seq.min_value {+ changes.push(format!("min: {} → {}", target_seq.min_value, source_seq.min_value));+ }+ if source_seq.max_value != target_seq.max_value {+ changes.push(format!("max: {} → {}", target_seq.max_value, source_seq.max_value));+ }+ if source_seq.increment != target_seq.increment {+ changes.push(format!("increment: {} → {}", target_seq.increment, source_seq.increment));+ }+ if source_seq.cycle != target_seq.cycle {+ changes.push(format!("cycle: {} → {}", target_seq.cycle, source_seq.cycle));+ }+ // Only compare last_value when both sides successfully retrieved it.+ // Avoid false positives when one side lacks permission (returns None).+ if let (Some(s), Some(t)) = (&source_seq.last_value, &target_seq.last_value) {+ if s != t {+ changes.push(format!("last_value: {} → {}", t, s));+ }+ }+ if !changes.is_empty() {+ diffs.push(SequenceDiff {+ diff_type: "modified".to_string(),+ name: source_seq.name.clone(),+ source: Some(source_seq.clone()),+ target: Some((*target_seq).clone()),+ changes,+ });+ }+ }++ for target_seq in target {+ if !source_map.contains_key(target_seq.name.as_str()) {+ diffs.push(SequenceDiff {+ diff_type: "removed".to_string(),+ name: target_seq.name.clone(),+ source: None,+ target: Some(target_seq.clone()),+ changes: Vec::new(),+ });+ }+ }++ diffs+}++pub fn diff_rules(source: &[RuleInfo], target: &[RuleInfo]) -> Vec<RuleDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &RuleInfo> = target.iter().map(|r| (r.name.as_str(), r)).collect();+ let source_map: HashMap<&str, &RuleInfo> = source.iter().map(|r| (r.name.as_str(), r)).collect();++ for source_rule in source {+ let Some(target_rule) = target_map.get(source_rule.name.as_str()) else {+ diffs.push(RuleDiff {+ diff_type: "added".to_string(),+ name: source_rule.name.clone(),+ source: Some(source_rule.clone()),+ target: None,+ changes: Vec::new(),+ });+ continue;+ };++ let mut changes = Vec::new();+ if source_rule.definition != target_rule.definition {+ changes.push("definition changed".to_string());+ }+ if !changes.is_empty() {+ diffs.push(RuleDiff {+ diff_type: "modified".to_string(),+ name: source_rule.name.clone(),+ source: Some(source_rule.clone()),+ target: Some((*target_rule).clone()),+ changes,+ });+ }+ }++ for target_rule in target {+ if !source_map.contains_key(target_rule.name.as_str()) {+ diffs.push(RuleDiff {+ diff_type: "removed".to_string(),+ name: target_rule.name.clone(),+ source: None,+ target: Some(target_rule.clone()),+ changes: Vec::new(),+ });+ }+ }++ diffs+}++pub fn diff_owners(source: &[OwnerInfo], target: &[OwnerInfo]) -> Vec<OwnerDiff> {+ let mut diffs = Vec::new();+ let target_map: HashMap<&str, &OwnerInfo> = target.iter().map(|o| (o.object_name.as_str(), o)).collect();+ let _source_map: HashMap<&str, &OwnerInfo> = source.iter().map(|o| (o.object_name.as_str(), o)).collect();++ for source_owner in source {+ let Some(target_owner) = target_map.get(source_owner.object_name.as_str()) else {+ continue; // skip added/removed objects, only compare owners for common objects+ };++ let mut changes = Vec::new();+ if source_owner.owner != target_owner.owner {+ changes.push(format!("owner: {} → {}", target_owner.owner, source_owner.owner));+ }+ if !changes.is_empty() {+ diffs.push(OwnerDiff {+ diff_type: "modified".to_string(),+ object_name: source_owner.object_name.clone(),+ source: Some(source_owner.clone()),+ target: Some((*target_owner).clone()),+ changes,+ });+ }+ }++ diffs+}++fn quote_id(name: &str, db_type: DatabaseType) -> String {+ profile_for(db_type).quote_ident(name)+}++fn column_def(col: &ColumnInfo, db_type: DatabaseType) -> String {+ let profile = profile_for(db_type);+ let mut definition = format!("{} {}", quote_id(&col.name, db_type), col.data_type);+ if !col.is_nullable {+ definition.push_str(" NOT NULL");+ }+ if let Some(default) = &col.column_default {+ definition.push_str(&format!(" DEFAULT {default}"));+ }+ if profile.inline_column_comment {+ if let Some(comment) = &col.comment {+ definition.push_str(&format!(" COMMENT {}", comment_literal(comment)));+ }+ }+ definition+}++fn qualified_name(name: &str, db_type: DatabaseType, schema: Option<&str>) -> String {+ schema+ .map(str::trim)+ .filter(|schema| !schema.is_empty())+ .map(|schema| format!("{}.{}", quote_id(schema, db_type), quote_id(name, db_type)))+ .unwrap_or_else(|| quote_id(name, db_type))+}++fn drop_index_sql(table_name: &str, index_name: &str, db_type: DatabaseType, schema: Option<&str>) -> String {+ let profile = profile_for(db_type);+ let table = qualified_name(table_name, db_type, schema);+ let index = qualified_name(index_name, db_type, schema);+ if profile.drop_index_uses_on_table {+ format!("DROP INDEX {} ON {table};", quote_id(index_name, db_type))+ } else {+ format!("DROP INDEX IF EXISTS {index};")+ }+}++fn mysql_index_column_sql(column: &str) -> String {+ let trimmed = column.trim();+ // MySQL metadata represents a functional key part as an expression wrapped for CREATE INDEX.+ if trimmed.starts_with("((") && trimmed.ends_with("))") {+ trimmed.to_string()+ } else {+ quote_id(column, DatabaseType::Mysql)+ }+}++fn create_index_sql(table_name: &str, index: &IndexInfo, db_type: DatabaseType, schema: Option<&str>) -> String {+ use crate::sql_dialect::ddl_profile::IndexTypePlacement;+ let profile = profile_for(db_type);+ let table = qualified_name(table_name, db_type, schema);+ let columns =+ index+ .columns+ .iter()+ .map(|column| {+ if db_type == DatabaseType::Mysql {+ mysql_index_column_sql(column)+ } else {+ quote_id(column, db_type)+ }+ })+ .collect::<Vec<_>>()+ .join(", ");+ let unique = if index.is_unique { "UNIQUE " } else { "" };+ let index_type = index.index_type.as_deref().unwrap_or_default();+ let (type_prefix, using_before_on, using_suffix) = if index_type.is_empty() {+ (String::new(), String::new(), String::new())+ } else {+ match profile.index_type_placement {+ IndexTypePlacement::None => (String::new(), String::new(), String::new()),+ IndexTypePlacement::TypePrefix => (format!("{index_type} "), String::new(), String::new()),+ IndexTypePlacement::UsingBeforeOn => (String::new(), format!(" USING {index_type}"), String::new()),+ IndexTypePlacement::UsingSuffix => (String::new(), String::new(), format!(" USING {index_type}")),+ }+ };+ let included_columns = index.included_columns.clone().unwrap_or_default();+ let include_clause = if !included_columns.is_empty() && profile.index_supports_include {+ format!(+ " INCLUDE ({})",+ included_columns.iter().map(|column| quote_id(column, db_type)).collect::<Vec<_>>().join(", ")+ )+ } else {+ String::new()+ };+ let filter = if profile.index_supports_filter { index.filter.as_deref().unwrap_or_default() } else { "" };+ let filter_clause = if filter.is_empty() { String::new() } else { format!(" WHERE {filter}") };+ let comment = index.comment.as_deref().unwrap_or("");+ let comment_clause = if !comment.trim().is_empty() && profile.index_supports_comment {+ format!(" COMMENT {}", comment_literal(comment))+ } else {+ String::new()+ };+ // MySQL-style puts USING before ON and omits INCLUDE/WHERE placement used by PG/SS.+ if profile.drop_index_uses_on_table {+ format!(+ "CREATE {unique}{type_prefix}INDEX {}{using_before_on} ON {table} ({columns}){comment_clause};",+ quote_id(&index.name, db_type)+ )+ } else {+ format!(+ "CREATE {unique}{type_prefix}INDEX {} ON {table}{using_suffix} ({columns}){include_clause}{filter_clause};",+ quote_id(&index.name, db_type)+ )+ }+}++fn drop_foreign_key_sql(table_name: &str, fk_name: &str, db_type: DatabaseType, schema: Option<&str>) -> String {+ let profile = profile_for(db_type);+ let table = qualified_name(table_name, db_type, schema);+ let fk = quote_id(fk_name, db_type);+ if profile.drop_fk_as_foreign_key {+ format!("ALTER TABLE {table} DROP FOREIGN KEY {fk};")+ } else {+ format!("ALTER TABLE {table} DROP CONSTRAINT {fk};")+ }+}++fn add_foreign_key_sql(table_name: &str, fk: &ForeignKeyInfo, db_type: DatabaseType, schema: Option<&str>) -> String {+ let table = qualified_name(table_name, db_type, schema);+ let ref_table = qualified_name(&fk.ref_table, db_type, fk.ref_schema.as_deref().or(schema));+ let on_delete = fk.on_delete.as_ref().map(|action| format!(" ON DELETE {action}")).unwrap_or_default();+ let on_update = fk.on_update.as_ref().map(|action| format!(" ON UPDATE {action}")).unwrap_or_default();+ format!(+ "ALTER TABLE {table} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {ref_table} ({}){on_delete}{on_update};",+ quote_id(&fk.name, db_type),+ quote_id(&fk.column, db_type),+ quote_id(&fk.ref_column, db_type)+ )+}++fn drop_object_sql(diff: &TableDiff, db_type: DatabaseType, schema: Option<&str>, cascade: &str) -> String {+ let object_type = if diff.object_type.as_deref() == Some("view") { "VIEW" } else { "TABLE" };+ format!("DROP {object_type} IF EXISTS {}{cascade};", qualified_name(&diff.name, db_type, schema))+}++fn comment_literal(comment: &str) -> String {+ format!("'{}'", comment.replace('\'', "''"))+}++fn column_comment_sql(+ table_name: &str,+ column_name: &str,+ comment: &str,+ db_type: DatabaseType,+ schema: Option<&str>,+) -> String {+ let profile = profile_for(db_type);+ if profile.column_comment_via_modify_only {+ return format!("-- Column comment for {column_name}: use ALTER TABLE ... MODIFY COLUMN to set comment");+ }+ let table = qualified_name(table_name, db_type, schema);+ format!("COMMENT ON COLUMN {table}.{} IS {};", quote_id(column_name, db_type), comment_literal(comment))+}++fn table_comment_sql(table_name: &str, comment: &str, db_type: DatabaseType, schema: Option<&str>) -> String {+ let profile = profile_for(db_type);+ let table = qualified_name(table_name, db_type, schema);+ if profile.table_comment_via_alter {+ format!("ALTER TABLE {table} COMMENT = {};", comment_literal(comment))+ } else {+ format!("COMMENT ON TABLE {table} IS {};", comment_literal(comment))+ }+}++fn create_trigger_sql(+ profile: &crate::sql_dialect::ddl_profile::DdlDialectProfile,+ name: &str,+ timing: &str,+ event: &str,+ table: &str,+ body: &str,+) -> String {+ use crate::sql_dialect::ddl_profile::TriggerTemplate;+ let qname = profile.quote_ident(name);+ match profile.trigger_template {+ TriggerTemplate::MysqlStyle => {+ format!("CREATE TRIGGER {qname} {timing} {event} ON {table} FOR EACH ROW BEGIN\n{body} END;")+ }+ TriggerTemplate::PostgresStyle => {+ format!(+ "CREATE TRIGGER {qname} {timing} {event} ON {table} FOR EACH ROW EXECUTE FUNCTION {};",+ body.trim_end_matches(';')+ )+ }+ TriggerTemplate::SqlServerStyle => {+ format!("CREATE TRIGGER {qname} ON {table} {timing} {event} AS BEGIN {body} END;")+ }+ TriggerTemplate::GenericRowBody => {+ format!("CREATE TRIGGER {qname} {timing} {event} ON {table} FOR EACH ROW BEGIN {body} END;")+ }+ }+}++fn generate_create_table_sql(+ name: &str,+ columns: &[ColumnDiff],+ indexes: &[IndexDiff],+ foreign_keys: &[ForeignKeyDiff],+ table_comment: Option<&str>,+ db_type: DatabaseType,+ schema: Option<&str>,+ source_dialect: Option<DialectKind>,+ field_mappings: &[FieldMapping],+ triggers: &[TriggerInfo],+) -> (String, Vec<MissingRollbackObject>) {+ let mut lines = Vec::new();+ let target_dialect = DialectKind::from_database_type(db_type);+ let profile = profile_for(db_type);+ // Type rewrite: user mappings → profile type_map → DialectKind matrix → normalize.+ // Call sites must not branch on individual DatabaseType values.+ let map_type = |source_type: &str| -> String {+ if let Some(user_target) = FieldMapping::apply_with_params(field_mappings, source_type, target_dialect) {+ return user_target;+ }+ rewrite_column_type(source_type, db_type, source_dialect)+ };+ let table = qualified_name(name, db_type, schema);++ // Collect column definitions+ let mut col_defs = Vec::new();+ let mut pk_cols = Vec::new();+ let mut has_int_pk = false;+ let mut auto_col_name: Option<String> = None;++ for col_diff in columns {+ let Some(col) = &col_diff.source else {+ continue;+ };+ let col_name = quote_id(&col.name, db_type);+ let mapped_type = map_type(&col.data_type);+ let is_int = type_looks_integer(&mapped_type);+ let auto_build = apply_auto_inc_to_column_def(&profile, &col_name, &mapped_type, col, is_int);++ match auto_build {+ AutoIncColumnBuild::Complete { def, .. } => {+ col_defs.push(def);+ if col.is_primary_key {+ pk_cols.push(col_name);+ }+ continue;+ }+ AutoIncColumnBuild::AppendSuffix { suffix, skip_default, postgres_sequence } => {+ let mut def = format!("{} {}", col_name, mapped_type);+ if !col.is_nullable {+ def.push_str(" NOT NULL");+ }+ if !skip_default {+ if let Some(default) = &col.column_default {+ def.push_str(&format!(" DEFAULT {default}"));+ }+ }+ if profile.inline_column_comment {+ if let Some(comment) = col.comment.as_deref().filter(|c| !c.is_empty()) {+ def.push_str(&format!(" COMMENT {}", comment_literal(comment)));+ }+ }+ if !suffix.is_empty() {+ def.push_str(suffix);+ }+ if postgres_sequence {+ has_int_pk = true;+ auto_col_name = Some(col.name.clone());+ }+ col_defs.push(def);+ if col.is_primary_key {+ pk_cols.push(quote_id(&col.name, db_type));+ }+ }+ AutoIncColumnBuild::Normal { skip_default } => {+ let mut def = format!("{} {}", col_name, mapped_type);+ if !col.is_nullable {+ def.push_str(" NOT NULL");+ }+ if !skip_default {+ if let Some(default) = &col.column_default {+ def.push_str(&format!(" DEFAULT {default}"));+ }+ }+ if profile.inline_column_comment {+ if let Some(comment) = col.comment.as_deref().filter(|c| !c.is_empty()) {+ def.push_str(&format!(" COMMENT {}", comment_literal(comment)));+ }+ }+ col_defs.push(def);+ if col.is_primary_key {+ pk_cols.push(quote_id(&col.name, db_type));+ }+ }+ }+ }++ if profile.foreign_keys_inline_in_create {+ for fk_diff in foreign_keys {+ let Some(fk) = &fk_diff.source else {+ continue;+ };+ let ref_table = qualified_name(&fk.ref_table, db_type, fk.ref_schema.as_deref().or(schema));+ let on_delete = fk.on_delete.as_ref().map(|action| format!(" ON DELETE {action}")).unwrap_or_default();+ let on_update = fk.on_update.as_ref().map(|action| format!(" ON UPDATE {action}")).unwrap_or_default();+ col_defs.push(format!(+ "CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {}({}){}{}",+ quote_id(&fk.name, db_type),+ quote_id(&fk.column, db_type),+ ref_table,+ quote_id(&fk.ref_column, db_type),+ on_delete,+ on_update+ ));+ }+ }++ let mut create = format!("CREATE TABLE {} (\n", table);+ create.push_str(&format!(" {}", col_defs.join(",\n ")));++ if !pk_cols.is_empty() {+ create.push_str(&format!(",\n PRIMARY KEY ({})", pk_cols.join(", ")));+ }++ create.push_str("\n);");+ lines.push(format!("-- Create table: {}", name));+ lines.push(create);+ lines.push(String::new());++ // Postgres identity / sequence+ if has_int_pk {+ if let Some(seq_col) = auto_col_name {+ let seq_name = format!("{}_{}_seq", name, seq_col);+ let quoted_seq = quote_id(&seq_name, db_type);+ let quoted_col = quote_id(&seq_col, db_type);+ lines.push(format!("CREATE SEQUENCE IF NOT EXISTS {} OWNED BY {}.{};", quoted_seq, table, quoted_col));+ lines.push(format!(+ "ALTER TABLE {} ALTER COLUMN {} SET DEFAULT nextval('{}');",+ table, quoted_col, seq_name+ ));+ lines.push(format!("ALTER SEQUENCE {} START WITH 1;", quoted_seq));+ lines.push(String::new());+ }+ }++ // Indexes+ for idx_diff in indexes {+ let Some(idx) = &idx_diff.source else {+ continue;+ };+ if idx.is_primary {+ continue;+ }+ lines.push(create_index_sql(name, idx, db_type, schema));+ }+ if !indexes.is_empty() {+ lines.push(String::new());+ }++ // Foreign Keys (skipped when already inlined into CREATE TABLE via profile)+ for fk_diff in foreign_keys {+ if profile.foreign_keys_inline_in_create {+ continue;+ }+ let Some(fk) = &fk_diff.source else {+ continue;+ };+ let fk_name = quote_id(&fk.name, db_type);+ let fk_col = quote_id(&fk.column, db_type);+ let ref_table = qualified_name(&fk.ref_table, db_type, fk.ref_schema.as_deref().or(schema));+ let ref_col = quote_id(&fk.ref_column, db_type);+ let on_delete = fk.on_delete.as_ref().map(|a| format!(" ON DELETE {}", a)).unwrap_or_default();+ let on_update = fk.on_update.as_ref().map(|a| format!(" ON UPDATE {}", a)).unwrap_or_default();+ lines.push(format!(+ "ALTER TABLE {} ADD CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {}({}){}{};",+ table, fk_name, fk_col, ref_table, ref_col, on_delete, on_update+ ));+ }+ if !foreign_keys.is_empty() {+ lines.push(String::new());+ }++ // Column comments (ANSI COMMENT ON … when profile does not use inline COMMENT)+ for col_diff in columns {+ let Some(col) = &col_diff.source else {+ continue;+ };+ if let Some(comment) = &col.comment {+ if !comment.is_empty() {+ let col_name = quote_id(&col.name, db_type);+ let esc_comment = comment.replace('\'', "''");+ if !profile.inline_column_comment {+ lines.push(format!("COMMENT ON COLUMN {}.{} IS '{}';", table, col_name, esc_comment));+ }+ }+ }+ }++ // Table comment+ if let Some(comment) = table_comment {+ if !comment.is_empty() {+ lines.push(table_comment_sql(name, comment, db_type, schema));+ }+ }++ // Trigger recreation — collect structured missing objects (do not rely on SQL comments alone).+ let mut missing: Vec<MissingRollbackObject> = Vec::new();+ if !triggers.is_empty() {+ lines.push(String::new());+ for trigger in triggers {+ let event_desc = if trigger.event.to_uppercase().contains("INSERT") {+ "INSERT"+ } else if trigger.event.to_uppercase().contains("UPDATE") {+ "UPDATE"+ } else if trigger.event.to_uppercase().contains("DELETE") {+ "DELETE"+ } else {+ &trigger.event+ };+ let timing = &trigger.timing;++ if let Some(stmt) = &trigger.statement {+ if !stmt.trim().is_empty() {+ lines.push(create_trigger_sql(&profile, &trigger.name, timing, event_desc, &table, stmt));+ } else {+ missing.push(MissingRollbackObject {+ kind: "trigger".to_string(),+ name: trigger.name.clone(),+ table: Some(name.to_string()),+ reason: "trigger body is empty; cannot reconstruct CREATE TRIGGER".to_string(),+ });+ }+ } else {+ missing.push(MissingRollbackObject {+ kind: "trigger".to_string(),+ name: trigger.name.clone(),+ table: Some(name.to_string()),+ reason: "trigger statement/body missing from schema snapshot".to_string(),+ });+ }+ }+ if !missing.is_empty() {+ lines.push(String::new());+ lines.push(format!(+ "-- WARNING: Rollback DDL is INCOMPLETE — one or more triggers on table '{}' could not be reconstructed.",+ name+ ));+ lines.push("-- Manual intervention required before executing this rollback script.".to_string());+ for m in &missing {+ lines.push(format!("-- missing {}: {} ({})", m.kind, m.name, m.reason));+ }+ }+ }++ (lines.join("\n"), missing)+}++#[allow(clippy::too_many_arguments)]+pub fn generate_schema_sync_sql(+ diffs: &[TableDiff],+ function_diffs: &[FunctionDiff],+ sequence_diffs: &[SequenceDiff],+ rule_diffs: &[RuleDiff],+ owner_diffs: &[OwnerDiff],+ db_type: DatabaseType,+ schema: Option<&str>,+ cascade_delete: bool,+ source_dialect: Option<DialectKind>,+ field_mappings: &[FieldMapping],+) -> String {+ generate_schema_sync_sql_inner(+ diffs,+ function_diffs,+ sequence_diffs,+ rule_diffs,+ owner_diffs,+ db_type,+ schema,+ cascade_delete,+ source_dialect,+ field_mappings,+ )+ .0+}++fn generate_schema_sync_sql_inner(+ diffs: &[TableDiff],+ function_diffs: &[FunctionDiff],+ sequence_diffs: &[SequenceDiff],+ rule_diffs: &[RuleDiff],+ owner_diffs: &[OwnerDiff],+ db_type: DatabaseType,+ schema: Option<&str>,+ cascade_delete: bool,+ source_dialect: Option<DialectKind>,+ field_mappings: &[FieldMapping],+) -> (String, Vec<MissingRollbackObject>) {+ let mut lines = Vec::new();+ let mut missing_objects: Vec<MissingRollbackObject> = Vec::new();+ let profile = profile_for(db_type);+ let cascade = if cascade_delete { " CASCADE" } else { "" };++ let map_type = |source_type: &str| -> String {+ let tgt = DialectKind::from_database_type(db_type);+ if let Some(user_target) = FieldMapping::apply_with_params(field_mappings, source_type, tgt) {+ return user_target;+ }+ rewrite_column_type(source_type, db_type, source_dialect)+ };++ for diff in diffs {+ let table = qualified_name(&diff.name, db_type, schema);++ if diff.diff_type == "added" && diff.object_type.as_deref() != Some("view") {+ let has_structured_snapshot = diff.columns.as_ref().is_some_and(|columns| !columns.is_empty());+ let is_rollback_recreation = diff.ddl.is_none() && diff.target_ddl.is_some();+ let is_same_dialect =+ source_dialect.map(|src| DialectKind::from_database_type(db_type) == src).unwrap_or(false);+ if is_rollback_recreation {+ if has_structured_snapshot {+ let trigger_infos: Vec<TriggerInfo> = diff+ .triggers+ .as_ref()+ .map_or_else(Vec::new, |triggers| triggers.iter().filter_map(|t| t.source.clone()).collect());+ let (generated, missing) = generate_create_table_sql(+ &diff.name,+ diff.columns.as_ref().map_or(&[] as &[ColumnDiff], |columns| columns.as_slice()),+ diff.indexes.as_ref().map_or(&[] as &[IndexDiff], |indexes| indexes.as_slice()),+ diff.foreign_keys+ .as_ref()+ .map_or(&[] as &[ForeignKeyDiff], |foreign_keys| foreign_keys.as_slice()),+ diff.source_table_comment.as_ref().and_then(|comment| comment.as_deref()),+ db_type,+ schema,+ None,+ field_mappings,+ &trigger_infos,+ );+ if !generated.is_empty() {+ lines.push(generated);+ }+ missing_objects.extend(missing);+ } else if let Some(ddl) = diff.target_ddl.as_deref() {+ // Inversion places only the removed target table's native+ // DDL here, validating that it belongs to the dialect restored.+ lines.push(format!("-- Recreate table from native target DDL: {}", diff.name));+ lines.push(format!("{};", ddl.trim_end_matches(';')));+ lines.push(String::new());+ }+ } else if is_same_dialect+ || (source_dialect.is_none()+ && diff.ddl.is_some()+ && (profile.prefers_native_source_ddl || !has_structured_snapshot))+ {+ // Prefer native source DDL when the target profile wants it+ // (MySQL-family), or as fallback without a structured snapshot.+ if let Some(ddl) = &diff.ddl {+ lines.push(format!("-- Create {}: {}", diff.object_type.as_deref().unwrap_or("table"), diff.name));+ lines.push(format!("{};", ddl));+ lines.push(String::new());+ } else if let Some(cols) = &diff.columns {+ let trigger_infos: Vec<TriggerInfo> = diff+ .triggers+ .as_ref()+ .map_or_else(Vec::new, |triggers| triggers.iter().filter_map(|t| t.source.clone()).collect());+ let (gen, missing) = generate_create_table_sql(+ &diff.name,+ cols,+ diff.indexes.as_ref().map_or(&[] as &[IndexDiff], |v| v.as_slice()),+ diff.foreign_keys.as_ref().map_or(&[] as &[ForeignKeyDiff], |v| v.as_slice()),+ diff.source_table_comment.as_ref().and_then(|c| c.as_deref()),+ db_type,+ schema,+ source_dialect,+ field_mappings,+ &trigger_infos,+ );+ if !gen.is_empty() {+ lines.push(gen);+ }+ missing_objects.extend(missing);+ }+ } else if has_structured_snapshot {+ // Cross-dialect → generate CREATE TABLE from column info+ let _cols: &[ColumnDiff] = diff.columns.as_ref().map_or(&[] as &[ColumnDiff], |v| v.as_slice());+ let _idxs: &[IndexDiff] = diff.indexes.as_ref().map_or(&[] as &[IndexDiff], |v| v.as_slice());+ let _fks: &[ForeignKeyDiff] =+ diff.foreign_keys.as_ref().map_or(&[] as &[ForeignKeyDiff], |v| v.as_slice());+ let trigger_infos: Vec<TriggerInfo> = diff+ .triggers+ .as_ref()+ .map_or_else(Vec::new, |triggers| triggers.iter().filter_map(|t| t.source.clone()).collect());+ let (gen, missing) = generate_create_table_sql(+ &diff.name,+ diff.columns.as_ref().map_or(&[] as &[ColumnDiff], |v| v.as_slice()),+ diff.indexes.as_ref().map_or(&[] as &[IndexDiff], |v| v.as_slice()),+ diff.foreign_keys.as_ref().map_or(&[] as &[ForeignKeyDiff], |v| v.as_slice()),+ diff.source_table_comment.as_ref().and_then(|c| c.as_deref()),+ db_type,+ schema,+ source_dialect,+ field_mappings,+ &trigger_infos,+ );+ if !gen.is_empty() {+ lines.push(gen);+ }+ missing_objects.extend(missing);+ }+ continue;+ }++ if diff.diff_type == "added" && diff.object_type.as_deref() == Some("view") {+ lines.push(format!("-- View exists only in source: {}", diff.name));+ lines.push("-- Source view definition is not available from this driver yet.".to_string());+ lines.push(String::new());+ continue;+ }++ if diff.diff_type == "removed" {+ lines.push(format!("-- Drop {}: {}", diff.object_type.as_deref().unwrap_or("table"), diff.name));+ lines.push(drop_object_sql(diff, db_type, schema, cascade));+ lines.push(String::new());+ continue;+ }++ if diff.diff_type != "modified" {+ continue;+ }++ let mut parts = Vec::new();+ let mut standalone_statements = Vec::new();+ if let Some(foreign_keys) = &diff.foreign_keys {+ for fk in foreign_keys {+ if fk.diff_type == "removed" || fk.diff_type == "modified" {+ lines.push(drop_foreign_key_sql(&diff.name, &fk.name, db_type, schema));+ }+ }+ }++ if let Some(columns) = &diff.columns {+ let convert_col =+ |col: &ColumnInfo| -> ColumnInfo { ColumnInfo { data_type: map_type(&col.data_type), ..col.clone() } };+ for column in columns {+ match column.diff_type.as_str() {+ "added" => {+ if let Some(source) = &column.source {+ parts.push(format!(" ADD COLUMN {}", column_def(&convert_col(source), db_type)));+ }+ }+ "removed" => {+ parts.push(format!(" DROP COLUMN {}", quote_id(&column.name, db_type)));+ }+ "modified" => {+ if let Some(source) = &column.source {+ let mapped = convert_col(source);+ if profile.alter_uses_modify_column {+ if column.changes.iter().any(|change| !change.starts_with("order:")) {+ parts.push(format!(" MODIFY COLUMN {}", column_def(&mapped, db_type)));+ }+ } else {+ let name = quote_id(&column.name, db_type);+ if column.changes.iter().any(|change| change.starts_with("type:")) {+ parts.push(format!(" ALTER COLUMN {name} TYPE {}", mapped.data_type));+ }+ if column.changes.iter().any(|change| change.starts_with("nullable:")) {+ parts.push(if source.is_nullable {+ format!(" ALTER COLUMN {name} DROP NOT NULL")+ } else {+ format!(" ALTER COLUMN {name} SET NOT NULL")+ });+ }+ if column.changes.iter().any(|change| change.starts_with("default:")) {+ parts.push(if let Some(default) = &source.column_default {+ format!(" ALTER COLUMN {name} SET DEFAULT {default}")+ } else {+ format!(" ALTER COLUMN {name} DROP DEFAULT")+ });+ }+ }+ }+ }+ "renamed" => {+ if let (Some(source), Some(target_col)) = (&column.source, &column.target) {+ use crate::sql_dialect::ddl_profile::RenameColumnSyntax;+ let mapped = convert_col(source);+ match profile.rename_column {+ RenameColumnSyntax::MysqlChangeColumn => {+ let old_name = quote_id(&target_col.name, db_type);+ parts.push(format!(+ " CHANGE COLUMN {} {}",+ old_name,+ column_def(&mapped, db_type)+ ));+ }+ RenameColumnSyntax::RenameColumn => {+ let old_name = quote_id(&target_col.name, db_type);+ let new_name = quote_id(&column.name, db_type);+ parts.push(format!(" RENAME COLUMN {old_name} TO {new_name}"));+ if source.data_type.to_lowercase() != target_col.data_type.to_lowercase() {+ parts.push(format!(" ALTER COLUMN {new_name} TYPE {}", mapped.data_type));+ }+ if source.is_nullable != target_col.is_nullable {+ let action = if source.is_nullable { "DROP NOT NULL" } else { "SET NOT NULL" };+ parts.push(format!(" ALTER COLUMN {new_name} {action}"));+ }+ }+ RenameColumnSyntax::AlterColumnRenameTo => {+ let old_name = quote_id(&target_col.name, db_type);+ let new_name = quote_id(&column.name, db_type);+ parts.push(format!(" ALTER COLUMN {old_name} RENAME TO {new_name}"));+ if source.data_type.to_lowercase() != target_col.data_type.to_lowercase() {+ parts.push(format!(+ " ALTER COLUMN {new_name} SET DATA TYPE {}",+ mapped.data_type+ ));+ }+ }+ RenameColumnSyntax::SqlServerSpRename => {+ let target_table = qualified_name(&diff.name, db_type, schema);+ let full_obj_path =+ format!("{target_table}.{}", quote_id(&target_col.name, db_type));+ standalone_statements.push(format!(+ "EXEC sp_rename '{}', '{}', 'COLUMN';",+ full_obj_path.replace('\'', "''"),+ column.name.replace('\'', "''")+ ));+ }+ }+ }+ }+ _ => {}+ }+ }+ }++ if !standalone_statements.is_empty() || !parts.is_empty() {+ lines.push(format!("-- Alter table: {}", diff.name));+ lines.extend(standalone_statements);+ if !parts.is_empty() {+ if profile.alter_batches_clauses {+ lines.push(format!("ALTER TABLE {table}"));+ lines.push(format!("{};", parts.join(",\n")));+ } else {+ for part in parts {+ lines.push(format!("ALTER TABLE {table}{part};"));+ }+ }+ }+ lines.push(String::new());+ }++ if !profile.column_comment_via_modify_only {+ if let Some(columns) = &diff.columns {+ for column in columns {+ if let Some(source) = &column.source {+ if column.changes.iter().any(|change| change.starts_with("comment:")) {+ lines.push(column_comment_sql(+ &diff.name,+ &column.name,+ source.comment.as_deref().unwrap_or_default(),+ db_type,+ schema,+ ));+ }+ if column.diff_type == "added" {+ if let Some(comment) = &source.comment {+ lines.push(column_comment_sql(&diff.name, &column.name, comment, db_type, schema));+ }+ }+ if column.diff_type == "renamed" {+ if let Some(comment) = &source.comment {+ lines.push(column_comment_sql(&diff.name, &column.name, comment, db_type, schema));+ }+ }+ }+ }+ }+ }++ if diff.source_table_comment.is_some() && diff.source_table_comment != diff.target_table_comment {+ let comment = diff.source_table_comment.as_ref().and_then(|comment| comment.as_deref()).unwrap_or_default();+ lines.push(table_comment_sql(&diff.name, comment, db_type, schema));+ }++ if let Some(indexes) = &diff.indexes {+ for index in indexes {+ match index.diff_type.as_str() {+ "added" => {+ if let Some(source) = &index.source {+ lines.push(create_index_sql(&diff.name, source, db_type, schema));+ }+ }+ "removed" => lines.push(drop_index_sql(&diff.name, &index.name, db_type, schema)),+ "modified" => {+ if let Some(source) = &index.source {+ lines.push(drop_index_sql(&diff.name, &index.name, db_type, schema));+ lines.push(create_index_sql(&diff.name, source, db_type, schema));+ }+ }+ _ => {}+ }+ }+ }++ if let Some(foreign_keys) = &diff.foreign_keys {+ for fk in foreign_keys {+ if fk.diff_type == "added" || fk.diff_type == "modified" {+ if let Some(source) = &fk.source {+ lines.push(add_foreign_key_sql(&diff.name, source, db_type, schema));+ }+ }+ }+ }++ if let Some(triggers) = &diff.triggers {+ for trigger in triggers {+ lines.push(format!(+ "-- Trigger {}: {} on {}; review trigger definition manually.",+ trigger.diff_type, trigger.name, diff.name+ ));+ }+ }++ if diff.indexes.as_ref().is_some_and(|indexes| !indexes.is_empty())+ || diff.foreign_keys.as_ref().is_some_and(|foreign_keys| !foreign_keys.is_empty())+ || diff.triggers.as_ref().is_some_and(|triggers| !triggers.is_empty())+ {+ lines.push(String::new());+ }++ if profile.warn_fk_needs_table_rebuild+ && diff.foreign_keys.as_ref().is_some_and(|foreign_keys| !foreign_keys.is_empty())+ {+ lines.push(format!("-- Foreign key synchronization may require table rebuild for: {}", diff.name));+ lines.push(String::new());+ }+ }++ // Function diffs — only emit executable SQL when profile has templates+ if !function_diffs.is_empty() {+ lines.push(String::new());+ lines.push("-- Functions".to_string());+ for diff in function_diffs {+ match diff.diff_type.as_str() {+ "added" | "modified" => {+ if let Some(source) = &diff.source {+ if let Some(template) = profile.function_create_template {+ let verb = if diff.diff_type == "added" { "Create" } else { "Alter" };+ lines.push(format!("-- {verb} function: {}", diff.name));+ let create_kw = if profile.create_function_or_replace {+ "CREATE OR REPLACE FUNCTION"+ } else {+ "CREATE FUNCTION"+ };+ let name = qualified_name(&diff.name, db_type, schema);+ lines.push(DdlDialectProfile::render_template(+ template,+ &[("create_kw", create_kw), ("name", &name), ("definition", &source.definition)],+ ));+ } else {+ lines.push(format!(+ "-- Skip function {}: target database does not support function DDL generation",+ diff.name+ ));+ }+ }+ }+ "removed" => {+ if let Some(template) = profile.function_drop_template {+ lines.push(format!("-- Drop function: {}", diff.name));+ let name = qualified_name(&diff.name, db_type, schema);+ lines.push(DdlDialectProfile::render_template(+ template,+ &[("name", &name), ("cascade", cascade)],+ ));+ } else {+ lines.push(format!("-- Skip drop function {}: unsupported on target", diff.name));+ }+ }+ _ => {}+ }+ }+ }++ // Sequence diffs+ if !sequence_diffs.is_empty() {+ lines.push(String::new());+ lines.push("-- Sequences".to_string());+ for diff in sequence_diffs {+ match diff.diff_type.as_str() {+ "added" => {+ if let Some(source) = &diff.source {+ if let Some(template) = profile.sequence_create_template {+ lines.push(format!("-- Create sequence: {}", diff.name));+ let name = qualified_name(&diff.name, db_type, schema);+ let cycle = if source.cycle { "CYCLE" } else { "NO CYCLE" };+ lines.push(DdlDialectProfile::render_template(+ template,+ &[+ ("name", &name),+ ("data_type", &source.data_type),+ ("start_value", &source.start_value),+ ("increment", &source.increment),+ ("min_value", &source.min_value),+ ("max_value", &source.max_value),+ ("cycle", cycle),+ ],+ ));+ } else {+ lines.push(format!(+ "-- Skip sequence {}: target database does not support sequence DDL generation",+ diff.name+ ));+ }+ }+ }+ "removed" => {+ if let Some(template) = profile.sequence_drop_template {+ lines.push(format!("-- Drop sequence: {}", diff.name));+ let name = qualified_name(&diff.name, db_type, schema);+ lines.push(DdlDialectProfile::render_template(+ template,+ &[("name", &name), ("cascade", cascade)],+ ));+ } else {+ lines.push(format!("-- Skip drop sequence {}: unsupported on target", diff.name));+ }+ }+ "modified" => {+ if let Some(source) = &diff.source {+ if let Some(template) = profile.sequence_alter_template {+ lines.push(format!("-- Alter sequence: {}", diff.name));+ let name = qualified_name(&diff.name, db_type, schema);+ let cycle = if source.cycle { "CYCLE" } else { "NO CYCLE" };+ lines.push(DdlDialectProfile::render_template(+ template,+ &[+ ("name", &name),+ ("data_type", &source.data_type),+ ("start_value", &source.start_value),+ ("increment", &source.increment),+ ("min_value", &source.min_value),+ ("max_value", &source.max_value),+ ("cycle", cycle),+ ],+ ));+ } else {+ lines.push(format!("-- Skip alter sequence {}: unsupported on target", diff.name));+ }+ }+ }+ _ => {}+ }+ }+ }++ // Rule diffs (PostgreSQL RULE)+ if !rule_diffs.is_empty() {+ lines.push(String::new());+ lines.push("-- Rules".to_string());+ for diff in rule_diffs {+ if profile.rule_drop_template.is_none() && !profile.supports_rule_ddl {+ lines.push(format!("-- Skip rule {}: target database does not support RULE DDL", diff.name));+ continue;+ }+ match diff.diff_type.as_str() {+ "added" => {+ if let Some(source) = &diff.source {+ if profile.supports_rule_ddl {+ lines.push(format!("-- Create rule: {}", diff.name));+ lines.push(source.definition.clone());+ } else {+ lines+ .push(format!("-- Skip rule {}: target database does not support RULE DDL", diff.name));+ }+ }+ }+ "removed" => {+ if let Some(template) = profile.rule_drop_template {+ lines.push(format!("-- Drop rule: {}", diff.name));+ // Removed diffs store the object on `target`; tests may put it on `source`.+ if let Some(rule) = diff.source.as_ref().or(diff.target.as_ref()) {+ let table_name = qualified_name(&rule.table_name, db_type, schema);+ lines.push(DdlDialectProfile::render_template(+ template,+ &[("rule_name", &diff.name), ("table_name", &table_name), ("cascade", cascade)],+ ));+ }+ } else {+ lines.push(format!("-- Skip rule {}: target database does not support RULE DDL", diff.name));+ }+ }+ "modified" => {+ if let Some(source) = &diff.source {+ if let Some(template) = profile.rule_drop_template {+ lines.push(format!("-- Alter rule: {}", diff.name));+ let table_name = qualified_name(&source.table_name, db_type, schema);+ lines.push(DdlDialectProfile::render_template(+ template,+ &[("rule_name", &diff.name), ("table_name", &table_name), ("cascade", cascade)],+ ));+ lines.push(source.definition.clone());+ } else {+ lines+ .push(format!("-- Skip rule {}: target database does not support RULE DDL", diff.name));+ }+ }+ }+ _ => {}+ }+ }+ }++ // Owner diffs+ if !owner_diffs.is_empty() {+ lines.push(String::new());+ lines.push("-- Owners".to_string());+ for diff in owner_diffs {+ if let (Some(source), Some(_target)) = (&diff.source, &diff.target) {+ if let Some(template) = profile.owner_alter_template {+ let object_type = match source.object_type.as_str() {+ "TABLE" => "TABLE",+ "VIEW" => "VIEW",+ "SEQUENCE" => "SEQUENCE",+ _ => "TABLE",+ };+ let name = qualified_name(&diff.object_name, db_type, schema);+ lines.push(DdlDialectProfile::render_template(+ template,+ &[("object_type", object_type), ("name", &name), ("owner", &source.owner)],+ ));+ } else {+ lines.push(format!("-- Skip OWNER change for {}: unsupported on target", diff.object_name));+ }+ }+ }+ }++ (lines.join("\n").trim().to_string(), missing_objects)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn index(overrides: IndexInfo) -> IndexInfo {+ IndexInfo {+ name: if overrides.name.is_empty() { "idx_users_email".to_string() } else { overrides.name },+ columns: if overrides.columns.is_empty() { vec!["email".to_string()] } else { overrides.columns },+ is_unique: overrides.is_unique,+ is_primary: overrides.is_primary,+ filter: overrides.filter,+ index_type: overrides.index_type,+ included_columns: overrides.included_columns,+ comment: overrides.comment,+ }+ }++ fn foreign_key(overrides: ForeignKeyInfo) -> ForeignKeyInfo {+ ForeignKeyInfo {+ name: if overrides.name.is_empty() { "orders_user_id_fk".to_string() } else { overrides.name },+ column: if overrides.column.is_empty() { "user_id".to_string() } else { overrides.column },+ ref_schema: overrides.ref_schema,+ ref_table: if overrides.ref_table.is_empty() { "users".to_string() } else { overrides.ref_table },+ ref_column: if overrides.ref_column.is_empty() { "id".to_string() } else { overrides.ref_column },+ on_update: overrides.on_update,+ on_delete: overrides.on_delete,+ }+ }++ fn column(name: &str, data_type: &str, comment: Option<&str>) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: data_type.to_string(),+ is_nullable: false,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: comment.map(str::to_string),+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }+ }++ #[test]+ fn ignores_column_order_when_option_is_disabled() {+ let diffs = diff_columns_with_options(+ &[column("id", "int", None), column("name", "varchar(64)", None), column("status", "varchar(16)", None)],+ &[column("status", "varchar(16)", None), column("id", "int", None), column("name", "varchar(64)", None)],+ false,+ false,+ false,+ 0.5,+ );++ assert!(diffs.is_empty());+ }++ #[test]+ fn detects_column_order_when_option_is_enabled() {+ let diffs = diff_columns_with_options(+ &[column("id", "int", None), column("name", "varchar(64)", None), column("status", "varchar(16)", None)],+ &[column("status", "varchar(16)", None), column("id", "int", None), column("name", "varchar(64)", None)],+ false,+ true,+ false,+ 0.5,+ );++ assert_eq!(diffs.len(), 3);+ assert_eq!(diffs[0].changes, vec!["order: 2 → 1"]);+ }++ #[test]+ fn detects_column_rename_with_same_type() {+ let source = vec![+ column("id", "int", None),+ column("name2", "varchar(120)", None),+ column("del_flag", "tinyint", None),+ column("create_at", "datetime", None),+ ];+ let target =+ vec![column("id", "int", None), column("name", "varchar(120)", None), column("del_flag", "tinyint", None)];+ let diffs = diff_columns_with_options(&source, &target, false, false, true, 0.5);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ let added: Vec<_> = diffs.iter().filter(|d| d.diff_type == "added").collect();+ let removed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "removed").collect();+ assert_eq!(renamed.len(), 1, "should detect one renamed column");+ assert_eq!(renamed[0].name, "name2");+ assert_eq!(renamed[0].changes, vec!["name → name2"]);+ assert_eq!(added.len(), 1, "should have one truly added column (create_at)");+ assert_eq!(added[0].name, "create_at");+ assert!(removed.is_empty(), "should have no removed columns");+ }++ #[test]+ fn detects_column_rename_with_compatible_type() {+ let source = vec![column("col_a", "varchar(64)", None), column("col_b", "int", None)];+ let target = vec![column("col_a_old", "varchar(100)", None), column("col_b", "int", None)];+ let diffs = diff_columns_with_options(&source, &target, false, false, true, 0.5);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed.len(), 1, "should detect rename across varchar family");+ assert_eq!(renamed[0].changes, vec!["col_a_old → col_a"]);+ }++ #[test]+ fn no_rename_detection_when_disabled() {+ let source = vec![+ column("id", "int", None),+ column("name2", "varchar(120)", None),+ column("create_at", "datetime", None),+ ];+ let target = vec![column("id", "int", None), column("name", "varchar(120)", None)];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ let added: Vec<_> = diffs.iter().filter(|d| d.diff_type == "added").collect();+ let removed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "removed").collect();+ assert!(renamed.is_empty(), "should not detect renames when disabled");+ assert_eq!(added.len(), 2);+ assert_eq!(removed.len(), 1);+ }++ #[test]+ fn rename_not_detected_with_unrelated_types() {+ let source = vec![column("col_a", "varchar(120)", None), column("col_b", "int", None)];+ let target = vec![column("col_old", "int", None), column("col_b", "int", None)];+ let diffs = diff_columns_with_options(&source, &target, false, false, true, 0.5);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ assert!(renamed.is_empty(), "should not rename across unrelated types");+ }++ #[test]+ fn rename_with_rollback_graph_inversion() {+ let source = vec![column("id", "int", None), column("new_name", "varchar(120)", None)];+ let target = vec![column("id", "int", None), column("old_name", "varchar(120)", None)];+ let diffs = diff_columns_with_options(&source, &target, false, false, true, 0.5);+ let inverted = RollbackGraph::invert_columns(&diffs);+ let renamed_inv: Vec<_> = inverted.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed_inv.len(), 1, "inverted rename should exist");+ assert_eq!(renamed_inv[0].name, "old_name");+ assert_eq!(renamed_inv[0].changes, vec!["new_name → old_name"]);+ }++ // -- helpers ----------------------------------------------+ fn make_col_diffs(source: &[(&str, &str)], target: &[(&str, &str)], detect_renames: bool) -> Vec<ColumnDiff> {+ let s: Vec<ColumnInfo> = source.iter().map(|(n, t)| column(n, t, None)).collect();+ let t: Vec<ColumnInfo> = target.iter().map(|(n, t)| column(n, t, None)).collect();+ diff_columns_with_options(&s, &t, false, false, detect_renames, 0.5)+ }++ fn wrap_table_diff(name: &str, columns: Vec<ColumnDiff>) -> TableDiff {+ TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: name.to_string(),+ columns: Some(columns),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }+ }++ fn gen_sql(diff: TableDiff, db_type: DatabaseType, source_dialect: Option<DialectKind>) -> String {+ generate_schema_sync_sql(&[diff], &[], &[], &[], &[], db_type, None, false, source_dialect, &[])+ }++ // -- 1. Same-dialect: MySQL (backticks, MODIFY/CHANGE/ADD COLUMN) --+ #[test]+ fn mysql_same_dialect_rename_and_add() {+ let diffs = make_col_diffs(+ &[("id", "int(11)"), ("name2", "varchar(120)"), ("del_flag", "tinyint(2)"), ("create_at", "datetime")],+ &[("id", "int"), ("name", "varchar(120)"), ("del_flag", "tinyint")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert!(sql.contains("CHANGE COLUMN `name` `name2`"), "MySQL rename: {sql}");+ assert!(sql.contains("ADD COLUMN `create_at`"), "MySQL new col: {sql}");+ assert!(sql.contains("MODIFY COLUMN `id`"), "MySQL modify type: {sql}");+ assert!(!sql.contains("DROP COLUMN"), "MySQL no drop: {sql}");+ }++ #[test]+ fn mysql_same_dialect_add_drop_modified() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_col", "varchar(50)")],+ &[("id", "bigint"), ("old_col", "int")],+ false,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert!(sql.contains("ADD COLUMN `new_col`"), "MySQL add: {sql}");+ assert!(sql.contains("DROP COLUMN `old_col`"), "MySQL drop: {sql}");+ assert!(sql.contains("MODIFY COLUMN `id`"), "MySQL modify: {sql}");+ }++ // -- 2. Same-dialect: PostgreSQL (double-quotes, ALTER COLUMN … TYPE) --+ #[test]+ fn postgresql_same_dialect_modify_and_rename() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(120)"), ("create_at", "timestamp")],+ &[("id", "int"), ("name", "varchar(120)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("RENAME COLUMN"), "PG rename: {sql}");+ assert!(sql.contains("ADD COLUMN"), "PG add: {sql}");+ assert!(sql.contains("\"t\""), "PG double-quote table: {sql}");+ assert!(!sql.contains('`'), "PG no backticks: {sql}");+ }++ // -- 3. Cross-dialect type conversion: MySQL → PostgreSQL --+ #[test]+ fn mysql_to_postgresql_type_conversion_full() {+ let diffs = make_col_diffs(+ &[("id", "int(11)"), ("name2", "varchar(120)"), ("flag", "tinyint(2)"), ("ts", "datetime")],+ &[("id", "integer"), ("name", "varchar(120)"), ("flag", "smallint")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, Some(DialectKind::Mysql));+ assert!(sql.contains("RENAME COLUMN"), "PG rename: {sql}");+ assert!(sql.contains("ADD COLUMN"), "PG add: {sql}");+ assert!(sql.contains("INTEGER"), "int(11)→INTEGER: {sql}");+ assert!(sql.contains("SMALLINT"), "tinyint→SMALLINT: {sql}");+ assert!(sql.contains("TIMESTAMP"), "datetime→TIMESTAMP: {sql}");+ assert!(!sql.contains('`'), "PG no backticks: {sql}");+ }++ #[test]+ fn mysql_to_postgresql_type_conversion_modified_only() {+ let diffs = make_col_diffs(+ &[("id", "int(11)"), ("amount", "decimal(10,2)"), ("created", "datetime")],+ &[("id", "integer"), ("amount", "numeric(10,2)"), ("created", "timestamp")],+ false,+ );+ let sql_with = gen_sql(wrap_table_diff("t", diffs.clone()), DatabaseType::Postgres, Some(DialectKind::Mysql));+ let sql_without = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql_with.contains("INTEGER"), "with: int(11)→INTEGER: {sql_with}");+ assert!(sql_with.contains("TIMESTAMP"), "with: datetime→TIMESTAMP: {sql_with}");+ // No source dialect: matrix skipped, but target profile still strips display width.+ assert!(sql_without.contains("INT"), "without: display width stripped: {sql_without}");+ assert!(!sql_without.contains("int(11)"), "without: no MySQL display width: {sql_without}");+ assert!(sql_without.contains("datetime"), "without: datetime preserved: {sql_without}");+ }++ // -- 4. Reverse: PostgreSQL → MySQL --+ #[test]+ fn postgresql_to_mysql_type_conversion_reverse() {+ let diffs = make_col_diffs(+ &[("id", "integer"), ("label", "text"), ("active", "boolean")],+ &[("id", "int"), ("label", "varchar(255)")],+ false,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, Some(DialectKind::Postgres));+ assert!(sql.contains('`'), "MySQL backticks: {sql}");+ assert!(sql.contains("MODIFY COLUMN"), "MySQL modify: {sql}");+ assert!(sql.contains("LONGTEXT"), "text→LONGTEXT: {sql}");+ assert!(sql.contains("TINYINT(1)"), "boolean→TINYINT(1): {sql}");+ assert!(sql.contains("INT"), "integer→INT: {sql}");+ }++ // -- 5. MySQL → SQLite type conversion --+ #[test]+ fn mysql_to_sqlite_type_conversion() {+ let diffs = make_col_diffs(+ &[("id", "int(11)"), ("renamed", "varchar(255)")],+ &[("id", "integer"), ("old", "text")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Sqlite, Some(DialectKind::Mysql));+ assert!(sql.contains("RENAME COLUMN"), "SQLite rename: {sql}");+ assert!(sql.contains("INTEGER"), "int(11)→INTEGER: {sql}");+ assert!(!sql.contains('`'), "SQLite no backticks: {sql}");+ }++ // -- 6. Database-specific rename syntax --+ #[test]+ fn sqlserver_rename_uses_sp_rename() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_name", "varchar(100)")],+ &[("id", "int"), ("old_name", "varchar(100)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("orders", diffs), DatabaseType::SqlServer, None);+ assert!(sql.contains("sp_rename"), "SQL Server uses sp_rename: {sql}");+ assert!(sql.contains("\"orders\""), "sp_rename table path: {sql}");+ assert!(!sql.contains("ALTER TABLE \"orders\" EXEC sp_rename"), "sp_rename must be standalone: {sql}");+ assert!(sql.lines().any(|line| line.starts_with("EXEC sp_rename")), "standalone sp_rename: {sql}");+ assert!(!sql.contains('`'), "SQL Server no backticks: {sql}");+ }++ #[test]+ fn h2_rename_uses_alter_column_rename_to() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_name", "varchar(100)")],+ &[("id", "int"), ("old_name", "varchar(100)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::H2, None);+ assert!(sql.contains("ALTER COLUMN"), "H2 ALTER COLUMN: {sql}");+ assert!(sql.contains("RENAME TO"), "H2 RENAME TO: {sql}");+ }++ #[test]+ fn default_rename_all_other_databases() {+ let databases = [+ DatabaseType::ClickHouse,+ DatabaseType::Oracle,+ DatabaseType::DuckDb,+ DatabaseType::Informix,+ DatabaseType::Questdb,+ ];+ for db in databases {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_name", "varchar(100)")],+ &[("id", "int"), ("old_name", "varchar(100)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), db, None);+ assert!(sql.contains("RENAME COLUMN"), "{db:?} uses RENAME COLUMN: {sql}");+ assert!(!sql.contains('`'), "{db:?} no backticks: {sql}");+ }+ }++ // -- 7. MySQL-like databases (Doris, StarRocks) --+ #[test]+ fn mysql_like_databases_use_mysql_syntax() {+ let mysql_likes = [+ DatabaseType::Doris,+ DatabaseType::StarRocks,+ DatabaseType::Goldendb,+ DatabaseType::Sundb,+ DatabaseType::Databend,+ DatabaseType::Gbase,+ ];+ for db in mysql_likes {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(50)")],+ &[("id", "int"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), db, None);+ assert!(sql.contains('`'), "{db:?} uses backticks: {sql}");+ assert!(sql.contains("CHANGE COLUMN"), "{db:?} uses CHANGE COLUMN: {sql}");+ }+ }++ // -- 8. No type conversion for unsupported dialect pairs --+ #[test]+ fn mysql_to_unsupported_dialect_types_pass_through() {+ let targets = [+ DatabaseType::SqlServer,+ DatabaseType::ClickHouse,+ DatabaseType::Oracle,+ DatabaseType::DuckDb,+ DatabaseType::Informix,+ DatabaseType::H2,+ DatabaseType::Questdb,+ ];+ for target in targets {+ let diffs = make_col_diffs(+ &[("id", "int(11)"), ("name2", "varchar(50)")],+ &[("id", "integer"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), target, Some(DialectKind::Mysql));+ // No dialect-pair matrix for these targets; profile still strips MySQL display width.+ assert!(sql.contains("INT"), "{target:?} strips display width to INT: {sql}");+ assert!(!sql.contains("int(11)"), "{target:?} no MySQL display width: {sql}");+ assert!(!sql.contains('`'), "{target:?} no backticks: {sql}");+ }+ }++ // -- 9. Passthrough when source_dialect is None --+ #[test]+ fn without_source_dialect_types_preserved() {+ let diffs = make_col_diffs(&[("id", "int(11)"), ("flag", "tinyint")], &[("id", "bigint")], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ // No source dialect → no matrix mapping; PG profile still strips display width.+ assert!(sql.contains("INT"), "display width stripped to INT: {sql}");+ assert!(!sql.contains("int(11)"), "no MySQL display width: {sql}");+ assert!(sql.contains("tinyint"), "passthrough tinyint: {sql}");+ }++ // -- 10. All MySQL→PostgreSQL type mapping rules --+ #[test]+ fn mysql_to_postgresql_specific_type_conversions() {+ let cases = [+ ("ti1", "tinyint(1)", "BOOLEAN"),+ ("tiny", "tinyint", "SMALLINT"),+ ("med", "mediumint", "INTEGER"),+ ("int_", "int", "INTEGER"),+ ("big", "bigint", "BIGINT"),+ ("flt", "float", "REAL"),+ ("dbl", "double", "DOUBLE PRECISION"),+ ("txs", "tinytext", "TEXT"),+ ("tx", "text", "TEXT"),+ ("txm", "mediumtext", "TEXT"),+ ("txl", "longtext", "TEXT"),+ ("blb", "blob", "BYTEA"),+ ("bls", "tinyblob", "BYTEA"),+ ("blm", "mediumblob", "BYTEA"),+ ("bll", "longblob", "BYTEA"),+ ("dt", "datetime", "TIMESTAMP"),+ ];+ for (name, mysql_type, expected_pg) in cases {+ let diffs = make_col_diffs(&[(name, mysql_type)], &[], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, Some(DialectKind::Mysql));+ assert!(sql.contains(expected_pg), "MySQL {mysql_type} → PostgreSQL {expected_pg}: {sql}");+ }+ }++ // -- 11. PostgreSQL→MySQL all reverse type mappings --+ #[test]+ fn postgresql_to_mysql_all_type_mappings() {+ let mappings = [+ ("sml", "smallint", "SMALLINT"),+ ("int_", "integer", "INT"),+ ("big", "bigint", "BIGINT"),+ ("real", "real", "FLOAT"),+ ("dp", "double precision", "DOUBLE"),+ ("tx", "text", "LONGTEXT"),+ ("ba", "bytea", "BLOB"),+ ("bl", "boolean", "TINYINT(1)"),+ ("ts", "timestamp", "DATETIME"),+ ("tstz", "timestamptz", "DATETIME"),+ ("uuid", "uuid", "CHAR(36)"),+ ("jb", "jsonb", "JSON"),+ ];+ for (name, pg_type, expected_mysql) in mappings {+ let diffs = make_col_diffs(&[(name, pg_type)], &[], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, Some(DialectKind::Postgres));+ assert!(sql.contains(expected_mysql), "PG {pg_type} → MySQL {expected_mysql}: {sql}");+ }+ }++ // -- 12. MySQL→SQLite all type mappings --+ #[test]+ fn mysql_to_sqlite_all_type_mappings() {+ let mappings = [+ ("int", "int", "INTEGER"),+ ("bi", "bigint", "INTEGER"),+ ("ti", "tinyint", "INTEGER"),+ ("si", "smallint", "INTEGER"),+ ("mi", "mediumint", "INTEGER"),+ ("db", "double", "REAL"),+ ("fl", "float", "REAL"),+ ("dt", "datetime", "TEXT"),+ ("ts", "timestamp", "TEXT"),+ ("tx", "text", "TEXT"),+ ("bl", "blob", "BLOB"),+ ];+ for (name, mysql_type, expected_sqlite) in mappings {+ let diffs = make_col_diffs(&[(name, mysql_type)], &[], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Sqlite, Some(DialectKind::Mysql));+ assert!(sql.contains(expected_sqlite), "MySQL {mysql_type} → SQLite {expected_sqlite}: {sql}");+ }+ }++ // -- 13. Same-dialect: ClickHouse (double-quotes, default rename) --+ #[test]+ fn clickhouse_same_dialect_operations() {+ let diffs = make_col_diffs(&[("id", "Int32"), ("new_col", "String")], &[("id", "Int32")], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::ClickHouse, None);+ assert!(sql.contains("ADD COLUMN"), "ClickHouse add: {sql}");+ assert!(!sql.contains('`'), "ClickHouse no backticks: {sql}");+ }++ // -- 14. Same-dialect: Oracle --+ #[test]+ fn oracle_same_dialect_operations() {+ let diffs = make_col_diffs(&[("id", "NUMBER"), ("name", "VARCHAR2(100)")], &[("id", "NUMBER")], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Oracle, None);+ assert!(sql.contains("ADD COLUMN"), "Oracle add: {sql}");+ assert!(!sql.contains('`'), "Oracle no backticks: {sql}");+ }++ // -- 15. Same-dialect: SQL Server with rename --+ #[test]+ fn sqlserver_same_dialect_rename() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_name", "nvarchar(100)")],+ &[("id", "int"), ("old_name", "nvarchar(100)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::SqlServer, None);+ assert!(sql.contains("sp_rename"), "SQL Server rename: {sql}");+ }++ // -- 16. Same-dialect: H2 --+ #[test]+ fn h2_same_dialect_rename() {+ let diffs = make_col_diffs(+ &[("id", "INT"), ("new_name", "VARCHAR(100)")],+ &[("id", "INT"), ("old_name", "VARCHAR(100)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::H2, None);+ assert!(sql.contains("ALTER COLUMN"), "H2 rename: {sql}");+ assert!(sql.contains("RENAME TO"), "H2 rename to: {sql}");+ }++ // -- 17. Same-dialect: DuckDB --+ #[test]+ fn duckdb_same_dialect_add() {+ let diffs = make_col_diffs(&[("id", "INTEGER"), ("name", "VARCHAR")], &[("id", "INTEGER")], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::DuckDb, None);+ assert!(sql.contains("ADD COLUMN"), "DuckDB add: {sql}");+ assert!(!sql.contains('`'), "DuckDB no backticks: {sql}");+ }++ // -- 18. Schema-qualified SQL output --+ #[test]+ fn schema_qualified_output() {+ let diffs = make_col_diffs(&[("name2", "varchar(50)")], &[("name", "varchar(50)")], true);+ let table_diff = wrap_table_diff("users", diffs);+ let sql = generate_schema_sync_sql(+ &[table_diff],+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Postgres,+ Some("public"),+ false,+ None,+ &[],+ );+ assert!(sql.contains("\"public\".\"users\""), "schema prefixed: {sql}");+ }++ #[test]+ fn schema_qualified_mysql() {+ let diffs = make_col_diffs(&[("name2", "varchar(50)")], &[("name", "varchar(50)")], true);+ let table_diff = wrap_table_diff("users", diffs);+ let sql = generate_schema_sync_sql(+ &[table_diff],+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Mysql,+ Some("mydb"),+ false,+ None,+ &[],+ );+ assert!(sql.contains("`mydb`.`users`"), "schema prefixed MySQL: {sql}");+ }++ // -- 19. Multiple operations in one diff --+ #[test]+ fn multiple_concurrent_operations() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(50)"), ("new_col", "text"), ("keep", "boolean")],+ &[("id", "bigint"), ("name", "varchar(50)"), ("old_col", "int"), ("keep", "boolean")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("RENAME COLUMN"), "rename: {sql}");+ assert!(sql.contains("ADD COLUMN"), "add: {sql}");+ assert!(sql.contains("DROP COLUMN"), "drop: {sql}");+ assert!(sql.contains("ALTER COLUMN"), "modify type: {sql}");+ }++ #[test]+ fn multiple_concurrent_operations_mysql() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(50)"), ("new_col", "text")],+ &[("id", "bigint"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert!(sql.contains("CHANGE COLUMN"), "MySQL rename: {sql}");+ assert!(sql.contains("ADD COLUMN"), "MySQL add: {sql}");+ assert!(sql.contains("MODIFY COLUMN"), "MySQL modify: {sql}");+ }++ // -- 20. All-removed and all-added edge cases --+ #[test]+ fn all_columns_removed() {+ let diffs = make_col_diffs(&[], &[("old1", "int"), ("old2", "varchar(10)")], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert_eq!(sql.matches("DROP COLUMN").count(), 2, "two drops: {sql}");+ }++ #[test]+ fn all_columns_added() {+ let diffs = make_col_diffs(&[("new1", "int"), ("new2", "varchar(10)")], &[], false);+ for db in [DatabaseType::Mysql, DatabaseType::Postgres, DatabaseType::Oracle] {+ let sql = gen_sql(wrap_table_diff("t", diffs.clone()), db, None);+ assert_eq!(sql.matches("ADD COLUMN").count(), 2, "{db:?} two adds: {sql}");+ }+ }++ // -- 21. Rename + type change in one column --+ #[test]+ fn rename_with_simultaneous_type_change() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_name", "varchar(200)")],+ &[("id", "int"), ("old_name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("RENAME COLUMN"), "rename: {sql}");+ assert!(sql.contains("TYPE varchar(200)"), "type change: {sql}");+ }++ // -- 22. PostgreSQL→PostgreSQL: nullability changes --+ #[test]+ fn postgres_nullable_change() {+ let source = vec![ColumnInfo {+ name: "name".into(),+ data_type: "text".into(),+ is_nullable: true,+ ..column("name", "text", None)+ }];+ let target = vec![ColumnInfo {+ name: "name".into(),+ data_type: "text".into(),+ is_nullable: false,+ ..column("name", "text", None)+ }];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("DROP NOT NULL"), "nullable change: {sql}");+ }++ #[test]+ fn postgres_not_nullable_change() {+ let source = vec![ColumnInfo {+ name: "name".into(),+ data_type: "text".into(),+ is_nullable: false,+ ..column("name", "text", None)+ }];+ let target = vec![ColumnInfo {+ name: "name".into(),+ data_type: "text".into(),+ is_nullable: true,+ ..column("name", "text", None)+ }];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("SET NOT NULL"), "not null change: {sql}");+ }++ // -- 23. PostgreSQL→SQLite (no existing mapping rules) --+ #[test]+ fn postgresql_to_sqlite_no_type_mapping() {+ let diffs = make_col_diffs(&[("id", "integer"), ("data", "text"), ("ts", "timestamp")], &[], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Sqlite, Some(DialectKind::Postgres));+ // No PG→SQLite dialect matrix, but SQLite profile type_map still rewrites affinities.+ assert!(sql.contains("INTEGER"), "integer→INTEGER: {sql}");+ assert!(sql.contains("TEXT"), "text/timestamp→TEXT: {sql}");+ assert!(!sql.contains("timestamp"), "timestamp mapped away: {sql}");+ }++ // -- 24. All MySQL-like databases with rename + type change --+ #[test]+ fn mysql_like_rename_with_type_conversion() {+ let mysql_likes: [(DatabaseType, &str); 7] = [+ (DatabaseType::Mysql, "Mysql"),+ (DatabaseType::Doris, "Doris"),+ (DatabaseType::StarRocks, "StarRocks"),+ (DatabaseType::Goldendb, "Goldendb"),+ (DatabaseType::Sundb, "Sundb"),+ (DatabaseType::Databend, "Databend"),+ (DatabaseType::Gbase, "Gbase"),+ ];+ for (db, label) in mysql_likes {+ let diffs = make_col_diffs(+ &[("id", "int(11)"), ("name2", "varchar(50)")],+ &[("id", "int"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), db, Some(DialectKind::Mysql));+ assert!(sql.contains("CHANGE COLUMN"), "{label} CHANGE COLUMN: {sql}");+ assert!(sql.contains('`'), "{label} backticks: {sql}");+ assert!(sql.contains("MODIFY COLUMN"), "{label} MODIFY: {sql}");+ }+ }++ // -- 25. Rename with nullable change --+ #[test]+ fn rename_with_nullable_change() {+ let source = vec![ColumnInfo {+ name: "new_col".into(),+ data_type: "text".into(),+ is_nullable: true,+ ..column("new_col", "text", None)+ }];+ let target = vec![ColumnInfo {+ name: "old_col".into(),+ data_type: "text".into(),+ is_nullable: false,+ ..column("old_col", "text", None)+ }];+ let diffs = diff_columns_with_options(&source, &target, false, false, true, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("RENAME COLUMN"), "rename: {sql}");+ assert!(sql.contains("DROP NOT NULL"), "nullable: {sql}");+ }++ // -- 26. Empty diff generates no SQL --+ #[test]+ fn empty_diff_generates_no_sql() {+ let diffs: Vec<ColumnDiff> = vec![];+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert_eq!(sql, "", "empty diff should generate no SQL");+ let sql = gen_sql(wrap_table_diff("t", vec![]), DatabaseType::Postgres, None);+ assert_eq!(sql, "", "empty diff should generate no SQL for postgres");+ }++ // -- 27. Databend and Gbase (MySQL-like) --+ #[test]+ fn databend_gbase_mysql_like() {+ for db in [DatabaseType::Databend, DatabaseType::Gbase] {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(50)")],+ &[("id", "int"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), db, None);+ assert!(sql.contains('`'), "{db:?} backticks: {sql}");+ }+ }++ // -- 28. Postgres-compatible databases (GaussDB, openGauss, etc.) --+ #[test]+ fn postgres_like_databases() {+ let pg_likes = [+ DatabaseType::Gaussdb,+ DatabaseType::Kwdb,+ DatabaseType::OpenGauss,+ DatabaseType::Highgo,+ DatabaseType::Vastbase,+ DatabaseType::Kingbase,+ DatabaseType::Firebird,+ DatabaseType::Redshift,+ DatabaseType::Vertica,+ DatabaseType::Exasol,+ ];+ for db in pg_likes {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(50)")],+ &[("id", "int"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), db, None);+ assert!(sql.contains("RENAME COLUMN"), "{db:?} RENAME COLUMN: {sql}");+ assert!(!sql.contains('`'), "{db:?} no backticks: {sql}");+ }+ }++ // -- 29. SQLite-compatible databases --+ #[test]+ fn sqlite_like_databases() {+ let sqlite_likes = [DatabaseType::Rqlite, DatabaseType::Turso];+ for db in sqlite_likes {+ let diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(50)")],+ &[("id", "int"), ("name", "varchar(50)")],+ true,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), db, None);+ assert!(sql.contains("RENAME COLUMN"), "{db:?} RENAME COLUMN: {sql}");+ assert!(!sql.contains('`'), "{db:?} no backticks: {sql}");+ }+ }++ // -- 30. ManticoreSearch (separate dialect) --+ #[test]+ fn manticore_search_sql() {+ let diffs = make_col_diffs(&[("id", "bigint"), ("title", "text")], &[("id", "bigint")], false);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::ManticoreSearch, None);+ assert!(sql.contains("ADD COLUMN"), "Manticore add: {sql}");+ assert!(sql.contains('`'), "Manticore uses backtick identifiers (MySQL-compatible): {sql}");+ }++ #[test]+ fn detects_modified_indexes_not_only_added_or_removed_indexes() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_orders_status".to_string(),+ columns: vec!["status".to_string(), "created_at".to_string()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_orders_status".to_string(),+ columns: vec!["status".to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ );++ assert_eq!(diffs.len(), 1);+ assert_eq!(diffs[0].diff_type, "modified");+ assert_eq!(diffs[0].changes, vec!["unique: YES → NO", "columns: status → status, created_at"]);+ }++ #[test]+ fn detects_mysql_functional_index_changes_and_preserves_expression_ddl() {+ let functional_key_part = "((case when (`STATUS` = _utf8mb4'online') then _utf8mb4'online' else NULL end))";+ let source_index = index(IndexInfo {+ name: "test_UNIQUE".to_string(),+ columns: vec!["attr".to_string(), "attr2".to_string(), functional_key_part.to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ });+ let target_index = index(IndexInfo {+ name: "test_UNIQUE".to_string(),+ columns: vec!["attr".to_string(), "attr2".to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ });++ let diffs = diff_indexes(std::slice::from_ref(&source_index), &[target_index]);+ assert_eq!(diffs.len(), 1);+ assert_eq!(diffs[0].diff_type, "modified");+ assert_eq!(diffs[0].changes, vec![format!("columns: attr, attr2 → attr, attr2, {functional_key_part}")]);++ let sql = generate_schema_sync_sql(+ &[TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "test".to_string(),+ columns: None,+ indexes: Some(diffs),+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }],+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Mysql,+ Some("dbx_issue_4114"),+ false,+ None,+ &[],+ );++ assert!(sql.contains("DROP INDEX `test_UNIQUE` ON `dbx_issue_4114`.`test`;"));+ assert!(sql.contains(&format!(+ "CREATE UNIQUE INDEX `test_UNIQUE` ON `dbx_issue_4114`.`test` (`attr`, `attr2`, {functional_key_part});"+ )));+ assert!(!sql.contains("`((case"));+ }++ #[test]+ fn detects_foreign_key_additions_removals_and_target_changes() {+ let diffs = diff_foreign_keys(+ &[+ foreign_key(ForeignKeyInfo {+ name: "orders_user_id_fk".to_string(),+ column: String::new(),+ ref_schema: None,+ ref_table: String::new(),+ ref_column: String::new(),+ on_update: None,+ on_delete: None,+ }),+ foreign_key(ForeignKeyInfo {+ name: "orders_account_id_fk".to_string(),+ column: "account_id".to_string(),+ ref_schema: None,+ ref_table: "accounts".to_string(),+ ref_column: String::new(),+ on_update: None,+ on_delete: None,+ }),+ ],+ &[+ foreign_key(ForeignKeyInfo {+ name: "orders_user_id_fk".to_string(),+ column: String::new(),+ ref_schema: None,+ ref_table: "members".to_string(),+ ref_column: String::new(),+ on_update: None,+ on_delete: None,+ }),+ foreign_key(ForeignKeyInfo {+ name: "orders_region_id_fk".to_string(),+ column: "region_id".to_string(),+ ref_schema: None,+ ref_table: "regions".to_string(),+ ref_column: String::new(),+ on_update: None,+ on_delete: None,+ }),+ ],+ );++ let summary: Vec<_> = diffs.iter().map(|diff| (diff.diff_type.as_str(), diff.name.as_str())).collect();+ assert_eq!(+ summary,+ vec![+ ("modified", "orders_user_id_fk"),+ ("added", "orders_account_id_fk"),+ ("removed", "orders_region_id_fk"),+ ]+ );+ }++ #[test]+ fn generates_sync_sql_for_index_and_foreign_key_changes() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: None,+ name: "orders".to_string(),+ columns: None,+ indexes: Some(vec![IndexDiff {+ diff_type: "modified".to_string(),+ name: "idx_orders_status".to_string(),+ source: Some(index(IndexInfo {+ name: "idx_orders_status".to_string(),+ columns: vec!["status".to_string(), "created_at".to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })),+ target: None,+ changes: Vec::new(),+ }]),+ foreign_keys: Some(vec![ForeignKeyDiff {+ diff_type: "modified".to_string(),+ name: "orders_user_id_fk".to_string(),+ source: Some(foreign_key(ForeignKeyInfo {+ name: "orders_user_id_fk".to_string(),+ column: String::new(),+ ref_schema: None,+ ref_table: "users".to_string(),+ ref_column: String::new(),+ on_update: None,+ on_delete: None,+ })),+ target: None,+ changes: Vec::new(),+ }]),+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ assert_eq!(+ generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, None, false, None, &[]),+ [+ "ALTER TABLE \"orders\" DROP CONSTRAINT \"orders_user_id_fk\";",+ "DROP INDEX IF EXISTS \"idx_orders_status\";",+ "CREATE UNIQUE INDEX \"idx_orders_status\" ON \"orders\" (\"status\", \"created_at\");",+ "ALTER TABLE \"orders\" ADD CONSTRAINT \"orders_user_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"users\" (\"id\");",+ ]+ .join("\n")+ );+ }++ #[test]+ fn mysql_column_comment_changes_generate_modify_column_sql() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: None,+ name: "users".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "modified".to_string(),+ name: "name".to_string(),+ source: Some(column("name", "varchar(64)", Some("用户姓名"))),+ target: Some(column("name", "varchar(64)", Some("Name"))),+ changes: vec!["comment: Name → 用户姓名".to_string()],+ }]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: Some(Some("用户表".to_string())),+ target_table_comment: Some(Some("Users".to_string())),+ sync_sql: None,+ }];++ assert_eq!(+ generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, None, false, None, &[]),+ [+ "-- Alter table: users",+ "ALTER TABLE `users`",+ " MODIFY COLUMN `name` varchar(64) NOT NULL COMMENT '用户姓名';",+ "",+ "ALTER TABLE `users` COMMENT = '用户表';",+ ]+ .join("\n")+ );+ }++ #[test]+ fn mysql_schema_sync_sql_qualifies_tables_with_target_database() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: None,+ name: "notify_channel_config".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "modified".to_string(),+ name: "config_json".to_string(),+ source: Some(column("config_json", "json", Some("渠道配置"))),+ target: Some(column("config_json", "json", Some("Config"))),+ changes: vec!["comment: Config → 渠道配置".to_string()],+ }]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ assert_eq!(+ generate_schema_sync_sql(+ &diffs,+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Mysql,+ Some("target_db"),+ false,+ None,+ &[]+ ),+ [+ "-- Alter table: notify_channel_config",+ "ALTER TABLE `target_db`.`notify_channel_config`",+ " MODIFY COLUMN `config_json` json NOT NULL COMMENT '渠道配置';",+ ]+ .join("\n")+ );+ }++ #[test]+ fn blank_target_schema_does_not_generate_empty_qualifier() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: None,+ name: "notify_channel_config".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "modified".to_string(),+ name: "config_json".to_string(),+ source: Some(column("config_json", "json", Some("渠道配置"))),+ target: Some(column("config_json", "json", Some("Config"))),+ changes: vec!["comment: Config → 渠道配置".to_string()],+ }]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ let sql =+ generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, Some(" "), false, None, &[]);++ assert!(sql.contains("ALTER TABLE `notify_channel_config`"));+ assert!(!sql.contains("``."));+ }++ #[test]+ fn ignore_comments_skips_column_and_table_comment_diffs() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: Some("用户表".to_string()),+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: Some("Users".to_string()),+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![column("name", "varchar(64)", Some("用户姓名"))],+ indexes: Vec::new(),+ foreign_keys: Vec::new(),+ triggers: Vec::new(),+ ddl: None,+ }],+ target_details: vec![TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![column("name", "varchar(64)", Some("Name"))],+ indexes: Vec::new(),+ foreign_keys: Vec::new(),+ triggers: Vec::new(),+ ddl: None,+ }],+ source_functions: Vec::new(),+ target_functions: Vec::new(),+ source_sequences: Vec::new(),+ target_sequences: Vec::new(),+ source_rules: Vec::new(),+ target_rules: Vec::new(),+ source_owners: Vec::new(),+ target_owners: Vec::new(),+ database_type: DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: true,+ cascade_delete: false,+ compare_column_order: false,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(result.diffs.is_empty());+ assert!(result.sync_sql.is_empty());+ }++ #[test]+ fn prepare_schema_diff_attaches_per_table_sync_sql() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![column("name", "varchar(128)", None)],+ indexes: Vec::new(),+ foreign_keys: Vec::new(),+ triggers: Vec::new(),+ ddl: Some("CREATE TABLE `users` (`name` varchar(128));".to_string()),+ }],+ target_details: vec![TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![column("name", "varchar(64)", None)],+ indexes: Vec::new(),+ foreign_keys: Vec::new(),+ triggers: Vec::new(),+ ddl: Some("CREATE TABLE `users` (`name` varchar(64));".to_string()),+ }],+ source_functions: Vec::new(),+ target_functions: Vec::new(),+ source_sequences: Vec::new(),+ target_sequences: Vec::new(),+ source_rules: Vec::new(),+ target_rules: Vec::new(),+ source_owners: Vec::new(),+ target_owners: Vec::new(),+ database_type: DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ let table_sync_sql = result.diffs[0].sync_sql.as_deref().unwrap_or_default();++ assert!(table_sync_sql.contains("ALTER TABLE `users`"));+ assert!(!table_sync_sql.contains("CREATE TABLE"));+ }++ #[test]+ fn qualifies_generated_schema_sync_sql_with_target_schema() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: None,+ name: "orders".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "added".to_string(),+ name: "status".to_string(),+ source: Some(ColumnInfo {+ name: "status".to_string(),+ data_type: "text".to_string(),+ is_nullable: true,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }),+ target: None,+ changes: Vec::new(),+ }]),+ indexes: Some(vec![IndexDiff {+ diff_type: "added".to_string(),+ name: "idx_orders_status".to_string(),+ source: Some(index(IndexInfo {+ name: "idx_orders_status".to_string(),+ columns: vec!["status".to_string()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })),+ target: None,+ changes: Vec::new(),+ }]),+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ assert_eq!(+ generate_schema_sync_sql(+ &diffs,+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Postgres,+ Some("sales"),+ false,+ None,+ &[]+ ),+ [+ "-- Alter table: orders",+ "ALTER TABLE \"sales\".\"orders\" ADD COLUMN \"status\" text;",+ "",+ "CREATE INDEX \"idx_orders_status\" ON \"sales\".\"orders\" (\"status\");",+ ]+ .join("\n")+ );+ }++ // ========================================================================+ // Phase 4.1: Dependency Graph Tests+ // ========================================================================++ #[test]+ fn dependency_graph_builds_dag_from_foreign_keys() {+ let details = vec![+ TableSchemaDetail {+ name: "orders".to_string(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![ForeignKeyInfo {+ name: "fk_orders_users".to_string(),+ column: "user_id".to_string(),+ ref_schema: None,+ ref_table: "users".to_string(),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: None,+ }],+ triggers: vec![],+ ddl: None,+ },+ TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ },+ ];+ let tables = vec![+ TableInfo {+ name: "orders".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ },+ TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ },+ ];++ let graph = DependencyGraph::build(&details, &tables);+ assert_eq!(graph.nodes.len(), 2);+ assert!(graph.nodes["orders"].depends_on.contains(&"users".to_string()));+ assert_eq!(graph.nodes["orders"].depends_on.len(), 1);+ assert_eq!(graph.nodes["users"].depends_on.len(), 0);+ }++ #[test]+ fn dependency_graph_topological_sort_drop_order() {+ let details = vec![+ TableSchemaDetail {+ name: "order_items".to_string(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![ForeignKeyInfo {+ name: "fk_items_orders".to_string(),+ column: "order_id".to_string(),+ ref_schema: None,+ ref_table: "orders".to_string(),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: None,+ }],+ triggers: vec![],+ ddl: None,+ },+ TableSchemaDetail {+ name: "orders".to_string(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![ForeignKeyInfo {+ name: "fk_orders_users".to_string(),+ column: "user_id".to_string(),+ ref_schema: None,+ ref_table: "users".to_string(),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: None,+ }],+ triggers: vec![],+ ddl: None,+ },+ TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ },+ ];+ let tables = vec![+ TableInfo {+ name: "order_items".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ },+ TableInfo {+ name: "orders".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ },+ TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ },+ ];++ let graph = DependencyGraph::build(&details, &tables);+ let drop_order = graph.drop_order();++ let di = drop_order.iter().position(|n| n == "order_items").unwrap();+ let oi = drop_order.iter().position(|n| n == "orders").unwrap();+ assert!(di < oi, "order_items should be dropped before orders");+ }++ #[test]+ fn coverage_score_empty_graph_returns_one() {+ let graph = DependencyGraph { nodes: HashMap::new(), topological_order: vec![] };+ assert_eq!(graph.coverage_score(&[]), 1.0);+ }++ #[test]+ fn coverage_score_partial_coverage() {+ let mut nodes = HashMap::new();+ nodes.insert(+ "a".to_string(),+ DependencyNode { table_name: "a".to_string(), depends_on: vec!["b".to_string()], depended_by: vec![] },+ );+ nodes.insert(+ "b".to_string(),+ DependencyNode {+ table_name: "b".to_string(),+ depends_on: vec!["c".to_string()],+ depended_by: vec!["a".to_string()],+ },+ );+ nodes.insert(+ "c".to_string(),+ DependencyNode { table_name: "c".to_string(), depends_on: vec![], depended_by: vec!["b".to_string()] },+ );+ let graph =+ DependencyGraph { nodes, topological_order: vec!["c".to_string(), "b".to_string(), "a".to_string()] };++ let score = graph.coverage_score(&["a".to_string(), "b".to_string()]);+ assert!((score - 0.5).abs() < 0.01);+ }++ #[test]+ fn coverage_score_level2_transitive_edges() {+ let mut nodes = HashMap::new();+ nodes.insert(+ "a".to_string(),+ DependencyNode { table_name: "a".to_string(), depends_on: vec!["b".to_string()], depended_by: vec![] },+ );+ nodes.insert(+ "b".to_string(),+ DependencyNode {+ table_name: "b".to_string(),+ depends_on: vec!["c".to_string()],+ depended_by: vec!["a".to_string()],+ },+ );+ nodes.insert(+ "c".to_string(),+ DependencyNode { table_name: "c".to_string(), depends_on: vec![], depended_by: vec!["b".to_string()] },+ );+ let graph =+ DependencyGraph { nodes, topological_order: vec!["c".to_string(), "b".to_string(), "a".to_string()] };++ let l2_score = graph.coverage_score_level2(&["a".to_string(), "b".to_string(), "c".to_string()]);+ assert!((l2_score - 1.0).abs() < 0.01, "full coverage should give 1.0");+ }++ #[test]+ fn coverage_score_level2_partial() {+ let mut nodes = HashMap::new();+ nodes.insert(+ "a".to_string(),+ DependencyNode { table_name: "a".to_string(), depends_on: vec!["b".to_string()], depended_by: vec![] },+ );+ nodes.insert(+ "b".to_string(),+ DependencyNode {+ table_name: "b".to_string(),+ depends_on: vec!["c".to_string()],+ depended_by: vec!["a".to_string()],+ },+ );+ nodes.insert(+ "c".to_string(),+ DependencyNode { table_name: "c".to_string(), depends_on: vec![], depended_by: vec!["b".to_string()] },+ );+ let graph =+ DependencyGraph { nodes, topological_order: vec!["c".to_string(), "b".to_string(), "a".to_string()] };++ let l2_score = graph.coverage_score_level2(&["a".to_string(), "b".to_string()]);+ assert!((l2_score - 0.0).abs() < 0.01, "missing grandparent c means 0 transitive coverage");+ }++ #[test]+ fn composite_coverage_full_coverage() {+ let mut nodes = HashMap::new();+ nodes.insert(+ "a".to_string(),+ DependencyNode { table_name: "a".to_string(), depends_on: vec!["b".to_string()], depended_by: vec![] },+ );+ nodes.insert(+ "b".to_string(),+ DependencyNode {+ table_name: "b".to_string(),+ depends_on: vec!["c".to_string()],+ depended_by: vec!["a".to_string()],+ },+ );+ nodes.insert(+ "c".to_string(),+ DependencyNode { table_name: "c".to_string(), depends_on: vec![], depended_by: vec!["b".to_string()] },+ );+ let graph =+ DependencyGraph { nodes, topological_order: vec!["c".to_string(), "b".to_string(), "a".to_string()] };++ let report = graph.composite_coverage_score(&["a".to_string(), "b".to_string(), "c".to_string()]);+ assert!((report.level1_score - 1.0).abs() < 0.01);+ assert!((report.level2_score - 1.0).abs() < 0.01);+ assert!((report.composite_score - 1.0).abs() < 0.01);+ assert_eq!(report.level1_covered, 2);+ assert_eq!(report.level1_total, 2);+ assert_eq!(report.level2_covered, 1);+ assert_eq!(report.level2_total, 1);+ }++ #[test]+ fn composite_coverage_partial() {+ let mut nodes = HashMap::new();+ nodes.insert(+ "a".to_string(),+ DependencyNode { table_name: "a".to_string(), depends_on: vec!["b".to_string()], depended_by: vec![] },+ );+ nodes.insert(+ "b".to_string(),+ DependencyNode {+ table_name: "b".to_string(),+ depends_on: vec!["c".to_string()],+ depended_by: vec!["a".to_string()],+ },+ );+ nodes.insert(+ "c".to_string(),+ DependencyNode { table_name: "c".to_string(), depends_on: vec![], depended_by: vec!["b".to_string()] },+ );+ let graph =+ DependencyGraph { nodes, topological_order: vec!["c".to_string(), "b".to_string(), "a".to_string()] };++ let report = graph.composite_coverage_score(&["a".to_string(), "b".to_string()]);+ assert!((report.level1_score - 0.5).abs() < 0.01);+ assert!((report.level2_score - 0.0).abs() < 0.01);+ assert!((report.composite_score - 0.3).abs() < 0.01, "0.6*0.5 + 0.4*0.0 = 0.3");+ assert_eq!(report.level1_covered, 1);+ assert_eq!(report.level1_total, 2);+ assert!(!report.uncovered_edges.is_empty());+ }++ #[test]+ fn composite_coverage_no_dependencies() {+ let mut nodes = HashMap::new();+ nodes.insert(+ "t1".to_string(),+ DependencyNode { table_name: "t1".to_string(), depends_on: vec![], depended_by: vec![] },+ );+ nodes.insert(+ "t2".to_string(),+ DependencyNode { table_name: "t2".to_string(), depends_on: vec![], depended_by: vec![] },+ );+ let graph = DependencyGraph { nodes, topological_order: vec!["t1".to_string(), "t2".to_string()] };++ let report = graph.composite_coverage_score(&["t1".to_string()]);+ assert!((report.level1_score - 1.0).abs() < 0.01);+ assert!((report.level2_score - 1.0).abs() < 0.01);+ assert!((report.composite_score - 1.0).abs() < 0.01);+ assert!(report.uncovered_edges.is_empty());+ }++ // ========================================================================+ // Phase 4.1: Rename Detection Tests+ // ========================================================================++ #[test]+ fn detect_renames_high_similarity_columns() {+ let source_details = vec![TableSchemaDetail {+ name: "users_old".to_string(),+ columns: vec![+ column("id", "int", None),+ column("name", "varchar(100)", None),+ column("email", "varchar(255)", None),+ column("created_at", "datetime", None),+ ],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }];+ let target_details = vec![TableSchemaDetail {+ name: "users_new".to_string(),+ columns: vec![+ column("id", "integer", None),+ column("name", "varchar(100)", None),+ column("email", "varchar(255)", None),+ column("updated_at", "datetime", None),+ ],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }];++ let candidates = detect_renames(+ &["users_new".to_string()],+ &["users_old".to_string()],+ &source_details,+ &target_details,+ 0.5,+ );++ assert_eq!(candidates.len(), 1);+ assert_eq!(candidates[0].source_name, "users_old");+ assert_eq!(candidates[0].target_name, "users_new");+ assert!(candidates[0].score >= 0.5);+ }++ #[test]+ fn detect_renames_low_similarity_below_threshold() {+ let source_details = vec![TableSchemaDetail {+ name: "users".to_string(),+ columns: vec![column("id", "int", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }];+ let target_details = vec![TableSchemaDetail {+ name: "products".to_string(),+ columns: vec![column("sku", "varchar(50)", None), column("price", "decimal", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }];++ let candidates =+ detect_renames(&["users".to_string()], &["products".to_string()], &source_details, &target_details, 0.5);++ assert!(candidates.is_empty());+ }++ #[test]+ fn jaccard_similarity_identical_sets() {+ let a: HashSet<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();+ let b: HashSet<String> = ["a", "b", "c"].iter().map(|s| s.to_string()).collect();+ assert!((jaccard_similarity(&a, &b) - 1.0).abs() < f64::EPSILON);+ }++ // ========================================================================+ // Phase 4.2: Batch Naming Pattern Tests+ // ========================================================================++ #[test]+ fn batch_pattern_matching_wildcard() {+ let source = vec!["log_2024_01".to_string(), "log_2024_02".to_string(), "users".to_string()];+ let target = vec!["log_2024_03".to_string()];+ let patterns = vec![BatchPattern {+ pattern: "log_*".to_string(),+ is_regex: false,+ description: "all log tables".to_string(),+ }];++ let (_added, removed, common, match_results) = diff_names_with_patterns(&source, &target, &patterns);+ assert_eq!(removed, vec!["log_2024_03"]);+ assert_eq!(common.len(), 0);+ assert_eq!(match_results.len(), 1);+ assert_eq!(match_results[0].len(), 2);+ }++ #[test]+ fn batch_pattern_regex_matching() {+ let source = vec!["tbl_001".to_string(), "tbl_002".to_string(), "other".to_string()];+ let target = vec![];+ let patterns = vec![BatchPattern {+ pattern: r"tbl_\d{3}".to_string(),+ is_regex: true,+ description: "numbered tables".to_string(),+ }];++ let (_added, _removed, _common, match_results) = diff_names_with_patterns(&source, &target, &patterns);+ assert_eq!(match_results[0].len(), 2);+ }++ #[test]+ fn pattern_conflict_detection() {+ let patterns = vec![+ BatchPattern { pattern: "user_*".to_string(), is_regex: false, description: "user tables".to_string() },+ BatchPattern {+ pattern: "user_data".to_string(),+ is_regex: false,+ description: "specific user data".to_string(),+ },+ ];++ let names = vec!["user_data".to_string(), "user_log".to_string()];+ let conflicts = detect_pattern_conflicts(&patterns, &names);+ assert!(!conflicts.is_empty());+ }++ // ========================================================================+ // Phase 4.3: Type Compatibility Tests+ // ========================================================================++ #[test]+ fn diff_columns_with_compatibility_integer_family() {+ let (_diffs, warnings) = diff_columns_with_compatibility(+ &[column("id", "INT", None)],+ &[column("id", "BIGINT", None)],+ false,+ false,+ DialectKind::Mysql,+ DialectKind::Mysql,+ 0.9,+ &[],+ );+ assert!(!warnings.is_empty());+ assert_eq!(warnings[0].risk, ColumnConversionRisk::Low);+ }++ #[test]+ fn diff_columns_with_compatibility_exact_match_no_warning() {+ let (_diffs, warnings) = diff_columns_with_compatibility(+ &[column("id", "INT", None)],+ &[column("id", "INT", None)],+ false,+ false,+ DialectKind::Mysql,+ DialectKind::Mysql,+ 0.5,+ &[],+ );+ assert!(warnings.is_empty());+ }++ // ========================================================================+ // Phase 4.4: Bidirectional Diff & Rollback Tests+ // ========================================================================++ fn make_diff(diff_type: &str, name: &str) -> TableDiff {+ TableDiff {+ diff_type: diff_type.to_string(),+ object_type: Some("table".to_string()),+ name: name.to_string(),+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }+ }++ #[test]+ fn rollback_graph_add_becomes_drop() {+ let diffs = vec![make_diff("added", "new_table")];+ let dep_graph = DependencyGraph { nodes: HashMap::new(), topological_order: vec![] };+ let graph = RollbackGraph::from_forward_diffs(&diffs, &[], &dep_graph);++ assert_eq!(graph.forward_nodes.len(), 1);+ assert_eq!(graph.rollback_nodes.len(), 1);+ assert_eq!(graph.forward_nodes[0].table_diff.diff_type, "added");+ assert_eq!(graph.rollback_nodes[0].table_diff.diff_type, "removed");+ }++ #[test]+ fn rollback_graph_remove_becomes_add() {+ let diffs = vec![make_diff("removed", "old_table")];+ let dep_graph = DependencyGraph { nodes: HashMap::new(), topological_order: vec![] };+ let graph = RollbackGraph::from_forward_diffs(&diffs, &[], &dep_graph);++ assert_eq!(graph.rollback_nodes[0].table_diff.diff_type, "added");+ assert_eq!(graph.rollback_nodes[0].table_diff.ddl, None);+ }++ fn rollback_removed_table_sql(+ database_type: DatabaseType,+ target_schema: Option<&str>,+ source_dialect: Option<DialectKind>,+ target_dialect: DialectKind,+ table_name: &str,+ table_comment: Option<&str>,+ target_detail: TableSchemaDetail,+ ) -> SchemaDiffPreparation {+ prepare_schema_diff(SchemaDiffPreparationOptions {+ target_tables: vec![TableInfo {+ name: table_name.to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: table_comment.map(str::to_string),+ parent_schema: None,+ parent_name: None,+ }],+ target_details: vec![target_detail],+ database_type,+ target_schema: target_schema.map(str::to_string),+ enable_rollback: true,+ source_dialect,+ target_dialect: Some(target_dialect),+ ..Default::default()+ })+ }++ #[test]+ fn dropped_postgres_table_rollback_preserves_structured_snapshot() {+ let table_name = "Order Items";+ let result = rollback_removed_table_sql(+ DatabaseType::Postgres,+ Some("sales"),+ Some(DialectKind::Postgres),+ DialectKind::Postgres,+ table_name,+ Some("order line history"),+ TableSchemaDetail {+ name: table_name.to_string(),+ columns: vec![+ ColumnInfo {+ is_primary_key: true,+ column_default: Some("gen_random_uuid()".to_string()),+ ..column("Item ID", "uuid", Some("stable row id"))+ },+ ColumnInfo {+ column_default: Some("'new'::text".to_string()),+ ..column("Status", "text", Some("workflow state"))+ },+ column("User ID", "bigint", None),+ ],+ indexes: vec![index(IndexInfo {+ name: "Order Status IDX".to_string(),+ columns: vec!["Status".to_string()],+ is_unique: true,+ is_primary: false,+ filter: Some("\"Status\" <> 'deleted'".to_string()),+ index_type: Some("btree".to_string()),+ included_columns: Some(vec!["User ID".to_string()]),+ comment: None,+ })],+ foreign_keys: vec![foreign_key(ForeignKeyInfo {+ name: "Order User FK".to_string(),+ column: "User ID".to_string(),+ ref_schema: Some("auth".to_string()),+ ref_table: "Users".to_string(),+ ref_column: "ID".to_string(),+ on_update: None,+ on_delete: Some("CASCADE".to_string()),+ })],+ triggers: vec![],+ ddl: Some("CREATE TABLE native_postgres_fallback (ignored int)".to_string()),+ },+ );+ let rollback = result.rollback_sync_sql.unwrap();++ assert!(rollback.contains("CREATE TABLE \"sales\".\"Order Items\""), "{rollback}");+ assert!(rollback.contains("\"Item ID\" uuid NOT NULL DEFAULT gen_random_uuid()"), "{rollback}");+ assert!(rollback.contains("PRIMARY KEY (\"Item ID\")"), "{rollback}");+ assert!(rollback.contains("CREATE UNIQUE INDEX \"Order Status IDX\""), "{rollback}");+ assert!(rollback.contains("USING btree"), "{rollback}");+ assert!(rollback.contains("INCLUDE (\"User ID\")"), "{rollback}");+ assert!(rollback.contains("WHERE \"Status\" <> 'deleted'"), "{rollback}");+ assert!(rollback.contains("REFERENCES \"auth\".\"Users\"(\"ID\") ON DELETE CASCADE"), "{rollback}");+ assert!(rollback.contains("COMMENT ON COLUMN \"sales\".\"Order Items\".\"Status\" IS 'workflow state'"));+ assert!(rollback.contains("COMMENT ON TABLE \"sales\".\"Order Items\" IS 'order line history'"));+ assert!(!rollback.contains("native_postgres_fallback"), "{rollback}");+ }++ #[test]+ fn dropped_mysql_table_rollback_preserves_defaults_comments_indexes_and_fk() {+ let table_name = "order-items";+ let result = rollback_removed_table_sql(+ DatabaseType::Mysql,+ Some("shop"),+ Some(DialectKind::Mysql),+ DialectKind::Mysql,+ table_name,+ Some("order item history"),+ TableSchemaDetail {+ name: table_name.to_string(),+ columns: vec![+ ColumnInfo {+ is_primary_key: true,+ column_default: Some("(uuid())".to_string()),+ ..column("item-id", "varchar(36)", Some("stable item id"))+ },+ ColumnInfo {+ column_default: Some("'new'".to_string()),+ ..column("status", "varchar(32)", Some("workflow state"))+ },+ column("user-id", "bigint", None),+ ],+ indexes: vec![index(IndexInfo {+ name: "status-index".to_string(),+ columns: vec!["status".to_string()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: Some("BTREE".to_string()),+ included_columns: None,+ comment: Some("status lookup".to_string()),+ })],+ foreign_keys: vec![foreign_key(ForeignKeyInfo {+ name: "user-fk".to_string(),+ column: "user-id".to_string(),+ ref_schema: Some("identity".to_string()),+ ref_table: "users".to_string(),+ ref_column: "id".to_string(),+ on_update: Some("CASCADE".to_string()),+ on_delete: Some("RESTRICT".to_string()),+ })],+ triggers: vec![],+ ddl: Some("CREATE TABLE native_mysql_fallback (ignored int)".to_string()),+ },+ );+ let rollback = result.rollback_sync_sql.unwrap();++ assert!(rollback.contains("CREATE TABLE `shop`.`order-items`"), "{rollback}");+ assert!(rollback.contains("`item-id` varchar(36) NOT NULL DEFAULT (uuid()) COMMENT 'stable item id'"));+ assert!(rollback.contains("PRIMARY KEY (`item-id`)"), "{rollback}");+ assert!(rollback.contains("CREATE UNIQUE INDEX `status-index` USING BTREE ON `shop`.`order-items` (`status`)"));+ assert!(rollback.contains("COMMENT 'status lookup'"), "{rollback}");+ assert!(rollback.contains("REFERENCES `identity`.`users`(`id`) ON DELETE RESTRICT ON UPDATE CASCADE"));+ assert!(rollback.contains("ALTER TABLE `shop`.`order-items` COMMENT = 'order item history'"));+ assert!(!rollback.contains("native_mysql_fallback"), "{rollback}");+ }++ #[test]+ fn dropped_sqlite_table_rollback_preserves_quoted_pk_index_fk_and_default() {+ let table_name = "select \"items";+ let result = rollback_removed_table_sql(+ DatabaseType::Sqlite,+ None,+ Some(DialectKind::Sqlite),+ DialectKind::Sqlite,+ table_name,+ None,+ TableSchemaDetail {+ name: table_name.to_string(),+ columns: vec![+ ColumnInfo { is_primary_key: true, ..column("item \"id", "TEXT", None) },+ ColumnInfo { column_default: Some("'new'".to_string()), ..column("status", "TEXT", None) },+ column("parent id", "TEXT", None),+ ],+ indexes: vec![index(IndexInfo {+ name: "active status index".to_string(),+ columns: vec!["status".to_string()],+ is_unique: false,+ is_primary: false,+ filter: Some("status <> 'deleted'".to_string()),+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ foreign_keys: vec![foreign_key(ForeignKeyInfo {+ name: "parent item fk".to_string(),+ column: "parent id".to_string(),+ ref_schema: None,+ ref_table: "parent items".to_string(),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: Some("SET NULL".to_string()),+ })],+ triggers: vec![],+ ddl: Some("CREATE TABLE native_sqlite_fallback (ignored int)".to_string()),+ },+ );+ let rollback = result.rollback_sync_sql.unwrap();++ assert!(rollback.contains("CREATE TABLE \"select \"\"items\""), "{rollback}");+ assert!(rollback.contains("\"item \"\"id\" TEXT NOT NULL"), "{rollback}");+ assert!(rollback.contains("\"status\" TEXT NOT NULL DEFAULT 'new'"), "{rollback}");+ assert!(rollback.contains("PRIMARY KEY (\"item \"\"id\")"), "{rollback}");+ assert!(rollback.contains("CONSTRAINT \"parent item fk\" FOREIGN KEY (\"parent id\")"), "{rollback}");+ assert!(rollback.contains("REFERENCES \"parent items\"(\"id\") ON DELETE SET NULL"), "{rollback}");+ assert!(rollback.contains("CREATE INDEX \"active status index\""), "{rollback}");+ assert!(rollback.contains("WHERE status <> 'deleted'"), "{rollback}");+ assert!(!rollback.contains("ALTER TABLE"), "SQLite FK must be part of CREATE TABLE: {rollback}");+ assert!(!rollback.contains("native_sqlite_fallback"), "{rollback}");+ }++ #[test]+ fn dropped_table_cross_dialect_rollback_uses_target_snapshot_and_syntax() {+ let result = rollback_removed_table_sql(+ DatabaseType::Mysql,+ Some("archive"),+ Some(DialectKind::Postgres),+ DialectKind::Mysql,+ "Audit Log",+ None,+ TableSchemaDetail {+ name: "Audit Log".to_string(),+ columns: vec![ColumnInfo {+ is_primary_key: true,+ column_default: Some("0".to_string()),+ ..column("Event ID", "BIGINT UNSIGNED", None)+ }],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: Some("CREATE TABLE native_cross_dialect_fallback (ignored int)".to_string()),+ },+ );+ let rollback = result.rollback_sync_sql.unwrap();++ assert!(rollback.contains("CREATE TABLE `archive`.`Audit Log`"), "{rollback}");+ assert!(rollback.contains("`Event ID` BIGINT UNSIGNED NOT NULL DEFAULT 0 AUTO_INCREMENT"), "{rollback}");+ assert!(!rollback.contains('"'), "rollback must use target MySQL quoting: {rollback}");+ assert!(!rollback.contains("native_cross_dialect_fallback"), "{rollback}");+ }++ #[test]+ fn dropped_table_rollback_uses_native_target_ddl_only_without_structured_columns() {+ let result = rollback_removed_table_sql(+ DatabaseType::Postgres,+ Some("archive"),+ Some(DialectKind::Postgres),+ DialectKind::Postgres,+ "legacy_table",+ None,+ TableSchemaDetail {+ name: "legacy_table".to_string(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: Some("CREATE TABLE \"archive\".\"legacy_table\" (\"id\" bigint PRIMARY KEY)".to_string()),+ },+ );+ let rollback = result.rollback_sync_sql.unwrap();++ assert!(rollback.contains("-- Recreate table from native target DDL: legacy_table"));+ assert!(rollback.contains("CREATE TABLE \"archive\".\"legacy_table\" (\"id\" bigint PRIMARY KEY);"));+ assert!(!rollback.contains("CREATE TABLE \"archive\".\"legacy_table\" (\n \n)"), "{rollback}");+ }++ #[test]+ fn dropped_table_incomplete_trigger_sets_structured_missing_objects() {+ let result = rollback_removed_table_sql(+ DatabaseType::Mysql,+ None,+ Some(DialectKind::Mysql),+ DialectKind::Mysql,+ "orders",+ None,+ TableSchemaDetail {+ name: "orders".to_string(),+ columns: vec![column("id", "int", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![crate::types::TriggerInfo {+ name: "trg_orders".to_string(),+ event: "INSERT".to_string(),+ timing: "AFTER".to_string(),+ statement: None,+ }],+ ddl: None,+ },+ );++ assert_eq!(result.rollback_completeness, RollbackCompleteness::Incomplete);+ assert!(!result.missing_rollback_objects.is_empty());+ assert_eq!(result.missing_rollback_objects[0].kind, "trigger");+ assert_eq!(result.missing_rollback_objects[0].name, "trg_orders");+ assert!(result.missing_rollback_objects[0].table.as_deref() == Some("orders"));+ }++ #[test]+ fn rollback_graph_modified_stays_modified_swapped() {+ let source_col = column("name", "varchar(100)", None);+ let target_col = column("name", "varchar(50)", None);+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "users".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "modified".to_string(),+ name: "name".to_string(),+ source: Some(source_col.clone()),+ target: Some(target_col.clone()),+ changes: vec!["type: varchar(50) → varchar(100)".to_string()],+ }]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ let dep_graph = DependencyGraph { nodes: HashMap::new(), topological_order: vec![] };+ let graph = RollbackGraph::from_forward_diffs(&diffs, &[], &dep_graph);++ let rollback = &graph.rollback_nodes[0];+ assert_eq!(rollback.table_diff.diff_type, "modified");+ let rb_cols = rollback.table_diff.columns.as_ref().unwrap();+ assert_eq!(rb_cols[0].diff_type, "modified");+ assert_eq!(rb_cols[0].source.as_ref().unwrap().data_type, "varchar(50)");+ assert_eq!(rb_cols[0].target.as_ref().unwrap().data_type, "varchar(100)");+ }++ #[test]+ fn rollback_consistency_validation() {+ let diffs = vec![make_diff("added", "t1"), make_diff("removed", "t2")];+ let dep_graph = DependencyGraph { nodes: HashMap::new(), topological_order: vec![] };+ let mut graph = RollbackGraph::from_forward_diffs(&diffs, &[], &dep_graph);+ assert!(graph.validate_consistency());+ assert!(graph.consistency_issues.is_empty());+ }++ // ========================================================================+ // Phase 4.6: Permission Tests+ // ========================================================================++ #[test]+ fn diff_permissions_detects_added_and_removed() {+ let source = vec![PermissionInfo {+ grantee: "app_user".to_string(),+ object_type: "TABLE".to_string(),+ object_name: "orders".to_string(),+ privilege: "SELECT".to_string(),+ is_grantable: false,+ }];+ let target = vec![PermissionInfo {+ grantee: "app_user".to_string(),+ object_type: "TABLE".to_string(),+ object_name: "orders".to_string(),+ privilege: "INSERT".to_string(),+ is_grantable: false,+ }];++ let diffs = diff_permissions(&source, &target);+ assert_eq!(diffs.len(), 2);+ assert!(diffs.iter().any(|d| d.diff_type == "added"));+ assert!(diffs.iter().any(|d| d.diff_type == "removed"));+ }++ #[test]+ fn generate_permission_sql_mysql() {+ let diffs = vec![PermissionDiff {+ diff_type: "added".to_string(),+ grantee: "app_user".to_string(),+ object_name: "orders".to_string(),+ privilege: "SELECT".to_string(),+ source: Some(PermissionInfo {+ grantee: "app_user".to_string(),+ object_type: "TABLE".to_string(),+ object_name: "orders".to_string(),+ privilege: "SELECT".to_string(),+ is_grantable: true,+ }),+ target: None,+ }];++ let sql = generate_permission_sync_sql(&diffs, DatabaseType::Mysql, Some("mydb"));+ assert!(sql.contains("GRANT SELECT ON `mydb`.`orders` TO 'app_user' WITH GRANT OPTION"));+ }++ #[test]+ fn generate_permission_sql_postgres_revoke() {+ let diffs = vec![PermissionDiff {+ diff_type: "removed".to_string(),+ grantee: "old_user".to_string(),+ object_name: "users".to_string(),+ privilege: "INSERT".to_string(),+ source: None,+ target: Some(PermissionInfo {+ grantee: "old_user".to_string(),+ object_type: "TABLE".to_string(),+ object_name: "users".to_string(),+ privilege: "INSERT".to_string(),+ is_grantable: false,+ }),+ }];++ let sql = generate_permission_sync_sql(&diffs, DatabaseType::Postgres, Some("public"));+ assert!(sql.contains("REVOKE INSERT ON TABLE \"public\".\"users\" FROM \"old_user\""));+ }++ // ========================================================================+ // Phase 4.7: Resource Scheduling Tests+ // ========================================================================++ #[test]+ fn adaptive_scheduler_optimal_batch_size() {+ let constraint = ResourceConstraint::default();+ let scheduler = AdaptiveScheduler::new(constraint, 400);+ let batch = scheduler.optimal_batch_size();+ assert!(batch > 0);+ assert!(batch <= 50);+ }++ #[test]+ fn adaptive_scheduler_shard_count() {+ let constraint = ResourceConstraint::default();+ let scheduler = AdaptiveScheduler::new(constraint, 200);+ let count = scheduler.recommended_shard_count();+ assert!(count >= 1);+ assert!(count <= 4);+ }++ // ========================================================================+ // Phase 4.8: Backward Compatibility Tests+ // ========================================================================++ #[test]+ fn new_options_default_values_do_not_affect_basic_diff() {+ let options = SchemaDiffPreparationOptions::default();+ let result = prepare_schema_diff(options);+ assert!(result.diffs.is_empty());+ assert!(result.sync_sql.is_empty());+ assert!(result.rollback_sync_sql.is_none());+ assert!(result.rename_candidates.is_empty());+ assert!(result.rollback_graph.is_none());+ assert!(result.compatibility_warnings.is_empty());+ assert!(result.permission_diffs.is_empty());+ }++ #[test]+ fn prepare_schema_diff_with_rename_detection() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "users_old".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "users_new".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "users_old".to_string(),+ columns: vec![column("id", "int", None), column("name", "varchar(100)", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ target_details: vec![TableSchemaDetail {+ name: "users_new".to_string(),+ columns: vec![column("id", "int", None), column("name", "varchar(100)", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ source_functions: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type: DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ detect_renames: true,+ detect_table_renames: true,+ rename_threshold: 0.5,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(!result.rename_candidates.is_empty());+ assert!(result.rename_candidates[0].score >= 0.5);+ }++ #[test]+ fn prepare_schema_diff_with_rollback_generates_rollback_sql() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "new_table".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![],+ source_details: vec![TableSchemaDetail {+ name: "new_table".to_string(),+ columns: vec![column("id", "int", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: Some("CREATE TABLE new_table (id int);".to_string()),+ }],+ target_details: vec![],+ source_functions: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type: DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(result.rollback_sync_sql.is_some());+ assert!(result.rollback_graph.is_some());+ let graph = result.rollback_graph.unwrap();+ assert!(graph.is_consistent);+ assert_eq!(graph.forward_nodes.len(), 1);+ assert_eq!(graph.rollback_nodes.len(), 1);+ assert_eq!(graph.rollback_nodes[0].table_diff.diff_type, "removed");+ }++ // -- 31. column_type_similarity_score unit tests --+ #[test]+ fn column_type_similarity_exact_match() {+ assert_eq!(column_type_similarity_score("int", "int"), 1.0);+ assert_eq!(column_type_similarity_score("VARCHAR(255)", "varchar(255)"), 1.0);+ assert_eq!(column_type_similarity_score("datetime", "datetime"), 1.0);+ }++ #[test]+ fn column_type_similarity_synonym() {+ assert_eq!(column_type_similarity_score("int", "integer"), 1.0);+ assert_eq!(column_type_similarity_score("boolean", "bool"), 1.0);+ assert_eq!(column_type_similarity_score("datetime", "timestamp"), 1.0);+ assert_eq!(column_type_similarity_score("double", "double precision"), 1.0);+ }++ #[test]+ fn column_type_similarity_family() {+ assert_eq!(column_type_similarity_score("tinyint", "bigint"), 0.8);+ assert_eq!(column_type_similarity_score("char", "text"), 0.8);+ assert_eq!(column_type_similarity_score("mediumtext", "clob"), 0.8);+ }++ #[test]+ fn column_type_similarity_unrelated() {+ assert_eq!(column_type_similarity_score("int", "varchar"), 0.0);+ assert_eq!(column_type_similarity_score("boolean", "text"), 0.0);+ assert_eq!(column_type_similarity_score("blob", "date"), 0.0);+ }++ #[test]+ fn column_type_similarity_parameterized_ignored() {+ assert_eq!(column_type_similarity_score("int(11)", "int(11)"), 1.0);+ assert_eq!(column_type_similarity_score("int(11)", "integer"), 1.0);+ assert_eq!(column_type_similarity_score("varchar(255)", "varchar(64)"), 1.0);+ }++ // -- 32. Multiple renames in one table --+ #[test]+ fn multiple_renames_in_one_table() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_a", "varchar(50)"), ("new_b", "int")],+ &[("id", "int"), ("old_a", "varchar(50)"), ("old_b", "int")],+ true,+ );+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed.len(), 2, "should detect two renames: {renamed:?}");+ assert_eq!(renamed[0].name, "new_a");+ assert_eq!(renamed[1].name, "new_b");+ }++ #[test]+ fn multiple_renames_sql() {+ let diffs = make_col_diffs(+ &[("id", "int"), ("new_a", "varchar(50)"), ("new_b", "int")],+ &[("id", "int"), ("old_a", "varchar(50)"), ("old_b", "int")],+ true,+ );+ for (db, label) in [(DatabaseType::Mysql, "MySQL"), (DatabaseType::Postgres, "PG")] {+ let sql = gen_sql(wrap_table_diff("t", diffs.clone()), db, None);+ // Two renames → two CHANGE COLUMN / RENAME COLUMN operations+ let _n: u64 = 2;+ assert!(sql.contains("COLUMN"), "{label}: {sql}");+ }+ }++ // -- 33. Rename threshold edge cases --+ #[test]+ fn rename_threshold_zero_detects_all() {+ let s: Vec<ColumnInfo> = vec![column("a", "int", None), column("b2", "varchar(10)", None)];+ let t: Vec<ColumnInfo> = vec![column("a", "int", None), column("b1", "varchar(10)", None)];+ // rename detection is skipped when threshold <= 0.0, use a tiny threshold+ let diffs = diff_columns_with_options(&s, &t, false, false, true, 0.001);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed.len(), 1, "threshold near-zero should detect: {renamed:?}");+ }++ #[test]+ fn rename_threshold_one_detects_exact_only() {+ let s: Vec<ColumnInfo> = vec![column("a", "varchar(10)", None), column("b2", "text", None)];+ let t: Vec<ColumnInfo> = vec![column("a", "varchar(10)", None), column("b1", "varchar(10)", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, true, 1.0);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed.len(), 0, "threshold 1 should not match text≠varchar: {renamed:?}");+ }++ #[test]+ fn rename_threshold_mid_detects_family_only() {+ let s: Vec<ColumnInfo> = vec![column("a", "tinyint", None), column("b2", "int", None)];+ let t: Vec<ColumnInfo> = vec![column("a", "tinyint", None), column("b1", "bigint", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, true, 0.9);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed.len(), 0, "threshold 0.9 should not match tinyint≠bigint: {renamed:?}");+ let diffs2 = diff_columns_with_options(&s, &t, false, false, true, 0.5);+ let renamed2: Vec<_> = diffs2.iter().filter(|d| d.diff_type == "renamed").collect();+ assert_eq!(renamed2.len(), 1, "threshold 0.5 should detect integer family: {renamed2:?}");+ }++ // -- 34. Default value changes --+ #[test]+ fn default_value_change_mysql() {+ let source = vec![ColumnInfo { column_default: Some("'guest'".into()), ..column("name", "varchar(50)", None) }];+ let target = vec![ColumnInfo { column_default: None, ..column("name", "varchar(50)", None) }];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert!(sql.contains("MODIFY COLUMN"), "default change: {sql}");+ }++ #[test]+ fn default_value_change_postgres() {+ let source = vec![ColumnInfo { column_default: Some("'guest'".into()), ..column("name", "varchar(50)", None) }];+ let target = vec![ColumnInfo { column_default: None, ..column("name", "varchar(50)", None) }];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("SET DEFAULT"), "default add: {sql}");+ }++ #[test]+ fn default_value_drop_postgres() {+ let source = vec![ColumnInfo { column_default: None, ..column("name", "varchar(50)", None) }];+ let target = vec![ColumnInfo { column_default: Some("'old'".into()), ..column("name", "varchar(50)", None) }];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("DROP DEFAULT"), "default drop: {sql}");+ }++ // -- 35. Column order changes --+ #[test]+ fn column_order_change_only_no_type_change() {+ let source = vec![column("id", "int", None), column("name", "text", None), column("age", "int", None)];+ let target = vec![column("age", "int", None), column("name", "text", None), column("id", "int", None)];+ let diffs = diff_columns_with_options(&source, &target, false, true, false, 0.5);+ assert!(!diffs.is_empty(), "should detect order changes");+ assert!(diffs.iter().all(|d| d.diff_type == "modified"), "all should be modified");+ assert!(diffs.iter().all(|d| d.changes.iter().any(|c| c.starts_with("order:"))), "all order changes");+ }++ #[test]+ fn column_order_changes_with_source_dialect() {+ let source = vec![column("id", "int(11)", None), column("name", "varchar(50)", None)];+ let target = vec![column("name", "text", None), column("id", "int", None)];+ let diffs = diff_columns_with_options(&source, &target, false, true, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, Some(DialectKind::Mysql));+ assert!(sql.contains("INTEGER"), "type converted: {sql}");+ }++ // -- 36. prepare_schema_diff integration with source_dialect --+ #[test]+ fn prepare_schema_diff_with_source_dialect() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "users".into(),+ table_type: "BASE TABLE".into(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "users".into(),+ table_type: "BASE TABLE".into(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "users".into(),+ columns: vec![column("name2", "varchar(100)", None), column("id", "int(11)", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ target_details: vec![TableSchemaDetail {+ name: "users".into(),+ columns: vec![column("name", "varchar(100)", None), column("id", "int", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ database_type: DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ detect_renames: true,+ detect_table_renames: false,+ rename_threshold: 0.5,+ enable_rollback: false,+ source_dialect: Some(DialectKind::Mysql),+ target_dialect: Some(DialectKind::Mysql),+ ..Default::default()+ };+ let result = prepare_schema_diff(options);+ assert!(!result.diffs.is_empty(), "should have diffs");+ let sql = &result.sync_sql;+ assert!(sql.contains("CHANGE COLUMN"), "detected rename: {sql}");+ assert!(!sql.contains("DROP COLUMN"), "no false drop: {sql}");+ }++ #[test]+ fn prepare_schema_diff_integration_cross_dialect() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "t".into(),+ columns: vec![column("flag", "tinyint", None), column("name2", "varchar(50)", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ target_details: vec![TableSchemaDetail {+ name: "t".into(),+ columns: vec![column("flag", "smallint", None), column("name", "varchar(50)", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ database_type: DatabaseType::Postgres,+ detect_renames: true,+ rename_threshold: 0.5,+ source_dialect: Some(DialectKind::Mysql),+ target_dialect: Some(DialectKind::Postgres),+ ..Default::default()+ };+ let result = prepare_schema_diff(options);+ let sql = &result.sync_sql;+ assert!(sql.contains("RENAME COLUMN"), "PG rename: {sql}");+ assert!(sql.contains("SMALLINT"), "tinyint→SMALLINT: {sql}");+ assert!(!sql.contains('`'), "PG no backticks: {sql}");+ }++ // -- 37. Index + column rename combined --+ #[test]+ fn index_and_rename_combined() {+ let col_diffs =+ make_col_diffs(&[("id", "int"), ("name2", "varchar(50)")], &[("id", "int"), ("name", "varchar(50)")], true);+ let table_diff = TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: Some(col_diffs),+ indexes: Some(vec![IndexDiff {+ diff_type: "added".to_string(),+ name: "idx_name".to_string(),+ source: Some(index(IndexInfo {+ name: "idx_name".to_string(),+ columns: vec!["name2".to_string()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })),+ target: None,+ changes: vec![],+ }]),+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql =+ generate_schema_sync_sql(&[table_diff], &[], &[], &[], &[], DatabaseType::Postgres, None, false, None, &[]);+ assert!(sql.contains("RENAME COLUMN"), "rename: {sql}");+ assert!(sql.contains("CREATE INDEX"), "index: {sql}");+ }++ #[test]+ fn index_and_rename_combined_mysql() {+ let col_diffs =+ make_col_diffs(&[("id", "int"), ("name2", "varchar(50)")], &[("id", "int"), ("name", "varchar(50)")], true);+ let table_diff = TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: Some(col_diffs),+ indexes: Some(vec![IndexDiff {+ diff_type: "removed".to_string(),+ name: "idx_old".to_string(),+ source: None,+ target: Some(index(IndexInfo {+ name: "idx_old".to_string(),+ columns: vec!["name".to_string()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })),+ changes: vec![],+ }]),+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql =+ generate_schema_sync_sql(&[table_diff], &[], &[], &[], &[], DatabaseType::Mysql, None, false, None, &[]);+ assert!(sql.contains("CHANGE COLUMN"), "rename: {sql}");+ assert!(sql.contains("DROP INDEX"), "drop index: {sql}");+ }++ // -- 38. diff_columns_with_compatibility cross-dialect --+ #[test]+ fn diff_columns_with_compatibility_cross_dialect() {+ let source = vec![column("id", "int(11)", None)];+ let target = vec![column("id", "integer", None)];+ let (_diffs, warnings) = diff_columns_with_compatibility(+ &source,+ &target,+ false,+ false,+ DialectKind::Mysql,+ DialectKind::Postgres,+ 0.5,+ &[],+ );+ // int(11)→integer should be compatible+ let has_warning = warnings.iter().any(|w| w.column_name == "id");+ assert!(!has_warning, "int(11)→integer should be compatible");+ }++ #[test]+ fn diff_columns_with_compatibility_warning() {+ let source = vec![column("id", "int", None)];+ let target = vec![column("id", "text", None)];+ let (_diffs, warnings) = diff_columns_with_compatibility(+ &source,+ &target,+ false,+ false,+ DialectKind::Mysql,+ DialectKind::Postgres,+ 0.9,+ &[],+ );+ let has_warning = warnings.iter().any(|w| w.column_name == "id");+ assert!(has_warning, "int→text should generate warning");+ }++ // -- 39. Type mapping prefix matching edge cases --+ #[test]+ fn convert_type_prefix_matches_parameterized() {+ use crate::sql_dialect::descriptor::TypeMappingMatrix;+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ let (result, _) = matrix.convert_type("tinyint(1)");+ assert_eq!(result, "BOOLEAN", "tinyint(1) → BOOLEAN");+ // tinyint(4) matches TINYINT prefix rule → SMALLINT (not BOOLEAN)+ let (result, _) = matrix.convert_type("tinyint(4)");+ assert_eq!(result, "SMALLINT", "tinyint(4) → SMALLINT");+ }++ #[test]+ fn convert_type_unknown_type_passthrough() {+ use crate::sql_dialect::descriptor::TypeMappingMatrix;+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ let (result, requires_cast) = matrix.convert_type("geometry");+ assert_eq!(result, "geometry", "unknown type passthrough");+ assert!(requires_cast, "unknown type requires cast");+ }++ #[test]+ fn convert_type_empty_string() {+ use crate::sql_dialect::descriptor::TypeMappingMatrix;+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ let (result, _) = matrix.convert_type("");+ assert_eq!(result, "", "empty string passthrough");+ }++ // -- 40. Rollback SQL with column renames --+ #[test]+ fn rollback_graph_with_renames() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "renamed".to_string(),+ name: "new_name".to_string(),+ source: Some(column("new_name", "varchar(50)", None)),+ target: Some(column("old_name", "varchar(50)", None)),+ changes: vec!["old_name → new_name".to_string()],+ }]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];+ let dep_graph = DependencyGraph::build(&[], &[]);+ let graph = RollbackGraph::from_forward_diffs(&diffs, &[], &dep_graph);+ let rollback_sql = generate_rollback_sync_sql(&graph, DatabaseType::Mysql, None, false);+ assert!(+ rollback_sql.contains("CHANGE COLUMN `new_name` `old_name`"),+ "rollback should reverse rename: {rollback_sql}"+ );+ }++ #[test]+ fn rollback_with_cross_dialect_type_conversion() {+ let diffs = vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "added".to_string(),+ name: "id".to_string(),+ source: Some(column("id", "int(11)", None)),+ target: None,+ changes: vec![],+ }]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];+ let dep_graph = DependencyGraph::build(&[], &[]);+ let graph = RollbackGraph::from_forward_diffs(&diffs, &[], &dep_graph);+ let rollback_sql = generate_rollback_sync_sql(&graph, DatabaseType::Postgres, None, false);+ assert!(rollback_sql.contains("DROP COLUMN"), "rollback add→drop: {rollback_sql}");+ }++ // -- 41. Multiple MySQL→PG type conversion in combined SQL --+ #[test]+ fn cross_dialect_multiple_type_conversions_in_one_alter() {+ let diffs = make_col_diffs(+ &[("a1", "tinyint"), ("b1", "mediumint"), ("c1", "float"), ("d1", "double"), ("e1", "datetime")],+ &[],+ false,+ );+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, Some(DialectKind::Mysql));+ assert!(sql.contains("SMALLINT"), "tinyint→SMALLINT: {sql}");+ assert!(sql.contains("INTEGER"), "mediumint→INTEGER: {sql}");+ assert!(sql.contains("REAL"), "float→REAL: {sql}");+ assert!(sql.contains("DOUBLE PRECISION"), "double→DOUBLE PRECISION: {sql}");+ assert!(sql.contains("TIMESTAMP"), "datetime→TIMESTAMP: {sql}");+ }++ // -- 42. ADD COLUMN with default value --+ #[test]+ fn add_column_with_default_value() {+ let source = vec![ColumnInfo { column_default: Some("0".into()), ..column("status", "int", None) }];+ let target: Vec<ColumnInfo> = vec![];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ for (db, label) in [(DatabaseType::Mysql, "MySQL"), (DatabaseType::Postgres, "PG")] {+ let sql = gen_sql(wrap_table_diff("t", diffs.clone()), db, None);+ assert!(sql.contains("DEFAULT 0"), "{label} default: {sql}");+ }+ }++ // -- 43. Comment changes for non-MySQL databases --+ #[test]+ fn column_comment_change_non_mysql() {+ let source = vec![column("name", "text", Some("new comment"))];+ let target = vec![column("name", "text", Some("old comment"))];+ let diffs = diff_columns_with_options(&source, &target, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Postgres, None);+ assert!(sql.contains("COMMENT ON COLUMN"), "PG comment: {sql}");+ }++ #[test]+ fn table_comment_change_mysql() {+ let _diffs: Vec<ColumnDiff> = vec![];+ let table_diff = TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: Some(Some("new".to_string())),+ target_table_comment: Some(Some("old".to_string())),+ sync_sql: None,+ };+ let sql =+ generate_schema_sync_sql(&[table_diff], &[], &[], &[], &[], DatabaseType::Mysql, None, false, None, &[]);+ assert!(sql.contains("COMMENT ="), "MySQL table comment: {sql}");+ }++ // -- 44. Detect renames function (table-level) --+ #[test]+ fn table_detect_renames_exact_match() {+ let removed = vec!["old_table".to_string()];+ let added = vec!["new_table".to_string()];+ let source_details = vec![TableSchemaDetail {+ name: "new_table".into(),+ columns: vec![column("id", "int", None), column("name", "text", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }];+ let target_details = vec![TableSchemaDetail {+ name: "old_table".into(),+ columns: vec![column("id", "int", None), column("name", "text", None)],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }];+ let candidates = detect_renames(&removed, &added, &source_details, &target_details, 0.5);+ assert_eq!(candidates.len(), 1, "should detect table rename");+ assert_eq!(candidates[0].source_name, "new_table");+ assert_eq!(candidates[0].target_name, "old_table");+ }++ // -- 45. Column rename detection: greedy matching avoids conflicts --+ #[test]+ fn rename_greedy_matching() {+ let s: Vec<ColumnInfo> = vec![column("a", "int", None), column("b", "varchar(10)", None)];+ let t: Vec<ColumnInfo> = vec![column("x", "int", None), column("y", "int", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, true, 0.5);+ let renamed: Vec<_> = diffs.iter().filter(|d| d.diff_type == "renamed").collect();+ // Only one should be renamed (greedy: best score), the other stays added/removed+ assert!(renamed.len() <= 1, "greedy should avoid double matching: {renamed:?}");+ }++ // -- 46. Column precision/scale changes --+ #[test]+ fn column_precision_scale_change() {+ let s = vec![column("amount", "decimal(10,2)", None)];+ let t = vec![column("amount", "decimal(8,0)", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ assert_eq!(diffs.len(), 1, "should detect precision change");+ assert!(+ diffs[0].changes.iter().any(|c| c.contains("decimal(8,0) → decimal(10,2)")),+ "precision diff: {:?}",+ diffs[0].changes+ );+ }++ #[test]+ fn column_precision_change_generates_sql() {+ let s = vec![column("price", "decimal(10,2)", None)];+ let t = vec![column("price", "decimal(8,2)", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert!(sql.contains("decimal(10,2)"), "precision in sql: {sql}");+ }++ // -- 47. Column length changes --+ #[test]+ fn column_length_change_detected() {+ let s = vec![column("name", "varchar(255)", None)];+ let t = vec![column("name", "varchar(100)", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ assert_eq!(diffs.len(), 1, "should detect length change");+ assert!(+ diffs[0].changes.iter().any(|c| c.contains("varchar(100) → varchar(255)")),+ "length diff: {:?}",+ diffs[0].changes+ );+ }++ #[test]+ fn column_length_change_generates_modify_sql() {+ let s = vec![column("name", "varchar(255)", None)];+ let t = vec![column("name", "varchar(100)", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ for (db, label) in [(DatabaseType::Mysql, "MySQL"), (DatabaseType::Postgres, "PG")] {+ let sql = gen_sql(wrap_table_diff("t", diffs.clone()), db, None);+ assert!(sql.contains("varchar(255)"), "{label} length: {sql}");+ }+ }++ // -- 48. Column comment changes with ignore_comments option --+ #[test]+ fn column_comment_change_detected() {+ let s = vec![column("name", "int", Some("new comment"))];+ let t = vec![column("name", "int", Some("old comment"))];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ assert_eq!(diffs.len(), 1, "should detect comment change");+ assert!(diffs[0].changes.iter().any(|c| c.starts_with("comment:")), "comment diff: {:?}", diffs[0].changes);+ }++ #[test]+ fn column_comment_ignored_when_option_set() {+ let s = vec![column("name", "int", Some("new"))];+ let t = vec![column("name", "int", Some("old"))];+ let diffs = diff_columns_with_options(&s, &t, true, false, false, 0.5);+ assert!(diffs.is_empty(), "should ignore comment when option set: {diffs:?}");+ }++ #[test]+ fn column_comment_change_mysql_sql() {+ let s = vec![column("name", "varchar(50)", Some("中文注释"))];+ let t = vec![column("name", "varchar(50)", Some("old"))];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ let sql = gen_sql(wrap_table_diff("t", diffs), DatabaseType::Mysql, None);+ assert!(sql.contains("COMMENT"), "MySQL comment: {sql}");+ assert!(sql.contains("中文注释"), "Chinese comment: {sql}");+ }++ #[test]+ fn table_comment_change_mysql_sql() {+ let _diffs: Vec<ColumnDiff> = vec![];+ let table_diff = TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: None,+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: Some(Some("新表".to_string())),+ target_table_comment: Some(Some("旧表".to_string())),+ sync_sql: None,+ };+ let sql =+ generate_schema_sync_sql(&[table_diff], &[], &[], &[], &[], DatabaseType::Mysql, None, false, None, &[]);+ assert!(sql.contains("COMMENT ="), "MySQL table comment: {sql}");+ assert!(sql.contains("新表"), "Chinese table comment: {sql}");+ }++ #[test]+ fn table_comment_ignored_with_option() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: Some("new".into()),+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: Some("old".into()),+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "t".into(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ target_details: vec![TableSchemaDetail {+ name: "t".into(),+ columns: vec![],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ database_type: DatabaseType::Mysql,+ ignore_comments: true,+ ..Default::default()+ };+ let result = prepare_schema_diff(options);+ assert!(result.diffs.is_empty(), "should ignore table comment: {:?}", result.diffs);+ }++ // -- 49. Index type differences --+ #[test]+ fn index_type_diff_btree_vs_hash() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: Some("BTREE".into()),+ included_columns: None,+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: Some("HASH".into()),+ included_columns: None,+ comment: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "index type diff detected");+ assert!(diffs[0].changes.iter().any(|c| c.contains("type:")), "type change: {:?}", diffs[0].changes);+ }++ #[test]+ fn index_type_fulltext_detected() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["content".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: Some("FULLTEXT".into()),+ included_columns: None,+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["content".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ );+ assert_eq!(diffs[0].changes.iter().filter(|c| c.contains("FULLTEXT")).count(), 1, "fulltext change");+ }++ // -- 50. Index column ordering --+ #[test]+ fn index_column_order_different() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into(), "b".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["b".into(), "a".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "order diff detected");+ assert!(diffs[0].changes.iter().any(|c| c.contains("columns:")), "column order change: {:?}", diffs[0].changes);+ }++ // -- 51. Included columns in indexes --+ #[test]+ fn index_included_columns_diff() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: Some(vec!["b".into(), "c".into()]),+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: Some(vec!["b".into()]),+ comment: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "included columns diff detected");+ assert!(diffs[0].changes.iter().any(|c| c.contains("include:")), "include change: {:?}", diffs[0].changes);+ }++ #[test]+ fn index_included_columns_added() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: Some(vec!["b".into()]),+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["a".into()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "included added");+ }++ // -- 52. Filtered/partial indexes --+ #[test]+ fn index_filter_change() {+ let diffs = diff_indexes(+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["status".into()],+ is_unique: false,+ is_primary: false,+ filter: Some("status > 0".into()),+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ &[index(IndexInfo {+ name: "idx_t".into(),+ columns: vec!["status".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "filter diff");+ assert!(diffs[0].changes.iter().any(|c| c.contains("filter:")), "filter change: {:?}", diffs[0].changes);+ }++ // -- 53. Multiple index operations in one diff --+ #[test]+ fn multiple_index_operations() {+ let diffs = diff_indexes(+ &[+ index(IndexInfo {+ name: "idx_new".into(),+ columns: vec!["a".into()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ }),+ index(IndexInfo {+ name: "idx_modified".into(),+ columns: vec!["a".into(), "b".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: Some("BTREE".into()),+ included_columns: None,+ comment: None,+ }),+ ],+ &[+ index(IndexInfo {+ name: "idx_removed".into(),+ columns: vec!["c".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ }),+ index(IndexInfo {+ name: "idx_modified".into(),+ columns: vec!["a".into()],+ is_unique: true,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ }),+ ],+ );+ assert_eq!(diffs.len(), 3, "add + modify + remove: {diffs:?}");+ let types: Vec<&str> = diffs.iter().map(|d| d.diff_type.as_str()).collect();+ assert!(types.contains(&"added"), "should have added");+ assert!(types.contains(&"removed"), "should have removed");+ assert!(types.contains(&"modified"), "should have modified");+ }++ // -- 54. Foreign key ref_table / ref_column changes --+ #[test]+ fn foreign_key_reference_table_change() {+ let diffs = diff_foreign_keys(+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: None,+ })],+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: None,+ ref_table: "employees".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "ref_table change");+ assert!(diffs[0].changes.iter().any(|c| c.contains("ref table")), "ref table: {:?}", diffs[0].changes);+ }++ #[test]+ fn foreign_key_reference_column_change() {+ let diffs = diff_foreign_keys(+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: None,+ })],+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "uid".into(),+ on_update: None,+ on_delete: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "ref_column change");+ }++ #[test]+ fn foreign_key_local_column_change() {+ let diffs = diff_foreign_keys(+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: None,+ })],+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "member_id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "local column change");+ }++ #[test]+ fn foreign_key_referential_action_change() {+ let diffs = diff_foreign_keys(+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: Some("auth".into()),+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: Some("cascade".into()),+ on_delete: Some("SET NULL".into()),+ })],+ &[foreign_key(ForeignKeyInfo {+ name: "fk_t".into(),+ column: "user_id".into(),+ ref_schema: Some("auth".into()),+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: Some("NO ACTION".into()),+ on_delete: Some("RESTRICT".into()),+ })],+ );+ assert_eq!(diffs.len(), 1, "referential action change: {diffs:?}");+ assert!(diffs[0].changes.iter().any(|change| change == "delete: RESTRICT → SET NULL"));+ assert!(diffs[0].changes.iter().any(|change| change == "update: NO ACTION → CASCADE"));+ }++ #[test]+ fn modified_foreign_key_sql_preserves_reference_schema_and_actions() {+ let table_diff = TableDiff {+ diff_type: "modified".into(),+ object_type: Some("table".into()),+ name: "orders".into(),+ columns: None,+ indexes: None,+ foreign_keys: Some(vec![ForeignKeyDiff {+ diff_type: "modified".into(),+ name: "orders_user_fk".into(),+ source: Some(foreign_key(ForeignKeyInfo {+ name: "orders_user_fk".into(),+ column: "user_id".into(),+ ref_schema: Some("identity".into()),+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: Some("CASCADE".into()),+ on_delete: Some("SET NULL".into()),+ })),+ target: None,+ changes: vec![],+ }]),+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql = generate_schema_sync_sql(+ &[table_diff],+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Postgres,+ Some("sales"),+ false,+ None,+ &[],+ );+ assert!(sql.contains("REFERENCES \"identity\".\"users\" (\"id\")"), "schema: {sql}");+ assert!(sql.contains("ON DELETE SET NULL ON UPDATE CASCADE"), "actions: {sql}");+ }++ #[test]+ fn column_index_fk_combined_diff() {+ let col_diffs = make_col_diffs(+ &[("id", "int"), ("name2", "varchar(100)")],+ &[("id", "int"), ("name", "varchar(50)")],+ true,+ );+ let table_diff = TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "t".to_string(),+ columns: Some(col_diffs),+ indexes: Some(vec![+ IndexDiff {+ diff_type: "added".to_string(),+ name: "idx_name".into(),+ source: Some(index(IndexInfo {+ name: "idx_name".into(),+ columns: vec!["name2".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: Some("BTREE".into()),+ included_columns: None,+ comment: None,+ })),+ target: None,+ changes: vec![],+ },+ IndexDiff {+ diff_type: "removed".to_string(),+ name: "idx_old".into(),+ source: None,+ target: Some(index(IndexInfo {+ name: "idx_old".into(),+ columns: vec!["name".into()],+ is_unique: false,+ is_primary: false,+ filter: None,+ index_type: None,+ included_columns: None,+ comment: None,+ })),+ changes: vec![],+ },+ ]),+ foreign_keys: Some(vec![ForeignKeyDiff {+ diff_type: "modified".to_string(),+ name: "fk_ref".into(),+ source: Some(foreign_key(ForeignKeyInfo {+ name: "fk_ref".into(),+ column: "id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: Some("CASCADE".into()),+ })),+ target: Some(foreign_key(ForeignKeyInfo {+ name: "fk_ref".into(),+ column: "id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: Some("SET NULL".into()),+ })),+ changes: vec!["delete: SET NULL → CASCADE".into()],+ }]),+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql =+ generate_schema_sync_sql(&[table_diff], &[], &[], &[], &[], DatabaseType::Postgres, None, false, None, &[]);+ assert!(sql.contains("RENAME COLUMN"), "rename: {sql}");+ assert!(sql.contains("CREATE INDEX"), "add index: {sql}");+ assert!(sql.contains("DROP INDEX"), "drop index: {sql}");+ assert!(sql.contains("DROP CONSTRAINT"), "fk drop: {sql}");+ assert!(sql.contains("ADD CONSTRAINT"), "fk add: {sql}");}- lines.join("\n").trim().to_string()-}--#[cfg(test)]-mod tests {- use super::*;-- fn index(overrides: IndexInfo) -> IndexInfo {- IndexInfo {- name: if overrides.name.is_empty() { "idx_users_email".to_string() } else { overrides.name },- columns: if overrides.columns.is_empty() { vec!["email".to_string()] } else { overrides.columns },- is_unique: overrides.is_unique,- is_primary: overrides.is_primary,- filter: overrides.filter,- index_type: overrides.index_type,- included_columns: overrides.included_columns,- comment: overrides.comment,- }+ // -- 56. Column order changes with comment option --+ #[test]+ fn column_order_ignored_when_disabled_but_comment_detected() {+ let s = vec![column("a", "int", Some("x")), column("b", "varchar(10)", None)];+ let t = vec![column("b", "varchar(10)", None), column("a", "int", None)];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ // order compare disabled, so only comment change on "a" should be detected+ assert!(!diffs.is_empty(), "comment change should be detected: {diffs:?}");}- fn foreign_key(overrides: ForeignKeyInfo) -> ForeignKeyInfo {- ForeignKeyInfo {- name: if overrides.name.is_empty() { "orders_user_id_fk".to_string() } else { overrides.name },- column: if overrides.column.is_empty() { "user_id".to_string() } else { overrides.column },- ref_schema: overrides.ref_schema,- ref_table: if overrides.ref_table.is_empty() { "users".to_string() } else { overrides.ref_table },- ref_column: if overrides.ref_column.is_empty() { "id".to_string() } else { overrides.ref_column },- on_update: overrides.on_update,- on_delete: overrides.on_delete,- }+ // -- 57. Type conversion with precision types (decimal, numeric) --+ #[test]+ fn decimal_type_conversion_mysql_to_postgres() {+ use crate::sql_dialect::descriptor::TypeMappingMatrix;+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ // decimal is not in the mapping rules → passes through+ let (result, _) = matrix.convert_type("decimal(10,2)");+ assert_eq!(result, "decimal(10,2)", "decimal passthrough");}- fn column(name: &str, data_type: &str, comment: Option<&str>) -> ColumnInfo {- ColumnInfo {- name: name.to_string(),- data_type: data_type.to_string(),+ // -- 58. Column diff with all attributes different --+ #[test]+ fn column_all_attributes_changed() {+ let s = vec![ColumnInfo {+ name: "c".into(),+ data_type: "varchar(100)".into(),+ is_nullable: true,+ column_default: Some("'default'".into()),+ comment: Some("new".into()),+ is_primary_key: false,+ extra: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }];+ let t = vec![ColumnInfo {+ name: "c".into(),+ data_type: "varchar(50)".into(),is_nullable: false,column_default: None,+ comment: Some("old".into()),is_primary_key: false,extra: None,- comment: comment.map(str::to_string),numeric_precision: None,numeric_scale: None,character_maximum_length: None,enum_values: None,- ..Default::default()- }+ character_set: None,+ collation: None,+ }];+ let diffs = diff_columns_with_options(&s, &t, false, false, false, 0.5);+ assert_eq!(diffs.len(), 1, "all changes in one diff");+ let changes = &diffs[0].changes;+ assert!(changes.iter().any(|c| c.starts_with("type:")), "type: {changes:?}");+ assert!(changes.iter().any(|c| c.starts_with("nullable:")), "nullable: {changes:?}");+ assert!(changes.iter().any(|c| c.starts_with("default:")), "default: {changes:?}");+ assert!(changes.iter().any(|c| c.starts_with("comment:")), "comment: {changes:?}");}+ // -- 56. Foreign key with multiple changes (ref_table + ref_column) --#[test]- fn formats_mysql_metadata_defaults_as_valid_column_definitions() {- let cases = [- ("varchar(50)", "外籍一般件", "DEFAULT '外籍一般件'"),- ("VARCHAR(50)", "uppercase type", "DEFAULT 'uppercase type'"),- ("varchar(50)", "", "DEFAULT ''"),- ("varchar(50)", "O'Reilly\\docs", "DEFAULT 'O''Reilly\\docs'"),- ("int", "7", "DEFAULT 7"),- ("decimal(10,2)", "1.00", "DEFAULT 1.00"),- ("timestamp", "CURRENT_TIMESTAMP", "DEFAULT CURRENT_TIMESTAMP"),- ("timestamp(3)", "CURRENT_TIMESTAMP(3)", "DEFAULT CURRENT_TIMESTAMP(3)"),- ("varchar(36)", "(UUID())", "DEFAULT (UUID())"),- ("json", "(JSON_ARRAY())", "DEFAULT (JSON_ARRAY())"),- ("text", "plain text", "DEFAULT ('plain text')"),- ("json", "{}", "DEFAULT ('{}')"),- ("varchar(50)", "'already quoted'", "DEFAULT 'already quoted'"),- ];+ fn foreign_key_multiple_changes() {+ let diffs = diff_foreign_keys(+ &[foreign_key(ForeignKeyInfo {+ name: "fk".into(),+ column: "id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: None,+ })],+ &[foreign_key(ForeignKeyInfo {+ name: "fk".into(),+ column: "id".into(),+ ref_schema: None,+ ref_table: "employees".into(),+ ref_column: "uid".into(),+ on_update: None,+ on_delete: None,+ })],+ );+ assert_eq!(diffs.len(), 1, "multiple FK changes");+ assert!(diffs[0].changes.iter().any(|c| c.contains("ref table")), "ref table: {:?}", diffs[0].changes);+ assert!(diffs[0].changes.iter().any(|c| c.contains("ref column")), "ref column: {:?}", diffs[0].changes);+ }- for (data_type, default, expected) in cases {- let mut source = column("value", data_type, None);- source.column_default = Some(default.to_string());- assert!(column_def(&source, DatabaseType::Mysql).contains(expected), "{data_type}: {default}");+ // -- 60. With and without ignore_comments on prepare_schema_diff --+ #[test]+ fn prepare_schema_diff_comment_option_toggle() {+ fn run_test(ignore: bool, expect_diffs: bool) {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: Some("new_comment".into()),+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: Some("old_comment".into()),+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![TableSchemaDetail {+ name: "t".into(),+ columns: vec![column("c", "int", Some("col_new"))],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ target_details: vec![TableSchemaDetail {+ name: "t".into(),+ columns: vec![column("c", "int", Some("col_old"))],+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }],+ database_type: DatabaseType::Mysql,+ ignore_comments: ignore,+ ..Default::default()+ };+ let result = prepare_schema_diff(options);+ if expect_diffs {+ assert!(!result.diffs.is_empty(), "should have diffs when ignore={ignore}");+ } else {+ assert!(result.diffs.is_empty(), "should be empty when ignore={ignore}");+ }}+ run_test(true, false);+ run_test(false, true);}- #[test]- fn leaves_non_mysql_defaults_unchanged() {- let mut source = column("value", "varchar(50)", None);- source.column_default = Some("unquoted_metadata_value".to_string());+ // ═══════════════════════════════════════════════════════════════+ // Cross-dialect CREATE TABLE tests (all 11×11 pairs)+ // ═══════════════════════════════════════════════════════════════- assert!(column_def(&source, DatabaseType::Postgres).contains("DEFAULT unquoted_metadata_value"));- assert!(column_def(&source, DatabaseType::Doris).contains("DEFAULT unquoted_metadata_value"));+ fn _dialect_from_db(db: DatabaseType) -> DialectKind {+ DialectKind::from_database_type(db)}- #[test]- fn ignores_column_order_when_option_is_disabled() {- let diffs = diff_columns_with_options(- &[column("id", "int", None), column("name", "varchar(64)", None), column("status", "varchar(16)", None)],- &[column("status", "varchar(16)", None), column("id", "int", None), column("name", "varchar(64)", None)],- ColumnDiffOptions::default(),- );-- assert!(diffs.is_empty());+ fn all_kinds() -> Vec<DialectKind> {+ vec![+ DialectKind::Mysql,+ DialectKind::Postgres,+ DialectKind::Sqlite,+ DialectKind::SqlServer,+ DialectKind::Oracle,+ DialectKind::H2,+ DialectKind::ClickHouse,+ DialectKind::DuckDb,+ DialectKind::ManticoreSearch,+ DialectKind::Informix,+ DialectKind::Questdb,+ ]}- #[test]- fn detects_column_order_when_option_is_enabled() {- let diffs = diff_columns_with_options(- &[column("id", "int", None), column("name", "varchar(64)", None), column("status", "varchar(16)", None)],- &[column("status", "varchar(16)", None), column("id", "int", None), column("name", "varchar(64)", None)],- ColumnDiffOptions { compare_column_order: true, ..ColumnDiffOptions::default() },- );+ fn kind_to_db(kind: DialectKind) -> Option<DatabaseType> {+ match kind {+ DialectKind::Mysql => Some(DatabaseType::Mysql),+ DialectKind::Postgres => Some(DatabaseType::Postgres),+ DialectKind::Sqlite => Some(DatabaseType::Sqlite),+ DialectKind::SqlServer => Some(DatabaseType::SqlServer),+ DialectKind::Oracle => Some(DatabaseType::Oracle),+ DialectKind::H2 => Some(DatabaseType::H2),+ DialectKind::ClickHouse => Some(DatabaseType::ClickHouse),+ DialectKind::DuckDb => Some(DatabaseType::DuckDb),+ DialectKind::ManticoreSearch => Some(DatabaseType::ManticoreSearch),+ DialectKind::Informix => Some(DatabaseType::Informix),+ DialectKind::Questdb => Some(DatabaseType::Questdb),+ _ => None,+ }+ }- assert_eq!(diffs.len(), 3);- assert_eq!(diffs[0].changes, vec!["order: 2 → 1"]);+ fn col_pk(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo { is_primary_key: true, ..column(name, data_type, None) }}- #[test]- fn keeps_case_sensitive_column_names_distinct_by_default() {- let diffs = diff_columns_with_options(- &[column("FREEDATE", "datetime", None)],- &[column("freedate", "datetime", None)],- ColumnDiffOptions::default(),- );+ fn _make_added_table_detail(+ name: &str,+ columns: Vec<ColumnInfo>,+ indexes: Vec<IndexInfo>,+ fks: Vec<ForeignKeyInfo>,+ ddl: Option<&str>,+ ) -> TableSchemaDetail {+ TableSchemaDetail {+ name: name.to_string(),+ columns,+ indexes,+ foreign_keys: fks,+ triggers: vec![],+ ddl: ddl.map(|s| s.to_string()),+ }+ }- assert_eq!(diffs.len(), 2);- assert_eq!(diffs[0].diff_type, "added");- assert_eq!(diffs[1].diff_type, "removed");+ fn _prepare_create_table(+ columns: Vec<ColumnInfo>,+ indexes: Vec<IndexInfo>,+ fks: Vec<ForeignKeyInfo>,+ source_kind: DialectKind,+ target_kind: DialectKind,+ ddl: Option<&str>,+ ) -> String {+ let Some(db) = kind_to_db(target_kind) else { return String::new() };+ let _src_db = kind_to_db(source_kind).unwrap_or(DatabaseType::Mysql);+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![],+ source_details: vec![_make_added_table_detail("t", columns, indexes, fks, ddl)],+ target_details: vec![],+ source_functions: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type: db,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ detect_renames: false,+ detect_table_renames: false,+ rename_threshold: 0.5,+ enable_rollback: false,+ source_dialect: Some(source_kind),+ target_dialect: Some(target_kind),+ batch_patterns: vec![],+ compatibility_threshold: 0.5,+ source_permissions: vec![],+ target_permissions: vec![],+ shard_strategy: None,+ resource_constraint: None,+ field_mappings: vec![],+ };+ let result = prepare_schema_diff(options);+ result.sync_sql}- #[test]- fn matches_mysql_column_names_case_insensitively() {- let diffs = diff_columns_with_options(- &[column("FREEDATE", "datetime", None), column("DATETYPE", "char(6)", Some("holiday type"))],- &[column("freedate", "datetime", None), column("datetype", "char(6)", Some("holiday type"))],- ColumnDiffOptions { case_insensitive_names: true, ..ColumnDiffOptions::default() },- );+ fn check_identifiers(sql: &str, tgt: DialectKind) {+ match tgt {+ DialectKind::Mysql | DialectKind::ManticoreSearch => {+ assert!(sql.contains('`'), "{tgt:?} should use backticks");+ }+ DialectKind::Oracle => {+ assert!(!sql.contains('`'), "Oracle no backticks");+ assert!(!sql.contains('"'), "Oracle no double-quotes");+ }+ _ => {+ assert!(!sql.contains('`'), "{tgt:?} should NOT use backticks: {sql}");+ }+ }+ }- assert_eq!(diffs.len(), 2);- assert!(diffs.iter().all(|diff| diff.diff_type == "modified"));- assert_eq!(diffs[0].changes, vec!["name: freedate → FREEDATE"]);- assert_eq!(diffs[1].changes, vec!["name: datetype → DATETYPE"]);+ fn check_no_mysql_residue(sql: &str, tgt: DialectKind) {+ if !matches!(tgt, DialectKind::Mysql | DialectKind::ManticoreSearch) {+ assert!(!sql.contains("ENGINE="), "residual ENGINE= in {tgt:?}: {sql}");+ assert!(!sql.contains("CHARSET"), "residual CHARSET in {tgt:?}: {sql}");+ }+ }- let sql = generate_schema_sync_sql(- &[TableDiff {- diff_type: "modified".to_string(),- object_type: Some("table".to_string()),- name: "c_freedate".to_string(),- columns: Some(diffs),- indexes: None,- foreign_keys: None,- triggers: None,- ddl: None,- target_ddl: None,- source_table_comment: None,- target_table_comment: None,- sync_sql: None,- }],- &[],+ #[test]+ fn mysql_to_access_create_table_uses_access_types_and_counter() {+ let columns = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(ColumnInfo {+ name: "id".into(),+ data_type: "int(11)".into(),+ is_nullable: false,+ is_primary_key: true,+ extra: Some("auto_increment".into()),+ ..Default::default()+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "name2".into(),+ source: Some(ColumnInfo {+ name: "name2".into(),+ data_type: "varchar(120)".into(),+ is_nullable: false,+ ..Default::default()+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "del_flag".into(),+ source: Some(ColumnInfo {+ name: "del_flag".into(),+ data_type: "tinyint(2)".into(),+ is_nullable: false,+ ..Default::default()+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "create_at".into(),+ source: Some(ColumnInfo {+ name: "create_at".into(),+ data_type: "datetime".into(),+ is_nullable: true,+ ..Default::default()+ }),+ target: None,+ changes: vec![],+ },+ ];+ let indexes = vec![IndexDiff {+ diff_type: "added".into(),+ name: "idx_del_flag".into(),+ source: Some(IndexInfo {+ name: "idx_del_flag".into(),+ columns: vec!["del_flag".into()],+ is_unique: false,+ is_primary: false,+ index_type: None,+ filter: None,+ included_columns: None,+ comment: None,+ }),+ target: None,+ changes: vec![],+ }];+ let (sql, missing) = generate_create_table_sql(+ "tb_user",+ &columns,+ &indexes,&[],+ None,+ DatabaseType::Access,+ None,+ Some(DialectKind::Mysql),&[],&[],- DatabaseType::Mysql,- None,- false,);+ assert!(missing.is_empty(), "{missing:?}");+ assert!(sql.contains("COUNTER"), "Access PK should use COUNTER: {sql}");+ assert!(!sql.contains("IDENTITY"), "Access must not emit SQL Server IDENTITY: {sql}");+ assert!(!sql.contains("int(11)"), "MySQL display width must be stripped: {sql}");+ assert!(sql.contains("TEXT(120)") || sql.contains("TEXT (120)"), "varchar→TEXT(n): {sql}");+ assert!(+ sql.contains("BYTE") || sql.contains("\"del_flag\" BYTE") || sql.to_ascii_uppercase().contains("BYTE"),+ "tinyint→BYTE: {sql}"+ );+ assert!(sql.to_ascii_uppercase().contains("DATETIME"), "datetime stays DATETIME: {sql}");+ assert!(sql.contains("CREATE INDEX"), "index: {sql}");+ }++ fn check_auto_increment(sql: &str, tgt: DialectKind) {+ match tgt {+ DialectKind::Mysql | DialectKind::ManticoreSearch => {+ assert!(sql.contains("AUTO_INCREMENT"), "{tgt:?} should have AUTO_INCREMENT: {sql}");+ }+ DialectKind::Postgres => {+ assert!(sql.contains("SEQUENCE"), "{tgt:?} should use SEQUENCE: {sql}");+ }+ DialectKind::SqlServer => {+ assert!(sql.contains("IDENTITY"), "{tgt:?} should use IDENTITY: {sql}");+ }+ DialectKind::Oracle => {+ assert!(+ sql.contains("GENERATED BY DEFAULT AS IDENTITY"),+ "{tgt:?} should use GENERATED BY DEFAULT AS IDENTITY: {sql}"+ );+ }+ _ => {+ // Other dialects may or may not have auto-increment+ }+ }+ }++ fn check_type_conversion(sql: &str, src: DialectKind, tgt: DialectKind) {+ match (src, tgt) {+ (DialectKind::Mysql, DialectKind::Postgres) => {+ assert!(sql.contains("INTEGER"), "int→INTEGER in PG: {sql}");+ // Only check if source has these types (S2 has tinyint, datetime)+ if sql.contains("tinyint") || sql.contains("TINYINT") {+ assert!(sql.contains("SMALLINT"), "tinyint→SMALLINT in PG: {sql}");+ }+ if sql.contains("datetime") || sql.contains("DATETIME") {+ assert!(sql.contains("TIMESTAMP"), "datetime→TIMESTAMP in PG: {sql}");+ }+ }+ (DialectKind::Mysql, DialectKind::Sqlite) => {+ assert!(sql.contains("INTEGER"), "int→INTEGER in SQLite: {sql}");+ if sql.contains("datetime") || sql.contains("DATETIME") {+ assert!(sql.contains("TEXT"), "datetime→TEXT in SQLite: {sql}");+ }+ }+ (DialectKind::Postgres, DialectKind::Mysql) if sql.contains("text") || sql.contains("TEXT") => {}+ _ => {}+ }+ }++ fn check_table_sql_structure(sql: &str, tgt: DialectKind) {+ assert!(sql.contains("CREATE TABLE"), "{tgt:?} missing CREATE TABLE");+ match tgt {+ DialectKind::Mysql | DialectKind::ManticoreSearch => {+ assert!(sql.contains("PRIMARY KEY"), "{tgt:?} missing PK");+ }+ _ => {+ assert!(sql.contains("PRIMARY KEY"), "{tgt:?} missing PK: {sql}");+ }+ }+ }- assert!(sql.contains("CHANGE COLUMN `freedate` `FREEDATE` datetime NOT NULL"));- assert!(sql.contains("CHANGE COLUMN `datetype` `DATETYPE` char(6) NOT NULL COMMENT 'holiday type'"));- assert!(!sql.contains("ADD COLUMN"));- assert!(!sql.contains("DROP COLUMN"));+ // -- S1: simple table (id INT PK AUTO_INCREMENT, name VARCHAR) --+ fn s1_diffs() -> Vec<ColumnDiff> {+ vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "int")),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "name".into(),+ source: Some(ColumnInfo {+ name: "name".into(),+ data_type: "varchar(100)".into(),+ is_nullable: false,+ ..column("name", "varchar(100)", None)+ }),+ target: None,+ changes: vec![],+ },+ ]+ }++ fn s1_table_diff(src_kind: DialectKind, tgt_kind: DialectKind) -> TableDiff {+ let Some(_db) = kind_to_db(tgt_kind) else { panic!("no db for {tgt_kind:?}") };+ let is_mysql_tgt = matches!(tgt_kind, DialectKind::Mysql | DialectKind::ManticoreSearch);+ let ddl = if is_mysql_tgt {+ Some("CREATE TABLE `t` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB".into())+ } else if src_kind == tgt_kind {+ Some(+ "CREATE TABLE \"t\" (\"id\" INTEGER NOT NULL, \"name\" varchar(100) NOT NULL, PRIMARY KEY (\"id\"));"+ .into(),+ )+ } else {+ None+ };+ TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(s1_diffs()),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }}#[test]- fn detects_modified_indexes_not_only_added_or_removed_indexes() {- let diffs = diff_indexes(- &[index(IndexInfo {- name: "idx_orders_status".to_string(),- columns: vec!["status".to_string(), "created_at".to_string()],- is_unique: false,- is_primary: false,- filter: None,- index_type: None,- included_columns: None,- comment: None,- })],- &[index(IndexInfo {- name: "idx_orders_status".to_string(),- columns: vec!["status".to_string()],- is_unique: true,+ fn cross_dialect_s1_all_pairs_simple_table() {+ let kinds = all_kinds();+ for src in &kinds {+ for tgt in &kinds {+ let Some(db) = kind_to_db(*tgt) else { continue };+ let src_dialect = if src == tgt { None } else { Some(*src) };+ let td = s1_table_diff(*src, *tgt);+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, src_dialect, &[]);+ check_table_sql_structure(&sql, *tgt);+ check_identifiers(&sql, *tgt);+ check_no_mysql_residue(&sql, *tgt);+ check_auto_increment(&sql, *tgt);+ check_type_conversion(&sql, *src, *tgt);+ }+ }+ }++ // -- S2: full table (multiple types, index) --+ fn s2_diffs() -> (Vec<ColumnDiff>, Vec<IndexDiff>) {+ let cols = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "int")),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "title".into(),+ source: Some(ColumnInfo {+ name: "title".into(),+ data_type: "varchar(200)".into(),+ is_nullable: false,+ ..column("title", "varchar(200)", None)+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "body".into(),+ source: Some(ColumnInfo {+ name: "body".into(),+ data_type: "text".into(),+ is_nullable: true,+ ..column("body", "text", None)+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "views".into(),+ source: Some(ColumnInfo {+ name: "views".into(),+ data_type: "int".into(),+ is_nullable: true,+ column_default: Some("0".into()),+ ..column("views", "int", None)+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "is_pub".into(),+ source: Some(ColumnInfo {+ name: "is_pub".into(),+ data_type: "tinyint".into(),+ is_nullable: true,+ ..column("is_pub", "tinyint", None)+ }),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "created".into(),+ source: Some(ColumnInfo {+ name: "created".into(),+ data_type: "datetime".into(),+ is_nullable: true,+ ..column("created", "datetime", None)+ }),+ target: None,+ changes: vec![],+ },+ ];+ let idxs = vec![IndexDiff {+ diff_type: "added".into(),+ name: "idx_views".into(),+ source: Some(IndexInfo {+ name: "idx_views".into(),+ columns: vec!["views".into()],+ is_unique: false,is_primary: false,filter: None,index_type: None,included_columns: None,comment: None,- })],- );+ }),+ target: None,+ changes: vec![],+ }];+ (cols, idxs)+ }- assert_eq!(diffs.len(), 1);- assert_eq!(diffs[0].diff_type, "modified");- assert_eq!(diffs[0].changes, vec!["unique: YES → NO", "columns: status → status, created_at"]);+ #[test]+ fn cross_dialect_s2_full_table() {+ let kinds = all_kinds();+ for src in &kinds {+ for tgt in &kinds {+ let Some(db) = kind_to_db(*tgt) else { continue };+ let src_dialect = if src == tgt { None } else { Some(*src) };+ let (cols, idxs) = s2_diffs();+ let td = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(cols),+ indexes: Some(idxs),+ foreign_keys: None,+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, src_dialect, &[]);+ check_table_sql_structure(&sql, *tgt);+ check_identifiers(&sql, *tgt);+ check_no_mysql_residue(&sql, *tgt);+ check_auto_increment(&sql, *tgt);+ check_type_conversion(&sql, *src, *tgt);+ match tgt {+ DialectKind::Mysql | DialectKind::ManticoreSearch => {+ assert!(sql.contains("KEY "), "{tgt:?} index missing: {sql}");+ }+ _ => {+ assert!(sql.contains("CREATE INDEX"), "{tgt:?} CREATE INDEX missing: {sql}");+ }+ }+ }+ }+ }++ // -- S3: table with foreign keys --+ fn s3_diffs() -> (Vec<ColumnDiff>, Vec<ForeignKeyDiff>) {+ let cols = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "int")),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "user_id".into(),+ source: Some(ColumnInfo {+ name: "user_id".into(),+ data_type: "int".into(),+ is_nullable: false,+ ..column("user_id", "int", None)+ }),+ target: None,+ changes: vec![],+ },+ ];+ let fks = vec![ForeignKeyDiff {+ diff_type: "added".into(),+ name: "fk_user".into(),+ source: Some(ForeignKeyInfo {+ name: "fk_user".into(),+ column: "user_id".into(),+ ref_schema: None,+ ref_table: "users".into(),+ ref_column: "id".into(),+ on_update: None,+ on_delete: Some("CASCADE".into()),+ }),+ target: None,+ changes: vec![],+ }];+ (cols, fks)}#[test]- fn detects_mysql_functional_index_changes_and_preserves_expression_ddl() {- let functional_key_part = "((case when (`STATUS` = _utf8mb4'online') then _utf8mb4'online' else NULL end))";- let source_index = index(IndexInfo {- name: "test_UNIQUE".to_string(),- columns: vec!["attr".to_string(), "attr2".to_string(), functional_key_part.to_string()],- is_unique: true,- is_primary: false,- filter: None,- index_type: None,- included_columns: None,- comment: None,- });- let target_index = index(IndexInfo {- name: "test_UNIQUE".to_string(),- columns: vec!["attr".to_string(), "attr2".to_string()],- is_unique: true,- is_primary: false,- filter: None,- index_type: None,- included_columns: None,- comment: None,- });+ fn cross_dialect_s3_foreign_key_table() {+ let kinds = all_kinds();+ for src in &kinds {+ for tgt in &kinds {+ let Some(db) = kind_to_db(*tgt) else { continue };+ let src_dialect = if src == tgt { None } else { Some(*src) };+ let (cols, fks) = s3_diffs();+ let td = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(cols),+ indexes: None,+ foreign_keys: Some(fks),+ triggers: None,+ ddl: None,+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, src_dialect, &[]);+ check_table_sql_structure(&sql, *tgt);+ check_identifiers(&sql, *tgt);+ check_no_mysql_residue(&sql, *tgt);+ assert!(sql.contains("FOREIGN KEY"), "{tgt:?} FK constraint missing: {sql}");+ assert!(sql.contains("REFERENCES"), "{tgt:?} REFERENCES missing: {sql}");+ }+ }+ }- let diffs = diff_indexes(std::slice::from_ref(&source_index), &[target_index]);- assert_eq!(diffs.len(), 1);- assert_eq!(diffs[0].diff_type, "modified");- assert_eq!(diffs[0].changes, vec![format!("columns: attr, attr2 → attr, attr2, {functional_key_part}")]);+ // -- source_dialect=None: verify original DDL preservation --+ fn _prepare_create_table_no_dialect(+ columns: Vec<ColumnInfo>,+ indexes: Vec<IndexInfo>,+ target_kind: DialectKind,+ ddl: Option<&str>,+ ) -> String {+ let Some(db) = kind_to_db(target_kind) else { return String::new() };+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".into(),+ table_type: "BASE TABLE".into(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![],+ source_details: vec![_make_added_table_detail("t", columns, indexes, vec![], ddl)],+ target_details: vec![],+ database_type: db,+ ..Default::default()+ };+ let result = prepare_schema_diff(options);+ result.sync_sql+ }- let sql = generate_schema_sync_sql(- &[TableDiff {- diff_type: "modified".to_string(),- object_type: Some("table".to_string()),- name: "test".to_string(),- columns: None,- indexes: Some(diffs),+ #[test]+ fn cross_dialect_none_source_dialect_original_ddl() {+ let kinds = all_kinds();+ for tgt in &kinds {+ let Some(db) = kind_to_db(*tgt) else { continue };+ let is_mysql_tgt = matches!(tgt, DialectKind::Mysql | DialectKind::ManticoreSearch);+ let ddl_str = "CREATE TABLE `t` (`id` int NOT NULL AUTO_INCREMENT, `name` varchar(100) NOT NULL, PRIMARY KEY (`id`)) ENGINE=InnoDB";+ let td = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(s1_diffs()),+ indexes: None,foreign_keys: None,triggers: None,- ddl: None,+ ddl: Some(ddl_str.into()),target_ddl: None,source_table_comment: None,target_table_comment: None,sync_sql: None,- }],- &[],- &[],- &[],- &[],- DatabaseType::Mysql,- Some("dbx_issue_4114"),- false,- );-- assert!(sql.contains("DROP INDEX `test_UNIQUE` ON `dbx_issue_4114`.`test`;"));- assert!(sql.contains(&format!(- "CREATE UNIQUE INDEX `test_UNIQUE` ON `dbx_issue_4114`.`test` (`attr`, `attr2`, {functional_key_part});"- )));- assert!(!sql.contains("`((case"));- }-- #[test]- fn detects_foreign_key_additions_removals_and_target_changes() {- let diffs = diff_foreign_keys(- &[- foreign_key(ForeignKeyInfo {- name: "orders_user_id_fk".to_string(),- column: String::new(),- ref_schema: None,- ref_table: String::new(),- ref_column: String::new(),- on_update: None,- on_delete: None,- }),- foreign_key(ForeignKeyInfo {- name: "orders_account_id_fk".to_string(),- column: "account_id".to_string(),- ref_schema: None,- ref_table: "accounts".to_string(),- ref_column: String::new(),- on_update: None,- on_delete: None,- }),- ],- &[- foreign_key(ForeignKeyInfo {- name: "orders_user_id_fk".to_string(),- column: String::new(),- ref_schema: None,- ref_table: "members".to_string(),- ref_column: String::new(),- on_update: None,- on_delete: None,- }),- foreign_key(ForeignKeyInfo {- name: "orders_region_id_fk".to_string(),- column: "region_id".to_string(),- ref_schema: None,- ref_table: "regions".to_string(),- ref_column: String::new(),- on_update: None,- on_delete: None,- }),- ],- );-- let summary: Vec<_> = diffs.iter().map(|diff| (diff.diff_type.as_str(), diff.name.as_str())).collect();- assert_eq!(- summary,- vec![- ("modified", "orders_user_id_fk"),- ("added", "orders_account_id_fk"),- ("removed", "orders_region_id_fk"),- ]- );+ };+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, None, &[]);+ check_table_sql_structure(&sql, *tgt);+ if is_mysql_tgt {+ assert!(sql.contains("ENGINE=InnoDB"), "original DDL preserved for {tgt:?}");+ } else {+ assert!(!sql.contains("ENGINE="), "ENGINE stripped for {tgt:?}: {sql}");+ }+ }}+ // -- Reverse cross-dialect: non-MySQL source → MySQL target --#[test]- fn generates_sync_sql_for_index_and_foreign_key_changes() {- let diffs = vec![TableDiff {- diff_type: "modified".to_string(),- object_type: None,- name: "orders".to_string(),- columns: None,- indexes: Some(vec![IndexDiff {- diff_type: "modified".to_string(),- name: "idx_orders_status".to_string(),- source: Some(index(IndexInfo {- name: "idx_orders_status".to_string(),- columns: vec!["status".to_string(), "created_at".to_string()],- is_unique: true,- is_primary: false,- filter: None,- index_type: None,- included_columns: None,- comment: None,- })),+ fn cross_dialect_postgres_source_to_mysql_target() {+ let src = DialectKind::Postgres;+ let tgt = DialectKind::Mysql;+ let Some(db) = kind_to_db(tgt) else { return };+ let cols = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "integer")),target: None,- changes: Vec::new(),- }]),- foreign_keys: Some(vec![ForeignKeyDiff {- diff_type: "modified".to_string(),- name: "orders_user_id_fk".to_string(),- source: Some(foreign_key(ForeignKeyInfo {- name: "orders_user_id_fk".to_string(),- column: String::new(),- ref_schema: None,- ref_table: "users".to_string(),- ref_column: String::new(),- on_update: None,- on_delete: None,- })),+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "label".into(),+ source: Some(ColumnInfo {+ name: "label".into(),+ data_type: "text".into(),+ is_nullable: false,+ ..column("label", "text", None)+ }),target: None,- changes: Vec::new(),- }]),+ changes: vec![],+ },+ ];+ let td = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(cols),+ indexes: None,+ foreign_keys: None,triggers: None,ddl: None,target_ddl: None,source_table_comment: None,target_table_comment: None,sync_sql: None,- }];-- assert_eq!(- generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, None, false),- [- "ALTER TABLE \"orders\" DROP CONSTRAINT \"orders_user_id_fk\";",- "DROP INDEX IF EXISTS \"idx_orders_status\";",- "CREATE UNIQUE INDEX \"idx_orders_status\" ON \"orders\" (\"status\", \"created_at\");",- "ALTER TABLE \"orders\" ADD CONSTRAINT \"orders_user_id_fk\" FOREIGN KEY (\"user_id\") REFERENCES \"users\" (\"id\");",- ]- .join("\n")- );+ };+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, Some(src), &[]);+ check_table_sql_structure(&sql, tgt);+ check_identifiers(&sql, tgt);+ check_type_conversion(&sql, src, tgt);+ assert!(sql.contains("AUTO_INCREMENT"), "MySQL auto_increment: {sql}");+ assert!(sql.contains("LONGTEXT"), "text→LONGTEXT in MySQL: {sql}");}#[test]- fn mysql_column_comment_changes_generate_modify_column_sql() {- let diffs = vec![TableDiff {- diff_type: "modified".to_string(),- object_type: None,- name: "users".to_string(),- columns: Some(vec![ColumnDiff {- diff_type: "modified".to_string(),- name: "name".to_string(),- source: Some(column("name", "varchar(64)", Some("用户姓名"))),- target: Some(column("name", "varchar(64)", Some("Name"))),- changes: vec!["comment: Name → 用户姓名".to_string()],- }]),+ fn cross_dialect_sqlserver_source_to_postgres_target() {+ let src = DialectKind::SqlServer;+ let tgt = DialectKind::Postgres;+ let Some(db) = kind_to_db(tgt) else { return };+ let cols = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "int")),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "data".into(),+ source: Some(ColumnInfo {+ name: "data".into(),+ data_type: "nvarchar(255)".into(),+ is_nullable: true,+ ..column("data", "nvarchar(255)", None)+ }),+ target: None,+ changes: vec![],+ },+ ];+ let td = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(cols),indexes: None,foreign_keys: None,triggers: None,ddl: None,target_ddl: None,- source_table_comment: Some(Some("用户表".to_string())),- target_table_comment: Some(Some("Users".to_string())),- sync_sql: None,- }];-- assert_eq!(- generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, None, false),- [- "-- Alter table: users",- "ALTER TABLE `users`",- " MODIFY COLUMN `name` varchar(64) NOT NULL COMMENT '用户姓名';",- "",- "ALTER TABLE `users` COMMENT = '用户表';",- ]- .join("\n")- );- }-- #[test]- fn mysql_schema_sync_sql_qualifies_tables_with_target_database() {- let diffs = vec![TableDiff {- diff_type: "modified".to_string(),- object_type: None,- name: "notify_channel_config".to_string(),- columns: Some(vec![ColumnDiff {- diff_type: "modified".to_string(),- name: "config_json".to_string(),- source: Some(column("config_json", "json", Some("渠道配置"))),- target: Some(column("config_json", "json", Some("Config"))),- changes: vec!["comment: Config → 渠道配置".to_string()],- }]),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, Some(src), &[]);+ check_table_sql_structure(&sql, tgt);+ check_identifiers(&sql, tgt);+ // No mapping rules for SQL Server→PG → types pass through+ assert!(sql.contains("nvarchar(255)"), "passthrough nvarchar: {sql}");+ }++ #[test]+ fn cross_dialect_clickhouse_source_to_mysql_target() {+ let src = DialectKind::ClickHouse;+ let tgt = DialectKind::Mysql;+ let Some(db) = kind_to_db(tgt) else { return };+ let cols = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "Int32")),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "data".into(),+ source: Some(ColumnInfo {+ name: "data".into(),+ data_type: "String".into(),+ is_nullable: true,+ ..column("data", "String", None)+ }),+ target: None,+ changes: vec![],+ },+ ];+ let td = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(cols),indexes: None,foreign_keys: None,triggers: None,@@ -2007,216 +8222,284 @@ mod tests {source_table_comment: None,target_table_comment: None,sync_sql: None,- }];-- assert_eq!(- generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, Some("target_db"), false),- [- "-- Alter table: notify_channel_config",- "ALTER TABLE `target_db`.`notify_channel_config`",- " MODIFY COLUMN `config_json` json NOT NULL COMMENT '渠道配置';",- ]- .join("\n")- );+ };+ let sql = generate_schema_sync_sql(&[td], &[], &[], &[], &[], db, None, false, Some(src), &[]);+ check_table_sql_structure(&sql, tgt);+ check_identifiers(&sql, tgt);+ // No mapping rules → types pass through+ assert!(sql.contains("Int32"), "passthrough Int32: {sql}");+ assert!(sql.contains("String"), "passthrough String: {sql}");}#[test]- fn blank_target_schema_does_not_generate_empty_qualifier() {- let diffs = vec![TableDiff {- diff_type: "modified".to_string(),- object_type: None,- name: "notify_channel_config".to_string(),- columns: Some(vec![ColumnDiff {- diff_type: "modified".to_string(),- name: "config_json".to_string(),- source: Some(column("config_json", "json", Some("渠道配置"))),- target: Some(column("config_json", "json", Some("Config"))),- changes: vec!["comment: Config → 渠道配置".to_string()],- }]),+ fn mysql_to_postgres_direct_generate() {+ let diffs = vec![+ ColumnDiff {+ diff_type: "added".into(),+ name: "id".into(),+ source: Some(col_pk("id", "int")),+ target: None,+ changes: vec![],+ },+ ColumnDiff {+ diff_type: "added".into(),+ name: "name".into(),+ source: Some(ColumnInfo {+ name: "name".into(),+ data_type: "varchar(100)".into(),+ is_nullable: false,+ ..column("name", "varchar(100)", None)+ }),+ target: None,+ changes: vec![],+ },+ ];+ let table_diff = TableDiff {+ diff_type: "added".into(),+ object_type: Some("table".into()),+ name: "t".into(),+ columns: Some(diffs),indexes: None,foreign_keys: None,triggers: None,- ddl: None,+ ddl: Some("CREATE TABLE `t` (`id` int NOT NULL AUTO_INCREMENT, PRIMARY KEY (`id`)) ENGINE=InnoDB".into()),target_ddl: None,source_table_comment: None,target_table_comment: None,sync_sql: None,- }];+ };+ let sql = generate_schema_sync_sql(+ &[table_diff],+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Postgres,+ None,+ false,+ Some(DialectKind::Mysql),+ &[],+ );+ assert!(!sql.contains('`'), "PG SQL should not have backticks: {sql}");+ assert!(sql.contains("INTEGER"), "int→INTEGER: {sql}");+ assert!(!sql.contains("ENGINE="), "no MySQL ENGINE: {sql}");+ }- let sql = generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, Some(" "), false);+ // -- FieldMapping apply_with_params tests --- assert!(sql.contains("ALTER TABLE `notify_channel_config`"));- assert!(!sql.contains("``."));+ #[test]+ fn field_mapping_preserve_params() {+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "VARCHAR2".into(),+ param_strategy: ParamStrategy::Preserve,+ custom_params: None,+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(255)", DialectKind::Oracle);+ assert_eq!(result, Some("VARCHAR2(255)".to_string()));}#[test]- fn ignore_comments_skips_column_and_table_comment_diffs() {- let options = SchemaDiffPreparationOptions {- source_tables: vec![TableInfo {- name: "users".to_string(),- table_type: "BASE TABLE".to_string(),- comment: Some("用户表".to_string()),- parent_schema: None,- parent_name: None,- }],- target_tables: vec![TableInfo {- name: "users".to_string(),- table_type: "BASE TABLE".to_string(),- comment: Some("Users".to_string()),- parent_schema: None,- parent_name: None,- }],- source_details: vec![TableSchemaDetail {- name: "users".to_string(),- columns: vec![column("name", "varchar(64)", Some("用户姓名"))],- indexes: Vec::new(),- foreign_keys: Vec::new(),- triggers: Vec::new(),- ddl: None,- }],- target_details: vec![TableSchemaDetail {- name: "users".to_string(),- columns: vec![column("name", "varchar(64)", Some("Name"))],- indexes: Vec::new(),- foreign_keys: Vec::new(),- triggers: Vec::new(),- ddl: None,- }],- source_functions: Vec::new(),- target_functions: Vec::new(),- source_sequences: Vec::new(),- target_sequences: Vec::new(),- source_rules: Vec::new(),- target_rules: Vec::new(),- source_owners: Vec::new(),- target_owners: Vec::new(),- database_type: DatabaseType::Mysql,- target_schema: None,- ignore_comments: true,- cascade_delete: false,- compare_column_order: false,- };+ fn field_mapping_strip_params() {+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "TEXT".into(),+ param_strategy: ParamStrategy::Strip,+ custom_params: None,+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(255)", DialectKind::Oracle);+ assert_eq!(result, Some("TEXT".to_string()));+ }- let result = prepare_schema_diff(options);- assert!(result.diffs.is_empty());- assert!(result.sync_sql.is_empty());+ #[test]+ fn field_mapping_custom_params() {+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "VARCHAR2".into(),+ param_strategy: ParamStrategy::Custom,+ custom_params: Some("(500)".to_string()),+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(255)", DialectKind::Oracle);+ assert_eq!(result, Some("VARCHAR2(500)".to_string()));}#[test]- fn prepare_schema_diff_attaches_per_table_sync_sql() {- let options = SchemaDiffPreparationOptions {- source_tables: vec![TableInfo {- name: "users".to_string(),- table_type: "BASE TABLE".to_string(),- comment: None,- parent_schema: None,- parent_name: None,- }],- target_tables: vec![TableInfo {- name: "users".to_string(),- table_type: "BASE TABLE".to_string(),- comment: None,- parent_schema: None,- parent_name: None,- }],- source_details: vec![TableSchemaDetail {- name: "users".to_string(),- columns: vec![column("name", "varchar(128)", None)],- indexes: Vec::new(),- foreign_keys: Vec::new(),- triggers: Vec::new(),- ddl: Some("CREATE TABLE `users` (`name` varchar(128));".to_string()),- }],- target_details: vec![TableSchemaDetail {- name: "users".to_string(),- columns: vec![column("name", "varchar(64)", None)],- indexes: Vec::new(),- foreign_keys: Vec::new(),- triggers: Vec::new(),- ddl: Some("CREATE TABLE `users` (`name` varchar(64));".to_string()),- }],- source_functions: Vec::new(),- target_functions: Vec::new(),- source_sequences: Vec::new(),- target_sequences: Vec::new(),- source_rules: Vec::new(),- target_rules: Vec::new(),- source_owners: Vec::new(),- target_owners: Vec::new(),- database_type: DatabaseType::Mysql,- target_schema: None,- ignore_comments: false,- cascade_delete: false,- compare_column_order: false,- };+ fn field_mapping_custom_empty_params_falls_back() {+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "TEXT".into(),+ param_strategy: ParamStrategy::Custom,+ custom_params: Some("".to_string()),+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(255)", DialectKind::Oracle);+ assert_eq!(result, Some("TEXT".to_string()));+ }- let result = prepare_schema_diff(options);- let table_sync_sql = result.diffs[0].sync_sql.as_deref().unwrap_or_default();+ #[test]+ fn field_mapping_no_match_returns_none() {+ let mappings = vec![FieldMapping {+ source_type: "INT".into(),+ target_type: "INTEGER".into(),+ param_strategy: ParamStrategy::Preserve,+ custom_params: None,+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(255)", DialectKind::Oracle);+ assert_eq!(result, None);+ }- assert!(table_sync_sql.contains("ALTER TABLE `users`"));- assert!(!table_sync_sql.contains("CREATE TABLE"));+ #[test]+ fn field_mapping_preserve_with_yaml_char_type() {+ crate::sql_dialect::dialect_loader::register_core_dialects();+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "CHAR".into(),+ param_strategy: ParamStrategy::Preserve,+ custom_params: None,+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(200)", DialectKind::Oracle);+ assert_eq!(+ result,+ Some("CHAR(200)".to_string()),+ "Preserve should keep params for CHAR which has has_length in Oracle YAML"+ );}#[test]- fn qualifies_generated_schema_sync_sql_with_target_schema() {- let diffs = vec![TableDiff {- diff_type: "modified".to_string(),- object_type: None,- name: "orders".to_string(),- columns: Some(vec![ColumnDiff {- diff_type: "added".to_string(),- name: "status".to_string(),- source: Some(ColumnInfo {- name: "status".to_string(),- data_type: "text".to_string(),- is_nullable: true,- column_default: None,- is_primary_key: false,- extra: None,- comment: None,- numeric_precision: None,- numeric_scale: None,- character_maximum_length: None,- enum_values: None,- ..Default::default()- }),- target: None,- changes: Vec::new(),- }]),- indexes: Some(vec![IndexDiff {- diff_type: "added".to_string(),- name: "idx_orders_status".to_string(),- source: Some(index(IndexInfo {- name: "idx_orders_status".to_string(),- columns: vec!["status".to_string()],- is_unique: false,- is_primary: false,- filter: None,- index_type: None,- included_columns: None,- comment: None,- })),- target: None,- changes: Vec::new(),- }]),- foreign_keys: None,- triggers: None,- ddl: None,- target_ddl: None,- source_table_comment: None,- target_table_comment: None,- sync_sql: None,+ fn field_mapping_mysql_varchar_to_postgres_character_keeps_params() {+ crate::sql_dialect::dialect_loader::register_core_dialects();+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "character".into(),+ param_strategy: ParamStrategy::Preserve,+ custom_params: None,+ }];+ let result = FieldMapping::apply_with_params(&mappings, "varchar(120)", DialectKind::Postgres);+ assert_eq!(+ result,+ Some("character(120)".to_string()),+ "Preserve should keep (120) for PostgreSQL CHARACTER which has has_length in YAML"+ );+ }++ #[test]+ fn field_mapping_custom_params_without_parens_is_normalized() {+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "character".into(),+ param_strategy: ParamStrategy::Custom,+ custom_params: Some("100".to_string()),}];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(120)", DialectKind::Postgres);+ assert_eq!(+ result,+ Some("character(100)".to_string()),+ "Custom params without parentheses should be wrapped as (100)"+ );+ }+ #[test]+ fn field_mapping_custom_params_with_parens_preserved() {+ let mappings = vec![FieldMapping {+ source_type: "VARCHAR".into(),+ target_type: "character".into(),+ param_strategy: ParamStrategy::Custom,+ custom_params: Some("(100)".to_string()),+ }];+ let result = FieldMapping::apply_with_params(&mappings, "VARCHAR(120)", DialectKind::Postgres);assert_eq!(- generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, Some("sales"), false),- [- "-- Alter table: orders",- "ALTER TABLE \"sales\".\"orders\" ADD COLUMN \"status\" text;",- "",- "CREATE INDEX \"idx_orders_status\" ON \"sales\".\"orders\" (\"status\");",- ]- .join("\n")+ result,+ Some("character(100)".to_string()),+ "Custom params already wrapped in parentheses should be kept as-is"+ );+ }++ #[test]+ fn postgres_function_sequence_rule_owner_use_profile_templates() {+ let fn_diff = FunctionDiff {+ diff_type: "added".into(),+ name: "f1".into(),+ source: Some(FunctionInfo {+ name: "f1".into(),+ function_type: "FUNCTION".into(),+ data_type: "int".into(),+ definition: "RETURNS int LANGUAGE sql AS $$ SELECT 1 $$".into(),+ arguments: "".into(),+ }),+ target: None,+ changes: vec![],+ };+ let seq_diff = SequenceDiff {+ diff_type: "added".into(),+ name: "s1".into(),+ source: Some(SequenceInfo {+ name: "s1".into(),+ data_type: "bigint".into(),+ start_value: "1".into(),+ min_value: "1".into(),+ max_value: "100".into(),+ increment: "1".into(),+ cycle: false,+ last_value: None,+ }),+ target: None,+ changes: vec![],+ };+ let rule_diff = RuleDiff {+ diff_type: "removed".into(),+ name: "r1".into(),+ source: Some(RuleInfo {+ name: "r1".into(),+ table_name: "t1".into(),+ definition: "CREATE RULE r1 AS ON INSERT TO t1 DO NOTHING".into(),+ }),+ target: None,+ changes: vec![],+ };+ let owner_diff = OwnerDiff {+ diff_type: "modified".into(),+ object_name: "t1".into(),+ source: Some(OwnerInfo { object_name: "t1".into(), object_type: "TABLE".into(), owner: "app".into() }),+ target: Some(OwnerInfo { object_name: "t1".into(), object_type: "TABLE".into(), owner: "old".into() }),+ changes: vec![],+ };++ let sql = generate_schema_sync_sql(+ &[],+ &[fn_diff],+ &[seq_diff],+ &[rule_diff],+ &[owner_diff],+ DatabaseType::Postgres,+ Some("public"),+ true,+ None,+ &[],);+ assert!(sql.contains("CREATE OR REPLACE FUNCTION"), "{sql}");+ assert!(sql.contains("CREATE SEQUENCE"), "{sql}");+ assert!(sql.contains("NO CYCLE"), "{sql}");+ assert!(sql.contains("DROP RULE IF EXISTS r1 ON"), "{sql}");+ assert!(sql.contains("OWNER TO app"), "{sql}");+ assert!(sql.contains("CASCADE"), "{sql}");+ }++ #[test]+ fn mysql_skips_function_sequence_when_templates_absent() {+ let fn_diff = FunctionDiff {+ diff_type: "added".into(),+ name: "f1".into(),+ source: Some(FunctionInfo {+ name: "f1".into(),+ function_type: "FUNCTION".into(),+ data_type: "int".into(),+ definition: "RETURNS int RETURN 1".into(),+ arguments: "".into(),+ }),+ target: None,+ changes: vec![],+ };+ let sql = generate_schema_sync_sql(&[], &[fn_diff], &[], &[], &[], DatabaseType::Mysql, None, false, None, &[]);+ assert!(sql.contains("-- Skip function f1"), "{sql}");+ assert!(!sql.contains("CREATE FUNCTION"), "{sql}");}}diff --git a/crates/dbx-core/src/script_generator.rs b/crates/dbx-core/src/script_generator.rsnew file mode 100644index 0000000000..353ca56541--- /dev/null+++ b/crates/dbx-core/src/script_generator.rs@@ -0,0 +1,2295 @@+use std::collections::HashMap;++use minijinja::{context, Environment};+use serde::{Deserialize, Serialize};++use crate::correction::JointCorrectionPlan;+use crate::data_compare::DataCompareFromTablesPreparation;+use crate::dml_binding::BindingEngine;+use crate::models::connection::DatabaseType;+use crate::schema_diff::{+ generate_schema_sync_sql, ColumnCompatibilityWarning, RollbackGraph, SchemaDiffPreparation, TableDiff,+};+use crate::sql_dialect::descriptor::{+ DialectCapabilityDescriptor, DialectKind, CAP_CREATE_OR_REPLACE, CAP_IF_NOT_EXISTS,+};+use crate::state_persistence::StateBackend;+use crate::types::TableInfo;++// ============================================================================+// 9.2: Jinja2 Dialect-Aware Template Engine+// ============================================================================++const SCHEMA_SYNC_TEMPLATE: &str = r#"-- ============================================================+-- Database Schema Synchronization Script+-- Generated: {{ generated_at }}+-- Source Dialect: {{ source_dialect }}+-- Target Dialect: {{ target_dialect }}+-- Database Type: {{ db_type }}+{% if target_schema %}-- Target Schema: {{ target_schema }}{% endif %}+-- Strategy: {{ idempotent_strategy }}+-- ============================================================++{% if pre_checks %}{% for check in pre_checks %}+-- Pre-check: {{ check }}+{% endfor %}+{% endif %}++{{ header_comment | safe }}++{% if sync_sql %}+{{ sync_sql | safe }}+{% endif %}++{% if rollback_sql %}+-- ============================================================+-- Rollback Script+-- ============================================================+{{ rollback_sql | safe }}+{% endif %}++-- End of synchronization script+"#;++const JOINT_ORCHESTRATION_TEMPLATE: &str = r#"-- ============================================================+-- Joint Structure-Data Synchronization Script+-- Generated: {{ generated_at }}+-- Strategy: {{ strategy }}+-- Schema Steps: {{ schema_diff_count }}+-- Data Steps: {{ data_diff_count }}+-- Total Steps: {{ total_steps }}+-- ============================================================++{% if pre_checks %}{% for check in pre_checks %}+-- Pre-check: {{ check }}+{% endfor %}+{% endif %}++{% for step in steps %}+-- ------------------------------------------------------------------+-- Step {{ loop.index }}: {{ step.step_type }} [{{ step.risk_level }}]+-- {{ step.description }}+{% if step.table_name %}-- Table: {{ step.table_name }}{% endif %}+{% if step.depends_on %}-- Depends on: {{ step.depends_on }}{% endif %}+-- ------------------------------------------------------------------+{{ step.sql }}++{% if step.rollback_sql %}+-- Rollback:+{{ step.rollback_sql }}+{% endif %}++{% if include_checkpoints and step.step_type == "Checkpoint" %}+-- <<< CHECKPOINT: {{ step.description }} >>>+{% endif %}+{% endfor %}++-- End of joint synchronization script+"#;++const BATCH_TEMPLATE: &str = r#"-- ============================================================+-- Batch {{ batch_id }} / {{ total_batches }}+-- Description: {{ description }}+-- Estimated Rows: {{ estimated_rows }}+-- ============================================================++{% if pre_checks %}{% for check in pre_checks %}+-- Pre-check: {{ check }}+{% endfor %}+{% endif %}++{{ sql | safe }}++{% if rollback_sql %}+-- Rollback for batch {{ batch_id }}:+{{ rollback_sql | safe }}+{% endif %}++-- End of batch {{ batch_id }}+-- <<< CHECKPOINT: batch_{{ batch_id }}_complete >>>+"#;++pub struct ScriptTemplateEngine {+ env: Environment<'static>,+}++impl Default for ScriptTemplateEngine {+ fn default() -> Self {+ Self::new()+ }+}++impl ScriptTemplateEngine {+ pub fn new() -> Self {+ let mut env = Environment::new();+ env.add_template("schema_sync", SCHEMA_SYNC_TEMPLATE).expect("schema_sync template");+ env.add_template("joint_orchestration", JOINT_ORCHESTRATION_TEMPLATE).expect("joint_orchestration template");+ env.add_template("batch", BATCH_TEMPLATE).expect("batch template");+ Self { env }+ }++ pub fn from_dialect_yaml(dialect: &crate::sql_dialect::dialect_yaml::ScriptTemplatesYaml) -> Self {+ let mut engine = Self::new();+ if let Some(tmpl) = &dialect.schema_sync {+ let leaked: &'static str = Box::leak(tmpl.clone().into_boxed_str());+ engine.env.add_template("schema_sync", leaked).expect("schema_sync from yaml");+ }+ if let Some(tmpl) = &dialect.joint_orchestration {+ let leaked: &'static str = Box::leak(tmpl.clone().into_boxed_str());+ engine.env.add_template("joint_orchestration", leaked).expect("joint_orchestration from yaml");+ }+ if let Some(tmpl) = &dialect.batch {+ let leaked: &'static str = Box::leak(tmpl.clone().into_boxed_str());+ engine.env.add_template("batch", leaked).expect("batch from yaml");+ }+ engine+ }++ pub fn render_schema_sync(+ &self,+ sync_sql: &str,+ rollback_sql: Option<&str>,+ db_type: &str,+ source_dialect: &str,+ target_dialect: &str,+ idempotent_strategy: &str,+ target_schema: Option<&str>,+ header_comment: &str,+ pre_checks: &[String],+ ) -> Result<String, String> {+ let tmpl = self.env.get_template("schema_sync").map_err(|e| e.to_string())?;+ tmpl.render(context! {+ generated_at => chrono::Utc::now().to_rfc3339(),+ db_type,+ source_dialect,+ target_dialect,+ idempotent_strategy,+ target_schema,+ header_comment,+ sync_sql,+ rollback_sql => rollback_sql.unwrap_or(""),+ pre_checks,+ })+ .map_err(|e| e.to_string())+ }++ pub fn render_joint_script(+ &self,+ plan: &JointCorrectionPlan,+ include_checkpoints: bool,+ pre_checks: &[String],+ ) -> Result<String, String> {+ let tmpl = self.env.get_template("joint_orchestration").map_err(|e| e.to_string())?;+ let steps: Vec<HashMap<String, String>> = plan+ .steps+ .iter()+ .map(|s| {+ let mut m = HashMap::new();+ m.insert("step_type".to_string(), format!("{:?}", s.step_type));+ m.insert("risk_level".to_string(), format!("{:?}", s.risk_level));+ m.insert("description".to_string(), s.description.clone());+ m.insert("sql".to_string(), s.sql.clone());+ m.insert("rollback_sql".to_string(), s.rollback_sql.clone().unwrap_or_default());+ m.insert("table_name".to_string(), s.table_name.clone().unwrap_or_default());+ m.insert(+ "depends_on".to_string(),+ if s.depends_on.is_empty() {+ String::new()+ } else {+ s.depends_on.iter().map(|d| d.to_string()).collect::<Vec<_>>().join(", ")+ },+ );+ m+ })+ .collect();++ tmpl.render(context! {+ generated_at => chrono::Utc::now().to_rfc3339(),+ strategy => format!("{:?}", plan.strategy),+ schema_diff_count => plan.schema_diff_count,+ data_diff_count => plan.data_diff_count,+ total_steps => plan.steps.len(),+ steps,+ include_checkpoints,+ pre_checks,+ })+ .map_err(|e| e.to_string())+ }++ pub fn render_batch(+ &self,+ batch_id: usize,+ total_batches: usize,+ description: &str,+ sql: &str,+ rollback_sql: Option<&str>,+ estimated_rows: Option<u64>,+ pre_checks: &[String],+ ) -> Result<String, String> {+ let tmpl = self.env.get_template("batch").map_err(|e| e.to_string())?;+ tmpl.render(context! {+ batch_id,+ total_batches,+ description,+ estimated_rows => estimated_rows.unwrap_or(0),+ sql,+ rollback_sql => rollback_sql.unwrap_or(""),+ pre_checks,+ })+ .map_err(|e| e.to_string())+ }+}++// ============================================================================+// 9.3: Adaptive Idempotent Strategy+// ============================================================================++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum IdempotentStrategy {+ IfNotExists,+ CreateOrReplace,+ ConditionalCheck,+ None,+}++impl IdempotentStrategy {+ pub fn label(&self) -> &'static str {+ match self {+ Self::IfNotExists => "if_not_exists",+ Self::CreateOrReplace => "create_or_replace",+ Self::ConditionalCheck => "conditional_check",+ Self::None => "none",+ }+ }+}++fn dialect_supports(descriptor: Option<&DialectCapabilityDescriptor>, flag: u64) -> bool {+ descriptor.is_some_and(|d| d.flags & flag != 0)+}++pub fn select_strategy(+ _dialect_kind: Option<DialectKind>,+ descriptor: Option<&DialectCapabilityDescriptor>,+) -> IdempotentStrategy {+ if dialect_supports(descriptor, CAP_IF_NOT_EXISTS) {+ IdempotentStrategy::IfNotExists+ } else if dialect_supports(descriptor, CAP_CREATE_OR_REPLACE) {+ IdempotentStrategy::CreateOrReplace+ } else {+ IdempotentStrategy::ConditionalCheck+ }+}++fn strip_leading_comments(s: &str) -> &str {+ let mut pos = 0;+ for line in s.lines() {+ let t = line.trim();+ if t.is_empty() || t.starts_with("--") {+ pos += line.len() + 1; // +1 for newline+ } else {+ break;+ }+ }+ if pos >= s.len() {+ ""+ } else {+ s[pos..].trim_start()+ }+}++pub fn apply_idempotent_strategy(sql: &str, db_type: DatabaseType, strategy: IdempotentStrategy) -> String {+ if strategy == IdempotentStrategy::None || sql.trim().is_empty() {+ return sql.to_string();+ }++ let statements = split_sql_statements(sql);+ let mut result = Vec::new();++ for stmt in statements {+ let trimmed = stmt.trim();+ if trimmed.is_empty() {+ result.push(stmt);+ continue;+ }++ let stripped = strip_leading_comments(trimmed);+ if stripped.is_empty() {+ result.push(stmt);+ continue;+ }++ let leading_comment =+ if stripped.len() < trimmed.len() { &trimmed[..trimmed.len() - stripped.len()] } else { "" };++ let idempotent_body = match strategy {+ IdempotentStrategy::IfNotExists => wrap_if_not_exists(stripped, db_type),+ IdempotentStrategy::CreateOrReplace => wrap_create_or_replace(stripped, db_type),+ IdempotentStrategy::ConditionalCheck => wrap_conditional_check(stripped, db_type),+ IdempotentStrategy::None => trimmed.to_string(),+ };++ if leading_comment.is_empty() || idempotent_body == trimmed {+ result.push(idempotent_body);+ } else {+ result.push(format!("{leading_comment}{idempotent_body}"));+ }+ }++ result.join("\n")+}++fn split_sql_statements(sql: &str) -> Vec<String> {+ let mut statements = Vec::new();+ let mut current = String::new();+ let mut in_string = false;+ let mut string_char = ' ';+ let mut chars = sql.chars().peekable();++ while let Some(ch) = chars.next() {+ if in_string {+ current.push(ch);+ if ch == string_char {+ // SQL escaped quote: '' or "" stays inside the string.+ if chars.peek() == Some(&string_char) {+ current.push(chars.next().unwrap());+ } else {+ in_string = false;+ }+ }+ } else if ch == '\'' || ch == '"' {+ in_string = true;+ string_char = ch;+ current.push(ch);+ } else if ch == ';' {+ current.push(ch);+ statements.push(std::mem::take(&mut current));+ } else {+ current.push(ch);+ }+ }++ if !current.trim().is_empty() {+ statements.push(current);+ }++ statements+}++fn upper_first_word(s: &str) -> &str {+ let trimmed = s.trim_start();+ trimmed.split_whitespace().next().unwrap_or("")+}++fn wrap_if_not_exists(sql: &str, db_type: DatabaseType) -> String {+ use crate::sql_dialect::ddl_profile::profile_for;+ let profile = profile_for(db_type);+ let upper = sql.trim_start().to_uppercase();++ if upper.starts_with("CREATE TABLE") {+ if !profile.create_table_if_not_exists {+ return sql.to_string();+ }+ if upper.contains("IF NOT EXISTS") {+ return sql.to_string();+ }+ let idx = sql.find("CREATE TABLE").unwrap_or(0) + "CREATE TABLE".len();+ let (prefix, suffix) = sql.split_at(idx);+ format!("{prefix} IF NOT EXISTS{suffix}")+ } else if upper.starts_with("CREATE UNIQUE INDEX") || upper.starts_with("CREATE INDEX") {+ if !profile.create_index_if_not_exists {+ return sql.to_string();+ }+ if upper.contains("IF NOT EXISTS") {+ return sql.to_string();+ }+ // PostgreSQL/MySQL: CREATE [UNIQUE] INDEX IF NOT EXISTS name ON ...+ // (not CREATE IF NOT EXISTS INDEX ...)+ let keyword = if upper.starts_with("CREATE UNIQUE INDEX") { "CREATE UNIQUE INDEX" } else { "CREATE INDEX" };+ let idx = upper.find(keyword).unwrap_or(0) + keyword.len();+ let (prefix, suffix) = sql.split_at(idx);+ format!("{prefix} IF NOT EXISTS{suffix}")+ } else if upper.starts_with("DROP TABLE") {+ if upper.contains("IF EXISTS") {+ return sql.to_string();+ }+ let idx = sql.find("DROP TABLE").unwrap_or(0) + "DROP TABLE".len();+ let (prefix, suffix) = sql.split_at(idx);+ format!("{prefix} IF EXISTS{suffix}")+ } else if upper.starts_with("DROP INDEX") {+ if upper.contains("IF EXISTS") {+ return sql.to_string();+ }+ let idx = sql.find("DROP INDEX").unwrap_or(0) + "DROP INDEX".len();+ let (prefix, suffix) = sql.split_at(idx);+ format!("{prefix} IF EXISTS{suffix}")+ } else if upper.starts_with("DROP SEQUENCE") || upper.starts_with("DROP FUNCTION") {+ if upper.contains("IF EXISTS") {+ return sql.to_string();+ }+ let pos = if upper.starts_with("DROP SEQUENCE") {+ sql.find("DROP SEQUENCE").unwrap_or(0) + "DROP SEQUENCE".len()+ } else {+ sql.find("DROP FUNCTION").unwrap_or(0) + "DROP FUNCTION".len()+ };+ let (prefix, suffix) = sql.split_at(pos);+ format!("{prefix} IF EXISTS{suffix}")+ } else {+ sql.to_string()+ }+}++fn wrap_create_or_replace(sql: &str, db_type: DatabaseType) -> String {+ use crate::sql_dialect::ddl_profile::profile_for;+ let profile = profile_for(db_type);+ let upper = sql.trim_start().to_uppercase();++ if upper.starts_with("CREATE VIEW") {+ if upper.contains("OR REPLACE") {+ return sql.to_string();+ }+ let idx = sql.find("CREATE").unwrap_or(0) + "CREATE".len();+ let (prefix, suffix) = sql.split_at(idx);+ format!("{prefix} OR REPLACE{suffix}")+ } else if upper.starts_with("CREATE FUNCTION") || upper.starts_with("CREATE OR REPLACE FUNCTION") {+ if upper.contains("OR REPLACE") || upper.contains("IF NOT EXISTS") {+ return sql.to_string();+ }+ if profile.create_function_or_replace {+ let idx = sql.find("CREATE").unwrap_or(0) + "CREATE".len();+ let (prefix, suffix) = sql.split_at(idx);+ format!("{prefix} OR REPLACE{suffix}")+ } else {+ sql.to_string()+ }+ } else {+ sql.to_string()+ }+}++fn wrap_conditional_check(sql: &str, db_type: DatabaseType) -> String {+ use crate::sql_dialect::ddl_profile::profile_for;+ let profile = profile_for(db_type);+ let trimmed = sql.trim().trim_end_matches(';').trim_end();+ let upper = trimmed.to_uppercase();+ let first_word = upper_first_word(trimmed);++ if first_word == "CREATE" && upper.contains("TABLE") {+ // Prefer native IF NOT EXISTS — never append bare DDL after a SELECT CASE+ // (SELECT does not execute the string payload).+ if profile.create_table_if_not_exists {+ return wrap_if_not_exists(sql, db_type);+ }+ let table_identifier = extract_object_identifier(trimmed, "TABLE");+ let table_name = extract_table_name(trimmed, "TABLE");+ let ddl_literal = trimmed.replace('\'', "''");+ return match db_type {+ DatabaseType::Postgres+ | DatabaseType::Gaussdb+ | DatabaseType::OpenGauss+ | DatabaseType::Kingbase+ | DatabaseType::Highgo+ | DatabaseType::Vastbase+ | DatabaseType::Uxdb+ | DatabaseType::Redshift => {+ let (schema_name, table_name) = postgres_table_identity(table_identifier);+ let schema_predicate = schema_name.map_or_else(+ || "table_schema = current_schema()".to_string(),+ |schema| format!("table_schema = '{}'", schema.replace('\'', "''")),+ );+ let table_literal = table_name.replace('\'', "''");+ format!(+ "DO $dbx_idempotent$\nBEGIN\n IF NOT EXISTS (\n SELECT 1 FROM information_schema.tables\n WHERE {schema_predicate}\n AND table_name = '{table_literal}'\n ) THEN\n EXECUTE $dbx_ddl${trimmed}$dbx_ddl$;\n END IF;\nEND\n$dbx_idempotent$;"+ )+ }+ DatabaseType::Oracle+ | DatabaseType::Dameng+ | DatabaseType::OceanbaseOracle+ | DatabaseType::Yashandb+ | DatabaseType::Xugu+ | DatabaseType::Iris => {+ // ORA-00955: name is already used by an existing object+ format!(+ "BEGIN\n EXECUTE IMMEDIATE '{ddl_literal}';\nEXCEPTION\n WHEN OTHERS THEN\n IF SQLCODE != -955 THEN RAISE; END IF;\nEND;"+ )+ }+ _ => {+ format!("-- ConditionalCheck: run only if table {table_name} does not exist\n{trimmed};")+ }+ };+ }++ if first_word == "DROP" {+ let rebuilt = format!("{trimmed};");+ let guarded = wrap_if_not_exists(&rebuilt, db_type);+ if guarded != rebuilt && guarded.contains("IF EXISTS") {+ return guarded;+ }+ let obj_type = if upper.contains("TABLE") {+ "TABLE"+ } else if upper.contains("INDEX") {+ "INDEX"+ } else {+ ""+ };+ if !obj_type.is_empty() {+ let obj_name = extract_table_name(trimmed, obj_type);+ return format!("-- Conditional: only execute if {obj_type} {obj_name} exists\n{trimmed};");+ }+ }++ sql.to_string()+}++fn extract_object_identifier<'a>(sql: &'a str, keyword: &str) -> &'a str {+ let upper = sql.to_uppercase();+ let search = format!(" {} ", keyword);+ if let Some(pos) = upper.find(&search) {+ let mut after = sql[pos + search.len()..].trim();+ if after.to_ascii_uppercase().starts_with("IF NOT EXISTS ") {+ after = after["IF NOT EXISTS ".len()..].trim_start();+ }++ let mut quote = None;+ let mut end = after.len();+ for (index, ch) in after.char_indices() {+ match quote {+ Some('"') if ch == '"' => quote = None,+ Some('`') if ch == '`' => quote = None,+ Some(']') if ch == ']' => quote = None,+ Some(_) => {}+ None if ch == '"' || ch == '`' => quote = Some(ch),+ None if ch == '[' => quote = Some(']'),+ None if ch.is_whitespace() || ch == '(' || ch == ';' => {+ end = index;+ break;+ }+ None => {}+ }+ }+ after[..end].trim()+ } else {+ "unknown"+ }+}++fn extract_table_name<'a>(sql: &'a str, keyword: &str) -> &'a str {+ extract_object_identifier(sql, keyword).trim_matches('"').trim_matches('`').trim_matches('[').trim_matches(']')+}++fn postgres_table_identity(identifier: &str) -> (Option<String>, String) {+ let mut quote = false;+ let mut separator = None;+ let chars: Vec<(usize, char)> = identifier.char_indices().collect();+ let mut index = 0;+ while index < chars.len() {+ let (byte_index, ch) = chars[index];+ if ch == '"' {+ if quote && chars.get(index + 1).is_some_and(|(_, next)| *next == '"') {+ index += 1;+ } else {+ quote = !quote;+ }+ } else if ch == '.' && !quote {+ separator = Some(byte_index);+ }+ index += 1;+ }++ let (schema, table) = separator+ .map_or((None, identifier), |separator| (Some(&identifier[..separator]), &identifier[separator + 1..]));+ (schema.map(postgres_identifier_value), postgres_identifier_value(table))+}++fn postgres_identifier_value(identifier: &str) -> String {+ let identifier = identifier.trim();+ if identifier.starts_with('"') && identifier.ends_with('"') && identifier.len() >= 2 {+ identifier[1..identifier.len() - 1].replace("\"\"", "\"")+ } else {+ identifier.to_lowercase()+ }+}++// ============================================================================+// 9.4: Rollback Script Generator+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RollbackScriptOptions {+ pub db_type: DatabaseType,+ pub target_schema: Option<String>,+ pub cascade_delete: bool,+ pub include_header: bool,+ pub include_safety_checks: bool,+ pub idempotent_strategy: IdempotentStrategy,+}++impl Default for RollbackScriptOptions {+ fn default() -> Self {+ Self {+ db_type: DatabaseType::Postgres,+ target_schema: None,+ cascade_delete: false,+ include_header: true,+ include_safety_checks: true,+ idempotent_strategy: IdempotentStrategy::IfNotExists,+ }+ }+}++pub fn generate_rollback_script(rollback_graph: &RollbackGraph, options: &RollbackScriptOptions) -> String {+ let mut lines = Vec::new();++ if options.include_header {+ lines.push("-- ============================================================".to_string());+ lines.push("-- ROLLBACK SCRIPT".to_string());+ lines.push(format!("-- Generated: {}", chrono::Utc::now().to_rfc3339()));+ lines.push(format!("-- Database Type: {:?}", options.db_type));+ if let Some(schema) = &options.target_schema {+ lines.push(format!("-- Target Schema: {schema}"));+ }+ lines.push(format!("-- Forward Nodes: {}", rollback_graph.forward_nodes.len()));+ lines.push(format!("-- Rollback Nodes: {}", rollback_graph.rollback_nodes.len()));+ lines.push(format!("-- Consistent: {}", rollback_graph.is_consistent));+ if !rollback_graph.consistency_issues.is_empty() {+ lines.push("-- WARNING: Consistency issues detected:".to_string());+ for issue in &rollback_graph.consistency_issues {+ lines.push(format!("-- - {issue}"));+ }+ }+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ }++ if options.include_safety_checks {+ lines.push("-- SAFETY: Review this rollback script before execution.".to_string());+ lines.push("-- Ensure the state captured in the rollback graph matches current database state.".to_string());+ lines.push(String::new());+ }++ let rollback_diffs: Vec<TableDiff> = rollback_graph+ .rollback_nodes+ .iter()+ .map(|n| {+ let mut diff = n.table_diff.clone();+ diff.sync_sql = None;+ diff+ })+ .collect();++ let sync_sql = generate_schema_sync_sql(+ &rollback_diffs,+ &[],+ &[],+ &[],+ &[],+ options.db_type,+ options.target_schema.as_deref(),+ options.cascade_delete,+ None,+ &[],+ );++ let idempotent_sql = apply_idempotent_strategy(&sync_sql, options.db_type, options.idempotent_strategy);++ lines.push(idempotent_sql);+ lines.join("\n")+}++pub fn generate_reverse_diff_rollback(+ forward_sync_sql: &str,+ db_type: DatabaseType,+ schema_diff: &SchemaDiffPreparation,+ options: &RollbackScriptOptions,+) -> String {+ if let Some(graph) = &schema_diff.rollback_graph {+ return generate_rollback_script(graph, options);+ }++ let mut lines = Vec::new();+ if options.include_header {+ lines.push("-- ============================================================".to_string());+ lines.push("-- ROLLBACK SCRIPT (from reverse diff)".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ }++ let _ = forward_sync_sql;++ if let Some(rollback_sql) = &schema_diff.rollback_sync_sql {+ lines.push(apply_idempotent_strategy(rollback_sql, db_type, options.idempotent_strategy));+ } else {+ lines.push("-- No rollback SQL available. Rollback must be designed manually.".to_string());+ }++ lines.join("\n")+}++// ============================================================================+// 9.5: Structure-Data Joint Orchestration+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct JointScriptOptions {+ pub strategy: JointScriptStrategy,+ pub include_checkpoints: bool,+ pub include_rollback: bool,+ pub shadow_table_switch: bool,+ pub idempotent_strategy: IdempotentStrategy,+ pub db_type: DatabaseType,+ pub target_schema: Option<String>,+}++impl Default for JointScriptOptions {+ fn default() -> Self {+ Self {+ strategy: JointScriptStrategy::StructureFirst,+ include_checkpoints: true,+ include_rollback: true,+ shadow_table_switch: false,+ idempotent_strategy: IdempotentStrategy::IfNotExists,+ db_type: DatabaseType::Postgres,+ target_schema: None,+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum JointScriptStrategy {+ StructureFirst,+ DataFirst,+ Interleaved,+ ShadowTable,+}++pub fn generate_joint_script(+ schema_diff: &SchemaDiffPreparation,+ data_compare: Option<&DataCompareFromTablesPreparation>,+ options: &JointScriptOptions,+) -> String {+ let _engine = ScriptTemplateEngine::new();+ let mut lines: Vec<String> = Vec::new();++ let header = format!(+ "-- Joint Structure-Data Synchronization Script\n-- Strategy: {:?}\n-- Generated: {}\n-- Database: {:?}\n",+ options.strategy,+ chrono::Utc::now().to_rfc3339(),+ options.db_type+ );+ lines.push(header);++ if let Some(schema) = &options.target_schema {+ lines.push(format!("-- Target Schema: {schema}"));+ }+ lines.push(String::new());++ match options.strategy {+ JointScriptStrategy::StructureFirst => {+ lines.push("-- PHASE 1: Structure Changes".to_string());+ lines.push(String::new());+ let schema_sql =+ apply_idempotent_strategy(&schema_diff.sync_sql, options.db_type, options.idempotent_strategy);+ lines.push(schema_sql);+ lines.push(String::new());++ if let Some(dc) = data_compare {+ lines.push("-- PHASE 2: Data Synchronization".to_string());+ lines.push(String::new());+ if !dc.sync_sql.is_empty() {+ lines.push(dc.sync_sql.clone());+ }+ lines.push(String::new());+ }++ if options.include_checkpoints {+ lines.push("-- <<< CHECKPOINT: structure_data_sync_complete >>>".to_string());+ lines.push(String::new());+ }+ }+ JointScriptStrategy::DataFirst => {+ lines.push("-- PHASE 1: Data Synchronization".to_string());+ lines.push(String::new());+ if let Some(dc) = data_compare {+ if !dc.sync_sql.is_empty() {+ lines.push(dc.sync_sql.clone());+ }+ lines.push(String::new());+ }++ lines.push("-- PHASE 2: Structure Changes".to_string());+ lines.push(String::new());+ let schema_sql =+ apply_idempotent_strategy(&schema_diff.sync_sql, options.db_type, options.idempotent_strategy);+ lines.push(schema_sql);+ lines.push(String::new());+ }+ JointScriptStrategy::Interleaved => {+ let table_diffs: Vec<&TableDiff> =+ schema_diff.diffs.iter().filter(|d| d.diff_type != "unchanged" && d.diff_type != "none").collect();++ for (i, td) in table_diffs.iter().enumerate() {+ lines.push(format!("-- Step {}: Processing table {}", i + 1, td.name));+ lines.push(String::new());++ if let Some(dc) = data_compare {+ if dc.sync_sql.contains(&td.name) {+ lines.push(format!("-- Data sync for {}", td.name));+ lines.push(dc.sync_sql.clone());+ lines.push(String::new());+ }+ }++ if let Some(sync_sql) = &td.sync_sql {+ let idempotent = apply_idempotent_strategy(sync_sql, options.db_type, options.idempotent_strategy);+ lines.push(format!("-- Schema sync for {}", td.name));+ lines.push(idempotent);+ lines.push(String::new());+ }+ }+ }+ JointScriptStrategy::ShadowTable => {+ lines.push(generate_shadow_table_script(schema_diff, data_compare, options));+ }+ }++ if options.include_rollback {+ if let Some(rollback_sql) = &schema_diff.rollback_sync_sql {+ lines.push(String::new());+ lines.push("-- ============================================================".to_string());+ lines.push("-- ROLLBACK SECTION".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(apply_idempotent_strategy(rollback_sql, options.db_type, options.idempotent_strategy));+ }+ }++ lines.push(String::new());+ lines.push("-- End of joint synchronization script".to_string());++ lines.join("\n")+}++fn generate_shadow_table_script(+ schema_diff: &SchemaDiffPreparation,+ data_compare: Option<&DataCompareFromTablesPreparation>,+ options: &JointScriptOptions,+) -> String {+ let mut lines = Vec::new();++ lines.push("-- Shadow Table Switch Strategy".to_string());+ lines.push("-- This strategy creates shadow tables, syncs data, then swaps.".to_string());+ lines.push(String::new());++ for diff in &schema_diff.diffs {+ if diff.diff_type == "added" {+ lines.push(format!("-- New table {}: create directly (no shadow needed)", diff.name));+ if let Some(sync_sql) = &diff.sync_sql {+ lines.push(apply_idempotent_strategy(sync_sql, options.db_type, options.idempotent_strategy));+ lines.push(String::new());+ }+ } else if diff.diff_type == "modified" {+ let shadow_name = format!("_shadow_{}", diff.name);+ lines.push(format!("-- Shadow table strategy for: {}", diff.name));+ lines.push(String::new());++ lines.push(format!("-- Step 1: Create shadow table {}", shadow_name));+ if let Some(ddl) = &diff.ddl {+ let shadow_ddl = ddl.replace(&diff.name, &shadow_name);+ lines.push(format!("{shadow_ddl};"));+ lines.push(String::new());+ }++ lines.push("-- Step 2: Copy data to shadow table".to_string());+ lines.push(format!("INSERT INTO {shadow_name} SELECT * FROM {};", diff.name));+ lines.push(String::new());++ if let Some(dc) = data_compare {+ if dc.sync_sql.contains(&diff.name) {+ lines.push("-- Step 2b: Apply data sync on shadow table".to_string());+ lines.push(dc.sync_sql.clone());+ lines.push(String::new());+ }+ }++ lines.push("-- Step 3: Begin transaction and swap tables".to_string());+ lines.push("BEGIN;".to_string());+ lines.push(format!("ALTER TABLE {} RENAME TO _old_{};", diff.name, diff.name));+ lines.push(format!("ALTER TABLE {shadow_name} RENAME TO {};", diff.name));++ if options.include_rollback {+ lines.push("-- Rollback point: rename _old_ back if needed".to_string());+ }++ lines.push("COMMIT;".to_string());+ lines.push(String::new());++ lines.push("-- Step 4: Drop old table (after verification)".to_string());+ lines.push(format!("DROP TABLE IF EXISTS _old_{};", diff.name));+ lines.push(String::new());+ }+ }++ lines.join("\n")+}++// ============================================================================+// 9.6: Checkpoint Resume & Large Table Batching+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BatchConfig {+ pub max_statements_per_batch: usize,+ pub max_estimated_rows_per_batch: u64,+ pub enable_checkpoints: bool,+ pub checkpoint_key_prefix: String,+}++impl Default for BatchConfig {+ fn default() -> Self {+ Self {+ max_statements_per_batch: 100,+ max_estimated_rows_per_batch: 1_000_000,+ enable_checkpoints: true,+ checkpoint_key_prefix: "batch_sync".to_string(),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BatchInfo {+ pub batch_id: usize,+ pub description: String,+ pub sql: String,+ pub rollback_sql: Option<String>,+ pub estimated_rows: Option<u64>,+ pub table_names: Vec<String>,+ pub checkpoint_key: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct BatchState {+ pub batch_id: usize,+ pub total_batches: usize,+ pub completed_batches: Vec<usize>,+ pub current_batch: Option<usize>,+ pub status: String,+ pub started_at: String,+ pub updated_at: String,+}++impl BatchState {+ pub fn new(total_batches: usize) -> Self {+ let now = chrono::Utc::now().to_rfc3339();+ Self {+ batch_id: 0,+ total_batches,+ completed_batches: Vec::new(),+ current_batch: None,+ status: "created".to_string(),+ started_at: now.clone(),+ updated_at: now,+ }+ }++ pub fn checkpoint_key(config: &BatchConfig) -> String {+ format!("{}_state", config.checkpoint_key_prefix)+ }+}++pub struct BatchController {+ config: BatchConfig,+ engine: ScriptTemplateEngine,+}++impl BatchController {+ pub fn new(config: BatchConfig) -> Self {+ Self { config, engine: ScriptTemplateEngine::new() }+ }++ pub fn build_batches(+ &self,+ sync_sql: &str,+ rollback_sql: Option<&str>,+ table_infos: &[TableInfo],+ ) -> Vec<BatchInfo> {+ let statements = split_sql_statements(sync_sql);+ if statements.is_empty() {+ return Vec::new();+ }++ let total = statements.len();+ let batch_size = self.config.max_statements_per_batch.max(1);+ let num_batches = total.div_ceil(batch_size);+ let engine = &self.engine;++ let mut batches = Vec::new();++ for i in 0..num_batches {+ let start = i * batch_size;+ let end = ((i + 1) * batch_size).min(total);+ let batch_sql = statements[start..end].join("\n");++ let table_names: Vec<String> = statements[start..end]+ .iter()+ .filter_map(|s| {+ let upper = s.trim_start().to_uppercase();+ let tbl = if upper.contains("ALTER TABLE") {+ extract_from_alter(s)+ } else if upper.contains("CREATE TABLE") || upper.contains("DROP TABLE") {+ Some(extract_table_name(s, "TABLE").to_string())+ } else {+ None+ };+ tbl+ })+ .collect();++ let checkpoint_key = if self.config.enable_checkpoints {+ Some(format!("{}_batch_{}", self.config.checkpoint_key_prefix, i + 1))+ } else {+ None+ };++ let description = if num_batches > 1 {+ format!("Batch {}/{}: {} tables ({}-{})", i + 1, num_batches, table_names.len(), start + 1, end)+ } else {+ format!("Full sync: {} statements", total)+ };++ let rendered = engine+ .render_batch(i + 1, num_batches, &description, &batch_sql, None, None, &[])+ .unwrap_or_else(|_| batch_sql.clone());++ batches.push(BatchInfo {+ batch_id: i + 1,+ description,+ sql: rendered,+ rollback_sql: rollback_sql.map(|s| s.to_string()),+ estimated_rows: None,+ table_names,+ checkpoint_key,+ });+ }++ let _ = table_infos;+ batches+ }++ pub async fn save_checkpoint(&self, backend: &dyn StateBackend, state: &BatchState) -> Result<(), String> {+ let key = BatchState::checkpoint_key(&self.config);+ let data = serde_json::to_vec(state).map_err(|e| e.to_string())?;+ backend.save(&key, &data).await+ }++ pub async fn load_checkpoint(&self, backend: &dyn StateBackend) -> Result<Option<BatchState>, String> {+ let key = BatchState::checkpoint_key(&self.config);+ let data = backend.load(&key).await?;+ match data {+ Some(bytes) => {+ let state: BatchState = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;+ Ok(Some(state))+ }+ None => Ok(None),+ }+ }++ pub async fn delete_checkpoint(&self, backend: &dyn StateBackend) -> Result<(), String> {+ let key = BatchState::checkpoint_key(&self.config);+ backend.delete(&key).await+ }++ pub fn get_next_batch<'a>(&self, state: &BatchState, batches: &'a [BatchInfo]) -> Option<&'a BatchInfo> {+ let next_id = state.completed_batches.last().map(|id| id + 1).unwrap_or(1);+ batches.iter().find(|b| b.batch_id == next_id)+ }++ pub fn mark_batch_complete(&self, state: &mut BatchState, batch_id: usize) {+ if !state.completed_batches.contains(&batch_id) {+ state.completed_batches.push(batch_id);+ }+ state.current_batch = None;+ state.updated_at = chrono::Utc::now().to_rfc3339();+ if state.completed_batches.len() >= state.total_batches {+ state.status = "completed".to_string();+ }+ }+}++fn extract_from_alter(sql: &str) -> Option<String> {+ let upper = sql.to_uppercase();+ if let Some(pos) = upper.find("ALTER TABLE ") {+ let after = &sql[pos + "ALTER TABLE ".len()..].trim();+ let end = after.find(|c: char| c.is_whitespace() || c == '(' || c == ';').unwrap_or(after.len());+ let name = after[..end].trim().trim_matches('"').trim_matches('`').trim_matches('[').trim_matches(']');+ Some(name.to_string())+ } else {+ None+ }+}++// ============================================================================+// Convenience Functions+// ============================================================================++pub fn generate_enhanced_sync_sql(+ schema_diff: &SchemaDiffPreparation,+ db_type: DatabaseType,+ _target_schema: Option<&str>,+ strategy: IdempotentStrategy,+) -> String {+ let raw_sql = &schema_diff.sync_sql;+ if raw_sql.is_empty() {+ return String::new();+ }+ apply_idempotent_strategy(raw_sql, db_type, strategy)+}++pub fn generate_enhanced_rollback_sql(+ schema_diff: &SchemaDiffPreparation,+ db_type: DatabaseType,+ target_schema: Option<&str>,+ cascade_delete: bool,+ strategy: IdempotentStrategy,+) -> Option<String> {+ if let Some(graph) = &schema_diff.rollback_graph {+ let options = RollbackScriptOptions {+ db_type,+ target_schema: target_schema.map(|s| s.to_string()),+ cascade_delete,+ include_header: true,+ include_safety_checks: true,+ idempotent_strategy: strategy,+ };+ Some(generate_rollback_script(graph, &options))+ } else {+ schema_diff.rollback_sync_sql.as_ref().map(|sql| apply_idempotent_strategy(sql, db_type, strategy))+ }+}++pub fn generate_complete_script(+ schema_diff: &SchemaDiffPreparation,+ data_compare: Option<&DataCompareFromTablesPreparation>,+ db_type: DatabaseType,+ target_schema: Option<&str>,+ strategy: IdempotentStrategy,+) -> String {+ let mut lines = Vec::new();++ let dialect_kind = DialectKind::from_database_type(db_type);+ let dialect_name = dialect_kind.label();++ lines.push("-- ============================================================".to_string());+ lines.push("-- Complete Database Synchronization Script".to_string());+ lines.push(format!("-- Generated: {}", chrono::Utc::now().to_rfc3339()));+ lines.push(format!("-- Dialect: {dialect_name}"));+ lines.push(format!("-- Idempotent Strategy: {:?}", strategy));+ if let Some(schema) = target_schema {+ lines.push(format!("-- Target Schema: {schema}"));+ }+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());++ let sync_sql = apply_idempotent_strategy(&schema_diff.sync_sql, db_type, strategy);++ if !sync_sql.is_empty() {+ lines.push("-- ============================================================".to_string());+ lines.push("-- SECTION 1: Structure Changes".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ lines.push(sync_sql);+ lines.push(String::new());+ }++ let dml_clean = generate_all_dml_clean_sql(schema_diff, 0.8);+ if !dml_clean.is_empty() {+ lines.push("-- ============================================================".to_string());+ lines.push("-- SECTION 1b: DML Pre-Clean (lossy type mappings)".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ for stmt in &dml_clean {+ lines.push(format!("{stmt};"));+ }+ lines.push(String::new());+ }++ if let Some(perm_sql) = &schema_diff.permission_sync_sql {+ if !perm_sql.is_empty() {+ lines.push("-- ============================================================".to_string());+ lines.push("-- SECTION 2: Permission Changes".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ lines.push(apply_idempotent_strategy(perm_sql, db_type, strategy));+ lines.push(String::new());+ }+ }++ if let Some(dc) = data_compare {+ if !dc.sync_sql.is_empty() {+ lines.push("-- ============================================================".to_string());+ lines.push("-- SECTION 3: Data Synchronization".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ if let Some(level) = &dc.degradation_level {+ lines.push(format!("-- Data Quality: degradation_level={level}"));+ }+ if let Some(confidence) = dc.confidence_score {+ lines.push(format!("-- Confidence Score: {confidence:.2}"));+ }+ lines.push(String::new());+ lines.push(dc.sync_sql.clone());+ lines.push(String::new());+ }+ }++ if let Some(rollback_sql) = &schema_diff.rollback_sync_sql {+ lines.push("-- ============================================================".to_string());+ lines.push("-- SECTION 4: Rollback Script".to_string());+ lines.push("-- ============================================================".to_string());+ lines.push(String::new());+ lines.push(apply_idempotent_strategy(rollback_sql, db_type, strategy));+ lines.push(String::new());+ }++ lines.push("-- End of complete synchronization script".to_string());+ lines.join("\n")+}++// ============================================================================+// Phase 14.6: DML Clean — pre-transform SQL for lossy type mappings+// ============================================================================++/// Generate DML clean SQL from compatibility warnings.+/// Produces structure-data pre-clean statements (e.g. UPDATE ... SET ... = NULL).+pub fn generate_dml_clean_sql(+ warnings: &[ColumnCompatibilityWarning],+ table_name: &str,+ fidelity_threshold: f64,+) -> Vec<String> {+ let mut statements = Vec::new();+ let mut seen = std::collections::HashSet::new();++ for warning in warnings {+ let result = BindingEngine::bind(+ &warning.source_type,+ &warning.target_type,+ table_name,+ &warning.column_name,+ fidelity_threshold,+ );++ if let Some(sql) = &result.pre_transform_sql {+ if seen.insert(sql.clone()) {+ statements.push(sql.clone());+ }+ }+ }++ statements+}++/// Generate DML clean SQL for ALL tables in a SchemaDiffPreparation.+/// Iterates table diffs → modified columns → checks type compatibility → binds DML.+pub fn generate_all_dml_clean_sql(schema_diff: &SchemaDiffPreparation, fidelity_threshold: f64) -> Vec<String> {+ let mut all_statements = Vec::new();++ for diff in &schema_diff.diffs {+ let table_name = &diff.name;+ if let Some(columns) = &diff.columns {+ for col_diff in columns {+ if col_diff.diff_type == "modified" {+ if let (Some(src), Some(tgt)) = (&col_diff.source, &col_diff.target) {+ let result = BindingEngine::bind(+ &src.data_type,+ &tgt.data_type,+ table_name,+ &col_diff.name,+ fidelity_threshold,+ );+ if let Some(sql) = result.pre_transform_sql {+ all_statements.push(sql);+ }+ }+ }+ }+ }+ }++ all_statements.dedup();+ all_statements+}++// ============================================================================+// Phase 15.7: Lock Timeout Injection+// ============================================================================++/// Return dialect-appropriate SET lock_timeout statement.+pub fn lock_timeout_statement(db_type: DatabaseType) -> Option<&'static str> {+ crate::sql_dialect::ddl_profile::profile_for(db_type).lock_timeout_sql+}++// ============================================================================+// Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;+ use crate::correction::*;+ use crate::schema_diff::{ColumnDiff, DiffNode, RollbackGraph, SchemaDiffPreparation, TableDiff};+ use crate::sql_dialect::descriptor::{+ DialectCapabilityDescriptor, DialectKind, CAP_CREATE_OR_REPLACE, CAP_CREATE_TABLE, CAP_IF_NOT_EXISTS,+ };+ use crate::types::{ColumnInfo, TableInfo};++ fn make_table_info(name: &str) -> TableInfo {+ TableInfo {+ name: name.to_string(),+ table_type: "table".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }+ }++ fn make_column_info(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: data_type.to_string(),+ is_nullable: true,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }+ }++ // ========================================================================+ // 9.2: Template Engine Tests+ // ========================================================================++ #[test]+ fn template_engine_creation() {+ let engine = ScriptTemplateEngine::new();+ assert!(engine.env.get_template("schema_sync").is_ok());+ assert!(engine.env.get_template("joint_orchestration").is_ok());+ assert!(engine.env.get_template("batch").is_ok());+ }++ #[test]+ fn render_schema_sync_template() {+ let engine = ScriptTemplateEngine::new();+ let result = engine.render_schema_sync(+ "CREATE TABLE users (id INT);",+ Some("DROP TABLE IF EXISTS users;"),+ "mysql",+ "mysql",+ "mysql",+ "if_not_exists",+ None,+ "Schema sync for test",+ &[],+ );+ assert!(result.is_ok());+ let output = result.unwrap();+ assert!(output.contains("CREATE TABLE users (id INT);"));+ assert!(output.contains("DROP TABLE IF EXISTS users;"));+ assert!(output.contains("Schema sync for test"));+ }++ #[test]+ fn render_joint_script_template() {+ let engine = ScriptTemplateEngine::new();+ let plan = JointCorrectionPlan {+ strategy: CorrectionStrategy::StructureFirst,+ steps: vec![CorrectionStep {+ step_type: CorrectionStepType::SchemaCreate,+ table_name: Some("users".to_string()),+ sql: "CREATE TABLE users (id INT);".to_string(),+ rollback_sql: Some("DROP TABLE users;".to_string()),+ description: "Create users table".to_string(),+ risk_level: CorrectionRiskLevel::Safe,+ depends_on: vec![],+ }],+ schema_diff_count: 1,+ data_diff_count: 0,+ total_estimated_duration_secs: None,+ rollback_steps: vec![],+ };++ let result = engine.render_joint_script(&plan, true, &[]);+ assert!(result.is_ok());+ let output = result.unwrap();+ assert!(output.contains("StructureFirst"));+ assert!(output.contains("CREATE TABLE users"));+ assert!(output.contains("Step 1"));+ }++ #[test]+ fn render_batch_template() {+ let engine = ScriptTemplateEngine::new();+ let result = engine.render_batch(+ 1,+ 3,+ "Batch 1: Create tables",+ "CREATE TABLE a (id INT);",+ Some("DROP TABLE a;"),+ Some(100),+ &[],+ );+ assert!(result.is_ok());+ let output = result.unwrap();+ assert!(output.contains("Batch 1 / 3"));+ assert!(output.contains("CREATE TABLE a"));+ assert!(output.contains("DROP TABLE a"));+ assert!(output.contains("CHECKPOINT: batch_1_complete"));+ }++ // ========================================================================+ // 9.3: Idempotent Strategy Tests+ // ========================================================================++ #[test]+ fn select_strategy_if_not_exists() {+ let desc = DialectCapabilityDescriptor { flags: CAP_IF_NOT_EXISTS | CAP_CREATE_TABLE, ..Default::default() };+ let strategy = select_strategy(Some(DialectKind::Mysql), Some(&desc));+ assert_eq!(strategy, IdempotentStrategy::IfNotExists);+ }++ #[test]+ fn select_strategy_create_or_replace() {+ let desc =+ DialectCapabilityDescriptor { flags: CAP_CREATE_OR_REPLACE | CAP_CREATE_TABLE, ..Default::default() };+ let strategy = select_strategy(Some(DialectKind::Postgres), Some(&desc));+ assert_eq!(strategy, IdempotentStrategy::CreateOrReplace);+ }++ #[test]+ fn select_strategy_conditional() {+ let desc = DialectCapabilityDescriptor { flags: 0, ..Default::default() };+ let strategy = select_strategy(Some(DialectKind::Sqlite), Some(&desc));+ assert_eq!(strategy, IdempotentStrategy::ConditionalCheck);+ }++ #[test]+ fn idempotent_create_table_if_not_exists_mysql() {+ let sql = "CREATE TABLE users (id INT PRIMARY KEY);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert!(result.contains("CREATE TABLE IF NOT EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_create_table_if_not_exists_sqlite() {+ let sql = "CREATE TABLE users (id INT);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Sqlite, IdempotentStrategy::IfNotExists);+ assert!(result.contains("CREATE TABLE IF NOT EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_create_table_if_not_exists_clickhouse() {+ let sql = "CREATE TABLE events (ts DateTime);";+ let result = apply_idempotent_strategy(sql, DatabaseType::ClickHouse, IdempotentStrategy::IfNotExists);+ assert!(result.contains("CREATE TABLE IF NOT EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_drop_table_if_exists() {+ let sql = "DROP TABLE old_users;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert!(result.contains("DROP TABLE IF EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_drop_index_if_exists() {+ let sql = "DROP INDEX idx_email;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::IfNotExists);+ assert!(result.contains("DROP INDEX IF EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_create_index_if_not_exists_postgres() {+ let sql = "CREATE INDEX idx_name ON users (name);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::IfNotExists);+ assert!(result.contains("CREATE INDEX IF NOT EXISTS"), "Got: {result}");+ assert!(!result.contains("CREATE IF NOT EXISTS INDEX"), "wrong IF NOT EXISTS placement: {result}");+ }++ #[test]+ fn idempotent_create_unique_index_if_not_exists_postgres() {+ let sql = "CREATE UNIQUE INDEX idx_email ON users (email);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::IfNotExists);+ assert!(result.contains("CREATE UNIQUE INDEX IF NOT EXISTS"), "Got: {result}");+ assert!(!result.contains("CREATE IF NOT EXISTS"), "wrong IF NOT EXISTS placement: {result}");+ }++ #[test]+ fn idempotent_drop_sequence_if_exists() {+ let sql = "DROP SEQUENCE user_seq;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::IfNotExists);+ assert!(result.contains("DROP SEQUENCE IF EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_drop_function_if_exists() {+ let sql = "DROP FUNCTION calculate_total;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::IfNotExists);+ assert!(result.contains("DROP FUNCTION IF EXISTS"), "Got: {result}");+ }++ #[test]+ fn idempotent_skip_comments() {+ let sql = "-- This is a comment\nCREATE TABLE users (id INT);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert!(result.contains("-- This is a comment"));+ assert!(result.contains("IF NOT EXISTS"));+ }++ #[test]+ fn idempotent_no_wrap_alter_table() {+ let sql = "ALTER TABLE users ADD COLUMN age INT;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert!(!result.contains("IF NOT EXISTS"), "ALTER TABLE should not be wrapped: {result}");+ }++ #[test]+ fn idempotent_already_if_not_exists() {+ let sql = "CREATE TABLE IF NOT EXISTS users (id INT);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert_eq!(result.matches("IF NOT EXISTS").count(), 1, "Should not double-wrap: {result}");+ }++ #[test]+ fn idempotent_already_if_exists_drop() {+ let sql = "DROP TABLE IF EXISTS users;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert_eq!(result.matches("IF EXISTS").count(), 1, "Should not double-wrap: {result}");+ }++ #[test]+ fn idempotent_create_or_replace_view() {+ let sql = "CREATE VIEW user_view AS SELECT * FROM users;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::CreateOrReplace);+ assert!(result.contains("CREATE OR REPLACE"), "Got: {result}");+ }++ #[test]+ fn idempotent_create_or_replace_function() {+ let sql = "CREATE FUNCTION add(a INT, b INT) RETURNS INT AS $$ BEGIN RETURN a + b; END; $$ LANGUAGE plpgsql;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::CreateOrReplace);+ assert!(result.contains("CREATE OR REPLACE"), "Got: {result}");+ }++ #[test]+ fn idempotent_create_or_replace_not_for_table() {+ let sql = "CREATE TABLE users (id INT);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::CreateOrReplace);+ assert!(!result.contains("OR REPLACE"), "Tables should not get OR REPLACE: {result}");+ }++ #[test]+ fn idempotent_none_passthrough() {+ let sql = "CREATE TABLE users (id INT);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::None);+ assert_eq!(result, sql);+ }++ #[test]+ fn split_sql_respects_escaped_single_quotes() {+ let sql = "INSERT INTO t VALUES ('it''s ok'); CREATE TABLE u (id INT);";+ let parts = split_sql_statements(sql);+ assert_eq!(parts.len(), 2, "parts={parts:?}");+ assert!(parts[0].contains("it''s ok"), "first={:?}", parts[0]);+ assert!(parts[1].to_uppercase().contains("CREATE TABLE"), "second={:?}", parts[1]);+ }++ #[test]+ fn conditional_check_does_not_emit_unconditional_ddl_after_select() {+ let sql = "CREATE TABLE users (id INT);";+ let mysql = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::ConditionalCheck);+ assert!(mysql.contains("CREATE TABLE IF NOT EXISTS"), "mysql={mysql}");+ assert!(!mysql.contains("THEN 'EXECUTE:"), "must not use inert SELECT CASE: {mysql}");++ let pg = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::ConditionalCheck);+ assert!(pg.contains("DO $dbx_idempotent$") || pg.contains("IF NOT EXISTS"), "pg={pg}");+ assert!(!pg.contains("THEN 'EXECUTE:"), "must not use inert SELECT CASE: {pg}");+ // Body is inside EXECUTE dollar-quote, not as a bare follow-up statement.+ let after_do = pg.find("DO $dbx_idempotent$").map(|i| &pg[i..]).unwrap_or(&pg);+ assert!(!after_do.contains("\nCREATE TABLE users"), "bare CREATE must not follow check: {pg}");++ let oracle = apply_idempotent_strategy(sql, DatabaseType::Oracle, IdempotentStrategy::ConditionalCheck);+ assert!(oracle.contains("EXECUTE IMMEDIATE") || oracle.contains("BEGIN"), "oracle={oracle}");+ assert!(!oracle.contains("THEN 'EXECUTE:"), "must not use inert SELECT CASE: {oracle}");+ }++ #[test]+ fn conditional_check_postgres_matches_schema_and_table_separately() {+ let qualified = apply_idempotent_strategy(+ "CREATE TABLE sales.users (id INT);",+ DatabaseType::Postgres,+ IdempotentStrategy::ConditionalCheck,+ );+ assert!(qualified.contains("table_schema = 'sales'"), "qualified={qualified}");+ assert!(qualified.contains("table_name = 'users'"), "qualified={qualified}");+ assert!(!qualified.contains("table_name = 'sales.users'"), "qualified={qualified}");++ let unqualified = apply_idempotent_strategy(+ "CREATE TABLE users (id INT);",+ DatabaseType::Postgres,+ IdempotentStrategy::ConditionalCheck,+ );+ assert!(unqualified.contains("table_schema = current_schema()"), "unqualified={unqualified}");++ let quoted = apply_idempotent_strategy(+ "CREATE TABLE \"Sales\".\"Users\" (id INT);",+ DatabaseType::Postgres,+ IdempotentStrategy::ConditionalCheck,+ );+ assert!(quoted.contains("table_schema = 'Sales'"), "quoted={quoted}");+ assert!(quoted.contains("table_name = 'Users'"), "quoted={quoted}");+ }++ #[test]+ fn conditional_check_object_exists_path_uses_if_exists_when_available() {+ let sql = "DROP TABLE users;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::ConditionalCheck);+ assert!(result.contains("DROP TABLE IF EXISTS") || result.contains("Conditional:"), "Got: {result}");+ assert!(!result.contains("THEN 'EXECUTE:"), "{result}");+ }++ #[test]+ fn idempotent_empty_string() {+ let result = apply_idempotent_strategy("", DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert_eq!(result, "");+ }++ #[test]+ fn idempotent_conditional_check_drop() {+ let sql = "DROP TABLE old_data;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Sqlite, IdempotentStrategy::ConditionalCheck);+ // Prefer real IF EXISTS over an inert comment+DDL pair.+ assert!(result.contains("DROP TABLE IF EXISTS") || result.contains("Conditional"), "Got: {result}");+ assert!(result.contains("old_data"), "Got: {result}");+ assert!(!result.contains("THEN 'EXECUTE:"), "{result}");+ }++ #[test]+ fn idempotent_create_or_replace_already_has_or_replace() {+ let sql = "CREATE OR REPLACE VIEW v AS SELECT 1;";+ let result = apply_idempotent_strategy(sql, DatabaseType::Postgres, IdempotentStrategy::CreateOrReplace);+ assert_eq!(result.matches("OR REPLACE").count(), 1, "Should not double-wrap: {result}");+ }++ // ========================================================================+ // 9.4: Rollback Script Generator Tests+ // ========================================================================++ #[test]+ fn generate_rollback_script_from_graph() {+ let table_diff = TableDiff {+ diff_type: "added".to_string(),+ object_type: Some("table".to_string()),+ name: "users".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "added".to_string(),+ name: "id".to_string(),+ source: Some(make_column_info("id", "INT")),+ target: None,+ changes: vec![],+ }]),+ indexes: Some(vec![]),+ foreign_keys: Some(vec![]),+ triggers: Some(vec![]),+ ddl: Some("CREATE TABLE users (id INT);".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };++ let mut graph = RollbackGraph {+ forward_nodes: vec![DiffNode {+ table_diff: table_diff.clone(),+ direction: crate::schema_diff::DiffDirection::Forward,+ dependency_order: 0,+ rename_source: None,+ rename_target: None,+ rename_score: None,+ }],+ rollback_nodes: vec![DiffNode {+ table_diff: TableDiff {+ diff_type: "removed".to_string(),+ object_type: Some("table".to_string()),+ name: "users".to_string(),+ columns: Some(vec![ColumnDiff {+ diff_type: "removed".to_string(),+ name: "id".to_string(),+ source: Some(make_column_info("id", "INT")),+ target: None,+ changes: vec![],+ }]),+ indexes: Some(vec![]),+ foreign_keys: Some(vec![]),+ triggers: Some(vec![]),+ ddl: None,+ target_ddl: Some("CREATE TABLE users (id INT);".to_string()),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ },+ direction: crate::schema_diff::DiffDirection::Rollback,+ dependency_order: 0,+ rename_source: None,+ rename_target: None,+ rename_score: None,+ }],+ is_consistent: true,+ consistency_issues: vec![],+ };+ graph.is_consistent = true;++ let options = RollbackScriptOptions {+ db_type: DatabaseType::Postgres,+ target_schema: Some("public".to_string()),+ cascade_delete: false,+ include_header: true,+ include_safety_checks: true,+ idempotent_strategy: IdempotentStrategy::IfNotExists,+ };++ let script = generate_rollback_script(&graph, &options);+ assert!(script.contains("ROLLBACK SCRIPT"));+ assert!(script.contains("IF EXISTS"), "Got: {script}");+ }++ #[test]+ fn generate_rollback_script_with_inconsistency_warning() {+ let graph = RollbackGraph {+ forward_nodes: vec![],+ rollback_nodes: vec![],+ is_consistent: false,+ consistency_issues: vec!["Missing rollback for added table 'users'".to_string()],+ };++ let options = RollbackScriptOptions::default();+ let script = generate_rollback_script(&graph, &options);+ assert!(script.contains("WARNING"));+ assert!(script.contains("Missing rollback"));+ }++ #[test]+ fn generate_rollback_script_empty_graph() {+ let graph = RollbackGraph {+ forward_nodes: vec![],+ rollback_nodes: vec![],+ is_consistent: true,+ consistency_issues: vec![],+ };++ let options = RollbackScriptOptions::default();+ let script = generate_rollback_script(&graph, &options);+ assert!(script.contains("ROLLBACK SCRIPT"));+ }++ #[test]+ fn rollback_script_respects_no_header_option() {+ let graph = RollbackGraph {+ forward_nodes: vec![],+ rollback_nodes: vec![],+ is_consistent: true,+ consistency_issues: vec![],+ };++ let options =+ RollbackScriptOptions { include_header: false, include_safety_checks: false, ..Default::default() };++ let script = generate_rollback_script(&graph, &options);+ assert!(!script.contains("ROLLBACK SCRIPT"));+ }++ // ========================================================================+ // 9.5: Joint Script Tests+ // ========================================================================++ #[test]+ fn generate_joint_script_structure_first() {+ let schema_diff = make_simple_schema_diff();+ let options = JointScriptOptions {+ strategy: JointScriptStrategy::StructureFirst,+ include_checkpoints: true,+ include_rollback: true,+ db_type: DatabaseType::Mysql,+ ..Default::default()+ };++ let script = generate_joint_script(&schema_diff, None, &options);+ assert!(script.contains("StructureFirst"), "Got: {script}");+ assert!(script.contains("PHASE 1: Structure"));+ assert!(script.contains("CHECKPOINT"));+ }++ #[test]+ fn generate_joint_script_data_first() {+ let schema_diff = make_simple_schema_diff();+ let options = JointScriptOptions {+ strategy: JointScriptStrategy::DataFirst,+ db_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let script = generate_joint_script(&schema_diff, None, &options);+ assert!(script.contains("PHASE 1: Data"));+ assert!(script.contains("PHASE 2: Structure"));+ }++ #[test]+ fn generate_joint_script_shadow_table() {+ let schema_diff = SchemaDiffPreparation {+ diffs: vec![TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("table".to_string()),+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: Some(vec![]),+ foreign_keys: Some(vec![]),+ triggers: Some(vec![]),+ ddl: Some("CREATE TABLE users (id INT, name VARCHAR(100));".to_string()),+ target_ddl: Some("CREATE TABLE users (id INT);".to_string()),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }],+ sync_sql: "ALTER TABLE users ADD COLUMN name VARCHAR(100);".to_string(),+ ..Default::default()+ };++ let options = JointScriptOptions {+ strategy: JointScriptStrategy::ShadowTable,+ db_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let script = generate_joint_script(&schema_diff, None, &options);+ assert!(script.contains("Shadow Table"));+ assert!(script.contains("_shadow_users"), "Got: {script}");+ assert!(script.contains("RENAME TO"), "Got: {script}");+ }++ #[test]+ fn generate_joint_script_no_rollback() {+ let schema_diff = make_simple_schema_diff();+ let options = JointScriptOptions {+ strategy: JointScriptStrategy::StructureFirst,+ include_rollback: false,+ db_type: DatabaseType::Mysql,+ ..Default::default()+ };++ let script = generate_joint_script(&schema_diff, None, &options);+ assert!(!script.contains("ROLLBACK SECTION"));+ }++ // Helper: minimal SchemaDiffPreparation for tests+ fn make_simple_schema_diff() -> SchemaDiffPreparation {+ SchemaDiffPreparation {+ diffs: vec![TableDiff {+ diff_type: "added".to_string(),+ object_type: Some("table".to_string()),+ name: "test_table".to_string(),+ columns: Some(vec![]),+ indexes: Some(vec![]),+ foreign_keys: Some(vec![]),+ triggers: Some(vec![]),+ ddl: Some("CREATE TABLE test_table (id INT PRIMARY KEY);".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: Some("CREATE TABLE test_table (id INT PRIMARY KEY);".to_string()),+ }],+ sync_sql: "CREATE TABLE test_table (id INT PRIMARY KEY);".to_string(),+ rollback_sync_sql: Some("DROP TABLE IF EXISTS test_table;".to_string()),+ ..Default::default()+ }+ }++ impl Default for SchemaDiffPreparation {+ fn default() -> Self {+ Self {+ diffs: vec![],+ function_diffs: vec![],+ sequence_diffs: vec![],+ rule_diffs: vec![],+ owner_diffs: vec![],+ sync_sql: String::new(),+ rollback_sync_sql: None,+ rollback_completeness: crate::schema_diff::RollbackCompleteness::Complete,+ missing_rollback_objects: vec![],+ rename_candidates: vec![],+ rollback_graph: None,+ compatibility_warnings: vec![],+ permission_diffs: vec![],+ permission_sync_sql: None,+ dependency_graph: None,+ }+ }+ }++ // ========================================================================+ // 9.6: Batch Controller Tests+ // ========================================================================++ #[test]+ fn build_batches_single_batch() {+ let config = BatchConfig { max_statements_per_batch: 10, ..Default::default() };+ let controller = BatchController::new(config);+ let sql = "CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);";+ let table_infos = vec![make_table_info("a"), make_table_info("b")];++ let batches = controller.build_batches(sql, None, &table_infos);+ assert_eq!(batches.len(), 1, "Should have 1 batch for 2 statements with batch_size=10");+ assert_eq!(batches[0].batch_id, 1);+ assert!(batches[0].sql.contains("Batch 1"));+ }++ #[test]+ fn build_batches_multiple_batches() {+ let config = BatchConfig { max_statements_per_batch: 2, ..Default::default() };+ let controller = BatchController::new(config);++ let mut statements = String::new();+ for i in 0..5 {+ statements.push_str(&format!("CREATE TABLE t{i} (id INT);\n"));+ }++ let batches = controller.build_batches(&statements, None, &[]);+ assert_eq!(batches.len(), 3, "5 statements with batch_size=2 should give 3 batches");+ assert_eq!(batches[0].batch_id, 1);+ assert_eq!(batches[1].batch_id, 2);+ assert_eq!(batches[2].batch_id, 3);+ }++ #[test]+ fn build_batches_empty_sql() {+ let config = BatchConfig::default();+ let controller = BatchController::new(config);+ let batches = controller.build_batches("", None, &[]);+ assert!(batches.is_empty());+ }++ #[test]+ fn build_batches_with_table_names() {+ let config = BatchConfig { max_statements_per_batch: 1, ..Default::default() };+ let controller = BatchController::new(config);+ let sql =+ "CREATE TABLE users (id INT);\nALTER TABLE users ADD COLUMN name VARCHAR(100);\nDROP TABLE old_table;";++ let batches = controller.build_batches(sql, None, &[]);+ assert_eq!(batches.len(), 3);++ assert!(+ batches[0].table_names.contains(&"users".to_string()),+ "Batch 0 table_names: {:?}",+ batches[0].table_names+ );+ assert!(+ batches[1].table_names.contains(&"users".to_string()),+ "Batch 1 table_names: {:?}",+ batches[1].table_names+ );+ assert!(+ batches[2].table_names.contains(&"old_table".to_string()),+ "Batch 2 table_names: {:?}",+ batches[2].table_names+ );+ }++ #[test]+ fn batch_state_checkpoint_key() {+ let config = BatchConfig { checkpoint_key_prefix: "my_sync".to_string(), ..Default::default() };+ assert_eq!(BatchState::checkpoint_key(&config), "my_sync_state");+ }++ #[test]+ fn batch_state_new() {+ let state = BatchState::new(5);+ assert_eq!(state.total_batches, 5);+ assert_eq!(state.status, "created");+ assert!(state.completed_batches.is_empty());+ }++ #[test]+ fn batch_controller_get_next_batch() {+ let config = BatchConfig { max_statements_per_batch: 1, ..Default::default() };+ let controller = BatchController::new(config);++ let sql = "CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);\nCREATE TABLE c (id INT);";+ let batches = controller.build_batches(sql, None, &[]);++ let mut state = BatchState::new(batches.len());++ let next = controller.get_next_batch(&state, &batches);+ assert!(next.is_some());+ assert_eq!(next.unwrap().batch_id, 1);++ controller.mark_batch_complete(&mut state, 1);+ let next = controller.get_next_batch(&state, &batches);+ assert!(next.is_some());+ assert_eq!(next.unwrap().batch_id, 2);+ }++ #[test]+ fn batch_controller_mark_all_complete() {+ let config = BatchConfig::default();+ let controller = BatchController::new(config);+ let mut state = BatchState::new(2);++ assert_eq!(state.status, "created");+ controller.mark_batch_complete(&mut state, 1);+ controller.mark_batch_complete(&mut state, 2);+ assert_eq!(state.status, "completed");+ }++ #[test]+ fn batch_controller_no_duplicate_completion() {+ let config = BatchConfig::default();+ let controller = BatchController::new(config);+ let mut state = BatchState::new(2);++ controller.mark_batch_complete(&mut state, 1);+ controller.mark_batch_complete(&mut state, 1);+ assert_eq!(state.completed_batches.len(), 1, "Should not duplicate");+ }++ // ========================================================================+ // Enhanced Functions Tests+ // ========================================================================++ #[test]+ fn generate_enhanced_sync_sql_with_idempotent() {+ let schema_diff =+ SchemaDiffPreparation { sync_sql: "CREATE TABLE test (id INT);".to_string(), ..Default::default() };++ let result =+ generate_enhanced_sync_sql(&schema_diff, DatabaseType::Mysql, None, IdempotentStrategy::IfNotExists);+ assert!(result.contains("IF NOT EXISTS"), "Got: {result}");+ }++ #[test]+ fn generate_enhanced_rollback_from_graph() {+ let table_diff = TableDiff {+ diff_type: "added".to_string(),+ object_type: Some("table".to_string()),+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: Some(vec![]),+ foreign_keys: Some(vec![]),+ triggers: Some(vec![]),+ ddl: Some("CREATE TABLE users (id INT);".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };++ let graph = RollbackGraph {+ forward_nodes: vec![DiffNode {+ table_diff: table_diff.clone(),+ direction: crate::schema_diff::DiffDirection::Forward,+ dependency_order: 0,+ rename_source: None,+ rename_target: None,+ rename_score: None,+ }],+ rollback_nodes: vec![DiffNode {+ table_diff: TableDiff {+ diff_type: "removed".to_string(),+ object_type: Some("table".to_string()),+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: Some(vec![]),+ foreign_keys: Some(vec![]),+ triggers: Some(vec![]),+ ddl: None,+ target_ddl: Some("CREATE TABLE users (id INT);".to_string()),+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ },+ direction: crate::schema_diff::DiffDirection::Rollback,+ dependency_order: 0,+ rename_source: None,+ rename_target: None,+ rename_score: None,+ }],+ is_consistent: true,+ consistency_issues: vec![],+ };++ let schema_diff = SchemaDiffPreparation {+ sync_sql: "CREATE TABLE users (id INT);".to_string(),+ rollback_sync_sql: Some("DROP TABLE IF EXISTS users;".to_string()),+ rollback_graph: Some(graph),+ ..Default::default()+ };++ let result = generate_enhanced_rollback_sql(+ &schema_diff,+ DatabaseType::Postgres,+ Some("public"),+ false,+ IdempotentStrategy::IfNotExists,+ );+ assert!(result.is_some());+ assert!(result.unwrap().contains("ROLLBACK SCRIPT"));+ }++ #[test]+ fn generate_complete_script_with_all_sections() {+ let schema_diff = SchemaDiffPreparation {+ sync_sql: "CREATE TABLE test (id INT);".to_string(),+ rollback_sync_sql: Some("DROP TABLE IF EXISTS test;".to_string()),+ permission_sync_sql: Some("GRANT SELECT ON test TO reader;".to_string()),+ ..Default::default()+ };++ let script = generate_complete_script(+ &schema_diff,+ None,+ DatabaseType::Postgres,+ Some("public"),+ IdempotentStrategy::IfNotExists,+ );++ assert!(script.contains("Structure Changes"));+ assert!(script.contains("Permission Changes"));+ assert!(script.contains("Rollback Script"));+ assert!(script.contains("public"));+ }++ #[test]+ fn idempotent_mysql_table_contains_if_not_exists_no_double_wrap() {+ let sql = "CREATE TABLE IF NOT EXISTS existing (id INT);";+ let result = apply_idempotent_strategy(sql, DatabaseType::Mysql, IdempotentStrategy::IfNotExists);+ assert_eq!(result.matches("IF NOT EXISTS").count(), 1, "Already contains IF NOT EXISTS: {result}");+ }++ #[test]+ fn extract_table_name_from_create() {+ assert_eq!(extract_table_name("CREATE TABLE users (id INT)", "TABLE"), "users");+ assert_eq!(extract_table_name("CREATE TABLE `my_table` (id INT)", "TABLE"), "my_table");+ assert_eq!(extract_table_name("DROP TABLE old_data;", "TABLE"), "old_data");+ }++ #[test]+ fn extract_from_alter_table() {+ assert_eq!(extract_from_alter("ALTER TABLE users ADD COLUMN name VARCHAR(100);"), Some("users".to_string()));+ assert_eq!(+ extract_from_alter("ALTER TABLE \"schema\".\"users\" ADD COLUMN name VARCHAR(100);"),+ Some("schema\".\"users".to_string())+ );+ }++ #[test]+ fn split_sql_statements_basic() {+ let sql = "CREATE TABLE a (id INT);\nCREATE TABLE b (id INT);";+ let stmts = split_sql_statements(sql);+ assert_eq!(stmts.len(), 2);+ }++ #[test]+ fn split_sql_statements_with_string_literal() {+ let sql = "INSERT INTO t VALUES ('hello; world');\nSELECT * FROM t;";+ let stmts = split_sql_statements(sql);+ assert_eq!(stmts.len(), 2);+ assert!(stmts[0].contains("hello; world"));+ }++ #[test]+ fn split_sql_statements_trailing_without_semicolon() {+ let sql = "CREATE TABLE a (id INT);\nSELECT 1";+ let stmts = split_sql_statements(sql);+ assert_eq!(stmts.len(), 2);+ }++ #[test]+ fn generate_dml_clean_integration() {+ use crate::schema_diff::ColumnDiff;+ use crate::types::ColumnInfo;++ let col_diff = ColumnDiff {+ diff_type: "modified".to_string(),+ name: "large_val".to_string(),+ source: Some(ColumnInfo {+ name: "large_val".to_string(),+ data_type: "BIGINT".to_string(),+ is_nullable: true,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }),+ target: Some(ColumnInfo {+ name: "large_val".to_string(),+ data_type: "INT".to_string(),+ is_nullable: true,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }),+ changes: vec!["data_type BIGINT → INT".to_string()],+ };++ let table_diff = TableDiff {+ diff_type: "modified".to_string(),+ object_type: Some("TABLE".to_string()),+ name: "test_table".to_string(),+ columns: Some(vec![col_diff]),+ ..Default::default()+ };++ let prep = SchemaDiffPreparation { diffs: vec![table_diff], ..Default::default() };++ // Seed a pair-specific rule so the test does not depend on CWD for YAML files.+ {+ use crate::dml_binding::{DmlCleanRule, DmlCleanRuleRegistry};+ if let Ok(mut registry) = DmlCleanRuleRegistry::global().write() {+ registry.rules = vec![DmlCleanRule {+ name: "bigint_to_int".to_string(),+ source_type: "BIGINT".to_string(),+ target_type: "INT".to_string(),+ max_fidelity: 1.0,+ pre_transform_sql: Some(+ "UPDATE {table} SET {column} = NULL WHERE {column} > 2147483647".to_string(),+ ),+ description: None,+ }];+ }+ }++ let sql = generate_all_dml_clean_sql(&prep, 0.8);+ assert!(!sql.is_empty(), "DML should be generated for BIGINT→INT");+ assert!(sql[0].contains("2147483647"));+ }+}diff --git a/crates/dbx-core/src/sql_dialect.rs b/crates/dbx-core/src/sql_dialect.rsindex f619f0b2c3..d889b695c4 100644--- a/crates/dbx-core/src/sql_dialect.rs+++ b/crates/dbx-core/src/sql_dialect.rs@@ -1,19 +1,77 @@mod capabilities;+pub mod ddl_profile;+pub mod descriptor;+pub mod dialect_loader;+pub mod dialect_types;+pub mod dialect_yaml;+pub mod hot_reload;mod identifiers;+pub mod inference;mod table_select;+pub mod type_rewrite;mod types;#[cfg(test)]mod tests;+#[cfg(test)]+mod descriptor_snapshots;+pub use capabilities::{firebird_rows_clause, is_schema_aware, pagination_strategy, table_pagination_strategy, uses_fetch_first,uses_oracle_row_id, uses_single_row_insert_statements, PaginationContext, TablePaginationStrategy,};+pub use ddl_profile::{+ profile_for, AutoIncSyntax, DdlDialectProfile, IndexTypePlacement, QuoteStyle, RenameColumnSyntax, TriggerTemplate,+ TypeMapEntry,+};+pub use descriptor::{+ dialect_check, dialect_check_all, DialectCapabilityDescriptor, DialectInfo, DialectKind, TypeConversionRule,+ TypeMappingMatrix, CAP_ADD_COLUMN, CAP_ALTER_EXISTING_COLUMN, CAP_ALTER_OWNER, CAP_ALTER_PRIMARY_KEY,+ CAP_AUTO_INCREMENT, CAP_COMMENT, CAP_CREATE_FUNCTION, CAP_CREATE_INDEX, CAP_CREATE_OR_REPLACE, CAP_CREATE_SEQUENCE,+ CAP_CREATE_TABLE, CAP_CREATE_TRIGGER, CAP_DROP_COLUMN, CAP_DROP_FUNCTION, CAP_DROP_INDEX, CAP_DROP_SEQUENCE,+ CAP_DROP_TABLE, CAP_DROP_TRIGGER, CAP_FOREIGN_KEY, CAP_GRANT_REVOKE, CAP_IDENTITY_COLUMNS, CAP_IF_NOT_EXISTS,+ CAP_INDEX_COMMENT, CAP_INDEX_FILTER, CAP_INDEX_INCLUDE, CAP_INDEX_TYPE, CAP_REBUILD_INDEX, CAP_RENAME_COLUMN,+ CAP_REORDER_COLUMN, CAP_TEMPORARY_TABLE, CAP_TRANSACTIONAL_DDL, CAP_TRUNCATE_TABLE,+};pub use identifiers::{normalize_where_input, qualified_table_name, qualified_table_name_with_catalog, quote_table_identifier,};pub(crate) use identifiers::{parse_sqlserver_linked_schema_ref, qualified_transfer_table, quote_transfer_identifier};pub use table_select::{build_count_table_sql, build_table_data_select_sql, build_table_select_sql};pub(crate) use table_select::{quote_table_data_identifier, table_data_qualified_table_name};+pub use type_rewrite::{+ apply_auto_inc_to_column_def, column_is_auto_increment, rewrite_column_type, split_type_base_params,+ type_looks_integer, AutoIncColumnBuild,+};pub use types::*;++/// Resolve a dialect descriptor for the given kind.+pub fn resolve(kind: descriptor::DialectKind) -> descriptor::DialectCapabilityDescriptor {+ lazy_init();+ if let Some(desc) = dialect_loader::DialectRegistry::global().get_descriptor(kind.label()) {+ return desc;+ }+ descriptor::DialectCapabilityDescriptor::for_dialect(kind)+}++fn lazy_init() {+ use std::sync::OnceLock;+ static INIT: OnceLock<()> = OnceLock::new();+ INIT.get_or_init(|| {+ dialect_loader::register_core_dialects();+ let _ = crate::dml_binding::DmlCleanRuleRegistry::load_default();+ });+}++pub fn resolve_for_db(db_type: crate::models::connection::DatabaseType) -> descriptor::DialectCapabilityDescriptor {+ let kind = descriptor::DialectKind::from_database_type(db_type);+ resolve(kind)+}++pub fn resolve_label(kind: descriptor::DialectKind) -> String {+ if let Some(loaded) = dialect_loader::DialectRegistry::global().get(kind.label()) {+ return loaded.yaml.dialect.display_name.clone().unwrap_or_else(|| kind.label().to_string());+ }+ kind.label().to_string()+}diff --git a/crates/dbx-core/src/sql_dialect/ddl_profile.rs b/crates/dbx-core/src/sql_dialect/ddl_profile.rsnew file mode 100644index 0000000000..1bcfb64966--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/ddl_profile.rs@@ -0,0 +1,750 @@+//! Target-database DDL profile: how to *write* SQL for a concrete [`DatabaseType`].+//!+//! Profiles are data + small enums. Call sites must not branch on individual databases;+//! they only consult profile fields (quote style, auto-increment form, type map, …).++use crate::models::connection::DatabaseType;++/// Identifier quoting style for generated DDL.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum QuoteStyle {+ /// MySQL-family: `name`+ Backtick,+ /// PostgreSQL / Access / most ANSI: "name"+ DoubleQuote,+ /// SQL Server: [name]+ Brackets,+ /// Oracle-style unquoted uppercase+ UnquotedUpper,+}++/// How auto-increment / identity is expressed on the target database.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum AutoIncSyntax {+ /// No special auto-increment DDL.+ None,+ /// Append a fixed suffix to the column definition (e.g. ` AUTO_INCREMENT`, ` IDENTITY(1,1)`).+ Suffix(&'static str),+ /// Replace the mapped type with this type name for auto PK columns (e.g. Access `COUNTER`).+ ReplaceTypeWith(&'static str),+ /// PostgreSQL-style sequence + DEFAULT nextval (handled by generator after CREATE).+ PostgresSequence,+}++/// Static type rewrite rule: source base type (uppercase, no params) → target template.+/// Target may use `{}` for a single length/precision placeholder (first param only).+#[derive(Debug, Clone, Copy)]+pub struct TypeMapEntry {+ pub source_base: &'static str,+ pub target_template: &'static str,+}++/// How CREATE INDEX places the index method / type.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum IndexTypePlacement {+ /// No index-type clause.+ None,+ /// PostgreSQL: `CREATE INDEX … ON t USING btree (…)`+ UsingSuffix,+ /// SQL Server: `CREATE CLUSTERED INDEX …`+ TypePrefix,+ /// MySQL: `CREATE INDEX … USING BTREE ON t (…)`+ UsingBeforeOn,+}++/// CREATE TRIGGER body shape (templates use `{name}` `{timing}` `{event}` `{table}` `{body}`).+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum TriggerTemplate {+ /// `CREATE TRIGGER {name} {timing} {event} ON {table} FOR EACH ROW BEGIN {body} END;`+ MysqlStyle,+ /// `CREATE TRIGGER {name} {timing} {event} ON {table} FOR EACH ROW EXECUTE FUNCTION {body};`+ PostgresStyle,+ /// `CREATE TRIGGER {name} ON {table} {timing} {event} AS BEGIN {body} END;`+ SqlServerStyle,+ /// Conservative MySQL-like default for unknown engines.+ GenericRowBody,+}++/// RENAME COLUMN strategy inside ALTER TABLE.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum RenameColumnSyntax {+ /// `CHANGE COLUMN old new_def` (MySQL)+ MysqlChangeColumn,+ /// `RENAME COLUMN old TO new`+ RenameColumn,+ /// `ALTER COLUMN old RENAME TO new` (H2)+ AlterColumnRenameTo,+ /// `EXEC sp_rename 't.old', 'new', 'COLUMN'`+ SqlServerSpRename,+}++/// DDL generation profile for one [`DatabaseType`].+#[derive(Debug, Clone, Copy)]+pub struct DdlDialectProfile {+ pub database_type: DatabaseType,+ pub quote: QuoteStyle,+ pub auto_inc: AutoIncSyntax,+ /// When false, display widths like `INT(11)` are stripped if no type_map hit.+ pub supports_display_width: bool,+ /// Cap for length params when applying `{}` templates (e.g. Access TEXT max 255).+ pub max_varchar_len: Option<u32>,+ /// MySQL-style inline `COMMENT '...'` on columns.+ pub inline_column_comment: bool,+ /// SQLite-style: emit FOREIGN KEY clauses inside CREATE TABLE.+ pub foreign_keys_inline_in_create: bool,+ /// `DROP INDEX name ON table` (MySQL) vs `DROP INDEX IF EXISTS name`.+ pub drop_index_uses_on_table: bool,+ /// `DROP FOREIGN KEY` (MySQL) vs `DROP CONSTRAINT`.+ pub drop_fk_as_foreign_key: bool,+ /// Index method placement.+ pub index_type_placement: IndexTypePlacement,+ /// `INCLUDE (cols)` on indexes.+ pub index_supports_include: bool,+ /// Partial index `WHERE …`.+ pub index_supports_filter: bool,+ /// Index `COMMENT '…'` (MySQL).+ pub index_supports_comment: bool,+ /// Table comment: `ALTER TABLE t COMMENT = '…'` vs `COMMENT ON TABLE`.+ pub table_comment_via_alter: bool,+ /// Standalone column comment SQL is unsupported (MySQL needs MODIFY COLUMN).+ pub column_comment_via_modify_only: bool,+ pub trigger_template: TriggerTemplate,+ pub rename_column: RenameColumnSyntax,+ /// MySQL `MODIFY COLUMN` vs ANSI `ALTER COLUMN … TYPE/SET`.+ pub alter_uses_modify_column: bool,+ /// Batch multiple alter clauses in one `ALTER TABLE` statement.+ pub alter_batches_clauses: bool,+ /// Prefer emitting source SHOW CREATE / native DDL when dialects match (MySQL-family).+ pub prefers_native_source_ddl: bool,+ /// GRANT/REVOKE identifier style: backtick + user quotes vs ANSI double-quote.+ pub grant_uses_mysql_user_syntax: bool,+ /// Emit a comment that FK changes may need table rebuild (SQLite-family).+ pub warn_fk_needs_table_rebuild: bool,+ pub create_table_if_not_exists: bool,+ pub create_index_if_not_exists: bool,+ pub create_function_or_replace: bool,+ pub supports_function_ddl: bool,+ pub supports_sequence_ddl: bool,+ pub supports_rule_ddl: bool,+ pub supports_owner_ddl: bool,+ /// `{create_kw} {name} {definition};` — `create_kw` is CREATE [OR REPLACE] FUNCTION.+ pub function_create_template: Option<&'static str>,+ /// `DROP FUNCTION IF EXISTS {name}{cascade};`+ pub function_drop_template: Option<&'static str>,+ /// `CREATE SEQUENCE {name} AS {data_type} START WITH {start_value} … {cycle};`+ pub sequence_create_template: Option<&'static str>,+ /// `ALTER SEQUENCE {name} AS {data_type} START WITH {start_value} … {cycle};`+ pub sequence_alter_template: Option<&'static str>,+ /// `DROP SEQUENCE {name}{cascade};`+ pub sequence_drop_template: Option<&'static str>,+ /// `DROP RULE IF EXISTS {rule_name} ON {table_name};`+ pub rule_drop_template: Option<&'static str>,+ /// `ALTER {object_type} {name} OWNER TO {owner};`+ pub owner_alter_template: Option<&'static str>,+ /// Optional session lock-timeout preamble for generated scripts.+ pub lock_timeout_sql: Option<&'static str>,+ /// Data-driven base-type rewrites for this target (empty → rely on matrix / normalize only).+ pub type_map: &'static [TypeMapEntry],+}++impl DdlDialectProfile {+ pub fn lookup_type(&self, source_base_upper: &str) -> Option<&'static str> {+ self.type_map.iter().find(|e| e.source_base.eq_ignore_ascii_case(source_base_upper)).map(|e| e.target_template)+ }++ pub fn quote_ident(&self, name: &str) -> String {+ match self.quote {+ QuoteStyle::Backtick => format!("`{}`", name.replace('`', "``")),+ QuoteStyle::DoubleQuote => format!("\"{}\"", name.replace('"', "\"\"")),+ QuoteStyle::Brackets => format!("[{}]", name.replace(']', "]]")),+ // Oracle: unquoted identifiers fold to uppercase. Mixed-case names and+ // special characters must be double-quoted with original spelling preserved.+ QuoteStyle::UnquotedUpper => {+ let has_lower = name.chars().any(|c| c.is_ascii_lowercase());+ let has_upper = name.chars().any(|c| c.is_ascii_uppercase());+ let has_special = name.chars().any(|c| !c.is_ascii_alphanumeric() && c != '_' && c != '$' && c != '#');+ let bad_start =+ name.is_empty() || !name.chars().next().is_some_and(|c| c.is_ascii_alphabetic() || c == '_');+ // All-lower "emp" stays unquoted → EMP (Oracle fold). Mixed "empMixed" → "empMixed".+ let needs_quotes = (has_lower && has_upper) || has_special || bad_start;+ if needs_quotes {+ format!("\"{}\"", name.replace('"', "\"\""))+ } else {+ name.to_uppercase()+ }+ }+ }+ }++ /// Replace `{key}` placeholders. Unknown keys are left unchanged.+ pub fn render_template(template: &str, vars: &[(&str, &str)]) -> String {+ let mut out = template.to_string();+ for (key, value) in vars {+ out = out.replace(&format!("{{{key}}}"), value);+ }+ out+ }+}++const FN_CREATE: &str = "{create_kw} {name} {definition};";+const FN_DROP: &str = "DROP FUNCTION IF EXISTS {name}{cascade};";+const SEQ_CREATE: &str =+ "CREATE SEQUENCE {name} AS {data_type} START WITH {start_value} INCREMENT BY {increment} MINVALUE {min_value} MAXVALUE {max_value} {cycle};";+const SEQ_ALTER: &str =+ "ALTER SEQUENCE {name} AS {data_type} START WITH {start_value} INCREMENT BY {increment} MINVALUE {min_value} MAXVALUE {max_value} {cycle};";+const SEQ_DROP: &str = "DROP SEQUENCE {name}{cascade};";+const RULE_DROP: &str = "DROP RULE IF EXISTS {rule_name} ON {table_name}{cascade};";+const OWNER_ALTER: &str = "ALTER {object_type} {name} OWNER TO {owner};";++// ---------------------------------------------------------------------------+// Type maps (data only — no per-database logic at call sites)+// ---------------------------------------------------------------------------++const ACCESS_TYPE_MAP: &[TypeMapEntry] = &[+ TypeMapEntry { source_base: "BOOL", target_template: "YESNO" },+ TypeMapEntry { source_base: "BOOLEAN", target_template: "YESNO" },+ TypeMapEntry { source_base: "BIT", target_template: "YESNO" },+ TypeMapEntry { source_base: "YESNO", target_template: "YESNO" },+ TypeMapEntry { source_base: "TINYINT", target_template: "BYTE" },+ TypeMapEntry { source_base: "BYTE", target_template: "BYTE" },+ TypeMapEntry { source_base: "SMALLINT", target_template: "SMALLINT" },+ TypeMapEntry { source_base: "SHORT", target_template: "SMALLINT" },+ TypeMapEntry { source_base: "MEDIUMINT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "INT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "INTEGER", target_template: "INTEGER" },+ TypeMapEntry { source_base: "INT4", target_template: "INTEGER" },+ TypeMapEntry { source_base: "LONG", target_template: "INTEGER" },+ TypeMapEntry { source_base: "BIGINT", target_template: "DECIMAL(20,0)" },+ TypeMapEntry { source_base: "INT8", target_template: "DECIMAL(20,0)" },+ TypeMapEntry { source_base: "FLOAT", target_template: "SINGLE" },+ TypeMapEntry { source_base: "REAL", target_template: "SINGLE" },+ TypeMapEntry { source_base: "SINGLE", target_template: "SINGLE" },+ TypeMapEntry { source_base: "DOUBLE", target_template: "DOUBLE" },+ TypeMapEntry { source_base: "DOUBLE PRECISION", target_template: "DOUBLE" },+ TypeMapEntry { source_base: "DECIMAL", target_template: "DECIMAL({})" },+ TypeMapEntry { source_base: "NUMERIC", target_template: "DECIMAL({})" },+ TypeMapEntry { source_base: "NUMBER", target_template: "DECIMAL({})" },+ TypeMapEntry { source_base: "CURRENCY", target_template: "CURRENCY" },+ TypeMapEntry { source_base: "VARCHAR", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "CHARACTER VARYING", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "CHAR", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "CHARACTER", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "NVARCHAR", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "NVARCHAR2", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "VARCHAR2", target_template: "TEXT({})" },+ TypeMapEntry { source_base: "TEXT", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "TINYTEXT", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "MEDIUMTEXT", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "LONGTEXT", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "CLOB", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "MEMO", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "DATE", target_template: "DATETIME" },+ TypeMapEntry { source_base: "DATETIME", target_template: "DATETIME" },+ TypeMapEntry { source_base: "TIMESTAMP", target_template: "DATETIME" },+ TypeMapEntry { source_base: "TIME", target_template: "DATETIME" },+ TypeMapEntry { source_base: "YEAR", target_template: "SMALLINT" },+ TypeMapEntry { source_base: "BLOB", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "TINYBLOB", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "MEDIUMBLOB", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "LONGBLOB", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "BINARY", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "VARBINARY", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "IMAGE", target_template: "OLEOBJECT" },+ TypeMapEntry { source_base: "JSON", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "JSONB", target_template: "LONGTEXT" },+ TypeMapEntry { source_base: "UUID", target_template: "GUID" },+ TypeMapEntry { source_base: "UNIQUEIDENTIFIER", target_template: "GUID" },+ TypeMapEntry { source_base: "GUID", target_template: "GUID" },+];++const SQLITE_TYPE_MAP: &[TypeMapEntry] = &[+ TypeMapEntry { source_base: "TINYINT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "SMALLINT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "MEDIUMINT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "INT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "INTEGER", target_template: "INTEGER" },+ TypeMapEntry { source_base: "BIGINT", target_template: "INTEGER" },+ TypeMapEntry { source_base: "FLOAT", target_template: "REAL" },+ TypeMapEntry { source_base: "DOUBLE", target_template: "REAL" },+ TypeMapEntry { source_base: "DOUBLE PRECISION", target_template: "REAL" },+ TypeMapEntry { source_base: "DECIMAL", target_template: "NUMERIC" },+ TypeMapEntry { source_base: "NUMERIC", target_template: "NUMERIC" },+ TypeMapEntry { source_base: "VARCHAR", target_template: "TEXT" },+ TypeMapEntry { source_base: "CHAR", target_template: "TEXT" },+ TypeMapEntry { source_base: "TEXT", target_template: "TEXT" },+ TypeMapEntry { source_base: "TINYTEXT", target_template: "TEXT" },+ TypeMapEntry { source_base: "MEDIUMTEXT", target_template: "TEXT" },+ TypeMapEntry { source_base: "LONGTEXT", target_template: "TEXT" },+ TypeMapEntry { source_base: "DATETIME", target_template: "TEXT" },+ TypeMapEntry { source_base: "TIMESTAMP", target_template: "TEXT" },+ TypeMapEntry { source_base: "DATE", target_template: "TEXT" },+ TypeMapEntry { source_base: "BLOB", target_template: "BLOB" },+ TypeMapEntry { source_base: "JSON", target_template: "TEXT" },+];++// ---------------------------------------------------------------------------+// Profile families (shared shapes; registration is the only DatabaseType match)+// ---------------------------------------------------------------------------++fn mysql_family(db: DatabaseType) -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: db,+ quote: QuoteStyle::Backtick,+ auto_inc: AutoIncSyntax::Suffix(" AUTO_INCREMENT"),+ supports_display_width: true,+ max_varchar_len: Some(65_535),+ inline_column_comment: true,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: true,+ drop_fk_as_foreign_key: true,+ index_type_placement: IndexTypePlacement::UsingBeforeOn,+ index_supports_include: false,+ index_supports_filter: false,+ index_supports_comment: true,+ table_comment_via_alter: true,+ column_comment_via_modify_only: true,+ trigger_template: TriggerTemplate::MysqlStyle,+ rename_column: RenameColumnSyntax::MysqlChangeColumn,+ prefers_native_source_ddl: true,+ grant_uses_mysql_user_syntax: true,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: true,+ alter_batches_clauses: true,+ create_table_if_not_exists: true,+ create_index_if_not_exists: false,+ create_function_or_replace: false,+ supports_function_ddl: false,+ supports_sequence_ddl: false,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ function_create_template: None,+ function_drop_template: None,+ sequence_create_template: None,+ sequence_alter_template: None,+ sequence_drop_template: None,+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: Some("SET SESSION lock_wait_timeout = 3;"),+ type_map: &[],+ }+}++fn postgres_family(db: DatabaseType) -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: db,+ quote: QuoteStyle::DoubleQuote,+ auto_inc: AutoIncSyntax::PostgresSequence,+ supports_display_width: false,+ max_varchar_len: None,+ inline_column_comment: false,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::UsingSuffix,+ index_supports_include: true,+ index_supports_filter: true,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::PostgresStyle,+ rename_column: RenameColumnSyntax::RenameColumn,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: false,+ create_index_if_not_exists: true,+ create_function_or_replace: true,+ supports_function_ddl: true,+ supports_sequence_ddl: true,+ supports_rule_ddl: true,+ supports_owner_ddl: true,+ function_create_template: Some(FN_CREATE),+ function_drop_template: Some(FN_DROP),+ sequence_create_template: Some(SEQ_CREATE),+ sequence_alter_template: Some(SEQ_ALTER),+ sequence_drop_template: Some(SEQ_DROP),+ rule_drop_template: Some(RULE_DROP),+ owner_alter_template: Some(OWNER_ALTER),+ lock_timeout_sql: Some("SET lock_timeout = '3s';"),+ type_map: &[],+ }+}++fn oracle_family(db: DatabaseType) -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: db,+ quote: QuoteStyle::UnquotedUpper,+ auto_inc: AutoIncSyntax::Suffix(" GENERATED BY DEFAULT AS IDENTITY"),+ supports_display_width: false,+ max_varchar_len: Some(4000),+ inline_column_comment: false,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::None,+ index_supports_include: false,+ index_supports_filter: false,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::GenericRowBody,+ rename_column: RenameColumnSyntax::RenameColumn,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: false,+ create_index_if_not_exists: false,+ create_function_or_replace: false,+ supports_function_ddl: true,+ supports_sequence_ddl: true,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ // Same ANSI shapes as Postgres for the subset currently generated by schema_diff.+ function_create_template: Some(FN_CREATE),+ function_drop_template: Some(FN_DROP),+ sequence_create_template: Some(SEQ_CREATE),+ sequence_alter_template: Some(SEQ_ALTER),+ sequence_drop_template: Some(SEQ_DROP),+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: Some("ALTER SESSION SET DDL_LOCK_TIMEOUT = 3;"),+ type_map: &[],+ }+}++fn sqlserver_family(db: DatabaseType) -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: db,+ quote: QuoteStyle::DoubleQuote,+ auto_inc: AutoIncSyntax::Suffix(" IDENTITY(1,1)"),+ supports_display_width: false,+ max_varchar_len: None,+ inline_column_comment: false,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::TypePrefix,+ index_supports_include: true,+ index_supports_filter: true,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::SqlServerStyle,+ rename_column: RenameColumnSyntax::SqlServerSpRename,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: false,+ create_index_if_not_exists: true,+ create_function_or_replace: false,+ supports_function_ddl: true,+ supports_sequence_ddl: true,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ function_create_template: Some(FN_CREATE),+ function_drop_template: Some(FN_DROP),+ sequence_create_template: Some(SEQ_CREATE),+ sequence_alter_template: Some(SEQ_ALTER),+ sequence_drop_template: Some(SEQ_DROP),+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: Some("SET LOCK_TIMEOUT 3000;"),+ type_map: &[],+ }+}++fn sqlite_family(db: DatabaseType) -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: db,+ quote: QuoteStyle::DoubleQuote,+ auto_inc: AutoIncSyntax::None,+ supports_display_width: false,+ max_varchar_len: None,+ inline_column_comment: false,+ foreign_keys_inline_in_create: true,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::None,+ index_supports_include: false,+ index_supports_filter: true,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::GenericRowBody,+ rename_column: RenameColumnSyntax::RenameColumn,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: true,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: true,+ create_index_if_not_exists: true,+ create_function_or_replace: false,+ supports_function_ddl: false,+ supports_sequence_ddl: false,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ function_create_template: None,+ function_drop_template: None,+ sequence_create_template: None,+ sequence_alter_template: None,+ sequence_drop_template: None,+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: None,+ type_map: SQLITE_TYPE_MAP,+ }+}++fn access_profile() -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: DatabaseType::Access,+ quote: QuoteStyle::DoubleQuote,+ auto_inc: AutoIncSyntax::ReplaceTypeWith("COUNTER"),+ supports_display_width: false,+ max_varchar_len: Some(255),+ inline_column_comment: false,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::None,+ index_supports_include: false,+ index_supports_filter: false,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::GenericRowBody,+ rename_column: RenameColumnSyntax::RenameColumn,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: false,+ create_index_if_not_exists: false,+ create_function_or_replace: false,+ supports_function_ddl: false,+ supports_sequence_ddl: false,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ function_create_template: None,+ function_drop_template: None,+ sequence_create_template: None,+ sequence_alter_template: None,+ sequence_drop_template: None,+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: None,+ type_map: ACCESS_TYPE_MAP,+ }+}++fn h2_profile() -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: DatabaseType::H2,+ quote: QuoteStyle::DoubleQuote,+ auto_inc: AutoIncSyntax::None,+ supports_display_width: false,+ max_varchar_len: None,+ inline_column_comment: false,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::None,+ index_supports_include: false,+ index_supports_filter: false,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::GenericRowBody,+ rename_column: RenameColumnSyntax::AlterColumnRenameTo,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: false,+ create_index_if_not_exists: false,+ create_function_or_replace: false,+ supports_function_ddl: false,+ supports_sequence_ddl: false,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ function_create_template: None,+ function_drop_template: None,+ sequence_create_template: None,+ sequence_alter_template: None,+ sequence_drop_template: None,+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: None,+ type_map: &[],+ }+}++fn conservative_ansi(db: DatabaseType) -> DdlDialectProfile {+ DdlDialectProfile {+ database_type: db,+ quote: QuoteStyle::DoubleQuote,+ auto_inc: AutoIncSyntax::None,+ supports_display_width: false,+ max_varchar_len: None,+ inline_column_comment: false,+ foreign_keys_inline_in_create: false,+ drop_index_uses_on_table: false,+ drop_fk_as_foreign_key: false,+ index_type_placement: IndexTypePlacement::None,+ index_supports_include: false,+ index_supports_filter: false,+ index_supports_comment: false,+ table_comment_via_alter: false,+ column_comment_via_modify_only: false,+ trigger_template: TriggerTemplate::GenericRowBody,+ rename_column: RenameColumnSyntax::RenameColumn,+ prefers_native_source_ddl: false,+ grant_uses_mysql_user_syntax: false,+ warn_fk_needs_table_rebuild: false,+ alter_uses_modify_column: false,+ alter_batches_clauses: false,+ create_table_if_not_exists: false,+ create_index_if_not_exists: false,+ create_function_or_replace: false,+ supports_function_ddl: false,+ supports_sequence_ddl: false,+ supports_rule_ddl: false,+ supports_owner_ddl: false,+ function_create_template: None,+ function_drop_template: None,+ sequence_create_template: None,+ sequence_alter_template: None,+ sequence_drop_template: None,+ rule_drop_template: None,+ owner_alter_template: None,+ lock_timeout_sql: None,+ type_map: &[],+ }+}++fn clickhouse_profile() -> DdlDialectProfile {+ let mut p = conservative_ansi(DatabaseType::ClickHouse);+ // ClickHouse supports CREATE TABLE IF NOT EXISTS like MySQL/SQLite.+ p.create_table_if_not_exists = true;+ p.lock_timeout_sql = None;+ p+}++/// Resolve DDL profile for a concrete target database type.+///+/// This is the **only** place that maps [`DatabaseType`] → profile data.+/// Generators must not re-match on individual databases afterward.+pub fn profile_for(db_type: DatabaseType) -> DdlDialectProfile {+ use DatabaseType::*;+ match db_type {+ // MySQL family+ Mysql | Doris | StarRocks | Goldendb | Sundb | Databend | Gbase | ManticoreSearch => mysql_family(db_type),++ // PostgreSQL family+ Postgres | Redshift | Gaussdb | Kingbase | Highgo | Vastbase | OpenGauss | Kwdb | Firebird | Vertica+ | Exasol | Uxdb => postgres_family(db_type),++ // Oracle family+ Oracle | Dameng | OceanbaseOracle | Yashandb | Xugu | Iris => oracle_family(db_type),++ // SQL Server (not Access)+ SqlServer => sqlserver_family(db_type),++ // Access: own profile (must not inherit SqlServer IDENTITY)+ Access => access_profile(),++ // SQLite family+ Sqlite | Rqlite | Turso | CloudflareD1 => sqlite_family(db_type),++ H2 => h2_profile(),++ ClickHouse => clickhouse_profile(),++ DuckDb | Questdb | SapHana | Teradata | Snowflake | Trino | PrestoSql | Hive | Spark | Db2 | Informix+ | Bigquery | Kylin | Oscar | Tdengine | Iotdb | Databricks | Jdbc => conservative_ansi(db_type),++ // Non-tabular / not applicable for relational CREATE TABLE+ Redis | MongoDb | Elasticsearch | Qdrant | Milvus | Weaviate | ChromaDb | Neo4j | Cassandra | Etcd+ | ZooKeeper | Nacos | InfluxDb | MessageQueue | Hbase => conservative_ansi(db_type),+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn access_profile_is_not_sqlserver_identity() {+ let access = profile_for(DatabaseType::Access);+ let mssql = profile_for(DatabaseType::SqlServer);+ assert!(matches!(access.auto_inc, AutoIncSyntax::ReplaceTypeWith("COUNTER")));+ assert!(matches!(mssql.auto_inc, AutoIncSyntax::Suffix(s) if s.contains("IDENTITY")));+ assert!(access.lookup_type("VARCHAR").is_some());+ assert!(mssql.type_map.is_empty());+ // Access must not inherit SQL Server lock-timeout / idempotent flags.+ assert_eq!(access.lock_timeout_sql, None);+ assert!(mssql.lock_timeout_sql.is_some());+ assert!(!access.create_index_if_not_exists);+ assert!(mssql.create_index_if_not_exists);+ }++ #[test]+ fn oracle_profile_uses_valid_identity_and_ddl_lock_timeout() {+ let oracle = profile_for(DatabaseType::Oracle);+ assert!(matches!(+ oracle.auto_inc,+ AutoIncSyntax::Suffix(s) if s.contains("GENERATED BY DEFAULT AS IDENTITY")+ ));+ assert_eq!(oracle.lock_timeout_sql, Some("ALTER SESSION SET DDL_LOCK_TIMEOUT = 3;"));+ }++ #[test]+ fn quote_styles() {+ assert_eq!(profile_for(DatabaseType::Mysql).quote_ident("a`b"), "`a``b`");+ assert_eq!(profile_for(DatabaseType::Access).quote_ident(r#"a"b"#), "\"a\"\"b\"");+ assert_eq!(profile_for(DatabaseType::Oracle).quote_ident("emp"), "EMP");+ assert_eq!(profile_for(DatabaseType::Oracle).quote_ident("EMP"), "EMP");+ // Mixed-case must preserve spelling via quotes (not EMPMIXED).+ assert_eq!(profile_for(DatabaseType::Oracle).quote_ident("empMixed"), "\"empMixed\"");+ assert_eq!(profile_for(DatabaseType::Oracle).quote_ident("Emp"), "\"Emp\"");+ }++ #[test]+ fn postgres_object_templates_are_populated() {+ let p = profile_for(DatabaseType::Postgres);+ assert!(p.function_create_template.is_some());+ assert!(p.function_drop_template.is_some());+ assert!(p.sequence_create_template.is_some());+ assert!(p.sequence_alter_template.is_some());+ assert!(p.sequence_drop_template.is_some());+ assert!(p.rule_drop_template.is_some());+ assert!(p.owner_alter_template.is_some());+ }++ #[test]+ fn mysql_object_templates_are_absent() {+ let p = profile_for(DatabaseType::Mysql);+ assert!(p.function_create_template.is_none());+ assert!(p.sequence_create_template.is_none());+ assert!(p.rule_drop_template.is_none());+ assert!(p.owner_alter_template.is_none());+ }++ #[test]+ fn render_template_replaces_placeholders() {+ let rendered = DdlDialectProfile::render_template(+ "DROP FUNCTION IF EXISTS {name}{cascade};",+ &[("name", "\"public\".\"f\""), ("cascade", " CASCADE")],+ );+ assert_eq!(rendered, "DROP FUNCTION IF EXISTS \"public\".\"f\" CASCADE;");+ }+}diff --git a/crates/dbx-core/src/sql_dialect/descriptor.rs b/crates/dbx-core/src/sql_dialect/descriptor.rsnew file mode 100644index 0000000000..075477d676--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/descriptor.rs@@ -0,0 +1,1151 @@+use crate::models::connection::DatabaseType;++#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum DialectKind {+ Mysql,+ Postgres,+ Sqlite,+ DuckDb,+ SqlServer,+ Oracle,+ H2,+ ClickHouse,+ ManticoreSearch,+ Informix,+ Questdb,+ Unsupported,+}++impl DialectKind {+ pub fn from_database_type(db_type: DatabaseType) -> Self {+ match db_type {+ DatabaseType::Mysql+ | DatabaseType::Doris+ | DatabaseType::StarRocks+ | DatabaseType::Goldendb+ | DatabaseType::Sundb+ | DatabaseType::Databend+ | DatabaseType::Gbase => DialectKind::Mysql,+ DatabaseType::Postgres+ | DatabaseType::Gaussdb+ | DatabaseType::Kwdb+ | DatabaseType::OpenGauss+ | DatabaseType::Highgo+ | DatabaseType::Vastbase+ | DatabaseType::Kingbase+ | DatabaseType::Firebird+ | DatabaseType::Redshift+ | DatabaseType::Vertica+ | DatabaseType::Exasol => DialectKind::Postgres,+ DatabaseType::Sqlite | DatabaseType::Rqlite | DatabaseType::Turso => DialectKind::Sqlite,+ DatabaseType::DuckDb => DialectKind::DuckDb,+ DatabaseType::SqlServer | DatabaseType::Access => DialectKind::SqlServer,+ DatabaseType::Oracle+ | DatabaseType::Dameng+ | DatabaseType::OceanbaseOracle+ | DatabaseType::Iris+ | DatabaseType::Yashandb+ | DatabaseType::Xugu => DialectKind::Oracle,+ DatabaseType::H2 => DialectKind::H2,+ DatabaseType::ClickHouse => DialectKind::ClickHouse,+ DatabaseType::ManticoreSearch => DialectKind::ManticoreSearch,+ DatabaseType::Informix => DialectKind::Informix,+ DatabaseType::Questdb => DialectKind::Questdb,+ _ => DialectKind::Unsupported,+ }+ }++ pub fn to_database_type(self) -> Option<DatabaseType> {+ match self {+ DialectKind::Mysql => Some(DatabaseType::Mysql),+ DialectKind::Postgres => Some(DatabaseType::Postgres),+ DialectKind::Sqlite => Some(DatabaseType::Sqlite),+ DialectKind::DuckDb => Some(DatabaseType::DuckDb),+ DialectKind::SqlServer => Some(DatabaseType::SqlServer),+ DialectKind::Oracle => Some(DatabaseType::Oracle),+ DialectKind::H2 => Some(DatabaseType::H2),+ DialectKind::ClickHouse => Some(DatabaseType::ClickHouse),+ DialectKind::ManticoreSearch => Some(DatabaseType::ManticoreSearch),+ DialectKind::Informix => Some(DatabaseType::Informix),+ DialectKind::Questdb => Some(DatabaseType::Questdb),+ DialectKind::Unsupported => None,+ }+ }++ pub fn label(self) -> &'static str {+ match self {+ DialectKind::Mysql => "mysql",+ DialectKind::Postgres => "postgres",+ DialectKind::Sqlite => "sqlite",+ DialectKind::DuckDb => "duckdb",+ DialectKind::SqlServer => "sqlserver",+ DialectKind::Oracle => "oracle",+ DialectKind::H2 => "h2",+ DialectKind::ClickHouse => "clickhouse",+ DialectKind::ManticoreSearch => "manticoresearch",+ DialectKind::Informix => "informix",+ DialectKind::Questdb => "questdb",+ DialectKind::Unsupported => "unsupported",+ }+ }++ pub fn from_label(label: &str) -> Option<Self> {+ match label.to_ascii_lowercase().as_str() {+ // MySQL family+ "mysql" | "doris" | "starrocks" | "goldendb" | "sundb" | "databend" | "gbase" => Some(DialectKind::Mysql),+ // PostgreSQL family+ "postgresql" | "postgres" | "gaussdb" | "kwdb" | "opengauss" | "highgo" | "vastbase" | "kingbase"+ | "firebird" | "redshift" | "vertica" | "exasol" => Some(DialectKind::Postgres),+ // SQLite family+ "sqlite" | "rqlite" | "turso" => Some(DialectKind::Sqlite),+ // DuckDB+ "duckdb" => Some(DialectKind::DuckDb),+ // SQL Server family+ "sqlserver" | "mssql" | "sql server" | "access" => Some(DialectKind::SqlServer),+ // Oracle family+ "oracle" | "dameng" | "oceanbaseoracle" | "oceanbase" | "iris" | "yashandb" | "xugu" => {+ Some(DialectKind::Oracle)+ }+ // Others+ "h2" => Some(DialectKind::H2),+ "clickhouse" => Some(DialectKind::ClickHouse),+ "manticoresearch" => Some(DialectKind::ManticoreSearch),+ "informix" => Some(DialectKind::Informix),+ "questdb" => Some(DialectKind::Questdb),+ _ => None,+ }+ }+}++type DdlCapabilityFlags = u64;++pub const CAP_ADD_COLUMN: DdlCapabilityFlags = 1 << 0;+pub const CAP_DROP_COLUMN: DdlCapabilityFlags = 1 << 1;+pub const CAP_RENAME_COLUMN: DdlCapabilityFlags = 1 << 2;+pub const CAP_ALTER_EXISTING_COLUMN: DdlCapabilityFlags = 1 << 3;+pub const CAP_REORDER_COLUMN: DdlCapabilityFlags = 1 << 4;+pub const CAP_COMMENT: DdlCapabilityFlags = 1 << 5;+pub const CAP_CREATE_INDEX: DdlCapabilityFlags = 1 << 6;+pub const CAP_DROP_INDEX: DdlCapabilityFlags = 1 << 7;+pub const CAP_REBUILD_INDEX: DdlCapabilityFlags = 1 << 8;+pub const CAP_INDEX_TYPE: DdlCapabilityFlags = 1 << 9;+pub const CAP_INDEX_INCLUDE: DdlCapabilityFlags = 1 << 10;+pub const CAP_INDEX_FILTER: DdlCapabilityFlags = 1 << 11;+pub const CAP_INDEX_COMMENT: DdlCapabilityFlags = 1 << 12;+pub const CAP_ALTER_PRIMARY_KEY: DdlCapabilityFlags = 1 << 13;+pub const CAP_FOREIGN_KEY: DdlCapabilityFlags = 1 << 14;+pub const CAP_CREATE_TABLE: DdlCapabilityFlags = 1 << 15;+pub const CAP_DROP_TABLE: DdlCapabilityFlags = 1 << 16;+pub const CAP_TRUNCATE_TABLE: DdlCapabilityFlags = 1 << 17;+pub const CAP_CREATE_TRIGGER: DdlCapabilityFlags = 1 << 18;+pub const CAP_DROP_TRIGGER: DdlCapabilityFlags = 1 << 19;+pub const CAP_CREATE_FUNCTION: DdlCapabilityFlags = 1 << 20;+pub const CAP_DROP_FUNCTION: DdlCapabilityFlags = 1 << 21;+pub const CAP_CREATE_SEQUENCE: DdlCapabilityFlags = 1 << 22;+pub const CAP_DROP_SEQUENCE: DdlCapabilityFlags = 1 << 23;+pub const CAP_ALTER_OWNER: DdlCapabilityFlags = 1 << 24;+pub const CAP_GRANT_REVOKE: DdlCapabilityFlags = 1 << 25;+pub const CAP_IF_NOT_EXISTS: DdlCapabilityFlags = 1 << 26;+pub const CAP_CREATE_OR_REPLACE: DdlCapabilityFlags = 1 << 27;+pub const CAP_TEMPORARY_TABLE: DdlCapabilityFlags = 1 << 28;+pub const CAP_TRANSACTIONAL_DDL: DdlCapabilityFlags = 1 << 29;+pub const CAP_AUTO_INCREMENT: DdlCapabilityFlags = 1 << 30;+pub const CAP_IDENTITY_COLUMNS: DdlCapabilityFlags = 1 << 31;++const CAP_NAMES: &[(DdlCapabilityFlags, &str)] = &[+ (CAP_ADD_COLUMN, "add_column"),+ (CAP_DROP_COLUMN, "drop_column"),+ (CAP_RENAME_COLUMN, "rename_column"),+ (CAP_ALTER_EXISTING_COLUMN, "alter_existing_column"),+ (CAP_REORDER_COLUMN, "reorder_column"),+ (CAP_COMMENT, "comment"),+ (CAP_CREATE_INDEX, "create_index"),+ (CAP_DROP_INDEX, "drop_index"),+ (CAP_REBUILD_INDEX, "rebuild_index"),+ (CAP_INDEX_TYPE, "index_type"),+ (CAP_INDEX_INCLUDE, "index_include"),+ (CAP_INDEX_FILTER, "index_filter"),+ (CAP_INDEX_COMMENT, "index_comment"),+ (CAP_ALTER_PRIMARY_KEY, "alter_primary_key"),+ (CAP_FOREIGN_KEY, "foreign_key"),+ (CAP_CREATE_TABLE, "create_table"),+ (CAP_DROP_TABLE, "drop_table"),+ (CAP_TRUNCATE_TABLE, "truncate_table"),+ (CAP_CREATE_TRIGGER, "create_trigger"),+ (CAP_DROP_TRIGGER, "drop_trigger"),+ (CAP_CREATE_FUNCTION, "create_function"),+ (CAP_DROP_FUNCTION, "drop_function"),+ (CAP_CREATE_SEQUENCE, "create_sequence"),+ (CAP_DROP_SEQUENCE, "drop_sequence"),+ (CAP_ALTER_OWNER, "alter_owner"),+ (CAP_GRANT_REVOKE, "grant_revoke"),+ (CAP_IF_NOT_EXISTS, "if_not_exists"),+ (CAP_CREATE_OR_REPLACE, "create_or_replace"),+ (CAP_TEMPORARY_TABLE, "temporary_table"),+ (CAP_TRANSACTIONAL_DDL, "transactional_ddl"),+ (CAP_AUTO_INCREMENT, "auto_increment"),+ (CAP_IDENTITY_COLUMNS, "identity_columns"),+];++#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, serde::Deserialize)]+pub struct DialectCapabilityDescriptor {+ pub dialect: DialectKind,+ pub flags: DdlCapabilityFlags,+ pub max_identifier_length: u32,+ pub supports_schemas: bool,+ pub supports_catalogs: bool,+ pub max_columns_per_table: u32,+ pub max_indexes_per_table: u32,+ pub max_query_size_bytes: u64,+ pub supports_full_text_index: bool,+ pub supports_spatial_index: bool,+ pub supports_partitioning: bool,+ pub supports_table_sampling: bool,+ pub max_foreign_key_name_length: u32,+ pub supports_on_update_cascade: bool,+ pub supports_on_delete_set_null: bool,+ pub supports_deferrable_constraints: bool,+ pub supports_array_type: bool,+ pub supports_json_type: bool,+ pub supports_enum_type: bool,+ pub supports_uuid_type: bool,+ pub supports_identity_columns: bool,+ pub supports_auto_increment: bool,+ pub supports_sequences: bool,+}++impl Default for DialectCapabilityDescriptor {+ fn default() -> Self {+ Self {+ dialect: DialectKind::Unsupported,+ flags: 0,+ max_identifier_length: 0,+ supports_schemas: false,+ supports_catalogs: false,+ max_columns_per_table: 0,+ max_indexes_per_table: 0,+ max_query_size_bytes: 0,+ supports_full_text_index: false,+ supports_spatial_index: false,+ supports_partitioning: false,+ supports_table_sampling: false,+ max_foreign_key_name_length: 0,+ supports_on_update_cascade: false,+ supports_on_delete_set_null: false,+ supports_deferrable_constraints: false,+ supports_array_type: false,+ supports_json_type: false,+ supports_enum_type: false,+ supports_uuid_type: false,+ supports_identity_columns: false,+ supports_auto_increment: false,+ supports_sequences: false,+ }+ }+}++impl DialectCapabilityDescriptor {+ pub fn has_capability(&self, flag: DdlCapabilityFlags) -> bool {+ self.flags & flag != 0+ }++ pub fn for_dialect(kind: DialectKind) -> Self {+ match kind {+ DialectKind::Mysql => Self {+ dialect: DialectKind::Mysql,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_REORDER_COLUMN+ | CAP_COMMENT+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_INDEX_TYPE+ | CAP_INDEX_COMMENT+ | CAP_ALTER_PRIMARY_KEY+ | CAP_FOREIGN_KEY+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_CREATE_FUNCTION+ | CAP_DROP_FUNCTION+ | CAP_CREATE_SEQUENCE+ | CAP_DROP_SEQUENCE+ | CAP_ALTER_OWNER+ | CAP_GRANT_REVOKE+ | CAP_IF_NOT_EXISTS+ | CAP_TEMPORARY_TABLE+ | CAP_AUTO_INCREMENT,+ max_identifier_length: 64,+ max_columns_per_table: 4096,+ max_indexes_per_table: 64,+ max_query_size_bytes: 16 * 1024 * 1024,+ max_foreign_key_name_length: 64,+ supports_full_text_index: true,+ supports_spatial_index: true,+ supports_partitioning: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_json_type: true,+ supports_enum_type: true,+ supports_auto_increment: true,+ ..Default::default()+ },+ DialectKind::Postgres => Self {+ dialect: DialectKind::Postgres,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_COMMENT+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_INDEX_TYPE+ | CAP_INDEX_INCLUDE+ | CAP_INDEX_FILTER+ | CAP_INDEX_COMMENT+ | CAP_ALTER_PRIMARY_KEY+ | CAP_FOREIGN_KEY+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_CREATE_FUNCTION+ | CAP_DROP_FUNCTION+ | CAP_CREATE_SEQUENCE+ | CAP_DROP_SEQUENCE+ | CAP_ALTER_OWNER+ | CAP_GRANT_REVOKE+ | CAP_IF_NOT_EXISTS+ | CAP_CREATE_OR_REPLACE+ | CAP_TRANSACTIONAL_DDL+ | CAP_TEMPORARY_TABLE+ | CAP_IDENTITY_COLUMNS,+ max_identifier_length: 63,+ supports_schemas: true,+ max_columns_per_table: 1600,+ max_indexes_per_table: 100,+ max_query_size_bytes: 256 * 1024 * 1024,+ max_foreign_key_name_length: 63,+ supports_full_text_index: true,+ supports_spatial_index: true,+ supports_partitioning: true,+ supports_table_sampling: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_deferrable_constraints: true,+ supports_array_type: true,+ supports_json_type: true,+ supports_enum_type: true,+ supports_uuid_type: true,+ supports_identity_columns: true,+ supports_sequences: true,+ ..Default::default()+ },+ DialectKind::Sqlite => Self {+ dialect: DialectKind::Sqlite,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_INDEX_FILTER+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_CREATE_FUNCTION+ | CAP_DROP_FUNCTION+ | CAP_CREATE_SEQUENCE+ | CAP_DROP_SEQUENCE+ | CAP_IF_NOT_EXISTS+ | CAP_AUTO_INCREMENT,+ max_identifier_length: 255,+ max_columns_per_table: 2000,+ max_indexes_per_table: 200,+ max_foreign_key_name_length: 255,+ supports_full_text_index: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_auto_increment: true,+ ..Default::default()+ },+ DialectKind::DuckDb => Self {+ dialect: DialectKind::DuckDb,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_IF_NOT_EXISTS+ | CAP_CREATE_OR_REPLACE+ | CAP_TEMPORARY_TABLE,+ max_identifier_length: 255,+ supports_schemas: true,+ max_columns_per_table: 1600,+ max_indexes_per_table: 100,+ max_query_size_bytes: 256 * 1024 * 1024,+ max_foreign_key_name_length: 255,+ supports_spatial_index: true,+ supports_partitioning: true,+ supports_table_sampling: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_array_type: true,+ supports_json_type: true,+ supports_enum_type: true,+ supports_uuid_type: true,+ supports_sequences: true,+ ..Default::default()+ },+ DialectKind::SqlServer => Self {+ dialect: DialectKind::SqlServer,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_COMMENT+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_INDEX_TYPE+ | CAP_INDEX_INCLUDE+ | CAP_INDEX_FILTER+ | CAP_INDEX_COMMENT+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_CREATE_FUNCTION+ | CAP_DROP_FUNCTION+ | CAP_CREATE_SEQUENCE+ | CAP_DROP_SEQUENCE+ | CAP_ALTER_OWNER+ | CAP_GRANT_REVOKE+ | CAP_IF_NOT_EXISTS+ | CAP_TEMPORARY_TABLE+ | CAP_TRANSACTIONAL_DDL+ | CAP_IDENTITY_COLUMNS,+ max_identifier_length: 128,+ supports_schemas: true,+ supports_catalogs: true,+ max_columns_per_table: 1024,+ max_indexes_per_table: 999,+ max_query_size_bytes: 65_536 * 4_096,+ max_foreign_key_name_length: 128,+ supports_full_text_index: true,+ supports_spatial_index: true,+ supports_partitioning: true,+ supports_table_sampling: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_json_type: true,+ supports_uuid_type: true,+ supports_identity_columns: true,+ supports_sequences: true,+ ..Default::default()+ },+ DialectKind::Oracle => Self {+ dialect: DialectKind::Oracle,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_COMMENT+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_INDEX_TYPE+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_CREATE_FUNCTION+ | CAP_DROP_FUNCTION+ | CAP_CREATE_SEQUENCE+ | CAP_DROP_SEQUENCE+ | CAP_ALTER_OWNER+ | CAP_GRANT_REVOKE+ | CAP_IF_NOT_EXISTS+ | CAP_TEMPORARY_TABLE,+ max_identifier_length: 30,+ supports_schemas: true,+ max_columns_per_table: 1000,+ max_indexes_per_table: 100,+ max_query_size_bytes: 64 * 1024,+ max_foreign_key_name_length: 30,+ supports_full_text_index: true,+ supports_spatial_index: true,+ supports_partitioning: true,+ supports_table_sampling: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_deferrable_constraints: true,+ supports_json_type: true,+ supports_identity_columns: true,+ supports_sequences: true,+ ..Default::default()+ },+ DialectKind::H2 => Self {+ dialect: DialectKind::H2,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_COMMENT+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_CREATE_FUNCTION+ | CAP_DROP_FUNCTION+ | CAP_IF_NOT_EXISTS+ | CAP_TEMPORARY_TABLE+ | CAP_IDENTITY_COLUMNS,+ max_identifier_length: 256,+ supports_schemas: true,+ max_columns_per_table: 1600,+ max_indexes_per_table: 100,+ max_query_size_bytes: 128 * 1024,+ max_foreign_key_name_length: 256,+ supports_full_text_index: true,+ supports_spatial_index: true,+ supports_on_update_cascade: true,+ supports_on_delete_set_null: true,+ supports_deferrable_constraints: true,+ supports_json_type: true,+ supports_uuid_type: true,+ supports_identity_columns: true,+ supports_sequences: true,+ ..Default::default()+ },+ DialectKind::ClickHouse => Self {+ dialect: DialectKind::ClickHouse,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_REORDER_COLUMN+ | CAP_COMMENT+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_IF_NOT_EXISTS+ | CAP_TEMPORARY_TABLE,+ max_identifier_length: 256,+ supports_schemas: true,+ max_columns_per_table: 1000,+ max_query_size_bytes: 256 * 1024 * 1024,+ max_foreign_key_name_length: 256,+ supports_full_text_index: true,+ supports_partitioning: true,+ supports_table_sampling: true,+ supports_array_type: true,+ supports_json_type: true,+ supports_enum_type: true,+ supports_uuid_type: true,+ ..Default::default()+ },+ DialectKind::ManticoreSearch => Self {+ dialect: DialectKind::ManticoreSearch,+ flags: CAP_ADD_COLUMN | CAP_DROP_COLUMN | CAP_CREATE_TABLE | CAP_DROP_TABLE | CAP_TRUNCATE_TABLE,+ max_identifier_length: 256,+ max_columns_per_table: 512,+ max_query_size_bytes: 16 * 1024 * 1024,+ supports_full_text_index: true,+ supports_spatial_index: true,+ supports_json_type: true,+ supports_auto_increment: true,+ ..Default::default()+ },+ DialectKind::Informix => Self {+ dialect: DialectKind::Informix,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_CREATE_INDEX+ | CAP_DROP_INDEX+ | CAP_REBUILD_INDEX+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_CREATE_TRIGGER+ | CAP_DROP_TRIGGER+ | CAP_GRANT_REVOKE,+ max_identifier_length: 128,+ supports_schemas: true,+ max_columns_per_table: 32767,+ max_indexes_per_table: 200,+ max_query_size_bytes: 2 * 1024 * 1024,+ max_foreign_key_name_length: 128,+ supports_partitioning: true,+ supports_on_delete_set_null: true,+ supports_deferrable_constraints: true,+ supports_sequences: true,+ ..Default::default()+ },+ DialectKind::Questdb => Self {+ dialect: DialectKind::Questdb,+ flags: CAP_ADD_COLUMN+ | CAP_DROP_COLUMN+ | CAP_RENAME_COLUMN+ | CAP_ALTER_EXISTING_COLUMN+ | CAP_CREATE_TABLE+ | CAP_DROP_TABLE+ | CAP_TRUNCATE_TABLE+ | CAP_IF_NOT_EXISTS,+ max_identifier_length: 256,+ max_columns_per_table: 1024,+ max_query_size_bytes: 64 * 1024,+ supports_partitioning: true,+ ..Default::default()+ },+ DialectKind::Unsupported => Self::default(),+ }+ }++ pub fn capabilities_for_database_type(db_type: DatabaseType) -> Self {+ crate::sql_dialect::resolve_for_db(db_type)+ }+}++#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)]+pub struct TypeConversionRule {+ pub source_type: String,+ pub target_type: String,+ pub precision_loss: bool,+ pub requires_cast: bool,+}++#[derive(Debug, Clone, PartialEq)]+pub struct TypeMappingMatrix {+ pub from: DialectKind,+ pub to: DialectKind,+ pub rules: Vec<TypeConversionRule>,+}++impl TypeMappingMatrix {+ pub fn for_dialects(from: DialectKind, to: DialectKind) -> Self {+ let rules = Self::build_rules(from, to);+ Self { from, to, rules }+ }++ fn build_rules(from: DialectKind, to: DialectKind) -> Vec<TypeConversionRule> {+ let mut rules = Vec::new();+ match (from, to) {+ (DialectKind::Mysql, DialectKind::Postgres) => {+ rules.push(TypeConversionRule {+ source_type: "TINYINT(1)".into(),+ target_type: "BOOLEAN".into(),+ precision_loss: false,+ requires_cast: true,+ });+ rules.push(TypeConversionRule {+ source_type: "TINYINT".into(),+ target_type: "SMALLINT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "MEDIUMINT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "INT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BIGINT".into(),+ target_type: "BIGINT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "FLOAT".into(),+ target_type: "REAL".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "DOUBLE".into(),+ target_type: "DOUBLE PRECISION".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TINYTEXT".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TEXT".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "MEDIUMTEXT".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "LONGTEXT".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BLOB".into(),+ target_type: "BYTEA".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TINYBLOB".into(),+ target_type: "BYTEA".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "MEDIUMBLOB".into(),+ target_type: "BYTEA".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "LONGBLOB".into(),+ target_type: "BYTEA".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "DATETIME".into(),+ target_type: "TIMESTAMP".into(),+ precision_loss: false,+ requires_cast: false,+ });+ }+ (DialectKind::Postgres, DialectKind::Mysql) => {+ rules.push(TypeConversionRule {+ source_type: "SMALLINT".into(),+ target_type: "SMALLINT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "INTEGER".into(),+ target_type: "INT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BIGINT".into(),+ target_type: "BIGINT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "REAL".into(),+ target_type: "FLOAT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "DOUBLE PRECISION".into(),+ target_type: "DOUBLE".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TEXT".into(),+ target_type: "LONGTEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BYTEA".into(),+ target_type: "BLOB".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BOOLEAN".into(),+ target_type: "TINYINT(1)".into(),+ precision_loss: false,+ requires_cast: true,+ });+ rules.push(TypeConversionRule {+ source_type: "TIMESTAMP".into(),+ target_type: "DATETIME".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TIMESTAMPTZ".into(),+ target_type: "DATETIME".into(),+ precision_loss: true,+ requires_cast: true,+ });+ rules.push(TypeConversionRule {+ source_type: "UUID".into(),+ target_type: "CHAR(36)".into(),+ precision_loss: false,+ requires_cast: true,+ });+ rules.push(TypeConversionRule {+ source_type: "JSONB".into(),+ target_type: "JSON".into(),+ precision_loss: false,+ requires_cast: false,+ });+ }+ (DialectKind::Mysql, DialectKind::Sqlite) => {+ rules.push(TypeConversionRule {+ source_type: "INT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BIGINT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TINYINT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "SMALLINT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "MEDIUMINT".into(),+ target_type: "INTEGER".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "DOUBLE".into(),+ target_type: "REAL".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "FLOAT".into(),+ target_type: "REAL".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "DATETIME".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TIMESTAMP".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "TEXT".into(),+ target_type: "TEXT".into(),+ precision_loss: false,+ requires_cast: false,+ });+ rules.push(TypeConversionRule {+ source_type: "BLOB".into(),+ target_type: "BLOB".into(),+ precision_loss: false,+ requires_cast: false,+ });+ }+ _ => {}+ }+ rules+ }++ pub fn convert_type(&self, source_type: &str) -> (String, bool) {+ let trimmed = source_type.trim().to_ascii_uppercase();++ for rule in &self.rules {+ if trimmed == rule.source_type {+ return (rule.target_type.clone(), rule.requires_cast);+ }+ if trimmed.starts_with(&rule.source_type) {+ let remaining = trimmed.trim_start_matches(&rule.source_type);+ if remaining.is_empty() || remaining.starts_with(' ') || remaining.starts_with('(') {+ return (rule.target_type.clone(), rule.requires_cast);+ }+ }+ }++ (source_type.to_string(), true)+ }+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct DialectInfo {+ pub kind: DialectKind,+ pub label: String,+ pub capabilities: Vec<String>,+ pub max_identifier_length: u32,+ pub supports_schemas: bool,+ pub supports_catalogs: bool,+ pub max_columns_per_table: u32,+ pub supports_json_type: bool,+ pub supports_array_type: bool,+ pub supports_enum_type: bool,+ pub supports_uuid_type: bool,+ pub supports_auto_increment: bool,+ pub supports_identity_columns: bool,+ pub supports_sequences: bool,+ pub supports_partitioning: bool,+ pub supports_full_text_index: bool,+ pub supports_spatial_index: bool,+ pub supports_transactional_ddl: bool,+}++impl From<DialectCapabilityDescriptor> for DialectInfo {+ fn from(caps: DialectCapabilityDescriptor) -> Self {+ Self {+ kind: caps.dialect,+ label: caps.dialect.label().to_string(),+ capabilities: CAP_NAMES+ .iter()+ .filter(|(flag, _)| caps.has_capability(*flag))+ .map(|(_, name)| name.to_string())+ .collect(),+ max_identifier_length: caps.max_identifier_length,+ supports_schemas: caps.supports_schemas,+ supports_catalogs: caps.supports_catalogs,+ max_columns_per_table: caps.max_columns_per_table,+ supports_json_type: caps.supports_json_type,+ supports_array_type: caps.supports_array_type,+ supports_enum_type: caps.supports_enum_type,+ supports_uuid_type: caps.supports_uuid_type,+ supports_auto_increment: caps.supports_auto_increment,+ supports_identity_columns: caps.supports_identity_columns,+ supports_sequences: caps.supports_sequences,+ supports_partitioning: caps.supports_partitioning,+ supports_full_text_index: caps.supports_full_text_index,+ supports_spatial_index: caps.supports_spatial_index,+ supports_transactional_ddl: caps.has_capability(CAP_TRANSACTIONAL_DDL),+ }+ }+}++impl DialectInfo {+ pub fn for_kind(kind: DialectKind) -> Self {+ let caps = crate::sql_dialect::resolve(kind);+ Self::from(caps)+ }++ pub fn all() -> Vec<Self> {+ use DialectKind::*;+ vec![Mysql, Postgres, Sqlite, DuckDb, SqlServer, Oracle, H2, ClickHouse, ManticoreSearch, Informix, Questdb]+ .into_iter()+ .map(Self::for_kind)+ .collect()+ }+}++pub fn dialect_check(kind: DialectKind) -> DialectInfo {+ DialectInfo::for_kind(kind)+}++pub fn dialect_check_all() -> Vec<DialectInfo> {+ DialectInfo::all()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn dialect_kind_from_database_type_roundtrip() {+ let test_cases = vec![+ (DatabaseType::Mysql, DialectKind::Mysql),+ (DatabaseType::Postgres, DialectKind::Postgres),+ (DatabaseType::Sqlite, DialectKind::Sqlite),+ (DatabaseType::DuckDb, DialectKind::DuckDb),+ (DatabaseType::SqlServer, DialectKind::SqlServer),+ (DatabaseType::Oracle, DialectKind::Oracle),+ (DatabaseType::H2, DialectKind::H2),+ (DatabaseType::ClickHouse, DialectKind::ClickHouse),+ (DatabaseType::ManticoreSearch, DialectKind::ManticoreSearch),+ (DatabaseType::Informix, DialectKind::Informix),+ (DatabaseType::Questdb, DialectKind::Questdb),+ (DatabaseType::Redis, DialectKind::Unsupported),+ (DatabaseType::MongoDb, DialectKind::Unsupported),+ ];+ for (db_type, expected) in test_cases {+ assert_eq!(DialectKind::from_database_type(db_type), expected, "Mismatch for {db_type:?}");+ }+ }++ #[test]+ fn dialect_kind_to_database_type_roundtrip() {+ for kind in &[+ DialectKind::Mysql,+ DialectKind::Postgres,+ DialectKind::Sqlite,+ DialectKind::DuckDb,+ DialectKind::SqlServer,+ DialectKind::Oracle,+ DialectKind::H2,+ DialectKind::ClickHouse,+ DialectKind::ManticoreSearch,+ DialectKind::Informix,+ DialectKind::Questdb,+ ] {+ let db_type = kind.to_database_type().unwrap();+ let back = DialectKind::from_database_type(db_type);+ assert_eq!(*kind, back, "Roundtrip failed for {kind:?}");+ }+ assert_eq!(DialectKind::Unsupported.to_database_type(), None);+ }++ #[test]+ fn dialect_capability_descriptor_for_all_kinds() {+ for kind in &[+ DialectKind::Mysql,+ DialectKind::Postgres,+ DialectKind::Sqlite,+ DialectKind::DuckDb,+ DialectKind::SqlServer,+ DialectKind::Oracle,+ DialectKind::H2,+ DialectKind::ClickHouse,+ DialectKind::ManticoreSearch,+ DialectKind::Informix,+ DialectKind::Questdb,+ DialectKind::Unsupported,+ ] {+ let desc = DialectCapabilityDescriptor::for_dialect(*kind);+ assert_eq!(desc.dialect, *kind);+ }+ }++ #[test]+ fn mysql_capabilities_match_capabilities_for() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Mysql);+ assert!(desc.has_capability(CAP_ADD_COLUMN));+ assert!(desc.has_capability(CAP_DROP_COLUMN));+ assert!(desc.has_capability(CAP_RENAME_COLUMN));+ assert!(desc.has_capability(CAP_FOREIGN_KEY));+ assert!(desc.supports_auto_increment);+ assert!(desc.supports_json_type);+ assert!(desc.supports_enum_type);+ assert!(!desc.supports_schemas);+ assert!(!desc.supports_identity_columns);+ }++ #[test]+ fn postgres_capabilities() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Postgres);+ assert!(desc.has_capability(CAP_ADD_COLUMN));+ assert!(desc.has_capability(CAP_FOREIGN_KEY));+ assert!(desc.has_capability(CAP_INDEX_INCLUDE));+ assert!(desc.has_capability(CAP_INDEX_FILTER));+ assert!(desc.has_capability(CAP_TRANSACTIONAL_DDL));+ assert!(desc.supports_schemas);+ assert!(desc.supports_array_type);+ assert!(desc.supports_json_type);+ assert!(desc.supports_enum_type);+ assert!(desc.supports_uuid_type);+ assert!(desc.supports_sequences);+ assert!(!desc.supports_auto_increment);+ assert_eq!(desc.max_identifier_length, 63);+ }++ #[test]+ fn mysql_to_postgres_type_mapping() {+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ assert_eq!(matrix.convert_type("INT"), ("INTEGER".to_string(), false));+ assert_eq!(matrix.convert_type("TINYINT"), ("SMALLINT".to_string(), false));+ assert_eq!(matrix.convert_type("BIGINT"), ("BIGINT".to_string(), false));+ assert_eq!(matrix.convert_type("BLOB"), ("BYTEA".to_string(), false));+ assert_eq!(matrix.convert_type("DATETIME"), ("TIMESTAMP".to_string(), false));+ assert_eq!(matrix.convert_type("TEXT"), ("TEXT".to_string(), false));+ assert!(matrix.convert_type("TINYINT(1)").1);+ }++ #[test]+ fn postgres_to_mysql_type_mapping() {+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Postgres, DialectKind::Mysql);+ assert_eq!(matrix.convert_type("INTEGER"), ("INT".to_string(), false));+ assert_eq!(matrix.convert_type("BIGINT"), ("BIGINT".to_string(), false));+ assert_eq!(matrix.convert_type("TEXT"), ("LONGTEXT".to_string(), false));+ assert_eq!(matrix.convert_type("BYTEA"), ("BLOB".to_string(), false));+ assert_eq!(matrix.convert_type("BOOLEAN"), ("TINYINT(1)".to_string(), true));+ assert_eq!(matrix.convert_type("UUID"), ("CHAR(36)".to_string(), true));+ }++ #[test]+ fn mysql_to_sqlite_type_mapping() {+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Sqlite);+ assert_eq!(matrix.convert_type("INT"), ("INTEGER".to_string(), false));+ assert_eq!(matrix.convert_type("BIGINT"), ("INTEGER".to_string(), false));+ assert_eq!(matrix.convert_type("TEXT"), ("TEXT".to_string(), false));+ let (result, lossy) = matrix.convert_type("VARCHAR(255)");+ assert_eq!(result, "VARCHAR(255)");+ assert!(lossy);+ }++ #[test]+ fn type_mapping_unknown_type_passthrough() {+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ let (result, lossy) = matrix.convert_type("GEOGRAPHY");+ assert_eq!(result, "GEOGRAPHY");+ assert!(lossy);+ }++ #[test]+ fn dialect_kind_label() {+ assert_eq!(DialectKind::Mysql.label(), "mysql");+ assert_eq!(DialectKind::Postgres.label(), "postgres");+ assert_eq!(DialectKind::Unsupported.label(), "unsupported");+ }++ #[test]+ fn unsupported_capabilities_are_all_false() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Unsupported);+ assert_eq!(desc.flags, 0);+ assert!(!desc.supports_schemas);+ assert!(!desc.supports_partitioning);+ }+}diff --git a/crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs b/crates/dbx-core/src/sql_dialect/descriptor_snapshots.rsnew file mode 100644index 0000000000..c0bd29c265--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs@@ -0,0 +1,68 @@+use crate::sql_dialect::descriptor::{DialectCapabilityDescriptor, DialectInfo, DialectKind, TypeMappingMatrix};+use insta::assert_json_snapshot;++#[test]+fn snapshot_mysql_descriptor() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Mysql);+ assert_json_snapshot!("mysql_descriptor", desc);+}++#[test]+fn snapshot_postgres_descriptor() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Postgres);+ assert_json_snapshot!("postgres_descriptor", desc);+}++#[test]+fn snapshot_sqlite_descriptor() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Sqlite);+ assert_json_snapshot!("sqlite_descriptor", desc);+}++#[test]+fn snapshot_sqlserver_descriptor() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::SqlServer);+ assert_json_snapshot!("sqlserver_descriptor", desc);+}++#[test]+fn snapshot_oracle_descriptor() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Oracle);+ assert_json_snapshot!("oracle_descriptor", desc);+}++#[test]+fn snapshot_duckdb_descriptor() {+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::DuckDb);+ assert_json_snapshot!("duckdb_descriptor", desc);+}++#[test]+fn snapshot_mysql_info() {+ let info = DialectInfo::for_kind(DialectKind::Mysql);+ assert_json_snapshot!("mysql_info", info);+}++#[test]+fn snapshot_postgres_info() {+ let info = DialectInfo::for_kind(DialectKind::Postgres);+ assert_json_snapshot!("postgres_info", info);+}++#[test]+fn snapshot_mysql_to_postgres_type_mapping() {+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Mysql, DialectKind::Postgres);+ assert_json_snapshot!("mysql_to_postgres_mapping", &matrix.rules);+}++#[test]+fn snapshot_postgres_to_mysql_type_mapping() {+ let matrix = TypeMappingMatrix::for_dialects(DialectKind::Postgres, DialectKind::Mysql);+ assert_json_snapshot!("postgres_to_mysql_mapping", &matrix.rules);+}++#[test]+fn snapshot_all_dialects_info() {+ let all = DialectInfo::all();+ assert_json_snapshot!("all_dialects_info", all);+}diff --git a/crates/dbx-core/src/sql_dialect/dialect_loader.rs b/crates/dbx-core/src/sql_dialect/dialect_loader.rsnew file mode 100644index 0000000000..04915cf317--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/dialect_loader.rs@@ -0,0 +1,429 @@+use std::collections::HashMap;+use std::fs;+use std::path::{Path, PathBuf};+use std::sync::RwLock;++use super::descriptor::{DialectCapabilityDescriptor, DialectKind};+use super::dialect_yaml::DialectYaml;++/// Singleton dialect registry that holds all loaded dialect descriptors.+/// Thread-safe via RwLock. Access via `DialectRegistry::global()`.+pub struct DialectRegistry {+ descriptors: RwLock<HashMap<String, LoadedDialect>>,+ plugin_dirs: RwLock<Vec<PathBuf>>,+}++#[derive(Debug, Clone)]+pub struct LoadedDialect {+ pub dialect_name: String,+ pub kind: DialectKind,+ pub descriptor: DialectCapabilityDescriptor,+ pub yaml: DialectYaml,+ pub source_path: Option<PathBuf>,+ pub loaded_at: String,+}++#[derive(Debug, Clone)]+pub struct LoadError {+ pub path: PathBuf,+ pub error: String,+}++impl DialectRegistry {+ pub fn new() -> Self {+ Self { descriptors: RwLock::new(HashMap::new()), plugin_dirs: RwLock::new(Vec::new()) }+ }++ pub fn global() -> &'static Self {+ use std::sync::OnceLock;+ static INSTANCE: OnceLock<DialectRegistry> = OnceLock::new();+ INSTANCE.get_or_init(DialectRegistry::new)+ }++ pub fn add_plugin_dir(&self, dir: PathBuf) {+ if let Ok(mut dirs) = self.plugin_dirs.write() {+ if !dirs.contains(&dir) {+ dirs.push(dir);+ }+ }+ }++ pub fn get(&self, name: &str) -> Option<LoadedDialect> {+ self.descriptors.read().ok().and_then(|d| d.get(&name.to_ascii_lowercase()).cloned())+ }++ pub fn get_by_kind(&self, kind: DialectKind) -> Option<LoadedDialect> {+ self.descriptors.read().ok().and_then(|d| d.values().find(|ld| ld.kind == kind).cloned())+ }++ /// Return all loaded dialects that map to the given kind.+ /// Unlike `get_by_kind` (which returns only the first match), this is+ /// order-independent and is used when a type's capabilities must be+ /// resolved across an entire dialect family (e.g. PostgreSQL, HighGo,+ /// KingBase all share `DialectKind::Postgres`).+ pub fn get_all_by_kind(&self, kind: DialectKind) -> Vec<LoadedDialect> {+ self.descriptors+ .read()+ .ok()+ .map(|d| d.values().filter(|ld| ld.kind == kind).cloned().collect())+ .unwrap_or_default()+ }++ pub fn get_descriptor(&self, name: &str) -> Option<DialectCapabilityDescriptor> {+ self.get(name).map(|ld| ld.descriptor)+ }++ pub fn get_descriptor_for_db(+ &self,+ db_type: crate::models::connection::DatabaseType,+ ) -> Option<DialectCapabilityDescriptor> {+ let kind = DialectKind::from_database_type(db_type);+ let label = kind.label();+ let db_name = format!("{db_type:?}").to_ascii_lowercase();+ self.get(&db_name).or_else(|| self.get(label)).map(|ld| ld.descriptor)+ }++ pub fn get_yaml(&self, name: &str) -> Option<DialectYaml> {+ self.get(name).map(|ld| ld.yaml)+ }++ pub fn has(&self, name: &str) -> bool {+ self.descriptors.read().ok().is_some_and(|d| d.contains_key(&name.to_ascii_lowercase()))+ }++ pub fn all_names(&self) -> Vec<String> {+ self.descriptors.read().ok().map(|d| d.keys().cloned().collect()).unwrap_or_default()+ }++ pub fn all_descriptors(&self) -> Vec<DialectCapabilityDescriptor> {+ self.descriptors.read().ok().map(|d| d.values().map(|ld| ld.descriptor).collect()).unwrap_or_default()+ }++ pub fn register(+ &self,+ name: &str,+ kind: DialectKind,+ descriptor: DialectCapabilityDescriptor,+ yaml: DialectYaml,+ source_path: Option<PathBuf>,+ ) {+ if let Ok(mut d) = self.descriptors.write() {+ d.insert(+ name.to_ascii_lowercase(),+ LoadedDialect {+ dialect_name: name.to_string(),+ kind,+ descriptor,+ yaml,+ source_path,+ loaded_at: chrono::Utc::now().to_rfc3339(),+ },+ );+ }+ }++ pub fn register_yaml(&self, path: &Path, yaml: DialectYaml, descriptor: DialectCapabilityDescriptor) {+ let kind = descriptor.dialect;+ let name = yaml.dialect.name.clone();+ self.register(&name, kind, descriptor, yaml, Some(path.to_path_buf()));+ }++ pub fn register_descriptor(&self, name: &str, descriptor: DialectCapabilityDescriptor, yaml: DialectYaml) {+ let kind = descriptor.dialect;+ self.register(name, kind, descriptor, yaml, None);+ }++ pub fn unregister(&self, name: &str) -> bool {+ self.descriptors.write().ok().is_some_and(|mut d| d.remove(&name.to_ascii_lowercase()).is_some())+ }++ pub fn is_empty(&self) -> bool {+ self.descriptors.read().ok().is_none_or(|d| d.is_empty())+ }++ pub fn len(&self) -> usize {+ self.descriptors.read().ok().map_or(0, |d| d.len())+ }+}++impl Default for DialectRegistry {+ fn default() -> Self {+ Self::new()+ }+}++/// Register all core dialect YAML definitions embedded at compile time.+/// Called once at startup by `lazy_init()`.+pub fn register_core_dialects() {+ use std::sync::Once;+ static INIT: Once = Once::new();+ INIT.call_once(|| {+ let registry = DialectRegistry::global();+ include!(concat!(env!("OUT_DIR"), "/core_dialects.rs"));+ let n = registry.len();+ log::info!("Registered {n} core dialects");+ });+}++// ============================================================================+// DialectPluginLoader — scans plugin directories and loads YAML files+// ============================================================================++pub struct DialectPluginLoader;++#[derive(Debug)]+pub struct LoadResult {+ pub loaded: Vec<DialectKind>,+ pub errors: Vec<LoadError>,+ pub skipped: Vec<PathBuf>,+}++impl DialectPluginLoader {+ pub fn scan_and_load(registry: &DialectRegistry, plugin_dirs: &[PathBuf]) -> LoadResult {+ let mut result = LoadResult { loaded: Vec::new(), errors: Vec::new(), skipped: Vec::new() };++ for dir in plugin_dirs {+ if !dir.exists() {+ continue;+ }++ let entries = match fs::read_dir(dir) {+ Ok(entries) => entries,+ Err(e) => {+ result.errors.push(LoadError { path: dir.clone(), error: format!("Cannot read directory: {e}") });+ continue;+ }+ };++ for entry in entries {+ let entry = match entry {+ Ok(e) => e,+ Err(_) => continue,+ };++ let path = entry.path();+ if !path.is_file() {+ continue;+ }++ let file_name = path.file_stem().and_then(|s| s.to_str()).unwrap_or("");+ let extension = path.extension().and_then(|s| s.to_str()).unwrap_or("");++ if !matches!(extension, "yaml" | "yml") {+ continue;+ }++ match Self::load_file(&path) {+ Ok((kind, yaml, descriptor)) => {+ registry.register(file_name, kind, descriptor, yaml, Some(path.clone()));+ result.loaded.push(kind);+ }+ Err(e) => {+ result.errors.push(LoadError { path: path.clone(), error: e });+ }+ }+ }+ }++ result+ }++ pub fn load_file(path: &Path) -> Result<(DialectKind, DialectYaml, DialectCapabilityDescriptor), String> {+ let content = fs::read_to_string(path).map_err(|e| format!("Cannot read file: {e}"))?;+ Self::load_from_string(&content, Some(path))+ }++ pub fn load_from_string(+ yaml_str: &str,+ source_path: Option<&Path>,+ ) -> Result<(DialectKind, DialectYaml, DialectCapabilityDescriptor), String> {+ let parsed: DialectYaml = serde_yaml::from_str(yaml_str).map_err(|e| format!("YAML parse error: {e}"))?;++ let kind = parsed.dialect_kind().ok_or_else(|| {+ format!(+ "Unknown dialect name '{}' in {}",+ parsed.dialect.name,+ source_path.map_or_else(|| "<string>".to_string(), |p| p.display().to_string())+ )+ })?;++ let validation_errors = parsed.validate();+ if !validation_errors.is_empty() {+ let msgs: Vec<String> = validation_errors.iter().map(|e| e.to_string()).collect();+ return Err(format!("Validation errors: {}", msgs.join("; ")));+ }++ let descriptor = parsed.to_descriptor(kind);+ Ok((kind, parsed, descriptor))+ }++ pub fn load_directory(registry: &DialectRegistry, dir: &Path) -> LoadResult {+ Self::scan_and_load(registry, &[dir.to_path_buf()])+ }+}++// ============================================================================+// Fallback: use hardcoded descriptors when YAML is unavailable+// ============================================================================++pub fn resolve_descriptor(kind: DialectKind, registry: &DialectRegistry) -> DialectCapabilityDescriptor {+ if let Some(desc) = registry.get_descriptor(kind.label()) {+ return desc;+ }+ DialectCapabilityDescriptor::for_dialect(kind)+}++pub fn resolve_descriptor_for_db(+ db_type: crate::models::connection::DatabaseType,+ registry: &DialectRegistry,+) -> DialectCapabilityDescriptor {+ if let Some(desc) = registry.get_descriptor_for_db(db_type) {+ return desc;+ }+ let kind = DialectKind::from_database_type(db_type);+ DialectCapabilityDescriptor::for_dialect(kind)+}++// ============================================================================+// Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ fn temp_dialect_dir() -> PathBuf {+ let stamp = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos();+ let dir = std::env::temp_dir().join(format!("dbx-dialect-test-{}-{stamp}", std::process::id()));+ fs::create_dir_all(&dir).unwrap();+ dir+ }++ fn write_temp_yaml(dir: &Path, name: &str, dialect_name: &str) -> PathBuf {+ let file_path = dir.join(name);+ let yaml_content = format!(+ r#"+dialect:+ name: "{dialect_name}"+ versions:+ - version: "1.0"+identifier_rules:+ quote_char: "\""+ max_length: 64+"#+ );+ let mut file = fs::File::create(&file_path).unwrap();+ file.write_all(yaml_content.as_bytes()).unwrap();+ file_path+ }++ fn cleanup_temp_dir(dir: &Path) {+ let _ = fs::remove_dir_all(dir);+ }++ #[test]+ fn load_valid_yaml_file() {+ let dir = temp_dialect_dir();+ let path = write_temp_yaml(&dir, "dialect_postgresql.yaml", "PostgreSQL");+ let result = DialectPluginLoader::load_file(&path);+ cleanup_temp_dir(&dir);+ assert!(result.is_ok());+ let (kind, _yaml, desc) = result.unwrap();+ assert_eq!(kind, DialectKind::Postgres);+ assert_eq!(desc.dialect, DialectKind::Postgres);+ }++ #[test]+ fn load_valid_yaml_file_mysql() {+ let dir = temp_dialect_dir();+ let path = write_temp_yaml(&dir, "dialect_mysql.yaml", "MySQL");+ let result = DialectPluginLoader::load_file(&path);+ cleanup_temp_dir(&dir);+ assert!(result.is_ok());+ let (kind, _, _) = result.unwrap();+ assert_eq!(kind, DialectKind::Mysql);+ }++ #[test]+ fn load_invalid_dialect_name() {+ let dir = temp_dialect_dir();+ let path = write_temp_yaml(&dir, "dialect_unknown.yaml", "UnknownDB");+ let result = DialectPluginLoader::load_file(&path);+ cleanup_temp_dir(&dir);+ assert!(result.is_err());+ }++ #[test]+ fn load_invalid_yaml_syntax() {+ let dir = temp_dialect_dir();+ let path = dir.join("dialect_bad.yaml");+ let mut file = fs::File::create(&path).unwrap();+ file.write_all(b"dialect: [invalid: yaml: syntax:").unwrap();+ let result = DialectPluginLoader::load_file(&path);+ cleanup_temp_dir(&dir);+ assert!(result.is_err());+ }++ #[test]+ fn registry_register_and_get() {+ let registry = DialectRegistry::new();+ assert!(registry.is_empty());++ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Mysql);+ let yaml = DialectYaml {+ dialect: super::super::dialect_yaml::DialectMeta {+ name: "MySQL".to_string(),+ display_name: Some("MySQL".to_string()),+ versions: vec![],+ },+ identifier_rules: super::super::dialect_yaml::IdentifierRules {+ quote_char: "`".to_string(),+ case_sensitive: false,+ max_length: 64,+ },+ ..Default::default()+ };++ registry.register_descriptor("MySQL", desc, yaml);+ assert_eq!(registry.len(), 1);+ assert!(registry.has("MySQL"));+ assert!(!registry.has("PostgreSQL"));++ let loaded = registry.get("MySQL").unwrap();+ assert_eq!(loaded.dialect_name, "MySQL");++ registry.unregister("MySQL");+ assert!(registry.is_empty());+ }++ #[test]+ fn registry_fallback_resolve() {+ let registry = DialectRegistry::new();+ let desc = resolve_descriptor(DialectKind::Mysql, ®istry);+ assert!(desc.has_capability(super::super::descriptor::CAP_ADD_COLUMN));+ }++ #[test]+ fn registry_all_kinds() {+ let registry = DialectRegistry::new();+ let desc = DialectCapabilityDescriptor::for_dialect(DialectKind::Mysql);+ let yaml = DialectYaml {+ dialect: super::super::dialect_yaml::DialectMeta {+ name: "MySQL".to_string(),+ display_name: None,+ versions: vec![],+ },+ identifier_rules: super::super::dialect_yaml::IdentifierRules {+ quote_char: "`".to_string(),+ case_sensitive: false,+ max_length: 64,+ },+ ..Default::default()+ };++ registry.register_descriptor("MySQL", desc, yaml);+ let names = registry.all_names();+ assert_eq!(names, vec!["mysql"]);+ }+}diff --git a/crates/dbx-core/src/sql_dialect/dialect_types.rs b/crates/dbx-core/src/sql_dialect/dialect_types.rsnew file mode 100644index 0000000000..22b277f03b--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/dialect_types.rs@@ -0,0 +1,134 @@+use crate::sql_dialect::descriptor::DialectKind;+use crate::sql_dialect::dialect_loader::DialectRegistry;++pub fn list_dialect_type_names(dialect_name: &str) -> Vec<String> {+ super::lazy_init();+ list_dialect_type_names_in(dialect_name, DialectRegistry::global())+}++fn list_dialect_type_names_in(dialect_name: &str, registry: &DialectRegistry) -> Vec<String> {+ if let Some(loaded) = registry.get(dialect_name) {+ return loaded.yaml.types.iter().map(|t| t.name.clone()).collect();+ }++ // Public callers may use stable dialect labels such as `postgres`,+ // while the embedded catalog keeps the product name `PostgreSQL`.+ if let Some(kind) = DialectKind::from_label(dialect_name) {+ if let Some(loaded) = registry.get(core_catalog_name(kind)) {+ return loaded.yaml.types.iter().map(|t| t.name.clone()).collect();+ }+ // Last-resort fallback: any dialect in the same family+ if let Some(loaded) = registry.get_by_kind(kind) {+ return loaded.yaml.types.iter().map(|t| t.name.clone()).collect();+ }+ }++ Vec::new()+}++fn core_catalog_name(kind: DialectKind) -> &'static str {+ match kind {+ DialectKind::Mysql => "MySQL",+ DialectKind::Postgres => "PostgreSQL",+ DialectKind::Sqlite => "SQLite",+ DialectKind::DuckDb => "DuckDB",+ DialectKind::SqlServer => "SQL Server",+ DialectKind::Oracle => "Oracle",+ DialectKind::H2 => "H2",+ DialectKind::ClickHouse => "ClickHouse",+ DialectKind::ManticoreSearch => "ManticoreSearch",+ DialectKind::Informix => "Informix",+ DialectKind::Questdb => "QuestDB",+ DialectKind::Unsupported => "Unsupported",+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::sql_dialect::descriptor::DialectCapabilityDescriptor;+ use crate::sql_dialect::dialect_yaml::{DialectMeta, DialectType, DialectVersion, DialectYaml, IdentifierRules};++ fn make_registry_with_types(dialect_name: &str, type_names: &[&str]) -> DialectRegistry {+ let registry = DialectRegistry::new();+ let types: Vec<DialectType> = type_names+ .iter()+ .map(|&name| DialectType {+ name: name.to_string(),+ category: "STRING".to_string(),+ max_precision: None,+ precision_range: None,+ has_length: false,+ has_precision: false,+ aliases: vec![],+ semantic_fidelity_base: 1.0,+ })+ .collect();++ let yaml = DialectYaml {+ dialect: DialectMeta {+ name: dialect_name.to_string(),+ display_name: Some(dialect_name.to_string()),+ versions: vec![DialectVersion { version: "1.0".to_string(), status: "COMPATIBLE".to_string() }],+ },+ types,+ identifier_rules: IdentifierRules { quote_char: "\"".to_string(), case_sensitive: false, max_length: 64 },+ ..Default::default()+ };++ let kind = yaml.dialect_kind().unwrap();+ let descriptor = DialectCapabilityDescriptor::for_dialect(kind);+ registry.register_descriptor(dialect_name, descriptor, yaml);+ registry+ }++ #[test]+ fn list_mysql_types() {+ let registry = make_registry_with_types("MySQL", &["VARCHAR", "INT", "BIGINT"]);+ let types = list_dialect_type_names_in("MySQL", ®istry);+ assert_eq!(types, vec!["VARCHAR", "INT", "BIGINT"]);+ assert!(types.contains(&"VARCHAR".to_string()));+ }++ #[test]+ fn list_dameng_types() {+ let registry = make_registry_with_types(+ "Dameng",+ &[+ "VARCHAR",+ "VARCHAR2",+ "INT",+ "INTEGER",+ "BIGINT",+ "FLOAT",+ "DOUBLE",+ "DATE",+ "TIMESTAMP",+ "CLOB",+ "BLOB",+ "TEXT",+ ],+ );+ let types = list_dialect_type_names_in("Dameng", ®istry);+ assert!(!types.is_empty(), "Dameng should have types");+ assert!(types.contains(&"VARCHAR2".to_string()));+ assert_eq!(types.len(), 12);+ }++ #[test]+ fn list_unknown_dialect_returns_empty() {+ let registry = DialectRegistry::new();+ let types = list_dialect_type_names_in("nonexistent_db", ®istry);+ assert!(types.is_empty());+ }++ #[test]+ fn lists_embedded_postgres_types_by_name_and_label() {+ let by_name = list_dialect_type_names("PostgreSQL");+ let by_label = list_dialect_type_names("postgres");++ assert!(!by_name.is_empty());+ assert_eq!(by_label, by_name);+ assert!(by_name.contains(&"SMALLINT".to_string()));+ }+}diff --git a/crates/dbx-core/src/sql_dialect/dialect_yaml.rs b/crates/dbx-core/src/sql_dialect/dialect_yaml.rsnew file mode 100644index 0000000000..fa556b2966--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/dialect_yaml.rs@@ -0,0 +1,1344 @@+use serde::{Deserialize, Serialize};++use super::descriptor::{+ DialectCapabilityDescriptor, DialectKind, CAP_ADD_COLUMN, CAP_ALTER_EXISTING_COLUMN, CAP_ALTER_OWNER,+ CAP_ALTER_PRIMARY_KEY, CAP_AUTO_INCREMENT, CAP_COMMENT, CAP_CREATE_FUNCTION, CAP_CREATE_INDEX,+ CAP_CREATE_OR_REPLACE, CAP_CREATE_SEQUENCE, CAP_CREATE_TABLE, CAP_CREATE_TRIGGER, CAP_DROP_COLUMN,+ CAP_DROP_FUNCTION, CAP_DROP_INDEX, CAP_DROP_SEQUENCE, CAP_DROP_TABLE, CAP_DROP_TRIGGER, CAP_FOREIGN_KEY,+ CAP_GRANT_REVOKE, CAP_IDENTITY_COLUMNS, CAP_IF_NOT_EXISTS, CAP_INDEX_COMMENT, CAP_INDEX_FILTER, CAP_INDEX_INCLUDE,+ CAP_INDEX_TYPE, CAP_REBUILD_INDEX, CAP_RENAME_COLUMN, CAP_REORDER_COLUMN, CAP_TEMPORARY_TABLE,+ CAP_TRANSACTIONAL_DDL, CAP_TRUNCATE_TABLE,+};++// ============================================================================+// YAML Dialect Descriptor — complete Schema matching V4 design §3.1.1+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct DialectYaml {+ pub dialect: DialectMeta,+ #[serde(default)]+ pub types: Vec<DialectType>,+ #[serde(default)]+ pub ddl_capabilities: DdlCapabilitiesYaml,+ #[serde(default)]+ pub structural_capabilities: StructuralCapabilitiesYaml,+ #[serde(default)]+ pub rollback_templates: RollbackTemplatesYaml,+ #[serde(default)]+ pub online_safety: OnlineSafetyYaml,+ #[serde(default)]+ pub destruction_level: DestructionLevelsYaml,+ pub identifier_rules: IdentifierRules,+ #[serde(default)]+ pub metadata_queries: MetadataQueriesYaml,+ #[serde(default)]+ pub pre_execution_checks: Vec<PreExecutionCheck>,+ #[serde(default)]+ pub version_conditions: VersionConditionsYaml,+ #[serde(default)]+ pub script_templates: ScriptTemplatesYaml,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct DialectMeta {+ pub name: String,+ #[serde(default)]+ pub display_name: Option<String>,+ #[serde(default)]+ pub versions: Vec<DialectVersion>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DialectVersion {+ pub version: String,+ #[serde(default = "default_version_status")]+ pub status: String,+}++fn default_version_status() -> String {+ "COMPATIBLE".to_string()+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DialectType {+ pub name: String,+ pub category: String,+ #[serde(default)]+ pub max_precision: Option<u32>,+ #[serde(default)]+ pub precision_range: Option<[i64; 2]>,+ #[serde(default)]+ pub has_length: bool,+ #[serde(default)]+ pub has_precision: bool,+ #[serde(default)]+ pub aliases: Vec<String>,+ #[serde(default = "default_fidelity")]+ pub semantic_fidelity_base: f64,+}++fn default_fidelity() -> f64 {+ 1.0+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DdlCapabilitiesYaml {+ #[serde(default = "default_true")]+ pub add_column: bool,+ #[serde(default = "default_true")]+ pub drop_column: bool,+ #[serde(default)]+ pub rename_column: bool,+ #[serde(default)]+ pub alter_column_type: bool,+ #[serde(default)]+ pub reorder_column: bool,+ #[serde(default)]+ pub comment: bool,+ #[serde(default = "default_true")]+ pub create_index: bool,+ #[serde(default = "default_true")]+ pub drop_index: bool,+ #[serde(default)]+ pub rebuild_index: bool,+ #[serde(default)]+ pub index_type: bool,+ #[serde(default)]+ pub index_include: bool,+ #[serde(default)]+ pub index_filter: bool,+ #[serde(default)]+ pub index_comment: bool,+ #[serde(default)]+ pub alter_primary_key: bool,+ #[serde(default)]+ pub foreign_key: bool,+ #[serde(default = "default_true")]+ pub create_table: bool,+ #[serde(default = "default_true")]+ pub drop_table: bool,+ #[serde(default)]+ pub truncate_table: bool,+ #[serde(default)]+ pub create_trigger: bool,+ #[serde(default)]+ pub drop_trigger: bool,+ #[serde(default)]+ pub create_function: bool,+ #[serde(default)]+ pub drop_function: bool,+ #[serde(default)]+ pub create_sequence: bool,+ #[serde(default)]+ pub drop_sequence: bool,+ #[serde(default)]+ pub alter_owner: bool,+ #[serde(default)]+ pub grant_revoke: bool,+ #[serde(default)]+ pub if_not_exists: bool,+ #[serde(default)]+ pub create_or_replace: bool,+ #[serde(default)]+ pub temporary_table: bool,+ #[serde(default)]+ pub transactional_ddl: bool,+ #[serde(default)]+ pub auto_increment: bool,+ #[serde(default)]+ pub identity_columns: bool,+ #[serde(default)]+ pub templates: DdlTemplatesYaml,+}++impl Default for DdlCapabilitiesYaml {+ fn default() -> Self {+ Self {+ add_column: true,+ drop_column: true,+ rename_column: false,+ alter_column_type: false,+ reorder_column: false,+ comment: false,+ create_index: true,+ drop_index: true,+ rebuild_index: false,+ index_type: false,+ index_include: false,+ index_filter: false,+ index_comment: false,+ alter_primary_key: false,+ foreign_key: false,+ create_table: true,+ drop_table: true,+ truncate_table: false,+ create_trigger: false,+ drop_trigger: false,+ create_function: false,+ drop_function: false,+ create_sequence: false,+ drop_sequence: false,+ alter_owner: false,+ grant_revoke: false,+ if_not_exists: false,+ create_or_replace: false,+ temporary_table: false,+ transactional_ddl: false,+ auto_increment: false,+ identity_columns: false,+ templates: DdlTemplatesYaml::default(),+ }+ }+}++fn default_true() -> bool {+ true+}++impl DdlCapabilitiesYaml {+ fn apply_descriptor_flags(&mut self, flags: u64) {+ self.add_column = flags & CAP_ADD_COLUMN != 0;+ self.drop_column = flags & CAP_DROP_COLUMN != 0;+ self.rename_column = flags & CAP_RENAME_COLUMN != 0;+ self.alter_column_type = flags & CAP_ALTER_EXISTING_COLUMN != 0;+ self.reorder_column = flags & CAP_REORDER_COLUMN != 0;+ self.comment = flags & CAP_COMMENT != 0;+ self.create_index = flags & CAP_CREATE_INDEX != 0;+ self.drop_index = flags & CAP_DROP_INDEX != 0;+ self.rebuild_index = flags & CAP_REBUILD_INDEX != 0;+ self.index_type = flags & CAP_INDEX_TYPE != 0;+ self.index_include = flags & CAP_INDEX_INCLUDE != 0;+ self.index_filter = flags & CAP_INDEX_FILTER != 0;+ self.index_comment = flags & CAP_INDEX_COMMENT != 0;+ self.alter_primary_key = flags & CAP_ALTER_PRIMARY_KEY != 0;+ self.foreign_key = flags & CAP_FOREIGN_KEY != 0;+ self.create_table = flags & CAP_CREATE_TABLE != 0;+ self.drop_table = flags & CAP_DROP_TABLE != 0;+ self.truncate_table = flags & CAP_TRUNCATE_TABLE != 0;+ self.create_trigger = flags & CAP_CREATE_TRIGGER != 0;+ self.drop_trigger = flags & CAP_DROP_TRIGGER != 0;+ self.create_function = flags & CAP_CREATE_FUNCTION != 0;+ self.drop_function = flags & CAP_DROP_FUNCTION != 0;+ self.create_sequence = flags & CAP_CREATE_SEQUENCE != 0;+ self.drop_sequence = flags & CAP_DROP_SEQUENCE != 0;+ self.alter_owner = flags & CAP_ALTER_OWNER != 0;+ self.grant_revoke = flags & CAP_GRANT_REVOKE != 0;+ self.if_not_exists = flags & CAP_IF_NOT_EXISTS != 0;+ self.create_or_replace = flags & CAP_CREATE_OR_REPLACE != 0;+ self.temporary_table = flags & CAP_TEMPORARY_TABLE != 0;+ self.transactional_ddl = flags & CAP_TRANSACTIONAL_DDL != 0;+ self.auto_increment = flags & CAP_AUTO_INCREMENT != 0;+ self.identity_columns = flags & CAP_IDENTITY_COLUMNS != 0;+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct DdlTemplatesYaml {+ #[serde(default)]+ pub add_column: String,+ #[serde(default)]+ pub drop_column: String,+ #[serde(default)]+ pub rename_column: String,+ #[serde(default)]+ pub modify_column: String,+ #[serde(default)]+ pub create_table: String,+ #[serde(default)]+ pub drop_table: String,+ #[serde(default)]+ pub create_index: String,+ #[serde(default)]+ pub drop_index: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct RollbackTemplatesYaml {+ #[serde(default)]+ pub add_column: String,+ #[serde(default)]+ pub drop_column: String,+ #[serde(default)]+ pub rename_column: String,+ #[serde(default)]+ pub modify_column: String,+ #[serde(default)]+ pub create_table: String,+ #[serde(default)]+ pub drop_table: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct OnlineSafetyYaml {+ #[serde(default)]+ pub add_column: SafetyEntry,+ #[serde(default)]+ pub modify_column: SafetyEntry,+ #[serde(default)]+ pub drop_column: SafetyEntry,+ #[serde(default)]+ pub drop_table: SafetyEntry,+ #[serde(default)]+ pub truncate: SafetyEntry,+ #[serde(default)]+ pub create_index: SafetyEntry,+ #[serde(default)]+ pub drop_index: SafetyEntry,+ pub osc_template: Option<OscTemplateYaml>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SafetyEntry {+ #[serde(default = "default_blocking_short")]+ pub level: String,+ #[serde(default = "default_cost_medium")]+ pub cost: String,+}++fn default_blocking_short() -> String {+ "BLOCKING_SHORT".to_string()+}++fn default_cost_medium() -> String {+ "MEDIUM".to_string()+}++impl Default for SafetyEntry {+ fn default() -> Self {+ Self { level: "NON_BLOCKING".to_string(), cost: "LOW".to_string() }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct OscTemplateYaml {+ #[serde(default)]+ pub gh_ost: String,+ #[serde(default)]+ pub pt_osc: String,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct DestructionLevelsYaml {+ #[serde(default = "default_fatal")]+ pub drop_table: String,+ #[serde(default = "default_fatal")]+ pub drop_schema: String,+ #[serde(default = "default_dangerous")]+ pub truncate: String,+ #[serde(default = "default_dangerous")]+ pub drop_column: String,+ #[serde(default = "default_modify")]+ pub alter_type: String,+ #[serde(default = "default_safe")]+ pub add_column: String,+ #[serde(default = "default_safe")]+ pub create_table: String,+}++fn default_fatal() -> String {+ "FATAL".to_string()+}+fn default_dangerous() -> String {+ "DANGEROUS".to_string()+}+fn default_modify() -> String {+ "MODIFY".to_string()+}+fn default_safe() -> String {+ "SAFE".to_string()+}++/// Structural/behavioral dialect properties (replaces hardcoded per-kind inference in to_descriptor).+#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct StructuralCapabilitiesYaml {+ #[serde(default)]+ pub supports_schemas: bool,+ #[serde(default)]+ pub supports_catalogs: bool,+ #[serde(default = "default_max_cols")]+ pub max_columns_per_table: u32,+ #[serde(default = "default_max_idxs")]+ pub max_indexes_per_table: u32,+ #[serde(default = "default_query_bytes")]+ pub max_query_size_bytes: u64,+ #[serde(default)]+ pub supports_full_text_index: bool,+ #[serde(default)]+ pub supports_spatial_index: bool,+ #[serde(default)]+ pub supports_partitioning: bool,+ #[serde(default)]+ pub supports_table_sampling: bool,+ #[serde(default)]+ pub max_foreign_key_name_length: u32,+ #[serde(default)]+ pub supports_on_update_cascade: bool,+ #[serde(default)]+ pub supports_on_delete_set_null: bool,+ #[serde(default)]+ pub supports_deferrable_constraints: bool,+ #[serde(default)]+ pub supports_array_type: bool,+ #[serde(default)]+ pub supports_json_type: bool,+ #[serde(default)]+ pub supports_enum_type: bool,+ #[serde(default)]+ pub supports_uuid_type: bool,+ #[serde(default)]+ pub supports_sequences: bool,+}++fn default_max_cols() -> u32 {+ 1600+}+fn default_max_idxs() -> u32 {+ 100+}+fn default_query_bytes() -> u64 {+ 16 * 1024 * 1024+}++impl Default for StructuralCapabilitiesYaml {+ fn default() -> Self {+ Self {+ supports_schemas: false,+ supports_catalogs: false,+ max_columns_per_table: 1600,+ max_indexes_per_table: 100,+ max_query_size_bytes: 16 * 1024 * 1024,+ supports_full_text_index: false,+ supports_spatial_index: false,+ supports_partitioning: false,+ supports_table_sampling: false,+ max_foreign_key_name_length: 0,+ supports_on_update_cascade: false,+ supports_on_delete_set_null: false,+ supports_deferrable_constraints: false,+ supports_array_type: false,+ supports_json_type: false,+ supports_enum_type: false,+ supports_uuid_type: false,+ supports_sequences: false,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct IdentifierRules {+ pub quote_char: String,+ #[serde(default)]+ pub case_sensitive: bool,+ pub max_length: u32,+}++impl Default for IdentifierRules {+ fn default() -> Self {+ Self { quote_char: "\"".to_string(), case_sensitive: false, max_length: 128 }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct MetadataQueriesYaml {+ #[serde(default)]+ pub list_tables: Option<MetadataQuery>,+ #[serde(default)]+ pub list_columns: Option<MetadataQuery>,+ #[serde(default)]+ pub list_indexes: Option<MetadataQuery>,+ #[serde(default)]+ pub list_foreign_keys: Option<MetadataQuery>,+ #[serde(default)]+ pub list_triggers: Option<MetadataQuery>,+ #[serde(default)]+ pub list_functions: Option<MetadataQuery>,+ #[serde(default)]+ pub list_sequences: Option<MetadataQuery>,+ pub dependencies: Option<DependencyQuery>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct MetadataQuery {+ pub sql: String,+ #[serde(default = "default_light")]+ pub performance_profile: String,+}++fn default_light() -> String {+ "LIGHT".to_string()+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct DependencyQuery {+ pub sql: String,+ #[serde(default)]+ pub depth_support: u32,+ #[serde(default = "default_heavy")]+ pub performance_profile: String,+}++fn default_heavy() -> String {+ "HEAVY".to_string()+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PreExecutionCheck {+ pub name: String,+ pub sql: String,+ #[serde(default)]+ pub threshold: Option<PreExecThreshold>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct PreExecThreshold {+ #[serde(default)]+ pub min_bytes: Option<u64>,+ #[serde(default)]+ pub min_rows: Option<u64>,+}++#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct VersionConditionsYaml {+ #[serde(default)]+ pub add_column_concurrent: Vec<VersionConditionEntry>,+ #[serde(default)]+ pub drop_column_concurrent: Vec<VersionConditionEntry>,+ #[serde(default)]+ pub modify_column_concurrent: Vec<VersionConditionEntry>,+}++/// Script-level Jinja2 template overrides (Phase 14 template dialect migration).+/// When set, these replace the 3 hardcoded template strings in ScriptTemplateEngine.+#[derive(Debug, Clone, Serialize, Deserialize, Default)]+pub struct ScriptTemplatesYaml {+ #[serde(default)]+ pub schema_sync: Option<String>,+ #[serde(default)]+ pub joint_orchestration: Option<String>,+ #[serde(default)]+ pub batch: Option<String>,+ #[serde(default)]+ pub lock_timeout_statement: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct VersionConditionEntry {+ #[serde(default)]+ pub min_version: Option<String>,+ #[serde(default)]+ pub max_version: Option<String>,+ pub template: String,+}++// ============================================================================+// DialectYaml → DialectCapabilityDescriptor conversion+// ============================================================================++impl DialectYaml {+ fn build_capability_flags(caps: &DdlCapabilitiesYaml) -> u64 {+ let mut flags: u64 = 0;+ if caps.add_column {+ flags |= CAP_ADD_COLUMN;+ }+ if caps.drop_column {+ flags |= CAP_DROP_COLUMN;+ }+ if caps.rename_column {+ flags |= CAP_RENAME_COLUMN;+ }+ if caps.alter_column_type {+ flags |= CAP_ALTER_EXISTING_COLUMN;+ }+ if caps.reorder_column {+ flags |= CAP_REORDER_COLUMN;+ }+ if caps.comment {+ flags |= CAP_COMMENT;+ }+ if caps.create_index {+ flags |= CAP_CREATE_INDEX;+ }+ if caps.drop_index {+ flags |= CAP_DROP_INDEX;+ }+ if caps.rebuild_index {+ flags |= CAP_REBUILD_INDEX;+ }+ if caps.index_type {+ flags |= CAP_INDEX_TYPE;+ }+ if caps.index_include {+ flags |= CAP_INDEX_INCLUDE;+ }+ if caps.index_filter {+ flags |= CAP_INDEX_FILTER;+ }+ if caps.index_comment {+ flags |= CAP_INDEX_COMMENT;+ }+ if caps.alter_primary_key {+ flags |= CAP_ALTER_PRIMARY_KEY;+ }+ if caps.foreign_key {+ flags |= CAP_FOREIGN_KEY;+ }+ if caps.create_table {+ flags |= CAP_CREATE_TABLE;+ }+ if caps.drop_table {+ flags |= CAP_DROP_TABLE;+ }+ if caps.truncate_table {+ flags |= CAP_TRUNCATE_TABLE;+ }+ if caps.create_trigger {+ flags |= CAP_CREATE_TRIGGER;+ }+ if caps.drop_trigger {+ flags |= CAP_DROP_TRIGGER;+ }+ if caps.create_function {+ flags |= CAP_CREATE_FUNCTION;+ }+ if caps.drop_function {+ flags |= CAP_DROP_FUNCTION;+ }+ if caps.create_sequence {+ flags |= CAP_CREATE_SEQUENCE;+ }+ if caps.drop_sequence {+ flags |= CAP_DROP_SEQUENCE;+ }+ if caps.alter_owner {+ flags |= CAP_ALTER_OWNER;+ }+ if caps.grant_revoke {+ flags |= CAP_GRANT_REVOKE;+ }+ if caps.if_not_exists {+ flags |= CAP_IF_NOT_EXISTS;+ }+ if caps.create_or_replace {+ flags |= CAP_CREATE_OR_REPLACE;+ }+ if caps.temporary_table {+ flags |= CAP_TEMPORARY_TABLE;+ }+ if caps.transactional_ddl {+ flags |= CAP_TRANSACTIONAL_DDL;+ }+ if caps.auto_increment {+ flags |= CAP_AUTO_INCREMENT;+ }+ if caps.identity_columns {+ flags |= CAP_IDENTITY_COLUMNS;+ }+ flags+ }++ pub fn to_descriptor(&self, kind: DialectKind) -> DialectCapabilityDescriptor {+ let flags = Self::build_capability_flags(&self.ddl_capabilities);+ let id = &self.identifier_rules;+ let sc = &self.structural_capabilities;++ DialectCapabilityDescriptor {+ dialect: kind,+ flags,+ max_identifier_length: id.max_length,+ supports_schemas: sc.supports_schemas,+ supports_catalogs: sc.supports_catalogs,+ max_columns_per_table: sc.max_columns_per_table,+ max_indexes_per_table: sc.max_indexes_per_table,+ max_query_size_bytes: sc.max_query_size_bytes,+ supports_full_text_index: sc.supports_full_text_index,+ supports_spatial_index: sc.supports_spatial_index,+ supports_partitioning: sc.supports_partitioning,+ supports_table_sampling: sc.supports_table_sampling,+ max_foreign_key_name_length: if sc.max_foreign_key_name_length > 0 {+ sc.max_foreign_key_name_length+ } else {+ id.max_length+ },+ supports_on_update_cascade: sc.supports_on_update_cascade,+ supports_on_delete_set_null: sc.supports_on_delete_set_null,+ supports_deferrable_constraints: sc.supports_deferrable_constraints,+ supports_array_type: sc.supports_array_type,+ supports_json_type: sc.supports_json_type,+ supports_enum_type: sc.supports_enum_type,+ supports_uuid_type: sc.supports_uuid_type,+ supports_identity_columns: flags & CAP_IDENTITY_COLUMNS != 0,+ supports_auto_increment: flags & CAP_AUTO_INCREMENT != 0,+ supports_sequences: sc.supports_sequences,+ }+ }++ pub fn dialect_kind(&self) -> Option<DialectKind> {+ DialectKind::from_label(&self.dialect.name)+ }++ pub fn to_yaml_string(&self) -> Result<String, String> {+ serde_yaml::to_string(self).map_err(|e| format!("YAML serialization error: {e}"))+ }++ pub fn from_descriptor(kind: DialectKind) -> Self {+ let desc = DialectCapabilityDescriptor::for_dialect(kind);+ Self::from_descriptor_with_caps(kind, &desc)+ }++ pub fn from_descriptor_with_caps(kind: DialectKind, desc: &DialectCapabilityDescriptor) -> Self {+ let (versions, mut ddl_caps) = match kind {+ DialectKind::Mysql => (+ vec![+ DialectVersion { version: "8.0".to_string(), status: "RECOMMENDED".to_string() },+ DialectVersion { version: "5.7".to_string(), status: "COMPATIBLE".to_string() },+ ],+ DdlCapabilitiesYaml {+ add_column: true,+ drop_column: true,+ rename_column: true,+ alter_column_type: true,+ reorder_column: true,+ comment: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ index_type: true,+ index_comment: true,+ alter_primary_key: true,+ foreign_key: true,+ truncate_table: true,+ create_trigger: true,+ drop_trigger: true,+ create_function: true,+ drop_function: true,+ create_sequence: true,+ drop_sequence: true,+ alter_owner: true,+ grant_revoke: true,+ if_not_exists: true,+ temporary_table: true,+ auto_increment: true,+ ..Default::default()+ },+ ),+ DialectKind::Postgres => (+ vec![+ DialectVersion { version: "16".to_string(), status: "RECOMMENDED".to_string() },+ DialectVersion { version: "15".to_string(), status: "COMPATIBLE".to_string() },+ ],+ DdlCapabilitiesYaml {+ rename_column: true,+ alter_column_type: true,+ comment: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ index_type: true,+ index_include: true,+ index_filter: true,+ index_comment: true,+ alter_primary_key: true,+ foreign_key: true,+ truncate_table: true,+ create_trigger: true,+ drop_trigger: true,+ create_function: true,+ drop_function: true,+ create_sequence: true,+ drop_sequence: true,+ alter_owner: true,+ grant_revoke: true,+ if_not_exists: true,+ create_or_replace: true,+ transactional_ddl: true,+ temporary_table: true,+ identity_columns: true,+ ..Default::default()+ },+ ),+ DialectKind::Sqlite => (+ vec![DialectVersion { version: "3".to_string(), status: "RECOMMENDED".to_string() }],+ DdlCapabilitiesYaml {+ rename_column: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ index_filter: true,+ truncate_table: true,+ create_trigger: true,+ drop_trigger: true,+ create_function: true,+ drop_function: true,+ create_sequence: true,+ drop_sequence: true,+ if_not_exists: true,+ auto_increment: true,+ ..Default::default()+ },+ ),+ DialectKind::DuckDb => (+ vec![DialectVersion { version: "1".to_string(), status: "RECOMMENDED".to_string() }],+ DdlCapabilitiesYaml {+ rename_column: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ truncate_table: true,+ if_not_exists: true,+ create_or_replace: true,+ temporary_table: true,+ ..Default::default()+ },+ ),+ DialectKind::SqlServer => (+ vec![DialectVersion { version: "2022".to_string(), status: "RECOMMENDED".to_string() }],+ DdlCapabilitiesYaml {+ rename_column: true,+ alter_column_type: true,+ comment: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ index_type: true,+ index_include: true,+ index_filter: true,+ index_comment: true,+ truncate_table: true,+ create_trigger: true,+ drop_trigger: true,+ create_function: true,+ drop_function: true,+ create_sequence: true,+ drop_sequence: true,+ alter_owner: true,+ grant_revoke: true,+ if_not_exists: true,+ temporary_table: true,+ transactional_ddl: true,+ identity_columns: true,+ ..Default::default()+ },+ ),+ DialectKind::Oracle => (+ vec![DialectVersion { version: "21c".to_string(), status: "RECOMMENDED".to_string() }],+ DdlCapabilitiesYaml {+ rename_column: true,+ alter_column_type: true,+ comment: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ index_type: true,+ truncate_table: true,+ create_trigger: true,+ drop_trigger: true,+ create_function: true,+ drop_function: true,+ create_sequence: true,+ drop_sequence: true,+ alter_owner: true,+ grant_revoke: true,+ if_not_exists: true,+ temporary_table: true,+ ..Default::default()+ },+ ),+ DialectKind::H2 => (+ vec![DialectVersion { version: "2".to_string(), status: "RECOMMENDED".to_string() }],+ DdlCapabilitiesYaml {+ rename_column: true,+ alter_column_type: true,+ comment: true,+ create_index: true,+ drop_index: true,+ rebuild_index: true,+ truncate_table: true,+ create_trigger: true,+ drop_trigger: true,+ create_function: true,+ drop_function: true,+ if_not_exists: true,+ temporary_table: true,+ identity_columns: true,+ ..Default::default()+ },+ ),+ DialectKind::ClickHouse => (+ vec![DialectVersion { version: "24".to_string(), status: "RECOMMENDED".to_string() }],+ DdlCapabilitiesYaml {+ rename_column: true,+ alter_column_type: true,+ reorder_column: true,+ comment: true,+ truncate_table: true,+ if_not_exists: true,+ temporary_table: true,+ ..Default::default()+ },+ ),+ _ => (+ vec![DialectVersion { version: "1".to_string(), status: "COMPATIBLE".to_string() }],+ DdlCapabilitiesYaml::default(),+ ),+ };++ // Export must preserve the canonical descriptor exactly; the+ // hard-coded blocks above only provide human-friendly templates.+ ddl_caps.apply_descriptor_flags(desc.flags);++ let identifier_rules = match kind {+ DialectKind::Mysql => IdentifierRules {+ quote_char: "`".to_string(),+ case_sensitive: false,+ max_length: desc.max_identifier_length,+ },+ DialectKind::Postgres => IdentifierRules {+ quote_char: "\"".to_string(),+ case_sensitive: true,+ max_length: desc.max_identifier_length,+ },+ DialectKind::Sqlite => IdentifierRules {+ quote_char: "\"".to_string(),+ case_sensitive: false,+ max_length: desc.max_identifier_length,+ },+ DialectKind::SqlServer => IdentifierRules {+ quote_char: "\"".to_string(),+ case_sensitive: false,+ max_length: desc.max_identifier_length,+ },+ DialectKind::Oracle => IdentifierRules {+ quote_char: "\"".to_string(),+ case_sensitive: true,+ max_length: desc.max_identifier_length,+ },+ _ => IdentifierRules { quote_char: "\"".to_string(), case_sensitive: false, max_length: 128 },+ };++ DialectYaml {+ dialect: DialectMeta { name: kind_name(kind), display_name: Some(kind_name(kind)), versions },+ types: vec![],+ ddl_capabilities: ddl_caps,+ structural_capabilities: StructuralCapabilitiesYaml {+ supports_schemas: desc.supports_schemas,+ supports_catalogs: desc.supports_catalogs,+ max_columns_per_table: desc.max_columns_per_table,+ max_indexes_per_table: desc.max_indexes_per_table,+ max_query_size_bytes: desc.max_query_size_bytes,+ supports_full_text_index: desc.supports_full_text_index,+ supports_spatial_index: desc.supports_spatial_index,+ supports_partitioning: desc.supports_partitioning,+ supports_table_sampling: desc.supports_table_sampling,+ max_foreign_key_name_length: desc.max_foreign_key_name_length,+ supports_on_update_cascade: desc.supports_on_update_cascade,+ supports_on_delete_set_null: desc.supports_on_delete_set_null,+ supports_deferrable_constraints: desc.supports_deferrable_constraints,+ supports_array_type: desc.supports_array_type,+ supports_json_type: desc.supports_json_type,+ supports_enum_type: desc.supports_enum_type,+ supports_uuid_type: desc.supports_uuid_type,+ supports_sequences: desc.supports_sequences,+ },+ identifier_rules,+ ..Default::default()+ }+ }+}++fn kind_name(kind: DialectKind) -> String {+ match kind {+ DialectKind::Mysql => "MySQL",+ DialectKind::Postgres => "PostgreSQL",+ DialectKind::Sqlite => "SQLite",+ DialectKind::DuckDb => "DuckDB",+ DialectKind::SqlServer => "SQL Server",+ DialectKind::Oracle => "Oracle",+ DialectKind::H2 => "H2",+ DialectKind::ClickHouse => "ClickHouse",+ DialectKind::ManticoreSearch => "ManticoreSearch",+ DialectKind::Informix => "Informix",+ DialectKind::Questdb => "QuestDB",+ DialectKind::Unsupported => "Unsupported",+ }+ .to_string()+}++// ============================================================================+// Schema validation+// ============================================================================++#[derive(Debug, Clone)]+pub struct YamlValidationError {+ pub field: String,+ pub message: String,+}++impl std::fmt::Display for YamlValidationError {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ write!(f, "{}: {}", self.field, self.message)+ }+}++impl DialectYaml {+ pub fn validate(&self) -> Vec<YamlValidationError> {+ let mut errors = Vec::new();++ if self.dialect.name.is_empty() {+ errors.push(YamlValidationError {+ field: "dialect.name".to_string(),+ message: "dialect name is required".to_string(),+ });+ }++ if self.identifier_rules.max_length == 0 {+ errors.push(YamlValidationError {+ field: "identifier_rules.max_length".to_string(),+ message: "max_length must be > 0".to_string(),+ });+ }++ if self.identifier_rules.quote_char.is_empty() {+ errors.push(YamlValidationError {+ field: "identifier_rules.quote_char".to_string(),+ message: "quote_char is required".to_string(),+ });+ }++ errors+ }++ pub fn is_valid(&self) -> bool {+ self.validate().is_empty()+ }+}++// ============================================================================+// Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_minimal_mysql_yaml() {+ let yaml = r#"+dialect:+ name: "MySQL"+ versions:+ - version: "8.0"+ status: "RECOMMENDED"+identifier_rules:+ quote_char: "`"+ max_length: 64+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ assert_eq!(parsed.dialect.name, "MySQL");+ assert_eq!(parsed.identifier_rules.quote_char, "`");+ assert_eq!(parsed.identifier_rules.max_length, 64);+ assert!(parsed.is_valid());+ }++ #[test]+ fn ddl_capability_default_matches_serde_defaults() {+ let from_default = DdlCapabilitiesYaml::default();+ let from_yaml: DdlCapabilitiesYaml = serde_yaml::from_str("{}").unwrap();++ assert_eq!(DialectYaml::build_capability_flags(&from_default), DialectYaml::build_capability_flags(&from_yaml));+ assert!(from_default.add_column);+ assert!(from_default.drop_column);+ assert!(from_default.create_index);+ assert!(from_default.drop_index);+ assert!(from_default.create_table);+ assert!(from_default.drop_table);+ }++ #[test]+ fn parse_mysql_with_capabilities() {+ let yaml = r#"+dialect:+ name: "MySQL"+ display_name: "MySQL"+ versions:+ - version: "8.0"+ status: "RECOMMENDED"+ - version: "5.7"+ status: "COMPATIBLE"+types:+ - name: "VARCHAR"+ category: "STRING"+ max_precision: 65535+ has_length: true+ aliases: ["CHARACTER VARYING"]+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ reorder_column: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ index_comment: true+ alter_primary_key: true+ foreign_key: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {original_type}"+online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ osc_template:+ gh_ost: "gh-ost --alter='{ddl}' --execute ..."+ pt_osc: "pt-online-schema-change --alter='{ddl}' --execute ..."+destruction_level:+ drop_table: "FATAL"+ drop_column: "DANGEROUS"+ truncate: "DANGEROUS"+identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64+metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}'"+ performance_profile: "LIGHT"+ dependencies:+ sql: "SELECT ..."+ depth_support: 2+ performance_profile: "HEAVY"+pre_execution_checks:+ - name: "tablespace_free"+ sql: "SELECT ..."+ threshold:+ min_bytes: 1073741824+version_conditions:+ add_column_concurrent:+ - min_version: "8.0"+ template: "ALTER TABLE {table} ADD COLUMN {column} {type}, ALGORITHM=INPLACE"+ - max_version: "8.0"+ template: "ALTER TABLE {table} ADD COLUMN {column} {type}"+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ assert_eq!(parsed.dialect.name, "MySQL");+ assert_eq!(parsed.types.len(), 2);+ assert_eq!(parsed.types[0].name, "VARCHAR");+ assert!(parsed.ddl_capabilities.add_column);+ assert!(!parsed.ddl_capabilities.transactional_ddl);+ assert_eq!(parsed.ddl_capabilities.templates.add_column, "ALTER TABLE {table} ADD COLUMN {column} {type}");+ assert_eq!(parsed.online_safety.add_column.level, "BLOCKING_SHORT");+ assert_eq!(parsed.destruction_level.drop_table, "FATAL");+ assert_eq!(parsed.metadata_queries.list_tables.as_ref().unwrap().performance_profile, "LIGHT");+ assert_eq!(parsed.metadata_queries.dependencies.as_ref().unwrap().depth_support, 2);+ assert_eq!(parsed.pre_execution_checks.len(), 1);+ assert_eq!(parsed.version_conditions.add_column_concurrent.len(), 2);+ assert!(parsed.is_valid());+ }++ #[test]+ fn yaml_to_descriptor_mysql() {+ let yaml = r#"+dialect:+ name: "MySQL"+ versions:+ - version: "8.0"+ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ foreign_key: true+ if_not_exists: true+ auto_increment: true+ grant_revoke: true+ comment: true+ alter_owner: true+identifier_rules:+ quote_char: "`"+ max_length: 64+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ let desc = parsed.to_descriptor(DialectKind::Mysql);+ assert!(desc.has_capability(CAP_ADD_COLUMN));+ assert!(desc.has_capability(CAP_RENAME_COLUMN));+ assert!(desc.has_capability(CAP_FOREIGN_KEY));+ assert!(desc.has_capability(CAP_IF_NOT_EXISTS));+ assert!(desc.has_capability(CAP_AUTO_INCREMENT));+ assert!(!desc.has_capability(CAP_TRANSACTIONAL_DDL));+ assert_eq!(desc.max_identifier_length, 64);+ assert!(desc.supports_auto_increment);+ }++ #[test]+ fn yaml_default_capabilities_are_true() {+ let yaml = r#"+dialect:+ name: "Test"+ versions: []+identifier_rules:+ quote_char: "\""+ max_length: 128+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ assert!(parsed.ddl_capabilities.add_column);+ assert!(parsed.ddl_capabilities.drop_column);+ assert!(parsed.ddl_capabilities.create_table);+ assert!(parsed.ddl_capabilities.drop_table);+ assert!(parsed.ddl_capabilities.create_index);+ assert!(parsed.ddl_capabilities.drop_index);+ assert!(!parsed.ddl_capabilities.rename_column);+ assert!(!parsed.ddl_capabilities.alter_column_type);+ }++ #[test]+ fn yaml_validation_missing_name() {+ let yaml = r#"+dialect:+ name: ""+ versions: []+identifier_rules:+ quote_char: "\""+ max_length: 128+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ let errors = parsed.validate();+ assert!(!errors.is_empty());+ assert!(errors.iter().any(|e| e.field == "dialect.name"));+ }++ #[test]+ fn yaml_validation_missing_quote_char() {+ let yaml = r#"+dialect:+ name: "MySQL"+ versions: []+identifier_rules:+ quote_char: ""+ max_length: 64+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ let errors = parsed.validate();+ assert!(!errors.is_empty());+ assert!(errors.iter().any(|e| e.field == "identifier_rules.quote_char"));+ }++ #[test]+ fn yaml_validation_zero_max_length() {+ let yaml = r#"+dialect:+ name: "MySQL"+ versions: []+identifier_rules:+ quote_char: "`"+ max_length: 0+"#;+ let parsed: DialectYaml = serde_yaml::from_str(yaml).unwrap();+ let errors = parsed.validate();+ assert!(!errors.is_empty());+ assert!(errors.iter().any(|e| e.field == "identifier_rules.max_length"));+ }++ #[test]+ fn from_descriptor_mysql_roundtrip() {+ let yaml = DialectYaml::from_descriptor(DialectKind::Mysql);+ assert_eq!(yaml.dialect.name, "MySQL");+ assert!(yaml.ddl_capabilities.add_column);+ assert!(yaml.ddl_capabilities.auto_increment);+ assert!(!yaml.ddl_capabilities.transactional_ddl);+ assert_eq!(yaml.identifier_rules.quote_char, "`");+ assert_eq!(yaml.identifier_rules.max_length, 64);+ }++ #[test]+ fn from_descriptor_postgres_roundtrip() {+ let yaml = DialectYaml::from_descriptor(DialectKind::Postgres);+ assert_eq!(yaml.dialect.name, "PostgreSQL");+ assert!(yaml.ddl_capabilities.add_column);+ assert!(yaml.ddl_capabilities.drop_column);+ assert!(yaml.ddl_capabilities.create_table);+ assert!(yaml.ddl_capabilities.drop_table);+ assert!(yaml.ddl_capabilities.transactional_ddl);+ assert!(yaml.ddl_capabilities.identity_columns);+ assert_eq!(yaml.identifier_rules.quote_char, "\"");+ assert_eq!(yaml.identifier_rules.max_length, 63);+ }++ #[test]+ fn from_descriptor_to_yaml_and_back() {+ for kind in &[+ DialectKind::Mysql,+ DialectKind::Postgres,+ DialectKind::Sqlite,+ DialectKind::DuckDb,+ DialectKind::SqlServer,+ DialectKind::Oracle,+ DialectKind::H2,+ DialectKind::ClickHouse,+ ] {+ let yaml = DialectYaml::from_descriptor(*kind);+ let yaml_str = yaml.to_yaml_string().unwrap();+ let parsed: DialectYaml = serde_yaml::from_str(&yaml_str).unwrap();+ let desc = parsed.to_descriptor(*kind);+ let expected = DialectCapabilityDescriptor::for_dialect(*kind);+ assert_eq!(desc.dialect, *kind);+ assert_eq!(desc.flags, expected.flags, "capabilities changed for {kind:?}");+ }+ }++ #[test]+ fn from_descriptor_all_core_dialects() {+ let kinds = &[+ DialectKind::Mysql,+ DialectKind::Postgres,+ DialectKind::Sqlite,+ DialectKind::DuckDb,+ DialectKind::SqlServer,+ DialectKind::Oracle,+ DialectKind::H2,+ DialectKind::ClickHouse,+ DialectKind::ManticoreSearch,+ DialectKind::Informix,+ DialectKind::Questdb,+ ];+ for kind in kinds {+ let yaml = DialectYaml::from_descriptor(*kind);+ assert!(!yaml.dialect.name.is_empty());+ assert!(!yaml.identifier_rules.quote_char.is_empty());+ assert!(yaml.identifier_rules.max_length > 0);+ }+ }+}diff --git a/crates/dbx-core/src/sql_dialect/hot_reload.rs b/crates/dbx-core/src/sql_dialect/hot_reload.rsnew file mode 100644index 0000000000..20dc48b366--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/hot_reload.rs@@ -0,0 +1,143 @@+use std::path::PathBuf;+use std::time::Duration;++use notify::{Config, Event, EventKind, RecommendedWatcher, RecursiveMode, Watcher};+use tokio::sync::mpsc;++use super::dialect_loader::DialectPluginLoader;++/// Configuration for the hot-reload watcher.+#[derive(Debug, Clone)]+pub struct HotReloadConfig {+ /// Debounce duration — multiple changes within this window are coalesced.+ pub debounce_ms: u64,+ /// Whether to enable polling (needed for some network filesystems).+ pub enable_polling: bool,+ /// Polling interval when polling is enabled.+ pub poll_interval_ms: u64,+}++impl Default for HotReloadConfig {+ fn default() -> Self {+ Self { debounce_ms: 500, enable_polling: false, poll_interval_ms: 2000 }+ }+}++/// Result of a hot-reload operation on a changed file.+#[derive(Debug, Clone)]+pub enum ReloadEvent {+ /// A dialect YAML file was successfully loaded/updated.+ Loaded { path: PathBuf },+ /// A dialect YAML file was removed — dialect unregistered.+ Removed { path: PathBuf, dialect: String },+ /// A file changed but failed to load.+ Error { path: PathBuf, error: String },+}++/// Hot-reload watcher that monitors `plugins/dialects/` for YAML changes+/// and updates the `DialectRegistry` in real time.+pub struct DialectHotReload {+ watcher: Option<RecommendedWatcher>,+ config: HotReloadConfig,+}++impl DialectHotReload {+ pub fn new(config: HotReloadConfig) -> Self {+ Self { watcher: None, config }+ }++ /// Start watching. Returns a channel receiver for reload events.+ pub fn start(&mut self, watch_dirs: Vec<PathBuf>) -> Result<mpsc::UnboundedReceiver<ReloadEvent>, String> {+ let (tx, rx) = mpsc::unbounded_channel();++ let _debounce = Duration::from_millis(self.config.debounce_ms);++ let tx_clone = tx.clone();+ let mut watcher = RecommendedWatcher::new(+ move |res: Result<Event, notify::Error>| match res {+ Ok(event) => {+ if !Self::is_relevant(&event) {+ return;+ }+ for path in &event.paths {+ let _ = tx_clone.send(match event.kind {+ EventKind::Create(_) | EventKind::Modify(_) => ReloadEvent::Loaded { path: path.clone() },+ EventKind::Remove(_) => ReloadEvent::Removed {+ path: path.clone(),+ dialect: path.file_stem().and_then(|s| s.to_str()).unwrap_or("unknown").to_string(),+ },+ _ => continue,+ });+ }+ }+ Err(e) => {+ let _ = tx_clone+ .send(ReloadEvent::Error { path: PathBuf::from("."), error: format!("Watcher error: {e}") });+ }+ },+ Config::default()+ .with_poll_interval(Duration::from_millis(self.config.poll_interval_ms))+ .with_compare_contents(true),+ )+ .map_err(|e| format!("Failed to create file watcher: {e}"))?;++ for dir in &watch_dirs {+ if dir.exists() {+ watcher+ .watch(dir, RecursiveMode::NonRecursive)+ .map_err(|e| format!("Failed to watch {}: {e}", dir.display()))?;+ }+ }++ self.watcher = Some(watcher);+ Ok(rx)+ }++ /// Process reload events in a loop, updating the registry.+ /// This is a convenience function that runs forever on the current task.+ pub async fn run_forever(+ watch_dirs: Vec<PathBuf>,+ registry: &'static super::dialect_loader::DialectRegistry,+ ) -> Result<(), String> {+ let mut reload = Self::new(HotReloadConfig::default());+ let mut rx = reload.start(watch_dirs)?;++ while let Some(event) = rx.recv().await {+ match &event {+ ReloadEvent::Loaded { path } => match DialectPluginLoader::load_file(path) {+ Ok((kind, yaml, descriptor)) => {+ registry.register_yaml(path, yaml, descriptor);+ log::info!("Hot-reload: loaded dialect {:?} from {}", kind, path.display());+ }+ Err(e) => {+ log::warn!("Hot-reload: failed to load {}: {e}", path.display());+ }+ },+ ReloadEvent::Removed { path, dialect } => {+ registry.unregister(dialect);+ log::info!("Hot-reload: unregistered dialect {dialect} ({})", path.display());+ }+ ReloadEvent::Error { path, error } => {+ log::error!("Hot-reload: error watching {}: {error}", path.display());+ }+ }+ }++ Ok(())+ }++ fn is_relevant(event: &Event) -> bool {+ for path in &event.paths {+ if let Some(ext) = path.extension().and_then(|s| s.to_str()) {+ if matches!(ext, "yaml" | "yml") {+ return true;+ }+ }+ }+ false+ }++ pub fn stop(&mut self) {+ self.watcher = None;+ }+}diff --git a/crates/dbx-core/src/sql_dialect/inference.rs b/crates/dbx-core/src/sql_dialect/inference.rsnew file mode 100644index 0000000000..db0c6bcccd--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/inference.rs@@ -0,0 +1,320 @@+use super::descriptor::{DialectKind, TypeMappingMatrix};++#[derive(Debug, Clone, PartialEq)]+pub struct ColumnType {+ pub base_type: String,+ pub precision: Option<u32>,+ pub scale: Option<u32>,+ pub length: Option<u32>,+ pub is_array: bool,+ pub is_unsigned: bool,+ pub extras: Vec<String>,+}++impl ColumnType {+ pub fn parse(type_str: &str) -> Self {+ let trimmed = type_str.trim();+ let (base_type, params_str) = match trimmed.find('(') {+ Some(pos) if trimmed.ends_with(')') => {+ let base = trimmed[..pos].trim().to_string();+ let params = trimmed[pos + 1..trimmed.len() - 1].trim();+ (base, Some(params))+ }+ _ => (trimmed.to_string(), None),+ };++ let is_unsigned = base_type.to_ascii_lowercase().contains("unsigned");+ let is_array = trimmed.ends_with("[]") || trimmed.to_ascii_lowercase().contains(" array");+ let base_type_clean =+ base_type.replace(" unsigned", "").replace(" UNSIGNED", "").replace("[]", "").trim().to_string();++ let (precision, scale, length) = match params_str {+ Some(params) if params.contains(',') => {+ let parts: Vec<&str> = params.split(',').collect();+ if parts.len() >= 2 {+ let p = parts[0].trim().parse().ok();+ let s = parts[1].trim().parse().ok();+ (p, s, None)+ } else {+ (None, None, params.parse().ok())+ }+ }+ Some(params) => {+ let v = params.parse().ok();+ (None, None, v)+ }+ None => (None, None, None),+ };++ Self { base_type: base_type_clean, precision, scale, length, is_array, is_unsigned, extras: Vec::new() }+ }++ pub fn to_string(&self, dialect: DialectKind) -> String {+ let mut result = self.base_type.clone();++ if self.is_unsigned && dialect == DialectKind::Mysql {+ result.push_str(" UNSIGNED");+ }++ if let Some(len) = self.length {+ result.push_str(&format!("({len})"));+ } else if let Some(p) = self.precision {+ if let Some(s) = self.scale {+ result.push_str(&format!("({p},{s})"));+ } else {+ result.push_str(&format!("({p})"));+ }+ }++ if self.is_array && (dialect == DialectKind::Postgres || dialect == DialectKind::DuckDb) {+ result.push_str("[]");+ }++ result+ }+}++pub trait TypeInferenceEngine {+ fn infer_type(&self, source_type: &str, source_dialect: DialectKind, target_dialect: DialectKind) -> ColumnType;++ fn suggest_type(&self, column: &ColumnType, target_dialect: DialectKind) -> String;++ fn convert_default_value(+ &self,+ default_expr: &str,+ source_dialect: DialectKind,+ target_dialect: DialectKind,+ ) -> String;++ fn type_compatibility_score(&self, source: &ColumnType, target: &ColumnType) -> f64;+}++const SCORE_IDENTICAL: f64 = 1.0;+const SCORE_ALIAS: f64 = 0.9;+const SCORE_INTEGER_FAMILY: f64 = 0.8;+const SCORE_TEXT_FAMILY: f64 = 0.7;+const SCORE_UNRELATED: f64 = 0.3;++pub struct DefaultTypeInferenceEngine;++impl DefaultTypeInferenceEngine {+ fn map_type_name(&self, type_name: &str, from: DialectKind, to: DialectKind) -> String {+ let matrix = TypeMappingMatrix::for_dialects(from, to);+ let (converted, _) = matrix.convert_type(type_name);+ converted+ }+}++impl TypeInferenceEngine for DefaultTypeInferenceEngine {+ fn infer_type(&self, source_type: &str, source_dialect: DialectKind, target_dialect: DialectKind) -> ColumnType {+ let source_parsed = ColumnType::parse(source_type);+ let mapped_base = self.map_type_name(&source_parsed.base_type, source_dialect, target_dialect);++ let target_caps = crate::sql_dialect::resolve(target_dialect);+ let needs_precision = mapped_base.to_ascii_lowercase().contains("decimal")+ || mapped_base.to_ascii_lowercase().contains("numeric")+ || mapped_base.to_ascii_lowercase().contains("varchar");++ let (precision, scale, length) = if needs_precision {+ (source_parsed.precision, source_parsed.scale, source_parsed.length)+ } else if mapped_base.eq_ignore_ascii_case("integer") && source_parsed.precision.is_some() {+ (None, None, None)+ } else {+ (source_parsed.precision, source_parsed.scale, source_parsed.length)+ };++ ColumnType {+ base_type: mapped_base,+ precision,+ scale,+ length,+ is_array: source_parsed.is_array && target_caps.supports_array_type,+ is_unsigned: source_parsed.is_unsigned && target_dialect == DialectKind::Mysql,+ extras: source_parsed.extras,+ }+ }++ fn suggest_type(&self, column: &ColumnType, target_dialect: DialectKind) -> String {+ column.to_string(target_dialect)+ }++ fn convert_default_value(+ &self,+ default_expr: &str,+ source_dialect: DialectKind,+ target_dialect: DialectKind,+ ) -> String {+ let trimmed = default_expr.trim();+ if trimmed.is_empty() || trimmed.eq_ignore_ascii_case("null") || trimmed.eq_ignore_ascii_case("NULL") {+ return String::new();+ }++ match (source_dialect, target_dialect) {+ (DialectKind::Mysql, DialectKind::Postgres) => {+ let lower = trimmed.to_ascii_lowercase();+ if lower == "current_timestamp" || lower == "current_timestamp()" || lower == "now()" {+ return "CURRENT_TIMESTAMP".to_string();+ }+ if lower.starts_with("on update ") {+ return String::new();+ }+ }+ (DialectKind::Postgres, DialectKind::Mysql) => {+ let lower = trimmed.to_ascii_lowercase();+ if lower == "current_timestamp" || lower == "now()" || lower == "transaction_timestamp()" {+ return "CURRENT_TIMESTAMP".to_string();+ }+ }+ (DialectKind::Mysql, DialectKind::Sqlite) => {+ let lower = trimmed.to_ascii_lowercase();+ if lower == "current_timestamp" || lower == "current_timestamp()" || lower == "now()" {+ return "CURRENT_TIMESTAMP".to_string();+ }+ }+ _ => {}+ }++ trimmed.to_string()+ }++ fn type_compatibility_score(&self, source: &ColumnType, target: &ColumnType) -> f64 {+ let source_lower = source.base_type.to_ascii_lowercase();+ let target_lower = target.base_type.to_ascii_lowercase();++ if source_lower == target_lower {+ return SCORE_IDENTICAL;+ }++ let exact_matches = [+ ("int", "integer"),+ ("integer", "int"),+ ("float", "real"),+ ("real", "float"),+ ("double", "double precision"),+ ("double precision", "double"),+ ("bool", "boolean"),+ ("boolean", "bool"),+ ("timestamp", "datetime"),+ ("datetime", "timestamp"),+ ];+ if exact_matches.contains(&(source_lower.as_str(), target_lower.as_str())) {+ return SCORE_ALIAS;+ }++ let integer_family = ["tinyint", "smallint", "mediumint", "int", "integer", "bigint", "serial", "bigserial"];+ let text_family = ["char", "varchar", "text", "tinytext", "mediumtext", "longtext", "clob", "nclob"];++ if integer_family.contains(&source_lower.as_str()) && integer_family.contains(&target_lower.as_str()) {+ return SCORE_INTEGER_FAMILY;+ }+ if text_family.contains(&source_lower.as_str()) && text_family.contains(&target_lower.as_str()) {+ return SCORE_TEXT_FAMILY;+ }++ SCORE_UNRELATED+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn parse_simple_type() {+ let t = ColumnType::parse("INT");+ assert_eq!(t.base_type, "INT");+ assert!(t.precision.is_none());+ assert!(t.length.is_none());+ }++ #[test]+ fn parse_type_with_length() {+ let t = ColumnType::parse("VARCHAR(255)");+ assert_eq!(t.base_type, "VARCHAR");+ assert_eq!(t.length, Some(255));+ }++ #[test]+ fn parse_type_with_precision_scale() {+ let t = ColumnType::parse("DECIMAL(10,2)");+ assert_eq!(t.base_type, "DECIMAL");+ assert_eq!(t.precision, Some(10));+ assert_eq!(t.scale, Some(2));+ }++ #[test]+ fn parse_unsigned_type() {+ let t = ColumnType::parse("INT UNSIGNED");+ assert_eq!(t.base_type, "INT");+ assert!(t.is_unsigned);+ }++ #[test]+ fn infer_mysql_int_to_postgres() {+ let engine = DefaultTypeInferenceEngine;+ let result = engine.infer_type("INT", DialectKind::Mysql, DialectKind::Postgres);+ assert_eq!(result.base_type, "INTEGER");+ }++ #[test]+ fn infer_mysql_datetime_to_postgres() {+ let engine = DefaultTypeInferenceEngine;+ let result = engine.infer_type("DATETIME", DialectKind::Mysql, DialectKind::Postgres);+ assert_eq!(result.base_type, "TIMESTAMP");+ }++ #[test]+ fn infer_postgres_text_to_mysql() {+ let engine = DefaultTypeInferenceEngine;+ let result = engine.infer_type("TEXT", DialectKind::Postgres, DialectKind::Mysql);+ assert_eq!(result.base_type, "LONGTEXT");+ }++ #[test]+ fn type_compatibility_exact_match() {+ let engine = DefaultTypeInferenceEngine;+ let a = ColumnType::parse("INT");+ let b = ColumnType::parse("INTEGER");+ let score = engine.type_compatibility_score(&a, &b);+ assert!((score - 0.9).abs() < 0.01);+ }++ #[test]+ fn type_compatibility_integer_family() {+ let engine = DefaultTypeInferenceEngine;+ let a = ColumnType::parse("SMALLINT");+ let b = ColumnType::parse("BIGINT");+ let score = engine.type_compatibility_score(&a, &b);+ assert!((score - 0.8).abs() < 0.01);+ }++ #[test]+ fn convert_default_value_mysql_to_postgres() {+ let engine = DefaultTypeInferenceEngine;+ assert_eq!(+ engine.convert_default_value("CURRENT_TIMESTAMP", DialectKind::Mysql, DialectKind::Postgres),+ "CURRENT_TIMESTAMP"+ );+ assert_eq!(+ engine.convert_default_value("NOW()", DialectKind::Mysql, DialectKind::Postgres),+ "CURRENT_TIMESTAMP"+ );+ assert!(engine+ .convert_default_value("ON UPDATE CURRENT_TIMESTAMP", DialectKind::Mysql, DialectKind::Postgres)+ .is_empty());+ }++ #[test]+ fn unknown_type_passthrough() {+ let engine = DefaultTypeInferenceEngine;+ let result = engine.infer_type("GEOGRAPHY(POINT)", DialectKind::Postgres, DialectKind::Mysql);+ assert_eq!(result.base_type, "GEOGRAPHY");+ }++ #[test]+ fn parse_array_type() {+ let t = ColumnType::parse("INTEGER[]");+ assert!(t.is_array);+ assert_eq!(t.base_type, "INTEGER");+ }+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__all_dialects_info.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__all_dialects_info.snapnew file mode 100644index 0000000000..b40733d8a9--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__all_dialects_info.snap@@ -0,0 +1,431 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 67+expression: all+---+[+ {+ "kind": "mysql",+ "label": "mysql",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "reorder_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_type",+ "index_comment",+ "alter_primary_key",+ "foreign_key",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "alter_owner",+ "grant_revoke",+ "if_not_exists",+ "temporary_table",+ "auto_increment"+ ],+ "max_identifier_length": 64,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 4096,+ "supports_json_type": true,+ "supports_array_type": false,+ "supports_enum_type": true,+ "supports_uuid_type": false,+ "supports_auto_increment": true,+ "supports_identity_columns": false,+ "supports_sequences": false,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": false+ },+ {+ "kind": "postgres",+ "label": "postgres",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_type",+ "index_include",+ "index_filter",+ "index_comment",+ "alter_primary_key",+ "foreign_key",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "alter_owner",+ "grant_revoke",+ "if_not_exists",+ "create_or_replace",+ "temporary_table",+ "transactional_ddl",+ "identity_columns"+ ],+ "max_identifier_length": 63,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1600,+ "supports_json_type": true,+ "supports_array_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": true,+ "supports_auto_increment": false,+ "supports_identity_columns": true,+ "supports_sequences": true,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": true+ },+ {+ "kind": "sqlite",+ "label": "sqlite",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_filter",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "if_not_exists",+ "auto_increment"+ ],+ "max_identifier_length": 255,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 2000,+ "supports_json_type": false,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_auto_increment": true,+ "supports_identity_columns": false,+ "supports_sequences": false,+ "supports_partitioning": false,+ "supports_full_text_index": true,+ "supports_spatial_index": false,+ "supports_transactional_ddl": false+ },+ {+ "kind": "duck_db",+ "label": "duckdb",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "create_index",+ "drop_index",+ "rebuild_index",+ "create_table",+ "drop_table",+ "truncate_table",+ "if_not_exists",+ "create_or_replace",+ "temporary_table"+ ],+ "max_identifier_length": 255,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1600,+ "supports_json_type": true,+ "supports_array_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": true,+ "supports_auto_increment": false,+ "supports_identity_columns": false,+ "supports_sequences": true,+ "supports_partitioning": true,+ "supports_full_text_index": false,+ "supports_spatial_index": true,+ "supports_transactional_ddl": false+ },+ {+ "kind": "sql_server",+ "label": "sqlserver",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_type",+ "index_include",+ "index_filter",+ "index_comment",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "alter_owner",+ "grant_revoke",+ "if_not_exists",+ "temporary_table",+ "transactional_ddl",+ "identity_columns"+ ],+ "max_identifier_length": 128,+ "supports_schemas": true,+ "supports_catalogs": true,+ "max_columns_per_table": 1024,+ "supports_json_type": true,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": true,+ "supports_auto_increment": false,+ "supports_identity_columns": true,+ "supports_sequences": true,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": true+ },+ {+ "kind": "oracle",+ "label": "oracle",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_type",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "alter_owner",+ "grant_revoke",+ "if_not_exists",+ "temporary_table",+ "identity_columns"+ ],+ "max_identifier_length": 30,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1000,+ "supports_json_type": true,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_auto_increment": false,+ "supports_identity_columns": true,+ "supports_sequences": true,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": false+ },+ {+ "kind": "h2",+ "label": "h2",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "if_not_exists",+ "temporary_table",+ "identity_columns"+ ],+ "max_identifier_length": 256,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1600,+ "supports_json_type": true,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": true,+ "supports_auto_increment": false,+ "supports_identity_columns": true,+ "supports_sequences": true,+ "supports_partitioning": false,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": false+ },+ {+ "kind": "click_house",+ "label": "clickhouse",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "reorder_column",+ "comment",+ "create_table",+ "drop_table",+ "truncate_table",+ "if_not_exists",+ "temporary_table"+ ],+ "max_identifier_length": 256,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1000,+ "supports_json_type": true,+ "supports_array_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": true,+ "supports_auto_increment": false,+ "supports_identity_columns": false,+ "supports_sequences": false,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": false,+ "supports_transactional_ddl": false+ },+ {+ "kind": "manticore_search",+ "label": "manticoresearch",+ "capabilities": [+ "add_column",+ "drop_column",+ "create_table",+ "drop_table",+ "truncate_table",+ "auto_increment"+ ],+ "max_identifier_length": 256,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 512,+ "supports_json_type": true,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_auto_increment": true,+ "supports_identity_columns": false,+ "supports_sequences": false,+ "supports_partitioning": false,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": false+ },+ {+ "kind": "informix",+ "label": "informix",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "create_index",+ "drop_index",+ "rebuild_index",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "grant_revoke"+ ],+ "max_identifier_length": 128,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 32767,+ "supports_json_type": false,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_auto_increment": false,+ "supports_identity_columns": false,+ "supports_sequences": true,+ "supports_partitioning": true,+ "supports_full_text_index": false,+ "supports_spatial_index": false,+ "supports_transactional_ddl": false+ },+ {+ "kind": "questdb",+ "label": "questdb",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "create_table",+ "drop_table",+ "truncate_table",+ "if_not_exists"+ ],+ "max_identifier_length": 256,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 1024,+ "supports_json_type": false,+ "supports_array_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_auto_increment": false,+ "supports_identity_columns": false,+ "supports_sequences": false,+ "supports_partitioning": true,+ "supports_full_text_index": false,+ "supports_spatial_index": false,+ "supports_transactional_ddl": false+ }+]diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__duckdb_descriptor.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__duckdb_descriptor.snapnew file mode 100644index 0000000000..f99e5beba9--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__duckdb_descriptor.snap@@ -0,0 +1,30 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 37+expression: desc+---+{+ "dialect": "duck_db",+ "flags": 469991879,+ "max_identifier_length": 255,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1600,+ "max_indexes_per_table": 100,+ "max_query_size_bytes": 268435456,+ "supports_full_text_index": false,+ "supports_spatial_index": true,+ "supports_partitioning": true,+ "supports_table_sampling": true,+ "max_foreign_key_name_length": 255,+ "supports_on_update_cascade": true,+ "supports_on_delete_set_null": true,+ "supports_deferrable_constraints": false,+ "supports_array_type": true,+ "supports_json_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": true,+ "supports_identity_columns": false,+ "supports_auto_increment": false,+ "supports_sequences": true+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_descriptor.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_descriptor.snapnew file mode 100644index 0000000000..40a95906cb--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_descriptor.snap@@ -0,0 +1,30 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 7+expression: desc+---+{+ "dialect": "mysql",+ "flags": 1476391935,+ "max_identifier_length": 64,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 4096,+ "max_indexes_per_table": 64,+ "max_query_size_bytes": 16777216,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_partitioning": true,+ "supports_table_sampling": false,+ "max_foreign_key_name_length": 64,+ "supports_on_update_cascade": true,+ "supports_on_delete_set_null": true,+ "supports_deferrable_constraints": false,+ "supports_array_type": false,+ "supports_json_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": false,+ "supports_identity_columns": false,+ "supports_auto_increment": true,+ "supports_sequences": false+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_info.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_info.snapnew file mode 100644index 0000000000..bc23732d48--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_info.snap@@ -0,0 +1,53 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 43+expression: info+---+{+ "kind": "mysql",+ "label": "mysql",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "reorder_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_type",+ "index_comment",+ "alter_primary_key",+ "foreign_key",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "alter_owner",+ "grant_revoke",+ "if_not_exists",+ "temporary_table",+ "auto_increment"+ ],+ "max_identifier_length": 64,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 4096,+ "supports_json_type": true,+ "supports_array_type": false,+ "supports_enum_type": true,+ "supports_uuid_type": false,+ "supports_auto_increment": true,+ "supports_identity_columns": false,+ "supports_sequences": false,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": false+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_to_postgres_mapping.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_to_postgres_mapping.snapnew file mode 100644index 0000000000..574907f791--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__mysql_to_postgres_mapping.snap@@ -0,0 +1,103 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 55+expression: "&matrix.rules"+---+[+ {+ "source_type": "TINYINT(1)",+ "target_type": "BOOLEAN",+ "precision_loss": false,+ "requires_cast": true+ },+ {+ "source_type": "TINYINT",+ "target_type": "SMALLINT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "MEDIUMINT",+ "target_type": "INTEGER",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "INT",+ "target_type": "INTEGER",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "BIGINT",+ "target_type": "BIGINT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "FLOAT",+ "target_type": "REAL",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "DOUBLE",+ "target_type": "DOUBLE PRECISION",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "TINYTEXT",+ "target_type": "TEXT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "TEXT",+ "target_type": "TEXT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "MEDIUMTEXT",+ "target_type": "TEXT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "LONGTEXT",+ "target_type": "TEXT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "BLOB",+ "target_type": "BYTEA",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "TINYBLOB",+ "target_type": "BYTEA",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "MEDIUMBLOB",+ "target_type": "BYTEA",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "LONGBLOB",+ "target_type": "BYTEA",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "DATETIME",+ "target_type": "TIMESTAMP",+ "precision_loss": false,+ "requires_cast": false+ }+]diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__oracle_descriptor.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__oracle_descriptor.snapnew file mode 100644index 0000000000..e413bdd1ee--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__oracle_descriptor.snap@@ -0,0 +1,30 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 31+expression: desc+---+{+ "dialect": "oracle",+ "flags": 402621423,+ "max_identifier_length": 30,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1000,+ "max_indexes_per_table": 100,+ "max_query_size_bytes": 65536,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_partitioning": true,+ "supports_table_sampling": true,+ "max_foreign_key_name_length": 30,+ "supports_on_update_cascade": true,+ "supports_on_delete_set_null": true,+ "supports_deferrable_constraints": true,+ "supports_array_type": false,+ "supports_json_type": true,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_identity_columns": true,+ "supports_auto_increment": false,+ "supports_sequences": true+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_descriptor.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_descriptor.snapnew file mode 100644index 0000000000..7868298f7e--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_descriptor.snap@@ -0,0 +1,30 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 13+expression: desc+---+{+ "dialect": "postgres",+ "flags": 3221225455,+ "max_identifier_length": 63,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1600,+ "max_indexes_per_table": 100,+ "max_query_size_bytes": 268435456,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_partitioning": true,+ "supports_table_sampling": true,+ "max_foreign_key_name_length": 63,+ "supports_on_update_cascade": true,+ "supports_on_delete_set_null": true,+ "supports_deferrable_constraints": true,+ "supports_array_type": true,+ "supports_json_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": true,+ "supports_identity_columns": true,+ "supports_auto_increment": false,+ "supports_sequences": true+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_info.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_info.snapnew file mode 100644index 0000000000..23fa9d4d7b--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_info.snap@@ -0,0 +1,56 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 49+expression: info+---+{+ "kind": "postgres",+ "label": "postgres",+ "capabilities": [+ "add_column",+ "drop_column",+ "rename_column",+ "alter_existing_column",+ "comment",+ "create_index",+ "drop_index",+ "rebuild_index",+ "index_type",+ "index_include",+ "index_filter",+ "index_comment",+ "alter_primary_key",+ "foreign_key",+ "create_table",+ "drop_table",+ "truncate_table",+ "create_trigger",+ "drop_trigger",+ "create_function",+ "drop_function",+ "create_sequence",+ "drop_sequence",+ "alter_owner",+ "grant_revoke",+ "if_not_exists",+ "create_or_replace",+ "temporary_table",+ "transactional_ddl",+ "identity_columns"+ ],+ "max_identifier_length": 63,+ "supports_schemas": true,+ "supports_catalogs": false,+ "max_columns_per_table": 1600,+ "supports_json_type": true,+ "supports_array_type": true,+ "supports_enum_type": true,+ "supports_uuid_type": true,+ "supports_auto_increment": false,+ "supports_identity_columns": true,+ "supports_sequences": true,+ "supports_partitioning": true,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_transactional_ddl": true+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_to_mysql_mapping.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_to_mysql_mapping.snapnew file mode 100644index 0000000000..3aa4350ac8--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__postgres_to_mysql_mapping.snap@@ -0,0 +1,79 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 61+expression: "&matrix.rules"+---+[+ {+ "source_type": "SMALLINT",+ "target_type": "SMALLINT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "INTEGER",+ "target_type": "INT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "BIGINT",+ "target_type": "BIGINT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "REAL",+ "target_type": "FLOAT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "DOUBLE PRECISION",+ "target_type": "DOUBLE",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "TEXT",+ "target_type": "LONGTEXT",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "BYTEA",+ "target_type": "BLOB",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "BOOLEAN",+ "target_type": "TINYINT(1)",+ "precision_loss": false,+ "requires_cast": true+ },+ {+ "source_type": "TIMESTAMP",+ "target_type": "DATETIME",+ "precision_loss": false,+ "requires_cast": false+ },+ {+ "source_type": "TIMESTAMPTZ",+ "target_type": "DATETIME",+ "precision_loss": true,+ "requires_cast": true+ },+ {+ "source_type": "UUID",+ "target_type": "CHAR(36)",+ "precision_loss": false,+ "requires_cast": true+ },+ {+ "source_type": "JSONB",+ "target_type": "JSON",+ "precision_loss": false,+ "requires_cast": false+ }+]diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__sqlite_descriptor.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__sqlite_descriptor.snapnew file mode 100644index 0000000000..90aa9e45f1--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__sqlite_descriptor.snap@@ -0,0 +1,30 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 19+expression: desc+---+{+ "dialect": "sqlite",+ "flags": 1157597639,+ "max_identifier_length": 255,+ "supports_schemas": false,+ "supports_catalogs": false,+ "max_columns_per_table": 2000,+ "max_indexes_per_table": 200,+ "max_query_size_bytes": 0,+ "supports_full_text_index": true,+ "supports_spatial_index": false,+ "supports_partitioning": false,+ "supports_table_sampling": false,+ "max_foreign_key_name_length": 255,+ "supports_on_update_cascade": true,+ "supports_on_delete_set_null": true,+ "supports_deferrable_constraints": false,+ "supports_array_type": false,+ "supports_json_type": false,+ "supports_enum_type": false,+ "supports_uuid_type": false,+ "supports_identity_columns": false,+ "supports_auto_increment": true,+ "supports_sequences": false+}diff --git a/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__sqlserver_descriptor.snap b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__sqlserver_descriptor.snapnew file mode 100644index 0000000000..519f0d0af3--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/snapshots/dbx_core__sql_dialect__descriptor_snapshots__sqlserver_descriptor.snap@@ -0,0 +1,30 @@+---+source: crates/dbx-core/src/sql_dialect/descriptor_snapshots.rs+assertion_line: 25+expression: desc+---+{+ "dialect": "sql_server",+ "flags": 3086983151,+ "max_identifier_length": 128,+ "supports_schemas": true,+ "supports_catalogs": true,+ "max_columns_per_table": 1024,+ "max_indexes_per_table": 999,+ "max_query_size_bytes": 268435456,+ "supports_full_text_index": true,+ "supports_spatial_index": true,+ "supports_partitioning": true,+ "supports_table_sampling": true,+ "max_foreign_key_name_length": 128,+ "supports_on_update_cascade": true,+ "supports_on_delete_set_null": true,+ "supports_deferrable_constraints": false,+ "supports_array_type": false,+ "supports_json_type": true,+ "supports_enum_type": false,+ "supports_uuid_type": true,+ "supports_identity_columns": true,+ "supports_auto_increment": false,+ "supports_sequences": true+}diff --git a/crates/dbx-core/src/sql_dialect/type_rewrite.rs b/crates/dbx-core/src/sql_dialect/type_rewrite.rsnew file mode 100644index 0000000000..f77c3b6a34--- /dev/null+++ b/crates/dbx-core/src/sql_dialect/type_rewrite.rs@@ -0,0 +1,243 @@+//! Column type rewrite pipeline for cross-database DDL generation.+//!+//! Order:+//! 1. Caller-applied user field mappings (highest priority — not handled here)+//! 2. Target [`DdlDialectProfile::type_map`] (data-driven)+//! 3. [`TypeMappingMatrix`] between source/target [`DialectKind`] when available+//! 4. Generic normalization (strip display width when profile disallows it)++use crate::models::connection::DatabaseType;+use crate::sql_dialect::ddl_profile::{profile_for, DdlDialectProfile};+use crate::sql_dialect::descriptor::{DialectKind, TypeMappingMatrix};+use crate::types::ColumnInfo;++/// Split `INT(11)` / `DECIMAL(10,2)` / `VARCHAR` into base + params.+pub fn split_type_base_params(source_type: &str) -> (String, Option<String>) {+ let trimmed = source_type.trim();+ let upper = trimmed.to_ascii_uppercase();+ match upper.find('(') {+ Some(i) => {+ let base = upper[..i].trim().to_string();+ let end = upper.rfind(')').unwrap_or(upper.len());+ let params = upper[i + 1..end].trim().to_string();+ (base, Some(params))+ }+ None => (upper, None),+ }+}++fn first_length_param(params: Option<&str>) -> Option<u32> {+ params.and_then(|p| p.split(',').next()).and_then(|p| p.trim().parse::<u32>().ok())+}++fn apply_template(template: &str, params: Option<&str>, max_varchar_len: Option<u32>) -> String {+ if !template.contains("{}") {+ return template.to_string();+ }+ // Prefer full params for DECIMAL(p,s); single length for TEXT({})+ if template.starts_with("DECIMAL") || template.starts_with("NUMERIC") {+ return match params {+ Some(p) if !p.is_empty() => template.replacen("{}", p, 1),+ _ => template.replace("({})", "").replace("{}", ""),+ };+ }+ let mut len = first_length_param(params).unwrap_or(255);+ if let Some(max) = max_varchar_len {+ len = len.clamp(1, max);+ } else {+ len = len.max(1);+ }+ template.replacen("{}", &len.to_string(), 1)+}++/// Strip MySQL-style display width: `INT(11)` → `INT`, keep `DECIMAL(10,2)` / `VARCHAR(100)`.+///+/// When keeping length/precision params, original casing is preserved (passthrough-ish).+/// When stripping display width, the base is uppercased as a normalized form.+pub fn strip_display_width_if_needed(source_type: &str, profile: &DdlDialectProfile) -> String {+ if profile.supports_display_width {+ return source_type.trim().to_string();+ }+ let trimmed = source_type.trim();+ let (base, params) = split_type_base_params(trimmed);+ let Some(params) = params else {+ return trimmed.to_string();+ };+ // Keep types where parentheses are meaningful precision/length for most targets.+ let keep_params = matches!(+ base.as_str(),+ "VARCHAR"+ | "CHARACTER VARYING"+ | "CHAR"+ | "CHARACTER"+ | "NVARCHAR"+ | "NVARCHAR2"+ | "VARCHAR2"+ | "DECIMAL"+ | "NUMERIC"+ | "NUMBER"+ | "FLOAT"+ | "DOUBLE"+ | "TIME"+ | "TIMESTAMP"+ | "DATETIME"+ | "ENUM"+ | "SET"+ );+ if keep_params {+ // Reconstruct from the original slice so casing stays source-faithful.+ let orig_base = trimmed.split('(').next().unwrap_or(trimmed).trim();+ let open = trimmed.find('(').unwrap_or(orig_base.len());+ let close = trimmed.rfind(')').unwrap_or(trimmed.len());+ let orig_params = if open < close { trimmed[open + 1..close].trim() } else { params.as_str() };+ format!("{orig_base}({orig_params})")+ } else {+ // INT(11), BIGINT(20), TINYINT(2), YEAR(4), … — normalized uppercase base.+ base+ }+}++/// Special-case: TINYINT(1) often means boolean on MySQL-like sources.+fn tinyint1_as_boolean_key(base: &str, params: Option<&str>) -> Option<&'static str> {+ if base.eq_ignore_ascii_case("TINYINT") && params == Some("1") {+ Some("BOOL")+ } else {+ None+ }+}++/// Rewrite a source column type for `target` database.+///+/// User field mappings must be applied by the caller *before* this function.+pub fn rewrite_column_type(source_type: &str, target: DatabaseType, source_dialect: Option<DialectKind>) -> String {+ let profile = profile_for(target);+ let (base, params) = split_type_base_params(source_type);++ // Profile type_map (includes synthetic BOOL for TINYINT(1) when mapped)+ let lookup_key = tinyint1_as_boolean_key(&base, params.as_deref()).unwrap_or(base.as_str());+ if let Some(template) = profile.lookup_type(lookup_key) {+ return apply_template(template, params.as_deref(), profile.max_varchar_len);+ }+ // Also try original base if we used BOOL alias miss+ if lookup_key != base && profile.lookup_type(&base).is_some() {+ if let Some(template) = profile.lookup_type(&base) {+ return apply_template(template, params.as_deref(), profile.max_varchar_len);+ }+ }++ // Dialect-kind matrix+ if let Some(src) = source_dialect {+ let target_kind = DialectKind::from_database_type(target);+ let matrix = TypeMappingMatrix::for_dialects(src, target_kind);+ let (converted, _) = matrix.convert_type(source_type);+ if converted != source_type {+ return strip_display_width_if_needed(&converted, &profile);+ }+ }++ strip_display_width_if_needed(source_type, &profile)+}++/// Whether the column metadata indicates auto-increment / identity / serial.+pub fn column_is_auto_increment(col: &ColumnInfo) -> bool {+ col.extra.as_deref().is_some_and(|extra| {+ let lower = extra.to_ascii_lowercase();+ lower.contains("auto_increment") || lower.contains("identity") || lower.contains("serial")+ })+}++/// Whether a rewritten type looks integer-like (for PK auto-inc heuristics).+pub fn type_looks_integer(mapped_type: &str) -> bool {+ let lower = mapped_type.to_ascii_lowercase();+ lower.contains("int")+ || lower.contains("integer")+ || lower.contains("serial")+ || lower.eq_ignore_ascii_case("counter")+ || lower.eq_ignore_ascii_case("byte")+ || lower.starts_with("decimal")+ || lower.starts_with("number")+ || lower.starts_with("numeric")+}++/// Build column type + optional auto-inc contribution using profile only (no DatabaseType branches).+pub fn apply_auto_inc_to_column_def(+ profile: &DdlDialectProfile,+ quoted_name: &str,+ _mapped_type: &str,+ col: &ColumnInfo,+ is_integer_like: bool,+) -> AutoIncColumnBuild {+ let wants_auto = col.is_primary_key && (column_is_auto_increment(col) || is_integer_like);++ match profile.auto_inc {+ crate::sql_dialect::ddl_profile::AutoIncSyntax::ReplaceTypeWith(type_name)+ if wants_auto && col.is_primary_key =>+ {+ let mut def = format!("{quoted_name} {type_name}");+ if !col.is_nullable {+ def.push_str(" NOT NULL");+ }+ AutoIncColumnBuild::Complete { def, skip_default: true }+ }+ crate::sql_dialect::ddl_profile::AutoIncSyntax::Suffix(suffix) if col.is_primary_key && is_integer_like => {+ AutoIncColumnBuild::AppendSuffix { suffix, skip_default: false, postgres_sequence: false }+ }+ crate::sql_dialect::ddl_profile::AutoIncSyntax::PostgresSequence if col.is_primary_key && is_integer_like => {+ AutoIncColumnBuild::AppendSuffix { suffix: "", skip_default: false, postgres_sequence: true }+ }+ _ => AutoIncColumnBuild::Normal { skip_default: false },+ }+}++#[derive(Debug)]+pub enum AutoIncColumnBuild {+ /// Full column definition already built (e.g. COUNTER).+ Complete {+ def: String,+ skip_default: bool,+ },+ /// Continue normal type def; optionally append suffix; maybe register PG sequence.+ AppendSuffix {+ suffix: &'static str,+ skip_default: bool,+ postgres_sequence: bool,+ },+ Normal {+ skip_default: bool,+ },+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn access_rewrites_mysql_types() {+ let t = DatabaseType::Access;+ let src = Some(DialectKind::Mysql);+ assert_eq!(rewrite_column_type("int(11)", t, src), "INTEGER");+ assert_eq!(rewrite_column_type("varchar(120)", t, src), "TEXT(120)");+ assert_eq!(rewrite_column_type("tinyint(2)", t, src), "BYTE");+ assert_eq!(rewrite_column_type("tinyint(1)", t, src), "YESNO");+ assert_eq!(rewrite_column_type("datetime", t, src), "DATETIME");+ assert_eq!(rewrite_column_type("longtext", t, src), "LONGTEXT");+ }++ #[test]+ fn sqlserver_keeps_identity_path_not_counter() {+ let profile = profile_for(DatabaseType::SqlServer);+ assert!(matches!(+ profile.auto_inc,+ crate::sql_dialect::ddl_profile::AutoIncSyntax::Suffix(s) if s.contains("IDENTITY")+ ));+ // No Access type map: display width stripped+ let t = rewrite_column_type("int(11)", DatabaseType::SqlServer, Some(DialectKind::Mysql));+ assert_eq!(t, "INT");+ }++ #[test]+ fn mysql_keeps_display_width() {+ let t = rewrite_column_type("int(11)", DatabaseType::Mysql, None);+ assert_eq!(t, "int(11)");+ }+}diff --git a/crates/dbx-core/src/sql_parser/ast_filter.rs b/crates/dbx-core/src/sql_parser/ast_filter.rsnew file mode 100644index 0000000000..715b556896--- /dev/null+++ b/crates/dbx-core/src/sql_parser/ast_filter.rs@@ -0,0 +1,446 @@+use serde::{Deserialize, Serialize};+use sqlparser::ast::Statement;+use sqlparser::dialect::GenericDialect;+use sqlparser::parser::Parser;++use crate::schema_diff::SchemaDiffPreparationOptions;+use crate::types::FunctionInfo;++#[derive(Debug, Clone)]+pub enum FilterAction {+ Allow,+ Deny(String),+}++pub trait AstFilter {+ fn filter_statement(&self, stmt: &Statement) -> FilterAction;+}++#[derive(Debug, Clone)]+pub struct FilterResult {+ pub allowed: Vec<String>,+ pub denied: Vec<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SandboxResult {+ pub allowed: Vec<String>,+ pub denied: Vec<String>,+ pub nesting_violations: Vec<String>,+ pub is_pure: bool,+ pub stats: SandboxStats,+}++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]+#[serde(rename_all = "snake_case")]+pub enum SandboxMode {+ Permissive,+ #[default]+ Strict,+ Isolation,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct SandboxStats {+ pub total_statements: usize,+ pub allowed_count: usize,+ pub denied_count: usize,+ pub mode: String,+ pub max_nesting_depth: usize,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct AstSandbox {+ pub mode: SandboxMode,+ pub max_nesting_depth: usize,+}++impl Default for AstSandbox {+ fn default() -> Self {+ Self { mode: SandboxMode::Strict, max_nesting_depth: 10 }+ }+}++impl AstSandbox {+ pub fn new(mode: SandboxMode, max_nesting_depth: usize) -> Self {+ Self { mode, max_nesting_depth }+ }++ pub fn filter_sql(&self, sql: &str, dialect_str: &str) -> Result<SandboxResult, String> {+ let base = AstTransmitFilter::filter_sql(sql, dialect_str)?;++ let stats = SandboxStats {+ total_statements: base.allowed.len() + base.denied.len(),+ allowed_count: base.allowed.len(),+ denied_count: base.denied.len(),+ mode: match self.mode {+ SandboxMode::Permissive => "permissive".to_string(),+ SandboxMode::Strict => "strict".to_string(),+ SandboxMode::Isolation => "isolation".to_string(),+ },+ max_nesting_depth: self.max_nesting_depth,+ };++ let (further_blocked, nest_violations) = match self.mode {+ SandboxMode::Permissive => (Vec::new(), Vec::new()),+ SandboxMode::Strict | SandboxMode::Isolation => self.check_nesting(&base.allowed, self.max_nesting_depth),+ };++ let is_pure = match self.mode {+ SandboxMode::Permissive => base.denied.is_empty(),+ SandboxMode::Strict => base.denied.is_empty() && further_blocked.is_empty(),+ SandboxMode::Isolation => {+ base.denied.is_empty() && further_blocked.is_empty() && nest_violations.is_empty()+ }+ };++ Ok(SandboxResult {+ allowed: base.allowed,+ denied: base.denied.iter().chain(further_blocked.iter()).cloned().collect(),+ nesting_violations: nest_violations,+ is_pure,+ stats,+ })+ }++ fn check_nesting(&self, statements: &[String], max_depth: usize) -> (Vec<String>, Vec<String>) {+ let mut further_blocked = Vec::new();+ let mut violations = Vec::new();+ for stmt in statements {+ let depth = self.count_nesting(stmt);+ if depth > max_depth {+ further_blocked.push(stmt.clone());+ violations.push(format!("Nesting depth {depth} exceeds max {max_depth}: {stmt}"));+ }+ }+ (further_blocked, violations)+ }++ fn count_nesting(&self, stmt: &str) -> usize {+ let mut max_depth = 0usize;+ let mut current = 0usize;+ for ch in stmt.chars() {+ match ch {+ '(' => {+ current += 1;+ max_depth = max_depth.max(current);+ }+ ')' => {+ current = current.saturating_sub(1);+ }+ _ => {}+ }+ }+ max_depth+ }+}++pub struct AstTransmitFilter;++impl AstTransmitFilter {+ pub fn filter_sql(sql: &str, dialect_str: &str) -> Result<FilterResult, String> {+ let dialect = resolve_dialect(dialect_str);+ let stmts =+ Parser::parse_sql(dialect.as_ref(), sql).map_err(|e| format!("SQL parse error in AST filter: {e}"))?;++ let filter = Self;+ let mut allowed = Vec::new();+ let mut denied: Vec<String> = Vec::new();++ for stmt in &stmts {+ match filter.filter_statement(stmt) {+ FilterAction::Allow => {+ allowed.push(stmt.to_string());+ }+ FilterAction::Deny(reason) => {+ denied.push(format!("Blocked: {reason} — {stmt}"));+ }+ }+ }++ Ok(FilterResult { allowed, denied })+ }++ fn is_dangerous_body_node(&self, stmt: &Statement) -> bool {+ matches!(+ stmt,+ Statement::CreateFunction { .. } | Statement::CreateProcedure { .. } | Statement::CreateTrigger { .. }+ )+ }++ pub fn filter_diff_preparation_options(+ options: SchemaDiffPreparationOptions,+ _dialect: &str,+ ) -> SchemaDiffPreparationOptions {+ let mut filtered = options;++ let is_dangerous_fn = |f: &FunctionInfo| -> bool {+ let upper = f.definition.to_ascii_uppercase();+ let keywords = ["FUNCTION", "PROCEDURE", "TRIGGER", "BEGIN", "DECLARE", "LANGUAGE"];+ keywords.iter().any(|kw| upper.contains(kw))+ };++ filtered.source_functions.retain(|f| !is_dangerous_fn(f));+ filtered.target_functions.retain(|f| !is_dangerous_fn(f));++ filtered+ }+}++fn resolve_dialect(dialect: &str) -> Box<dyn sqlparser::dialect::Dialect> {+ match dialect.to_ascii_lowercase().as_str() {+ "postgres" | "postgresql" => Box::new(sqlparser::dialect::PostgreSqlDialect {}),+ "mysql" | "mariadb" | "tidb" => Box::new(sqlparser::dialect::MySqlDialect {}),+ "sqlite" => Box::new(sqlparser::dialect::SQLiteDialect {}),+ "sqlserver" | "mssql" => Box::new(sqlparser::dialect::MsSqlDialect {}),+ "clickhouse" => Box::new(sqlparser::dialect::ClickHouseDialect {}),+ "duckdb" => Box::new(sqlparser::dialect::DuckDbDialect {}),+ _ => Box::new(GenericDialect {}),+ }+}++impl AstFilter for AstTransmitFilter {+ fn filter_statement(&self, stmt: &Statement) -> FilterAction {+ if self.is_dangerous_body_node(stmt) {+ return FilterAction::Deny("Function/procedure/trigger body not allowed in schema diff".into());+ }++ match stmt {+ Statement::CreateTable { .. }+ | Statement::CreateView { .. }+ | Statement::CreateIndex { .. }+ | Statement::CreateSchema { .. }+ | Statement::CreateSequence { .. }+ | Statement::AlterTable { .. }+ | Statement::AlterIndex { .. }+ | Statement::AlterView { .. }+ | Statement::Drop { .. }+ | Statement::Truncate { .. } => FilterAction::Allow,++ _ => FilterAction::Deny("Statement type not in whitelist for schema diff".into()),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn allows_create_table() {+ let result =+ AstTransmitFilter::filter_sql("CREATE TABLE users (id INT PRIMARY KEY, name VARCHAR(100))", "generic")+ .unwrap();+ assert!(!result.allowed.is_empty());+ assert!(result.allowed[0].contains("CREATE TABLE"));+ }++ #[test]+ fn allows_create_index() {+ let result = AstTransmitFilter::filter_sql("CREATE INDEX idx_users_name ON users (name)", "generic").unwrap();+ assert!(!result.allowed.is_empty());+ }++ #[test]+ fn allows_alter_table() {+ let result = AstTransmitFilter::filter_sql("ALTER TABLE users ADD COLUMN age INT", "generic").unwrap();+ assert!(!result.allowed.is_empty());+ }++ #[test]+ fn allows_drop_table() {+ let result = AstTransmitFilter::filter_sql("DROP TABLE users", "generic").unwrap();+ assert!(!result.allowed.is_empty());+ }++ #[test]+ fn blocks_create_function() {+ let result = AstTransmitFilter::filter_sql(+ "CREATE FUNCTION add(a INT, b INT) RETURNS INT LANGUAGE SQL RETURN a + b",+ "generic",+ )+ .unwrap();+ assert!(result.allowed.is_empty());+ assert!(!result.denied.is_empty());+ }++ #[test]+ fn blocks_create_procedure() {+ let result = AstTransmitFilter::filter_sql(+ "CREATE PROCEDURE test_proc() AS LANGUAGE SQL BEGIN ATOMIC SELECT 1; END",+ "postgres",+ );+ // parse failure on some platforms is acceptable+ if let Ok(r) = result {+ assert!(r.allowed.is_empty());+ assert!(!r.denied.is_empty());+ }+ }++ #[test]+ fn blocks_create_trigger() {+ let result = AstTransmitFilter::filter_sql(+ "CREATE TRIGGER test_trigger BEFORE INSERT ON users FOR EACH ROW EXECUTE FUNCTION log_change()",+ "postgres",+ )+ .unwrap();+ assert!(result.allowed.is_empty());+ assert!(!result.denied.is_empty());+ }++ #[test]+ fn allows_multiple_ddl_statements() {+ let result = AstTransmitFilter::filter_sql(+ "CREATE TABLE a (id INT); CREATE TABLE b (id INT); ALTER TABLE a ADD COLUMN x INT;",+ "generic",+ )+ .unwrap();+ assert_eq!(result.allowed.len(), 3);+ }++ #[test]+ fn blocks_mixed_ddl_and_function() {+ let result = AstTransmitFilter::filter_sql(+ "CREATE TABLE t (id INT); CREATE FUNCTION f() RETURNS INT AS $$ SELECT 1 $$ LANGUAGE SQL",+ "postgres",+ )+ .unwrap();+ assert_eq!(result.allowed.len(), 1);+ assert_eq!(result.denied.len(), 1);+ }++ #[test]+ fn blocks_select_statement() {+ let result = AstTransmitFilter::filter_sql("SELECT * FROM users", "generic").unwrap();+ assert!(result.allowed.is_empty());+ assert!(!result.denied.is_empty());+ }++ #[test]+ fn allows_create_view() {+ let result = AstTransmitFilter::filter_sql(+ "CREATE VIEW active_users AS SELECT * FROM users WHERE active = 1",+ "generic",+ )+ .unwrap();+ assert!(!result.allowed.is_empty());+ }++ #[test]+ fn deny_insert_statement() {+ let result = AstTransmitFilter::filter_sql("INSERT INTO users VALUES (1, 'a')", "generic").unwrap();+ assert!(result.allowed.is_empty());+ assert!(!result.denied.is_empty());+ }++ #[test]+ fn filter_options_removes_dangerous_functions() {+ let opts = SchemaDiffPreparationOptions {+ source_functions: vec![+ FunctionInfo {+ name: "f1".into(),+ definition: "CREATE FUNCTION f1() RETURNS INT ...".into(),+ function_type: "FUNCTION".into(),+ data_type: "int".into(),+ arguments: "".into(),+ },+ FunctionInfo {+ name: "t1".into(),+ definition: "TABLE t1".into(),+ function_type: "TABLE".into(),+ data_type: "".into(),+ arguments: "".into(),+ },+ ],+ source_tables: vec![],+ target_tables: vec![],+ source_details: vec![],+ target_details: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type: crate::models::connection::DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ ..Default::default()+ };++ let filtered = AstTransmitFilter::filter_diff_preparation_options(opts, "mysql");+ assert_eq!(filtered.source_functions.len(), 1);+ assert_eq!(filtered.source_functions[0].name, "t1");+ }++ #[test]+ fn sandbox_strict_mode_blocks_dangerous_statement() {+ let sandbox = AstSandbox::new(SandboxMode::Strict, 10);+ let result = sandbox+ .filter_sql(+ "CREATE TABLE t (id INT); CREATE FUNCTION f() RETURNS INT AS $$ SELECT 1 $$ LANGUAGE SQL",+ "postgres",+ )+ .unwrap();+ assert_eq!(result.allowed.len(), 1);+ assert!(!result.denied.is_empty());+ assert!(!result.is_pure);+ }++ #[test]+ fn sandbox_isolation_mode_checks_nesting() {+ let sandbox = AstSandbox::new(SandboxMode::Isolation, 4);+ let result = sandbox+ .filter_sql("CREATE TABLE t (a INT, b INT, c INT, d INT, e INT DEFAULT (((1))))", "generic")+ .unwrap();+ assert!(result.nesting_violations.is_empty(), "Should pass with nesting depth 4");+ assert!(result.is_pure);+ }++ #[test]+ fn sandbox_isolation_blocks_deeply_nested() {+ let sandbox = AstSandbox::new(SandboxMode::Isolation, 1);+ let result = sandbox.filter_sql("CREATE TABLE t (a INT DEFAULT ((((1)))))", "generic").unwrap();+ assert!(!result.nesting_violations.is_empty());+ assert!(!result.is_pure);+ }++ #[test]+ fn sandbox_permissive_accepts_everything_allowed() {+ let sandbox = AstSandbox::new(SandboxMode::Permissive, 10);+ let result = sandbox+ .filter_sql("CREATE TABLE t (id INT); CREATE FUNCTION f() RETURNS INT LANGUAGE SQL RETURN 1", "generic")+ .unwrap();+ assert_eq!(result.allowed.len(), 1, "Permissive allows CREATE TABLE but blocks CREATE FUNCTION");+ assert!(!result.denied.is_empty(), "Permissive denies function but not table");+ assert!(!result.is_pure, "Permissive is not pure when function is denied by base filter");+ }++ #[test]+ fn sandbox_permissive_no_nesting_check() {+ let sandbox = AstSandbox::new(SandboxMode::Permissive, 0);+ let result = sandbox.filter_sql("CREATE TABLE t (a INT DEFAULT ((((1)))))", "generic").unwrap();+ assert!(!result.allowed.is_empty());+ assert!(result.nesting_violations.is_empty());+ assert!(result.is_pure);+ }++ #[test]+ fn sandbox_stats_correct() {+ let sandbox = AstSandbox::new(SandboxMode::Strict, 10);+ let result = sandbox+ .filter_sql(+ "CREATE TABLE t1 (id INT); CREATE TABLE t2 (id INT); DROP TABLE t3; SELECT * FROM t1",+ "generic",+ )+ .unwrap();+ assert_eq!(result.stats.total_statements, 4);+ assert_eq!(result.stats.allowed_count, 3);+ assert_eq!(result.stats.denied_count, 1);+ assert_eq!(result.stats.mode, "strict");+ assert_eq!(result.stats.max_nesting_depth, 10);+ }+}diff --git a/crates/dbx-core/src/sql_parser/git.rs b/crates/dbx-core/src/sql_parser/git.rsnew file mode 100644index 0000000000..27c2041fda--- /dev/null+++ b/crates/dbx-core/src/sql_parser/git.rs@@ -0,0 +1,268 @@+use std::collections::HashSet;+use std::path::Path;++use crate::schema_diff::SchemaDiffPreparationOptions;++#[derive(Debug, Clone)]+pub struct DiffEntry {+ pub file_path: String,+ pub sql_content: String,+ pub change_type: ChangeType,+ pub old_path: Option<String>,+}++#[derive(Debug, Clone, PartialEq, Eq)]+pub enum ChangeType {+ Added,+ Modified,+ Deleted,+ Renamed,+}++pub struct GitDiffScanner {+ repo_path: String,+ base_commit: String,+ target_commit: String,+}++impl GitDiffScanner {+ pub fn new(repo_path: &Path, base_commit: &str, target_commit: &str) -> Result<Self, String> {+ if base_commit.is_empty() || target_commit.is_empty() {+ return Err("Git commit refs cannot be empty".into());+ }+ let git_path = repo_path.join(".git");+ let is_git_repo =+ git_path.is_dir() || (git_path.is_file() && git_path.exists()) || repo_path.join("../.git").exists();+ if !is_git_repo {+ return Err(format!("Not a git repository: {}", repo_path.display()));+ }+ Ok(Self {+ repo_path: repo_path.to_string_lossy().to_string(),+ base_commit: base_commit.to_string(),+ target_commit: target_commit.to_string(),+ })+ }++ pub fn scan(&self) -> Result<Vec<DiffEntry>, String> {+ let output = self.run_git_diff()?;++ let sql_filter = self.build_sql_filter()?;++ let raw_entries = self.parse_diff_output(&output, &sql_filter)?;++ let entries = raw_entries+ .into_iter()+ .filter_map(|entry| {+ if entry.change_type == ChangeType::Deleted {+ return Some(entry);+ }+ let path = Path::new(&self.repo_path).join(&entry.file_path);+ let content = std::fs::read_to_string(&path).ok()?;+ Some(DiffEntry { sql_content: content, ..entry })+ })+ .collect();++ Ok(entries)+ }++ fn run_git_diff(&self) -> Result<String, String> {+ let output = std::process::Command::new("git")+ .arg("diff")+ .arg("--diff-filter=ACMR")+ .arg(&self.base_commit)+ .arg(&self.target_commit)+ .arg("--")+ .arg("*.sql")+ .arg("*.ddl")+ .current_dir(&self.repo_path)+ .output()+ .map_err(|e| format!("Failed to run git diff: {e}"))?;++ if !output.status.success() {+ let stderr = String::from_utf8_lossy(&output.stderr);+ return Err(format!("git diff failed: {stderr}"));+ }++ Ok(String::from_utf8_lossy(&output.stdout).to_string())+ }++ fn build_sql_filter(&self) -> Result<HashSet<String>, String> {+ let mut patterns = HashSet::new();+ let gitattributes_path = Path::new(&self.repo_path).join(".gitattributes");+ if gitattributes_path.exists() {+ let content = std::fs::read_to_string(&gitattributes_path)+ .map_err(|e| format!("Failed to read .gitattributes: {e}"))?;+ for line in content.lines() {+ let line = line.trim();+ if line.is_empty() || line.starts_with('#') {+ continue;+ }+ let parts: Vec<&str> = line.split_whitespace().collect();+ if parts.len() >= 2 && parts[1] == "linguist-language=SQL" {+ let pattern = parts[0].trim_matches('*');+ if !pattern.is_empty() {+ patterns.insert(pattern.to_string());+ } else {+ patterns.insert("sql".to_string());+ }+ }+ }+ }+ if patterns.is_empty() {+ patterns.insert("sql".to_string());+ }+ Ok(patterns)+ }++ fn parse_diff_output(&self, output: &str, _filter: &HashSet<String>) -> Result<Vec<DiffEntry>, String> {+ let mut entries = Vec::new();+ let mut current_file: Option<String> = None;+ let mut current_status: Option<ChangeType> = None;+ let mut current_old_path: Option<String> = None;++ for line in output.lines() {+ if line.starts_with("diff --git ") {+ Self::flush_raw_entry(&mut current_file, &mut current_status, &mut current_old_path, &mut entries);+ let parts: Vec<&str> = line.split_whitespace().collect();+ if parts.len() >= 4 {+ let b_path = parts.get(3).copied().unwrap_or("");+ let b_path = b_path.trim_start_matches("b/");+ current_file = Some(b_path.to_string());+ current_status = Some(ChangeType::Modified);+ }+ } else if line.starts_with("--- ") {+ let path = line.trim_start_matches("--- ").trim_start_matches("a/");+ if path != "/dev/null" {+ current_old_path = Some(path.to_string());+ }+ } else if line.starts_with("+++ ") {+ let path = line.trim_start_matches("+++ ").trim_start_matches("b/");+ if path != "/dev/null" {+ current_file = Some(path.to_string());+ }+ } else if line.starts_with("new file mode") {+ current_status = Some(ChangeType::Added);+ } else if line.starts_with("deleted file mode") {+ current_status = Some(ChangeType::Deleted);+ } else if line.starts_with("rename from ") {+ current_old_path = Some(line.trim_start_matches("rename from ").to_string());+ } else if line.starts_with("rename to ") {+ current_file = Some(line.trim_start_matches("rename to ").to_string());+ current_status = Some(ChangeType::Renamed);+ }+ }++ Self::flush_raw_entry(&mut current_file, &mut current_status, &mut current_old_path, &mut entries);++ Ok(entries)+ }++ fn flush_raw_entry(+ file: &mut Option<String>,+ status: &mut Option<ChangeType>,+ old_path: &mut Option<String>,+ entries: &mut Vec<DiffEntry>,+ ) {+ let file_path = file.take();+ let st = status.take().unwrap_or(ChangeType::Modified);+ let op = old_path.take();+ if let Some(path) = file_path {+ entries.push(DiffEntry { file_path: path, sql_content: String::new(), change_type: st, old_path: op });+ }+ }++ pub fn bind_to_commit(options: SchemaDiffPreparationOptions, _commit_id: &str) -> SchemaDiffPreparationOptions {+ options+ }++ pub fn list_commits(&self, max_count: usize) -> Result<Vec<String>, String> {+ let output = std::process::Command::new("git")+ .arg("log")+ .arg("--oneline")+ .arg("-n")+ .arg(max_count.to_string())+ .arg("--")+ .arg("*.sql")+ .arg("*.ddl")+ .current_dir(&self.repo_path)+ .output()+ .map_err(|e| format!("Failed to run git log: {e}"))?;++ if !output.status.success() {+ return Err(String::from_utf8_lossy(&output.stderr).to_string());+ }++ let stdout = String::from_utf8_lossy(&output.stdout);+ Ok(stdout.lines().map(|l| l.to_string()).collect())+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn rejects_non_git_directory() {+ let tmp = std::env::temp_dir().join("dbx_test_not_a_repo");+ let _ = std::fs::create_dir_all(&tmp);+ let result = GitDiffScanner::new(&tmp, "HEAD~1", "HEAD");+ assert!(result.is_err());+ let _ = std::fs::remove_dir_all(&tmp);+ }++ #[test]+ fn parses_diff_output_with_added_file() {+ let scanner =+ GitDiffScanner { repo_path: "/tmp/repo".into(), base_commit: "abc".into(), target_commit: "def".into() };+ let output = "diff --git a/schema.sql b/schema.sql\nnew file mode 100644\n--- /dev/null\n+++ b/schema.sql\n@@ -0,0 +1 @@\n+CREATE TABLE t (id INT);\n";+ let mut filter = HashSet::new();+ filter.insert("sql".to_string());+ let entries = scanner.parse_diff_output(output, &filter).unwrap();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].file_path, "schema.sql");+ assert_eq!(entries[0].change_type, ChangeType::Added);+ }++ #[test]+ fn parses_diff_output_with_modified_file() {+ let scanner =+ GitDiffScanner { repo_path: "/tmp/repo".into(), base_commit: "abc".into(), target_commit: "def".into() };+ let output = "diff --git a/schema.sql b/schema.sql\n--- a/schema.sql\n+++ b/schema.sql\n@@ -1 +1 @@\n-CREATE TABLE t (id INT);\n+CREATE TABLE t (id BIGINT);\n";+ let mut filter = HashSet::new();+ filter.insert("sql".to_string());+ let entries = scanner.parse_diff_output(output, &filter).unwrap();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].change_type, ChangeType::Modified);+ }++ #[test]+ fn parses_diff_output_with_renamed_file() {+ let scanner =+ GitDiffScanner { repo_path: "/tmp/repo".into(), base_commit: "abc".into(), target_commit: "def".into() };+ let output = "diff --git a/old.sql b/new.sql\nrename from old.sql\nrename to new.sql\n";+ let mut filter = HashSet::new();+ filter.insert("sql".to_string());+ let entries = scanner.parse_diff_output(output, &filter).unwrap();+ assert_eq!(entries.len(), 1);+ assert_eq!(entries[0].change_type, ChangeType::Renamed);+ assert_eq!(entries[0].old_path, Some("old.sql".to_string()));+ }++ #[test]+ fn parses_gitattributes_for_sql_patterns() {+ let tmp = std::env::temp_dir().join("dbx_test_gitattributes");+ let _ = std::fs::create_dir_all(&tmp);+ let gitattributes = tmp.join(".gitattributes");+ std::fs::write(&gitattributes, "*.sql linguist-language=SQL\n*.ddl linguist-language=SQL\n").unwrap();++ let scanner = GitDiffScanner {+ repo_path: tmp.to_string_lossy().to_string(),+ base_commit: "abc".into(),+ target_commit: "def".into(),+ };+ let filter = scanner.build_sql_filter().unwrap();+ assert!(!filter.is_empty());++ let _ = std::fs::remove_dir_all(&tmp);+ }+}diff --git a/crates/dbx-core/src/sql_parser/input.rs b/crates/dbx-core/src/sql_parser/input.rsnew file mode 100644index 0000000000..dfba42f5dc--- /dev/null+++ b/crates/dbx-core/src/sql_parser/input.rs@@ -0,0 +1,301 @@+use std::path::{Path, PathBuf};++use crate::models::connection::ConnectionConfig;+use crate::schema_diff::SchemaDiffPreparationOptions;+use crate::sql_parser::meta::{validate_sql_meta_consistency, MetaData, MetaReader};++#[derive(Debug, Clone)]+#[allow(clippy::large_enum_variant)]+pub enum InputSource {+ DdlFiles(Vec<PathBuf>),+ DatabaseConnection(ConnectionConfig),+ GitDiff { repo_path: PathBuf, base_commit: String, target_commit: String },+ MetaData(MetaData),+}++#[derive(Debug, Clone)]+pub struct ResolvedInput {+ pub source: InputSource,+ pub meta: Option<MetaData>,+ pub ddl_sql: Option<String>,+ pub has_errors: bool,+ pub warnings: Vec<String>,+}++pub struct InputResolver;++impl InputResolver {+ pub fn discover_ddl_files(dir: &Path) -> Vec<PathBuf> {+ let mut files = Vec::new();+ if !dir.is_dir() {+ return files;+ }+ let entries = match std::fs::read_dir(dir) {+ Ok(e) => e,+ Err(_) => return files,+ };+ for entry in entries.flatten() {+ let path = entry.path();+ if path.is_dir() {+ files.extend(Self::discover_ddl_files(&path));+ continue;+ }+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");+ if matches!(ext, "sql" | "ddl" | "txt") {+ let file_name = path.file_name().and_then(|n| n.to_str()).unwrap_or("");+ if !file_name.starts_with('.') {+ files.push(path);+ }+ }+ }+ files+ }++ pub fn load_meta_for(sql_path: &Path) -> Option<MetaData> {+ let dir = sql_path.parent()?;+ let stem = sql_path.file_stem().and_then(|s| s.to_str())?;+ for ext in &["meta.json", "meta.yaml", "meta.yml"] {+ let meta_path = dir.join(format!("{}.{}", stem, ext));+ if meta_path.exists() {+ if let Ok(meta) = MetaReader::from_file(&meta_path) {+ return Some(meta);+ }+ }+ }+ let meta_path = dir.join(".dbmeta.json");+ if meta_path.exists() {+ if let Ok(meta) = MetaReader::from_file(&meta_path) {+ return Some(meta);+ }+ }+ None+ }++ pub fn resolve(inputs: Vec<InputSource>) -> ResolvedInput {+ let mut meta: Option<MetaData> = None;+ let mut sql_parts: Vec<String> = Vec::new();+ let mut warnings: Vec<String> = Vec::new();+ let mut live_db: Option<ConnectionConfig> = None;++ for input in inputs {+ match input {+ InputSource::DdlFiles(files) => {+ for file in files {+ if let Ok(content) = std::fs::read_to_string(&file) {+ if let Some(file_meta) = Self::load_meta_for(&file) {+ let mw = validate_sql_meta_consistency(&content, &file_meta);+ warnings.extend(mw.into_iter().map(|w| format!("{}: {}", file.display(), w)));+ meta = Self::merge_meta(meta.take(), Some(file_meta));+ }+ sql_parts.push(content);+ } else {+ warnings.push(format!("Cannot read DDL file: {}", file.display()));+ }+ }+ }+ InputSource::DatabaseConnection(config) => {+ live_db = Some(config);+ }+ InputSource::GitDiff { repo_path, base_commit, target_commit } => {+ match crate::sql_parser::git::GitDiffScanner::new(&repo_path, &base_commit, &target_commit) {+ Ok(scanner) => match scanner.scan() {+ Ok(entries) => {+ for entry in entries {+ sql_parts.push(entry.sql_content);+ }+ }+ Err(e) => warnings.push(format!("Git diff scan error: {e}")),+ },+ Err(e) => warnings.push(format!("Git scanner init error: {e}")),+ }+ }+ InputSource::MetaData(m) => {+ meta = Self::merge_meta(meta.take(), Some(m));+ }+ }+ }++ if let Some(ref meta_data) = meta {+ let mw = MetaReader::validate_consistency(meta_data);+ warnings.extend(mw);+ }++ let source = if let Some(config) = live_db {+ InputSource::DatabaseConnection(config)+ } else {+ InputSource::DdlFiles(Vec::new())+ };++ ResolvedInput {+ source,+ meta,+ ddl_sql: if sql_parts.is_empty() { None } else { Some(sql_parts.join("\n\n")) },+ has_errors: warnings.iter().any(|w| w.starts_with("Cannot read") || w.contains("error")),+ warnings,+ }+ }++ fn merge_meta(existing: Option<MetaData>, incoming: Option<MetaData>) -> Option<MetaData> {+ match (existing, incoming) {+ (None, incoming) => incoming,+ (existing, None) => existing,+ (Some(mut e), Some(i)) => {+ e.dialect = e.dialect.or(i.dialect);+ e.version = e.version.or(i.version);+ e.charset = e.charset.or(i.charset);+ e.collation = e.collation.or(i.collation);+ e.sql_mode = e.sql_mode.or(i.sql_mode);+ e.explicit_dependencies.extend(i.explicit_dependencies);+ Some(e)+ }+ }+ }++ pub fn normalize_to_diff_options(resolved: ResolvedInput) -> (SchemaDiffPreparationOptions, Vec<String>) {+ let mut options = SchemaDiffPreparationOptions {+ source_tables: Vec::new(),+ target_tables: Vec::new(),+ source_details: Vec::new(),+ target_details: Vec::new(),+ source_functions: Vec::new(),+ target_functions: Vec::new(),+ source_sequences: Vec::new(),+ target_sequences: Vec::new(),+ source_rules: Vec::new(),+ target_rules: Vec::new(),+ source_owners: Vec::new(),+ target_owners: Vec::new(),+ database_type: crate::models::connection::DatabaseType::Mysql,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ ..Default::default()+ };++ if let Some(ref meta) = resolved.meta {+ if let Some(ref dialect) = meta.dialect {+ let db_type = dialect_to_database_type(dialect);+ options.database_type = db_type;+ }+ }++ (options, resolved.warnings)+ }+}++fn dialect_to_database_type(dialect: &str) -> crate::models::connection::DatabaseType {+ match dialect.to_ascii_lowercase().as_str() {+ "mysql" | "mariadb" | "tidb" => crate::models::connection::DatabaseType::Mysql,+ "postgres" | "postgresql" => crate::models::connection::DatabaseType::Postgres,+ "sqlite" => crate::models::connection::DatabaseType::Sqlite,+ "sqlserver" | "mssql" => crate::models::connection::DatabaseType::SqlServer,+ "clickhouse" => crate::models::connection::DatabaseType::ClickHouse,+ "duckdb" => crate::models::connection::DatabaseType::DuckDb,+ "oracle" => crate::models::connection::DatabaseType::Oracle,+ _ => crate::models::connection::DatabaseType::Mysql,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::io::Write;++ #[test]+ fn discovers_sql_files_in_directory() {+ let dir = std::env::temp_dir().join("dbx_test_ddl_discover");+ let _ = std::fs::create_dir_all(&dir);+ let mut f1 = std::fs::File::create(dir.join("schema.sql")).unwrap();+ f1.write_all(b"CREATE TABLE t (id INT);").unwrap();+ let mut f2 = std::fs::File::create(dir.join("data.ddl")).unwrap();+ f2.write_all(b"INSERT INTO t VALUES (1);").unwrap();+ let _hidden = std::fs::File::create(dir.join(".ignore.sql")).unwrap();++ let files = InputResolver::discover_ddl_files(&dir);+ let names: Vec<String> =+ files.iter().filter_map(|f| f.file_name().and_then(|n| n.to_str()).map(|s| s.to_string())).collect();+ assert!(names.contains(&"schema.sql".to_string()));+ assert!(names.contains(&"data.ddl".to_string()));+ assert!(!names.contains(&".ignore.sql".to_string()));++ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn loads_meta_file_for_sql() {+ let dir = std::env::temp_dir().join("dbx_test_meta_load");+ let _ = std::fs::create_dir_all(&dir);+ let sql_path = dir.join("test.sql");+ let meta_path = dir.join("test.meta.json");+ std::fs::write(&sql_path, "CREATE TABLE t (id INT);").unwrap();+ std::fs::write(&meta_path, r#"{"dialect": "postgres", "version": "15"}"#).unwrap();++ let meta = InputResolver::load_meta_for(&sql_path);+ assert!(meta.is_some());+ assert_eq!(meta.unwrap().dialect.as_deref(), Some("postgres"));++ let _ = std::fs::remove_dir_all(&dir);+ }++ #[test]+ fn normalize_uses_meta_dialect() {+ let resolved = ResolvedInput {+ source: InputSource::DdlFiles(Vec::new()),+ meta: Some(MetaData {+ dialect: Some("postgres".into()),+ version: None,+ charset: None,+ collation: None,+ sql_mode: None,+ explicit_dependencies: std::collections::HashMap::new(),+ }),+ ddl_sql: Some("CREATE TABLE t (id INT);".into()),+ has_errors: false,+ warnings: Vec::new(),+ };+ let (options, _) = InputResolver::normalize_to_diff_options(resolved);+ assert_eq!(options.database_type, crate::models::connection::DatabaseType::Postgres);+ }++ #[test]+ fn resolve_adds_has_errors_on_failed_read() {+ let resolved = InputResolver::resolve(vec![InputSource::DdlFiles(vec![PathBuf::from(+ r"C:\non_existent_dir\nonexistent.sql",+ )])]);+ assert!(resolved.has_errors);+ assert_eq!(resolved.warnings.len(), 1);+ }++ #[test]+ fn resolve_merges_meta_from_multiple_sources() {+ let meta1 = InputSource::MetaData(MetaData {+ dialect: Some("mysql".into()),+ version: Some("8.0".into()),+ charset: None,+ collation: None,+ sql_mode: None,+ explicit_dependencies: std::collections::HashMap::new(),+ });+ let meta2 = InputSource::MetaData(MetaData {+ dialect: None,+ version: None,+ charset: Some("utf8mb4".into()),+ collation: None,+ sql_mode: None,+ explicit_dependencies: std::collections::HashMap::new(),+ });+ let resolved = InputResolver::resolve(vec![meta1, meta2]);+ assert_eq!(resolved.meta.as_ref().and_then(|m| m.dialect.as_deref()), Some("mysql"));+ assert_eq!(resolved.meta.as_ref().and_then(|m| m.charset.as_deref()), Some("utf8mb4"));+ }++ #[test]+ fn empty_ddl_dir_returns_no_files() {+ let dir = std::env::temp_dir().join("dbx_test_empty_ddl");+ let _ = std::fs::create_dir_all(&dir);+ let files = InputResolver::discover_ddl_files(&dir);+ assert!(files.is_empty());+ let _ = std::fs::remove_dir_all(&dir);+ }+}diff --git a/crates/dbx-core/src/sql_parser/meta.rs b/crates/dbx-core/src/sql_parser/meta.rsnew file mode 100644index 0000000000..454e2428ae--- /dev/null+++ b/crates/dbx-core/src/sql_parser/meta.rs@@ -0,0 +1,233 @@+use std::collections::HashMap;+use std::path::Path;++use serde::{Deserialize, Serialize};++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct MetaData {+ #[serde(default)]+ pub dialect: Option<String>,+ #[serde(default)]+ pub version: Option<String>,+ #[serde(default)]+ pub charset: Option<String>,+ #[serde(default)]+ pub collation: Option<String>,+ #[serde(default)]+ pub sql_mode: Option<String>,+ #[serde(default, skip_serializing_if = "HashMap::is_empty")]+ pub explicit_dependencies: HashMap<String, Vec<String>>,+}++pub struct MetaReader;++impl MetaReader {+ pub fn from_file(path: &Path) -> Result<MetaData, String> {+ let content = std::fs::read_to_string(path).map_err(|e| format!("Failed to read meta file: {e}"))?;+ let ext = path.extension().and_then(|e| e.to_str()).unwrap_or("");+ match ext {+ "json" => Self::from_json(&content),+ "yaml" | "yml" => Self::from_yaml(&content),+ _ => Self::from_json(&content),+ }+ }++ pub fn from_json(content: &str) -> Result<MetaData, String> {+ serde_json::from_str(content).map_err(|e| format!("Invalid meta JSON: {e}"))+ }++ pub fn from_yaml(content: &str) -> Result<MetaData, String> {+ serde_yaml::from_str(content).map_err(|e| format!("Invalid meta YAML: {e}"))+ }++ pub fn to_json(meta: &MetaData) -> Result<String, String> {+ serde_json::to_string_pretty(meta).map_err(|e| format!("Serialize meta error: {e}"))+ }++ pub fn validate_consistency(meta: &MetaData) -> Vec<String> {+ let mut warnings = Vec::new();+ if let Some(ref dialect) = meta.dialect {+ let lower = dialect.to_ascii_lowercase();+ let known = [+ "mysql",+ "postgres",+ "postgresql",+ "sqlite",+ "mssql",+ "sqlserver",+ "clickhouse",+ "duckdb",+ "oracle",+ "tidb",+ "mariadb",+ ];+ if !known.contains(&lower.as_str()) {+ warnings.push(format!("Unknown dialect '{}' in metadata", meta.dialect.as_ref().unwrap()));+ }+ }+ if let Some(ref version) = meta.version {+ let cleaned = version.trim_start_matches(|c: char| c.is_ascii_alphabetic() || c == 'v' || c == 'V');+ let is_valid = !cleaned.is_empty()+ && cleaned.chars().all(|c| c.is_ascii_digit() || c == '.' || c == '-')+ && cleaned.chars().any(|c| c.is_ascii_digit());+ if !is_valid {+ warnings.push(format!("Unusual version format '{}'", version));+ }+ }+ warnings+ }+}++pub fn validate_sql_meta_consistency(sql: &str, meta: &MetaData) -> Vec<String> {+ let mut warnings = Vec::new();+ if let Some(ref charset) = meta.charset {+ if !charset_mentions_match(sql, charset, meta.dialect.as_deref()) {+ warnings.push(format!("SQL content does not reference charset '{}' from metadata", charset));+ }+ }+ warnings+}++fn charset_mentions_match(sql: &str, charset: &str, dialect: Option<&str>) -> bool {+ let sql_upper = sql.to_ascii_uppercase();+ let charset_upper = charset.to_ascii_uppercase();+ let is_pg = dialect.is_some_and(|d| matches!(d.to_ascii_lowercase().as_str(), "postgres" | "postgresql"));+ if is_pg {+ sql_upper.contains(&format!("ENCODING '{}'", charset_upper))+ || sql_upper.contains(&format!("ENCODING '{}'", charset_upper.to_ascii_lowercase()))+ } else {+ let pattern = format!("CHARACTER SET {}", charset_upper);+ sql_upper.contains(&pattern) || sql_upper.contains(&format!("CHARSET {}", charset_upper))+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn reads_valid_json_metadata() {+ let json = r#"{+ "dialect": "mysql",+ "version": "8.0",+ "charset": "utf8mb4",+ "explicitDependencies": {+ "view_orders": ["orders", "users"]+ }+ }"#;+ let meta = MetaReader::from_json(json).unwrap();+ assert_eq!(meta.dialect.as_deref(), Some("mysql"));+ assert_eq!(meta.version.as_deref(), Some("8.0"));+ assert_eq!(+ meta.explicit_dependencies.get("view_orders").map(|v| v.as_slice()),+ Some(&["orders".to_string(), "users".to_string()][..])+ );+ }++ #[test]+ fn reads_valid_yaml_metadata() {+ let yaml = r#"+dialect: postgres+version: "15"+charset: UTF8+explicitDependencies:+ expensive_view: [table_a, table_b]+"#;+ let meta = MetaReader::from_yaml(yaml).unwrap();+ assert_eq!(meta.dialect.as_deref(), Some("postgres"));+ assert_eq!(meta.explicit_dependencies.get("expensive_view").map(|v| v.len()), Some(2));+ }++ #[test]+ fn validates_known_dialect() {+ let meta = MetaData {+ dialect: Some("mysql".into()),+ version: Some("8.0".into()),+ charset: None,+ collation: None,+ sql_mode: None,+ explicit_dependencies: HashMap::new(),+ };+ assert!(MetaReader::validate_consistency(&meta).is_empty());+ }++ #[test]+ fn warns_unknown_dialect() {+ let meta = MetaData {+ dialect: Some("fakedb".into()),+ version: None,+ charset: None,+ collation: None,+ sql_mode: None,+ explicit_dependencies: HashMap::new(),+ };+ let warnings = MetaReader::validate_consistency(&meta);+ assert!(!warnings.is_empty());+ assert!(warnings[0].contains("fakedb"));+ }++ #[test]+ fn warns_unusual_version_format() {+ let meta = MetaData {+ dialect: Some("mysql".into()),+ version: Some("latest".into()),+ charset: None,+ collation: None,+ sql_mode: None,+ explicit_dependencies: HashMap::new(),+ };+ let warnings = MetaReader::validate_consistency(&meta);+ assert!(!warnings.is_empty());+ assert!(warnings[0].contains("latest"));+ }++ #[test]+ fn charset_consistency_check() {+ let meta = MetaData {+ dialect: Some("mysql".into()),+ version: Some("8.0".into()),+ charset: Some("utf8mb4".into()),+ collation: None,+ sql_mode: None,+ explicit_dependencies: HashMap::new(),+ };+ let sql = "CREATE TABLE t (c VARCHAR(100)) CHARACTER SET utf8mb4";+ assert!(validate_sql_meta_consistency(sql, &meta).is_empty());++ let sql_no_charset = "CREATE TABLE t (c VARCHAR(100))";+ let warnings = validate_sql_meta_consistency(sql_no_charset, &meta);+ assert!(!warnings.is_empty());+ assert!(warnings[0].contains("utf8mb4"));+ }++ #[test]+ fn empty_meta_has_no_warnings() {+ let meta = MetaData {+ dialect: None,+ version: None,+ charset: None,+ collation: None,+ sql_mode: None,+ explicit_dependencies: HashMap::new(),+ };+ assert!(MetaReader::validate_consistency(&meta).is_empty());+ }++ #[test]+ fn serializes_and_deserializes_roundtrip() {+ let meta = MetaData {+ dialect: Some("postgres".into()),+ version: Some("16".into()),+ charset: Some("UTF8".into()),+ collation: Some("en_US.UTF-8".into()),+ sql_mode: None,+ explicit_dependencies: HashMap::from([("v".into(), vec!["a".into(), "b".into()])]),+ };+ let json = MetaReader::to_json(&meta).unwrap();+ let restored = MetaReader::from_json(&json).unwrap();+ assert_eq!(restored.dialect, meta.dialect);+ assert_eq!(restored.version, meta.version);+ assert_eq!(restored.explicit_dependencies.len(), 1);+ }+}diff --git a/crates/dbx-core/src/sql_parser/mod.rs b/crates/dbx-core/src/sql_parser/mod.rsnew file mode 100644index 0000000000..ce38a77861--- /dev/null+++ b/crates/dbx-core/src/sql_parser/mod.rs@@ -0,0 +1,4 @@+pub mod ast_filter;+pub mod git;+pub mod input;+pub mod meta;diff --git a/crates/dbx-core/src/state_calibrator.rs b/crates/dbx-core/src/state_calibrator.rsnew file mode 100644index 0000000000..643346d4f8--- /dev/null+++ b/crates/dbx-core/src/state_calibrator.rs@@ -0,0 +1,838 @@+use std::collections::HashMap;++use chrono::Utc;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};+use uuid::Uuid;++use crate::schema_diff::normalize_definition;++// ============================================================================+// 6.1: State Data Structures+// ============================================================================++const DRIFT_NONE: f64 = 0.0;+const DRIFT_NEW_OBJECT: f64 = 0.3;+const DRIFT_SINGLE_SIDE: f64 = 0.33;+const DRIFT_IDENTICAL_CHANGE: f64 = 0.5;+const DRIFT_DELETED: f64 = 0.66;+const DRIFT_STALE_BASELINE: f64 = 0.8;+const DRIFT_CONFLICT: f64 = 1.0;+const DRIFT_PSEUDO: f64 = 0.0;++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct SemanticFingerprint {+ pub fingerprint: String,+ pub object_fingerprints: HashMap<String, String>,+}++impl SemanticFingerprint {+ pub fn compute(objects: &[ObjectDefinition]) -> Self {+ let mut object_fingerprints = HashMap::new();+ for obj in objects {+ let normalized = normalize_definition(&obj.definition);+ let hash = hex(Sha256::digest(normalized.as_bytes()));+ object_fingerprints.insert(obj.key(), hash);+ }++ let mut all_keys: Vec<&String> = object_fingerprints.keys().collect();+ all_keys.sort();+ let mut hasher = Sha256::new();+ for key in all_keys {+ hasher.update(key.as_bytes());+ hasher.update(b":");+ hasher.update(object_fingerprints[key].as_bytes());+ hasher.update(b";");+ }+ let fingerprint = hex(hasher.finalize());++ Self { fingerprint, object_fingerprints }+ }++ pub fn object_fingerprint(def: &str) -> String {+ let normalized = normalize_definition(def);+ hex(Sha256::digest(normalized.as_bytes()))+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ObjectDefinition {+ pub kind: ObjectKind,+ pub name: String,+ pub schema: Option<String>,+ pub definition: String,+}++impl ObjectDefinition {+ pub fn key(&self) -> String {+ match &self.schema {+ Some(schema) => format!("{}.{}.{}", self.kind.as_str(), schema, self.name),+ None => format!("{}.{}", self.kind.as_str(), self.name),+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, Hash)]+#[serde(rename_all = "snake_case")]+pub enum ObjectKind {+ Table,+ View,+ Function,+ Sequence,+ Rule,+ Permission,+}++impl ObjectKind {+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Table => "table",+ Self::View => "view",+ Self::Function => "function",+ Self::Sequence => "sequence",+ Self::Rule => "rule",+ Self::Permission => "permission",+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct StateSnapshot {+ pub id: String,+ pub timestamp: String,+ pub label: String,+ pub objects: Vec<ObjectDefinition>,+ pub fingerprint: SemanticFingerprint,+}++impl StateSnapshot {+ pub fn new(label: &str, objects: Vec<ObjectDefinition>) -> Self {+ let fingerprint = SemanticFingerprint::compute(&objects);+ Self {+ id: Uuid::new_v4().to_string(),+ timestamp: Utc::now().to_rfc3339(),+ label: label.to_string(),+ objects,+ fingerprint,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum ObjectReconciliationStatus {+ Synced,+ SourceDrifted,+ TargetDrifted,+ BothDriftedIdentical,+ BothDriftedConflict,+ DeletedInSource,+ DeletedInTarget,+ NewInSource,+ NewInTarget,+ NewInBoth,+ BaselineOnly,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ObjectReconciliation {+ pub object_key: String,+ pub kind: ObjectKind,+ pub name: String,+ pub status: ObjectReconciliationStatus,+ pub baseline_fingerprint: Option<String>,+ pub source_fingerprint: Option<String>,+ pub target_fingerprint: Option<String>,+ pub source_definition: Option<String>,+ pub target_definition: Option<String>,+ pub drift_score: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ReconciliationResult {+ pub baseline_id: String,+ pub source_id: String,+ pub target_id: String,+ pub timestamp: String,+ pub total_objects: usize,+ pub synced_count: usize,+ pub drifted_count: usize,+ pub conflict_count: usize,+ pub object_reconciliations: Vec<ObjectReconciliation>,+}++pub fn reconcile_three_way(+ baseline: &StateSnapshot,+ source_id: &str,+ source: &[ObjectDefinition],+ target_id: &str,+ target: &[ObjectDefinition],+) -> ReconciliationResult {+ let baseline_map: HashMap<String, &ObjectDefinition> = baseline.objects.iter().map(|o| (o.key(), o)).collect();+ let source_map: HashMap<String, &ObjectDefinition> = source.iter().map(|o| (o.key(), o)).collect();+ let target_map: HashMap<String, &ObjectDefinition> = target.iter().map(|o| (o.key(), o)).collect();++ let all_keys: Vec<String> = {+ let mut keys: Vec<String> = Vec::new();+ let mut seen = std::collections::HashSet::new();+ for map in [&baseline_map, &source_map, &target_map] {+ for key in map.keys() {+ if seen.insert(key.clone()) {+ keys.push(key.clone());+ }+ }+ }+ keys.sort();+ keys+ };++ let mut object_reconciliations = Vec::new();+ let mut synced = 0;+ let mut drifted = 0;+ let mut conflicts = 0;++ for key in &all_keys {+ let b_obj = baseline_map.get(key);+ let s_obj = source_map.get(key);+ let t_obj = target_map.get(key);++ let b_fp = b_obj.map(|o| SemanticFingerprint::object_fingerprint(&o.definition));+ let s_fp = s_obj.map(|o| SemanticFingerprint::object_fingerprint(&o.definition));+ let t_fp = t_obj.map(|o| SemanticFingerprint::object_fingerprint(&o.definition));++ let (status, drift_score) = classify_reconciliation(&b_fp, &s_fp, &t_fp);++ match status {+ ObjectReconciliationStatus::Synced | ObjectReconciliationStatus::NewInBoth => synced += 1,+ ObjectReconciliationStatus::BothDriftedConflict => {+ drifted += 1;+ conflicts += 1;+ }+ _ => drifted += 1,+ }++ let kind = b_obj.or(s_obj).or(t_obj).map(|o| o.kind.clone()).unwrap_or(ObjectKind::Table);++ let name = b_obj.or(s_obj).or(t_obj).map(|o| o.name.clone()).unwrap_or_default();++ object_reconciliations.push(ObjectReconciliation {+ object_key: key.clone(),+ kind,+ name,+ status,+ baseline_fingerprint: b_fp,+ source_fingerprint: s_fp,+ target_fingerprint: t_fp,+ source_definition: s_obj.map(|o| o.definition.clone()),+ target_definition: t_obj.map(|o| o.definition.clone()),+ drift_score,+ });+ }++ ReconciliationResult {+ baseline_id: baseline.id.clone(),+ source_id: source_id.to_string(),+ target_id: target_id.to_string(),+ timestamp: Utc::now().to_rfc3339(),+ total_objects: all_keys.len(),+ synced_count: synced,+ drifted_count: drifted,+ conflict_count: conflicts,+ object_reconciliations,+ }+}++fn classify_reconciliation(+ b_fp: &Option<String>,+ s_fp: &Option<String>,+ t_fp: &Option<String>,+) -> (ObjectReconciliationStatus, f64) {+ match (b_fp, s_fp, t_fp) {+ // All present+ (Some(b), Some(s), Some(t)) => {+ if b == s && s == t {+ (ObjectReconciliationStatus::Synced, DRIFT_NONE)+ } else if b == s && s != t {+ (ObjectReconciliationStatus::TargetDrifted, DRIFT_SINGLE_SIDE)+ } else if b == t && s != t {+ (ObjectReconciliationStatus::SourceDrifted, DRIFT_SINGLE_SIDE)+ } else if s == t && b != s {+ (ObjectReconciliationStatus::BothDriftedIdentical, DRIFT_IDENTICAL_CHANGE)+ } else {+ (ObjectReconciliationStatus::BothDriftedConflict, DRIFT_CONFLICT)+ }+ }+ // Baseline present, others may be absent+ (Some(_), None, Some(_)) => (ObjectReconciliationStatus::DeletedInSource, DRIFT_DELETED),+ (Some(_), Some(_), None) => (ObjectReconciliationStatus::DeletedInTarget, DRIFT_DELETED),+ (Some(_), None, None) => (ObjectReconciliationStatus::BaselineOnly, DRIFT_STALE_BASELINE),+ // Baseline absent, one or both present+ (None, Some(s), Some(t)) => {+ if s == t {+ (ObjectReconciliationStatus::NewInBoth, DRIFT_NONE)+ } else {+ (ObjectReconciliationStatus::BothDriftedConflict, DRIFT_CONFLICT)+ }+ }+ (None, Some(_), None) => (ObjectReconciliationStatus::NewInSource, DRIFT_NONE),+ (None, None, Some(_)) => (ObjectReconciliationStatus::NewInTarget, DRIFT_NONE),+ (None, None, None) => (ObjectReconciliationStatus::Synced, DRIFT_NONE),+ }+}++// ============================================================================+// 6.2: Semantic Fingerprints — Drift Detection & Scoring+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DriftReport {+ pub has_drift: bool,+ pub drifted_objects: Vec<DriftedObject>,+ pub pseudo_drift_count: usize,+ pub real_drift_count: usize,+ pub overall_drift_score: f64,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DriftedObject {+ pub object_key: String,+ pub baseline_fingerprint: String,+ pub current_fingerprint: String,+ pub is_pseudo_drift: bool,+ pub score: f64,+}++pub fn detect_drift(baseline: &StateSnapshot, current: &[ObjectDefinition]) -> DriftReport {+ let current_fp = SemanticFingerprint::compute(current);+ let overall_has_drift = baseline.fingerprint.fingerprint != current_fp.fingerprint;++ let current_map: HashMap<String, &ObjectDefinition> = current.iter().map(|o| (o.key(), o)).collect();++ let mut drifted_objects = Vec::new();+ let mut pseudo = 0;+ let mut real = 0;++ for obj in &baseline.objects {+ let b_fp = baseline.fingerprint.object_fingerprints.get(&obj.key()).cloned().unwrap_or_default();+ let c_fp = current_fp.object_fingerprints.get(&obj.key()).cloned().unwrap_or_default();++ if b_fp != c_fp {+ let is_pseudo =+ filter_pseudo_drift(&obj.definition, current_map.get(&obj.key()).map(|o| o.definition.as_str()));+ if is_pseudo {+ pseudo += 1;+ } else {+ real += 1;+ }+ drifted_objects.push(DriftedObject {+ object_key: obj.key(),+ baseline_fingerprint: b_fp,+ current_fingerprint: c_fp,+ is_pseudo_drift: is_pseudo,+ score: if is_pseudo { DRIFT_PSEUDO } else { DRIFT_IDENTICAL_CHANGE },+ });+ }+ }++ // Check for new objects in current+ for obj in current {+ if !baseline.fingerprint.object_fingerprints.contains_key(&obj.key()) {+ real += 1;+ drifted_objects.push(DriftedObject {+ object_key: obj.key(),+ baseline_fingerprint: String::new(),+ current_fingerprint: current_fp.object_fingerprints.get(&obj.key()).cloned().unwrap_or_default(),+ is_pseudo_drift: false,+ score: DRIFT_NEW_OBJECT,+ });+ }+ }++ let total = drifted_objects.len();+ let overall_drift_score =+ if total == 0 { 0.0 } else { drifted_objects.iter().map(|d| d.score).sum::<f64>() / total as f64 };++ DriftReport {+ has_drift: overall_has_drift || !drifted_objects.is_empty(),+ drifted_objects,+ pseudo_drift_count: pseudo,+ real_drift_count: real,+ overall_drift_score,+ }+}++fn filter_pseudo_drift(baseline_def: &str, current_def: Option<&str>) -> bool {+ let Some(cur_def) = current_def else {+ return false;+ };++ let b_norm = normalize_definition(baseline_def);+ let c_norm = normalize_definition(cur_def);++ // Pseudo-drift: normalized forms are equal (whitespace-only changes)+ if b_norm == c_norm {+ return true;+ }++ // Pseudo-drift: only comment lines changed+ let b_no_comments = strip_sql_comments(&b_norm);+ let c_no_comments = strip_sql_comments(&c_norm);+ if b_no_comments == c_no_comments {+ return true;+ }++ false+}++fn strip_sql_comments(sql: &str) -> String {+ sql.lines()+ .filter(|line| {+ let trimmed = line.trim();+ !(trimmed.starts_with("--") || trimmed.starts_with("//") || trimmed.starts_with('#'))+ })+ .collect::<Vec<_>>()+ .join("\n")+}++fn hex(data: sha2::digest::Output<Sha256>) -> String {+ data.iter().map(|b| format!("{:02x}", b)).collect()+}++// ============================================================================+// 6.3: Smart Baseline Reset+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]+#[serde(rename_all = "snake_case")]+pub enum RebaseResolution {+ AcceptSource,+ AcceptTarget,+ AcceptBaseline,+ ManualReview,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct ConflictItem {+ pub object_key: String,+ pub resolution: RebaseResolution,+ pub baseline_fingerprint: Option<String>,+ pub source_fingerprint: Option<String>,+ pub target_fingerprint: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RebasePlan {+ pub conflicts: Vec<ConflictItem>,+ pub proposed_objects: Vec<ObjectDefinition>,+ pub requires_manual_review: bool,+}++pub fn build_rebase_plan(+ baseline: &StateSnapshot,+ source: &[ObjectDefinition],+ target: &[ObjectDefinition],+ auto_resolve: bool,+) -> RebasePlan {+ let result = reconcile_three_way(baseline, "", source, "", target);+ let mut conflicts = Vec::new();+ let mut proposed_objects: Vec<ObjectDefinition> = Vec::new();+ let mut requires_manual = false;++ let source_map: HashMap<String, &ObjectDefinition> = source.iter().map(|o| (o.key(), o)).collect();+ let target_map: HashMap<String, &ObjectDefinition> = target.iter().map(|o| (o.key(), o)).collect();++ for rec in &result.object_reconciliations {+ match rec.status {+ ObjectReconciliationStatus::Synced | ObjectReconciliationStatus::BothDriftedIdentical => {+ if let Some(obj) = source_map.get(&rec.object_key).or_else(|| target_map.get(&rec.object_key)) {+ proposed_objects.push((*obj).clone());+ }+ }+ ObjectReconciliationStatus::TargetDrifted => {+ if auto_resolve {+ if let Some(obj) = target_map.get(&rec.object_key) {+ proposed_objects.push((*obj).clone());+ }+ conflicts.push(ConflictItem {+ object_key: rec.object_key.clone(),+ resolution: RebaseResolution::AcceptTarget,+ baseline_fingerprint: rec.baseline_fingerprint.clone(),+ source_fingerprint: rec.source_fingerprint.clone(),+ target_fingerprint: rec.target_fingerprint.clone(),+ });+ } else {+ requires_manual = true;+ conflicts.push(ConflictItem {+ object_key: rec.object_key.clone(),+ resolution: RebaseResolution::ManualReview,+ baseline_fingerprint: rec.baseline_fingerprint.clone(),+ source_fingerprint: rec.source_fingerprint.clone(),+ target_fingerprint: rec.target_fingerprint.clone(),+ });+ }+ }+ ObjectReconciliationStatus::SourceDrifted => {+ if auto_resolve {+ if let Some(obj) = source_map.get(&rec.object_key) {+ proposed_objects.push((*obj).clone());+ }+ conflicts.push(ConflictItem {+ object_key: rec.object_key.clone(),+ resolution: RebaseResolution::AcceptSource,+ baseline_fingerprint: rec.baseline_fingerprint.clone(),+ source_fingerprint: rec.source_fingerprint.clone(),+ target_fingerprint: rec.target_fingerprint.clone(),+ });+ } else {+ requires_manual = true;+ conflicts.push(ConflictItem {+ object_key: rec.object_key.clone(),+ resolution: RebaseResolution::ManualReview,+ baseline_fingerprint: rec.baseline_fingerprint.clone(),+ source_fingerprint: rec.source_fingerprint.clone(),+ target_fingerprint: rec.target_fingerprint.clone(),+ });+ }+ }+ ObjectReconciliationStatus::BothDriftedConflict => {+ requires_manual = true;+ conflicts.push(ConflictItem {+ object_key: rec.object_key.clone(),+ resolution: RebaseResolution::ManualReview,+ baseline_fingerprint: rec.baseline_fingerprint.clone(),+ source_fingerprint: rec.source_fingerprint.clone(),+ target_fingerprint: rec.target_fingerprint.clone(),+ });+ }+ ObjectReconciliationStatus::NewInBoth | ObjectReconciliationStatus::NewInSource => {+ if let Some(obj) = source_map.get(&rec.object_key) {+ proposed_objects.push((*obj).clone());+ }+ }+ ObjectReconciliationStatus::NewInTarget => {+ if let Some(obj) = target_map.get(&rec.object_key) {+ proposed_objects.push((*obj).clone());+ }+ }+ ObjectReconciliationStatus::DeletedInSource | ObjectReconciliationStatus::DeletedInTarget => {+ // Object is deleted in at least one source, don't include it+ }+ ObjectReconciliationStatus::BaselineOnly => {+ // Only in baseline, not in source or target — drop it+ }+ }+ }++ RebasePlan { conflicts, proposed_objects, requires_manual_review: requires_manual }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct RebaseHistoryEntry {+ pub id: String,+ pub timestamp: String,+ pub previous_baseline_id: String,+ pub new_baseline_id: String,+ pub object_count: usize,+ pub conflict_count: usize,+ pub auto_resolved: bool,+ pub notes: String,+}++impl RebaseHistoryEntry {+ pub fn new(+ previous_baseline_id: &str,+ new_baseline_id: &str,+ object_count: usize,+ conflict_count: usize,+ auto_resolved: bool,+ notes: &str,+ ) -> Self {+ Self {+ id: Uuid::new_v4().to_string(),+ timestamp: Utc::now().to_rfc3339(),+ previous_baseline_id: previous_baseline_id.to_string(),+ new_baseline_id: new_baseline_id.to_string(),+ object_count,+ conflict_count,+ auto_resolved,+ notes: notes.to_string(),+ }+ }+}++// ============================================================================+// Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;++ fn make_obj(kind: ObjectKind, name: &str, definition: &str) -> ObjectDefinition {+ ObjectDefinition { kind, name: name.to_string(), schema: None, definition: definition.to_string() }+ }++ fn make_table(name: &str, def: &str) -> ObjectDefinition {+ make_obj(ObjectKind::Table, name, def)+ }++ // --- 6.4: Three-way merge 9 combinations ---++ #[test]+ fn test_twm_all_synced() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let source = objs.clone();+ let target = objs.clone();+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.synced_count, 1);+ assert_eq!(result.drifted_count, 0);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::Synced);+ }++ #[test]+ fn test_twm_target_drifted() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let source = objs.clone();+ let target = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.drifted_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::TargetDrifted);+ }++ #[test]+ fn test_twm_source_drifted() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let source = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let target = objs.clone();+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.drifted_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::SourceDrifted);+ }++ #[test]+ fn test_twm_both_drifted_identical() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs);+ let source = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let target = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.drifted_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::BothDriftedIdentical);+ }++ #[test]+ fn test_twm_both_drifted_conflict() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs);+ let source = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let target = vec![make_table("t1", "CREATE TABLE t1 (name TEXT)")];+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.conflict_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::BothDriftedConflict);+ }++ #[test]+ fn test_twm_target_deleted() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let source = objs.clone();+ let target: Vec<ObjectDefinition> = vec![];+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.drifted_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::DeletedInTarget);+ }++ #[test]+ fn test_twm_source_deleted() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let source: Vec<ObjectDefinition> = vec![];+ let target = objs.clone();+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.drifted_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::DeletedInSource);+ }++ #[test]+ fn test_twm_new_in_both() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", vec![]);+ let source = objs.clone();+ let target = objs.clone();+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.synced_count, 1);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::NewInBoth);+ }++ #[test]+ fn test_twm_new_in_source_only() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", vec![]);+ let source = objs.clone();+ let target: Vec<ObjectDefinition> = vec![];+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.synced_count, 0);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::NewInSource);+ }++ #[test]+ fn test_twm_baseline_only() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs);+ let source: Vec<ObjectDefinition> = vec![];+ let target: Vec<ObjectDefinition> = vec![];+ let result = reconcile_three_way(&baseline, "", &source, "", &target);+ assert_eq!(result.object_reconciliations[0].status, ObjectReconciliationStatus::BaselineOnly);+ }++ // --- Fingerprint stability tests ---++ #[test]+ fn test_fingerprint_equivalent_ddl_same() {+ let ddl1 = "CREATE TABLE t1 (id INT, name TEXT)";+ let ddl2 = "CREATE TABLE t1 (id INT, name TEXT)";+ assert_eq!(SemanticFingerprint::object_fingerprint(ddl1), SemanticFingerprint::object_fingerprint(ddl2));+ }++ #[test]+ fn test_fingerprint_crlf_vs_lf() {+ let ddl1 = "CREATE TABLE t1 (id INT)\n";+ let ddl2 = "CREATE TABLE t1 (id INT)\r\n";+ assert_eq!(SemanticFingerprint::object_fingerprint(ddl1), SemanticFingerprint::object_fingerprint(ddl2));+ }++ #[test]+ fn test_fingerprint_tabs_vs_spaces() {+ let ddl1 = "CREATE TABLE t1 (id INT)";+ let ddl2 = "CREATE\tTABLE\tt1\t(id\tINT)";+ assert_eq!(SemanticFingerprint::object_fingerprint(ddl1), SemanticFingerprint::object_fingerprint(ddl2));+ }++ #[test]+ fn test_fingerprint_different_ddl_different() {+ let ddl1 = "CREATE TABLE t1 (id INT)";+ let ddl2 = "CREATE TABLE t1 (id BIGINT)";+ assert_ne!(SemanticFingerprint::object_fingerprint(ddl1), SemanticFingerprint::object_fingerprint(ddl2));+ }++ // --- Drift detection tests ---++ #[test]+ fn test_detect_drift_no_drift() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let report = detect_drift(&baseline, &objs);+ assert!(!report.has_drift);+ assert_eq!(report.drifted_objects.len(), 0);+ }++ #[test]+ fn test_detect_drift_with_drift() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs);+ let current = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let report = detect_drift(&baseline, ¤t);+ assert!(report.has_drift);+ assert_eq!(report.real_drift_count, 1);+ assert_eq!(report.pseudo_drift_count, 0);+ }++ #[test]+ fn test_detect_pseudo_drift_whitespace() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs);+ let current = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let report = detect_drift(&baseline, ¤t);+ // Whitespace-only changes normalize to same fingerprint → no drift+ assert!(!report.has_drift);+ assert_eq!(report.pseudo_drift_count, 0);+ assert_eq!(report.real_drift_count, 0);+ }++ #[test]+ fn test_detect_pseudo_drift_comments_only() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)\n-- this is a comment")];+ let baseline = StateSnapshot::new("baseline", objs);+ let current = vec![make_table("t1", "CREATE TABLE t1 (id INT)\n-- updated comment")];+ let report = detect_drift(&baseline, ¤t);+ assert!(report.has_drift);+ assert_eq!(report.pseudo_drift_count, 1);+ assert_eq!(report.real_drift_count, 0);+ }++ // --- Rebase plan tests ---++ #[test]+ fn test_rebase_plan_auto_resolve_synced() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let plan = build_rebase_plan(&baseline, &objs, &objs, true);+ assert!(!plan.requires_manual_review);+ assert_eq!(plan.proposed_objects.len(), 1);+ assert_eq!(plan.conflicts.len(), 0);+ }++ #[test]+ fn test_rebase_plan_auto_resolve_target_drifted() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs.clone());+ let source = objs.clone();+ let target = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let plan = build_rebase_plan(&baseline, &source, &target, true);+ assert!(!plan.requires_manual_review);+ assert_eq!(plan.conflicts.len(), 1);+ assert_eq!(plan.conflicts[0].resolution, RebaseResolution::AcceptTarget);+ }++ #[test]+ fn test_rebase_plan_requires_manual_on_conflict() {+ let objs = vec![make_table("t1", "CREATE TABLE t1 (id INT)")];+ let baseline = StateSnapshot::new("baseline", objs);+ let source = vec![make_table("t1", "CREATE TABLE t1 (id BIGINT)")];+ let target = vec![make_table("t1", "CREATE TABLE t1 (name TEXT)")];+ let plan = build_rebase_plan(&baseline, &source, &target, true);+ assert!(plan.requires_manual_review);+ assert_eq!(plan.conflicts[0].resolution, RebaseResolution::ManualReview);+ }++ #[test]+ fn test_rebase_history_entry_creation() {+ let entry = RebaseHistoryEntry::new("baseline-1", "baseline-2", 5, 1, true, "Auto-resolved");+ assert_eq!(entry.previous_baseline_id, "baseline-1");+ assert_eq!(entry.new_baseline_id, "baseline-2");+ assert_eq!(entry.object_count, 5);+ assert_eq!(entry.conflict_count, 1);+ assert!(entry.auto_resolved);+ }++ #[test]+ fn test_filter_pseudo_drift_pure_whitespace() {+ assert!(filter_pseudo_drift("CREATE TABLE t1 (id INT)", Some("CREATE TABLE t1 (id INT)")));+ }++ #[test]+ fn test_filter_pseudo_drift_comment_changes() {+ assert!(filter_pseudo_drift(+ "CREATE TABLE t1 (id INT)\n-- comment v1",+ Some("CREATE TABLE t1 (id INT)\n-- comment v2")+ ));+ }++ #[test]+ fn test_filter_pseudo_drift_real_change() {+ assert!(!filter_pseudo_drift("CREATE TABLE t1 (id INT)", Some("CREATE TABLE t1 (id BIGINT)")));+ }+}diff --git a/crates/dbx-core/src/state_persistence.rs b/crates/dbx-core/src/state_persistence.rsnew file mode 100644index 0000000000..7d8695ed2f--- /dev/null+++ b/crates/dbx-core/src/state_persistence.rs@@ -0,0 +1,1366 @@+use std::sync::Arc;++use aes_gcm::{+ aead::{rand_core::RngCore, Aead, KeyInit, OsRng},+ Aes256Gcm, Nonce,+};+use argon2::{Algorithm, Argon2, Params, Version};+use async_trait::async_trait;+use base64::Engine as _;+use serde::{Deserialize, Serialize};+use sha2::{Digest, Sha256};++use crate::models::connection::ConnectionConfig;+use crate::storage::Storage;++// ============================================================================+// 8.2: State Backend Plugin System+// ============================================================================++#[async_trait]+pub trait StateBackend: Send + Sync {+ async fn save(&self, key: &str, value: &[u8]) -> Result<(), String>;+ async fn save_with_content_type(&self, key: &str, value: &[u8], content_type: &str) -> Result<(), String>;+ async fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String>;+ async fn delete(&self, key: &str) -> Result<(), String>;+ async fn exists(&self, key: &str) -> Result<bool, String>;++ async fn compare_and_swap(&self, key: &str, old: Option<&[u8]>, new: &[u8]) -> Result<bool, String> {+ let _ = (key, old, new);+ Err("CAS not supported by this backend".to_string())+ }+}++// ============================================================================+// LocalBackend: SQLite-backed via existing Storage+// ============================================================================++pub struct LocalBackend {+ storage: Arc<Storage>,+}++impl LocalBackend {+ pub fn new(storage: Arc<Storage>) -> Self {+ Self { storage }+ }+}++#[async_trait]+impl StateBackend for LocalBackend {+ async fn save(&self, key: &str, value: &[u8]) -> Result<(), String> {+ self.storage.save_state(key, value, "application/octet-stream").await+ }++ async fn save_with_content_type(&self, key: &str, value: &[u8], content_type: &str) -> Result<(), String> {+ self.storage.save_state(key, value, content_type).await+ }++ async fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String> {+ self.storage.load_state(key).await.map(|opt| opt.map(|(data, _)| data))+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ self.storage.delete_state(key).await+ }++ async fn exists(&self, key: &str) -> Result<bool, String> {+ self.storage.state_exists(key).await+ }++ async fn compare_and_swap(&self, key: &str, old: Option<&[u8]>, new: &[u8]) -> Result<bool, String> {+ let expected_version = match old {+ Some(data) => {+ let entry: StateEntry =+ serde_json::from_slice(data).map_err(|e| format!("CAS deserialize error: {e}"))?;+ Some(entry.version)+ }+ None => None,+ };+ self.storage.compare_and_swap_state(key, expected_version, new, "application/json").await+ }+}++// ============================================================================+// RedisBackend+// ============================================================================++pub struct RedisBackend {+ client: redis::Client,+ prefix: String,+}++impl RedisBackend {+ pub fn new(redis_url: &str, prefix: &str) -> Result<Self, String> {+ let client = redis::Client::open(redis_url).map_err(|e| format!("redis connect error: {e}"))?;+ Ok(Self { client, prefix: prefix.to_string() })+ }++ fn prefixed(&self, key: &str) -> String {+ format!("{}:{}", self.prefix, key)+ }+}++#[async_trait]+impl StateBackend for RedisBackend {+ async fn save(&self, key: &str, value: &[u8]) -> Result<(), String> {+ let mut conn =+ self.client.get_multiplexed_async_connection().await.map_err(|e| format!("redis connection error: {e}"))?;+ let prefixed = self.prefixed(key);+ redis::cmd("SET")+ .arg(&[prefixed.as_bytes(), value])+ .query_async::<()>(&mut conn)+ .await+ .map_err(|e| format!("redis set error: {e}"))+ }++ async fn save_with_content_type(&self, key: &str, value: &[u8], _content_type: &str) -> Result<(), String> {+ self.save(key, value).await+ }++ async fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String> {+ let mut conn =+ self.client.get_multiplexed_async_connection().await.map_err(|e| format!("redis connection error: {e}"))?;+ let prefixed = self.prefixed(key);+ let result: Option<Vec<u8>> = redis::cmd("GET")+ .arg(&[prefixed.as_bytes()])+ .query_async(&mut conn)+ .await+ .map_err(|e| format!("redis get error: {e}"))?;+ Ok(result)+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ let mut conn =+ self.client.get_multiplexed_async_connection().await.map_err(|e| format!("redis connection error: {e}"))?;+ let prefixed = self.prefixed(key);+ redis::cmd("DEL")+ .arg(&[prefixed.as_bytes()])+ .query_async::<()>(&mut conn)+ .await+ .map_err(|e| format!("redis del error: {e}"))+ }++ async fn exists(&self, key: &str) -> Result<bool, String> {+ let mut conn =+ self.client.get_multiplexed_async_connection().await.map_err(|e| format!("redis connection error: {e}"))?;+ let prefixed = self.prefixed(key);+ let count: i64 = redis::cmd("EXISTS")+ .arg(&[prefixed.as_bytes()])+ .query_async(&mut conn)+ .await+ .map_err(|e| format!("redis exists error: {e}"))?;+ Ok(count > 0)+ }+}++// ============================================================================+// DBBackend: Generic SQL database backend+// ============================================================================++pub struct DBBackend {+ pool: deadpool_postgres::Pool,+ schema_table: String,+}++impl DBBackend {+ pub fn new(pool: deadpool_postgres::Pool, schema_table: &str) -> Self {+ assert!(!schema_table.is_empty(), "schema_table must not be empty");+ assert!(!schema_table.starts_with(|c: char| c.is_ascii_digit()), "schema_table must not start with a digit");+ assert!(+ schema_table.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'),+ "schema_table contains invalid characters: {schema_table:?}"+ );+ Self { pool, schema_table: schema_table.to_string() }+ }++ pub async fn ensure_table(&self) -> Result<(), String> {+ let client = self.pool.get().await.map_err(|e| format!("db pool error: {e}"))?;+ let stmt = format!(+ "CREATE TABLE IF NOT EXISTS {} (+ key TEXT PRIMARY KEY,+ payload BYTEA NOT NULL,+ version BIGINT NOT NULL DEFAULT 1,+ content_type TEXT NOT NULL DEFAULT 'application/octet-stream',+ created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()+ )",+ self.schema_table+ );+ client.batch_execute(&stmt).await.map_err(|e| format!("db create table error: {e}"))+ }+}++#[async_trait]+impl StateBackend for DBBackend {+ async fn save(&self, key: &str, value: &[u8]) -> Result<(), String> {+ self.save_with_content_type(key, value, "application/octet-stream").await+ }++ async fn save_with_content_type(&self, key: &str, value: &[u8], content_type: &str) -> Result<(), String> {+ let client = self.pool.get().await.map_err(|e| format!("db pool error: {e}"))?;+ let stmt = format!(+ "INSERT INTO {} (key, payload, content_type) VALUES ($1, $2, $3) \+ ON CONFLICT (key) DO UPDATE SET payload = $2, content_type = $3, \+ version = {}.version + 1, updated_at = NOW()",+ self.schema_table, self.schema_table+ );+ client+ .execute(&stmt, &[&key.to_string(), &value.to_vec(), &content_type.to_string()])+ .await+ .map_err(|e| format!("db upsert error: {e}"))?;+ Ok(())+ }++ async fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String> {+ let client = self.pool.get().await.map_err(|e| format!("db pool error: {e}"))?;+ let stmt = format!("SELECT payload FROM {} WHERE key = $1", self.schema_table);+ let rows = client.query(&stmt, &[&key.to_string()]).await.map_err(|e| format!("db query error: {e}"))?;+ Ok(rows.first().map(|row| row.get::<_, Vec<u8>>(0)))+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ let client = self.pool.get().await.map_err(|e| format!("db pool error: {e}"))?;+ let stmt = format!("DELETE FROM {} WHERE key = $1", self.schema_table);+ client.execute(&stmt, &[&key.to_string()]).await.map_err(|e| format!("db delete error: {e}"))?;+ Ok(())+ }++ async fn exists(&self, key: &str) -> Result<bool, String> {+ let client = self.pool.get().await.map_err(|e| format!("db pool error: {e}"))?;+ let stmt = format!("SELECT COUNT(*) FROM {} WHERE key = $1", self.schema_table);+ let count: i64 =+ client.query_one(&stmt, &[&key.to_string()]).await.map_err(|e| format!("db exists error: {e}"))?.get(0);+ Ok(count > 0)+ }+}++// Secret string that zeros memory on drop to minimize secret retention+pub struct SecretStr {+ inner: Vec<u8>,+}++impl SecretStr {+ pub fn new(s: &str) -> Self {+ Self { inner: s.as_bytes().to_vec() }+ }++ pub fn as_str(&self) -> &str {+ std::str::from_utf8(&self.inner).expect("SecretStr must be valid UTF-8")+ }+}++impl std::fmt::Display for SecretStr {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.as_str().fmt(f)+ }+}++impl Drop for SecretStr {+ fn drop(&mut self) {+ for byte in &mut self.inner {+ *byte = 0;+ }+ }+}++// ============================================================================+// S3Backend+// ============================================================================++#[allow(dead_code)]+pub struct S3Backend {+ client: reqwest::Client,+ bucket: String,+ region: String,+ access_key: SecretStr,+ secret_key: SecretStr,+ endpoint: String,+ prefix: String,+}++impl S3Backend {+ pub fn new(+ bucket: &str,+ region: &str,+ access_key: &str,+ secret_key: &str,+ endpoint: Option<&str>,+ prefix: &str,+ ) -> Self {+ let endpoint = endpoint+ .filter(|s| !s.is_empty())+ .unwrap_or(&format!("https://{bucket}.s3.{region}.amazonaws.com"))+ .to_string();+ Self {+ client: reqwest::Client::new(),+ bucket: bucket.to_string(),+ region: region.to_string(),+ access_key: SecretStr::new(access_key),+ secret_key: SecretStr::new(secret_key),+ endpoint,+ prefix: prefix.to_string(),+ }+ }++ fn object_key(&self, key: &str) -> String {+ if self.prefix.is_empty() {+ key.to_string()+ } else {+ format!("{}/{}", self.prefix, key)+ }+ }++ fn auth_header(&self, method: &reqwest::Method, path: &str, body: &[u8]) -> Result<String, String> {+ let amz_date = chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string();+ let date_stamp = &amz_date[..8];+ let content_sha256 = hex(Sha256::digest(body));++ let canonical_uri = format!("/{}", path);+ let canonical_querystring = "";+ let canonical_headers =+ format!("host:{}\nx-amz-content-sha256:{content_sha256}\nx-amz-date:{amz_date}\n", self.build_host());+ let signed_headers = "host;x-amz-content-sha256;x-amz-date";+ let canonical_request = format!("{method}\n{canonical_uri}\n{canonical_querystring}\n{canonical_headers}\n{signed_headers}\n{content_sha256}");++ let algorithm = "AWS4-HMAC-SHA256";+ let credential_scope = format!("{date_stamp}/{}/s3/aws4_request", self.region);+ let string_to_sign = format!(+ "{algorithm}\n{amz_date}\n{credential_scope}\n{}",+ hex(Sha256::digest(canonical_request.as_bytes()))+ );++ let signing_key = self.signing_key(date_stamp)?;+ let signature = hex(hmac_sha256(&signing_key, string_to_sign.as_bytes()));+ Ok(format!(+ "{algorithm} Credential={}/{credential_scope}, SignedHeaders={signed_headers}, Signature={signature}",+ self.access_key+ ))+ }++ fn build_host(&self) -> String {+ let url = &self.endpoint;+ url.trim_start_matches("https://").trim_start_matches("http://").trim_end_matches('/').to_string()+ }++ fn signing_key(&self, date_stamp: &str) -> Result<Vec<u8>, String> {+ let k_secret = format!("AWS4{}", self.secret_key);+ let k_date = hmac_sha256(k_secret.as_bytes(), date_stamp.as_bytes());+ let k_region = hmac_sha256(&k_date, self.region.as_bytes());+ let k_service = hmac_sha256(&k_region, b"s3");+ Ok(hmac_sha256(&k_service, b"aws4_request").to_vec())+ }+}++#[async_trait]+impl StateBackend for S3Backend {+ async fn save(&self, key: &str, value: &[u8]) -> Result<(), String> {+ self.save_with_content_type(key, value, "application/octet-stream").await+ }++ async fn save_with_content_type(&self, key: &str, value: &[u8], content_type: &str) -> Result<(), String> {+ let object_key = self.object_key(key);+ let url = format!("{}/{}", self.endpoint.trim_end_matches('/'), object_key);+ let method = reqwest::Method::PUT;+ let auth = self.auth_header(&method, &object_key, value)?;+ let content_sha256 = hex(Sha256::digest(value));++ let resp = self+ .client+ .put(&url)+ .header("Authorization", &auth)+ .header("x-amz-content-sha256", &content_sha256)+ .header("x-amz-date", &chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string())+ .header("Content-Type", content_type)+ .body(value.to_vec())+ .send()+ .await+ .map_err(|e| format!("s3 put error: {e}"))?;++ if !resp.status().is_success() {+ let status = resp.status();+ let body = resp.text().await.unwrap_or_else(|e| format!("<body read error: {e}>"));+ return Err(format!("s3 put failed: {status} {body}"));+ }+ Ok(())+ }++ async fn load(&self, key: &str) -> Result<Option<Vec<u8>>, String> {+ let object_key = self.object_key(key);+ let url = format!("{}/{}", self.endpoint.trim_end_matches('/'), object_key);+ let method = reqwest::Method::GET;+ let auth = self.auth_header(&method, &object_key, b"")?;++ let resp = self+ .client+ .get(&url)+ .header("Authorization", &auth)+ .header("x-amz-content-sha256", hex(Sha256::digest(b"")))+ .header("x-amz-date", &chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string())+ .send()+ .await+ .map_err(|e| format!("s3 get error: {e}"))?;++ if resp.status() == reqwest::StatusCode::NOT_FOUND {+ return Ok(None);+ }+ if !resp.status().is_success() {+ let status = resp.status();+ let body = resp.text().await.unwrap_or_else(|e| format!("<body read error: {e}>"));+ return Err(format!("s3 get failed: {status} {body}"));+ }+ let bytes = resp.bytes().await.map_err(|e| format!("s3 read error: {e}"))?;+ Ok(Some(bytes.to_vec()))+ }++ async fn delete(&self, key: &str) -> Result<(), String> {+ let object_key = self.object_key(key);+ let url = format!("{}/{}", self.endpoint.trim_end_matches('/'), object_key);+ let method = reqwest::Method::DELETE;+ let auth = self.auth_header(&method, &object_key, b"")?;++ let resp = self+ .client+ .delete(&url)+ .header("Authorization", &auth)+ .header("x-amz-content-sha256", hex(Sha256::digest(b"")))+ .header("x-amz-date", &chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string())+ .send()+ .await+ .map_err(|e| format!("s3 delete error: {e}"))?;++ if !resp.status().is_success() && resp.status() != reqwest::StatusCode::NOT_FOUND {+ let status = resp.status();+ let body = resp.text().await.unwrap_or_else(|e| format!("<body read error: {e}>"));+ return Err(format!("s3 delete failed: {status} {body}"));+ }+ Ok(())+ }++ async fn exists(&self, key: &str) -> Result<bool, String> {+ let object_key = self.object_key(key);+ let url = format!("{}/{}", self.endpoint.trim_end_matches('/'), object_key);+ let method = reqwest::Method::HEAD;+ let auth = self.auth_header(&method, &object_key, b"")?;++ let resp = self+ .client+ .head(&url)+ .header("Authorization", &auth)+ .header("x-amz-content-sha256", hex(Sha256::digest(b"")))+ .header("x-amz-date", &chrono::Utc::now().format("%Y%m%dT%H%M%SZ").to_string())+ .send()+ .await+ .map_err(|e| format!("s3 head error: {e}"))?;++ Ok(resp.status().is_success())+ }+}++// ============================================================================+// 8.3: EncryptedPayload — AES-256-GCM + Argon2id + HMAC-SHA256 signing+// ============================================================================++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct EncryptedPayload {+ pub version: u8,+ pub kdf: String,+ pub cipher: String,+ pub salt: String,+ pub nonce: String,+ pub ciphertext: String,+ #[serde(skip_serializing_if = "Option::is_none")]+ pub signature: Option<String>,+}++impl EncryptedPayload {+ pub fn encrypt(plaintext: &[u8], passphrase: &str) -> Result<Self, String> {+ let mut salt = [0u8; 16];+ let mut nonce = [0u8; 12];+ OsRng.fill_bytes(&mut salt);+ OsRng.fill_bytes(&mut nonce);+ let key = derive_key(passphrase, &salt)?;+ let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| e.to_string())?;+ let ciphertext = cipher.encrypt(Nonce::from_slice(&nonce), plaintext).map_err(|e| e.to_string())?;+ Ok(Self {+ version: 1,+ kdf: "argon2id".to_string(),+ cipher: "aes-256-gcm".to_string(),+ salt: base64_engine().encode(salt),+ nonce: base64_engine().encode(nonce),+ ciphertext: base64_engine().encode(ciphertext),+ signature: None,+ })+ }++ pub fn decrypt(&self, passphrase: &str) -> Result<Vec<u8>, String> {+ if self.version != 1 || self.kdf != "argon2id" || self.cipher != "aes-256-gcm" {+ return Err("Unsupported encrypted payload format".to_string());+ }+ let salt = base64_engine().decode(&self.salt).map_err(|e| e.to_string())?;+ let nonce = base64_engine().decode(&self.nonce).map_err(|e| e.to_string())?;+ let ciphertext = base64_engine().decode(&self.ciphertext).map_err(|e| e.to_string())?;+ if nonce.len() != 12 {+ return Err("Invalid nonce length".to_string());+ }+ let key = derive_key(passphrase, &salt)?;+ let cipher = Aes256Gcm::new_from_slice(&key).map_err(|e| e.to_string())?;+ cipher.decrypt(Nonce::from_slice(&nonce), ciphertext.as_ref()).map_err(|_| "Decryption failed".to_string())+ }++ pub fn sign(&mut self, signing_key: &[u8]) {+ let payload = self.signing_payload();+ let sig = hmac_sha256(signing_key, payload.as_bytes());+ self.signature = Some(base64_engine().encode(sig));+ }++ pub fn verify(&self, signing_key: &[u8]) -> bool {+ let Some(sig_b64) = &self.signature else {+ return false;+ };+ let Ok(expected_sig) = base64_engine().decode(sig_b64) else {+ return false;+ };+ let payload = self.signing_payload();+ let computed = hmac_sha256(signing_key, payload.as_bytes());+ constant_time_eq(&expected_sig, &computed)+ }++ fn signing_payload(&self) -> String {+ format!("{}.{}.{}.{}.{}.{}", self.version, self.kdf, self.cipher, self.salt, self.nonce, self.ciphertext)+ }+}++// Argon2id KDF parameters (used as key derivation for encryption, not password hashing).+// The memory cost (19 MiB) and iteration count (2) are adequate for a KDF running in a+// desktop context where the derived key only exists ephemerally in memory.+const KDF_MEMORY_COST: u32 = 19 * 1024;+const KDF_ITERATIONS: u32 = 2;+const KDF_PARALLELISM: u32 = 1;++fn derive_key(passphrase: &str, salt: &[u8]) -> Result<[u8; 32], String> {+ let params = Params::new(KDF_MEMORY_COST, KDF_ITERATIONS, KDF_PARALLELISM, Some(32)).map_err(|e| e.to_string())?;+ let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);+ let mut key = [0u8; 32];+ argon2.hash_password_into(passphrase.as_bytes(), salt, &mut key).map_err(|e| e.to_string())?;+ Ok(key)+}++fn base64_engine() -> base64::engine::GeneralPurpose {+ base64::engine::general_purpose::STANDARD+}++fn hmac_sha256(key: &[u8], data: &[u8]) -> [u8; 32] {+ const BLOCK_SIZE: usize = 64;+ let mut k = [0u8; BLOCK_SIZE];+ if key.len() > BLOCK_SIZE {+ let hash = Sha256::digest(key);+ k[..32].copy_from_slice(&hash);+ } else {+ k[..key.len()].copy_from_slice(key);+ }+ let mut ipad = [0x36u8; BLOCK_SIZE];+ let mut opad = [0x5cu8; BLOCK_SIZE];+ for i in 0..BLOCK_SIZE {+ ipad[i] ^= k[i];+ opad[i] ^= k[i];+ }+ let inner = Sha256::digest([&ipad[..], data].concat());+ let result = Sha256::digest([&opad[..], &inner[..]].concat());+ result.into()+}++fn hex(bytes: impl AsRef<[u8]>) -> String {+ bytes.as_ref().iter().map(|b| format!("{b:02x}")).collect()+}++fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {+ if a.len() != b.len() {+ return false;+ }+ let mut result = 0u8;+ for (x, y) in a.iter().zip(b.iter()) {+ result |= x ^ y;+ }+ result == 0+}++// ============================================================================+// 8.4: State Machine with CAS Optimistic Locking (extended Phase 15)+// ============================================================================++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum StateTransition {+ Created,+ Running,+ Paused,+ OscSyncing,+ Completed,+ Failed,+ Cancelled,+ RollingBack,+ FullyRolledBack,+ PartiallyRolledBack,+ RecoveryRequired,+}++impl StateTransition {+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Created => "created",+ Self::Running => "running",+ Self::Paused => "paused",+ Self::OscSyncing => "osc_syncing",+ Self::Completed => "completed",+ Self::Failed => "failed",+ Self::Cancelled => "cancelled",+ Self::RollingBack => "rolling_back",+ Self::FullyRolledBack => "fully_rolled_back",+ Self::PartiallyRolledBack => "partially_rolled_back",+ Self::RecoveryRequired => "recovery_required",+ }+ }++ fn from_str(s: &str) -> Option<Self> {+ match s {+ "created" => Some(Self::Created),+ "running" => Some(Self::Running),+ "paused" => Some(Self::Paused),+ "osc_syncing" => Some(Self::OscSyncing),+ "completed" => Some(Self::Completed),+ "failed" => Some(Self::Failed),+ "cancelled" => Some(Self::Cancelled),+ "rolling_back" => Some(Self::RollingBack),+ "fully_rolled_back" => Some(Self::FullyRolledBack),+ "partially_rolled_back" => Some(Self::PartiallyRolledBack),+ "recovery_required" => Some(Self::RecoveryRequired),+ _ => None,+ }+ }+}++const ALLOWED_TRANSITIONS: &[(StateTransition, &[StateTransition])] = &[+ (StateTransition::Created, &[StateTransition::Running, StateTransition::Cancelled]),+ (+ StateTransition::Running,+ &[StateTransition::Paused, StateTransition::OscSyncing, StateTransition::Completed, StateTransition::Failed],+ ),+ (StateTransition::Paused, &[StateTransition::Running, StateTransition::Cancelled]),+ (StateTransition::OscSyncing, &[StateTransition::Completed, StateTransition::Failed]),+ (StateTransition::Completed, &[StateTransition::RollingBack, StateTransition::FullyRolledBack]),+ (+ StateTransition::Failed,+ &[+ StateTransition::Running,+ StateTransition::Cancelled,+ StateTransition::RollingBack,+ StateTransition::RecoveryRequired,+ ],+ ),+ (StateTransition::Cancelled, &[]),+ (+ StateTransition::RollingBack,+ &[StateTransition::FullyRolledBack, StateTransition::PartiallyRolledBack, StateTransition::RecoveryRequired],+ ),+ (StateTransition::FullyRolledBack, &[]),+ (StateTransition::PartiallyRolledBack, &[StateTransition::RecoveryRequired]),+ (StateTransition::RecoveryRequired, &[]),+];++pub fn is_valid_transition(from: &StateTransition, to: &StateTransition) -> bool {+ ALLOWED_TRANSITIONS.iter().any(|(state, allowed)| state == from && allowed.contains(to))+}++#[derive(Debug, Clone, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct StateEntry {+ pub key: String,+ pub current_state: String,+ pub version: u64,+ pub metadata: serde_json::Value,+}++const STATE_KEY_PREFIX: &str = "state:";++pub struct StateMachine {+ backend: Arc<dyn StateBackend>,+}++impl StateMachine {+ pub fn new(backend: Arc<dyn StateBackend>) -> Self {+ Self { backend }+ }++ pub async fn create_state(&self, key: &str, metadata: serde_json::Value) -> Result<StateEntry, String> {+ let entry = StateEntry {+ key: key.to_string(),+ current_state: StateTransition::Created.as_str().to_string(),+ version: 1,+ metadata,+ };+ let data = serde_json::to_vec(&entry).map_err(|e| e.to_string())?;+ self.backend.save(&format!("{STATE_KEY_PREFIX}{key}"), &data).await?;+ Ok(entry)+ }++ pub async fn transition(&self, key: &str, to: StateTransition) -> Result<StateEntry, String> {+ let state_key = format!("{STATE_KEY_PREFIX}{key}");+ let max_retries = 3;++ for attempt in 0..=max_retries {+ let raw = self.backend.load(&state_key).await?;+ let mut entry: StateEntry = match raw {+ Some(data) => serde_json::from_slice(&data).map_err(|e| e.to_string())?,+ None => return Err(format!("State not found: {key}")),+ };++ let current = StateTransition::from_str(&entry.current_state)+ .ok_or_else(|| format!("Invalid current state: {}", entry.current_state))?;++ if !is_valid_transition(¤t, &to) {+ return Err(format!("Invalid transition: {} -> {}", current.as_str(), to.as_str()));+ }++ let expected_version = entry.version;+ entry.current_state = to.as_str().to_string();+ entry.version += 1;++ let success = self.compare_and_swap_state(key, expected_version, &entry).await?;+ if success {+ return Ok(entry);+ }++ if attempt < max_retries {+ log::warn!(+ "CAS conflict for state key '{}' at version {}, retrying {}/{}",+ key,+ expected_version,+ attempt + 1,+ max_retries+ );+ }+ }++ Err(format!("CAS failed after {} retries for state key: {}", max_retries, key))+ }++ pub async fn get_state(&self, key: &str) -> Result<Option<StateEntry>, String> {+ let state_key = format!("{STATE_KEY_PREFIX}{key}");+ let raw = self.backend.load(&state_key).await?;+ match raw {+ Some(data) => {+ let entry: StateEntry = serde_json::from_slice(&data).map_err(|e| e.to_string())?;+ Ok(Some(entry))+ }+ None => Ok(None),+ }+ }++ pub async fn compare_and_swap_state(+ &self,+ key: &str,+ expected_version: u64,+ new_state: &StateEntry,+ ) -> Result<bool, String> {+ let state_key = format!("{STATE_KEY_PREFIX}{key}");++ let old_entry = StateEntry {+ key: key.to_string(),+ current_state: String::new(),+ version: expected_version,+ metadata: serde_json::Value::Null,+ };+ let old_data = serde_json::to_vec(&old_entry).map_err(|e| e.to_string())?;+ let new_data = serde_json::to_vec(new_state).map_err(|e| e.to_string())?;++ self.backend.compare_and_swap(&state_key, Some(&old_data), &new_data).await+ }++ pub async fn delete_state(&self, key: &str) -> Result<(), String> {+ self.backend.delete(&format!("{STATE_KEY_PREFIX}{key}")).await+ }+}++// ============================================================================+// 8.5: Desensitization Rule Engine+// ============================================================================++#[derive(Debug, Clone)]+pub enum DesensitizeRule {+ /// Replace matching pattern with asterisks+ Pattern { name: String, pattern: String, replacement: String, preserve_prefix: usize },+ /// Show first N chars, mask the rest+ PrefixKeep { name: String, keep: usize },+ /// Show last N chars, mask the rest+ SuffixKeep { name: String, keep: usize },+ /// Custom function (regex replace)+ Regex { name: String, pattern: regex::Regex, replacement: String },+}++impl DesensitizeRule {+ pub fn name(&self) -> &str {+ match self {+ Self::Pattern { name, .. }+ | Self::PrefixKeep { name, .. }+ | Self::SuffixKeep { name, .. }+ | Self::Regex { name, .. } => name,+ }+ }++ pub fn apply(&self, value: &str) -> String {+ match self {+ Self::Pattern { pattern, replacement, preserve_prefix, .. } => {+ if *preserve_prefix > 0 && value.len() > *preserve_prefix {+ let prefix = &value[..*preserve_prefix];+ let rest: String = value.chars().skip(*preserve_prefix).map(|_| '*').collect();+ format!("{prefix}{rest}")+ } else if value == pattern {+ replacement.clone()+ } else if value.contains(pattern) {+ value.replace(pattern, replacement)+ } else {+ value.chars().map(|_| '*').collect()+ }+ }+ Self::PrefixKeep { keep, .. } => {+ if value.len() <= *keep {+ value.to_string()+ } else {+ let visible: String = value.chars().take(*keep).collect();+ let rest: String = value.chars().skip(*keep).map(|_| '*').collect();+ format!("{visible}{rest}")+ }+ }+ Self::SuffixKeep { keep, .. } => {+ if value.len() <= *keep {+ value.to_string()+ } else {+ let visible: String =+ value.chars().rev().take(*keep).collect::<Vec<_>>().into_iter().rev().collect();+ let rest: String =+ value.chars().rev().skip(*keep).map(|_| '*').collect::<Vec<_>>().into_iter().rev().collect();+ format!("{rest}{visible}")+ }+ }+ Self::Regex { pattern, replacement, .. } => pattern.replace_all(value, replacement.as_str()).to_string(),+ }+ }+}++pub struct DesensitizationEngine {+ rules: Vec<DesensitizeRule>,+}++impl DesensitizationEngine {+ pub fn new() -> Self {+ Self { rules: Vec::new() }+ }++ pub fn add_rule(&mut self, rule: DesensitizeRule) -> &mut Self {+ self.rules.push(rule);+ self+ }++ pub fn apply(&self, key: &str, value: &str) -> String {+ for rule in &self.rules {+ if key.contains(rule.name()) || rule.name() == "*" {+ return rule.apply(value);+ }+ }+ value.to_string()+ }++ pub fn apply_to_json(&self, json: &mut serde_json::Value) {+ match json {+ serde_json::Value::Object(map) => {+ for (key, value) in map.iter_mut() {+ if let serde_json::Value::String(s) = value {+ let desensitized = self.apply(key, s);+ *value = serde_json::Value::String(desensitized);+ } else {+ self.apply_to_json(value);+ }+ }+ }+ serde_json::Value::Array(arr) => {+ for item in arr.iter_mut() {+ self.apply_to_json(item);+ }+ }+ _ => {}+ }+ }++ pub fn default_connection_rules() -> Self {+ let mut engine = Self::new();+ engine.add_rule(DesensitizeRule::PrefixKeep { name: "password".to_string(), keep: 2 });+ engine.add_rule(DesensitizeRule::PrefixKeep { name: "secret".to_string(), keep: 4 });+ engine.add_rule(DesensitizeRule::PrefixKeep { name: "token".to_string(), keep: 4 });+ engine.add_rule(DesensitizeRule::PrefixKeep { name: "connection_string".to_string(), keep: 8 });+ engine.add_rule(DesensitizeRule::PrefixKeep { name: "key".to_string(), keep: 4 });+ engine.add_rule(DesensitizeRule::PrefixKeep { name: "passphrase".to_string(), keep: 2 });+ engine+ }++ pub fn desensitize_connection_config(&self, config: &ConnectionConfig) -> serde_json::Value {+ let mut json = serde_json::to_value(config.clone()).unwrap_or_default();+ self.apply_to_json(&mut json);+ json+ }+}++impl Default for DesensitizationEngine {+ fn default() -> Self {+ Self::default_connection_rules()+ }+}++// ============================================================================+// 8.6: Tests+// ============================================================================++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::Arc;+ use std::time::{SystemTime, UNIX_EPOCH};++ fn temp_db_path(name: &str) -> std::path::PathBuf {+ let stamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();+ std::env::temp_dir().join(format!("dbx-state-persistence-{name}-{}-{stamp}.db", std::process::id()))+ }++ async fn create_local_backend() -> LocalBackend {+ let path = temp_db_path("local-backend");+ let storage = Arc::new(Storage::open(&path).await.unwrap());+ LocalBackend::new(storage)+ }++ // --- StateBackend CRUD Tests (LocalBackend) ---++ #[tokio::test]+ async fn local_backend_save_and_load() {+ let backend = create_local_backend().await;+ backend.save("test-key", b"hello world").await.unwrap();+ let result = backend.load("test-key").await.unwrap().unwrap();+ assert_eq!(result, b"hello world");+ }++ #[tokio::test]+ async fn local_backend_load_nonexistent() {+ let backend = create_local_backend().await;+ let result = backend.load("nonexistent").await.unwrap();+ assert!(result.is_none());+ }++ #[tokio::test]+ async fn local_backend_delete() {+ let backend = create_local_backend().await;+ backend.save("delete-key", b"to-delete").await.unwrap();+ assert!(backend.exists("delete-key").await.unwrap());+ backend.delete("delete-key").await.unwrap();+ assert!(!backend.exists("delete-key").await.unwrap());+ }++ #[tokio::test]+ async fn local_backend_overwrite() {+ let backend = create_local_backend().await;+ backend.save("overwrite-key", b"first").await.unwrap();+ backend.save("overwrite-key", b"second").await.unwrap();+ let result = backend.load("overwrite-key").await.unwrap().unwrap();+ assert_eq!(result, b"second");+ }++ #[tokio::test]+ async fn local_backend_binary_data() {+ let backend = create_local_backend().await;+ let binary = vec![0u8, 255, 128, 64, 32, 16, 8, 4, 2, 1];+ backend.save("binary-key", &binary).await.unwrap();+ let result = backend.load("binary-key").await.unwrap().unwrap();+ assert_eq!(result, binary);+ }++ // --- EncryptedPayload Tests ---++ #[test]+ fn encrypt_decrypt_roundtrip() {+ let payload = EncryptedPayload::encrypt(b"sensitive data", "strong-passphrase").unwrap();+ let decrypted = payload.decrypt("strong-passphrase").unwrap();+ assert_eq!(decrypted, b"sensitive data");+ }++ #[test]+ fn encrypt_decrypt_wrong_passphrase_fails() {+ let payload = EncryptedPayload::encrypt(b"sensitive data", "correct-passphrase").unwrap();+ let result = payload.decrypt("wrong-passphrase");+ assert!(result.is_err());+ }++ #[test]+ fn encrypt_decrypt_empty_data() {+ let payload = EncryptedPayload::encrypt(b"", "passphrase").unwrap();+ let decrypted = payload.decrypt("passphrase").unwrap();+ assert!(decrypted.is_empty());+ }++ #[test]+ fn encrypt_decrypt_large_data() {+ let large = vec![0xABu8; 65536];+ let payload = EncryptedPayload::encrypt(&large, "strong-passphrase").unwrap();+ let decrypted = payload.decrypt("strong-passphrase").unwrap();+ assert_eq!(decrypted, large);+ }++ #[test]+ fn unique_nonce_per_encryption() {+ let p1 = EncryptedPayload::encrypt(b"data", "pwd").unwrap();+ let p2 = EncryptedPayload::encrypt(b"data", "pwd").unwrap();+ assert_ne!(p1.nonce, p2.nonce);+ }++ #[test]+ fn sign_and_verify() {+ let mut payload = EncryptedPayload::encrypt(b"data", "pwd").unwrap();+ let signing_key = b"my-signing-key-32-bytes-long!!!";+ payload.sign(signing_key);+ assert!(payload.verify(signing_key));+ }++ #[test]+ fn verify_wrong_key_fails() {+ let mut payload = EncryptedPayload::encrypt(b"data", "pwd").unwrap();+ payload.sign(b"correct-key");+ assert!(!payload.verify(b"wrong-key"));+ }++ #[test]+ fn verify_no_signature_fails() {+ let payload = EncryptedPayload::encrypt(b"data", "pwd").unwrap();+ assert!(!payload.verify(b"any-key"));+ }++ #[test]+ fn sign_tamper_ciphertext_fails_verification() {+ let mut payload = EncryptedPayload::encrypt(b"data", "pwd").unwrap();+ let signing_key = b"my-signing-key";+ payload.sign(signing_key);++ let mut tampered = payload.clone();+ tampered.ciphertext = base64_engine().encode(b"tampered-data");+ assert!(!tampered.verify(signing_key));+ }++ // --- HMAC-SHA256 Tests ---++ #[test]+ fn hmac_sha256_consistency() {+ let result1 = hmac_sha256(b"key", b"data");+ let result2 = hmac_sha256(b"key", b"data");+ assert_eq!(result1, result2);+ }++ #[test]+ fn hmac_sha256_different_keys_different_results() {+ let r1 = hmac_sha256(b"key1", b"data");+ let r2 = hmac_sha256(b"key2", b"data");+ assert_ne!(r1, r2);+ }++ #[test]+ fn hmac_sha256_long_key() {+ let long_key = vec![0xABu8; 128];+ let _result = hmac_sha256(&long_key, b"data");+ }++ // --- State Machine Tests ---++ #[tokio::test]+ async fn state_machine_create_and_get() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ let entry = sm.create_state("job-1", serde_json::json!({"priority": "high"})).await.unwrap();+ assert_eq!(entry.current_state, "created");+ assert_eq!(entry.version, 1);++ let loaded = sm.get_state("job-1").await.unwrap().unwrap();+ assert_eq!(loaded.current_state, "created");+ assert_eq!(loaded.metadata, serde_json::json!({"priority": "high"}));+ }++ #[tokio::test]+ async fn state_machine_transition_created_to_running() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ sm.create_state("job-2", serde_json::json!({})).await.unwrap();+ let entry = sm.transition("job-2", StateTransition::Running).await.unwrap();+ assert_eq!(entry.current_state, "running");+ assert_eq!(entry.version, 2);+ }++ #[tokio::test]+ async fn state_machine_invalid_transition_fails() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ sm.create_state("job-3", serde_json::json!({})).await.unwrap();+ let result = sm.transition("job-3", StateTransition::Completed).await;+ assert!(result.is_err());+ }++ #[tokio::test]+ async fn state_machine_full_lifecycle() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ sm.create_state("job-4", serde_json::json!({})).await.unwrap();+ sm.transition("job-4", StateTransition::Running).await.unwrap();+ sm.transition("job-4", StateTransition::Completed).await.unwrap();+ let entry = sm.get_state("job-4").await.unwrap().unwrap();+ assert_eq!(entry.current_state, "completed");+ }++ #[tokio::test]+ async fn state_machine_pause_resume() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ sm.create_state("job-5", serde_json::json!({})).await.unwrap();+ sm.transition("job-5", StateTransition::Running).await.unwrap();+ sm.transition("job-5", StateTransition::Paused).await.unwrap();+ let entry = sm.get_state("job-5").await.unwrap().unwrap();+ assert_eq!(entry.current_state, "paused");+ sm.transition("job-5", StateTransition::Running).await.unwrap();+ let entry = sm.get_state("job-5").await.unwrap().unwrap();+ assert_eq!(entry.current_state, "running");+ }++ #[tokio::test]+ async fn state_machine_delete() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ sm.create_state("job-6", serde_json::json!({})).await.unwrap();+ assert!(sm.get_state("job-6").await.unwrap().is_some());+ sm.delete_state("job-6").await.unwrap();+ assert!(sm.get_state("job-6").await.unwrap().is_none());+ }++ #[tokio::test]+ async fn state_machine_cas_success() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ let entry = sm.create_state("cas-key", serde_json::json!({})).await.unwrap();+ let mut new_entry = entry.clone();+ new_entry.current_state = StateTransition::Running.as_str().to_string();+ new_entry.version += 1;+ let success = sm.compare_and_swap_state("cas-key", 1, &new_entry).await.unwrap();+ assert!(success);+ let loaded = sm.get_state("cas-key").await.unwrap().unwrap();+ assert_eq!(loaded.current_state, "running");+ assert_eq!(loaded.version, 2);+ }++ #[tokio::test]+ async fn state_machine_cas_failure() {+ let backend = Arc::new(create_local_backend().await);+ let sm = StateMachine::new(backend);+ let entry = sm.create_state("cas-fail", serde_json::json!({})).await.unwrap();+ let mut new_entry = entry.clone();+ new_entry.current_state = StateTransition::Running.as_str().to_string();+ new_entry.version += 1;+ let success = sm.compare_and_swap_state("cas-fail", 999, &new_entry).await.unwrap();+ assert!(!success);+ }++ // --- is_valid_transition Tests ---++ #[test]+ fn valid_transitions_are_correct() {+ assert!(is_valid_transition(&StateTransition::Created, &StateTransition::Running));+ assert!(is_valid_transition(&StateTransition::Created, &StateTransition::Cancelled));+ assert!(is_valid_transition(&StateTransition::Running, &StateTransition::Paused));+ assert!(is_valid_transition(&StateTransition::Running, &StateTransition::Completed));+ assert!(is_valid_transition(&StateTransition::Running, &StateTransition::Failed));+ assert!(is_valid_transition(&StateTransition::Paused, &StateTransition::Running));+ assert!(is_valid_transition(&StateTransition::Paused, &StateTransition::Cancelled));+ assert!(is_valid_transition(&StateTransition::Completed, &StateTransition::FullyRolledBack));+ assert!(is_valid_transition(&StateTransition::Failed, &StateTransition::Running));+ assert!(is_valid_transition(&StateTransition::Failed, &StateTransition::Cancelled));+ }++ #[test]+ fn invalid_transitions_are_rejected() {+ assert!(!is_valid_transition(&StateTransition::Created, &StateTransition::Completed));+ assert!(!is_valid_transition(&StateTransition::Running, &StateTransition::Created));+ assert!(!is_valid_transition(&StateTransition::Completed, &StateTransition::Running));+ assert!(!is_valid_transition(&StateTransition::Cancelled, &StateTransition::Running));+ assert!(!is_valid_transition(&StateTransition::FullyRolledBack, &StateTransition::Created));+ assert!(!is_valid_transition(&StateTransition::PartiallyRolledBack, &StateTransition::Running));+ }++ // --- Desensitization Engine Tests ---++ #[test]+ fn desensitize_password_prefix_keep() {+ let engine = DesensitizationEngine::default_connection_rules();+ let result = engine.apply("password", "mySecretP@ss!");+ assert_eq!(result, "my***********");+ }++ #[test]+ fn desensitize_token_prefix_keep() {+ let engine = DesensitizationEngine::default_connection_rules();+ let result = engine.apply("token", "eyJhbGciOiJIUzI1NiJ9");+ assert_eq!(result, "eyJh****************");+ }++ #[test]+ fn desensitize_short_password() {+ let engine = DesensitizationEngine::default_connection_rules();+ let result = engine.apply("password", "ab");+ assert_eq!(result, "ab");+ }++ #[test]+ fn desensitize_unknown_field() {+ let engine = DesensitizationEngine::default_connection_rules();+ let result = engine.apply("username", "admin");+ assert_eq!(result, "admin");+ }++ #[test]+ fn desensitize_json_object() {+ let engine = DesensitizationEngine::default_connection_rules();+ let mut json = serde_json::json!({+ "password": "super-secret",+ "username": "admin",+ "token": "abcdef123456",+ "host": "localhost"+ });+ engine.apply_to_json(&mut json);+ assert_eq!(json["password"], "su**********");+ assert_eq!(json["username"], "admin");+ assert_eq!(json["token"], "abcd********");+ assert_eq!(json["host"], "localhost");+ }++ #[test]+ fn desensitize_nested_json() {+ let engine = DesensitizationEngine::default_connection_rules();+ let mut json = serde_json::json!({+ "connection": {+ "password": "nested-secret",+ "details": {+ "api_key": "key-12345"+ }+ }+ });+ engine.apply_to_json(&mut json);+ assert_eq!(json["connection"]["password"], "ne***********");+ assert_eq!(json["connection"]["details"]["api_key"], "key-*****");+ }++ #[test]+ fn desensitize_prefix_keep_rule() {+ let rule = DesensitizeRule::PrefixKeep { name: "test".to_string(), keep: 3 };+ assert_eq!(rule.apply("abcdef"), "abc***");+ assert_eq!(rule.apply("ab"), "ab");+ }++ #[test]+ fn desensitize_suffix_keep_rule() {+ let rule = DesensitizeRule::SuffixKeep { name: "test".to_string(), keep: 3 };+ assert_eq!(rule.apply("abcdef"), "***def");+ assert_eq!(rule.apply("ab"), "ab");+ }++ #[test]+ fn desensitize_regex_rule() {+ let pattern = regex::Regex::new(r"\d{4}-\d{4}-\d{4}-\d{4}").unwrap();+ let rule = DesensitizeRule::Regex {+ name: "card".to_string(),+ pattern,+ replacement: "****-****-****-****".to_string(),+ };+ assert_eq!(rule.apply("My card: 1234-5678-9012-3456"), "My card: ****-****-****-****");+ }++ #[test]+ fn desensitize_via_json_value() {+ let engine = DesensitizationEngine::default_connection_rules();+ let mut json = serde_json::json!({+ "password": "mySecretPass123",+ "username": "root",+ "host": "localhost"+ });+ engine.apply_to_json(&mut json);+ assert_eq!(json["password"], "my*************");+ assert_eq!(json["username"], "root");+ assert_eq!(json["host"], "localhost");+ }++ // --- StateBackend S3 Constructor Test (no network) ---++ #[test]+ fn s3_backend_constructor() {+ let backend = S3Backend::new("my-bucket", "us-east-1", "AKID", "secret", None, "dbx/state");+ assert_eq!(backend.object_key("test"), "dbx/state/test");+ }++ #[test]+ fn s3_backend_no_prefix() {+ let backend = S3Backend::new("my-bucket", "us-east-1", "AKID", "secret", Some("https://s3.custom.com"), "");+ assert_eq!(backend.object_key("test"), "test");+ }++ // --- Storage CAS Tests ---++ #[tokio::test]+ async fn storage_compare_and_swap_new_key() {+ let path = temp_db_path("cas-new-key");+ let storage = Arc::new(Storage::open(&path).await.unwrap());+ let success = storage.compare_and_swap_state("cas-new", None, b"data", "text/plain").await.unwrap();+ assert!(success);+ let (data, _) = storage.load_state("cas-new").await.unwrap().unwrap();+ assert_eq!(data, b"data");+ }++ #[tokio::test]+ async fn storage_compare_and_swap_exact_version() {+ let path = temp_db_path("cas-exact");+ let storage = Arc::new(Storage::open(&path).await.unwrap());+ storage.save_state("cas-key", b"v1", "text/plain").await.unwrap();+ let version = storage.get_state_version("cas-key").await.unwrap().unwrap();+ assert_eq!(version, 1);++ let success = storage.compare_and_swap_state("cas-key", Some(1), b"v2", "text/plain").await.unwrap();+ assert!(success);+ let (data, _) = storage.load_state("cas-key").await.unwrap().unwrap();+ assert_eq!(data, b"v2");+ }++ #[tokio::test]+ async fn storage_compare_and_swap_wrong_version() {+ let path = temp_db_path("cas-wrong-ver");+ let storage = Arc::new(Storage::open(&path).await.unwrap());+ storage.save_state("cas-key", b"v1", "text/plain").await.unwrap();+ let success = storage.compare_and_swap_state("cas-key", Some(999), b"v2", "text/plain").await.unwrap();+ assert!(!success);+ let (data, _) = storage.load_state("cas-key").await.unwrap().unwrap();+ assert_eq!(data, b"v1");+ }++ // --- Hex helper test ---++ #[test]+ fn hex_encoding() {+ assert_eq!(hex([0x00, 0xFF, 0xAB]), "00ffab");+ assert_eq!(hex([] as [u8; 0]), "");+ }++ // --- Constant time eq test ---++ #[test]+ fn constant_time_eq_works() {+ assert!(constant_time_eq(b"abc", b"abc"));+ assert!(!constant_time_eq(b"abc", b"abd"));+ assert!(!constant_time_eq(b"abc", b"abcd"));+ }+}diff --git a/crates/dbx-core/src/storage.rs b/crates/dbx-core/src/storage.rsindex f74bf51f46..1a2db3769e 100644--- a/crates/dbx-core/src/storage.rs+++ b/crates/dbx-core/src/storage.rs@@ -105,6 +105,7 @@ pub fn maybe_import_user_data_db(Ok(DataDbImportResult::Imported)}+#[derive(Clone)]pub struct Storage {db: SqliteHandle,/// Path to the SQLite database file (`dbx.db`). Its parent directory is the@@ -378,6 +379,13 @@ const SCHEMA_STATEMENTS: &[&str] = &[config_json TEXT NOT NULL,is_default INTEGER NOT NULL DEFAULT 0)",+ "CREATE TABLE IF NOT EXISTS state_store (+ key TEXT PRIMARY KEY,+ value BLOB NOT NULL,+ content_type TEXT NOT NULL DEFAULT 'application/octet-stream',+ version INTEGER NOT NULL DEFAULT 1,+ payload BLOB DEFAULT x''+ )","CREATE TABLE IF NOT EXISTS prompt_templates (id TEXT PRIMARY KEY,name TEXT NOT NULL UNIQUE,@@ -412,6 +420,7 @@ impl Storage {ensure_saved_sql_columns_sync(conn)?;ensure_tab_runtime_cache_columns_sync(conn)?;ensure_ai_configs_columns_sync(conn)?;+ ensure_state_store_columns_sync(conn)?;Ok(())})}@@ -582,6 +591,19 @@ fn ensure_table_columns(conn: &Connection, table_name: &str, columns: &[(&str, &Ok(())}+fn ensure_state_store_columns_sync(conn: &Connection) -> Result<(), String> {+ conn.execute("CREATE TABLE IF NOT EXISTS state_store (key TEXT PRIMARY KEY, value BLOB NOT NULL, content_type TEXT NOT NULL DEFAULT 'application/octet-stream', version INTEGER NOT NULL DEFAULT 1)", []).map_err(|e| e.to_string())?;++ // SQLite ALTER TABLE ADD COLUMN rejects parenthesized default expressions.+ const COLUMNS: &[(&str, &str)] = &[+ ("value", "BLOB NOT NULL DEFAULT x''"),+ ("content_type", "TEXT NOT NULL DEFAULT 'application/octet-stream'"),+ ("version", "INTEGER NOT NULL DEFAULT 1"),+ ("payload", "BLOB DEFAULT x''"),+ ];+ ensure_table_columns(conn, "state_store", COLUMNS)+}+fn ssh_tunnel_secret_segment(index: usize, hop: &crate::models::connection::SshTunnelConfig) -> String {if hop.id.trim().is_empty() {index.to_string()@@ -2907,6 +2929,109 @@ impl Storage {}).await}++ // State persistence store (CAS-aware key-value store for state machines)++ pub async fn save_state(&self, key: &str, value: &[u8], content_type: &str) -> Result<(), String> {+ let key = key.to_string();+ let value = value.to_vec();+ let content_type = content_type.to_string();+ self.with_conn(move |conn| {+ conn.execute(+ "INSERT INTO state_store (key, value, content_type, version, payload) \+ VALUES (?1, ?2, ?3, 1, x'') \+ ON CONFLICT(key) DO UPDATE SET value = excluded.value, content_type = excluded.content_type, \+ version = version + 1, payload = excluded.payload",+ params![key, value, content_type],+ )+ .map(|_| ())+ .map_err(|e| e.to_string())+ })+ .await+ }++ pub async fn load_state(&self, key: &str) -> Result<Option<(Vec<u8>, String)>, String> {+ let key = key.to_string();+ self.with_conn(move |conn| {+ let mut stmt = conn+ .prepare("SELECT value, content_type FROM state_store WHERE key = ?1")+ .map_err(|e| e.to_string())?;+ let result: Option<(Vec<u8>, String)> = stmt+ .query_row(params![key], |row| Ok((row.get(0)?, row.get(1)?)))+ .optional()+ .map_err(|e| e.to_string())?;+ Ok(result)+ })+ .await+ }++ pub async fn delete_state(&self, key: &str) -> Result<(), String> {+ let key = key.to_string();+ self.with_conn(move |conn| {+ conn.execute("DELETE FROM state_store WHERE key = ?1", params![key]).map(|_| ()).map_err(|e| e.to_string())+ })+ .await+ }++ pub async fn state_exists(&self, key: &str) -> Result<bool, String> {+ let key = key.to_string();+ self.with_conn(move |conn| {+ let exists: bool = conn+ .query_row("SELECT EXISTS(SELECT 1 FROM state_store WHERE key = ?1)", params![key], |row| row.get(0))+ .map_err(|e| e.to_string())?;+ Ok(exists)+ })+ .await+ }++ pub async fn get_state_version(&self, key: &str) -> Result<Option<u64>, String> {+ let key = key.to_string();+ self.with_conn(move |conn| {+ conn.prepare("SELECT version FROM state_store WHERE key = ?1")+ .and_then(|mut stmt| stmt.query_row(params![key], |row| row.get(0)).optional())+ .map_err(|e| e.to_string())+ })+ .await+ }++ pub async fn compare_and_swap_state(+ &self,+ key: &str,+ expected_version: Option<u64>,+ new_value: &[u8],+ content_type: &str,+ ) -> Result<bool, String> {+ let key = key.to_string();+ let new_value = new_value.to_vec();+ let content_type = content_type.to_string();+ self.with_conn(move |conn| {+ let current: Option<u64> = conn+ .prepare("SELECT version FROM state_store WHERE key = ?1")+ .and_then(|mut stmt| stmt.query_row(params![&key], |row| row.get(0)).optional())+ .map_err(|e| e.to_string())?;++ match (current, expected_version) {+ (None, None) => {+ conn.execute(+ "INSERT INTO state_store (key, value, content_type, version, payload) VALUES (?1, ?2, ?3, 1, x'')",+ params![key, new_value, content_type],+ )+ .map(|_| true)+ .map_err(|e| e.to_string())+ }+ (Some(v), Some(expected)) if v == expected => {+ conn.execute(+ "UPDATE state_store SET value = ?1, content_type = ?2, version = version + 1 WHERE key = ?3 AND version = ?4",+ params![new_value, content_type, key, expected],+ )+ .map(|rows| rows > 0)+ .map_err(|e| e.to_string())+ }+ _ => Ok(false),+ }+ })+ .await+ }}// Tab runtime cachediff --git a/crates/dbx-core/src/two_phase_commit.rs b/crates/dbx-core/src/two_phase_commit.rsnew file mode 100644index 0000000000..b82c26c2a0--- /dev/null+++ b/crates/dbx-core/src/two_phase_commit.rs@@ -0,0 +1,678 @@+use async_trait::async_trait;+use serde::{Deserialize, Serialize};+use std::future::Future;+use std::pin::Pin;+use std::sync::Arc;++use crate::state_persistence::{StateBackend, StateMachine};++#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "snake_case")]+pub enum TransactionStatus {+ Preparing,+ Prepared,+ Committing,+ Committed,+ RollingBack,+ RolledBack,+ Mixed,+ Unknown,+}++impl TransactionStatus {+ pub fn as_str(&self) -> &'static str {+ match self {+ Self::Preparing => "preparing",+ Self::Prepared => "prepared",+ Self::Committing => "committing",+ Self::Committed => "committed",+ Self::RollingBack => "rolling_back",+ Self::RolledBack => "rolled_back",+ Self::Mixed => "mixed",+ Self::Unknown => "unknown",+ }+ }++ #[allow(clippy::should_implement_trait)]+ pub fn from_str(s: &str) -> Self {+ match s {+ "preparing" => Self::Preparing,+ "prepared" => Self::Prepared,+ "committing" => Self::Committing,+ "committed" => Self::Committed,+ "rolling_back" => Self::RollingBack,+ "rolled_back" => Self::RolledBack,+ "mixed" => Self::Mixed,+ _ => Self::Unknown,+ }+ }+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct VoteResult {+ pub participant_id: String,+ pub vote: bool,+ pub reason: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ParticipantCommitResult {+ pub participant_id: String,+ pub committed: bool,+ pub error: Option<String>,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct ParticipantInfo {+ pub id: String,+ pub name: String,+ pub role: String,+}++#[derive(Debug, Clone, Serialize, Deserialize)]+pub struct TransactionLog {+ pub transaction_id: String,+ pub status: String,+ pub participants: Vec<ParticipantInfo>,+ pub created_at: String,+ pub updated_at: String,+ pub metadata: serde_json::Value,+}++impl TransactionLog {+ fn new(transaction_id: String, participants: &[ParticipantInfo], metadata: serde_json::Value) -> Self {+ Self {+ transaction_id,+ status: TransactionStatus::Preparing.as_str().to_string(),+ participants: participants.to_vec(),+ created_at: chrono::Utc::now().to_rfc3339(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ metadata,+ }+ }+}++#[async_trait]+pub trait Participant: Send + Sync {+ fn id(&self) -> &str;+ fn name(&self) -> &str;+ fn role(&self) -> &str;++ async fn prepare(&self, transaction_id: &str) -> Result<(), String>;+ async fn commit(&self, transaction_id: &str) -> Result<(), String>;+ async fn rollback(&self, transaction_id: &str) -> Result<(), String>;+}++pub struct TwoPhaseCommit {+ backend: Arc<dyn StateBackend>,+ state_machine: StateMachine,+}++impl TwoPhaseCommit {+ pub fn new(backend: Arc<dyn StateBackend>) -> Self {+ let sm = StateMachine::new(backend.clone());+ Self { backend, state_machine: sm }+ }++ fn log_key(transaction_id: &str) -> String {+ format!("2pc:tx:{transaction_id}")+ }++ async fn save_log(&self, log: &TransactionLog) -> Result<(), String> {+ let data = serde_json::to_vec(log).map_err(|e| e.to_string())?;+ self.backend.save(&Self::log_key(&log.transaction_id), &data).await+ }++ async fn load_log(&self, transaction_id: &str) -> Result<Option<TransactionLog>, String> {+ let raw = self.backend.load(&Self::log_key(transaction_id)).await?;+ match raw {+ Some(data) => {+ let log: TransactionLog = serde_json::from_slice(&data).map_err(|e| e.to_string())?;+ Ok(Some(log))+ }+ None => Ok(None),+ }+ }++ async fn update_status(&self, transaction_id: &str, status: TransactionStatus) -> Result<TransactionLog, String> {+ let mut log =+ self.load_log(transaction_id).await?.ok_or_else(|| format!("Transaction not found: {transaction_id}"))?;+ log.status = status.as_str().to_string();+ log.updated_at = chrono::Utc::now().to_rfc3339();+ self.save_log(&log).await?;+ Ok(log)+ }++ pub async fn execute(+ &self,+ transaction_id: &str,+ participants: &[Arc<dyn Participant>],+ metadata: serde_json::Value,+ ) -> Result<TransactionLog, String> {+ let infos: Vec<ParticipantInfo> = participants+ .iter()+ .map(|p| ParticipantInfo { id: p.id().to_string(), name: p.name().to_string(), role: p.role().to_string() })+ .collect();++ let log = TransactionLog::new(transaction_id.to_string(), &infos, metadata);+ self.save_log(&log).await?;++ let _state = self+ .state_machine+ .create_state(&format!("2pc_{transaction_id}"), serde_json::json!({"phase": "begin"}))+ .await?;++ let vote_results = self.prepare_phase(transaction_id, participants).await?;+ let all_agreed = vote_results.iter().all(|v| v.vote);++ if all_agreed {+ self.update_status(transaction_id, TransactionStatus::Committing).await?;+ let commit_results = self.commit_phase(transaction_id, participants, 2).await;+ let all_committed =+ participants.is_empty() || (!commit_results.is_empty() && commit_results.iter().all(|r| r.committed));+ if all_committed {+ let log = self.update_status(transaction_id, TransactionStatus::Committed).await?;+ let _ = self+ .state_machine+ .transition(&format!("2pc_{transaction_id}"), crate::state_persistence::StateTransition::Completed)+ .await;+ Ok(log)+ } else {+ let _ = self.update_status(transaction_id, TransactionStatus::RollingBack).await?;+ let _ = self.rollback_phase(transaction_id, participants).await;++ // Use commit-phase outcomes only — never re-invoke commit() to probe.+ let has_committed = commit_results.iter().any(|r| r.committed);+ let final_status = if has_committed { TransactionStatus::Mixed } else { TransactionStatus::RolledBack };++ let log = self.update_status(transaction_id, final_status).await?;+ let _ = self+ .state_machine+ .transition(&format!("2pc_{transaction_id}"), crate::state_persistence::StateTransition::Failed)+ .await;+ let failures: Vec<String> = commit_results+ .iter()+ .filter(|r| !r.committed)+ .map(|r| format!("{}: {}", r.participant_id, r.error.as_deref().unwrap_or("unknown")))+ .collect();+ Err(format!("Commit phase failed: {}. Status: {}", failures.join("; "), log.status))+ }+ } else {+ let _ = self.update_status(transaction_id, TransactionStatus::RollingBack).await?;+ let _ = self.rollback_phase(transaction_id, participants).await;+ let log = self.update_status(transaction_id, TransactionStatus::RolledBack).await?;+ let _ = self+ .state_machine+ .transition(&format!("2pc_{transaction_id}"), crate::state_persistence::StateTransition::Failed)+ .await;++ let rejections: Vec<String> = vote_results+ .iter()+ .filter_map(|v| {+ if !v.vote {+ Some(format!(+ "{}: {}",+ v.participant_id,+ v.reason.clone().unwrap_or_else(|| "no reason".to_string())+ ))+ } else {+ None+ }+ })+ .collect();++ Err(format!(+ "Prepare phase failed: participants did not agree. Rejections: [{}]. Status: {}",+ rejections.join(", "),+ log.status+ ))+ }+ }++ async fn prepare_phase(+ &self,+ transaction_id: &str,+ participants: &[Arc<dyn Participant>],+ ) -> Result<Vec<VoteResult>, String> {+ self.update_status(transaction_id, TransactionStatus::Preparing).await?;++ let mut results = Vec::new();+ for p in participants {+ match p.prepare(transaction_id).await {+ Ok(()) => {+ results.push(VoteResult { participant_id: p.id().to_string(), vote: true, reason: None });+ }+ Err(e) => {+ results.push(VoteResult {+ participant_id: p.id().to_string(),+ vote: false,+ reason: Some(e.clone()),+ });+ return Ok(results);+ }+ }+ }++ self.update_status(transaction_id, TransactionStatus::Prepared).await?;+ Ok(results)+ }++ /// Run commit for all participants; always returns per-participant outcomes+ /// (including partial success) so callers can mark Mixed without re-committing.+ async fn commit_phase(+ &self,+ transaction_id: &str,+ participants: &[Arc<dyn Participant>],+ max_retries: u32,+ ) -> Vec<ParticipantCommitResult> {+ let mut results: Vec<ParticipantCommitResult> = Vec::new();+ let mut pending: Vec<&Arc<dyn Participant>> = participants.iter().collect();++ for attempt in 0..=max_retries {+ let mut next_pending = Vec::new();+ for p in pending {+ match p.commit(transaction_id).await {+ Ok(()) => {+ results.push(ParticipantCommitResult {+ participant_id: p.id().to_string(),+ committed: true,+ error: None,+ });+ }+ Err(e) => {+ if attempt < max_retries {+ log::warn!(+ "2PC commit retry {}/{} for participant {}: {}",+ attempt + 1,+ max_retries,+ p.id(),+ e+ );+ next_pending.push(p);+ } else {+ results.push(ParticipantCommitResult {+ participant_id: p.id().to_string(),+ committed: false,+ error: Some(e),+ });+ }+ }+ }+ }+ pending = next_pending;+ if pending.is_empty() {+ break;+ }+ }++ results+ }++ async fn rollback_phase(&self, transaction_id: &str, participants: &[Arc<dyn Participant>]) -> Result<(), String> {+ let mut errors = Vec::new();+ for p in participants {+ if let Err(e) = p.rollback(transaction_id).await {+ errors.push(format!("{}: {}", p.id(), e));+ }+ }+ if errors.is_empty() {+ Ok(())+ } else {+ Err(errors.join("; "))+ }+ }++ pub async fn recover(+ &self,+ transaction_id: &str,+ participants: &[Arc<dyn Participant>],+ ) -> Result<TransactionLog, String> {+ let log = self+ .load_log(transaction_id)+ .await?+ .ok_or_else(|| format!("No transaction log found for: {transaction_id}"))?;++ let status = TransactionStatus::from_str(&log.status);+ match status {+ TransactionStatus::Preparing | TransactionStatus::Prepared => {+ self.rollback_phase(transaction_id, participants).await?;+ self.update_status(transaction_id, TransactionStatus::RolledBack).await+ }+ TransactionStatus::Committing => {+ let commit_results = self.commit_phase(transaction_id, participants, 2).await;+ let all_committed = participants.is_empty()+ || (!commit_results.is_empty() && commit_results.iter().all(|r| r.committed));+ if all_committed {+ self.update_status(transaction_id, TransactionStatus::Committed).await+ } else {+ self.rollback_phase(transaction_id, participants).await?;+ let has_committed = commit_results.iter().any(|r| r.committed);+ let final_status =+ if has_committed { TransactionStatus::Mixed } else { TransactionStatus::RolledBack };+ self.update_status(transaction_id, final_status).await?;+ let failures: Vec<String> = commit_results+ .iter()+ .filter(|r| !r.committed)+ .map(|r| format!("{}: {}", r.participant_id, r.error.as_deref().unwrap_or("unknown")))+ .collect();+ Err(format!("Recovery failed during commit: {}", failures.join("; ")))+ }+ }+ TransactionStatus::RollingBack => {+ self.rollback_phase(transaction_id, participants).await?;+ self.update_status(transaction_id, TransactionStatus::RolledBack).await+ }+ TransactionStatus::Committed | TransactionStatus::RolledBack | TransactionStatus::Mixed => Ok(log),+ TransactionStatus::Unknown => {+ Err(format!("Unknown transaction status for {transaction_id}: cannot recover"))+ }+ }+ }+}++/// Participant adapter for database statement execution via TwoPhaseCommit.+/// The caller provides async closures for the actual database operations.+#[allow(clippy::type_complexity)]+pub struct FnParticipant {+ id: String,+ name: String,+ role: String,+ prepare_fn: Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> + Send + Sync>,+ commit_fn: Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> + Send + Sync>,+ rollback_fn: Box<dyn Fn() -> Pin<Box<dyn Future<Output = Result<(), String>> + Send>> + Send + Sync>,+}++impl FnParticipant {+ pub fn new(+ id: String,+ name: String,+ role: String,+ prepare_fn: impl Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>+ + Send+ + Sync+ + 'static,+ commit_fn: impl Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>+ + Send+ + Sync+ + 'static,+ rollback_fn: impl Fn() -> std::pin::Pin<Box<dyn std::future::Future<Output = Result<(), String>> + Send>>+ + Send+ + Sync+ + 'static,+ ) -> Self {+ Self {+ id,+ name,+ role,+ prepare_fn: Box::new(prepare_fn),+ commit_fn: Box::new(commit_fn),+ rollback_fn: Box::new(rollback_fn),+ }+ }+}++#[async_trait]+impl Participant for FnParticipant {+ fn id(&self) -> &str {+ &self.id+ }+ fn name(&self) -> &str {+ &self.name+ }+ fn role(&self) -> &str {+ &self.role+ }++ async fn prepare(&self, _transaction_id: &str) -> Result<(), String> {+ (self.prepare_fn)().await+ }++ async fn commit(&self, _transaction_id: &str) -> Result<(), String> {+ (self.commit_fn)().await+ }++ async fn rollback(&self, _transaction_id: &str) -> Result<(), String> {+ (self.rollback_fn)().await+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use std::sync::Mutex;++ struct MockParticipant {+ id: String,+ name: String,+ role: String,+ should_fail_prepare: bool,+ should_fail_commit: bool,+ prepare_called: Mutex<bool>,+ commit_called: Mutex<bool>,+ rollback_called: Mutex<bool>,+ }++ impl MockParticipant {+ fn new(id: &str, name: &str) -> Self {+ Self {+ id: id.to_string(),+ name: name.to_string(),+ role: "worker".to_string(),+ should_fail_prepare: false,+ should_fail_commit: false,+ prepare_called: Mutex::new(false),+ commit_called: Mutex::new(false),+ rollback_called: Mutex::new(false),+ }+ }++ fn with_prepare_failure(mut self) -> Self {+ self.should_fail_prepare = true;+ self+ }++ fn with_commit_failure(mut self) -> Self {+ self.should_fail_commit = true;+ self+ }++ #[allow(dead_code)]+ fn prepare_was_called(&self) -> bool {+ *self.prepare_called.lock().unwrap()+ }++ #[allow(dead_code)]+ fn commit_was_called(&self) -> bool {+ *self.commit_called.lock().unwrap()+ }++ #[allow(dead_code)]+ fn rollback_was_called(&self) -> bool {+ *self.rollback_called.lock().unwrap()+ }+ }++ #[async_trait]+ impl Participant for MockParticipant {+ fn id(&self) -> &str {+ &self.id+ }+ fn name(&self) -> &str {+ &self.name+ }+ fn role(&self) -> &str {+ &self.role+ }++ async fn prepare(&self, _transaction_id: &str) -> Result<(), String> {+ *self.prepare_called.lock().unwrap() = true;+ if self.should_fail_prepare {+ Err(format!("{}: prepare failed", self.id))+ } else {+ Ok(())+ }+ }++ async fn commit(&self, _transaction_id: &str) -> Result<(), String> {+ *self.commit_called.lock().unwrap() = true;+ if self.should_fail_commit {+ Err(format!("{}: commit failed", self.id))+ } else {+ Ok(())+ }+ }++ async fn rollback(&self, _transaction_id: &str) -> Result<(), String> {+ *self.rollback_called.lock().unwrap() = true;+ Ok(())+ }+ }++ async fn make_2pc() -> (TwoPhaseCommit, std::path::PathBuf) {+ use crate::storage::Storage;+ let path = std::env::temp_dir().join(format!("test_2pc_{}.db", uuid::Uuid::new_v4()));+ let storage = Arc::new(Storage::open(&path).await.unwrap());+ let backend: Arc<dyn StateBackend> = Arc::new(crate::state_persistence::LocalBackend::new(storage));+ (TwoPhaseCommit::new(backend), path)+ }++ #[tokio::test]+ async fn two_phase_commit_success() {+ let (coordinator, _tmp) = make_2pc().await;+ let p1: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "worker1"));+ let p2: Arc<dyn Participant> = Arc::new(MockParticipant::new("p2", "worker2"));++ let result =+ coordinator.execute("tx_success", &[p1.clone(), p2.clone()], serde_json::json!({"op": "test"})).await;++ assert!(result.is_ok());+ let log = result.unwrap();+ assert_eq!(log.status, TransactionStatus::Committed.as_str());+ }++ #[tokio::test]+ async fn two_phase_commit_prepare_failure_triggers_rollback() {+ let (coordinator, _tmp) = make_2pc().await;+ let p1: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "good").with_commit_failure());+ let p2: Arc<dyn Participant> = Arc::new(MockParticipant::new("p2", "bad").with_prepare_failure());++ let result = coordinator.execute("tx_prepare_fail", &[p1.clone(), p2.clone()], serde_json::json!({})).await;++ assert!(result.is_err());+ let err = result.unwrap_err();+ assert!(err.contains("Prepare phase failed"));+ assert!(err.contains("p2"));+ }++ #[tokio::test]+ async fn two_phase_commit_commit_failure_triggers_rollback() {+ let (coordinator, _tmp) = make_2pc().await;+ let failing: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "fail_commit").with_commit_failure());+ let passing: Arc<dyn Participant> = Arc::new(MockParticipant::new("p2", "ok"));++ let result =+ coordinator.execute("tx_commit_fail", &[failing.clone(), passing.clone()], serde_json::json!({})).await;++ assert!(result.is_err());+ let log = coordinator.load_log("tx_commit_fail").await.unwrap().unwrap();+ assert_eq!(log.status, TransactionStatus::Mixed.as_str());+ }++ #[tokio::test]+ async fn two_phase_commit_empty_participants() {+ let (coordinator, _tmp) = make_2pc().await;+ let participants: Vec<Arc<dyn Participant>> = vec![];++ let result = coordinator.execute("tx_empty", &participants, serde_json::json!({})).await;++ assert!(result.is_ok());+ let log = result.unwrap();+ assert_eq!(log.status, TransactionStatus::Committed.as_str());+ }++ #[tokio::test]+ async fn recovery_from_preparing_state() {+ let (coordinator, _tmp) = make_2pc().await;+ let p1: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "w1"));++ let log = TransactionLog {+ transaction_id: "tx_recover_preparing".to_string(),+ status: TransactionStatus::Preparing.as_str().to_string(),+ participants: vec![ParticipantInfo {+ id: "p1".to_string(),+ name: "w1".to_string(),+ role: "worker".to_string(),+ }],+ created_at: chrono::Utc::now().to_rfc3339(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ metadata: serde_json::json!({}),+ };+ coordinator.save_log(&log).await.unwrap();++ let result = coordinator.recover("tx_recover_preparing", &[Arc::clone(&p1)]).await;++ assert!(result.is_ok());+ let recovered = result.unwrap();+ assert_eq!(recovered.status, TransactionStatus::RolledBack.as_str());+ }++ #[tokio::test]+ async fn recovery_from_committing_state() {+ let (coordinator, _tmp) = make_2pc().await;+ let p1: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "w1"));++ let log = TransactionLog {+ transaction_id: "tx_recover_committing".to_string(),+ status: TransactionStatus::Committing.as_str().to_string(),+ participants: vec![ParticipantInfo {+ id: "p1".to_string(),+ name: "w1".to_string(),+ role: "worker".to_string(),+ }],+ created_at: chrono::Utc::now().to_rfc3339(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ metadata: serde_json::json!({}),+ };+ coordinator.save_log(&log).await.unwrap();++ let result = coordinator.recover("tx_recover_committing", &[Arc::clone(&p1)]).await;++ assert!(result.is_ok());+ let recovered = result.unwrap();+ assert_eq!(recovered.status, TransactionStatus::Committed.as_str());+ }++ #[tokio::test]+ async fn recovery_already_completed_noop() {+ let (coordinator, _tmp) = make_2pc().await;+ let p1: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "w1"));++ let log = TransactionLog {+ transaction_id: "tx_done".to_string(),+ status: TransactionStatus::Committed.as_str().to_string(),+ participants: vec![ParticipantInfo {+ id: "p1".to_string(),+ name: "w1".to_string(),+ role: "worker".to_string(),+ }],+ created_at: chrono::Utc::now().to_rfc3339(),+ updated_at: chrono::Utc::now().to_rfc3339(),+ metadata: serde_json::json!({}),+ };+ coordinator.save_log(&log).await.unwrap();++ let result = coordinator.recover("tx_done", &[p1]).await;+ assert!(result.is_ok());+ let recovered = result.unwrap();+ assert_eq!(recovered.status, TransactionStatus::Committed.as_str());+ }++ #[tokio::test]+ async fn recovery_unknown_transaction_errors() {+ let (coordinator, _tmp) = make_2pc().await;+ let p1: Arc<dyn Participant> = Arc::new(MockParticipant::new("p1", "w1"));++ let result = coordinator.recover("tx_nonexistent", &[p1]).await;+ assert!(result.is_err());+ }+}diff --git a/crates/dbx-core/tests/api_contract_verification.rs b/crates/dbx-core/tests/api_contract_verification.rsnew file mode 100644index 0000000000..c742b1b412--- /dev/null+++ b/crates/dbx-core/tests/api_contract_verification.rs@@ -0,0 +1,342 @@+// ============================================================================+// 12.4 — CLI/Tauri/dbx-web API Contract Verification+//+// These tests verify that public API types maintain backward-compatible+// serialization contracts (field names, optional field handling) and+// that function signatures haven't changed.+// ============================================================================++use dbx_core::data_compare::{DataComparePreparation, DataCompareSyncPlan};+use dbx_core::models::connection::DatabaseType;+use dbx_core::schema_diff::{prepare_schema_diff, SchemaDiffPreparation, SchemaDiffPreparationOptions};+use dbx_core::sql_risk::{classify_sql_risk, SqlRisk};+use dbx_core::types::{ColumnInfo, TableInfo};++// ============================================================================+// Compile-time checks: core function signatures compile+// ============================================================================++/// Verify prepare_schema_diff accepts SchemaDiffPreparationOptions and returns SchemaDiffPreparation+#[test]+fn prepare_schema_diff_function_signature() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".to_string(),+ table_type: "TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "t".to_string(),+ table_type: "TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![],+ target_details: vec![],+ source_functions: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type: DatabaseType::Postgres,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ detect_renames: false,+ detect_table_renames: false,+ rename_threshold: 0.5,+ enable_rollback: false,+ batch_patterns: vec![],+ source_dialect: None,+ target_dialect: None,+ compatibility_threshold: 0.5,+ source_permissions: vec![],+ target_permissions: vec![],+ shard_strategy: None,+ resource_constraint: None,+ field_mappings: vec![],+ };+ let _result: SchemaDiffPreparation = prepare_schema_diff(options);+}++/// Verify generate_schema_sync_sql accepts all arg types+#[test]+fn generate_schema_sync_sql_function_signature() {+ let _sql = dbx_core::schema_diff::generate_schema_sync_sql(+ &[],+ &[],+ &[],+ &[],+ &[],+ DatabaseType::Postgres,+ None,+ false,+ None,+ &[],+ );+}++/// Verify classify_sql_risk function signature+#[test]+fn classify_sql_risk_function_signature() {+ let _risk: SqlRisk = classify_sql_risk("SELECT 1", "postgres").unwrap();+}++// ============================================================================+// Serialization contract: field naming conventions+// ============================================================================++/// SchemaDiffPreparation fields use camelCase in JSON+#[test]+fn schema_diff_preparation_field_names() {+ let result = prepare_schema_diff(SchemaDiffPreparationOptions {+ source_tables: vec![TableInfo {+ name: "t".to_string(),+ table_type: "TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ target_tables: vec![TableInfo {+ name: "t".to_string(),+ table_type: "TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }],+ source_details: vec![],+ target_details: vec![],+ source_functions: vec![],+ target_functions: vec![],+ source_sequences: vec![],+ target_sequences: vec![],+ source_rules: vec![],+ target_rules: vec![],+ source_owners: vec![],+ target_owners: vec![],+ database_type: DatabaseType::Postgres,+ target_schema: None,+ ignore_comments: false,+ cascade_delete: false,+ compare_column_order: false,+ detect_renames: false,+ detect_table_renames: false,+ rename_threshold: 0.5,+ enable_rollback: false,+ batch_patterns: vec![],+ source_dialect: None,+ target_dialect: None,+ compatibility_threshold: 0.5,+ source_permissions: vec![],+ target_permissions: vec![],+ shard_strategy: None,+ resource_constraint: None,+ field_mappings: vec![],+ });++ let json = serde_json::to_value(&result).unwrap();+ let obj = json.as_object().unwrap();+ let keys: Vec<&str> = obj.keys().map(|k| k.as_str()).collect();++ // All keys must be camelCase (no underscores)+ for key in &keys {+ assert!(!key.contains('_'), "Key '{}' should be camelCase, not snake_case", key);+ }++ // Core fields must be present+ assert!(keys.contains(&"diffs"), "diffs field must be present");+ assert!(keys.contains(&"syncSql"), "syncSql field must be present");+}++/// DataComparePreparation fields use camelCase+#[test]+fn data_compare_preparation_field_names() {+ use dbx_core::data_compare::{DataCompareResult, DataCompareRow};+ use serde_json::Value;++ let prep = DataComparePreparation {+ result: DataCompareResult {+ added: vec![DataCompareRow {+ key: "1".to_string(),+ key_values: [("id".to_string(), Value::Number(1.into()))].into(),+ values: [("name".to_string(), Value::String("Alice".to_string()))].into(),+ }],+ removed: vec![],+ modified: vec![],+ },+ sync_statements: vec!["INSERT INTO t VALUES (1)".to_string()],+ sync_sql: "INSERT INTO t VALUES (1)".to_string(),+ };++ let json = serde_json::to_value(&prep).unwrap();+ let obj = json.as_object().unwrap();+ for key in obj.keys() {+ assert!(!key.contains('_'), "Key '{}' should be camelCase", key);+ }+ assert!(obj.contains_key("result"), "result must be present");+}++/// DataCompareSyncPlan fields use camelCase+#[test]+fn data_compare_sync_plan_field_names() {+ let plan = DataCompareSyncPlan {+ insert_count: 0,+ update_count: 0,+ delete_count: 0,+ statement_count: 0,+ sync_statements: vec![],+ sync_sql: String::new(),+ };++ let json = serde_json::to_value(&plan).unwrap();+ let obj = json.as_object().unwrap();+ for key in obj.keys() {+ assert!(!key.contains('_'), "Key '{}' should be camelCase", key);+ }+}++// ============================================================================+// Type serialization roundtrip: types used in API boundaries+// ============================================================================++/// Core types must serialize/deserialize consistently+#[test]+fn core_types_serialization_roundtrip() {+ let table = TableInfo {+ name: "users".to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: Some("user table".to_string()),+ parent_schema: Some("public".to_string()),+ parent_name: None,+ };+ let json = serde_json::to_value(&table).unwrap();+ let deserialized: TableInfo = serde_json::from_value(json).unwrap();+ assert_eq!(table.name, deserialized.name);+ assert_eq!(table.comment, deserialized.comment);+}++/// ColumnInfo must serialize/deserialize consistently+#[test]+fn column_info_serialization_roundtrip() {+ let col = ColumnInfo {+ name: "id".to_string(),+ data_type: "int".to_string(),+ is_nullable: false,+ column_default: None,+ is_primary_key: true,+ extra: None,+ comment: None,+ numeric_precision: Some(10),+ numeric_scale: Some(0),+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ };+ let json = serde_json::to_value(&col).unwrap();+ let deserialized: ColumnInfo = serde_json::from_value(json).unwrap();+ assert_eq!(col.name, deserialized.name);+ assert_eq!(col.numeric_precision, deserialized.numeric_precision);+}++// ============================================================================+// DatabaseType serialization consistency+// ============================================================================++#[test]+fn database_type_serialization() {+ let json = serde_json::to_value(DatabaseType::Postgres).unwrap();+ assert_eq!(json, "postgres", "DatabaseType serializes using snake_case");++ let json = serde_json::to_value(DatabaseType::Mysql).unwrap();+ assert_eq!(json, "mysql", "DatabaseType serializes using snake_case");+}++// ============================================================================+// Tauri command argument compatibility: Option parameters+// ============================================================================++/// Verify that the types used as Tauri command args serialize/deserialize properly.+/// Tauri passes these as JSON from the frontend, so serde roundtrip must work.+#[test]+fn option_types_work_in_tauri_command_boundary() {+ // Simulate how Tauri passes optional params from JS frontend+ #[derive(serde::Serialize, serde::Deserialize)]+ #[serde(rename_all = "camelCase")]+ struct TauriLikeCommand {+ diffs: Vec<dbx_core::schema_diff::TableDiff>,+ function_diffs: Option<Vec<dbx_core::schema_diff::FunctionDiff>>,+ cascade_delete: Option<bool>,+ target_schema: Option<String>,+ }++ // Without optional params (frontend omitting them)+ let input = serde_json::json!({+ "diffs": [],+ "functionDiffs": null,+ "cascadeDelete": null,+ "targetSchema": null+ });+ let cmd: TauriLikeCommand = serde_json::from_value(input).unwrap();+ assert!(cmd.function_diffs.is_none());+ assert!(cmd.cascade_delete.is_none());++ // With explicit values+ let input = serde_json::json!({+ "diffs": [],+ "cascadeDelete": true+ });+ let cmd: TauriLikeCommand = serde_json::from_value(input).unwrap();+ assert_eq!(cmd.cascade_delete, Some(true));+}++// ============================================================================+// Web API request compatibility+// ============================================================================++/// Verify GenerateSchemaSyncSqlRequest contract matches the core function signature+#[test]+fn web_api_schema_sync_request_fields() {+ #[derive(serde::Deserialize)]+ #[serde(rename_all = "camelCase")]+ #[allow(dead_code)]+ struct WebApiRequest {+ diffs: Vec<dbx_core::schema_diff::TableDiff>,+ function_diffs: Option<Vec<dbx_core::schema_diff::FunctionDiff>>,+ sequence_diffs: Option<Vec<dbx_core::schema_diff::SequenceDiff>>,+ rule_diffs: Option<Vec<dbx_core::schema_diff::RuleDiff>>,+ owner_diffs: Option<Vec<dbx_core::schema_diff::OwnerDiff>>,+ database_type: DatabaseType,+ target_schema: Option<String>,+ cascade_delete: Option<bool>,+ }++ let json = serde_json::json!({+ "diffs": [],+ "databaseType": "postgres"+ });+ let req: WebApiRequest = serde_json::from_value(json).unwrap();+ assert!(req.diffs.is_empty());+ assert_eq!(req.database_type, DatabaseType::Postgres);+ assert!(req.target_schema.is_none());+ assert!(req.cascade_delete.is_none());+}++// ============================================================================+// SqlRisk enum backward compat: JSON serialization+// ============================================================================++#[test]+fn sql_risk_json_representation() {+ assert_eq!(serde_json::to_value(SqlRisk::ReadOnly).unwrap(), "ReadOnly");+ assert_eq!(serde_json::to_value(SqlRisk::Write).unwrap(), "Write");+ assert_eq!(serde_json::to_value(SqlRisk::Ddl).unwrap(), "Ddl");+ assert_eq!(serde_json::to_value(SqlRisk::Transaction).unwrap(), "Transaction");+}diff --git a/crates/dbx-core/tests/bidirectional_diff_e2e.rs b/crates/dbx-core/tests/bidirectional_diff_e2e.rsnew file mode 100644index 0000000000..8ce6b4dd04--- /dev/null+++ b/crates/dbx-core/tests/bidirectional_diff_e2e.rs@@ -0,0 +1,273 @@+use dbx_core::models::connection::DatabaseType;+use dbx_core::schema_diff::{prepare_schema_diff, RollbackGraph, SchemaDiffPreparationOptions, TableSchemaDetail};+use dbx_core::types::{ColumnInfo, TableInfo};++fn table(name: &str) -> TableInfo {+ TableInfo {+ name: name.to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }+}++fn col(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: data_type.to_string(),+ is_nullable: false,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }+}++fn detail(name: &str, columns: Vec<ColumnInfo>) -> TableSchemaDetail {+ TableSchemaDetail {+ name: name.to_string(),+ columns,+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }+}++// ============================================================================+// 12.3 — Bidirectional Diff E2E Tests+// ============================================================================++/// Create scenario: source (desired) has [id, name, email], target (current) has [id, name]+/// Forward: ADD column email → Rollback: DROP column email+#[test]+fn bidirectional_diff_add_rollback_identity() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail(+ "users",+ vec![col("id", "int"), col("name", "varchar(64)"), col("email", "varchar(128)")],+ )],+ target_details: vec![detail("users", vec![col("id", "int"), col("name", "varchar(64)")])],+ database_type: DatabaseType::Postgres,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ assert!(!result.diffs.is_empty(), "Should detect new column in source");+ assert!(result.rollback_sync_sql.is_some(), "Rollback SQL should be generated");++ let forward_sql = &result.sync_sql;+ let rollback_sql = result.rollback_sync_sql.as_ref().unwrap();++ // Forward should ADD column to target, rollback should DROP column+ assert!(forward_sql.contains("ADD"), "Forward SQL should contain ADD");+ assert!(rollback_sql.contains("DROP"), "Rollback SQL should contain DROP");+}++/// Delete scenario: source (desired) has [id], target (current) has [id, name, status]+/// Forward: DROP column name, status → Rollback: ADD column name, status+#[test]+fn bidirectional_diff_delete_rollback_identity() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail("users", vec![col("id", "int")])],+ target_details: vec![detail(+ "users",+ vec![col("id", "int"), col("name", "varchar(64)"), col("status", "varchar(16)")],+ )],+ database_type: DatabaseType::Postgres,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ assert!(!result.diffs.is_empty(), "Should detect extra columns in target");+ assert!(result.rollback_sync_sql.is_some(), "Rollback SQL should be generated");++ let forward_sql = &result.sync_sql;+ let rollback_sql = result.rollback_sync_sql.as_ref().unwrap();++ // Forward should contain DROP for removed columns+ assert!(forward_sql.contains("DROP"), "Forward SQL should contain DROP");+ assert!(!rollback_sql.is_empty(), "Rollback SQL should not be empty");+}++/// Modify scenario: source (desired) has varchar(64), target (current) has varchar(128)+/// Forward: ALTER column type → Rollback: ALTER column back+#[test]+fn bidirectional_diff_modify_rollback_identity() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail("users", vec![col("name", "varchar(64)")])],+ target_details: vec![detail("users", vec![col("name", "varchar(128)")])],+ database_type: DatabaseType::Postgres,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ assert!(!result.diffs.is_empty(), "Should detect modified column");+ assert_eq!(result.diffs[0].diff_type, "modified");++ // Should have rollback SQL+ assert!(result.rollback_sync_sql.is_some(), "Rollback SQL should be generated");+}++/// RollbackGraph consistency: forward ∘ rollback = identity+#[test]+fn rollback_graph_consistency() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail("users", vec![col("id", "int"), col("name", "varchar(64)")])],+ target_details: vec![detail(+ "users",+ vec![col("id", "int"), col("name", "varchar(64)"), col("email", "varchar(128)")],+ )],+ database_type: DatabaseType::Postgres,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ assert!(result.rollback_graph.is_some(), "RollbackGraph should be generated");+ let graph = result.rollback_graph.as_ref().unwrap();+ assert!(graph.is_consistent, "RollbackGraph should be consistent");+ assert!(graph.consistency_issues.is_empty(), "RollbackGraph should have no consistency issues");+}++/// RollbackGraph forward + rollback roundtrip: verify rollback_nodes are generated+#[test]+fn rollback_graph_generates_rollback_nodes() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail("users", vec![col("id", "int"), col("status", "varchar(16)")])],+ target_details: vec![detail("users", vec![col("id", "int"), col("status", "varchar(32)")])],+ database_type: DatabaseType::Postgres,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(result.rollback_graph.is_some());++ let graph = result.rollback_graph.as_ref().unwrap();+ assert!(!graph.rollback_nodes.is_empty(), "rollback_nodes should be non-empty");+ assert!(graph.is_consistent, "RollbackGraph should be consistent");+}++/// Multiple table E2E: modify one table, add/remove columns in others+#[test]+fn bidirectional_diff_multi_table_e2e() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("orders"), table("items"), table("archive")],+ target_tables: vec![table("orders"), table("items"), table("archive")],+ source_details: vec![+ // desired: orders with larger decimal + status column added+ detail("orders", vec![col("id", "int"), col("total", "decimal(12,2)"), col("status", "varchar(16)")]),+ // desired: items with larger name+ detail("items", vec![col("id", "int"), col("name", "varchar(128)")]),+ // desired: archive with only id+ detail("archive", vec![col("id", "int")]),+ ],+ target_details: vec![+ // current: orders with smaller decimal, no status+ detail("orders", vec![col("id", "int"), col("total", "decimal(10,2)")]),+ // current: items with smaller name+ detail("items", vec![col("id", "int"), col("name", "varchar(64)")]),+ // current: archive with extra column+ detail("archive", vec![col("id", "int"), col("data", "text")]),+ ],+ database_type: DatabaseType::Postgres,+ enable_rollback: true,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ assert!(!result.diffs.is_empty(), "Should detect differences across multiple tables");+ assert!(result.rollback_sync_sql.is_some(), "Rollback SQL should be generated");++ let forward_sql = &result.sync_sql;+ let rollback_sql = result.rollback_sync_sql.as_ref().unwrap();++ assert!(!forward_sql.is_empty(), "Forward SQL should be non-empty");+ assert!(!rollback_sql.is_empty(), "Rollback SQL should be non-empty");++ // Forward and rollback should be different+ assert_ne!(forward_sql, rollback_sql, "Forward and rollback SQL should differ");+}++/// Rename detection: verify rename candidates are populated with matching column structures+#[test]+fn bidirectional_diff_with_rename_detection() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("user_profiles")],+ source_details: vec![detail("users", vec![col("id", "int"), col("name", "varchar(64)")])],+ target_details: vec![detail("user_profiles", vec![col("id", "int"), col("name", "varchar(64)")])],+ database_type: DatabaseType::Postgres,+ detect_renames: true,+ detect_table_renames: true,+ rename_threshold: 0.5,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ // With identical column structure, rename should at least produce diffs+ assert!(!result.diffs.is_empty(), "Should detect difference between differently-named tables");++ // With identical column structures and table rename detection on, candidates must be populated+ assert!(+ !result.rename_candidates.is_empty(),+ "Rename candidates should be detected for identical column structures"+ );+ assert!(result.rename_candidates[0].score > 0.0, "Rename score should be positive");+}++/// RollbackGraph validate_consistency directly+#[test]+fn rollback_graph_direct_consistency_check() {+ use dbx_core::schema_diff::DependencyGraph;++ let forward_diff = dbx_core::schema_diff::TableDiff {+ diff_type: "added".to_string(),+ object_type: None,+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: Some("CREATE TABLE users (id INT)".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ };++ let dep_graph =+ DependencyGraph { nodes: std::collections::HashMap::new(), topological_order: vec!["users".to_string()] };++ let mut graph = RollbackGraph::from_forward_diffs(&[forward_diff], &[], &dep_graph);+ graph.validate_consistency();+ assert!(graph.is_consistent, "Simple add should produce consistent rollback graph");+ assert!(graph.consistency_issues.is_empty());+}diff --git a/crates/dbx-core/tests/cross_dialect_integration.rs b/crates/dbx-core/tests/cross_dialect_integration.rsnew file mode 100644index 0000000000..e03574f08c--- /dev/null+++ b/crates/dbx-core/tests/cross_dialect_integration.rs@@ -0,0 +1,248 @@+use dbx_core::models::connection::DatabaseType;+use dbx_core::schema_diff::{+ generate_schema_sync_sql, prepare_schema_diff, SchemaDiffPreparationOptions, TableSchemaDetail,+};+use dbx_core::sql_dialect::descriptor::DialectKind;+use dbx_core::types::{ColumnInfo, TableInfo};++fn table(name: &str) -> TableInfo {+ TableInfo {+ name: name.to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }+}++fn col(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: data_type.to_string(),+ is_nullable: false,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }+}++fn detail(name: &str, columns: Vec<ColumnInfo>) -> TableSchemaDetail {+ TableSchemaDetail {+ name: name.to_string(),+ columns,+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }+}++// ============================================================================+// 12.2 — Cross-dialect full-chain integration tests+// ============================================================================++/// MySQL → PostgreSQL: diff a schema between MySQL source and PG target,+/// verify SQL output uses PostgreSQL syntax and identifiers.+#[test]+fn mysql_to_postgresql_full_chain_diff_and_sql_generation() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail(+ "users",+ vec![col("id", "int"), col("name", "varchar(64)"), col("email", "varchar(128)")],+ )],+ target_details: vec![detail(+ "users",+ vec![col("id", "serial"), col("name", "text"), col("email", "varchar(128)"), col("age", "int")],+ )],+ database_type: DatabaseType::Postgres,+ source_dialect: Some(DialectKind::Mysql),+ target_dialect: Some(DialectKind::Postgres),+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ // Should detect column type changes and an extra column in target+ assert!(!result.diffs.is_empty(), "Should detect differences between MySQL and PG schemas");++ // SQL should use PostgreSQL double-quote identifiers+ let pg_sql = &result.sync_sql;+ assert!(pg_sql.contains('"'), "PostgreSQL SQL should use double-quoted identifiers");+ assert!(!pg_sql.contains('`'), "PostgreSQL SQL should NOT use backtick identifiers");++ // Verify compatibility warnings if type differences exist+ // varchar(64) → text may or may not generate a warning depending on threshold+}++/// PostgreSQL → SQLite: diff a schema between PG source and SQLite target,+/// verify SQL output uses SQLite-compatible syntax.+#[test]+fn postgresql_to_sqlite_full_chain_diff_and_sql_generation() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("products")],+ target_tables: vec![table("products")],+ source_details: vec![detail(+ "products",+ vec![col("id", "serial"), col("name", "varchar(100)"), col("price", "numeric(10,2)")],+ )],+ target_details: vec![detail(+ "products",+ vec![col("id", "integer"), col("name", "text"), col("price", "real"), col("category", "text")],+ )],+ database_type: DatabaseType::Sqlite,+ source_dialect: Some(DialectKind::Postgres),+ target_dialect: Some(DialectKind::Sqlite),+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ assert!(!result.diffs.is_empty(), "Should detect differences between PG and SQLite schemas");++ // SQLite identifiers are double-quoted or unquoted+ let sqlite_sql = &result.sync_sql;+ // SQLite uses CREATE TABLE IF NOT EXISTS etc.+ assert!(!sqlite_sql.contains("::"), "SQLite SQL should not contain PG type casts");+}++/// MySQL → SQLite: full chain cross-dialect comparison+#[test]+fn mysql_to_sqlite_cross_dialect_diff() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("events")],+ target_tables: vec![table("events")],+ source_details: vec![detail(+ "events",+ vec![+ col("id", "bigint unsigned"),+ col("event_type", "enum('click','view')"),+ col("created_at", "datetime"),+ ],+ )],+ target_details: vec![detail(+ "events",+ vec![col("id", "integer"), col("event_type", "text"), col("created_at", "text"), col("source", "text")],+ )],+ database_type: DatabaseType::Sqlite,+ source_dialect: Some(DialectKind::Mysql),+ target_dialect: Some(DialectKind::Sqlite),+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(!result.diffs.is_empty(), "MySQL enum → SQLite text should be detected as a difference");+}++// ============================================================================+// 12.2 — Same-dialect consistency: diff should be empty when schemas match+// ============================================================================++#[test]+fn identical_mysql_schemas_produce_no_diff() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail("users", vec![col("id", "int"), col("name", "varchar(64)")])],+ target_details: vec![detail("users", vec![col("id", "int"), col("name", "varchar(64)")])],+ database_type: DatabaseType::Mysql,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(result.diffs.is_empty(), "Identical schemas should produce no diffs");+ assert!(result.sync_sql.is_empty(), "Identical schemas should produce no SQL");+}++#[test]+fn identical_postgres_schemas_produce_no_diff() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![table("users")],+ target_tables: vec![table("users")],+ source_details: vec![detail("users", vec![col("id", "int"), col("name", "text")])],+ target_details: vec![detail("users", vec![col("id", "int"), col("name", "text")])],+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(result.diffs.is_empty(), "Identical schemas should produce no diffs");+}++// ============================================================================+// 12.2 — Cross-dialect generate_schema_sync_sql verification+// ============================================================================++#[test]+fn generate_schema_sync_sql_mysql_output_format() {+ let diffs = vec![dbx_core::schema_diff::TableDiff {+ diff_type: "added".to_string(),+ object_type: None,+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: Some("CREATE TABLE `users` (`id` INT NOT NULL, `name` VARCHAR(64) NOT NULL)".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ let sql = generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Mysql, None, false, None, &[]);++ assert!(sql.contains("CREATE TABLE"), "MySQL SQL should contain CREATE TABLE");+ assert!(sql.contains('`'), "MySQL SQL should use backtick identifiers");+}++#[test]+fn generate_schema_sync_sql_postgres_output_format() {+ let diffs = vec![dbx_core::schema_diff::TableDiff {+ diff_type: "added".to_string(),+ object_type: None,+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: Some("CREATE TABLE users (id SERIAL PRIMARY KEY, name TEXT NOT NULL)".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ let sql = generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, None, false, None, &[]);+ assert!(sql.contains("CREATE TABLE"), "PostgreSQL SQL should contain CREATE TABLE");+ assert!(sql.contains("SERIAL"), "PostgreSQL SQL should use SERIAL type");+}++#[test]+fn generate_schema_sync_sql_sqlite_output_format() {+ let diffs = vec![dbx_core::schema_diff::TableDiff {+ diff_type: "added".to_string(),+ object_type: None,+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: Some("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT NOT NULL)".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ let sql = generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Sqlite, None, false, None, &[]);+ assert!(sql.contains("CREATE TABLE"), "SQLite SQL should contain CREATE TABLE");+}diff --git a/crates/dbx-core/tests/performance_benchmarks.rs b/crates/dbx-core/tests/performance_benchmarks.rsnew file mode 100644index 0000000000..85d920b542--- /dev/null+++ b/crates/dbx-core/tests/performance_benchmarks.rs@@ -0,0 +1,274 @@+// ============================================================================+// 12.5 — Performance Benchmarks+//+// These benchmarks measure schema diff performance with large table sets.+// Run with: cargo test --release --test performance_benchmarks -- --ignored+// ============================================================================++use std::time::Instant;++use dbx_core::models::connection::DatabaseType;+use dbx_core::schema_diff::{+ prepare_schema_diff, SchemaDiffPreparationOptions, ShardBy, ShardStrategy, TableSchemaDetail,+};+use dbx_core::types::{ColumnInfo, TableInfo};++fn generate_tables(count: usize, prefix: &str) -> Vec<TableInfo> {+ (0..count)+ .map(|i| TableInfo {+ name: format!("{}_{}", prefix, i),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ })+ .collect()+}++fn generate_details(tables: &[TableInfo], columns_per_table: usize) -> Vec<TableSchemaDetail> {+ tables+ .iter()+ .map(|t| TableSchemaDetail {+ name: t.name.clone(),+ columns: (0..columns_per_table)+ .map(|j| ColumnInfo {+ name: format!("col_{}", j),+ data_type: if j % 3 == 0 { "int".to_string() } else { "varchar(64)".to_string() },+ is_nullable: j % 2 == 0,+ column_default: if j == 0 { Some("0".to_string()) } else { None },+ is_primary_key: j == 0,+ extra: None,+ comment: None,+ numeric_precision: if j % 3 == 0 { Some(10) } else { None },+ numeric_scale: if j % 3 == 0 { Some(0) } else { None },+ character_maximum_length: if j % 3 != 0 { Some(64) } else { None },+ enum_values: None,+ character_set: None,+ collation: None,+ })+ .collect(),+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ })+ .collect()+}++/// Benchmark: diff a small number of tables (baseline)+#[ignore]+#[test]+fn benchmark_small_schema_diff() {+ let table_count = 10;+ let columns_per_table = 5;+ let source_tables = generate_tables(table_count, "src");+ let target_tables = generate_tables(table_count, "tgt");+ let source_details = generate_details(&source_tables, columns_per_table);+ let target_details = generate_details(&target_tables, columns_per_table);++ let options = SchemaDiffPreparationOptions {+ source_tables,+ target_tables,+ source_details,+ target_details,+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let start = Instant::now();+ let result = prepare_schema_diff(options);+ let elapsed = start.elapsed();++ assert!(!result.diffs.is_empty(), "Should detect differences");+ eprintln!("[BENCHMARK] small_schema_diff ({} tables, {} cols): {:?}", table_count, columns_per_table, elapsed);+}++/// Benchmark: diff a medium number of tables+#[ignore]+#[test]+fn benchmark_medium_schema_diff() {+ let table_count = 100;+ let columns_per_table = 10;+ let source_tables = generate_tables(table_count, "src");+ let target_tables = generate_tables(table_count, "tgt");+ let source_details = generate_details(&source_tables, columns_per_table);+ let target_details = generate_details(&target_tables, columns_per_table);++ let options = SchemaDiffPreparationOptions {+ source_tables,+ target_tables,+ source_details,+ target_details,+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let start = Instant::now();+ let result = prepare_schema_diff(options);+ let elapsed = start.elapsed();++ assert!(!result.diffs.is_empty(), "Should detect differences");+ eprintln!("[BENCHMARK] medium_schema_diff ({} tables, {} cols): {:?}", table_count, columns_per_table, elapsed);+}++/// Benchmark: diff a large number of tables+#[ignore]+#[test]+fn benchmark_large_schema_diff() {+ let table_count = 200;+ let columns_per_table = 10;+ let source_tables = generate_tables(table_count, "src");+ let target_tables = generate_tables(table_count, "tgt");+ let source_details = generate_details(&source_tables, columns_per_table);+ let target_details = generate_details(&target_tables, columns_per_table);++ let options = SchemaDiffPreparationOptions {+ source_tables,+ target_tables,+ source_details,+ target_details,+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let start = Instant::now();+ let result = prepare_schema_diff(options);+ let elapsed = start.elapsed();++ assert!(!result.diffs.is_empty(), "Should detect differences");+ eprintln!("[BENCHMARK] large_schema_diff ({} tables, {} cols): {:?}", table_count, columns_per_table, elapsed);+}++/// Benchmark: diff 1000 tables (simulates the 1000-table requirement)+#[ignore]+#[test]+fn benchmark_thousand_table_schema_diff() {+ let table_count = 1000;+ let columns_per_table = 5;+ let source_tables = generate_tables(table_count, "src");+ let target_tables = generate_tables(table_count, "tgt");+ let source_details = generate_details(&source_tables, columns_per_table);+ let target_details = generate_details(&target_tables, columns_per_table);++ let options = SchemaDiffPreparationOptions {+ source_tables,+ target_tables,+ source_details,+ target_details,+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let start = Instant::now();+ let result = prepare_schema_diff(options);+ let elapsed = start.elapsed();++ assert!(!result.diffs.is_empty(), "Should detect differences");+ eprintln!(+ "[BENCHMARK] thousand_table_schema_diff ({} tables, {} cols): {:?}",+ table_count, columns_per_table, elapsed+ );+}++/// Benchmark: shard-parallel speedup comparison+#[ignore]+#[test]+fn benchmark_shard_parallel_speedup() {+ let table_count = 200;+ let columns_per_table = 8;+ let source_tables = generate_tables(table_count, "src");+ let target_tables = generate_tables(table_count, "tgt");+ let source_details = generate_details(&source_tables, columns_per_table);+ let target_details = generate_details(&target_tables, columns_per_table);++ // Single-threaded (shard_count = 1)+ let options_single = SchemaDiffPreparationOptions {+ source_tables: source_tables.clone(),+ target_tables: target_tables.clone(),+ source_details: source_details.clone(),+ target_details: target_details.clone(),+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let start_single = Instant::now();+ let _result_single = prepare_schema_diff(options_single);+ let single_time = start_single.elapsed();++ // Shard-parallel (shard_count = 4)+ let shard_options = SchemaDiffPreparationOptions {+ source_tables: source_tables.clone(),+ target_tables: target_tables.clone(),+ source_details: source_details.clone(),+ target_details: target_details.clone(),+ database_type: DatabaseType::Postgres,+ shard_strategy: Some(ShardStrategy { shard_count: 4, shard_by: ShardBy::RoundRobin }),+ ..Default::default()+ };++ let start_parallel = Instant::now();+ let _result_parallel = prepare_schema_diff(shard_options);+ let parallel_time = start_parallel.elapsed();++ eprintln!(+ "[BENCHMARK] shard_speedup: single={:?}, parallel(4 shards)={:?}, speedup={:.2}x",+ single_time,+ parallel_time,+ single_time.as_secs_f64() / parallel_time.as_secs_f64().max(0.0001)+ );++ assert!(+ parallel_time <= single_time * 3, // Allow some overhead; shard_count=4 may not be 4x faster on small data+ "Parallel should not be significantly slower than single-threaded"+ );+}++/// Benchmark: DependencyGraph build time+#[ignore]+#[test]+fn benchmark_dependency_graph_build() {+ use dbx_core::schema_diff::DependencyGraph;+ use dbx_core::types::ForeignKeyInfo;++ let details: Vec<TableSchemaDetail> = (0..100)+ .map(|i| {+ let mut fks = vec![];+ if i > 0 {+ fks.push(ForeignKeyInfo {+ name: format!("fk_{}_to_{}", i, i - 1),+ column: "parent_id".to_string(),+ ref_schema: None,+ ref_table: format!("tgt_{}", i - 1),+ ref_column: "id".to_string(),+ on_update: None,+ on_delete: None,+ });+ }+ TableSchemaDetail {+ name: format!("tgt_{}", i),+ columns: vec![],+ indexes: vec![],+ foreign_keys: fks,+ triggers: vec![],+ ddl: None,+ }+ })+ .collect();++ let tables: Vec<TableInfo> = (0..100)+ .map(|i| TableInfo {+ name: format!("tgt_{}", i),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ })+ .collect();++ let start = Instant::now();+ let graph = DependencyGraph::build(&details, &tables);+ let elapsed = start.elapsed();++ assert_eq!(graph.nodes.len(), 100);+ eprintln!("[BENCHMARK] dependency_graph_build (100 tables): {:?}", elapsed);+}diff --git a/crates/dbx-core/tests/regression_compatibility.rs b/crates/dbx-core/tests/regression_compatibility.rsnew file mode 100644index 0000000000..78a7589e80--- /dev/null+++ b/crates/dbx-core/tests/regression_compatibility.rs@@ -0,0 +1,297 @@+use dbx_core::data_compare::{DataCompareFromTablesPreparation, DataComparePreparation, DataCompareResult};+use dbx_core::models::connection::DatabaseType;+use dbx_core::schema_diff::{+ generate_schema_sync_sql, prepare_schema_diff, SchemaDiffPreparation, SchemaDiffPreparationOptions, TableDiff,+ TableSchemaDetail,+};+use dbx_core::sql_risk::{classify_sql_risk, SqlRisk};+use dbx_core::types::{ColumnInfo, TableInfo};++// ============================================================================+// 12.1 — SchemaDiffPreparation backward-compatibility regression tests+// ============================================================================++fn basic_table_info(name: &str) -> TableInfo {+ TableInfo {+ name: name.to_string(),+ table_type: "BASE TABLE".to_string(),+ comment: None,+ parent_schema: None,+ parent_name: None,+ }+}++fn col(name: &str, data_type: &str) -> ColumnInfo {+ ColumnInfo {+ name: name.to_string(),+ data_type: data_type.to_string(),+ is_nullable: false,+ column_default: None,+ is_primary_key: false,+ extra: None,+ comment: None,+ numeric_precision: None,+ numeric_scale: None,+ character_maximum_length: None,+ enum_values: None,+ character_set: None,+ collation: None,+ }+}++fn detail(name: &str, columns: Vec<ColumnInfo>) -> TableSchemaDetail {+ TableSchemaDetail {+ name: name.to_string(),+ columns,+ indexes: vec![],+ foreign_keys: vec![],+ triggers: vec![],+ ddl: None,+ }+}++/// Verify that new optional fields in SchemaDiffPreparation are well-formed+/// when using basic (non-enhanced) options, ensuring backward compatibility+/// for existing callers that only use the original fields.+#[test]+fn schema_diff_preparation_new_fields_defaults_backward_compatible() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![basic_table_info("users")],+ target_tables: vec![basic_table_info("users")],+ source_details: vec![detail("users", vec![col("name", "varchar(64)")])],+ target_details: vec![detail("users", vec![col("name", "varchar(128)")])],+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);++ // Original required fields must be present+ assert!(!result.diffs.is_empty(), "diffs should be non-empty");+ assert!(!result.sync_sql.is_empty(), "sync_sql should be non-empty");++ // New optional fields from Phase 4+ must have sensible defaults+ assert!(result.rollback_sync_sql.is_none(), "rollback_sync_sql should default to None");+ assert!(result.rename_candidates.is_empty(), "rename_candidates should default to empty");+ assert!(result.rollback_graph.is_none(), "rollback_graph should default to None");+ assert!(result.compatibility_warnings.is_empty(), "compatibility_warnings should default to empty");+ assert!(result.permission_diffs.is_empty(), "permission_diffs should default to empty");+ assert!(result.permission_sync_sql.is_none(), "permission_sync_sql should default to None");++ // dependency_graph is always built by prepare_schema_diff regardless of options+ // (it's used internally for topological ordering)+ assert!(result.dependency_graph.is_some(), "dependency_graph should be present (always built for ordering)");+}++/// Verify that SchemaDiffPreparation serializes to JSON with backward-compatible+/// field names (camelCase) and optional fields skipped when None/empty.+#[test]+fn schema_diff_preparation_json_serialization_skips_optional_fields() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![basic_table_info("users")],+ target_tables: vec![basic_table_info("users")],+ source_details: vec![detail("users", vec![col("name", "varchar(64)")])],+ target_details: vec![detail("users", vec![col("name", "varchar(128)")])],+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ let json = serde_json::to_value(&result).expect("Serialization should succeed");++ // Original fields must be present+ assert!(json.get("diffs").is_some(), "diffs must be present");+ assert!(json.get("syncSql").is_some(), "syncSql must be present");++ // New optional fields should NOT appear when None/empty+ assert!(json.get("rollbackSyncSql").is_none(), "rollbackSyncSql should be absent");+ assert!(json.get("renameCandidates").is_none(), "renameCandidates should be absent");+ assert!(json.get("rollbackGraph").is_none(), "rollbackGraph should be absent");+ assert!(json.get("compatibilityWarnings").is_none(), "compatibilityWarnings should be absent");+ assert!(json.get("permissionDiffs").is_none(), "permissionDiffs should be absent");+ assert!(json.get("permissionSyncSql").is_none(), "permissionSyncSql should be absent");++ // dependency_graph is always populated by prepare_schema_diff+ assert!(json.get("dependencyGraph").is_some(), "dependencyGraph is always built by prepare_schema_diff");+}++/// Verify that an old-format JSON (without new fields) can be deserialized+/// into SchemaDiffPreparation with defaults.+#[test]+fn schema_diff_preparation_deserializes_old_format_with_defaults() {+ let old_json = serde_json::json!({+ "diffs": [],+ "syncSql": "SELECT 1"+ });++ let result: SchemaDiffPreparation = serde_json::from_value(old_json).expect("Old-format JSON should deserialize");++ assert!(result.diffs.is_empty());+ assert_eq!(result.sync_sql, "SELECT 1");+ assert!(result.rollback_sync_sql.is_none());+ assert!(result.rename_candidates.is_empty());+ assert!(result.dependency_graph.is_none());+}++/// Verify that generate_schema_sync_sql output is invariant under default options+/// — i.e., callers that don't pass rollback/rename/permission options still get+/// identical SQL output.+#[test]+fn generate_schema_sync_sql_output_invariant() {+ let diffs = vec![TableDiff {+ diff_type: "added".to_string(),+ object_type: None,+ name: "users".to_string(),+ columns: Some(vec![]),+ indexes: None,+ foreign_keys: None,+ triggers: None,+ ddl: Some("CREATE TABLE users (id INT)".to_string()),+ target_ddl: None,+ source_table_comment: None,+ target_table_comment: None,+ sync_sql: None,+ }];++ let sql = generate_schema_sync_sql(&diffs, &[], &[], &[], &[], DatabaseType::Postgres, None, false, None, &[]);+ assert!(sql.contains("CREATE TABLE"), "SQL should contain CREATE TABLE");+ assert!(sql.contains("users"), "SQL should contain table name");+}++/// Verify that with all enhancement flags off, the output of+/// prepare_schema_diff matches the same as if they didn't exist.+#[test]+fn prepare_schema_diff_with_default_options_matches_basic_diff() {+ let options = SchemaDiffPreparationOptions {+ source_tables: vec![basic_table_info("orders")],+ target_tables: vec![basic_table_info("orders")],+ source_details: vec![detail("orders", vec![col("id", "int"), col("status", "varchar(16)")])],+ target_details: vec![detail("orders", vec![col("id", "int"), col("status", "varchar(32)")])],+ database_type: DatabaseType::Postgres,+ ..Default::default()+ };++ let result = prepare_schema_diff(options);+ assert!(!result.diffs.is_empty());+ assert_eq!(result.diffs.len(), 1);+ assert_eq!(result.diffs[0].diff_type, "modified");+ assert!(!result.sync_sql.is_empty());+}++// ============================================================================+// 12.1 — SqlRisk backward-compatibility regression tests+// ============================================================================++/// Verify that SqlRisk::ReadOnly classification is unchanged+#[test]+fn sql_risk_readonly_classification_invariant() {+ assert_eq!(classify_sql_risk("SELECT * FROM users", "postgres").unwrap(), SqlRisk::ReadOnly);+ assert_eq!(classify_sql_risk("SELECT id, name FROM users WHERE id = 1", "mysql").unwrap(), SqlRisk::ReadOnly);+ assert_eq!(classify_sql_risk("SHOW TABLES", "mysql").unwrap(), SqlRisk::ReadOnly);+ assert_eq!(classify_sql_risk("DESCRIBE users", "mysql").unwrap(), SqlRisk::ReadOnly);+ assert_eq!(classify_sql_risk("EXPLAIN SELECT * FROM users", "postgres").unwrap(), SqlRisk::ReadOnly);+ assert_eq!(classify_sql_risk("WITH cte AS (SELECT 1) SELECT * FROM cte", "postgres").unwrap(), SqlRisk::ReadOnly);+}++/// Verify that SqlRisk::Write classification is unchanged+#[test]+fn sql_risk_write_classification_invariant() {+ assert_eq!(classify_sql_risk("INSERT INTO users VALUES (1)", "postgres").unwrap(), SqlRisk::Write);+ assert_eq!(classify_sql_risk("UPDATE users SET name = 'x'", "postgres").unwrap(), SqlRisk::Write);+ assert_eq!(classify_sql_risk("DELETE FROM users WHERE id = 1", "postgres").unwrap(), SqlRisk::Write);+}++/// Verify that SqlRisk::Ddl classification is unchanged+#[test]+fn sql_risk_ddl_classification_invariant() {+ assert_eq!(classify_sql_risk("CREATE TABLE users (id INT)", "postgres").unwrap(), SqlRisk::Ddl);+ assert_eq!(classify_sql_risk("DROP TABLE users", "postgres").unwrap(), SqlRisk::Ddl);+ assert_eq!(classify_sql_risk("ALTER TABLE users ADD COLUMN age INT", "postgres").unwrap(), SqlRisk::Ddl);+ assert_eq!(classify_sql_risk("TRUNCATE TABLE users", "postgres").unwrap(), SqlRisk::Ddl);+}++/// Verify that multi-statement returns highest risk (unchanged)+#[test]+fn sql_risk_multi_statement_invariant() {+ assert_eq!(classify_sql_risk("SELECT 1; INSERT INTO users VALUES (1)", "postgres").unwrap(), SqlRisk::Write);+ assert_eq!(classify_sql_risk("SELECT 1; CREATE TABLE t (id INT)", "postgres").unwrap(), SqlRisk::Ddl);+}++// ============================================================================+// 12.1 — DataCompare result format compatibility tests+// ============================================================================++/// Verify that DataCompareFromTablesPreparation serializes with backward-compatible+/// field names and new optional fields are skipped when None.+#[test]+fn data_compare_from_tables_preparation_optional_fields_default() {+ let prep = DataCompareFromTablesPreparation {+ result: DataCompareResult { added: vec![], removed: vec![], modified: vec![] },+ sync_statements: vec![],+ sync_sql: String::new(),+ pre_sync_statements: vec![],+ source_row_count: 0,+ target_row_count: 0,+ source_truncated: false,+ target_truncated: false,+ degradation_level: None,+ sampling_rate: None,+ confidence_score: None,+ verification_method: None,+ source_checksums: None,+ target_checksums: None,+ };++ let json = serde_json::to_value(&prep).expect("Serialization should succeed");++ // Core fields must be present+ assert!(json.get("result").is_some(), "result must be present");+ assert!(json.get("syncSql").is_some(), "syncSql must be present");++ // New optional fields should be absent when None+ assert!(json.get("degradationLevel").is_none(), "degradationLevel should be absent");+ assert!(json.get("samplingRate").is_none(), "samplingRate should be absent");+ assert!(json.get("confidenceScore").is_none(), "confidenceScore should be absent");+ assert!(json.get("verificationMethod").is_none(), "verificationMethod should be absent");+ assert!(json.get("sourceChecksums").is_none(), "sourceChecksums should be absent");+ assert!(json.get("targetChecksums").is_none(), "targetChecksums should be absent");+}++/// Verify that an old-format JSON can be deserialized into DataCompareFromTablesPreparation+#[test]+fn data_compare_from_tables_preparation_deserializes_old_format() {+ let old_json = serde_json::json!({+ "result": { "added": [], "removed": [], "modified": [] },+ "syncStatements": [],+ "syncSql": "",+ "preSyncStatements": [],+ "sourceRowCount": 100,+ "targetRowCount": 100,+ "sourceTruncated": false,+ "targetTruncated": false+ });++ let prep: DataCompareFromTablesPreparation =+ serde_json::from_value(old_json).expect("Old-format JSON should deserialize");++ assert_eq!(prep.source_row_count, 100);+ assert_eq!(prep.target_row_count, 100);+ assert!(prep.degradation_level.is_none());+ assert!(prep.sampling_rate.is_none());+ assert!(prep.confidence_score.is_none());+}++/// Verify that DataComparePreparation (the original struct) remains unchanged+#[test]+fn data_compare_preparation_format_stable() {+ let prep = DataComparePreparation {+ result: DataCompareResult { added: vec![], removed: vec![], modified: vec![] },+ sync_statements: vec!["INSERT INTO t VALUES (1)".to_string()],+ sync_sql: "INSERT INTO t VALUES (1)".to_string(),+ };++ let json = serde_json::to_value(&prep).expect("Serialization should succeed");+ assert_eq!(json["syncStatements"][0], "INSERT INTO t VALUES (1)");+ assert_eq!(json["syncSql"], "INSERT INTO t VALUES (1)");+ assert!(json.get("result").is_some());+}diff --git a/crates/dbx-web/src/error.rs b/crates/dbx-web/src/error.rsindex 01d5ea070d..501dc38f59 100644--- a/crates/dbx-web/src/error.rs+++ b/crates/dbx-web/src/error.rs@@ -1,11 +1,19 @@use axum::http::StatusCode;use axum::response::{IntoResponse, Response};+use std::fmt;+#[derive(Debug)]pub struct AppError {pub message: String,pub status: StatusCode,}+impl fmt::Display for AppError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.message)+ }+}+impl AppError {pub fn internal(msg: impl Into<String>) -> Self {AppError { message: msg.into(), status: StatusCode::INTERNAL_SERVER_ERROR }diff --git a/crates/dbx-web/src/main.rs b/crates/dbx-web/src/main.rsindex c1184f63c9..0e4e2db6a4 100644--- a/crates/dbx-web/src/main.rs+++ b/crates/dbx-web/src/main.rs@@ -17,6 +17,8 @@ use axum::middleware;use axum::routing::{delete, get, post};use axum::Router;use dbx_core::connection::AppState;+use dbx_core::sql_dialect::dialect_loader::{register_core_dialects, DialectPluginLoader, DialectRegistry};+use dbx_core::sql_dialect::hot_reload::DialectHotReload;use dbx_core::storage::Storage;use state::WebState;use tokio::sync::RwLock;@@ -202,6 +204,28 @@ async fn main() {let db_path = data_dir.join("dbx.db");let storage = Storage::open(&db_path).await.expect("Failed to open storage");storage.migrate_from_json(&data_dir).await.expect("Failed to migrate JSON data");++ // Initialize core dialect registry and load external plugin dialects+ register_core_dialects();+ let registry = DialectRegistry::global();+ let plugin_dirs = vec![data_dir.join("plugins").join("dialects")];+ let load_result = DialectPluginLoader::scan_and_load(registry, &plugin_dirs);+ log::info!(+ "Dialect plugins loaded: {} success, {} errors, {} skipped",+ load_result.loaded.len(),+ load_result.errors.len(),+ load_result.skipped.len()+ );++ // Start dialect YAML hot-reload watcher+ let watch_dirs = plugin_dirs.clone();+ tokio::spawn(async move {+ if let Err(e) = DialectHotReload::run_forever(watch_dirs, DialectRegistry::global()).await {+ log::error!("Dialect hot-reload watcher exited: {e}");+ }+ });+ log::info!("Dialect hot-reload watcher started");+Arc::new(AppState::new_with_plugin_and_agent_dir_and_app_version(storage,data_dir.join("plugins"),@@ -348,6 +372,7 @@ async fn main() {.route("/schema/extensions", get(routes::schema::list_extensions)).route("/schema/available-extensions", get(routes::schema::list_available_extensions)).route("/schema/ddl", get(routes::schema::get_ddl))+ .route("/dialect/data-types", get(routes::dialect::list_data_types)).route("/schema-diff/prepare", post(routes::schema_diff::prepare_schema_diff)).route("/schema-diff/generate-sync-sql", post(routes::schema_diff::generate_schema_sync_sql)).route(@@ -370,6 +395,7 @@ async fn main() {.route("/query/execute-batch", post(routes::query::execute_batch)).route("/query/execute-script", post(routes::query::execute_script)).route("/query/execute-in-transaction", post(routes::query::execute_in_transaction))+ .route("/query/execute-script-2pc", post(routes::query::execute_script_with_2pc)).route("/query/analyze-sql-references", post(routes::query::analyze_sql_references)).route("/query/find-statement-at-cursor", post(routes::query::find_statement_at_cursor)).route("/query/prepare-pagination-plan", post(routes::query::prepare_query_pagination_execution_plan))diff --git a/crates/dbx-web/src/routes/connection.rs b/crates/dbx-web/src/routes/connection.rsindex 1f34d8c205..ca83b219ed 100644--- a/crates/dbx-web/src/routes/connection.rs+++ b/crates/dbx-web/src/routes/connection.rs@@ -396,7 +396,7 @@ mod tests {test_connection_with_info, ConnectRequest, DisconnectRequest, McpAddConnectionRequest,McpRemoveConnectionRequest, SaveConnectionDatabaseInfoRequest, SaveConnectionsRequest,};- use crate::state::{LoginRateLimit, WebState};+ use crate::state::WebState;use axum::extract::State;use axum::Json;use dbx_core::connection::{AppState, PoolKind};@@ -405,13 +405,11 @@ mod tests {TransportLayerConfig,};use dbx_core::storage::{McpGlobalPolicy, Storage};- use std::collections::{HashMap, HashSet};use std::sync::Arc;#[cfg(feature = "mq-admin")]use tokio::io::{AsyncReadExt, AsyncWriteExt};#[cfg(feature = "mq-admin")]use tokio::net::TcpListener;- use tokio::sync::{Mutex, RwLock};fn sqlite_config(id: &str, path: &str) -> ConnectionConfig {ConnectionConfig {@@ -487,22 +485,7 @@ mod tests {std::fs::create_dir_all(&dir).unwrap();let storage = Storage::open(&dir.join("storage.db")).await.unwrap();let app = Arc::new(AppState::new_with_plugin_dir(storage, dir.join("plugins")));- let state = Arc::new(WebState {- app,- data_dir: dir.clone(),- public_base_path: "/".to_string(),- password_disabled: false,- password_hash: RwLock::new(None),- sessions: RwLock::new(HashSet::new()),- sse_channels: RwLock::new(HashMap::new()),- transfer_progress_channels: RwLock::new(HashMap::new()),- table_import_channels: RwLock::new(HashMap::new()),- sql_file_executions: RwLock::new(HashMap::new()),- nacos_imports: RwLock::new(HashMap::new()),- login_rate_limit: Mutex::new(LoginRateLimit { fail_count: 0, locked_until: None }),- export_files: RwLock::new(HashMap::new()),- ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),- });+ let state = Arc::new(WebState::for_tests(app, dir.clone()));(state, dir)}diff --git a/crates/dbx-web/src/routes/dialect.rs b/crates/dbx-web/src/routes/dialect.rsnew file mode 100644index 0000000000..2b999aa509--- /dev/null+++ b/crates/dbx-web/src/routes/dialect.rs@@ -0,0 +1,25 @@+use axum::extract::Query;+use axum::Json;+use serde::Deserialize;++#[derive(Deserialize)]+pub struct DialectDataTypesQuery {+ dialect_name: String,+}++pub async fn list_data_types(Query(query): Query<DialectDataTypesQuery>) -> Json<Vec<String>> {+ Json(dbx_core::sql_dialect::dialect_types::list_dialect_type_names(&query.dialect_name))+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn list_data_types_matches_tauri_command_behavior() {+ dbx_core::sql_dialect::dialect_loader::register_core_dialects();+ let Json(types) =+ list_data_types(Query(DialectDataTypesQuery { dialect_name: "PostgreSQL".to_string() })).await;+ assert!(!types.is_empty(), "Expected non-empty types, got {types:?}");+ }+}diff --git a/crates/dbx-web/src/routes/mod.rs b/crates/dbx-web/src/routes/mod.rsindex e7b32fdc54..132f822a2a 100644--- a/crates/dbx-web/src/routes/mod.rs+++ b/crates/dbx-web/src/routes/mod.rs@@ -5,6 +5,7 @@ pub mod cloud_sync;pub mod connection;pub mod data_compare;pub mod database_export;+pub mod dialect;pub mod document_store;pub mod etcd;pub mod hbase;diff --git a/crates/dbx-web/src/routes/mongo.rs b/crates/dbx-web/src/routes/mongo.rsindex b885637505..0b48367f81 100644--- a/crates/dbx-web/src/routes/mongo.rs+++ b/crates/dbx-web/src/routes/mongo.rs@@ -797,14 +797,12 @@ async fn ensure_find_one_write_policy(#[cfg(test)]mod tests {use super::ensure_find_one_write_policy;- use crate::state::{LoginRateLimit, WebState};+ use crate::state::WebState;use axum::http::{HeaderMap, HeaderValue};use dbx_core::connection::AppState;use dbx_core::models::connection::ConnectionConfig;use dbx_core::storage::{McpGlobalPolicy, Storage};- use std::collections::{HashMap, HashSet};use std::sync::Arc;- use tokio::sync::{Mutex, RwLock};fn mongo_config(is_production: bool) -> ConnectionConfig {serde_json::from_value(serde_json::json!({@@ -826,22 +824,7 @@ mod tests {std::fs::create_dir_all(&dir).unwrap();let storage = Storage::open(&dir.join("storage.db")).await.unwrap();let app = Arc::new(AppState::new_with_plugin_dir(storage, dir.join("plugins")));- let state = Arc::new(WebState {- app,- data_dir: dir.clone(),- public_base_path: "/".to_string(),- password_disabled: false,- password_hash: RwLock::new(None),- sessions: RwLock::new(HashSet::new()),- sse_channels: RwLock::new(HashMap::new()),- transfer_progress_channels: RwLock::new(HashMap::new()),- table_import_channels: RwLock::new(HashMap::new()),- sql_file_executions: RwLock::new(HashMap::new()),- nacos_imports: RwLock::new(HashMap::new()),- login_rate_limit: Mutex::new(LoginRateLimit { fail_count: 0, locked_until: None }),- export_files: RwLock::new(HashMap::new()),- ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),- });+ let state = Arc::new(WebState::for_tests(app, dir.clone()));(state, dir)}diff --git a/crates/dbx-web/src/routes/query.rs b/crates/dbx-web/src/routes/query.rsindex 0fa70438aa..f8fccc788b 100644--- a/crates/dbx-web/src/routes/query.rs+++ b/crates/dbx-web/src/routes/query.rs@@ -514,6 +514,23 @@ pub async fn execute_in_transaction(Ok(Json(result))}+pub async fn execute_script_with_2pc(+ State(state): State<Arc<WebState>>,+ Json(req): Json<ExecuteBatchRequest>,+) -> Result<Json<dbx_core::query::SchemaDiffDeployResult>, AppError> {+ tracing::debug!(connection_id = %req.connection_id, "execute_script_with_2pc");+ // Single-connection real transaction (not per-statement auto-commit 2PC).+ let result = dbx_core::query::execute_schema_diff_deploy(+ &state.app,+ &req.connection_id,+ &req.database,+ &req.statements,+ req.schema.as_deref(),+ )+ .await;+ Ok(Json(result))+}+pub async fn analyze_sql_references(Json(req): Json<AnalyzeSqlReferencesRequest>,) -> Result<Json<dbx_core::sql_analysis::SqlReferenceAnalysis>, AppError> {@@ -883,3 +900,86 @@ pub async fn build_database_sql_export(}dbx_core::database_export::build_database_sql_export(options).map(Json).map_err(AppError::from)}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::state::WebState;+ use axum::extract::State as AxumState;+ use dbx_core::connection::AppState;+ use dbx_core::storage::Storage;++ async fn test_web_state() -> (Arc<WebState>, std::path::PathBuf) {+ let dir = std::env::temp_dir().join(format!("dbx-web-query-test-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();+ let app = Arc::new(AppState::new_with_plugin_dir(storage, dir.join("plugins")));+ let state = Arc::new(WebState::for_tests(app, dir.clone()));+ (state, dir)+ }++ #[tokio::test]+ async fn execute_script_with_2pc_returns_structured_result() {+ let (state, _dir) = test_web_state().await;+ let req = ExecuteBatchRequest {+ connection_id: "conn-1".to_string(),+ database: "testdb".to_string(),+ statements: vec!["SELECT 1".to_string()],+ schema: None,+ timeout_secs: None,+ };++ let result = execute_script_with_2pc(AxumState(state), Json(req))+ .await+ .expect("execute_script_with_2pc should return Ok(Json(...))");+ let log = result.0;+ assert!(!log.transaction_id.is_empty());+ assert!(!log.participants.is_empty());+ assert_eq!(log.status, "rolled_back");+ assert!(log.error.as_ref().is_some_and(|e| !e.is_empty()));+ assert_eq!(log.statement_count, 1);+ assert_eq!(log.executed_count, 0);+ }++ #[tokio::test]+ async fn execute_script_with_2pc_empty_statements_succeeds() {+ let (state, _dir) = test_web_state().await;+ let req = ExecuteBatchRequest {+ connection_id: "conn-empty".to_string(),+ database: "testdb".to_string(),+ statements: vec![],+ schema: None,+ timeout_secs: None,+ };++ let result = execute_script_with_2pc(AxumState(state), Json(req)).await.expect("empty deploy should succeed");+ let log = result.0;+ assert_eq!(log.status, "committed");+ assert_eq!(log.statement_count, 0);+ assert_eq!(log.executed_count, 0);+ assert!(log.error.is_none());+ assert_eq!(log.participants.len(), 1);+ }++ #[tokio::test]+ async fn execute_script_with_2pc_propagates_structured_failure_fields() {+ let (state, _dir) = test_web_state().await;+ let req = ExecuteBatchRequest {+ connection_id: "missing-conn".to_string(),+ database: "testdb".to_string(),+ statements: vec!["CREATE TABLE t1 (id INT)".to_string(), "CREATE TABLE t2 (id INT)".to_string()],+ schema: None,+ timeout_secs: None,+ };++ let result = execute_script_with_2pc(AxumState(state), Json(req))+ .await+ .expect("deploy endpoint should return structured JSON even on failure");+ let log = result.0;+ assert!(log.status == "rolled_back" || log.status == "mixed", "status={}", log.status);+ assert_eq!(log.statement_count, 2);+ assert!(log.error.as_ref().is_some_and(|e| !e.is_empty()));+ // Missing connection cannot have applied statements.+ assert_eq!(log.executed_count, 0);+ }+}diff --git a/crates/dbx-web/src/routes/schema_diff.rs b/crates/dbx-web/src/routes/schema_diff.rsindex 97413e6dea..e3fea2abb1 100644--- a/crates/dbx-web/src/routes/schema_diff.rs+++ b/crates/dbx-web/src/routes/schema_diff.rs@@ -12,6 +12,8 @@ pub struct GenerateSchemaSyncSqlRequest {pub database_type: dbx_core::models::connection::DatabaseType,pub target_schema: Option<String>,pub cascade_delete: Option<bool>,+ pub source_dialect: Option<String>,+ pub field_mappings: Option<Vec<dbx_core::schema_diff::FieldMapping>>,}pub async fn prepare_schema_diff(@@ -30,5 +32,7 @@ pub async fn generate_schema_sync_sql(Json(req): Json<GenerateSchemaSyncSqlRequereq.database_type,req.target_schema.as_deref(),req.cascade_delete.unwrap_or(false),+ req.source_dialect.as_deref().and_then(dbx_core::sql_dialect::descriptor::DialectKind::from_label),+ req.field_mappings.as_deref().unwrap_or(&[]),))}diff --git a/crates/dbx-web/src/state.rs b/crates/dbx-web/src/state.rsindex c5784b5c83..deb5d93d3b 100644--- a/crates/dbx-web/src/state.rs+++ b/crates/dbx-web/src/state.rs@@ -42,4 +42,25 @@ impl WebState {pub async fn remove_sse_channel(&self, id: &str) {self.sse_channels.write().await.remove(id);}++ /// Test helper: full field set so new WebState fields don't break scattered test fixtures.+ #[cfg(test)]+ pub fn for_tests(app: Arc<AppState>, data_dir: PathBuf) -> Self {+ Self {+ app,+ data_dir,+ public_base_path: "/".to_string(),+ password_disabled: false,+ password_hash: RwLock::new(None),+ sessions: RwLock::new(HashSet::new()),+ sse_channels: RwLock::new(HashMap::new()),+ transfer_progress_channels: RwLock::new(HashMap::new()),+ table_import_channels: RwLock::new(HashMap::new()),+ sql_file_executions: RwLock::new(HashMap::new()),+ nacos_imports: RwLock::new(HashMap::new()),+ login_rate_limit: Mutex::new(LoginRateLimit { fail_count: 0, locked_until: None }),+ export_files: RwLock::new(HashMap::new()),+ ssh_prompts: Arc::new(crate::ssh_prompt::SshPromptHub::new()),+ }+ }}diff --git a/docs/superpowers/plans/2026-07-16-field-mapping-dialog.md b/docs/superpowers/plans/2026-07-16-field-mapping-dialog.mdnew file mode 100644index 0000000000..42b67c64f5--- /dev/null+++ b/docs/superpowers/plans/2026-07-16-field-mapping-dialog.md@@ -0,0 +1,411 @@+# 字段类型映射独立弹窗 + JSON 导入/导出 实现计划++> **面向 AI 代理的工作者:** 必需子技能:使用 superpowers:subagent-driven-development(推荐)或 superpowers:executing-plans 逐任务实现此计划。步骤使用复选框(`- [ ]`)语法来跟踪进度。++**目标:** 在"比较架构"配置步骤的"选项"按钮后增加"字段类型映射"按钮,点击打开独立弹窗编辑映射(内部可滚动、底部操作栏始终可达),并支持映射配置的 JSON 导入/导出。++**架构:** 新建 `FieldMappingDialog.vue` 复用 `SchemaDiffDialog` 已有的 overlay 弹窗模式;通过 `SchemaDiffConfigStep` 透传 `open-field-mapping` 事件到 `SchemaDiffDialog`;弹窗内持有本地副本(`editingMappings`),"完成"时 emit `save` 复用现有 `handleFieldMappingsUpdate` 写回 `activeConfig.options.fieldMappings`。导入/导出采用现有 `TagManagementPanel` 的 Blob 下载 + 隐藏 file input 模式。++**技术栈:** Vue 3 `<script setup>` + TypeScript + Tailwind(shadcn-vue 风格)、`@lucide/vue` 图标、`vue-i18n`(`t()`)、`useToast` composable。无 Rust 变更。++---++## 文件结构++- 新建 `apps/desktop/src/components/diff/FieldMappingDialog.vue`+ - 职责:独立弹窗容器,渲染 `FieldMappingPanel` + 底部导入/导出/完成栏;持有 `editingMappings` 本地副本;实现 `handleExport` / `handleImport` / `onFileSelected`;深拷贝初始化。+- 修改 `apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`+ - 职责:在"选项"按钮后插入"字段类型映射"按钮,新增 `open-field-mapping` emit;保留内嵌 `FieldMappingPanel`。+- 修改 `apps/desktop/src/components/diff/SchemaDiffDialog.vue`+ - 职责:新增 `showFieldMappingDialog` ref,挂载 `<FieldMappingDialog>` 并接线 `open` / `save` / `update:open`,传入 `sourceDbType` / `targetDbType`。+- 修改 `apps/desktop/src/i18n/locales/zh-CN.ts`+ - 职责:在 `schemaDiff.fieldMapping` 对象内新增 `openFieldMapping` / `import` / `export` / `importError` / `done` 键。+- 修改 `apps/desktop/src/i18n/locales/en.ts`+ - 职责:同上英文键。++---++## 任务 1:新建 FieldMappingDialog.vue 容器与导入/导出++**文件:**+- 创建:`apps/desktop/src/components/diff/FieldMappingDialog.vue`++- [ ] **步骤 1:编写组件(script + template + style)**++完整内容如下(注意:`FieldMappingEntry` 来自 `@/types/schemaDiff`;`FieldMappingPanel` 已存在并可复用;`useToast` 提供 `toast(msg, duration?)`):++```vue+<script setup lang="ts">+import { ref, watch } from "vue";+import { useI18n } from "vue-i18n";+import { Button } from "@/components/ui/button";+import { Download, Upload, Check, X } from "@lucide/vue";+import FieldMappingPanel from "@/components/diff/FieldMappingPanel.vue";+import type { FieldMappingEntry } from "@/types/schemaDiff";+import { useToast } from "@/composables/useToast";++const props = defineProps<{+ open: boolean;+ mappings: FieldMappingEntry[];+ sourceDbType: string;+ targetDbType: string;+}>();++const emit = defineEmits<{+ (e: "update:open", value: boolean): void;+ (e: "save", value: FieldMappingEntry[]): void;+}>();++const { t } = useI18n();+const toast = useToast();++const editingMappings = ref<FieldMappingEntry[]>([]);+const fileInputRef = ref<HTMLInputElement | null>(null);++// 打开时深拷贝当前映射为本地副本(单向数据流,取消不写回)+watch(+ () => props.open,+ (isOpen) => {+ if (isOpen) {+ editingMappings.value = props.mappings.map((m) => ({ ...m }));+ }+ },+ { immediate: true },+);++function handleUpdateMappings(v: FieldMappingEntry[]) {+ editingMappings.value = v;+}++function handleExport() {+ const blob = new Blob([JSON.stringify(editingMappings.value, null, 2)], {+ type: "application/json",+ });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = "field-mappings.json";+ a.click();+ URL.revokeObjectURL(url);+}++function handleImportClick() {+ fileInputRef.value?.click();+}++function onFileSelected(event: Event) {+ const input = event.target as HTMLInputElement;+ const file = input.files?.[0];+ if (!file) return;+ const reader = new FileReader();+ reader.onload = () => {+ try {+ const parsed = JSON.parse(String(reader.result)) as unknown;+ if (!Array.isArray(parsed)) throw new Error("not an array");+ const normalized: FieldMappingEntry[] = parsed.map((item: any) => ({+ sourceType: String(item.sourceType ?? ""),+ targetType: String(item.targetType ?? ""),+ paramStrategy: item.paramStrategy === "strip" || item.paramStrategy === "custom" ? item.paramStrategy : "preserve",+ customParams: item.customParams ? String(item.customParams) : undefined,+ }));+ if (normalized.some((m) => !m.sourceType || !m.targetType)) {+ throw new Error("missing sourceType/targetType");+ }+ editingMappings.value = normalized;+ toast(t("diff.fieldMapping.importSuccess"), 2000);+ } catch {+ toast(t("diff.fieldMapping.importError"), 3000);+ } finally {+ input.value = "";+ }+ };+ reader.onerror = () => toast(t("diff.fieldMapping.importError"), 3000);+ reader.readAsText(file);+}++function handleDone() {+ emit("save", editingMappings.value.map((m) => ({ ...m })));+ emit("update:open", false);+}++function handleClose() {+ emit("update:open", false);+}+</script>++<template>+ <div v-if="open" class="absolute inset-0 bg-background/80 backdrop-blur-sm z-50 flex items-center justify-center" @click.self="handleClose">+ <div class="bg-card border rounded-lg shadow-lg w-[760px] max-w-[calc(100vw-2rem)] max-h-[80vh] overflow-auto p-4">+ <div class="flex items-center justify-between mb-4">+ <h3 class="text-sm font-medium">{{ t("diff.fieldMapping.title") }}</h3>+ <Button variant="ghost" size="sm" @click="handleClose">+ <X class="w-3.5 h-3.5" />+ </Button>+ </div>++ <FieldMappingPanel+ :mappings="editingMappings"+ :source-db-type="sourceDbType"+ :target-db-type="targetDbType"+ @update:mappings="handleUpdateMappings"+ />++ <div class="flex items-center justify-between mt-4 pt-3 border-t">+ <div class="flex items-center gap-2">+ <Button variant="outline" size="sm" @click="handleImportClick">+ <Upload class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.import") }}+ </Button>+ <Button variant="outline" size="sm" @click="handleExport">+ <Download class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.export") }}+ </Button>+ </div>+ <Button size="sm" @click="handleDone">+ <Check class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.fieldMapping.done") }}+ </Button>+ </div>++ <input ref="fileInputRef" type="file" accept=".json,application/json" class="hidden" @change="onFileSelected" />+ </div>+ </div>+</template>+```++- [ ] **步骤 2:类型检查确认组件无错误**++运行:`cd apps/desktop && pnpm vue-tsc --noEmit --project tsconfig.json`(或仓库根 `pnpm typecheck`)+预期:该文件无 `FieldMappingDialog` 相关报错(已知 2 个与本次无关的预存错误:`dbAdminSql.ts` / `McpServerStatus.node_path`)。++- [ ] **步骤 3:Commit**++```bash+git add apps/desktop/src/components/diff/FieldMappingDialog.vue+git commit -m "feat(desktop): add FieldMappingDialog with JSON import/export"+```++---++## 任务 2:SchemaDiffConfigStep 增加"字段类型映射"按钮++**文件:**+- 修改:`apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`++- [ ] **步骤 1:在 defineEmits 中新增 open-field-mapping 事件**++定位 `const emit = defineEmits<{ ... }>();` 块,在现有事件(如 `(e: "update:fieldMappings", value: FieldMappingEntry[]): void;`)之后新增一行:++```ts+ (e: "open-field-mapping"): void;+```++- [ ] **步骤 2:在"选项"按钮后插入"字段类型映射"按钮**++定位底部操作栏(约 468-488 行):++```html+ <!-- Bottom Actions -->+ <div class="flex items-center justify-between pt-2">+ <div class="flex items-center gap-2">+ <Button variant="outline" size="sm" @click="$emit('saveConfig')">+ <Save class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.saveConfig") }}+ </Button>+ <Button variant="outline" size="sm" @click="$emit('loadConfig')">+ <FolderOpen class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.loadConfig") }}+ </Button>+ <Button variant="outline" size="sm" @click="$emit('showOptions')">+ <Settings class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.options") }}+ </Button>+ </div>+```++在 `{{ t("diff.options") }}` 按钮的 `</Button>` 之后、`</div>` 之前,插入:++```html+ <Button v-if="showFieldMapping" variant="outline" size="sm" @click="$emit('open-field-mapping')">+ <ArrowLeftRight class="w-3.5 h-3.5 mr-1" />+ {{ t("diff.openFieldMapping") }}+ </Button>+```++(注:`showFieldMapping` 已在 `<script>` 中定义为 `computed`,见 `SchemaDiffConfigStep.vue:66`。`ArrowLeftRight` 图标已在文件顶部 import。)++- [ ] **步骤 3:类型检查**++运行:`pnpm typecheck`+预期:无新增该文件报错。++- [ ] **步骤 4:Commit**++```bash+git add apps/desktop/src/components/diff/SchemaDiffConfigStep.vue+git commit -m "feat(desktop): add open-field-mapping button in config step"+```++---++## 任务 3:SchemaDiffDialog 挂载 FieldMappingDialog 并接线++**文件:**+- 修改:`apps/desktop/src/components/diff/SchemaDiffDialog.vue`++- [ ] **步骤 1:导入组件与图标**++在文件顶部 import 区(`SchemaDiffConfigStep` import 附近,约 11 行)新增:++```ts+import FieldMappingDialog from "@/components/diff/FieldMappingDialog.vue";+```++确认 `Download` / `Upload` / `Check` / `X` 不需要在此文件导入(`FieldMappingDialog` 内部已自带)。++- [ ] **步骤 2:新增 ref 并接线到 SchemaDiffConfigStep**++在 `showOptionsPanel` ref 定义附近(约 70 行 `const showOptionsPanel = ref(false);`)新增:++```ts+const showFieldMappingDialog = ref(false);+```++定位 `<SchemaDiffConfigStep ... >`(约 810-831 行),在其 `@update:field-mappings="handleFieldMappingsUpdate"` 之后新增一行:++```html+ @open-field-mapping="showFieldMappingDialog = true"+```++- [ ] **步骤 3:渲染 FieldMappingDialog(放在 showOptionsPanel overlay 之后,约 1055 行 `</DialogContent>` 之前)**++```html+ <!-- Field Mapping Dialog Overlay -->+ <FieldMappingDialog+ :open="showFieldMappingDialog"+ :mappings="activeConfig?.options.fieldMappings ?? []"+ :source-db-type="sourceDbType"+ :target-db-type="targetDbType"+ @update:open="showFieldMappingDialog = $event"+ @save="handleFieldMappingsUpdate"+ />+```++(注:`sourceDbType` / `targetDbType` 已在 `SchemaDiffDialog` 的 `<script>` 中计算,`handleFieldMappingsUpdate(mappings: FieldMappingEntry[])` 签名见 298 行,直接复用。)++- [ ] **步骤 4:类型检查**++运行:`pnpm typecheck`+预期:无新增报错。++- [ ] **步骤 5:Commit**++```bash+git add apps/desktop/src/components/diff/SchemaDiffDialog.vue+git commit -m "feat(desktop): wire FieldMappingDialog into SchemaDiffDialog"+```++---++## 任务 4:i18n 新增键(zh-CN + en)++**文件:**+- 修改:`apps/desktop/src/i18n/locales/zh-CN.ts`+- 修改:`apps/desktop/src/i18n/locales/en.ts`++- [ ] **步骤 1:zh-CN 新增键**++定位 `schemaDiff.fieldMapping` 对象(约 2444 行 `fieldMapping: {`)。在 `selectPreset: "选择预设...",` 行之后新增:++```ts+ openFieldMapping: "字段类型映射",+ import: "导入",+ export: "导出",+ importSuccess: "导入成功",+ importError: "导入失败:文件不是合法的字段类型映射 JSON",+ done: "完成",+```++- [ ] **步骤 2:en 新增键**++定位 `schemaDiff.fieldMapping` 对象(约 2457 行 `fieldMapping: {`)。在 `selectPreset: "Select preset...",` 行之后新增:++```ts+ openFieldMapping: "Field Type Mapping",+ import: "Import",+ export: "Export",+ importSuccess: "Imported successfully",+ importError: "Import failed: file is not a valid field type mapping JSON",+ done: "Done",+```++- [ ] **步骤 3:类型检查(i18n 为运行时键,typecheck 不校验缺失键,但确认 JSON 结构无语法错误)**++运行:`pnpm typecheck`+预期:无新增报错。++- [ ] **步骤 4:Commit**++```bash+git add apps/desktop/src/i18n/locales/zh-CN.ts apps/desktop/src/i18n/locales/en.ts+git commit -m "feat(desktop): add i18n keys for field mapping dialog"+```++---++## 任务 5:FieldMappingPanel 内嵌滚动兜底++**文件:**+- 修改:`apps/desktop/src/components/diff/FieldMappingPanel.vue`++- [ ] **步骤 1:给映射列表容器加最大高度与滚动**++定位 `<div v-else class="p-3">`(约 100 行,内含映射列表的 `v-else` 分支)。将其改为带 `max-h` + `overflow-auto`,使内嵌面板(非弹窗场景)也能滚动:++```html+ <div v-else class="p-3 max-h-[42vh] overflow-auto">+```++(弹窗场景下外层已有 `max-h-[80vh] overflow-auto`,内层再加一层可滚避免双重长列表;内嵌场景下这层是关键兜底。)++- [ ] **步骤 2:类型检查**++运行:`pnpm typecheck`+预期:无新增报错。++- [ ] **步骤 3:Commit**++```bash+git add apps/desktop/src/components/diff/FieldMappingPanel.vue+git commit -m "feat(desktop): make FieldMappingPanel list scrollable as fallback"+```++---++## 自检(计划作者视角)++**规格覆盖度:**+- 独立弹窗(任务 1 + 3)✓+- "选项"后按钮(任务 2)✓+- 单向数据流 / 取消不写回(任务 1 watch + handleClose)✓+- JSON 导出(任务 1 handleExport,参考 TagManagementPanel)✓+- JSON 导入 + 校验(任务 1 onFileSelected)✓+- 弹窗内滚动 + 内嵌兜底(任务 1 max-h-[80vh] + 任务 5)✓+- 配置步骤底部操作栏始终可见(弹窗隔离映射,任务 3)✓+- i18n(任务 4)✓++**占位符扫描:** 无 TODO / 待定 / "补充细节"。所有步骤含完整代码。++**类型一致性:** `FieldMappingEntry` 来自 `@/types/schemaDiff`;`handleFieldMappingsUpdate(mappings: FieldMappingEntry[])` 在任务 3 复用任务 1 emit 的 `save(FieldMappingEntry[])`;`sourceDbType` / `targetDbType` 在 `SchemaDiffDialog` 已存在;i18n 键在任务 4 定义、任务 1 使用,名称一致(`openFieldMapping` / `import` / `export` / `importSuccess` / `importError` / `done`)。++---++## 验收(手动,pnpm dev)++1. 打开"比较架构"弹窗,源/目标选不同类型 → 出现"字段类型映射"按钮。+2. 点按钮 → 独立弹窗打开,渲染映射面板。+3. 弹窗内添加大量映射 → 弹窗内部可滚动,底部"导入/导出/完成"始终可点。+4. 点"导出" → 下载 `field-mappings.json`,内容为 `FieldMappingEntry[]`。+5. 清空映射后点"导入"选该 json → 映射恢复;非法文件 → 报错 toast 且不替换。+6. 点"完成" → 写回配置步骤;关闭弹窗后底部操作栏(保存/加载/选项/开始比较)始终可见可点。+7. 点遮罩 / ✕ → 未"完成"的修改不写回。diff --git a/docs/superpowers/specs/2026-07-16-field-mapping-dialog-design.md b/docs/superpowers/specs/2026-07-16-field-mapping-dialog-design.mdnew file mode 100644index 0000000000..68e9b6af53--- /dev/null+++ b/docs/superpowers/specs/2026-07-16-field-mapping-dialog-design.md@@ -0,0 +1,167 @@+# 字段类型映射:独立弹窗 + 导入/导出++日期:2026-07-16+状态:已批准(待实现)++## 背景 / 问题++在"比较架构"配置步骤(`SchemaDiffConfigStep.vue`)中,字段类型映射面板+(`FieldMappingPanel`)直接内嵌在配置步骤里,没有内部滚动。当用户添加大量+映射条目时,面板会把底部的操作栏(保存配置 / 加载配置 / 选项 / 开始比较)+顶出视口,导致这些按钮无法点击、看不到。++用户要求:在"选项"按钮后面增加一个"字段类型映射"按钮,点击打开一个独立的+页面/弹窗来配置映射;并且该弹窗需要支持以 JSON 格式导入、导出映射配置,+参考现有导出功能。++## 目标++1. 字段类型映射添加再多,配置步骤底部的操作栏始终可见、可点击。+2. 提供独立弹窗编辑映射,体验与现有"选项"弹窗一致。+3. 弹窗内支持映射配置的 JSON 导入与导出。++## 非目标(YAGNI)++- 不新增映射列表内的搜索/过滤框(后续可加)。+- 不改动 Rust 侧逻辑(`FieldMapping` / `generate_schema_sync_sql` 已在上一个+ 会话修复)。+- 不改动配置整体的保存/加载/历史逻辑。++## 方案++采用方案 A:在"选项"按钮后增加一个"字段类型映射"按钮,点击打开一个叠加+Dialog(overlay),与现有"选项"弹窗(`SchemaDiffDialog` 的 `showOptionsPanel`)+同一风格。++### 1. 组件结构++- **新建 `apps/desktop/src/components/diff/FieldMappingDialog.vue`**+ - 复用 `SchemaDiffDialog` 的 overlay 模式:`absolute inset-0 bg-background/80+ backdrop-blur-sm z-50 flex items-center justify-center`,内层+ `bg-card border rounded-lg shadow-lg w-[760px] max-w-[calc(100vw-2rem)]+ max-h-[80vh] overflow-auto p-4`。+ - 内部渲染 `FieldMappingPanel`(`source-db-type` / `target-db-type` /+ `:mappings` / `@update:mappings`)。+ - 底部操作栏:导入 / 导出 / 完成(✕ 关闭在右上角)。+ - Props:`open: boolean`、`mappings: FieldMappingEntry[]`、+ `sourceDbType: string`、`targetDbType: string`。+ - Emits:`update:open(boolean)`、`save(FieldMappingEntry[])`。+ - 打开时把 `mappings` 深拷贝为本地 `editingMappings`(单向数据流,取消不写回)。++- **改动 `apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`**+ - 在"选项"按钮(`@show-options`)之后、同一 `<div class="flex items-center gap-2">`+ 内,插入"字段类型映射"按钮:`v-if="showFieldMapping"`,+ `@click="$emit('open-field-mapping')"`,文案 `t('diff.openFieldMapping')`,+ 图标 `ListChecks` 或 `ArrowLeftRight`。+ - 保留现有内嵌 `<FieldMappingPanel>`(行 429)作为快捷入口,行为不变。+ - `defineEmits` 新增 `(e: "open-field-mapping"): void;`。++- **改动 `apps/desktop/src/components/diff/SchemaDiffDialog.vue`**+ - 新增 `const showFieldMappingDialog = ref(false);`+ - `<SchemaDiffConfigStep>` 增加 `@open-field-mapping="showFieldMappingDialog = true"`。+ - 在 `showOptionsPanel` overlay 之后,新增 `<FieldMappingDialog>`:+ - `:open="showFieldMappingDialog"`+ - `:mappings="activeConfig?.options.fieldMappings ?? []"`+ - `:source-db-type="sourceDbType"`、`:target-db-type="targetDbType"`+ (沿用 `SchemaDiffConfigStep` 中既有的 source/target db type 取值方式)+ - `@update:open="showFieldMappingDialog = $event"`+ - `@save="handleFieldMappingsUpdate"`(复用现有写回函数,签名一致:+ `(v: FieldMappingEntry[]) => void`)++### 2. 数据流(单向,与 Options 一致)++打开弹窗 → 用当前 `fieldMappings` 深拷贝为本地 `editingMappings`+(`JSON.parse(JSON.stringify(...))` 或 `map` 拷贝)→ 弹窗内增删改只动本地副本+→ 点"完成" → `emit('save', editingMappings)` → `handleFieldMappingsUpdate`+写回 `activeConfig.options.fieldMappings` → 关闭弹窗。+点遮罩 / ✕ 仅关闭,不写回(取消)。++### 3. 导入 / 导出(JSON)++参考现有 `TagManagementPanel.handleExport`(Blob 下载)与+`useSchemaDiffConfig`(JSON 解析校验)。++- **导出**(`FieldMappingDialog` 内 `handleExport`):+ ```ts+ const blob = new Blob([JSON.stringify(editingMappings, null, 2)], { type: "application/json" });+ const url = URL.createObjectURL(blob);+ const a = document.createElement("a");+ a.href = url;+ a.download = "field-mappings.json";+ a.click();+ URL.revokeObjectURL(url);+ ```++- **导入**(`FieldMappingDialog` 内 `handleImport` + 隐藏 file input):+ - `<input ref="fileInputRef" type="file" accept=".json,application/json" class="hidden" @change="onFileSelected" />`+ - 读取文本 → `JSON.parse` → 校验为数组且每项含 `sourceType` / `targetType` /+ `paramStrategy`(缺 `paramStrategy` 默认 `"preserve"`,缺 `customParams`+ 默认 `undefined`)→ 替换本地 `editingMappings`。+ - 解析失败或结构不合法:`toast(t('diff.fieldMapping.importError'))` 并报错,+ 不替换。++- **JSON 结构**:即 `FieldMappingEntry[]`:+ ```json+ [+ { "sourceType": "VARCHAR", "targetType": "character", "paramStrategy": "preserve" },+ { "sourceType": "DECIMAL", "targetType": "numeric", "paramStrategy": "custom", "customParams": "(10,2)" }+ ]+ ```+ 与运行时 / Rust 侧 `FieldMapping` 对齐,可被 `generate_schema_sync_sql`+ 直接消费。++### 4. 滚动与可达性(根本修复)++- 弹窗内部 `max-h-[80vh] overflow-auto`:映射再多也在弹窗内滚动,绝不撑出视口。+- 同时给 `FieldMappingPanel` 的映射列表容器(`v-else` 分支根 `div`)加+ `max-h-[40vh] overflow-auto` 作为内嵌兜底,保证即便内嵌面板也滚动。++### 5. i18n++复用现有 `diff.fieldMapping.*` 键。新增(zh-CN / en,其余语言按现有+`exportConfig`/`importConfig` 模式补,本次至少保证 zh-CN + en):++- `diff.openFieldMapping`:打开字段类型映射弹窗的按钮文案+ (zh-CN: "字段类型映射";en: "Field Type Mapping")+- `diff.fieldMapping.import`:导入(zh-CN: "导入";en: "Import")+- `diff.fieldMapping.export`:导出(zh-CN: "导出";en: "Export")+- `diff.fieldMapping.importError`:导入失败提示+ (zh-CN: "导入失败:文件不是合法的字段类型映射 JSON";+ en: "Import failed: file is not a valid field type mapping JSON")+- `diff.fieldMapping.done`:完成按钮(zh-CN: "完成";en: "Done")++位置:zh-CN.ts 的 `schemaDiff.fieldMapping` 对象内(约 2444 行);+en.ts 的 `schemaDiff.fieldMapping` 对象内(约 2457 行)。++### 6. 测试 / 验收++纯前端改动,无 Rust 逻辑变更。手动验收(`pnpm dev`):++1. 打开"比较架构"弹窗,源/目标选择不同类型(触发 `showFieldMapping`)。+2. 点"选项"后的"字段类型映射"按钮 → 弹出独立弹窗。+3. 在弹窗内添加大量映射,确认弹窗内部可滚动、底部"导入/导出/完成"始终可点。+4. 点"导出" → 下载 `field-mappings.json`,内容正确。+5. 清空映射后点"导入",选择刚导出的 json → 映射恢复。+6. 点"完成" → 映射写回配置步骤;关闭弹窗后配置步骤底部操作栏(保存/加载/+ 选项/开始比较)始终可见可点。+7. 点遮罩 / ✕ 关闭弹窗 → 本地未"完成"的修改不写回。++类型检查:`pnpm typecheck`(仅关注本次改动文件无新增错误;已知 2 个与本次无关的+预存错误:`dbAdminSql.ts` / `McpServerStatus.node_path`)。++## 受影响文件++- 新建 `apps/desktop/src/components/diff/FieldMappingDialog.vue`+- 改 `apps/desktop/src/components/diff/SchemaDiffConfigStep.vue`+- 改 `apps/desktop/src/components/diff/SchemaDiffDialog.vue`+- 改 `apps/desktop/src/i18n/locales/zh-CN.ts`+- 改 `apps/desktop/src/i18n/locales/en.ts`+- (可选,非必须)其他语言 locale 的 `schemaDiff.fieldMapping` 补键++## 风险 / 注意++- `FieldMappingPanel` 现有 `space-y-3` 列表容器加上 `max-h` + `overflow-auto`+ 后,嵌套在弹窗的 `overflow-auto` 里可能产生双重滚动条;需实测,优先让弹窗+ 外层滚动,内层列表仅在高度受限时滚动。+- 导入校验要宽松:允许缺省 `customParams` / `paramStrategy`,避免严格校验把+ 合法旧配置拒掉。diff --git a/handoff.md b/handoff.mdnew file mode 100644index 0000000000..dfce92195c--- /dev/null+++ b/handoff.md@@ -0,0 +1,116 @@+# 🤝 Context Handoff++## Meta+- **exported_at**: 2026-07-24T21:38:36.3992945+08:00+- **exported_from**: opencode+- **session_id**: a8f3c1++## Project+- **name**: dbx+- **stack**: Rust, TypeScript, Vue 3, Tauri, Axum, PNPM+- **root**: D:\Developments\jetbrains\workspace\rust\dbx+- **package_manager**: pnpm++## Current Task+We are finishing the review-driven stabilization of the Schema Diff and synchronization tool. The main active blocker is in `crates/dbx-core/src/query.rs`, specifically `execute_schema_diff_deploy`, which currently distinguishes `committed`, `rolled_back`, and `mixed`, but still needs a stronger DDL atomicity model based on both target database behavior and SQL type semantics. This affects the Desktop and Web deploy flow exposed through `src-tauri/src/commands/query.rs`, `crates/dbx-web/src/routes/query.rs`, and the frontend orchestration in `apps/desktop/src/components/diff/SchemaDiffDialog.vue`. In parallel, we documented the overall problem and optimization plan in a new requirements doc and completed a long-term DDL architecture refactor that introduced `DdlDialectProfile` and `type_rewrite` for cross-database DDL generation.++## Progress+- [x] Merged latest `origin/main` into local `main`, then merged local `main` into local `cmp`+- [x] Preserved cmp branch functionality after merge, including schema-diff deploy and rollback completeness changes+- [x] Replaced fake per-statement 2PC deploy path with `execute_schema_diff_deploy` single-connection deploy result flow+- [x] Unified Schema Diff DDL panel execution and deploy-review confirmation through the same guarded frontend path (`executeDeploySql`)+- [x] Added structured rollback completeness fields: `rollbackCompleteness` and `missingRollbackObjects`+- [x] Blocked incomplete rollback execution in the frontend UI (button disable + toast + confirm-dialog gate)+- [x] Fixed `two_phase_commit` mixed-status logic to avoid re-running `commit()` as a probe+- [x] Added `detectTableRenames` option and separated table-rename detection from column rename detection+- [x] Aligned Schema Diff field mapping type source with table structure editor using `listDataTypes(connectionId, database)` + `getDataTypeOptions(dbType)`+- [x] Introduced `crates/dbx-core/src/sql_dialect/ddl_profile.rs`+- [x] Introduced `crates/dbx-core/src/sql_dialect/type_rewrite.rs`+- [x] Migrated CREATE/ALTER table, index, FK, comment, trigger, rename, and permission SQL generation onto profile/type-rewrite driven behavior+- [x] Reworked MySQL -> Access CREATE TABLE generation to use Access-compatible types and `COUNTER`+- [x] `execute_schema_diff_deploy` classifies atomicity by DB capability (`CAP_TRANSACTIONAL_DDL`) + SQL risk + transactional path+- [x] Unit tests cover MySQL/Oracle partial DDL failure → `mixed` + executed_count, Postgres → `rolled_back` + 0+- [x] Frontend `deployTxResult` maps mixed/rolled_back with executedCount/statementCount+- [x] Merged main into cmp; fixed functional-index test 10-arg call site+- [ ] Optionally finish template-level profile datafication for function / sequence / rule / owner SQL shapes+- [ ] Live DB e2e for deploy partial-failure (optional; unit/web structured tests already present)++## Active Files+- `handoff.md` — this handoff document for the next AI+- `需求问题/2026年7月24日-结构比对与同步工具-问题与优化方案.md` — new problem statement and optimization plan based on current code+- `crates/dbx-core/src/query.rs` — `SchemaDiffDeployResult` and `execute_schema_diff_deploy`; current blocker lives here+- `src-tauri/src/commands/query.rs` — Tauri deploy endpoint now delegates to `execute_schema_diff_deploy`+- `crates/dbx-web/src/routes/query.rs` — Web deploy route now delegates to `execute_schema_diff_deploy`; includes tests+- `crates/dbx-core/src/two_phase_commit.rs` — mixed / rolled_back logic no longer probes by re-calling `commit()`+- `crates/dbx-core/src/schema_diff.rs` — main schema diff DDL generation path; profile-driven create/alter/index/fk/comment/trigger logic+- `crates/dbx-core/src/script_generator.rs` — idempotent wrapper and lock-timeout behavior now profile-driven+- `crates/dbx-core/src/sql_dialect.rs` — exports for new ddl_profile and type_rewrite modules+- `crates/dbx-core/src/sql_dialect/ddl_profile.rs` — target `DatabaseType` profile registry and DDL behavior knobs+- `crates/dbx-core/src/sql_dialect/type_rewrite.rs` — type rewrite pipeline and auto-increment helpers+- `apps/desktop/src/components/diff/SchemaDiffDialog.vue` — unified protected deploy flow, rollback completeness handling, field mapping dialog wiring+- `apps/desktop/src/components/diff/SchemaDiffDdlPanel.vue` — rollback incomplete banner and execution block props+- `apps/desktop/src/components/diff/SchemaDiffDeployStep.vue` — deploy-step rollback incomplete banner and disabled deploy state+- `apps/desktop/src/lib/schema/deployTxResult.ts` — deploy result status/message mapping including `mixed` and `rolled_back`+- `apps/desktop/src/lib/schema/__tests__/deployTxResult.spec.ts` — frontend unit tests for deploy result interpretation+- `apps/desktop/src/lib/schema/schemaDiff.ts` — frontend types for `SchemaDiffPreparation`, rollback completeness, and missing rollback objects+- `apps/desktop/src/components/diff/FieldMappingPanel.vue` — field mapping types now use the same live/static source strategy as table structure editor+- `apps/desktop/src/components/diff/FieldMappingDialog.vue` — passes source/target connection and database context into field mapping panel+- `apps/desktop/src/types/database.ts` — expanded frontend deploy result / transaction fields+- `apps/desktop/src/i18n/locales/en.ts` — new rollback incomplete strings and detect-table-renames strings+- `apps/desktop/src/i18n/locales/zh-CN.ts` — Chinese strings for rollback incomplete and table rename detection+- `apps/desktop/src/i18n/locales/zh-TW.ts` — same strings for Traditional Chinese+- `apps/desktop/src/i18n/locales/es.ts` — same strings for Spanish+- `apps/desktop/src/i18n/locales/it.ts` — same strings for Italian+- `apps/desktop/src/i18n/locales/ja.ts` — same strings for Japanese+- `apps/desktop/src/i18n/locales/pt-BR.ts` — same strings for Brazilian Portuguese+- `crates/dbx-web/src/state.rs` — added `WebState::for_tests` helper to avoid missing new fields in scattered test fixtures+- `crates/dbx-web/src/routes/connection.rs` — updated tests to use `WebState::for_tests`+- `crates/dbx-web/src/routes/mongo.rs` — updated tests to use `WebState::for_tests`+- `crates/dbx-core/tests/api_contract_verification.rs` — full options initializer updated with `detect_table_renames`+- `crates/dbx-core/tests/bidirectional_diff_e2e.rs` — rename detection test updated to enable table rename detection explicitly++## Blocker+PR #3861 owner review items (2PC fake prepare, structured rollback, status mapping) are implemented on `cmp`.+Residual risk: no live MySQL/Oracle integration test against a real server for partial DDL failure; classification is covered by pure unit tests + web structured endpoint tests.+GitHub still may show `mergeable_state: dirty` until rechecked after push.++## Key Decisions+- The table structure editor must **not** be modified further in this task.+- Schema Diff field mapping must use the same type source strategy as table structure editor: `listDataTypes(connectionId, database)` plus `getDataTypeOptions(dbType)` fallback.+- Do **not** revert to `listDialectDataTypes` for field mapping dropdowns.+- Cross-database DDL generation must be driven by `DdlDialectProfile` + `type_rewrite`, not by scattered `if Access` / `if Mysql` / `if SqlServer` branches in generators.+- `profile_for(DatabaseType)` is the only acceptable place to register target-database-specific DDL behavior.+- Incomplete rollback must remain structurally represented (`rollbackCompleteness`, `missingRollbackObjects`) and blocked in the UI.+- Schema Diff deploy execution paths must remain unified through a single protected frontend flow using `executeWithProductionSqlGuard`.+- `two_phase_commit` must never determine partial commit state by re-running `commit()`.++## Environment+- Runtime version: not fully verified locally; Rust workspace compile on this Windows host is limited by missing OpenSSL/Perl toolchain for some crates+- Relevant env vars: GitHub Actions workflow issues referenced `I18N_BOT_TOKEN`; local work did not rely on it+- Dev command: `pnpm check` for frontend; Rust checks typically via `cargo check` / `cargo test`+- Package manager: `pnpm`+- Platform: Windows local development, CI issues referenced Linux runners+- Known local limitation: `cargo check` for the full workspace can fail or hang due to OpenSSL build prerequisites (`perl` missing) on this machine++## Next Steps+1. Push latest `cmp` and re-request review on PR #3861 with a short reply mapping each review point to commits.+2. Optionally add live MySQL/Oracle partial-DDL e2e if CI has those services.+3. Optional architecture cleanup: move function/sequence/rule/owner templates fully into `DdlDialectProfile` data.++## For the Next AI+- Read all Active Files before doing anything.+- Do NOT change Key Decisions without flagging first.+- Start from `crates/dbx-core/src/query.rs`; that is the last review blocker that is still not fully solved.+- Treat the new DDL profile architecture as the canonical direction; do not reintroduce scattered database-specific generator branches.+- Do not touch table structure editor code.+- Use the requirements doc in `需求问题/2026年7月24日-结构比对与同步工具-问题与优化方案.md` as the planning baseline.++---++✅ handoff.md written to project root.+Switch to your next tool and run /handoff-load to continue.++Summary:+- Task: finalize Schema Diff deploy correctness and long-term DDL profile architecture+- Next step: replace pool-kind DDL atomicity heuristic with database+SQL semantic classification in execute_schema_diff_deploy+- Blocker: MySQL/Oracle and other non-transactional DDL paths may still report rolled_back too optimisticallydiff --git a/plugins/dialects/access.yaml b/plugins/dialects/access.yamlnew file mode 100644index 0000000000..8d7b799ada--- /dev/null+++ b/plugins/dialects/access.yaml@@ -0,0 +1,103 @@+dialect:+ name: "Access"+ display_name: "Microsoft Access"+ versions:+ - version: "2019"+ status: "RECOMMENDED"++types:+ - name: "BYTE"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ aliases: ["SHORT"]+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "LONG"]+ - name: "SINGLE"+ category: "FLOAT"+ aliases: ["FLOAT", "REAL"]+ - name: "DOUBLE"+ category: "FLOAT"+ aliases: ["DOUBLE PRECISION"]+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "CURRENCY"+ category: "DECIMAL"+ semantic_fidelity_base: 0.8+ - name: "TEXT"+ category: "STRING"+ has_length: true+ max_precision: 255+ aliases: ["VARCHAR", "CHAR"]+ - name: "LONGTEXT"+ category: "STRING"+ aliases: ["MEMO"]+ - name: "DATETIME"+ category: "DATETIME"+ aliases: ["DATE", "TIME", "TIMESTAMP"]+ - name: "YESNO"+ category: "BOOLEAN"+ aliases: ["BIT", "BOOLEAN"]+ - name: "OLEOBJECT"+ category: "BINARY"+ semantic_fidelity_base: 0.3+ - name: "BINARY"+ category: "BINARY"+ - name: "GUID"+ category: "UUID"+ - name: "HYPERLINK"+ category: "STRING"+ semantic_fidelity_base: 0.4++ddl_capabilities:+ add_column: true+ drop_column: true+ create_index: true+ drop_index: true+ create_table: true+ drop_table: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"++structural_capabilities:+ max_columns_per_table: 255+ max_indexes_per_table: 32+ max_query_size_bytes: 65536+ max_foreign_key_name_length: 64+ supports_full_text_index: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT Name FROM MSysObjects WHERE Type = 1 AND Flags = 0"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT * FROM {table} WHERE 1=0"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT Name FROM MSysObjects WHERE Type = 1"+ depth_support: 0+ performance_profile: "LIGHT"diff --git a/plugins/dialects/clickhouse.yaml b/plugins/dialects/clickhouse.yamlnew file mode 100644index 0000000000..4f7584cd48--- /dev/null+++ b/plugins/dialects/clickhouse.yaml@@ -0,0 +1,186 @@+dialect:+ name: "ClickHouse"+ display_name: "ClickHouse"+ versions:+ - version: "24"+ status: "RECOMMENDED"++types:+ - name: "UInt8"+ category: "INTEGER"+ aliases: ["TINYINT"]+ - name: "UInt16"+ category: "INTEGER"+ aliases: ["SMALLINT"]+ - name: "UInt32"+ category: "INTEGER"+ aliases: ["INT", "INTEGER"]+ - name: "UInt64"+ category: "INTEGER"+ aliases: ["BIGINT"]+ - name: "Int8"+ category: "INTEGER"+ - name: "Int16"+ category: "INTEGER"+ - name: "Int32"+ category: "INTEGER"+ - name: "Int64"+ category: "INTEGER"+ - name: "Int128"+ category: "INTEGER"+ semantic_fidelity_base: 0.6+ - name: "Int256"+ category: "INTEGER"+ semantic_fidelity_base: 0.5+ - name: "Float32"+ category: "FLOAT"+ aliases: ["FLOAT"]+ - name: "Float64"+ category: "FLOAT"+ aliases: ["DOUBLE"]+ - name: "Decimal"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "String"+ category: "STRING"+ aliases: ["VARCHAR", "TEXT"]+ - name: "FixedString"+ category: "STRING"+ semantic_fidelity_base: 0.9+ - name: "UUID"+ category: "UUID"+ - name: "Date"+ category: "DATE"+ - name: "Date32"+ category: "DATE"+ semantic_fidelity_base: 0.9+ - name: "DateTime"+ category: "DATETIME"+ aliases: ["TIMESTAMP"]+ - name: "DateTime64"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "Enum"+ category: "ENUM"+ semantic_fidelity_base: 0.8+ - name: "Array"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "Map"+ category: "MAP"+ semantic_fidelity_base: 0.3+ - name: "Tuple"+ category: "TUPLE"+ semantic_fidelity_base: 0.3+ - name: "Nullable"+ category: "NULLABLE"+ semantic_fidelity_base: 0.9+ - name: "LowCardinality"+ category: "STRING"+ semantic_fidelity_base: 0.8+ - name: "JSON"+ category: "JSON"+ - name: "IPv4"+ category: "NETWORK"+ semantic_fidelity_base: 0.3+ - name: "IPv6"+ category: "NETWORK"+ semantic_fidelity_base: 0.3+ - name: "Point"+ category: "SPATIAL"+ - name: "Ring"+ category: "SPATIAL"+ - name: "Polygon"+ category: "SPATIAL"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ reorder_column: true+ comment: true+ create_index: false+ drop_index: false+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ temporary_table: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns}) ENGINE = MergeTree() ORDER BY tuple()"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "ALTER TABLE {table} ADD INDEX {name} {columns} TYPE minmax GRANULARITY 1"+ drop_index: "ALTER TABLE {table} DROP INDEX {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1000+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 256+ supports_full_text_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_array_type: true+ supports_json_type: true+ supports_enum_type: true+ supports_uuid_type: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 256++metadata_queries:+ list_tables:+ sql: "SELECT name FROM system.tables WHERE database = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT name, type, is_nullable, default_expression FROM system.columns WHERE database = '{schema}' AND table = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT table FROM system.columns WHERE database = '{schema}'"+ depth_support: 0+ performance_profile: "LIGHT"++pre_execution_checks:+ - name: "mutation_sync"+ sql: "SELECT 1"diff --git a/plugins/dialects/dameng.yaml b/plugins/dialects/dameng.yamlnew file mode 100644index 0000000000..f93ecbcc34--- /dev/null+++ b/plugins/dialects/dameng.yaml@@ -0,0 +1,183 @@+dialect:+ name: "Dameng"+ display_name: "达梦 (DM)"+ versions:+ - version: "8"+ status: "RECOMMENDED"+ - version: "7"+ status: "COMPATIBLE"++types:+ - name: "TINYINT"+ category: "INTEGER"+ precision_range: [-128, 127]+ - name: "SMALLINT"+ category: "INTEGER"+ precision_range: [-32768, 32767]+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ aliases: ["DOUBLE PRECISION"]+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL", "NUMBER"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 8188+ aliases: ["VARCHAR2", "CHARACTER VARYING"]+ - name: "CHAR"+ category: "STRING"+ has_length: true+ max_precision: 8188+ aliases: ["CHARACTER"]+ - name: "TEXT"+ category: "STRING"+ aliases: ["CLOB", "LONGVARCHAR"]+ - name: "BLOB"+ category: "BINARY"+ aliases: ["IMAGE", "LONGVARBINARY"]+ - name: "BINARY"+ category: "BINARY"+ has_length: true+ aliases: ["VARBINARY"]+ - name: "DATE"+ category: "DATETIME"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ aliases: ["DATETIME"]+ - name: "INTERVAL YEAR"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "INTERVAL DAY"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "BOOLEAN"+ category: "BOOLEAN"+ aliases: ["BIT"]+ - name: "ROWID"+ category: "SYSTEM"+ semantic_fidelity_base: 0.1++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY {column} {type}"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 2048+ max_indexes_per_table: 64+ max_query_size_bytes: 134217728+ max_foreign_key_name_length: 128+ supports_full_text_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_json_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}' ORDER BY COLUMN_ID"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT INDEX_NAME, COLUMN_NAME FROM ALL_IND_COLUMNS WHERE TABLE_OWNER = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT a.CONSTRAINT_NAME, a.COLUMN_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}' AND c.TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT TRIGGER_NAME, TRIGGER_TYPE, TRIGGERING_EVENT, TRIGGER_BODY FROM ALL_TRIGGERS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT a.TABLE_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/databend.yaml b/plugins/dialects/databend.yamlnew file mode 100644index 0000000000..92d1b21a9b--- /dev/null+++ b/plugins/dialects/databend.yaml@@ -0,0 +1,99 @@+dialect:+ name: "Databend"+ display_name: "Databend"+ versions:+ - version: "1"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "STRING"+ category: "STRING"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "ARRAY"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "VARIANT"+ category: "JSON"+ - name: "MAP"+ category: "MAP"+ semantic_fidelity_base: 0.4+ - name: "BITMAP"+ category: "BITMAP"+ semantic_fidelity_base: 0.2++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 4096+ max_query_size_bytes: 268435456+ supports_json_type: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 256++metadata_queries:+ list_tables:+ sql: "SELECT name FROM system.tables WHERE database = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT name, type FROM system.columns WHERE database = '{schema}' AND table = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT name FROM system.tables WHERE database = '{schema}'"+ depth_support: 0+ performance_profile: "LIGHT"diff --git a/plugins/dialects/doris.yaml b/plugins/dialects/doris.yamlnew file mode 100644index 0000000000..acf1d8c165--- /dev/null+++ b/plugins/dialects/doris.yaml@@ -0,0 +1,148 @@+dialect:+ name: "Doris"+ display_name: "Apache Doris"+ versions:+ - version: "2.1"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ - name: "BIGINT"+ category: "INTEGER"+ - name: "LARGEINT"+ category: "INTEGER"+ semantic_fidelity_base: 0.6+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 65533+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "STRING"+ category: "STRING"+ max_precision: 2147483643+ - name: "TEXT"+ category: "STRING"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "ARRAY"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "JSON"+ category: "JSON"+ - name: "MAP"+ category: "MAP"+ semantic_fidelity_base: 0.4+ - name: "STRUCT"+ category: "STRUCT"+ semantic_fidelity_base: 0.3+ - name: "BITMAP"+ category: "BITMAP"+ semantic_fidelity_base: 0.2+ - name: "HLL"+ category: "HLL"+ semantic_fidelity_base: 0.1+ - name: "QUANTILE_STATE"+ category: "QUANTILE"+ semantic_fidelity_base: 0.1++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ rebuild_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ temporary_table: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX {name} ON {table} ({columns}) USING BITMAP"+ drop_index: "DROP INDEX {name} ON {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 4096+ max_indexes_per_table: 64+ max_query_size_bytes: 16777216+ max_foreign_key_name_length: 64+ supports_full_text_index: true+ supports_spatial_index: true+ supports_partitioning: true+ supports_json_type: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SHOW INDEX FROM {table}"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/duckdb.yaml b/plugins/dialects/duckdb.yamlnew file mode 100644index 0000000000..51fc0a95ca--- /dev/null+++ b/plugins/dialects/duckdb.yaml@@ -0,0 +1,163 @@+dialect:+ name: "DuckDB"+ display_name: "DuckDB"+ versions:+ - version: "1"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "INT4"]+ - name: "BIGINT"+ category: "INTEGER"+ aliases: ["INT8"]+ - name: "HUGEINT"+ category: "INTEGER"+ semantic_fidelity_base: 0.6+ - name: "FLOAT"+ category: "FLOAT"+ aliases: ["FLOAT4", "REAL"]+ - name: "DOUBLE"+ category: "FLOAT"+ aliases: ["FLOAT8"]+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "BLOB"+ category: "BINARY"+ aliases: ["BYTEA", "BINARY", "VARBINARY"]+ - name: "BOOLEAN"+ category: "BOOLEAN"+ aliases: ["BOOL"]+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ aliases: ["DATETIME"]+ - name: "TIMESTAMP WITH TIME ZONE"+ category: "DATETIME"+ aliases: ["TIMESTAMPTZ"]+ - name: "INTERVAL"+ category: "INTERVAL"+ semantic_fidelity_base: 0.7+ - name: "UUID"+ category: "UUID"+ - name: "JSON"+ category: "JSON"+ - name: "LIST"+ category: "ARRAY"+ semantic_fidelity_base: 0.4+ - name: "MAP"+ category: "MAP"+ semantic_fidelity_base: 0.3+ - name: "STRUCT"+ category: "STRUCT"+ semantic_fidelity_base: 0.3+ - name: "ENUM"+ category: "ENUM"+ semantic_fidelity_base: 0.7+ - name: "UNION"+ category: "UNION"+ semantic_fidelity_base: 0.2++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ create_index: true+ drop_index: true+ rebuild_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ create_or_replace: true+ temporary_table: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX IF NOT EXISTS {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "SAFE"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 255+ supports_spatial_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_array_type: true+ supports_json_type: true+ supports_enum_type: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 255++metadata_queries:+ list_tables:+ sql: "SELECT table_name FROM information_schema.tables WHERE table_schema = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ list_sequences:+ sql: "SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema = '{schema}'"+ performance_profile: "LIGHT"+ dependencies:+ sql: "SELECT table_name FROM information_schema.tables WHERE table_schema = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/exasol.yaml b/plugins/dialects/exasol.yamlnew file mode 100644index 0000000000..195c3acea6--- /dev/null+++ b/plugins/dialects/exasol.yaml@@ -0,0 +1,115 @@+dialect:+ name: "Exasol"+ display_name: "Exasol"+ versions:+ - version: "8"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 2000000+ - name: "CHAR"+ category: "STRING"+ has_length: true+ max_precision: 2000+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMP WITH LOCAL TIME ZONE"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "INTERVAL YEAR TO MONTH"+ category: "INTERVAL"+ - name: "INTERVAL DAY TO SECOND"+ category: "INTERVAL"+ - name: "GEOMETRY"+ category: "SPATIAL"+ - name: "HASHTYPE"+ category: "SYSTEM"+ semantic_fidelity_base: 0.1++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ grant_revoke: true+ if_not_exists: true+ transactional_ddl: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 100000+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ supports_partitioning: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM EXA_ALL_TABLES WHERE TABLE_SCHEMA = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, COLUMN_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM EXA_ALL_COLUMNS WHERE COLUMN_SCHEMA = '{schema}' AND COLUMN_TABLE = '{table}' ORDER BY COLUMN_ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME FROM EXA_ALL_TABLES WHERE TABLE_SCHEMA = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/firebird.yaml b/plugins/dialects/firebird.yamlnew file mode 100644index 0000000000..236774e9c5--- /dev/null+++ b/plugins/dialects/firebird.yaml@@ -0,0 +1,98 @@+dialect:+ name: "Firebird"+ display_name: "Firebird"+ versions:+ - version: "5"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "BLOB SUB_TYPE TEXT"+ category: "STRING"+ - name: "BLOB SUB_TYPE BINARY"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"++ddl_capabilities:+ add_column: true+ drop_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ create_trigger: true+ drop_trigger: true+ alter_owner: true+ if_not_exists: true+ transactional_ddl: true+ templates:+ add_column: "ALTER TABLE {table} ADD {column} {type}"+ drop_column: "ALTER TABLE {table} DROP {column}"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP {column}"+ drop_column: "ALTER TABLE {table} ADD {column} {original_type}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: false+ max_columns_per_table: 32768+ max_indexes_per_table: 256+ max_query_size_bytes: 16777216+ max_foreign_key_name_length: 31+ supports_on_update_cascade: true+ supports_deferrable_constraints: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 31++metadata_queries:+ list_tables:+ sql: "SELECT RDB$RELATION_NAME FROM RDB$RELATIONS WHERE RDB$SYSTEM_FLAG = 0 AND RDB$VIEW_BLR IS NULL"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT RDB$FIELD_NAME, RDB$FIELD_SOURCE FROM RDB$RELATION_FIELDS WHERE RDB$RELATION_NAME = '{table}' ORDER BY RDB$FIELD_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT RDB$RELATION_NAME, RDB$CONSTRAINT_NAME FROM RDB$RELATION_CONSTRAINTS WHERE RDB$CONSTRAINT_TYPE = 'FOREIGN KEY'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/gaussdb.yaml b/plugins/dialects/gaussdb.yamlnew file mode 100644index 0000000000..573ee8d5db--- /dev/null+++ b/plugins/dialects/gaussdb.yaml@@ -0,0 +1,204 @@+dialect:+ name: "GaussDB"+ display_name: "GaussDB / openGauss"+ versions:+ - version: "5.0"+ status: "RECOMMENDED"+ - version: "3.0"+ status: "COMPATIBLE"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ aliases: ["INT2"]+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "INT4"]+ - name: "BIGINT"+ category: "INTEGER"+ aliases: ["INT8"]+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLSERIAL"+ category: "INTEGER"+ - name: "SERIAL"+ category: "INTEGER"+ - name: "BIGSERIAL"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ aliases: ["FLOAT4"]+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ aliases: ["FLOAT8"]+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ aliases: ["CHARACTER VARYING"]+ - name: "CHAR"+ category: "STRING"+ has_length: true+ aliases: ["CHARACTER"]+ - name: "TEXT"+ category: "STRING"+ - name: "CLOB"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ aliases: ["BLOB", "RAW"]+ - name: "BOOLEAN"+ category: "BOOLEAN"+ aliases: ["BOOL"]+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMPTZ"+ category: "DATETIME"+ aliases: ["TIMESTAMP WITH TIME ZONE"]+ semantic_fidelity_base: 0.9+ - name: "INTERVAL"+ category: "INTERVAL"+ semantic_fidelity_base: 0.7+ - name: "UUID"+ category: "UUID"+ - name: "JSON"+ category: "JSON"+ - name: "JSONB"+ category: "JSON"+ semantic_fidelity_base: 0.9+ - name: "POINT"+ category: "SPATIAL"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ index_include: true+ index_filter: true+ alter_primary_key: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ create_or_replace: true+ transactional_ddl: true+ temporary_table: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX IF NOT EXISTS {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 63+ supports_full_text_index: true+ supports_spatial_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_deferrable_constraints: true+ supports_array_type: true+ supports_json_type: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT indexname, indexdef FROM pg_catalog.pg_indexes WHERE schemaname = '{schema}' AND tablename = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT tc.constraint_name, kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}' AND tc.table_name = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 3+ performance_profile: "HEAVY"++pre_execution_checks:+ - name: "lock_timeout"+ sql: "SET lock_timeout = '3s'"+ - name: "statement_timeout"+ sql: "SET statement_timeout = '30s'"diff --git a/plugins/dialects/gbase.yaml b/plugins/dialects/gbase.yamlnew file mode 100644index 0000000000..daf174780d--- /dev/null+++ b/plugins/dialects/gbase.yaml@@ -0,0 +1,97 @@+dialect:+ name: "GBase"+ display_name: "GBase 8a"+ versions:+ - version: "8a"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ max_columns_per_table: 4096+ max_indexes_per_table: 64+ max_query_size_bytes: 16777216+ supports_full_text_index: true+ supports_partitioning: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/goldendb.yaml b/plugins/dialects/goldendb.yamlnew file mode 100644index 0000000000..bba4991b9a--- /dev/null+++ b/plugins/dialects/goldendb.yaml@@ -0,0 +1,114 @@+dialect:+ name: "GoldenDB"+ display_name: "GoldenDB"+ versions:+ - version: "5"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "MEDIUMINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 65535+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "JSON"+ category: "JSON"+ - name: "ENUM"+ category: "ENUM"+ semantic_fidelity_base: 0.8++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ grant_revoke: true+ if_not_exists: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"++structural_capabilities:+ max_columns_per_table: 4096+ max_indexes_per_table: 64+ max_query_size_bytes: 16777216+ max_foreign_key_name_length: 64+ supports_full_text_index: true+ supports_partitioning: true+ supports_json_type: true+ supports_enum_type: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME, REFERENCED_TABLE_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{schema}' AND REFERENCED_TABLE_NAME IS NOT NULL"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/h2.yaml b/plugins/dialects/h2.yamlnew file mode 100644index 0000000000..0ed8e6d3f7--- /dev/null+++ b/plugins/dialects/h2.yaml@@ -0,0 +1,170 @@+dialect:+ name: "H2"+ display_name: "H2"+ versions:+ - version: "2"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER", "MEDIUMINT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "IDENTITY"+ category: "INTEGER"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC", "DEC", "NUMBER"]+ - name: "DOUBLE"+ category: "FLOAT"+ aliases: ["DOUBLE PRECISION", "FLOAT", "FLOAT8"]+ - name: "REAL"+ category: "FLOAT"+ aliases: ["FLOAT4"]+ - name: "TIME"+ category: "TIME"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ aliases: ["DATETIME"]+ - name: "TIMESTAMP WITH TIME ZONE"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ aliases: ["LONGVARCHAR", "VARCHAR2", "NVARCHAR", "NVARCHAR2", "VARCHAR_CASESENSITIVE"]+ - name: "CHAR"+ category: "STRING"+ has_length: true+ aliases: ["CHARACTER", "NCHAR"]+ - name: "CLOB"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ aliases: ["LONGVARBINARY", "IMAGE", "TINYBLOB", "MEDIUMBLOB", "LONGBLOB"]+ - name: "BINARY"+ category: "BINARY"+ has_length: true+ aliases: ["VARBINARY", "RAW"]+ - name: "BOOLEAN"+ category: "BOOLEAN"+ aliases: ["BOOL", "BIT"]+ - name: "UUID"+ category: "UUID"+ - name: "ARRAY"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "GEOMETRY"+ category: "SPATIAL"+ - name: "JSON"+ category: "JSON"+ - name: "ENUM"+ category: "ENUM"+ - name: "INTERVAL"+ category: "INTERVAL"+ semantic_fidelity_base: 0.6++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ if_not_exists: true+ temporary_table: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} ALTER COLUMN {old} RENAME TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX IF NOT EXISTS {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} ALTER COLUMN {new} RENAME TO {old}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 131072+ max_foreign_key_name_length: 256+ supports_full_text_index: true+ supports_spatial_index: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_deferrable_constraints: true+ supports_json_type: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 256++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT INDEX_NAME, COLUMN_NAME FROM INFORMATION_SCHEMA.INDEXES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.CROSS_REFERENCES WHERE PKTABLE_SCHEMA = '{schema}' AND FKTABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT FKTABLE_NAME AS table_name, PKTABLE_NAME AS ref_table FROM INFORMATION_SCHEMA.CROSS_REFERENCES WHERE PKTABLE_SCHEMA = '{schema}'"+ depth_support: 2+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/highgo.yaml b/plugins/dialects/highgo.yamlnew file mode 100644index 0000000000..12a4b4e039--- /dev/null+++ b/plugins/dialects/highgo.yaml@@ -0,0 +1,104 @@+dialect:+ name: "HighGo"+ display_name: "HighGo DB"+ versions:+ - version: "6"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "BOOLEAN"+ category: "BOOLEAN"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ if_not_exists: true+ transactional_ddl: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 63+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/informix.yaml b/plugins/dialects/informix.yamlnew file mode 100644index 0000000000..8fffd6b46f--- /dev/null+++ b/plugins/dialects/informix.yaml@@ -0,0 +1,151 @@+dialect:+ name: "Informix"+ display_name: "Informix"+ versions:+ - version: "14"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ aliases: ["INT8"]+ - name: "INT8"+ category: "INTEGER"+ - name: "SERIAL"+ category: "INTEGER"+ - name: "BIGSERIAL"+ category: "INTEGER"+ aliases: ["SERIAL8"]+ - name: "SMALLFLOAT"+ category: "FLOAT"+ aliases: ["REAL"]+ - name: "FLOAT"+ category: "FLOAT"+ aliases: ["DOUBLE PRECISION"]+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC", "DEC"]+ - name: "MONEY"+ category: "DECIMAL"+ semantic_fidelity_base: 0.8+ - name: "CHAR"+ category: "STRING"+ has_length: true+ aliases: ["CHARACTER"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ aliases: ["CHARACTER VARYING", "NVARCHAR"]+ - name: "NCHAR"+ category: "STRING"+ has_length: true+ - name: "LVARCHAR"+ category: "STRING"+ - name: "TEXT"+ category: "STRING"+ semantic_fidelity_base: 0.9+ - name: "BYTE"+ category: "BINARY"+ semantic_fidelity_base: 0.9+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME YEAR TO SECOND"+ category: "DATETIME"+ aliases: ["DATETIME"]+ semantic_fidelity_base: 0.9+ - name: "INTERVAL"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "BLOB"+ category: "BINARY"+ - name: "CLOB"+ category: "STRING"+ - name: "JSON"+ category: "JSON"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ rebuild_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ grant_revoke: true+ templates:+ add_column: "ALTER TABLE {table} ADD {column} {type}"+ drop_column: "ALTER TABLE {table} DROP {column}"+ rename_column: "RENAME COLUMN {table}.{old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {type})"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP {column}"+ drop_column: "ALTER TABLE {table} ADD {column} {original_type}"+ rename_column: "RENAME COLUMN {table}.{new} TO {old}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 32767+ max_indexes_per_table: 200+ max_query_size_bytes: 2097152+ max_foreign_key_name_length: 128+ supports_partitioning: true+ supports_on_delete_set_null: true+ supports_deferrable_constraints: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT tabname FROM systables WHERE tabtype = 'T' AND tabid > 99"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT colname, coltype FROM syscolumns WHERE tabid = (SELECT tabid FROM systables WHERE tabname = '{table}')"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tabname FROM systables WHERE tabtype = 'T'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/iris.yaml b/plugins/dialects/iris.yamlnew file mode 100644index 0000000000..d1ed97ae45--- /dev/null+++ b/plugins/dialects/iris.yaml@@ -0,0 +1,107 @@+dialect:+ name: "Iris"+ display_name: "InterSystems IRIS"+ versions:+ - version: "2024"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "TINYINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ aliases: ["DOUBLE PRECISION"]+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "POSIXTIME"+ category: "DATETIME"+ semantic_fidelity_base: 0.7++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ grant_revoke: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} {type}"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1000+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 128+ supports_partitioning: true+ supports_json_type: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME, REFERENCED_TABLE_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{schema}' AND REFERENCED_TABLE_NAME IS NOT NULL"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/kingbase.yaml b/plugins/dialects/kingbase.yamlnew file mode 100644index 0000000000..de1b3ce05a--- /dev/null+++ b/plugins/dialects/kingbase.yaml@@ -0,0 +1,116 @@+dialect:+ name: "Kingbase"+ display_name: "KingbaseES"+ versions:+ - version: "V8"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "JSON"+ category: "JSON"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ create_or_replace: true+ transactional_ddl: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 63+ supports_deferrable_constraints: true+ supports_json_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/kwdb.yaml b/plugins/dialects/kwdb.yamlnew file mode 100644index 0000000000..3d245e3f5b--- /dev/null+++ b/plugins/dialects/kwdb.yaml@@ -0,0 +1,97 @@+dialect:+ name: "KwDB"+ display_name: "KwDB"+ versions:+ - version: "2.0"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_sequence: true+ drop_sequence: true+ if_not_exists: true+ transactional_ddl: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/manticoresearch.yaml b/plugins/dialects/manticoresearch.yamlnew file mode 100644index 0000000000..f2bf2010e5--- /dev/null+++ b/plugins/dialects/manticoresearch.yaml@@ -0,0 +1,85 @@+dialect:+ name: "ManticoreSearch"+ display_name: "ManticoreSearch"+ versions:+ - version: "6"+ status: "RECOMMENDED"++types:+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "BIGINT"]+ - name: "FLOAT"+ category: "FLOAT"+ - name: "TEXT"+ category: "STRING"+ aliases: ["STRING"]+ - name: "JSON"+ category: "JSON"+ - name: "MULTI"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "MULTI64"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "TIMESTAMP"+ category: "DATETIME"++ddl_capabilities:+ add_column: true+ drop_column: true+ create_index: false+ drop_index: false+ create_table: true+ drop_table: true+ truncate_table: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ max_columns_per_table: 512+ max_query_size_bytes: 16777216+ supports_full_text_index: true+ supports_spatial_index: true+ supports_json_type: true++identifier_rules:+ quote_char: '`'+ case_sensitive: false+ max_length: 256++metadata_queries:+ list_tables:+ sql: "SHOW TABLES"+ performance_profile: "LIGHT"+ list_columns:+ sql: "DESC {table}"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SHOW TABLES"+ depth_support: 0+ performance_profile: "LIGHT"diff --git a/plugins/dialects/mysql.yaml b/plugins/dialects/mysql.yamlnew file mode 100644index 0000000000..8dadf6ca39--- /dev/null+++ b/plugins/dialects/mysql.yaml@@ -0,0 +1,220 @@+dialect:+ name: "MySQL"+ display_name: "MySQL"+ versions:+ - version: "8.0"+ status: "RECOMMENDED"+ - version: "5.7"+ status: "COMPATIBLE"++types:+ - name: "TINYINT"+ category: "INTEGER"+ precision_range: [-128, 127]+ aliases: ["BOOL", "BOOLEAN"]+ - name: "SMALLINT"+ category: "INTEGER"+ precision_range: [-32768, 32767]+ - name: "MEDIUMINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ aliases: ["DOUBLE PRECISION", "REAL"]+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ max_precision: 65535+ has_length: true+ aliases: ["CHARACTER VARYING"]+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "TINYTEXT"+ category: "STRING"+ - name: "MEDIUMTEXT"+ category: "STRING"+ - name: "LONGTEXT"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "TINYBLOB"+ category: "BINARY"+ - name: "MEDIUMBLOB"+ category: "BINARY"+ - name: "LONGBLOB"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIME"+ category: "TIME"+ - name: "YEAR"+ category: "INTEGER"+ - name: "ENUM"+ category: "ENUM"+ has_length: true+ semantic_fidelity_base: 0.8+ - name: "SET"+ category: "SET"+ has_length: true+ semantic_fidelity_base: 0.7+ - name: "JSON"+ category: "JSON"+ - name: "GEOMETRY"+ category: "SPATIAL"+ - name: "POINT"+ category: "SPATIAL"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ reorder_column: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ index_comment: true+ alter_primary_key: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX {name} ON {table} ({columns})"+ drop_index: "DROP INDEX {name} ON {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"+ osc_template:+ # Credentials via conf/defaults-file only — never interpolate {password} into argv/scripts/logs.+ gh_ost: "gh-ost --alter='{ddl}' --conf={defaults_file} --database={database} --table={table} --execute"+ pt_osc: "pt-online-schema-change --defaults-file={defaults_file} --alter='{ddl}' --execute D={database},t={table}"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: false+ max_columns_per_table: 4096+ max_indexes_per_table: 64+ max_query_size_bytes: 16777216+ supports_full_text_index: true+ supports_spatial_index: true+ supports_partitioning: true+ max_foreign_key_name_length: 64+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_json_type: true+ supports_enum_type: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT, COLUMN_TYPE, EXTRA FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT INDEX_NAME, COLUMN_NAME, NON_UNIQUE, INDEX_TYPE FROM INFORMATION_SCHEMA.STATISTICS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT CONSTRAINT_NAME, COLUMN_NAME, REFERENCED_TABLE_NAME, REFERENCED_COLUMN_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' AND REFERENCED_TABLE_NAME IS NOT NULL"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT TRIGGER_NAME, EVENT_MANIPULATION, ACTION_TIMING, ACTION_STATEMENT FROM INFORMATION_SCHEMA.TRIGGERS WHERE EVENT_OBJECT_SCHEMA = '{schema}' AND EVENT_OBJECT_TABLE = '{table}'"+ performance_profile: "MEDIUM"+ list_functions:+ sql: "SELECT ROUTINE_NAME, ROUTINE_TYPE, DTD_IDENTIFIER, ROUTINE_DEFINITION FROM INFORMATION_SCHEMA.ROUTINES WHERE ROUTINE_SCHEMA = '{schema}' AND ROUTINE_TYPE = 'FUNCTION'"+ performance_profile: "HEAVY"+ dependencies:+ sql: "SELECT TABLE_NAME, REFERENCED_TABLE_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{schema}' AND REFERENCED_TABLE_NAME IS NOT NULL"+ depth_support: 2+ performance_profile: "HEAVY"++pre_execution_checks:+ - name: "lock_wait_timeout"+ sql: "SET SESSION lock_wait_timeout = 3"+ - name: "foreign_key_checks"+ sql: "SET FOREIGN_KEY_CHECKS = 0"+ - name: "sql_mode"+ sql: "SET SESSION sql_mode = 'STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION'"++version_conditions:+ add_column_concurrent:+ - min_version: "8.0"+ template: "ALTER TABLE {table} ADD COLUMN {column} {type}, ALGORITHM=INPLACE, LOCK=NONE"+ - max_version: "8.0"+ template: "ALTER TABLE {table} ADD COLUMN {column} {type}"diff --git a/plugins/dialects/oceanbase.yaml b/plugins/dialects/oceanbase.yamlnew file mode 100644index 0000000000..61ba66f54b--- /dev/null+++ b/plugins/dialects/oceanbase.yaml@@ -0,0 +1,165 @@+dialect:+ name: "OceanBase"+ display_name: "OceanBase (Oracle Mode)"+ versions:+ - version: "4"+ status: "RECOMMENDED"++types:+ - name: "NUMBER"+ category: "DECIMAL"+ has_precision: true+ - name: "FLOAT"+ category: "FLOAT"+ - name: "BINARY_FLOAT"+ category: "FLOAT"+ - name: "BINARY_DOUBLE"+ category: "FLOAT"+ - name: "VARCHAR2"+ category: "STRING"+ has_length: true+ max_precision: 32767+ - name: "CHAR"+ category: "STRING"+ has_length: true+ max_precision: 2000+ - name: "CLOB"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "RAW"+ category: "BINARY"+ has_length: true+ - name: "DATE"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMP WITH TIME ZONE"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "INTERVAL YEAR TO MONTH"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "INTERVAL DAY TO SECOND"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "ROWID"+ category: "SYSTEM"+ semantic_fidelity_base: 0.1+ - name: "BINARY"+ category: "BINARY"+ - name: "JSON"+ category: "JSON"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ templates:+ add_column: "ALTER TABLE {table} ADD ({column} {type})"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {type})"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE {table} CASCADE CONSTRAINTS"+ create_index: "CREATE INDEX {name} ON {table} ({columns})"+ drop_index: "DROP INDEX {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD ({column} {original_type})"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {original_type})"+ create_table: "DROP TABLE {table} CASCADE CONSTRAINTS"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 4096+ max_indexes_per_table: 128+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 128+ supports_full_text_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_json_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}' ORDER BY COLUMN_ID"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT INDEX_NAME, COLUMN_NAME FROM ALL_IND_COLUMNS WHERE TABLE_OWNER = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT a.CONSTRAINT_NAME, a.COLUMN_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}' AND c.TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT TRIGGER_NAME, TRIGGER_TYPE, TRIGGERING_EVENT FROM ALL_TRIGGERS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT a.TABLE_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/opengauss.yaml b/plugins/dialects/opengauss.yamlnew file mode 100644index 0000000000..e1bfa56dba--- /dev/null+++ b/plugins/dialects/opengauss.yaml@@ -0,0 +1,142 @@+dialect:+ name: "openGauss"+ display_name: "openGauss"+ versions:+ - version: "6.0"+ status: "RECOMMENDED"+ - version: "5.0"+ status: "COMPATIBLE"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "INT4"]+ - name: "BIGINT"+ category: "INTEGER"+ aliases: ["INT8"]+ - name: "TINYINT"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ aliases: ["FLOAT4"]+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ aliases: ["FLOAT8"]+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "CLOB"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMPTZ"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "UUID"+ category: "UUID"+ - name: "JSON"+ category: "JSON"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ alter_primary_key: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ create_or_replace: true+ transactional_ddl: true+ temporary_table: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {original_type}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 63+ supports_partitioning: true+ supports_deferrable_constraints: true+ supports_json_type: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"++pre_execution_checks:+ - name: "lock_timeout"+ sql: "SET lock_timeout = '3s'"diff --git a/plugins/dialects/oracle.yaml b/plugins/dialects/oracle.yamlnew file mode 100644index 0000000000..eb8473d75c--- /dev/null+++ b/plugins/dialects/oracle.yaml@@ -0,0 +1,199 @@+dialect:+ name: "Oracle"+ display_name: "Oracle"+ versions:+ - version: "21c"+ status: "RECOMMENDED"+ - version: "19c"+ status: "COMPATIBLE"++types:+ - name: "NUMBER"+ category: "DECIMAL"+ has_precision: true+ - name: "FLOAT"+ category: "FLOAT"+ - name: "BINARY_FLOAT"+ category: "FLOAT"+ - name: "BINARY_DOUBLE"+ category: "FLOAT"+ - name: "VARCHAR2"+ category: "STRING"+ has_length: true+ max_precision: 4000+ - name: "NVARCHAR2"+ category: "STRING"+ has_length: true+ max_precision: 2000+ - name: "CHAR"+ category: "STRING"+ has_length: true+ max_precision: 2000+ - name: "NCHAR"+ category: "STRING"+ has_length: true+ max_precision: 1000+ - name: "CLOB"+ category: "STRING"+ semantic_fidelity_base: 0.9+ - name: "NCLOB"+ category: "STRING"+ semantic_fidelity_base: 0.9+ - name: "BLOB"+ category: "BINARY"+ - name: "RAW"+ category: "BINARY"+ has_length: true+ - name: "LONG"+ category: "STRING"+ semantic_fidelity_base: 0.5+ - name: "LONG RAW"+ category: "BINARY"+ semantic_fidelity_base: 0.5+ - name: "DATE"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMP WITH TIME ZONE"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "INTERVAL YEAR TO MONTH"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "INTERVAL DAY TO SECOND"+ category: "INTERVAL"+ semantic_fidelity_base: 0.5+ - name: "ROWID"+ category: "SYSTEM"+ semantic_fidelity_base: 0.1+ - name: "UROWID"+ category: "SYSTEM"+ semantic_fidelity_base: 0.1+ - name: "XMLTYPE"+ category: "XML"+ semantic_fidelity_base: 0.5+ - name: "SDO_GEOMETRY"+ category: "SPATIAL"+ semantic_fidelity_base: 0.6++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD ({column} {type})"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {type})"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE {table} CASCADE CONSTRAINTS"+ create_index: "CREATE INDEX {name} ON {table} ({columns})"+ drop_index: "DROP INDEX {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD ({column} {original_type})"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {original_type})"+ create_table: "DROP TABLE {table} CASCADE CONSTRAINTS"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1000+ max_indexes_per_table: 100+ max_query_size_bytes: 65536+ max_foreign_key_name_length: 30+ supports_full_text_index: true+ supports_spatial_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_deferrable_constraints: true+ supports_json_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 30++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}' ORDER BY COLUMN_ID"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT INDEX_NAME, COLUMN_NAME FROM ALL_IND_COLUMNS WHERE TABLE_OWNER = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT a.CONSTRAINT_NAME, a.COLUMN_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}' AND c.TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT TRIGGER_NAME, TRIGGER_TYPE, TRIGGERING_EVENT, TRIGGER_BODY FROM ALL_TRIGGERS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}'"+ performance_profile: "MEDIUM"+ list_functions:+ sql: "SELECT OBJECT_NAME, OBJECT_TYPE FROM ALL_OBJECTS WHERE OWNER = '{schema}' AND OBJECT_TYPE = 'FUNCTION'"+ performance_profile: "HEAVY"+ list_sequences:+ sql: "SELECT SEQUENCE_NAME FROM ALL_SEQUENCES WHERE SEQUENCE_OWNER = '{schema}'"+ performance_profile: "LIGHT"+ dependencies:+ sql: "SELECT a.TABLE_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/postgresql.yaml b/plugins/dialects/postgresql.yamlnew file mode 100644index 0000000000..c388598e35--- /dev/null+++ b/plugins/dialects/postgresql.yaml@@ -0,0 +1,245 @@+dialect:+ name: "PostgreSQL"+ display_name: "PostgreSQL"+ versions:+ - version: "16"+ status: "RECOMMENDED"+ - version: "15"+ status: "COMPATIBLE"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ precision_range: [-32768, 32767]+ aliases: ["INT2"]+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "INT4"]+ - name: "BIGINT"+ category: "INTEGER"+ aliases: ["INT8"]+ - name: "SMALLSERIAL"+ category: "INTEGER"+ - name: "SERIAL"+ category: "INTEGER"+ - name: "BIGSERIAL"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ aliases: ["FLOAT4"]+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ aliases: ["FLOAT8"]+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL"]+ - name: "MONEY"+ category: "DECIMAL"+ semantic_fidelity_base: 0.8+ - name: "CHARACTER VARYING"+ category: "STRING"+ has_length: true+ aliases: ["VARCHAR"]+ - name: "CHARACTER"+ category: "STRING"+ has_length: true+ aliases: ["CHAR"]+ - name: "TEXT"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ aliases: ["BOOL"]+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMPTZ"+ category: "DATETIME"+ aliases: ["TIMESTAMP WITH TIME ZONE"]+ semantic_fidelity_base: 0.9+ - name: "INTERVAL"+ category: "INTERVAL"+ semantic_fidelity_base: 0.7+ - name: "UUID"+ category: "UUID"+ - name: "JSON"+ category: "JSON"+ - name: "JSONB"+ category: "JSON"+ semantic_fidelity_base: 0.9+ - name: "XML"+ category: "XML"+ semantic_fidelity_base: 0.5+ - name: "INTEGER[]"+ category: "ARRAY"+ semantic_fidelity_base: 0.6+ - name: "TEXT[]"+ category: "ARRAY"+ semantic_fidelity_base: 0.6+ - name: "CIDR"+ category: "NETWORK"+ semantic_fidelity_base: 0.3+ - name: "INET"+ category: "NETWORK"+ semantic_fidelity_base: 0.4+ - name: "MACADDR"+ category: "NETWORK"+ semantic_fidelity_base: 0.3+ - name: "POINT"+ category: "SPATIAL"+ - name: "GEOMETRY"+ category: "SPATIAL"+ - name: "GEOGRAPHY"+ category: "SPATIAL"+ - name: "TSVECTOR"+ category: "FULLTEXT"+ semantic_fidelity_base: 0.3+ - name: "OID"+ category: "SYSTEM"+ semantic_fidelity_base: 0.2+ - name: "ENUM"+ category: "ENUM"+ semantic_fidelity_base: 0.8++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ index_include: true+ index_filter: true+ index_comment: true+ alter_primary_key: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ create_or_replace: true+ transactional_ddl: true+ temporary_table: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX IF NOT EXISTS {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 63+ supports_full_text_index: true+ supports_spatial_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_deferrable_constraints: true+ supports_array_type: true+ supports_json_type: true+ supports_enum_type: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT indexname, indexdef FROM pg_catalog.pg_indexes WHERE schemaname = '{schema}' AND tablename = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT tc.constraint_name, kcu.column_name, ccu.table_name AS ref_table, ccu.column_name AS ref_column FROM information_schema.table_constraints tc JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}' AND tc.table_name = '{table}'"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT trigger_name, event_manipulation, action_timing, action_statement FROM information_schema.triggers WHERE event_object_schema = '{schema}' AND event_object_table = '{table}'"+ performance_profile: "MEDIUM"+ list_functions:+ sql: "SELECT routine_name, routine_type, data_type, routine_definition FROM information_schema.routines WHERE routine_schema = '{schema}' AND routine_type = 'FUNCTION'"+ performance_profile: "HEAVY"+ list_sequences:+ sql: "SELECT sequence_name FROM information_schema.sequences WHERE sequence_schema = '{schema}'"+ performance_profile: "LIGHT"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 3+ performance_profile: "HEAVY"++pre_execution_checks:+ - name: "lock_timeout"+ sql: "SET lock_timeout = '3s'"+ - name: "statement_timeout"+ sql: "SET statement_timeout = '30s'"diff --git a/plugins/dialects/questdb.yaml b/plugins/dialects/questdb.yamlnew file mode 100644index 0000000000..97f105fb28--- /dev/null+++ b/plugins/dialects/questdb.yaml@@ -0,0 +1,114 @@+dialect:+ name: "QuestDB"+ display_name: "QuestDB"+ versions:+ - version: "8"+ status: "RECOMMENDED"++types:+ - name: "BYTE"+ category: "INTEGER"+ - name: "SHORT"+ category: "INTEGER"+ aliases: ["SMALLINT"]+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "LONG"+ category: "INTEGER"+ aliases: ["BIGINT"]+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "STRING"+ category: "STRING"+ aliases: ["VARCHAR"]+ - name: "SYMBOL"+ category: "STRING"+ semantic_fidelity_base: 0.8+ - name: "CHAR"+ category: "STRING"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "BINARY"+ category: "BINARY"+ - name: "UUID"+ category: "UUID"+ - name: "LONG256"+ category: "INTEGER"+ semantic_fidelity_base: 0.4+ - name: "GEOHASH"+ category: "SPATIAL"+ semantic_fidelity_base: 0.3+ - name: "IPv4"+ category: "NETWORK"+ semantic_fidelity_base: 0.3++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: false+ drop_index: false+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ max_columns_per_table: 1024+ max_query_size_bytes: 65536+ supports_partitioning: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 256++metadata_queries:+ list_tables:+ sql: "SELECT name FROM tables()"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column, type FROM table_columns('{table}')"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT name FROM tables()"+ depth_support: 0+ performance_profile: "LIGHT"diff --git a/plugins/dialects/redshift.yaml b/plugins/dialects/redshift.yamlnew file mode 100644index 0000000000..692f60c87d--- /dev/null+++ b/plugins/dialects/redshift.yaml@@ -0,0 +1,112 @@+dialect:+ name: "Redshift"+ display_name: "Amazon Redshift"+ versions:+ - version: "1.0"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "INT4"]+ - name: "BIGINT"+ category: "INTEGER"+ aliases: ["INT8"]+ - name: "REAL"+ category: "FLOAT"+ aliases: ["FLOAT4"]+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ aliases: ["FLOAT8"]+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 65535+ - name: "CHAR"+ category: "STRING"+ has_length: true+ max_precision: 4096+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMPTZ"+ category: "DATETIME"+ - name: "SUPER"+ category: "JSON"+ semantic_fidelity_base: 0.5++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ transactional_ddl: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ supports_partitioning: true+ supports_table_sampling: true+ supports_json_type: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 127++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/rqlite.yaml b/plugins/dialects/rqlite.yamlnew file mode 100644index 0000000000..5019956df8--- /dev/null+++ b/plugins/dialects/rqlite.yaml@@ -0,0 +1,76 @@+dialect:+ name: "Rqlite"+ display_name: "rqlite"+ versions:+ - version: "8"+ status: "RECOMMENDED"++types:+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "REAL"+ category: "FLOAT"+ - name: "TEXT"+ category: "STRING"+ aliases: ["VARCHAR"]+ - name: "BLOB"+ category: "BINARY"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ create_index: true+ drop_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ max_columns_per_table: 2000+ max_indexes_per_table: 200+ max_foreign_key_name_length: 255+ supports_full_text_index: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 255++metadata_queries:+ list_tables:+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "PRAGMA table_info('{table}')"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "PRAGMA foreign_key_list('{table}')"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/sqlite.yaml b/plugins/dialects/sqlite.yamlnew file mode 100644index 0000000000..0b9a095d5e--- /dev/null+++ b/plugins/dialects/sqlite.yaml@@ -0,0 +1,127 @@+dialect:+ name: "SQLite"+ display_name: "SQLite"+ versions:+ - version: "3"+ status: "RECOMMENDED"++types:+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT", "TINYINT", "SMALLINT", "MEDIUMINT", "BIGINT"]+ - name: "REAL"+ category: "FLOAT"+ aliases: ["FLOAT", "DOUBLE", "DOUBLE PRECISION"]+ - name: "TEXT"+ category: "STRING"+ aliases: ["VARCHAR", "CHAR", "CHARACTER", "CLOB", "NCHAR", "NVARCHAR"]+ - name: "BLOB"+ category: "BINARY"+ aliases: ["NONE"]+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ aliases: ["DECIMAL", "BOOLEAN", "DATE", "DATETIME"]+ semantic_fidelity_base: 0.5+ - name: "NULL"+ category: "NULL"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_filter: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ if_not_exists: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX IF NOT EXISTS {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ drop_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "NON_BLOCKING"+ cost: "LOW"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "SAFE"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ max_columns_per_table: 2000+ max_indexes_per_table: 200+ max_foreign_key_name_length: 255+ supports_full_text_index: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 255++metadata_queries:+ list_tables:+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "PRAGMA table_info('{table}')"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "PRAGMA index_list('{table}')"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "PRAGMA foreign_key_list('{table}')"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT name, sql FROM sqlite_master WHERE type = 'trigger' AND tbl_name = '{table}'"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "PRAGMA foreign_key_list('{table}')"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/sqlserver.yaml b/plugins/dialects/sqlserver.yamlnew file mode 100644index 0000000000..ac83b08342--- /dev/null+++ b/plugins/dialects/sqlserver.yaml@@ -0,0 +1,222 @@+dialect:+ name: "SQL Server"+ display_name: "SQL Server"+ versions:+ - version: "2022"+ status: "RECOMMENDED"+ - version: "2019"+ status: "COMPATIBLE"++types:+ - name: "TINYINT"+ category: "INTEGER"+ precision_range: [0, 255]+ - name: "SMALLINT"+ category: "INTEGER"+ precision_range: [-32768, 32767]+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "BIT"+ category: "BOOLEAN"+ semantic_fidelity_base: 0.9+ - name: "FLOAT"+ category: "FLOAT"+ - name: "REAL"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "MONEY"+ category: "DECIMAL"+ semantic_fidelity_base: 0.8+ - name: "SMALLMONEY"+ category: "DECIMAL"+ semantic_fidelity_base: 0.9+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 8000+ - name: "NVARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 4000+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "NCHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ semantic_fidelity_base: 0.8+ - name: "NTEXT"+ category: "STRING"+ semantic_fidelity_base: 0.7+ - name: "VARBINARY"+ category: "BINARY"+ has_length: true+ - name: "IMAGE"+ category: "BINARY"+ semantic_fidelity_base: 0.8+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "DATETIME2"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "SMALLDATETIME"+ category: "DATETIME"+ semantic_fidelity_base: 0.9+ - name: "DATETIMEOFFSET"+ category: "DATETIME"+ semantic_fidelity_base: 0.8+ - name: "UNIQUEIDENTIFIER"+ category: "UUID"+ - name: "XML"+ category: "XML"+ semantic_fidelity_base: 0.5+ - name: "SQL_VARIANT"+ category: "VARIANT"+ semantic_fidelity_base: 0.2+ - name: "GEOMETRY"+ category: "SPATIAL"+ - name: "GEOGRAPHY"+ category: "SPATIAL"+ - name: "HIERARCHYID"+ category: "SYSTEM"+ semantic_fidelity_base: 0.1++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ index_type: true+ index_include: true+ index_filter: true+ index_comment: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_trigger: true+ drop_trigger: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ transactional_ddl: true+ identity_columns: true+ templates:+ add_column: "ALTER TABLE {table} ADD {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "EXEC sp_rename '{table}.{old}', '{new}', 'COLUMN'"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} {type}"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX {name} ON {table} ({columns})"+ drop_index: "DROP INDEX IF EXISTS {name} ON {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD {column} {original_type}"+ rename_column: "EXEC sp_rename '{table}.{new}', '{old}', 'COLUMN'"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} {original_type}"+ create_table: "DROP TABLE IF EXISTS {table}"+ drop_table: "-- Restore from backup: {table}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"+ modify_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_column:+ level: "BLOCKING_LONG"+ cost: "MEDIUM"+ drop_table:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ truncate:+ level: "REQUIRES_GHOST"+ cost: "HIGH"+ create_index:+ level: "BLOCKING_SHORT"+ cost: "MEDIUM"+ drop_index:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"+ alter_type: "MODIFY"+ add_column: "SAFE"+ create_table: "SAFE"++structural_capabilities:+ supports_schemas: true+ supports_catalogs: true+ max_columns_per_table: 1024+ max_indexes_per_table: 999+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 128+ supports_full_text_index: true+ supports_spatial_index: true+ supports_partitioning: true+ supports_table_sampling: true+ supports_on_update_cascade: true+ supports_on_delete_set_null: true+ supports_json_type: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ list_indexes:+ sql: "SELECT i.name AS index_name, c.name AS column_name, i.is_unique, i.type_desc FROM sys.indexes i JOIN sys.index_columns ic ON i.object_id = ic.object_id AND i.index_id = ic.index_id JOIN sys.columns c ON ic.object_id = c.object_id AND ic.column_id = c.column_id WHERE OBJECT_NAME(i.object_id) = '{table}'"+ performance_profile: "MEDIUM"+ list_foreign_keys:+ sql: "SELECT fk.name AS constraint_name, c1.name AS column_name, OBJECT_NAME(fk.referenced_object_id) AS ref_table, c2.name AS ref_column FROM sys.foreign_keys fk JOIN sys.foreign_key_columns fkc ON fk.object_id = fkc.constraint_object_id JOIN sys.columns c1 ON fkc.parent_object_id = c1.object_id AND fkc.parent_column_id = c1.column_id JOIN sys.columns c2 ON fkc.referenced_object_id = c2.object_id AND fkc.referenced_column_id = c2.column_id WHERE OBJECT_NAME(fk.parent_object_id) = '{table}'"+ performance_profile: "MEDIUM"+ list_triggers:+ sql: "SELECT name, OBJECT_DEFINITION(object_id) AS definition FROM sys.triggers WHERE parent_id = OBJECT_ID('{table}')"+ performance_profile: "MEDIUM"+ list_functions:+ sql: "SELECT name, OBJECT_DEFINITION(object_id) AS definition FROM sys.objects WHERE type IN ('FN', 'IF', 'TF') AND SCHEMA_NAME(schema_id) = '{schema}'"+ performance_profile: "HEAVY"+ dependencies:+ sql: "SELECT OBJECT_NAME(fk.parent_object_id) AS table_name, OBJECT_NAME(fk.referenced_object_id) AS ref_table FROM sys.foreign_keys fk"+ depth_support: 2+ performance_profile: "HEAVY"++pre_execution_checks:+ - name: "lock_timeout"+ sql: "SET LOCK_TIMEOUT 3000"diff --git a/plugins/dialects/starrocks.yaml b/plugins/dialects/starrocks.yamlnew file mode 100644index 0000000000..2d1ccb6a2a--- /dev/null+++ b/plugins/dialects/starrocks.yaml@@ -0,0 +1,122 @@+dialect:+ name: "StarRocks"+ display_name: "StarRocks"+ versions:+ - version: "3"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ - name: "BIGINT"+ category: "INTEGER"+ - name: "LARGEINT"+ category: "INTEGER"+ semantic_fidelity_base: 0.6+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 1048576+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "STRING"+ category: "STRING"+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "ARRAY"+ category: "ARRAY"+ semantic_fidelity_base: 0.5+ - name: "JSON"+ category: "JSON"+ - name: "MAP"+ category: "MAP"+ semantic_fidelity_base: 0.4+ - name: "STRUCT"+ category: "STRUCT"+ semantic_fidelity_base: 0.3+ - name: "BITMAP"+ category: "BITMAP"+ semantic_fidelity_base: 0.2+ - name: "HLL"+ category: "HLL"+ semantic_fidelity_base: 0.1++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ create_index: true+ drop_index: true+ rebuild_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"+ create_index: "CREATE INDEX {name} ON {table} ({columns})"+ drop_index: "DROP INDEX {name} ON {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {original_type}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 4096+ max_indexes_per_table: 64+ max_query_size_bytes: 16777216+ supports_full_text_index: true+ supports_partitioning: true+ supports_json_type: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/sundb.yaml b/plugins/dialects/sundb.yamlnew file mode 100644index 0000000000..0e0357a9e3--- /dev/null+++ b/plugins/dialects/sundb.yaml@@ -0,0 +1,110 @@+dialect:+ name: "SunDB"+ display_name: "SunDB"+ versions:+ - version: "3"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "MEDIUMINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 65535+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "DATETIME"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "JSON"+ category: "JSON"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ grant_revoke: true+ if_not_exists: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY COLUMN {column} {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"+ drop_column: "DANGEROUS"++structural_capabilities:+ max_columns_per_table: 4096+ max_indexes_per_table: 64+ max_query_size_bytes: 16777216+ max_foreign_key_name_length: 64+ supports_full_text_index: true+ supports_partitioning: true+ supports_json_type: true++identifier_rules:+ quote_char: "`"+ case_sensitive: false+ max_length: 64++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = '{schema}' AND TABLE_TYPE = 'BASE TABLE'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, IS_NULLABLE, COLUMN_DEFAULT FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '{schema}' AND TABLE_NAME = '{table}' ORDER BY ORDINAL_POSITION"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME, REFERENCED_TABLE_NAME FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE WHERE TABLE_SCHEMA = '{schema}' AND REFERENCED_TABLE_NAME IS NOT NULL"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/turso.yaml b/plugins/dialects/turso.yamlnew file mode 100644index 0000000000..131b899f02--- /dev/null+++ b/plugins/dialects/turso.yaml@@ -0,0 +1,76 @@+dialect:+ name: "Turso"+ display_name: "Turso (libSQL)"+ versions:+ - version: "1"+ status: "RECOMMENDED"++types:+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "REAL"+ category: "FLOAT"+ - name: "TEXT"+ category: "STRING"+ aliases: ["VARCHAR"]+ - name: "BLOB"+ category: "BINARY"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ create_index: true+ drop_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ if_not_exists: true+ auto_increment: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ max_columns_per_table: 2000+ max_indexes_per_table: 200+ max_foreign_key_name_length: 255+ supports_full_text_index: true++identifier_rules:+ quote_char: '"'+ case_sensitive: false+ max_length: 255++metadata_queries:+ list_tables:+ sql: "SELECT name FROM sqlite_master WHERE type = 'table' AND name NOT LIKE 'sqlite_%'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "PRAGMA table_info('{table}')"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "PRAGMA foreign_key_list('{table}')"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/vastbase.yaml b/plugins/dialects/vastbase.yamlnew file mode 100644index 0000000000..1865eb90ca--- /dev/null+++ b/plugins/dialects/vastbase.yaml@@ -0,0 +1,104 @@+dialect:+ name: "Vastbase"+ display_name: "Vastbase"+ versions:+ - version: "G100"+ status: "RECOMMENDED"++types:+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "REAL"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "TEXT"+ category: "STRING"+ - name: "BYTEA"+ category: "BINARY"+ - name: "DATE"+ category: "DATE"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "BOOLEAN"+ category: "BOOLEAN"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ alter_owner: true+ if_not_exists: true+ transactional_ddl: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "NON_BLOCKING"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 63+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 63++metadata_queries:+ list_tables:+ sql: "SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM information_schema.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT tc.table_name, ccu.table_name AS ref_table FROM information_schema.table_constraints tc JOIN information_schema.constraint_column_usage ccu ON tc.constraint_name = ccu.constraint_name WHERE tc.constraint_type = 'FOREIGN KEY' AND tc.table_schema = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/dialects/vertica.yaml b/plugins/dialects/vertica.yamlnew file mode 100644index 0000000000..7b3e4333b8--- /dev/null+++ b/plugins/dialects/vertica.yaml@@ -0,0 +1,113 @@+dialect:+ name: "Vertica"+ display_name: "Vertica"+ versions:+ - version: "24"+ status: "RECOMMENDED"++types:+ - name: "INTEGER"+ category: "INTEGER"+ aliases: ["INT"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "NUMERIC"+ category: "DECIMAL"+ has_precision: true+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 65000+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "BOOLEAN"+ category: "BOOLEAN"+ - name: "DATE"+ category: "DATE"+ - name: "TIME"+ category: "TIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "TIMESTAMPTZ"+ category: "DATETIME"+ - name: "INTERVAL"+ category: "INTERVAL"+ - name: "BINARY"+ category: "BINARY"+ - name: "VARBINARY"+ category: "BINARY"+ - name: "UUID"+ category: "UUID"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ foreign_key: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ grant_revoke: true+ if_not_exists: true+ temporary_table: true+ transactional_ddl: true+ templates:+ add_column: "ALTER TABLE {table} ADD COLUMN {column} {type}"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} ALTER COLUMN {column} SET DATA TYPE {type}"+ create_table: "CREATE TABLE IF NOT EXISTS {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD COLUMN {column} {original_type}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ drop_schema: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1600+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ supports_partitioning: true+ supports_table_sampling: true+ supports_uuid_type: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT table_name FROM v_catalog.tables WHERE table_schema = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT column_name, data_type, is_nullable, column_default FROM v_catalog.columns WHERE table_schema = '{schema}' AND table_name = '{table}' ORDER BY ordinal_position"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT table_name FROM v_catalog.tables WHERE table_schema = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/xugu.yaml b/plugins/dialects/xugu.yamlnew file mode 100644index 0000000000..b7fdd5d269--- /dev/null+++ b/plugins/dialects/xugu.yaml@@ -0,0 +1,107 @@+dialect:+ name: "Xugu"+ display_name: "虚谷数据库 (XuguDB)"+ versions:+ - version: "12"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE"+ category: "FLOAT"+ - name: "DECIMAL"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 4000+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "CLOB"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "DATE"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "BOOLEAN"+ category: "BOOLEAN"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ grant_revoke: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD ({column} {type})"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {type})"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD ({column} {original_type})"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1000+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 128+ supports_full_text_index: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}' ORDER BY COLUMN_ID"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '{schema}'"+ depth_support: 1+ performance_profile: "MEDIUM"diff --git a/plugins/dialects/yashandb.yaml b/plugins/dialects/yashandb.yamlnew file mode 100644index 0000000000..c8d61c8545--- /dev/null+++ b/plugins/dialects/yashandb.yaml@@ -0,0 +1,112 @@+dialect:+ name: "YashanDB"+ display_name: "崖山数据库 (YashanDB)"+ versions:+ - version: "23"+ status: "RECOMMENDED"++types:+ - name: "TINYINT"+ category: "INTEGER"+ - name: "SMALLINT"+ category: "INTEGER"+ - name: "INT"+ category: "INTEGER"+ aliases: ["INTEGER"]+ - name: "BIGINT"+ category: "INTEGER"+ - name: "FLOAT"+ category: "FLOAT"+ - name: "DOUBLE PRECISION"+ category: "FLOAT"+ - name: "NUMBER"+ category: "DECIMAL"+ has_precision: true+ aliases: ["NUMERIC", "DECIMAL"]+ - name: "VARCHAR"+ category: "STRING"+ has_length: true+ max_precision: 8000+ - name: "VARCHAR2"+ category: "STRING"+ has_length: true+ - name: "CHAR"+ category: "STRING"+ has_length: true+ - name: "CLOB"+ category: "STRING"+ - name: "BLOB"+ category: "BINARY"+ - name: "DATE"+ category: "DATETIME"+ - name: "TIMESTAMP"+ category: "DATETIME"+ - name: "BOOLEAN"+ category: "BOOLEAN"++ddl_capabilities:+ add_column: true+ drop_column: true+ rename_column: true+ alter_column_type: true+ comment: true+ create_index: true+ drop_index: true+ rebuild_index: true+ create_table: true+ drop_table: true+ truncate_table: true+ create_function: true+ drop_function: true+ create_sequence: true+ drop_sequence: true+ grant_revoke: true+ if_not_exists: true+ templates:+ add_column: "ALTER TABLE {table} ADD ({column} {type})"+ drop_column: "ALTER TABLE {table} DROP COLUMN {column}"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {old} TO {new}"+ modify_column: "ALTER TABLE {table} MODIFY ({column} {type})"+ create_table: "CREATE TABLE {table} ({columns})"+ drop_table: "DROP TABLE IF EXISTS {table}"++rollback_templates:+ add_column: "ALTER TABLE {table} DROP COLUMN {column}"+ drop_column: "ALTER TABLE {table} ADD ({column} {original_type})"+ rename_column: "ALTER TABLE {table} RENAME COLUMN {new} TO {old}"++online_safety:+ add_column:+ level: "BLOCKING_SHORT"+ cost: "LOW"++destruction_level:+ drop_table: "FATAL"+ truncate: "DANGEROUS"++structural_capabilities:+ supports_schemas: true+ max_columns_per_table: 1000+ max_indexes_per_table: 100+ max_query_size_bytes: 268435456+ max_foreign_key_name_length: 128+ supports_full_text_index: true+ supports_partitioning: true+ supports_sequences: true++identifier_rules:+ quote_char: '"'+ case_sensitive: true+ max_length: 128++metadata_queries:+ list_tables:+ sql: "SELECT TABLE_NAME FROM ALL_TABLES WHERE OWNER = '{schema}'"+ performance_profile: "LIGHT"+ list_columns:+ sql: "SELECT COLUMN_NAME, DATA_TYPE, NULLABLE, DATA_DEFAULT FROM ALL_TAB_COLUMNS WHERE OWNER = '{schema}' AND TABLE_NAME = '{table}' ORDER BY COLUMN_ID"+ performance_profile: "MEDIUM"+ dependencies:+ sql: "SELECT a.TABLE_NAME, c_pk.TABLE_NAME AS R_TABLE_NAME FROM ALL_CONS_COLUMNS a JOIN ALL_CONSTRAINTS c ON a.CONSTRAINT_NAME = c.CONSTRAINT_NAME JOIN ALL_CONSTRAINTS c_pk ON c.R_CONSTRAINT_NAME = c_pk.CONSTRAINT_NAME WHERE c.CONSTRAINT_TYPE = 'R' AND a.OWNER = '{schema}'"+ depth_support: 2+ performance_profile: "HEAVY"diff --git a/plugins/mappings/rules/dml_clean_rules.yaml b/plugins/mappings/rules/dml_clean_rules.yamlnew file mode 100644index 0000000000..35fc320dae--- /dev/null+++ b/plugins/mappings/rules/dml_clean_rules.yaml@@ -0,0 +1,128 @@+# DML Clean Rules — pre-transform SQL templates for lossy type mappings+# Each rule fires when fidelity_score < max_fidelity for the source→target pair.+# The {table} and {column} placeholders are substituted at generation time.++rules:+ - name: "bigint_to_int"+ source_type: "BIGINT"+ target_type: "INT"+ max_fidelity: 0.8+ pre_transform_sql: "UPDATE {table} SET {column} = NULL WHERE {column} > 2147483647"+ description: "Truncate BIGINT values exceeding INT range"++ - name: "bigint_to_int_numeric"+ source_type: "BIGINT"+ target_type: "INTEGER"+ max_fidelity: 0.8+ pre_transform_sql: "UPDATE {table} SET {column} = NULL WHERE {column} > 2147483647"++ - name: "bigint_to_smallint"+ source_type: "BIGINT"+ target_type: "SMALLINT"+ max_fidelity: 0.6+ pre_transform_sql: "UPDATE {table} SET {column} = NULL WHERE {column} > 32767"+ description: "Truncate BIGINT values exceeding SMALLINT range"++ - name: "bigint_to_tinyint"+ source_type: "BIGINT"+ target_type: "TINYINT"+ max_fidelity: 0.5+ pre_transform_sql: "UPDATE {table} SET {column} = NULL WHERE {column} > 127"++ - name: "int_to_smallint"+ source_type: "INT"+ target_type: "SMALLINT"+ max_fidelity: 0.7+ pre_transform_sql: "UPDATE {table} SET {column} = NULL WHERE {column} > 32767"++ - name: "int_to_tinyint"+ source_type: "INT"+ target_type: "TINYINT"+ max_fidelity: 0.6+ pre_transform_sql: "UPDATE {table} SET {column} = NULL WHERE {column} > 127"++ - name: "varchar_truncate_255"+ source_type: "VARCHAR"+ target_type: "VARCHAR"+ max_fidelity: 0.7+ pre_transform_sql: "UPDATE {table} SET {column} = LEFT({column}, 255) WHERE LENGTH({column}) > 255"+ description: "Truncate VARCHAR values exceeding target max length (generic 255)"++ - name: "varchar_to_text"+ source_type: "VARCHAR"+ target_type: "TEXT"+ max_fidelity: 0.9+ # No DML needed — widening to TEXT is safe (fidelity >= 0.9)++ - name: "float_to_int"+ source_type: "FLOAT"+ target_type: "INT"+ max_fidelity: 0.6+ pre_transform_sql: "UPDATE {table} SET {column} = ROUND({column}) WHERE {column} IS NOT NULL"+ description: "Round floating-point values before integer cast"++ - name: "timestamp_with_tz_to_timestamp"+ source_type: "TIMESTAMPTZ"+ target_type: "TIMESTAMP"+ max_fidelity: 0.8+ pre_transform_sql: "UPDATE {table} SET {column} = {column} AT TIME ZONE 'UTC'"+ description: "Convert to UTC before stripping timezone"++ - name: "timestamptz_to_datetime"+ source_type: "TIMESTAMPTZ"+ target_type: "DATETIME"+ max_fidelity: 0.7+ pre_transform_sql: "UPDATE {table} SET {column} = {column} AT TIME ZONE 'UTC'"++ - name: "bool_to_tinyint"+ source_type: "BOOLEAN"+ target_type: "TINYINT"+ max_fidelity: 0.8+ pre_transform_sql: "UPDATE {table} SET {column} = CASE WHEN {column} = true THEN 1 ELSE 0 END"+ description: "Convert BOOLEAN to TINYINT(1)"++ - name: "uuid_to_char"+ source_type: "UUID"+ target_type: "CHAR"+ max_fidelity: 0.7+ pre_transform_sql: "UPDATE {table} SET {column} = CAST({column} AS VARCHAR(36))"+ description: "Cast UUID to CHAR(36) before migration"++ - name: "decimal_to_int"+ source_type: "DECIMAL"+ target_type: "INT"+ max_fidelity: 0.6+ pre_transform_sql: "UPDATE {table} SET {column} = ROUND({column}) WHERE {column} IS NOT NULL"++ - name: "decimal_to_float"+ source_type: "DECIMAL"+ target_type: "FLOAT"+ max_fidelity: 0.8+ pre_transform_sql: "UPDATE {table} SET {column} = CAST({column} AS DOUBLE) WHERE {column} IS NOT NULL"++ - name: "json_to_text"+ source_type: "JSON"+ target_type: "TEXT"+ max_fidelity: 0.5+ pre_transform_sql: "UPDATE {table} SET {column} = CAST({column} AS VARCHAR) WHERE {column} IS NOT NULL"+ description: "JSON→TEXT loses structure — store as serialized string"++ - name: "json_to_varchar"+ source_type: "JSON"+ target_type: "VARCHAR"+ max_fidelity: 0.5+ pre_transform_sql: "UPDATE {table} SET {column} = CAST({column} AS VARCHAR) WHERE {column} IS NOT NULL"++ - name: "enum_to_varchar"+ source_type: "ENUM"+ target_type: "VARCHAR"+ max_fidelity: 0.7+ pre_transform_sql: "UPDATE {table} SET {column} = CAST({column} AS CHAR) WHERE {column} IS NOT NULL"+ description: "ENUM→VARCHAR: explicit cast to string"++ - name: "text_to_varchar_truncate"+ source_type: "TEXT"+ target_type: "VARCHAR"+ max_fidelity: 0.6+ pre_transform_sql: "UPDATE {table} SET {column} = LEFT({column}, 65535) WHERE LENGTH({column}) > 65535"+ description: "Truncate TEXT exceeding VARCHAR max length"diff --git a/src-tauri/src/commands/config_cmd.rs b/src-tauri/src/commands/config_cmd.rsnew file mode 100644index 0000000000..7dddfc0d25--- /dev/null+++ b/src-tauri/src/commands/config_cmd.rs@@ -0,0 +1,24 @@+use dbx_core::config::{TraceEntry, TraceRingBuffer};++// ---- Trace commands ----++#[tauri::command]+#[allow(dead_code)]+pub fn trace_export_command(entries: Vec<TraceEntry>, capacity: Option<usize>) -> Result<String, String> {+ let cap = capacity.unwrap_or(1000);+ let mut buf = TraceRingBuffer::new(cap);+ for entry in entries {+ buf.push(entry);+ }+ buf.export_json()+}++#[tauri::command]+#[allow(dead_code)]+pub fn trace_stats_command(entries: Vec<TraceEntry>) -> dbx_core::config::TraceStats {+ let mut buf = TraceRingBuffer::new(entries.len().max(1));+ for entry in entries {+ buf.push(entry);+ }+ buf.stats()+}diff --git a/src-tauri/src/commands/dialect_cmd.rs b/src-tauri/src/commands/dialect_cmd.rsnew file mode 100644index 0000000000..0521c87774--- /dev/null+++ b/src-tauri/src/commands/dialect_cmd.rs@@ -0,0 +1,134 @@+use std::path::PathBuf;++use dbx_core::sql_dialect::{+ descriptor::DialectKind, dialect_check, dialect_check_all, dialect_yaml::DialectYaml, DialectInfo,+};++#[tauri::command]+#[allow(dead_code)]+pub fn dialect_check_command(kind: String) -> Result<DialectInfo, String> {+ let db_type = match kind.to_ascii_lowercase().as_str() {+ "mysql" => DialectKind::Mysql,+ "postgres" | "postgresql" => DialectKind::Postgres,+ "sqlite" => DialectKind::Sqlite,+ "duckdb" => DialectKind::DuckDb,+ "sqlserver" | "mssql" => DialectKind::SqlServer,+ "oracle" => DialectKind::Oracle,+ "h2" => DialectKind::H2,+ "clickhouse" => DialectKind::ClickHouse,+ "manticore" | "manticoresearch" => DialectKind::ManticoreSearch,+ "informix" => DialectKind::Informix,+ "questdb" => DialectKind::Questdb,+ _ => return Err(format!("Unknown dialect: {kind}")),+ };+ Ok(dialect_check(db_type))+}++#[tauri::command]+#[allow(dead_code)]+pub fn dialect_check_all_command() -> Vec<DialectInfo> {+ dialect_check_all()+}++#[derive(serde::Serialize)]+#[allow(dead_code)]+pub struct DialectExportResult {+ pub files_written: Vec<String>,+ pub errors: Vec<String>,+}++/// Export all hardcoded dialect descriptors to YAML files.+/// Writes to `plugins/dialects/<label>.yaml` for each core dialect.+#[tauri::command]+#[allow(dead_code)]+pub fn dialect_export_command(target_dir: Option<String>) -> DialectExportResult {+ let dir = target_dir.filter(|d| !d.is_empty()).unwrap_or_else(|| "plugins/dialects".to_string());+ let dir_path = PathBuf::from(&dir);++ if let Err(e) = std::fs::create_dir_all(&dir_path) {+ return DialectExportResult {+ files_written: vec![],+ errors: vec![format!("Cannot create directory {dir}: {e}")],+ };+ }++ let kinds = [+ DialectKind::Mysql,+ DialectKind::Postgres,+ DialectKind::Sqlite,+ DialectKind::DuckDb,+ DialectKind::SqlServer,+ DialectKind::Oracle,+ DialectKind::H2,+ DialectKind::ClickHouse,+ DialectKind::ManticoreSearch,+ DialectKind::Informix,+ DialectKind::Questdb,+ ];++ let mut files_written = Vec::new();+ let mut errors = Vec::new();++ for kind in kinds {+ let yaml = DialectYaml::from_descriptor(kind);+ let file_name = format!("{}.yaml", kind.label());+ let file_path = dir_path.join(&file_name);++ match yaml.to_yaml_string() {+ Ok(content) => match std::fs::write(&file_path, &content) {+ Ok(()) => files_written.push(file_path.display().to_string()),+ Err(e) => errors.push(format!("Failed to write {}: {e}", file_path.display())),+ },+ Err(e) => errors.push(format!("Failed to serialize {}: {e}", kind.label())),+ }+ }++ DialectExportResult { files_written, errors }+}++/// Initialize a new dialect YAML descriptor with minimal required fields.+/// This creates a skeleton YAML file at `plugins/dialects/<label>.yaml`.+#[tauri::command]+#[allow(dead_code)]+pub fn dialect_init_command(+ name: String,+ _display_name: Option<String>,+ quote_char: Option<String>,+ max_length: Option<u32>,+ target_dir: Option<String>,+) -> Result<String, String> {+ if name.trim().is_empty() {+ return Err("Dialect name is required".to_string());+ }++ let dir = target_dir.filter(|d| !d.is_empty()).unwrap_or_else(|| "plugins/dialects".to_string());+ let dir_path = PathBuf::from(&dir);+ std::fs::create_dir_all(&dir_path).map_err(|e| format!("Cannot create directory: {e}"))?;++ let label = name.to_ascii_lowercase().replace(' ', "_");+ let file_name = format!("dialect_{label}.yaml");+ let file_path = dir_path.join(&file_name);++ let quote = quote_char.unwrap_or_else(|| "\"".to_string());+ let max_len = max_length.unwrap_or(128);++ let content = format!(+ r#"dialect:+ name: "{name}"+ display_name: "{name}"+ versions: ""+identifier_rules:+ quote_char: "{quote}"+ max_length: {max_len}+"#,+ );++ std::fs::write(&file_path, &content).map_err(|e| format!("Failed to write {file_name}: {e}"))?;++ Ok(format!("Created dialect descriptor at {}", file_path.display()))+}++#[tauri::command]+pub async fn list_dialect_data_types(dialect_name: String) -> Vec<String> {+ dbx_core::sql_dialect::dialect_types::list_dialect_type_names(&dialect_name)+}diff --git a/src-tauri/src/commands/mod.rs b/src-tauri/src/commands/mod.rsindex 30fa03b198..3d77a3dcdf 100644--- a/src-tauri/src/commands/mod.rs+++ b/src-tauri/src/commands/mod.rs@@ -3,6 +3,7 @@ pub mod ai;pub mod ai_multi_config;pub mod app_settings;pub mod cloud_sync;+pub mod config_cmd;pub mod connection;#[allow(dead_code, unused_imports)]mod connection_secrets;@@ -10,6 +11,7 @@ pub mod csv_export;pub mod data_compare;pub mod database_export;pub mod deep_link;+pub mod dialect_cmd;pub mod document_cmd;pub mod etcd_cmd;pub mod external_db;diff --git a/src-tauri/src/commands/query.rs b/src-tauri/src/commands/query.rsindex 5617fbac88..300d7ea4d5 100644--- a/src-tauri/src/commands/query.rs+++ b/src-tauri/src/commands/query.rs@@ -241,6 +241,33 @@ pub async fn execute_in_transaction(.await}+/// Schema Diff deploy entrypoint (legacy command name kept for API compatibility).+///+/// Executes as one single-connection transaction via [`execute_schema_diff_deploy`].+/// On failure, status is `rolled_back` when DDL/DML atomicity is guaranteed for the+/// target, otherwise `mixed` with a best-effort `executed_count` (e.g. MySQL/Oracle DDL).+pub async fn execute_script_with_2pc_core(+ app: Arc<AppState>,+ connection_id: String,+ database: String,+ statements: Vec<String>,+ schema: Option<String>,+) -> dbx_core::query::SchemaDiffDeployResult {+ dbx_core::query::execute_schema_diff_deploy(&app, &connection_id, &database, &statements, schema.as_deref()).await+}++#[tauri::command]+pub async fn execute_script_with_2pc(+ state: State<'_, Arc<AppState>>,+ connection_id: String,+ database: String,+ statements: Vec<String>,+ schema: Option<String>,+) -> Result<dbx_core::query::SchemaDiffDeployResult, String> {+ let app: Arc<AppState> = (*state).clone();+ Ok(execute_script_with_2pc_core(app, connection_id, database, statements, schema).await)+}+#[tauri::command]pub async fn begin_manual_transaction(state: State<'_, Arc<AppState>>,@@ -676,3 +703,86 @@ pub async fn get_explain_info(pub fn build_create_user_sql(username: String, password: String, tablespace: String) -> Result<String, String> {Ok(dbx_core::db_admin_sql::build_create_user_sql(&username, &password, &tablespace))}++#[cfg(test)]+mod tests {+ use super::*;+ use dbx_core::storage::Storage;+ use std::sync::Arc;++ async fn test_app_state() -> Arc<AppState> {+ let dir = std::env::temp_dir().join(format!("dbx-query-test-{}", uuid::Uuid::new_v4()));+ std::fs::create_dir_all(&dir).unwrap();+ let storage = Storage::open(&dir.join("storage.db")).await.unwrap();+ Arc::new(AppState::new_with_plugin_dir(storage, dir.join("plugins")))+ }++ #[tokio::test]+ async fn execute_script_with_2pc_returns_structured_result() {+ let state = test_app_state().await;+ let result = execute_script_with_2pc_core(+ state,+ "conn-1".to_string(),+ "testdb".to_string(),+ vec!["SELECT 1".to_string()],+ None,+ )+ .await;++ assert!(!result.transaction_id.is_empty());+ assert!(!result.participants.is_empty());+ // No real connection: rolled_back with error, not silent auto-commit success.+ assert_eq!(result.status, "rolled_back");+ assert!(result.error.as_ref().is_some_and(|e| !e.is_empty()));+ assert_eq!(result.statement_count, 1);+ assert_eq!(result.executed_count, 0);+ }++ #[tokio::test]+ async fn execute_script_with_2pc_empty_statements_succeeds() {+ let state = test_app_state().await;+ let result =+ execute_script_with_2pc_core(state, "conn-empty".to_string(), "testdb".to_string(), vec![], None).await;++ assert_eq!(result.status, "committed");+ assert_eq!(result.statement_count, 0);+ assert_eq!(result.executed_count, 0);+ assert!(result.error.is_none());+ assert_eq!(result.participants.len(), 1);+ }++ #[tokio::test]+ async fn execute_script_with_2pc_comment_only_is_empty_success() {+ let state = test_app_state().await;+ let result = execute_script_with_2pc_core(+ state,+ "conn-comment".to_string(),+ "testdb".to_string(),+ vec!["-- WARNING: incomplete\n-- manual only".to_string()],+ None,+ )+ .await;++ assert_eq!(result.status, "committed");+ assert_eq!(result.statement_count, 0);+ assert!(result.error.is_none());+ }++ #[tokio::test]+ async fn execute_script_with_2pc_propagates_structured_failure_fields() {+ let state = test_app_state().await;+ let result = execute_script_with_2pc_core(+ state,+ "missing-conn".to_string(),+ "testdb".to_string(),+ vec!["CREATE TABLE t1 (id INT)".to_string(), "CREATE TABLE t2 (id INT)".to_string()],+ None,+ )+ .await;++ assert!(result.status == "rolled_back" || result.status == "mixed", "status={}", result.status);+ assert_eq!(result.statement_count, 2);+ assert!(result.error.as_ref().is_some_and(|e| !e.is_empty()));+ assert_eq!(result.executed_count, 0);+ }+}diff --git a/src-tauri/src/commands/schema_diff.rs b/src-tauri/src/commands/schema_diff.rsindex a2de22fb40..2f6e2c3893 100644--- a/src-tauri/src/commands/schema_diff.rs+++ b/src-tauri/src/commands/schema_diff.rs@@ -16,6 +16,8 @@ pub fn generate_schema_sync_sql(database_type: dbx_core::models::connection::DatabaseType,target_schema: Option<String>,cascade_delete: Option<bool>,+ source_dialect: Option<dbx_core::sql_dialect::descriptor::DialectKind>,+ field_mappings: Option<Vec<dbx_core::schema_diff::FieldMapping>>,) -> Result<String, String> {Ok(dbx_core::schema_diff::generate_schema_sync_sql(&diffs,@@ -26,5 +28,7 @@ pub fn generate_schema_sync_sql(database_type,target_schema.as_deref(),cascade_delete.unwrap_or(false),+ source_dialect,+ &field_mappings.unwrap_or_default(),))}diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex bb78886635..e8d37401fa 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -7,6 +7,8 @@ mod models;mod window_state_guard;use commands::connection::AppState;+use dbx_core::sql_dialect::dialect_loader::{register_core_dialects, DialectPluginLoader, DialectRegistry};+use dbx_core::sql_dialect::hot_reload::DialectHotReload;use dbx_core::storage::{maybe_import_user_data_db, DesktopIconTheme, DesktopSettings, Storage};use std::sync::atomic::{AtomicBool, Ordering};use std::sync::Arc;@@ -1218,6 +1220,29 @@ pub fn run() {apply_debug_log_level(desktop_settings.debug_logging_enabled);eprintln!("[STARTUP] storage ready in {:?}", t.elapsed());+ // Initialize core dialect registry and load external plugin dialects+ let dialect_init_start = Instant::now();+ register_core_dialects();+ let registry = DialectRegistry::global();+ let plugin_dirs = vec![data_dir.join("plugins").join("dialects")];+ let load_result = DialectPluginLoader::scan_and_load(registry, &plugin_dirs);+ eprintln!(+ "[STARTUP] dialect plugins loaded: {} success, {} errors, {} skipped in {:?}",+ load_result.loaded.len(),+ load_result.errors.len(),+ load_result.skipped.len(),+ dialect_init_start.elapsed()+ );++ // Start dialect YAML hot-reload watcher+ let watch_dirs = plugin_dirs.clone();+ tauri::async_runtime::spawn(async move {+ if let Err(e) = DialectHotReload::run_forever(watch_dirs, DialectRegistry::global()).await {+ log::error!("[STARTUP] dialect hot-reload watcher exited: {e}");+ }+ });+ eprintln!("[STARTUP] dialect hot-reload watcher started");+let default_agent_dir = data_dir_resolution.uses_custom_data_dir().then(|| data_dir.join("agents"));let (plugin_dir, agent_dir) = commands::app_settings::resolve_driver_store_dirs_from_settings(&desktop_settings,@@ -1427,6 +1452,7 @@ pub fn run() {commands::schema::list_available_extensions,commands::schema_diff::prepare_schema_diff,commands::schema_diff::generate_schema_sync_sql,+ commands::dialect_cmd::list_dialect_data_types,commands::schema_cache::save_schema_cache,commands::schema_cache::load_schema_cache,commands::schema_cache::delete_schema_cache_prefix,@@ -1444,6 +1470,7 @@ pub fn run() {commands::query::execute_batch,commands::query::execute_script,commands::query::execute_in_transaction,+ commands::query::execute_script_with_2pc,commands::query::begin_manual_transaction,commands::query::execute_in_manual_transaction,commands::query::commit_manual_transaction,