qail-pg 1.3.0

Rust PostgreSQL driver for typed AST queries with direct wire-protocol execution
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
//! Native access-policy wrappers for qail-pg execution APIs.

use qail_core::access::{AccessContext, AccessError, AccessPolicy};
use qail_core::ast::Qail;

use super::{
    AstPipelineMode, AutoCountPlan, PgDriver, PgError, PgPool, PgResult, PgRow, PooledConnection,
    PreparedAstQuery, QueryResult, ResultFormat,
};

fn access_denied_error(err: AccessError) -> PgError {
    PgError::Query(format!("Access denied by policy: {}", err))
}

fn check_access(policy: &AccessPolicy, ctx: &AccessContext, cmd: &Qail) -> PgResult<()> {
    policy.check_command(ctx, cmd).map_err(access_denied_error)
}

fn check_all_access(policy: &AccessPolicy, ctx: &AccessContext, cmds: &[Qail]) -> PgResult<()> {
    for cmd in cmds {
        check_access(policy, ctx, cmd)?;
    }
    Ok(())
}

fn copy_export_table_command(table: &str, columns: &[String]) -> Qail {
    Qail::export(table).columns(columns.iter().map(String::as_str))
}

impl PgDriver {
    /// Check a command against an access policy without executing it.
    pub fn check_access(
        &self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()> {
        check_access(access_policy, access_ctx, cmd)
    }

    /// Execute a checked QAIL command and fetch all rows using the default text format.
    pub async fn fetch_all_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all(cmd).await
    }

    /// Execute a checked QAIL command and fetch all rows using an explicit result format.
    pub async fn fetch_all_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_with_format(cmd, result_format).await
    }

    /// Execute a checked QAIL command using the uncached path.
    pub async fn fetch_all_uncached_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_uncached(cmd).await
    }

    /// Execute a checked QAIL command using the uncached path and explicit result format.
    pub async fn fetch_all_uncached_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_uncached_with_format(cmd, result_format)
            .await
    }

    /// Execute a checked QAIL command using the fast path.
    pub async fn fetch_all_fast_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_fast(cmd).await
    }

    /// Execute a checked QAIL command using the fast path and explicit result format.
    pub async fn fetch_all_fast_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_fast_with_format(cmd, result_format).await
    }

    /// Execute a checked QAIL command and fetch one row.
    pub async fn fetch_one_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<PgRow> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_one(cmd).await
    }

    /// Prepare a checked AST query once and return a reusable frozen handle.
    ///
    /// Policy is checked at prepare time. Callers that need per-request policy
    /// changes should prepare per request or execute through the non-prepared
    /// checked wrappers.
    pub async fn prepare_ast_query_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<PreparedAstQuery> {
        check_access(access_policy, access_ctx, cmd)?;
        self.prepare_ast_query(cmd).await
    }

    /// Execute a checked QAIL command and decode rows into typed structs.
    pub async fn fetch_typed_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_typed(cmd).await
    }

    /// Execute a checked QAIL command and decode typed rows using an explicit result format.
    pub async fn fetch_typed_with_format_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_typed_with_format(cmd, result_format).await
    }

    /// Execute a checked QAIL command and decode one typed row.
    pub async fn fetch_one_typed_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Option<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_one_typed(cmd).await
    }

    /// Execute a checked QAIL command and decode one typed row using an explicit format.
    pub async fn fetch_one_typed_with_format_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Option<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_one_typed_with_format(cmd, result_format).await
    }

    /// Execute a checked mutation command.
    pub async fn execute_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<u64> {
        check_access(access_policy, access_ctx, cmd)?;
        self.execute(cmd).await
    }

    /// Bulk insert checked AST rows using PostgreSQL COPY.
    pub async fn copy_bulk_checked(
        &mut self,
        cmd: &Qail,
        rows: &[Vec<qail_core::ast::Value>],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<u64> {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_bulk(cmd, rows).await
    }

    /// Bulk insert checked pre-encoded COPY bytes.
    pub async fn copy_bulk_bytes_checked(
        &mut self,
        cmd: &Qail,
        data: &[u8],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<u64> {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_bulk_bytes(cmd, data).await
    }

    /// Export a checked table/column selection using COPY TO STDOUT.
    pub async fn copy_export_table_checked(
        &mut self,
        table: &str,
        columns: &[String],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<u8>> {
        check_access(
            access_policy,
            access_ctx,
            &copy_export_table_command(table, columns),
        )?;
        self.copy_export_table(table, columns).await
    }

    /// Stream a checked table/column selection using COPY TO STDOUT.
    pub async fn copy_export_table_stream_checked<F, Fut>(
        &mut self,
        table: &str,
        columns: &[String],
        on_chunk: F,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: std::future::Future<Output = PgResult<()>>,
    {
        check_access(
            access_policy,
            access_ctx,
            &copy_export_table_command(table, columns),
        )?;
        self.copy_export_table_stream(table, columns, on_chunk)
            .await
    }

    /// Stream a checked AST-native export command as raw COPY chunks.
    pub async fn copy_export_cmd_stream_checked<F, Fut>(
        &mut self,
        cmd: &Qail,
        on_chunk: F,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: std::future::Future<Output = PgResult<()>>,
    {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_export_cmd_stream(cmd, on_chunk).await
    }

    /// Stream a checked AST-native export command as parsed rows.
    pub async fn copy_export_cmd_stream_rows_checked<F>(
        &mut self,
        cmd: &Qail,
        on_row: F,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<String>) -> PgResult<()>,
    {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_export_cmd_stream_rows(cmd, on_row).await
    }

    /// Stream checked cursor batches for a QAIL command.
    pub async fn stream_cmd_checked(
        &mut self,
        cmd: &Qail,
        batch_size: usize,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<Vec<PgRow>>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.stream_cmd(cmd, batch_size).await
    }

    /// Execute a checked query and return a structured query result.
    pub async fn query_ast_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<QueryResult> {
        check_access(access_policy, access_ctx, cmd)?;
        self.query_ast(cmd).await
    }

    /// Execute a checked query and return a structured query result using an explicit format.
    pub async fn query_ast_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<QueryResult> {
        check_access(access_policy, access_ctx, cmd)?;
        self.query_ast_with_format(cmd, result_format).await
    }

    /// Execute checked commands in one transaction.
    ///
    /// All commands are checked before `BEGIN`, so a denied later command cannot
    /// partially execute earlier commands.
    pub async fn execute_batch_checked(
        &mut self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<u64>> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.execute_batch(cmds).await
    }

    /// Execute checked commands with runtime auto strategy and return both count and plan.
    pub async fn execute_count_auto_with_plan_checked(
        &mut self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<(usize, AutoCountPlan)> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.execute_count_auto_with_plan(cmds).await
    }

    /// Execute checked commands with runtime auto strategy.
    pub async fn execute_count_auto_checked(
        &mut self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<usize> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.execute_count_auto(cmds).await
    }

    /// Execute checked commands with an explicit pipeline strategy.
    pub async fn pipeline_execute_count_with_mode_checked(
        &mut self,
        cmds: &[Qail],
        mode: AstPipelineMode,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<usize> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.pipeline_execute_count_with_mode(cmds, mode).await
    }

    /// Execute checked commands with the default pipeline strategy.
    pub async fn pipeline_execute_count_checked(
        &mut self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<usize> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.pipeline_execute_count(cmds).await
    }

    /// Execute checked commands and return full row data.
    pub async fn pipeline_execute_rows_checked(
        &mut self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<Vec<PgRow>>> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.pipeline_execute_rows(cmds).await
    }
}

impl PooledConnection {
    /// Check a command against an access policy without executing it.
    pub fn check_access(
        &self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()> {
        check_access(access_policy, access_ctx, cmd)
    }

    /// Execute a checked QAIL command using the default cached pooled path.
    pub async fn fetch_all_cached_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_cached(cmd).await
    }

    /// Execute a checked QAIL command using the cached pooled path with explicit format.
    pub async fn fetch_all_cached_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_cached_with_format(cmd, result_format).await
    }

    /// Execute a checked QAIL command using the uncached pooled path.
    pub async fn fetch_all_uncached_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_uncached(cmd).await
    }

    /// Execute a checked QAIL command using the uncached pooled path with explicit format.
    pub async fn fetch_all_uncached_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_uncached_with_format(cmd, result_format)
            .await
    }

    /// Execute a checked QAIL command using the fast pooled path.
    pub async fn fetch_all_fast_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_fast(cmd).await
    }

    /// Execute a checked QAIL command using the fast pooled path with explicit format.
    pub async fn fetch_all_fast_with_format_checked(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_fast_with_format(cmd, result_format).await
    }

    /// Execute a checked QAIL command under an already prepared RLS setup string.
    pub async fn fetch_all_with_rls_checked(
        &mut self,
        cmd: &Qail,
        rls_sql: &str,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_with_rls(cmd, rls_sql).await
    }

    /// Execute a checked QAIL command under RLS with an explicit result format.
    pub async fn fetch_all_with_rls_with_format_checked(
        &mut self,
        cmd: &Qail,
        rls_sql: &str,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<PgRow>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_all_with_rls_with_format(cmd, rls_sql, result_format)
            .await
    }

    /// Export checked data using AST-native COPY TO STDOUT.
    pub async fn copy_export_checked(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<Vec<String>>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_export(cmd).await
    }

    /// Stream a checked AST-native COPY export as raw chunks.
    pub async fn copy_export_stream_raw_checked<F, Fut>(
        &mut self,
        cmd: &Qail,
        on_chunk: F,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: std::future::Future<Output = PgResult<()>>,
    {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_export_stream_raw(cmd, on_chunk).await
    }

    /// Stream a checked AST-native COPY export as parsed rows.
    pub async fn copy_export_stream_rows_checked<F>(
        &mut self,
        cmd: &Qail,
        on_row: F,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<String>) -> PgResult<()>,
    {
        check_access(access_policy, access_ctx, cmd)?;
        self.copy_export_stream_rows(cmd, on_row).await
    }

    /// Export a checked table/column selection using COPY TO STDOUT.
    pub async fn copy_export_table_checked(
        &mut self,
        table: &str,
        columns: &[String],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<u8>> {
        check_access(
            access_policy,
            access_ctx,
            &copy_export_table_command(table, columns),
        )?;
        self.copy_export_table(table, columns).await
    }

    /// Stream a checked table/column selection using COPY TO STDOUT.
    pub async fn copy_export_table_stream_checked<F, Fut>(
        &mut self,
        table: &str,
        columns: &[String],
        on_chunk: F,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<()>
    where
        F: FnMut(Vec<u8>) -> Fut,
        Fut: std::future::Future<Output = PgResult<()>>,
    {
        check_access(
            access_policy,
            access_ctx,
            &copy_export_table_command(table, columns),
        )?;
        self.copy_export_table_stream(table, columns, on_chunk)
            .await
    }

    /// Execute a checked QAIL command and decode rows into typed structs.
    pub async fn fetch_typed_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_typed(cmd).await
    }

    /// Execute a checked QAIL command and decode typed rows using an explicit result format.
    pub async fn fetch_typed_with_format_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_typed_with_format(cmd, result_format).await
    }

    /// Execute a checked QAIL command and decode one typed row.
    pub async fn fetch_one_typed_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Option<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_one_typed(cmd).await
    }

    /// Execute a checked QAIL command and decode one typed row using an explicit format.
    pub async fn fetch_one_typed_with_format_checked<T: super::row::QailRow>(
        &mut self,
        cmd: &Qail,
        result_format: ResultFormat,
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Option<T>> {
        check_access(access_policy, access_ctx, cmd)?;
        self.fetch_one_typed_with_format(cmd, result_format).await
    }

    /// Execute checked AST commands in one pooled pipeline call.
    pub async fn pipeline_execute_rows_ast_checked(
        &mut self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<Vec<Vec<Vec<Option<Vec<u8>>>>>> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.pipeline_execute_rows_ast(cmds).await
    }
}

impl PgPool {
    /// Execute checked commands with the pool auto strategy and return both count and plan.
    pub async fn execute_count_auto_with_plan_checked(
        &self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<(usize, AutoCountPlan)> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.execute_count_auto_with_plan(cmds).await
    }

    /// Execute checked commands with the pool auto strategy.
    pub async fn execute_count_auto_checked(
        &self,
        cmds: &[Qail],
        access_ctx: &AccessContext,
        access_policy: &AccessPolicy,
    ) -> PgResult<usize> {
        check_all_access(access_policy, access_ctx, cmds)?;
        self.execute_count_auto(cmds).await
    }
}

#[cfg(test)]
mod tests {
    use qail_core::access::{
        AccessContext, AccessOperation, AccessPolicy, ColumnRule, TableAccessPolicy,
    };
    use qail_core::ast::{Expr, Qail};

    use super::{check_access, check_all_access, copy_export_table_command};
    use crate::driver::PgError;

    #[test]
    fn checked_pg_error_uses_existing_query_variant() {
        let err = check_access(
            &AccessPolicy::new(),
            &AccessContext::anonymous(),
            &Qail::get("orders"),
        )
        .expect_err("missing policy should fail closed");

        match err {
            PgError::Query(message) => {
                assert!(message.contains("Access denied by policy"));
                assert!(message.contains("orders"));
            }
            other => panic!("unexpected error variant: {other:?}"),
        }
    }

    #[test]
    fn checked_batch_rejects_denied_later_command_before_execution() {
        let policy = AccessPolicy::new().with_table(
            "orders",
            TableAccessPolicy::new()
                .allow_operations([AccessOperation::Read])
                .read_columns(ColumnRule::only(["id"])),
        );
        let cmds = vec![
            Qail::get("orders").columns(["id"]),
            Qail::get("orders").columns(["id", "private_note"]),
        ];

        let err = check_all_access(&policy, &AccessContext::anonymous(), &cmds)
            .expect_err("second command should deny before any wrapper executes");

        assert!(matches!(err, PgError::Query(_)));
    }

    #[test]
    fn checked_policy_recurses_into_subqueries() {
        let policy = AccessPolicy::new().with_table(
            "orders",
            TableAccessPolicy::new().allow_operations([AccessOperation::Read]),
        );
        let cmd = Qail::get("orders").columns_expr([Expr::Subquery {
            query: Box::new(Qail::get("users").columns(["id"])),
            alias: None,
        }]);

        let err = check_access(&policy, &AccessContext::anonymous(), &cmd)
            .expect_err("subquery table should require its own policy");

        match err {
            PgError::Query(message) => assert!(message.contains("users")),
            other => panic!("unexpected error variant: {other:?}"),
        }
    }

    #[test]
    fn checked_copy_export_table_command_uses_read_column_policy() {
        let policy = AccessPolicy::new().with_table(
            "orders",
            TableAccessPolicy::new()
                .allow_operations([AccessOperation::Read])
                .read_columns(ColumnRule::only(["id"])),
        );
        let columns = vec!["id".to_string(), "private_note".to_string()];
        let cmd = copy_export_table_command("orders", &columns);

        let err = check_access(&policy, &AccessContext::anonymous(), &cmd)
            .expect_err("denied COPY export column should fail before execution");

        match err {
            PgError::Query(message) => assert!(message.contains("private_note")),
            other => panic!("unexpected error variant: {other:?}"),
        }
    }
}