Skip to main content

elif_orm/model/
query_methods.rs

1//! Query Methods - Collection and batch query operations for models
2//!
3//! Provides methods for querying multiple records, filtering, counting,
4//! and other collection-based database operations.
5
6use sqlx::{Pool, Postgres, Row};
7
8use crate::error::{ModelError, ModelResult};
9use crate::model::core_trait::Model;
10use crate::query::QueryBuilder;
11
12/// Trait providing query operations for model collections
13#[allow(async_fn_in_trait)]
14pub trait QueryMethods: Model {
15    // <<<ELIF:BEGIN agent-editable:model_query_methods>>>
16    /// Get a query builder for this model
17    fn query() -> QueryBuilder<Self>
18    where
19        Self: Sized,
20    {
21        let builder = QueryBuilder::new().from(Self::table_name());
22
23        // Exclude soft-deleted records by default
24        if Self::uses_soft_deletes() {
25            builder.where_null("deleted_at")
26        } else {
27            builder
28        }
29    }
30
31    /// Get all records for this model with proper SQL execution
32    async fn all(pool: &Pool<Postgres>) -> ModelResult<Vec<Self>>
33    where
34        Self: Sized,
35    {
36        let sql = if Self::uses_soft_deletes() {
37            format!(
38                "SELECT * FROM {} WHERE deleted_at IS NULL",
39                Self::table_name()
40            )
41        } else {
42            format!("SELECT * FROM {}", Self::table_name())
43        };
44
45        let rows = sqlx::query(&sql).fetch_all(pool).await.map_err(|e| {
46            ModelError::Database(format!(
47                "Failed to fetch all from {}: {}",
48                Self::table_name(),
49                e
50            ))
51        })?;
52
53        let mut models = Vec::new();
54        for row in rows {
55            models.push(Self::from_row(&row)?);
56        }
57
58        Ok(models)
59    }
60
61    /// Count all records for this model with proper SQL execution
62    async fn count(pool: &Pool<Postgres>) -> ModelResult<i64>
63    where
64        Self: Sized,
65    {
66        let sql = if Self::uses_soft_deletes() {
67            format!(
68                "SELECT COUNT(*) FROM {} WHERE deleted_at IS NULL",
69                Self::table_name()
70            )
71        } else {
72            format!("SELECT COUNT(*) FROM {}", Self::table_name())
73        };
74
75        let row = sqlx::query(&sql).fetch_one(pool).await.map_err(|e| {
76            ModelError::Database(format!("Failed to count {}: {}", Self::table_name(), e))
77        })?;
78
79        let count: i64 = row
80            .try_get(0)
81            .map_err(|e| ModelError::Database(format!("Failed to extract count: {}", e)))?;
82        Ok(count)
83    }
84
85    /// Find models by a specific field value with proper parameter binding
86    async fn where_field<V>(pool: &Pool<Postgres>, field: &str, value: V) -> ModelResult<Vec<Self>>
87    where
88        Self: Sized,
89        V: Send + Sync + 'static,
90        for<'q> V: sqlx::Encode<'q, Postgres> + sqlx::Type<Postgres>,
91    {
92        let sql = if Self::uses_soft_deletes() {
93            format!(
94                "SELECT * FROM {} WHERE {} = $1 AND deleted_at IS NULL",
95                Self::table_name(),
96                field
97            )
98        } else {
99            format!("SELECT * FROM {} WHERE {} = $1", Self::table_name(), field)
100        };
101
102        let rows = sqlx::query(&sql)
103            .bind(value)
104            .fetch_all(pool)
105            .await
106            .map_err(|e| {
107                ModelError::Database(format!(
108                    "Failed to query {} by {}: {}",
109                    Self::table_name(),
110                    field,
111                    e
112                ))
113            })?;
114
115        let mut models = Vec::new();
116        for row in rows {
117            models.push(Self::from_row(&row)?);
118        }
119
120        Ok(models)
121    }
122
123    /// Find the first model by a specific field value
124    async fn first_where<V>(
125        pool: &Pool<Postgres>,
126        field: &str,
127        value: V,
128    ) -> ModelResult<Option<Self>>
129    where
130        Self: Sized,
131        V: Send + Sync + 'static,
132        for<'q> V: sqlx::Encode<'q, Postgres> + sqlx::Type<Postgres>,
133    {
134        let sql = if Self::uses_soft_deletes() {
135            format!(
136                "SELECT * FROM {} WHERE {} = $1 AND deleted_at IS NULL LIMIT 1",
137                Self::table_name(),
138                field
139            )
140        } else {
141            format!(
142                "SELECT * FROM {} WHERE {} = $1 LIMIT 1",
143                Self::table_name(),
144                field
145            )
146        };
147
148        let row = sqlx::query(&sql)
149            .bind(value)
150            .fetch_optional(pool)
151            .await
152            .map_err(|e| {
153                ModelError::Database(format!(
154                    "Failed to find first {} by {}: {}",
155                    Self::table_name(),
156                    field,
157                    e
158                ))
159            })?;
160
161        match row {
162            Some(row) => {
163                let model = Self::from_row(&row)?;
164                Ok(Some(model))
165            }
166            None => Ok(None),
167        }
168    }
169
170    /// Get the first record from this model
171    async fn first(pool: &Pool<Postgres>) -> ModelResult<Option<Self>>
172    where
173        Self: Sized,
174    {
175        let sql = if Self::uses_soft_deletes() {
176            format!(
177                "SELECT * FROM {} WHERE deleted_at IS NULL LIMIT 1",
178                Self::table_name()
179            )
180        } else {
181            format!("SELECT * FROM {} LIMIT 1", Self::table_name())
182        };
183
184        let row = sqlx::query(&sql).fetch_optional(pool).await.map_err(|e| {
185            ModelError::Database(format!("Failed to get first {}: {}", Self::table_name(), e))
186        })?;
187
188        match row {
189            Some(row) => {
190                let model = Self::from_row(&row)?;
191                Ok(Some(model))
192            }
193            None => Ok(None),
194        }
195    }
196
197    /// Get the last record from this model (ordered by primary key)
198    async fn last(pool: &Pool<Postgres>) -> ModelResult<Option<Self>>
199    where
200        Self: Sized,
201    {
202        let sql = if Self::uses_soft_deletes() {
203            format!(
204                "SELECT * FROM {} WHERE deleted_at IS NULL ORDER BY {} DESC LIMIT 1",
205                Self::table_name(),
206                Self::primary_key_name()
207            )
208        } else {
209            format!(
210                "SELECT * FROM {} ORDER BY {} DESC LIMIT 1",
211                Self::table_name(),
212                Self::primary_key_name()
213            )
214        };
215
216        let row = sqlx::query(&sql).fetch_optional(pool).await.map_err(|e| {
217            ModelError::Database(format!("Failed to get last {}: {}", Self::table_name(), e))
218        })?;
219
220        match row {
221            Some(row) => {
222                let model = Self::from_row(&row)?;
223                Ok(Some(model))
224            }
225            None => Ok(None),
226        }
227    }
228    // <<<ELIF:END agent-editable:model_query_methods>>>
229}
230
231// Implement QueryMethods for all types that implement Model
232impl<T: Model> QueryMethods for T {}