diesel 2.4.0

A safe, extensible ORM and Query Builder for PostgreSQL, SQLite, and MySQL
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
//! Types for the SQLite authorizer callback.
//!
//! See [`sqlite3_set_authorizer`](https://sqlite.org/c3ref/set_authorizer.html)
//! and the [action code constants](https://sqlite.org/c3ref/c_alter_table.html).
//!
//! The authorizer callback receives an [`AuthorizerContext`]. It is an enum
//! with one variant per SQLite action code, and every variant carries the
//! arguments for that action under descriptive field names, so there is no
//! need to consult a table of what each positional argument means.
//!
//! Two fields recur across variants. `database` is the name of the database
//! (`"main"`, `"temp"`, or an `ATTACH` alias) an object lives in, when SQLite
//! reports it. `accessor` is the name of the inner-most trigger or view
//! responsible for the access, or `None` when the access is directly from
//! top-level SQL. A string argument is `None` when SQLite passes `NULL` or a
//! value that is not valid UTF-8.

#[cfg(not(all(target_family = "wasm", target_os = "unknown")))]
extern crate libsqlite3_sys as ffi;

#[cfg(all(target_family = "wasm", target_os = "unknown"))]
use sqlite_wasm_rs as ffi;

use super::SqliteConnection;

/// Authorizing a `CREATE INDEX` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateIndex<'a> {
    /// Name of the index being created.
    pub index: Option<&'a str>,
    /// Name of the table the index is created on.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateTable<'a> {
    /// Name of the table being created.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE TEMP INDEX` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateTempIndex<'a> {
    /// Name of the index being created.
    pub index: Option<&'a str>,
    /// Name of the table the index is created on.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE TEMP TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateTempTable<'a> {
    /// Name of the table being created.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE TEMP TRIGGER` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateTempTrigger<'a> {
    /// Name of the trigger being created.
    pub trigger: Option<&'a str>,
    /// Name of the table the trigger is attached to.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE TEMP VIEW` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateTempView<'a> {
    /// Name of the view being created.
    pub view: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE TRIGGER` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateTrigger<'a> {
    /// Name of the trigger being created.
    pub trigger: Option<&'a str>,
    /// Name of the table the trigger is attached to.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE VIEW` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateView<'a> {
    /// Name of the view being created.
    pub view: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DELETE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Delete<'a> {
    /// Name of the table rows are deleted from.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP INDEX` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropIndex<'a> {
    /// Name of the index being dropped.
    pub index: Option<&'a str>,
    /// Name of the table the index belongs to.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropTable<'a> {
    /// Name of the table being dropped.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP TEMP INDEX` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropTempIndex<'a> {
    /// Name of the index being dropped.
    pub index: Option<&'a str>,
    /// Name of the table the index belongs to.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP TEMP TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropTempTable<'a> {
    /// Name of the table being dropped.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP TEMP TRIGGER` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropTempTrigger<'a> {
    /// Name of the trigger being dropped.
    pub trigger: Option<&'a str>,
    /// Name of the table the trigger is attached to.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP TEMP VIEW` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropTempView<'a> {
    /// Name of the view being dropped.
    pub view: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP TRIGGER` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropTrigger<'a> {
    /// Name of the trigger being dropped.
    pub trigger: Option<&'a str>,
    /// Name of the table the trigger is attached to.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP VIEW` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropView<'a> {
    /// Name of the view being dropped.
    pub view: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing an `INSERT` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Insert<'a> {
    /// Name of the table rows are inserted into.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `PRAGMA` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Pragma<'a> {
    /// Name of the pragma.
    pub name: Option<&'a str>,
    /// Argument to the pragma, or `None` when it is queried without one.
    pub argument: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a column read.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Read<'a> {
    /// Name of the table being read.
    pub table: Option<&'a str>,
    /// Name of the column being read.
    pub column: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `SELECT` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Select<'a> {
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a transaction control operation (`BEGIN`, `COMMIT`, `ROLLBACK`).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Transaction<'a> {
    /// The operation, for example `"BEGIN"`, `"COMMIT"`, or `"ROLLBACK"`.
    pub operation: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing an `UPDATE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Update<'a> {
    /// Name of the table being updated.
    pub table: Option<&'a str>,
    /// Name of the column being updated.
    pub column: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing an `ATTACH DATABASE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Attach<'a> {
    /// Filename of the database being attached.
    pub filename: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DETACH DATABASE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Detach<'a> {
    /// Name of the database being detached.
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing an `ALTER TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct AlterTable<'a> {
    /// Database the table lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Name of the table being altered.
    pub table: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `REINDEX` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Reindex<'a> {
    /// Name of the index being rebuilt.
    pub index: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing an `ANALYZE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Analyze<'a> {
    /// Name of the table being analyzed.
    pub table: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `CREATE VIRTUAL TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CreateVTable<'a> {
    /// Name of the virtual table being created.
    pub table: Option<&'a str>,
    /// Name of the module implementing the virtual table.
    pub module: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `DROP VIRTUAL TABLE` statement.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct DropVTable<'a> {
    /// Name of the virtual table being dropped.
    pub table: Option<&'a str>,
    /// Name of the module implementing the virtual table.
    pub module: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a SQL function call.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Function<'a> {
    /// Name of the function being called.
    pub function: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a `SAVEPOINT` operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Savepoint<'a> {
    /// The operation, for example `"BEGIN"`, `"RELEASE"`, or `"ROLLBACK"`.
    pub operation: Option<&'a str>,
    /// Name of the savepoint.
    pub name: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Authorizing a recursive `SELECT`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Recursive<'a> {
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// An action code SQLite reported that this version of diesel does not model.
///
/// The raw arguments are exposed unchanged for forward compatibility.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Unknown<'a> {
    /// The raw SQLite action code.
    pub code: i32,
    /// The third argument to the authorizer callback, if any.
    pub arg1: Option<&'a str>,
    /// The fourth argument to the authorizer callback, if any.
    pub arg2: Option<&'a str>,
    /// Database the object lives in (`"main"`, `"temp"`, or an `ATTACH` alias).
    pub database: Option<&'a str>,
    /// Inner-most trigger or view responsible for the access, if any.
    pub accessor: Option<&'a str>,
}

/// Context information passed to the authorizer callback.
///
/// One variant per SQLite action code. Each variant carries the arguments for
/// that action under descriptive field names, so there is no need to consult a
/// table of what each positional argument means. The callback is invoked
/// during SQL statement compilation (not during execution).
///
/// Added in SQLite 3.0.0 (June 2004).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum AuthorizerContext<'a> {
    /// `CREATE INDEX`
    CreateIndex(CreateIndex<'a>),
    /// `CREATE TABLE`
    CreateTable(CreateTable<'a>),
    /// `CREATE TEMP INDEX`
    CreateTempIndex(CreateTempIndex<'a>),
    /// `CREATE TEMP TABLE`
    CreateTempTable(CreateTempTable<'a>),
    /// `CREATE TEMP TRIGGER`
    CreateTempTrigger(CreateTempTrigger<'a>),
    /// `CREATE TEMP VIEW`
    CreateTempView(CreateTempView<'a>),
    /// `CREATE TRIGGER`
    CreateTrigger(CreateTrigger<'a>),
    /// `CREATE VIEW`
    CreateView(CreateView<'a>),
    /// `DELETE`
    Delete(Delete<'a>),
    /// `DROP INDEX`
    DropIndex(DropIndex<'a>),
    /// `DROP TABLE`
    DropTable(DropTable<'a>),
    /// `DROP TEMP INDEX`
    DropTempIndex(DropTempIndex<'a>),
    /// `DROP TEMP TABLE`
    DropTempTable(DropTempTable<'a>),
    /// `DROP TEMP TRIGGER`
    DropTempTrigger(DropTempTrigger<'a>),
    /// `DROP TEMP VIEW`
    DropTempView(DropTempView<'a>),
    /// `DROP TRIGGER`
    DropTrigger(DropTrigger<'a>),
    /// `DROP VIEW`
    DropView(DropView<'a>),
    /// `INSERT`
    Insert(Insert<'a>),
    /// `PRAGMA`
    Pragma(Pragma<'a>),
    /// Reading a column value.
    Read(Read<'a>),
    /// `SELECT`
    Select(Select<'a>),
    /// Transaction control (`BEGIN`, `COMMIT`, `ROLLBACK`).
    Transaction(Transaction<'a>),
    /// `UPDATE`
    Update(Update<'a>),
    /// `ATTACH DATABASE`
    Attach(Attach<'a>),
    /// `DETACH DATABASE`
    Detach(Detach<'a>),
    /// `ALTER TABLE`
    AlterTable(AlterTable<'a>),
    /// `REINDEX`
    Reindex(Reindex<'a>),
    /// `ANALYZE`
    Analyze(Analyze<'a>),
    /// `CREATE VIRTUAL TABLE`
    CreateVTable(CreateVTable<'a>),
    /// `DROP VIRTUAL TABLE`
    DropVTable(DropVTable<'a>),
    /// A SQL function call.
    Function(Function<'a>),
    /// `SAVEPOINT`
    Savepoint(Savepoint<'a>),
    /// A recursive `SELECT`.
    Recursive(Recursive<'a>),
    /// An action code this version of diesel does not model.
    Unknown(Unknown<'a>),
}

impl<'a> AuthorizerContext<'a> {
    /// Returns `true` if this action modifies the database schema.
    ///
    /// Schema-modifying actions include creating, dropping, or altering
    /// tables, indexes, triggers, views, and virtual tables, writing to the
    /// schema table or `sqlite_dbpage`, and assigning the `writable_schema` or
    /// `schema_version` pragma. Writes to virtual-table shadow tables are not
    /// recognised, so use [`set_defensive`](SqliteConnection::set_defensive)
    /// to stop ordinary SQL from corrupting the schema.
    ///
    /// # Example
    ///
    /// ```rust
    /// # use diesel::prelude::*;
    /// use diesel::sqlite::{SqliteConnection, AuthorizerContext, AuthorizerDecision};
    ///
    /// # let conn = &mut SqliteConnection::establish(":memory:").unwrap();
    /// conn.on_authorize(|ctx| {
    ///     if ctx.is_schema_modifying() {
    ///         AuthorizerDecision::Deny
    ///     } else {
    ///         AuthorizerDecision::Allow
    ///     }
    /// });
    /// ```
    pub fn is_schema_modifying(&self) -> bool {
        matches!(
            self,
            Self::CreateIndex(_)
                | Self::CreateTable(_)
                | Self::CreateTempIndex(_)
                | Self::CreateTempTable(_)
                | Self::CreateTempTrigger(_)
                | Self::CreateTempView(_)
                | Self::CreateTrigger(_)
                | Self::CreateView(_)
                | Self::CreateVTable(_)
                | Self::DropIndex(_)
                | Self::DropTable(_)
                | Self::DropTempIndex(_)
                | Self::DropTempTable(_)
                | Self::DropTempTrigger(_)
                | Self::DropTempView(_)
                | Self::DropTrigger(_)
                | Self::DropView(_)
                | Self::DropVTable(_)
                | Self::AlterTable(_)
        ) || self.writes_schema_storage()
    }

    /// Returns `true` for a write to the schema table or `sqlite_dbpage`, or an assignment of `writable_schema` or `schema_version`.
    fn writes_schema_storage(&self) -> bool {
        const SCHEMA_TABLES: [&str; 5] = [
            "sqlite_schema",
            "sqlite_master",
            "sqlite_temp_schema",
            "sqlite_temp_master",
            "sqlite_dbpage",
        ];
        match self {
            Self::Insert(Insert { table, .. })
            | Self::Delete(Delete { table, .. })
            | Self::Update(Update { table, .. }) => table.is_some_and(|table| {
                SCHEMA_TABLES
                    .iter()
                    .any(|schema_table| table.eq_ignore_ascii_case(schema_table))
            }),
            Self::Pragma(Pragma {
                name: Some(name),
                argument: Some(_),
                ..
            }) => {
                name.eq_ignore_ascii_case("writable_schema")
                    || name.eq_ignore_ascii_case("schema_version")
            }
            _ => false,
        }
    }

    /// Builds the context from the raw authorizer callback arguments.
    ///
    /// `database` is the 5th callback argument (the database name) and
    /// `accessor` is the 6th (the trigger or view responsible). The `arg1` and
    /// `arg2` values are the 3rd and 4th arguments, whose meaning depends on
    /// the action code per the SQLite documentation.
    pub(crate) fn from_ffi(
        code: i32,
        arg1: Option<&'a str>,
        arg2: Option<&'a str>,
        database: Option<&'a str>,
        accessor: Option<&'a str>,
    ) -> Self {
        match code {
            ffi::SQLITE_CREATE_INDEX => Self::CreateIndex(CreateIndex {
                index: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_TABLE => Self::CreateTable(CreateTable {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_TEMP_INDEX => Self::CreateTempIndex(CreateTempIndex {
                index: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_TEMP_TABLE => Self::CreateTempTable(CreateTempTable {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_TEMP_TRIGGER => Self::CreateTempTrigger(CreateTempTrigger {
                trigger: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_TEMP_VIEW => Self::CreateTempView(CreateTempView {
                view: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_TRIGGER => Self::CreateTrigger(CreateTrigger {
                trigger: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_VIEW => Self::CreateView(CreateView {
                view: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_DELETE => Self::Delete(Delete {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_INDEX => Self::DropIndex(DropIndex {
                index: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_TABLE => Self::DropTable(DropTable {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_TEMP_INDEX => Self::DropTempIndex(DropTempIndex {
                index: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_TEMP_TABLE => Self::DropTempTable(DropTempTable {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_TEMP_TRIGGER => Self::DropTempTrigger(DropTempTrigger {
                trigger: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_TEMP_VIEW => Self::DropTempView(DropTempView {
                view: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_TRIGGER => Self::DropTrigger(DropTrigger {
                trigger: arg1,
                table: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_VIEW => Self::DropView(DropView {
                view: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_INSERT => Self::Insert(Insert {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_PRAGMA => Self::Pragma(Pragma {
                name: arg1,
                argument: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_READ => Self::Read(Read {
                table: arg1,
                column: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_SELECT => Self::Select(Select { accessor }),
            ffi::SQLITE_TRANSACTION => Self::Transaction(Transaction {
                operation: arg1,
                accessor,
            }),
            ffi::SQLITE_UPDATE => Self::Update(Update {
                table: arg1,
                column: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_ATTACH => Self::Attach(Attach {
                filename: arg1,
                accessor,
            }),
            ffi::SQLITE_DETACH => Self::Detach(Detach {
                database: arg1,
                accessor,
            }),
            ffi::SQLITE_ALTER_TABLE => Self::AlterTable(AlterTable {
                database: arg1,
                table: arg2,
                accessor,
            }),
            ffi::SQLITE_REINDEX => Self::Reindex(Reindex {
                index: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_ANALYZE => Self::Analyze(Analyze {
                table: arg1,
                database,
                accessor,
            }),
            ffi::SQLITE_CREATE_VTABLE => Self::CreateVTable(CreateVTable {
                table: arg1,
                module: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_DROP_VTABLE => Self::DropVTable(DropVTable {
                table: arg1,
                module: arg2,
                database,
                accessor,
            }),
            ffi::SQLITE_FUNCTION => Self::Function(Function {
                function: arg2,
                accessor,
            }),
            ffi::SQLITE_SAVEPOINT => Self::Savepoint(Savepoint {
                operation: arg1,
                name: arg2,
                accessor,
            }),
            ffi::SQLITE_RECURSIVE => Self::Recursive(Recursive { accessor }),
            other => Self::Unknown(Unknown {
                code: other,
                arg1,
                arg2,
                database,
                accessor,
            }),
        }
    }
}

/// Authorizer callback decision.
///
/// Returned by the authorizer callback to indicate whether to allow,
/// ignore, or deny the requested operation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AuthorizerDecision {
    /// Allow the operation to proceed (`SQLITE_OK`).
    Allow,
    /// Ignore the operation (`SQLITE_IGNORE`).
    ///
    /// For `Read` actions, returns `NULL` instead of the column value.
    /// For other actions, treats the operation as a no-op.
    Ignore,
    /// Deny the operation (`SQLITE_DENY`).
    ///
    /// Causes the entire SQL statement to fail with an authorization error.
    Deny,
}

impl AuthorizerDecision {
    /// Converts the decision to the FFI return code.
    pub(crate) fn to_ffi(self) -> i32 {
        match self {
            Self::Allow => ffi::SQLITE_OK,
            Self::Ignore => ffi::SQLITE_IGNORE,
            Self::Deny => ffi::SQLITE_DENY,
        }
    }
}

impl SqliteConnection {
    /// Registers an authorizer callback for SQL compilation access control.
    /// Added in SQLite 3.0.0 (June 2004).
    ///
    /// The callback is invoked during `sqlite3_prepare()` (statement
    /// compilation) to control access to database objects. It receives
    /// an [`AuthorizerContext`] describing the operation and returns an
    /// [`AuthorizerDecision`].
    ///
    /// The authorizer is consulted only at statement preparation, so treat it
    /// as defense-in-depth rather than a complete sandbox. SQLite re-checks
    /// already-prepared statements when an authorizer is installed. Removing the
    /// authorizer clears diesel's statement cache so statements prepared while
    /// it was active are re-prepared without it.
    ///
    /// The authorizer may be re-invoked during `sqlite3_step()` if a schema
    /// change triggers statement recompilation.
    ///
    /// The callback must not modify the database connection. It is invoked
    /// synchronously on the thread driving the connection, so it is never
    /// called concurrently.
    ///
    /// Only one authorizer can be active at a time per connection.
    /// Registering a new one replaces the previous. Panics in the callback
    /// abort the process.
    ///
    /// See: [`sqlite3_set_authorizer`](https://sqlite.org/c3ref/set_authorizer.html)
    ///
    /// # Example
    ///
    /// ```rust
    /// # use diesel::prelude::*;
    /// use diesel::sqlite::{SqliteConnection, AuthorizerContext, AuthorizerDecision};
    ///
    /// # let conn = &mut SqliteConnection::establish(":memory:").unwrap();
    /// conn.on_authorize(|ctx| match ctx {
    ///     AuthorizerContext::Delete(_) => AuthorizerDecision::Deny,
    ///     AuthorizerContext::DropTable(_) | AuthorizerContext::DropIndex(_) => {
    ///         AuthorizerDecision::Deny
    ///     }
    ///     _ => AuthorizerDecision::Allow,
    /// });
    ///
    /// // Later: remove the authorizer
    /// conn.remove_authorizer();
    /// ```
    pub fn on_authorize<F>(&mut self, hook: F)
    where
        F: FnMut(AuthorizerContext<'_>) -> AuthorizerDecision + Send + 'static,
    {
        // No cache clear is needed here. Installing a non-null authorizer makes
        // SQLite expire every prepared statement on the connection, and because
        // diesel prepares with `sqlite3_prepare_v3` those statements are
        // transparently re-prepared under the new authorizer on their next step.
        self.raw_connection.set_authorizer(hook);
        // The public documentation doesn't explicitly state what happens with existing
        // prepared statements, so rather be safe and nuke them. We don't
        // expect that people change the authorizer all the time, so this should be fine
        self.statement_cache.clear();
    }

    /// Removes the authorizer callback.
    ///
    /// See [`on_authorize`](Self::on_authorize) for usage example.
    pub fn remove_authorizer(&mut self) {
        self.raw_connection.remove_authorizer();
        // Removing an authorizer does not expire prepared statements: SQLite
        // expires them only when a non-null authorizer is installed. A statement
        // prepared while the authorizer was active can have its decisions
        // compiled in (an `Ignore` on a column read, for example, bakes a `NULL`
        // into the statement), and nothing invalidates that cached statement on
        // removal, so it keeps returning the old result. Clear the cache to force
        // the next query to re-prepare without the authorizer.
        self.statement_cache.clear();
    }
}

// miri doesn't support callbacks yet
#[cfg(all(test, not(miri)))]
mod tests {
    use super::*;
    use crate::connection::Connection;
    use crate::query_dsl::RunQueryDsl;
    use std::sync::Arc;
    use std::sync::atomic::{AtomicU32, Ordering};

    fn connection() -> SqliteConnection {
        SqliteConnection::establish(":memory:").unwrap()
    }

    #[diesel_test_helper::test]
    fn on_authorize_deny_rejects_statement() {
        let conn = &mut connection();
        crate::sql_query("CREATE TABLE auth_basic (id INTEGER PRIMARY KEY)")
            .execute(conn)
            .unwrap();

        let calls = Arc::new(AtomicU32::new(0));
        let calls2 = calls.clone();

        conn.on_authorize(move |_ctx| {
            calls2.fetch_add(1, Ordering::Relaxed);
            AuthorizerDecision::Deny
        });

        // The authorizer is consulted while the statement is prepared, denies
        // it, and the statement is rejected.
        let denied = crate::sql_query("SELECT id FROM auth_basic").execute(conn);
        assert!(denied.is_err(), "a denied statement should fail to prepare");
        assert!(
            calls.load(Ordering::Relaxed) > 0,
            "the authorizer callback should have been invoked"
        );

        // Removing the authorizer restores access.
        conn.remove_authorizer();
        crate::sql_query("SELECT id FROM auth_basic")
            .execute(conn)
            .unwrap();
    }

    #[diesel_test_helper::test]
    fn remove_authorizer_re_prepares_cached_statements() {
        use crate::prelude::*;
        use crate::sqlite::AuthorizerContext;

        crate::table! {
            auth_ignore_items (id) {
                id -> Integer,
            }
        }

        let conn = &mut connection();
        crate::sql_query("CREATE TABLE auth_ignore_items (id INTEGER PRIMARY KEY)")
            .execute(conn)
            .unwrap();
        crate::sql_query("INSERT INTO auth_ignore_items (id) VALUES (42)")
            .execute(conn)
            .unwrap();

        // An authorizer that ignores column reads. SQLite bakes a NULL
        // substitution for the column into the prepared (and cached) statement.
        // A typed query is used because raw `sql_query` is never cached.
        conn.on_authorize(|ctx| match ctx {
            AuthorizerContext::Read(_) => AuthorizerDecision::Ignore,
            _ => AuthorizerDecision::Allow,
        });
        let ignored = auth_ignore_items::table
            .select(auth_ignore_items::id.nullable())
            .load::<Option<i32>>(conn)
            .unwrap();
        assert_eq!(
            ignored,
            vec![None],
            "Ignore substitutes NULL for the column"
        );

        // SQLite does not expire prepared statements when an authorizer is
        // removed, so `remove_authorizer` clears diesel's statement cache to
        // force the cached statement (with its baked-in NULL) to be re-prepared.
        conn.remove_authorizer();
        let restored = auth_ignore_items::table
            .select(auth_ignore_items::id.nullable())
            .load::<Option<i32>>(conn)
            .unwrap();
        assert_eq!(
            restored,
            vec![Some(42)],
            "after removing the authorizer the real value is returned"
        );
    }

    #[diesel_test_helper::test]
    fn on_authorize_re_prepares_cached_statements() {
        use crate::prelude::*;
        use crate::sqlite::AuthorizerContext;

        crate::table! {
            auth_replace_items (id) {
                id -> Integer,
            }
        }

        let conn = &mut connection();
        crate::sql_query("CREATE TABLE auth_replace_items (id INTEGER PRIMARY KEY)")
            .execute(conn)
            .unwrap();
        crate::sql_query("INSERT INTO auth_replace_items (id) VALUES (42)")
            .execute(conn)
            .unwrap();

        // A first authorizer that allows everything. The typed query is
        // prepared and cached while it is active, returning the real value.
        conn.on_authorize(|_ctx| AuthorizerDecision::Allow);
        let allowed = auth_replace_items::table
            .select(auth_replace_items::id.nullable())
            .load::<Option<i32>>(conn)
            .unwrap();
        assert_eq!(
            allowed,
            vec![Some(42)],
            "the allow-all authorizer returns the real value"
        );

        // Installing the replacement authorizer expires the cached statement
        // (SQLite expires all prepared statements when a non-null authorizer is
        // set), so `sqlite3_prepare_v3` re-prepares it under the new authorizer
        // and it now yields NULL. This documents that no diesel-side cache clear
        // is required on the install path.
        conn.on_authorize(|ctx| match ctx {
            AuthorizerContext::Read(_) => AuthorizerDecision::Ignore,
            _ => AuthorizerDecision::Allow,
        });
        let ignored = auth_replace_items::table
            .select(auth_replace_items::id.nullable())
            .load::<Option<i32>>(conn)
            .unwrap();
        assert_eq!(
            ignored,
            vec![None],
            "after replacing the authorizer the new decision takes effect"
        );
    }

    #[diesel_test_helper::test]
    #[expect(
        unsafe_code,
        reason = "a non-UTF-8 identifier cannot be written through `&str` SQL"
    )]
    fn non_utf8_names_are_denied_before_the_callback() {
        use std::sync::Mutex;

        let conn = &mut connection();
        let sql = c"CREATE VIEW \"helper\xff\" AS SELECT abs(-1) AS id; CREATE VIEW items AS SELECT id FROM \"helper\xff\";";
        // SAFETY: the connection is live, and `sql` is a NUL-terminated string borrowed for the call.
        let rc = unsafe {
            conn.with_raw_connection(|raw| {
                ffi::sqlite3_exec(
                    raw,
                    sql.as_ptr(),
                    None,
                    core::ptr::null_mut(),
                    core::ptr::null_mut(),
                )
            })
        };
        assert_eq!(rc, ffi::SQLITE_OK);

        let abs_accessors = Arc::new(Mutex::new(Vec::new()));
        let abs_accessors2 = abs_accessors.clone();
        conn.on_authorize(move |ctx| {
            if let AuthorizerContext::Function(function) = ctx
                && function.function == Some("abs")
            {
                abs_accessors2
                    .lock()
                    .unwrap()
                    .push(function.accessor.map(str::to_owned));
            }
            AuthorizerDecision::Allow
        });

        let result = crate::sql_query("SELECT id FROM items").execute(conn);
        assert!(result.is_err());
        assert!(abs_accessors.lock().unwrap().iter().all(Option::is_some));
    }

    #[diesel_test_helper::test]
    fn schema_modifying_policy_blocks_writable_schema_edits() {
        use crate::connection::SimpleConnection;
        use crate::dsl::sql;
        use crate::sql_types::BigInt;

        let conn = &mut connection();
        conn.batch_execute(
            "CREATE TABLE accounts (id INTEGER PRIMARY KEY, balance INTEGER NOT NULL CHECK (balance >= 0));
             CREATE TRIGGER audit AFTER UPDATE ON accounts BEGIN SELECT 1; END;",
        )
        .unwrap();
        conn.on_authorize(|ctx| {
            if ctx.is_schema_modifying() {
                AuthorizerDecision::Deny
            } else {
                AuthorizerDecision::Allow
            }
        });

        let _ = conn.batch_execute(
            "PRAGMA writable_schema = ON;
             DELETE FROM sqlite_schema WHERE name = 'audit';
             PRAGMA writable_schema = RESET;",
        );
        assert!(conn.batch_execute("PRAGMA writable_schema").is_ok());
        assert!(conn.batch_execute("PRAGMA schema_version").is_ok());

        conn.remove_authorizer();
        let triggers: i64 =
            sql::<BigInt>("SELECT count(*) FROM sqlite_schema WHERE name = 'audit'")
                .get_result(conn)
                .unwrap();
        assert_eq!(triggers, 1);
    }
}