linq_rs_sql 0.1.0

A typed SQL query builder — compile-time checked columns, bound parameters, no driver and no dependencies
Documentation
//! [`Query`] builder, [`Table`] trait, [`Selection`] trait, and
//! [`QueryOutput`].
//!
//! The query type tracks the selection at the type level (so the SELECT
//! list can later be matched to a struct for row mapping in Phase 6+), but
//! treats the WHERE clause and ORDER BY list as runtime data. WHERE
//! predicates accumulate via `.filter(p)` and are joined with `AND`.
//!
//! ## Trade-off: `'static` bound on filter predicates
//!
//! WHERE predicates are stored as `Box<dyn SqlWriter + 'static>`, so the
//! predicate (and anything it captures) must be `'static`. In practice
//! that means primitive literals, `String`, and `&'static str` work
//! directly; borrowed `&str` does not. Convert with `.to_string()` first.

use crate::column::Column;
use crate::expr::Expr;
use crate::types::Boolean;
use crate::value::SqlValue;
use core::fmt::Write;
use core::marker::PhantomData;

// ═══════════════════════════════════════════════════════════════════════════
// Table + Selection traits
// ═══════════════════════════════════════════════════════════════════════════

/// A SQL table. Generated by [`crate::table!`].
pub trait Table {
    /// The SQL identifier (table name).
    const NAME: &'static str;
}

/// Something that can appear in a SELECT list — a single column, a tuple
/// of columns, or [`All`] for `SELECT *`.
///
/// Every variant carries a `Table` associated type so the query builder
/// can reject selections that mix columns from different tables (a
/// scenario only meaningful once JOINs ship in Phase 2).
pub trait Selection {
    /// The table this selection's columns come from.
    type Table;
    /// Append the comma-separated list of selected items to `sql`.
    ///
    /// Named `write_select` (not `write_to`) to disambiguate from
    /// [`Expr::write_to`] since `Column`
    /// types implement both traits.
    fn write_select(&self, sql: &mut String);
}

/// Marker for `SELECT *`. The default selection when no `.select(...)`
/// call is made.
#[derive(Debug, Clone, Copy, Default)]
pub struct All<T> {
    _ty: PhantomData<T>,
}

impl<T> All<T> {
    /// Construct an `All<T>` selection. Mostly internal — use
    /// [`Query::new`] which sets this as the default.
    pub fn new() -> Self {
        Self { _ty: PhantomData }
    }
}

impl<T: Table> Selection for All<T> {
    type Table = T;
    fn write_select(&self, sql: &mut String) {
        sql.push('*');
    }
}

// Single column is a valid Selection.
impl<C: Column> Selection for C {
    type Table = C::Table;
    fn write_select(&self, sql: &mut String) {
        sql.push_str(C::NAME);
    }
}

// Tuples of 2..=8 columns. All must belong to the same table.
macro_rules! impl_selection_tuple {
    ($head:ident $(, $tail:ident)+) => {
        impl<$head, $($tail),+> Selection for ($head, $($tail),+)
        where
            $head: Column,
            $($tail: Column<Table = $head::Table>),+
        {
            type Table = $head::Table;
            #[allow(non_snake_case)]
            fn write_select(&self, sql: &mut String) {
                let ($head, $($tail),+) = self;
                Selection::write_select($head, sql);
                $(
                    sql.push_str(", ");
                    Selection::write_select($tail, sql);
                )+
            }
        }
    };
}

impl_selection_tuple!(A, B);
impl_selection_tuple!(A, B, C);
impl_selection_tuple!(A, B, C, D);
impl_selection_tuple!(A, B, C, D, E);
impl_selection_tuple!(A, B, C, D, E, F);
impl_selection_tuple!(A, B, C, D, E, F, G);
impl_selection_tuple!(A, B, C, D, E, F, G, H);

// ═══════════════════════════════════════════════════════════════════════════
// ORDER BY direction + clause
// ═══════════════════════════════════════════════════════════════════════════

/// Sort direction for `ORDER BY`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Direction {
    /// Ascending — SQL `ASC` (also the SQL default).
    Asc,
    /// Descending — SQL `DESC`.
    Desc,
}

#[derive(Debug, Clone)]
struct OrderClause {
    name: &'static str,
    dir: Direction,
}

// ═══════════════════════════════════════════════════════════════════════════
// Query output
// ═══════════════════════════════════════════════════════════════════════════

/// Output of [`Query::to_sql`] — the parameterized SQL text and its
/// bind values, in declaration order.
#[derive(Debug, Clone, PartialEq)]
pub struct QueryOutput {
    /// SQL text with `?` placeholders for bound values.
    pub sql: String,
    /// Bound values in the order they appear in `sql`. Feed these to the
    /// driver alongside the SQL string.
    pub params: Vec<SqlValue>,
}

// ═══════════════════════════════════════════════════════════════════════════
// Internal: trait-object wrapper for runtime WHERE storage
// ═══════════════════════════════════════════════════════════════════════════

trait SqlWriter {
    fn write_to(&self, sql: &mut String, params: &mut Vec<SqlValue>);
}

impl<E: Expr<SqlType = Boolean> + 'static> SqlWriter for E {
    fn write_to(&self, sql: &mut String, params: &mut Vec<SqlValue>) {
        <E as Expr>::write_to(self, sql, params);
    }
}

// ═══════════════════════════════════════════════════════════════════════════
// Query
// ═══════════════════════════════════════════════════════════════════════════

/// A typed SELECT query under construction.
///
/// `T` is the source table. `S` is the SELECT clause (defaults to
/// [`All<T>`] meaning `SELECT *`). Build up the query with method chains;
/// finalize with [`to_sql`](Self::to_sql).
///
/// ```rust
/// use linq_rs_sql::*;
///
/// linq_rs_sql::table! {
///     people (id) {
///         id   -> Integer,
///         name -> Text,
///         age  -> Integer,
///     }
/// }
///
/// let q = people::table()
///     .filter(people::age.gt(18).and(people::name.like("A%".to_string())))
///     .select((people::id, people::name))
///     .order_by_desc(people::age)
///     .limit(10)
///     .to_sql();
///
/// assert!(q.sql.starts_with("SELECT id, name FROM people WHERE"));
/// ```
pub struct Query<T: Table, S: Selection<Table = T>> {
    selection: S,
    where_parts: Vec<Box<dyn SqlWriter>>,
    order_by: Vec<OrderClause>,
    limit: Option<u64>,
    offset: Option<u64>,
    _table: PhantomData<T>,
}

impl<T: Table> Default for Query<T, All<T>> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T: Table> Query<T, All<T>> {
    /// Start a new query against table `T` with `SELECT *` as the default
    /// projection. Prefer the generated `<table>::table()` constructor
    /// over calling this directly.
    pub fn new() -> Self {
        Self {
            selection: All::new(),
            where_parts: Vec::new(),
            order_by: Vec::new(),
            limit: None,
            offset: None,
            _table: PhantomData,
        }
    }
}

impl<T: Table, S: Selection<Table = T>> Query<T, S> {
    /// Add an `AND`-joined predicate to the WHERE clause. Multiple
    /// `.filter()` calls accumulate; combine with `.or()` for OR-paths.
    pub fn filter<P>(mut self, predicate: P) -> Self
    where
        P: Expr<SqlType = Boolean> + 'static,
    {
        self.where_parts.push(Box::new(predicate));
        self
    }

    /// Replace the SELECT clause. Pass a single column or a tuple of up
    /// to 8 columns, all from this query's table.
    pub fn select<NS: Selection<Table = T>>(self, selection: NS) -> Query<T, NS> {
        Query {
            selection,
            where_parts: self.where_parts,
            order_by: self.order_by,
            limit: self.limit,
            offset: self.offset,
            _table: PhantomData,
        }
    }

    /// Append an ascending `ORDER BY` clause on `column`. Stable: multiple
    /// calls preserve the order they were made in (becomes
    /// `ORDER BY a, b, c`).
    pub fn order_by<C: Column<Table = T>>(mut self, _column: C) -> Self {
        self.order_by.push(OrderClause {
            name: C::NAME,
            dir: Direction::Asc,
        });
        self
    }

    /// Append a descending `ORDER BY` clause on `column`.
    pub fn order_by_desc<C: Column<Table = T>>(mut self, _column: C) -> Self {
        self.order_by.push(OrderClause {
            name: C::NAME,
            dir: Direction::Desc,
        });
        self
    }

    /// Set the `LIMIT` (overwrites any previous limit).
    pub fn limit(mut self, n: u64) -> Self {
        self.limit = Some(n);
        self
    }

    /// Set the `OFFSET` (overwrites any previous offset).
    pub fn offset(mut self, n: u64) -> Self {
        self.offset = Some(n);
        self
    }

    /// Finalize the query and emit the SQL + bind parameters.
    pub fn to_sql(&self) -> QueryOutput {
        let mut sql = String::from("SELECT ");
        self.selection.write_select(&mut sql);
        sql.push_str(" FROM ");
        sql.push_str(T::NAME);

        let mut params = Vec::new();

        if !self.where_parts.is_empty() {
            sql.push_str(" WHERE ");
            let mut first = true;
            for part in &self.where_parts {
                if !first {
                    sql.push_str(" AND ");
                }
                part.write_to(&mut sql, &mut params);
                first = false;
            }
        }

        if !self.order_by.is_empty() {
            sql.push_str(" ORDER BY ");
            let mut first = true;
            for o in &self.order_by {
                if !first {
                    sql.push_str(", ");
                }
                sql.push_str(o.name);
                if o.dir == Direction::Desc {
                    sql.push_str(" DESC");
                }
                first = false;
            }
        }

        if let Some(n) = self.limit {
            write!(&mut sql, " LIMIT {n}").unwrap();
        }
        if let Some(n) = self.offset {
            write!(&mut sql, " OFFSET {n}").unwrap();
        }

        QueryOutput { sql, params }
    }
}