backbone-orm 2.7.36

Backbone Framework ORM - Database layer with PostgreSQL support
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
//! `GenericCrudRepository<T, DeleteMode>` — one implementation for all entities.
//!
//! The generated repository file previously duplicated ~20 identical method bodies
//! for every entity.  This module provides those implementations once so that
//! the generator can emit a thin newtype wrapper instead of hundreds of lines of
//! copy-paste.
//!
//! # Delete mode markers
//!
//! | Marker | Behaviour |
//! |--------|-----------|
//! | [`SoftDelete`] | `deleted_at` stored in `metadata` JSONB; active rows filter `IS NULL` |
//! | [`HardDelete`] | Rows are permanently deleted; no trash concept |
//!
//! # Generated output (after this change)
//!
//! ```rust,ignore
//! // ~20 lines total instead of ~460-560
//! pub struct UserRepository(
//!     backbone_orm::GenericCrudRepository<User, backbone_orm::SoftDelete>
//! );
//! impl std::ops::Deref for UserRepository {
//!     type Target = backbone_orm::GenericCrudRepository<User, backbone_orm::SoftDelete>;
//!     fn deref(&self) -> &Self::Target { &self.0 }
//! }
//! impl UserRepository {
//!     pub fn new(pool: sqlx::PgPool) -> Self {
//!         Self(backbone_orm::GenericCrudRepository::new(pool, "users"))
//!     }
//!     // entity-specific methods only:
//!     pub async fn find_by_email(&self, email: &str) -> anyhow::Result<Option<User>> { … }
//!     pub async fn partial_update(…) { … }
//!     pub async fn list_paginated_filtered(…) { … }
//! }
//! backbone_core::impl_crud_repository!(UserRepository, User, soft_delete);
//! ```

use std::collections::HashMap;
use std::marker::PhantomData;

use anyhow::Result;
use serde::Serialize;
use sqlx::postgres::PgRow;
use sqlx::{FromRow, PgPool};
use uuid::Uuid;

use crate::repository::{
    DatabaseOperations, PaginatedResult, PaginationInfo, PaginationParams, PostgresRepository,
};

// ─── EntityRepoMeta trait ─────────────────────────────────────────────────────

/// Metadata trait that entities implement so `GenericCrudRepository` can provide
/// `list_paginated_filtered` and `list_deleted_filtered` without per-entity boilerplate.
///
/// Generated once per entity by the `rust` generator.
///
/// | Method | Purpose |
/// |--------|---------|
/// | `column_types` | PostgreSQL cast hints (e.g. `{"id": "uuid"}`) |
/// | `search_fields` | Text columns searched with `ILIKE` |
pub trait EntityRepoMeta {
    /// PostgreSQL type hints for filter/sort (e.g. `{"id": "uuid"}`).
    fn column_types() -> HashMap<String, String>;
    /// Text columns to include in full-text / ILIKE search.
    fn search_fields() -> &'static [&'static str];

    // ── Field-level security (response shaping) ──
    // Names below are RESPONSE JSON keys (camelCase), not DB columns — they are
    // matched against the serialized response object. Defaults = no restriction.

    /// Response fields visible only to the row owner and platform/root callers
    /// (`@private`). Stripped for everyone else.
    fn private_fields() -> &'static [&'static str] {
        &[]
    }

    /// The response field (camelCase) holding the owner/company id (`@owner`),
    /// compared against the caller's access scope to decide private-field
    /// visibility. `None` = the entity has no owner concept.
    fn owner_field() -> Option<&'static str> {
        None
    }

    // ── Row-level company isolation ──

    /// The DB column that scopes rows to a company (snake_case, e.g. `company_id`).
    /// `None` = the entity is global (reference data) and is not fenced.
    ///
    /// The generator emits this **structurally** — from the presence of the company
    /// column, a fact it cannot forget — and an entity opts OUT with `@global`.
    /// The polarity is deliberate: `owner_field()` above is opt-IN via `@owner`, and
    /// in a year of generated entities not one model ever declared it, so the whole
    /// field-security path silently never ran. Security that must be remembered, in a
    /// file nobody edits for security reasons, defaults to open and stays open. Here
    /// silence means fenced, and forgetting is the safe direction.
    ///
    /// This is a *row-visibility fence*, the same category as `SoftDelete`'s
    /// unconditional `deleted_at IS NULL` — not domain logic.
    fn company_field() -> Option<&'static str> {
        None
    }

    /// To-one relations expandable via `?include=<name>`, as
    /// `(relation_name, target_table, local_fk_field)` — all response keys
    /// (relation_name/local_fk in camelCase; target_table is the DB table).
    /// Default: none.
    fn relations() -> &'static [(&'static str, &'static str, &'static str)] {
        &[]
    }
}

// ─── Delete-mode markers ──────────────────────────────────────────────────────

// ─── Row-level company fence ───────────────────────────────────────────────────

/// The caller could not be scoped to a company for an entity that requires one.
///
/// Deliberately an error and not an empty result: an empty list is a silent lie that
/// looks identical to "no data" and gets debugged for days, whereas this names the
/// wiring bug. Callers should surface it as 403.
#[derive(Debug, thiserror::Error)]
#[error("entity is company-scoped ({column}) but the request carries no company scope")]
pub struct MissingCompanyScope {
    /// The column that would have fenced the query.
    pub column: &'static str,
}

/// Build the SQL fence for `T`, or fail closed.
///
/// - entity is global (`company_field() == None`) → no fence, reference data reads freely
/// - entity is fenced but the request has no company → **`Err`**, never an unfenced query
/// - both present → `col = '<uuid>'`, ANDed into the WHERE by the caller
///
/// The literal is safe to interpolate: `column` is generator-emitted (never client
/// input) and `Uuid`'s `Display` can only produce hex and dashes, so neither side can
/// carry a quote. The ORM's filter layer has no typed-parameter slot for a base
/// condition — `__base_condition` is injected verbatim — so this is the seam the
/// design already established for `SoftDelete`.
pub fn company_fence<T: EntityRepoMeta>(company: Option<Uuid>) -> Result<Option<String>, MissingCompanyScope> {
    match (T::company_field(), company) {
        (None, _) => Ok(None),
        (Some(column), None) => Err(MissingCompanyScope { column }),
        (Some(column), Some(id)) => Ok(Some(format!("{column} = '{id}'"))),
    }
}

/// Remove any caller-supplied filter on the company column.
///
/// The HTTP filter map is `#[serde(flatten)]`, so `?company_id=<victim>` arrives as an
/// ordinary filter and the builder honours it. The fence is ANDed, so a client cannot
/// widen past its own company — but leaving the key in lets a caller AND a *second*,
/// contradictory company predicate and turn every list into an empty-vs-nonempty oracle
/// for "does company X have rows matching Y". Strip it: a client may narrow **within**
/// its company, never speak about the company at all.
///
/// Handles the snake_case column, its camelCase response key, and both operator forms
/// (`company_id[eq]=…`).
pub fn strip_client_company_filters<T: EntityRepoMeta>(filters: &mut HashMap<String, String>) {
    let Some(column) = T::company_field() else {
        return;
    };
    let camel = snake_to_camel(column);
    filters.retain(|key, _| {
        let base = key.split('[').next().unwrap_or(key);
        !base.eq_ignore_ascii_case(column) && !base.eq_ignore_ascii_case(&camel)
    });
}

/// AND two optional SQL conditions into the single `__base_condition` slot.
///
/// `__base_condition` is one HashMap key, so the soft-delete guard and the company fence
/// have to arrive as a single string rather than two independent predicates.
pub fn and_conditions(a: Option<&str>, b: Option<String>) -> Option<String> {
    match (a, b) {
        (None, None) => None,
        (Some(a), None) => Some(a.to_string()),
        (None, Some(b)) => Some(b),
        (Some(a), Some(b)) => Some(format!("{a} AND {b}")),
    }
}

fn snake_to_camel(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut upper = false;
    for c in s.chars() {
        if c == '_' {
            upper = true;
        } else if upper {
            out.push(c.to_ascii_uppercase());
            upper = false;
        } else {
            out.push(c);
        }
    }
    out
}

/// Marker: entity uses JSONB-based soft delete (`metadata->>'deleted_at'`).
///
/// Active rows satisfy `metadata->>'deleted_at' IS NULL`.
pub struct SoftDelete;

/// Marker: entity uses hard deletes only — no soft delete / trash concept.
pub struct HardDelete;

// ─── GenericCrudRepository ────────────────────────────────────────────────────

/// Generic PostgreSQL CRUD repository parameterised by entity type `T` and
/// delete strategy `D` ([`SoftDelete`] or [`HardDelete`]).
///
/// All standard CRUD methods are implemented here once.  Generated repository
/// structs wrap this type via newtype + `Deref` and only add entity-specific
/// methods (`find_by_*`, `exists_by_*`, `partial_update`, filtered listings).
pub struct GenericCrudRepository<T, D = SoftDelete>
where
    T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
{
    inner: PostgresRepository<T>,
    _mode: PhantomData<D>,
}

// ─── Common (both modes) ──────────────────────────────────────────────────────

impl<T, D> GenericCrudRepository<T, D>
where
    T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
{
    pub fn new(pool: PgPool, table_name: &str) -> Self {
        Self {
            inner: PostgresRepository::new(pool, table_name),
            _mode: PhantomData,
        }
    }

    pub fn pool(&self) -> &PgPool {
        self.inner.pool()
    }

    pub fn table_name(&self) -> &str {
        self.inner.table_name()
    }

    /// Insert a new entity row and return the created row.
    pub async fn create(&self, entity: &T) -> Result<T>
    where
        T: Serialize + Send + Sync,
    {
        self.inner.create(entity).await
    }

    /// Insert multiple entity rows inside a single transaction.
    pub async fn bulk_create(&self, entities: &[T]) -> Result<Vec<T>>
    where
        T: Serialize + Send + Sync,
    {
        let tx = sqlx::pool::Pool::begin(self.pool()).await?;
        let mut results = Vec::with_capacity(entities.len());
        for entity in entities {
            results.push(self.create(entity).await?);
        }
        tx.commit().await?;
        Ok(results)
    }

    // ── Generic unique-field lookups ──────────────────────────────────────────
    //
    // These are shared across both delete modes. The SQL is the same for both;
    // the soft-delete guard is added separately by the per-mode wrappers below.

    /// Internal: query by a text field with a caller-supplied extra condition.
    async fn find_by_text_field_with_cond(
        &self,
        field: &str,
        value: &str,
        extra: &str,
    ) -> Result<Option<T>> {
        let query = format!(
            "SELECT * FROM {} WHERE {} = $1{}",
            self.table_name(), field, extra
        );
        let result = crate::company_scope::fetch_optional_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(value),
        )
        .await?;
        Ok(result)
    }

    /// Internal: existence check by a text field with a caller-supplied extra condition.
    async fn exists_by_text_field_with_cond(
        &self,
        field: &str,
        value: &str,
        extra: &str,
    ) -> Result<bool> {
        let query = format!(
            "SELECT 1 FROM {} WHERE {} = $1{} LIMIT 1",
            self.table_name(), field, extra
        );
        let result = crate::company_scope::fetch_optional_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i32>(&query).bind(value),
        )
        .await?;
        Ok(result.is_some())
    }

    /// Internal: query by a UUID field with a caller-supplied extra condition.
    async fn find_by_uuid_field_with_cond(
        &self,
        field: &str,
        value: Uuid,
        extra: &str,
    ) -> Result<Option<T>> {
        let query = format!(
            "SELECT * FROM {} WHERE {} = $1{}",
            self.table_name(), field, extra
        );
        let result = crate::company_scope::fetch_optional_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(value),
        )
        .await?;
        Ok(result)
    }

    /// Internal: existence check by a UUID field with a caller-supplied extra condition.
    async fn exists_by_uuid_field_with_cond(
        &self,
        field: &str,
        value: Uuid,
        extra: &str,
    ) -> Result<bool> {
        let query = format!(
            "SELECT 1 FROM {} WHERE {} = $1{} LIMIT 1",
            self.table_name(), field, extra
        );
        let result = crate::company_scope::fetch_optional_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i32>(&query).bind(value),
        )
        .await?;
        Ok(result.is_some())
    }

    /// Execute a filtered / paginated query against this entity's table.
    ///
    /// `base_condition` — when `Some`, it is inserted as the `__base_condition`
    /// filter key which the ORM injects verbatim into the WHERE clause.  Use
    /// this to add soft-delete guards without touching the caller-supplied
    /// filters.
    ///
    /// NOTE: prefer the `*_scoped` entry points for anything a client can reach —
    /// they compose the company fence into this condition. This raw form applies no
    /// fence and is for internal/job callers that have already established scope.
    pub async fn run_filtered_query(
        &self,
        pagination: PaginationParams,
        base_condition: Option<&str>,
        filters: &HashMap<String, String>,
        column_types: &HashMap<String, String>,
        search_fields: &[&str],
    ) -> Result<PaginatedResult<T>>
    where
        T: Send + Sync,
    {
        let mut filters_map = filters.clone();
        if let Some(cond) = base_condition {
            filters_map.insert("__base_condition".to_string(), cond.to_string());
        }
        self.inner
            .list_with_filters(pagination, &filters_map, column_types, search_fields)
            .await
    }

    /// The aggregate twin of [`Self::run_filtered_query`].
    ///
    /// Takes the same `base_condition` so an aggregate is computed over exactly
    /// the row set the matching list would return — a total that counted
    /// soft-deleted rows, or another tenant's, would be wrong in a way no
    /// caller could see.
    pub async fn run_aggregate_query(
        &self,
        spec: &crate::repository::AggregateSpec,
        base_condition: Option<&str>,
        filters: &HashMap<String, String>,
        column_types: &HashMap<String, String>,
        search_fields: &[&str],
    ) -> Result<crate::repository::AggregateResult>
    where
        T: crate::EntityRepoMeta + Send + Sync,
    {
        // Resolve the group column's relation HERE (the only layer that
        // knows the entity's metadata): a group on a relation FK gets its
        // target table passed down so the inner query can carry the label.
        let mut spec = spec.clone();
        if let (Some(group), Some(label)) = (&spec.group_by, &spec.label_field) {
            let _ = label;
            let camel = snake_to_camel(group);
            if let Some((_, table, _)) = T::relations().iter().find(|(_, _, fk)| *fk == camel) {
                let base_fk = camel_to_snake(&camel);
                spec.label_relation = Some((table.to_string(), base_fk));
            }
        }
        let mut filters_map = filters.clone();
        if let Some(cond) = base_condition {
            filters_map.insert("__base_condition".to_string(), cond.to_string());
        }
        self.inner
            .aggregate_with_filters(&spec, &filters_map, column_types, search_fields)
            .await
    }
}

// ─── SoftDelete mode ──────────────────────────────────────────────────────────

impl<T> GenericCrudRepository<T, SoftDelete>
where
    T: for<'r> FromRow<'r, PgRow> + Send + Unpin,
{
    // ── Unique-field lookups (active records only) ────────────────────────────

    /// Find an active entity by a unique text field.
    ///
    /// Filters `metadata->>'deleted_at' IS NULL` automatically.
    pub async fn find_by_text_field(&self, field: &str, value: &str) -> Result<Option<T>> {
        self.find_by_text_field_with_cond(field, value, " AND metadata->>'deleted_at' IS NULL").await
    }

    /// Check existence by a unique text field (active records only).
    pub async fn exists_by_text_field(&self, field: &str, value: &str) -> Result<bool> {
        self.exists_by_text_field_with_cond(field, value, " AND metadata->>'deleted_at' IS NULL").await
    }

    /// Find an active entity by a unique UUID field.
    pub async fn find_by_uuid_field(&self, field: &str, value: Uuid) -> Result<Option<T>> {
        self.find_by_uuid_field_with_cond(field, value, " AND metadata->>'deleted_at' IS NULL").await
    }

    /// Check existence by a unique UUID field (active records only).
    pub async fn exists_by_uuid_field(&self, field: &str, value: Uuid) -> Result<bool> {
        self.exists_by_uuid_field_with_cond(field, value, " AND metadata->>'deleted_at' IS NULL").await
    }

    // ── Filtered pagination (requires EntityRepoMeta on T) ────────────────────

    /// Paginate active entities with filter and search support.
    ///
    /// Requires `T: EntityRepoMeta` for column type hints and search fields.
    pub async fn list_paginated_filtered(
        &self,
        pagination: PaginationParams,
        filters: Option<&HashMap<String, String>>,
    ) -> Result<PaginatedResult<T>>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let filters_map = filters.cloned().unwrap_or_default();
        let column_types = T::column_types();
        let search_fields_owned: Vec<&'static str> = T::search_fields().iter().copied().collect();
        self.run_filtered_query(
            pagination,
            Some("metadata->>'deleted_at' IS NULL"),
            &filters_map,
            &column_types,
            &search_fields_owned,
        ).await
    }

    /// Group and reduce active entities, skipping the soft-deleted.
    pub async fn aggregate_filtered(
        &self,
        spec: &crate::repository::AggregateSpec,
        filters: Option<&HashMap<String, String>>,
    ) -> Result<crate::repository::AggregateResult>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let filters_map = filters.cloned().unwrap_or_default();
        let column_types = T::column_types();
        let search_fields_owned: Vec<&'static str> = T::search_fields().iter().copied().collect();
        self.run_aggregate_query(spec, Some("metadata->>'deleted_at' IS NULL"), &filters_map, &column_types, &search_fields_owned).await
    }

    /// Paginate active entities, fenced to `company`.
    ///
    /// The company-scoped counterpart of [`Self::list_paginated_filtered`] and the one any
    /// client-reachable read should use. Fails closed: a fenced entity with no company
    /// returns [`MissingCompanyScope`] rather than every company's rows.
    ///
    /// The fence is ANDed into the same `__base_condition` the soft-delete guard uses, so
    /// it lands in SQL — which is what keeps `total` honest. A post-filter in the handler
    /// would fetch `limit` rows and return the survivors, leaving callers unable to tell
    /// "end of data" from "filtered", and could not fix `COUNT` at all.
    pub async fn list_paginated_filtered_scoped(
        &self,
        pagination: PaginationParams,
        filters: Option<&HashMap<String, String>>,
        company: Option<Uuid>,
    ) -> Result<PaginatedResult<T>>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let fence = company_fence::<T>(company)?;
        let mut filters_map = filters.cloned().unwrap_or_default();
        strip_client_company_filters::<T>(&mut filters_map);
        let column_types = T::column_types();
        let search_fields_owned: Vec<&'static str> = T::search_fields().iter().copied().collect();
        self.run_filtered_query(
            pagination,
            and_conditions(Some("metadata->>'deleted_at' IS NULL"), fence).as_deref(),
            &filters_map,
            &column_types,
            &search_fields_owned,
        )
        .await
    }

    /// Paginate soft-deleted entities, fenced to `company`.
    ///
    /// `/trash` is the worse leak of the two: it serves rows whose owners were told the
    /// data is gone. Same fence, same fail-closed contract.
    pub async fn list_deleted_filtered_scoped(
        &self,
        pagination: PaginationParams,
        filters: Option<&HashMap<String, String>>,
        company: Option<Uuid>,
    ) -> Result<PaginatedResult<T>>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let fence = company_fence::<T>(company)?;
        let mut filters_map = filters.cloned().unwrap_or_default();
        strip_client_company_filters::<T>(&mut filters_map);
        let column_types = T::column_types();
        let empty: &[&str] = &[];
        self.run_filtered_query(
            pagination,
            and_conditions(Some("metadata->>'deleted_at' IS NOT NULL"), fence).as_deref(),
            &filters_map,
            &column_types,
            empty,
        )
        .await
    }

    /// Paginate soft-deleted entities with filter support.
    pub async fn list_deleted_filtered(
        &self,
        pagination: PaginationParams,
        filters: Option<&HashMap<String, String>>,
    ) -> Result<PaginatedResult<T>>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let filters_map = filters.cloned().unwrap_or_default();
        let column_types = T::column_types();
        let empty: &[&str] = &[];
        self.run_filtered_query(
            pagination,
            Some("metadata->>'deleted_at' IS NOT NULL"),
            &filters_map,
            &column_types,
            empty,
        ).await
    }

    /// Find an active (non-deleted) entity by primary key.
    pub async fn find_by_id(&self, id: &str) -> Result<Option<T>> {
        let query = format!(
            "SELECT * FROM {} WHERE id = $1::uuid AND metadata->>'deleted_at' IS NULL",
            self.table_name()
        );
        let result = crate::company_scope::fetch_optional_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(id),
        )
        .await?;
        Ok(result)
    }

    /// Return all active (non-deleted) entities.
    pub async fn find_all(&self) -> Result<Vec<T>> {
        let query = format!(
            "SELECT * FROM {} WHERE metadata->>'deleted_at' IS NULL",
            self.table_name()
        );
        let results = crate::company_scope::fetch_all_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query),
        )
        .await?;
        Ok(results)
    }

    /// Full update — skips silently if the record is already soft-deleted.
    pub async fn update(&self, id: &str, entity: &T) -> Result<Option<T>>
    where
        T: Serialize + Send + Sync,
    {
        if self.find_by_id(id).await?.is_none() {
            return Ok(None);
        }
        self.inner.update(id, entity).await
    }

    /// Soft-delete an entity (sets `metadata.deleted_at`).
    pub async fn delete(&self, id: &str) -> Result<bool> {
        self.soft_delete(id).await
    }

    /// Count active (non-deleted) entities.
    pub async fn count(&self) -> Result<u64> {
        self.count_active().await
    }

    /// Return `true` if an active entity with the given ID exists.
    pub async fn exists(&self, id: &str) -> Result<bool> {
        let query = format!(
            "SELECT 1 FROM {} WHERE id = $1::uuid AND metadata->>'deleted_at' IS NULL LIMIT 1",
            self.table_name()
        );
        let result = crate::company_scope::fetch_optional_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i32>(&query).bind(id),
        )
        .await?;
        Ok(result.is_some())
    }

    /// Paginate active entities (most-recent-first by ID).
    pub async fn list_paginated(&self, pagination: PaginationParams) -> Result<PaginatedResult<T>> {
        let offset = pagination.offset();
        let limit = pagination.limit();
        let query = format!(
            "SELECT * FROM {} WHERE metadata->>'deleted_at' IS NULL \
             ORDER BY id DESC LIMIT $1 OFFSET $2",
            self.table_name()
        );
        let data = crate::company_scope::fetch_all_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(limit as i64).bind(offset as i64),
        )
        .await?;
        let total = self.count_active().await?;
        Ok(PaginatedResult {
            data,
            pagination: PaginationInfo::new(pagination.page, pagination.per_page, total),
        })
    }

    // ── Soft-delete helpers ───────────────────────────────────────────────────

    /// Set `metadata.deleted_at` to NOW() (soft delete).
    pub async fn soft_delete(&self, id: &str) -> Result<bool> {
        let query = format!(
            "UPDATE {} SET metadata = jsonb_set(\
               COALESCE(metadata, '{{}}'), \
               '{{deleted_at}}', \
               to_jsonb(NOW())\
             ) WHERE id = $1::uuid AND (metadata->>'deleted_at') IS NULL",
            self.table_name()
        );
        let result = crate::company_scope::execute_scoped(
            self.pool(),
            sqlx::query(&query).bind(id),
        )
        .await?;
        Ok(result.rows_affected() > 0)
    }

    /// Remove `deleted_at` from metadata, restoring the entity.
    pub async fn restore(&self, id: &str) -> Result<Option<T>> {
        let query = format!(
            "UPDATE {} SET metadata = metadata - 'deleted_at' \
             WHERE id = $1::uuid AND (metadata->>'deleted_at') IS NOT NULL \
             RETURNING *",
            self.table_name()
        );
        let result = crate::company_scope::fetch_optional_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(id),
        )
        .await?;
        Ok(result)
    }

    /// Paginate soft-deleted entities (trash view).
    pub async fn list_deleted(&self, pagination: PaginationParams) -> Result<PaginatedResult<T>> {
        let offset = pagination.offset();
        let limit = pagination.limit();
        let query = format!(
            "SELECT * FROM {} WHERE (metadata->>'deleted_at') IS NOT NULL \
             ORDER BY (metadata->>'deleted_at') DESC LIMIT $1 OFFSET $2",
            self.table_name()
        );
        let data = crate::company_scope::fetch_all_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(limit as i64).bind(offset as i64),
        )
        .await?;
        let count_query = format!(
            "SELECT COUNT(*) FROM {} WHERE (metadata->>'deleted_at') IS NOT NULL",
            self.table_name()
        );
        let total = crate::company_scope::fetch_one_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i64>(&count_query),
        )
        .await? as u64;
        Ok(PaginatedResult {
            data,
            pagination: PaginationInfo::new(pagination.page, pagination.per_page, total),
        })
    }

    /// Permanently delete all soft-deleted rows (empty trash).
    pub async fn empty_trash(&self) -> Result<u64> {
        let query = format!(
            "DELETE FROM {} WHERE (metadata->>'deleted_at') IS NOT NULL",
            self.table_name()
        );
        let result = crate::company_scope::execute_scoped(self.pool(), sqlx::query(&query)).await?;
        Ok(result.rows_affected())
    }

    /// Find a soft-deleted entity by primary key.
    pub async fn find_deleted_by_id(&self, id: &str) -> Result<Option<T>> {
        let query = format!(
            "SELECT * FROM {} WHERE id = $1::uuid AND (metadata->>'deleted_at') IS NOT NULL",
            self.table_name()
        );
        let result = crate::company_scope::fetch_optional_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(id),
        )
        .await?;
        Ok(result)
    }

    /// Permanently delete a soft-deleted entity by primary key.
    pub async fn permanent_delete(&self, id: &str) -> Result<bool> {
        let query = format!(
            "DELETE FROM {} WHERE id = $1::uuid AND (metadata->>'deleted_at') IS NOT NULL",
            self.table_name()
        );
        let result = crate::company_scope::execute_scoped(
            self.pool(),
            sqlx::query(&query).bind(id),
        )
        .await?;
        Ok(result.rows_affected() > 0)
    }

    /// Count active (non-deleted) entities.
    pub async fn count_active(&self) -> Result<u64> {
        let query = format!(
            "SELECT COUNT(*) FROM {} WHERE (metadata->>'deleted_at') IS NULL",
            self.table_name()
        );
        let count = crate::company_scope::fetch_one_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i64>(&query),
        )
        .await? as u64;
        Ok(count)
    }

    /// Count soft-deleted entities.
    pub async fn count_deleted(&self) -> Result<u64> {
        let query = format!(
            "SELECT COUNT(*) FROM {} WHERE (metadata->>'deleted_at') IS NOT NULL",
            self.table_name()
        );
        let count = crate::company_scope::fetch_one_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i64>(&query),
        )
        .await? as u64;
        Ok(count)
    }

    // ── Atomic batch operations ───────────────────────────────────────────────
    //
    // Each runs inside a single transaction. For id-list operations the affected
    // row count must equal the number of ids requested, otherwise the whole batch
    // is rolled back — all-or-nothing semantics where a missing / already-in-the-
    // target-state id (or a duplicate id) fails the entire request.

    /// Soft-delete many active rows atomically.
    pub async fn bulk_soft_delete(&self, ids: &[String]) -> Result<u64> {
        if ids.is_empty() {
            return Ok(0);
        }
        let placeholders = id_in_placeholders(ids.len());
        let query = format!(
            "UPDATE {} SET metadata = jsonb_set(\
               COALESCE(metadata, '{{}}'), '{{deleted_at}}', to_jsonb(NOW())\
             ) WHERE id IN ({placeholders}) AND (metadata->>'deleted_at') IS NULL",
            self.table_name()
        );
        let mut tx = self.pool().begin().await?;
        crate::company_scope::bind_current_company(&mut tx).await?;
        let mut q = sqlx::query(&query);
        for id in ids {
            q = q.bind(id);
        }
        let affected = q.execute(&mut *tx).await?.rows_affected();
        if affected != ids.len() as u64 {
            // `tx` is dropped here without commit → rolled back.
            return Err(anyhow::anyhow!(
                "bulk_soft_delete: {} of {} ids were not active/deletable; rolled back",
                ids.len() as u64 - affected,
                ids.len()
            ));
        }
        tx.commit().await?;
        Ok(affected)
    }

    /// Restore many soft-deleted rows atomically, returning the restored rows.
    pub async fn bulk_restore(&self, ids: &[String]) -> Result<Vec<T>> {
        if ids.is_empty() {
            return Ok(Vec::new());
        }
        let placeholders = id_in_placeholders(ids.len());
        let query = format!(
            "UPDATE {} SET metadata = metadata - 'deleted_at' \
             WHERE id IN ({placeholders}) AND (metadata->>'deleted_at') IS NOT NULL \
             RETURNING *",
            self.table_name()
        );
        let mut tx = self.pool().begin().await?;
        crate::company_scope::bind_current_company(&mut tx).await?;
        let mut q = sqlx::query_as::<_, T>(&query);
        for id in ids {
            q = q.bind(id);
        }
        let rows = q.fetch_all(&mut *tx).await?;
        if rows.len() != ids.len() {
            return Err(anyhow::anyhow!(
                "bulk_restore: {} of {} ids were not in trash; rolled back",
                ids.len() - rows.len(),
                ids.len()
            ));
        }
        tx.commit().await?;
        Ok(rows)
    }

    /// Permanently delete many soft-deleted rows atomically.
    pub async fn bulk_permanent_delete(&self, ids: &[String]) -> Result<u64> {
        if ids.is_empty() {
            return Ok(0);
        }
        let placeholders = id_in_placeholders(ids.len());
        let query = format!(
            "DELETE FROM {} WHERE id IN ({placeholders}) AND (metadata->>'deleted_at') IS NOT NULL",
            self.table_name()
        );
        let mut tx = self.pool().begin().await?;
        crate::company_scope::bind_current_company(&mut tx).await?;
        let mut q = sqlx::query(&query);
        for id in ids {
            q = q.bind(id);
        }
        let affected = q.execute(&mut *tx).await?.rows_affected();
        if affected != ids.len() as u64 {
            return Err(anyhow::anyhow!(
                "bulk_permanent_delete: {} of {} ids were not in trash; rolled back",
                ids.len() as u64 - affected,
                ids.len()
            ));
        }
        tx.commit().await?;
        Ok(affected)
    }

    /// Restore every soft-deleted row, returning the restored rows. A single
    /// `UPDATE ... RETURNING` is atomic, and the returned rows let the service
    /// layer emit a `Restored` event per entity.
    pub async fn restore_all(&self) -> Result<Vec<T>> {
        let query = format!(
            "UPDATE {} SET metadata = metadata - 'deleted_at' \
             WHERE (metadata->>'deleted_at') IS NOT NULL \
             RETURNING *",
            self.table_name()
        );
        let rows = crate::company_scope::fetch_all_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query),
        )
        .await?;
        Ok(rows)
    }

    /// Update many active rows atomically. Every entity must reference an
    /// existing active (non-soft-deleted) row or the whole batch is rolled back.
    pub async fn bulk_update(&self, entities: &[T]) -> Result<Vec<T>>
    where
        T: Serialize + Send + Sync,
    {
        bulk_update_rows(
            self.pool(),
            self.table_name(),
            " AND t.metadata->>'deleted_at' IS NULL",
            entities,
        )
        .await
    }
}

/// Build `"$1::uuid, $2::uuid, …"` for an `id IN (…)` clause of `n` bound ids.
fn id_in_placeholders(n: usize) -> String {
    (1..=n)
        .map(|i| format!("${i}::uuid"))
        .collect::<Vec<_>>()
        .join(", ")
}

/// Serialize an entity and return `(id, json_string, quoted_column_list)` for the
/// `jsonb_populate_record` update query — shared by the per-mode `bulk_update`s.
fn build_update_parts<T: Serialize>(entity: &T) -> Result<(String, String, String)> {
    let json_value = serde_json::to_value(entity)?;
    let json_obj = match json_value {
        serde_json::Value::Object(obj) => obj,
        _ => return Err(anyhow::anyhow!("entity must serialize to a JSON object")),
    };
    let id = json_obj
        .get("id")
        .and_then(|v| v.as_str())
        .ok_or_else(|| anyhow::anyhow!("entity missing string 'id' field"))?
        .to_string();
    let column_names = json_obj
        .keys()
        .filter(|k| *k != "id")
        .map(|k| format!("\"{k}\""))
        .collect::<Vec<_>>()
        .join(", ");
    let json_str = serde_json::to_string(&json_obj)?;
    Ok((id, json_str, column_names))
}

// ─── HardDelete mode ─────────────────────────────────────────────────────────

impl<T> GenericCrudRepository<T, HardDelete>
where
    T: for<'r> FromRow<'r, PgRow> + Send + Sync + Unpin + Serialize,
{
    // ── Unique-field lookups (no soft-delete guard) ───────────────────────────

    /// Find an entity by a unique text field (no soft-delete guard).
    pub async fn find_by_text_field(&self, field: &str, value: &str) -> Result<Option<T>> {
        self.find_by_text_field_with_cond(field, value, "").await
    }

    /// Check existence by a unique text field.
    pub async fn exists_by_text_field(&self, field: &str, value: &str) -> Result<bool> {
        self.exists_by_text_field_with_cond(field, value, "").await
    }

    /// Find an entity by a unique UUID field.
    pub async fn find_by_uuid_field(&self, field: &str, value: Uuid) -> Result<Option<T>> {
        self.find_by_uuid_field_with_cond(field, value, "").await
    }

    /// Check existence by a unique UUID field.
    pub async fn exists_by_uuid_field(&self, field: &str, value: Uuid) -> Result<bool> {
        self.exists_by_uuid_field_with_cond(field, value, "").await
    }

    // ── Filtered pagination ───────────────────────────────────────────────────

    /// Paginate entities with filter and search support.
    pub async fn list_paginated_filtered(
        &self,
        pagination: PaginationParams,
        filters: Option<&HashMap<String, String>>,
    ) -> Result<PaginatedResult<T>>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let filters_map = filters.cloned().unwrap_or_default();
        let column_types = T::column_types();
        let search_fields_owned: Vec<&'static str> = T::search_fields().iter().copied().collect();
        self.run_filtered_query(pagination, None, &filters_map, &column_types, &search_fields_owned).await
    }

    /// Group and reduce entities. This mode has no trash to exclude.
    pub async fn aggregate_filtered(
        &self,
        spec: &crate::repository::AggregateSpec,
        filters: Option<&HashMap<String, String>>,
    ) -> Result<crate::repository::AggregateResult>
    where
        T: EntityRepoMeta + Send + Sync,
    {
        let filters_map = filters.cloned().unwrap_or_default();
        let column_types = T::column_types();
        let search_fields_owned: Vec<&'static str> = T::search_fields().iter().copied().collect();
        self.run_aggregate_query(spec, None, &filters_map, &column_types, &search_fields_owned).await
    }

    /// Find an entity by primary key.
    pub async fn find_by_id(&self, id: &str) -> Result<Option<T>> {
        self.inner.find_by_id(id).await
    }

    /// Return all entities.
    pub async fn find_all(&self) -> Result<Vec<T>> {
        let query = format!("SELECT * FROM {}", self.table_name());
        let results = crate::company_scope::fetch_all_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query),
        )
        .await?;
        Ok(results)
    }

    /// Full update.
    pub async fn update(&self, id: &str, entity: &T) -> Result<Option<T>> {
        self.inner.update(id, entity).await
    }

    /// Permanently delete an entity by primary key.
    pub async fn delete(&self, id: &str) -> Result<bool> {
        self.inner.delete(id).await
    }

    /// Count all entities.
    pub async fn count(&self) -> Result<u64> {
        let query = format!("SELECT COUNT(*) FROM {}", self.table_name());
        let count = crate::company_scope::fetch_one_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i64>(&query),
        )
        .await? as u64;
        Ok(count)
    }

    /// Return `true` if an entity with the given ID exists.
    pub async fn exists(&self, id: &str) -> Result<bool> {
        let query = format!(
            "SELECT 1 FROM {} WHERE id = $1::uuid LIMIT 1",
            self.table_name()
        );
        let result = crate::company_scope::fetch_optional_scalar_scoped(
            self.pool(),
            sqlx::query_scalar::<_, i32>(&query).bind(id),
        )
        .await?;
        Ok(result.is_some())
    }

    /// Paginate entities (most-recent-first by ID).
    pub async fn list_paginated(&self, pagination: PaginationParams) -> Result<PaginatedResult<T>> {
        let offset = pagination.offset();
        let limit = pagination.limit();
        let query = format!(
            "SELECT * FROM {} ORDER BY id DESC LIMIT $1 OFFSET $2",
            self.table_name()
        );
        let data = crate::company_scope::fetch_all_scoped(
            self.pool(),
            sqlx::query_as::<_, T>(&query).bind(limit as i64).bind(offset as i64),
        )
        .await?;
        let total = self.count().await?;
        Ok(PaginatedResult {
            data,
            pagination: PaginationInfo::new(pagination.page, pagination.per_page, total),
        })
    }

    // ── Atomic batch operations ───────────────────────────────────────────────

    /// Hard-delete many rows atomically. Rolls back unless every id matched.
    pub async fn bulk_delete(&self, ids: &[String]) -> Result<u64> {
        if ids.is_empty() {
            return Ok(0);
        }
        let placeholders = id_in_placeholders(ids.len());
        let query = format!(
            "DELETE FROM {} WHERE id IN ({placeholders})",
            self.table_name()
        );
        let mut tx = self.pool().begin().await?;
        crate::company_scope::bind_current_company(&mut tx).await?;
        let mut q = sqlx::query(&query);
        for id in ids {
            q = q.bind(id);
        }
        let affected = q.execute(&mut *tx).await?.rows_affected();
        if affected != ids.len() as u64 {
            return Err(anyhow::anyhow!(
                "bulk_delete: {} of {} ids not found; rolled back",
                ids.len() as u64 - affected,
                ids.len()
            ));
        }
        tx.commit().await?;
        Ok(affected)
    }

    /// Update many rows atomically. No soft-delete guard in this mode.
    pub async fn bulk_update(&self, entities: &[T]) -> Result<Vec<T>> {
        bulk_update_rows(self.pool(), self.table_name(), "", entities).await
    }
}

/// Qualify a relation target table with the calling entity's schema.
///
/// `EntityRepoMeta::relations()` emits bare table names (e.g. `countries`), but
/// module tables live in the module's own schema (`geo.countries`) and the
/// runtime app role's search_path does not include module schemas — an
/// unqualified reference fails with "relation does not exist". The calling
/// entity's table name is schema-qualified, so its prefix is the schema a
/// relation declared inside one module shares with its target. Targets that
/// already carry a schema, and callers that do not, pass through unchanged.
pub fn qualify_relation_table(caller_table: &str, target_table: &str) -> String {
    if target_table.contains('.') || !caller_table.contains('.') {
        target_table.to_string()
    } else {
        let schema = caller_table.split('.').next().unwrap_or(caller_table);
        format!("{schema}.{target_table}")
    }
}

/// True when the error is Postgres `undefined_table` (SQLSTATE 42P01).
///
/// Walks the anyhow chain because the scoped-fetch error is converted with `?`
/// on its way up — the sqlx error rides as the (only) source.
fn is_undefined_table(err: &anyhow::Error) -> bool {
    err.chain()
        .filter_map(|cause| cause.downcast_ref::<sqlx::Error>())
        .any(|sqlx_err| {
            sqlx_err
                .as_database_error()
                .map(|db| db.code().as_deref() == Some("42P01"))
                .unwrap_or(false)
        })
}

/// Fetch rows from an arbitrary table by id list, as JSON — hydrates `?include=`
/// relations in the generic CRUD handler without a typed repository for the
/// target entity. `table` is a generator-emitted collection name (from
/// `EntityRepoMeta::relations()`), NEVER client input, so the interpolation is
/// not an injection vector. `caller_table` is the hydrated entity's own
/// (schema-qualified) table name, used to qualify a bare `table` — see
/// [`qualify_relation_table`]. One batched `WHERE id = ANY(...)` per relation.
/// Returns `row_to_json` objects keyed by raw (snake_case) column names.
///
/// Resolution is two-step for bare targets: the caller's schema first, then —
/// only on `undefined_table` — the name as written, which resolves through the
/// role's search_path (platform tables such as `users` or `roles` live in
/// `public` while their declaring entities live in a module schema). Any other
/// error, or a target that fails both spellings, is returned to the caller.
pub async fn fetch_by_ids_as_json(
    pool: &PgPool,
    caller_table: &str,
    table: &str,
    ids: &[String],
) -> Result<Vec<serde_json::Value>> {
    if ids.is_empty() {
        return Ok(Vec::new());
    }
    let qualified = qualify_relation_table(caller_table, table);
    match fetch_rows_as_json(pool, &qualified, ids).await {
        Ok(rows) => Ok(rows),
        Err(err) if qualified != table && is_undefined_table(&err) => {
            fetch_rows_as_json(pool, table, ids).await
        }
        Err(err) => Err(err),
    }
}

/// The scoped fetch behind [`fetch_by_ids_as_json`] — one relation, one table
/// spelling. Scoped because an `?include=` hydration of a company-fenced
/// relation must obey the same fence, so a cross-company related row is never
/// leaked through the expansion.
async fn fetch_rows_as_json(
    pool: &PgPool,
    table: &str,
    ids: &[String],
) -> Result<Vec<serde_json::Value>> {
    let query = format!("SELECT row_to_json(t) AS j FROM {table} t WHERE t.id = ANY($1::uuid[])");
    let rows: Vec<(serde_json::Value,)> =
        crate::company_scope::fetch_all_scoped(pool, sqlx::query_as(&query).bind(ids)).await?;
    Ok(rows.into_iter().map(|(j,)| j).collect())
}

/// Shared transactional bulk-update used by both delete modes. Each entity is
/// updated by id inside one transaction; a missing (or, with `active_guard`,
/// soft-deleted) row rolls the whole batch back. `active_guard` is an extra SQL
/// predicate ANDed into the `WHERE` clause (`""` for none).
async fn bulk_update_rows<T>(
    pool: &PgPool,
    table: &str,
    active_guard: &str,
    entities: &[T],
) -> Result<Vec<T>>
where
    T: for<'r> FromRow<'r, PgRow> + Send + Sync + Unpin + Serialize,
{
    if entities.is_empty() {
        return Ok(Vec::new());
    }
    let mut tx = pool.begin().await?;
    crate::company_scope::bind_current_company(&mut tx).await?;
    let mut out = Vec::with_capacity(entities.len());
    for entity in entities {
        let (id, json_str, column_names) = build_update_parts(entity)?;
        let query = format!(
            "WITH new_row AS (\
                SELECT (jsonb_populate_record(NULL::{table}, $1::jsonb)).*\
             ) UPDATE {table} AS t \
             SET ({columns}) = (SELECT {columns} FROM new_row) \
             WHERE t.id = $2::uuid{guard} \
             RETURNING t.*",
            table = table,
            columns = column_names,
            guard = active_guard,
        );
        let updated = sqlx::query_as::<_, T>(&query)
            .bind(&json_str)
            .bind(&id)
            .fetch_optional(&mut *tx)
            .await?;
        match updated {
            Some(e) => out.push(e),
            None => {
                return Err(anyhow::anyhow!(
                    "bulk_update: id '{id}' not found or already deleted; rolled back"
                ));
            }
        }
    }
    tx.commit().await?;
    Ok(out)
}

/// camelCase → snake_case (`projectId` → `project_id`), the SQL vocabulary.
fn camel_to_snake(s: &str) -> String {
    let mut out = String::with_capacity(s.len() + 4);
    for ch in s.chars() {
        if ch.is_uppercase() {
            out.push('_');
            out.extend(ch.to_lowercase());
        } else {
            out.push(ch);
        }
    }
    out
}