Skip to main content

mongreldb_kit/
schema.rs

1//! Schema/value conversion between the kit model and MongrelDB core.
2
3use crate::error::{KitError, Result};
4use mongreldb_core::memtable::Value as CoreValue;
5use mongreldb_core::schema::{
6    ColumnDef, ColumnFlags, IndexDef, IndexKind, Schema as CoreSchema, TypeId,
7};
8use mongreldb_kit_core::schema::{
9    Column, ColumnType, IndexKind as KitIndexKind, Table as KitTable,
10};
11use serde_json::{Map, Value};
12
13/// Convert a kit table to a core schema.
14pub fn to_core_schema(table: &KitTable) -> CoreSchema {
15    let columns: Vec<ColumnDef> = table
16        .columns
17        .iter()
18        .map(|c| ColumnDef {
19            id: c.id as u16,
20            name: c.name.clone(),
21            ty: match c.storage_type {
22                ColumnType::Embedding => TypeId::Embedding {
23                    dim: c.embedding_dim.unwrap_or(0),
24                },
25                other => to_core_type(other),
26            },
27            flags: to_core_flags(table, c),
28        })
29        .collect();
30
31    let mut indexes: Vec<IndexDef> = Vec::new();
32    for idx in &table.indexes {
33        let kind = match idx.kind {
34            KitIndexKind::Bitmap => IndexKind::Bitmap,
35            KitIndexKind::Fm => IndexKind::FmIndex,
36            KitIndexKind::Ann => IndexKind::Ann,
37            KitIndexKind::Sparse => IndexKind::Sparse,
38            KitIndexKind::MinHash => IndexKind::MinHash,
39            KitIndexKind::LearnedRange => IndexKind::LearnedRange,
40        };
41        for col_name in &idx.columns {
42            if let Some(col) = table.column(col_name) {
43                indexes.push(IndexDef {
44                    name: format!("{}_{}", idx.name, col_name),
45                    column_id: col.id as u16,
46                    kind,
47                });
48            }
49        }
50    }
51    for uq in &table.unique_constraints {
52        for col_name in &uq.columns {
53            if let Some(col) = table.column(col_name) {
54                indexes.push(IndexDef {
55                    name: format!("uq_{}_{}", uq.name, col_name),
56                    column_id: col.id as u16,
57                    kind: IndexKind::Bitmap,
58                });
59            }
60        }
61    }
62
63    CoreSchema {
64        schema_id: table.id as u64,
65        columns,
66        indexes,
67        colocation: Vec::new(),
68        constraints: Default::default(),
69    }
70}
71
72pub(crate) fn to_core_flags(table: &KitTable, column: &Column) -> ColumnFlags {
73    let mut flags = ColumnFlags::empty();
74    if column.nullable {
75        flags = flags.with(ColumnFlags::NULLABLE);
76    }
77    if table.primary_key.contains(&column.name) || column.primary_key {
78        flags = flags.with(ColumnFlags::PRIMARY_KEY);
79    }
80    if column.encrypted {
81        flags = flags.with(ColumnFlags::ENCRYPTED);
82    }
83    if column.encrypted_indexable {
84        flags = flags.with(ColumnFlags::ENCRYPTED_INDEXABLE);
85    }
86    flags
87}
88
89pub(crate) fn to_core_type(ty: ColumnType) -> TypeId {
90    match ty {
91        ColumnType::Bool => TypeId::Bool,
92        ColumnType::Int8 | ColumnType::Int16 | ColumnType::Int32 | ColumnType::Int64 => {
93            TypeId::Int64
94        }
95        ColumnType::Float32 | ColumnType::Float64 => TypeId::Float64,
96        ColumnType::Text
97        | ColumnType::Bytes
98        | ColumnType::Json
99        | ColumnType::Date
100        | ColumnType::DateTime => TypeId::Bytes,
101        ColumnType::TimestampNanos => TypeId::Int64,
102        // Dimension is filled from the column's `embedding_dim` in
103        // `to_core_schema`; a bare type has no dimension context.
104        ColumnType::Embedding => TypeId::Embedding { dim: 0 },
105        // Sparse vectors are stored as bincode'd `Vec<(u32, f32)>` in a Bytes
106        // column; the Sparse index reads the tokens from those bytes.
107        ColumnType::Sparse => TypeId::Bytes,
108    }
109}
110
111/// Convert a JSON value to a core cell value using the column type for guidance.
112pub fn json_to_core(value: &Value, ty: ColumnType) -> Result<CoreValue> {
113    Ok(match value {
114        Value::Null => CoreValue::Null,
115        Value::Bool(b) => CoreValue::Bool(*b),
116        Value::Number(n) => {
117            if let Some(i) = n.as_i64() {
118                CoreValue::Int64(i)
119            } else {
120                CoreValue::Float64(n.as_f64().unwrap_or(f64::NAN))
121            }
122        }
123        Value::String(s) => CoreValue::Bytes(s.as_bytes().to_vec()),
124        Value::Array(arr) => {
125            if ty == ColumnType::Sparse {
126                let mut terms: Vec<(u32, f32)> = Vec::with_capacity(arr.len());
127                for pair in arr {
128                    let p = pair
129                        .as_array()
130                        .ok_or_else(|| KitError::Validation("sparse expects pairs".into()))?;
131                    let token =
132                        p.first().and_then(|v| v.as_u64()).ok_or_else(|| {
133                            KitError::Validation("sparse token must be u32".into())
134                        })? as u32;
135                    let weight = p.get(1).and_then(|v| v.as_f64()).ok_or_else(|| {
136                        KitError::Validation("sparse weight must be number".into())
137                    })? as f32;
138                    terms.push((token, weight));
139                }
140                CoreValue::Bytes(
141                    bincode::serialize(&terms).map_err(|e| KitError::Validation(e.to_string()))?,
142                )
143            } else if ty == ColumnType::Embedding {
144                let mut vec = Vec::with_capacity(arr.len());
145                for v in arr {
146                    match v.as_f64() {
147                        Some(f) => vec.push(f as f32),
148                        None => {
149                            return Err(KitError::Validation("embedding expects numbers".into()))
150                        }
151                    }
152                }
153                CoreValue::Embedding(vec)
154            } else if ty == ColumnType::Bytes {
155                let mut bytes = Vec::with_capacity(arr.len());
156                for v in arr {
157                    match v {
158                        Value::Number(n) => bytes.push(n.as_i64().unwrap_or(0) as u8),
159                        _ => return Err(KitError::Validation("bytes array expected".into())),
160                    }
161                }
162                CoreValue::Bytes(bytes)
163            } else {
164                CoreValue::Bytes(serde_json::to_vec(value)?)
165            }
166        }
167        Value::Object(_) => CoreValue::Bytes(serde_json::to_vec(value)?),
168    })
169}
170
171/// Convert a core cell value back to JSON, guided by the column type.
172pub fn core_to_json(value: &CoreValue, ty: ColumnType) -> Result<Value> {
173    Ok(match (value, ty) {
174        (CoreValue::Null, _) => Value::Null,
175        (CoreValue::Bool(b), _) => Value::Bool(*b),
176        (CoreValue::Int64(i), ColumnType::Int8) => Value::Number((*i as i8).into()),
177        (CoreValue::Int64(i), ColumnType::Int16) => Value::Number((*i as i16).into()),
178        (CoreValue::Int64(i), ColumnType::Int32) => Value::Number((*i as i32).into()),
179        (CoreValue::Int64(i), ColumnType::Int64) => Value::Number((*i).into()),
180        (CoreValue::Int64(i), ColumnType::TimestampNanos) => Value::Number((*i).into()),
181        (CoreValue::Int64(i), _) => Value::Number((*i).into()),
182        (CoreValue::Float64(f), ColumnType::Float32) => serde_json::to_value(*f as f32)?,
183        (CoreValue::Float64(f), _) => serde_json::to_value(*f)?,
184        (CoreValue::Bytes(b), ColumnType::Sparse) => {
185            let terms: Vec<(u32, f32)> =
186                bincode::deserialize(b).map_err(|e| KitError::Validation(e.to_string()))?;
187            Value::Array(
188                terms
189                    .into_iter()
190                    .map(|(t, w)| Value::Array(vec![Value::from(t), Value::from(w as f64)]))
191                    .collect(),
192            )
193        }
194        (CoreValue::Bytes(b), ColumnType::Bytes) => {
195            Value::Array(b.iter().map(|x| Value::Number((*x).into())).collect())
196        }
197        (CoreValue::Bytes(b), _) => match std::str::from_utf8(b) {
198            Ok(s) => Value::String(s.to_string()),
199            Err(_) => Value::Array(b.iter().map(|x| Value::Number((*x).into())).collect()),
200        },
201        (CoreValue::Embedding(v), _) => serde_json::to_value(v)?,
202    })
203}
204
205/// Build a JSON row from a core row and a kit table definition.
206pub fn core_row_to_json(row: &mongreldb_core::memtable::Row, table: &KitTable) -> Result<Row> {
207    let mut values = Map::new();
208    for col in &table.columns {
209        let v = row
210            .columns
211            .get(&(col.id as u16))
212            .cloned()
213            .unwrap_or(CoreValue::Null);
214        values.insert(col.name.clone(), core_to_json(&v, col.storage_type)?);
215    }
216    Ok(Row {
217        row_id: row.row_id.0,
218        values,
219    })
220}
221
222/// A kit row, identified by its internal storage row id and column values.
223#[derive(Debug, Clone, PartialEq)]
224pub struct Row {
225    pub row_id: u64,
226    pub values: Map<String, Value>,
227}
228
229impl Row {
230    /// Extract the primary-key value(s) as a JSON value.
231    ///
232    /// Single-column primary keys return the scalar value; composite keys return
233    /// an object.
234    pub fn pk(&self, table: &KitTable) -> Option<Value> {
235        if table.primary_key.len() == 1 {
236            self.values.get(&table.primary_key[0]).cloned()
237        } else {
238            let mut obj = Map::new();
239            for name in &table.primary_key {
240                obj.insert(
241                    name.clone(),
242                    self.values.get(name).cloned().unwrap_or(Value::Null),
243                );
244            }
245            Some(Value::Object(obj))
246        }
247    }
248}
249
250/// Extract the primary-key value(s) from a JSON value map.
251pub fn pk_value(values: &Map<String, Value>, table: &KitTable) -> Option<Value> {
252    if table.primary_key.len() == 1 {
253        values.get(&table.primary_key[0]).cloned()
254    } else {
255        let mut obj = Map::new();
256        for name in &table.primary_key {
257            obj.insert(
258                name.clone(),
259                values.get(name).cloned().unwrap_or(Value::Null),
260            );
261        }
262        Some(Value::Object(obj))
263    }
264}
265
266/// Convert a primary-key value into the column values for lookup.
267pub fn pk_to_map(pk: &Value, table: &KitTable) -> Result<Map<String, Value>> {
268    let mut map = Map::new();
269    match pk {
270        Value::Object(obj) => {
271            for name in &table.primary_key {
272                let v = obj
273                    .get(name)
274                    .cloned()
275                    .ok_or_else(|| KitError::Validation(format!("missing pk column {name}")))?;
276                map.insert(name.clone(), v);
277            }
278        }
279        scalar if table.primary_key.len() == 1 => {
280            map.insert(table.primary_key[0].clone(), scalar.clone());
281        }
282        _ => {
283            return Err(KitError::Validation(
284                "primary key value shape mismatch".into(),
285            ))
286        }
287    }
288    Ok(map)
289}
290
291/// Build a core cell vector from a JSON row and kit table definition.
292pub fn row_to_core_cells(
293    values: &Map<String, Value>,
294    table: &KitTable,
295) -> Result<Vec<(u16, CoreValue)>> {
296    let mut cells = Vec::with_capacity(table.columns.len());
297    for col in &table.columns {
298        let v = values.get(&col.name).cloned().unwrap_or(Value::Null);
299        cells.push((col.id as u16, json_to_core(&v, col.storage_type)?));
300    }
301    Ok(cells)
302}