Cotton code
40 lines · 1.4 KB · RustRaw
//! Row expressions against a table: the shape and arithmetic are//! cotton-rules' (`cotton_rules::expressions`, the Worker's too); what a//! column's type is, and the clock an expression reads, are this crate's.use super::said;use crate::definitions::{ColumnType, TableDefinition};use serde_json::{Map, Value};pub use cotton_rules::expressions::{evaluate_at, Type};pub fn column_type(t: ColumnType) -> Type {    match t {        ColumnType::Number | ColumnType::Amount | ColumnType::Bytes => Type::Number,        ColumnType::Bool => Type::Bool,        _ => Type::Text,    }}pub fn validate(value: &Value, table: &TableDefinition) -> Result<Type, String> {    cotton_rules::expressions::visit(        value,        &mut |key| {            if key == "id" {                return Ok(Type::Text);            }            table                .columns                .iter()                .find(|c| c.key == key)                .map(|c| if c.multiple == Some(true) { Type::Other } else { column_type(c.column_type) })                .ok_or_else(|| said("unknown_expression_column", &[("key", &key)]))        },        0,    )}/// [`evaluate_at`] at this moment, UTC.pub fn evaluate(value: &Value, row: &Map<String, Value>) -> Result<Value, String> {    let now = chrono::Utc::now();    evaluate_at(value, row, &now.to_rfc3339_opts(chrono::SecondsFormat::Millis, true), &now.format("%Y-%m-%d").to_string())}