glacier-web 0.3.0

A batteries-included web framework for Rust, inspired by Rails, Phoenix and Laravel.
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
//! Migrations: schema changes written in Rust, rendered for each database.
//!
//! A migration is a module with `up` and `down` functions, listed in
//! `src/migrations/mod.rs` via [`migrations!`](crate::migrations).
//! `glacier generate migration create_posts` writes both for you:
//!
//! ```
//! use glacier::db::migration::*;
//!
//! pub fn up(s: &mut Schema) {
//!     s.create_table("posts", |t| {
//!         t.string("title").not_null();
//!         t.string("slug").not_null().unique();
//!         t.text("body");
//!         t.boolean("published").not_null().default(false);
//!         t.references("author").on_delete_cascade();
//!         t.timestamps();
//!     });
//! }
//!
//! pub fn down(s: &mut Schema) {
//!     s.drop_table("posts");
//! }
//! ```
//!
//! Every table gets an auto-incrementing `id` primary key. Columns are
//! nullable unless marked `not_null()`.

use std::fmt::Write;

use super::sql::{Dialect, quote_ident};
use super::value::{ToValue, Value};
use super::{Repo, Sql};
use crate::error::{Error, Result};

pub(crate) const MIGRATIONS_TABLE: &str = "schema_migrations";
/// Where Glacier records its migrations in a database Rails also
/// migrates: Rails' `schema_migrations` has only a `version`.
pub(crate) const BESIDE_RAILS_TABLE: &str = "glacier_schema_migrations";

/// Collects the statements of one migration.
pub struct Schema {
    dialect: Dialect,
    statements: Vec<String>,
}

impl Schema {
    pub fn new(dialect: Dialect) -> Self {
        Self {
            dialect,
            statements: Vec::new(),
        }
    }

    pub fn dialect(&self) -> Dialect {
        self.dialect
    }

    /// The SQL statements collected so far.
    pub fn statements(&self) -> &[String] {
        &self.statements
    }

    pub fn create_table(&mut self, name: &str, define: impl FnOnce(&mut Table)) {
        let mut table = Table {
            dialect: self.dialect,
            columns: Vec::new(),
        };
        define(&mut table);
        let id = match self.dialect {
            Dialect::Postgres => "\"id\" BIGSERIAL PRIMARY KEY",
            Dialect::Sqlite => "\"id\" INTEGER PRIMARY KEY AUTOINCREMENT",
        };
        let mut definitions = vec![id.to_owned()];
        definitions.extend(table.columns.iter().map(Column::definition));
        definitions.extend(table.columns.iter().filter_map(Column::foreign_key));
        self.statements.push(format!(
            "CREATE TABLE {} (\n  {}\n)",
            quote_ident(name),
            definitions.join(",\n  ")
        ));
    }

    pub fn drop_table(&mut self, name: &str) {
        self.statements
            .push(format!("DROP TABLE {}", quote_ident(name)));
    }

    pub fn rename_table(&mut self, from: &str, to: &str) {
        self.statements.push(format!(
            "ALTER TABLE {} RENAME TO {}",
            quote_ident(from),
            quote_ident(to)
        ));
    }

    /// Changes an existing table. SQLite can't add `UNIQUE` columns this
    /// way, and a new `NOT NULL` column needs a default.
    pub fn alter_table(&mut self, name: &str, change: impl FnOnce(&mut Alter)) {
        let mut alter = Alter {
            dialect: self.dialect,
            table: name.to_owned(),
            columns: Vec::new(),
            statements: Vec::new(),
        };
        change(&mut alter);
        for column in &alter.columns {
            let mut definition = column.definition();
            if let Some(reference) = column.reference_clause() {
                definition.push_str(&reference);
            }
            alter.statements.push(format!(
                "ALTER TABLE {} ADD COLUMN {definition}",
                quote_ident(name)
            ));
        }
        self.statements.extend(alter.statements);
    }

    pub fn add_index(&mut self, table: &str, columns: &[&str]) {
        self.index(table, columns, false);
    }

    pub fn add_unique_index(&mut self, table: &str, columns: &[&str]) {
        self.index(table, columns, true);
    }

    pub fn drop_index(&mut self, table: &str, columns: &[&str]) {
        self.statements.push(format!(
            "DROP INDEX {}",
            quote_ident(&index_name(table, columns))
        ));
    }

    fn index(&mut self, table: &str, columns: &[&str], unique: bool) {
        let list: Vec<String> = columns.iter().map(|c| quote_ident(c)).collect();
        self.statements.push(format!(
            "CREATE {}INDEX {} ON {} ({})",
            if unique { "UNIQUE " } else { "" },
            quote_ident(&index_name(table, columns)),
            quote_ident(table),
            list.join(", ")
        ));
    }

    /// Raw SQL, for anything the DSL doesn't cover. Branch on
    /// `s.dialect()` when it differs between databases.
    pub fn execute(&mut self, sql: &str) {
        self.statements.push(sql.to_owned());
    }
}

fn index_name(table: &str, columns: &[&str]) -> String {
    format!("{table}_{}_index", columns.join("_"))
}

/// The columns of a table being created.
pub struct Table {
    dialect: Dialect,
    columns: Vec<Column>,
}

macro_rules! column_types {
    ($($(#[$doc:meta])* $method:ident => $pg:literal, $sqlite:literal;)*) => {
        $(
            $(#[$doc])*
            pub fn $method(&mut self, name: &str) -> &mut Column {
                let sql_type = match self.dialect {
                    Dialect::Postgres => $pg,
                    Dialect::Sqlite => $sqlite,
                };
                self.add(name, sql_type)
            }
        )*
    };
}

impl Table {
    column_types! {
        /// Short text (`VARCHAR` / `TEXT`); a `String` field.
        string => "VARCHAR", "TEXT";
        /// Long text; a `String` field.
        text => "TEXT", "TEXT";
        /// 32-bit integer; an `i32` field.
        integer => "INTEGER", "INTEGER";
        /// 64-bit integer; an `i64` field.
        bigint => "BIGINT", "BIGINT";
        /// Double-precision float; an `f64` field.
        float => "DOUBLE PRECISION", "REAL";
        /// A `bool` field.
        boolean => "BOOLEAN", "BOOLEAN";
        /// A `Timestamp` field (UTC).
        timestamp => "TIMESTAMPTZ", "TEXT";
        /// Raw bytes; a `Vec<u8>` field.
        binary => "BYTEA", "BLOB";
        /// JSON (`JSONB` / `TEXT`); a `serde_json::Value` field.
        json => "JSONB", "TEXT";
    }

    /// A `<name>_id` column referencing the pluralized table's `id`, e.g.
    /// `t.references("author")` → `author_id` → `authors(id)`.
    pub fn references(&mut self, name: &str) -> &mut Column {
        let table = glacier_inflect::pluralize(name);
        self.references_table(name, &table)
    }

    /// Like `references`, with an explicit table: `("author", "users")`.
    pub fn references_table(&mut self, name: &str, table: &str) -> &mut Column {
        let column = self.bigint(&format!("{name}_id"));
        column.references = Some(table.to_owned());
        column
    }

    /// `inserted_at` and `updated_at`, filled in by changesets.
    pub fn timestamps(&mut self) {
        self.timestamp("inserted_at").not_null();
        self.timestamp("updated_at").not_null();
    }

    fn add(&mut self, name: &str, sql_type: &'static str) -> &mut Column {
        self.columns.push(Column {
            name: name.to_owned(),
            sql_type,
            not_null: false,
            unique: false,
            default: None,
            references: None,
            on_delete: None,
            dialect: self.dialect,
        });
        self.columns.last_mut().expect("just pushed")
    }
}

/// Changes to an existing table.
pub struct Alter {
    dialect: Dialect,
    table: String,
    columns: Vec<Column>,
    statements: Vec<String>,
}

macro_rules! alter_column_types {
    ($($method:ident),*) => {
        $(
            #[doc = concat!("Adds a column; see [`Table::", stringify!($method), "`].")]
            pub fn $method(&mut self, name: &str) -> &mut Column {
                let mut table = Table { dialect: self.dialect, columns: Vec::new() };
                table.$method(name);
                self.columns.extend(table.columns);
                self.columns.last_mut().expect("just added")
            }
        )*
    };
}

impl Alter {
    alter_column_types!(
        string, text, integer, bigint, float, boolean, timestamp, binary, json
    );

    pub fn references(&mut self, name: &str) -> &mut Column {
        let mut table = Table {
            dialect: self.dialect,
            columns: Vec::new(),
        };
        table.references(name);
        self.columns.extend(table.columns);
        self.columns.last_mut().expect("just added")
    }

    pub fn drop_column(&mut self, name: &str) {
        self.statements.push(format!(
            "ALTER TABLE {} DROP COLUMN {}",
            quote_ident(&self.table),
            quote_ident(name)
        ));
    }

    pub fn rename_column(&mut self, from: &str, to: &str) {
        self.statements.push(format!(
            "ALTER TABLE {} RENAME COLUMN {} TO {}",
            quote_ident(&self.table),
            quote_ident(from),
            quote_ident(to)
        ));
    }
}

/// A column definition; chain modifiers onto it.
pub struct Column {
    name: String,
    sql_type: &'static str,
    not_null: bool,
    unique: bool,
    default: Option<String>,
    references: Option<String>,
    on_delete: Option<&'static str>,
    dialect: Dialect,
}

impl Column {
    pub fn not_null(&mut self) -> &mut Self {
        self.not_null = true;
        self
    }

    pub fn unique(&mut self) -> &mut Self {
        self.unique = true;
        self
    }

    /// A default value, e.g. `.default(0)` or `.default(false)`.
    pub fn default(&mut self, value: impl ToValue) -> &mut Self {
        self.default = Some(literal(&value.to_value(), self.dialect));
        self
    }

    /// For `references`: delete these rows when the referenced row is
    /// deleted.
    pub fn on_delete_cascade(&mut self) -> &mut Self {
        self.on_delete = Some("CASCADE");
        self
    }

    /// For `references`: set this column to NULL when the referenced row is
    /// deleted.
    pub fn on_delete_nullify(&mut self) -> &mut Self {
        self.on_delete = Some("SET NULL");
        self
    }

    fn definition(&self) -> String {
        let mut sql = format!("{} {}", quote_ident(&self.name), self.sql_type);
        if self.not_null {
            sql.push_str(" NOT NULL");
        }
        if self.unique {
            sql.push_str(" UNIQUE");
        }
        if let Some(default) = &self.default {
            let _ = write!(sql, " DEFAULT {default}");
        }
        sql
    }

    fn reference_clause(&self) -> Option<String> {
        let table = self.references.as_ref()?;
        let mut sql = format!(" REFERENCES {}(\"id\")", quote_ident(table));
        if let Some(action) = self.on_delete {
            let _ = write!(sql, " ON DELETE {action}");
        }
        Some(sql)
    }

    fn foreign_key(&self) -> Option<String> {
        let clause = self.reference_clause()?;
        Some(format!("FOREIGN KEY ({}){clause}", quote_ident(&self.name)))
    }
}

/// A SQL literal for a column default.
fn literal(value: &Value, dialect: Dialect) -> String {
    match value {
        Value::Null => "NULL".into(),
        Value::Bool(true) => "TRUE".into(),
        Value::Bool(false) => "FALSE".into(),
        Value::Int(v) => v.to_string(),
        Value::Float(v) => v.to_string(),
        Value::Text(v) => format!("'{}'", v.replace('\'', "''")),
        Value::Timestamp(v) => match dialect {
            Dialect::Postgres => format!("'{}'", v.to_rfc3339()),
            Dialect::Sqlite => format!("'{}'", super::sqlite_timestamp(v)),
        },
        Value::Json(v) => format!("'{}'", v.to_string().replace('\'', "''")),
        Value::Decimal(v) => v.to_string(),
        Value::Uuid(v) => format!("'{v}'"),
        Value::List(items) => items
            .iter()
            .map(|item| literal(item, dialect))
            .collect::<Vec<_>>()
            .join(", "),
        Value::Date(v) => format!("'{v}'"),
        Value::Bytes(v) => {
            let hex: String = v.iter().map(|b| format!("{b:02x}")).collect();
            match dialect {
                Dialect::Postgres => format!("'\\x{hex}'"),
                Dialect::Sqlite => format!("X'{hex}'"),
            }
        }
    }
}

/// One migration: its version (the timestamp in its name) and its steps.
#[derive(Clone)]
pub struct Migration {
    version: String,
    name: String,
    up: fn(&mut Schema),
    down: fn(&mut Schema),
}

impl Migration {
    /// `name` is the module name, `m<version>_<description>`.
    pub fn new(name: &str, up: fn(&mut Schema), down: fn(&mut Schema)) -> Self {
        let trimmed = name.trim_start_matches('m');
        let version: String = trimmed.chars().take_while(char::is_ascii_digit).collect();
        Self {
            version,
            name: name.to_owned(),
            up,
            down,
        }
    }

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

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

    /// The SQL `up` would run on `dialect`.
    pub fn up_sql(&self, dialect: Dialect) -> Vec<String> {
        let mut schema = Schema::new(dialect);
        (self.up)(&mut schema);
        schema.statements
    }

    pub fn down_sql(&self, dialect: Dialect) -> Vec<String> {
        let mut schema = Schema::new(dialect);
        (self.down)(&mut schema);
        schema.statements
    }
}

/// Applies and reverts migrations, tracking them in `schema_migrations`.
/// Each migration runs in its own transaction.
pub struct Migrator {
    repo: Repo,
    migrations: Vec<Migration>,
    table: tokio::sync::OnceCell<&'static str>,
}

/// A migration and whether it has been applied.
pub struct Status {
    pub migration: Migration,
    pub applied: bool,
}

impl Migrator {
    /// # Errors
    ///
    /// If a migration's name has no version, or two share a version.
    pub fn new(repo: &Repo, mut migrations: Vec<Migration>) -> Result<Self> {
        migrations.sort_by(|a, b| a.version.cmp(&b.version));
        for migration in &migrations {
            if migration.version.is_empty() {
                return Err(Error::internal(format!(
                    "migration `{}` needs a name like m20261003120000_create_posts",
                    migration.name
                )));
            }
        }
        if let Some(pair) = migrations
            .windows(2)
            .find(|pair| pair[0].version == pair[1].version)
        {
            return Err(Error::internal(format!(
                "migrations `{}` and `{}` share version {}",
                pair[0].name, pair[1].name, pair[0].version
            )));
        }
        Ok(Self {
            repo: repo.clone(),
            migrations,
            table: tokio::sync::OnceCell::new(),
        })
    }

    /// The table applied versions are kept in: `schema_migrations`, or
    /// `glacier_schema_migrations` when that name is Rails' (a port that
    /// shares the Rails app's database), so the two never collide.
    async fn table(&self) -> Result<&'static str> {
        self.table
            .get_or_try_init(|| async {
                let columns = match self.repo.dialect() {
                    Dialect::Postgres => {
                        super::sql(
                            "SELECT column_name AS name FROM information_schema.columns \
                             WHERE table_schema = current_schema() AND table_name = ?",
                        )
                        .bind(MIGRATIONS_TABLE)
                        .on(&self.repo)
                        .fetch_all()
                        .await?
                    }
                    Dialect::Sqlite => {
                        super::sql(&format!("PRAGMA table_info({MIGRATIONS_TABLE})"))
                            .on(&self.repo)
                            .fetch_all()
                            .await?
                    }
                };
                let names: Vec<String> = columns
                    .iter()
                    .filter_map(|row| row.get::<String>("name").ok())
                    .collect();
                let rails = !names.is_empty() && !names.iter().any(|n| n == "inserted_at");
                Ok::<_, Error>(if rails {
                    BESIDE_RAILS_TABLE
                } else {
                    MIGRATIONS_TABLE
                })
            })
            .await
            .copied()
    }

    async fn ensure_table(&self) -> Result<()> {
        let table = self.table().await?;
        let sql = format!(
            "CREATE TABLE IF NOT EXISTS {table} (version VARCHAR(255) PRIMARY KEY, inserted_at {})",
            match self.repo.dialect() {
                Dialect::Postgres => "TIMESTAMPTZ",
                Dialect::Sqlite => "TEXT",
            }
        );
        // Many tests may start at once; on Postgres two `CREATE TABLE IF NOT
        // EXISTS` together can still collide. If it exists now, all is well.
        if let Err(err) = super::sql(&sql).on(&self.repo).execute().await {
            let exists = super::sql(&format!("SELECT 1 FROM {table} WHERE 1 = 0"))
                .on(&self.repo)
                .fetch_all()
                .await
                .is_ok();
            if !exists {
                return Err(err);
            }
        }
        Ok(())
    }

    async fn applied(&self) -> Result<Vec<String>> {
        self.ensure_table().await?;
        let table = self.table().await?;
        let rows = super::sql(&format!("SELECT version FROM {table} ORDER BY version"))
            .on(&self.repo)
            .fetch_all()
            .await?;
        rows.iter().map(|row| row.get("version")).collect()
    }

    pub async fn status(&self) -> Result<Vec<Status>> {
        let applied = self.applied().await?;
        Ok(self
            .migrations
            .iter()
            .map(|m| Status {
                migration: m.clone(),
                applied: applied.contains(&m.version),
            })
            .collect())
    }

    /// Migrations not yet applied, oldest first.
    pub async fn pending(&self) -> Result<Vec<Migration>> {
        Ok(self
            .status()
            .await?
            .into_iter()
            .filter(|s| !s.applied)
            .map(|s| s.migration)
            .collect())
    }

    /// Applies every pending migration, returning their names.
    pub async fn migrate(&self) -> Result<Vec<String>> {
        let mut done = Vec::new();
        let table = self.table().await?;
        for migration in self.pending().await? {
            let tx = self.repo.begin().await?;
            for statement in migration.up_sql(self.repo.dialect()) {
                super::sql(&statement)
                    .on(&tx)
                    .execute()
                    .await
                    .map_err(|e| {
                        Error::internal(format!("{}: {}\n{statement}", migration.name, e.message()))
                    })?;
            }
            let mut record = Sql::new();
            record
                .push(&format!(
                    "INSERT INTO {table} (version, inserted_at) VALUES ("
                ))
                .push_value(Value::Text(migration.version.clone()))
                .push(", ")
                .push_value(Value::Timestamp(chrono::Utc::now()))
                .push(")");
            super::Connection::from(&tx).execute(&record).await?;
            tx.commit().await?;
            done.push(migration.name);
        }
        Ok(done)
    }

    /// Reverts the last `steps` applied migrations, returning their names.
    pub async fn rollback(&self, steps: usize) -> Result<Vec<String>> {
        let applied = self.applied().await?;
        let table = self.table().await?;
        let mut done = Vec::new();
        for version in applied.iter().rev().take(steps) {
            let migration = self
                .migrations
                .iter()
                .find(|m| &m.version == version)
                .ok_or_else(|| {
                    Error::internal(format!(
                        "migration {version} is applied but missing from the code"
                    ))
                })?;
            let tx = self.repo.begin().await?;
            for statement in migration.down_sql(self.repo.dialect()) {
                super::sql(&statement)
                    .on(&tx)
                    .execute()
                    .await
                    .map_err(|e| {
                        Error::internal(format!("{}: {}\n{statement}", migration.name, e.message()))
                    })?;
            }
            super::sql(&format!("DELETE FROM {table} WHERE version = ?"))
                .bind(version.as_str())
                .on(&tx)
                .execute()
                .await?;
            tx.commit().await?;
            done.push(migration.name.clone());
        }
        Ok(done)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn up(s: &mut Schema) {
        s.create_table("posts", |t| {
            t.string("title").not_null();
            t.integer("views").not_null().default(0);
            t.boolean("published").not_null().default(false);
            t.references("author").on_delete_cascade();
            t.timestamps();
        });
        s.add_unique_index("posts", &["title"]);
    }

    #[test]
    fn renders_create_table_per_dialect() {
        let m = Migration::new("m20261003120000_create_posts", up, |_| {});
        assert_eq!(m.version(), "20261003120000");
        let pg = m.up_sql(Dialect::Postgres);
        assert_eq!(
            pg[0],
            "CREATE TABLE \"posts\" (\n  \"id\" BIGSERIAL PRIMARY KEY,\n  \"title\" VARCHAR NOT NULL,\n  \"views\" INTEGER NOT NULL DEFAULT 0,\n  \"published\" BOOLEAN NOT NULL DEFAULT FALSE,\n  \"author_id\" BIGINT,\n  \"inserted_at\" TIMESTAMPTZ NOT NULL,\n  \"updated_at\" TIMESTAMPTZ NOT NULL,\n  FOREIGN KEY (\"author_id\") REFERENCES \"authors\"(\"id\") ON DELETE CASCADE\n)"
        );
        assert_eq!(
            pg[1],
            "CREATE UNIQUE INDEX \"posts_title_index\" ON \"posts\" (\"title\")"
        );
        let sqlite = m.up_sql(Dialect::Sqlite);
        assert!(sqlite[0].contains("\"id\" INTEGER PRIMARY KEY AUTOINCREMENT"));
        assert!(sqlite[0].contains("\"inserted_at\" TEXT NOT NULL"));
    }

    #[test]
    fn renders_literals() {
        assert_eq!(
            literal(&Value::Text("it's".into()), Dialect::Sqlite),
            "'it''s'"
        );
        assert_eq!(
            literal(&Value::Bytes(vec![1, 255]), Dialect::Sqlite),
            "X'01ff'"
        );
        assert_eq!(
            literal(&Value::Bytes(vec![1, 255]), Dialect::Postgres),
            "'\\x01ff'"
        );
    }
}