use std::{fmt, panic::Location, sync::Arc};
use sea_orm::{DbBackend, DbErr, IntoMockRow, ProxyExecResult, ProxyRow, Statement};
use crate::{
classify::StmtKind,
matcher::{Arg, SqlMatcher, StatementExt, normalize, wrong_args},
parse::Parsed,
problem::{Declared, Mismatch, Rejection},
};
pub(crate) type RowsFn = Arc<dyn Fn(&Statement) -> Result<Vec<ProxyRow>, DbErr> + Send + Sync>;
pub(crate) type ExecFn = Arc<dyn Fn(&Statement) -> Result<ProxyExecResult, DbErr> + Send + Sync>;
#[derive(Clone)]
pub(crate) enum Rows {
Static(Vec<ProxyRow>),
Fn(RowsFn),
}
#[derive(Clone)]
pub(crate) enum Exec {
Static(ProxyExecResult),
Fn(ExecFn),
}
#[derive(Clone)]
pub(crate) struct Expectation {
pub spec: Arc<Spec>,
pub response: Arc<Response>,
pub min: usize,
pub max: usize,
pub calls: usize,
pub location: &'static Location<'static>,
}
#[derive(Clone)]
pub(crate) struct Spec {
pub kind: Option<StmtKind>,
pub table: Option<String>,
pub matchers: Vec<SqlMatcher>,
pub args: Option<Vec<Arg>>,
}
#[derive(Clone, Default)]
pub(crate) struct Response {
pub rows: Option<Rows>,
pub exec: Option<Exec>,
pub returning_pk: Option<ProxyRow>,
pub error: Option<DbErr>,
pub raw_rows: bool,
}
impl Expectation {
pub(crate) fn new(kind: Option<StmtKind>, location: &'static Location<'static>) -> Self {
Self {
spec: Arc::new(Spec {
kind,
table: None,
matchers: Vec::new(),
args: None,
}),
response: Arc::default(),
min: 1,
max: 1,
calls: 0,
location,
}
}
pub(crate) fn spec_mut(&mut self) -> &mut Spec {
Arc::make_mut(&mut self.spec)
}
pub(crate) fn response_mut(&mut self) -> &mut Response {
Arc::make_mut(&mut self.response)
}
pub(crate) fn exhausted(&self) -> bool {
self.calls >= self.max
}
pub(crate) fn has_result(&self) -> bool {
let response = &self.response;
self.spec.is_transaction() || response.rows.is_some() || response.exec.is_some() || response.error.is_some()
}
pub(crate) fn satisfied(&self) -> bool {
self.calls >= self.min
}
pub(crate) fn times(&mut self, n: usize) {
if self.min > 0 {
self.min = n;
}
self.max = n;
}
pub(crate) fn maybe(&mut self) {
self.min = 0;
}
pub(crate) fn close(&mut self) {
self.max = self.calls;
}
pub(crate) fn exec_mut(&mut self) -> &mut ProxyExecResult {
let response = self.response_mut();
if !matches!(response.exec, Some(Exec::Static(_))) {
response.exec = Some(Exec::Static(ProxyExecResult::default()));
}
match &mut response.exec {
Some(Exec::Static(exec)) => exec,
_ => unreachable!(),
}
}
pub(crate) fn declared(&self) -> Declared {
Declared {
label: self.label().to_string(),
location: self.location,
}
}
pub(crate) fn label(&self) -> Label<'_> {
Label(self)
}
pub(crate) fn rejection(&self, mismatch: Mismatch) -> Rejection {
Rejection {
expectation: self.declared(),
mismatch,
}
}
}
impl Spec {
pub(crate) fn is_transaction(&self) -> bool {
self.kind.is_some_and(StmtKind::is_transaction)
}
pub(crate) fn check(&self, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<(), Mismatch> {
if let Some(expected) = self.kind
&& expected != kind
{
return Err(Mismatch::Kind { expected, actual: kind });
}
if self.is_transaction() {
return Ok(());
}
if let Some(table) = &self.table {
let mismatch = |actual: Option<&str>| Mismatch::Table {
expected: table.clone(),
actual: actual.map(str::to_string),
backend: stmt.db_backend,
};
match parsed.and_then(|parsed| parsed.target.as_deref()) {
Some(target) if target != table => return Err(mismatch(Some(target))),
Some(_) => {}
None if !stmt.sql.contains("e(stmt.db_backend, table)) => return Err(mismatch(None)),
None => {}
}
}
if let Some(matcher) = self.matchers.iter().find(|matcher| !matcher.matches(stmt, parsed)) {
return Err(Mismatch::Sql {
matcher: Box::new(matcher.clone()),
hint: matcher.hint(stmt, parsed),
});
}
if let Some(args) = &self.args
&& let Some(wrong) = wrong_args(args, stmt.args())
{
return Err(Mismatch::Args {
expected: args.clone(),
actual: stmt.args().to_vec(),
wrong,
});
}
Ok(())
}
}
impl Response {
pub(crate) fn has_rows(&self) -> bool {
self.rows.is_some() || self.returning_pk.is_some() || self.error.is_some()
}
pub(crate) fn query(&self, table: Option<&str>, stmt: &Statement, parsed: Option<&Parsed>) -> Result<Vec<ProxyRow>, DbErr> {
if let Some(err) = &self.error {
return Err(err.clone());
}
let rows = match (&self.rows, &self.returning_pk) {
(Some(Rows::Static(rows)), _) => rows.clone(),
(Some(Rows::Fn(f)), _) => f(stmt)?,
(None, Some(pk)) => vec![pk.clone()],
(None, None) => Vec::new(),
};
Ok(match table {
Some(table) if !self.raw_rows => apply_aliases(rows, table, parsed),
_ => rows,
})
}
pub(crate) fn exec(&self, stmt: &Statement) -> Result<ProxyExecResult, DbErr> {
if let Some(err) = &self.error {
return Err(err.clone());
}
match (&self.exec, &self.rows) {
(Some(Exec::Static(exec)), _) => Ok(exec.clone()),
(Some(Exec::Fn(f)), _) => f(stmt),
(None, Some(Rows::Static(rows))) => Ok(ProxyExecResult::new(0, rows.len() as u64)),
(None, Some(Rows::Fn(f))) => Ok(ProxyExecResult::new(0, f(stmt)?.len() as u64)),
(None, None) => Ok(ProxyExecResult::default()),
}
}
}
pub(crate) struct Label<'a>(&'a Expectation);
impl fmt::Display for Label<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let Label(expectation) = self;
let spec = &expectation.spec;
match spec.kind {
None => write!(f, "any statement")?,
Some(kind) => write!(f, "{kind}")?,
}
if let Some(table) = &spec.table {
write!(f, " on `{table}`")?;
}
if !spec.is_transaction() {
write!(f, " with ")?;
if spec.matchers.is_empty() {
write!(f, "any SQL")?;
}
for (idx, matcher) in spec.matchers.iter().enumerate() {
if idx > 0 {
write!(f, " and ")?;
}
write!(f, "{matcher}")?;
}
}
if let Some(args) = &spec.args {
write!(f, " and args {args:?}")?;
}
match (expectation.min, expectation.max) {
(1, 1) => {}
(0, 1) => write!(f, " (optional)")?,
(0, max) => write!(f, " ({}/up to {max} calls)", expectation.calls)?,
(_, max) => write!(f, " ({}/{max} calls)", expectation.calls)?,
}
Ok(())
}
}
pub(crate) fn into_proxy_row(row: impl IntoMockRow) -> ProxyRow {
ProxyRow::new(row.into_mock_row().into_column_value_tuples().collect())
}
pub(crate) fn rows_with<R: IntoMockRow>(f: impl Fn(&Statement) -> Result<Vec<R>, DbErr> + Send + Sync + 'static) -> Rows {
Rows::Fn(Arc::new(move |stmt| Ok(f(stmt)?.into_iter().map(into_proxy_row).collect())))
}
fn apply_aliases(mut rows: Vec<ProxyRow>, table: &str, parsed: Option<&Parsed>) -> Vec<ProxyRow> {
let Some(parsed) = parsed else {
return rows;
};
let aliases = parsed
.aliases
.iter()
.filter(|(t, column, alias)| t == table && column != alias)
.map(|(_, column, alias)| (column, alias))
.collect::<Vec<_>>();
if aliases.is_empty() {
return rows;
}
let kept = |column: &str| parsed.wildcard || parsed.plain.iter().any(|(t, c)| t == table && c == column) || aliases.iter().any(|(_, alias)| *alias == column);
for row in &mut rows {
let original = row.values.clone();
for (column, alias) in &aliases {
if let Some(value) = original.get(*column) {
row.values.insert(alias.to_string(), value.clone());
}
}
for (column, _) in &aliases {
if !kept(column) {
row.values.remove(*column);
}
}
}
rows
}
pub(crate) fn describe(stmt: &Statement) -> String {
format!("`{}` with {:?}", normalize(&stmt.sql, stmt.db_backend), stmt.args())
}
pub(crate) fn quote(backend: DbBackend, ident: &str) -> String {
match backend {
DbBackend::MySql => format!("`{ident}`"),
_ => format!("\"{ident}\""),
}
}