1use std::collections::BTreeSet;
7
8use serde::Deserialize;
9use ssp2::segment::{Column, ColumnType};
10
11#[derive(Debug, Clone, Deserialize)]
12pub struct SchemaIr {
13 #[serde(alias = "schemaVersion")]
14 pub version: i32,
15 pub tables: Vec<TableIr>,
16}
17
18#[derive(Debug, Clone, Deserialize)]
19#[serde(rename_all = "camelCase")]
20pub struct TableIr {
21 pub name: String,
22 pub columns: Vec<ColumnIr>,
23 pub primary_key: String,
24 pub scopes: Vec<ScopePatternIr>,
25 #[serde(default)]
28 pub indexes: Vec<IndexIr>,
29 #[serde(default)]
30 pub local_projections: Vec<LocalProjection>,
31 #[serde(default)]
33 pub generation: Option<String>,
34 #[serde(default)]
36 pub equivalent_generations: Vec<String>,
37 #[serde(default)]
40 pub fts_indexes: Option<serde_json::Value>,
41}
42
43#[derive(Debug, Clone, Deserialize)]
44pub struct ColumnIr {
45 pub name: String,
46 #[serde(rename = "type")]
47 pub column_type: String,
48 pub nullable: bool,
49 #[serde(default)]
52 pub encrypted: bool,
53 #[serde(default, rename = "declaredType")]
55 pub declared_type: Option<String>,
56 #[serde(default, rename = "serverOwned")]
59 pub server_owned: bool,
60}
61
62#[derive(Debug, Clone, Deserialize)]
64pub struct IndexIr {
65 pub name: String,
66 pub columns: Vec<String>,
67 pub unique: bool,
68}
69
70#[derive(Debug, Clone, Deserialize)]
71#[serde(rename_all = "camelCase", deny_unknown_fields)]
72pub struct LocalProjection {
73 pub name: String,
74 pub generation: String,
75 pub columns: Vec<ProjectionColumn>,
76 pub fts: Option<ProjectionFts>,
77 #[serde(default)]
78 pub dependencies: Vec<ProjectionDependency>,
79}
80
81#[derive(Debug, Clone, Deserialize)]
82#[serde(rename_all = "camelCase", deny_unknown_fields)]
83pub struct ProjectionColumn {
84 pub name: String,
85 pub declared_type: ProjectionType,
86 #[serde(default)]
89 pub source: Option<String>,
90}
91
92impl LocalProjection {
93 pub fn built_in(&self) -> bool {
95 self.columns.iter().any(|column| column.source.is_some())
96 }
97}
98
99#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
100#[serde(rename_all = "lowercase")]
101pub enum ProjectionType {
102 String,
103 Integer,
104 Real,
105 Boolean,
106 Json,
107}
108
109#[derive(Debug, Clone, Deserialize)]
110#[serde(deny_unknown_fields)]
111pub struct ProjectionFts {
112 pub tokenize: String,
113 pub columns: Vec<String>,
114}
115
116#[derive(Debug, Clone, Deserialize)]
117#[serde(rename_all = "camelCase", deny_unknown_fields)]
118pub struct ProjectionDependency {
119 pub table: String,
120 pub column: String,
121 pub source_column: String,
122}
123
124fn fts_tokenizer(tokenizer: &str) -> bool {
125 matches!(
126 tokenizer,
127 "unicode61"
128 | "unicode61 remove_diacritics 0"
129 | "unicode61 remove_diacritics 1"
130 | "unicode61 remove_diacritics 2"
131 | "porter unicode61"
132 | "trigram"
133 )
134}
135
136#[derive(Debug, Clone)]
138pub struct IndexSchema {
139 pub name: String,
140 pub columns: Vec<String>,
141 pub unique: bool,
142}
143
144#[derive(Debug, Clone, Deserialize)]
145pub struct ScopePatternIr {
146 pub pattern: String,
147 #[serde(default)]
148 pub column: Option<String>,
149}
150
151#[derive(Debug, Clone)]
153pub struct ScopeVariable {
154 pub variable: String,
155 pub column: String,
156 pub prefix: String,
157}
158
159#[derive(Debug, Clone)]
163pub struct EncryptedColumn {
164 pub index: usize,
165 pub declared_type: String,
166}
167
168#[derive(Debug, Clone)]
169pub struct TableSchema {
170 pub name: String,
171 pub columns: Vec<Column>,
176 pub wire_columns: Vec<Column>,
181 pub primary_key: String,
182 pub pk_index: usize,
183 pub scope_variables: Vec<ScopeVariable>,
184 pub indexes: Vec<IndexSchema>,
186 pub local_projections: Vec<LocalProjection>,
187 pub encrypted_columns: Vec<EncryptedColumn>,
189 pub server_owned_columns: Vec<usize>,
191 pub generation: Option<String>,
193 pub equivalent_generations: Vec<String>,
195}
196
197impl TableSchema {
198 pub fn has_encrypted_columns(&self) -> bool {
200 !self.encrypted_columns.is_empty()
201 }
202
203 pub fn sealed_columns(&self) -> &'static [&'static str] {
207 if self.has_encrypted_columns() {
208 &["_sync_sealed_key", "_sync_sealed"]
209 } else {
210 &[]
211 }
212 }
213}
214
215impl TableSchema {
216 pub fn scope_column(&self, variable: &str) -> Option<&str> {
219 self.scope_variables
220 .iter()
221 .find(|s| s.variable == variable)
222 .map(|s| s.column.as_str())
223 }
224}
225
226#[derive(Debug, Clone)]
227pub struct ClientSchema {
228 pub version: i32,
229 pub tables: Vec<TableSchema>,
230}
231
232impl ClientSchema {
233 pub fn table(&self, name: &str) -> Option<&TableSchema> {
234 self.tables.iter().find(|t| t.name == name)
235 }
236}
237
238fn parse_column_type(name: &str) -> Result<ColumnType, String> {
239 match name {
240 "string" => Ok(ColumnType::String),
241 "integer" => Ok(ColumnType::Integer),
242 "float" => Ok(ColumnType::Float),
243 "boolean" => Ok(ColumnType::Boolean),
244 "json" => Ok(ColumnType::Json),
245 "bytes" => Ok(ColumnType::Bytes),
246 "blob_ref" => Ok(ColumnType::BlobRef),
247 "crdt" => Ok(ColumnType::Crdt),
248 other => Err(format!("unknown column type {other:?}")),
249 }
250}
251
252fn parse_pattern_variable(pattern: &str) -> Result<String, String> {
254 let open = pattern
255 .find('{')
256 .ok_or_else(|| format!("scope pattern {pattern:?} has no {{variable}}"))?;
257 let close = pattern
258 .rfind('}')
259 .filter(|end| *end > open)
260 .ok_or_else(|| format!("scope pattern {pattern:?} has no closing brace"))?;
261 let variable = &pattern[open + 1..close];
262 if variable.is_empty() {
263 return Err(format!("scope pattern {pattern:?} has an empty variable"));
264 }
265 Ok(variable.to_owned())
266}
267
268pub fn compile_schema(ir: &SchemaIr) -> Result<ClientSchema, String> {
269 if ir.version < 1 {
274 return Err(
275 "sync.invalid_request: generated schema version must be an integer in 1..=2147483647"
276 .to_owned(),
277 );
278 }
279 let mut tables = Vec::with_capacity(ir.tables.len());
280 let mut schema_object_names = BTreeSet::new();
281 for table in &ir.tables {
282 if table.fts_indexes.is_some() {
283 return Err(format!(
284 "client.schema_invalid: table {:?} declares ftsIndexes; regenerate the schema",
285 table.name
286 ));
287 }
288 if !schema_object_names.insert(table.name.clone()) {
289 return Err(format!("duplicate table or schema object {:?}", table.name));
290 }
291 }
292 for table in &ir.tables {
293 let mut wire_columns = Vec::with_capacity(table.columns.len());
297 let mut columns = Vec::with_capacity(table.columns.len());
298 let mut encrypted_columns = Vec::new();
299 let mut server_owned_columns = Vec::new();
300 for (index, column) in table.columns.iter().enumerate() {
301 if column.server_owned {
303 server_owned_columns.push(index);
304 }
305 let wire_ty = parse_column_type(&column.column_type)?;
306 wire_columns.push(Column {
307 name: column.name.clone(),
308 ty: wire_ty,
309 nullable: column.nullable,
310 });
311 if column.encrypted {
312 let declared_name = column.declared_type.clone().ok_or_else(|| {
313 format!(
314 "table {:?}: encrypted column {:?} has no declaredType (§5.11)",
315 table.name, column.name
316 )
317 })?;
318 let declared_ty = parse_column_type(&declared_name)?;
319 columns.push(Column {
320 name: column.name.clone(),
321 ty: declared_ty,
322 nullable: column.nullable,
323 });
324 encrypted_columns.push(EncryptedColumn {
325 index,
326 declared_type: declared_name,
327 });
328 } else {
329 columns.push(Column {
330 name: column.name.clone(),
331 ty: wire_ty,
332 nullable: column.nullable,
333 });
334 }
335 }
336 let pk_index = columns
337 .iter()
338 .position(|c| c.name == table.primary_key)
339 .ok_or_else(|| {
340 format!(
341 "table {:?}: primary key {:?} is not a column",
342 table.name, table.primary_key
343 )
344 })?;
345 if !matches!(
349 columns[pk_index].ty,
350 ColumnType::String | ColumnType::Integer | ColumnType::Boolean | ColumnType::Json
351 ) {
352 return Err(format!(
353 "table {:?}: primary key {:?} has an ineligible column type (§2.4); a primary key must be string, integer, boolean, or json",
354 table.name, table.primary_key
355 ));
356 }
357 let mut scope_variables = Vec::with_capacity(table.scopes.len());
358 for scope in &table.scopes {
359 let variable = parse_pattern_variable(&scope.pattern)?;
360 let column = scope.column.clone().unwrap_or_else(|| variable.clone());
361 if !columns.iter().any(|c| {
362 c.name == column && matches!(c.ty, ColumnType::String | ColumnType::Integer)
363 }) {
364 return Err(format!(
365 "table {:?}: scope column {column:?} must be a string or integer column (§3.1)",
366 table.name
367 ));
368 }
369 let open = scope.pattern.find('{').expect("validated scope pattern");
370 let prefix = scope.pattern[..open]
371 .strip_suffix(':')
372 .unwrap_or(&scope.pattern[..open])
373 .to_owned();
374 scope_variables.push(ScopeVariable {
375 variable,
376 column,
377 prefix,
378 });
379 }
380 let mut indexes = Vec::with_capacity(table.indexes.len());
381 for index in &table.indexes {
382 if !schema_object_names.insert(index.name.clone()) {
383 return Err(format!(
384 "table {:?}: index {:?} conflicts with another schema object",
385 table.name, index.name
386 ));
387 }
388 for col in &index.columns {
389 if !columns.iter().any(|c| &c.name == col) {
390 return Err(format!(
391 "table {:?}: index {:?} names unknown column {col:?}",
392 table.name, index.name
393 ));
394 }
395 }
396 indexes.push(IndexSchema {
397 name: index.name.clone(),
398 columns: index.columns.clone(),
399 unique: index.unique,
400 });
401 }
402 if table.generation.as_deref() == Some("") {
403 return Err(format!(
404 "table {:?}: generation must be a non-empty string (§7.4.3)",
405 table.name
406 ));
407 }
408 tables.push(TableSchema {
409 generation: table.generation.clone(),
410 equivalent_generations: table.equivalent_generations.clone(),
411 name: table.name.clone(),
412 columns,
413 wire_columns,
414 primary_key: table.primary_key.clone(),
415 pk_index,
416 scope_variables,
417 indexes,
418 local_projections: table.local_projections.clone(),
419 encrypted_columns,
420 server_owned_columns,
421 });
422 }
423 let mut names: BTreeSet<_> = schema_object_names
424 .into_iter()
425 .map(|name| name.to_ascii_lowercase())
426 .collect();
427 for source in &tables {
428 for spec in &source.local_projections {
429 let invalid =
430 || "client.schema_invalid: invalid local projection declaration".to_owned();
431 let valid_ident = |name: &str| {
432 let lower = name.to_ascii_lowercase();
433 name.len() <= 63
434 && !lower.starts_with("_sync")
435 && !lower.starts_with("sync_")
436 && !lower.starts_with("sqlite_")
437 && name
438 .bytes()
439 .next()
440 .is_some_and(|byte| byte.is_ascii_alphabetic() || byte == b'_')
441 && name
442 .bytes()
443 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
444 };
445 let lower = spec.name.to_ascii_lowercase();
446 if !valid_ident(&spec.name)
447 || !names.insert(lower.clone())
448 || spec.generation.is_empty()
449 || spec.columns.is_empty()
450 || spec.fts.as_ref().is_some_and(|fts| {
451 !fts_tokenizer(&fts.tokenize)
452 || fts.columns.is_empty()
453 || fts.columns.iter().collect::<BTreeSet<_>>().len() != fts.columns.len()
454 || !fts.columns.iter().all(|field| {
455 spec.columns.iter().any(|col| {
456 col.name == *field && col.declared_type == ProjectionType::String
457 })
458 })
459 })
460 {
461 return Err(invalid());
462 }
463 if spec.built_in()
466 && (spec.fts.is_none()
467 || !spec.dependencies.is_empty()
468 || !spec.columns.iter().all(|column| {
469 column.declared_type == ProjectionType::String
470 && column.source.as_ref().is_some_and(|name| {
471 source.columns.iter().any(|col| {
472 col.name == *name && matches!(col.ty, ColumnType::String)
473 })
474 })
475 }))
476 {
477 return Err(invalid());
478 }
479 let mut columns = BTreeSet::new();
480 if spec.fts.is_some() {
481 columns.extend([lower, "rank".to_owned(), "rowid".to_owned()]);
482 }
483 for column in &spec.columns {
484 if !valid_ident(&column.name) || !columns.insert(column.name.to_ascii_lowercase()) {
485 return Err(invalid());
486 }
487 }
488 for dependency in &spec.dependencies {
489 let dep = tables
490 .iter()
491 .find(|table| table.name == dependency.table)
492 .ok_or_else(invalid)?;
493 let plaintext = |table: &TableSchema, name: &str| {
494 table
495 .columns
496 .iter()
497 .position(|col| col.name == name)
498 .is_some_and(|index| {
499 !table.encrypted_columns.iter().any(|col| col.index == index)
500 })
501 };
502 if !plaintext(dep, &dependency.column)
503 || !plaintext(source, &dependency.source_column)
504 || (dependency.source_column != source.primary_key
505 && !source
506 .indexes
507 .iter()
508 .any(|index| index.columns.first() == Some(&dependency.source_column)))
509 {
510 return Err(invalid());
511 }
512 }
513 }
514 }
515 Ok(ClientSchema {
516 version: ir.version,
517 tables,
518 })
519}
520
521pub fn parse_schema_json(json: &serde_json::Value) -> Result<ClientSchema, String> {
522 let version = json
528 .get("version")
529 .or_else(|| json.get("schemaVersion"))
530 .and_then(serde_json::Value::as_i64);
531 if !version.is_some_and(|version| (1..=i32::MAX as i64).contains(&version)) {
532 return Err(
533 "sync.invalid_request: generated schema version must be an integer in 1..=2147483647"
534 .to_owned(),
535 );
536 }
537 let ir: SchemaIr = serde_json::from_value(json.clone()).map_err(|e| {
538 if json
539 .get("tables")
540 .and_then(serde_json::Value::as_array)
541 .is_some_and(|tables| {
542 tables.iter().any(|table| {
543 table.get("localProjections").is_some_and(|projections| {
544 serde_json::from_value::<Vec<LocalProjection>>(projections.clone()).is_err()
545 })
546 })
547 })
548 {
549 "client.schema_invalid: invalid local projection declaration".to_owned()
550 } else {
551 format!("bad schema IR: {e}")
552 }
553 })?;
554 compile_schema(&ir)
555}
556
557#[cfg(test)]
558mod tests {
559 use super::*;
560 use serde_json::json;
561
562 fn schema_with_fts(column: serde_json::Value, tokenize: &str) -> serde_json::Value {
563 json!({
564 "version": 1,
565 "tables": [{
566 "name": "docs",
567 "primaryKey": "id",
568 "columns": [
569 { "name": "id", "type": "string", "nullable": false },
570 { "name": "org_id", "type": "string", "nullable": false },
571 column
572 ],
573 "scopes": [{ "pattern": "org:{org_id}" }],
574 "localProjections": [{
575 "name": "docs_fts",
576 "generation": "1",
577 "columns": [{ "name": "body", "declaredType": "string", "source": "body" }],
578 "fts": { "tokenize": tokenize, "columns": ["body"] }
579 }]
580 }]
581 })
582 }
583
584 #[test]
585 fn accepts_the_schema_version_alias_and_refuses_conflicting_spellings() {
586 let schema = json!({
587 "schemaVersion": 2,
588 "tables": [{
589 "name": "tasks",
590 "primaryKey": "id",
591 "columns": [{ "name": "id", "type": "string", "nullable": false }],
592 "scopes": []
593 }]
594 });
595 let compiled = parse_schema_json(&schema).expect("the server IR alias compiles");
596 assert_eq!(compiled.version, 2);
597 let mut both = schema.clone();
600 both["version"] = json!(3);
601 let error = parse_schema_json(&both).expect_err("duplicate version spellings");
602 assert!(error.starts_with("bad schema IR:"), "{error}");
603 let mut out_of_range = schema.clone();
605 out_of_range["schemaVersion"] = json!(0);
606 let error = parse_schema_json(&out_of_range).expect_err("out-of-range alias");
607 assert!(error.starts_with("sync.invalid_request:"), "{error}");
608 }
609
610 #[test]
611 fn carries_equivalent_generations_and_refuses_a_non_string_list() {
612 let table = |list: serde_json::Value| {
613 json!({
614 "version": 1,
615 "tables": [{
616 "name": "tasks",
617 "generation": "g2",
618 "equivalentGenerations": list,
619 "primaryKey": "id",
620 "columns": [{ "name": "id", "type": "string", "nullable": false }],
621 "scopes": []
622 }]
623 })
624 };
625 let compiled = parse_schema_json(&table(json!(["g1"]))).expect("a string list compiles");
626 assert_eq!(compiled.tables[0].equivalent_generations, ["g1"]);
627 for list in [json!("g1"), json!([1])] {
628 let error = parse_schema_json(&table(list)).expect_err("a non-string list");
629 assert!(error.starts_with("bad schema IR:"), "{error}");
630 }
631 }
632
633 #[test]
634 fn compiles_server_owned_column_indices() {
635 let compiled = parse_schema_json(&json!({
636 "version": 1,
637 "tables": [{
638 "name": "tasks",
639 "primaryKey": "id",
640 "columns": [
641 { "name": "id", "type": "string", "nullable": false },
642 { "name": "title", "type": "string", "nullable": true },
643 { "name": "stamp", "type": "string", "nullable": true, "serverOwned": true }
644 ],
645 "scopes": []
646 }]
647 }))
648 .expect("compiles");
649 assert_eq!(compiled.tables[0].server_owned_columns, vec![2]);
650 }
651
652 #[test]
653 fn compiles_an_allowlisted_string_fts_projection() {
654 let schema = parse_schema_json(&schema_with_fts(
655 json!({ "name": "body", "type": "string", "nullable": false }),
656 "unicode61 remove_diacritics 2",
657 ))
658 .expect("valid FTS schema");
659 assert!(schema.tables[0].local_projections[0].built_in());
660 }
661
662 #[test]
663 fn accepts_encrypted_declared_strings_and_rejects_other_fts_definitions() {
664 let encrypted = schema_with_fts(
665 json!({
666 "name": "body", "type": "bytes", "nullable": false,
667 "encrypted": true, "declaredType": "string"
668 }),
669 "unicode61",
670 );
671 parse_schema_json(&encrypted).expect("local plaintext FTS accepts encrypted strings");
672
673 let non_string = schema_with_fts(
674 json!({ "name": "body", "type": "integer", "nullable": false }),
675 "unicode61",
676 );
677 assert!(parse_schema_json(&non_string)
678 .expect_err("non-string FTS must fail")
679 .starts_with("client.schema_invalid:"));
680
681 let tokenizer = schema_with_fts(
682 json!({ "name": "body", "type": "string", "nullable": false }),
683 "custom",
684 );
685 assert!(parse_schema_json(&tokenizer)
686 .expect_err("custom tokenizer must fail")
687 .starts_with("client.schema_invalid:"));
688 }
689
690 #[test]
691 fn refuses_a_schema_that_still_carries_fts_indexes() {
692 let mut schema = schema_with_fts(
693 json!({ "name": "body", "type": "string", "nullable": false }),
694 "unicode61",
695 );
696 schema["tables"][0]["ftsIndexes"] = json!([]);
697 let error = parse_schema_json(&schema).expect_err("ftsIndexes is refused");
698 assert!(
699 error.starts_with("client.schema_invalid:") && error.contains("ftsIndexes"),
700 "{error}"
701 );
702 }
703
704 #[test]
705 fn refuses_a_mixed_or_fts_less_built_in_projection() {
706 let body = json!({ "name": "body", "type": "string", "nullable": false });
707 let mut mixed = schema_with_fts(body.clone(), "unicode61");
708 mixed["tables"][0]["localProjections"][0]["columns"]
709 .as_array_mut()
710 .unwrap()
711 .push(json!({ "name": "note", "declaredType": "string" }));
712 let mut without_fts = schema_with_fts(body.clone(), "unicode61");
713 without_fts["tables"][0]["localProjections"][0]
714 .as_object_mut()
715 .unwrap()
716 .remove("fts");
717 let mut unknown_source = schema_with_fts(body, "unicode61");
718 unknown_source["tables"][0]["localProjections"][0]["columns"][0]["source"] =
719 json!("missing");
720 for schema in [mixed, without_fts, unknown_source] {
721 assert_eq!(
722 parse_schema_json(&schema).expect_err("invalid built-in projection"),
723 "client.schema_invalid: invalid local projection declaration"
724 );
725 }
726 }
727}