use core::marker::PhantomData;
use std::rc::Rc;
use indexmap::IndexMap;
use itertools::Itertools;
pub use rusqlite::{Connection, Result as SqlResult, Row};
use rusqlite::{
Params, ToSql, params_from_iter,
types::{FromSql, ToSqlOutput, Value},
};
use crate::{
ModelSelectError,
db::{max_rows_per_batch, sqlite_parameter_limit},
};
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Direction {
#[default]
Asc,
Desc,
CaseInsensitiveAsc,
CaseInsensitiveDesc,
}
impl Direction {
const fn as_sql(self) -> &'static str {
match self {
Self::Asc => "ASC",
Self::Desc => "DESC",
Self::CaseInsensitiveAsc => "ASC",
Self::CaseInsensitiveDesc => "DESC",
}
}
const fn uses_case_insensitive_collation(self) -> bool {
match self {
Self::Asc | Self::Desc => false,
Self::CaseInsensitiveAsc | Self::CaseInsensitiveDesc => true,
}
}
}
#[doc(hidden)]
pub enum HistoryRefValue {}
#[doc(hidden)]
pub enum OptionalHistoryRefValue {}
#[doc(hidden)]
pub trait IntoHistoryRef<Kind> {
fn into_history_ref(self) -> Option<String>;
}
impl<T> IntoHistoryRef<HistoryRefValue> for T
where
T: Into<String>,
{
fn into_history_ref(self) -> Option<String> {
Some(self.into())
}
}
impl<T> IntoHistoryRef<OptionalHistoryRefValue> for Option<T>
where
T: Into<String>,
{
fn into_history_ref(self) -> Option<String> {
self.map(Into::into)
}
}
#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum SelectorBuildError {
InvalidSelector(String),
HistoryNotSupported { table_name: &'static str },
}
impl From<SelectorBuildError> for ModelSelectError {
fn from(error: SelectorBuildError) -> Self {
match error {
SelectorBuildError::InvalidSelector(message) => Self::InvalidSelector(message),
SelectorBuildError::HistoryNotSupported { table_name } => Self::HistoryNotSupported {
table_name: table_name.to_string(),
},
}
}
}
#[doc(hidden)]
pub fn sql_value(value: &impl ToSql) -> Result<Value, SelectorBuildError> {
let value = value.to_sql().map_err(|error| {
SelectorBuildError::InvalidSelector(format!(
"failed to convert selector value to SQL: {error}"
))
})?;
match value {
ToSqlOutput::Borrowed(value) => Value::try_from(value).map_err(|error| {
SelectorBuildError::InvalidSelector(format!(
"failed to copy selector SQL value: {error}"
))
}),
ToSqlOutput::Owned(value) => Ok(value),
_ => Err(SelectorBuildError::InvalidSelector(
"selector values must map to SQLite scalar values".to_string(),
)),
}
}
#[doc(hidden)]
#[derive(Clone, Debug, PartialEq)]
pub struct SqlFilter {
pub clause: String,
pub params: Vec<Value>,
ordered_in: Option<OrderedSqlIn>,
}
impl SqlFilter {
pub fn new(clause: impl Into<String>, params: Vec<Value>) -> Self {
Self {
clause: clause.into(),
params,
ordered_in: None,
}
}
}
#[derive(Clone, Debug, PartialEq)]
struct OrderedSqlIn {
columns: Vec<String>,
rows: Vec<Vec<Value>>,
}
#[doc(hidden)]
pub fn sql_in_filter(column: impl Into<String>, params: Vec<Value>) -> SqlFilter {
if params.is_empty() {
SqlFilter::new("0 = 1", params)
} else {
SqlFilter {
clause: String::new(),
params: Vec::new(),
ordered_in: Some(OrderedSqlIn {
columns: vec![column.into()],
rows: params.into_iter().map(|value| vec![value]).collect(),
}),
}
}
}
#[doc(hidden)]
pub fn sql_composite_in_filter(
columns: Vec<String>,
rows: Vec<Vec<Value>>,
) -> Result<SqlFilter, SelectorBuildError> {
if columns.is_empty() {
return Err(SelectorBuildError::InvalidSelector(
"a composite primary key must contain at least one column".to_string(),
));
}
if rows.iter().any(|row| row.len() != columns.len()) {
return Err(SelectorBuildError::InvalidSelector(
"each composite primary-key value must match the number of key columns".to_string(),
));
}
if rows.is_empty() {
Ok(SqlFilter::new("0 = 1", Vec::new()))
} else {
Ok(SqlFilter {
clause: String::new(),
params: Vec::new(),
ordered_in: Some(OrderedSqlIn { columns, rows }),
})
}
}
#[derive(Clone, Debug)]
enum SqlParameter {
Scalar(Value),
Array(Rc<Vec<Value>>),
}
impl ToSql for SqlParameter {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
match self {
Self::Scalar(value) => value.to_sql(),
Self::Array(values) => values.to_sql(),
}
}
}
#[doc(hidden)]
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct SqlOrder {
column: String,
direction: Direction,
relevance_search: Option<String>,
}
impl SqlOrder {
pub fn new(column: impl Into<String>, direction: Direction) -> Self {
Self {
column: column.into(),
direction,
relevance_search: None,
}
}
pub fn relevance(column: impl Into<String>, search: String) -> Self {
Self {
column: column.into(),
direction: Direction::Asc,
relevance_search: Some(search),
}
}
}
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct SqlSource {
table_name: &'static str,
alias: &'static str,
source_id: &'static str,
supports_history: bool,
source_clause: fn(Option<&str>) -> String,
}
impl SqlSource {
pub const fn new(
table_name: &'static str,
alias: &'static str,
source_id: &'static str,
supports_history: bool,
source_clause: fn(Option<&str>) -> String,
) -> Self {
Self {
table_name,
alias,
source_id,
supports_history,
source_clause,
}
}
fn clause(self, history_ref: Option<&str>) -> String {
(self.source_clause)(history_ref)
}
pub fn table_name(self) -> &'static str {
self.table_name
}
pub fn alias(self) -> &'static str {
self.alias
}
fn supports_history(self) -> bool {
self.supports_history
}
fn has_same_definition(self, other: Self) -> bool {
self.table_name == other.table_name
&& self.alias == other.alias
&& self.source_id == other.source_id
&& self.supports_history == other.supports_history
}
}
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct SqlJoin {
source: SqlSource,
condition: String,
}
impl SqlJoin {
fn new(source: SqlSource, condition: String) -> Self {
Self { source, condition }
}
fn append_sql(&self, query: &mut String, history_ref: Option<&str>) {
query.push_str(" JOIN ");
query.push_str(&self.source.clause(history_ref));
query.push_str(" ON ");
query.push_str(&self.condition);
}
pub fn source(&self) -> SqlSource {
self.source
}
}
#[doc(hidden)]
#[derive(Clone, Debug, Default)]
pub struct SqlJoins {
joins: IndexMap<&'static str, SqlJoin>,
}
impl SqlJoins {
pub fn len(&self) -> usize {
self.joins.len()
}
pub fn is_empty(&self) -> bool {
self.joins.is_empty()
}
pub fn iter(&self) -> impl Iterator<Item = &SqlJoin> {
self.joins.values()
}
pub fn insert(&mut self, join: SqlJoin) -> Result<(), SelectorBuildError> {
let alias = join.source.alias();
if let Some(existing) = self.joins.get(alias) {
if !existing.source.has_same_definition(join.source)
|| existing.condition != join.condition
{
return Err(SelectorBuildError::InvalidSelector(format!(
"cannot use SQL source alias `{alias}` for different joins"
)));
}
} else {
self.joins.insert(alias, join);
}
Ok(())
}
pub fn extend_from(&mut self, joins: &Self) -> Result<(), SelectorBuildError> {
for join in joins.iter() {
self.insert(join.clone())?;
}
Ok(())
}
}
#[doc(hidden)]
pub trait SelectQuery {
fn connection(&self) -> &Connection;
fn source(&self) -> SqlSource;
fn error(&self) -> Option<&SelectorBuildError>;
fn history_ref(&self) -> Option<&str>;
fn joins(&self) -> &SqlJoins;
fn filters(&self) -> &[SqlFilter];
fn order_by(&self) -> &[SqlOrder];
fn default_order_by(&self) -> &[SqlOrder];
fn limit(&self) -> Option<u32>;
fn offset(&self) -> u32;
fn select_clause(&self) -> String {
select_all_sql(self.source().alias())
}
}
#[doc(hidden)]
#[derive(Debug, Eq, PartialEq)]
pub struct SelectField<M, T, JoinType = T> {
table_name: &'static str,
alias: &'static str,
column: &'static str,
field: PhantomData<fn() -> (M, T)>,
join_type: PhantomData<fn() -> JoinType>,
}
impl<M, T, JoinType> SelectField<M, T, JoinType> {
pub const fn new(table_name: &'static str, alias: &'static str, column: &'static str) -> Self {
Self {
table_name,
alias,
column,
field: PhantomData,
join_type: PhantomData,
}
}
pub const fn column(self) -> &'static str {
self.column
}
pub const fn table_name(self) -> &'static str {
self.table_name
}
pub const fn alias(self) -> &'static str {
self.alias
}
}
impl<M, T, JoinType> Clone for SelectField<M, T, JoinType> {
fn clone(&self) -> Self {
*self
}
}
impl<M, T, JoinType> Copy for SelectField<M, T, JoinType> {}
#[doc(hidden)]
pub trait ProjectionField {
type Output;
fn table_name(&self) -> &'static str;
fn alias(&self) -> &'static str;
fn column(&self) -> &'static str;
fn process_row(&self, row: &Row, index: usize) -> rusqlite::Result<Self::Output>;
}
impl<M, T, JoinType> ProjectionField for SelectField<M, T, JoinType>
where
T: FromSql,
{
type Output = T;
fn table_name(&self) -> &'static str {
self.table_name
}
fn alias(&self) -> &'static str {
self.alias
}
fn column(&self) -> &'static str {
self.column
}
fn process_row(&self, row: &Row, index: usize) -> rusqlite::Result<Self::Output> {
row.get(index)
}
}
#[doc(hidden)]
pub trait SelectableModel: Sized {
fn table_name() -> &'static str;
fn alias() -> &'static str;
fn columns() -> &'static [&'static str];
fn process_row(row: &Row, offset: usize) -> SqlResult<Self>;
}
#[doc(hidden)]
pub trait ModelSelectRow: Sized {
fn process_row(row: &Row) -> SqlResult<Self>;
}
#[doc(hidden)]
pub trait ModelSelectSource: Sized + 'static {
type Selector<'conn>: SelectQuery;
fn selector(conn: &Connection) -> Self::Selector<'_>;
}
#[doc(hidden)]
pub trait SelectProjection {
type Output;
fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)>;
fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output>;
}
impl<M, T, JoinType> SelectProjection for SelectField<M, T, JoinType>
where
T: FromSql,
{
type Output = T;
fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)> {
vec![(self.table_name, self.alias, self.column)]
}
fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output> {
row.get(0)
}
}
macro_rules! impl_select_projection_for_tuple {
($($field:ident:$index:tt),+) => {
impl<$($field),+> SelectProjection for ($($field,)+)
where
$($field: ProjectionField,)+
{
type Output = ($(<$field as ProjectionField>::Output,)+);
fn fields(&self) -> Vec<(&'static str, &'static str, &'static str)> {
vec![$(
(
self.$index.table_name(),
self.$index.alias(),
self.$index.column(),
)
),+]
}
fn process_row(&self, row: &Row) -> rusqlite::Result<Self::Output> {
Ok(($(self.$index.process_row(row, $index)?,)+))
}
}
};
}
impl_select_projection_for_tuple!(A:0);
impl_select_projection_for_tuple!(A:0, B:1);
impl_select_projection_for_tuple!(A:0, B:1, C:2);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8);
impl_select_projection_for_tuple!(A:0, B:1, C:2, D:3, E:4, F:5, G:6, H:7, I:8, J:9);
impl_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);
impl_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);
impl_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);
impl_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);
impl_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);
impl_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);
#[doc(hidden)]
pub trait ModelProjection {
type Output;
fn fields() -> Vec<(&'static str, &'static str, &'static str)>;
fn process_row(row: &Row) -> SqlResult<Self::Output>;
}
macro_rules! impl_model_projection_for_tuple {
($($model:ident),+) => {
impl<$($model),+> ModelProjection for ($($model,)+)
where
$($model: SelectableModel,)+
{
type Output = ($($model,)+);
fn fields() -> Vec<(&'static str, &'static str, &'static str)> {
let mut fields = Vec::new();
$(
for column in <$model as SelectableModel>::columns() {
fields.push((
<$model as SelectableModel>::table_name(),
<$model as SelectableModel>::alias(),
*column,
));
}
)+
fields
}
fn process_row(row: &Row) -> SqlResult<Self::Output> {
let mut offset = 0;
let output = ($({
let model = <$model as SelectableModel>::process_row(row, offset)?;
offset += <$model as SelectableModel>::columns().len();
model
},)+);
let _ = offset;
Ok(output)
}
}
};
}
impl_model_projection_for_tuple!(A);
impl_model_projection_for_tuple!(A, B);
impl_model_projection_for_tuple!(A, B, C);
impl_model_projection_for_tuple!(A, B, C, D);
impl_model_projection_for_tuple!(A, B, C, D, E);
impl_model_projection_for_tuple!(A, B, C, D, E, F);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O);
impl_model_projection_for_tuple!(A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P);
#[doc(hidden)]
pub struct SelectedFields<S, P> {
select: S,
projection: P,
}
impl<S, P> SelectedFields<S, P> {
pub fn new(select: S, projection: P) -> Self {
Self { select, projection }
}
}
impl<S, P> SelectedFields<S, P>
where
S: SelectQuery,
P: SelectProjection,
{
pub fn load(self) -> Result<Vec<P::Output>, ModelSelectError> {
let Self { select, projection } = self;
load_projection(select, projection.fields(), |row| {
projection.process_row(row)
})
}
}
#[doc(hidden)]
pub struct SelectedModels<S, P> {
select: S,
projection: PhantomData<fn() -> P>,
}
impl<S, P> SelectedModels<S, P> {
pub fn new(select: S) -> Self {
Self {
select,
projection: PhantomData,
}
}
}
impl<S, P> SelectedModels<S, P>
where
S: SelectQuery,
P: ModelProjection,
{
pub fn load(self) -> Result<Vec<P::Output>, ModelSelectError> {
load_projection(self.select, P::fields(), P::process_row)
}
}
fn load_projection<S, T>(
select: S,
fields: Vec<(&'static str, &'static str, &'static str)>,
process_row: impl FnMut(&Row) -> SqlResult<T>,
) -> Result<Vec<T>, ModelSelectError>
where
S: SelectQuery,
{
if let Some(error) = select.error() {
return Err(error.clone().into());
}
validate_projection_sources(&select, &fields)?;
let select_clause = fields
.iter()
.map(|(_, alias, column)| qualify_sql_column(alias, column))
.join(", ");
let (query, params) = render_query(&select, select_clause, None)?;
query_rows(select.connection(), &query, params, process_row)
}
fn validate_projection_sources<S>(
select: &S,
fields: &[(&'static str, &'static str, &'static str)],
) -> Result<(), ModelSelectError>
where
S: SelectQuery,
{
for (table_name, alias, _) in fields {
let source = select.source();
let source_is_available = source.table_name() == *table_name && source.alias() == *alias
|| select.joins().iter().any(|join| {
let source = join.source();
source.table_name() == *table_name && source.alias() == *alias
});
if !source_is_available {
return Err(ModelSelectError::ProjectionSourceNotSelected {
table_name: (*table_name).to_string(),
alias: (*alias).to_string(),
});
}
}
Ok(())
}
#[doc(hidden)]
pub fn load<M, S>(conn: &Connection, select: &S) -> Result<Vec<M>, ModelSelectError>
where
M: ModelSelectRow,
S: SelectQuery,
{
let (query, params) = render_query(select, select.select_clause(), None)?;
query_rows(conn, &query, params, M::process_row)
}
#[doc(hidden)]
pub fn get<M, S>(conn: &Connection, select: &S) -> Result<Option<M>, ModelSelectError>
where
M: ModelSelectRow,
S: SelectQuery,
{
let (query, params) = render_query(select, select.select_clause(), Some(2))?;
let mut rows = query_rows(conn, &query, params, M::process_row)?;
match rows.len() {
0 => Ok(None),
1 => Ok(rows.pop()),
_ => Err(ModelSelectError::MultipleResults),
}
}
fn render_query<S>(
select: &S,
select_clause: String,
maximum_rows: Option<u32>,
) -> Result<(String, Vec<SqlParameter>), ModelSelectError>
where
S: SelectQuery,
{
if let Some(error) = select.error() {
return Err(error.clone().into());
}
if select.history_ref().is_some() {
for source in
core::iter::once(select.source()).chain(select.joins().iter().map(|join| join.source()))
{
if !source.supports_history() {
return Err(SelectorBuildError::HistoryNotSupported {
table_name: source.table_name(),
}
.into());
}
}
}
let mut query = format!(
"SELECT {select_clause} FROM {}",
select.source().clause(select.history_ref()),
);
for join in select.joins().iter() {
join.append_sql(&mut query, select.history_ref());
}
let mut params = select
.history_ref()
.map(|history_ref| vec![SqlParameter::Scalar(Value::from(history_ref.to_string()))])
.unwrap_or_default();
let filters = select.filters();
for (index, ordered_in) in filters
.iter()
.filter_map(|filter| filter.ordered_in.as_ref())
.enumerate()
{
append_ordered_in_join(&mut query, &mut params, ordered_in, index);
}
if filters.iter().any(|filter| !filter.clause.is_empty()) {
query.push_str(" WHERE ");
for (index, filter) in filters
.iter()
.filter(|filter| !filter.clause.is_empty())
.enumerate()
{
if index > 0 {
query.push_str(" AND ");
}
query.push_str(&filter.clause);
params.extend(filter.params.iter().cloned().map(SqlParameter::Scalar));
}
}
let order_by = if select.order_by().is_empty() {
select.default_order_by()
} else {
select.order_by()
};
let ordered_in_count = filters
.iter()
.filter(|filter| filter.ordered_in.is_some())
.count();
if ordered_in_count > 0 || !order_by.is_empty() {
query.push_str(" ORDER BY ");
for index in 0..ordered_in_count {
if index > 0 {
query.push_str(", ");
}
query.push_str(&qualify_sql_column(
&format!("__model_select_in_{index}"),
"position",
));
query.push_str(" ASC");
}
for (index, order) in order_by.iter().enumerate() {
if ordered_in_count > 0 || index > 0 {
query.push_str(", ");
}
if let Some(search) = &order.relevance_search {
let column = &order.column;
query.push_str(&format!(
"CASE WHEN {column} = ? THEN 0 WHEN lower({column}) = lower(?) THEN 1 \
WHEN {column} LIKE ? || '%' THEN 2 \
WHEN {column} LIKE '%' || ? || '%' THEN 3 ELSE 4 END",
));
params.extend((0..4).map(|_| SqlParameter::Scalar(Value::from(search.clone()))));
} else {
query.push_str(&order.column);
}
if order.direction.uses_case_insensitive_collation() {
query.push_str(" COLLATE NOCASE");
}
query.push(' ');
query.push_str(order.direction.as_sql());
}
}
let effective_limit = maximum_rows.or(select.limit());
if let Some(limit) = effective_limit {
query.push_str(" LIMIT ?");
params.push(SqlParameter::Scalar(Value::from(i64::from(limit))));
}
let offset = select.offset();
if offset > 0 {
if effective_limit.is_none() {
query.push_str(" LIMIT -1");
}
query.push_str(" OFFSET ?");
params.push(SqlParameter::Scalar(Value::from(i64::from(offset))));
}
let parameter_limit = sqlite_parameter_limit(select.connection());
if params.len() > parameter_limit {
return Err(SelectorBuildError::InvalidSelector(format!(
"selector requires {} SQL parameters, but the connection limit is {parameter_limit}",
params.len(),
))
.into());
}
Ok((query, params))
}
#[doc(hidden)]
pub fn delete_by_ids(
conn: &Connection,
table_name: &str,
primary_keys: &[&str],
rows: Vec<Vec<Value>>,
) -> Result<usize, ModelSelectError> {
if primary_keys.is_empty() {
return Err(SelectorBuildError::InvalidSelector(
"a primary key must contain at least one column".to_string(),
)
.into());
}
if rows.iter().any(|row| row.len() != primary_keys.len()) {
return Err(SelectorBuildError::InvalidSelector(
"each primary-key value must match the number of key columns".to_string(),
)
.into());
}
if rows.is_empty() {
return Ok(0);
}
let quoted_table = quote_sql_identifier(table_name);
let aliases = (0..primary_keys.len())
.map(|index| format!("__model_select_delete_key_{index}"))
.collect::<Vec<_>>();
let mut query = format!("DELETE FROM {quoted_table} WHERE ");
if primary_keys.len() > 1 {
query.push('(');
}
for (index, primary_key) in primary_keys.iter().enumerate() {
if index > 0 {
query.push_str(", ");
}
query.push_str(&qualify_sql_column(table_name, primary_key));
}
if primary_keys.len() > 1 {
query.push(')');
}
query.push_str(" IN (SELECT ");
for (index, alias) in aliases.iter().enumerate() {
if index > 0 {
query.push_str(", ");
}
query.push_str(&qualify_sql_column(alias, "value"));
}
query.push_str(" FROM ");
for (index, alias) in aliases.iter().enumerate() {
if index == 0 {
query.push_str(&format!(
"rarray(?{}) AS {}",
index + 1,
quote_sql_identifier(alias),
));
} else {
query.push_str(&format!(
" JOIN rarray(?{}) AS {} ON {} = {}",
index + 1,
quote_sql_identifier(alias),
qualify_sql_column(alias, "rowid"),
qualify_sql_column(&aliases[0], "rowid"),
));
}
}
query.push(')');
let batch_size = max_rows_per_batch(conn, primary_keys.len());
let mut deleted = 0;
let mut statement = conn.prepare(&query)?;
for chunk in rows.chunks(batch_size) {
let params = (0..primary_keys.len()).map(|column_index| {
SqlParameter::Array(Rc::new(
chunk.iter().map(|row| row[column_index].clone()).collect(),
))
});
deleted += statement.execute(params_from_iter(params))?;
}
Ok(deleted)
}
fn append_ordered_in_join(
query: &mut String,
params: &mut Vec<SqlParameter>,
ordered_in: &OrderedSqlIn,
index: usize,
) {
let column_count = ordered_in.columns.len();
let values_alias = quote_sql_identifier(&format!("__model_select_in_values_{index}"));
let order_alias = format!("__model_select_in_{index}");
let value_columns = (0..column_count)
.map(|column_index| format!("value_{column_index}"))
.collect::<Vec<_>>();
query.push_str(" JOIN (SELECT ");
for (column_index, value_column) in value_columns.iter().enumerate() {
if column_index > 0 {
query.push_str(", ");
}
query.push_str("e_sql_identifier(value_column));
}
query.push_str(", MIN(\"position\") AS \"position\" FROM (");
let array_aliases = (0..column_count)
.map(|column_index| format!("__model_select_in_array_{index}_{column_index}"))
.collect::<Vec<_>>();
query.push_str("SELECT ");
for (column_index, (array_alias, value_column)) in
array_aliases.iter().zip(&value_columns).enumerate()
{
if column_index > 0 {
query.push_str(", ");
}
query.push_str(&qualify_sql_column(array_alias, "value"));
query.push_str(" AS ");
query.push_str("e_sql_identifier(value_column));
}
query.push_str(", ");
query.push_str(&qualify_sql_column(&array_aliases[0], "rowid"));
query.push_str(" AS \"position\" FROM ");
for (column_index, array_alias) in array_aliases.iter().enumerate() {
if column_index == 0 {
query.push_str("rarray(?) AS ");
query.push_str("e_sql_identifier(array_alias));
} else {
query.push_str(" JOIN rarray(?) AS ");
query.push_str("e_sql_identifier(array_alias));
query.push_str(" ON ");
query.push_str(&qualify_sql_column(array_alias, "rowid"));
query.push_str(" = ");
query.push_str(&qualify_sql_column(&array_aliases[0], "rowid"));
}
params.push(SqlParameter::Array(Rc::new(
ordered_in
.rows
.iter()
.map(|row| row[column_index].clone())
.collect(),
)));
}
query.push_str(") AS ");
query.push_str(&values_alias);
query.push_str(" GROUP BY ");
for (column_index, value_column) in value_columns.iter().enumerate() {
if column_index > 0 {
query.push_str(", ");
}
query.push_str("e_sql_identifier(value_column));
}
query.push_str(") AS ");
query.push_str("e_sql_identifier(&order_alias));
query.push_str(" ON ");
for (column_index, (column, value_column)) in
ordered_in.columns.iter().zip(&value_columns).enumerate()
{
if column_index > 0 {
query.push_str(" AND ");
}
query.push_str(column);
query.push_str(" = ");
query.push_str(&qualify_sql_column(&order_alias, value_column));
}
}
fn query_rows<T>(
conn: &Connection,
query: &str,
params: Vec<SqlParameter>,
mut process_row: impl FnMut(&Row) -> rusqlite::Result<T>,
) -> Result<Vec<T>, ModelSelectError> {
let mut statement = conn.prepare(query)?;
let rows = statement.query_map(params_from_iter(params), |row| process_row(row))?;
rows.collect::<Result<Vec<_>, _>>().map_err(Into::into)
}
#[doc(hidden)]
pub fn query_models<M, P>(conn: &Connection, query: &str, params: P) -> SqlResult<Vec<M>>
where
M: ModelSelectRow,
P: Params,
{
let mut statement = conn.prepare(query)?;
let rows = statement.query_map(params, M::process_row)?;
rows.collect()
}
#[doc(hidden)]
pub fn qualify_sql_column(alias: &str, column: &str) -> String {
format!(
"{}.{}",
quote_sql_identifier(alias),
quote_sql_identifier(column),
)
}
#[doc(hidden)]
pub fn select_all_sql(alias: &str) -> String {
format!("{}.*", quote_sql_identifier(alias))
}
#[doc(hidden)]
pub fn default_sql_source(
table_name: &str,
history_table_name: Option<&str>,
alias: &str,
history_ref: Option<&str>,
) -> String {
let source = sql_table_name_with_history_ref(table_name, history_table_name, history_ref);
format!("{source} AS {}", quote_sql_identifier(alias))
}
#[doc(hidden)]
pub fn sql_table_name_with_history_ref(
table_name: &str,
history_table_name: Option<&str>,
history_ref: Option<&str>,
) -> String {
if history_ref.is_some() {
let history_table_name = history_table_name.expect("should support history ref queries");
quote_sql_identifier(&format!("dolt_at_{history_table_name}")) + "(:history_ref)"
} else {
quote_sql_identifier(table_name)
}
}
#[doc(hidden)]
pub fn sql_join_on<SourceModel, SourceType, JoinedModel, JoinedType, JoinType>(
existing_sources: &[SqlSource],
joined_source: SqlSource,
source_field: SelectField<SourceModel, SourceType, JoinType>,
joined_field: SelectField<JoinedModel, JoinedType, JoinType>,
) -> Result<SqlJoin, SelectorBuildError> {
if existing_sources
.first()
.is_some_and(|source| source.alias() == joined_source.alias())
{
return Err(SelectorBuildError::InvalidSelector(format!(
"cannot join the base SQL source alias `{}`",
joined_source.alias(),
)));
}
if !existing_sources.iter().any(|source| {
source.table_name() == source_field.table_name() && source.alias() == source_field.alias()
}) {
return Err(SelectorBuildError::InvalidSelector(format!(
"cannot join from unselected SQL source `{} AS {}`",
source_field.table_name(),
source_field.alias(),
)));
}
if joined_source.table_name() != joined_field.table_name()
|| joined_source.alias() != joined_field.alias()
{
return Err(SelectorBuildError::InvalidSelector(format!(
"joined field source `{} AS {}` does not match selector source `{} AS {}`",
joined_field.table_name(),
joined_field.alias(),
joined_source.table_name(),
joined_source.alias(),
)));
}
let condition = format!(
"{} = {}",
qualify_sql_column(source_field.alias(), source_field.column()),
qualify_sql_column(joined_field.alias(), joined_field.column()),
);
Ok(SqlJoin::new(joined_source, condition))
}
fn quote_sql_identifier(identifier: &str) -> String {
format!("\"{}\"", identifier.replace('"', "\"\""))
}
#[cfg(test)]
mod tests {
use super::{
SelectField, SelectorBuildError, SqlJoins, SqlSource, default_sql_source,
qualify_sql_column, select_all_sql, sql_join_on,
};
fn child_source_clause(_history_ref: Option<&str>) -> String {
"selector_children".to_string()
}
fn parent_source_clause(_history_ref: Option<&str>) -> String {
"selector_parents".to_string()
}
#[test]
fn test_explicit_join_quotes_field_identifiers_without_database_metadata() {
let child_source = SqlSource::new(
"selector_children",
"children.alias",
"tests::children",
true,
child_source_clause,
);
let parent_source = SqlSource::new(
"selector_parents",
"parents\" --",
"tests::parents",
true,
parent_source_clause,
);
let source_field = SelectField::<(), i64>::new(
"selector_children",
"children.alias",
"source\" OR attacker_effect()",
);
let joined_field =
SelectField::<(), i64>::new("selector_parents", "parents\" --", "target.column");
let join = sql_join_on(&[child_source], parent_source, source_field, joined_field)
.expect("should create an explicit join");
assert_eq!(
join.condition,
"\"children.alias\".\"source\"\" OR attacker_effect()\" = \"parents\"\" --\".\"target.column\"",
);
}
#[test]
fn test_duplicate_identical_joins_are_deduplicated_in_insertion_order() {
let child_source = SqlSource::new(
"selector_children",
"selector_children",
"tests::children",
true,
child_source_clause,
);
let later_source = SqlSource::new(
"later_parents",
"z_parents",
"tests::later_parents",
true,
parent_source_clause,
);
let earlier_source = SqlSource::new(
"earlier_parents",
"a_parents",
"tests::earlier_parents",
true,
parent_source_clause,
);
let source_field =
SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id");
let later_field = SelectField::<(), i64>::new("later_parents", "z_parents", "id");
let earlier_field = SelectField::<(), i64>::new("earlier_parents", "a_parents", "id");
let later_join = sql_join_on(&[child_source], later_source, source_field, later_field)
.expect("should create the later join");
let earlier_join =
sql_join_on(&[child_source], earlier_source, source_field, earlier_field)
.expect("should create the earlier join");
let mut joins = SqlJoins::default();
joins
.insert(later_join.clone())
.expect("should insert the later join");
joins
.insert(earlier_join)
.expect("should insert the earlier join");
joins
.insert(later_join)
.expect("should deduplicate the later join");
assert_eq!(joins.len(), 2);
assert_eq!(
joins
.iter()
.map(|join| join.source().alias())
.collect::<Vec<_>>(),
vec!["z_parents", "a_parents"],
);
}
#[test]
fn test_duplicate_alias_with_different_join_is_rejected() {
let child_source = SqlSource::new(
"selector_children",
"selector_children",
"tests::children",
true,
child_source_clause,
);
let parent_source = SqlSource::new(
"selector_parents",
"selector_parents",
"tests::parents",
true,
parent_source_clause,
);
let joined_field =
SelectField::<(), i64>::new("selector_parents", "selector_parents", "id");
let first_join = sql_join_on(
&[child_source],
parent_source,
SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id"),
joined_field,
)
.expect("should create the first join");
let second_join = sql_join_on(
&[child_source],
parent_source,
SelectField::<(), i64>::new(
"selector_children",
"selector_children",
"other_parent_id",
),
joined_field,
)
.expect("should create the second join");
let mut joins = SqlJoins::default();
joins
.insert(first_join)
.expect("should insert the first join");
let error = joins
.insert(second_join)
.expect_err("should reject a conflicting join");
assert_eq!(
error,
SelectorBuildError::InvalidSelector(
"cannot use SQL source alias `selector_parents` for different joins".to_string(),
)
);
}
#[test]
fn test_duplicate_alias_with_different_source_is_rejected() {
let child_source = SqlSource::new(
"selector_children",
"selector_children",
"tests::children",
true,
child_source_clause,
);
let first_source = SqlSource::new(
"selector_parents",
"shared_parents",
"tests::parents",
true,
parent_source_clause,
);
let second_source = SqlSource::new(
"alternate_parents",
"shared_parents",
"tests::alternate_parents",
true,
parent_source_clause,
);
let source_field =
SelectField::<(), i64>::new("selector_children", "selector_children", "parent_id");
let first_join = sql_join_on(
&[child_source],
first_source,
source_field,
SelectField::<(), i64>::new("selector_parents", "shared_parents", "id"),
)
.expect("should create the first join");
let second_join = sql_join_on(
&[child_source],
second_source,
source_field,
SelectField::<(), i64>::new("alternate_parents", "shared_parents", "id"),
)
.expect("should create the second join");
let mut joins = SqlJoins::default();
joins
.insert(first_join)
.expect("should insert the first join");
let error = joins
.insert(second_join)
.expect_err("should reject a conflicting source");
assert_eq!(
error,
SelectorBuildError::InvalidSelector(
"cannot use SQL source alias `shared_parents` for different joins".to_string(),
)
);
}
#[test]
fn test_structured_sql_helpers_quote_every_identifier() {
assert_eq!(
qualify_sql_column("source.alias", "target.column"),
"\"source.alias\".\"target.column\"",
);
assert_eq!(select_all_sql("source\"alias"), "\"source\"\"alias\".*");
assert_eq!(
default_sql_source("table name", Some("history.table"), "select", None),
"\"table name\" AS \"select\"",
);
assert_eq!(
default_sql_source("table name", Some("history.table"), "select", Some("main"),),
"\"dolt_at_history.table\"(:history_ref) AS \"select\"",
);
}
}