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
// SPDX-FileCopyrightText: 2025-2026 RAprogramm <andrey.rozanov.vl@gmail.com>
// SPDX-License-Identifier: MIT
//! Query method generator for `PostgreSQL`.
//!
//! Generates the `query` method that provides type-safe filtering using
//! the entity's Query struct (generated from `#[filter]` attributes).
//!
//! # Generated SQL
//!
//! ```sql
//! SELECT col1, col2, ... FROM schema.table
//! WHERE condition1 AND condition2 AND ...
//! ORDER BY id DESC
//! LIMIT $n OFFSET $m
//! ```
//!
//! # Dynamic WHERE Clause
//!
//! The WHERE clause is built at runtime based on which filter fields
//! are set in the query struct. Only `Some` values generate conditions.
use proc_macro2::TokenStream;
use quote::quote;
use super::{
context::Context,
helpers::{generate_query_bindings, generate_where_conditions}
};
impl Context<'_> {
/// Generate the `query` method implementation.
///
/// # Returns
///
/// Empty `TokenStream` if entity has no filter fields.
///
/// # Generated Code
///
/// ```rust,ignore
/// async fn query(&self, query: UserQuery) -> Result<Vec<User>, Self::Error> {
/// let mut conditions: Vec<String> = Vec::new();
/// let mut param_idx: usize = 1;
///
/// // Build conditions based on filter fields
/// if query.name.is_some() {
/// conditions.push(format!("name = ${}", param_idx));
/// param_idx += 1;
/// }
/// // ... more conditions
///
/// let where_clause = if conditions.is_empty() {
/// String::new()
/// } else {
/// format!("WHERE {}", conditions.join(" AND "))
/// };
///
/// let sql = format!("SELECT ... FROM ... {} ORDER BY ...", where_clause);
///
/// let mut q = sqlx::query_as::<_, UserRow>(&sql);
/// // Bind filter values
/// if let Some(ref v) = query.name {
/// q = q.bind(v);
/// }
/// // ... more bindings
///
/// q = q.bind(query.limit.unwrap_or(100)).bind(query.offset.unwrap_or(0));
/// let rows = q.fetch_all(self).await?;
/// Ok(rows.into_iter().map(User::from).collect())
/// }
/// ```
/// Expression yielding the runtime `ORDER BY` fragment.
///
/// With `#[sort]` fields the fragment comes from the whitelisted
/// `{Entity}SortField::order_by`; otherwise the historical
/// `{id} DESC` default is kept.
fn order_by_expr(&self) -> TokenStream {
let id_name = self.id_name;
let default = format!("{id_name} DESC");
if self.entity.has_sort_fields() {
quote! {
query.sort.map(|s| s.order_by()).unwrap_or(#default)
}
} else {
quote! { #default }
}
}
pub fn query_method(&self) -> TokenStream {
if !self.entity.has_filters() && !self.entity.has_sort_fields() {
return TokenStream::new();
}
let Self {
entity_name,
row_name,
table,
columns_str,
soft_delete,
..
} = self;
let query_type = self.entity.ident_with("", "Query");
let filter_fields = self.entity.filter_fields();
let where_conditions = generate_where_conditions(&filter_fields, *soft_delete);
let bindings = generate_query_bindings(&filter_fields);
let order_by_expr = self.order_by_expr();
quote! {
async fn query(&self, query: #query_type) -> Result<Vec<#entity_name>, Self::Error> {
let mut conditions: Vec<String> = Vec::new();
let mut param_idx: usize = 1;
#where_conditions
let where_clause = if conditions.is_empty() {
String::new()
} else {
format!("WHERE {}", conditions.join(" AND "))
};
let limit_idx = param_idx;
param_idx += 1;
let offset_idx = param_idx;
let __order_by = #order_by_expr;
let sql = format!(
"SELECT {} FROM {} {} ORDER BY {} LIMIT ${} OFFSET ${}",
#columns_str, #table, where_clause, __order_by, limit_idx, offset_idx
);
let mut q = sqlx::query_as::<_, #row_name>(::sqlx::AssertSqlSafe(sql));
#bindings
q = q.bind(query.limit.unwrap_or(100)).bind(query.offset.unwrap_or(0));
let rows = q.fetch_all(self).await?;
Ok(rows.into_iter().map(#entity_name::from).collect())
}
}
}
/// Generate the `stream_filtered` method implementation.
///
/// # Returns
///
/// Empty `TokenStream` if entity has no streams or filter fields.
pub fn stream_filtered_method(&self) -> TokenStream {
if !self.streams || !self.entity.has_filters() {
return TokenStream::new();
}
let Self {
entity_name,
row_name,
table,
columns_str,
soft_delete,
..
} = self;
let filter_type = self.entity.ident_with("", "Filter");
let filter_fields = self.entity.filter_fields();
let where_conditions = generate_where_conditions(&filter_fields, *soft_delete);
let bindings = generate_query_bindings(&filter_fields);
// For now, generate a simple implementation that fetches all and converts to
// stream True streaming would require more complex lifetime handling
let order_by_expr = self.order_by_expr();
quote! {
async fn stream_filtered(
&self,
filter: #filter_type,
) -> Result<std::pin::Pin<Box<dyn futures::Stream<Item = Result<#entity_name, Self::Error>> + Send + '_>>, Self::Error> {
use futures::StreamExt;
let mut conditions: Vec<String> = Vec::new();
let mut param_idx: usize = 1;
// Rename filter to query for binding code compatibility
let query = filter;
#where_conditions
let where_clause = if conditions.is_empty() {
String::new()
} else {
format!("WHERE {}", conditions.join(" AND "))
};
let limit_idx = param_idx;
param_idx += 1;
let offset_idx = param_idx;
let __order_by = #order_by_expr;
let sql = format!(
"SELECT {} FROM {} {} ORDER BY {} LIMIT ${} OFFSET ${}",
#columns_str, #table, where_clause, __order_by, limit_idx, offset_idx
);
let mut q = sqlx::query_as::<_, #row_name>(::sqlx::AssertSqlSafe(sql));
#bindings
q = q.bind(query.limit.unwrap_or(10000)).bind(query.offset.unwrap_or(0));
// Fetch all results and convert to stream for simpler lifetime handling
let rows = q.fetch_all(self).await?;
let entities: Vec<#entity_name> = rows.into_iter().map(#entity_name::from).collect();
let stream = futures::stream::iter(entities.into_iter().map(Ok));
Ok(Box::pin(stream))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::entity::parse::EntityDef;
#[test]
fn query_method_no_filters_returns_empty() {
let input: syn::DeriveInput = syn::parse_quote! {
#[entity(table = "users")]
pub struct User {
#[id]
pub id: uuid::Uuid,
#[field(create, response)]
pub name: String,
}
};
let entity = EntityDef::from_derive_input(&input).unwrap();
let ctx = Context::new(&entity);
let method = ctx.query_method();
assert!(method.is_empty());
}
#[test]
fn query_method_with_filter() {
let input: syn::DeriveInput = syn::parse_quote! {
#[entity(table = "users")]
pub struct User {
#[id]
pub id: uuid::Uuid,
#[field(create, response)]
#[filter]
pub name: String,
}
};
let entity = EntityDef::from_derive_input(&input).unwrap();
let ctx = Context::new(&entity);
let method = ctx.query_method();
let method_str = method.to_string();
assert!(method_str.contains("async fn query"));
assert!(method_str.contains("UserQuery"));
assert!(method_str.contains("conditions"));
assert!(method_str.contains("where_clause"));
}
#[test]
fn query_method_with_soft_delete() {
let input: syn::DeriveInput = syn::parse_quote! {
#[entity(table = "users", soft_delete)]
pub struct User {
#[id]
pub id: uuid::Uuid,
#[field(create, response)]
#[filter]
pub name: String,
#[field(response)]
#[auto]
pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,
}
};
let entity = EntityDef::from_derive_input(&input).unwrap();
let ctx = Context::new(&entity);
let method = ctx.query_method();
let method_str = method.to_string();
assert!(method_str.contains("deleted_at"));
}
#[test]
fn stream_filtered_no_streams_returns_empty() {
let input: syn::DeriveInput = syn::parse_quote! {
#[entity(table = "users")]
pub struct User {
#[id]
pub id: uuid::Uuid,
#[field(create, response)]
#[filter]
pub name: String,
}
};
let entity = EntityDef::from_derive_input(&input).unwrap();
let ctx = Context::new(&entity);
let method = ctx.stream_filtered_method();
assert!(method.is_empty());
}
#[test]
fn stream_filtered_no_filters_returns_empty() {
let input: syn::DeriveInput = syn::parse_quote! {
#[entity(table = "users", streams)]
pub struct User {
#[id]
pub id: uuid::Uuid,
#[field(create, response)]
pub name: String,
}
};
let entity = EntityDef::from_derive_input(&input).unwrap();
let ctx = Context::new(&entity);
let method = ctx.stream_filtered_method();
assert!(method.is_empty());
}
#[test]
fn stream_filtered_with_streams_and_filters() {
let input: syn::DeriveInput = syn::parse_quote! {
#[entity(table = "users", streams)]
pub struct User {
#[id]
pub id: uuid::Uuid,
#[field(create, response)]
#[filter]
pub name: String,
}
};
let entity = EntityDef::from_derive_input(&input).unwrap();
let ctx = Context::new(&entity);
let method = ctx.stream_filtered_method();
let method_str = method.to_string();
assert!(method_str.contains("stream_filtered"));
assert!(method_str.contains("UserFilter"));
assert!(method_str.contains("futures"));
}
}