Connection pools and migrations
Quick answer
A connection pool reuses database connections and limits simultaneous database access. A migration records an ordered schema change that can be applied to a database.
Bound concurrency and version the schema
A service typically creates one pool at startup and shares its handle. Set a connection maximum and acquisition timeout; too many connections can overwhelm the database. Do not hold a connection during unrelated network work. Store ordered migration files in version control and test both fresh installation and upgrades. SQLx's migrate macro embeds migrations from a directory when enabled. The examples below use the previous SQLite setup; for the migration candidate also enable SQLx macros and migrate features and create the named file before compiling. Never run these examples on production data.
use sqlx::sqlite::SqlitePoolOptions;use std::time::Duration;#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), sqlx::Error> { let p = SqlitePoolOptions::new().max_connections(1).acquire_timeout(Duration::from_secs(2)).connect("sqlite::memory:").await?; let n: i64 = sqlx::query_scalar("SELECT 42").fetch_one(&p).await?; println!("{n}"); p.close().await; Ok(())}Manual local Rust/Cargo candidate; not executed. Expected behavior:
42One connection is suitable for this tiny isolated exercise.
// migrations/0001_create_items.sql must contain:// CREATE TABLE items (id INTEGER PRIMARY KEY);use sqlx::sqlite::SqlitePoolOptions;#[tokio::main(flavor = "current_thread")]async fn main() -> Result<(), Box<dyn std::error::Error>> { let p = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; sqlx::migrate!("./migrations").run(&p).await?; let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM items").fetch_one(&p).await?; println!("{n}"); Ok(())}Manual local Rust/Cargo candidate; not executed. Expected behavior:
0 after creating the migration file and resolving dependencies.This creates the schema before the query; the SQL line above belongs in the separate file.
Common mistake
Do not edit an already applied migration in a shared environment; create a new one.
Try it yourself
Create a second migration adding a nullable description and test both an empty database and an upgrade.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Connection pools and migrations — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A request waits on an external API while holding a database connection. How can pool pressure be reduced?
Connection pools and migrations — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust use sqlx::sqlite::SqlitePoolOptions; use std::time::Duration; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), sqlx::Error> { let p = SqlitePoolOptions::new().max_connections(1).acquire_timeout(Duration::from_secs(2)).connect("sqlite::memory:").await?; let n: i64 = sqlx::query_scalar("SELECT 42").fetch_one(&p).await?; println!("{n}"); p.close().await; Ok(()) } ``` What standard output should the program produce if its run succeeds? Ignore Cargo and diagnostic messages.
Connection pools and migrations — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust // migrations/0001_create_items.sql must contain: // CREATE TABLE items (id INTEGER PRIMARY KEY); use sqlx::sqlite::SqlitePoolOptions; #[tokio::main(flavor = "current_thread")] async fn main() -> Result<(), Box<dyn std::error::Error>> { let p = SqlitePoolOptions::new().max_connections(1).connect("sqlite::memory:").await?; sqlx::migrate!("./migrations").run(&p).await?; let n: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM items").fetch_one(&p).await?; println!("{n}"); Ok(()) } ``` Which outcome or interpretation best matches this example?