Skip to main content

gen_models/
select.rs

1//! Internal support for selectors generated by `ModelSelect`.
2
3use core::marker::PhantomData;
4use std::rc::Rc;
5
6use indexmap::IndexMap;
7use itertools::Itertools;
8pub use rusqlite::{Connection, Result as SqlResult, Row};
9use rusqlite::{
10    Params, ToSql, params_from_iter,
11    types::{FromSql, ToSqlOutput, Value},
12};
13
14use crate::{
15    ModelSelectError,
16    db::{max_rows_per_batch, sqlite_parameter_limit},
17};
18
19#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
20pub enum Direction {
21    #[default]
22    Asc,
23    Desc,
24    CaseInsensitiveAsc,
25    CaseInsensitiveDesc,
26}
27
28impl Direction {
29    const fn as_sql(self) -> &'static str {
30        match self {
31            Self::Asc => "ASC",
32            Self::Desc => "DESC",
33            Self::CaseInsensitiveAsc => "ASC",
34            Self::CaseInsensitiveDesc => "DESC",
35        }
36    }
37
38    const fn uses_case_insensitive_collation(self) -> bool {
39        match self {
40            Self::Asc | Self::Desc => false,
41            Self::CaseInsensitiveAsc | Self::CaseInsensitiveDesc => true,
42        }
43    }
44}
45
46#[doc(hidden)]
47pub enum HistoryRefValue {}
48
49#[doc(hidden)]
50pub enum OptionalHistoryRefValue {}
51
52#[doc(hidden)]
53pub trait IntoHistoryRef<Kind> {
54    fn into_history_ref(self) -> Option<String>;
55}
56
57impl<T> IntoHistoryRef<HistoryRefValue> for T
58where
59    T: Into<String>,
60{
61    fn into_history_ref(self) -> Option<String> {
62        Some(self.into())
63    }
64}
65
66impl<T> IntoHistoryRef<OptionalHistoryRefValue> for Option<T>
67where
68    T: Into<String>,
69{
70    fn into_history_ref(self) -> Option<String> {
71        self.map(Into::into)
72    }
73}
74
75#[doc(hidden)]
76#[derive(Clone, Debug, Eq, PartialEq)]
77pub enum SelectorBuildError {
78    InvalidSelector(String),
79    HistoryNotSupported { table_name: &'static str },
80}
81
82impl From<SelectorBuildError> for ModelSelectError {
83    fn from(error: SelectorBuildError) -> Self {
84        match error {
85            SelectorBuildError::InvalidSelector(message) => Self::InvalidSelector(message),
86            SelectorBuildError::HistoryNotSupported { table_name } => Self::HistoryNotSupported {
87                table_name: table_name.to_string(),
88            },
89        }
90    }
91}
92
93#[doc(hidden)]
94pub fn sql_value(value: &impl ToSql) -> Result<Value, SelectorBuildError> {
95    let value = value.to_sql().map_err(|error| {
96        SelectorBuildError::InvalidSelector(format!(
97            "failed to convert selector value to SQL: {error}"
98        ))
99    })?;
100    match value {
101        ToSqlOutput::Borrowed(value) => Value::try_from(value).map_err(|error| {
102            SelectorBuildError::InvalidSelector(format!(
103                "failed to copy selector SQL value: {error}"
104            ))
105        }),
106        ToSqlOutput::Owned(value) => Ok(value),
107        _ => Err(SelectorBuildError::InvalidSelector(
108            "selector values must map to SQLite scalar values".to_string(),
109        )),
110    }
111}
112
113#[doc(hidden)]
114#[derive(Clone, Debug, PartialEq)]
115pub struct SqlFilter {
116    pub clause: String,
117    pub params: Vec<Value>,
118    ordered_in: Option<OrderedSqlIn>,
119}
120
121impl SqlFilter {
122    pub fn new(clause: impl Into<String>, params: Vec<Value>) -> Self {
123        Self {
124            clause: clause.into(),
125            params,
126            ordered_in: None,
127        }
128    }
129}
130
131#[derive(Clone, Debug, PartialEq)]
132struct OrderedSqlIn {
133    columns: Vec<String>,
134    rows: Vec<Vec<Value>>,
135}
136
137#[doc(hidden)]
138pub fn sql_in_filter(column: impl Into<String>, params: Vec<Value>) -> SqlFilter {
139    if params.is_empty() {
140        // An empty IN set must match no rows. Keeping an explicit false predicate avoids both
141        // invalid `IN ()` SQL and accidentally dropping the filter, which would match every row.
142        SqlFilter::new("0 = 1", params)
143    } else {
144        SqlFilter {
145            clause: String::new(),
146            params: Vec::new(),
147            ordered_in: Some(OrderedSqlIn {
148                columns: vec![column.into()],
149                rows: params.into_iter().map(|value| vec![value]).collect(),
150            }),
151        }
152    }
153}
154
155#[doc(hidden)]
156pub fn sql_composite_in_filter(
157    columns: Vec<String>,
158    rows: Vec<Vec<Value>>,
159) -> Result<SqlFilter, SelectorBuildError> {
160    if columns.is_empty() {
161        return Err(SelectorBuildError::InvalidSelector(
162            "a composite primary key must contain at least one column".to_string(),
163        ));
164    }
165    if rows.iter().any(|row| row.len() != columns.len()) {
166        return Err(SelectorBuildError::InvalidSelector(
167            "each composite primary-key value must match the number of key columns".to_string(),
168        ));
169    }
170    if rows.is_empty() {
171        // Composite IN follows the same empty-set semantics as scalar IN: it is a valid selector
172        // that deliberately matches nothing, not an absent filter.
173        Ok(SqlFilter::new("0 = 1", Vec::new()))
174    } else {
175        Ok(SqlFilter {
176            clause: String::new(),
177            params: Vec::new(),
178            ordered_in: Some(OrderedSqlIn { columns, rows }),
179        })
180    }
181}
182
183#[derive(Clone, Debug)]
184enum SqlParameter {
185    Scalar(Value),
186    Array(Rc<Vec<Value>>),
187}
188
189impl ToSql for SqlParameter {
190    fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
191        match self {
192            Self::Scalar(value) => value.to_sql(),
193            Self::Array(values) => values.to_sql(),
194        }
195    }
196}
197
198#[doc(hidden)]
199#[derive(Clone, Debug, Eq, PartialEq)]
200pub struct SqlOrder {
201    column: String,
202    direction: Direction,
203    relevance_search: Option<String>,
204}
205
206impl SqlOrder {
207    pub fn new(column: impl Into<String>, direction: Direction) -> Self {
208        Self {
209            column: column.into(),
210            direction,
211            relevance_search: None,
212        }
213    }
214
215    pub fn relevance(column: impl Into<String>, search: String) -> Self {
216        Self {
217            column: column.into(),
218            direction: Direction::Asc,
219            relevance_search: Some(search),
220        }
221    }
222}
223
224#[doc(hidden)]
225#[derive(Clone, Copy, Debug)]
226pub struct SqlSource {
227    table_name: &'static str,
228    alias: &'static str,
229    source_id: &'static str,
230    supports_history: bool,
231    source_clause: fn(Option<&str>) -> String,
232}
233
234impl SqlSource {
235    pub const fn new(
236        table_name: &'static str,
237        alias: &'static str,
238        source_id: &'static str,
239        supports_history: bool,
240        source_clause: fn(Option<&str>) -> String,
241    ) -> Self {
242        Self {
243            table_name,
244            alias,
245            source_id,
246            supports_history,
247            source_clause,
248        }
249    }
250
251    fn clause(self, history_ref: Option<&str>) -> String {
252        (self.source_clause)(history_ref)
253    }
254
255    pub fn table_name(self) -> &'static str {
256        self.table_name
257    }
258
259    pub fn alias(self) -> &'static str {
260        self.alias
261    }
262
263    fn supports_history(self) -> bool {
264        self.supports_history
265    }
266
267    fn has_same_definition(self, other: Self) -> bool {
268        self.table_name == other.table_name
269            && self.alias == other.alias
270            && self.source_id == other.source_id
271            && self.supports_history == other.supports_history
272    }
273}
274
275#[doc(hidden)]
276#[derive(Clone, Debug)]
277pub struct SqlJoin {
278    source: SqlSource,
279    condition: String,
280}
281
282impl SqlJoin {
283    fn new(source: SqlSource, condition: String) -> Self {
284        Self { source, condition }
285    }
286
287    fn append_sql(&self, query: &mut String, history_ref: Option<&str>) {
288        query.push_str(" JOIN ");
289        query.push_str(&self.source.clause(history_ref));
290        query.push_str(" ON ");
291        query.push_str(&self.condition);
292    }
293
294    pub fn source(&self) -> SqlSource {
295        self.source
296    }
297}
298
299#[doc(hidden)]
300#[derive(Clone, Debug, Default)]
301pub struct SqlJoins {
302    joins: IndexMap<&'static str, SqlJoin>,
303}
304
305impl SqlJoins {
306    pub fn len(&self) -> usize {
307        self.joins.len()
308    }
309
310    pub fn is_empty(&self) -> bool {
311        self.joins.is_empty()
312    }
313
314    pub fn iter(&self) -> impl Iterator<Item = &SqlJoin> {
315        self.joins.values()
316    }
317
318    pub fn insert(&mut self, join: SqlJoin) -> Result<(), SelectorBuildError> {
319        let alias = join.source.alias();
320        if let Some(existing) = self.joins.get(alias) {
321            if !existing.source.has_same_definition(join.source)
322                || existing.condition != join.condition
323            {
324                return Err(SelectorBuildError::InvalidSelector(format!(
325                    "cannot use SQL source alias `{alias}` for different joins"
326                )));
327            }
328        } else {
329            self.joins.insert(alias, join);
330        }
331        Ok(())
332    }
333
334    pub fn extend_from(&mut self, joins: &Self) -> Result<(), SelectorBuildError> {
335        for join in joins.iter() {
336            self.insert(join.clone())?;
337        }
338        Ok(())
339    }
340}
341
342#[doc(hidden)]
343pub trait SelectQuery {
344    fn connection(&self) -> &Connection;
345
346    fn source(&self) -> SqlSource;
347
348    fn error(&self) -> Option<&SelectorBuildError>;
349
350    fn history_ref(&self) -> Option<&str>;
351
352    fn joins(&self) -> &SqlJoins;
353
354    fn filters(&self) -> &[SqlFilter];
355
356    fn order_by(&self) -> &[SqlOrder];
357
358    fn default_order_by(&self) -> &[SqlOrder];
359
360    fn limit(&self) -> Option<u32>;
361
362    fn offset(&self) -> u32;
363
364    fn select_clause(&self) -> String {
365        select_all_sql(self.source().alias())
366    }
367}
368
369#[doc(hidden)]
370#[derive(Debug, Eq, PartialEq)]
371pub struct SelectField<M, T, JoinType = T> {
372    table_name: &'static str,
373    alias: &'static str,
374    column: &'static str,
375    field: PhantomData<fn() -> (M, T)>,
376    join_type: PhantomData<fn() -> JoinType>,
377}
378
379impl<M, T, JoinType> SelectField<M, T, JoinType> {
380    pub const fn new(table_name: &'static str, alias: &'static str, column: &'static str) -> Self {
381        Self {
382            table_name,
383            alias,
384            column,
385            field: PhantomData,
386            join_type: PhantomData,
387        }
388    }
389
390    pub const fn column(self) -> &'static str {
391        self.column
392    }
393
394    pub const fn table_name(self) -> &'static str {
395        self.table_name
396    }
397
398    pub const fn alias(self) -> &'static str {
399        self.alias
400    }
401}
402
403impl<M, T, JoinType> Clone for SelectField<M, T, JoinType> {
404    fn clone(&self) -> Self {
405        *self
406    }
407}
408
409impl<M, T, JoinType> Copy for SelectField<M, T, JoinType> {}
410
411#[doc(hidden)]
412pub trait ProjectionField {
413    type Output;
414
415    fn table_name(&self) -> &'static str;
416
417    fn alias(&self) -> &'static str;
418
419    fn column(&self) -> &'static str;
420
421    fn process_row(&self, row: &Row, index: usize) -> rusqlite::Result<Self::Output>;
422}
423
424impl<M, T, JoinType> ProjectionField for SelectField<M, T, JoinType>
425where
426    T: FromSql,
427{
428    type Output = T;
429
430    fn table_name(&self) -> &'static str {
431        self.table_name
432    }
433
434    fn alias(&self) -> &'static str {
435        self.alias
436    }
437
438    fn column(&self) -> &'static str {
439        self.column
440    }
441
442    fn process_row(&self, row: &Row, index: usize) -> rusqlite::Result<Self::Output> {
443        row.get(index)
444    }
445}
446
447#[doc(hidden)]
448pub trait SelectableModel: Sized {
449    fn table_name() -> &'static str;
450
451    fn alias() -> &'static str;
452
453    fn columns() -> &'static [&'static str];
454
455    fn process_row(row: &Row, offset: usize) -> SqlResult<Self>;
456}
457
458/// Connects each derive-generated full-row decoder to the shared loader. This is the only model
459/// behavior the runtime needs generically; table and column metadata stay in generated selectors.
460#[doc(hidden)]
461pub trait ModelSelectRow: Sized {
462    fn process_row(row: &Row) -> SqlResult<Self>;
463}
464
465#[doc(hidden)]
466pub trait ModelSelectSource: Sized + 'static {
467    type Selector<'conn>: SelectQuery;
468
469    fn selector(conn: &Connection) -> Self::Selector<'_>;
470}
471
472#[doc(hidden)]
473pub trait SelectProjection {
474    type Output;
475
476    fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)>;
477
478    fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output>;
479}
480
481impl<M, T, JoinType> SelectProjection for SelectField<M, T, JoinType>
482where
483    T: FromSql,
484{
485    type Output = T;
486
487    fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)> {
488        vec![(self.table_name, self.alias, self.column)]
489    }
490
491    fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output> {
492        row.get(0)
493    }
494}
495
496macro_rules! impl_select_projection_for_tuple {
497    ($($field:ident:$index:tt),+) => {
498        impl<$($field),+> SelectProjection for ($($field,)+)
499        where
500            $($field: ProjectionField,)+
501        {
502            type Output = ($(<$field as ProjectionField>::Output,)+);
503
504            fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)> {
505                vec![$(
506                    (
507                        self.$index.table_name(),
508                        self.$index.alias(),
509                        self.$index.column(),
510                    )
511                ),+]
512            }
513
514            fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output> {
515                Ok(($(self.$index.process_row(row, $index)?,)+))
516            }
517        }
518    };
519}
520
521impl_select_projection_for_tuple!(A:0);
522impl_select_projection_for_tuple!(A:0, B:1);
523impl_select_projection_for_tuple!(A:0, B:1, C:2);
524impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3);
525impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4);
526impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5);
527impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6);
528impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7);
529impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8);
530impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9);
531impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10);
532impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11);
533impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12);
534impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13);
535impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14);
536impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9, K:10, L:11, M:12, N:13, O:14, P:15);
537
538#[doc(hidden)]
539pub trait ModelProjection {
540    type Output;
541
542    fn fields() -> Vec<(&'static str, &'static str, &'static str)>;
543
544    fn process_row(row: &Row) -> SqlResult<Self::Output>;
545}
546
547macro_rules! impl_model_projection_for_tuple {
548    ($($model:ident),+) => {
549        impl<$($model),+> ModelProjection for ($($model,)+)
550        where
551            $($model: SelectableModel,)+
552        {
553            type Output = ($($model,)+);
554
555            fn fields() -> Vec<(&'static str, &'static str, &'static str)> {
556                let mut fields = Vec::new();
557                $(
558                    for column in <$model as SelectableModel>::columns() {
559                        fields.push((
560                            <$model as SelectableModel>::table_name(),
561                            <$model as SelectableModel>::alias(),
562                            *column,
563                        ));
564                    }
565                )+
566                fields
567            }
568
569            fn process_row(row: &Row) -> SqlResult<Self::Output> {
570                let mut offset = 0;
571                let output = ($({
572                    let model = <$model as SelectableModel>::process_row(row, offset)?;
573                    offset += <$model as SelectableModel>::columns().len();
574                    model
575                },)+);
576                let _ = offset;
577                Ok(output)
578            }
579        }
580    };
581}
582
583impl_model_projection_for_tuple!(A);
584impl_model_projection_for_tuple!(A, B);
585impl_model_projection_for_tuple!(A, B, C);
586impl_model_projection_for_tuple!(A, B, C, D);
587impl_model_projection_for_tuple!(A, B, C, D, E);
588impl_model_projection_for_tuple!(A, B, C, D, E, F);
589impl_model_projection_for_tuple!(A, B, C, D, E, F, G);
590impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H);
591impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I);
592impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J);
593impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
594impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
595impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
596impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
597impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
598impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
599
600#[doc(hidden)]
601pub struct SelectedFields<S, P> {
602    select: S,
603    projection: P,
604}
605
606impl<S, P> SelectedFields<S, P> {
607    pub fn new(select: S, projection: P) -> Self {
608        Self { select, projection }
609    }
610}
611
612impl<S, P> SelectedFields<S, P>
613where
614    S: SelectQuery,
615    P: SelectProjection,
616{
617    pub fn load(self) -> Result<Vec<P::Output>, ModelSelectError> {
618        let Self { select, projection } = self;
619        load_projection(select, projection.fields(), |row| {
620            projection.process_row(row)
621        })
622    }
623}
624
625#[doc(hidden)]
626pub struct SelectedModels<S, P> {
627    select: S,
628    projection: PhantomData<fn() -> P>,
629}
630
631impl<S, P> SelectedModels<S, P> {
632    pub fn new(select: S) -> Self {
633        Self {
634            select,
635            projection: PhantomData,
636        }
637    }
638}
639
640impl<S, P> SelectedModels<S, P>
641where
642    S: SelectQuery,
643    P: ModelProjection,
644{
645    pub fn load(self) -> Result<Vec<P::Output>, ModelSelectError> {
646        load_projection(self.select, P::fields(), P::process_row)
647    }
648}
649
650fn load_projection<S, T>(
651    select: S,
652    fields: Vec<(&'static str, &'static str, &'static str)>,
653    process_row: impl FnMut(&Row) -> SqlResult<T>,
654) -> Result<Vec<T>, ModelSelectError>
655where
656    S: SelectQuery,
657{
658    if let Some(error) = select.error() {
659        return Err(error.clone().into());
660    }
661    validate_projection_sources(&select, &fields)?;
662    let select_clause = fields
663        .iter()
664        .map(|(_, alias, column)| qualify_sql_column(alias, column))
665        .join(", ");
666    let (query, params) = render_query(&select, select_clause, None)?;
667    query_rows(select.connection(), &query, params, process_row)
668}
669
670fn validate_projection_sources<S>(
671    select: &S,
672    fields: &[(&'static str, &'static str, &'static str)],
673) -> Result<(), ModelSelectError>
674where
675    S: SelectQuery,
676{
677    for (table_name, alias, _) in fields {
678        let source = select.source();
679        let source_is_available = source.table_name() == *table_name && source.alias() == *alias
680            || select.joins().iter().any(|join| {
681                let source = join.source();
682                source.table_name() == *table_name && source.alias() == *alias
683            });
684        if !source_is_available {
685            return Err(ModelSelectError::ProjectionSourceNotSelected {
686                table_name: (*table_name).to_string(),
687                alias: (*alias).to_string(),
688            });
689        }
690    }
691    Ok(())
692}
693
694#[doc(hidden)]
695pub fn load<M, S>(conn: &Connection, select: &S) -> Result<Vec<M>, ModelSelectError>
696where
697    M: ModelSelectRow,
698    S: SelectQuery,
699{
700    let (query, params) = render_query(select, select.select_clause(), None)?;
701    query_rows(conn, &query, params, M::process_row)
702}
703
704#[doc(hidden)]
705pub fn get<M, S>(conn: &Connection, select: &S) -> Result<Option<M>, ModelSelectError>
706where
707    M: ModelSelectRow,
708    S: SelectQuery,
709{
710    let (query, params) = render_query(select, select.select_clause(), Some(2))?;
711    let mut rows = query_rows(conn, &query, params, M::process_row)?;
712    match rows.len() {
713        0 => Ok(None),
714        1 => Ok(rows.pop()),
715        _ => Err(ModelSelectError::MultipleResults),
716    }
717}
718
719fn render_query<S>(
720    select: &S,
721    select_clause: String,
722    maximum_rows: Option<u32>,
723) -> Result<(String, Vec<SqlParameter>), ModelSelectError>
724where
725    S: SelectQuery,
726{
727    if let Some(error) = select.error() {
728        return Err(error.clone().into());
729    }
730    if select.history_ref().is_some() {
731        for source in
732            core::iter::once(select.source()).chain(select.joins().iter().map(|join| join.source()))
733        {
734            if !source.supports_history() {
735                return Err(SelectorBuildError::HistoryNotSupported {
736                    table_name: source.table_name(),
737                }
738                .into());
739            }
740        }
741    }
742
743    let mut query = format!(
744        "SELECT {select_clause} FROM {}",
745        select.source().clause(select.history_ref()),
746    );
747    for join in select.joins().iter() {
748        join.append_sql(&mut query, select.history_ref());
749    }
750
751    let mut params = select
752        .history_ref()
753        .map(|history_ref| vec![SqlParameter::Scalar(Value::from(history_ref.to_string()))])
754        .unwrap_or_default();
755    let filters = select.filters();
756    for (index, ordered_in) in filters
757        .iter()
758        .filter_map(|filter| filter.ordered_in.as_ref())
759        .enumerate()
760    {
761        append_ordered_in_join(&mut query, &mut params, ordered_in, index);
762    }
763
764    if filters.iter().any(|filter| !filter.clause.is_empty()) {
765        query.push_str(" WHERE ");
766        for (index, filter) in filters
767            .iter()
768            .filter(|filter| !filter.clause.is_empty())
769            .enumerate()
770        {
771            if index > 0 {
772                query.push_str(" AND ");
773            }
774            query.push_str(&filter.clause);
775            params.extend(filter.params.iter().cloned().map(SqlParameter::Scalar));
776        }
777    }
778
779    let order_by = if select.order_by().is_empty() {
780        select.default_order_by()
781    } else {
782        select.order_by()
783    };
784    let ordered_in_count = filters
785        .iter()
786        .filter(|filter| filter.ordered_in.is_some())
787        .count();
788    if ordered_in_count > 0 || !order_by.is_empty() {
789        query.push_str(" ORDER BY ");
790        // Each ordered-IN relation exposes the first input position for a value. Sorting by its
791        // internal alias preserves caller order after duplicate inputs have been grouped away.
792        for index in 0..ordered_in_count {
793            if index > 0 {
794                query.push_str(", ");
795            }
796            query.push_str(&qualify_sql_column(
797                &format!("__model_select_in_{index}"),
798                "position",
799            ));
800            query.push_str(" ASC");
801        }
802        for (index, order) in order_by.iter().enumerate() {
803            if ordered_in_count > 0 || index > 0 {
804                query.push_str(", ");
805            }
806            if let Some(search) = &order.relevance_search {
807                let column = &order.column;
808                query.push_str(&format!(
809                    "CASE WHEN {column} = ? THEN 0 WHEN lower({column}) = lower(?) THEN 1 \
810                     WHEN {column} LIKE ? || '%' THEN 2 \
811                     WHEN {column} LIKE '%' || ? || '%' THEN 3 ELSE 4 END",
812                ));
813                // Ordering parameters follow all source and filter parameters, regardless of
814                // the order in which builder methods or joined selectors were composed.
815                params.extend((0..4).map(|_| SqlParameter::Scalar(Value::from(search.clone()))));
816            } else {
817                query.push_str(&order.column);
818            }
819            if order.direction.uses_case_insensitive_collation() {
820                query.push_str(" COLLATE NOCASE");
821            }
822            query.push(' ');
823            query.push_str(order.direction.as_sql());
824        }
825    }
826
827    let effective_limit = maximum_rows.or(select.limit());
828    if let Some(limit) = effective_limit {
829        query.push_str(" LIMIT ?");
830        params.push(SqlParameter::Scalar(Value::from(i64::from(limit))));
831    }
832    let offset = select.offset();
833    if offset > 0 {
834        if effective_limit.is_none() {
835            query.push_str(" LIMIT -1");
836        }
837        query.push_str(" OFFSET ?");
838        params.push(SqlParameter::Scalar(Value::from(i64::from(offset))));
839    }
840
841    let parameter_limit = sqlite_parameter_limit(select.connection());
842    if params.len() > parameter_limit {
843        return Err(SelectorBuildError::InvalidSelector(format!(
844            "selector requires {} SQL parameters, but the connection limit is {parameter_limit}",
845            params.len(),
846        ))
847        .into());
848    }
849
850    Ok((query, params))
851}
852
853#[doc(hidden)]
854pub fn delete_by_ids(
855    conn: &Connection,
856    table_name: &str,
857    primary_keys: &[&str],
858    rows: Vec<Vec<Value>>,
859) -> Result<usize, ModelSelectError> {
860    if primary_keys.is_empty() {
861        return Err(SelectorBuildError::InvalidSelector(
862            "a primary key must contain at least one column".to_string(),
863        )
864        .into());
865    }
866    if rows.iter().any(|row| row.len() != primary_keys.len()) {
867        return Err(SelectorBuildError::InvalidSelector(
868            "each primary-key value must match the number of key columns".to_string(),
869        )
870        .into());
871    }
872    if rows.is_empty() {
873        return Ok(0);
874    }
875
876    let quoted_table = quote_sql_identifier(table_name);
877    // Generated aliases share SQL's identifier namespace with model tables and columns. The
878    // distinctive prefix marks them as renderer-owned, while the key index keeps them distinct.
879    let aliases = (0..primary_keys.len())
880        .map(|index| format!("__model_select_delete_key_{index}"))
881        .collect::<Vec<_>>();
882    let mut query = format!("DELETE FROM {quoted_table} WHERE ");
883    if primary_keys.len() > 1 {
884        query.push('(');
885    }
886    for (index, primary_key) in primary_keys.iter().enumerate() {
887        if index > 0 {
888            query.push_str(", ");
889        }
890        query.push_str(&qualify_sql_column(table_name, primary_key));
891    }
892    if primary_keys.len() > 1 {
893        query.push(')');
894    }
895    query.push_str(" IN (SELECT ");
896    for (index, alias) in aliases.iter().enumerate() {
897        if index > 0 {
898            query.push_str(", ");
899        }
900        query.push_str(&qualify_sql_column(alias, "value"));
901    }
902    query.push_str(" FROM ");
903    for (index, alias) in aliases.iter().enumerate() {
904        if index == 0 {
905            query.push_str(&format!(
906                "rarray(?{}) AS {}",
907                index + 1,
908                quote_sql_identifier(alias),
909            ));
910        } else {
911            query.push_str(&format!(
912                " JOIN rarray(?{}) AS {} ON {} = {}",
913                index + 1,
914                quote_sql_identifier(alias),
915                qualify_sql_column(alias, "rowid"),
916                qualify_sql_column(&aliases[0], "rowid"),
917            ));
918        }
919    }
920    query.push(')');
921
922    let batch_size = max_rows_per_batch(conn, primary_keys.len());
923    let mut deleted = 0;
924    let mut statement = conn.prepare(&query)?;
925    for chunk in rows.chunks(batch_size) {
926        let params = (0..primary_keys.len()).map(|column_index| {
927            SqlParameter::Array(Rc::new(
928                chunk.iter().map(|row| row[column_index].clone()).collect(),
929            ))
930        });
931        deleted += statement.execute(params_from_iter(params))?;
932    }
933    Ok(deleted)
934}
935
936fn append_ordered_in_join(
937    query: &mut String,
938    params: &mut Vec<SqlParameter>,
939    ordered_in: &OrderedSqlIn,
940    index: usize,
941) {
942    let column_count = ordered_in.columns.len();
943    // Ordered-IN expands one rarray relation per key column. The renderer-owned prefix and filter
944    // and column indexes keep those synthetic relations distinct from one another.
945    let values_alias = quote_sql_identifier(&format!("__model_select_in_values_{index}"));
946    let order_alias = format!("__model_select_in_{index}");
947    let value_columns = (0..column_count)
948        .map(|column_index| format!("value_{column_index}"))
949        .collect::<Vec<_>>();
950    query.push_str(" JOIN (SELECT ");
951    for (column_index, value_column) in value_columns.iter().enumerate() {
952        if column_index > 0 {
953            query.push_str(", ");
954        }
955        query.push_str(&quote_sql_identifier(value_column));
956    }
957    query.push_str(", MIN(\"position\") AS \"position\" FROM (");
958    let array_aliases = (0..column_count)
959        .map(|column_index| format!("__model_select_in_array_{index}_{column_index}"))
960        .collect::<Vec<_>>();
961    query.push_str("SELECT ");
962    for (column_index, (array_alias, value_column)) in
963        array_aliases.iter().zip(&value_columns).enumerate()
964    {
965        if column_index > 0 {
966            query.push_str(", ");
967        }
968        query.push_str(&qualify_sql_column(array_alias, "value"));
969        query.push_str(" AS ");
970        query.push_str(&quote_sql_identifier(value_column));
971    }
972    query.push_str(", ");
973    query.push_str(&qualify_sql_column(&array_aliases[0], "rowid"));
974    query.push_str(" AS \"position\" FROM ");
975    for (column_index, array_alias) in array_aliases.iter().enumerate() {
976        if column_index == 0 {
977            query.push_str("rarray(?) AS ");
978            query.push_str(&quote_sql_identifier(array_alias));
979        } else {
980            query.push_str(" JOIN rarray(?) AS ");
981            query.push_str(&quote_sql_identifier(array_alias));
982            query.push_str(" ON ");
983            query.push_str(&qualify_sql_column(array_alias, "rowid"));
984            query.push_str(" = ");
985            query.push_str(&qualify_sql_column(&array_aliases[0], "rowid"));
986        }
987        params.push(SqlParameter::Array(Rc::new(
988            ordered_in
989                .rows
990                .iter()
991                .map(|row| row[column_index].clone())
992                .collect(),
993        )));
994    }
995    query.push_str(") AS ");
996    query.push_str(&values_alias);
997    query.push_str(" GROUP BY ");
998    for (column_index, value_column) in value_columns.iter().enumerate() {
999        if column_index > 0 {
1000            query.push_str(", ");
1001        }
1002        query.push_str(&quote_sql_identifier(value_column));
1003    }
1004    query.push_str(") AS ");
1005    query.push_str(&quote_sql_identifier(&order_alias));
1006    query.push_str(" ON ");
1007    for (column_index, (column, value_column)) in
1008        ordered_in.columns.iter().zip(&value_columns).enumerate()
1009    {
1010        if column_index > 0 {
1011            query.push_str(" AND ");
1012        }
1013        query.push_str(column);
1014        query.push_str(" = ");
1015        query.push_str(&qualify_sql_column(&order_alias, value_column));
1016    }
1017}
1018
1019fn query_rows<T>(
1020    conn: &Connection,
1021    query: &str,
1022    params: Vec<SqlParameter>,
1023    mut process_row: impl FnMut(&Row) -> rusqlite::Result<T>,
1024) -> Result<Vec<T>, ModelSelectError> {
1025    let mut statement = conn.prepare(query)?;
1026    let rows = statement.query_map(params_from_iter(params), |row| process_row(row))?;
1027    rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
1028}
1029
1030/// Decodes model rows for internal SQL that cannot be represented by the fluent selector, such as
1031/// recursive CTEs. Callers remain responsible for using bound parameters for runtime values.
1032#[doc(hidden)]
1033pub fn query_models<M, P>(conn: &Connection, query: &str, params: P) -> SqlResult<Vec<M>>
1034where
1035    M: ModelSelectRow,
1036    P: Params,
1037{
1038    let mut statement = conn.prepare(query)?;
1039    let rows = statement.query_map(params, M::process_row)?;
1040    rows.collect()
1041}
1042
1043#[doc(hidden)]
1044pub fn qualify_sql_column(alias: &str, column: &str) -> String {
1045    format!(
1046        "{}.{}",
1047        quote_sql_identifier(alias),
1048        quote_sql_identifier(column),
1049    )
1050}
1051
1052#[doc(hidden)]
1053pub fn select_all_sql(alias: &str) -> String {
1054    format!("{}.*", quote_sql_identifier(alias))
1055}
1056
1057#[doc(hidden)]
1058pub fn default_sql_source(
1059    table_name: &str,
1060    history_table_name: Option<&str>,
1061    alias: &str,
1062    history_ref: Option<&str>,
1063) -> String {
1064    let source = sql_table_name_with_history_ref(table_name, history_table_name, history_ref);
1065    format!("{source} AS {}", quote_sql_identifier(alias))
1066}
1067
1068#[doc(hidden)]
1069pub fn sql_table_name_with_history_ref(
1070    table_name: &str,
1071    history_table_name: Option<&str>,
1072    history_ref: Option<&str>,
1073) -> String {
1074    if history_ref.is_some() {
1075        let history_table_name = history_table_name.expect("should support history ref queries");
1076        quote_sql_identifier(&format!("dolt_at_{history_table_name}")) + "(:history_ref)"
1077    } else {
1078        quote_sql_identifier(table_name)
1079    }
1080}
1081
1082#[doc(hidden)]
1083pub fn sql_join_on<SourceModel, SourceType, JoinedModel, JoinedType, JoinType>(
1084    existing_sources: &[SqlSource],
1085    joined_source: SqlSource,
1086    source_field: SelectField<SourceModel, SourceType, JoinType>,
1087    joined_field: SelectField<JoinedModel, JoinedType, JoinType>,
1088) -> Result<SqlJoin, SelectorBuildError> {
1089    if existing_sources
1090        .first()
1091        .is_some_and(|source| source.alias() == joined_source.alias())
1092    {
1093        return Err(SelectorBuildError::InvalidSelector(format!(
1094            "cannot join the base SQL source alias `{}`",
1095            joined_source.alias(),
1096        )));
1097    }
1098    if !existing_sources.iter().any(|source| {
1099        source.table_name() == source_field.table_name() && source.alias() == source_field.alias()
1100    }) {
1101        return Err(SelectorBuildError::InvalidSelector(format!(
1102            "cannot join from unselected SQL source `{} AS {}`",
1103            source_field.table_name(),
1104            source_field.alias(),
1105        )));
1106    }
1107    if joined_source.table_name() != joined_field.table_name()
1108        || joined_source.alias() != joined_field.alias()
1109    {
1110        return Err(SelectorBuildError::InvalidSelector(format!(
1111            "joined field source `{} AS {}` does not match selector source `{} AS {}`",
1112            joined_field.table_name(),
1113            joined_field.alias(),
1114            joined_source.table_name(),
1115            joined_source.alias(),
1116        )));
1117    }
1118
1119    let condition = format!(
1120        "{} = {}",
1121        qualify_sql_column(source_field.alias(), source_field.column()),
1122        qualify_sql_column(joined_field.alias(), joined_field.column()),
1123    );
1124    Ok(SqlJoin::new(joined_source, condition))
1125}
1126
1127fn quote_sql_identifier(identifier: &str) -> String {
1128    format!("\"{}\"", identifier.replace('"', "\"\""))
1129}
1130
1131#[cfg(test)]
1132mod tests {
1133    use super::{
1134        SelectField, SelectorBuildError, SqlJoins, SqlSource, default_sql_source,
1135        qualify_sql_column, select_all_sql, sql_join_on,
1136    };
1137
1138    fn child_source_clause(_history_ref: Option<&str>) -> String {
1139        "selector_children".to_string()
1140    }
1141
1142    fn parent_source_clause(_history_ref: Option<&str>) -> String {
1143        "selector_parents".to_string()
1144    }
1145
1146    #[test]
1147    fn test_explicit_join_quotes_field_identifiers_without_database_metadata() {
1148        let child_source = SqlSource::new(
1149            "selector_children",
1150            "children.alias",
1151            "tests::children",
1152            true,
1153            child_source_clause,
1154        );
1155        let parent_source = SqlSource::new(
1156            "selector_parents",
1157            "parents\" --",
1158            "tests::parents",
1159            true,
1160            parent_source_clause,
1161        );
1162        let source_field = SelectField::<(), i64>::new(
1163            "selector_children",
1164            "children.alias",
1165            "source\" OR attacker_effect()",
1166        );
1167        let joined_field =
1168            SelectField::<(), i64>::new("selector_parents", "parents\" --", "target.column");
1169
1170        let join = sql_join_on(&[child_source], parent_source, source_field, joined_field)
1171            .expect("should create an explicit join");
1172        assert_eq!(
1173            join.condition,
1174            "\"children.alias\".\"source\"\" OR attacker_effect()\" = \"parents\"\" --\".\"target.column\"",
1175        );
1176    }
1177
1178    #[test]
1179    fn test_duplicate_identical_joins_are_deduplicated_in_insertion_order() {
1180        let child_source = SqlSource::new(
1181            "selector_children",
1182            "selector_children",
1183            "tests::children",
1184            true,
1185            child_source_clause,
1186        );
1187        let later_source = SqlSource::new(
1188            "later_parents",
1189            "z_parents",
1190            "tests::later_parents",
1191            true,
1192            parent_source_clause,
1193        );
1194        let earlier_source = SqlSource::new(
1195            "earlier_parents",
1196            "a_parents",
1197            "tests::earlier_parents",
1198            true,
1199            parent_source_clause,
1200        );
1201        let source_field =
1202            SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id");
1203        let later_field = SelectField::<(), i64>::new("later_parents", "z_parents", "id");
1204        let earlier_field = SelectField::<(), i64>::new("earlier_parents", "a_parents", "id");
1205        let later_join = sql_join_on(&[child_source], later_source, source_field, later_field)
1206            .expect("should create the later join");
1207        let earlier_join =
1208            sql_join_on(&[child_source], earlier_source, source_field, earlier_field)
1209                .expect("should create the earlier join");
1210        let mut joins = SqlJoins::default();
1211
1212        joins
1213            .insert(later_join.clone())
1214            .expect("should insert the later join");
1215        joins
1216            .insert(earlier_join)
1217            .expect("should insert the earlier join");
1218        joins
1219            .insert(later_join)
1220            .expect("should deduplicate the later join");
1221
1222        assert_eq!(joins.len(), 2);
1223        assert_eq!(
1224            joins
1225                .iter()
1226                .map(|join| join.source().alias())
1227                .collect::<Vec<_>>(),
1228            vec!["z_parents", "a_parents"],
1229        );
1230    }
1231
1232    #[test]
1233    fn test_duplicate_alias_with_different_join_is_rejected() {
1234        let child_source = SqlSource::new(
1235            "selector_children",
1236            "selector_children",
1237            "tests::children",
1238            true,
1239            child_source_clause,
1240        );
1241        let parent_source = SqlSource::new(
1242            "selector_parents",
1243            "selector_parents",
1244            "tests::parents",
1245            true,
1246            parent_source_clause,
1247        );
1248        let joined_field =
1249            SelectField::<(), i64>::new("selector_parents", "selector_parents", "id");
1250        let first_join = sql_join_on(
1251            &[child_source],
1252            parent_source,
1253            SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id"),
1254            joined_field,
1255        )
1256        .expect("should create the first join");
1257        let second_join = sql_join_on(
1258            &[child_source],
1259            parent_source,
1260            SelectField::<(), i64>::new(
1261                "selector_children",
1262                "selector_children",
1263                "other_parent_id",
1264            ),
1265            joined_field,
1266        )
1267        .expect("should create the second join");
1268        let mut joins = SqlJoins::default();
1269
1270        joins
1271            .insert(first_join)
1272            .expect("should insert the first join");
1273        let error = joins
1274            .insert(second_join)
1275            .expect_err("should reject a conflicting join");
1276
1277        assert_eq!(
1278            error,
1279            SelectorBuildError::InvalidSelector(
1280                "cannot use SQL source alias `selector_parents` for different joins".to_string(),
1281            )
1282        );
1283    }
1284
1285    #[test]
1286    fn test_duplicate_alias_with_different_source_is_rejected() {
1287        let child_source = SqlSource::new(
1288            "selector_children",
1289            "selector_children",
1290            "tests::children",
1291            true,
1292            child_source_clause,
1293        );
1294        let first_source = SqlSource::new(
1295            "selector_parents",
1296            "shared_parents",
1297            "tests::parents",
1298            true,
1299            parent_source_clause,
1300        );
1301        let second_source = SqlSource::new(
1302            "alternate_parents",
1303            "shared_parents",
1304            "tests::alternate_parents",
1305            true,
1306            parent_source_clause,
1307        );
1308        let source_field =
1309            SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id");
1310        let first_join = sql_join_on(
1311            &[child_source],
1312            first_source,
1313            source_field,
1314            SelectField::<(), i64>::new("selector_parents", "shared_parents", "id"),
1315        )
1316        .expect("should create the first join");
1317        let second_join = sql_join_on(
1318            &[child_source],
1319            second_source,
1320            source_field,
1321            SelectField::<(), i64>::new("alternate_parents", "shared_parents", "id"),
1322        )
1323        .expect("should create the second join");
1324        let mut joins = SqlJoins::default();
1325
1326        joins
1327            .insert(first_join)
1328            .expect("should insert the first join");
1329        let error = joins
1330            .insert(second_join)
1331            .expect_err("should reject a conflicting source");
1332
1333        assert_eq!(
1334            error,
1335            SelectorBuildError::InvalidSelector(
1336                "cannot use SQL source alias `shared_parents` for different joins".to_string(),
1337            )
1338        );
1339    }
1340
1341    #[test]
1342    fn test_structured_sql_helpers_quote_every_identifier() {
1343        assert_eq!(
1344            qualify_sql_column("source.alias", "target.column"),
1345            "\"source.alias\".\"target.column\"",
1346        );
1347        assert_eq!(select_all_sql("source\"alias"), "\"source\"\"alias\".*");
1348        assert_eq!(
1349            default_sql_source("table name", Some("history.table"), "select", None),
1350            "\"table name\" AS \"select\"",
1351        );
1352        assert_eq!(
1353            default_sql_source("table name", Some("history.table"), "select", Some("main"),),
1354            "\"dolt_at_history.table\"(:history_ref) AS \"select\"",
1355        );
1356    }
1357}