Skip to main content

ojak_postgres/
lib.rs

1//! PostgreSQL backends for Ojak: the queue, [`PostgresQueue`], and the
2//! key-value store, [`PostgresKvStore`], each in a table of its own that it
3//! creates on first use or that the application creates in a migration.
4//!
5//! Queries are built at run time rather than checked by `sqlx`'s macros
6//! against a database at compile time, since the tables' names are the
7//! application's to choose and an application building with this crate
8//! should not need a database for it.
9
10mod kv;
11mod queue;
12
13pub use kv::PostgresKvStore;
14pub use queue::PostgresQueue;
15
16/// `table`, if it is a plain SQL identifier: ASCII letters, digits and
17/// underscores, not starting with a digit, optionally prefixed by a schema
18/// of the same shape and a dot. Table names are put into queries as they
19/// are, so nothing else is.
20fn table_name(table: &str) -> Result<String, String> {
21    let valid = table.split('.').count() <= 2
22        && table.split('.').all(|part| {
23            !part.is_empty()
24                && part.len() <= 63
25                && !part.starts_with(|c: char| c.is_ascii_digit())
26                && part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
27        });
28    if valid {
29        Ok(table.to_owned())
30    } else {
31        Err(format!("not a table name: {table}"))
32    }
33}
34
35/// A statement with a table name in it, which sqlx 0.9 takes only once it is
36/// said to be safe: the only part not written here is a name `table_name`
37/// let through, and every value is bound.
38fn sql(statement: String) -> sqlx::AssertSqlSafe<String> {
39    sqlx::AssertSqlSafe(statement)
40}