Skip to main content

rustf/models/
model_query.rs

1//! Model-scoped query builder for RustF framework
2//!
3//! This module provides a ModelQuery struct that enables Laravel-style
4//! model queries like `UserModel::query().where_eq("email", email).first().await?`
5
6use crate::database::types::SqlValue;
7use crate::db::DB;
8use crate::error::{Error, Result};
9use crate::models::base_model::BaseModel;
10use crate::models::filter::ModelFilter;
11use crate::models::paged_result::PagedResult;
12use crate::models::query_builder::{
13    DatabaseBackend, JoinClause, JoinType, OrderByClause, OrderDirection, QueryBuilder, QueryError,
14    WhereCondition, WhereConnector,
15};
16use std::marker::PhantomData;
17
18/// Model-scoped query builder that provides type-safe, chainable query operations
19///
20/// This struct wraps the generic QueryBuilder and provides model-specific
21/// functionality with automatic table names and typed results.
22pub struct ModelQuery<T> {
23    query_builder: QueryBuilder,
24    _phantom: PhantomData<T>,
25}
26
27impl<T: BaseModel> ModelQuery<T> {
28    /// Create a new ModelQuery for the specified table
29    ///
30    /// This is typically called from the model's `query()` method rather than directly.
31    pub fn new(table_name: &str) -> Result<Self> {
32        let query_builder = DB::query()?.from(table_name);
33
34        Ok(Self {
35            query_builder,
36            _phantom: PhantomData,
37        })
38    }
39
40    // =========================================================================
41    // TABLE ALIASING
42    // =========================================================================
43
44    /// Set an alias for the main table
45    ///
46    /// This is useful for:
47    /// - Self-joins (joining the same table multiple times)
48    /// - Simplifying long table names
49    /// - Making queries more readable
50    ///
51    /// # Example
52    /// ```ignore
53    /// // Simple aliasing
54    /// let users = Users::query()?
55    ///     .alias("u")
56    ///     .select(&["u.id", "u.name"])
57    ///     .where_eq("u.is_active", true)
58    ///     .get()
59    ///     .await?;
60    ///
61    /// // Self-join for hierarchical data
62    /// let employees = Users::query()?
63    ///     .alias("emp")
64    ///     .select(&["emp.name as employee", "mgr.name as manager"])
65    ///     .left_join("users AS mgr", "mgr.id = emp.manager_id")
66    ///     .where_not_null("emp.manager_id")
67    ///     .get_raw()
68    ///     .await?;
69    /// ```
70    pub fn alias(mut self, alias: &str) -> Self {
71        self.query_builder = self.query_builder.as_alias(alias);
72        self
73    }
74
75    // =========================================================================
76    // WHERE CONDITIONS
77    // =========================================================================
78
79    /// Add WHERE column = value condition
80    pub fn where_eq<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
81        self.query_builder = self.query_builder.where_eq(column, value);
82        self
83    }
84
85    /// Add WHERE column != value condition
86    pub fn where_ne<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
87        self.query_builder = self.query_builder.where_ne(column, value);
88        self
89    }
90
91    /// Add WHERE column > value condition
92    pub fn where_gt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
93        self.query_builder = self.query_builder.where_gt(column, value);
94        self
95    }
96
97    /// Add WHERE column < value condition
98    pub fn where_lt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
99        self.query_builder = self.query_builder.where_lt(column, value);
100        self
101    }
102
103    /// Add WHERE column >= value condition
104    pub fn where_gte<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
105        self.query_builder = self.query_builder.where_gte(column, value);
106        self
107    }
108
109    /// Add WHERE column <= value condition
110    pub fn where_lte<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
111        self.query_builder = self.query_builder.where_lte(column, value);
112        self
113    }
114
115    /// Add WHERE column LIKE value condition
116    pub fn where_like<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
117        self.query_builder = self.query_builder.where_like(column, value);
118        self
119    }
120
121    /// Add WHERE column NOT LIKE value condition
122    pub fn where_not_like(mut self, column: &str, pattern: &str) -> Self {
123        self.query_builder = self.query_builder.where_not_like(column, pattern);
124        self
125    }
126
127    /// Add WHERE column IN (values) condition
128    pub fn where_in<V: Into<SqlValue>>(mut self, column: &str, values: Vec<V>) -> Self {
129        self.query_builder = self.query_builder.where_in(column, values);
130        self
131    }
132
133    /// Add WHERE column NOT IN (values) condition
134    pub fn where_not_in<V: Into<SqlValue>>(mut self, column: &str, values: Vec<V>) -> Self {
135        self.query_builder = self.query_builder.where_not_in(column, values);
136        self
137    }
138
139    /// Add WHERE column BETWEEN start AND end condition
140    pub fn where_between<V: Into<SqlValue>>(mut self, column: &str, start: V, end: V) -> Self {
141        self.query_builder = self.query_builder.where_between(column, start, end);
142        self
143    }
144
145    /// Add WHERE column IS NULL condition
146    pub fn where_null(mut self, column: &str) -> Self {
147        self.query_builder = self.query_builder.where_null(column);
148        self
149    }
150
151    /// Add WHERE column IS NOT NULL condition
152    pub fn where_not_null(mut self, column: &str) -> Self {
153        self.query_builder = self.query_builder.where_not_null(column);
154        self
155    }
156
157    /// Apply a reusable filter to this query
158    ///
159    /// This allows you to define common filters once and apply them to multiple queries.
160    ///
161    /// # Example
162    /// ```ignore
163    /// let active_filter = ModelFilter::new()
164    ///     .where_eq("is_active", true)
165    ///     .where_not_null("verified_at");
166    ///
167    /// let count = Users::query()?
168    ///     .apply_filter(&active_filter)
169    ///     .count()
170    ///     .await?;
171    ///
172    /// let users = Users::query()?
173    ///     .apply_filter(&active_filter)
174    ///     .limit(10)
175    ///     .get()
176    ///     .await?;
177    /// ```
178    pub fn apply_filter(mut self, filter: &ModelFilter) -> Self {
179        // Apply each condition from the filter to the query builder
180        self.query_builder
181            .where_conditions
182            .extend(filter.get_conditions().iter().cloned());
183        self
184    }
185
186    // =========================================================================
187    // OR WHERE CONDITIONS
188    // =========================================================================
189
190    /// Add OR WHERE column = value condition
191    pub fn or_where_eq<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
192        self.query_builder = self.query_builder.or_where_eq(column, value);
193        self
194    }
195
196    /// Add OR WHERE column != value condition
197    pub fn or_where_ne<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
198        self.query_builder = self.query_builder.or_where_ne(column, value);
199        self
200    }
201
202    /// Add OR WHERE column > value condition
203    pub fn or_where_gt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
204        self.query_builder = self.query_builder.or_where_gt(column, value);
205        self
206    }
207
208    /// Add OR WHERE column < value condition
209    pub fn or_where_lt<V: Into<SqlValue>>(mut self, column: &str, value: V) -> Self {
210        self.query_builder = self.query_builder.or_where_lt(column, value);
211        self
212    }
213
214    /// Add OR WHERE column LIKE pattern condition
215    pub fn or_where_like(mut self, column: &str, pattern: &str) -> Self {
216        self.query_builder = self.query_builder.or_where_like(column, pattern);
217        self
218    }
219
220    /// Add OR WHERE column IN (values) condition
221    pub fn or_where_in<V: Into<SqlValue>>(mut self, column: &str, values: Vec<V>) -> Self {
222        self.query_builder = self.query_builder.or_where_in(column, values);
223        self
224    }
225
226    /// Add OR WHERE column IS NULL condition
227    pub fn or_where_null(mut self, column: &str) -> Self {
228        self.query_builder = self.query_builder.or_where_null(column);
229        self
230    }
231
232    // =========================================================================
233    // FIELD SELECTION
234    // =========================================================================
235
236    /// Select specific fields instead of SELECT *
237    ///
238    /// # Example
239    /// ```ignore
240    /// // Select specific columns
241    /// let users = Users::query()?
242    ///     .select(&["id", "name", "email"])
243    ///     .where_eq("is_active", true)
244    ///     .get()
245    ///     .await?;
246    ///
247    /// // Select with table prefixes (useful for JOINs)
248    /// let results = Users::query()?
249    ///     .select(&["users.id", "users.name", "posts.title"])
250    ///     .join("posts", "posts.user_id = users.id")
251    ///     .get()
252    ///     .await?;
253    /// ```
254    pub fn select(mut self, columns: &[&str]) -> Self {
255        let columns_vec: Vec<String> = columns.iter().map(|s| s.to_string()).collect();
256        self.query_builder = self.query_builder.select(columns_vec);
257        self
258    }
259
260    /// Select with raw SQL expressions
261    ///
262    /// Use this for complex selections including SQL functions and aggregations.
263    ///
264    /// # Example
265    /// ```ignore
266    /// let results = Users::query()?
267    ///     .select_raw(&[
268    ///         "users.name",
269    ///         "COUNT(posts.id) as post_count",
270    ///         "MAX(posts.created_at) as latest_post"
271    ///     ])
272    ///     .left_join("posts", "posts.user_id = users.id")
273    ///     .group_by(&["users.id", "users.name"])
274    ///     .get_raw()
275    ///     .await?;
276    /// ```
277    pub fn select_raw(mut self, expressions: &[&str]) -> Self {
278        let expr_vec: Vec<String> = expressions.iter().map(|s| s.to_string()).collect();
279        self.query_builder = self.query_builder.select(expr_vec);
280        self
281    }
282
283    // =========================================================================
284    // ORDERING AND LIMITS
285    // =========================================================================
286
287    /// Add ORDER BY column ASC/DESC
288    pub fn order_by(mut self, column: &str, direction: OrderDirection) -> Self {
289        self.query_builder = self.query_builder.order_by(column, direction);
290        self
291    }
292
293    /// Set LIMIT
294    pub fn limit(mut self, limit: i64) -> Self {
295        self.query_builder = self.query_builder.limit(limit);
296        self
297    }
298
299    /// Set OFFSET
300    pub fn offset(mut self, offset: i64) -> Self {
301        self.query_builder = self.query_builder.offset(offset);
302        self
303    }
304
305    /// Paginate results (page starts at 1)
306    pub fn paginate(mut self, page: u32, per_page: u32) -> Self {
307        self.query_builder = self.query_builder.paginate(page, per_page);
308        self
309    }
310
311    // =========================================================================
312    // GROUPING
313    // =========================================================================
314
315    /// Add GROUP BY clause
316    ///
317    /// # Example
318    /// ```ignore
319    /// let results = Users::query()?
320    ///     .select_raw(&["department", "COUNT(*) as count"])
321    ///     .group_by(&["department"])
322    ///     .get_raw()
323    ///     .await?;
324    /// ```
325    pub fn group_by(mut self, columns: &[&str]) -> Self {
326        for column in columns {
327            self.query_builder = self.query_builder.group_by(column.to_string());
328        }
329        self
330    }
331
332    // =========================================================================
333    // JOINS (if needed)
334    // =========================================================================
335
336    /// Add INNER JOIN
337    pub fn join(mut self, table: &str, on: &str) -> Self {
338        self.query_builder = self.query_builder.join(table, on);
339        self
340    }
341
342    /// Add LEFT JOIN
343    pub fn left_join(mut self, table: &str, on: &str) -> Self {
344        self.query_builder = self.query_builder.left_join(table, on);
345        self
346    }
347
348    // =========================================================================
349    // QUERY EXECUTION - Returns Model Instances
350    // =========================================================================
351
352    /// Execute query and return all matching records
353    ///
354    /// # Returns
355    /// * `Ok(Vec<T>)` - All records matching the query
356    /// * `Err(Error)` - If query execution fails
357    ///
358    /// # Examples
359    /// ```ignore
360    /// let users = Users::query()
361    ///     .where_eq("is_active", 1)
362    ///     .order_by("created_at", OrderDirection::Desc)
363    ///     .get_all()
364    ///     .await?;
365    /// ```
366    pub async fn get_all(self) -> Result<Vec<T>> {
367        let (sql, params) = self
368            .query_builder
369            .build()
370            .map_err(|e| Error::template(format!("Query build failed: {}", e)))?;
371
372        T::execute_select_query(&sql, params)
373            .await
374            .map_err(|e| Error::template(format!("Query execution failed: {}", e)))
375    }
376
377    /// Execute query and return the first matching record
378    ///
379    /// Automatically adds LIMIT 1 to the query for efficiency.
380    ///
381    /// # Returns
382    /// * `Ok(Some(T))` - First record if found
383    /// * `Ok(None)` - If no records match
384    /// * `Err(Error)` - If query execution fails
385    pub async fn get_first(mut self) -> Result<Option<T>> {
386        // Add LIMIT 1 for efficiency
387        self.query_builder = self.query_builder.limit(1);
388
389        let results = self.get_all().await?;
390        Ok(results.into_iter().next())
391    }
392
393    /// Find a record by its primary key ID
394    ///
395    /// This is a convenience method that adds WHERE id = ? to the query.
396    ///
397    /// # Arguments
398    /// * `id` - The primary key value to search for
399    ///
400    /// # Returns
401    /// * `Ok(Some(T))` - Record if found
402    /// * `Ok(None)` - If no record with that ID exists
403    /// * `Err(Error)` - If query execution fails
404    pub async fn get_by_id(mut self, id: T::IdType) -> Result<Option<T>> {
405        self.query_builder = self.query_builder.where_eq(T::PRIMARY_KEY, id.into());
406        self.get_first().await
407    }
408
409    /// Get one record (alias for get_first)
410    ///
411    /// This is an alias that AI agents and developers often expect.
412    ///
413    /// # Returns
414    /// * `Ok(Some(T))` - First record if found
415    /// * `Ok(None)` - If no records match
416    /// * `Err(Error)` - If query execution fails
417    pub async fn get_one(self) -> Result<Option<T>> {
418        self.get_first().await
419    }
420
421    // Deprecated aliases for backward compatibility
422
423    /// Execute query and return all matching records
424    ///
425    /// **DEPRECATED**: Use `get_all()` instead
426    #[deprecated(since = "0.2.0", note = "Please use `get_all()` instead")]
427    pub async fn get(self) -> Result<Vec<T>> {
428        self.get_all().await
429    }
430
431    /// Execute query and return the first matching record
432    ///
433    /// **DEPRECATED**: Use `get_first()` instead
434    #[deprecated(since = "0.2.0", note = "Please use `get_first()` instead")]
435    pub async fn first(self) -> Result<Option<T>> {
436        self.get_first().await
437    }
438
439    /// Find a record by its primary key ID
440    ///
441    /// **DEPRECATED**: Use `get_by_id()` instead
442    #[deprecated(since = "0.2.0", note = "Please use `get_by_id()` instead")]
443    pub async fn find(self, id: T::IdType) -> Result<Option<T>> {
444        self.get_by_id(id).await
445    }
446
447    fn extract_count_from_json(value: serde_json::Value) -> Result<i64> {
448        fn to_i64(val: &serde_json::Value) -> Option<i64> {
449            match val {
450                serde_json::Value::Number(n) => n.as_i64().or_else(|| n.as_u64().map(|u| u as i64)),
451                serde_json::Value::String(s) => s.parse::<i64>().ok(),
452                _ => None,
453            }
454        }
455
456        if let Some(i) = to_i64(&value) {
457            return Ok(i);
458        }
459
460        if let serde_json::Value::Object(map) = value {
461            for key in ["count", "COUNT(*)", "count(*)", "COUNT(1)"] {
462                if let Some(val) = map.get(key).and_then(to_i64) {
463                    return Ok(val);
464                }
465            }
466
467            if map.len() == 1 {
468                if let Some((_key, val)) = map.iter().next() {
469                    if let Some(i) = to_i64(val) {
470                        return Ok(i);
471                    }
472                }
473            }
474        }
475
476        Err(Error::template(
477            "Count query did not return a numeric result",
478        ))
479    }
480
481    /// Count the number of records matching the query
482    ///
483    /// # Returns
484    /// * `Ok(i64)` - Number of matching records
485    /// * `Err(Error)` - If query execution fails
486    pub async fn count(mut self) -> Result<i64> {
487        // Replace SELECT with COUNT(*)
488        self.query_builder = self.query_builder.count();
489
490        let (sql, params) = self
491            .query_builder
492            .build()
493            .map_err(|e| Error::template(format!("Count query build failed: {}", e)))?;
494
495        let row = DB::fetch_one_with_params(&sql, params)
496            .await
497            .map_err(|e| Error::template(format!("Count query failed: {}", e)))?;
498
499        match row {
500            Some(value) => Self::extract_count_from_json(value),
501            None => Ok(0),
502        }
503    }
504
505    /// Check if any records exist matching the query
506    ///
507    /// This is more efficient than counting when you only need to know
508    /// if records exist.
509    ///
510    /// # Returns
511    /// * `Ok(true)` - At least one record exists
512    /// * `Ok(false)` - No records match
513    /// * `Err(Error)` - If query execution fails
514    pub async fn exists(self) -> Result<bool> {
515        let count = self.count().await?;
516        Ok(count > 0)
517    }
518
519    /// Execute raw query and return results as JSON
520    ///
521    /// This is useful for queries with custom SELECT expressions, aggregations,
522    /// or complex JOINs that don't map directly to the model structure.
523    ///
524    /// # Returns
525    ///
526    /// A vector of JSON objects representing the query results.
527    ///
528    /// # Example
529    ///
530    /// ```ignore
531    /// let results = Users::query()?
532    ///     .select_raw(&[
533    ///         "department",
534    ///         "COUNT(*) as user_count",
535    ///         "AVG(salary) as avg_salary"
536    ///     ])
537    ///     .group_by(&["department"])
538    ///     .get_raw()
539    ///     .await?;
540    ///
541    /// for row in results {
542    ///     let dept = row["department"].as_str().unwrap();
543    ///     let count = row["user_count"].as_i64().unwrap();
544    ///     let avg_salary = row["avg_salary"].as_f64().unwrap();
545    ///     println!("{}: {} users, avg salary: {}", dept, count, avg_salary);
546    /// }
547    /// ```
548    pub async fn get_raw(self) -> Result<Vec<serde_json::Value>> {
549        let (sql, params) = self
550            .query_builder
551            .build()
552            .map_err(|e| Error::template(format!("Query build failed: {}", e)))?;
553
554        let rows = DB::fetch_all_with_params(&sql, params)
555            .await
556            .map_err(|e| Error::database_query(e.to_string()))?;
557
558        Ok(rows)
559    }
560
561    /// Get the underlying QueryBuilder for advanced operations
562    ///
563    /// This provides access to the raw QueryBuilder if you need functionality
564    /// not exposed by ModelQuery.
565    pub fn query_builder(&self) -> &QueryBuilder {
566        &self.query_builder
567    }
568
569    /// Get the raw SQL and parameters (for debugging)
570    ///
571    /// # Returns
572    /// * `Ok((String, Vec<SqlValue>))` - SQL string and parameters
573    /// * `Err(QueryError)` - If query building fails
574    pub fn to_sql(&self) -> std::result::Result<(String, Vec<SqlValue>), QueryError> {
575        self.query_builder.build()
576    }
577
578    // =========================================================================
579    // PAGINATION WITH METADATA
580    // =========================================================================
581
582    /// Extract query conditions for reuse in COUNT and SELECT queries
583    fn extract_query_parts(&self) -> QueryParts {
584        QueryParts {
585            table: self.query_builder.table.clone(),
586            table_alias: self.query_builder.table_alias.clone(),
587            where_conditions: self.query_builder.where_conditions.clone(),
588            joins: self.query_builder.joins.clone(),
589            order_by: self.query_builder.order_by.clone(),
590            group_by: self.query_builder._group_by.clone(),
591            having_conditions: self.query_builder._having_conditions.clone(),
592            backend: self.query_builder.backend,
593        }
594    }
595
596    /// Apply extracted conditions to a QueryBuilder
597    fn apply_conditions_to_builder(mut builder: QueryBuilder, parts: &QueryParts) -> QueryBuilder {
598        // Apply table alias if present
599        if let Some(ref alias) = parts.table_alias {
600            builder = builder.as_alias(alias.clone());
601        }
602
603        // Apply WHERE conditions
604        for condition in &parts.where_conditions {
605            match condition.connector {
606                WhereConnector::And => {
607                    builder = match condition.operator.as_str() {
608                        "=" => builder.where_eq(&condition.column, condition.value.clone()),
609                        "!=" => builder.where_ne(&condition.column, condition.value.clone()),
610                        ">" => builder.where_gt(&condition.column, condition.value.clone()),
611                        "<" => builder.where_lt(&condition.column, condition.value.clone()),
612                        // Note: where_gte and where_lte may not exist in QueryBuilder
613                        // They are handled via where_raw if needed
614                        _ if condition.operator == ">=" => {
615                            builder.where_raw(&format!("{} >= ?", condition.column))
616                        }
617                        _ if condition.operator == "<=" => {
618                            builder.where_raw(&format!("{} <= ?", condition.column))
619                        }
620                        "IS" if matches!(condition.value, SqlValue::Null) => {
621                            builder.where_null(&condition.column)
622                        }
623                        "IS NOT" if matches!(condition.value, SqlValue::Null) => {
624                            builder.where_not_null(&condition.column)
625                        }
626                        _ if condition.operator.starts_with("LIKE") => {
627                            if let SqlValue::String(ref pattern) = condition.value {
628                                builder.where_like(&condition.column, pattern)
629                            } else {
630                                builder
631                            }
632                        }
633                        _ if condition.operator.starts_with("IN") => {
634                            // IN clause is already formatted in operator
635                            builder
636                                .where_raw(&format!("{} {}", condition.column, condition.operator))
637                        }
638                        _ => builder
639                            .where_raw(&format!("{} {} ?", condition.column, condition.operator)),
640                    };
641                }
642                WhereConnector::Or => {
643                    builder = match condition.operator.as_str() {
644                        "=" => builder.or_where_eq(&condition.column, condition.value.clone()),
645                        "!=" => builder.or_where_ne(&condition.column, condition.value.clone()),
646                        ">" => builder.or_where_gt(&condition.column, condition.value.clone()),
647                        "<" => builder.or_where_lt(&condition.column, condition.value.clone()),
648                        "IS" if matches!(condition.value, SqlValue::Null) => {
649                            builder.or_where_null(&condition.column)
650                        }
651                        _ => builder.where_raw(&format!(
652                            "OR {} {} ?",
653                            condition.column, condition.operator
654                        )),
655                    };
656                }
657            }
658        }
659
660        // Apply JOINs
661        // Note: We need to handle right_join specially since it returns Result
662        // For now, we'll skip right joins in the count query to avoid complexity
663        for join in &parts.joins {
664            builder = match join.join_type {
665                JoinType::Inner => builder.join(join.table.clone(), join.on_condition.clone()),
666                JoinType::Left => builder.left_join(join.table.clone(), join.on_condition.clone()),
667                JoinType::Right | JoinType::Full => {
668                    // Right and Full joins are complex to handle here
669                    // For COUNT queries, we can skip them as they don't affect the count
670                    // The SELECT query will still have them from the original builder
671                    builder
672                }
673            };
674        }
675
676        // Apply GROUP BY
677        for group_col in &parts.group_by {
678            builder = builder.group_by(group_col.clone());
679        }
680
681        builder
682    }
683
684    /// Execute paginated query and return results with pagination metadata
685    ///
686    /// This method executes two queries:
687    /// 1. A COUNT query to get the total number of matching records (WITHOUT LIMIT/OFFSET/ORDER BY)
688    /// 2. A SELECT query to get the actual data for the current page (WITH all conditions + pagination)
689    ///
690    /// # Arguments
691    /// * `page` - Page number (1-based)
692    /// * `per_page` - Number of items per page
693    ///
694    /// # Returns
695    /// * `Ok(PagedResult<T>)` - Paginated results with metadata
696    /// * `Err(Error)` - If query execution fails
697    ///
698    /// # Example
699    ///
700    /// ```ignore
701    /// let result = Users::query()?
702    ///     .where_eq("is_active", true)
703    ///     .order_by("created_at", OrderDirection::Desc)
704    ///     .get_paginated(2, 20)
705    ///     .await?;
706    ///
707    /// // Access the data
708    /// for user in &result.rows {
709    ///     println!("User: {}", user.name);
710    /// }
711    ///
712    /// // Access pagination metadata
713    /// println!("Page {} of {}", result.page, result.total_pages);
714    /// println!("Total rows: {}", result.total_rows);
715    /// ```
716    pub async fn get_paginated(mut self, page: u32, per_page: u32) -> Result<PagedResult<T>> {
717        // Extract query conditions before consuming the builder
718        let parts = self.extract_query_parts();
719
720        // Get table name (use model's TABLE_NAME if not set in query)
721        let table_name = parts
722            .table
723            .clone()
724            .unwrap_or_else(|| T::TABLE_NAME.to_string());
725
726        // Build COUNT query (WHERE + JOINs + GROUP BY/HAVING, but NO LIMIT/OFFSET/ORDER BY)
727        let mut count_builder = QueryBuilder::new(parts.backend).from(table_name.clone());
728        count_builder = Self::apply_conditions_to_builder(count_builder, &parts);
729
730        // Convert to COUNT query
731        count_builder = count_builder.count();
732
733        // Build SELECT query (WHERE + JOINs + ORDER BY + LIMIT/OFFSET)
734        // Use the original builder but ensure pagination is set
735        self.query_builder = self.query_builder.paginate(page, per_page);
736
737        // Execute both queries in parallel
738        let (total_result, rows_result) =
739            tokio::join!(Self::execute_count_query(count_builder), self.get_all());
740
741        let total_rows = total_result?;
742        let rows = rows_result?;
743
744        // Create PagedResult with calculated metadata
745        Ok(PagedResult::new(rows, page, per_page, total_rows))
746    }
747
748    /// Execute a COUNT query and return the total count
749    async fn execute_count_query(builder: QueryBuilder) -> Result<i64> {
750        let (sql, params) = builder
751            .build()
752            .map_err(|e| Error::template(format!("Count query build failed: {}", e)))?;
753
754        let row = DB::fetch_one_with_params(&sql, params)
755            .await
756            .map_err(|e| Error::template(format!("Count query failed: {}", e)))?;
757
758        match row {
759            Some(value) => Self::extract_count_from_json(value),
760            None => Ok(0),
761        }
762    }
763}
764
765/// Internal structure to hold extracted query parts for reuse
766#[allow(dead_code)] // order_by and having_conditions are kept for future use
767struct QueryParts {
768    table: Option<String>,
769    table_alias: Option<String>,
770    where_conditions: Vec<WhereCondition>,
771    joins: Vec<JoinClause>,
772    order_by: Vec<OrderByClause>, // Not used in COUNT query, but kept for consistency
773    group_by: Vec<String>,
774    having_conditions: Vec<WhereCondition>, // Not currently used, but kept for future HAVING support
775    backend: DatabaseBackend,
776}