orbit-orm 0.3.0

An ORM for Rocket.rs apps, with MySQL and MariaDB, PostgreSQL and SQLite
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
use super::Dialect;
use super::column::{Column, ColumnType};
use crate::query::validate;
use crate::{Driver, Error};

/// What a foreign key does to this table's rows when the referenced row is deleted or updated.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    Cascade,
    Restrict,
    SetNull,
    SetDefault,
    NoAction,
}

impl Action {
    fn sql(self) -> &'static str {
        match self {
            Self::Cascade => "CASCADE",
            Self::Restrict => "RESTRICT",
            Self::SetNull => "SET NULL",
            Self::SetDefault => "SET DEFAULT",
            Self::NoAction => "NO ACTION",
        }
    }
}

/// A foreign key under construction. Chain `references`, `on_delete`, `on_update` and `name`.
#[derive(Debug, Clone)]
pub struct ForeignKey {
    column: String,
    name: Option<String>,
    target: Option<(String, String)>,
    on_delete: Option<Action>,
    on_update: Option<Action>,
}

impl ForeignKey {
    /// The table and column that this column points at.
    pub fn references(&mut self, table: &str, column: &str) -> &mut Self {
        self.target = Some((table.to_owned(), column.to_owned()));
        self
    }

    /// What happens when the referenced row is deleted.
    pub fn on_delete(&mut self, action: Action) -> &mut Self {
        self.on_delete = Some(action);
        self
    }

    /// What happens when the referenced key is updated.
    pub fn on_update(&mut self, action: Action) -> &mut Self {
        self.on_update = Some(action);
        self
    }

    /// Names the constraint, as the second argument of Laravel's `$table->foreign('col', 'name')`.
    /// Without it the name is `{table}_{column}_foreign`.
    pub fn name(&mut self, name: &str) -> &mut Self {
        self.name = Some(name.to_owned());
        self
    }
}

/// A plain or unique index under construction. Chain `name` to choose its name.
#[derive(Debug, Clone)]
pub struct Index {
    columns: Vec<String>,
    unique: bool,
    name: Option<String>,
}

impl Index {
    /// Names the index, as the second argument of Laravel's `$table->index(['a'], 'name')`.
    /// Without it the name is `{table}_{columns}_index`, or `{table}_{columns}_unique` for a
    /// unique index.
    pub fn name(&mut self, name: &str) -> &mut Self {
        self.name = Some(name.to_owned());
        self
    }

    /// The index's name, checked: the custom one, or the default for `table`.
    fn name_for(&self, table: &str) -> Result<String, Error> {
        match &self.name {
            Some(name) => {
                validate(name)?;
                Ok(name.clone())
            }
            None => Ok(name_of(
                table,
                &self.columns,
                if self.unique { "unique" } else { "index" },
            )),
        }
    }
}

/// Every operation of a blueprint, in call order. A column is recorded as `Column`, its index in
/// the column list, at the point it is declared, as Laravel 11+ records each column as a command.
/// `schema::create` renders the columns, then the indexes, primary keys and foreign keys inside
/// `CREATE TABLE`; `schema::table` renders every command as its own statement in call order.
#[derive(Debug, Clone)]
enum Command {
    Column(usize),
    Index(Index),
    Primary { columns: Vec<String> },
    Foreign(ForeignKey),
    RenameColumn { from: String, to: String },
    DropColumn { name: String },
    DropIndex { name: String },
    DropForeign { name: String },
}

/// The columns and commands (indexes, keys, renames, drops) of a table, in the order they were
/// added.
#[derive(Debug, Clone, Default)]
pub struct Blueprint {
    columns: Vec<Column>,
    commands: Vec<Command>,
}

impl Blueprint {
    pub(crate) fn new() -> Self {
        Self::default()
    }

    fn add(&mut self, name: &str, ty: ColumnType) -> &mut Column {
        self.commands.push(Command::Column(self.columns.len()));
        self.columns.push(Column::new(name, ty));
        self.columns.last_mut().expect("just pushed")
    }

    /// An auto-incrementing 64-bit primary key named `id`. In [`schema::table`](super::table)
    /// SQLite cannot add it, as SQLite cannot add a primary key column to an existing table.
    pub fn id(&mut self) -> &mut Column {
        self.add("id", ColumnType::Id)
    }

    /// A `VARCHAR(255)`; `TEXT` on SQLite. Change the length with `.length(n)`.
    pub fn string(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::String(255))
    }

    /// A `TEXT` column.
    pub fn text(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::Text)
    }

    /// An `INTEGER` column.
    pub fn integer(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::Integer)
    }

    /// A `BIGINT` column; `INTEGER` on SQLite, whose integers are 64-bit already.
    pub fn big_integer(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::BigInteger)
    }

    /// A boolean: `BOOLEAN` on PostgreSQL, `TINYINT(1)` elsewhere.
    pub fn boolean(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::Boolean)
    }

    /// A date and time without a time zone: `DATETIME`, or `TIMESTAMP(0)` on PostgreSQL. Set
    /// fractional seconds with `.precision(p)` and a default of the current time with
    /// `.use_current()`.
    pub fn date_time(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::DateTime(0))
    }

    /// A timestamp, as Laravel's `timestamp`: `TIMESTAMP` on MySQL, `TIMESTAMP(0) WITHOUT TIME
    /// ZONE` on PostgreSQL, `DATETIME` on SQLite. Set fractional seconds with `.precision(p)` and
    /// a default of the current time with `.use_current()`.
    ///
    /// On MySQL and MariaDB with `explicit_defaults_for_timestamp` off (the MariaDB default
    /// before 10.10), the first `TIMESTAMP` column of a table that is `NOT NULL` and has no
    /// default gets `DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP` from the server.
    /// Laravel's columns get the same. Add `.nullable()` or a default to avoid it.
    pub fn timestamp(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::Timestamp(0))
    }

    /// A column of raw bytes, as Laravel's `binary`: `BLOB`, or `BYTEA` on PostgreSQL.
    pub fn binary(&mut self, name: &str) -> &mut Column {
        self.add(name, ColumnType::Binary)
    }

    /// Nullable `created_at` and `updated_at` columns.
    pub fn timestamps(&mut self) {
        self.date_time("created_at").nullable();
        self.date_time("updated_at").nullable();
    }

    /// A unique constraint over `columns`, named `{table}_{columns}_unique` unless `.name()`
    /// gives another name.
    pub fn unique<I, S>(&mut self, columns: I) -> &mut Index
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.add_index(columns, true)
    }

    /// A plain index over `columns`, named `{table}_{columns}_index` unless `.name()` gives
    /// another name.
    pub fn index<I, S>(&mut self, columns: I) -> &mut Index
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.add_index(columns, false)
    }

    fn add_index<I, S>(&mut self, columns: I, unique: bool) -> &mut Index
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.commands.push(Command::Index(Index {
            columns: collect(columns),
            unique,
            name: None,
        }));
        match self.commands.last_mut() {
            Some(Command::Index(index)) => index,
            _ => unreachable!("just pushed an index"),
        }
    }

    /// A primary key over `columns`, as Laravel's `$table->primary(['a', 'b'])`: the table
    /// constraint `PRIMARY KEY (a, b)`. For a key of one column, `.primary()` on the column does
    /// the same. In [`schema::table`](super::table) SQLite cannot add it: it is
    /// [`Error::Unsupported`] there.
    pub fn primary<I, S>(&mut self, columns: I)
    where
        I: IntoIterator<Item = S>,
        S: AsRef<str>,
    {
        self.commands.push(Command::Primary {
            columns: collect(columns),
        });
    }

    /// A foreign key on `column`, named `{table}_{column}_foreign` unless `.name()` gives another
    /// name. In [`schema::table`](super::table) SQLite renders nothing, as SQLite cannot add a
    /// constraint to an existing table.
    pub fn foreign(&mut self, column: &str) -> &mut ForeignKey {
        self.commands.push(Command::Foreign(ForeignKey {
            column: column.to_owned(),
            name: None,
            target: None,
            on_delete: None,
            on_update: None,
        }));
        match self.commands.last_mut() {
            Some(Command::Foreign(fk)) => fk,
            _ => unreachable!("just pushed a foreign key"),
        }
    }

    /// Renames the column `from` to `to`: `ALTER TABLE ... RENAME COLUMN`. Only in
    /// [`schema::table`](super::table).
    ///
    /// `RENAME COLUMN` needs MySQL 8.0.3 or later, or MariaDB 10.5.2 or later. On older servers
    /// Laravel falls back to `CHANGE old new <definition>`; Orbit does not, and the server
    /// reports a syntax error.
    pub fn rename_column(&mut self, from: &str, to: &str) {
        self.commands.push(Command::RenameColumn {
            from: from.to_owned(),
            to: to.to_owned(),
        });
    }

    /// Drops the column `name`: `ALTER TABLE ... DROP COLUMN`. Only in
    /// [`schema::table`](super::table). SQLite needs version 3.35 or later.
    pub fn drop_column(&mut self, name: &str) {
        self.commands.push(Command::DropColumn {
            name: name.to_owned(),
        });
    }

    /// Drops the index `name`, as Laravel's `dropIndex('name')`. Only in
    /// [`schema::table`](super::table).
    ///
    /// On MySQL it drops a unique index too. On SQLite it drops a unique only when `unique` added
    /// it in `schema::table`: a unique declared in [`schema::create`](super::create) is an inline
    /// constraint there and cannot be dropped this way. On PostgreSQL `unique` always adds a
    /// constraint, and `DROP INDEX` cannot drop the index of a constraint. Orbit has no
    /// `drop_unique` (Laravel's `dropUnique`).
    pub fn drop_index(&mut self, name: &str) {
        self.commands.push(Command::DropIndex {
            name: name.to_owned(),
        });
    }

    /// Drops the foreign key `name`, as Laravel's `dropForeign('name')`. Only in
    /// [`schema::table`](super::table). SQLite renders nothing, as it cannot drop a constraint
    /// from an existing table and `foreign` added none there.
    pub fn drop_foreign(&mut self, name: &str) {
        self.commands.push(Command::DropForeign {
            name: name.to_owned(),
        });
    }

    /// Renders `CREATE TABLE`, and the separate `CREATE INDEX` statements of PostgreSQL and
    /// SQLite. With `if_not_exists`, both take `IF NOT EXISTS`.
    pub(crate) fn render_create(
        &self,
        driver: Driver,
        dialect: Dialect,
        table: &str,
        if_not_exists: bool,
    ) -> Result<Vec<String>, Error> {
        validate(table)?;
        let unsupported = |operation| Error::Unsupported {
            operation,
            driver: driver.name(),
        };
        let q = |name: &str| driver.quote(name);
        let exists = if if_not_exists { "IF NOT EXISTS " } else { "" };

        let mut parts = Vec::new();
        for column in &self.columns {
            if column.change {
                return Err(unsupported("changing a column in create"));
            }
            parts.push(column.render(driver, dialect)?);
        }
        let mut after = Vec::new();
        for command in &self.commands {
            match command {
                Command::Column(_) => {}
                Command::Index(index) => {
                    let columns = column_list(driver, &index.columns)?;
                    let name = index.name_for(table)?;
                    if index.unique {
                        parts.push(format!("CONSTRAINT {} UNIQUE ({columns})", q(&name)));
                    } else {
                        match dialect {
                            Dialect::MySql => parts.push(format!("INDEX {} ({columns})", q(&name))),
                            _ => after.push(format!(
                                "CREATE INDEX {exists}{} ON {} ({columns})",
                                q(&name),
                                q(table)
                            )),
                        }
                    }
                }
                Command::Primary { columns } => {
                    parts.push(format!("PRIMARY KEY ({})", column_list(driver, columns)?));
                }
                Command::Foreign(_) => {}
                Command::RenameColumn { .. } => {
                    return Err(unsupported("renaming a column in create"));
                }
                Command::DropColumn { .. } => {
                    return Err(unsupported("dropping a column in create"));
                }
                Command::DropIndex { .. } => {
                    return Err(unsupported("dropping an index in create"));
                }
                Command::DropForeign { .. } => {
                    return Err(unsupported("dropping a foreign key in create"));
                }
            }
        }
        // Foreign keys follow the indexes inside CREATE TABLE.
        for command in &self.commands {
            if let Command::Foreign(fk) = command {
                parts.push(fk.render(driver, table)?);
            }
        }
        let mut out = vec![format!(
            "CREATE TABLE {exists}{} ({})",
            q(table),
            parts.join(", ")
        )];
        out.extend(after);
        Ok(out)
    }

    /// Renders the changes to an existing table, one statement per operation, in call order as
    /// Laravel 11+ does: an added or changed column renders where it was declared, among the
    /// other commands. A foreign key and `drop_foreign` render nothing on SQLite.
    pub(crate) fn render_alter(
        &self,
        driver: Driver,
        dialect: Dialect,
        table: &str,
    ) -> Result<Vec<String>, Error> {
        validate(table)?;
        let unsupported = |operation| Error::Unsupported {
            operation,
            driver: driver.name(),
        };
        let q = |name: &str| driver.quote(name);
        let alter = format!("ALTER TABLE {}", q(table));

        let mut out = Vec::new();
        for command in &self.commands {
            match command {
                Command::Column(i) => {
                    let column = &self.columns[*i];
                    if column.change {
                        if dialect == Dialect::Sqlite {
                            return Err(unsupported("changing a column"));
                        }
                        if column.ty == ColumnType::Id {
                            return Err(unsupported("changing an id column"));
                        }
                        if column.primary {
                            return Err(unsupported("changing a column into a primary key"));
                        }
                        out.push(match dialect {
                            Dialect::Postgres => {
                                format!("{alter} {}", column.render_change_postgres(driver)?)
                            }
                            _ => {
                                format!("{alter} MODIFY COLUMN {}", column.render(driver, dialect)?)
                            }
                        });
                    } else {
                        if (column.ty == ColumnType::Id || column.primary)
                            && dialect == Dialect::Sqlite
                        {
                            return Err(unsupported("adding a primary key column"));
                        }
                        out.push(format!(
                            "{alter} ADD COLUMN {}",
                            column.render(driver, dialect)?
                        ));
                    }
                }
                Command::Index(index) => {
                    let columns = column_list(driver, &index.columns)?;
                    let name = q(&index.name_for(table)?);
                    out.push(match (dialect, index.unique) {
                        (Dialect::MySql, false) => format!("{alter} ADD INDEX {name} ({columns})"),
                        (Dialect::MySql, true) => format!("{alter} ADD UNIQUE {name} ({columns})"),
                        (Dialect::Postgres, true) => {
                            format!("{alter} ADD CONSTRAINT {name} UNIQUE ({columns})")
                        }
                        (Dialect::Sqlite, true) => {
                            format!("CREATE UNIQUE INDEX {name} ON {} ({columns})", q(table))
                        }
                        (_, false) => format!("CREATE INDEX {name} ON {} ({columns})", q(table)),
                    });
                }
                Command::Primary { columns } => {
                    let columns = column_list(driver, columns)?;
                    if dialect == Dialect::Sqlite {
                        return Err(unsupported("adding a primary key"));
                    }
                    out.push(format!("{alter} ADD PRIMARY KEY ({columns})"));
                }
                Command::Foreign(fk) => {
                    // Rendered on SQLite too, so a missing target or a bad name is still an error.
                    let constraint = fk.render(driver, table)?;
                    if dialect != Dialect::Sqlite {
                        out.push(format!("{alter} ADD {constraint}"));
                    }
                }
                Command::RenameColumn { from, to } => {
                    validate(from)?;
                    validate(to)?;
                    out.push(format!("{alter} RENAME COLUMN {} TO {}", q(from), q(to)));
                }
                Command::DropColumn { name } => {
                    validate(name)?;
                    out.push(format!("{alter} DROP COLUMN {}", q(name)));
                }
                Command::DropIndex { name } => {
                    validate(name)?;
                    out.push(match dialect {
                        Dialect::MySql => format!("{alter} DROP INDEX {}", q(name)),
                        _ => format!("DROP INDEX {}", q(name)),
                    });
                }
                Command::DropForeign { name } => {
                    validate(name)?;
                    match dialect {
                        Dialect::MySql => out.push(format!("{alter} DROP FOREIGN KEY {}", q(name))),
                        Dialect::Postgres => {
                            out.push(format!("{alter} DROP CONSTRAINT {}", q(name)))
                        }
                        Dialect::Sqlite => {}
                    }
                }
            }
        }
        Ok(out)
    }
}

impl ForeignKey {
    /// The `CONSTRAINT ... FOREIGN KEY ... REFERENCES ...` clause, with its custom name or the
    /// default one for `table`.
    fn render(&self, driver: Driver, table: &str) -> Result<String, Error> {
        let q = |name: &str| driver.quote(name);
        validate(&self.column)?;
        let Some((ref_table, ref_column)) = &self.target else {
            return Err(Error::Unsupported {
                operation: "a foreign key without references()",
                driver: driver.name(),
            });
        };
        validate(ref_table)?;
        validate(ref_column)?;
        let name = match &self.name {
            Some(name) => {
                validate(name)?;
                name.clone()
            }
            None => name_of(table, std::slice::from_ref(&self.column), "foreign"),
        };
        let mut sql = format!(
            "CONSTRAINT {} FOREIGN KEY ({}) REFERENCES {} ({})",
            q(&name),
            q(&self.column),
            q(ref_table),
            q(ref_column)
        );
        if let Some(a) = self.on_delete {
            sql.push_str(&format!(" ON DELETE {}", a.sql()));
        }
        if let Some(a) = self.on_update {
            sql.push_str(&format!(" ON UPDATE {}", a.sql()));
        }
        Ok(sql)
    }
}

/// The default name of an index or constraint: `{table}_{columns}_{suffix}`, as Laravel names it.
fn name_of(table: &str, columns: &[String], suffix: &str) -> String {
    format!("{table}_{}_{suffix}", columns.join("_"))
}

/// The quoted, comma-separated column list of an index, each name checked.
fn column_list(driver: Driver, columns: &[String]) -> Result<String, Error> {
    for c in columns {
        validate(c)?;
    }
    Ok(columns
        .iter()
        .map(|c| driver.quote(c))
        .collect::<Vec<_>>()
        .join(", "))
}

fn collect<I, S>(columns: I) -> Vec<String>
where
    I: IntoIterator<Item = S>,
    S: AsRef<str>,
{
    columns.into_iter().map(|c| c.as_ref().to_owned()).collect()
}