prax-orm 0.11.0

A next-generation, type-safe ORM for Rust inspired by Prisma
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
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
//! End-to-end coverage for phase-6 aggregate macros:
//!
//!   - `count!` select: per-column `COUNT(col)` / `COUNT(*)` emission.
//!   - `aggregate!` all five aggregate functions (SUM/AVG/MIN/MAX/COUNT).
//!   - `aggregate!` WHERE-clause filtering.
//!   - `group_by!` GROUP BY clause emission.
//!   - `group_by!` HAVING clause emission.
//!   - `aggregate!` omits unspecified aggregate blocks.
//!
//! # Design — runtime API for shape tests, macro DSL for emission tests
//!
//! The `aggregate!` / `group_by!` / `count!` macro lowering for aggregate
//! fields is driven by schema metadata in a `LowerCtx` which requires the
//! schema to be resolved via `prax_schema!("prax/schema.prax")`.  The
//! schema-path codegen's `relation_helpers` emit `super::<Model>` paths that
//! don't resolve in the workspace-root test crate context — a latent issue
//! documented in `tests/nested_writes_e2e.rs` and `tests/computed_fields_e2e.rs`.
//!
//! The `AggregateArgs` / `GroupByArgs` structs and the
//! `with_aggregate_args` / `with_group_by_args` extension traits are emitted
//! by the **derive** macro (`prax-codegen/src/generators/derive.rs`); it was
//! the **schema path** (`prax_schema!`) that lacked emission until it was
//! added (`prax-codegen/src/generators/model.rs`).  Derive-style models avoid
//! the relation-helper path issue when no cross-model relations are declared,
//! so Tests 10–12 below invoke the actual macros against the derive model in
//! this file, while Tests 1–9 pin runtime-builder SQL shapes directly.
//!
//! All tests call `build_sql(&Postgres)` (synchronous) to materialise the
//! operation into SQL — this is the right level for "DSL → SQL emission chain"
//! tests.  No live engine is needed.
//!
//! # TODO (cleanup)
//!
//! When the schema-path `relation_helpers` path-resolution bug is fixed, the
//! macro-DSL variants can also run against `prax_schema!` models.
//!
//! Note on columns: the macros validate columns against the
//! `prax/schema.prax` fixture (`id, email, name, age, active, created_at`)
//! but emit references to this file's derive-generated `user::` structs
//! (`id, email, team_id, region, active, views, score`), so the macro tests
//! are restricted to the intersection (`id`/`email`/`active`) — `id` stands
//! in as the numeric column since `views`/`score` don't exist in the fixture.

#![allow(dead_code)]
#![allow(unused_imports)]

use std::borrow::Cow;
use std::sync::{Arc, Mutex};

use prax_orm::{Model, client};
use prax_query::capabilities::{SupportsNestedWrites, SupportsScalarSubqueryInSelect};
use prax_query::dialect::SqlDialect;
use prax_query::error::{QueryError, QueryResult};
use prax_query::filter::{Filter, FilterValue};
use prax_query::row::{FromRow, RowError, RowRef};
use prax_query::traits::{BoxFuture, Model as ModelTrait, QueryEngine};
use prax_query::types::{OrderBy, OrderByField, SortOrder};
use prax_query::{
    AggregateField, AggregateOperation, GroupByOperation, HavingCondition, HavingOp, having,
};

// ── RecordingEngine ───────────────────────────────────────────────────────────
//
// Verbatim copy from tests/nested_writes_e2e.rs.

type StatementLog = Arc<Mutex<Vec<(String, Vec<FilterValue>)>>>;

/// Recording mock engine for e2e tests.
#[derive(Clone)]
struct RecordingEngine {
    recorded: StatementLog,
}

impl RecordingEngine {
    fn new() -> Self {
        Self {
            recorded: Arc::new(Mutex::new(Vec::new())),
        }
    }

    fn statements(&self) -> Vec<(String, Vec<FilterValue>)> {
        self.recorded.lock().unwrap().clone()
    }
}

impl QueryEngine for RecordingEngine {
    fn dialect(&self) -> &dyn SqlDialect {
        &prax_query::dialect::Postgres
    }
    fn query_many<T: ModelTrait + FromRow + Send + 'static>(
        &self,
        sql: &str,
        params: Vec<FilterValue>,
    ) -> BoxFuture<'_, QueryResult<Vec<T>>> {
        let recorded = self.recorded.clone();
        let sql = sql.to_string();
        Box::pin(async move {
            recorded.lock().unwrap().push((sql, params));
            Ok(Vec::new())
        })
    }
    fn query_one<T: ModelTrait + FromRow + Send + 'static>(
        &self,
        sql: &str,
        params: Vec<FilterValue>,
    ) -> BoxFuture<'_, QueryResult<T>> {
        let recorded = self.recorded.clone();
        let sql = sql.to_string();
        Box::pin(async move {
            recorded.lock().unwrap().push((sql, params));
            T::from_row(&CannedRow).map_err(|e| QueryError::internal(e.to_string()))
        })
    }
    fn query_optional<T: ModelTrait + FromRow + Send + 'static>(
        &self,
        _sql: &str,
        _params: Vec<FilterValue>,
    ) -> BoxFuture<'_, QueryResult<Option<T>>> {
        Box::pin(async { Ok(None) })
    }
    fn execute_insert<T: ModelTrait + FromRow + Send + 'static>(
        &self,
        sql: &str,
        params: Vec<FilterValue>,
    ) -> BoxFuture<'_, QueryResult<T>> {
        let recorded = self.recorded.clone();
        let sql = sql.to_string();
        Box::pin(async move {
            recorded.lock().unwrap().push((sql, params));
            T::from_row(&CannedRow).map_err(|e| QueryError::internal(e.to_string()))
        })
    }
    fn execute_update<T: ModelTrait + FromRow + Send + 'static>(
        &self,
        sql: &str,
        params: Vec<FilterValue>,
    ) -> BoxFuture<'_, QueryResult<Vec<T>>> {
        let recorded = self.recorded.clone();
        let sql = sql.to_string();
        Box::pin(async move {
            recorded.lock().unwrap().push((sql, params));
            Ok(Vec::new())
        })
    }
    fn execute_delete(
        &self,
        _sql: &str,
        _params: Vec<FilterValue>,
    ) -> BoxFuture<'_, QueryResult<u64>> {
        Box::pin(async { Ok(0) })
    }
    fn execute_raw(&self, sql: &str, params: Vec<FilterValue>) -> BoxFuture<'_, QueryResult<u64>> {
        let recorded = self.recorded.clone();
        let sql = sql.to_string();
        Box::pin(async move {
            recorded.lock().unwrap().push((sql, params));
            Ok(1)
        })
    }
    fn count(&self, _sql: &str, _params: Vec<FilterValue>) -> BoxFuture<'_, QueryResult<u64>> {
        Box::pin(async { Ok(0) })
    }
}

impl SupportsNestedWrites for RecordingEngine {}
impl SupportsScalarSubqueryInSelect for RecordingEngine {}

// Canned row — returns plausible defaults for all scalar types so that
// `T::from_row(&CannedRow)` succeeds in `execute_insert` / `query_one`.
struct CannedRow;

impl RowRef for CannedRow {
    fn get_i32(&self, _column: &str) -> Result<i32, RowError> {
        Ok(1)
    }
    fn get_i32_opt(&self, _column: &str) -> Result<Option<i32>, RowError> {
        Ok(Some(1))
    }
    fn get_i64(&self, _column: &str) -> Result<i64, RowError> {
        Ok(0)
    }
    fn get_i64_opt(&self, _column: &str) -> Result<Option<i64>, RowError> {
        Ok(None)
    }
    fn get_f64(&self, _column: &str) -> Result<f64, RowError> {
        Ok(0.0)
    }
    fn get_f64_opt(&self, _column: &str) -> Result<Option<f64>, RowError> {
        Ok(None)
    }
    fn get_bool(&self, _column: &str) -> Result<bool, RowError> {
        Ok(false)
    }
    fn get_bool_opt(&self, _column: &str) -> Result<Option<bool>, RowError> {
        Ok(None)
    }
    fn get_str(&self, _column: &str) -> Result<&str, RowError> {
        Ok("canned")
    }
    fn get_str_opt(&self, _column: &str) -> Result<Option<&str>, RowError> {
        Ok(Some("canned"))
    }
    fn get_bytes(&self, _column: &str) -> Result<&[u8], RowError> {
        Ok(b"")
    }
    fn get_bytes_opt(&self, _column: &str) -> Result<Option<&[u8]>, RowError> {
        Ok(None)
    }
}

// ── Models ────────────────────────────────────────────────────────────────────

/// Derive-style model used by all aggregate e2e tests.
///
/// No cross-model relations are declared, so the `relation_helpers`
/// schema-path bug does not fire.
#[derive(Model, Debug, Clone, Default)]
#[prax(table = "users")]
pub struct User {
    #[prax(id, auto)]
    pub id: i32,
    #[prax(unique)]
    pub email: String,
    pub team_id: i32,
    pub region: String,
    pub active: bool,
    pub views: i32,
    pub score: i32,
}

client!(User);

// ── Test 1: count! select — per-column COUNT emission ─────────────────────────

/// `count! select: { _all: true, email: true }` (runtime equiv):
/// emits `COUNT(*)` and `COUNT(email)` in SELECT.
///
/// Uses the runtime `count_column` / `count` builder methods because the
/// `count!` select macro requires codegen-emitted `UserCountSelect` structs.
#[test]
fn count_select_emits_per_column_counts() {
    let op: AggregateOperation<User, RecordingEngine> = AggregateOperation::new()
        .count() // _all: true  → COUNT(*)
        .count_column("email"); // email: true → COUNT(email)

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(sql.contains("COUNT(*)"), "missing COUNT(*); got: {sql}");
    assert!(
        sql.contains("COUNT(\"email\")"),
        "missing COUNT(email); got: {sql}"
    );
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

// ── Test 2: aggregate! — all five functions ───────────────────────────────────

/// `aggregate! { _sum: { views }, _avg: { score }, _min: { views },
///               _max: { views }, _count: { _all } }` (runtime equiv):
/// emits SUM, AVG, MIN, MAX, COUNT(*) in a single SELECT.
#[test]
fn aggregate_emits_all_five_functions() {
    let op: AggregateOperation<User, RecordingEngine> = AggregateOperation::new()
        .sum("views")
        .avg("score")
        .min("views")
        .max("views")
        .count();

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(
        sql.contains("SUM(\"views\")"),
        "missing SUM(views); got: {sql}"
    );
    assert!(
        sql.contains("AVG(\"score\")"),
        "missing AVG(score); got: {sql}"
    );
    assert!(
        sql.contains("MIN(\"views\")"),
        "missing MIN(views); got: {sql}"
    );
    assert!(
        sql.contains("MAX(\"views\")"),
        "missing MAX(views); got: {sql}"
    );
    assert!(sql.contains("COUNT(*)"), "missing COUNT(*); got: {sql}");
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

// ── Test 3: aggregate! where — WHERE clause filtering ────────────────────────

/// `aggregate! { where: { active: true }, _count: { _all } }` (runtime equiv):
/// emits a WHERE clause containing the `active` column and records the param.
#[test]
fn aggregate_where_filters_underlying_select() {
    let op: AggregateOperation<User, RecordingEngine> = AggregateOperation::new()
        .count()
        .r#where(Filter::Equals("active".into(), FilterValue::Bool(true)));

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(sql.contains("WHERE"), "missing WHERE clause; got: {sql}");
    assert!(
        sql.contains("active"),
        "missing `active` column in WHERE; got: {sql}"
    );
    assert_eq!(params.len(), 1, "expected exactly 1 param; got: {params:?}");
    assert_eq!(
        params[0],
        FilterValue::Bool(true),
        "param should be Bool(true); got: {:?}",
        params[0]
    );
}

// ── Test 4: group_by! — GROUP BY clause ──────────────────────────────────────

/// `group_by!(c.user, { by: [team_id, region], _count: { _all } })` (runtime equiv):
/// emits `GROUP BY team_id, region` and `COUNT(*)` in SELECT.
#[test]
fn group_by_emits_group_by_clause() {
    let op: GroupByOperation<User, RecordingEngine> =
        GroupByOperation::new(vec!["team_id".into(), "region".into()]).count();

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(
        sql.contains("GROUP BY \"team_id\", \"region\""),
        "missing GROUP BY clause; got: {sql}"
    );
    assert!(sql.contains("COUNT(*)"), "missing COUNT(*); got: {sql}");
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

// ── Test 5: group_by! having — HAVING clause ─────────────────────────────────

/// `group_by!(c.user, { by: [team_id], _count: { _all },
///             having: { _count: { _all: { gt: 5 } } } })` (runtime equiv):
/// emits `HAVING COUNT(*) > 5`.
///
/// Note: HAVING thresholds are inlined as float literals, not parameterized.
#[test]
fn group_by_having_emits_having_clause() {
    let op: GroupByOperation<User, RecordingEngine> = GroupByOperation::new(vec!["team_id".into()])
        .count()
        .having(having::count_gt(5.0));

    let (sql, _params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(sql.contains("HAVING"), "missing HAVING clause; got: {sql}");
    assert!(
        sql.contains("COUNT(*) > $1"),
        "missing `COUNT(*) > $1` in HAVING; got: {sql}"
    );
}

// ── Test 6: aggregate! — omits unspecified blocks ────────────────────────────

/// `aggregate! { _sum: { views } }` (runtime equiv):
/// emits `SUM(views)` but NOT `AVG`, `MIN`, `MAX`, or `COUNT`.
#[test]
fn aggregate_omits_unspecified_blocks() {
    let op: AggregateOperation<User, RecordingEngine> = AggregateOperation::new().sum("views");

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(
        sql.contains("SUM(\"views\")"),
        "missing SUM(views); got: {sql}"
    );
    assert!(!sql.contains("AVG"), "unexpected AVG in SQL; got: {sql}");
    assert!(!sql.contains("MIN"), "unexpected MIN in SQL; got: {sql}");
    assert!(!sql.contains("MAX"), "unexpected MAX in SQL; got: {sql}");
    assert!(
        !sql.contains("COUNT"),
        "unexpected COUNT in SQL; got: {sql}"
    );
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

// ── Test 7: count_distinct — COUNT(DISTINCT col) SQL emission ────────────────

/// `count_distinct("region")` emits `COUNT(DISTINCT region) AS _count_distinct_region`.
#[test]
fn distinct_count_emits_count_distinct_sql() {
    let op: AggregateOperation<User, RecordingEngine> =
        AggregateOperation::new().count_distinct("region");

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(
        sql.contains("COUNT(DISTINCT \"region\")"),
        "missing COUNT(DISTINCT region); got: {sql}"
    );
    assert!(
        sql.contains("_count_distinct_region"),
        "missing alias _count_distinct_region; got: {sql}"
    );
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

// ── Test 8: group_by order_by — ORDER BY clause emission ─────────────────────

/// `GroupByOperation::new(vec!["team_id"]).sum("views").order_by(OrderByField::desc("_sum_views"))`
/// emits `ORDER BY _sum_views DESC`.
#[test]
fn group_by_order_by_emits_order_by_clause() {
    let op: GroupByOperation<User, RecordingEngine> = GroupByOperation::new(vec!["team_id".into()])
        .sum("views")
        .order_by(OrderByField::desc("_sum_views"));

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(
        sql.contains("ORDER BY"),
        "missing ORDER BY clause; got: {sql}"
    );
    assert!(
        sql.contains("_sum_views"),
        "missing _sum_views in ORDER BY; got: {sql}"
    );
    assert!(sql.contains("DESC"), "missing DESC in ORDER BY; got: {sql}");
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

// ── Test 9: AggregateResult hydration — per-column + distinct counts ──────────

/// `AggregateResult::from_row` correctly populates `count`, `count_of("email")`,
/// and `count_distinct_of("email")` from a raw HashMap.
#[test]
fn aggregate_result_hydrates_per_column_and_distinct_counts() {
    use std::collections::HashMap;

    let mut row: HashMap<String, prax_query::filter::FilterValue> = HashMap::new();
    row.insert(
        "_count".to_string(),
        prax_query::filter::FilterValue::Int(10),
    );
    row.insert(
        "_count_email".to_string(),
        prax_query::filter::FilterValue::Int(8),
    );
    row.insert(
        "_count_distinct_email".to_string(),
        prax_query::filter::FilterValue::Int(5),
    );

    let result = prax_query::operations::AggregateResult::from_row(row);

    assert_eq!(
        result.count,
        Some(10),
        "overall COUNT(*) should be 10; got: {:?}",
        result.count
    );
    assert_eq!(
        result.count_of("email"),
        Some(8),
        "COUNT(email) should be 8; got: {:?}",
        result.count_of("email")
    );
    assert_eq!(
        result.count_distinct_of("email"),
        Some(5),
        "COUNT(DISTINCT email) should be 5; got: {:?}",
        result.count_distinct_of("email")
    );
    // The distinct entry must not bleed into count_columns as "distinct_email".
    assert_eq!(
        result.count_of("distinct_email"),
        None,
        "distinct_email must not appear in count_columns"
    );
}

// ── Tests 10-12: macro-DSL emission through `aggregate!`/`group_by!`/`count!` ─
//
// These invoke the actual macros against the derive model above (accessor
// form mirrors `tests/read_macros_e2e.rs`).  Columns are restricted to the
// schema-fixture intersection (`id`/`email`/`active`) — see the header note.

use user::{AggregateOperationExt, GroupByOperationExt};

struct AppClient {
    user: user::Client<RecordingEngine>,
}

impl AppClient {
    fn new() -> Self {
        Self {
            user: user::Client::new(RecordingEngine::new()),
        }
    }
}

/// Test 10: `count!` with `select:` — the select block is passed directly to
/// the aggregate-select lowering, so the accepted syntax is flat
/// (`select: { _all: true, email: true }`; a nested `_count:` key would be a
/// compile error — see `count_select_value_not_true_fail.rs` ui fixture).
#[test]
fn count_macro_select_emits_per_column_counts() {
    let client = AppClient::new();
    let op = prax_orm::count!(client.user, {
        select: { _all: true, email: true },
    });

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(sql.contains("COUNT(*)"), "missing COUNT(*); got: {sql}");
    assert!(
        sql.contains("COUNT(\"email\")"),
        "missing COUNT(email); got: {sql}"
    );
    assert!(params.is_empty(), "no params expected; got: {params:?}");
}

/// Test 11: `aggregate!` — WHERE filter, `_sum`/`_avg` on a numeric column,
/// and `_count: { _all }` in one SELECT.
#[test]
fn aggregate_macro_emits_sum_avg_count_and_where() {
    let client = AppClient::new();
    let op = prax_orm::aggregate!(client.user, {
        where: { active: true },
        _sum: { id: true },
        _avg: { id: true },
        _count: { _all: true },
    });

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(sql.contains("SUM(\"id\")"), "missing SUM(id); got: {sql}");
    assert!(sql.contains("AVG(\"id\")"), "missing AVG(id); got: {sql}");
    assert!(sql.contains("COUNT(*)"), "missing COUNT(*); got: {sql}");
    assert!(sql.contains("WHERE"), "missing WHERE clause; got: {sql}");
    assert_eq!(params.len(), 1, "one WHERE param expected; got: {params:?}");
    assert_eq!(params[0], FilterValue::Bool(true));
}

/// Test 12: `group_by!` — `by:` columns, an aggregate, and a `having:`
/// predicate (parameterized after the HAVING-binding fix).
#[test]
fn group_by_macro_emits_group_by_aggregate_and_having() {
    let client = AppClient::new();
    let op = prax_orm::group_by!(client.user, {
        by: [active, email],
        _count: { _all: true },
        _sum: { id: true },
        having: { _count: { _all: { gt: 5 } } },
    });

    let (sql, params) = op.build_sql(&prax_query::dialect::Postgres);

    assert!(
        sql.contains("GROUP BY \"active\", \"email\""),
        "missing GROUP BY clause; got: {sql}"
    );
    assert!(sql.contains("COUNT(*)"), "missing COUNT(*); got: {sql}");
    assert!(sql.contains("SUM(\"id\")"), "missing SUM(id); got: {sql}");
    assert!(
        sql.contains("HAVING COUNT(*) > $1"),
        "missing parameterized HAVING; got: {sql}"
    );
    assert!(
        params.iter().any(|p| matches!(p, FilterValue::Float(_))),
        "HAVING param expected; got: {params:?}"
    );
}