modde-core 0.3.0

Core types and logic for the modde mod manager
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
//! Backend-agnostic async SQL executor shared by every [`ModdeDb`](super::ModdeDb)
//! method.
//!
//! modde supports two storage backends — `SQLite` (always available) and
//! `PostgreSQL` (behind the default-on `postgres` feature). Rather than write two
//! copies of every query, the ~60 CRUD methods are authored **once** against
//! this thin executor: SQL is written with `?` placeholders and a small set of
//! portable constructs (`RETURNING id`, `ON CONFLICT … DO UPDATE … EXCLUDED`,
//! `lower(name)`, `bool` columns) that both `sqlx`'s bundled `SQLite` (3.46+) and
//! `PostgreSQL` understand. Only the schema/migration DDL genuinely differs
//! between backends; that lives in [`super::migrate`].
//!
//! The executor bridges the two real divergences:
//!
//! * **Placeholders** — Postgres needs `$1, $2, …`; the `SQLite` `?` form is
//!   rewritten on the way out via [`rewrite_placeholders`].
//! * **`now()`** — the `{NOW}` token expands to `datetime('now')` on `SQLite` and
//!   to a matching `to_char(now(), …)` TEXT expression on Postgres, so the
//!   timestamp columns stay `TEXT` and the Rust struct fields stay `String`.

use std::borrow::Cow;

use sqlx::sqlite::{SqliteArguments, SqlitePool, SqliteRow};
use sqlx::{Arguments, Row};

#[cfg(feature = "postgres")]
use sqlx::postgres::{PgArguments, PgPool, PgRow};

use crate::error::{CoreError, Result};
use crate::resolver::{GameId, ModId};

/// A backend-agnostic bound parameter.
///
/// Nulls are *typed* (`NullText` / `NullI64`) so `PostgreSQL` — which, unlike
/// `SQLite`, will not infer the type of a bare `NULL` parameter in every position
/// — always receives a parameter with a concrete type.
#[derive(Debug, Clone)]
pub enum Val {
    NullText,
    NullI64,
    Bool(bool),
    I64(i64),
    Text(String),
}

impl From<&str> for Val {
    fn from(s: &str) -> Self {
        Val::Text(s.to_string())
    }
}
impl From<String> for Val {
    fn from(s: String) -> Self {
        Val::Text(s)
    }
}
impl From<&String> for Val {
    fn from(s: &String) -> Self {
        Val::Text(s.clone())
    }
}
impl From<i64> for Val {
    fn from(v: i64) -> Self {
        Val::I64(v)
    }
}
impl From<bool> for Val {
    fn from(v: bool) -> Self {
        Val::Bool(v)
    }
}
impl From<&GameId> for Val {
    fn from(v: &GameId) -> Self {
        Val::Text(v.as_str().to_string())
    }
}
impl From<&ModId> for Val {
    fn from(v: &ModId) -> Self {
        Val::Text(v.as_str().to_string())
    }
}
impl From<Option<String>> for Val {
    fn from(v: Option<String>) -> Self {
        v.map_or(Val::NullText, Val::Text)
    }
}
impl From<Option<&str>> for Val {
    fn from(v: Option<&str>) -> Self {
        v.map_or(Val::NullText, |s| Val::Text(s.to_string()))
    }
}
impl From<Option<i64>> for Val {
    fn from(v: Option<i64>) -> Self {
        v.map_or(Val::NullI64, Val::I64)
    }
}

/// Build a parameter list for an executor call.
///
/// Expands to a fixed-size `[Val; N]` array (not a `Vec`, so no heap
/// allocation and no `clippy::useless_vec` at the `&vals![..]` call sites).
/// Each argument is converted into a [`Val`] via [`Into`], so `i64`, `bool`,
/// `&str`, `String`, `&GameId`, `&ModId`, and the `Option<…>` variants can be
/// passed directly; callers pass `&vals![..]`, which coerces to `&[Val]`.
macro_rules! vals {
    () => { [] };
    ($($x:expr),+ $(,)?) => { [ $( $crate::db::backend::Val::from($x) ),+ ] };
}
pub(crate) use vals;

/// Column accessor presented to row-mapping closures.
///
/// Implemented for both `SqliteRow` and `PgRow`, this lets every mapper be
/// written once against `&dyn DbRow` with no `sqlx` trait bounds leaking into
/// the call site.
pub trait DbRow {
    fn i64(&self, idx: usize) -> Result<i64>;
    fn opt_i64(&self, idx: usize) -> Result<Option<i64>>;
    fn string(&self, idx: usize) -> Result<String>;
    fn opt_string(&self, idx: usize) -> Result<Option<String>>;
    fn bool(&self, idx: usize) -> Result<bool>;
}

impl DbRow for SqliteRow {
    fn i64(&self, idx: usize) -> Result<i64> {
        Ok(self.try_get(idx)?)
    }
    fn opt_i64(&self, idx: usize) -> Result<Option<i64>> {
        Ok(self.try_get(idx)?)
    }
    fn string(&self, idx: usize) -> Result<String> {
        Ok(self.try_get(idx)?)
    }
    fn opt_string(&self, idx: usize) -> Result<Option<String>> {
        Ok(self.try_get(idx)?)
    }
    fn bool(&self, idx: usize) -> Result<bool> {
        Ok(self.try_get(idx)?)
    }
}

#[cfg(feature = "postgres")]
impl DbRow for PgRow {
    fn i64(&self, idx: usize) -> Result<i64> {
        Ok(self.try_get(idx)?)
    }
    fn opt_i64(&self, idx: usize) -> Result<Option<i64>> {
        Ok(self.try_get(idx)?)
    }
    fn string(&self, idx: usize) -> Result<String> {
        Ok(self.try_get(idx)?)
    }
    fn opt_string(&self, idx: usize) -> Result<Option<String>> {
        Ok(self.try_get(idx)?)
    }
    fn bool(&self, idx: usize) -> Result<bool> {
        Ok(self.try_get(idx)?)
    }
}

/// Which SQL dialect a connection speaks, used to shape the query text.
#[derive(Clone, Copy)]
enum Dialect {
    Sqlite,
    #[cfg(feature = "postgres")]
    Postgres,
}

fn bind_err(e: impl std::fmt::Display) -> CoreError {
    CoreError::Other(format!("failed to bind SQL parameter: {e}").into())
}

fn sqlite_args(vals: &[Val]) -> Result<SqliteArguments<'static>> {
    let mut args = SqliteArguments::default();
    for v in vals {
        match v {
            Val::NullText => args.add(None::<String>),
            Val::NullI64 => args.add(None::<i64>),
            Val::Bool(b) => args.add(*b),
            Val::I64(i) => args.add(*i),
            Val::Text(s) => args.add(s.clone()),
        }
        .map_err(bind_err)?;
    }
    Ok(args)
}

#[cfg(feature = "postgres")]
fn pg_args(vals: &[Val]) -> Result<PgArguments> {
    let mut args = PgArguments::default();
    for v in vals {
        match v {
            Val::NullText => args.add(None::<String>),
            Val::NullI64 => args.add(None::<i64>),
            Val::Bool(b) => args.add(*b),
            Val::I64(i) => args.add(*i),
            Val::Text(s) => args.add(s.clone()),
        }
        .map_err(bind_err)?;
    }
    Ok(args)
}

/// Rewrite SQLite-style `?` placeholders into `PostgreSQL`'s positional
/// `$1, $2, …` form.
///
/// Single-quoted string literals are skipped so a `?` inside a literal (we have
/// none today, but be safe) is left untouched.
#[cfg(feature = "postgres")]
fn rewrite_placeholders(sql: &str) -> String {
    let mut out = String::with_capacity(sql.len() + 8);
    let mut n = 0u32;
    let mut in_str = false;
    for c in sql.chars() {
        match c {
            '\'' => {
                in_str = !in_str;
                out.push(c);
            }
            '?' if !in_str => {
                n += 1;
                out.push('$');
                out.push_str(&n.to_string());
            }
            _ => out.push(c),
        }
    }
    out
}

fn prepare_sql(dialect: Dialect, sql: &str) -> Cow<'_, str> {
    match dialect {
        Dialect::Sqlite => {
            if sql.contains("{NOW}") {
                Cow::Owned(sql.replace("{NOW}", "datetime('now')"))
            } else {
                Cow::Borrowed(sql)
            }
        }
        #[cfg(feature = "postgres")]
        Dialect::Postgres => {
            let sql = sql.replace("{NOW}", "to_char(now(), 'YYYY-MM-DD HH24:MI:SS')");
            Cow::Owned(rewrite_placeholders(&sql))
        }
    }
}

/// An open connection pool to one of the supported backends.
///
/// Cloning is cheap because the inner `sqlx` pool is reference-counted.
#[derive(Debug, Clone)]
pub enum Db {
    Sqlite(SqlitePool),
    #[cfg(feature = "postgres")]
    Postgres(PgPool),
}

impl Db {
    fn dialect(&self) -> Dialect {
        match self {
            Db::Sqlite(_) => Dialect::Sqlite,
            #[cfg(feature = "postgres")]
            Db::Postgres(_) => Dialect::Postgres,
        }
    }

    /// Run a statement, returning the number of affected rows.
    pub async fn execute(&self, sql: &str, vals: &[Val]) -> Result<u64> {
        let sql = prepare_sql(self.dialect(), sql);
        match self {
            Db::Sqlite(pool) => {
                let args = sqlite_args(vals)?;
                Ok(sqlx::query_with(&sql, args)
                    .execute(pool)
                    .await?
                    .rows_affected())
            }
            #[cfg(feature = "postgres")]
            Db::Postgres(pool) => {
                let args = pg_args(vals)?;
                Ok(sqlx::query_with(&sql, args)
                    .execute(pool)
                    .await?
                    .rows_affected())
            }
        }
    }

    /// Run a query and map every returned row.
    pub async fn fetch_all<T>(
        &self,
        sql: &str,
        vals: &[Val],
        map: impl Fn(&dyn DbRow) -> Result<T>,
    ) -> Result<Vec<T>> {
        let sql = prepare_sql(self.dialect(), sql);
        match self {
            Db::Sqlite(pool) => {
                let args = sqlite_args(vals)?;
                let rows = sqlx::query_with(&sql, args).fetch_all(pool).await?;
                rows.iter().map(|r| map(r as &dyn DbRow)).collect()
            }
            #[cfg(feature = "postgres")]
            Db::Postgres(pool) => {
                let args = pg_args(vals)?;
                let rows = sqlx::query_with(&sql, args).fetch_all(pool).await?;
                rows.iter().map(|r| map(r as &dyn DbRow)).collect()
            }
        }
    }

    /// Run a query expected to return at most one row.
    pub async fn fetch_optional<T>(
        &self,
        sql: &str,
        vals: &[Val],
        map: impl Fn(&dyn DbRow) -> Result<T>,
    ) -> Result<Option<T>> {
        let sql = prepare_sql(self.dialect(), sql);
        match self {
            Db::Sqlite(pool) => {
                let args = sqlite_args(vals)?;
                match sqlx::query_with(&sql, args).fetch_optional(pool).await? {
                    Some(r) => Ok(Some(map(&r as &dyn DbRow)?)),
                    None => Ok(None),
                }
            }
            #[cfg(feature = "postgres")]
            Db::Postgres(pool) => {
                let args = pg_args(vals)?;
                match sqlx::query_with(&sql, args).fetch_optional(pool).await? {
                    Some(r) => Ok(Some(map(&r as &dyn DbRow)?)),
                    None => Ok(None),
                }
            }
        }
    }

    /// Run a query expected to return exactly one row.
    pub async fn fetch_one<T>(
        &self,
        sql: &str,
        vals: &[Val],
        map: impl Fn(&dyn DbRow) -> Result<T>,
    ) -> Result<T> {
        let sql = prepare_sql(self.dialect(), sql);
        match self {
            Db::Sqlite(pool) => {
                let args = sqlite_args(vals)?;
                let r = sqlx::query_with(&sql, args).fetch_one(pool).await?;
                map(&r as &dyn DbRow)
            }
            #[cfg(feature = "postgres")]
            Db::Postgres(pool) => {
                let args = pg_args(vals)?;
                let r = sqlx::query_with(&sql, args).fetch_one(pool).await?;
                map(&r as &dyn DbRow)
            }
        }
    }

    /// Begin a transaction for the few multi-statement writers that need
    /// all-or-nothing semantics (`record_install`, `remove_installed_mod`).
    pub async fn begin(&self) -> Result<DbTx<'_>> {
        Ok(match self {
            Db::Sqlite(pool) => DbTx::Sqlite(pool.begin().await?),
            #[cfg(feature = "postgres")]
            Db::Postgres(pool) => DbTx::Postgres(pool.begin().await?),
        })
    }
}

/// An in-progress transaction mirroring [`Db`]'s query surface.
pub enum DbTx<'c> {
    Sqlite(sqlx::Transaction<'c, sqlx::Sqlite>),
    #[cfg(feature = "postgres")]
    Postgres(sqlx::Transaction<'c, sqlx::Postgres>),
}

impl DbTx<'_> {
    fn dialect(&self) -> Dialect {
        match self {
            DbTx::Sqlite(_) => Dialect::Sqlite,
            #[cfg(feature = "postgres")]
            DbTx::Postgres(_) => Dialect::Postgres,
        }
    }

    pub async fn execute(&mut self, sql: &str, vals: &[Val]) -> Result<u64> {
        let sql = prepare_sql(self.dialect(), sql);
        match self {
            DbTx::Sqlite(tx) => {
                let args = sqlite_args(vals)?;
                Ok(sqlx::query_with(&sql, args)
                    .execute(&mut **tx)
                    .await?
                    .rows_affected())
            }
            #[cfg(feature = "postgres")]
            DbTx::Postgres(tx) => {
                let args = pg_args(vals)?;
                Ok(sqlx::query_with(&sql, args)
                    .execute(&mut **tx)
                    .await?
                    .rows_affected())
            }
        }
    }

    pub async fn commit(self) -> Result<()> {
        match self {
            DbTx::Sqlite(tx) => tx.commit().await?,
            #[cfg(feature = "postgres")]
            DbTx::Postgres(tx) => tx.commit().await?,
        }
        Ok(())
    }
}