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
//! Typed access to SQLite [pragmas](https://www.sqlite.org/pragma.html).
//!
//! A pragma is declared as a type implementing [`Pragma`], with [`ReadPragma`] when it returns rows and [`WritePragma`] when it can be assigned an argument. Its [`Scope`](Pragma::Scope) decides whether it is used per database or per connection, and the caller picks the Rust type each row decodes into.
//!
//! # Per-schema pragmas
//!
//! A [`PerSchema`] pragma applies to one database and is read and written through [`SchemaPragma`], where a `None` schema selects `main`.
//!
//! ```rust
//! # include!("../doctest_setup.rs");
//! use diesel::sqlite::pragma::{PerSchema, Pragma, ReadPragma, SchemaPragma, WritePragma};
//!
//! struct UserVersion;
//!
//! impl Pragma for UserVersion {
//!     const NAME: &'static str = "user_version";
//!     type Scope = PerSchema;
//! }
//!
//! impl ReadPragma for UserVersion {
//!     type SqlType = Integer;
//! }
//!
//! impl WritePragma for UserVersion {
//!     type Argument<'a> = i32;
//! }
//!
//! # fn main() -> QueryResult<()> {
//! let conn = &mut SqliteConnection::establish(":memory:").unwrap();
//! UserVersion::set(7, None, conn)?;
//! assert_eq!(7, UserVersion::get::<i32>(None, conn)?);
//! #     Ok(())
//! # }
//! ```
//!
//! # Per-connection pragmas
//!
//! A [`PerConnection`] pragma applies to the whole connection and is read and written through [`ConnectionPragma`], which takes no schema.
//!
//! ```rust
//! # include!("../doctest_setup.rs");
//! use diesel::sqlite::pragma::{
//!     ConnectionPragma, PerConnection, Pragma, ReadPragma, WritePragma,
//! };
//!
//! struct ForeignKeys;
//!
//! impl Pragma for ForeignKeys {
//!     const NAME: &'static str = "foreign_keys";
//!     type Scope = PerConnection;
//! }
//!
//! impl ReadPragma for ForeignKeys {
//!     type SqlType = Bool;
//! }
//!
//! impl WritePragma for ForeignKeys {
//!     type Argument<'a> = bool;
//! }
//!
//! # fn main() -> QueryResult<()> {
//! let conn = &mut SqliteConnection::establish(":memory:").unwrap();
//! ForeignKeys::set(true, conn)?;
//! assert!(ForeignKeys::get::<bool>(conn)?);
//! #     Ok(())
//! # }
//! ```

use crate::connection::{DefaultLoadingMode, LoadConnection};
use crate::deserialize::FromSqlRow;
use crate::expression::QueryMetadata;
use crate::query_builder::{AstPass, Query, QueryFragment, QueryId};
use crate::result::{Error, QueryResult};
use crate::sql_types::SqlType;
use crate::sqlite::{AutoVacuumMode, Sqlite, SqliteConnection};
use alloc::string::ToString;
use alloc::vec::Vec;
use core::marker::PhantomData;
use core::num::NonZeroU32;

/// A pragma, named by [`NAME`](Self::NAME) and scoped by [`Scope`](Self::Scope).
pub trait Pragma: Sized {
    /// The pragma name, written into the SQL unquoted.
    ///
    /// A name that is empty or holds anything but ASCII letters, digits and underscores fails with [`Error::QueryBuilderError`] before reaching SQLite. Naming a pragma SQLite knows is up to the implementer, since SQLite ignores unknown ones.
    const NAME: &'static str;
    /// [`PerSchema`] or [`PerConnection`].
    type Scope: PragmaScope;
}

/// Whether a pragma targets one database or the whole connection.
pub trait PragmaScope: private::Sealed {}

/// A pragma that applies to one database, `main` or an attached one.
#[derive(Debug, Clone, Copy)]
pub enum PerSchema {}

/// A connection-wide pragma, whose schema qualifier SQLite ignores.
#[derive(Debug, Clone, Copy)]
pub enum PerConnection {}

impl PragmaScope for PerSchema {}
impl PragmaScope for PerConnection {}

mod private {
    use crate::query_builder::AstPass;
    use crate::result::QueryResult;
    use crate::sqlite::Sqlite;

    pub trait Sealed {}
    impl Sealed for super::PerSchema {}
    impl Sealed for super::PerConnection {}

    pub trait RenderArgument {
        fn render(&self, out: &mut AstPass<'_, '_, Sqlite>) -> QueryResult<()>;
    }
}

/// A pragma that returns rows when queried.
pub trait ReadPragma: Pragma {
    /// The SQL type of one returned row.
    type SqlType: SqlType;
}

/// A pragma that can be assigned an [`Argument`](Self::Argument).
///
/// Never assign secrets this way, since [`Instrumentation`](crate::connection::Instrumentation), [`on_trace`](SqliteConnection::on_trace) and [`on_authorize`](SqliteConnection::on_authorize) observe the statement.
pub trait WritePragma: Pragma {
    /// The argument assigned to the pragma, accepted as any type converting into it.
    type Argument<'a>: PragmaArgument;
}

/// A value written into a pragma statement, which takes no bind parameters.
///
/// Diesel renders every argument itself, so this trait cannot be implemented outside Diesel. A type of your own becomes an argument by converting into one with [`From`].
///
/// Integers and `bool` are written as decimal integers. An `Option<NonZeroU32>` writes `None` as 0, which limit pragmas such as `incremental_vacuum` read as no limit.
pub trait PragmaArgument: private::RenderArgument {}

/// A keyword written unquoted, such as `WAL` or `NORMAL`.
///
/// A keyword that is empty or holds anything but ASCII letters, digits and underscores fails with [`Error::QueryBuilderError`] before reaching SQLite.
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// use diesel::sqlite::pragma::{
///     PerSchema, Pragma, PragmaKeyword, ReadPragma, SchemaPragma, WritePragma,
/// };
///
/// struct Synchronous;
///
/// impl Pragma for Synchronous {
///     const NAME: &'static str = "synchronous";
///     type Scope = PerSchema;
/// }
///
/// impl ReadPragma for Synchronous {
///     type SqlType = Integer;
/// }
///
/// impl WritePragma for Synchronous {
///     type Argument<'a> = PragmaKeyword;
/// }
///
/// enum SynchronousMode {
///     Off,
///     Normal,
/// }
///
/// impl From<SynchronousMode> for PragmaKeyword {
///     fn from(mode: SynchronousMode) -> Self {
///         match mode {
///             SynchronousMode::Off => PragmaKeyword::new("OFF"),
///             SynchronousMode::Normal => PragmaKeyword::new("NORMAL"),
///         }
///     }
/// }
///
/// # fn main() -> QueryResult<()> {
/// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
/// Synchronous::set(SynchronousMode::Normal, None, conn)?;
/// assert_eq!(1, Synchronous::get::<i32>(None, conn)?);
/// Synchronous::set(SynchronousMode::Off, None, conn)?;
/// assert_eq!(0, Synchronous::get::<i32>(None, conn)?);
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PragmaKeyword(&'static str);

impl PragmaKeyword {
    /// Wrap `keyword`, which is checked when the statement is built.
    pub const fn new(keyword: &'static str) -> Self {
        Self(keyword)
    }
}

impl private::RenderArgument for PragmaKeyword {
    fn render(&self, out: &mut AstPass<'_, '_, Sqlite>) -> QueryResult<()> {
        push_bare_word(out, "keyword", self.0)
    }
}

impl PragmaArgument for PragmaKeyword {}

/// Text written as a single-quoted SQL string with embedded quotes doubled, such as `'UTF-16le'`.
///
/// Text holding a NUL byte fails with [`Error::InvalidCString`] before reaching SQLite.
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// use diesel::sqlite::pragma::{
///     ConnectionPragma, PerConnection, Pragma, PragmaText, ReadPragma, WritePragma,
/// };
///
/// struct Encoding;
///
/// impl Pragma for Encoding {
///     const NAME: &'static str = "encoding";
///     type Scope = PerConnection;
/// }
///
/// impl ReadPragma for Encoding {
///     type SqlType = Text;
/// }
///
/// impl WritePragma for Encoding {
///     type Argument<'a> = PragmaText<'a>;
/// }
///
/// # // Reading text allocated by the native sqlite library is not supported
/// # // by miri `-Zmiri-native-lib`.
/// # #[cfg(not(miri))]
/// # fn main() -> QueryResult<()> {
/// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
/// // SQLite only changes the encoding before anything is written.
/// Encoding::set("UTF-16le", conn)?;
/// assert_eq!("UTF-16le", Encoding::get::<String>(conn)?);
/// #     Ok(())
/// # }
/// # #[cfg(miri)]
/// # fn main() {}
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PragmaText<'a>(&'a str);

impl<'a> From<&'a str> for PragmaText<'a> {
    fn from(text: &'a str) -> Self {
        Self(text)
    }
}

impl private::RenderArgument for PragmaText<'_> {
    fn render(&self, out: &mut AstPass<'_, '_, Sqlite>) -> QueryResult<()> {
        out.push_sql("'");
        for piece in self.0.split_inclusive('\'') {
            out.push_sql(piece);
            if piece.ends_with('\'') {
                out.push_sql("'");
            }
        }
        out.push_sql("'");
        Ok(())
    }
}

impl PragmaArgument for PragmaText<'_> {}

macro_rules! integer_pragma_argument {
    ($($ty:ty),*) => {$(
        impl private::RenderArgument for $ty {
            fn render(&self, out: &mut AstPass<'_, '_, Sqlite>) -> QueryResult<()> {
                out.push_sql(&i64::from(*self).to_string());
                Ok(())
            }
        }

        impl PragmaArgument for $ty {}
    )*};
}

integer_pragma_argument!(i8, i16, i32, i64, u8, u16, u32, bool);

/// Reads and writes a [`PerSchema`] pragma, where a `None` schema selects `main`.
pub trait SchemaPragma: Pragma<Scope = PerSchema> {
    /// Read the first row, returning [`Error::NotFound`] if the pragma returns none.
    fn get<Row>(schema: Option<&str>, conn: &mut SqliteConnection) -> QueryResult<Row>
    where
        Self: ReadPragma,
        Sqlite: QueryMetadata<Self::SqlType>,
        Row: FromSqlRow<Self::SqlType, Sqlite>,
    {
        first_row::<Self, Row>(conn, Some(schema.unwrap_or("main")))
    }

    /// Read every row.
    fn get_all<Row>(schema: Option<&str>, conn: &mut SqliteConnection) -> QueryResult<Vec<Row>>
    where
        Self: ReadPragma,
        Sqlite: QueryMetadata<Self::SqlType>,
        Row: FromSqlRow<Self::SqlType, Sqlite>,
    {
        all_rows::<Self, Row>(conn, Some(schema.unwrap_or("main")))
    }

    /// Assign `argument`, running the statement to completion without confirming the value SQLite applied.
    fn set<'a>(
        argument: impl Into<Self::Argument<'a>>,
        schema: Option<&str>,
        conn: &mut SqliteConnection,
    ) -> QueryResult<()>
    where
        Self: WritePragma,
    {
        assign::<Self>(conn, Some(schema.unwrap_or("main")), argument.into())
    }
}

impl<P: Pragma<Scope = PerSchema>> SchemaPragma for P {}

/// Reads and writes a [`PerConnection`] pragma.
pub trait ConnectionPragma: Pragma<Scope = PerConnection> {
    /// Read the first row, returning [`Error::NotFound`] if the pragma returns none.
    fn get<Row>(conn: &mut SqliteConnection) -> QueryResult<Row>
    where
        Self: ReadPragma,
        Sqlite: QueryMetadata<Self::SqlType>,
        Row: FromSqlRow<Self::SqlType, Sqlite>,
    {
        first_row::<Self, Row>(conn, None)
    }

    /// Read every row.
    fn get_all<Row>(conn: &mut SqliteConnection) -> QueryResult<Vec<Row>>
    where
        Self: ReadPragma,
        Sqlite: QueryMetadata<Self::SqlType>,
        Row: FromSqlRow<Self::SqlType, Sqlite>,
    {
        all_rows::<Self, Row>(conn, None)
    }

    /// Assign `argument`, running the statement to completion without confirming the value SQLite applied.
    fn set<'a>(
        argument: impl Into<Self::Argument<'a>>,
        conn: &mut SqliteConnection,
    ) -> QueryResult<()>
    where
        Self: WritePragma,
    {
        assign::<Self>(conn, None, argument.into())
    }
}

impl<P: Pragma<Scope = PerConnection>> ConnectionPragma for P {}

/// `PRAGMA page_count`, the total number of pages in a database, read as an `i64`.
///
/// Multiply by the page size for the size the database accounts for.
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// use diesel::connection::SimpleConnection;
/// use diesel::sqlite::pragma::{PageCount, SchemaPragma};
///
/// # fn main() -> QueryResult<()> {
/// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
/// // An empty database occupies no pages until something is written.
/// assert_eq!(0, PageCount::get::<i64>(None, conn)?);
/// conn.batch_execute("CREATE TABLE items (id INTEGER PRIMARY KEY)")?;
/// assert!(PageCount::get::<i64>(None, conn)? > 0);
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct PageCount;

impl Pragma for PageCount {
    const NAME: &'static str = "page_count";
    type Scope = PerSchema;
}

impl ReadPragma for PageCount {
    type SqlType = crate::sql_types::BigInt;
}

/// `PRAGMA freelist_count`, the unused pages on a database's freelist, read as an `i64`.
///
/// A growing freelist is reclaimable space, freed by `VACUUM`.
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// use diesel::sqlite::pragma::{FreelistCount, SchemaPragma};
///
/// # fn main() -> QueryResult<()> {
/// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
/// assert_eq!(0, FreelistCount::get::<i64>(None, conn)?);
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct FreelistCount;

impl Pragma for FreelistCount {
    const NAME: &'static str = "freelist_count";
    type Scope = PerSchema;
}

impl ReadPragma for FreelistCount {
    type SqlType = crate::sql_types::BigInt;
}

/// `PRAGMA auto_vacuum`, read and set as an [`AutoVacuumMode`].
///
/// Changing from or to [`AutoVacuumMode::None`] only takes effect on a database with no tables yet, or after a subsequent `VACUUM`.
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// use diesel::sqlite::AutoVacuumMode;
/// use diesel::sqlite::pragma::{AutoVacuum, SchemaPragma};
///
/// # fn main() -> QueryResult<()> {
/// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
/// assert_eq!(AutoVacuumMode::None, AutoVacuum::get::<AutoVacuumMode>(None, conn)?);
/// AutoVacuum::set(AutoVacuumMode::Incremental, None, conn)?;
/// assert_eq!(
///     AutoVacuumMode::Incremental,
///     AutoVacuum::get::<AutoVacuumMode>(None, conn)?
/// );
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct AutoVacuum;

impl Pragma for AutoVacuum {
    const NAME: &'static str = "auto_vacuum";
    type Scope = PerSchema;
}

impl ReadPragma for AutoVacuum {
    type SqlType = crate::sql_types::Integer;
}

impl WritePragma for AutoVacuum {
    type Argument<'a> = AutoVacuumMode;
}

impl private::RenderArgument for AutoVacuumMode {
    fn render(&self, out: &mut AstPass<'_, '_, Sqlite>) -> QueryResult<()> {
        // Discriminant extraction, `#[repr(i32)]` makes it the mode's SQLite number.
        out.push_sql(&(*self as i32).to_string());
        Ok(())
    }
}

impl PragmaArgument for AutoVacuumMode {}

/// `PRAGMA incremental_vacuum`, shrinking a database by releasing freelist pages without the full rewrite [`VACUUM`](https://www.sqlite.org/lang_vacuum.html) performs.
///
/// `Some(pages)` releases at most that many pages, `None` the whole freelist. Only a database in [`AutoVacuumMode::Incremental`] has anything to release, on any other mode the assignment succeeds and does nothing.
///
/// ```rust
/// # include!("../doctest_setup.rs");
/// use diesel::sqlite::AutoVacuumMode;
/// use diesel::sqlite::pragma::{AutoVacuum, IncrementalVacuum, SchemaPragma};
/// use std::num::NonZeroU32;
///
/// # fn main() -> QueryResult<()> {
/// let conn = &mut SqliteConnection::establish(":memory:").unwrap();
/// AutoVacuum::set(AutoVacuumMode::Incremental, None, conn)?;
/// // Release at most 8 pages, then whatever is left.
/// IncrementalVacuum::set(NonZeroU32::new(8), None, conn)?;
/// IncrementalVacuum::set(None, None, conn)?;
/// #     Ok(())
/// # }
/// ```
#[derive(Debug, Clone, Copy)]
pub struct IncrementalVacuum;

impl Pragma for IncrementalVacuum {
    const NAME: &'static str = "incremental_vacuum";
    type Scope = PerSchema;
}

impl WritePragma for IncrementalVacuum {
    type Argument<'a> = Option<NonZeroU32>;
}

impl private::RenderArgument for Option<NonZeroU32> {
    fn render(&self, out: &mut AstPass<'_, '_, Sqlite>) -> QueryResult<()> {
        out.push_sql(&self.map_or(0, NonZeroU32::get).to_string());
        Ok(())
    }
}

impl PragmaArgument for Option<NonZeroU32> {}

fn cursor<'conn, 'query, P>(
    conn: &'conn mut SqliteConnection,
    schema: Option<&'query str>,
) -> QueryResult<<SqliteConnection as LoadConnection<DefaultLoadingMode>>::Cursor<'conn, 'query>>
where
    P: ReadPragma + 'query,
    Sqlite: QueryMetadata<P::SqlType>,
{
    LoadConnection::<DefaultLoadingMode>::load(conn, PragmaQuery::<P>::new(schema))
}

fn first_row<P, Row>(conn: &mut SqliteConnection, schema: Option<&str>) -> QueryResult<Row>
where
    P: ReadPragma,
    Sqlite: QueryMetadata<P::SqlType>,
    Row: FromSqlRow<P::SqlType, Sqlite>,
{
    let mut cursor = cursor::<P>(conn, schema)?;
    let row = cursor.next().ok_or(Error::NotFound)??;
    Row::build_from_row(&row).map_err(Error::DeserializationError)
}

fn all_rows<P, Row>(conn: &mut SqliteConnection, schema: Option<&str>) -> QueryResult<Vec<Row>>
where
    P: ReadPragma,
    Sqlite: QueryMetadata<P::SqlType>,
    Row: FromSqlRow<P::SqlType, Sqlite>,
{
    cursor::<P>(conn, schema)?
        .map(|row| Row::build_from_row(&row?).map_err(Error::DeserializationError))
        .collect()
}

fn assign<P: WritePragma>(
    conn: &mut SqliteConnection,
    schema: Option<&str>,
    argument: P::Argument<'_>,
) -> QueryResult<()> {
    use crate::connection::SimpleConnection;
    use crate::query_builder::QueryBuilder;
    use crate::sqlite::SqliteQueryBuilder;

    // Some pragmas do one unit of work per step, `incremental_vacuum` frees one page per step.
    // `sqlite3_exec` behind `batch_execute` runs to completion, while `StatementUse::run` steps once.
    let mut query = SqliteQueryBuilder::new();
    PragmaAssignment::<P, _> {
        schema,
        argument,
        pragma: PhantomData,
    }
    .to_sql(&mut query, &Sqlite)?;
    conn.batch_execute(&query.finish())
}

#[derive(Debug)]
struct PragmaQuery<'a, P> {
    schema: Option<&'a str>,

    pragma: PhantomData<P>,
}

impl<'a, P: Pragma> PragmaQuery<'a, P> {
    fn new(schema: Option<&'a str>) -> Self {
        Self {
            schema,
            pragma: PhantomData,
        }
    }
}

impl<P: Pragma> QueryFragment<Sqlite> for PragmaQuery<'_, P> {
    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Sqlite>) -> QueryResult<()> {
        push_pragma::<P>(&mut out, self.schema)
    }
}

// The schema name is runtime data, so the rendered SQL is not determined by the type.
impl<P> QueryId for PragmaQuery<'_, P> {
    type QueryId = ();

    const HAS_STATIC_QUERY_ID: bool = false;
}

impl<P: ReadPragma> Query for PragmaQuery<'_, P> {
    type SqlType = P::SqlType;
}

struct PragmaAssignment<'a, P, A> {
    schema: Option<&'a str>,
    argument: A,
    pragma: PhantomData<P>,
}

impl<P: Pragma, A: PragmaArgument> QueryFragment<Sqlite> for PragmaAssignment<'_, P, A> {
    fn walk_ast<'b>(&'b self, mut out: AstPass<'_, 'b, Sqlite>) -> QueryResult<()> {
        push_pragma::<P>(&mut out, self.schema)?;
        out.push_sql(" = ");
        self.argument.render(&mut out)
    }
}

fn push_pragma<P: Pragma>(
    out: &mut AstPass<'_, '_, Sqlite>,
    schema: Option<&str>,
) -> QueryResult<()> {
    out.push_sql("PRAGMA ");
    if let Some(schema) = schema {
        out.push_identifier(schema)?;
        out.push_sql(".");
    }
    push_bare_word(out, "name", P::NAME)
}

fn push_bare_word(
    out: &mut AstPass<'_, '_, Sqlite>,
    kind: &str,
    word: &'static str,
) -> QueryResult<()> {
    if word.is_empty()
        || !word
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
    {
        return Err(Error::QueryBuilderError(
            alloc::format!("`{word}` is not a valid pragma {kind}").into(),
        ));
    }
    out.push_sql(word);
    Ok(())
}