### Setup Database Source: https://github.com/rust-db/refinery/blob/main/refinery_cli/README.md Setup your database type and access credentials with the 'setup' command. ```sh $ refinery setup ``` -------------------------------- ### PostgreSQL-specific TLS setting example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example of setting TLS for PostgreSQL. ```rust let config = config.set_use_tls(true); ``` -------------------------------- ### report() Method Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to use the report() method to get the migration report. ```rust if let Some(report) = error.report() { println!("Applied {} migrations before error", report.applied_migrations().len()); } ``` -------------------------------- ### SQLite connection parameters example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example of setting connection parameters for SQLite. ```rust let config = Config::new(ConfigDbType::Sqlite) .set_db_path("/var/db/app.db"); ``` -------------------------------- ### load_sql_migrations Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/utilities.md Example demonstrating how to use `load_sql_migrations` to load SQL migrations from a directory. ```rust use refinery::load_sql_migrations; fn main() -> Result<(), Box> { let migrations = load_sql_migrations("./migrations")?; for migration in migrations { println!("Found: {} (v{})", migration.name(), migration.version()); } Ok(()) } ``` -------------------------------- ### TOML Configuration Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example TOML configuration for database connection details. ```toml [main] db_type = "postgres" db_host = "localhost" db_port = "5432" db_user = "myuser" db_pass = "mypass" db_name = "mydatabase" use_tls = false ``` -------------------------------- ### MSSQL-specific trust_cert example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example of setting trust_cert for MSSQL. ```rust let mut config = config; config.set_trust_cert(); ``` -------------------------------- ### CLI Example Source: https://github.com/rust-db/refinery/blob/main/README.md Example of how to use the Refinery CLI to run migrations. ```bash export DATABASE_URL="postgres://postgres:secret@localhost:5432/your-db" pushd migrations # Runs ./src/V1__*.rs or ./src/V1__*.sql refinery migrate -e DATABASE_URL -p ./src -t 1 popd ``` -------------------------------- ### Network database connection parameters example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example of setting connection parameters for network databases. ```rust let config = Config::new(ConfigDbType::Postgres) .set_db_host("localhost") .set_db_port("5432") .set_db_user("postgres") .set_db_pass("secret") .set_db_name("mydb"); ``` -------------------------------- ### Example of using the name accessor Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Migration.md Shows how to get and print the name of a migration. ```rust let name = migration.name(); println!("Running migration: {}", name); ``` -------------------------------- ### Good Code Example Convention Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example illustrating the convention for code examples, focusing on usage patterns. ```rust // ✓ Good: Shows how to use let runner = embedded::migrations::runner().set_grouped(true); // ✗ Avoid: Test code (assertions, test framework) assert_eq!(runner.get_migrations().len(), 3); ``` -------------------------------- ### Environment Variable Configuration Examples Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Examples of setting the DATABASE_URL environment variable for different database types. ```bash # PostgreSQL export DATABASE_URL="postgres://user:pass@localhost:5432/mydb" # MySQL export DATABASE_URL="mysql://user:pass@localhost:3306/mydb" # SQLite export DATABASE_URL="sqlite:///path/to/db.db" # MSSQL export DATABASE_URL="mssql://user:pass@localhost:1433/master" ``` -------------------------------- ### Complete Example: Dynamic Migration Runner Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/utilities.md A comprehensive example demonstrating how to load SQL migrations from the filesystem and run them using the Runner. ```rust use refinery::{load_sql_migrations, Runner, Migration}; use rusqlite::Connection; fn main() -> Result<(), Box> { // Load migrations from filesystem let migrations = load_sql_migrations("./migrations")?; println!("Loaded {} migrations:", migrations.len()); for m in &migrations { println!(" - {} (v{})", m.name(), m.version()); } // Create runner let runner = Runner::new(&migrations); // Apply migrations let mut conn = Connection::open("app.db")?; let report = runner.run(&mut conn)?; println!("Applied {} migrations", report.applied_migrations().len()); Ok(()) } ``` -------------------------------- ### RepeatedVersion Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to recover from a RepeatedVersion error. ```rust match error.kind() { Kind::RepeatedVersion(migration) => { eprintln!("Duplicate version: {} (v{})", migration.name(), migration.version()); eprintln!("Each migration must have unique version"); } _ => {} } ``` -------------------------------- ### MissingVersion Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to match and recover from a MissingVersion error. ```rust match error.kind() { Kind::MissingVersion(migration) => { eprintln!("Applied migration not found: {} (v{})", migration.name(), migration.version()); eprintln!("Option 1: Recreate the migration file"); eprintln!("Option 2: Use set_abort_missing(false) to allow"); } _ => {} } let runner = runner.set_abort_missing(false); ``` -------------------------------- ### find_migration_files Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/utilities.md Example demonstrating how to use `find_migration_files` to discover migration files, filtering by type. ```rust use refinery::{find_migration_files, MigrationType}; fn main() -> Result<(), Box> { // Find all migration files let all_files: Vec<_> = find_migration_files("./migrations", MigrationType::All)? .collect(); println!("Found {} migration files", all_files.len()); // Find SQL only let sql_files: Vec<_> = find_migration_files("./migrations", MigrationType::Sql)? .collect(); println!("Found {} SQL migrations", sql_files.len()); Ok(()) } ``` -------------------------------- ### Configuration Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example of configuring Refinery using environment variables and setting TLS usage. ```rust use refinery::config::Config; let config = Config::from_env_var("DATABASE_URL")? .set_use_tls(true); ``` -------------------------------- ### Library Example Source: https://github.com/rust-db/refinery/blob/main/README.md Example of how to use Refinery in a Rust library to embed migrations. ```rust use rusqlite::Connection; mod embedded { use refinery::embed_migrations; embed_migrations!("./tests/sql_migrations"); } fn main() { let mut conn = Connection::open_in_memory().unwrap(); embedded::migrations::runner().run(&mut conn).unwrap(); } ``` -------------------------------- ### RepeatedVersion Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example directory structure showing a RepeatedVersion error. ```rust migrations/ V1__initial.sql V1__setup.sql // ← Duplicate version! V2__users.sql ``` -------------------------------- ### InvalidVersion Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to recover from an InvalidVersion error. ```rust match error.kind() { Kind::InvalidVersion => { eprintln!("Migration version must be a valid number"); eprintln!("Examples: V1__init.sql, V100__feature.sql"); } _ => {} } ``` -------------------------------- ### Deadpool Example Source: https://github.com/rust-db/refinery/blob/main/README.md Example of using Refinery with Deadpool for async database connections. ```rust let mut conn = pool.get().await?; let client = conn.deref_mut().deref_mut(); let report = embedded::migrations::runner().run_async(client).await?; ``` -------------------------------- ### TOML Configuration File Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/API_INDEX.md Example of a TOML configuration file for Refinery. ```toml # refinery.toml [main] db_type = "postgres" db_host = "localhost" db_port = "5432" db_user = "myuser" db_pass = "mypass" db_name = "mydb" use_tls = false ``` -------------------------------- ### migrate Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the migrate method. ```rust let report = client.migrate( &migrations, true, // abort_divergent true, // abort_missing false, // grouped Target::Latest, "refinery_schema_history" )?; ``` -------------------------------- ### bb8 Example Source: https://github.com/rust-db/refinery/blob/main/README.md Example of using Refinery with bb8 for async database connections. ```rust let mut client = pool.dedicated_connection().await?; let report = embedded::migrations::runner().run_async(&mut client).await?; ``` -------------------------------- ### PostgreSQL Asynchronous Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using `Runner::run_async()` with a `tokio_postgres::Client`. ```rust use tokio_postgres::Client; let (client, connection) = tokio_postgres::connect("postgresql://...", tokio_postgres::NoTls).await?; tokio::spawn(async move { connection.await }); runner.run_async(&mut client).await?; ``` -------------------------------- ### PostgreSQL Synchronous Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using `Runner::run()` with a `postgres::Client`. ```rust use postgres::Client; use refinery::Runner; let mut client = Client::connect("postgresql://...", postgres::NoTls)?; runner.run(&mut client)?; ``` -------------------------------- ### DivergentVersion Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to match and recover from a DivergentVersion error. ```rust match error.kind() { Kind::DivergentVersion(applied, filesystem) => { eprintln!("Migration '{}' was modified after application", applied.name()); eprintln!("Applied checksum: {}", applied.checksum()); eprintln!("Filesystem checksum: {}", filesystem.checksum()); eprintln!("Option 1: Restore original migration file"); eprintln!("Option 2: Use set_abort_divergent(false) to allow changes"); } _ => {} } // Allow divergent migrations if intentional: let runner = runner.set_abort_divergent(false); ``` -------------------------------- ### PostgreSQL Asynchronous Driver Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using the asynchronous PostgreSQL driver with `refinery`. ```toml [dependencies] refinery = { version = "0.9", features = ["tokio-postgres"] } tokio-postgres = "0.7" tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Versioned Migration Naming Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example file names for versioned migrations. ```text V1__initial.sql V2__add_users.rs V3__create_posts.sql ``` -------------------------------- ### MySQL Synchronous Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using `Runner::run()` with a `mysql::Connection`. ```rust use mysql::Connection; let mut conn = Connection::new("mysql://...")?; runner.run(&mut conn)?; ``` -------------------------------- ### Set Target Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Runner.md Example of setting the target to a specific version. ```rust use refinery::Target; let runner = runner.set_target(Target::Version(5)); ``` -------------------------------- ### MySQL Asynchronous Driver Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using the asynchronous MySQL driver with `refinery`. ```toml [dependencies] refinery = { version = "0.9", features = ["mysql_async"] } mysql_async = "0.30" tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### migrate_async Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the asynchronous migrate method. ```rust let report = client.migrate( &migrations, true, true, false, Target::Latest, "refinery_schema_history" ).await?; ``` -------------------------------- ### InvalidMigrationPath Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Examples demonstrating scenarios that lead to an InvalidMigrationPath error. ```rust // These cause InvalidMigrationPath: embed_migrations!("./nonexistent"); // Path doesn't exist embed_migrations!("/root/migrations"); // Permission denied ``` -------------------------------- ### MySQL Asynchronous Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using `Runner::run_async()` with `mysql_async` connections. ```rust let mut conn = mysql_async::Conn::from_url("mysql://...")?; runner.run_async(&mut conn).await?; ``` -------------------------------- ### Method/Function Documentation Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example of how method/function documentation is structured, including parameters, return types, and descriptions. ```rust pub fn method_name(param: Type) -> ReturnType ``` -------------------------------- ### Comparison Traits Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Migration.md Example demonstrating the sorting of migrations using comparison traits. ```rust let mut migrations = vec![ Migration::unapplied("V3__third", "")?, Migration::unapplied("V1__first", "")?, Migration::unapplied("V2__second", "")?, ]; migrations.sort(); // Now ordered: V1__first, V2__second, V3__third ``` -------------------------------- ### Runner set_target example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Controls which migrations to apply. ```rust let runner = runner.set_target(Target::Version(5)); ``` -------------------------------- ### Example of using the checksum accessor Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Migration.md Shows how to retrieve and print the checksum of a migration. ```rust let checksum = migration.checksum(); println!("Migration checksum: {}", checksum); ``` -------------------------------- ### parse_migration_name Example Usage Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/utilities.md An example demonstrating how to use the parse_migration_name function and print its results. ```rust use refinery::parse_migration_name; fn main() -> Result<(), Box> { let (prefix, version, name) = parse_migration_name("V1__initial_schema")?; println!("Prefix: {:?}", prefix); // Versioned println!("Version: {}", version); // 1 println!("Name: {}", name); // initial_schema Ok(()) } ``` -------------------------------- ### TOML Example Config File Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML configuration file for Refinery. ```toml [main] db_type = "postgres" db_host = "localhost" db_port = "5432" db_user = "myuser" db_pass = "mypass" db_name = "mydb" ``` -------------------------------- ### MySQL Synchronous Driver Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using the synchronous MySQL driver with `refinery`. ```toml [dependencies] refinery = { version = "0.9", features = ["mysql"] } mysql = "24" ``` -------------------------------- ### InvalidMigrationFile Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to match and recover from an InvalidMigrationFile error. ```rust match error.kind() { Kind::InvalidMigrationFile(path, io_error) => { eprintln!("Cannot read migration file: {}", path.display()); eprintln!("Error: {}", io_error); // Check file encoding, permissions } _ => {} } ``` -------------------------------- ### PostgreSQL Synchronous Driver Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using the synchronous PostgreSQL driver with `refinery`. ```toml [dependencies] refinery = { version = "0.9", features = ["postgres"] } postgres = "0.19" ``` -------------------------------- ### InvalidMigrationPath Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to match and recover from an InvalidMigrationPath error. ```rust match error.kind() { Kind::InvalidMigrationPath(path, io_error) => { eprintln!("Cannot access migration directory: {}", path.display()); eprintln!("Reason: {}", io_error); // Check permissions, verify path exists } _ => {} } ``` -------------------------------- ### AsyncMigrate Usage Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/types.md Example of how to use the `get_applied_migrations` method from the `AsyncMigrate` trait. ```rust use refinery::AsyncMigrate; let migrations = client.get_applied_migrations("refinery_schema_history").await?; ``` -------------------------------- ### SQLite Synchronous Driver Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using the synchronous SQLite driver with `refinery`. ```toml [dependencies] refinery = { version = "0.9", features = ["rusqlite"] } rusqlite = { version = "0.29", features = ["bundled"] } ``` -------------------------------- ### SQL Migration Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/embed_migrations.md An example of a migration file written in SQL, demonstrating table creation. ```sql -- V1__initial_schema.sql CREATE TABLE users ( id INT PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ); CREATE TABLE posts ( id INT PRIMARY KEY AUTO_INCREMENT, user_id INT NOT NULL, title VARCHAR(500), body TEXT, FOREIGN KEY (user_id) REFERENCES users(id) ); ``` -------------------------------- ### Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Runner.md Example of creating a Runner instance using embedded migrations. ```rust use refinery::embed_migrations; use refinery::Migration; mod embedded { use refinery::embed_migrations; embed_migrations!("./migrations"); } let runner = embedded::migrations::runner(); ``` -------------------------------- ### Example of using the version accessor Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Migration.md Demonstrates how to retrieve and conditionally print the version of a migration. ```rust let version = migration.version(); if version > 10 { println!("Recent migration: v{}", version); } ``` -------------------------------- ### Quick Start Feature Combinations Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Recommended Refinery feature combinations for quick start scenarios. ```toml # For embedded migrations with PostgreSQL refinery = { version = "0.9", features = ["postgres"] } # For embedded migrations with async PostgreSQL refinery = { version = "0.9", features = ["tokio-postgres"] } # For embedded migrations with SQLite (best for dev) refinery = { version = "0.9", features = ["rusqlite"] } ``` -------------------------------- ### SQLite Synchronous Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example of using `Runner::run()` with a `rusqlite::Connection`. ```rust use rusqlite::Connection; let mut conn = Connection::open("app.db")?; runner.run(&mut conn)?; ``` -------------------------------- ### Nested Migration Directories Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example directory structure for migrations organized in nested subdirectories. ```text migrations/ postgres/ V1__initial.sql shared/ V2__users.sql ``` -------------------------------- ### Method Signature Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example of a full method signature with type parameters and bounds. ```rust pub fn run(&self, connection: &mut C) -> Result where C: Migrate, ``` -------------------------------- ### Set Grouped Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Runner.md Example of setting migrations to run in a single transaction. ```rust let runner = runner.set_grouped(true); ``` -------------------------------- ### NixOs Installation Source: https://github.com/rust-db/refinery/blob/main/refinery_cli/README.md Install refinery via the refinery-cli package for Nix users. ```sh $ nix-env -iA refinery-cli ``` -------------------------------- ### Serde Example Usage Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Rust code example demonstrating serialization of a Migration struct using Serde and serde_json. ```rust use serde_json; let migration = Migration::unapplied("V1__test", "SELECT 1")?; let json = serde_json::to_string(&migration)?; ``` -------------------------------- ### Debian/Ubuntu Installation Source: https://github.com/rust-db/refinery/blob/main/refinery_cli/README.md Install refinery using a binary .deb file for Debian/Ubuntu systems. ```sh $ curl -LO https://github.com/rust-db/refinery/releases/download/0.8.4/refinery_0.8.4_amd64.deb $ sudo dpkg -i refinery_0.8.4_amd64.deb ``` -------------------------------- ### kind() Method Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to use the kind() method to get the error kind. ```rust match error.kind() { Kind::InvalidName => println!("Invalid migration name"), Kind::Connection(msg, _) => println!("Database error: {}", msg), _ => println!("Other error"), } ``` -------------------------------- ### Migrate Trait Usage Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/types.md Example of using the `Migrate` trait to get applied migrations. ```rust use refinery::Migrate; use rusqlite::Connection; let mut conn = Connection::open(":memory:")?; let migrations = conn.get_applied_migrations("refinery_schema_history")?; ``` -------------------------------- ### Set Migration Table Name Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Runner.md Example of setting a custom migration table name. ```rust let mut runner = runner; runner.set_migration_table_name("my_migrations"); ``` -------------------------------- ### Get applied migrations Source: https://github.com/rust-db/refinery/blob/main/_autodocs/API_INDEX.md Examples of querying the runner to retrieve a list of all applied migrations or just the last applied migration. ```rust let applied = runner.get_applied_migrations(&mut conn)?; let last = runner.get_last_applied_migration(&mut conn)?; ``` -------------------------------- ### ConfigError Examples Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Examples demonstrating how ConfigError can be triggered by invalid URL schemes, missing environment variables, or invalid SSL modes. ```rust // Invalid URL scheme Config::from_str("http://localhost/db")? // Error: "Unsupported database" // Missing environment variable Config::from_env_var("MISSING_VAR")? // Error: "Couldn't find MISSING_VAR environment variable" // Invalid PostgreSQL SSL mode Url::parse("postgres://localhost/db?sslmode=maybe")? // Error: "Invalid sslmode value, please use disable/require" ``` -------------------------------- ### Runner Function Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/embed_migrations.md Illustrative example of the generated `runner()` function, showing how migrations are collected and prepared. ```rust pub fn runner() -> Runner { let quoted_migrations: Vec<(&str, String)> = vec![ ("V1__initial", include_str!(...).to_string()), ("V2__add_users", V2__add_users::migration()), // ... more migrations ]; let mut migrations: Vec = Vec::new(); for module in quoted_migrations.into_iter() { migrations.push(Migration::unapplied(module.0, &module.1).unwrap()); } Runner::new(&migrations) } ``` -------------------------------- ### Tiberius Async Runner Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Rust code example demonstrating the use of `run_async` with a tiberius client. ```rust let mut client = tiberius::Client::connect(config).await?; runner.run_async(&mut client).await?; ``` -------------------------------- ### Serialization Feature Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md TOML example for enabling the 'serde' feature for serialization support. ```toml refinery = { version = "0.9", features = ["postgres", "serde"] } ``` -------------------------------- ### TLS Support Features Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md TOML examples for enabling TLS support for PostgreSQL drivers. ```toml refinery = { version = "0.9", features = ["postgres-tls"] } # or refinery = { version = "0.9", features = ["tokio-postgres-tls"] } ``` -------------------------------- ### Connection Error Examples Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Examples of Connection errors, including connection refused, SQL syntax errors, and constraint violations. ```rust // Connection refused Error: "`error connecting to database`, `connection refused`" // SQL error Error: "`error applying migration V1__initial`, `syntax error in SQL`" // Constraint violation Error: "`error applying migration V2__users`, `UNIQUE constraint failed`" ``` -------------------------------- ### Error Handling Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example of handling potential errors during migration execution and reporting partial progress. ```rust match runner.run(&mut conn) { Ok(report) => println!("Applied {} migrations", report.applied_migrations().len()), Err(error) => { eprintln!("Error: {}", error); if let Some(report) = error.report() { eprintln!("Partial progress: {} migrations applied before error", report.applied_migrations().len()); } } } ``` -------------------------------- ### get_unapplied_migrations Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the get_unapplied_migrations method. ```rust let unapplied = client.get_unapplied_migrations( &filesystem_migrations, true, // abort on divergent true, // abort on missing "refinery_schema_history" )?; ``` -------------------------------- ### Realistic Usage Code Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Placeholder for a realistic usage code example within method/function documentation. ```rust // Realistic usage code ``` -------------------------------- ### get_applied_migrations example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the get_applied_migrations method. ```rust let applied = client.get_applied_migrations("refinery_schema_history")?; println!("Applied {} migrations", applied.len()); ``` -------------------------------- ### Default Version Numbering (i32) Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example migration file names using the default i32 version numbering. ```text V1__initial.sql V2__users.sql V100__feature.sql ``` -------------------------------- ### Int8 Versions Example Filename Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example filename demonstrating the use of large version numbers with the 'int8-versions' feature. ```text V9223372036854775807__future_feature.sql ``` -------------------------------- ### get_last_applied_migration example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the get_last_applied_migration method. ```rust if let Some(last) = client.get_last_applied_migration("refinery_schema_history")? { println!("Last migration: {} (v{})", last.name(), last.version()); } ``` -------------------------------- ### InvalidName Recovery Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Example of how to recover from an InvalidName error. ```rust match error.kind() { Kind::InvalidName => { eprintln!("Fix migration filename format"); eprintln!("Required: [V|U]{{number}}_{{name}}.[sql|rs]"); } _ => {} } ``` -------------------------------- ### assert_migrations_table example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the assert_migrations_table method. ```rust use refinery::Migrate; use postgres::Client; let mut client = /* ... */; client.assert_migrations_table("refinery_schema_history")?; ``` -------------------------------- ### i64 Version Numbering (with int8-versions feature) Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example migration file names using i64 version numbering enabled by the 'int8-versions' feature. ```text V1__initial.sql V9223372036854775807__future.sql # Max i64 ``` -------------------------------- ### Config Feature Dependency Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML dependency configuration for enabling general configuration support in Refinery. ```toml refinery = { version = "0.9", features = ["config"] } ``` -------------------------------- ### Example of using the sql accessor Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Migration.md Demonstrates how to conditionally print the SQL content of an unapplied migration. ```rust if let Some(sql) = migration.sql() { println!("SQL content:\n{}", sql); } else { println!("This is an applied migration (no SQL stored)"); } ``` -------------------------------- ### Rust Migration Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/embed_migrations.md An example of a migration file written in Rust, containing a migration() function that returns a String. ```rust // V2__add_status_column.rs pub fn migration() -> String { String::from( "ALTER TABLE users ADD COLUMN status VARCHAR(50) DEFAULT 'active';" ) } ``` -------------------------------- ### Help for Migrate Command Source: https://github.com/rust-db/refinery/blob/main/refinery_cli/README.md Get more information and migration options for the 'migrate' command. ```sh $ refinery migrate --help ``` -------------------------------- ### get_last_applied_migration_async Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/traits.md Example usage of the asynchronous get_last_applied_migration method. ```rust use refinery::AsyncMigrate; let last = client.get_last_applied_migration("refinery_schema_history").await?; ``` -------------------------------- ### Int8 Versions Feature Dependency Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML dependency configuration for enabling i64 migration version support in Refinery. ```toml [dependencies] refinery = { version = "0.9", features = ["int8-versions"] } ``` -------------------------------- ### Example of using the prefix accessor Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Migration.md Shows how to use a match statement with the `prefix` accessor to differentiate between versioned and unversioned migrations. ```rust use refinery::Type; match migration.prefix() { Type::Versioned => println!("Contiguous migration"), Type::Unversioned => println!("Non-contiguous migration"), } ``` -------------------------------- ### Grep Search Tips Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Command-line examples for searching documentation content using grep. ```bash # Find error types grep -r "InvalidName" . # Find configuration options grep -r "set_grouped" . # Find examples grep -r "Example:" . | head -20 # Find method signatures grep -r "pub fn " . ``` -------------------------------- ### Cargo.toml Feature Flags Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example of how to enable features in Cargo.toml. ```toml [dependencies] refinery = { version = "0.9", features = [ "postgres", "tokio-postgres", "mysql", "mysql_async", "rusqlite", "rusqlite-bundled", "tiberius", "tiberius-config", "config", "toml", "serde", "enums", "int8-versions", ] } ``` -------------------------------- ### Building Config Programmatically Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Config.md Example of constructing a Config object programmatically with various settings. ```rust use refinery::config::{Config, ConfigDbType}; let config = Config::new(ConfigDbType::Postgres) .set_db_host("prod-db.example.com") .set_db_port("5432") .set_db_user("appuser") .set_db_pass("secret") .set_db_name("production") .set_use_tls(true); ``` -------------------------------- ### SQLite Bundled Driver Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Enabling the bundled SQLite library for the `rusqlite` driver. ```toml [dependencies] refinery = { version = "0.9", features = ["rusqlite-bundled"] } ``` -------------------------------- ### Version Support Feature Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md TOML example for enabling the 'int8-versions' feature for extended version numbering. ```toml refinery = { version = "0.9", features = ["int8-versions"] } ``` -------------------------------- ### Cargo Installation Source: https://github.com/rust-db/refinery/blob/main/refinery_cli/README.md Install refinery_cli using cargo for Rust programmers. ```sh $ cargo install refinery_cli ``` -------------------------------- ### Set Abort Missing Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Runner.md Example of disabling the abort on missing migrations. ```rust let runner = runner.set_abort_missing(false); ``` -------------------------------- ### Set Abort Divergent Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Runner.md Example of disabling the abort on divergent migrations. ```rust let runner = runner.set_abort_divergent(false); ``` -------------------------------- ### InvalidVersion Error Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Examples of filenames that would cause an InvalidVersion error. ```rust // These cause InvalidVersion: "Vabc__initial.sql" // Non-numeric "V__name.sql" // Missing version "V1,000__name.sql" // Comma separator not valid ``` -------------------------------- ### InvalidName Error Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md Examples of filenames that would cause an InvalidName error. ```rust // These cause InvalidName: "V1_initial.sql" // Single underscore "initial_schema.sql" // Missing prefix "V1__add-users.sql" // Hyphen not allowed ``` -------------------------------- ### Testing Configuration Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md A basic setup for running migrations in a test environment using an in-memory SQLite database. ```rust mod embedded { use refinery::embed_migrations; embed_migrations!(); } #[cfg(test)] mod tests { use super::*; use rusqlite::Connection; #[test] fn test_migrations() -> Result<(), Box> { let mut conn = Connection::open_in_memory()?; embedded::migrations::runner().run(&mut conn)?; // Test code here Ok(()) } } ``` -------------------------------- ### Arch Linux Installation Source: https://github.com/rust-db/refinery/blob/main/refinery_cli/README.md Install the refinery_cli package from AUR for Arch Linux users. ```sh $ yay refinery_cli ``` -------------------------------- ### Load Configuration from URL String Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Rust code to load configuration directly from a URL string. ```rust use std::str::FromStr; let config = Config::from_str("postgres://localhost/mydb")?; ``` -------------------------------- ### Default Migration Directory Structure Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example directory structure for migrations using the default location. ```text project/ migrations/ V1__initial.sql V2__users.rs V3__posts.sql src/ main.rs ``` -------------------------------- ### Version Parsing with Default i32 Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/utilities.md Example of version parsing using the default i32 type. ```rust parse_migration_name("V123__name")?; // Returns: (Versioned, 123i32, "name") ``` -------------------------------- ### Conditional Features Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML configuration demonstrating conditional feature enabling in Refinery. ```toml [dependencies.refinery] version = "0.9" features = [] [dependencies.refinery.features] default = ["toml"] postgres = ["postgres_driver", "config"] mysql = ["mysql_driver", "config"] full = ["postgres", "mysql", "rusqlite", "serde", "enums"] ``` -------------------------------- ### Development (SQLite) Configuration Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md An example of how to configure Refinery for development using SQLite, allowing divergent and missing migrations. ```rust use refinery::Runner; use rusqlite::Connection; mod embedded { use refinery::embed_migrations; embed_migrations!(); } fn main() -> Result<(), Box> { let mut conn = Connection::open("dev.db")?; let runner = embedded::migrations::runner() .set_abort_divergent(false) // Allow changes in dev .set_abort_missing(false); // Allow deletions runner.run(&mut conn)?; Ok(()) } ``` -------------------------------- ### Configure runner Source: https://github.com/rust-db/refinery/blob/main/_autodocs/API_INDEX.md Example demonstrating how to configure the `Runner` with various options like target, transaction grouping, and error handling policies. ```rust let runner = runner .set_target(Target::Latest) // Which migrations to apply .set_grouped(true) // Single transaction .set_abort_divergent(true) // Fail on modified migrations .set_abort_missing(true); // Fail on missing migrations ``` -------------------------------- ### WrapMigrationError Trait Usage Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/types.md Example of using the `migration_err` method to wrap a database operation error. ```rust database_operation() .migration_err("error applying migration", Some(&applied_migrations))?; ``` -------------------------------- ### Dynamic Loading Migrations Usage Source: https://github.com/rust-db/refinery/blob/main/_autodocs/README.md Example of dynamically loading SQL migrations. ```rust use refinery::load_sql_migrations; let migrations = load_sql_migrations("./migrations")?; let runner = refinery::Runner::new(&migrations); ``` -------------------------------- ### Conditional Database Configuration Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Example demonstrating how to conditionally embed migrations based on feature flags, supporting both PostgreSQL and SQLite. ```rust #[cfg(feature = "postgres")] mod embedded { use refinery::embed_migrations; embed_migrations!("migrations/postgres"); } #[cfg(not(feature = "postgres"))] mod embedded { use refinery::embed_migrations; embed_migrations!("migrations/sqlite"); } ``` -------------------------------- ### Config creation for Postgres Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Create a Config for a specific database type. ```rust use refinery::config::{Config, ConfigDbType}; let config = Config::new(ConfigDbType::Postgres); ``` -------------------------------- ### Getting a Report from Runner::run_async() Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Report.md Shows how to get a Report from an asynchronous migration run using `run_async()`. ```rust use tokio_postgres::Client; let mut client = get_client().await?; match runner.run_async(&mut client).await { Ok(report) => { for migration in report.applied_migrations() { println!("Applied: {}", migration); } } Err(error) => { eprintln!("Migration error: {}", error); } } ``` -------------------------------- ### Tiberius Dependency Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML dependency configuration for using the tiberius (MSSQL) driver with Refinery. ```toml [dependencies] refinery = { version = "0.9", features = ["tiberius"] } tiberius = "0.12" tokio = { version = "1", features = ["full"] } ``` -------------------------------- ### Load Configuration from Environment Variable Source: https://github.com/rust-db/refinery/blob/main/_autodocs/configuration.md Rust code to load configuration from the DATABASE_URL environment variable. ```rust let config = Config::from_env_var("DATABASE_URL")?; ``` -------------------------------- ### WrapMigrationError Usage Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/errors.md An example demonstrating the usage of the WrapMigrationError trait to add context to a database query error. ```rust database_query() .migration_err("error applying migration V1__initial", Some(&applied))?; ``` -------------------------------- ### Embedded Migrations (Recommended) Source: https://github.com/rust-db/refinery/blob/main/_autodocs/API_INDEX.md Example of using the `embed_migrations!` macro to embed migrations directly into the binary and then running them. ```rust mod embedded { use refinery::embed_migrations; embed_migrations!(); // or embed_migrations!("path/to/migrations") } fn main() -> Result<(), Box> { use rusqlite::Connection; let mut conn = Connection::open("app.db")?; let runner = embedded::migrations::runner(); let report = runner.run(&mut conn)?; println!("Applied {} migrations", report.applied_migrations().len()); Ok(()) } ``` -------------------------------- ### Config::from_file_location constructor Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Config.md Loads Config from a TOML file on the filesystem. ```rust pub fn from_file_location>(location: T) -> Result ``` ```rust use refinery::config::Config; let config = Config::from_file_location("refinery.toml")?; ``` -------------------------------- ### Using Config with SQLx Source: https://github.com/rust-db/refinery/blob/main/_autodocs/api-reference/Config.md Example of using Refinery's Config to read database connection details for SQLx. ```rust use refinery::config::Config; use sqlx::PgPool; async fn run_migrations() -> Result<(), Box> { let config = Config::from_env_var("DATABASE_URL")?; // Use config to read connection details let pool = PgPool::connect( &format!("postgres://{}@{}:{}/{}", // config.db_user(), config.db_host().unwrap_or("localhost"), config.db_port().unwrap_or("5432"), config.db_name().unwrap_or("postgres") ) ).await?; // Now use your custom migration logic with the pool Ok(()) } ``` -------------------------------- ### Default Feature Set Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML dependency configuration showing the default features included with Refinery. ```toml [dependencies] refinery = "0.9" # Includes: toml ``` -------------------------------- ### Enums Feature Dependency Example Source: https://github.com/rust-db/refinery/blob/main/_autodocs/features.md Example TOML dependency configuration for enabling the generated EmbeddedMigration enum in Refinery. ```toml [dependencies] refinery = { version = "0.9", features = ["enums"] } ```