use super::{helpers, PlaceholderPositions, RowAccess};
use crate::idents::{ident_key, object_name_identity, unwrap_expr};
use sqlparser::ast::{
ConflictTarget, Expr, GroupByExpr, Insert, LimitClause, OnConflict, OnConflictAction, OnInsert,
Query, SelectItem, SetExpr, Statement, TableFactor, TableObject, Value,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LookupStep {
pub insert: bool,
pub row: RowAccess,
}
pub(crate) fn project(
statements: &[Statement],
positions: PlaceholderPositions<'_>,
enabled: bool,
) -> Option<LookupStep> {
if !enabled {
return None;
}
match statements {
[Statement::Insert(insert)] => insertion(insert, positions),
[Statement::Query(query)] => read(query, positions),
_ => None,
}
}
fn insertion(insert: &Insert, positions: PlaceholderPositions<'_>) -> Option<LookupStep> {
let Some(OnInsert::OnConflict(OnConflict {
conflict_target:
Some(ConflictTarget::Columns {
columns,
predicate: None,
}),
action: OnConflictAction::DoNothing,
})) = &insert.on
else {
return None;
};
let [column] = columns.as_slice() else {
return None;
};
let TableObject::TableName(relation) = &insert.table else {
return None;
};
if helpers::generated_name(relation, positions)
|| helpers::generated(column, positions)
|| insert.overriding.is_some()
|| !returns_id(insert.returning.as_deref()?, None)
{
return None;
}
let column = ident_key(column);
let value_index = insert.columns.iter().position(|entry| {
matches!(entry.0.as_slice(), [part] if part.as_ident()
.is_some_and(|ident| ident_key(ident) == column))
})?;
let query = insert.source.as_deref()?;
if query.limit_clause.is_some() || query.fetch.is_some() {
return None;
}
let SetExpr::Values(values) = query.body.as_ref() else {
return None;
};
let [values] = values.rows.as_slice() else {
return None;
};
let value = unwrap_expr(values.get(value_index)?);
if matches!(value, Expr::Cast { .. })
|| matches!(value, Expr::Value(value) if matches!(value.value, Value::Null))
{
return None;
}
let (key, recovered_key) = helpers::bound(value, positions)?;
Some(LookupStep {
insert: true,
row: RowAccess {
relation: Some(object_name_identity(relation)),
key: key.map(|key| (column.clone(), key)),
recovered_key: recovered_key.map(|key| (column, key)),
key_identity_unproven: false,
has_predicate: false,
only: false,
},
})
}
fn read(query: &Query, positions: PlaceholderPositions<'_>) -> Option<LookupStep> {
if query.with.is_some()
|| !singleton_limit(query.limit_clause.as_ref())
|| query.fetch.is_some()
|| !query.locks.is_empty()
{
return None;
}
let SetExpr::Select(select) = query.body.as_ref() else {
return None;
};
let [table] = select.from.as_slice() else {
return None;
};
if !table.joins.is_empty()
|| matches!(
&table.relation,
TableFactor::Table {
sample: Some(_),
..
}
)
|| select.selection.is_none()
|| select.into.is_some()
|| select.having.is_some()
|| !matches!(&select.group_by, GroupByExpr::Expressions(items, modifiers) if items.is_empty() && modifiers.is_empty())
|| !returns_id(&select.projection, Some(&table.relation))
{
return None;
}
let row = helpers::lookup_access(&table.relation, select.selection.as_ref(), positions);
(row.relation.is_some()
&& !row.key_identity_unproven
&& !row.only
&& (row.key.is_some() || row.recovered_key.is_some()))
.then_some(LookupStep { insert: false, row })
}
fn singleton_limit(clause: Option<&LimitClause>) -> bool {
match clause {
None => true,
Some(LimitClause::LimitOffset {
limit: Some(Expr::Value(limit)),
offset: None,
limit_by,
}) => {
limit_by.is_empty()
&& matches!(&limit.value, Value::Number(count, false) if count == "1")
}
Some(_) => false,
}
}
fn returns_id(items: &[SelectItem], relation: Option<&TableFactor>) -> bool {
let [SelectItem::UnnamedExpr(expr) | SelectItem::ExprWithAlias { expr, .. }] = items else {
return false;
};
match unwrap_expr(expr) {
Expr::Identifier(ident) => ident_key(ident) == "id",
Expr::CompoundIdentifier(parts) => {
let Some((column, prefix)) = parts.split_last() else {
return false;
};
let Some(TableFactor::Table { name, alias, .. }) = relation else {
return false;
};
if ident_key(column) != "id" {
return false;
}
let qualified = prefix.iter().map(ident_key).collect::<Vec<_>>();
match alias {
Some(alias) => alias.columns.is_empty() && qualified == [ident_key(&alias.name)],
None => {
let parts = name
.0
.iter()
.filter_map(|part| part.as_ident())
.map(ident_key)
.collect::<Vec<_>>();
prefix.len() <= parts.len() && parts.ends_with(&qualified)
}
}
}
_ => false,
}
}