1use crate::hash::xxhash32;
5use crate::json::{Object, Value, number, stringify};
6use std::fmt;
7
8pub const DESIRED_QUERIES_PREFIX: &str = "d/";
9pub const GOT_QUERIES_PREFIX: &str = "g/";
10pub const ENTITIES_PREFIX: &str = "e/";
11pub const AGGREGATES_PREFIX: &str = "a/";
14pub const MUTATIONS_PREFIX: &str = "m/";
15pub const ROW_VERSION_COLUMN: &str = "_0_version";
18
19pub const AGGREGATE_TABLE_PREFIX: &str = "aggregate:";
21
22pub mod aggregate_columns {
24 pub const VALUE: &str = "_0_value";
26 pub const KEY: &str = "_0_key";
28 pub const SUM: &str = "_0_sum";
30 pub const COUNT: &str = "_0_count";
31 pub const ROWS: &str = "_0_rows";
33 pub const PAYLOAD: [&str; 4] = [VALUE, SUM, COUNT, ROWS];
35}
36
37#[derive(Clone, Debug, PartialEq)]
39pub struct InvalidPrimaryKeyValue {
40 pub column: String,
41 pub value: Option<Value>,
42}
43
44impl fmt::Display for InvalidPrimaryKeyValue {
45 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 write!(
49 f,
50 "Expected string, number or boolean. Got {}",
51 valita_display(self.value.as_ref())
52 )
53 }
54}
55
56impl std::error::Error for InvalidPrimaryKeyValue {}
57
58pub fn valita_display(v: Option<&Value>) -> String {
60 match v {
61 None => "undefined".into(),
62 Some(Value::Null) => "null".into(),
63 Some(Value::Array(_)) => "array".into(),
64 Some(Value::Object(_)) => "object".into(),
65 Some(v) => stringify(v),
66 }
67}
68
69pub fn primary_key_string(
73 table: &str,
74 primary_key: &[impl AsRef<str>],
75 row: &Object,
76) -> Result<String, InvalidPrimaryKeyValue> {
77 key_string(ENTITIES_PREFIX, table, primary_key, row)
78}
79
80pub fn aggregate_row_key(table: &str, row: &Object) -> Result<String, InvalidPrimaryKeyValue> {
84 let columns = aggregate_row_key_columns(table, row.keys());
85 let name = table.strip_prefix(AGGREGATE_TABLE_PREFIX).unwrap_or(table);
86 key_string(AGGREGATES_PREFIX, name, &columns, row)
87}
88
89pub fn aggregate_row_key_columns<'a>(
94 table: &str,
95 columns: impl IntoIterator<Item = &'a String>,
96) -> Vec<String> {
97 if is_keyed_aggregate_table_name(table) {
98 return vec![aggregate_columns::KEY.to_owned()];
99 }
100 let mut out: Vec<String> = columns
101 .into_iter()
102 .filter(|c| !aggregate_columns::PAYLOAD.contains(&c.as_str()) && *c != ROW_VERSION_COLUMN)
103 .cloned()
104 .collect();
105 out.sort_by(|a, b| crate::strings::utf16(a, b));
106 out
107}
108
109fn key_string(
110 prefix: &str,
111 table: &str,
112 primary_key: &[impl AsRef<str>],
113 row: &Object,
114) -> Result<String, InvalidPrimaryKeyValue> {
115 let scalar = |column: &str| match row.get(column) {
116 Some(v @ (Value::String(_) | Value::Number(_) | Value::Bool(_))) => Ok(v.clone()),
117 v => Err(InvalidPrimaryKeyValue {
118 column: column.to_owned(),
119 value: v.cloned(),
120 }),
121 };
122 if let [column] = primary_key {
123 let v = scalar(column.as_ref())?;
124 return Ok(format!("{prefix}{table}/{}", js_string(&v)));
125 }
126 let values = primary_key
127 .iter()
128 .map(|c| scalar(c.as_ref()))
129 .collect::<Result<Vec<_>, _>>()?;
130 let hash = xxhash32::h128(&stringify(&Value::Array(values)));
131 Ok(format!("{prefix}{table}/{hash}"))
132}
133
134pub fn js_string(v: &Value) -> String {
136 match v {
137 Value::String(s) => s.clone(),
138 Value::Number(n) => number::format(*n),
139 Value::Bool(b) => b.to_string(),
140 Value::Null => "null".into(),
141 Value::Array(_) | Value::Object(_) => stringify(v),
142 }
143}
144
145pub fn is_aggregate_table_name(name: &str) -> bool {
147 name.starts_with(AGGREGATE_TABLE_PREFIX)
148}
149
150pub fn is_top_level_aggregate_table_name(name: &str) -> bool {
153 name.strip_prefix(AGGREGATE_TABLE_PREFIX)
154 .is_some_and(|rest| !rest.contains(':'))
155}
156
157pub fn is_keyed_aggregate_table_name(name: &str) -> bool {
160 is_top_level_aggregate_table_name(name)
161 || (is_aggregate_table_name(name) && name.ends_with(":#group"))
162}
163
164pub fn source_name(key: &str) -> String {
167 let rest = &key[ENTITIES_PREFIX.len()..];
169 let name = rest.split('/').next().unwrap_or(rest);
170 if key.starts_with(AGGREGATES_PREFIX) {
171 format!("{AGGREGATE_TABLE_PREFIX}{name}")
172 } else {
173 name.to_owned()
174 }
175}
176
177pub fn desired_queries_key(client_id: &str, hash: &str) -> String {
178 format!("{DESIRED_QUERIES_PREFIX}{client_id}/{hash}")
179}
180
181pub fn got_queries_key(hash: &str) -> String {
182 format!("{GOT_QUERIES_PREFIX}{hash}")
183}
184
185pub fn mutation_response_key(client_id: &str, id: f64) -> String {
186 format!("{MUTATIONS_PREFIX}{client_id}/{}", number::format(id))
187}