|
| 1 | +use std::sync::Once; |
| 2 | + |
| 3 | +use sqlx::{AnyConnection, Connection, Row}; |
| 4 | +use tokio::runtime::Builder; |
| 5 | + |
| 6 | +static INSTALL_DRIVERS: Once = Once::new(); |
| 7 | + |
| 8 | +/// Run a sqlx future to completion on a fresh current-thread Tokio runtime, so |
| 9 | +/// the async sqlx API can be exposed through synchronous `native fn` bindings. |
| 10 | +/// sqlx's `Any` backend drivers are installed once on first use. |
| 11 | +fn block_on<T, F>(future: F) -> Result<T, String> |
| 12 | +where |
| 13 | + F: std::future::Future<Output = Result<T, String>>, |
| 14 | +{ |
| 15 | + INSTALL_DRIVERS.call_once(sqlx::any::install_default_drivers); |
| 16 | + let runtime = Builder::new_current_thread() |
| 17 | + .enable_all() |
| 18 | + .build() |
| 19 | + .map_err(|error| error.to_string())?; |
| 20 | + runtime.block_on(future) |
| 21 | +} |
| 22 | + |
| 23 | +/// Run one or more SQL statements that produce no rows (DDL, `INSERT`, ...). |
| 24 | +pub fn execute(url: &str, sql: &str) -> Result<(), String> { |
| 25 | + block_on(async { |
| 26 | + let mut conn = AnyConnection::connect(url) |
| 27 | + .await |
| 28 | + .map_err(|error| error.to_string())?; |
| 29 | + let result = sqlx::raw_sql(sql) |
| 30 | + .execute(&mut conn) |
| 31 | + .await |
| 32 | + .map(|_| ()) |
| 33 | + .map_err(|error| error.to_string()); |
| 34 | + let _ = conn.close().await; |
| 35 | + result |
| 36 | + }) |
| 37 | +} |
| 38 | + |
| 39 | +/// Run a query and collect the first column of every row as a string. |
| 40 | +pub fn query_strings(url: &str, sql: &str) -> Result<Vec<String>, String> { |
| 41 | + block_on(async { |
| 42 | + let mut conn = AnyConnection::connect(url) |
| 43 | + .await |
| 44 | + .map_err(|error| error.to_string())?; |
| 45 | + let result = collect_first_column(&mut conn, sql).await; |
| 46 | + let _ = conn.close().await; |
| 47 | + result |
| 48 | + }) |
| 49 | +} |
| 50 | + |
| 51 | +/// Run a query and return the first column of the first row, if any. |
| 52 | +pub fn query_one_string(url: &str, sql: &str) -> Result<Option<String>, String> { |
| 53 | + let values = query_strings(url, sql)?; |
| 54 | + Ok(values.into_iter().next()) |
| 55 | +} |
| 56 | + |
| 57 | +async fn collect_first_column(conn: &mut AnyConnection, sql: &str) -> Result<Vec<String>, String> { |
| 58 | + let rows = sqlx::query(sql) |
| 59 | + .fetch_all(conn) |
| 60 | + .await |
| 61 | + .map_err(|error| error.to_string())?; |
| 62 | + let mut values = Vec::with_capacity(rows.len()); |
| 63 | + for row in &rows { |
| 64 | + let value: String = row.try_get(0).map_err(|error| error.to_string())?; |
| 65 | + values.push(value); |
| 66 | + } |
| 67 | + Ok(values) |
| 68 | +} |
| 69 | + |
| 70 | +#[cfg(test)] |
| 71 | +mod tests { |
| 72 | + #[test] |
| 73 | + fn executes_and_queries_over_sqlite() { |
| 74 | + let path = std::env::temp_dir().join(format!("rss-sqlx-{}.db", std::process::id())); |
| 75 | + let _ = std::fs::remove_file(&path); |
| 76 | + let url = format!("sqlite://{}?mode=rwc", path.display()); |
| 77 | + |
| 78 | + super::execute( |
| 79 | + &url, |
| 80 | + "create table item(name text); insert into item values ('a'), ('b');", |
| 81 | + ) |
| 82 | + .expect("sqlite setup should work"); |
| 83 | + |
| 84 | + assert_eq!( |
| 85 | + super::query_strings(&url, "select name from item order by name") |
| 86 | + .expect("query should work"), |
| 87 | + vec!["a".to_string(), "b".to_string()] |
| 88 | + ); |
| 89 | + assert_eq!( |
| 90 | + super::query_one_string(&url, "select name from item order by name") |
| 91 | + .expect("query should work"), |
| 92 | + Some("a".to_string()) |
| 93 | + ); |
| 94 | + |
| 95 | + let _ = std::fs::remove_file(path); |
| 96 | + } |
| 97 | + |
| 98 | + #[test] |
| 99 | + fn reports_connection_errors_as_strings() { |
| 100 | + let error = super::execute("postgres://127.0.0.1:1/missing", "select 1") |
| 101 | + .expect_err("connecting to a dead postgres should fail"); |
| 102 | + assert!(!error.is_empty()); |
| 103 | + } |
| 104 | +} |
0 commit comments