Skip to main content

linq_rs_sql/
query.rs

1//! [`Query`] builder, [`Table`] trait, [`Selection`] trait, and
2//! [`QueryOutput`].
3//!
4//! The query type tracks the selection at the type level (so the SELECT
5//! list can later be matched to a struct for row mapping in Phase 6+), but
6//! treats the WHERE clause and ORDER BY list as runtime data. WHERE
7//! predicates accumulate via `.filter(p)` and are joined with `AND`.
8//!
9//! ## Trade-off: `'static` bound on filter predicates
10//!
11//! WHERE predicates are stored as `Box<dyn SqlWriter + 'static>`, so the
12//! predicate (and anything it captures) must be `'static`. In practice
13//! that means primitive literals, `String`, and `&'static str` work
14//! directly; borrowed `&str` does not. Convert with `.to_string()` first.
15
16use crate::column::Column;
17use crate::expr::Expr;
18use crate::types::Boolean;
19use crate::value::SqlValue;
20use core::fmt::Write;
21use core::marker::PhantomData;
22
23// ═══════════════════════════════════════════════════════════════════════════
24// Table + Selection traits
25// ═══════════════════════════════════════════════════════════════════════════
26
27/// A SQL table. Generated by [`crate::table!`].
28pub trait Table {
29    /// The SQL identifier (table name).
30    const NAME: &'static str;
31}
32
33/// Something that can appear in a SELECT list — a single column, a tuple
34/// of columns, or [`All`] for `SELECT *`.
35///
36/// Every variant carries a `Table` associated type so the query builder
37/// can reject selections that mix columns from different tables (a
38/// scenario only meaningful once JOINs ship in Phase 2).
39pub trait Selection {
40    /// The table this selection's columns come from.
41    type Table;
42    /// Append the comma-separated list of selected items to `sql`.
43    ///
44    /// Named `write_select` (not `write_to`) to disambiguate from
45    /// [`Expr::write_to`] since `Column`
46    /// types implement both traits.
47    fn write_select(&self, sql: &mut String);
48}
49
50/// Marker for `SELECT *`. The default selection when no `.select(...)`
51/// call is made.
52#[derive(Debug, Clone, Copy, Default)]
53pub struct All<T> {
54    _ty: PhantomData<T>,
55}
56
57impl<T> All<T> {
58    /// Construct an `All<T>` selection. Mostly internal — use
59    /// [`Query::new`] which sets this as the default.
60    pub fn new() -> Self {
61        Self { _ty: PhantomData }
62    }
63}
64
65impl<T: Table> Selection for All<T> {
66    type Table = T;
67    fn write_select(&self, sql: &mut String) {
68        sql.push('*');
69    }
70}
71
72// Single column is a valid Selection.
73impl<C: Column> Selection for C {
74    type Table = C::Table;
75    fn write_select(&self, sql: &mut String) {
76        sql.push_str(C::NAME);
77    }
78}
79
80// Tuples of 2..=8 columns. All must belong to the same table.
81macro_rules! impl_selection_tuple {
82    ($head:ident $(, $tail:ident)+) => {
83        impl<$head, $($tail),+> Selection for ($head, $($tail),+)
84        where
85            $head: Column,
86            $($tail: Column<Table = $head::Table>),+
87        {
88            type Table = $head::Table;
89            #[allow(non_snake_case)]
90            fn write_select(&self, sql: &mut String) {
91                let ($head, $($tail),+) = self;
92                Selection::write_select($head, sql);
93                $(
94                    sql.push_str(", ");
95                    Selection::write_select($tail, sql);
96                )+
97            }
98        }
99    };
100}
101
102impl_selection_tuple!(A, B);
103impl_selection_tuple!(A, B, C);
104impl_selection_tuple!(A, B, C, D);
105impl_selection_tuple!(A, B, C, D, E);
106impl_selection_tuple!(A, B, C, D, E, F);
107impl_selection_tuple!(A, B, C, D, E, F, G);
108impl_selection_tuple!(A, B, C, D, E, F, G, H);
109
110// ═══════════════════════════════════════════════════════════════════════════
111// ORDER BY direction + clause
112// ═══════════════════════════════════════════════════════════════════════════
113
114/// Sort direction for `ORDER BY`.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub enum Direction {
117    /// Ascending — SQL `ASC` (also the SQL default).
118    Asc,
119    /// Descending — SQL `DESC`.
120    Desc,
121}
122
123#[derive(Debug, Clone)]
124struct OrderClause {
125    name: &'static str,
126    dir: Direction,
127}
128
129// ═══════════════════════════════════════════════════════════════════════════
130// Query output
131// ═══════════════════════════════════════════════════════════════════════════
132
133/// Output of [`Query::to_sql`] — the parameterized SQL text and its
134/// bind values, in declaration order.
135#[derive(Debug, Clone, PartialEq)]
136pub struct QueryOutput {
137    /// SQL text with `?` placeholders for bound values.
138    pub sql: String,
139    /// Bound values in the order they appear in `sql`. Feed these to the
140    /// driver alongside the SQL string.
141    pub params: Vec<SqlValue>,
142}
143
144// ═══════════════════════════════════════════════════════════════════════════
145// Internal: trait-object wrapper for runtime WHERE storage
146// ═══════════════════════════════════════════════════════════════════════════
147
148trait SqlWriter {
149    fn write_to(&self, sql: &mut String, params: &mut Vec<SqlValue>);
150}
151
152impl<E: Expr<SqlType = Boolean> + 'static> SqlWriter for E {
153    fn write_to(&self, sql: &mut String, params: &mut Vec<SqlValue>) {
154        <E as Expr>::write_to(self, sql, params);
155    }
156}
157
158// ═══════════════════════════════════════════════════════════════════════════
159// Query
160// ═══════════════════════════════════════════════════════════════════════════
161
162/// A typed SELECT query under construction.
163///
164/// `T` is the source table. `S` is the SELECT clause (defaults to
165/// [`All<T>`] meaning `SELECT *`). Build up the query with method chains;
166/// finalize with [`to_sql`](Self::to_sql).
167///
168/// ```rust
169/// use linq_rs_sql::*;
170///
171/// linq_rs_sql::table! {
172///     people (id) {
173///         id   -> Integer,
174///         name -> Text,
175///         age  -> Integer,
176///     }
177/// }
178///
179/// let q = people::table()
180///     .filter(people::age.gt(18).and(people::name.like("A%".to_string())))
181///     .select((people::id, people::name))
182///     .order_by_desc(people::age)
183///     .limit(10)
184///     .to_sql();
185///
186/// assert!(q.sql.starts_with("SELECT id, name FROM people WHERE"));
187/// ```
188pub struct Query<T: Table, S: Selection<Table = T>> {
189    selection: S,
190    where_parts: Vec<Box<dyn SqlWriter>>,
191    order_by: Vec<OrderClause>,
192    limit: Option<u64>,
193    offset: Option<u64>,
194    _table: PhantomData<T>,
195}
196
197impl<T: Table> Default for Query<T, All<T>> {
198    fn default() -> Self {
199        Self::new()
200    }
201}
202
203impl<T: Table> Query<T, All<T>> {
204    /// Start a new query against table `T` with `SELECT *` as the default
205    /// projection. Prefer the generated `<table>::table()` constructor
206    /// over calling this directly.
207    pub fn new() -> Self {
208        Self {
209            selection: All::new(),
210            where_parts: Vec::new(),
211            order_by: Vec::new(),
212            limit: None,
213            offset: None,
214            _table: PhantomData,
215        }
216    }
217}
218
219impl<T: Table, S: Selection<Table = T>> Query<T, S> {
220    /// Add an `AND`-joined predicate to the WHERE clause. Multiple
221    /// `.filter()` calls accumulate; combine with `.or()` for OR-paths.
222    pub fn filter<P>(mut self, predicate: P) -> Self
223    where
224        P: Expr<SqlType = Boolean> + 'static,
225    {
226        self.where_parts.push(Box::new(predicate));
227        self
228    }
229
230    /// Replace the SELECT clause. Pass a single column or a tuple of up
231    /// to 8 columns, all from this query's table.
232    pub fn select<NS: Selection<Table = T>>(self, selection: NS) -> Query<T, NS> {
233        Query {
234            selection,
235            where_parts: self.where_parts,
236            order_by: self.order_by,
237            limit: self.limit,
238            offset: self.offset,
239            _table: PhantomData,
240        }
241    }
242
243    /// Append an ascending `ORDER BY` clause on `column`. Stable: multiple
244    /// calls preserve the order they were made in (becomes
245    /// `ORDER BY a, b, c`).
246    pub fn order_by<C: Column<Table = T>>(mut self, _column: C) -> Self {
247        self.order_by.push(OrderClause {
248            name: C::NAME,
249            dir: Direction::Asc,
250        });
251        self
252    }
253
254    /// Append a descending `ORDER BY` clause on `column`.
255    pub fn order_by_desc<C: Column<Table = T>>(mut self, _column: C) -> Self {
256        self.order_by.push(OrderClause {
257            name: C::NAME,
258            dir: Direction::Desc,
259        });
260        self
261    }
262
263    /// Set the `LIMIT` (overwrites any previous limit).
264    pub fn limit(mut self, n: u64) -> Self {
265        self.limit = Some(n);
266        self
267    }
268
269    /// Set the `OFFSET` (overwrites any previous offset).
270    pub fn offset(mut self, n: u64) -> Self {
271        self.offset = Some(n);
272        self
273    }
274
275    /// Finalize the query and emit the SQL + bind parameters.
276    pub fn to_sql(&self) -> QueryOutput {
277        let mut sql = String::from("SELECT ");
278        self.selection.write_select(&mut sql);
279        sql.push_str(" FROM ");
280        sql.push_str(T::NAME);
281
282        let mut params = Vec::new();
283
284        if !self.where_parts.is_empty() {
285            sql.push_str(" WHERE ");
286            let mut first = true;
287            for part in &self.where_parts {
288                if !first {
289                    sql.push_str(" AND ");
290                }
291                part.write_to(&mut sql, &mut params);
292                first = false;
293            }
294        }
295
296        if !self.order_by.is_empty() {
297            sql.push_str(" ORDER BY ");
298            let mut first = true;
299            for o in &self.order_by {
300                if !first {
301                    sql.push_str(", ");
302                }
303                sql.push_str(o.name);
304                if o.dir == Direction::Desc {
305                    sql.push_str(" DESC");
306                }
307                first = false;
308            }
309        }
310
311        if let Some(n) = self.limit {
312            write!(&mut sql, " LIMIT {n}").unwrap();
313        }
314        if let Some(n) = self.offset {
315            write!(&mut sql, " OFFSET {n}").unwrap();
316        }
317
318        QueryOutput { sql, params }
319    }
320}