mysql_example/
mysql_example.rs

1use sqlx_db_tester::TestMySql;
2use std::path::Path;
3
4#[tokio::main]
5async fn main() -> anyhow::Result<()> {
6    // Create a test database with migrations
7    let tdb = TestMySql::new(
8        "mysql://root:password@127.0.0.1:3307".to_string(),
9        Path::new("./fixtures/mysql_migrations"),
10    );
11
12    println!("Created test database: {}", tdb.dbname);
13    println!("Database URL: {}", tdb.url());
14
15    // Get a connection pool
16    let pool = tdb.get_pool().await;
17
18    // Insert a test record
19    sqlx::query("INSERT INTO todos (title) VALUES (?)")
20        .bind("Test MySQL Todo")
21        .execute(&pool)
22        .await?;
23
24    // Query the record back
25    let (id, title): (i32, String) = sqlx::query_as("SELECT id, title FROM todos WHERE title = ?")
26        .bind("Test MySQL Todo")
27        .fetch_one(&pool)
28        .await?;
29
30    println!("Retrieved todo: id={id}, title={title}");
31
32    // Test CSV loading
33    let csv_data = "title\nLoaded from CSV\nAnother CSV entry";
34    tdb.load_csv_data("todos", csv_data).await?;
35
36    // Count all todos
37    let count: (i64,) = sqlx::query_as("SELECT COUNT(*) FROM todos")
38        .fetch_one(&pool)
39        .await?;
40
41    println!("Total todos in database: {}", count.0);
42
43    // The database will be automatically dropped when tdb goes out of scope
44    println!("Test completed successfully! Database will be cleaned up automatically.");
45
46    Ok(())
47}