1use hayson_engine::catalog::{IntegrityReport, MigrateOutcome, OrphanRecord, Relation};
2use hayson_engine::compaction::CompactionResult;
3use hayson_engine::database::{Layout, LayoutMigrationResult};
4use hayson_engine::query::{AccessPathSummary, OverlayStrategy, PlanBranch, PlanOverlay, QueryStrategy};
5use hayson_engine::schema::HaysonRecord;
6use hayson_engine::table::{BrokenLink, RefreshOutcome, RotationResult, TableStats};
7use hayson_engine::txn::UnitOfWorkResult;
8use serde_json::{json, Value};
9
10pub fn migrate_format1_outcome_to_json(outcome: &MigrateOutcome) -> Value {
11 match outcome {
12 MigrateOutcome::AlreadyMigrated { catalog } => json!({
13 "migrated": false,
14 "catalog": catalog.display().to_string(),
15 "tables": [],
16 "removedSchemaFiles": [],
17 }),
18 MigrateOutcome::Migrated {
19 catalog,
20 tables,
21 removed_schema_files,
22 } => json!({
23 "migrated": true,
24 "catalog": catalog.display().to_string(),
25 "tables": tables,
26 "removedSchemaFiles": removed_schema_files
27 .iter()
28 .map(|path| path.display().to_string())
29 .collect::<Vec<_>>(),
30 }),
31 }
32}
33
34pub fn record_to_json(record: &HaysonRecord) -> Value {
35 Value::Object(
36 record
37 .iter()
38 .map(|(field, value)| (field.clone(), value.clone()))
39 .collect(),
40 )
41}
42
43pub fn broken_links_to_json(broken: &[BrokenLink]) -> Value {
47 Value::Array(
48 broken
49 .iter()
50 .map(|link| json!({ "field": link.field, "path": link.path }))
51 .collect(),
52 )
53}
54
55fn strategy_name(strategy: QueryStrategy) -> &'static str {
56 match strategy {
57 QueryStrategy::Primary => "primary",
58 QueryStrategy::Exact => "exact",
59 QueryStrategy::Sorted => "sorted",
60 QueryStrategy::Fulltext => "fulltext",
61 QueryStrategy::Union => "union",
62 QueryStrategy::Scan => "scan",
63 }
64}
65
66fn plan_branch_to_json(branch: &PlanBranch) -> Value {
67 json!({
68 "strategy": strategy_name(branch.strategy),
69 "field": branch.field,
70 "candidates": branch.candidates,
71 })
72}
73
74fn overlay_strategy_name(strategy: OverlayStrategy) -> &'static str {
75 match strategy {
76 OverlayStrategy::Exact => "exact",
77 OverlayStrategy::Fulltext => "fulltext",
78 OverlayStrategy::Scan => "scan",
79 }
80}
81
82fn plan_overlay_to_json(overlay: &PlanOverlay) -> Value {
83 json!({
84 "staged": overlay.staged,
85 "suppressed": overlay.suppressed,
86 "rescored": overlay.rescored,
87 "strategy": overlay_strategy_name(overlay.strategy),
88 "size": overlay.size,
89 })
90}
91
92pub fn plan_to_json(plan: &AccessPathSummary) -> Value {
93 json!({
94 "strategy": strategy_name(plan.strategy),
95 "field": plan.field,
96 "index": plan.index,
97 "candidates": plan.candidates,
98 "ranked": plan.ranked,
99 "filteredOnProjection": plan.filtered_on_projection,
100 "reads": plan.reads,
101 "branches": plan.branches.as_ref().map(|branches| branches.iter().map(plan_branch_to_json).collect::<Vec<_>>()),
102 "overlay": plan.overlay.as_ref().map(plan_overlay_to_json),
103 })
104}
105
106pub fn query_result_to_json(
111 keys: &[String],
112 records: &[HaysonRecord],
113 matched: usize,
114 plan: &AccessPathSummary,
115) -> Value {
116 json!({
117 "keys": keys,
118 "records": records.iter().map(record_to_json).collect::<Vec<_>>(),
119 "matched": matched,
120 "plan": plan_to_json(plan),
121 })
122}
123
124pub fn optional_records_to_json(records: &[Option<HaysonRecord>]) -> Value {
128 Value::Array(
129 records
130 .iter()
131 .map(|record| record.as_ref().map(record_to_json).unwrap_or(Value::Null))
132 .collect(),
133 )
134}
135
136pub fn unit_of_work_result_to_json(result: &UnitOfWorkResult) -> Value {
140 json!({ "id": result.id, "tables": result.tables, "operations": result.operations })
141}
142
143pub fn relation_to_json(relation: &Relation) -> Value {
144 json!({
145 "name": relation.name,
146 "from": { "table": relation.from.table, "field": relation.from.field },
147 "to": { "table": relation.to.table, "field": relation.to.field },
148 "cardinality": relation.cardinality.as_str(),
149 "onDelete": relation.on_delete.map(|action| action.as_str()),
150 "enforce": relation.enforce,
151 })
152}
153
154pub fn relations_to_json(relations: &[Relation]) -> Value {
155 Value::Array(relations.iter().map(relation_to_json).collect())
156}
157
158fn orphan_record_to_json(orphan: &OrphanRecord) -> Value {
159 json!({
160 "relation": orphan.relation,
161 "table": orphan.table,
162 "field": orphan.field,
163 "primaryKey": orphan.primary_key,
164 "value": orphan.value,
165 })
166}
167
168pub fn integrity_report_to_json(report: &IntegrityReport) -> Value {
169 json!({ "orphans": report.orphans.iter().map(orphan_record_to_json).collect::<Vec<_>>() })
170}
171
172pub fn layout_to_json(layout: &Layout) -> Value {
177 let metadata_file = layout.metadata_file();
178 let metadata_path = layout.metadata_path().display().to_string();
179 json!({
180 "kind": layout.kind().as_str(),
181 "root": layout.root().display().to_string(),
182 "metadataFile": metadata_file,
183 "metadataPath": metadata_path,
184 "catalogFile": metadata_file,
185 "catalog": metadata_path,
186 "manifestFile": metadata_file,
187 "manifest": metadata_path,
188 "tables": layout.tables().display().to_string(),
189 "indexes": layout.indexes().display().to_string(),
190 "runtime": layout.runtime().display().to_string(),
191 "lock": layout.lock_path().display().to_string(),
192 "journal": layout.journal_path().display().to_string(),
193 })
194}
195
196pub fn layout_migration_to_json(result: &LayoutMigrationResult) -> Value {
200 json!({
201 "root": result.root.display().to_string(),
202 "from": result.from.as_str(),
203 "to": result.to.as_str(),
204 "moves": result
205 .moves
206 .iter()
207 .map(|step| json!({ "from": step.from.display().to_string(), "to": step.to.display().to_string() }))
208 .collect::<Vec<_>>(),
209 "unclaimed": result
210 .unclaimed
211 .iter()
212 .map(|path| path.display().to_string())
213 .collect::<Vec<_>>(),
214 "changed": result.changed,
215 "dryRun": result.dry_run,
216 })
217}
218
219pub fn table_stats_to_json(stats: &TableStats) -> Value {
220 json!({
221 "records": stats.records,
222 "liveBytes": stats.live_bytes,
223 "deadBytes": stats.dead_bytes,
224 "logBytes": stats.log_bytes,
225 "queueDepth": stats.queue_depth,
226 "gen": stats.gen,
227 "seq": stats.seq,
228 })
229}
230
231pub fn refresh_outcome_to_json(outcome: RefreshOutcome) -> Value {
235 let (name, entries) = match outcome {
236 RefreshOutcome::Unchanged => ("unchanged", 0),
237 RefreshOutcome::CaughtUp { entries } => ("caughtUp", entries),
238 RefreshOutcome::Reloaded => ("reloaded", 0),
239 };
240 json!({ "changed": outcome.changed(), "outcome": name, "entries": entries })
241}
242
243pub fn rotation_result_to_json(result: &RotationResult) -> Value {
246 json!({
247 "rotated": result.rotated,
248 "alreadyCurrent": result.already_current,
249 "skipped": result.skipped,
250 })
251}
252
253pub fn compaction_result_to_json(result: &CompactionResult) -> Value {
255 json!({
256 "records": result.records,
257 "bytesBefore": result.bytes_before,
258 "bytesAfter": result.bytes_after,
259 "reclaimedBytes": result.reclaimed_bytes,
260 })
261}
262
263#[cfg(test)]
264mod tests {
265 use hayson_engine::catalog::{RelationCardinality, RelationEnd};
266
267 use super::*;
268
269 #[test]
270 fn a_query_result_carries_keys_records_the_match_count_and_the_plan_in_one_document() {
271 let mut record = HaysonRecord::new();
272 record.insert("id".into(), json!("u1"));
273 record.insert("name".into(), json!("Ania"));
274 let plan = AccessPathSummary {
275 strategy: QueryStrategy::Exact,
276 field: Some("email".into()),
277 index: Some("users_email".into()),
278 candidates: 1,
279 ranked: false,
280 filtered_on_projection: true,
281 overlay: None,
282 reads: 1,
283 branches: None,
284 };
285
286 let described = query_result_to_json(&["u1".to_string()], &[record], 7, &plan);
287
288 assert_eq!(described["keys"], json!(["u1"]));
289 assert_eq!(described["records"], json!([{ "id": "u1", "name": "Ania" }]));
290 assert_eq!(
291 described["matched"],
292 json!(7),
293 "the page is one key wide, the match count is not"
294 );
295 assert_eq!(described["plan"]["strategy"], json!("exact"));
296 assert_eq!(described["plan"]["index"], json!("users_email"));
297 assert_eq!(described["plan"]["branches"], Value::Null);
298 }
299
300 #[test]
301 fn a_plan_carries_ranked_and_filtered_on_projection_under_the_names_the_ts_query_plan_declares() {
302 let plan = AccessPathSummary {
303 strategy: QueryStrategy::Fulltext,
304 field: None,
305 index: None,
306 candidates: 2,
307 ranked: true,
308 filtered_on_projection: false,
309 overlay: None,
310 reads: 2,
311 branches: None,
312 };
313
314 let described = plan_to_json(&plan);
315
316 assert_eq!(described["ranked"], json!(true));
317 assert_eq!(described["filteredOnProjection"], json!(false));
318 }
319
320 #[test]
321 fn every_query_strategy_has_a_lower_case_name_the_ts_union_already_uses() {
322 let all = [
323 QueryStrategy::Primary,
324 QueryStrategy::Exact,
325 QueryStrategy::Sorted,
326 QueryStrategy::Fulltext,
327 QueryStrategy::Union,
328 QueryStrategy::Scan,
329 ];
330 let names: Vec<&str> = all.into_iter().map(strategy_name).collect();
331
332 assert_eq!(names, vec!["primary", "exact", "sorted", "fulltext", "union", "scan"]);
333 }
334
335 #[test]
336 fn a_relation_is_flattened_into_the_shape_the_ts_relation_type_declares() {
337 let relation = Relation {
338 name: "orders_user".into(),
339 from: RelationEnd {
340 table: "orders".into(),
341 field: "userId".into(),
342 },
343 to: RelationEnd {
344 table: "users".into(),
345 field: "id".into(),
346 },
347 cardinality: RelationCardinality::ManyToOne,
348 on_delete: None,
349 enforce: Some(true),
350 };
351
352 let described = relations_to_json(&[relation]);
353
354 assert_eq!(described[0]["from"], json!({ "table": "orders", "field": "userId" }));
355 assert_eq!(described[0]["onDelete"], Value::Null);
356 assert_eq!(described[0]["enforce"], json!(true));
357 }
358
359 #[test]
360 fn a_get_many_answer_keeps_a_hole_where_the_table_held_no_record() {
361 let mut record = HaysonRecord::new();
362 record.insert("id".into(), json!("u1"));
363
364 let described = optional_records_to_json(&[None, Some(record), None]);
365
366 assert_eq!(described, json!([Value::Null, { "id": "u1" }, Value::Null]));
367 }
368
369 #[test]
370 fn a_committed_unit_reports_the_id_the_tables_and_how_many_operations_it_carried() {
371 let result = UnitOfWorkResult {
372 id: "42-1-0".into(),
373 tables: vec!["users".into(), "audit".into()],
374 operations: 3,
375 };
376
377 let described = unit_of_work_result_to_json(&result);
378
379 assert_eq!(
380 described,
381 json!({ "id": "42-1-0", "tables": ["users", "audit"], "operations": 3 })
382 );
383 }
384
385 #[test]
386 fn table_stats_cross_the_boundary_under_the_camel_case_names_the_ts_type_declares() {
387 let stats = TableStats {
388 records: 2,
389 live_bytes: 40,
390 dead_bytes: 10,
391 log_bytes: 50,
392 queue_depth: 0,
393 gen: 1,
394 seq: 7,
395 };
396
397 let described = table_stats_to_json(&stats);
398
399 assert_eq!(
400 described,
401 json!({ "records": 2, "liveBytes": 40, "deadBytes": 10, "logBytes": 50, "queueDepth": 0, "gen": 1, "seq": 7 })
402 );
403 }
404
405 #[test]
406 fn each_refresh_outcome_names_itself_and_agrees_with_its_own_changed_flag() {
407 let unchanged = refresh_outcome_to_json(RefreshOutcome::Unchanged);
408 let caught_up = refresh_outcome_to_json(RefreshOutcome::CaughtUp { entries: 3 });
409 let reloaded = refresh_outcome_to_json(RefreshOutcome::Reloaded);
410
411 assert_eq!(
412 unchanged,
413 json!({ "changed": false, "outcome": "unchanged", "entries": 0 })
414 );
415 assert_eq!(
416 caught_up,
417 json!({ "changed": true, "outcome": "caughtUp", "entries": 3 })
418 );
419 assert_eq!(
420 reloaded,
421 json!({ "changed": true, "outcome": "reloaded", "entries": 0 })
422 );
423 }
424
425 #[test]
426 fn a_record_keeps_its_field_order_across_the_boundary() {
427 let mut record = HaysonRecord::new();
428 record.insert("id".into(), json!("u1"));
429 record.insert("age".into(), json!(31));
430
431 let text = record_to_json(&record).to_string();
432
433 assert_eq!(
434 text, r#"{"age":31,"id":"u1"}"#,
435 "HaysonRecord is a BTreeMap — field order is its key order"
436 );
437 }
438}