renox 1.0.0

A batteries-included web framework for Rust, inspired by Laravel: Axum, HTMX and Alpine.js, SQLite or PostgreSQL, deployed as one binary.
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
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
//! M15a: query builder additions, `fetch_as`, relations and pivots, on
//! SQLite and (with TEST_DATABASE_URL) PostgreSQL.

use renox::db::Migration;
use renox::db::relations::{Pivot, belongs_to, has_many};
use renox::prelude::*;
use renox::testing::TestApp;

const SCHEMA: Migration = Migration::new("20300101000000_shop", "", None).sqlite("CREATE TABLE categories (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1);
             CREATE TABLE products (id INTEGER PRIMARY KEY AUTOINCREMENT, category_id INTEGER REFERENCES categories (id),
                 sku TEXT NOT NULL UNIQUE, name TEXT NOT NULL, price INTEGER NOT NULL, weight REAL NOT NULL DEFAULT 0,
                 stock INTEGER NOT NULL DEFAULT 0, created_at TEXT, updated_at TEXT);
             CREATE TABLE reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, product_id INTEGER NOT NULL REFERENCES products (id), stars INTEGER NOT NULL);
             CREATE TABLE tags (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL);
             CREATE TABLE product_tags (product_id INTEGER NOT NULL, tag_id INTEGER NOT NULL, UNIQUE (product_id, tag_id));", None).postgres("CREATE TABLE categories (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name TEXT NOT NULL, active BOOLEAN NOT NULL DEFAULT TRUE);
             CREATE TABLE products (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, category_id BIGINT REFERENCES categories (id),
                 sku TEXT NOT NULL UNIQUE, name TEXT NOT NULL, price BIGINT NOT NULL, weight DOUBLE PRECISION NOT NULL DEFAULT 0,
                 stock BIGINT NOT NULL DEFAULT 0, created_at TIMESTAMPTZ, updated_at TIMESTAMPTZ);
             CREATE TABLE reviews (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, product_id BIGINT NOT NULL REFERENCES products (id), stars BIGINT NOT NULL);
             CREATE TABLE tags (id BIGINT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY, name TEXT NOT NULL);
             CREATE TABLE product_tags (product_id BIGINT NOT NULL, tag_id BIGINT NOT NULL, UNIQUE (product_id, tag_id));", None);

#[derive(Model, serde::Serialize, Default, Debug, Clone, PartialEq)]
#[model(table = "categories")]
struct Category {
    id: i64,
    name: String,
    active: bool,
}

#[derive(Model, serde::Serialize, Default, Debug, Clone, PartialEq)]
#[model(table = "products")]
struct Product {
    id: i64,
    category_id: Option<i64>,
    sku: String,
    name: String,
    price: i64,
    weight: f64,
    stock: i64,
    created_at: Option<DateTime>,
    updated_at: Option<DateTime>,
}

#[derive(Model, serde::Serialize, Default, Debug, Clone)]
#[model(table = "reviews")]
struct Review {
    id: i64,
    product_id: i64,
    stars: i64,
}

#[derive(Model, serde::Serialize, Default, Debug, Clone)]
#[model(table = "tags")]
struct Tag {
    id: i64,
    name: String,
}

const PRODUCT_TAGS: Pivot = Pivot::new("product_tags", "product_id", "tag_id");

fn product(sku: &str, name: &str, price: i64, category_id: Option<i64>) -> Product {
    Product {
        sku: sku.into(),
        name: name.into(),
        price,
        category_id,
        weight: price as f64 / 1000.0,
        ..Default::default()
    }
}

/// Coffee (active) with Milk Coffee 18k and Black Coffee 15k; Tea (inactive)
/// with Pulled Tea 12k; Mineral Water 5k without a category.
async fn shop() -> (TestApp, Category, Category) {
    let app = TestApp::new(App::new().migrations(&[SCHEMA])).await;
    let db = app.db();
    let coffee = Category::create(
        db,
        Category {
            name: "Coffee".into(),
            active: true,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    let tea = Category::create(
        db,
        Category {
            name: "Tea".into(),
            active: false,
            ..Default::default()
        },
    )
    .await
    .unwrap();
    for p in [
        product("K1", "Milk Coffee", 18_000, Some(coffee.id)),
        product("K2", "Black Coffee", 15_000, Some(coffee.id)),
        product("T1", "Pulled Tea", 12_000, Some(tea.id)),
        product("A1", "Mineral Water", 5_000, None),
    ] {
        Product::create(db, p).await.unwrap();
    }
    (app, coffee, tea)
}

fn names(products: &[Product]) -> Vec<&str> {
    products.iter().map(|p| p.name.as_str()).collect()
}

#[renox::test]
async fn grouped_conditions_and_optional_filters() {
    let (app, coffee, _) = shop().await;
    let db = app.db();
    // category = coffee AND (price < 16000 OR name LIKE '%milk%')
    let found = Product::query()
        .where_eq("category_id", coffee.id)
        .where_any(|q| {
            q.where_op("price", "<", 16_000)
                .where_like("name", "%MILK%")
        })
        .order_by("name")
        .get(db)
        .await
        .unwrap();
    assert_eq!(names(&found), ["Black Coffee", "Milk Coffee"]);

    // (price >= 15000 AND price <= 16000) OR category IS NULL
    let found = Product::query()
        .where_any(|q| {
            q.where_all(|q| {
                q.where_op("price", ">=", 15_000)
                    .where_op("price", "<=", 16_000)
            })
            .where_null("category_id")
        })
        .order_by("name")
        .get(db)
        .await
        .unwrap();
    assert_eq!(names(&found), ["Black Coffee", "Mineral Water"]);

    for (search, expected) in [("", 4), ("coffee", 2)] {
        let found = Product::query()
            .when(!search.is_empty(), |q| {
                q.where_like("name", format!("%{search}%"))
            })
            .count(db)
            .await
            .unwrap();
        assert_eq!(found, expected, "search {search:?}");
    }
    assert_eq!(
        Product::query()
            .where_between("price", 12_000, 15_000)
            .count(db)
            .await
            .unwrap(),
        2
    );
    assert_eq!(
        Product::query()
            .where_not_in("sku", ["K1", "K2"])
            .count(db)
            .await
            .unwrap(),
        2
    );
    assert_eq!(
        Product::query()
            .where_not_in("sku", Vec::<String>::new())
            .count(db)
            .await
            .unwrap(),
        4,
        "NOT IN an empty list keeps everything"
    );
    assert_eq!(
        Product::query().where_any(|q| q).count(db).await.unwrap(),
        0
    );
    assert!(
        Product::query()
            .where_any(|q| q.where_eq("nope", 1))
            .get(db)
            .await
            .is_err(),
        "unknown columns inside groups are errors too"
    );
    let active = Product::query()
        .where_in_query("category_id", Category::where_eq("active", true), "id")
        .order_by("name")
        .get(db)
        .await
        .unwrap();
    assert_eq!(names(&active), ["Black Coffee", "Milk Coffee"]);
}

#[renox::test]
async fn aggregates_and_pluck() {
    let (app, coffee, _) = shop().await;
    let db = app.db();
    assert_eq!(
        Product::query().sum::<i64, _>(db, "price").await.unwrap(),
        50_000
    );
    let weight = Product::query().sum::<f64, _>(db, "weight").await.unwrap();
    assert!((weight - 50.0).abs() < 1e-9, "{weight}");
    let avg = Product::where_eq("category_id", coffee.id)
        .avg(db, "price")
        .await
        .unwrap();
    assert_eq!(avg, Some(16_500.0));
    assert_eq!(
        Product::query().min::<i64, _>(db, "price").await.unwrap(),
        Some(5_000)
    );
    assert_eq!(
        Product::query().max::<String, _>(db, "name").await.unwrap(),
        Some("Pulled Tea".into())
    );
    let none = Product::where_eq("sku", "nope");
    assert_eq!(none.clone().sum::<i64, _>(db, "price").await.unwrap(), 0);
    assert_eq!(none.clone().max::<i64, _>(db, "price").await.unwrap(), None);
    assert_eq!(none.avg(db, "price").await.unwrap(), None);
    let skus: Vec<String> = Product::query()
        .order_by_desc("price")
        .limit(2)
        .pluck(db, "sku")
        .await
        .unwrap();
    assert_eq!(skus, ["K1", "K2"]);
    assert!(
        Product::query()
            .pluck::<String, _>(db, "nope")
            .await
            .is_err()
    );
}

#[renox::test]
async fn bulk_updates_and_counters() {
    let (app, coffee, _) = shop().await;
    let db = app.db();
    let before = Product::where_eq("sku", "K1")
        .first_or_404(db)
        .await
        .unwrap();
    let changed = Product::where_eq("category_id", coffee.id)
        .update(db, &[("stock", &10_i64), ("name", &"Coffee")])
        .await
        .unwrap();
    assert_eq!(changed, 2);
    let after = Product::where_eq("sku", "K1")
        .first_or_404(db)
        .await
        .unwrap();
    assert_eq!((after.stock, after.name.as_str()), (10, "Coffee"));
    assert!(after.updated_at >= before.updated_at);

    Product::where_eq("sku", "K1")
        .increment(db, "stock", -3)
        .await
        .unwrap();
    Product::where_eq("sku", "K1")
        .increment(db, "stock", 1)
        .await
        .unwrap();
    assert_eq!(
        Product::where_eq("sku", "K1")
            .first_or_404(db)
            .await
            .unwrap()
            .stock,
        8
    );

    assert!(
        Product::query()
            .update(db, &[("id", &1_i64)])
            .await
            .is_err()
    );
    assert!(
        Product::query()
            .update(db, &[("nope", &1_i64)])
            .await
            .is_err()
    );
    let missing = Product::where_eq("sku", "nope")
        .first_or_404(db)
        .await
        .unwrap_err();
    assert_eq!(missing.status(), StatusCode::NOT_FOUND);
}

#[renox::test]
async fn first_or_create_chunk_insert_many_and_upsert() {
    let (app, _, _) = shop().await;
    let db = app.db();
    let made = Product::where_eq("sku", "N1")
        .first_or_create(db, || product("N1", "Rice", 20_000, None))
        .await
        .unwrap();
    let again = Product::where_eq("sku", "N1")
        .first_or_create(db, || product("N1", "Other", 1, None))
        .await
        .unwrap();
    assert_eq!((made.id, again.name.as_str()), (again.id, "Rice"));

    let many: Vec<Product> = (0..2500)
        .map(|i| product(&format!("B{i:04}"), &format!("Bulk {i}"), 1_000 + i, None))
        .collect();
    assert_eq!(Product::insert_many(db, many).await.unwrap(), 2500);
    assert_eq!(Product::query().count(db).await.unwrap(), 2505);
    assert!(
        Product::where_eq("sku", "B0001")
            .first_or_404(db)
            .await
            .unwrap()
            .created_at
            .is_some()
    );

    let mut batches = Vec::new();
    let seen = Product::query()
        .where_like("sku", "B%")
        .chunk(db, 1000, |rows| {
            batches.push(rows.len());
            async { Ok(()) }
        })
        .await
        .unwrap();
    assert_eq!((seen, batches), (2500, vec![1000, 1000, 500]));

    let feed = vec![
        product("K1", "Large Milk Coffee", 22_000, None),
        product("Z9", "New", 9_000, None),
    ];
    Product::upsert(db, feed, &["sku"], &["name", "price"])
        .await
        .unwrap();
    let k1 = Product::where_eq("sku", "K1")
        .first_or_404(db)
        .await
        .unwrap();
    assert_eq!((k1.name.as_str(), k1.price), ("Large Milk Coffee", 22_000));
    assert!(k1.category_id.is_some(), "columns not in `update` are kept");
    assert!(Product::where_eq("sku", "Z9").exists(db).await.unwrap());
    assert!(
        Product::upsert(db, Vec::new(), &["nope"], &[])
            .await
            .is_err()
    );
}

#[derive(renox::FromRow, Debug, PartialEq)]
struct CategorySales {
    category: String,
    products: i64,
    #[row(rename = "revenue")]
    total: i64,
    #[row(skip)]
    note: String,
}

#[renox::test]
async fn fetch_as_reads_joins_into_structs_and_tuples() {
    let (app, _, _) = shop().await;
    let db = app.db();
    let sales: Vec<CategorySales> = renox::db::sql(
        "SELECT c.name AS category, COUNT(p.id) AS products, CAST(SUM(p.price) AS BIGINT) AS revenue \
         FROM categories c JOIN products p ON p.category_id = c.id GROUP BY c.name ORDER BY c.name",
    )
    .fetch_as(db)
    .await
    .unwrap();
    assert_eq!(
        sales,
        [
            CategorySales {
                category: "Coffee".into(),
                products: 2,
                total: 33_000,
                note: String::new()
            },
            CategorySales {
                category: "Tea".into(),
                products: 1,
                total: 12_000,
                note: String::new()
            },
        ]
    );
    let pairs: Vec<(String, i64)> = renox::db::sql("SELECT sku, price FROM products ORDER BY sku")
        .fetch_as(db)
        .await
        .unwrap();
    assert_eq!(pairs[0], ("A1".to_owned(), 5_000));
    let model: Option<Product> = renox::db::sql("SELECT * FROM products WHERE sku = ?")
        .bind("K2")
        .fetch_optional_as(db)
        .await
        .unwrap();
    assert_eq!(model.unwrap().name, "Black Coffee");
}

#[renox::test]
async fn relations_load_a_page_without_n_plus_one() {
    let (app, coffee, tea) = shop().await;
    let db = app.db();
    let products = Product::query().order_by("sku").get(db).await.unwrap();

    let categories = belongs_to::<Category, _, _>(db, &products, |p| p.category_id)
        .await
        .unwrap();
    assert_eq!(categories.len(), 2);
    assert_eq!(categories[&coffee.id].name, "Coffee");
    assert_eq!(categories[&tea.id].name, "Tea");

    let k1 = products.iter().find(|p| p.sku == "K1").unwrap().id;
    for stars in [5, 3, 4] {
        Review::create(
            db,
            Review {
                product_id: k1,
                stars,
                ..Default::default()
            },
        )
        .await
        .unwrap();
    }
    let reviews = has_many(
        db,
        &products,
        Review::query().order_by_desc("stars"),
        "product_id",
        |r| r.product_id,
    )
    .await
    .unwrap();
    let stars: Vec<i64> = reviews[&k1].iter().map(|r| r.stars).collect();
    assert_eq!(stars, [5, 4, 3]);
    assert!(!reviews.contains_key(&products[0].id));

    let tags: Vec<Tag> = {
        let mut out = Vec::new();
        for name in ["hot", "sweet", "iced"] {
            out.push(
                Tag::create(
                    db,
                    Tag {
                        name: name.into(),
                        ..Default::default()
                    },
                )
                .await
                .unwrap(),
            );
        }
        out
    };
    let (hot, sweet, iced) = (tags[0].id, tags[1].id, tags[2].id);
    assert_eq!(
        PRODUCT_TAGS
            .attach(db, k1, [hot, sweet, hot])
            .await
            .unwrap(),
        2
    );
    assert_eq!(PRODUCT_TAGS.ids(db, k1).await.unwrap(), [hot, sweet]);
    PRODUCT_TAGS.sync(db, k1, [sweet, iced]).await.unwrap();
    assert_eq!(PRODUCT_TAGS.ids(db, k1).await.unwrap(), [sweet, iced]);
    assert_eq!(PRODUCT_TAGS.detach(db, k1, [iced]).await.unwrap(), 1);
    PRODUCT_TAGS
        .attach(db, products[0].id, [sweet])
        .await
        .unwrap();

    let loaded = PRODUCT_TAGS
        .load_for::<Tag, _>(db, &products)
        .await
        .unwrap();
    assert_eq!(
        loaded[&k1]
            .iter()
            .map(|t| t.name.as_str())
            .collect::<Vec<_>>(),
        ["sweet"]
    );
    let tagged = PRODUCT_TAGS
        .inverse()
        .load::<Product>(db, [sweet])
        .await
        .unwrap();
    assert_eq!(tagged[&sweet].len(), 2);
}