appdb 0.2.15

Lightweight SurrealDB helper library for Tauri embedded database apps
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
use std::marker::PhantomData;

mod relation_sync;

use anyhow::Result;
use async_trait::async_trait;
use serde::Serialize;
use serde_json::Value;
use surrealdb::opt::PatchOp;
use surrealdb::types::{RecordId, RecordIdKey, Table, Value as SurrealDbValue};

use crate::connection::get_db;
use crate::error::{DBError, DBErrorKind, classify_db_error_text};
use crate::model::meta::{HasId, ModelMeta, PaginationMeta, ResolveRecordId, UniqueLookupMeta};
use crate::pagination::PaginationPlan;
use crate::query::builder::{Order, QueryKind};
use crate::query::{RawSqlStmt, query_bound, query_bound_checked};
use crate::serde_utils::id::parse_record_id_or_plain_string;
use crate::{ForeignModel, StoredModel};

pub use crate::pagination::{Page, PageCursor};
use relation_sync::{
    append_relation_sync_to_stmt, append_relation_sync_with_anchor_expr_to_stmt,
    ensure_relation_tables,
};

fn struct_field_names<T: Serialize>(data: &T) -> Result<Vec<String>> {
    let value = serde_json::to_value(data)?;
    match value {
        Value::Object(map) => Ok(map.keys().cloned().collect()),
        _ => Ok(vec![]),
    }
}

fn strip_null_fields(value: &mut Value) {
    match value {
        Value::Object(map) => {
            let null_keys = map
                .iter()
                .filter_map(|(key, value)| {
                    if value.is_null() {
                        Some(key.clone())
                    } else {
                        None
                    }
                })
                .collect::<Vec<_>>();

            for key in null_keys {
                map.remove(&key);
            }

            for nested in map.values_mut() {
                strip_null_fields(nested);
            }
        }
        Value::Array(items) => {
            for nested in items {
                strip_null_fields(nested);
            }
        }
        _ => {}
    }
}

fn extract_record_id_key<T: Serialize>(data: &T) -> Result<RecordIdKey> {
    let value = serde_json::to_value(data)?;
    match value {
        Value::Object(map) => match map.get("id") {
            Some(Value::String(id)) if !id.is_empty() => Ok(RecordIdKey::String(id.clone())),
            Some(Value::Number(id)) => match id.as_i64() {
                Some(id) => Ok(RecordIdKey::Number(id)),
                None => Err(DBError::InvalidModel(format!(
                    "model `{}` has `id` but numeric id is out of i64 range",
                    std::any::type_name::<T>()
                ))
                .into()),
            },
            Some(_) => Err(DBError::InvalidModel(format!(
                "model `{}` has `id` but it is not a non-empty string or i64 number",
                std::any::type_name::<T>()
            ))
            .into()),
            None => Err(DBError::InvalidModel(format!(
                "model `{}` does not contain an `id` string or i64 field",
                std::any::type_name::<T>()
            ))
            .into()),
        },
        _ => Err(DBError::InvalidModel(format!(
            "model `{}` must serialize to an object",
            std::any::type_name::<T>()
        ))
        .into()),
    }
}

fn record_id_key_to_json_value(key: &RecordIdKey) -> Value {
    match key {
        RecordIdKey::String(value) => Value::String(value.clone()),
        RecordIdKey::Number(value) => Value::Number(serde_json::Number::from(*value)),
        _ => unreachable!("extract_record_id_key only returns string or number ids"),
    }
}

fn record_id_to_stable_key(record: &RecordId) -> Result<String> {
    let value = serde_json::to_value(record)?;
    Ok(value.to_string())
}

fn normalize_foreign_shapes(value: &mut serde_json::Value) {
    crate::rewrite_foreign_json_value(value);
    crate::decode_stored_record_links(value);
}

fn normalize_declared_foreign_fields<T>(row: &mut serde_json::Value)
where
    T: ForeignModel,
{
    let serde_json::Value::Object(map) = row else {
        return;
    };

    for field in T::foreign_field_names() {
        if let Some(value) = map.get_mut(*field) {
            normalize_foreign_shapes(value);
        }
    }
}

fn decode_error<T>(row: Value, err: serde_json::Error) -> anyhow::Error
where
    T: ModelMeta,
{
    let classified = classify_db_error_text(format!(
        "failed to decode stored `{}` row: {err}; row={row}",
        T::storage_table()
    ));
    debug_assert_eq!(classified.kind, DBErrorKind::Decode);
    classified.into_db_error().into()
}

fn normalize_root_record_id_string(value: &mut serde_json::Value) {
    if let serde_json::Value::Object(map) = value
        && let Some(id) = map.get_mut("id")
        && let serde_json::Value::String(text) = id
        && let Ok(record) = parse_record_id_or_plain_string(text, None)
    {
        *id = serde_json::to_value(record).expect("record id should serialize");
    }
}

fn normalize_public_output_ids(value: &mut serde_json::Value) {
    let current_id = value.as_object().and_then(|map| map.get("id")).cloned();

    crate::serde_utils::id::normalize_public_root_id_value(value);

    match current_id {
        Some(serde_json::Value::String(text)) if !text.contains(':') => {
            if let Some(map) = value.as_object_mut() {
                map.insert("id".to_owned(), serde_json::Value::String(text));
            }
        }
        Some(id @ serde_json::Value::Object(_)) => {
            if let Some(map) = value.as_object_mut() {
                map.insert("id".to_owned(), id);
            }
        }
        _ => {}
    }
}

async fn decode_hydrated_row<T>(mut row: serde_json::Value) -> Result<T>
where
    T: ForeignModel + ModelMeta,
{
    let record = record_id_from_row::<T>(&row)?;
    normalize_declared_foreign_fields::<T>(&mut row);
    if T::has_relation_fields() {
        T::inject_relation_values_from_db(record, &mut row).await?;
    }
    normalize_public_output_ids(&mut row);
    T::hydrate_foreign(serde_json::from_value(row)?).await
}

fn record_id_from_row<T>(row: &serde_json::Value) -> Result<RecordId>
where
    T: ModelMeta,
{
    let id = row
        .as_object()
        .and_then(|map| map.get("id"))
        .cloned()
        .ok_or_else(|| DBError::Decode("stored row is missing `id`".to_owned()))?;

    match id {
        serde_json::Value::String(text) => {
            parse_record_id_or_plain_string(&text, Some(T::storage_table())).map_err(|invalid| {
                DBError::Decode(format!("stored row contains invalid id value `{invalid}`")).into()
            })
        }
        serde_json::Value::Number(value) => value
            .as_i64()
            .map(|value| RecordId::new(T::storage_table(), value))
            .ok_or_else(|| {
                DBError::Decode(format!(
                    "stored row contains unsupported numeric id value `{value}`"
                ))
                .into()
            }),
        serde_json::Value::Object(_) => Ok(serde_json::from_value(id)?),
        other => Err(DBError::Decode(format!(
            "stored row contains unsupported id shape `{other}`"
        ))
        .into()),
    }
}

fn prepare_save_parts<M, T>(table: &str, data: T) -> Result<(RecordId, Value, Value)>
where
    T: Serialize,
    M: ForeignModel,
{
    let key = extract_record_id_key(&data)?;
    let id = record_id_key_to_json_value(&key);
    let record = RecordId::new(table, key);
    Ok((record, prepare_content::<M, _>(data)?, id))
}

fn prepare_content<M, T>(data: T) -> Result<Value>
where
    T: Serialize,
    M: ForeignModel,
{
    let mut content = serde_json::to_value(&data)?;
    if let Value::Object(map) = &mut content {
        map.remove("id");
    }
    M::strip_relation_fields(&mut content);
    strip_null_fields(&mut content);
    Ok(content)
}

fn prepare_create_content<M, T>(data: T) -> Result<Value>
where
    T: Serialize,
    M: ForeignModel,
{
    let mut content = serde_json::to_value(&data)?;
    M::strip_relation_fields(&mut content);
    strip_null_fields(&mut content);
    Ok(content)
}

async fn persist_explicit_id_primitive<T>(record: RecordId, data: T, create_only: bool) -> Result<T>
where
    T: ModelMeta + StoredModel + ForeignModel,
{
    let original = data.clone();
    let stored_input = T::persist_foreign(data).await?;
    let content = prepare_content::<T, _>(stored_input)?;
    let relation_writes = original.prepare_relation_writes(record.clone()).await?;
    ensure_relation_tables(&relation_writes).await?;
    let mut stmt = RawSqlStmt::new("BEGIN TRANSACTION;");
    stmt.sql.push_str(if create_only {
        "CREATE ONLY $record CONTENT $data RETURN AFTER;"
    } else {
        "UPSERT ONLY $record CONTENT $data RETURN AFTER;"
    });
    stmt = stmt.bind("record", record.clone()).bind("data", content);
    let (stmt_with_relations, _) = append_relation_sync_to_stmt(stmt, &relation_writes, "rel")?;
    let mut stmt = stmt_with_relations;
    stmt.sql.push_str("COMMIT TRANSACTION;");

    let result = query_bound(stmt).await;
    let mut result = match result {
        Ok(result) => result,
        Err(err) => {
            let typed = DBError::from(err);
            return if create_only && matches!(typed, DBError::EmptyResult(_)) {
                Err(DBError::Conflict("record already exists".to_owned()).into())
            } else {
                Err(typed.into())
            };
        }
    };
    result = match result.check() {
        Ok(result) => result,
        Err(err) => {
            let typed = DBError::from(err);
            return if create_only && matches!(typed, DBError::EmptyResult(_)) {
                Err(DBError::Conflict("record already exists".to_owned()).into())
            } else {
                Err(typed.into())
            };
        }
    };

    let row: Option<SurrealDbValue> = result.take(1)?;
    let row = row.ok_or_else(|| {
        if create_only {
            DBError::Conflict("record already exists".to_owned())
        } else {
            DBError::EmptyResult("persist_explicit_id_primitive")
        }
    })?;
    let stored =
        decode_saved_row_from_model::<T>(row, serde_json::to_value(record.clone())?, &original)?;
    let mut value = serde_json::to_value(T::hydrate_foreign(stored).await?)?;
    normalize_public_output_ids(&mut value);
    Ok(serde_json::from_value(value)?)
}

fn decode_saved_row_from_model<T>(row: SurrealDbValue, id: Value, model: &T) -> Result<T::Stored>
where
    T: ForeignModel + ModelMeta,
    T::Stored: serde::de::DeserializeOwned,
{
    let mut row = row.into_json_value();
    if let Value::Object(map) = &mut row {
        map.insert("id".to_owned(), id);
    }
    normalize_root_record_id_string(&mut row);
    normalize_declared_foreign_fields::<T>(&mut row);
    model.inject_relation_values_from_model(&mut row)?;
    serde_json::from_value(row.clone()).map_err(|err| decode_error::<T>(row, err))
}

fn decode_stored_row_value<T>(mut row: Value, id: Option<Value>) -> Result<T::Stored>
where
    T: ForeignModel + ModelMeta,
    T::Stored: serde::de::DeserializeOwned,
{
    if let Value::Object(map) = &mut row
        && let Some(id) = id
    {
        map.insert("id".to_owned(), id);
    }

    normalize_root_record_id_string(&mut row);
    normalize_declared_foreign_fields::<T>(&mut row);

    serde_json::from_value(row.clone()).map_err(|err| decode_error::<T>(row, err))
}

pub(crate) async fn record_exists(record: RecordId) -> Result<bool> {
    let db = get_db()?;
    let selected: std::result::Result<Option<SurrealDbValue>, surrealdb::Error> =
        db.select(record).await;
    match selected {
        Ok(existing) => Ok(existing.is_some()),
        Err(err) => match crate::error::classify_surreal_error(err) {
            crate::error::DBError::MissingTable(_) => Ok(false),
            other => Err(other.into()),
        },
    }
}

fn collect_lookup_parts<T>(data: &T) -> Result<Vec<(String, Value)>>
where
    T: UniqueLookupMeta + Serialize,
{
    let value = serde_json::to_value(data)?;
    let Value::Object(map) = value else {
        return Err(DBError::InvalidModel(format!(
            "model `{}` must serialize to an object",
            std::any::type_name::<T>()
        ))
        .into());
    };

    let fields = T::lookup_fields();
    if fields.is_empty() {
        return Err(DBError::InvalidModel(format!(
            "model `{}` has no fields available for automatic unique lookup",
            std::any::type_name::<T>()
        ))
        .into());
    }

    let mut parts = Vec::with_capacity(fields.len());
    for field in fields {
        let value = map.get(*field).cloned().ok_or_else(|| {
            DBError::InvalidModel(format!(
                "model `{}` is missing lookup field `{field}` during automatic unique lookup",
                std::any::type_name::<T>()
            ))
        })?;
        parts.push(((*field).to_owned(), value));
    }

    Ok(parts)
}

async fn stored_rows_to_public_hydrated<T>(rows: Vec<T::Stored>) -> Result<Vec<T>>
where
    T: ForeignModel,
{
    let mut values = Vec::with_capacity(rows.len());
    for row in rows {
        values.push(T::hydrate_foreign(row).await?);
    }
    Ok(values)
}

async fn decode_stored_row_from_db<T>(mut row: Value) -> Result<T::Stored>
where
    T: ForeignModel + ModelMeta,
    T::Stored: serde::de::DeserializeOwned,
{
    let record = record_id_from_row::<T>(&row)?;
    normalize_root_record_id_string(&mut row);
    normalize_declared_foreign_fields::<T>(&mut row);
    if T::has_relation_fields() {
        T::inject_relation_values_from_db(record, &mut row).await?;
    }
    serde_json::from_value(row.clone()).map_err(|err| decode_error::<T>(row, err))
}

pub(crate) async fn raw_rows_to_public_hydrated<T>(rows: Vec<SurrealDbValue>) -> Result<Vec<T>>
where
    T: ForeignModel + ModelMeta,
    T::Stored: serde::de::DeserializeOwned,
{
    let mut values = Vec::with_capacity(rows.len());
    for row in rows {
        let stored = decode_stored_row_from_db::<T>(row.into_json_value()).await?;
        values.push(T::hydrate_foreign(stored).await?);
    }
    Ok(values)
}

/// Internal repository building blocks for a model type.
///
/// This type remains public for advanced integration seams and mission-internal
/// tests, but application code should prefer the narrower model-facing CRUD
/// methods generated by `#[derive(Store)]` and the [`Crud`] trait wrappers.
pub struct Repo<T>(PhantomData<T>);

impl<T> Repo<T>
where
    T: ModelMeta + StoredModel + ForeignModel,
{
    /// Creates a new row in the model table.
    /// Creates a new row in the model table.
    pub async fn create(data: T) -> Result<T> {
        if T::has_relation_fields() {
            let original = data.clone();
            let stored_input = T::persist_foreign(data).await?;
            let content = prepare_create_content::<T, _>(stored_input)?;
            let anchor_record = RecordId::new(T::storage_table(), "__appdb_pending_create__");
            let relation_writes = original.prepare_relation_writes(anchor_record).await?;
            ensure_relation_tables(&relation_writes).await?;
            let mut stmt = RawSqlStmt::new(
                "BEGIN TRANSACTION; LET $created = CREATE ONLY $table CONTENT $data RETURN AFTER;",
            );
            stmt = stmt
                .bind("table", Table::from(T::storage_table()))
                .bind("data", content);
            let (mut stmt, relation_statement_count) =
                append_relation_sync_with_anchor_expr_to_stmt(
                    stmt,
                    &relation_writes,
                    "rel",
                    "$created",
                )?;
            stmt.sql
                .push_str("SELECT *, record::id(id) AS id FROM ONLY $created;");
            stmt.sql.push_str("COMMIT TRANSACTION;");
            let mut result = query_bound_checked(stmt).await?;
            let row: Option<SurrealDbValue> = result.take(2 + relation_statement_count)?;
            let row = row.ok_or(DBError::EmptyResult("create"))?;
            let row_json = row.into_json_value();
            let stored = decode_stored_row_from_db::<T>(row_json).await?;
            return Ok(T::hydrate_foreign(stored).await?);
        }

        let db = get_db()?;
        let created: Option<T::Stored> = db
            .create(T::storage_table())
            .content(T::persist_foreign(data).await?)
            .await?;
        match created {
            Some(stored) => Ok(T::hydrate_foreign(stored).await?),
            None => Err(DBError::EmptyResult("create").into()),
        }
    }

    /// Creates a new row and returns only its record id.
    /// Creates a new row and returns its record id.
    pub async fn create_return_id(data: T) -> Result<RecordId> {
        if !T::supports_create_return_id() {
            return Err(DBError::InvalidModel(format!(
                "model `{}` does not support create_return_id; use create or create_at instead",
                std::any::type_name::<T>()
            ))
            .into());
        }

        if T::has_relation_fields() {
            return Err(DBError::InvalidModel(
                "create_return_id is not supported for models with #[relate(...)] fields"
                    .to_owned(),
            )
            .into());
        }

        let db = get_db()?;
        let stored = T::persist_foreign(data).await?;
        let created: Option<RecordId> = db
            .query(QueryKind::create_return_id(T::storage_table()))
            .bind(("table", Table::from(T::storage_table())))
            .bind(("data", stored))
            .await?
            .check()?
            .take(0)?;
        created.ok_or(DBError::EmptyResult("create_return_id").into())
    }

    /// Creates a new row at the provided record id.
    pub async fn create_at(id: RecordId, data: T) -> Result<T> {
        persist_explicit_id_primitive::<T>(id, data, true).await
    }

    /// Upserts a row using [`HasId::id`] as the record id.
    /// Upserts a row using the record id exposed by `HasId`.
    pub async fn upsert(data: T) -> Result<T>
    where
        T: HasId,
    {
        let id = data.id();
        Self::upsert_at(id, data).await
    }

    /// Upserts a row at the provided record id.
    pub async fn upsert_at(id: RecordId, data: T) -> Result<T> {
        persist_explicit_id_primitive::<T>(id, data, false).await
    }

    /// Fetches a row by full record id.
    /// Loads a row by full `RecordId`.
    pub async fn get_record(record: RecordId) -> Result<T> {
        let db = get_db()?;
        let requested = record.clone();
        let record: Option<SurrealDbValue> = db.select(record).await?;
        match record {
            Some(stored) => {
                let stored = if T::has_relation_fields() {
                    let mut row = stored.into_json_value();
                    if let Value::Object(map) = &mut row {
                        map.insert("id".to_owned(), serde_json::to_value(requested.clone())?);
                    }
                    decode_stored_row_from_db::<T>(row).await?
                } else {
                    decode_stored_row_value::<T>(
                        stored.into_json_value(),
                        Some(serde_json::to_value(requested)?),
                    )?
                };
                let mut value = serde_json::to_value(T::hydrate_foreign(stored).await?)?;
                normalize_public_output_ids(&mut value);
                Ok(serde_json::from_value(value)?)
            }
            None => Err(DBError::NotFound.into()),
        }
    }

    pub async fn exists_record(record: RecordId) -> Result<bool> {
        record_exists(record).await
    }

    /// Replaces the stored content of a row at the provided record id.
    pub async fn update_at(id: RecordId, data: T) -> Result<T> {
        if T::has_relation_fields() {
            let original = data.clone();
            let stored_input = T::persist_foreign(data).await?;
            let content = prepare_content::<T, _>(stored_input)?;
            let relation_writes = original.prepare_relation_writes(id.clone()).await?;
            ensure_relation_tables(&relation_writes).await?;
            let mut stmt =
                RawSqlStmt::new("BEGIN TRANSACTION; UPDATE $record CONTENT $data RETURN AFTER;");
            stmt = stmt.bind("record", id.clone()).bind("data", content);
            let (stmt_with_relations, _) =
                append_relation_sync_to_stmt(stmt, &relation_writes, "rel")?;
            let mut stmt = stmt_with_relations;
            stmt.sql.push_str("COMMIT TRANSACTION;");
            let mut result = query_bound_checked(stmt).await?;
            let row: Option<SurrealDbValue> = result.take(1)?;
            let row = row.ok_or(DBError::NotFound)?;
            let stored =
                decode_saved_row_from_model::<T>(row, serde_json::to_value(id)?, &original)?;
            let mut value = serde_json::to_value(T::hydrate_foreign(stored).await?)?;
            normalize_public_output_ids(&mut value);
            return Ok(serde_json::from_value(value)?);
        }

        let db = get_db()?;
        let updated: Option<T::Stored> = db
            .update(id)
            .content(T::persist_foreign(data).await?)
            .await?;
        match updated {
            Some(stored) => Ok(T::hydrate_foreign(stored).await?),
            None => Err(DBError::NotFound.into()),
        }
    }

    /// Merges a partial JSON object into the row at `id`.
    /// Merges a partial JSON object into an existing row.
    pub async fn merge(id: RecordId, data: Value) -> Result<T> {
        let db = get_db()?;
        let merged: Option<T> = db.update(id).merge(data).await?;
        merged.ok_or(DBError::NotFound.into())
    }

    /// Applies SurrealDB patch operations to the row at `id`.
    /// Applies SurrealDB patch operations to an existing row.
    pub async fn patch(id: RecordId, data: Vec<PatchOp>) -> Result<T> {
        let db = get_db()?;

        if data.is_empty() {
            let record: Option<T> = db.select(id).await?;
            return record.ok_or(DBError::NotFound.into());
        }

        let mut ops = data.into_iter();
        let first_op = ops.next().expect("non-empty patch ops");
        let initial_patch_query = db.update(id).patch(first_op);
        let final_query = ops.fold(initial_patch_query, |query, op| query.patch(op));
        let patched: Option<T> = final_query.await?;
        patched.ok_or(DBError::NotFound.into())
    }

    /// Bulk-inserts rows into the model table.
    /// Inserts many rows using SurrealDB bulk insert.
    pub async fn insert(data: Vec<T>) -> Result<Vec<T>> {
        if T::has_relation_fields() {
            return Err(DBError::InvalidModel(
                "insert is not supported for models with #[relate(...)] fields; use save_many"
                    .to_owned(),
            )
            .into());
        }

        let db = get_db()?;
        let mut stored = Vec::with_capacity(data.len());
        for item in data {
            stored.push(T::persist_foreign(item).await?);
        }
        let created: Vec<T::Stored> = db.insert(T::storage_table()).content(stored).await?;
        stored_rows_to_public_hydrated::<T>(created).await
    }

    /// Bulk-inserts rows while ignoring conflicting duplicates.
    /// Inserts many rows while ignoring duplicate-key conflicts.
    pub async fn insert_ignore(data: Vec<T>) -> Result<Vec<T>> {
        if T::has_relation_fields() {
            return Err(DBError::InvalidModel(
                "insert_ignore is not supported for models with #[relate(...)] fields; use save_many"
                    .to_owned(),
            )
            .into());
        }

        let db = get_db()?;
        let chunk_size = 50_000;
        let mut inserted_all = Vec::with_capacity(data.len());

        for chunk in data.chunks(chunk_size) {
            let mut chunk_clone = Vec::with_capacity(chunk.len());
            for item in chunk.iter().cloned() {
                chunk_clone.push(T::persist_foreign(item).await?);
            }
            let inserted: Vec<T::Stored> = db
                .query(QueryKind::insert(T::storage_table()))
                .bind(("table", Table::from(T::storage_table())))
                .bind(("data", chunk_clone))
                .await?
                .check()?
                .take(0)?;
            inserted_all.extend(stored_rows_to_public_hydrated::<T>(inserted).await?);
        }

        Ok(inserted_all)
    }

    /// Bulk-inserts rows and updates existing rows on duplicate keys.
    /// Inserts many rows and updates existing rows on duplicate key.
    pub async fn insert_or_replace(data: Vec<T>) -> Result<Vec<T>> {
        if T::has_relation_fields() {
            return Err(DBError::InvalidModel(
                "insert_or_replace is not supported for models with #[relate(...)] fields; use save_many"
                    .to_owned(),
            )
            .into());
        }

        if data.is_empty() {
            return Ok(vec![]);
        }

        let db = get_db()?;
        let chunk_size = 50_000;
        let mut inserted_all = Vec::with_capacity(data.len());
        let keys = struct_field_names(&data[0])?;

        for chunk in data.chunks(chunk_size) {
            let mut chunk_clone = Vec::with_capacity(chunk.len());
            for item in chunk.iter().cloned() {
                chunk_clone.push(T::persist_foreign(item).await?);
            }
            let inserted: Vec<T::Stored> = db
                .query(QueryKind::insert_or_replace(
                    T::storage_table(),
                    keys.clone(),
                ))
                .bind(("table", Table::from(T::storage_table())))
                .bind(("data", chunk_clone))
                .await?
                .check()?
                .take(0)?;
            inserted_all.extend(stored_rows_to_public_hydrated::<T>(inserted).await?);
        }

        Ok(inserted_all)
    }

    /// Deletes a row by its table-local `id` value.
    pub async fn delete<K>(id: K) -> Result<()>
    where
        RecordIdKey: From<K>,
        K: Send,
    {
        let key: RecordIdKey = id.into();
        let record = match key {
            RecordIdKey::String(text) => RecordId::new(T::storage_table(), text),
            other => RecordId::new(T::storage_table(), other),
        };
        Self::delete_record(record).await
    }

    /// Deletes one row by full record id.
    /// Deletes a row by full `RecordId`.
    pub async fn delete_record(id: RecordId) -> Result<()> {
        let db = get_db()?;
        db.query(QueryKind::delete_record())
            .bind(("record", id))
            .await?
            .check()?;
        Ok(())
    }

    /// Deletes all rows from the model table.
    /// Deletes every row in the table.
    pub async fn delete_all() -> Result<()> {
        let db = get_db()?;
        let result = db
            .query(QueryKind::delete_table())
            .bind(("table", Table::from(T::storage_table())))
            .await?;
        if let Err(err) = result.check() {
            match DBError::from(err) {
                DBError::MissingTable(_) => {}
                other => return Err(other.into()),
            }
        }
        Ok(())
    }

    /// Finds the first record id matching a field equality filter.
    pub async fn find_one_id(k: &str, v: &str) -> Result<RecordId> {
        let db = get_db()?;
        let ids: Vec<RecordId> = db
            .query(QueryKind::select_id_single(T::storage_table()))
            .bind(("table", Table::from(T::storage_table())))
            .bind(("k", k.to_owned()))
            .bind(("v", v.to_owned()))
            .await?
            .check()?
            .take(0)?;
        let id = ids.into_iter().next();
        id.ok_or(DBError::NotFound.into())
    }

    /// Lists all record ids in the model table.
    /// Lists all record ids in the table.
    pub async fn list_record_ids() -> Result<Vec<RecordId>> {
        let db = get_db()?;
        let mut result = db
            .query(QueryKind::all_id(T::storage_table()))
            .bind(("table", Table::from(T::storage_table())))
            .await?
            .check()?;
        let ids: Vec<RecordId> = result.take(0)?;
        Ok(ids)
    }

    /// Returns whether the model table currently contains at least one row.
    pub async fn exists() -> Result<bool> {
        let db = get_db()?;
        let mut result = match db
            .query(QueryKind::table_has_rows(T::storage_table()))
            .bind(("table", Table::from(T::storage_table())))
            .await
        {
            Ok(result) => match result.check() {
                Ok(result) => result,
                Err(err) => match DBError::from(err) {
                    DBError::MissingTable(_) => return Ok(false),
                    other => return Err(other.into()),
                },
            },
            Err(err) => match DBError::from(err) {
                DBError::MissingTable(_) => return Ok(false),
                other => return Err(other.into()),
            },
        };

        let exists: Option<bool> = result.take(0)?;
        match exists {
            Some(exists) => Ok(exists),
            None => Ok(false),
        }
    }

    /// Finds exactly one record id by the model's automatic lookup fields.
    pub async fn find_unique_id_for(data: &T) -> Result<RecordId>
    where
        T: UniqueLookupMeta,
    {
        let db = get_db()?;
        let lookup_parts = collect_lookup_parts(data)?;
        let fields = lookup_parts
            .iter()
            .map(|(field, _)| field.clone())
            .collect::<Vec<_>>();
        let mut query = db
            .query(QueryKind::select_id_by_fields(&fields))
            .bind(("table", Table::from(T::storage_table())));

        for (idx, (field, value)) in lookup_parts.into_iter().enumerate() {
            query = query
                .bind((format!("field_{idx}"), field))
                .bind((format!("value_{idx}"), value));
        }

        let mut result = query.await?.check()?;
        let ids: Vec<RecordId> = result.take(0)?;

        match ids.len() {
            1 => Ok(ids.into_iter().next().expect("one id must exist")),
            0 => Err(DBError::NotFound.into()),
            _ => Err(DBError::InvalidModel(
                "automatic unique lookup matched multiple records".to_owned(),
            )
            .into()),
        }
    }
}

impl<T> Repo<T>
where
    T: ModelMeta + StoredModel + ForeignModel,
{
    /// Upserts one model using its `id` field and returns the normalized row.
    /// Saves a model by its `id` field and returns the normalized row.
    pub async fn save(data: T) -> Result<T> {
        if !T::has_foreign_fields() && extract_record_id_key(&data).is_ok() {
            let record = RecordId::new(T::storage_table(), extract_record_id_key(&data)?);
            return persist_explicit_id_primitive::<T>(record, data, false).await;
        }

        let db = get_db()?;
        let original = data.clone();
        let (stored, created_foreign_records) =
            crate::run_with_foreign_cleanup_scope(|| async { T::persist_foreign(data).await })
                .await?;
        let (record, content, id) = prepare_save_parts::<T, _>(T::storage_table(), stored)?;
        let relation_writes = original.prepare_relation_writes(record.clone()).await?;
        ensure_relation_tables(&relation_writes).await?;
        let mut stmt =
            RawSqlStmt::new("BEGIN TRANSACTION; UPSERT ONLY $record CONTENT $data RETURN AFTER;");
        stmt = stmt
            .bind("record", record.clone())
            .bind("data", content.clone());
        let (stmt_with_relations, _) = append_relation_sync_to_stmt(stmt, &relation_writes, "rel")?;
        let mut stmt = stmt_with_relations;
        stmt.sql.push_str("COMMIT TRANSACTION;");
        let mut result = query_bound_checked(stmt).await?;
        let row: Option<SurrealDbValue> = result.take(1)?;
        let row = row.ok_or(DBError::EmptyResult("save"))?;
        let stored = decode_saved_row_from_model::<T>(row, id, &original)?;
        match T::hydrate_foreign(stored).await {
            Ok(value) => Ok(value),
            Err(err) => {
                let _: Option<SurrealDbValue> = db.delete(record).await?;
                for foreign_record in created_foreign_records.into_iter().rev() {
                    let _: Option<SurrealDbValue> = db.delete(foreign_record).await?;
                }
                Err(err)
            }
        }
    }

    /// Fetches one model by raw id key and normalizes the returned `id`.
    /// Loads a row by its `id` field using the normalized query path.
    pub async fn get<K>(id: K) -> Result<T>
    where
        RecordIdKey: From<K>,
        K: Send,
    {
        let db = get_db()?;
        let key: RecordIdKey = id.into();
        let record = RecordId::new(T::storage_table(), key.clone());
        if T::has_foreign_fields() || T::has_relation_fields() {
            let stmt = crate::query::RawSqlStmt::new("SELECT * FROM type::record($table, $id);")
                .bind("table", T::storage_table())
                .bind("id", key);
            let raw = crate::query::query_bound_return::<serde_json::Value>(stmt)
                .await?
                .ok_or(DBError::NotFound)?;
            return decode_hydrated_row::<T>(raw).await;
        }
        let mut result = db
            .query(QueryKind::select_by_id())
            .bind(("record", record))
            .await?
            .check()?;
        let row: Option<T::Stored> = result.take(0)?;
        match row {
            Some(stored) => {
                let mut value = serde_json::to_value(T::hydrate_foreign(stored).await?)?;
                normalize_public_output_ids(&mut value);
                Ok(serde_json::from_value(value)?)
            }
            None => Err(DBError::NotFound.into()),
        }
    }

    /// Lists all rows with a normalized `id` field.
    /// Lists all rows with normalized `id` values.
    pub async fn list() -> Result<Vec<T>> {
        if T::has_foreign_fields() || T::has_relation_fields() {
            let db = get_db()?;
            let mut result = db
                .query(QueryKind::select_all_with_id())
                .bind(("table", Table::from(T::storage_table())))
                .await?
                .check()?;
            let rows: Vec<SurrealDbValue> = result.take(0)?;
            return raw_rows_to_public_hydrated::<T>(rows).await;
        }

        let db = get_db()?;
        let mut result = db
            .query(QueryKind::select_all_with_id())
            .bind(("table", Table::from(T::storage_table())))
            .await?
            .check()?;
        let rows: Vec<T::Stored> = result.take(0)?;
        stored_rows_to_public_hydrated::<T>(rows).await
    }

    /// Lists up to `count` rows with a normalized `id` field.
    /// Lists up to `count` rows with normalized `id` values.
    pub async fn list_limit(count: i64) -> Result<Vec<T>> {
        if T::has_foreign_fields() || T::has_relation_fields() {
            let db = get_db()?;
            let mut result = db
                .query(QueryKind::select_limit_with_id())
                .bind(("table", Table::from(T::storage_table())))
                .bind(("count", count))
                .await?
                .check()?;
            let rows: Vec<SurrealDbValue> = result.take(0)?;
            return raw_rows_to_public_hydrated::<T>(rows).await;
        }

        let db = get_db()?;
        let mut result = db
            .query(QueryKind::select_limit_with_id())
            .bind(("table", Table::from(T::storage_table())))
            .bind(("count", count))
            .await?
            .check()?;
        let rows: Vec<T::Stored> = result.take(0)?;
        stored_rows_to_public_hydrated::<T>(rows).await
    }

    async fn pagin_with_order(
        count: i64,
        cursor: Option<PageCursor>,
        order: Order,
    ) -> Result<Page<T>>
    where
        T: PaginationMeta,
        T::Stored: serde::de::DeserializeOwned,
    {
        let field = T::pagination_field().ok_or_else(|| {
            DBError::InvalidModel(format!(
                "model `{}` does not declare a #[pagin] field",
                std::any::type_name::<T>()
            ))
        })?;
        let plan = PaginationPlan::new(field, order);

        let requested = usize::try_from(count).map_err(|_| {
            DBError::InvalidModel(format!("pagination count must be positive, got `{count}`"))
        })?;
        if requested == 0 {
            return Err(
                DBError::InvalidModel("pagination count must be positive".to_owned()).into(),
            );
        }

        let query_count = count.checked_add(1).ok_or_else(|| {
            DBError::InvalidModel(format!(
                "pagination count `{count}` overflowed the lookahead window"
            ))
        })?;

        let stmt = plan.build_stmt(T::storage_table(), query_count, cursor.as_ref())?;
        let mut rows = crate::query::query_bound_take::<serde_json::Value>(stmt, Some(1)).await?;
        let next = if rows.len() > requested {
            rows.truncate(requested);
            Some(
                plan.build_cursor(
                    rows.last()
                        .expect("truncated page should retain its last row"),
                )?,
            )
        } else {
            None
        };

        let mut items = Vec::with_capacity(rows.len());
        for row in rows {
            items.push(decode_hydrated_row::<T>(row).await?);
        }

        Ok(Page { items, next })
    }

    /// Lists one descending keyset page using the model's `#[pagin]` field.
    pub async fn pagin_desc(count: i64, cursor: Option<PageCursor>) -> Result<Page<T>>
    where
        T: PaginationMeta,
        T::Stored: serde::de::DeserializeOwned,
    {
        Self::pagin_with_order(count, cursor, Order::Desc).await
    }

    /// Lists one ascending keyset page using the model's `#[pagin]` field.
    pub async fn pagin_asc(count: i64, cursor: Option<PageCursor>) -> Result<Page<T>>
    where
        T: PaginationMeta,
        T::Stored: serde::de::DeserializeOwned,
    {
        Self::pagin_with_order(count, cursor, Order::Asc).await
    }

    /// Batch-upserts models by their `id` field and returns normalized rows.
    /// Saves many rows in chunks and returns normalized results.
    pub async fn save_many(data: Vec<T>) -> Result<Vec<T>> {
        if data.is_empty() {
            return Ok(vec![]);
        }

        let mut inserted_all = Vec::with_capacity(data.len());
        let chunk_size = 5_000;

        for chunk in data.chunks(chunk_size) {
            let mut prepared = Vec::with_capacity(chunk.len());
            let mut originals = Vec::with_capacity(chunk.len());
            let mut relation_writes = Vec::new();
            let mut sql = String::from("BEGIN TRANSACTION; ");
            let mut created_foreign_records = Vec::new();
            let mut seen_records = std::collections::HashSet::<String>::with_capacity(chunk.len());

            for (idx, row) in chunk.iter().cloned().enumerate() {
                let original = row.clone();
                let ((record, content, id), row_foreign_records) =
                    crate::run_with_foreign_cleanup_scope(|| async {
                        let stored_row = T::persist_foreign(row).await?;
                        let (record, content, id) =
                            prepare_save_parts::<T, _>(T::storage_table(), stored_row)?;
                        Ok::<_, anyhow::Error>((record, content, id))
                    })
                    .await?;
                let record_key = record_id_to_stable_key(&record)?;
                if !seen_records.insert(record_key) {
                    return Err(DBError::Conflict(format!(
                        "save_many received duplicate record id in one batch: {record:?}"
                    ))
                    .into());
                }
                created_foreign_records.extend(row_foreign_records);
                relation_writes.extend(original.prepare_relation_writes(record.clone()).await?);
                sql.push_str(&format!(
                    "UPSERT ONLY $record_{idx} CONTENT $data_{idx} RETURN AFTER;"
                ));
                originals.push(original);
                prepared.push((record, content, id));
            }

            ensure_relation_tables(&relation_writes).await?;
            let mut stmt = RawSqlStmt::new(sql);
            for (idx, (record, content, _)) in prepared.iter().enumerate() {
                stmt = stmt
                    .bind(format!("record_{idx}"), record.clone())
                    .bind(format!("data_{idx}"), content.clone());
            }
            let (stmt_with_relations, _) =
                append_relation_sync_to_stmt(stmt, &relation_writes, "rel")?;
            let mut stmt = stmt_with_relations;
            stmt.sql.push_str("COMMIT TRANSACTION;");

            let mut result = query_bound_checked(stmt).await?;

            for (idx, (_, _, id)) in prepared.clone().into_iter().enumerate() {
                let row: Option<SurrealDbValue> = result.take(idx + 1)?;
                let row = row.ok_or(DBError::EmptyResult("save_many"))?;
                let stored = decode_saved_row_from_model::<T>(row, id, &originals[idx])?;
                match T::hydrate_foreign(stored).await {
                    Ok(value) => inserted_all.push(value),
                    Err(err) => {
                        let db = get_db()?;
                        for (record, _, _) in prepared.iter() {
                            let _: Option<SurrealDbValue> = db.delete(record.clone()).await?;
                        }
                        for foreign_record in created_foreign_records.into_iter().rev() {
                            let _: Option<SurrealDbValue> = db.delete(foreign_record).await?;
                        }
                        return Err(err);
                    }
                }
            }
        }

        Ok(inserted_all)
    }
}

#[async_trait]
/// Recommended model-facing CRUD surface.
///
/// `#[derive(Store)]` forwards its inherent methods through this trait so caller
/// code can stay on the domain model type instead of reaching for [`Repo`]
/// directly. Treat [`Repo`] as an internal composition layer unless you are
/// extending appdb itself or wiring a custom runtime seam.
pub trait Crud: ModelMeta + StoredModel + ForeignModel {
    /// Builds a full record id for this model table.
    fn record_id<T>(id: T) -> RecordId
    where
        RecordIdKey: From<T>,
    {
        <Self as ModelMeta>::record_id(id)
    }

    /// Creates a copy of `self` in the database.
    async fn create(&self) -> Result<Self> {
        Repo::<Self>::create(self.clone()).await
    }

    /// Creates a copy of `self` and returns its record id.
    async fn create_return_id(&self) -> Result<RecordId> {
        Repo::<Self>::create_return_id(self.clone()).await
    }

    /// Upserts `self` using its `HasId` implementation.
    async fn upsert(&self) -> Result<Self>
    where
        Self: HasId,
    {
        Repo::<Self>::upsert(self.clone()).await
    }

    /// Loads a row by full `RecordId`.
    async fn get_record(record: RecordId) -> Result<Self> {
        Repo::<Self>::get_record(record).await
    }

    /// Lists all rows with normalized `id` values.
    async fn list() -> Result<Vec<Self>> {
        Repo::<Self>::list().await
    }

    /// Lists up to `count` rows with normalized `id` values.
    async fn list_limit(count: i64) -> Result<Vec<Self>> {
        Repo::<Self>::list_limit(count).await
    }

    /// Lists every outgoing related record id reachable through `relation`.
    async fn outgoing_ids(&self, relation: &str) -> Result<Vec<RecordId>>
    where
        Self: ResolveRecordId + Sync,
    {
        crate::graph::outgoing_ids(self.resolve_record_id().await?, relation).await
    }

    /// Loads outgoing related records of type `T` reachable through `relation`.
    async fn outgoing<T>(&self, relation: &str) -> Result<Vec<T>>
    where
        Self: ResolveRecordId + Sync,
        T: ModelMeta + StoredModel + ForeignModel,
        T::Stored: serde::de::DeserializeOwned,
    {
        crate::graph::outgoing::<T>(self.resolve_record_id().await?, relation).await
    }

    /// Counts every outgoing edge reachable through `relation`.
    async fn outgoing_count(&self, relation: &str) -> Result<i64>
    where
        Self: ResolveRecordId + Sync,
    {
        crate::graph::outgoing_count(self.resolve_record_id().await?, relation).await
    }

    /// Counts outgoing related records of type `T` reachable through `relation`.
    async fn outgoing_count_as<T>(&self, relation: &str) -> Result<i64>
    where
        Self: ResolveRecordId + Sync,
        T: ModelMeta + StoredModel + ForeignModel,
    {
        crate::graph::outgoing_count_as::<T>(self.resolve_record_id().await?, relation).await
    }

    /// Lists every incoming related record id that points to `self` through `relation`.
    async fn incoming_ids(&self, relation: &str) -> Result<Vec<RecordId>>
    where
        Self: ResolveRecordId + Sync,
    {
        crate::graph::incoming_ids(self.resolve_record_id().await?, relation).await
    }

    /// Loads incoming related records of type `T` that point to `self` through `relation`.
    async fn incoming<T>(&self, relation: &str) -> Result<Vec<T>>
    where
        Self: ResolveRecordId + Sync,
        T: ModelMeta + StoredModel + ForeignModel,
        T::Stored: serde::de::DeserializeOwned,
    {
        crate::graph::incoming::<T>(self.resolve_record_id().await?, relation).await
    }

    /// Counts every incoming edge that points to `self` through `relation`.
    async fn incoming_count(&self, relation: &str) -> Result<i64>
    where
        Self: ResolveRecordId + Sync,
    {
        crate::graph::incoming_count(self.resolve_record_id().await?, relation).await
    }

    /// Counts incoming related records of type `T` that point to `self` through `relation`.
    async fn incoming_count_as<T>(&self, relation: &str) -> Result<i64>
    where
        Self: ResolveRecordId + Sync,
        T: ModelMeta + StoredModel + ForeignModel,
    {
        crate::graph::incoming_count_as::<T>(self.resolve_record_id().await?, relation).await
    }

    /// Returns whether the model table currently contains at least one row.
    async fn exists() -> Result<bool> {
        Repo::<Self>::exists().await
    }

    /// Replaces the stored content of `self`.
    async fn update(self) -> Result<Self>
    where
        Self: HasId,
    {
        Repo::<Self>::update_at(self.id(), self).await
    }

    /// Replaces the stored content of `self` at the provided record id.
    async fn update_at(self, id: RecordId) -> Result<Self> {
        Repo::<Self>::update_at(id, self).await
    }

    /// Merges a partial JSON object into an existing row.
    async fn merge(id: RecordId, data: Value) -> Result<Self> {
        Repo::<Self>::merge(id, data).await
    }

    /// Applies SurrealDB patch operations to an existing row.
    async fn patch(id: RecordId, data: Vec<PatchOp>) -> Result<Self> {
        Repo::<Self>::patch(id, data).await
    }

    /// Inserts many rows using SurrealDB bulk insert.
    async fn insert(data: Vec<Self>) -> Result<Vec<Self>> {
        Repo::<Self>::insert(data).await
    }

    /// Inserts many rows while ignoring duplicate-key conflicts.
    async fn insert_ignore(data: Vec<Self>) -> Result<Vec<Self>> {
        Repo::<Self>::insert_ignore(data).await
    }

    /// Inserts many rows and updates existing rows on duplicate key.
    async fn insert_or_replace(data: Vec<Self>) -> Result<Vec<Self>> {
        Repo::<Self>::insert_or_replace(data).await
    }

    /// Deletes `self` by its record id.
    async fn delete(self) -> Result<()>
    where
        Self: HasId,
    {
        Repo::<Self>::delete_record(self.id()).await
    }

    /// Deletes a row by full `RecordId`.
    async fn delete_record(id: RecordId) -> Result<()> {
        Repo::<Self>::delete_record(id).await
    }

    /// Deletes every row in the model table.
    async fn delete_all() -> Result<()> {
        Repo::<Self>::delete_all().await
    }

    /// Finds the first record id matching a field equality filter.
    async fn find_one_id(k: &str, v: &str) -> Result<RecordId> {
        Repo::<Self>::find_one_id(k, v).await
    }

    /// Lists all record ids in the model table.
    async fn list_record_ids() -> Result<Vec<RecordId>> {
        Repo::<Self>::list_record_ids().await
    }

    /// Saves `self` using its `id` field and returns the normalized row.
    async fn save(self) -> Result<Self> {
        Repo::<Self>::save(self).await
    }

    /// Loads a row by its `id` field.
    async fn get<T>(id: T) -> Result<Self>
    where
        RecordIdKey: From<T>,
        T: Send,
    {
        Repo::<Self>::get(id).await
    }

    /// Saves many rows in chunks and returns normalized results.
    async fn save_many(data: Vec<Self>) -> Result<Vec<Self>> {
        Repo::<Self>::save_many(data).await
    }
}

#[cfg(test)]
#[path = "tests.rs"]
mod tests;