runlight_sqlx/lib.rs
1//! Runlight's tables in the app's own database, through sqlx and the app's
2//! own pool.
3//!
4//! ```no_run
5//! # #[cfg(feature = "sqlite")]
6//! # async fn example() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
7//! use sqlx::sqlite::{SqliteConnectOptions, SqlitePool};
8//!
9//! let pool = SqlitePool::connect_with(SqliteConnectOptions::new().filename("data/runlight.db").create_if_missing(true)).await?;
10//! let store = runlight_sqlx::sqlite(pool);
11//! # Ok(())
12//! # }
13//! ```
14//!
15//! The tables are the TypeScript SDK's, statement for statement, so a Rust
16//! process can share a database with a Node or PHP one. Each database is a
17//! feature of the crate: `sqlite`, `postgres`, and `mysql` (MySQL 8.4 or
18//! MariaDB 11.4 and later).
19//!
20//! Values reach the database as the TypeScript drivers send them. SQLite
21//! binds them typed, as better-sqlite3 does. Postgres and MySQL get them in
22//! the statement's text, as node-postgres's untyped parameters and mysql2's
23//! client-side escaping do, so every statement means the same to the server
24//! as it does from Node: a value Postgres would infer the type of is written
25//! as a literal it infers the type of in the same way.
26
27#![forbid(unsafe_code)]
28
29#[cfg(feature = "mysql")]
30mod mysql;
31#[cfg(feature = "postgres")]
32mod postgres;
33mod rows;
34#[cfg(feature = "sqlite")]
35mod sqlite;
36
37#[cfg(feature = "mysql")]
38pub use mysql::MysqlDb;
39#[cfg(feature = "postgres")]
40pub use postgres::PostgresDb;
41#[cfg(feature = "sqlite")]
42pub use sqlite::SqliteDb;
43
44use runlight::store::SqlStore;
45#[cfg(any(feature = "sqlite", feature = "postgres", feature = "mysql"))]
46use std::sync::Arc;
47
48/// Runlight's tables in a SQLite database, on one connection of the app's pool, which the store
49/// holds for its statements in turn (an in-memory database is one per connection, and SQLite has one
50/// writer at a time anyway). The connection is put in WAL mode with a busy timeout of five seconds.
51#[cfg(feature = "sqlite")]
52pub fn sqlite(pool: sqlx::SqlitePool) -> SqlStore {
53 SqlStore::new(Arc::new(SqliteDb::new(pool)))
54}
55
56/// Runlight's tables in Postgres, on the app's pool. The pool needs at least two connections: some
57/// work holds one while it reads through another.
58#[cfg(feature = "postgres")]
59pub fn postgres(pool: sqlx::PgPool) -> SqlStore {
60 SqlStore::new(Arc::new(PostgresDb::new(pool)))
61}
62
63/// Runlight's tables in MySQL 8.4 or MariaDB 11.4 and later, on the app's pool, which needs at least
64/// two connections. Text is utf8mb4 with a binary collation, so it compares and sorts by code point,
65/// as SQLite and Postgres do. Values are written into each statement escaped with backslashes, so each
66/// statement first takes NO_BACKSLASH_ESCAPES out of its connection's sql_mode.
67#[cfg(feature = "mysql")]
68pub fn mysql(pool: sqlx::MySqlPool) -> SqlStore {
69 SqlStore::new(Arc::new(MysqlDb::new(pool)))
70}
71
72/// A store from a connection URL: `sqlite:` (or a path), `postgres://`, or `mysql://` and `mariadb://`,
73/// with a pool of its own, as the standalone server and the CLI open one.
74pub async fn connect(url: &str) -> Result<SqlStore, runlight::store::DbError> {
75 let fail = |e: &dyn std::fmt::Display| runlight::store::DbError(e.to_string());
76 let lower = url.to_ascii_lowercase();
77 if lower.starts_with("postgres://") || lower.starts_with("postgresql://") {
78 #[cfg(feature = "postgres")]
79 {
80 let pool = sqlx::postgres::PgPoolOptions::new()
81 .max_connections(10)
82 .acquire_timeout(std::time::Duration::from_secs(10))
83 .connect(url)
84 .await
85 .map_err(|e| fail(&e))?;
86 return Ok(postgres(pool));
87 }
88 #[cfg(not(feature = "postgres"))]
89 return Err(fail(&"Runlight: built without the postgres feature"));
90 }
91 if lower.starts_with("mysql://") || lower.starts_with("mariadb://") {
92 #[cfg(feature = "mysql")]
93 {
94 let url = format!("mysql://{}", &url[url.find("://").map_or(0, |i| i + 3)..]);
95 let pool = sqlx::mysql::MySqlPoolOptions::new()
96 .max_connections(10)
97 .acquire_timeout(std::time::Duration::from_secs(10))
98 .connect(&url)
99 .await
100 .map_err(|e| fail(&e))?;
101 return Ok(mysql(pool));
102 }
103 #[cfg(not(feature = "mysql"))]
104 return Err(fail(&"Runlight: built without the mysql feature"));
105 }
106 #[cfg(feature = "sqlite")]
107 {
108 use std::str::FromStr;
109 let path = url.strip_prefix("sqlite://").or_else(|| url.strip_prefix("sqlite:")).unwrap_or(url);
110 let options = if path == ":memory:" {
111 sqlx::sqlite::SqliteConnectOptions::from_str("sqlite::memory:").map_err(|e| fail(&e))?
112 } else {
113 sqlx::sqlite::SqliteConnectOptions::new().filename(path).create_if_missing(true)
114 };
115 let pool = sqlx::sqlite::SqlitePoolOptions::new()
116 .max_connections(1)
117 .connect_with(options)
118 .await
119 .map_err(|e| fail(&e))?;
120 Ok(sqlite(pool))
121 }
122 #[cfg(not(feature = "sqlite"))]
123 Err(fail(&"Runlight: built without the sqlite feature"))
124}