rust_store_core/dialect/mod.rs
1//! Mongo 方言 → 关系型 SQL 翻译层(纯逻辑,无 IO)
2//!
3//! 背景:core 按约定继续产出 **Mongo 命令 JSON**(`find`/`aggregate`/`countDocuments`/…)。
4//! 本模块提供一条**纯函数**翻译通道,把这些命令落成 MySQL / PostgreSQL / SQLite 各后端的
5//! 参数化 SQL 语句([`ir::SqlStmt`]),并负责把驱动返回的**平铺 JOIN 行**还原为嵌套 Mongo
6//! 文档([`row::restore_rows`])。
7//!
8//! 设计边界(对齐「用 MongoDB 方言,其他数据库适配」的要求):
9//! 1. [`translate::translate`] 只做 JSON → SQL 中间表示,完全不触数据库;Host 拿到
10//! `SqlStmt` 后自行绑定驱动。
11//! 2. 关系模型采用**严格关系范式**:标量字段落在单表,`object`/`array` 展平为附属表,
12//! 关系用 SQL JOIN 解析。
13//! 3. 无法安全翻译的组合输出 `_unsupported` 标志 + warning,**绝不生成错误 SQL**。
14//! 4. 平铺行 → 嵌套文档的还原与 introspection 行 → schemaJSON 的映射都是纯逻辑,四侧对拍可复现。
15
16pub mod filter;
17pub mod introspect;
18pub mod ir;
19pub mod overlay;
20pub mod row;
21pub mod select;
22pub mod translate;
23pub mod write;
24
25// 保持对外路径稳定:`crate::dialect::*` 直接可用(函数与其同名模块共存)
26pub use introspect::{introspect_to_schema_json, schema_def_from_rows};
27pub use overlay::merge_schema;
28pub use row::restore_rows_json;
29pub use translate::translate;
30
31use crate::schema::Schema;
32
33/// 标量字段 → 列名(本表列);object/array 展平字段跳过;点号路径按整串处理。
34///
35/// **读([`select`])与写([`write`])共用此唯一实现。** 两侧语义若各自漂移会产生
36/// 读写不对称(读得到的列写不进 / 写进去的列读不出),故收口到此,两侧只做薄包装。
37pub(crate) fn scalar_column(schema: &Schema, field: &str) -> Option<String> {
38 if field.contains('.') {
39 let (head, _) = field.split_once('.')?;
40 // 点号字段:若 head 是 object/array(其子字段展平到附属表)则跳过;否则按整串处理
41 let head_type = schema.fields.get(head).map(|f| f.field_type.as_str());
42 if matches!(head_type, Some("object") | Some("array")) {
43 return None;
44 }
45 return Some(field.to_string());
46 }
47 match schema.fields.get(field).map(|f| f.field_type.as_str()) {
48 Some("object") | Some("array") => None,
49 _ => Some(field.to_string()),
50 }
51}
52
53/// 字段 → 列引用(过滤 / 投影 / 回读用;object/array 走 JSON 单列)。
54///
55/// 与 [`scalar_column`] 的差异:`scalar_column` 只认标量列(object/array 返回 `None`,
56/// 供关系键解析、分组键等**必须标量**的场景);本函数在其基础上把 object/array 字段
57/// 展开为 JSON 列引用(见执行文档 §4.5 / 不足清单 #3):
58/// - 标量字段 → [`ColumnRef::Scalar`](调用方按别名限定 + 引号化);
59/// - object/array 整值 → [`ColumnRef::Json`](单列存 JSON 文本,读取时解析;`JsonKind` 区分
60/// 数组/对象,供 U1/U2 整值条件选择翻译方式);
61/// - object/array 的点号路径(U3 过滤 / U4 排序)→ [`ColumnRef::JsonPath`](提取表达式)。
62///
63/// 未声明字段返回 `None`(调用方据此显式报错,绝不静默)。
64pub(crate) fn field_column_ref(schema: &Schema, field: &str) -> Option<ColumnRef> {
65 if let Some((head, rest)) = field.split_once('.') {
66 let head_type = schema.fields.get(head).map(|f| f.field_type.as_str());
67 match head_type {
68 // U3/U4:object/array 点号路径 → JSON 提取(根列 head + 子路径 rest)
69 Some("object") | Some("array") => {
70 let path: Vec<String> = rest.split('.').map(String::from).collect();
71 Some(ColumnRef::JsonPath(head.to_string(), path))
72 }
73 // 点号字段的 head 非 object/array(如标量同名字段)→ 按整串列名处理(既有语义)
74 _ => Some(ColumnRef::Scalar(field.to_string())),
75 }
76 } else {
77 match schema.fields.get(field).map(|f| f.field_type.as_str()) {
78 Some("object") => Some(ColumnRef::Json(field.to_string(), JsonKind::Object)),
79 Some("array") => Some(ColumnRef::Json(field.to_string(), JsonKind::Array)),
80 // 已声明标量 / 未声明字段(与 `scalar_column` 宽松语义一致:按裸列名处理,
81 // 如物理主键 `_id` 不在 schema.fields 但恒为列)
82 _ => Some(ColumnRef::Scalar(field.to_string())),
83 }
84 }
85}
86
87/// JSON 整列的形态(`JsonKind`):决定 U1/U2 整值条件的翻译方式
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub enum JsonKind {
90 /// `object` 字段:整值条件按 JSON 结构等值比较(U2)
91 Object,
92 /// `array` 字段:整值条件按「数组包含元素 / 数组整体等值」翻译(U1)
93 Array,
94}
95
96/// 字段 → 列引用(见 [`field_column_ref`]):区分标量列 / JSON 整列 / JSON 点号路径。
97#[derive(Debug, Clone, PartialEq)]
98pub enum ColumnRef {
99 /// 标量列:字段名(调用方按表别名限定 + 引号化)
100 Scalar(String),
101 /// JSON 整列:object/array 字段落单列存 JSON 文本(读取时解析回嵌套对象)
102 Json(String, JsonKind),
103 /// JSON 点号路径(U3 过滤 / U4 排序):根列名 + 子路径(调用方构造提取表达式)
104 JsonPath(String, Vec<String>),
105}
106
107/// §9.7「布尔归一」:schema 字段是否为布尔类型(`boolean` 规范拼写 / `bool` 简写)。
108///
109/// 判定依据是 schema 的**声明类型**(不是驱动元数据,也不是物理列类型)——SQL 侧把布尔
110/// 存成 `TINYINT(1)` / `INTEGER` / `BOOLEAN` 都可能,唯一稳定的依据是 schema。命中即由
111/// [`row::restore_rows`] 在行还原时把 `0/1` 归一为 JSON `bool`。
112///
113/// 两种拼写都接受:core 的类型文档与 introspection 产出 `boolean`,而示例/用户 schema
114/// 常写 `bool`(如场景矩阵的 `paid` / `free`),二者语义相同。
115pub(crate) fn field_is_bool(schema: &Schema, field: &str) -> bool {
116 schema
117 .fields
118 .get(field)
119 .map(|f| {
120 f.field_type.eq_ignore_ascii_case("bool")
121 || f.field_type.eq_ignore_ascii_case("boolean")
122 })
123 .unwrap_or(false)
124}
125
126/// 支持的数据库后端
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum Backend {
129 Mysql,
130 Postgres,
131 Sqlite,
132}
133
134impl Backend {
135 /// 从字符串解析后端(未知 → Err)
136 pub fn parse(s: &str) -> Result<Backend, String> {
137 match s.to_lowercase().as_str() {
138 "mysql" => Ok(Backend::Mysql),
139 "postgres" | "pg" | "postgresql" => Ok(Backend::Postgres),
140 "sqlite" => Ok(Backend::Sqlite),
141 _ => Err(format!("不支持的后端: {}", s)),
142 }
143 }
144
145 /// 双重引号标识符
146 pub fn quote_ident(&self, ident: &str) -> String {
147 match self {
148 Backend::Mysql => format!("`{}`", ident.replace('`', "``")),
149 _ => format!("\"{}\"", ident.replace('"', "\"\"")),
150 }
151 }
152
153 /// 双精度浮点类型名(§9.7「数值归 double」)
154 ///
155 /// `SUM/AVG` 的结果在不同后端原生精度不同:MySQL `AVG(<int 列>)` 只保留 4 位小数
156 /// (`DECIMAL(scale+4)`),PG `AVG(<int 列>)` 返回精确 `numeric`,均与 Mongo `$avg`
157 /// 的 IEEE-754 double 存在差异。故 SQL 侧 `AVG` 前先把入参 `CAST` 到双精度。
158 pub fn double_type(&self) -> &'static str {
159 match self {
160 Backend::Mysql => "DOUBLE",
161 Backend::Postgres => "DOUBLE PRECISION",
162 Backend::Sqlite => "REAL",
163 }
164 }
165
166 /// 表名 → SQL:namespace 可选限定(`Some(ns)` → `"ns"."table"`;`None` → `"table"`)
167 ///
168 /// namespace 与连接的 search_path / 连接库 / ATTACH 库对应(见
169 /// `multi-datasource-routing-plan.md` §二);空串按 `None` 处理。
170 pub fn qualified_table(&self, namespace: Option<&str>, table: &str) -> String {
171 match namespace.filter(|s| !s.is_empty()) {
172 Some(ns) => format!("{}.{}", self.quote_ident(ns), self.quote_ident(table)),
173 None => self.quote_ident(table),
174 }
175 }
176
177 /// 占位符:SQLite/MySQL 用 `?`,PostgreSQL 用 `$n`(调用方保证按顺序传入 index)
178 pub fn placeholder(&self, _index: usize) -> String {
179 match self {
180 Backend::Postgres => format!("${}", _index + 1),
181 _ => "?".to_string(),
182 }
183 }
184
185 /// 后端标识(同 `Debug`,供绑定层序列化)
186 pub fn as_str(&self) -> &'static str {
187 match self {
188 Backend::Mysql => "mysql",
189 Backend::Postgres => "postgres",
190 Backend::Sqlite => "sqlite",
191 }
192 }
193
194 /// MySQL 无 RETURNING —— 需由 Host 编排 UPDATE + find 两段;PG/SQLite 原生支持
195 pub fn supports_returning(&self) -> bool {
196 !matches!(self, Backend::Mysql)
197 }
198
199 /// JSON 列的方言类型名(`object`/`array` 字段落单列存储的契约,见 §4.5 / 不足清单 #3)
200 ///
201 /// ⚠️ 跨方言对齐:`object`/`array` 字段在 SQL 后端**以单列存 JSON 文本** ——
202 /// MySQL `JSON` / PG `jsonb` / SQLite `TEXT`(JSON1 扩展)。core 不写 DDL(铁律 6),
203 /// 此常量供示例 DDL、introspection 与文档约定引用。
204 pub fn json_type_name(&self) -> &'static str {
205 match self {
206 Backend::Mysql => "JSON",
207 Backend::Postgres => "jsonb",
208 Backend::Sqlite => "TEXT",
209 }
210 }
211
212 /// JSON 点号路径 → **标量**提取表达式(U3 对象点号路径过滤 / U4 排序用)
213 ///
214 /// - MySQL:`JSON_UNQUOTE(JSON_EXTRACT(col, '$.a.b'))`
215 /// - PG:`(col #>> '{a,b}')`
216 /// - SQLite:`json_extract(col, '$.a.b')`
217 ///
218 /// 三者统一为「提取后标量(数值/字符串)」,供比较与 `ORDER BY` 使用;
219 /// `col` 须为已按后端引号化的**列标识符**,`path` 为点号各段(不含列名)。
220 pub fn json_extract_scalar(&self, col: &str, path: &[&str]) -> String {
221 match self {
222 Backend::Mysql => format!(
223 "JSON_UNQUOTE(JSON_EXTRACT({}, '{}'))",
224 col,
225 json_path_dollar(path)
226 ),
227 Backend::Postgres => format!("({} #>> '{{{}}}')", col, path.join(",")),
228 Backend::Sqlite => format!("json_extract({}, '{}')", col, json_path_dollar(path)),
229 }
230 }
231
232 /// JSON 数组「包含元素」谓词(U1:`{tags: "x"}` ⇒ 数组含 `"x"`)
233 ///
234 /// - MySQL:`JSON_CONTAINS(col, CAST(? AS JSON))`(候选是**值的 JSON 字面量**,如 `"x"` / `1`)
235 /// - PG:`col @> ?::jsonb`(候选是**单元素数组**的 JSON 文本,如 `["x"]`)
236 /// - SQLite:`EXISTS (SELECT 1 FROM json_each(col) WHERE json_each.value = ?)`(候选是标量原值)
237 ///
238 /// `ph` 为已生成的占位符(`?` / `$n`),参数由调用方按上述契约绑定(见 `filter::json_cond`)。
239 pub fn json_array_contains(&self, col: &str, ph: &str) -> String {
240 match self {
241 Backend::Mysql => format!("JSON_CONTAINS({}, CAST({} AS JSON))", col, ph),
242 Backend::Postgres => format!("{} @> {}::jsonb", col, ph),
243 Backend::Sqlite => format!(
244 "EXISTS (SELECT 1 FROM json_each({}) WHERE json_each.value = {})",
245 col, ph
246 ),
247 }
248 }
249
250 /// JSON 整值等值比较(U1 数组整体等值 / U2 对象结构等值)
251 ///
252 /// - MySQL:`col [<>] CAST(? AS JSON)`;PG:`col [<>] ?::jsonb`;SQLite:`json(col) [<>] json(?)`
253 ///
254 /// ⚠️ 跨后端语义差异(**已知不对齐点**,调用方须告警、禁静默,见「自动反馈原则」):
255 /// MySQL `JSON` / PG `jsonb` 的对象比较是**键序无关**的(存储即规范化),
256 /// 而 MongoDB 的对象等值匹配**字段顺序敏感**、SQLite(`json()` 文本 minify)**保留键序**。
257 /// 故 `object` 字段(U2)在 MySQL/PG 上可能比 Mongo/SQLite 命中更多行 ——
258 /// **不建议用于业务查询**,建议改用对象点号路径(U3);仅适合数据迁移 / 功能脚本。
259 pub fn json_value_eq(&self, col: &str, ph: &str, negate: bool) -> String {
260 let op = if negate { "<>" } else { "=" };
261 match self {
262 Backend::Mysql => format!("{} {} CAST({} AS JSON)", col, op, ph),
263 Backend::Postgres => format!("{} {} {}::jsonb", col, op, ph),
264 Backend::Sqlite => format!("json({}) {} json({})", col, op, ph),
265 }
266 }
267}
268
269/// 点号路径 → MySQL/SQLite `JSON_EXTRACT` 的 `$` 路径字面量(`["a","b"]` → `$.a.b`)
270fn json_path_dollar(path: &[&str]) -> String {
271 let mut s = String::from("$");
272 for seg in path {
273 s.push('.');
274 s.push_str(seg);
275 }
276 s
277}