kovlet 0.1.0

Kovlet's portable sync client core: sign-in, sync, merge, outbox and files for Rust, Tauri, Swift and Kotlin apps
Documentation
//! Declaring tables (`hello.schema`): `Tables::new().table("todos", [("title", col::string()), ("done", col::boolean())])`.

use std::collections::BTreeMap;

use crate::error::{Error, Result};
use crate::protocol::{ColumnDef, TableSchema};

/// Column constructors: `col::string()`, `col::number().optional()`, `col::reference("lists")`.
pub mod col {
    use crate::protocol::ColumnDef;

    pub fn string() -> ColumnDef {
        ColumnDef::new("string")
    }
    pub fn number() -> ColumnDef {
        ColumnDef::new("number")
    }
    pub fn boolean() -> ColumnDef {
        ColumnDef::new("boolean")
    }
    pub fn datetime() -> ColumnDef {
        ColumnDef::new("datetime")
    }
    pub fn json() -> ColumnDef {
        ColumnDef::new("json")
    }
    pub fn file_ref() -> ColumnDef {
        ColumnDef::new("file_ref")
    }
    pub fn reference(table: &str) -> ColumnDef {
        let mut c = ColumnDef::new("ref");
        c.ref_table = Some(table.to_string());
        c
    }
}

/// The tables a space declares.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Tables(pub BTreeMap<String, TableSchema>);

impl Tables {
    pub fn new() -> Tables {
        Tables::default()
    }

    /// Adds a table; columns keep the given order.
    pub fn table<I, S>(mut self, name: &str, columns: I) -> Tables
    where
        I: IntoIterator<Item = (S, ColumnDef)>,
        S: Into<String>,
    {
        let mut t = TableSchema::default();
        let mut order = Vec::new();
        for (n, c) in columns {
            let n = n.into();
            order.push(n.clone());
            t.columns.insert(n, c);
        }
        t.order = Some(order);
        self.0.insert(name.to_string(), t);
        self
    }

    /// From JSON: `{"todos": {"columns": {...}, "order": [...]}}` (as in `hello.schema`).
    pub fn from_json(json: &str) -> Result<Tables> {
        let m: BTreeMap<String, TableSchema> = serde_json::from_str(json)?;
        Ok(Tables(m))
    }

    pub fn validate(&self) -> Result<()> {
        for (name, t) in &self.0 {
            t.validate(name)?;
            if t.columns.contains_key("id") {
                return Err(Error::config(format!(
                    "{name}: a column can't be named id; the row id lives in the record's id"
                )));
            }
        }
        Ok(())
    }
}