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
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
//! Model-scoped query builder for RustF framework
//!
//! This module provides a ModelQuery struct that enables Laravel-style
//! model queries like `UserModel::query().where_eq("email", email).first().await?`
use crate::database::types::SqlValue;
use crate::db::DB;
use crate::error::{Error, Result};
use crate::models::base_model::BaseModel;
use crate::models::filter::ModelFilter;
use crate::models::paged_result::PagedResult;
use crate::models::query_builder::{
DatabaseBackend, JoinClause, JoinType, OrderByClause, OrderDirection, QueryBuilder, QueryError,
WhereCondition, WhereConnector,
};
use std::marker::PhantomData;
/// Model-scoped query builder that provides type-safe, chainable query operations
///
/// This struct wraps the generic QueryBuilder and provides model-specific
/// functionality with automatic table names and typed results.
pub struct ModelQuery<T> {
query_builder: QueryBuilder,
_phantom: PhantomData<T>,
}
impl<T: BaseModel> ModelQuery<T> {
/// Create a new ModelQuery for the specified table
///
/// This is typically called from the model's `query()` method rather than directly.
pub fn new(table_name: &str) -> Result<Self> {
let query_builder = DB::query()?.from(table_name);
Ok(Self {
query_builder,
_phantom: PhantomData,
})
}
// =========================================================================
// TABLE ALIASING
// =========================================================================
/// Set an alias for the main table
///
/// This is useful for:
/// - Self-joins (joining the same table multiple times)
/// - Simplifying long table names
/// - Making queries more readable
///
/// # Example
/// ```ignore
/// // Simple aliasing
/// let users = Users::query()?
/// .alias("u")
/// .select(&["u.id", "u.name"])
/// .where_eq("u.is_active", true)
/// .get()
/// .await?;
///
/// // Self-join for hierarchical data
/// let employees = Users::query()?
/// .alias("emp")
/// .select(&["emp.name as employee", "mgr.name as manager"])
/// .left_join("users AS mgr", "mgr.id = emp.manager_id")
/// .where_not_null("emp.manager_id")
/// .get_raw()
/// .await?;
/// ```
pub fn alias(mut self, alias: &str) -> Self {
self.query_builder = self.query_builder.as_alias(alias);
self
}
// =========================================================================
// WHERE CONDITIONS
// =========================================================================
/// Add WHERE column = value condition
pub fn where_eq<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_eq(column, value);
self
}
/// Add WHERE column != value condition
pub fn where_ne<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_ne(column, value);
self
}
/// Add WHERE column > value condition
pub fn where_gt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_gt(column, value);
self
}
/// Add WHERE column < value condition
pub fn where_lt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_lt(column, value);
self
}
/// Add WHERE column >= value condition
pub fn where_gte<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_gte(column, value);
self
}
/// Add WHERE column <= value condition
pub fn where_lte<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_lte(column, value);
self
}
/// Add WHERE column LIKE value condition
pub fn where_like<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.where_like(column, value);
self
}
/// Add WHERE column NOT LIKE value condition
pub fn where_not_like(mut self, column: &str, pattern: &str) -> Self {
self.query_builder = self.query_builder.where_not_like(column, pattern);
self
}
/// Add WHERE column IN (values) condition
pub fn where_in<V: Into<SqlValue>>(mut self, column: &str, values: Vec<V>) -> Self {
self.query_builder = self.query_builder.where_in(column, values);
self
}
/// Add WHERE column NOT IN (values) condition
pub fn where_not_in<V: Into<SqlValue>>(mut self, column: &str, values: Vec<V>) -> Self {
self.query_builder = self.query_builder.where_not_in(column, values);
self
}
/// Add WHERE column BETWEEN start AND end condition
pub fn where_between<V: Into<SqlValue>>(mut self, column: &str, start: V, end: V) -> Self {
self.query_builder = self.query_builder.where_between(column, start, end);
self
}
/// Add WHERE column IS NULL condition
pub fn where_null(mut self, column: &str) -> Self {
self.query_builder = self.query_builder.where_null(column);
self
}
/// Add WHERE column IS NOT NULL condition
pub fn where_not_null(mut self, column: &str) -> Self {
self.query_builder = self.query_builder.where_not_null(column);
self
}
/// Apply a reusable filter to this query
///
/// This allows you to define common filters once and apply them to multiple queries.
///
/// # Example
/// ```ignore
/// let active_filter = ModelFilter::new()
/// .where_eq("is_active", true)
/// .where_not_null("verified_at");
///
/// let count = Users::query()?
/// .apply_filter(&active_filter)
/// .count()
/// .await?;
///
/// let users = Users::query()?
/// .apply_filter(&active_filter)
/// .limit(10)
/// .get()
/// .await?;
/// ```
pub fn apply_filter(mut self, filter: &ModelFilter) -> Self {
// Apply each condition from the filter to the query builder
self.query_builder
.where_conditions
.extend(filter.get_conditions().iter().cloned());
self
}
// =========================================================================
// OR WHERE CONDITIONS
// =========================================================================
/// Add OR WHERE column = value condition
pub fn or_where_eq<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.or_where_eq(column, value);
self
}
/// Add OR WHERE column != value condition
pub fn or_where_ne<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.or_where_ne(column, value);
self
}
/// Add OR WHERE column > value condition
pub fn or_where_gt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.or_where_gt(column, value);
self
}
/// Add OR WHERE column < value condition
pub fn or_where_lt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
self.query_builder = self.query_builder.or_where_lt(column, value);
self
}
/// Add OR WHERE column LIKE pattern condition
pub fn or_where_like(mut self, column: &str, pattern: &str) -> Self {
self.query_builder = self.query_builder.or_where_like(column, pattern);
self
}
/// Add OR WHERE column IN (values) condition
pub fn or_where_in<V: Into<SqlValue>>(mut self, column: &str, values: Vec<V>) -> Self {
self.query_builder = self.query_builder.or_where_in(column, values);
self
}
/// Add OR WHERE column IS NULL condition
pub fn or_where_null(mut self, column: &str) -> Self {
self.query_builder = self.query_builder.or_where_null(column);
self
}
// =========================================================================
// FIELD SELECTION
// =========================================================================
/// Select specific fields instead of SELECT *
///
/// # Example
/// ```ignore
/// // Select specific columns
/// let users = Users::query()?
/// .select(&["id", "name", "email"])
/// .where_eq("is_active", true)
/// .get()
/// .await?;
///
/// // Select with table prefixes (useful for JOINs)
/// let results = Users::query()?
/// .select(&["users.id", "users.name", "posts.title"])
/// .join("posts", "posts.user_id = users.id")
/// .get()
/// .await?;
/// ```
pub fn select(mut self, columns: &[&str]) -> Self {
let columns_vec: Vec<String> = columns.iter().map(|s| s.to_string()).collect();
self.query_builder = self.query_builder.select(columns_vec);
self
}
/// Select with raw SQL expressions
///
/// Use this for complex selections including SQL functions and aggregations.
///
/// # Example
/// ```ignore
/// let results = Users::query()?
/// .select_raw(&[
/// "users.name",
/// "COUNT(posts.id) as post_count",
/// "MAX(posts.created_at) as latest_post"
/// ])
/// .left_join("posts", "posts.user_id = users.id")
/// .group_by(&["users.id", "users.name"])
/// .get_raw()
/// .await?;
/// ```
pub fn select_raw(mut self, expressions: &[&str]) -> Self {
let expr_vec: Vec<String> = expressions.iter().map(|s| s.to_string()).collect();
self.query_builder = self.query_builder.select(expr_vec);
self
}
// =========================================================================
// ORDERING AND LIMITS
// =========================================================================
/// Add ORDER BY column ASC/DESC
pub fn order_by(mut self, column: &str, direction: OrderDirection) -> Self {
self.query_builder = self.query_builder.order_by(column, direction);
self
}
/// Set LIMIT
pub fn limit(mut self, limit: i64) -> Self {
self.query_builder = self.query_builder.limit(limit);
self
}
/// Set OFFSET
pub fn offset(mut self, offset: i64) -> Self {
self.query_builder = self.query_builder.offset(offset);
self
}
/// Paginate results (page starts at 1)
pub fn paginate(mut self, page: u32, per_page: u32) -> Self {
self.query_builder = self.query_builder.paginate(page, per_page);
self
}
// =========================================================================
// GROUPING
// =========================================================================
/// Add GROUP BY clause
///
/// # Example
/// ```ignore
/// let results = Users::query()?
/// .select_raw(&["department", "COUNT(*) as count"])
/// .group_by(&["department"])
/// .get_raw()
/// .await?;
/// ```
pub fn group_by(mut self, columns: &[&str]) -> Self {
for column in columns {
self.query_builder = self.query_builder.group_by(column.to_string());
}
self
}
// =========================================================================
// JOINS (if needed)
// =========================================================================
/// Add INNER JOIN
pub fn join(mut self, table: &str, on: &str) -> Self {
self.query_builder = self.query_builder.join(table, on);
self
}
/// Add LEFT JOIN
pub fn left_join(mut self, table: &str, on: &str) -> Self {
self.query_builder = self.query_builder.left_join(table, on);
self
}
// =========================================================================
// QUERY EXECUTION - Returns Model Instances
// =========================================================================
/// Execute query and return all matching records
///
/// # Returns
/// * `Ok(Vec<T>)` - All records matching the query
/// * `Err(Error)` - If query execution fails
///
/// # Examples
/// ```ignore
/// let users = Users::query()
/// .where_eq("is_active", 1)
/// .order_by("created_at", OrderDirection::Desc)
/// .get_all()
/// .await?;
/// ```
pub async fn get_all(self) -> Result<Vec<T>> {
let (sql, params) = self
.query_builder
.build()
.map_err(|e| Error::template(format!("Query build failed: {}", e)))?;
T::execute_select_query(&sql, params)
.await
.map_err(|e| Error::template(format!("Query execution failed: {}", e)))
}
/// Execute query and return the first matching record
///
/// Automatically adds LIMIT 1 to the query for efficiency.
///
/// # Returns
/// * `Ok(Some(T))` - First record if found
/// * `Ok(None)` - If no records match
/// * `Err(Error)` - If query execution fails
pub async fn get_first(mut self) -> Result<Option<T>> {
// Add LIMIT 1 for efficiency
self.query_builder = self.query_builder.limit(1);
let results = self.get_all().await?;
Ok(results.into_iter().next())
}
/// Find a record by its primary key ID
///
/// This is a convenience method that adds WHERE id = ? to the query.
///
/// # Arguments
/// * `id` - The primary key value to search for
///
/// # Returns
/// * `Ok(Some(T))` - Record if found
/// * `Ok(None)` - If no record with that ID exists
/// * `Err(Error)` - If query execution fails
pub async fn get_by_id(mut self, id: T::IdType) -> Result<Option<T>> {
self.query_builder = self.query_builder.where_eq(T::PRIMARY_KEY, id.into());
self.get_first().await
}
/// Get one record (alias for get_first)
///
/// This is an alias that AI agents and developers often expect.
///
/// # Returns
/// * `Ok(Some(T))` - First record if found
/// * `Ok(None)` - If no records match
/// * `Err(Error)` - If query execution fails
pub async fn get_one(self) -> Result<Option<T>> {
self.get_first().await
}
// Deprecated aliases for backward compatibility
/// Execute query and return all matching records
///
/// **DEPRECATED**: Use `get_all()` instead
#[deprecated(since = "0.2.0", note = "Please use `get_all()` instead")]
pub async fn get(self) -> Result<Vec<T>> {
self.get_all().await
}
/// Execute query and return the first matching record
///
/// **DEPRECATED**: Use `get_first()` instead
#[deprecated(since = "0.2.0", note = "Please use `get_first()` instead")]
pub async fn first(self) -> Result<Option<T>> {
self.get_first().await
}
/// Find a record by its primary key ID
///
/// **DEPRECATED**: Use `get_by_id()` instead
#[deprecated(since = "0.2.0", note = "Please use `get_by_id()` instead")]
pub async fn find(self, id: T::IdType) -> Result<Option<T>> {
self.get_by_id(id).await
}
fn extract_count_from_json(value: serde_json::Value) -> Result<i64> {
fn to_i64(val: &serde_json::Value) -> Option<i64> {
match val {
serde_json::Value::Number(n) => n.as_i64().or_else(|| n.as_u64().map(|u| u as i64)),
serde_json::Value::String(s) => s.parse::<i64>().ok(),
_ => None,
}
}
if let Some(i) = to_i64(&value) {
return Ok(i);
}
if let serde_json::Value::Object(map) = value {
for key in ["count", "COUNT(*)", "count(*)", "COUNT(1)"] {
if let Some(val) = map.get(key).and_then(to_i64) {
return Ok(val);
}
}
if map.len() == 1 {
if let Some((_key, val)) = map.iter().next() {
if let Some(i) = to_i64(val) {
return Ok(i);
}
}
}
}
Err(Error::template(
"Count query did not return a numeric result",
))
}
/// Count the number of records matching the query
///
/// # Returns
/// * `Ok(i64)` - Number of matching records
/// * `Err(Error)` - If query execution fails
pub async fn count(mut self) -> Result<i64> {
// Replace SELECT with COUNT(*)
self.query_builder = self.query_builder.count();
let (sql, params) = self
.query_builder
.build()
.map_err(|e| Error::template(format!("Count query build failed: {}", e)))?;
let row = DB::fetch_one_with_params(&sql, params)
.await
.map_err(|e| Error::template(format!("Count query failed: {}", e)))?;
match row {
Some(value) => Self::extract_count_from_json(value),
None => Ok(0),
}
}
/// Check if any records exist matching the query
///
/// This is more efficient than counting when you only need to know
/// if records exist.
///
/// # Returns
/// * `Ok(true)` - At least one record exists
/// * `Ok(false)` - No records match
/// * `Err(Error)` - If query execution fails
pub async fn exists(self) -> Result<bool> {
let count = self.count().await?;
Ok(count > 0)
}
/// Execute raw query and return results as JSON
///
/// This is useful for queries with custom SELECT expressions, aggregations,
/// or complex JOINs that don't map directly to the model structure.
///
/// # Returns
///
/// A vector of JSON objects representing the query results.
///
/// # Example
///
/// ```ignore
/// let results = Users::query()?
/// .select_raw(&[
/// "department",
/// "COUNT(*) as user_count",
/// "AVG(salary) as avg_salary"
/// ])
/// .group_by(&["department"])
/// .get_raw()
/// .await?;
///
/// for row in results {
/// let dept = row["department"].as_str().unwrap();
/// let count = row["user_count"].as_i64().unwrap();
/// let avg_salary = row["avg_salary"].as_f64().unwrap();
/// println!("{}: {} users, avg salary: {}", dept, count, avg_salary);
/// }
/// ```
pub async fn get_raw(self) -> Result<Vec<serde_json::Value>> {
let (sql, params) = self
.query_builder
.build()
.map_err(|e| Error::template(format!("Query build failed: {}", e)))?;
let rows = DB::fetch_all_with_params(&sql, params)
.await
.map_err(|e| Error::database_query(e.to_string()))?;
Ok(rows)
}
/// Get the underlying QueryBuilder for advanced operations
///
/// This provides access to the raw QueryBuilder if you need functionality
/// not exposed by ModelQuery.
pub fn query_builder(&self) -> &QueryBuilder {
&self.query_builder
}
/// Get the raw SQL and parameters (for debugging)
///
/// # Returns
/// * `Ok((String, Vec<SqlValue>))` - SQL string and parameters
/// * `Err(QueryError)` - If query building fails
pub fn to_sql(&self) -> std::result::Result<(String, Vec<SqlValue>), QueryError> {
self.query_builder.build()
}
// =========================================================================
// PAGINATION WITH METADATA
// =========================================================================
/// Extract query conditions for reuse in COUNT and SELECT queries
fn extract_query_parts(&self) -> QueryParts {
QueryParts {
table: self.query_builder.table.clone(),
table_alias: self.query_builder.table_alias.clone(),
where_conditions: self.query_builder.where_conditions.clone(),
joins: self.query_builder.joins.clone(),
order_by: self.query_builder.order_by.clone(),
group_by: self.query_builder._group_by.clone(),
having_conditions: self.query_builder._having_conditions.clone(),
backend: self.query_builder.backend,
}
}
/// Apply extracted conditions to a QueryBuilder
fn apply_conditions_to_builder(mut builder: QueryBuilder, parts: &QueryParts) -> QueryBuilder {
// Apply table alias if present
if let Some(ref alias) = parts.table_alias {
builder = builder.as_alias(alias.clone());
}
// Apply WHERE conditions
for condition in &parts.where_conditions {
match condition.connector {
WhereConnector::And => {
builder = match condition.operator.as_str() {
"=" => builder.where_eq(&condition.column, condition.value.clone()),
"!=" => builder.where_ne(&condition.column, condition.value.clone()),
">" => builder.where_gt(&condition.column, condition.value.clone()),
"<" => builder.where_lt(&condition.column, condition.value.clone()),
// Note: where_gte and where_lte may not exist in QueryBuilder
// They are handled via where_raw if needed
_ if condition.operator == ">=" => {
builder.where_raw(&format!("{} >= ?", condition.column))
}
_ if condition.operator == "<=" => {
builder.where_raw(&format!("{} <= ?", condition.column))
}
"IS" if matches!(condition.value, SqlValue::Null) => {
builder.where_null(&condition.column)
}
"IS NOT" if matches!(condition.value, SqlValue::Null) => {
builder.where_not_null(&condition.column)
}
_ if condition.operator.starts_with("LIKE") => {
if let SqlValue::String(ref pattern) = condition.value {
builder.where_like(&condition.column, pattern)
} else {
builder
}
}
_ if condition.operator.starts_with("IN") => {
// IN clause is already formatted in operator
builder
.where_raw(&format!("{} {}", condition.column, condition.operator))
}
_ => builder
.where_raw(&format!("{} {} ?", condition.column, condition.operator)),
};
}
WhereConnector::Or => {
builder = match condition.operator.as_str() {
"=" => builder.or_where_eq(&condition.column, condition.value.clone()),
"!=" => builder.or_where_ne(&condition.column, condition.value.clone()),
">" => builder.or_where_gt(&condition.column, condition.value.clone()),
"<" => builder.or_where_lt(&condition.column, condition.value.clone()),
"IS" if matches!(condition.value, SqlValue::Null) => {
builder.or_where_null(&condition.column)
}
_ => builder.where_raw(&format!(
"OR {} {} ?",
condition.column, condition.operator
)),
};
}
}
}
// Apply JOINs
// Note: We need to handle right_join specially since it returns Result
// For now, we'll skip right joins in the count query to avoid complexity
for join in &parts.joins {
builder = match join.join_type {
JoinType::Inner => builder.join(join.table.clone(), join.on_condition.clone()),
JoinType::Left => builder.left_join(join.table.clone(), join.on_condition.clone()),
JoinType::Right | JoinType::Full => {
// Right and Full joins are complex to handle here
// For COUNT queries, we can skip them as they don't affect the count
// The SELECT query will still have them from the original builder
builder
}
};
}
// Apply GROUP BY
for group_col in &parts.group_by {
builder = builder.group_by(group_col.clone());
}
builder
}
/// Execute paginated query and return results with pagination metadata
///
/// This method executes two queries:
/// 1. A COUNT query to get the total number of matching records (WITHOUT LIMIT/OFFSET/ORDER BY)
/// 2. A SELECT query to get the actual data for the current page (WITH all conditions + pagination)
///
/// # Arguments
/// * `page` - Page number (1-based)
/// * `per_page` - Number of items per page
///
/// # Returns
/// * `Ok(PagedResult<T>)` - Paginated results with metadata
/// * `Err(Error)` - If query execution fails
///
/// # Example
///
/// ```ignore
/// let result = Users::query()?
/// .where_eq("is_active", true)
/// .order_by("created_at", OrderDirection::Desc)
/// .get_paginated(2, 20)
/// .await?;
///
/// // Access the data
/// for user in &result.rows {
/// println!("User: {}", user.name);
/// }
///
/// // Access pagination metadata
/// println!("Page {} of {}", result.page, result.total_pages);
/// println!("Total rows: {}", result.total_rows);
/// ```
pub async fn get_paginated(mut self, page: u32, per_page: u32) -> Result<PagedResult<T>> {
// Extract query conditions before consuming the builder
let parts = self.extract_query_parts();
// Get table name (use model's TABLE_NAME if not set in query)
let table_name = parts
.table
.clone()
.unwrap_or_else(|| T::TABLE_NAME.to_string());
// Build COUNT query (WHERE + JOINs + GROUP BY/HAVING, but NO LIMIT/OFFSET/ORDER BY)
let mut count_builder = QueryBuilder::new(parts.backend).from(table_name.clone());
count_builder = Self::apply_conditions_to_builder(count_builder, &parts);
// Convert to COUNT query
count_builder = count_builder.count();
// Build SELECT query (WHERE + JOINs + ORDER BY + LIMIT/OFFSET)
// Use the original builder but ensure pagination is set
self.query_builder = self.query_builder.paginate(page, per_page);
// Execute both queries in parallel
let (total_result, rows_result) =
tokio::join!(Self::execute_count_query(count_builder), self.get_all());
let total_rows = total_result?;
let rows = rows_result?;
// Create PagedResult with calculated metadata
Ok(PagedResult::new(rows, page, per_page, total_rows))
}
/// Execute a COUNT query and return the total count
async fn execute_count_query(builder: QueryBuilder) -> Result<i64> {
let (sql, params) = builder
.build()
.map_err(|e| Error::template(format!("Count query build failed: {}", e)))?;
let row = DB::fetch_one_with_params(&sql, params)
.await
.map_err(|e| Error::template(format!("Count query failed: {}", e)))?;
match row {
Some(value) => Self::extract_count_from_json(value),
None => Ok(0),
}
}
}
/// Internal structure to hold extracted query parts for reuse
#[allow(dead_code)] // order_by and having_conditions are kept for future use
struct QueryParts {
table: Option<String>,
table_alias: Option<String>,
where_conditions: Vec<WhereCondition>,
joins: Vec<JoinClause>,
order_by: Vec<OrderByClause>, // Not used in COUNT query, but kept for consistency
group_by: Vec<String>,
having_conditions: Vec<WhereCondition>, // Not currently used, but kept for future HAVING support
backend: DatabaseBackend,
}