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>
impl<'u> M<'u>
sourcepub fn set_up_hook(self, hook: impl MigrationHook + 'static) -> Self
Available on crate feature from-directory
only.
pub fn set_up_hook(self, hook: impl MigrationHook + 'static) -> Self
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
.
sourcepub fn set_down_hook(self, hook: impl MigrationHook + 'static) -> Self
Available on crate feature from-directory
only.
pub fn set_down_hook(self, hook: impl MigrationHook + 'static) -> Self
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>
impl<'u> M<'u>
sourcepub const fn up(sql: &'u str) -> Self
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 theSelf::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 inup
).
- Multiple SQL commands containing
PRAGMA
are not working with theextra_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 thefrom-directory
feature of this crate.
§Example
use rusqlite_migration::M;
M::up("CREATE TABLE animals (name TEXT);");
sourcepub fn up_with_hook(sql: &'u str, hook: impl MigrationHook + 'static) -> Self
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(())
},
),
]);
sourcepub const fn down(self, sql: &'u str) -> Self
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;");
sourcepub fn down_with_hook(
self,
sql: &'u str,
hook: impl MigrationHook + 'static
) -> Self
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.
sourcepub const fn foreign_key_check(self) -> Self
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 FromIterator<M<'static>> for AsyncMigrations
Available on crate feature alpha-async-tokio-rusqlite
only.
impl FromIterator<M<'static>> for AsyncMigrations
alpha-async-tokio-rusqlite
only.source§impl<'u> FromIterator<M<'u>> for Migrations<'u>
impl<'u> FromIterator<M<'u>> for Migrations<'u>
source§impl<'u> FromIterator<M<'u>> for MigrationsBuilder<'u>
Available on crate feature from-directory
only.
impl<'u> FromIterator<M<'u>> for MigrationsBuilder<'u>
from-directory
only.