rustango 0.38.0

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

use crate::core::Model as _;
use crate::core::{ConflictClause, DeleteQuery, Filter, InsertQuery, Op, SqlValue, WhereExpr};
use crate::sql::sqlx;
#[cfg(feature = "postgres")]
use crate::sql::sqlx::{PgPool, Row};
use crate::sql::Auto;
use crate::Model;

use super::error::TenancyError;

// ------------------------------------------------------------------ Models

/// A named group of permissions (Django `Group` equivalent).
///
/// Assign a user to a role via [`UserRole`]; grant codenames to a role
/// via [`RolePermission`].
#[derive(Model, Debug, Clone)]
#[rustango(
    table = "rustango_roles",
    display = "name",
    admin(
        list_display = "name, description",
        search_fields = "name, description",
        ordering = "name",
    )
)]
pub struct Role {
    #[rustango(primary_key)]
    pub id: Auto<i64>,
    /// Human-readable name. Unique within the tenant.
    #[rustango(max_length = 150, unique)]
    pub name: String,
    #[rustango(max_length = 500)]
    pub description: String,
    /// Flexible role metadata — display config, feature flags, UI
    /// hints. Never read by the permission engine.
    #[rustango(default = "'{}'")]
    pub data: serde_json::Value,
}

/// One codename granted to a role. Composite key (role_id, codename)
/// enforced by DB unique constraint; surrogate `id` for ORM compat.
#[derive(Model, Debug, Clone)]
#[rustango(
    table = "rustango_role_permissions",
    display = "codename",
    admin(
        list_display = "role_id, codename",
        search_fields = "codename",
        ordering = "role_id, codename",
    )
)]
pub struct RolePermission {
    #[rustango(primary_key)]
    pub id: Auto<i64>,
    /// The role this permission belongs to.
    pub role_id: i64,
    /// Permission codename — `{table}.{action}`, e.g. `post.change`.
    #[rustango(max_length = 100)]
    pub codename: String,
}

/// Membership row linking a user to a role.
/// Surrogate `id` for ORM compat; unique constraint on `(user_id, role_id)`.
#[derive(Model, Debug, Clone)]
#[rustango(
    table = "rustango_user_roles",
    admin(list_display = "user_id, role_id", ordering = "user_id, role_id",)
)]
pub struct UserRole {
    #[rustango(primary_key)]
    pub id: Auto<i64>,
    /// `rustango_users.id`
    pub user_id: i64,
    /// `rustango_roles.id`
    pub role_id: i64,
}

/// Per-user permission override. `granted = true` adds a codename
/// explicitly; `granted = false` denies it even if a role would grant it.
#[derive(Model, Debug, Clone)]
#[rustango(
    table = "rustango_user_permissions",
    display = "codename",
    admin(
        list_display = "user_id, codename, granted",
        search_fields = "codename",
        ordering = "user_id, codename",
    )
)]
pub struct UserPermission {
    #[rustango(primary_key)]
    pub id: Auto<i64>,
    /// `rustango_users.id`
    pub user_id: i64,
    /// Permission codename — `{table}.{action}`.
    #[rustango(max_length = 100)]
    pub codename: String,
    /// `true` = explicit grant; `false` = explicit denial.
    pub granted: bool,
    /// Extra context on this override — reason, granted-by, expiry
    /// hints. Never read by `has_perm`.
    #[rustango(default = "'{}'")]
    pub data: serde_json::Value,
}

// ------------------------------------------------------------------ ensure_tables (DDL)

const ENSURE_SQL: &str = r#"
CREATE TABLE IF NOT EXISTS "rustango_permissions" (
    "id"          BIGSERIAL    PRIMARY KEY,
    "table_name"  VARCHAR(150) NOT NULL,
    "codename"    VARCHAR(100) NOT NULL,
    "name"        VARCHAR(255) NOT NULL DEFAULT '',
    CONSTRAINT "rustango_permissions_uq" UNIQUE ("table_name", "codename")
);
CREATE TABLE IF NOT EXISTS "rustango_roles" (
    "id"          BIGSERIAL    PRIMARY KEY,
    "name"        VARCHAR(150) NOT NULL,
    "description" VARCHAR(500) NOT NULL DEFAULT '',
    "data"        JSONB        NOT NULL DEFAULT '{}',
    CONSTRAINT "rustango_roles_name_uq" UNIQUE ("name")
);
ALTER TABLE "rustango_roles"
    ADD COLUMN IF NOT EXISTS "data" JSONB NOT NULL DEFAULT '{}';
CREATE TABLE IF NOT EXISTS "rustango_role_permissions" (
    "id"       BIGSERIAL    PRIMARY KEY,
    "role_id"  BIGINT       NOT NULL
                             REFERENCES "rustango_roles"("id")
                             ON DELETE CASCADE,
    "codename" VARCHAR(100) NOT NULL,
    CONSTRAINT "rustango_role_permissions_uq" UNIQUE ("role_id", "codename")
);
CREATE TABLE IF NOT EXISTS "rustango_user_roles" (
    "id"      BIGSERIAL PRIMARY KEY,
    "user_id" BIGINT    NOT NULL
                         REFERENCES "rustango_users"("id")
                         ON DELETE CASCADE,
    "role_id" BIGINT    NOT NULL
                         REFERENCES "rustango_roles"("id")
                         ON DELETE CASCADE,
    CONSTRAINT "rustango_user_roles_uq" UNIQUE ("user_id", "role_id")
);
CREATE TABLE IF NOT EXISTS "rustango_user_permissions" (
    "id"       BIGSERIAL    PRIMARY KEY,
    "user_id"  BIGINT       NOT NULL
                             REFERENCES "rustango_users"("id")
                             ON DELETE CASCADE,
    "codename" VARCHAR(100) NOT NULL,
    "granted"  BOOLEAN      NOT NULL DEFAULT TRUE,
    "data"     JSONB        NOT NULL DEFAULT '{}',
    CONSTRAINT "rustango_user_permissions_uq" UNIQUE ("user_id", "codename")
);
ALTER TABLE "rustango_user_permissions"
    ADD COLUMN IF NOT EXISTS "data" JSONB NOT NULL DEFAULT '{}';
ALTER TABLE "rustango_users"
    ADD COLUMN IF NOT EXISTS "data" JSONB NOT NULL DEFAULT '{}';
ALTER TABLE "rustango_users"
    ADD COLUMN IF NOT EXISTS "password_changed_at" TIMESTAMPTZ NULL;
"#;

/// v0.38 — SQLite counterpart of [`ENSURE_SQL`].
///
/// Differences from the PG version:
/// - `BIGSERIAL` → `INTEGER PRIMARY KEY AUTOINCREMENT` (SQLite's
///   auto-rowid spelling — `INTEGER PRIMARY KEY` aliases to the
///   internal `ROWID`, AUTOINCREMENT enforces monotonic non-reuse).
/// - `BIGINT` / `VARCHAR(N)` / `JSONB` / `BOOLEAN` / `TIMESTAMPTZ`
///   collapse to SQLite's loose affinities (`INTEGER` / `TEXT`).
/// - `DEFAULT TRUE` → `DEFAULT 1` (SQLite has no bool literal —
///   1/0 are the canonical encoding the sqlx-sqlite driver reads
///   back via `<bool as Decode<Sqlite>>`).
/// - No `ALTER TABLE ADD COLUMN IF NOT EXISTS`. The PG ALTER block
///   is a legacy backfill for ≤0.27 installs; fresh SQLite tenants
///   never need it because the columns ship in the CREATE TABLE.
const ENSURE_SQL_SQLITE: &str = r#"
CREATE TABLE IF NOT EXISTS "rustango_permissions" (
    "id"          INTEGER     PRIMARY KEY AUTOINCREMENT,
    "table_name"  TEXT        NOT NULL,
    "codename"    TEXT        NOT NULL,
    "name"        TEXT        NOT NULL DEFAULT '',
    CONSTRAINT "rustango_permissions_uq" UNIQUE ("table_name", "codename")
);
CREATE TABLE IF NOT EXISTS "rustango_roles" (
    "id"          INTEGER     PRIMARY KEY AUTOINCREMENT,
    "name"        TEXT        NOT NULL,
    "description" TEXT        NOT NULL DEFAULT '',
    "data"        TEXT        NOT NULL DEFAULT '{}',
    CONSTRAINT "rustango_roles_name_uq" UNIQUE ("name")
);
CREATE TABLE IF NOT EXISTS "rustango_role_permissions" (
    "id"       INTEGER  PRIMARY KEY AUTOINCREMENT,
    "role_id"  INTEGER  NOT NULL
                         REFERENCES "rustango_roles"("id")
                         ON DELETE CASCADE,
    "codename" TEXT     NOT NULL,
    CONSTRAINT "rustango_role_permissions_uq" UNIQUE ("role_id", "codename")
);
CREATE TABLE IF NOT EXISTS "rustango_user_roles" (
    "id"      INTEGER PRIMARY KEY AUTOINCREMENT,
    "user_id" INTEGER NOT NULL
                       REFERENCES "rustango_users"("id")
                       ON DELETE CASCADE,
    "role_id" INTEGER NOT NULL
                       REFERENCES "rustango_roles"("id")
                       ON DELETE CASCADE,
    CONSTRAINT "rustango_user_roles_uq" UNIQUE ("user_id", "role_id")
);
CREATE TABLE IF NOT EXISTS "rustango_user_permissions" (
    "id"       INTEGER  PRIMARY KEY AUTOINCREMENT,
    "user_id"  INTEGER  NOT NULL
                         REFERENCES "rustango_users"("id")
                         ON DELETE CASCADE,
    "codename" TEXT     NOT NULL,
    "granted"  INTEGER  NOT NULL DEFAULT 1,
    "data"     TEXT     NOT NULL DEFAULT '{}',
    CONSTRAINT "rustango_user_permissions_uq" UNIQUE ("user_id", "codename")
);
"#;

/// v0.38 — MySQL counterpart of [`ENSURE_SQL`]. Identifier quoting
/// is backticks (MySQL rejects double-quoted identifiers in default
/// `ANSI_QUOTES=off` mode). `BIGSERIAL` → `BIGINT AUTO_INCREMENT
/// PRIMARY KEY`. `JSONB` → `JSON`. `TIMESTAMPTZ` → `DATETIME(6)`.
/// `BOOLEAN` is a `TINYINT(1)` alias. Same legacy-ALTER posture as
/// SQLite: omit the back-compat columns — fresh MySQL tenants ship
/// the `data` / `password_changed_at` columns from the CREATE.
const ENSURE_SQL_MYSQL: &str = r#"
CREATE TABLE IF NOT EXISTS `rustango_permissions` (
    `id`          BIGINT AUTO_INCREMENT PRIMARY KEY,
    `table_name`  VARCHAR(150) NOT NULL,
    `codename`    VARCHAR(100) NOT NULL,
    `name`        VARCHAR(255) NOT NULL DEFAULT '',
    CONSTRAINT `rustango_permissions_uq` UNIQUE (`table_name`, `codename`)
);
CREATE TABLE IF NOT EXISTS `rustango_roles` (
    `id`          BIGINT AUTO_INCREMENT PRIMARY KEY,
    `name`        VARCHAR(150) NOT NULL,
    `description` VARCHAR(500) NOT NULL DEFAULT '',
    `data`        JSON         NOT NULL,
    CONSTRAINT `rustango_roles_name_uq` UNIQUE (`name`)
);
CREATE TABLE IF NOT EXISTS `rustango_role_permissions` (
    `id`       BIGINT AUTO_INCREMENT PRIMARY KEY,
    `role_id`  BIGINT       NOT NULL,
    `codename` VARCHAR(100) NOT NULL,
    CONSTRAINT `rustango_role_permissions_uq` UNIQUE (`role_id`, `codename`),
    CONSTRAINT `rustango_role_permissions_fk_role`
        FOREIGN KEY (`role_id`) REFERENCES `rustango_roles`(`id`) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS `rustango_user_roles` (
    `id`      BIGINT AUTO_INCREMENT PRIMARY KEY,
    `user_id` BIGINT NOT NULL,
    `role_id` BIGINT NOT NULL,
    CONSTRAINT `rustango_user_roles_uq` UNIQUE (`user_id`, `role_id`),
    CONSTRAINT `rustango_user_roles_fk_user`
        FOREIGN KEY (`user_id`) REFERENCES `rustango_users`(`id`) ON DELETE CASCADE,
    CONSTRAINT `rustango_user_roles_fk_role`
        FOREIGN KEY (`role_id`) REFERENCES `rustango_roles`(`id`) ON DELETE CASCADE
);
CREATE TABLE IF NOT EXISTS `rustango_user_permissions` (
    `id`       BIGINT AUTO_INCREMENT PRIMARY KEY,
    `user_id`  BIGINT       NOT NULL,
    `codename` VARCHAR(100) NOT NULL,
    `granted`  BOOLEAN      NOT NULL DEFAULT TRUE,
    `data`     JSON         NOT NULL,
    CONSTRAINT `rustango_user_permissions_uq` UNIQUE (`user_id`, `codename`),
    CONSTRAINT `rustango_user_permissions_fk_user`
        FOREIGN KEY (`user_id`) REFERENCES `rustango_users`(`id`) ON DELETE CASCADE
);
"#;

/// Ensure all four permission tables exist in `pool`'s schema.
/// Idempotent — safe to call on every boot. The tables are framework-
/// managed (like `rustango_audit_log`) and live outside the user's
/// migration chain; `make_migrations` sees them as baseline.
///
/// # Errors
/// Driver failures from `CREATE TABLE IF NOT EXISTS`.
///
/// v0.38 — deprecated. The framework's bootstrap migrations
/// (`0001_rustango_tenant_initial.json` written by `init-tenancy`)
/// already create every permission table the engine needs, with
/// per-dialect DDL emitted by the migration runner. New code should
/// rely on `migrate` / `migrate-tenants` instead of calling this
/// directly. Kept for downstream tests that scaffold a registry by
/// hand and expect the tables to exist mid-test.
#[cfg(feature = "postgres")]
#[deprecated(
    since = "0.38.0",
    note = "use `cargo run -- migrate` (the bootstrap tenant migration creates these tables per-dialect); this runtime DDL helper is PG-only and predates the bootstrap migrations"
)]
pub async fn ensure_tables(pool: &PgPool) -> Result<(), sqlx::Error> {
    for stmt in ENSURE_SQL
        .split(';')
        .map(str::trim)
        .filter(|s| !s.is_empty())
    {
        sqlx::query(stmt).execute(pool).await?;
    }
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`ensure_tables`]. Picks the
/// per-dialect DDL constant ([`ENSURE_SQL`] / [`ENSURE_SQL_SQLITE`] /
/// [`ENSURE_SQL_MYSQL`]) and runs each statement as its own round-trip
/// because sqlx's simple-prepare path rejects multi-statement strings.
///
/// Long-term, the bootstrap tenant migration should create every
/// table the engine needs and this runtime helper goes away; today
/// the bootstrap only emits `CreateTable rustango_users` (the seven
/// auth/perm tables live in its snapshot but never get DDL'd by the
/// migration runner). This helper plugs that gap on all three
/// dialects.
///
/// # Errors
/// Driver / SQL failures from any `CREATE TABLE IF NOT EXISTS`.
pub async fn ensure_tables_pool(pool: &crate::sql::Pool) -> Result<(), sqlx::Error> {
    let dialect = pool.dialect();
    let ddl = match dialect.name() {
        "sqlite" => ENSURE_SQL_SQLITE,
        "mysql" => ENSURE_SQL_MYSQL,
        // PG and any future dialect fall through to the original
        // BIGSERIAL/JSONB/TIMESTAMPTZ DDL.
        _ => ENSURE_SQL,
    };
    for stmt in ddl.split(';').map(str::trim).filter(|s| !s.is_empty()) {
        crate::sql::raw_execute_pool(pool, stmt, Vec::new())
            .await
            .map_err(|e| match e {
                crate::sql::ExecError::Driver(err) => err,
                other => sqlx::Error::Protocol(format!("{other}")),
            })?;
    }
    Ok(())
}

// ------------------------------------------------------------------ has_perm (CTE query)

/// Check whether user `uid` holds permission `codename` in `pool`.
///
/// Resolution order:
/// 1. Superuser → always `true`.
/// 2. Explicit per-user denial (`granted = false`) → `false`.
/// 3. Explicit per-user grant (`granted = true`) → `true`.
/// 4. Any role the user belongs to grants `codename` → `true`.
/// 5. Default → `false`.
///
/// Single round-trip via a CTE.
///
/// # Errors
/// Driver / SQL failures.
#[cfg(feature = "postgres")]
pub async fn has_perm(uid: i64, codename: &str, pool: &PgPool) -> Result<bool, sqlx::Error> {
    has_perm_on(uid, codename, pool).await
}

/// v0.38 — tri-dialect counterpart of [`has_perm`]. Trades the single
/// CTE round-trip for three ORM queries (user-info, explicit grant,
/// role-via grant) — each an indexed lookup, total cost ≈ 3× the
/// CTE in latency but portable across PG/MySQL/SQLite without
/// dialect-specific `TRUE`/`FALSE` literals or array binding.
///
/// Resolution order is identical to [`has_perm`]:
/// 1. Superuser → true
/// 2. Explicit per-user denial (`granted = false`) → false
/// 3. Explicit per-user grant (`granted = true`) → true
/// 4. Any role the user belongs to grants `codename` → true
/// 5. Default → false
///
/// # Errors
/// Driver / SQL failures.
pub async fn has_perm_pool(
    uid: i64,
    codename: &str,
    pool: &crate::sql::Pool,
) -> Result<bool, TenancyError> {
    use sqlx::Row as _;
    let dialect = pool.dialect();
    let users_t = dialect.quote_ident("rustango_users");
    let user_perms_t = dialect.quote_ident("rustango_user_permissions");
    let user_roles_t = dialect.quote_ident("rustango_user_roles");
    let role_perms_t = dialect.quote_ident("rustango_role_permissions");
    // v0.38 — bind uid 3 times + codename 2 times. PG `placeholder(n)`
    // generates `$n` which the driver reuses, but MySQL/SQLite use
    // positional `?` so each occurrence must be a distinct bind.
    // Emitting 5 distinct placeholders + binding 5 values is portable
    // across all three.
    let p_uid_a = dialect.placeholder(1);
    let p_uid_b = dialect.placeholder(2);
    let p_cn_a = dialect.placeholder(3);
    let p_uid_c = dialect.placeholder(4);
    let p_cn_b = dialect.placeholder(5);
    let true_lit = dialect.bool_literal(true);
    let false_lit = dialect.bool_literal(false);
    let sql = format!(
        "SELECT \
            COALESCE((SELECT is_superuser FROM {users_t} \
                      WHERE id = {p_uid_a} AND active = {true_lit}), {false_lit}) AS is_super, \
            (SELECT granted FROM {user_perms_t} \
                WHERE user_id = {p_uid_b} AND codename = {p_cn_a}) AS explicit_grant, \
            EXISTS(SELECT 1 FROM {user_roles_t} ur \
                   JOIN {role_perms_t} rp ON rp.role_id = ur.role_id \
                   WHERE ur.user_id = {p_uid_c} AND rp.codename = {p_cn_b}) AS via_role"
    );
    let (is_super, explicit_grant, via_role) = match pool {
        #[cfg(feature = "postgres")]
        crate::sql::Pool::Postgres(pg) => {
            let row = sqlx::query(&sql)
                .bind(uid)
                .bind(uid)
                .bind(codename)
                .bind(uid)
                .bind(codename)
                .fetch_one(pg)
                .await?;
            (
                row.try_get::<bool, _>("is_super").unwrap_or(false),
                row.try_get::<Option<bool>, _>("explicit_grant")
                    .unwrap_or(None),
                row.try_get::<bool, _>("via_role").unwrap_or(false),
            )
        }
        #[cfg(feature = "mysql")]
        crate::sql::Pool::Mysql(my) => {
            let row = sqlx::query(&sql)
                .bind(uid)
                .bind(uid)
                .bind(codename)
                .bind(uid)
                .bind(codename)
                .fetch_one(my)
                .await?;
            // MySQL's EXISTS returns 0/1 as i64, BOOLEAN is TINYINT(1).
            let is_super: i64 = row.try_get("is_super").unwrap_or(0);
            let explicit: Option<i64> = row.try_get("explicit_grant").unwrap_or(None);
            let via_role: i64 = row.try_get("via_role").unwrap_or(0);
            (is_super != 0, explicit.map(|v| v != 0), via_role != 0)
        }
        #[cfg(feature = "sqlite")]
        crate::sql::Pool::Sqlite(sq) => {
            let row = sqlx::query(&sql)
                .bind(uid)
                .bind(uid)
                .bind(codename)
                .bind(uid)
                .bind(codename)
                .fetch_one(sq)
                .await?;
            // SQLite bools come back as i64; explicit_grant nullable.
            let is_super: i64 = row.try_get("is_super").unwrap_or(0);
            let explicit: Option<i64> = row.try_get("explicit_grant").unwrap_or(None);
            let via_role: i64 = row.try_get("via_role").unwrap_or(0);
            (is_super != 0, explicit.map(|v| v != 0), via_role != 0)
        }
    };
    if is_super {
        return Ok(true);
    }
    if let Some(granted) = explicit_grant {
        return Ok(granted);
    }
    Ok(via_role)
}

/// Like [`has_perm`] but accepts any sqlx executor. The
/// [`crate::viewset::ViewSet::tenant_router`] path uses this with the
/// per-request `&mut PgConnection` from
/// [`crate::extractors::Tenant::conn`] — `&PgPool` isn't usable in
/// schema-mode tenancy because each query needs `SET search_path`
/// against the same connection that issued it.
///
/// # Errors
/// As [`has_perm`].
#[cfg(feature = "postgres")]
pub async fn has_perm_on<'c, E>(uid: i64, codename: &str, executor: E) -> Result<bool, sqlx::Error>
where
    E: sqlx::Executor<'c, Database = sqlx::Postgres>,
{
    let row = sqlx::query(
        r#"
        WITH user_info AS (
            SELECT is_superuser
            FROM   "rustango_users"
            WHERE  id = $1 AND active = TRUE
        ),
        explicit AS (
            SELECT granted
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND codename = $2
        ),
        via_role AS (
            SELECT 1
            FROM   "rustango_user_roles" ur
            JOIN   "rustango_role_permissions" rp
                   ON rp.role_id = ur.role_id
            WHERE  ur.user_id = $1 AND rp.codename = $2
            LIMIT  1
        )
        SELECT
            COALESCE((SELECT is_superuser FROM user_info), FALSE) AS is_super,
            (SELECT granted FROM explicit)                         AS explicit_grant,
            EXISTS(SELECT 1 FROM via_role)                         AS via_role
        "#,
    )
    .bind(uid)
    .bind(codename)
    .fetch_one(executor)
    .await?;

    let is_super: bool = row.try_get("is_super").unwrap_or(false);
    if is_super {
        return Ok(true);
    }
    let explicit: Option<bool> = row.try_get("explicit_grant").unwrap_or(None);
    if let Some(granted) = explicit {
        return Ok(granted);
    }
    Ok(row.try_get("via_role").unwrap_or(false))
}

/// Check whether user `uid` holds ANY of the given `codenames`.
///
/// Single round-trip — resolves superuser, explicit denials, explicit
/// grants, and role-based grants in one CTE for the full array.
#[cfg(feature = "postgres")]
pub async fn has_any_perm(
    uid: i64,
    codenames: &[&str],
    pool: &PgPool,
) -> Result<bool, sqlx::Error> {
    if codenames.is_empty() {
        return Ok(false);
    }
    let names: Vec<&str> = codenames.to_vec();
    let row = sqlx::query(
        r#"
        WITH user_info AS (
            SELECT is_superuser
            FROM   "rustango_users"
            WHERE  id = $1 AND active = TRUE
        ),
        denied AS (
            SELECT codename
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND granted = FALSE AND codename = ANY($2::text[])
        ),
        via_role AS (
            SELECT 1
            FROM   "rustango_user_roles" ur
            JOIN   "rustango_role_permissions" rp ON rp.role_id = ur.role_id
            WHERE  ur.user_id = $1
              AND  rp.codename = ANY($2::text[])
              AND  rp.codename NOT IN (SELECT codename FROM denied)
            LIMIT  1
        ),
        explicit_grant AS (
            SELECT 1
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND granted = TRUE
              AND  codename = ANY($2::text[])
              AND  codename NOT IN (SELECT codename FROM denied)
            LIMIT  1
        )
        SELECT
            COALESCE((SELECT is_superuser FROM user_info), FALSE)                            AS is_super,
            EXISTS(SELECT 1 FROM via_role) OR EXISTS(SELECT 1 FROM explicit_grant) AS has_any
        "#,
    )
    .bind(uid)
    .bind(names)
    .fetch_one(pool)
    .await?;

    let is_super: bool = row.try_get("is_super").unwrap_or(false);
    if is_super {
        return Ok(true);
    }
    Ok(row.try_get("has_any").unwrap_or(false))
}

/// Check whether user `uid` holds ALL of the given `codenames`.
///
/// Single round-trip — counts effective grants (after applying denials)
/// and compares against the full codename list.
#[cfg(feature = "postgres")]
pub async fn has_all_perms(
    uid: i64,
    codenames: &[&str],
    pool: &PgPool,
) -> Result<bool, sqlx::Error> {
    if codenames.is_empty() {
        return Ok(true);
    }
    let names: Vec<&str> = codenames.to_vec();
    let expected = codenames.len() as i64;
    let row = sqlx::query(
        r#"
        WITH user_info AS (
            SELECT is_superuser
            FROM   "rustango_users"
            WHERE  id = $1 AND active = TRUE
        ),
        denied AS (
            SELECT codename
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND granted = FALSE AND codename = ANY($2::text[])
        ),
        effective AS (
            SELECT rp.codename
            FROM   "rustango_user_roles" ur
            JOIN   "rustango_role_permissions" rp ON rp.role_id = ur.role_id
            WHERE  ur.user_id = $1
              AND  rp.codename = ANY($2::text[])
              AND  rp.codename NOT IN (SELECT codename FROM denied)

            UNION

            SELECT codename
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND granted = TRUE
              AND  codename = ANY($2::text[])
              AND  codename NOT IN (SELECT codename FROM denied)
        )
        SELECT
            COALESCE((SELECT is_superuser FROM user_info), FALSE) AS is_super,
            COUNT(DISTINCT codename)                               AS matched
        FROM effective
        "#,
    )
    .bind(uid)
    .bind(names)
    .fetch_one(pool)
    .await?;

    let is_super: bool = row.try_get("is_super").unwrap_or(false);
    if is_super {
        return Ok(true);
    }
    let matched: i64 = row.try_get("matched").unwrap_or(0);
    Ok(matched == expected)
}

// ------------------------------------------------------------------ Role management (ORM-backed)

/// Create a role. Errors if name already exists.
#[cfg(feature = "postgres")]
pub async fn create_role(
    name: &str,
    description: &str,
    pool: &PgPool,
) -> Result<i64, TenancyError> {
    let mut role = Role {
        id: Auto::default(),
        name: name.to_owned(),
        description: description.to_owned(),
        data: serde_json::Value::Object(serde_json::Map::new()),
    };
    role.save_on(pool).await?;
    Ok(role.id.get().copied().unwrap_or(0))
}

/// v0.38 — tri-dialect counterpart of [`create_role`].
///
/// # Errors
/// As [`create_role`].
pub async fn create_role_pool(
    name: &str,
    description: &str,
    pool: &crate::sql::Pool,
) -> Result<i64, TenancyError> {
    let mut role = Role {
        id: Auto::default(),
        name: name.to_owned(),
        description: description.to_owned(),
        data: serde_json::Value::Object(serde_json::Map::new()),
    };
    role.save_pool(pool).await?;
    Ok(role.id.get().copied().unwrap_or(0))
}

/// v0.38 — tri-dialect counterpart of [`get_or_create_role`]. Two
/// round-trips on a fresh insert (SELECT-by-name, then INSERT on miss)
/// vs. the single-CTE PG variant; the bound surface is small and
/// idempotency is preserved by the unique constraint on `name`.
///
/// # Errors
/// As [`get_or_create_role`].
pub async fn get_or_create_role_pool(
    name: &str,
    description: &str,
    pool: &crate::sql::Pool,
) -> Result<i64, TenancyError> {
    use crate::core::Column as _;
    use crate::sql::FetcherPool as _;
    let existing: Vec<Role> = Role::objects()
        .where_(Role::name.eq(name.to_owned()))
        .limit(1)
        .fetch_pool(pool)
        .await?;
    if let Some(r) = existing.into_iter().next() {
        return Ok(r.id.get().copied().unwrap_or(0));
    }
    create_role_pool(name, description, pool).await
}

/// v0.38 — tri-dialect counterpart of [`has_any_perm`]. Issues one
/// `has_perm_pool` per codename and short-circuits on the first hit.
/// PG keeps the single-CTE [`has_any_perm`] for hot paths; the
/// loop-per-codename path is fine for sqlite/mysql given the typical
/// codename-list size (≤ a handful).
///
/// # Errors
/// As [`has_perm_pool`].
pub async fn has_any_perm_pool(
    uid: i64,
    codenames: &[&str],
    pool: &crate::sql::Pool,
) -> Result<bool, TenancyError> {
    for c in codenames {
        if has_perm_pool(uid, c, pool).await? {
            return Ok(true);
        }
    }
    Ok(false)
}

/// v0.38 — tri-dialect counterpart of [`has_all_perms`]. Issues one
/// `has_perm_pool` per codename and short-circuits on the first miss.
///
/// # Errors
/// As [`has_perm_pool`].
pub async fn has_all_perms_pool(
    uid: i64,
    codenames: &[&str],
    pool: &crate::sql::Pool,
) -> Result<bool, TenancyError> {
    for c in codenames {
        if !has_perm_pool(uid, c, pool).await? {
            return Ok(false);
        }
    }
    Ok(true)
}

/// v0.38 — tri-dialect counterpart of [`user_roles`]. Reuses
/// [`user_roles_qs_pool`] and projects to `(id, name)` pairs.
///
/// # Errors
/// As [`user_roles_qs_pool`].
pub async fn user_roles_pool(
    uid: i64,
    pool: &crate::sql::Pool,
) -> Result<Vec<(i64, String)>, TenancyError> {
    let roles = user_roles_qs_pool(uid, pool).await?;
    Ok(roles
        .into_iter()
        .map(|r| (r.id.get().copied().unwrap_or(0), r.name))
        .collect())
}

/// Get an existing role by name or create one. Returns the id.
#[cfg(feature = "postgres")]
pub async fn get_or_create_role(
    name: &str,
    description: &str,
    pool: &PgPool,
) -> Result<i64, TenancyError> {
    // Single round-trip: insert if absent, then union-select the id.
    let row = sqlx::query(
        r#"
        WITH ins AS (
            INSERT INTO "rustango_roles" (name, description, data)
            VALUES ($1, $2, '{}')
            ON CONFLICT (name) DO NOTHING
            RETURNING id
        )
        SELECT id FROM ins
        UNION ALL
        SELECT id FROM "rustango_roles" WHERE name = $1
        LIMIT 1
        "#,
    )
    .bind(name)
    .bind(description)
    .fetch_one(pool)
    .await?;
    Ok(row.try_get::<i64, _>("id").unwrap_or(0))
}

/// Grant a codename to a role. No-op if already granted.
///
/// Routed through the ORM's [`InsertQuery`] IR with
/// [`ConflictClause::DoNothing`] — the writer emits `INSERT … ON
/// CONFLICT DO NOTHING`, which matches the `(role_id, codename)`
/// unique constraint declared in [`ENSURE_SQL`].
#[cfg(feature = "postgres")]
pub async fn grant_role_perm(
    role_id: i64,
    codename: &str,
    pool: &PgPool,
) -> Result<(), TenancyError> {
    let query = InsertQuery {
        model: RolePermission::SCHEMA,
        columns: vec!["role_id", "codename"],
        values: vec![SqlValue::from(role_id), SqlValue::from(codename.to_owned())],
        returning: vec![],
        on_conflict: Some(ConflictClause::DoNothing),
    };
    crate::sql::insert(pool, &query).await?;
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`grant_role_perm`].
///
/// # Errors
/// As [`grant_role_perm`].
pub async fn grant_role_perm_pool(
    role_id: i64,
    codename: &str,
    pool: &crate::sql::Pool,
) -> Result<(), TenancyError> {
    let query = InsertQuery {
        model: RolePermission::SCHEMA,
        columns: vec!["role_id", "codename"],
        values: vec![SqlValue::from(role_id), SqlValue::from(codename.to_owned())],
        returning: vec![],
        on_conflict: Some(ConflictClause::DoNothing),
    };
    crate::sql::insert_pool(pool, &query).await?;
    Ok(())
}

/// Revoke a codename from a role.
#[cfg(feature = "postgres")]
pub async fn revoke_role_perm(
    role_id: i64,
    codename: &str,
    pool: &PgPool,
) -> Result<(), TenancyError> {
    crate::sql::delete(
        pool,
        &DeleteQuery {
            model: RolePermission::SCHEMA,
            where_clause: WhereExpr::and_predicates(vec![
                Filter {
                    column: "role_id",
                    op: Op::Eq,
                    value: SqlValue::from(role_id),
                },
                Filter {
                    column: "codename",
                    op: Op::Eq,
                    value: SqlValue::from(codename),
                },
            ]),
        },
    )
    .await?;
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`revoke_role_perm`].
///
/// # Errors
/// As [`revoke_role_perm`].
pub async fn revoke_role_perm_pool(
    role_id: i64,
    codename: &str,
    pool: &crate::sql::Pool,
) -> Result<(), TenancyError> {
    crate::sql::delete_pool(
        pool,
        &DeleteQuery {
            model: RolePermission::SCHEMA,
            where_clause: WhereExpr::and_predicates(vec![
                Filter {
                    column: "role_id",
                    op: Op::Eq,
                    value: SqlValue::from(role_id),
                },
                Filter {
                    column: "codename",
                    op: Op::Eq,
                    value: SqlValue::from(codename),
                },
            ]),
        },
    )
    .await?;
    Ok(())
}

/// Assign a user to a role. No-op if already assigned.
///
/// Same IR-routed pattern as [`grant_role_perm`].
#[cfg(feature = "postgres")]
pub async fn assign_role(user_id: i64, role_id: i64, pool: &PgPool) -> Result<(), TenancyError> {
    let query = InsertQuery {
        model: UserRole::SCHEMA,
        columns: vec!["user_id", "role_id"],
        values: vec![SqlValue::from(user_id), SqlValue::from(role_id)],
        returning: vec![],
        on_conflict: Some(ConflictClause::DoNothing),
    };
    crate::sql::insert(pool, &query).await?;
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`assign_role`].
pub async fn assign_role_pool(
    user_id: i64,
    role_id: i64,
    pool: &crate::sql::Pool,
) -> Result<(), TenancyError> {
    let query = InsertQuery {
        model: UserRole::SCHEMA,
        columns: vec!["user_id", "role_id"],
        values: vec![SqlValue::from(user_id), SqlValue::from(role_id)],
        returning: vec![],
        on_conflict: Some(ConflictClause::DoNothing),
    };
    crate::sql::insert_pool(pool, &query).await?;
    Ok(())
}

/// Remove a user from a role.
#[cfg(feature = "postgres")]
pub async fn remove_role(user_id: i64, role_id: i64, pool: &PgPool) -> Result<(), TenancyError> {
    crate::sql::delete(
        pool,
        &DeleteQuery {
            model: UserRole::SCHEMA,
            where_clause: WhereExpr::and_predicates(vec![
                Filter {
                    column: "user_id",
                    op: Op::Eq,
                    value: SqlValue::from(user_id),
                },
                Filter {
                    column: "role_id",
                    op: Op::Eq,
                    value: SqlValue::from(role_id),
                },
            ]),
        },
    )
    .await?;
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`remove_role`].
pub async fn remove_role_pool(
    user_id: i64,
    role_id: i64,
    pool: &crate::sql::Pool,
) -> Result<(), TenancyError> {
    crate::sql::delete_pool(
        pool,
        &DeleteQuery {
            model: UserRole::SCHEMA,
            where_clause: WhereExpr::and_predicates(vec![
                Filter {
                    column: "user_id",
                    op: Op::Eq,
                    value: SqlValue::from(user_id),
                },
                Filter {
                    column: "role_id",
                    op: Op::Eq,
                    value: SqlValue::from(role_id),
                },
            ]),
        },
    )
    .await?;
    Ok(())
}

/// Set a per-user permission override. Updates `granted` if a row already exists.
///
/// Routed through the ORM's [`InsertQuery`] IR with
/// [`ConflictClause::DoUpdate`] — the writer emits `INSERT … ON
/// CONFLICT (user_id, codename) DO UPDATE SET granted = EXCLUDED.granted`,
/// matching the composite unique constraint in [`ENSURE_SQL`]. `data`
/// is omitted from `update_columns` so the existing JSONB context
/// (reason / granted-by / etc.) survives a re-grant.
#[cfg(feature = "postgres")]
pub async fn set_user_perm(
    user_id: i64,
    codename: &str,
    granted: bool,
    pool: &PgPool,
) -> Result<(), TenancyError> {
    let query = InsertQuery {
        model: UserPermission::SCHEMA,
        columns: vec!["user_id", "codename", "granted", "data"],
        values: vec![
            SqlValue::from(user_id),
            SqlValue::from(codename.to_owned()),
            SqlValue::from(granted),
            SqlValue::Json(serde_json::json!({})),
        ],
        returning: vec![],
        on_conflict: Some(ConflictClause::DoUpdate {
            target: vec!["user_id", "codename"],
            update_columns: vec!["granted"],
        }),
    };
    crate::sql::insert(pool, &query).await?;
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`set_user_perm`].
pub async fn set_user_perm_pool(
    user_id: i64,
    codename: &str,
    granted: bool,
    pool: &crate::sql::Pool,
) -> Result<(), TenancyError> {
    let query = InsertQuery {
        model: UserPermission::SCHEMA,
        columns: vec!["user_id", "codename", "granted", "data"],
        values: vec![
            SqlValue::from(user_id),
            SqlValue::from(codename.to_owned()),
            SqlValue::from(granted),
            SqlValue::Json(serde_json::json!({})),
        ],
        returning: vec![],
        on_conflict: Some(ConflictClause::DoUpdate {
            target: vec!["user_id", "codename"],
            update_columns: vec!["granted"],
        }),
    };
    crate::sql::insert_pool(pool, &query).await?;
    Ok(())
}

/// Remove a per-user override, restoring role-based resolution.
#[cfg(feature = "postgres")]
pub async fn clear_user_perm(
    user_id: i64,
    codename: &str,
    pool: &PgPool,
) -> Result<(), TenancyError> {
    crate::sql::delete(
        pool,
        &DeleteQuery {
            model: UserPermission::SCHEMA,
            where_clause: WhereExpr::and_predicates(vec![
                Filter {
                    column: "user_id",
                    op: Op::Eq,
                    value: SqlValue::from(user_id),
                },
                Filter {
                    column: "codename",
                    op: Op::Eq,
                    value: SqlValue::from(codename),
                },
            ]),
        },
    )
    .await?;
    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`clear_user_perm`].
pub async fn clear_user_perm_pool(
    user_id: i64,
    codename: &str,
    pool: &crate::sql::Pool,
) -> Result<(), TenancyError> {
    crate::sql::delete_pool(
        pool,
        &DeleteQuery {
            model: UserPermission::SCHEMA,
            where_clause: WhereExpr::and_predicates(vec![
                Filter {
                    column: "user_id",
                    op: Op::Eq,
                    value: SqlValue::from(user_id),
                },
                Filter {
                    column: "codename",
                    op: Op::Eq,
                    value: SqlValue::from(codename),
                },
            ]),
        },
    )
    .await?;
    Ok(())
}

/// v0.37 — tri-dialect counterpart of [`user_roles_qs`]. SQL is
/// rendered via the dialect's emitter so identifier quoting +
/// placeholder syntax come out right per backend.
///
/// # Errors
/// Driver / SQL failures from the JOIN-SELECT.
pub async fn user_roles_qs_pool(
    user_id: i64,
    pool: &crate::sql::Pool,
) -> Result<Vec<Role>, sqlx::Error> {
    use sqlx::Row as _;
    let dialect = pool.dialect();
    let roles_t = dialect.quote_ident("rustango_roles");
    let user_roles_t = dialect.quote_ident("rustango_user_roles");
    let p1 = dialect.placeholder(1);
    // No table-aliasing — dialect emitters quote every identifier,
    // and the columns we need are unambiguous since `rustango_roles`
    // is the only side that has them.
    let sql = format!(
        "SELECT r.id, r.name, r.description, r.data \
         FROM {roles_t} r \
         JOIN {user_roles_t} ur ON ur.role_id = r.id \
         WHERE ur.user_id = {p1} \
         ORDER BY r.name"
    );
    let make_role = |id: i64, name: String, description: String, data: serde_json::Value| -> Role {
        Role {
            id: Auto::Set(id),
            name,
            description,
            data,
        }
    };
    match pool {
        #[cfg(feature = "postgres")]
        crate::sql::Pool::Postgres(pg) => {
            let rows = sqlx::query(&sql).bind(user_id).fetch_all(pg).await?;
            rows.iter()
                .map(|row| {
                    Ok(make_role(
                        row.try_get::<i64, _>("id")?,
                        row.try_get("name")?,
                        row.try_get("description")?,
                        row.try_get::<serde_json::Value, _>("data")
                            .unwrap_or_else(|_| serde_json::json!({})),
                    ))
                })
                .collect()
        }
        #[cfg(feature = "mysql")]
        crate::sql::Pool::Mysql(my) => {
            let rows = sqlx::query(&sql).bind(user_id).fetch_all(my).await?;
            rows.iter()
                .map(|row| {
                    let data: serde_json::Value = row
                        .try_get::<sqlx::types::Json<serde_json::Value>, _>("data")
                        .map(|j| j.0)
                        .unwrap_or_else(|_| serde_json::json!({}));
                    Ok(make_role(
                        row.try_get::<i64, _>("id")?,
                        row.try_get("name")?,
                        row.try_get("description")?,
                        data,
                    ))
                })
                .collect()
        }
        #[cfg(feature = "sqlite")]
        crate::sql::Pool::Sqlite(sq) => {
            let rows = sqlx::query(&sql).bind(user_id).fetch_all(sq).await?;
            rows.iter()
                .map(|row| {
                    let data: serde_json::Value = row
                        .try_get::<Option<String>, _>("data")
                        .ok()
                        .flatten()
                        .and_then(|s| serde_json::from_str(&s).ok())
                        .unwrap_or_else(|| serde_json::json!({}));
                    Ok(make_role(
                        row.try_get::<i64, _>("id")?,
                        row.try_get("name")?,
                        row.try_get("description")?,
                        data,
                    ))
                })
                .collect()
        }
    }
}

/// v0.37 — tri-dialect counterpart of [`user_permissions`]. The CTE
/// + UNION ALL shape is supported on PG, MySQL 8+ and SQLite 3.8+,
/// so the query template is the same across backends — only quoting
/// (`"…"` vs `` `…` ``) and placeholder syntax (`$1` vs `?`) differ,
/// and the dialect emitter handles both.
///
/// # Errors
/// Driver / SQL failures from the CTE SELECT.
pub async fn user_permissions_pool(
    uid: i64,
    pool: &crate::sql::Pool,
) -> Result<Vec<String>, TenancyError> {
    use sqlx::Row as _;
    let dialect = pool.dialect();
    let user_perms_t = dialect.quote_ident("rustango_user_permissions");
    let user_roles_t = dialect.quote_ident("rustango_user_roles");
    let role_perms_t = dialect.quote_ident("rustango_role_permissions");
    let p1 = dialect.placeholder(1);
    let p2 = dialect.placeholder(2);
    let p3 = dialect.placeholder(3);
    let true_lit = dialect.bool_literal(true);
    let false_lit = dialect.bool_literal(false);
    let sql = format!(
        "WITH denied AS ( \
            SELECT codename FROM {user_perms_t} \
            WHERE user_id = {p1} AND granted = {false_lit} \
         ) \
         SELECT DISTINCT codename FROM ( \
            SELECT rp.codename \
            FROM {user_roles_t} ur \
            JOIN {role_perms_t} rp ON rp.role_id = ur.role_id \
            WHERE ur.user_id = {p2} \
              AND rp.codename NOT IN (SELECT codename FROM denied) \
            UNION ALL \
            SELECT codename FROM {user_perms_t} \
            WHERE user_id = {p3} AND granted = {true_lit} \
              AND codename NOT IN (SELECT codename FROM denied) \
         ) effective \
         ORDER BY codename"
    );
    match pool {
        #[cfg(feature = "postgres")]
        crate::sql::Pool::Postgres(pg) => {
            let rows = sqlx::query(&sql)
                .bind(uid)
                .bind(uid)
                .bind(uid)
                .fetch_all(pg)
                .await?;
            Ok(rows
                .iter()
                .map(|r| r.try_get::<String, _>("codename").unwrap_or_default())
                .collect())
        }
        #[cfg(feature = "mysql")]
        crate::sql::Pool::Mysql(my) => {
            let rows = sqlx::query(&sql)
                .bind(uid)
                .bind(uid)
                .bind(uid)
                .fetch_all(my)
                .await?;
            Ok(rows
                .iter()
                .map(|r| r.try_get::<String, _>("codename").unwrap_or_default())
                .collect())
        }
        #[cfg(feature = "sqlite")]
        crate::sql::Pool::Sqlite(sq) => {
            let rows = sqlx::query(&sql)
                .bind(uid)
                .bind(uid)
                .bind(uid)
                .fetch_all(sq)
                .await?;
            Ok(rows
                .iter()
                .map(|r| r.try_get::<String, _>("codename").unwrap_or_default())
                .collect())
        }
    }
}

/// List all roles a user belongs to.
#[cfg(feature = "postgres")]
pub async fn user_roles_qs(user_id: i64, pool: &PgPool) -> Result<Vec<Role>, sqlx::Error> {
    let rows = sqlx::query(
        r#"SELECT r.id, r.name, r.description
           FROM   "rustango_roles" r
           JOIN   "rustango_user_roles" ur ON ur.role_id = r.id
           WHERE  ur.user_id = $1
           ORDER  BY r.name"#,
    )
    .bind(user_id)
    .fetch_all(pool)
    .await?;
    rows.iter()
        .map(|row| {
            Ok(Role {
                id: Auto::Set(row.try_get::<i64, _>("id")?),
                name: row.try_get("name")?,
                description: row.try_get("description")?,
                data: row
                    .try_get::<serde_json::Value, _>("data")
                    .unwrap_or_else(|_| serde_json::json!({})),
            })
        })
        .collect()
}

/// List all `(role_id, name)` pairs for a user.
#[cfg(feature = "postgres")]
pub async fn user_roles(uid: i64, pool: &PgPool) -> Result<Vec<(i64, String)>, sqlx::Error> {
    let roles = user_roles_qs(uid, pool).await?; // raw SQL join — stays sqlx::Error
    Ok(roles
        .into_iter()
        .map(|r| (r.id.get().copied().unwrap_or(0), r.name))
        .collect())
}

/// List all codenames a user has access to (union of role + direct grants,
/// minus explicit denials). Superuser implicit grants are NOT included —
/// callers that need to handle superusers should check `is_superuser` first.
///
/// Denial priority matches [`has_perm`]: an explicit `granted = false` row
/// removes the codename even if a role would otherwise grant it.
#[cfg(feature = "postgres")]
pub async fn user_permissions(uid: i64, pool: &PgPool) -> Result<Vec<String>, TenancyError> {
    let rows = sqlx::query(
        r#"
        WITH denied AS (
            SELECT codename
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND granted = FALSE
        )
        SELECT DISTINCT codename
        FROM (
            SELECT rp.codename
            FROM   "rustango_user_roles" ur
            JOIN   "rustango_role_permissions" rp ON rp.role_id = ur.role_id
            WHERE  ur.user_id = $1
              AND  rp.codename NOT IN (SELECT codename FROM denied)

            UNION ALL

            SELECT codename
            FROM   "rustango_user_permissions"
            WHERE  user_id = $1 AND granted = TRUE
              AND  codename NOT IN (SELECT codename FROM denied)
        ) effective
        ORDER BY codename
        "#,
    )
    .bind(uid)
    .fetch_all(pool)
    .await?;
    Ok(rows
        .iter()
        .map(|r| r.try_get::<String, _>("codename").unwrap_or_default())
        .collect())
}

// ------------------------------------------------------------------ Codename helpers

/// Standard four codenames for a model table (`add`, `change`, `delete`, `view`).
#[must_use]
pub fn model_codenames(table: &str) -> [String; 4] {
    [
        format!("{table}.add"),
        format!("{table}.change"),
        format!("{table}.delete"),
        format!("{table}.view"),
    ]
}

/// Seed the `rustango_permissions` catalog with the four standard CRUD
/// codenames for every model that carries `#[rustango(permissions)]`.
///
/// Idempotent — uses `ON CONFLICT DO NOTHING`. Call once at startup after
/// [`ensure_tables`] so the catalog reflects the current model set.
///
/// # Errors
/// Driver / SQL failures.
#[cfg(feature = "postgres")]
pub async fn auto_create_permissions(pool: &PgPool) -> Result<(), sqlx::Error> {
    use crate::core::{inventory, ModelEntry};

    let action_names = [
        ("add", "Can add"),
        ("change", "Can change"),
        ("delete", "Can delete"),
        ("view", "Can view"),
    ];

    let mut tables: Vec<&str> = Vec::new();
    let mut codenames: Vec<String> = Vec::new();
    let mut names: Vec<String> = Vec::new();

    for entry in inventory::iter::<ModelEntry> {
        if !entry.schema.permissions {
            continue;
        }
        let table = entry.schema.table;
        let model_name = entry.schema.name;
        for (action, verb) in &action_names {
            tables.push(table);
            codenames.push(format!("{table}.{action}"));
            names.push(format!("{verb} {model_name}"));
        }
    }

    if tables.is_empty() {
        return Ok(());
    }

    sqlx::query(
        r#"INSERT INTO "rustango_permissions" (table_name, codename, name)
           SELECT * FROM UNNEST($1::text[], $2::text[], $3::text[])
           ON CONFLICT (table_name, codename) DO NOTHING"#,
    )
    .bind(&tables)
    .bind(&codenames)
    .bind(&names)
    .execute(pool)
    .await?;

    Ok(())
}

/// v0.38 — tri-dialect counterpart of [`auto_create_permissions`].
///
/// Unlike [`ensure_tables`], this is *not* redundant with the
/// bootstrap migration: the migration creates the `rustango_permissions`
/// table but cannot know which models the binary has compiled in.
/// This walks the runtime `inventory::<ModelEntry>` and seeds one row
/// per `(model_table, action)` for every model carrying
/// `#[rustango(permissions)]`. Idempotent via `ON CONFLICT DO NOTHING`
/// (supported on PG, SQLite ≥ 3.24, MySQL via the IGNORE-style
/// `INSERT ... ON CONFLICT(...) DO NOTHING` which sqlx routes through
/// the `insert_pool` IR emitter).
///
/// PG path used a single `UNNEST($1::text[], $2::text[], $3::text[])`
/// to insert every row in one round-trip. SQLite + MySQL have no
/// `UNNEST` of parallel arrays, so the `_pool` variant builds one
/// `InsertQuery` per (table, action) and dispatches via `insert_pool`
/// — N round-trips for N codenames, where N ≤ `(model_count × 4)`.
/// Typical projects have <50 models, so this is <200 short
/// INSERTs at boot, well under a second.
///
/// # Errors
/// Driver / SQL failures from any of the per-row inserts.
pub async fn auto_create_permissions_pool(pool: &crate::sql::Pool) -> Result<(), TenancyError> {
    use crate::core::{inventory, ModelEntry};

    let action_names = [
        ("add", "Can add"),
        ("change", "Can change"),
        ("delete", "Can delete"),
        ("view", "Can view"),
    ];

    for entry in inventory::iter::<ModelEntry> {
        if !entry.schema.permissions {
            continue;
        }
        let table = entry.schema.table;
        let model_name = entry.schema.name;
        for (action, verb) in &action_names {
            // Hand-rolled `INSERT … ON CONFLICT (...) DO NOTHING`
            // via the dialect emitter — `rustango_permissions` isn't
            // a `#[derive(Model)]` so we can't go through the ORM
            // IR (`InsertQuery` needs a `&'static ModelSchema`).
            // Pattern mirrors `audit::audit_select_sql` from v0.37.
            let dialect = pool.dialect();
            let perm_t = dialect.quote_ident("rustango_permissions");
            let table_col = dialect.quote_ident("table_name");
            let codename_col = dialect.quote_ident("codename");
            let name_col = dialect.quote_ident("name");
            let p1 = dialect.placeholder(1);
            let p2 = dialect.placeholder(2);
            let p3 = dialect.placeholder(3);
            // `ON CONFLICT (col1, col2) DO NOTHING` is supported on
            // PG (always), SQLite (≥ 3.24), MySQL (8.0.19+ — older
            // MySQL would need `INSERT IGNORE` instead, but the
            // framework's minimum is MySQL 8). Same posture as
            // `audit::emit_one_pool` etc.
            let sql = format!(
                "INSERT INTO {perm_t} ({table_col}, {codename_col}, {name_col}) \
                 VALUES ({p1}, {p2}, {p3}) \
                 ON CONFLICT ({table_col}, {codename_col}) DO NOTHING"
            );
            let codename = format!("{table}.{action}");
            let display = format!("{verb} {model_name}");
            crate::sql::raw_execute_pool(
                pool,
                &sql,
                vec![
                    SqlValue::from(table.to_owned()),
                    SqlValue::from(codename),
                    SqlValue::from(display),
                ],
            )
            .await
            .map_err(|e| {
                TenancyError::Validation(format!(
                    "auto_create_permissions_pool: INSERT for `{table}.{action}` failed: {e}"
                ))
            })?;
        }
    }
    Ok(())
}

#[cfg(test)]
mod admin_config_tests {
    use super::*;
    use crate::core::Model;

    /// v0.28 — every model in this module participates in the auto-admin.
    /// Without admin config, list views render every column raw — usable
    /// but noisy. The configs below pick sensible `list_display` so
    /// operators see role/user IDs + codenames at a glance.
    #[test]
    fn perm_models_carry_admin_config() {
        for (label, schema) in [
            ("Role", Role::SCHEMA),
            ("RolePermission", RolePermission::SCHEMA),
            ("UserRole", UserRole::SCHEMA),
            ("UserPermission", UserPermission::SCHEMA),
        ] {
            assert!(schema.admin.is_some(), "expected admin config on {label}");
        }
    }

    #[test]
    fn perm_models_keep_tenant_scope() {
        // None of these are registry-scoped — they live in each
        // tenant's storage. The scope filter on the admin sidebar
        // must therefore include them when the admin is mounted in
        // tenant mode (which it is by default in `server::Builder`).
        for schema in [
            Role::SCHEMA,
            RolePermission::SCHEMA,
            UserRole::SCHEMA,
            UserPermission::SCHEMA,
        ] {
            assert_eq!(schema.scope, crate::core::ModelScope::Tenant);
        }
    }
}