surrealkit 0.6.3

Manage migrations, seeding and tests for your SurrealDB via CLI
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
use std::collections::{BTreeMap, BTreeSet};
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};
use walkdir::WalkDir;

use crate::core::sha256_hex;

pub const SCHEMA_DIR: &str = "database/schema";
pub const ROLLOUTS_DIR: &str = "database/rollouts";
pub const STATE_DIR: &str = "database/snapshots";
pub const SCHEMA_SNAPSHOT_PATH: &str = "database/snapshots/schema_snapshot.json";
pub const CATALOG_SNAPSHOT_PATH: &str = "database/snapshots/catalog_snapshot.json";

#[derive(Debug, Clone)]
pub struct SchemaFile {
	pub path: String,
	pub sql: String,
	pub hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct SchemaSnapshot {
	pub version: u32,
	pub files: Vec<SchemaSnapshotEntry>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct SchemaSnapshotEntry {
	pub path: String,
	pub hash: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
pub struct CatalogSnapshot {
	pub version: u32,
	pub entities: Vec<CatalogEntity>,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct EntityKey {
	pub kind: String,
	pub scope: Option<String>,
	pub name: String,
}

#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub struct CatalogEntity {
	pub kind: String,
	pub scope: Option<String>,
	pub name: String,
	pub source_path: String,
	pub statement_hash: String,
	pub file_hash: String,
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct FileDiff {
	pub added: Vec<String>,
	pub modified: Vec<String>,
	pub removed: Vec<String>,
}

#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct CatalogDiff {
	pub added: Vec<CatalogEntity>,
	pub removed: Vec<CatalogEntity>,
	pub modified: Vec<CatalogChange>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CatalogChange {
	pub old: CatalogEntity,
	pub new: CatalogEntity,
}

impl CatalogEntity {
	pub fn key(&self) -> EntityKey {
		EntityKey {
			kind: self.kind.clone(),
			scope: self.scope.clone(),
			name: self.name.clone(),
		}
	}
}

pub fn ensure_local_state_dirs() -> Result<()> {
	fs::create_dir_all(SCHEMA_DIR).with_context(|| format!("creating {}", SCHEMA_DIR))?;
	fs::create_dir_all(ROLLOUTS_DIR).with_context(|| format!("creating {}", ROLLOUTS_DIR))?;
	fs::create_dir_all(STATE_DIR).with_context(|| format!("creating {}", STATE_DIR))?;
	Ok(())
}

pub fn collect_schema_files() -> Result<Vec<SchemaFile>> {
	let mut files: Vec<PathBuf> = WalkDir::new(SCHEMA_DIR)
		.follow_links(true)
		.into_iter()
		.filter_map(|e| e.ok())
		.filter(|e| e.file_type().is_file())
		.map(|e| e.into_path())
		.filter(|p| p.extension().and_then(|s| s.to_str()) == Some("surql"))
		.collect();

	files.sort();

	let mut out = Vec::with_capacity(files.len());
	for path in files {
		let sql = fs::read_to_string(&path).with_context(|| format!("reading {:?}", path))?;
		let hash = sha256_hex(sql.as_bytes());
		let path_str = normalize_path(&path)?;
		out.push(SchemaFile {
			path: path_str,
			sql,
			hash,
		});
	}

	Ok(out)
}

pub fn snapshot_from_files(files: &[SchemaFile]) -> SchemaSnapshot {
	let mut entries: Vec<SchemaSnapshotEntry> = files
		.iter()
		.map(|f| SchemaSnapshotEntry {
			path: f.path.clone(),
			hash: f.hash.clone(),
		})
		.collect();
	entries.sort();
	SchemaSnapshot {
		version: 1,
		files: entries,
	}
}

pub fn hash_schema_snapshot(snapshot: &SchemaSnapshot) -> Result<String> {
	let canonical = serde_json::to_vec(snapshot).context("serializing schema snapshot")?;
	Ok(sha256_hex(&canonical))
}

pub fn load_schema_snapshot() -> Result<SchemaSnapshot> {
	load_json_or_default(
		SCHEMA_SNAPSHOT_PATH,
		SchemaSnapshot {
			version: 1,
			files: Vec::new(),
		},
	)
}

pub fn save_schema_snapshot(snapshot: &SchemaSnapshot) -> Result<()> {
	save_json_pretty(SCHEMA_SNAPSHOT_PATH, snapshot)
}

pub fn load_catalog_snapshot() -> Result<CatalogSnapshot> {
	load_json_or_default(
		CATALOG_SNAPSHOT_PATH,
		CatalogSnapshot {
			version: 2,
			entities: Vec::new(),
		},
	)
}

pub fn save_catalog_snapshot(snapshot: &CatalogSnapshot) -> Result<()> {
	save_json_pretty(CATALOG_SNAPSHOT_PATH, snapshot)
}

pub fn diff_schema(old: &SchemaSnapshot, new: &SchemaSnapshot) -> FileDiff {
	let old_map: BTreeMap<&str, &str> =
		old.files.iter().map(|f| (f.path.as_str(), f.hash.as_str())).collect();
	let new_map: BTreeMap<&str, &str> =
		new.files.iter().map(|f| (f.path.as_str(), f.hash.as_str())).collect();

	let mut added = Vec::new();
	let mut modified = Vec::new();
	let mut removed = Vec::new();

	for (path, hash) in &new_map {
		match old_map.get(path) {
			None => added.push((*path).to_string()),
			Some(old_hash) if old_hash != hash => modified.push((*path).to_string()),
			_ => {}
		}
	}

	for path in old_map.keys() {
		if !new_map.contains_key(path) {
			removed.push((*path).to_string());
		}
	}

	FileDiff {
		added,
		modified,
		removed,
	}
}

pub fn build_catalog_snapshot(files: &[SchemaFile]) -> Result<CatalogSnapshot> {
	let mut entities = BTreeSet::new();
	for file in files {
		let statements = parse_schema_statements(file)?;
		for entity in statements {
			entities.insert(entity);
		}
	}

	Ok(CatalogSnapshot {
		version: 2,
		entities: entities.into_iter().collect(),
	})
}

pub fn parse_schema_statements(file: &SchemaFile) -> Result<Vec<CatalogEntity>> {
	let mut entities = Vec::new();
	for stmt in split_statements(&strip_comments(&file.sql)) {
		let normalized = stmt.trim();
		if normalized.is_empty() {
			continue;
		}
		let upper = normalized.to_ascii_uppercase();
		if upper.starts_with("REMOVE ") {
			bail!(
				"schema file '{}' contains a REMOVE statement; destructive SQL must live in rollout steps",
				file.path
			);
		}
		if upper.starts_with("LET ") {
			continue;
		}
		if !upper.starts_with("DEFINE ") {
			bail!(
				"schema file '{}' contains a non-DEFINE statement: '{}'",
				file.path,
				truncate_stmt(normalized)
			);
		}
		let after_define = upper["DEFINE ".len()..].trim_start();
		if after_define.starts_with("NAMESPACE") || after_define.starts_with("DATABASE") {
			bail!(
				"schema file '{}' contains DEFINE NAMESPACE/DATABASE, which surrealkit does not manage: \
sync runs inside an already-selected namespace/database. Provision these out-of-band.",
				file.path
			);
		}
		let Some(mut entity) = parse_define_entity(normalized) else {
			bail!(
				"schema file '{}' contains an unsupported DEFINE statement: '{}'",
				file.path,
				truncate_stmt(normalized)
			);
		};
		entity.source_path = file.path.clone();
		entity.file_hash = file.hash.clone();
		entity.statement_hash = sha256_hex(normalize_statement(normalized).as_bytes());
		entities.push(entity);
	}
	Ok(entities)
}

pub fn catalog_snapshot_to_map(snapshot: &CatalogSnapshot) -> BTreeMap<EntityKey, CatalogEntity> {
	snapshot.entities.iter().cloned().map(|entity| (entity.key(), entity)).collect()
}

pub fn diff_catalog(old: &CatalogSnapshot, new: &CatalogSnapshot) -> CatalogDiff {
	let old_map = catalog_snapshot_to_map(old);
	let new_map = catalog_snapshot_to_map(new);
	let mut diff = CatalogDiff::default();

	for (key, new_entity) in &new_map {
		match old_map.get(key) {
			None => diff.added.push(new_entity.clone()),
			Some(old_entity) if old_entity.statement_hash != new_entity.statement_hash => {
				diff.modified.push(CatalogChange {
					old: old_entity.clone(),
					new: new_entity.clone(),
				});
			}
			_ => {}
		}
	}

	for (key, old_entity) in &old_map {
		if !new_map.contains_key(key) {
			diff.removed.push(old_entity.clone());
		}
	}

	diff.added.sort();
	diff.removed.sort();
	diff.modified.sort_by(|a, b| a.old.cmp(&b.old));
	diff
}

pub fn render_remove_sql(entities: &[EntityKey], api_supported: bool) -> Result<Vec<String>> {
	let mut ordered = entities.to_vec();
	ordered.sort_by_key(removal_sort_key);

	let mut out = Vec::new();
	for entity in ordered {
		let stmt = match entity.kind.as_str() {
			"field" => {
				format!("REMOVE FIELD {} ON {};", entity.name, scope_or_err(&entity, "FIELD")?)
			}
			"event" => {
				format!("REMOVE EVENT {} ON {};", entity.name, scope_or_err(&entity, "EVENT")?)
			}
			"index" => {
				format!("REMOVE INDEX {} ON {};", entity.name, scope_or_err(&entity, "INDEX")?)
			}
			"table" => format!("REMOVE TABLE {};", entity.name),
			"function" => format!("REMOVE FUNCTION {};", entity.name),
			"param" => format!("REMOVE PARAM {};", entity.name),
			"access" => match &entity.scope {
				Some(scope) => format!("REMOVE ACCESS {} ON {};", entity.name, scope),
				None => format!("REMOVE ACCESS {};", entity.name),
			},
			"analyzer" => format!("REMOVE ANALYZER {};", entity.name),
			"user" => match &entity.scope {
				Some(scope) => format!("REMOVE USER {} ON {};", entity.name, scope),
				None => format!("REMOVE USER {};", entity.name),
			},
			"api" => {
				if api_supported {
					format!("REMOVE API {};", entity.name)
				} else {
					bail!(
						"API removal requested for '{}' but this SurrealDB server does not support `REMOVE API`. \
Use a manual migration or upgrade server support.",
						entity.name
					);
				}
			}
			"bucket" => format!("REMOVE BUCKET {};", entity.name),
			"model" => format!("REMOVE MODEL {};", entity.name),
			"sequence" => format!("REMOVE SEQUENCE {};", entity.name),
			"config" => format!("REMOVE CONFIG {};", entity.name),
			_ => continue,
		};
		out.push(stmt);
	}
	Ok(out)
}

fn scope_or_err(entity: &EntityKey, object: &str) -> Result<String> {
	entity.scope.clone().ok_or_else(|| {
		anyhow!("cannot render REMOVE {} for '{}' because scope is missing", object, entity.name)
	})
}

fn removal_sort_key(entity: &EntityKey) -> (usize, Option<String>, String, String) {
	let weight = match entity.kind.as_str() {
		"index" => 0,
		"event" => 1,
		"field" => 2,
		"access" => 3,
		"user" => 4,
		"function" => 5,
		"param" => 6,
		"api" => 7,
		"analyzer" => 8,
		"bucket" => 9,
		"model" => 10,
		"sequence" => 11,
		"config" => 12,
		"table" => 13,
		_ => 14,
	};
	(weight, entity.scope.clone(), entity.kind.clone(), entity.name.clone())
}

fn normalize_path(path: &Path) -> Result<String> {
	let cwd = std::env::current_dir().context("resolving current directory")?;
	let rel = path.strip_prefix(&cwd).or_else(|_| path.strip_prefix(".")).unwrap_or(path);
	Ok(rel.to_string_lossy().replace('\\', "/"))
}

fn load_json_or_default<T>(path: &str, default: T) -> Result<T>
where
	T: for<'de> Deserialize<'de>,
{
	let p = Path::new(path);
	if !p.exists() {
		return Ok(default);
	}

	let raw = fs::read_to_string(p).with_context(|| format!("reading {}", path))?;
	let parsed = serde_json::from_str(&raw).with_context(|| format!("parsing {}", path))?;
	Ok(parsed)
}

fn save_json_pretty<T>(path: &str, value: &T) -> Result<()>
where
	T: Serialize,
{
	ensure_local_state_dirs()?;
	let raw = serde_json::to_string_pretty(value).context("serializing json")?;
	fs::write(path, format!("{raw}\n")).with_context(|| format!("writing {}", path))?;
	Ok(())
}

/// Ensures every `DEFINE` statement includes the `OVERWRITE` modifier so that
/// sync can re-apply schemas idempotently against an existing database.
pub fn ensure_overwrite(sql: &str) -> String {
	let stmts = split_statements(&strip_comments(sql));
	let mut out = Vec::with_capacity(stmts.len());
	for stmt in stmts {
		let trimmed = stmt.trim();
		if trimmed.is_empty() {
			continue;
		}
		let upper = trimmed.to_ascii_uppercase();
		if upper.starts_with("DEFINE ") {
			let tokens: Vec<&str> = trimmed.splitn(4, char::is_whitespace).collect();
			// tokens: ["DEFINE", "<KIND>", ...]
			if tokens.len() >= 3 {
				let after_kind = &trimmed[tokens[0].len()..].trim_start();
				let after_kind_word = &after_kind[tokens[1].len()..].trim_start();
				let rest_upper = after_kind_word.to_ascii_uppercase();
				if rest_upper.starts_with("OVERWRITE") {
					out.push(format!("{};", trimmed));
				} else if rest_upper.starts_with("IF NOT EXISTS") {
					// Replace IF NOT EXISTS with OVERWRITE so sync always applies the latest
					// schema; IF NOT EXISTS would silently skip updates to existing entities.
					let after_ine = after_kind_word["IF NOT EXISTS".len()..].trim_start();
					out.push(format!("DEFINE {} OVERWRITE {};", tokens[1], after_ine));
				} else {
					out.push(format!("DEFINE {} OVERWRITE {};", tokens[1], after_kind_word));
				}
			} else {
				out.push(format!("{};", trimmed));
			}
		} else {
			out.push(format!("{};", trimmed));
		}
	}
	out.join("\n")
}

fn strip_comments(sql: &str) -> String {
	let mut out = String::with_capacity(sql.len());
	let mut chars = sql.chars().peekable();
	let mut in_single = false;
	let mut in_double = false;
	let mut in_backtick = false;
	let mut prev_escape = false;

	while let Some(ch) = chars.next() {
		let in_string = in_single || in_double || in_backtick;
		if !in_string && !prev_escape {
			// Line comments: --, //, #
			if (ch == '-' || ch == '/') && chars.peek() == Some(&ch) {
				chars.next();
				for c in chars.by_ref() {
					if c == '\n' {
						out.push('\n');
						break;
					}
				}
				prev_escape = false;
				continue;
			}
			if ch == '#' {
				for c in chars.by_ref() {
					if c == '\n' {
						out.push('\n');
						break;
					}
				}
				prev_escape = false;
				continue;
			}
			// Block comment: /* ... */ (non-nesting, preserves newlines so line numbers stay sane)
			if ch == '/' && chars.peek() == Some(&'*') {
				chars.next();
				let mut prev = '\0';
				for c in chars.by_ref() {
					if c == '\n' {
						out.push('\n');
					}
					if prev == '*' && c == '/' {
						break;
					}
					prev = c;
				}
				out.push(' ');
				prev_escape = false;
				continue;
			}
		}

		match ch {
			'\'' if !in_double && !in_backtick && !prev_escape => in_single = !in_single,
			'"' if !in_single && !in_backtick && !prev_escape => in_double = !in_double,
			'`' if !in_single && !in_double && !prev_escape => in_backtick = !in_backtick,
			_ => {}
		}
		prev_escape = ch == '\\' && !prev_escape;
		out.push(ch);
	}
	out
}

fn split_statements(sql: &str) -> Vec<String> {
	let mut out = Vec::new();
	let mut buf = String::new();
	let mut in_single = false;
	let mut in_double = false;
	let mut in_backtick = false;
	let mut prev_escape = false;
	let mut brace_depth = 0usize;

	for ch in sql.chars() {
		match ch {
			'\'' if !in_double && !in_backtick && !prev_escape => in_single = !in_single,
			'"' if !in_single && !in_backtick && !prev_escape => in_double = !in_double,
			'`' if !in_single && !in_double && !prev_escape => in_backtick = !in_backtick,
			'{' if !in_single && !in_double && !in_backtick => brace_depth += 1,
			'}' if !in_single && !in_double && !in_backtick && brace_depth > 0 => brace_depth -= 1,
			';' if !in_single && !in_double && !in_backtick && brace_depth == 0 => {
				let stmt = buf.trim();
				if !stmt.is_empty() {
					out.push(stmt.to_string());
				}
				buf.clear();
				prev_escape = false;
				continue;
			}
			_ => {}
		}

		prev_escape = ch == '\\' && !prev_escape;
		buf.push(ch);
	}

	let tail = buf.trim();
	if !tail.is_empty() {
		out.push(tail.to_string());
	}

	out
}

fn parse_define_entity(stmt: &str) -> Option<CatalogEntity> {
	let tokens = tokenize(stmt);
	if tokens.len() < 3 || !eq(tokens[0], "DEFINE") {
		return None;
	}

	let kind = tokens[1].to_ascii_lowercase();
	let mut idx = 2;
	idx = skip_modifiers(&tokens, idx);
	if idx >= tokens.len() {
		return None;
	}

	let (scope, name) = match kind.as_str() {
		"table" => (None, clean_ident(tokens[idx])),
		"field" | "event" | "index" => {
			let name = clean_ident(tokens[idx]);
			let on_idx = find_token(&tokens, idx + 1, "ON")?;
			let mut scope_idx = on_idx + 1;
			if scope_idx < tokens.len() && eq(tokens[scope_idx], "TABLE") {
				scope_idx += 1;
			}
			if scope_idx >= tokens.len() {
				return None;
			}
			(Some(clean_ident(tokens[scope_idx])), name)
		}
		"function" | "param" | "analyzer" | "api" | "bucket" | "model" | "sequence" | "config" => {
			(None, clean_ident(tokens[idx]))
		}
		"access" | "user" => {
			let name = clean_ident(tokens[idx]);
			let scope = find_token(&tokens, idx + 1, "ON").and_then(|on_idx| {
				let i = on_idx + 1;
				if i < tokens.len() {
					Some(clean_ident(tokens[i]))
				} else {
					None
				}
			});
			(scope, name)
		}
		_ => return None,
	};

	Some(CatalogEntity {
		kind,
		scope,
		name,
		source_path: String::new(),
		statement_hash: String::new(),
		file_hash: String::new(),
	})
}

fn tokenize(stmt: &str) -> Vec<&str> {
	stmt.split_whitespace().collect()
}

fn clean_ident(token: &str) -> String {
	let trimmed = token.trim_matches(|c: char| {
		c == ',' || c == ';' || c == '(' || c == ')' || c == '{' || c == '}'
	});
	let core = match trimmed.find('(') {
		Some(pos) => &trimmed[..pos],
		None => trimmed,
	};
	core.to_string()
}

fn skip_modifiers(tokens: &[&str], mut idx: usize) -> usize {
	while idx < tokens.len()
		&& (eq(tokens[idx], "OVERWRITE")
			|| eq(tokens[idx], "IF")
			|| eq(tokens[idx], "NOT")
			|| eq(tokens[idx], "EXISTS"))
	{
		idx += 1;
	}
	idx
}

fn find_token(tokens: &[&str], start: usize, target: &str) -> Option<usize> {
	(start..tokens.len()).find(|&i| eq(tokens[i], target))
}

fn eq(value: &str, expected: &str) -> bool {
	value.eq_ignore_ascii_case(expected)
}

fn normalize_statement(stmt: &str) -> String {
	let mut out = String::new();
	let mut prev_space = false;
	for ch in stmt.trim().chars() {
		if ch.is_whitespace() {
			if !prev_space {
				out.push(' ');
			}
			prev_space = true;
		} else {
			out.push(ch);
			prev_space = false;
		}
	}
	out
}

fn truncate_stmt(stmt: &str) -> String {
	const LIMIT: usize = 96;
	if stmt.len() <= LIMIT {
		stmt.to_string()
	} else {
		format!("{}...", &stmt[..LIMIT])
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	#[test]
	fn schema_diff_detects_added_modified_removed() {
		let old = SchemaSnapshot {
			version: 1,
			files: vec![
				SchemaSnapshotEntry {
					path: "database/schema/a.surql".to_string(),
					hash: "1".to_string(),
				},
				SchemaSnapshotEntry {
					path: "database/schema/b.surql".to_string(),
					hash: "2".to_string(),
				},
			],
		};
		let new = SchemaSnapshot {
			version: 1,
			files: vec![
				SchemaSnapshotEntry {
					path: "database/schema/b.surql".to_string(),
					hash: "3".to_string(),
				},
				SchemaSnapshotEntry {
					path: "database/schema/c.surql".to_string(),
					hash: "4".to_string(),
				},
			],
		};

		let diff = diff_schema(&old, &new);
		assert_eq!(diff.added, vec!["database/schema/c.surql"]);
		assert_eq!(diff.modified, vec!["database/schema/b.surql"]);
		assert_eq!(diff.removed, vec!["database/schema/a.surql"]);
	}

	#[test]
	fn catalog_extracts_supported_entities() {
		let files = vec![SchemaFile {
			path: "database/schema/root.surql".to_string(),
			hash: "x".to_string(),
			sql: r#"
				DEFINE TABLE OVERWRITE person SCHEMAFULL;
				DEFINE FIELD OVERWRITE name ON person TYPE string;
				DEFINE EVENT changed ON person WHEN true THEN ();
				DEFINE INDEX by_name ON TABLE person FIELDS name;
				DEFINE FUNCTION fn::greet($name: string) { RETURN $name; };
				DEFINE PARAM $env VALUE "dev";
				DEFINE ACCESS admin ON DATABASE TYPE RECORD;
				DEFINE ANALYZER english TOKENIZERS blank, class;
				DEFINE USER app ON DATABASE PASSHASH "x";
				DEFINE API v1;
				DEFINE BUCKET assets;
				DEFINE SEQUENCE order_no;
				DEFINE CONFIG GRAPHQL AUTO;
			"#
			.to_string(),
		}];

		let catalog = build_catalog_snapshot(&files).expect("catalog build");
		assert!(catalog.entities.contains(&CatalogEntity {
			kind: "table".to_string(),
			scope: None,
			name: "person".to_string(),
			source_path: "database/schema/root.surql".to_string(),
			statement_hash: sha256_hex("DEFINE TABLE OVERWRITE person SCHEMAFULL".as_bytes()),
			file_hash: "x".to_string(),
		}));
		assert!(catalog.entities.iter().any(|entity| {
			entity.kind == "field"
				&& entity.scope.as_deref() == Some("person")
				&& entity.name == "name"
				&& entity.source_path == "database/schema/root.surql"
		}));
		assert!(catalog.entities.iter().any(|entity| entity.kind == "api" && entity.name == "v1"));
		assert!(
			catalog.entities.iter().any(|e| e.kind == "bucket" && e.name == "assets"),
			"bucket should be captured"
		);
		assert!(
			catalog.entities.iter().any(|e| e.kind == "sequence" && e.name == "order_no"),
			"sequence should be captured"
		);
		assert!(
			catalog.entities.iter().any(|e| e.kind == "config" && e.name == "GRAPHQL"),
			"config should be captured by its kind keyword"
		);
	}

	#[test]
	fn schema_rejects_define_namespace_and_database() {
		for stmt in ["DEFINE NAMESPACE prod;", "DEFINE DATABASE prod;"] {
			let file = SchemaFile {
				path: "database/schema/root.surql".to_string(),
				hash: "x".to_string(),
				sql: stmt.to_string(),
			};
			let err = parse_schema_statements(&file)
				.expect_err("DEFINE NAMESPACE/DATABASE must be rejected");
			assert!(
				err.to_string().contains("DEFINE NAMESPACE/DATABASE"),
				"unexpected error for {stmt}: {err}"
			);
		}
	}

	#[test]
	fn render_remove_sql_covers_new_kinds() {
		let entities = vec![
			EntityKey {
				kind: "bucket".to_string(),
				scope: None,
				name: "assets".to_string(),
			},
			EntityKey {
				kind: "sequence".to_string(),
				scope: None,
				name: "order_no".to_string(),
			},
			EntityKey {
				kind: "config".to_string(),
				scope: None,
				name: "GRAPHQL".to_string(),
			},
			EntityKey {
				kind: "model".to_string(),
				scope: None,
				name: "ml::sentiment".to_string(),
			},
		];
		let out = render_remove_sql(&entities, true).expect("remove sql");
		assert!(out.iter().any(|l| l == "REMOVE BUCKET assets;"));
		assert!(out.iter().any(|l| l == "REMOVE SEQUENCE order_no;"));
		assert!(out.iter().any(|l| l == "REMOVE CONFIG GRAPHQL;"));
		assert!(out.iter().any(|l| l == "REMOVE MODEL ml::sentiment;"));
	}

	#[test]
	fn render_remove_sql_respects_api_support() {
		let entities = vec![
			EntityKey {
				kind: "table".to_string(),
				scope: None,
				name: "person".to_string(),
			},
			EntityKey {
				kind: "field".to_string(),
				scope: Some("person".to_string()),
				name: "nickname".to_string(),
			},
			EntityKey {
				kind: "api".to_string(),
				scope: None,
				name: "v1".to_string(),
			},
		];

		let supported = render_remove_sql(&entities, true).expect("api should be supported");
		assert_eq!(supported[0], "REMOVE FIELD nickname ON person;");
		assert!(supported.iter().any(|line| line == "REMOVE API v1;"));
		assert_eq!(supported.last().expect("table removal"), "REMOVE TABLE person;");

		let unsupported = render_remove_sql(&entities, false);
		assert!(unsupported.is_err());
	}

	#[test]
	fn schema_rejects_non_define_sql() {
		let file = SchemaFile {
			path: "database/schema/root.surql".to_string(),
			hash: "x".to_string(),
			sql: "CREATE person SET name = 'a';".to_string(),
		};

		let err = parse_schema_statements(&file).expect_err("must reject create");
		assert!(err.to_string().contains("non-DEFINE"));
	}

	#[test]
	fn schema_allows_inline_dash_dash_comments() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD kind ON foo TYPE string; -- enum: A, B, C\n\
		           DEFINE FIELD name ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("inline -- comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_allows_inline_slash_slash_comments() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD kind ON foo TYPE string; // enum: A, B, C\n\
		           DEFINE FIELD name ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("inline // comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_preserves_dash_dash_inside_string_literal() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD note ON foo TYPE string DEFAULT 'a -- b // c';";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("string literal must be preserved");
		assert_eq!(entities.len(), 2);
		assert!(entities.iter().any(|e| e.name == "note"));
	}

	#[test]
	fn schema_allows_full_line_comments_everywhere() {
		let sql = "-- file header comment\n\
		           // second header line\n\
		           DEFINE TABLE foo SCHEMAFULL;\n\
		           -- between statements\n\
		           DEFINE FIELD a ON foo TYPE string;\n\
		           // also between\n\
		           DEFINE FIELD b ON foo TYPE string;\n\
		           -- trailing comment";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("full-line comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_allows_comment_at_end_of_file_without_newline() {
		let sql = "DEFINE TABLE foo SCHEMAFULL; -- no trailing newline";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities =
			parse_schema_statements(&file).expect("trailing comment without newline must parse");
		assert_eq!(entities.len(), 1);
	}

	#[test]
	fn schema_allows_inline_comment_with_no_space_after_semicolon() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;--tight\n\
		           DEFINE FIELD a ON foo TYPE string;//also tight\n\
		           DEFINE FIELD b ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("tight inline comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_allows_mid_statement_comment_across_newline() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD a ON foo -- mid-statement\n\
		           TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("mid-statement comment must parse");
		assert_eq!(entities.len(), 2);
		assert!(entities.iter().any(|e| e.name == "a"));
	}

	#[test]
	fn schema_does_not_strip_single_dash_or_slash() {
		// Single '-' (e.g. in DEFAULT -1) and single '/' (division) must not be treated as
		// comments.
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD n ON foo TYPE number DEFAULT -1;\n\
		           DEFINE FIELD m ON foo TYPE number VALUE 10 / 2;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("single - and / must not be stripped");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_preserves_comment_markers_inside_double_and_backtick_strings() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD a ON foo TYPE string DEFAULT \"x -- y // z\";\n\
		           DEFINE FIELD b ON `foo--bar` TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file)
			.expect("comment markers inside \"...\" and `...` must be preserved");
		assert_eq!(entities.len(), 3);
		// The field 'b' must survive — if '--' inside backticks were stripped, the table
		// scope token would be truncated and the statement would fail to parse.
		assert!(entities.iter().any(|e| e.name == "b"));
	}

	#[test]
	fn schema_handles_empty_comments() {
		let sql = "DEFINE TABLE foo SCHEMAFULL; --\n\
		           DEFINE FIELD a ON foo TYPE string; //\n\
		           DEFINE FIELD b ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("empty comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_handles_triple_dash_marker() {
		// '---' is a comment ('--' then '-' which is part of the comment body).
		let sql = "DEFINE TABLE foo SCHEMAFULL; --- triple dash\n\
		           DEFINE FIELD a ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("triple-dash must parse");
		assert_eq!(entities.len(), 2);
	}

	#[test]
	fn schema_allows_hash_line_comments() {
		let sql = "# header\n\
		           DEFINE TABLE foo SCHEMAFULL; # inline hash\n\
		           DEFINE FIELD a ON foo TYPE string;\n\
		           # trailing\n\
		           DEFINE FIELD b ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("# comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_preserves_hash_inside_string_literal() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD a ON foo TYPE string DEFAULT '#1 ranked';";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("# inside string must be preserved");
		assert_eq!(entities.len(), 2);
	}

	#[test]
	fn schema_allows_block_comments_inline() {
		let sql = "DEFINE TABLE foo SCHEMAFULL; /* inline block */\n\
		           DEFINE FIELD a ON foo /* mid */ TYPE string;\n\
		           DEFINE FIELD b ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("inline block comments must parse");
		assert_eq!(entities.len(), 3);
	}

	#[test]
	fn schema_allows_block_comments_spanning_multiple_lines() {
		let sql = "/*\n\
		            file header\n\
		            second line\n\
		           */\n\
		           DEFINE TABLE foo SCHEMAFULL;\n\
		           /* between\n\
		              statements */\n\
		           DEFINE FIELD a ON foo TYPE string;";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities =
			parse_schema_statements(&file).expect("multi-line block comments must parse");
		assert_eq!(entities.len(), 2);
	}

	#[test]
	fn schema_preserves_block_comment_markers_inside_string() {
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD a ON foo TYPE string DEFAULT '/* not a comment */';";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("/* inside string must be preserved");
		assert_eq!(entities.len(), 2);
	}

	#[test]
	fn schema_handles_unterminated_block_comment() {
		// An unterminated /* swallows the rest of input — same as treating the rest as comment.
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n/* never closes";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities = parse_schema_statements(&file).expect("unterminated block must parse");
		assert_eq!(entities.len(), 1);
	}

	#[test]
	fn schema_handles_escaped_quote_before_comment() {
		// Escaped quote inside a string should not terminate the string, so any '--' that
		// follows on the same line (still inside the string) must not be treated as a comment.
		let sql = "DEFINE TABLE foo SCHEMAFULL;\n\
		           DEFINE FIELD a ON foo TYPE string DEFAULT 'it\\'s -- still in string';";
		let file = SchemaFile {
			path: "database/schema/foo.surql".to_string(),
			hash: "x".to_string(),
			sql: sql.to_string(),
		};

		let entities =
			parse_schema_statements(&file).expect("escaped quote inside string must parse");
		assert_eq!(entities.len(), 2);
	}

	#[test]
	fn schema_allows_let_variables() {
		let file = SchemaFile {
			path: "database/schema/storage.surql".to_string(),
			hash: "x".to_string(),
			sql: "LET $types = ['image/png', 'image/jpeg'];\nDEFINE TABLE OVERWRITE storage SCHEMAFULL;".to_string(),
		};

		let entities = parse_schema_statements(&file).expect("LET should be allowed");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "table");
	}

	#[test]
	fn catalog_diff_detects_statement_changes() {
		let old = CatalogSnapshot {
			version: 2,
			entities: vec![CatalogEntity {
				kind: "field".to_string(),
				scope: Some("person".to_string()),
				name: "nickname".to_string(),
				source_path: "database/schema/a.surql".to_string(),
				statement_hash: "a".to_string(),
				file_hash: "file-a".to_string(),
			}],
		};
		let new = CatalogSnapshot {
			version: 2,
			entities: vec![CatalogEntity {
				kind: "field".to_string(),
				scope: Some("person".to_string()),
				name: "nickname".to_string(),
				source_path: "database/schema/a.surql".to_string(),
				statement_hash: "b".to_string(),
				file_hash: "file-b".to_string(),
			}],
		};

		let diff = diff_catalog(&old, &new);
		assert_eq!(diff.modified.len(), 1);
		assert_eq!(diff.modified[0].old.statement_hash, "a");
		assert_eq!(diff.modified[0].new.statement_hash, "b");
	}

	#[test]
	fn snapshot_from_files_is_sorted_for_determinism() {
		let files = vec![
			SchemaFile {
				path: "database/schema/z.surql".to_string(),
				sql: String::new(),
				hash: "z".to_string(),
			},
			SchemaFile {
				path: "database/schema/a.surql".to_string(),
				sql: String::new(),
				hash: "a".to_string(),
			},
		];

		let snap = snapshot_from_files(&files);
		assert_eq!(snap.files[0].path, "database/schema/a.surql");
		assert_eq!(snap.files[1].path, "database/schema/z.surql");
	}

	#[test]
	fn ensure_overwrite_injects_when_missing() {
		let sql = "DEFINE TABLE post SCHEMAFULL;\nDEFINE FIELD name ON post TYPE string;";
		let result = ensure_overwrite(sql);
		assert!(result.contains("DEFINE TABLE OVERWRITE post SCHEMAFULL;"));
		assert!(result.contains("DEFINE FIELD OVERWRITE name ON post TYPE string;"));
	}

	#[test]
	fn ensure_overwrite_preserves_existing() {
		let sql = "DEFINE TABLE OVERWRITE post SCHEMAFULL;";
		let result = ensure_overwrite(sql);
		assert!(result.contains("DEFINE TABLE OVERWRITE post SCHEMAFULL;"));
		// Should not double up OVERWRITE
		assert!(!result.contains("OVERWRITE OVERWRITE"));
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_with_overwrite() {
		// IF NOT EXISTS prevents schema changes from being applied in sync;
		// ensure_overwrite must replace it with OVERWRITE so updates are not silently skipped.
		let sql = "DEFINE TABLE IF NOT EXISTS post SCHEMAFULL;";
		let result = ensure_overwrite(sql);
		assert!(result.contains("DEFINE TABLE OVERWRITE post SCHEMAFULL;"), "got: {result}");
		assert!(!result.contains("IF NOT EXISTS"), "IF NOT EXISTS should be replaced: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_field() {
		let sql = "DEFINE FIELD IF NOT EXISTS email ON person TYPE string;";
		let result = ensure_overwrite(sql);
		assert!(
			result.contains("DEFINE FIELD OVERWRITE email ON person TYPE string;"),
			"got: {result}"
		);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_event() {
		let sql = "DEFINE EVENT IF NOT EXISTS changed ON person WHEN true THEN ();";
		let result = ensure_overwrite(sql);
		assert!(
			result.contains("DEFINE EVENT OVERWRITE changed ON person WHEN true THEN ();"),
			"got: {result}"
		);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_index() {
		let sql = "DEFINE INDEX IF NOT EXISTS by_email ON TABLE person FIELDS email;";
		let result = ensure_overwrite(sql);
		assert!(
			result.contains("DEFINE INDEX OVERWRITE by_email ON TABLE person FIELDS email;"),
			"got: {result}"
		);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_function() {
		let sql = "DEFINE FUNCTION IF NOT EXISTS fn::greet($name: string) { RETURN $name; };";
		let result = ensure_overwrite(sql);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
		assert!(result.contains("DEFINE FUNCTION OVERWRITE"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_param() {
		let sql = "DEFINE PARAM IF NOT EXISTS $env VALUE 'dev';";
		let result = ensure_overwrite(sql);
		assert!(result.contains("DEFINE PARAM OVERWRITE $env VALUE 'dev';"), "got: {result}");
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_analyzer() {
		let sql = "DEFINE ANALYZER IF NOT EXISTS english TOKENIZERS blank, class;";
		let result = ensure_overwrite(sql);
		assert!(
			result.contains("DEFINE ANALYZER OVERWRITE english TOKENIZERS blank, class;"),
			"got: {result}"
		);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_access() {
		let sql = "DEFINE ACCESS IF NOT EXISTS admin ON DATABASE TYPE RECORD;";
		let result = ensure_overwrite(sql);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
		assert!(result.contains("DEFINE ACCESS OVERWRITE"), "got: {result}");
	}

	#[test]
	fn ensure_overwrite_replaces_if_not_exists_user() {
		let sql = "DEFINE USER IF NOT EXISTS app ON DATABASE PASSHASH 'x';";
		let result = ensure_overwrite(sql);
		assert!(!result.contains("IF NOT EXISTS"), "got: {result}");
		assert!(result.contains("DEFINE USER OVERWRITE"), "got: {result}");
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_table() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE TABLE IF NOT EXISTS person SCHEMAFULL;".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS table");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "table");
		assert_eq!(entities[0].name, "person");
		assert!(entities[0].scope.is_none());
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_field() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE FIELD IF NOT EXISTS email ON person TYPE string;".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS field");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "field");
		assert_eq!(entities[0].name, "email");
		assert_eq!(entities[0].scope.as_deref(), Some("person"));
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_event() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE EVENT IF NOT EXISTS changed ON person WHEN true THEN ();".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS event");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "event");
		assert_eq!(entities[0].name, "changed");
		assert_eq!(entities[0].scope.as_deref(), Some("person"));
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_index() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE INDEX IF NOT EXISTS by_email ON TABLE person FIELDS email;".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS index");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "index");
		assert_eq!(entities[0].name, "by_email");
		assert_eq!(entities[0].scope.as_deref(), Some("person"));
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_function() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE FUNCTION IF NOT EXISTS fn::greet($name: string) { RETURN $name; };"
				.to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS function");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "function");
		assert_eq!(entities[0].name, "fn::greet");
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_param() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE PARAM IF NOT EXISTS $env VALUE 'dev';".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS param");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "param");
		assert_eq!(entities[0].name, "$env");
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_analyzer() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE ANALYZER IF NOT EXISTS english TOKENIZERS blank, class;".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS analyzer");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "analyzer");
		assert_eq!(entities[0].name, "english");
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_access() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE ACCESS IF NOT EXISTS admin ON DATABASE TYPE RECORD;".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS access");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "access");
		assert_eq!(entities[0].name, "admin");
		assert_eq!(entities[0].scope.as_deref(), Some("DATABASE"));
	}

	#[test]
	fn parse_schema_statements_accepts_if_not_exists_user() {
		let file = SchemaFile {
			path: "database/schema/test.surql".to_string(),
			hash: "h".to_string(),
			sql: "DEFINE USER IF NOT EXISTS app ON DATABASE PASSHASH 'x';".to_string(),
		};
		let entities = parse_schema_statements(&file).expect("should parse IF NOT EXISTS user");
		assert_eq!(entities.len(), 1);
		assert_eq!(entities[0].kind, "user");
		assert_eq!(entities[0].name, "app");
		assert_eq!(entities[0].scope.as_deref(), Some("DATABASE"));
	}

	#[test]
	fn build_catalog_snapshot_handles_all_if_not_exists_types() {
		let files = vec![SchemaFile {
			path: "database/schema/ine.surql".to_string(),
			hash: "ine".to_string(),
			sql: r#"
				DEFINE TABLE IF NOT EXISTS person SCHEMAFULL;
				DEFINE FIELD IF NOT EXISTS name ON person TYPE string;
				DEFINE EVENT IF NOT EXISTS audit ON person WHEN true THEN ();
				DEFINE INDEX IF NOT EXISTS by_name ON TABLE person FIELDS name;
				DEFINE FUNCTION IF NOT EXISTS fn::greet($n: string) { RETURN $n; };
				DEFINE PARAM IF NOT EXISTS $env VALUE 'dev';
				DEFINE ACCESS IF NOT EXISTS admin ON DATABASE TYPE RECORD;
				DEFINE ANALYZER IF NOT EXISTS eng TOKENIZERS blank;
				DEFINE USER IF NOT EXISTS ops ON DATABASE PASSHASH 'x';
			"#
			.to_string(),
		}];

		let catalog = build_catalog_snapshot(&files).expect("catalog should handle IF NOT EXISTS");
		assert_eq!(catalog.entities.len(), 9, "all 9 entity types should be extracted");

		let kinds: Vec<&str> = catalog.entities.iter().map(|e| e.kind.as_str()).collect();
		assert!(kinds.contains(&"table"));
		assert!(kinds.contains(&"field"));
		assert!(kinds.contains(&"event"));
		assert!(kinds.contains(&"index"));
		assert!(kinds.contains(&"function"));
		assert!(kinds.contains(&"param"));
		assert!(kinds.contains(&"access"));
		assert!(kinds.contains(&"analyzer"));
		assert!(kinds.contains(&"user"));
	}

	#[test]
	fn catalog_diff_treats_if_not_exists_and_overwrite_as_different() {
		// Changing from IF NOT EXISTS to OVERWRITE (or vice versa) should register
		// as a modification so the updated statement is applied on next sync.
		let ine_hash = sha256_hex("DEFINE TABLE IF NOT EXISTS person SCHEMAFULL".as_bytes());
		let ow_hash = sha256_hex("DEFINE TABLE OVERWRITE person SCHEMAFULL".as_bytes());

		let old = CatalogSnapshot {
			version: 2,
			entities: vec![CatalogEntity {
				kind: "table".to_string(),
				scope: None,
				name: "person".to_string(),
				source_path: "database/schema/a.surql".to_string(),
				statement_hash: ine_hash,
				file_hash: "f1".to_string(),
			}],
		};
		let new = CatalogSnapshot {
			version: 2,
			entities: vec![CatalogEntity {
				kind: "table".to_string(),
				scope: None,
				name: "person".to_string(),
				source_path: "database/schema/a.surql".to_string(),
				statement_hash: ow_hash,
				file_hash: "f2".to_string(),
			}],
		};

		let diff = diff_catalog(&old, &new);
		assert_eq!(diff.modified.len(), 1, "modifier change should be a modification");
	}
}