use std::{fmt, sync::Arc};
use sea_orm::{DbBackend, DbErr, IntoMockRow, ProxyExecResult, ProxyRow, Statement};
use crate::{
classify::StmtKind,
matcher::{Arg, SqlMatcher, StatementExt, args_match, normalize},
parse::Parsed,
};
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),
}
pub(crate) struct Expectation {
pub spec: Arc<Spec>,
pub response: Arc<Response>,
pub min: usize,
pub max: usize,
pub calls: usize,
}
#[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 fn new(kind: Option<StmtKind>) -> Self {
Self {
spec: Arc::new(Spec {
kind,
table: None,
matchers: Vec::new(),
args: None,
}),
response: Arc::default(),
min: 1,
max: 1,
calls: 0,
}
}
pub fn spec_mut(&mut self) -> &mut Spec {
Arc::make_mut(&mut self.spec)
}
pub fn response_mut(&mut self) -> &mut Response {
Arc::make_mut(&mut self.response)
}
pub fn exhausted(&self) -> bool {
self.calls >= self.max
}
pub 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 fn satisfied(&self) -> bool {
self.calls >= self.min
}
pub fn close(&mut self) {
self.max = self.calls;
}
pub 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 fn label(&self) -> Label<'_> {
Label {
spec: &self.spec,
calls: self.calls,
min: self.min,
max: self.max,
}
}
}
impl Spec {
pub fn is_transaction(&self) -> bool {
self.kind.is_some_and(StmtKind::is_transaction)
}
pub fn check(&self, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<(), String> {
if let Some(expected) = self.kind
&& expected != kind
{
let article = if matches!(expected, StmtKind::Insert | StmtKind::Update) { "an" } else { "a" };
return Err(format!("expected {article} {expected} statement, got {kind}"));
}
if self.is_transaction() {
return Ok(());
}
if let Some(table) = &self.table {
let quoted = quote(stmt.db_backend, table);
match parsed.and_then(|parsed| parsed.target.as_deref()) {
Some(target) if target != table => {
return Err(format!("it targets {}, not {quoted}", quote(stmt.db_backend, target)));
}
Some(_) => {}
None if !stmt.sql.contains("ed) => return Err(format!("it does not reference table {quoted}")),
None => {}
}
}
if let Some(matcher) = self.matchers.iter().find(|matcher| !matcher.matches(stmt, parsed)) {
let hint = matcher.hint(stmt, parsed).unwrap_or_default();
return Err(format!("it does not match {matcher}{hint}"));
}
if let Some(args) = &self.args
&& !args_match(args, stmt)
{
return Err(format!("arguments {:?} do not match expected {args:?}", stmt.args()));
}
Ok(())
}
}
impl Response {
pub fn has_rows(&self) -> bool {
self.rows.is_some() || self.returning_pk.is_some() || self.error.is_some()
}
pub 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 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> {
pub spec: &'a Spec,
pub calls: usize,
pub min: usize,
pub max: usize,
}
impl fmt::Display for Label<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let spec = self.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 (self.min, self.max) {
(1, 1) => {}
(0, 1) => write!(f, " (optional)")?,
(0, max) => write!(f, " ({}/up to {max} calls)", self.calls)?,
(_, max) => write!(f, " ({}/{max} calls)", self.calls)?,
}
Ok(())
}
}
pub(crate) fn into_proxy_row(row: impl IntoMockRow) -> ProxyRow {
ProxyRow::new(row.into_mock_row().into_column_value_tuples().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())
}
fn quote(backend: DbBackend, ident: &str) -> String {
match backend {
DbBackend::MySql => format!("`{ident}`"),
_ => format!("\"{ident}\""),
}
}