prax-orm 0.10.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
//! 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 — why we use the runtime API here
//!
//! 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`.
//!
//! Derive-style models (using `#[derive(Model)]`) avoid the relation-helper
//! path issue when no cross-model relations are declared.  However the
//! `aggregate!`, `group_by!`, and `count!` macros with select still require
//! `AggregateArgs` / `GroupByArgs` structs that are only emitted by
//! schema-path codegen, not by the derive macro.  Because of this we use the
//! runtime builder API (`AggregateOperation` / `GroupByOperation`) directly,
//! mirroring the approach taken in `computed_fields_e2e.rs`.
//!
//! 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 AND
//! the derive macro emits `AggregateArgs` structs, the macro-DSL variants of
//! these tests can be re-enabled.

#![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(*) > 5"),
        "missing `COUNT(*) > 5` 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"
    );
}