Skip to main content

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/// §9.7「布尔归一」:schema 字段是否为布尔类型(`boolean` 规范拼写 / `bool` 简写)。
54///
55/// 判定依据是 schema 的**声明类型**(不是驱动元数据,也不是物理列类型)——SQL 侧把布尔
56/// 存成 `TINYINT(1)` / `INTEGER` / `BOOLEAN` 都可能,唯一稳定的依据是 schema。命中即由
57/// [`row::restore_rows`] 在行还原时把 `0/1` 归一为 JSON `bool`。
58///
59/// 两种拼写都接受:core 的类型文档与 introspection 产出 `boolean`,而示例/用户 schema
60/// 常写 `bool`(如场景矩阵的 `paid` / `free`),二者语义相同。
61pub(crate) fn field_is_bool(schema: &Schema, field: &str) -> bool {
62    schema
63        .fields
64        .get(field)
65        .map(|f| {
66            f.field_type.eq_ignore_ascii_case("bool")
67                || f.field_type.eq_ignore_ascii_case("boolean")
68        })
69        .unwrap_or(false)
70}
71
72/// 支持的数据库后端
73#[derive(Debug, Clone, Copy, PartialEq, Eq)]
74pub enum Backend {
75    Mysql,
76    Postgres,
77    Sqlite,
78}
79
80impl Backend {
81    /// 从字符串解析后端(未知 → Err)
82    pub fn parse(s: &str) -> Result<Backend, String> {
83        match s.to_lowercase().as_str() {
84            "mysql" => Ok(Backend::Mysql),
85            "postgres" | "pg" | "postgresql" => Ok(Backend::Postgres),
86            "sqlite" => Ok(Backend::Sqlite),
87            _ => Err(format!("不支持的后端: {}", s)),
88        }
89    }
90
91    /// 双重引号标识符
92    pub fn quote_ident(&self, ident: &str) -> String {
93        match self {
94            Backend::Mysql => format!("`{}`", ident.replace('`', "``")),
95            _ => format!("\"{}\"", ident.replace('"', "\"\"")),
96        }
97    }
98
99    /// 双精度浮点类型名(§9.7「数值归 double」)
100    ///
101    /// `SUM/AVG` 的结果在不同后端原生精度不同:MySQL `AVG(<int 列>)` 只保留 4 位小数
102    /// (`DECIMAL(scale+4)`),PG `AVG(<int 列>)` 返回精确 `numeric`,均与 Mongo `$avg`
103    /// 的 IEEE-754 double 存在差异。故 SQL 侧 `AVG` 前先把入参 `CAST` 到双精度。
104    pub fn double_type(&self) -> &'static str {
105        match self {
106            Backend::Mysql => "DOUBLE",
107            Backend::Postgres => "DOUBLE PRECISION",
108            Backend::Sqlite => "REAL",
109        }
110    }
111
112    /// 表名 → SQL:namespace 可选限定(`Some(ns)` → `"ns"."table"`;`None` → `"table"`)
113    ///
114    /// namespace 与连接的 search_path / 连接库 / ATTACH 库对应(见
115    /// `multi-datasource-routing-plan.md` §二);空串按 `None` 处理。
116    pub fn qualified_table(&self, namespace: Option<&str>, table: &str) -> String {
117        match namespace.filter(|s| !s.is_empty()) {
118            Some(ns) => format!("{}.{}", self.quote_ident(ns), self.quote_ident(table)),
119            None => self.quote_ident(table),
120        }
121    }
122
123    /// 占位符:SQLite/MySQL 用 `?`,PostgreSQL 用 `$n`(调用方保证按顺序传入 index)
124    pub fn placeholder(&self, _index: usize) -> String {
125        match self {
126            Backend::Postgres => format!("${}", _index + 1),
127            _ => "?".to_string(),
128        }
129    }
130
131    /// 后端标识(同 `Debug`,供绑定层序列化)
132    pub fn as_str(&self) -> &'static str {
133        match self {
134            Backend::Mysql => "mysql",
135            Backend::Postgres => "postgres",
136            Backend::Sqlite => "sqlite",
137        }
138    }
139
140    /// MySQL 无 RETURNING —— 需由 Host 编排 UPDATE + find 两段;PG/SQLite 原生支持
141    pub fn supports_returning(&self) -> bool {
142        !matches!(self, Backend::Mysql)
143    }
144}