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