rustango 0.34.0

Django-shaped batteries-included web framework for Rust: ORM + migrations + auto-admin + multi-tenancy + audit log + auth (sessions, JWT, OAuth2/OIDC, HMAC) + APIs (ViewSet, OpenAPI auto-derive, JSON:API) + jobs (in-mem + Postgres) + email + media (S3 / R2 / B2 / MinIO + presigned uploads + collections + tags) + production middleware (CSRF, CSP, rate-limiting, compression, idempotency, etc.).
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
418
419
420
421
422
423
424
425
426
427
428
//! Test fixture loader — seed a test database from JSON files.
//!
//! ## Quick start
//!
//! ```ignore
//! use rustango::fixtures::Fixture;
//!
//! // fixtures/users.json:
//! // [
//! //   {"username": "alice", "email": "a@x.com"},
//! //   {"username": "bob",   "email": "b@x.com"}
//! // ]
//!
//! Fixture::new("users")
//!     .from_file("fixtures/users.json")?
//!     .load_into("rustango_users", &pool).await?;
//! ```
//!
//! ## How it works
//!
//! Each fixture is an array of JSON objects. For each object, the loader
//! emits an `INSERT INTO <table> (col1, col2, ...) VALUES (...)` against
//! the pool. Column names come from the JSON object's keys; values are
//! bound via sqlx parameter binding (no SQL injection).
//!
//! ## Ordering
//!
//! Fixtures load in registration order — register parent tables before
//! children to satisfy FK constraints.

use std::collections::HashSet;
use std::path::Path;

use serde_json::Value;

use crate::sql::sqlx;
#[cfg(feature = "postgres")]
use crate::sql::sqlx::PgPool;
use crate::sql::Pool;

#[derive(Debug, thiserror::Error)]
pub enum FixtureError {
    #[error("io error: {0}")]
    Io(String),
    #[error("invalid fixture format in {file}: {detail}")]
    Format { file: String, detail: String },
    #[error("database error: {0}")]
    Database(String),
}

/// One named fixture — a list of JSON object rows.
pub struct Fixture {
    name: String,
    rows: Vec<serde_json::Map<String, Value>>,
}

impl Fixture {
    /// New empty fixture with the given name (used in error messages).
    #[must_use]
    pub fn new(name: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            rows: Vec::new(),
        }
    }

    /// Add one row to the fixture.
    #[must_use]
    pub fn with_row(mut self, row: serde_json::Map<String, Value>) -> Self {
        self.rows.push(row);
        self
    }

    /// Number of rows in the fixture.
    #[must_use]
    pub fn row_count(&self) -> usize {
        self.rows.len()
    }

    /// Load rows from a JSON file. The file must contain an array of objects.
    ///
    /// # Errors
    /// [`FixtureError::Io`] when the file can't be read.
    /// [`FixtureError::Format`] when the JSON isn't an array of objects.
    pub fn from_file(mut self, path: impl AsRef<Path>) -> Result<Self, FixtureError> {
        let path = path.as_ref();
        let raw = std::fs::read_to_string(path).map_err(|e| FixtureError::Io(e.to_string()))?;
        let v: Value = serde_json::from_str(&raw).map_err(|e| FixtureError::Format {
            file: path.display().to_string(),
            detail: e.to_string(),
        })?;
        let arr = v.as_array().ok_or_else(|| FixtureError::Format {
            file: path.display().to_string(),
            detail: "expected top-level array".into(),
        })?;
        for (i, item) in arr.iter().enumerate() {
            let obj = item.as_object().ok_or_else(|| FixtureError::Format {
                file: path.display().to_string(),
                detail: format!("entry {i} is not an object"),
            })?;
            self.rows.push(obj.clone());
        }
        Ok(self)
    }

    /// Load rows from a JSON `Value` (must be an array of objects).
    ///
    /// # Errors
    /// [`FixtureError::Format`] when not an array of objects.
    pub fn from_value(mut self, v: Value) -> Result<Self, FixtureError> {
        let arr = v.as_array().ok_or_else(|| FixtureError::Format {
            file: self.name.clone(),
            detail: "expected top-level array".into(),
        })?;
        for (i, item) in arr.iter().enumerate() {
            let obj = item.as_object().ok_or_else(|| FixtureError::Format {
                file: self.name.clone(),
                detail: format!("entry {i} is not an object"),
            })?;
            self.rows.push(obj.clone());
        }
        Ok(self)
    }

    /// Insert every row into `table` against any rustango-supported
    /// backend. Routes through the [`crate::sql::Pool`] enum +
    /// per-dialect SQL emission (`pool.dialect().placeholder(n)` for
    /// `$N` / `?`; `pool.dialect().quote_ident(c)` for `"col"` /
    /// `` `col` ``).
    ///
    /// # Errors
    /// [`FixtureError::Database`] on driver-level failures.
    pub async fn load_into_pool(&self, table: &str, pool: &Pool) -> Result<usize, FixtureError> {
        validate_ident(table)?;
        let mut count = 0;
        for row in &self.rows {
            insert_row_pool(pool, table, row).await?;
            count += 1;
        }
        Ok(count)
    }

    /// PG-typed back-compat shim around [`Self::load_into_pool`].
    ///
    /// # Errors
    /// As [`Self::load_into_pool`].
    #[cfg(feature = "postgres")]
    pub async fn load_into(&self, table: &str, pool: &PgPool) -> Result<usize, FixtureError> {
        self.load_into_pool(table, &Pool::Postgres(pool.clone()))
            .await
    }
}

/// Load multiple fixtures in registration order against any
/// rustango-supported backend. Stops at first error.
///
/// # Errors
/// First fixture error encountered.
pub async fn load_all_pool(
    fixtures: &[(&str, &Fixture)],
    pool: &Pool,
) -> Result<usize, FixtureError> {
    let mut total = 0;
    for (table, fixture) in fixtures {
        total += fixture.load_into_pool(table, pool).await?;
    }
    Ok(total)
}

/// PG-typed back-compat shim around [`load_all_pool`].
///
/// # Errors
/// First fixture error encountered.
#[cfg(feature = "postgres")]
pub async fn load_all(fixtures: &[(&str, &Fixture)], pool: &PgPool) -> Result<usize, FixtureError> {
    load_all_pool(fixtures, &Pool::Postgres(pool.clone())).await
}

async fn insert_row_pool(
    pool: &Pool,
    table: &str,
    row: &serde_json::Map<String, Value>,
) -> Result<(), FixtureError> {
    if row.is_empty() {
        return Err(FixtureError::Format {
            file: table.to_owned(),
            detail: "row has no columns".into(),
        });
    }
    let columns: Vec<&String> = row.keys().collect();
    for col in &columns {
        validate_ident(col)?;
    }
    let dialect = pool.dialect();
    let cols_sql: Vec<String> = columns.iter().map(|c| dialect.quote_ident(c)).collect();
    let placeholders: Vec<String> = (1..=columns.len())
        .map(|i| dialect.placeholder(i))
        .collect();
    let sql = format!(
        "INSERT INTO {} ({}) VALUES ({})",
        dialect.quote_ident(table),
        cols_sql.join(", "),
        placeholders.join(", "),
    );
    // Bind per-backend. The JSON value → SQL parameter coercion is
    // identical across backends for the scalar types fixtures carry;
    // arrays / objects bind as `sqlx::types::Json<Value>` which all
    // three sqlx backends support via the `json` feature.
    match pool {
        #[cfg(feature = "postgres")]
        Pool::Postgres(pg) => {
            let mut q = sqlx::query(&sql);
            for col in &columns {
                let val = &row[col.as_str()];
                q = bind_pg(q, val);
            }
            q.execute(pg)
                .await
                .map_err(|e| FixtureError::Database(e.to_string()))?;
        }
        #[cfg(feature = "mysql")]
        Pool::Mysql(my) => {
            let mut q = sqlx::query(&sql);
            for col in &columns {
                let val = &row[col.as_str()];
                q = bind_my(q, val);
            }
            q.execute(my)
                .await
                .map_err(|e| FixtureError::Database(e.to_string()))?;
        }
        #[cfg(feature = "sqlite")]
        Pool::Sqlite(sq) => {
            let mut q = sqlx::query(&sql);
            for col in &columns {
                let val = &row[col.as_str()];
                q = bind_sqlite(q, val);
            }
            q.execute(sq)
                .await
                .map_err(|e| FixtureError::Database(e.to_string()))?;
        }
    }
    Ok(())
}

#[cfg(feature = "postgres")]
fn bind_pg<'a>(
    q: sqlx::query::Query<'a, sqlx::Postgres, sqlx::postgres::PgArguments>,
    v: &'a Value,
) -> sqlx::query::Query<'a, sqlx::Postgres, sqlx::postgres::PgArguments> {
    match v {
        Value::Null => q.bind(None::<i64>),
        Value::Bool(b) => q.bind(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                q.bind(i)
            } else if let Some(f) = n.as_f64() {
                q.bind(f)
            } else {
                q.bind(n.to_string())
            }
        }
        Value::String(s) => q.bind(s.as_str()),
        Value::Array(_) | Value::Object(_) => q.bind(v.clone()),
    }
}

#[cfg(feature = "mysql")]
fn bind_my<'a>(
    q: sqlx::query::Query<'a, sqlx::MySql, sqlx::mysql::MySqlArguments>,
    v: &'a Value,
) -> sqlx::query::Query<'a, sqlx::MySql, sqlx::mysql::MySqlArguments> {
    match v {
        Value::Null => q.bind(None::<i64>),
        Value::Bool(b) => q.bind(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                q.bind(i)
            } else if let Some(f) = n.as_f64() {
                q.bind(f)
            } else {
                q.bind(n.to_string())
            }
        }
        Value::String(s) => q.bind(s.as_str()),
        Value::Array(_) | Value::Object(_) => q.bind(sqlx::types::Json(v.clone())),
    }
}

#[cfg(feature = "sqlite")]
fn bind_sqlite<'a>(
    q: sqlx::query::Query<'a, sqlx::Sqlite, sqlx::sqlite::SqliteArguments<'a>>,
    v: &'a Value,
) -> sqlx::query::Query<'a, sqlx::Sqlite, sqlx::sqlite::SqliteArguments<'a>> {
    match v {
        Value::Null => q.bind(None::<i64>),
        Value::Bool(b) => q.bind(*b),
        Value::Number(n) => {
            if let Some(i) = n.as_i64() {
                q.bind(i)
            } else if let Some(f) = n.as_f64() {
                q.bind(f)
            } else {
                q.bind(n.to_string())
            }
        }
        Value::String(s) => q.bind(s.as_str()),
        Value::Array(_) | Value::Object(_) => q.bind(sqlx::types::Json(v.clone())),
    }
}

/// Reject identifiers (table / column names) with characters that could
/// break out of the quoted form. The full identifier is wrapped in `"..."`
/// so we just need to forbid `"`, NUL, and any control char.
fn validate_ident(name: &str) -> Result<(), FixtureError> {
    if name.is_empty() {
        return Err(FixtureError::Format {
            file: "<ident>".into(),
            detail: "identifier is empty".into(),
        });
    }
    let bad: HashSet<char> = ['"', '\0', '\n', '\r', '\\'].into();
    if name.chars().any(|c| bad.contains(&c) || c.is_control()) {
        return Err(FixtureError::Format {
            file: "<ident>".into(),
            detail: format!("identifier `{name}` contains forbidden characters"),
        });
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn fixture_with_row_increments_count() {
        let f = Fixture::new("test")
            .with_row(json!({"a": 1}).as_object().unwrap().clone())
            .with_row(json!({"a": 2}).as_object().unwrap().clone());
        assert_eq!(f.row_count(), 2);
    }

    #[test]
    fn from_value_parses_array() {
        let v = json!([{"name": "alice"}, {"name": "bob"}]);
        let f = Fixture::new("users").from_value(v).unwrap();
        assert_eq!(f.row_count(), 2);
    }

    #[test]
    fn from_value_rejects_non_array() {
        let v = json!({"not": "an array"});
        let r = Fixture::new("x").from_value(v);
        assert!(matches!(r, Err(FixtureError::Format { .. })));
    }

    #[test]
    fn from_value_rejects_non_object_entry() {
        let v = json!([{"ok": 1}, "scalar-not-object"]);
        let r = Fixture::new("x").from_value(v);
        assert!(matches!(r, Err(FixtureError::Format { .. })));
    }

    #[test]
    fn validate_ident_accepts_normal() {
        assert!(validate_ident("users").is_ok());
        assert!(validate_ident("user_id").is_ok());
        assert!(validate_ident("rustango_audit_log").is_ok());
    }

    #[test]
    fn validate_ident_rejects_quote() {
        assert!(validate_ident("evil\"name").is_err());
    }

    #[test]
    fn validate_ident_rejects_newline() {
        assert!(validate_ident("a\nb").is_err());
    }

    #[test]
    fn validate_ident_rejects_empty() {
        assert!(validate_ident("").is_err());
    }

    #[test]
    fn from_file_loads_array() {
        use std::io::Write;
        let path = std::env::temp_dir().join(format!(
            "rustango_fixture_test_{}_{}.json",
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos()
        ));
        std::fs::File::create(&path)
            .unwrap()
            .write_all(br#"[{"id": 1, "name": "one"}, {"id": 2, "name": "two"}]"#)
            .unwrap();
        let f = Fixture::new("test").from_file(&path).unwrap();
        assert_eq!(f.row_count(), 2);
        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn from_file_missing_file_is_io_error() {
        let r = Fixture::new("x").from_file("/no/such/file/exists.json");
        assert!(matches!(r, Err(FixtureError::Io(_))));
    }

    #[test]
    fn from_file_invalid_json_is_format_error() {
        use std::io::Write;
        let path =
            std::env::temp_dir().join(format!("rustango_fixture_bad_{}.json", std::process::id()));
        std::fs::File::create(&path)
            .unwrap()
            .write_all(b"{not valid json")
            .unwrap();
        let r = Fixture::new("x").from_file(&path);
        assert!(matches!(r, Err(FixtureError::Format { .. })));
        let _ = std::fs::remove_file(&path);
    }
}