Struct rusqlite_migration::M

source ·
pub struct M<'u> { /* private fields */ }
Expand description

One migration.

A migration can contain up- and down-hooks, which are incomparable closures. To signify M equality we compare if two migrations either don’t have hooks defined (they are set to None) or if the closure memory addresses are the same.

Implementations§

source§

impl<'u> M<'u>

source

pub fn set_up_hook(self, hook: impl MigrationHook + 'static) -> Self

Available on crate feature from-directory only.

Replace the up_hook in the given migration with the provided one.

§Warning

Use M::up_with_hook instead if you’re creating a new migration. This method is meant for editing existing transactions when using the MigrationsBuilder.

source

pub fn set_down_hook(self, hook: impl MigrationHook + 'static) -> Self

Available on crate feature from-directory only.

Replace the down_hook in the given migration with the provided one.

§Warning

Use M::down_with_hook instead if you’re creating a new migration. This method is meant for editing existing transactions when using the MigrationsBuilder.

source§

impl<'u> M<'u>

source

pub const fn up(sql: &'u str) -> Self

Create a schema update. The SQL command will be executed only when the migration has not been executed on the underlying database.

§Please note
§PRAGMA statements

PRAGMA statements are discouraged here. They are often better applied outside of migrations, because:

  • a PRAGMA executed this way may not be applied consistently. For instance:
    • foreign_keys needs to be executed for each sqlite connection, not just once per database as a migration. Please see the Self::foreign_key_check() method to maintain foreign key constraints during migrations instead.
    • journal_mode has no effect when executed inside transactions (that will be the case for the SQL written in up).
  • Multiple SQL commands containing PRAGMA are not working with the extra_check feature of rusqlite.
§Misc.
  • SQL commands should end with a “;”.
  • You can use the include_str! macro to include whole files or opt for the from-directory feature of this crate.
§Example
use rusqlite_migration::M;

M::up("CREATE TABLE animals (name TEXT);");
source

pub const fn comment(self, comment: &'u str) -> Self

Add a comment to the schema update

source

pub fn up_with_hook(sql: &'u str, hook: impl MigrationHook + 'static) -> Self

Create a schema update running additional Rust code. The SQL command will be executed only when the migration has not been executed on the underlying database. The hook code will be executed after the SQL command executed successfully.

See Self::up() for additional notes.

§Example
use rusqlite_migration::{M, Migrations};
use rusqlite::Transaction;

let migrations = Migrations::new(vec![
    // This table will later be filled with some novel content
    M::up("CREATE TABLE novels (text TEXT);"),
    M::up_with_hook(
        "ALTER TABLE novels ADD compressed TEXT;",
        |tx: &Transaction| {
            let mut stmt = tx.prepare("SELECT rowid, text FROM novels")?;
            let rows = stmt
                .query_map([], |row| {
                    Ok((row.get_unwrap::<_, i64>(0), row.get_unwrap::<_, String>(1)))
                })?;

            for row in rows {
                let row = row?;
                let rowid = row.0;
                let text = row.1;
                // Replace with a proper compression strategy ...
                let compressed = &text[..text.len() / 2];
                tx.execute(
                    "UPDATE novels SET compressed = ?1 WHERE rowid = ?2;",
                    rusqlite::params![compressed, rowid],
                )?;
            }

            Ok(())
        },
    ),
]);
source

pub const fn down(self, sql: &'u str) -> Self

Define a down-migration. This SQL statement should exactly reverse the changes performed in up().

A call to this method is not required.

§Example
use rusqlite_migration::M;

M::up("CREATE TABLE animals (name TEXT);")
    .down("DROP TABLE animals;");
source

pub fn down_with_hook( self, sql: &'u str, hook: impl MigrationHook + 'static ) -> Self

Define a down-migration running additional Rust code. This SQL statement should exactly reverse the changes performed in Self::up_with_hook(). hook will run before the SQL statement is executed.

source

pub const fn foreign_key_check(self) -> Self

Enable an automatic validation of foreign keys before the migration transaction is closed. This works both for upward and downward migrations.

This will cause the migration to fail if PRAGMA foreign_key_check returns any foreign key check violations.

§Turning PRAGMA foreign_keys ON and OFF

By default with SQLite, foreign key constraints are not checked (that may change in the future). If you wish to check this, you need to manually turn PRAGMA foreign_keys ON. However, the documentation for “Making Other Kinds Of Table Schema Changes” suggests turning this OFF before running the migrations.

This if you want to enforce foreign key checks, it seems best to disable it first (in case future versions of SQLite enable it by default), then run the migrations, then enable it, as in the example below.

Please make sure you do not call PRAGMA foreign_keys from inside the migrations, as it would be a no-op (each migration is run inside a transaction).

§Example
use rusqlite::{params, Connection};
use rusqlite_migration::{Migrations, M};

let migrations = Migrations::new(vec![
    M::up("CREATE TABLE animals (name TEXT);")
        .foreign_key_check(), // Let’s pretend this is necessary here
]);

let mut conn = Connection::open_in_memory().unwrap();

// Turn foreign key constraints off for the duration of the migration
conn.pragma_update(None, "foreign_keys", &"OFF").unwrap();

migrations.to_latest(&mut conn).unwrap();

// Restore foreign key constraints checks
conn.pragma_update(None, "foreign_keys", &"ON").unwrap();

conn.execute("INSERT INTO animals (name) VALUES (?1)", params!["dog"])
    .unwrap();

Trait Implementations§

source§

impl<'u> Clone for M<'u>

source§

fn clone(&self) -> M<'u>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'u> Debug for M<'u>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl FromIterator<M<'static>> for AsyncMigrations

Available on crate feature alpha-async-tokio-rusqlite only.
source§

fn from_iter<T: IntoIterator<Item = M<'static>>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<'u> FromIterator<M<'u>> for Migrations<'u>

source§

fn from_iter<T: IntoIterator<Item = M<'u>>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<'u> FromIterator<M<'u>> for MigrationsBuilder<'u>

Available on crate feature from-directory only.
source§

fn from_iter<T: IntoIterator<Item = M<'u>>>(iter: T) -> Self

Creates a value from an iterator. Read more
source§

impl<'u> PartialEq for M<'u>

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<'u> Eq for M<'u>

Auto Trait Implementations§

§

impl<'u> Freeze for M<'u>

§

impl<'u> !RefUnwindSafe for M<'u>

§

impl<'u> Send for M<'u>

§

impl<'u> Sync for M<'u>

§

impl<'u> Unpin for M<'u>

§

impl<'u> !UnwindSafe for M<'u>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.