1use core::marker::PhantomData;
4use std::rc::Rc;
5
6use indexmap::IndexMap;
7use itertools::Itertools;
8pub use rusqlite::{Connection, Error as SqlError, 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 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 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 fn set_history_ref(&mut self, _history_ref: Option<&str>) {}
458}
459
460#[doc(hidden)]
463pub trait ModelSelectRow: Sized {
464 fn process_row(row: &Row) -> SqlResult<Self>;
465
466 fn set_history_ref(&mut self, _history_ref: Option<&str>) {}
467}
468
469#[doc(hidden)]
470pub trait ModelSelectSource: Sized + 'static {
471 type Selector<'conn>: SelectQuery;
472
473 fn selector(conn: &Connection) -> Self::Selector<'_>;
474}
475
476#[doc(hidden)]
477pub trait SelectProjection {
478 type Output;
479
480 fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)>;
481
482 fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output>;
483}
484
485impl<M, T, JoinType> SelectProjection for SelectField<M, T, JoinType>
486where
487 T: FromSql,
488{
489 type Output = T;
490
491 fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)> {
492 vec![(self.table_name, self.alias, self.column)]
493 }
494
495 fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output> {
496 row.get(0)
497 }
498}
499
500macro_rules! impl_select_projection_for_tuple {
501 ($($field:ident:$index:tt),+) => {
502 impl<$($field),+> SelectProjection for ($($field,)+)
503 where
504 $($field: ProjectionField,)+
505 {
506 type Output = ($(<$field as ProjectionField>::Output,)+);
507
508 fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)> {
509 vec![$(
510 (
511 self.$index.table_name(),
512 self.$index.alias(),
513 self.$index.column(),
514 )
515 ),+]
516 }
517
518 fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output> {
519 Ok(($(self.$index.process_row(row, $index)?,)+))
520 }
521 }
522 };
523}
524
525impl_select_projection_for_tuple!(A:0);
526impl_select_projection_for_tuple!(A:0, B:1);
527impl_select_projection_for_tuple!(A:0, B:1, C:2);
528impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3);
529impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4);
530impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5);
531impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6);
532impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7);
533impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8);
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);
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);
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);
537impl_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);
538impl_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);
539impl_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);
540impl_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);
541
542#[doc(hidden)]
543pub trait ModelProjection {
544 type Output;
545
546 fn fields() -> Vec<(&'static str, &'static str, &'static str)>;
547
548 fn process_row(row: &Row, history_ref: Option<&str>) -> SqlResult<Self::Output>;
549}
550
551macro_rules! impl_model_projection_for_tuple {
552 ($($model:ident),+) => {
553 impl<$($model),+> ModelProjection for ($($model,)+)
554 where
555 $($model: SelectableModel,)+
556 {
557 type Output = ($($model,)+);
558
559 fn fields() -> Vec<(&'static str, &'static str, &'static str)> {
560 let mut fields = Vec::new();
561 $(
562 for column in <$model as SelectableModel>::columns() {
563 fields.push((
564 <$model as SelectableModel>::table_name(),
565 <$model as SelectableModel>::alias(),
566 *column,
567 ));
568 }
569 )+
570 fields
571 }
572
573 fn process_row(
574 row: &Row,
575 history_ref: Option<&str>,
576 ) -> SqlResult<Self::Output> {
577 let mut offset = 0;
578 let output = ($({
579 let mut model = <$model as SelectableModel>::process_row(row, offset)?;
580 <$model as SelectableModel>::set_history_ref(&mut model, history_ref);
581 offset += <$model as SelectableModel>::columns().len();
582 model
583 },)+);
584 let _ = offset;
585 Ok(output)
586 }
587 }
588 };
589}
590
591impl_model_projection_for_tuple!(A);
592impl_model_projection_for_tuple!(A, B);
593impl_model_projection_for_tuple!(A, B, C);
594impl_model_projection_for_tuple!(A, B, C, D);
595impl_model_projection_for_tuple!(A, B, C, D, E);
596impl_model_projection_for_tuple!(A, B, C, D, E, F);
597impl_model_projection_for_tuple!(A, B, C, D, E, F, G);
598impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H);
599impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I);
600impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J);
601impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
602impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
603impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
604impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
605impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
606impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
607
608#[doc(hidden)]
609pub struct SelectedFields<S, P> {
610 select: S,
611 projection: P,
612}
613
614impl<S, P> SelectedFields<S, P> {
615 pub fn new(select: S, projection: P) -> Self {
616 Self { select, projection }
617 }
618}
619
620impl<S, P> SelectedFields<S, P>
621where
622 S: SelectQuery,
623 P: SelectProjection,
624{
625 pub fn load(self) -> Result<Vec<P::Output>, ModelSelectError> {
626 let Self { select, projection } = self;
627 load_projection(select, projection.fields(), |row| {
628 projection.process_row(row)
629 })
630 }
631}
632
633#[doc(hidden)]
634pub struct SelectedModels<S, P> {
635 select: S,
636 projection: PhantomData<fn() -> P>,
637}
638
639impl<S, P> SelectedModels<S, P> {
640 pub fn new(select: S) -> Self {
641 Self {
642 select,
643 projection: PhantomData,
644 }
645 }
646}
647
648impl<S, P> SelectedModels<S, P>
649where
650 S: SelectQuery,
651 P: ModelProjection,
652{
653 pub fn load(self) -> Result<Vec<P::Output>, ModelSelectError> {
654 let history_ref = self.select.history_ref().map(str::to_owned);
655 load_projection(self.select, P::fields(), |row| {
656 P::process_row(row, history_ref.as_deref())
657 })
658 }
659}
660
661fn load_projection<S, T>(
662 select: S,
663 fields: Vec<(&'static str, &'static str, &'static str)>,
664 process_row: impl FnMut(&Row) -> SqlResult<T>,
665) -> Result<Vec<T>, ModelSelectError>
666where
667 S: SelectQuery,
668{
669 if let Some(error) = select.error() {
670 return Err(error.clone().into());
671 }
672 validate_projection_sources(&select, &fields)?;
673 let select_clause = fields
674 .iter()
675 .map(|(_, alias, column)| qualify_sql_column(alias, column))
676 .join(", ");
677 let (query, params) = render_query(&select, select_clause, None)?;
678 query_rows(select.connection(), &query, params, process_row)
679}
680
681fn validate_projection_sources<S>(
682 select: &S,
683 fields: &[(&'static str, &'static str, &'static str)],
684) -> Result<(), ModelSelectError>
685where
686 S: SelectQuery,
687{
688 for (table_name, alias, _) in fields {
689 let source = select.source();
690 let source_is_available = source.table_name() == *table_name && source.alias() == *alias
691 || select.joins().iter().any(|join| {
692 let source = join.source();
693 source.table_name() == *table_name && source.alias() == *alias
694 });
695 if !source_is_available {
696 return Err(ModelSelectError::ProjectionSourceNotSelected {
697 table_name: (*table_name).to_string(),
698 alias: (*alias).to_string(),
699 });
700 }
701 }
702 Ok(())
703}
704
705#[doc(hidden)]
706pub fn load<M, S>(conn: &Connection, select: &S) -> Result<Vec<M>, ModelSelectError>
707where
708 M: ModelSelectRow,
709 S: SelectQuery,
710{
711 let (query, params) = render_query(select, select.select_clause(), None)?;
712 let history_ref = select.history_ref().map(str::to_owned);
713 query_rows(conn, &query, params, |row| {
714 let mut model = M::process_row(row)?;
715 model.set_history_ref(history_ref.as_deref());
716 Ok(model)
717 })
718}
719
720#[doc(hidden)]
721pub fn get<M, S>(conn: &Connection, select: &S) -> Result<Option<M>, ModelSelectError>
722where
723 M: ModelSelectRow,
724 S: SelectQuery,
725{
726 let (query, params) = render_query(select, select.select_clause(), Some(2))?;
727 let history_ref = select.history_ref().map(str::to_owned);
728 let mut rows = query_rows(conn, &query, params, |row| {
729 let mut model = M::process_row(row)?;
730 model.set_history_ref(history_ref.as_deref());
731 Ok(model)
732 })?;
733 match rows.len() {
734 0 => Ok(None),
735 1 => Ok(rows.pop()),
736 _ => Err(ModelSelectError::MultipleResults),
737 }
738}
739
740fn render_query<S>(
741 select: &S,
742 select_clause: String,
743 maximum_rows: Option<u32>,
744) -> Result<(String, Vec<SqlParameter>), ModelSelectError>
745where
746 S: SelectQuery,
747{
748 if let Some(error) = select.error() {
749 return Err(error.clone().into());
750 }
751 if select.history_ref().is_some() {
752 for source in
753 core::iter::once(select.source()).chain(select.joins().iter().map(|join| join.source()))
754 {
755 if !source.supports_history() {
756 return Err(SelectorBuildError::HistoryNotSupported {
757 table_name: source.table_name(),
758 }
759 .into());
760 }
761 }
762 }
763
764 let mut query = format!(
765 "SELECT {select_clause} FROM {}",
766 select.source().clause(select.history_ref()),
767 );
768 for join in select.joins().iter() {
769 join.append_sql(&mut query, select.history_ref());
770 }
771
772 let mut params = select
773 .history_ref()
774 .map(|history_ref| vec![SqlParameter::Scalar(Value::from(history_ref.to_string()))])
775 .unwrap_or_default();
776 let filters = select.filters();
777 for (index, ordered_in) in filters
778 .iter()
779 .filter_map(|filter| filter.ordered_in.as_ref())
780 .enumerate()
781 {
782 append_ordered_in_join(&mut query, &mut params, ordered_in, index);
783 }
784
785 if filters.iter().any(|filter| !filter.clause.is_empty()) {
786 query.push_str(" WHERE ");
787 for (index, filter) in filters
788 .iter()
789 .filter(|filter| !filter.clause.is_empty())
790 .enumerate()
791 {
792 if index > 0 {
793 query.push_str(" AND ");
794 }
795 query.push_str(&filter.clause);
796 params.extend(filter.params.iter().cloned().map(SqlParameter::Scalar));
797 }
798 }
799
800 let order_by = if select.order_by().is_empty() {
801 select.default_order_by()
802 } else {
803 select.order_by()
804 };
805 let ordered_in_count = filters
806 .iter()
807 .filter(|filter| filter.ordered_in.is_some())
808 .count();
809 if ordered_in_count > 0 || !order_by.is_empty() {
810 query.push_str(" ORDER BY ");
811 for index in 0..ordered_in_count {
814 if index > 0 {
815 query.push_str(", ");
816 }
817 query.push_str(&qualify_sql_column(
818 &format!("__model_select_in_{index}"),
819 "position",
820 ));
821 query.push_str(" ASC");
822 }
823 for (index, order) in order_by.iter().enumerate() {
824 if ordered_in_count > 0 || index > 0 {
825 query.push_str(", ");
826 }
827 if let Some(search) = &order.relevance_search {
828 let column = &order.column;
829 query.push_str(&format!(
830 "CASE WHEN {column} = ? THEN 0 WHEN lower({column}) = lower(?) THEN 1 \
831 WHEN {column} LIKE ? || '%' THEN 2 \
832 WHEN {column} LIKE '%' || ? || '%' THEN 3 ELSE 4 END",
833 ));
834 params.extend((0..4).map(|_| SqlParameter::Scalar(Value::from(search.clone()))));
837 } else {
838 query.push_str(&order.column);
839 }
840 if order.direction.uses_case_insensitive_collation() {
841 query.push_str(" COLLATE NOCASE");
842 }
843 query.push(' ');
844 query.push_str(order.direction.as_sql());
845 }
846 }
847
848 let effective_limit = maximum_rows.or(select.limit());
849 if let Some(limit) = effective_limit {
850 query.push_str(" LIMIT ?");
851 params.push(SqlParameter::Scalar(Value::from(i64::from(limit))));
852 }
853 let offset = select.offset();
854 if offset > 0 {
855 if effective_limit.is_none() {
856 query.push_str(" LIMIT -1");
857 }
858 query.push_str(" OFFSET ?");
859 params.push(SqlParameter::Scalar(Value::from(i64::from(offset))));
860 }
861
862 let parameter_limit = sqlite_parameter_limit(select.connection());
863 if params.len() > parameter_limit {
864 return Err(SelectorBuildError::InvalidSelector(format!(
865 "selector requires {} SQL parameters, but the connection limit is {parameter_limit}",
866 params.len(),
867 ))
868 .into());
869 }
870
871 Ok((query, params))
872}
873
874#[doc(hidden)]
875pub fn delete_by_ids(
876 conn: &Connection,
877 table_name: &str,
878 primary_keys: &[&str],
879 rows: Vec<Vec<Value>>,
880) -> Result<usize, ModelSelectError> {
881 if primary_keys.is_empty() {
882 return Err(SelectorBuildError::InvalidSelector(
883 "a primary key must contain at least one column".to_string(),
884 )
885 .into());
886 }
887 if rows.iter().any(|row| row.len() != primary_keys.len()) {
888 return Err(SelectorBuildError::InvalidSelector(
889 "each primary-key value must match the number of key columns".to_string(),
890 )
891 .into());
892 }
893 if rows.is_empty() {
894 return Ok(0);
895 }
896
897 let quoted_table = quote_sql_identifier(table_name);
898 let aliases = (0..primary_keys.len())
901 .map(|index| format!("__model_select_delete_key_{index}"))
902 .collect::<Vec<_>>();
903 let mut query = format!("DELETE FROM {quoted_table} WHERE ");
904 if primary_keys.len() > 1 {
905 query.push('(');
906 }
907 for (index, primary_key) in primary_keys.iter().enumerate() {
908 if index > 0 {
909 query.push_str(", ");
910 }
911 query.push_str(&qualify_sql_column(table_name, primary_key));
912 }
913 if primary_keys.len() > 1 {
914 query.push(')');
915 }
916 query.push_str(" IN (SELECT ");
917 for (index, alias) in aliases.iter().enumerate() {
918 if index > 0 {
919 query.push_str(", ");
920 }
921 query.push_str(&qualify_sql_column(alias, "value"));
922 }
923 query.push_str(" FROM ");
924 for (index, alias) in aliases.iter().enumerate() {
925 if index == 0 {
926 query.push_str(&format!(
927 "rarray(?{}) AS {}",
928 index + 1,
929 quote_sql_identifier(alias),
930 ));
931 } else {
932 query.push_str(&format!(
933 " JOIN rarray(?{}) AS {} ON {} = {}",
934 index + 1,
935 quote_sql_identifier(alias),
936 qualify_sql_column(alias, "rowid"),
937 qualify_sql_column(&aliases[0], "rowid"),
938 ));
939 }
940 }
941 query.push(')');
942
943 let batch_size = max_rows_per_batch(conn, primary_keys.len());
944 let mut deleted = 0;
945 let mut statement = conn.prepare(&query)?;
946 for chunk in rows.chunks(batch_size) {
947 let params = (0..primary_keys.len()).map(|column_index| {
948 SqlParameter::Array(Rc::new(
949 chunk.iter().map(|row| row[column_index].clone()).collect(),
950 ))
951 });
952 deleted += statement.execute(params_from_iter(params))?;
953 }
954 Ok(deleted)
955}
956
957fn append_ordered_in_join(
958 query: &mut String,
959 params: &mut Vec<SqlParameter>,
960 ordered_in: &OrderedSqlIn,
961 index: usize,
962) {
963 let column_count = ordered_in.columns.len();
964 let values_alias = quote_sql_identifier(&format!("__model_select_in_values_{index}"));
967 let order_alias = format!("__model_select_in_{index}");
968 let value_columns = (0..column_count)
969 .map(|column_index| format!("value_{column_index}"))
970 .collect::<Vec<_>>();
971 query.push_str(" JOIN (SELECT ");
972 for (column_index, value_column) in value_columns.iter().enumerate() {
973 if column_index > 0 {
974 query.push_str(", ");
975 }
976 query.push_str("e_sql_identifier(value_column));
977 }
978 query.push_str(", MIN(\"position\") AS \"position\" FROM (");
979 let array_aliases = (0..column_count)
980 .map(|column_index| format!("__model_select_in_array_{index}_{column_index}"))
981 .collect::<Vec<_>>();
982 query.push_str("SELECT ");
983 for (column_index, (array_alias, value_column)) in
984 array_aliases.iter().zip(&value_columns).enumerate()
985 {
986 if column_index > 0 {
987 query.push_str(", ");
988 }
989 query.push_str(&qualify_sql_column(array_alias, "value"));
990 query.push_str(" AS ");
991 query.push_str("e_sql_identifier(value_column));
992 }
993 query.push_str(", ");
994 query.push_str(&qualify_sql_column(&array_aliases[0], "rowid"));
995 query.push_str(" AS \"position\" FROM ");
996 for (column_index, array_alias) in array_aliases.iter().enumerate() {
997 if column_index == 0 {
998 query.push_str("rarray(?) AS ");
999 query.push_str("e_sql_identifier(array_alias));
1000 } else {
1001 query.push_str(" JOIN rarray(?) AS ");
1002 query.push_str("e_sql_identifier(array_alias));
1003 query.push_str(" ON ");
1004 query.push_str(&qualify_sql_column(array_alias, "rowid"));
1005 query.push_str(" = ");
1006 query.push_str(&qualify_sql_column(&array_aliases[0], "rowid"));
1007 }
1008 params.push(SqlParameter::Array(Rc::new(
1009 ordered_in
1010 .rows
1011 .iter()
1012 .map(|row| row[column_index].clone())
1013 .collect(),
1014 )));
1015 }
1016 query.push_str(") AS ");
1017 query.push_str(&values_alias);
1018 query.push_str(" GROUP BY ");
1019 for (column_index, value_column) in value_columns.iter().enumerate() {
1020 if column_index > 0 {
1021 query.push_str(", ");
1022 }
1023 query.push_str("e_sql_identifier(value_column));
1024 }
1025 query.push_str(") AS ");
1026 query.push_str("e_sql_identifier(&order_alias));
1027 query.push_str(" ON ");
1028 for (column_index, (column, value_column)) in
1029 ordered_in.columns.iter().zip(&value_columns).enumerate()
1030 {
1031 if column_index > 0 {
1032 query.push_str(" AND ");
1033 }
1034 query.push_str(column);
1035 query.push_str(" = ");
1036 query.push_str(&qualify_sql_column(&order_alias, value_column));
1037 }
1038}
1039
1040fn query_rows<T>(
1041 conn: &Connection,
1042 query: &str,
1043 params: Vec<SqlParameter>,
1044 mut process_row: impl FnMut(&Row) -> rusqlite::Result<T>,
1045) -> Result<Vec<T>, ModelSelectError> {
1046 let mut statement = conn.prepare(query)?;
1047 let rows = statement.query_map(params_from_iter(params), |row| process_row(row))?;
1048 rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
1049}
1050
1051#[doc(hidden)]
1054pub fn query_models<M, P>(conn: &Connection, query: &str, params: P) -> SqlResult<Vec<M>>
1055where
1056 M: ModelSelectRow,
1057 P: Params,
1058{
1059 let mut statement = conn.prepare(query)?;
1060 let rows = statement.query_map(params, M::process_row)?;
1061 rows.collect()
1062}
1063
1064#[doc(hidden)]
1065pub fn qualify_sql_column(alias: &str, column: &str) -> String {
1066 format!(
1067 "{}.{}",
1068 quote_sql_identifier(alias),
1069 quote_sql_identifier(column),
1070 )
1071}
1072
1073#[doc(hidden)]
1074pub fn select_all_sql(alias: &str) -> String {
1075 format!("{}.*", quote_sql_identifier(alias))
1076}
1077
1078#[doc(hidden)]
1079pub fn default_sql_source(
1080 table_name: &str,
1081 history_table_name: Option<&str>,
1082 alias: &str,
1083 history_ref: Option<&str>,
1084) -> String {
1085 let source = sql_table_name_with_history_ref(table_name, history_table_name, history_ref);
1086 format!("{source} AS {}", quote_sql_identifier(alias))
1087}
1088
1089#[doc(hidden)]
1090pub fn sql_table_name_with_history_ref(
1091 table_name: &str,
1092 history_table_name: Option<&str>,
1093 history_ref: Option<&str>,
1094) -> String {
1095 if history_ref.is_some() {
1096 let history_table_name = history_table_name.expect("should support history ref queries");
1097 quote_sql_identifier(&format!("dolt_at_{history_table_name}")) + "(:history_ref)"
1098 } else {
1099 quote_sql_identifier(table_name)
1100 }
1101}
1102
1103#[doc(hidden)]
1104pub fn sql_join_on<SourceModel, SourceType, JoinedModel, JoinedType, JoinType>(
1105 existing_sources: &[SqlSource],
1106 joined_source: SqlSource,
1107 source_field: SelectField<SourceModel, SourceType, JoinType>,
1108 joined_field: SelectField<JoinedModel, JoinedType, JoinType>,
1109) -> Result<SqlJoin, SelectorBuildError> {
1110 if existing_sources
1111 .first()
1112 .is_some_and(|source| source.alias() == joined_source.alias())
1113 {
1114 return Err(SelectorBuildError::InvalidSelector(format!(
1115 "cannot join the base SQL source alias `{}`",
1116 joined_source.alias(),
1117 )));
1118 }
1119 if !existing_sources.iter().any(|source| {
1120 source.table_name() == source_field.table_name() && source.alias() == source_field.alias()
1121 }) {
1122 return Err(SelectorBuildError::InvalidSelector(format!(
1123 "cannot join from unselected SQL source `{} AS {}`",
1124 source_field.table_name(),
1125 source_field.alias(),
1126 )));
1127 }
1128 if joined_source.table_name() != joined_field.table_name()
1129 || joined_source.alias() != joined_field.alias()
1130 {
1131 return Err(SelectorBuildError::InvalidSelector(format!(
1132 "joined field source `{} AS {}` does not match selector source `{} AS {}`",
1133 joined_field.table_name(),
1134 joined_field.alias(),
1135 joined_source.table_name(),
1136 joined_source.alias(),
1137 )));
1138 }
1139
1140 let condition = format!(
1141 "{} = {}",
1142 qualify_sql_column(source_field.alias(), source_field.column()),
1143 qualify_sql_column(joined_field.alias(), joined_field.column()),
1144 );
1145 Ok(SqlJoin::new(joined_source, condition))
1146}
1147
1148fn quote_sql_identifier(identifier: &str) -> String {
1149 format!("\"{}\"", identifier.replace('"', "\"\""))
1150}
1151
1152#[cfg(test)]
1153mod tests {
1154 use super::{
1155 SelectField, SelectorBuildError, SqlJoins, SqlSource, default_sql_source,
1156 qualify_sql_column, select_all_sql, sql_join_on,
1157 };
1158
1159 fn child_source_clause(_history_ref: Option<&str>) -> String {
1160 "selector_children".to_string()
1161 }
1162
1163 fn parent_source_clause(_history_ref: Option<&str>) -> String {
1164 "selector_parents".to_string()
1165 }
1166
1167 #[test]
1168 fn test_explicit_join_quotes_field_identifiers_without_database_metadata() {
1169 let child_source = SqlSource::new(
1170 "selector_children",
1171 "children.alias",
1172 "tests::children",
1173 true,
1174 child_source_clause,
1175 );
1176 let parent_source = SqlSource::new(
1177 "selector_parents",
1178 "parents\" --",
1179 "tests::parents",
1180 true,
1181 parent_source_clause,
1182 );
1183 let source_field = SelectField::<(), i64>::new(
1184 "selector_children",
1185 "children.alias",
1186 "source\" OR attacker_effect()",
1187 );
1188 let joined_field =
1189 SelectField::<(), i64>::new("selector_parents", "parents\" --", "target.column");
1190
1191 let join = sql_join_on(&[child_source], parent_source, source_field, joined_field)
1192 .expect("should create an explicit join");
1193 assert_eq!(
1194 join.condition,
1195 "\"children.alias\".\"source\"\" OR attacker_effect()\" = \"parents\"\" --\".\"target.column\"",
1196 );
1197 }
1198
1199 #[test]
1200 fn test_duplicate_identical_joins_are_deduplicated_in_insertion_order() {
1201 let child_source = SqlSource::new(
1202 "selector_children",
1203 "selector_children",
1204 "tests::children",
1205 true,
1206 child_source_clause,
1207 );
1208 let later_source = SqlSource::new(
1209 "later_parents",
1210 "z_parents",
1211 "tests::later_parents",
1212 true,
1213 parent_source_clause,
1214 );
1215 let earlier_source = SqlSource::new(
1216 "earlier_parents",
1217 "a_parents",
1218 "tests::earlier_parents",
1219 true,
1220 parent_source_clause,
1221 );
1222 let source_field =
1223 SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id");
1224 let later_field = SelectField::<(), i64>::new("later_parents", "z_parents", "id");
1225 let earlier_field = SelectField::<(), i64>::new("earlier_parents", "a_parents", "id");
1226 let later_join = sql_join_on(&[child_source], later_source, source_field, later_field)
1227 .expect("should create the later join");
1228 let earlier_join =
1229 sql_join_on(&[child_source], earlier_source, source_field, earlier_field)
1230 .expect("should create the earlier join");
1231 let mut joins = SqlJoins::default();
1232
1233 joins
1234 .insert(later_join.clone())
1235 .expect("should insert the later join");
1236 joins
1237 .insert(earlier_join)
1238 .expect("should insert the earlier join");
1239 joins
1240 .insert(later_join)
1241 .expect("should deduplicate the later join");
1242
1243 assert_eq!(joins.len(), 2);
1244 assert_eq!(
1245 joins
1246 .iter()
1247 .map(|join| join.source().alias())
1248 .collect::<Vec<_>>(),
1249 vec!["z_parents", "a_parents"],
1250 );
1251 }
1252
1253 #[test]
1254 fn test_duplicate_alias_with_different_join_is_rejected() {
1255 let child_source = SqlSource::new(
1256 "selector_children",
1257 "selector_children",
1258 "tests::children",
1259 true,
1260 child_source_clause,
1261 );
1262 let parent_source = SqlSource::new(
1263 "selector_parents",
1264 "selector_parents",
1265 "tests::parents",
1266 true,
1267 parent_source_clause,
1268 );
1269 let joined_field =
1270 SelectField::<(), i64>::new("selector_parents", "selector_parents", "id");
1271 let first_join = sql_join_on(
1272 &[child_source],
1273 parent_source,
1274 SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id"),
1275 joined_field,
1276 )
1277 .expect("should create the first join");
1278 let second_join = sql_join_on(
1279 &[child_source],
1280 parent_source,
1281 SelectField::<(), i64>::new(
1282 "selector_children",
1283 "selector_children",
1284 "other_parent_id",
1285 ),
1286 joined_field,
1287 )
1288 .expect("should create the second join");
1289 let mut joins = SqlJoins::default();
1290
1291 joins
1292 .insert(first_join)
1293 .expect("should insert the first join");
1294 let error = joins
1295 .insert(second_join)
1296 .expect_err("should reject a conflicting join");
1297
1298 assert_eq!(
1299 error,
1300 SelectorBuildError::InvalidSelector(
1301 "cannot use SQL source alias `selector_parents` for different joins".to_string(),
1302 )
1303 );
1304 }
1305
1306 #[test]
1307 fn test_duplicate_alias_with_different_source_is_rejected() {
1308 let child_source = SqlSource::new(
1309 "selector_children",
1310 "selector_children",
1311 "tests::children",
1312 true,
1313 child_source_clause,
1314 );
1315 let first_source = SqlSource::new(
1316 "selector_parents",
1317 "shared_parents",
1318 "tests::parents",
1319 true,
1320 parent_source_clause,
1321 );
1322 let second_source = SqlSource::new(
1323 "alternate_parents",
1324 "shared_parents",
1325 "tests::alternate_parents",
1326 true,
1327 parent_source_clause,
1328 );
1329 let source_field =
1330 SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id");
1331 let first_join = sql_join_on(
1332 &[child_source],
1333 first_source,
1334 source_field,
1335 SelectField::<(), i64>::new("selector_parents", "shared_parents", "id"),
1336 )
1337 .expect("should create the first join");
1338 let second_join = sql_join_on(
1339 &[child_source],
1340 second_source,
1341 source_field,
1342 SelectField::<(), i64>::new("alternate_parents", "shared_parents", "id"),
1343 )
1344 .expect("should create the second join");
1345 let mut joins = SqlJoins::default();
1346
1347 joins
1348 .insert(first_join)
1349 .expect("should insert the first join");
1350 let error = joins
1351 .insert(second_join)
1352 .expect_err("should reject a conflicting source");
1353
1354 assert_eq!(
1355 error,
1356 SelectorBuildError::InvalidSelector(
1357 "cannot use SQL source alias `shared_parents` for different joins".to_string(),
1358 )
1359 );
1360 }
1361
1362 #[test]
1363 fn test_structured_sql_helpers_quote_every_identifier() {
1364 assert_eq!(
1365 qualify_sql_column("source.alias", "target.column"),
1366 "\"source.alias\".\"target.column\"",
1367 );
1368 assert_eq!(select_all_sql("source\"alias"), "\"source\"\"alias\".*");
1369 assert_eq!(
1370 default_sql_source("table name", Some("history.table"), "select", None),
1371 "\"table name\" AS \"select\"",
1372 );
1373 assert_eq!(
1374 default_sql_source("table name", Some("history.table"), "select", Some("main"),),
1375 "\"dolt_at_history.table\"(:history_ref) AS \"select\"",
1376 );
1377 }
1378}