//! Encode/decode between a domain value and what SQLite actually stores. //! The pair must round-trip exactly — `decode(encode(v)) === v` — because //! these run on both sides of the sync: a value encoded on the phone is //! decoded on the server and vice versa, and any asymmetry shows up as data //! that changes slightly every time it crosses. //! //! The domain value is a `serde_json::Value` here, because that is what an op //! carries across the wire and what the fold hands in. The storage value is a //! `rusqlite::types::Value` — the same four types SQLite has. use rusqlite::types::Value as SqlValue; use serde_json::{Map, Value as JsonValue}; use crate::error::{Result, StoreError}; use crate::protocol::js; use crate::schema::decl::Codec; /// `typeof value` — the word TypeScript's own error messages carry. fn type_of(value: &JsonValue) -> &'static str { match value { JsonValue::Null => "object", JsonValue::Bool(_) => "boolean", JsonValue::Number(_) => "number", JsonValue::String(_) => "string", JsonValue::Array(_) | JsonValue::Object(_) => "object", } } /// `String(value)` — used only inside the integer codec's error message, which /// prints the value rather than its type. fn string_of(value: &JsonValue) -> String { match value { JsonValue::Null => "null".to_string(), JsonValue::Bool(true) => "true".to_string(), JsonValue::Bool(false) => "false".to_string(), JsonValue::Number(number) => number .as_f64() .map_or_else(|| number.to_string(), js::number_to_string), JsonValue::String(text) => text.clone(), // `String([1,2])` is "1,2" and `String({})` is "[object Object]". JsonValue::Array(items) => items .iter() .map(|item| match item { JsonValue::Null => String::new(), other => string_of(other), }) .collect::>() .join(","), JsonValue::Object(_) => "[object Object]".to_string(), } } /// How a JSON number binds: an integral, exactly representable double goes in /// as an INTEGER, everything else as a REAL. /// /// It matters because the conformance dump types every value (`{"i":…}` vs /// `{"r":…}`), so binding `3` as a REAL would read as a divergence even though /// SQLite's own affinity would hide it. fn bind_number(value: f64) -> SqlValue { if value.is_finite() && value.fract() == 0.0 && (value as i64) as f64 == value { SqlValue::Integer(value as i64) } else { SqlValue::Real(value) } } fn as_number(value: &JsonValue) -> Option { match value { JsonValue::Number(number) => number.as_f64(), _ => None, } } /// Encode one value for its column's codec. `null` maps to NULL for every one. pub fn encode_value(codec: Codec, value: &JsonValue) -> Result { if value.is_null() { return Ok(SqlValue::Null); } match codec { Codec::Text => match value { JsonValue::String(text) => Ok(SqlValue::Text(text.clone())), other => Err(StoreError::encode(format!( "expected string, got {}", type_of(other) ))), }, // Accepts a string only — TypeScript also accepts a `Date`, which JSON // cannot carry, so an op never holds one. Stores the ISO form, always // UTC with a trailing Z, so string comparison is chronological. Codec::Timestamp => match value { JsonValue::String(text) => Ok(SqlValue::Text(to_utc_instant(text)?)), other => Err(StoreError::encode(format!( "expected timestamp, got {}", type_of(other) ))), }, Codec::MoneyMinor => { if let Some(amount) = value.as_i64() { return Ok(SqlValue::Integer(amount)); } // Whole floating JSON numbers from a statement reader are valid // only within the range where every integer is representable. if let Some(amount) = value.as_f64().filter(|amount| { amount.is_finite() && amount.fract() == 0.0 && amount.abs() <= 9_007_199_254_740_991.0 }) { return Ok(SqlValue::Integer(amount as i64)); } Err(StoreError::encode("expected exact integer minor units")) } Codec::Int => { let number = as_number(value).filter(|n| n.fract() == 0.0 && n.is_finite()); match number { Some(number) => Ok(bind_number(number)), None => Err(StoreError::encode(format!( "expected integer, got {}", string_of(value) ))), } } Codec::Real => match as_number(value) { Some(number) => Ok(bind_number(number)), None => Err(StoreError::encode(format!( "expected number, got {}", type_of(value) ))), }, Codec::Bool => match value { JsonValue::Bool(flag) => Ok(SqlValue::Integer(i64::from(*flag))), other => Err(StoreError::encode(format!( "expected boolean, got {}", type_of(other) ))), }, Codec::Json => Ok(SqlValue::Text(js::json_stringify(value))), // A decimal that must not become a float. Numbers are allowed in (the // callers hold JS numbers) but leave as text. Codec::DecimalText => match value { JsonValue::Number(number) => Ok(SqlValue::Text( number .as_f64() .map_or_else(|| number.to_string(), js::number_to_string), )), JsonValue::String(text) => Ok(SqlValue::Text(text.clone())), other => Err(StoreError::encode(format!( "expected decimal, got {}", type_of(other) ))), }, } } /// Z-form or nothing — the invariant string ordering depends on. /// /// Timestamps are stored as text precisely because string order IS /// chronological order. An offset form breaks that quietly: /// `2026-08-23T14:30:00+05:30` sorts after `2026-08-23T10:00:00Z` while /// actually being an hour EARLIER. /// /// NORMALISE rather than reject, deliberately: this runs inside the fold on /// both sides, and a throw here would make an op from a device running older /// code unfoldable — a rejected op is a user watching an edit vanish. /// /// EVERY value goes through the round-trip, including one that already ends in /// `Z`: two Z forms of different PRECISION mis-sort against each other exactly /// the way the offset forms do (`…T14:30:00.500Z` < `…T14:30:00Z` as strings, /// though it is half a second later). pub fn to_utc_instant(value: &str) -> Result { // A string carrying no zone at all is parsed by `new Date` in the RUNTIME's // local zone — so the phone (IST) and the host (UTC) would fold the same op // into two different instants. Pin it to UTC. let zoned = if has_zone(value) { value.to_string() } else { format!("{value}Z") }; let malformed = || { StoreError::encode(format!( "expected timestamp, got {}", js::json_stringify(&JsonValue::String(value.to_string())) )) }; let ms = js::parse_date_ms(&zoned).ok_or_else(malformed)?; js::to_iso_string(ms).ok_or_else(malformed) } /// TypeScript's `/(?:Z|[+-]\d{2}:?\d{2})$/` — a trailing `Z`, `+05:30` or /// `+0530`. Lower-case `z` deliberately does NOT count, exactly as the regex /// reads. fn has_zone(value: &str) -> bool { if value.ends_with('Z') { return true; } let bytes = value.as_bytes(); let is_digits = |slice: &[u8]| slice.iter().all(u8::is_ascii_digit); // `+HH:MM` if bytes.len() >= 6 { let tail = &bytes[bytes.len() - 6..]; if (tail[0] == b'+' || tail[0] == b'-') && is_digits(&tail[1..3]) && tail[3] == b':' && is_digits(&tail[4..6]) { return true; } } // `+HHMM` if bytes.len() >= 5 { let tail = &bytes[bytes.len() - 5..]; if (tail[0] == b'+' || tail[0] == b'-') && is_digits(&tail[1..5]) { return true; } } false } /// Decode one stored value back to its domain form. NULL is `null` for every /// codec. pub fn decode_value(codec: Codec, value: &SqlValue) -> Result { if matches!(value, SqlValue::Null) { return Ok(JsonValue::Null); } match codec { // `String(value)`. Codec::Text | Codec::Timestamp | Codec::DecimalText => { Ok(JsonValue::String(sql_to_string(value))) } // `typeof value === "number" ? value : Number(value)`. Codec::Int | Codec::MoneyMinor | Codec::Real => Ok(match value { SqlValue::Integer(int) => JsonValue::from(*int), SqlValue::Real(real) => number_json(*real), other => match sql_to_number(other) { Some(number) => number_json(number), // `Number("nope")` is NaN, and `JSON.stringify(NaN)` is null — // the only representation a JSON value has for it. None => JsonValue::Null, }, }), // `value === 1 || value === "1"`. Codec::Bool => Ok(JsonValue::Bool(match value { SqlValue::Integer(int) => *int == 1, SqlValue::Text(text) => text == "1", _ => false, })), // `typeof value === "string" ? JSON.parse(value) : value`. Codec::Json => match value { SqlValue::Text(text) => serde_json::from_str(text).map_err(|error| { StoreError::encode(format!("json column is not valid JSON: {error}")) }), SqlValue::Integer(int) => Ok(JsonValue::from(*int)), SqlValue::Real(real) => Ok(number_json(*real)), SqlValue::Blob(_) => Err(StoreError::encode( "json column holds a blob, which JSON cannot represent", )), SqlValue::Null => Ok(JsonValue::Null), }, } } fn number_json(value: f64) -> JsonValue { // An integral double is a JS integer; keeping it one is what makes // `Number.isInteger(back.amount_minor)` true after a round trip. if value.fract() == 0.0 && value.is_finite() && (value as i64) as f64 == value { JsonValue::from(value as i64) } else { serde_json::Number::from_f64(value).map_or(JsonValue::Null, JsonValue::Number) } } fn sql_to_string(value: &SqlValue) -> String { match value { SqlValue::Null => "null".to_string(), SqlValue::Integer(int) => int.to_string(), SqlValue::Real(real) => js::number_to_string(*real), SqlValue::Text(text) => text.clone(), // `String(buffer)` in Node decodes UTF-8; nothing in the schema stores // a blob in a text column, so this is a floor, not a path. SqlValue::Blob(bytes) => String::from_utf8_lossy(bytes).into_owned(), } } fn sql_to_number(value: &SqlValue) -> Option { match value { SqlValue::Integer(int) => Some(*int as f64), SqlValue::Real(real) => Some(*real), // `Number("")` is 0 and `Number(" 12 ")` is 12 — JS trims first. SqlValue::Text(text) if text.trim().is_empty() => Some(0.0), SqlValue::Text(text) => text.trim().parse::().ok(), _ => None, } } /// Encode a whole patch against a table's columns. Unknown columns refuse. /// /// An entry the patch does not carry is simply absent from `patch` — JSON has /// no `undefined`, and `JSON.stringify` drops such a key, which is exactly the /// protocol's reading: absent means "not part of this patch", an explicit /// `null` means "clear the column". /// /// `columns` is the table's `(name, codec)` list in declaration order; the /// output keeps the PATCH's order, as `Object.entries` does. pub fn encode_row( columns: &[(&str, Codec)], patch: &Map, ) -> Result> { let mut out = Vec::with_capacity(patch.len()); for (column, value) in patch { // The unknown-column check comes FIRST, deliberately: a misspelled // column must fail loudly whatever its value. let codec = columns .iter() .find(|(name, _)| name == column) .map(|(_, codec)| *codec) .ok_or_else(|| StoreError::encode(format!("unknown column: {column}")))?; out.push((column.clone(), encode_value(codec, value)?)); } Ok(out) } /// Decode a stored row to its domain form. Protocol bookkeeping (`_hlc` and /// friends) and columns the spec does not know are skipped, not refused. pub fn decode_row( columns: &[(&str, Codec)], row: &[(String, SqlValue)], ) -> Result> { let mut out = Map::new(); for (column, value) in row { if column.starts_with('_') { continue; // protocol bookkeeping, not the user's } let Some(codec) = columns .iter() .find(|(name, _)| name == column) .map(|(_, codec)| *codec) else { continue; }; out.insert(column.clone(), decode_value(codec, value)?); } Ok(out) } #[cfg(test)] #[path = "codecs_tests.rs"] mod tests;