|
| 1 | +//! What differs between the databases: connecting, transactions, the schema |
| 2 | +//! a client uses, and migrations. Everything else goes through River's |
| 3 | +//! database-independent `Client`. |
| 4 | +
|
| 5 | +use std::{str::FromStr, time::Duration}; |
| 6 | + |
| 7 | +use riverqueue::{ |
| 8 | + BoxError, Client, ClientBuilder, |
| 9 | + database::{ |
| 10 | + DatabaseTransactionExecutor, PostgresDatabase, SchemaName, SqliteDatabase, begin_postgres, |
| 11 | + begin_sqlite_write, |
| 12 | + }, |
| 13 | + migrate::{Direction, MigrateOpts, MigrateResult, PostgresMigrator, SqliteMigrator}, |
| 14 | + sqlx::{ |
| 15 | + self, PgPool, SqlitePool, Transaction, |
| 16 | + postgres::{PgConnectOptions, PgPoolOptions}, |
| 17 | + sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}, |
| 18 | + }, |
| 19 | +}; |
| 20 | + |
| 21 | +use crate::protocol::RpcError; |
| 22 | + |
| 23 | +/// A database River supports, which the server is generic over. |
| 24 | +pub trait Backend: Sized { |
| 25 | + type Db: sqlx::Database; |
| 26 | + |
| 27 | + /// The contract's name for the driver. |
| 28 | + const DRIVER: &'static str; |
| 29 | + |
| 30 | + /// Opens a pool on `url`, whose connections use `application_name` where |
| 31 | + /// the database has one. |
| 32 | + fn connect(url: &str, application_name: &str) -> Result<Self, BoxError>; |
| 33 | + |
| 34 | + /// Starts building a client on `schema`, or on the default for an empty |
| 35 | + /// one. |
| 36 | + fn builder(&self, schema: &str) -> Result<ClientBuilder, RpcError>; |
| 37 | + |
| 38 | + /// Begins a transaction for River's `.tx` requests. |
| 39 | + async fn begin(&self) -> Result<Transaction<'static, Self::Db>, sqlx::Error>; |
| 40 | + |
| 41 | + /// Passes a transaction to River's `.tx` requests. |
| 42 | + fn executor<'t>( |
| 43 | + transaction: &'t mut Transaction<'static, Self::Db>, |
| 44 | + ) -> impl DatabaseTransactionExecutor<'t>; |
| 45 | + |
| 46 | + /// Migrates `schema`. |
| 47 | + async fn migrate( |
| 48 | + &self, |
| 49 | + schema: &str, |
| 50 | + direction: Direction, |
| 51 | + opts: MigrateOpts, |
| 52 | + ) -> Result<MigrateResult, RpcError>; |
| 53 | +} |
| 54 | + |
| 55 | +#[derive(Debug)] |
| 56 | +pub struct Postgres(PgPool); |
| 57 | + |
| 58 | +impl Postgres { |
| 59 | + fn schema(schema: &str) -> Result<Option<SchemaName>, RpcError> { |
| 60 | + (!schema.is_empty()) |
| 61 | + .then(|| SchemaName::new(schema).map_err(RpcError::rejected)) |
| 62 | + .transpose() |
| 63 | + } |
| 64 | +} |
| 65 | + |
| 66 | +impl Backend for Postgres { |
| 67 | + type Db = sqlx::Postgres; |
| 68 | + |
| 69 | + const DRIVER: &'static str = "postgres"; |
| 70 | + |
| 71 | + fn connect(url: &str, application_name: &str) -> Result<Self, BoxError> { |
| 72 | + // The URL's `options` set the search path, which River uses when no |
| 73 | + // schema is given. |
| 74 | + let options = PgConnectOptions::from_str(url)?.application_name(application_name); |
| 75 | + Ok(Self( |
| 76 | + PgPoolOptions::new() |
| 77 | + .max_connections(10) |
| 78 | + .connect_lazy_with(options), |
| 79 | + )) |
| 80 | + } |
| 81 | + |
| 82 | + fn builder(&self, schema: &str) -> Result<ClientBuilder, RpcError> { |
| 83 | + let mut database = PostgresDatabase::new(self.0.clone()); |
| 84 | + if let Some(schema) = Self::schema(schema)? { |
| 85 | + database = database.with_schema(schema); |
| 86 | + } |
| 87 | + Ok(Client::builder(database)) |
| 88 | + } |
| 89 | + |
| 90 | + async fn begin(&self) -> Result<Transaction<'static, Self::Db>, sqlx::Error> { |
| 91 | + begin_postgres(&self.0).await |
| 92 | + } |
| 93 | + |
| 94 | + fn executor<'t>( |
| 95 | + transaction: &'t mut Transaction<'static, Self::Db>, |
| 96 | + ) -> impl DatabaseTransactionExecutor<'t> { |
| 97 | + transaction |
| 98 | + } |
| 99 | + |
| 100 | + async fn migrate( |
| 101 | + &self, |
| 102 | + schema: &str, |
| 103 | + direction: Direction, |
| 104 | + opts: MigrateOpts, |
| 105 | + ) -> Result<MigrateResult, RpcError> { |
| 106 | + let mut migrator = PostgresMigrator::new(self.0.clone()); |
| 107 | + if let Some(schema) = Self::schema(schema)? { |
| 108 | + migrator = migrator.with_schema(schema); |
| 109 | + } |
| 110 | + migrator |
| 111 | + .migrate(direction, opts) |
| 112 | + .await |
| 113 | + .map_err(RpcError::rejected) |
| 114 | + } |
| 115 | +} |
| 116 | + |
| 117 | +#[derive(Debug)] |
| 118 | +pub struct Sqlite(SqlitePool); |
| 119 | + |
| 120 | +/// SQLite has no schemas. |
| 121 | +fn no_schema(schema: &str) -> Result<(), RpcError> { |
| 122 | + if schema.is_empty() { |
| 123 | + Ok(()) |
| 124 | + } else { |
| 125 | + Err(RpcError::rejected("SQLite has no schemas")) |
| 126 | + } |
| 127 | +} |
| 128 | + |
| 129 | +impl Backend for Sqlite { |
| 130 | + type Db = sqlx::Sqlite; |
| 131 | + |
| 132 | + const DRIVER: &'static str = "sqlite"; |
| 133 | + |
| 134 | + fn connect(url: &str, _application_name: &str) -> Result<Self, BoxError> { |
| 135 | + // Several processes share the file, so the busy timeout must cover |
| 136 | + // another's writes, including its switch of a new database to WAL. |
| 137 | + let options = SqliteConnectOptions::new() |
| 138 | + .filename(url) |
| 139 | + .create_if_missing(true) |
| 140 | + .busy_timeout(Duration::from_secs(5)) |
| 141 | + .journal_mode(SqliteJournalMode::Wal) |
| 142 | + .foreign_keys(true); |
| 143 | + Ok(Self( |
| 144 | + SqlitePoolOptions::new() |
| 145 | + .max_connections(4) |
| 146 | + .connect_lazy_with(options), |
| 147 | + )) |
| 148 | + } |
| 149 | + |
| 150 | + fn builder(&self, schema: &str) -> Result<ClientBuilder, RpcError> { |
| 151 | + no_schema(schema)?; |
| 152 | + Ok(Client::builder(SqliteDatabase::new(self.0.clone()))) |
| 153 | + } |
| 154 | + |
| 155 | + async fn begin(&self) -> Result<Transaction<'static, Self::Db>, sqlx::Error> { |
| 156 | + begin_sqlite_write(&self.0).await |
| 157 | + } |
| 158 | + |
| 159 | + fn executor<'t>( |
| 160 | + transaction: &'t mut Transaction<'static, Self::Db>, |
| 161 | + ) -> impl DatabaseTransactionExecutor<'t> { |
| 162 | + transaction |
| 163 | + } |
| 164 | + |
| 165 | + async fn migrate( |
| 166 | + &self, |
| 167 | + schema: &str, |
| 168 | + direction: Direction, |
| 169 | + opts: MigrateOpts, |
| 170 | + ) -> Result<MigrateResult, RpcError> { |
| 171 | + no_schema(schema)?; |
| 172 | + SqliteMigrator::new(self.0.clone()) |
| 173 | + .migrate(direction, opts) |
| 174 | + .await |
| 175 | + .map_err(RpcError::rejected) |
| 176 | + } |
| 177 | +} |
0 commit comments