use std::{collections::BTreeMap, marker::PhantomData, sync::Arc};
use regex::Regex;
use sea_orm::{
DbBackend, DbErr, EntityTrait, Iden, IntoMockRow, Iterable, ModelTrait, PrimaryKeyToColumn, PrimaryKeyTrait, ProxyExecResult, ProxyRow, QueryTrait, Statement, StatementBuilder, TryFromU64, Value,
sea_query::IntoValueTuple,
};
use crate::{
expectation::{Exec, Expectation, Rows, into_proxy_row, rows_with},
matcher::{IntoArgs, SqlMatcher, integer},
mock::ExpectationRef,
};
type KeyOf<E> = <<E as EntityTrait>::PrimaryKey as PrimaryKeyTrait>::ValueType;
fn integer_key<M: ModelTrait>(model: &M) -> Option<u64> {
let mut keys = <M::Entity as EntityTrait>::PrimaryKey::iter();
let (Some(key), None) = (keys.next(), keys.next()) else {
return None;
};
as_u64(&model.get(key.into_column()))
}
fn as_u64(value: &Value) -> Option<u64> {
integer(value).flatten().and_then(|n| u64::try_from(n).ok())
}
macro_rules! matching_methods {
() => {
pub fn matching<Q: QueryTrait>(self, query: Q) -> Self {
let stmt = query.build(self.backend);
self.matching_statement(stmt)
}
pub fn matching_ignoring_limit<Q: QueryTrait>(self, query: Q) -> Self {
let stmt = query.build(self.backend);
self.set(|e| e.spec_mut().matchers.push(SqlMatcher::statement(stmt, true)))
}
pub fn matching_query<S: StatementBuilder>(self, query: &S) -> Self {
let stmt = self.backend.build(query);
self.matching_statement(stmt)
}
pub fn matching_statement(self, stmt: Statement) -> Self {
self.set(|e| e.spec_mut().matchers.push(SqlMatcher::statement(stmt, false)))
}
pub fn sql(self, sql: impl Into<String>) -> Self {
let sql = sql.into();
self.set(|e| e.spec_mut().matchers.push(SqlMatcher::Exact(sql)))
}
pub fn sql_regex(self, pattern: &str) -> Self {
let re = Regex::new(pattern).expect("invalid regular expression");
self.set(|e| e.spec_mut().matchers.push(SqlMatcher::Regex(re)))
}
pub fn sql_contains(self, needle: impl Into<String>) -> Self {
let needle = needle.into();
self.set(|e| e.spec_mut().matchers.push(SqlMatcher::Contains(needle)))
}
pub fn sql_fn(self, predicate: impl Fn(&Statement) -> bool + Send + Sync + 'static) -> Self {
self.set(|e| e.spec_mut().matchers.push(SqlMatcher::Fn(Arc::new(predicate))))
}
pub fn with_args(self, args: impl IntoArgs) -> Self {
let args = args.into_args();
self.set(|e| e.spec_mut().args = Some(args))
}
pub fn times(self, n: usize) -> Self {
self.set(|e| e.times(n))
}
pub fn maybe(self) -> Self {
self.set(Expectation::maybe)
}
pub fn returning_error(self, err: DbErr) {
self.inner.update(|e| e.response_mut().error = Some(err));
}
fn set(self, f: impl FnOnce(&mut Expectation)) -> Self {
self.inner.update(f);
self
}
};
}
#[must_use = "an expectation needs a result: call `returning(..)`, `returning_with(..)`, `returning_rows(..)` or `returning_error(..)`"]
pub struct SelectExpectation<E: EntityTrait> {
inner: ExpectationRef,
backend: DbBackend,
_entity: PhantomData<fn() -> E>,
}
impl<E: EntityTrait> SelectExpectation<E> {
pub(crate) fn new(inner: ExpectationRef, backend: DbBackend) -> Self {
Self { inner, backend, _entity: PhantomData }
}
matching_methods!();
pub fn returning<M>(self, models: impl IntoIterator<Item = M>)
where
M: ModelTrait<Entity = E>,
{
let rows = models.into_iter().map(into_proxy_row).collect();
self.inner.update(|e| e.response_mut().rows = Some(Rows::Static(rows)));
}
pub fn returning_with<M, F>(self, f: F)
where
M: ModelTrait<Entity = E>,
F: Fn(&Statement) -> Result<Vec<M>, DbErr> + Send + Sync + 'static,
{
self.inner.update(|e| e.response_mut().rows = Some(rows_with(f)));
}
#[track_caller]
pub fn returning_with_columns<M, C, K, V>(self, rows: impl IntoIterator<Item = (M, C)>)
where
M: ModelTrait<Entity = E>,
C: IntoIterator<Item = (K, V)>,
K: Into<String>,
V: Into<Value>,
{
let mut proxy_rows = Vec::new();
for (model, columns) in rows {
let mut row = into_proxy_row(model);
for (column, value) in columns {
let column = column.into();
if row.values.contains_key(&column) {
panic!("extra column `{column}` is already a column of the model");
}
row.values.insert(column, value.into());
}
proxy_rows.push(row);
}
self.inner.update(|e| e.response_mut().rows = Some(Rows::Static(proxy_rows)));
}
pub fn returning_rows<R: IntoMockRow>(self, rows: impl IntoIterator<Item = R>) {
let rows = rows.into_iter().map(into_proxy_row).collect();
self.inner.update(|e| {
let response = e.response_mut();
response.rows = Some(Rows::Static(rows));
response.raw_rows = true;
});
}
}
#[must_use = "an expectation needs a result: call `rows_affected(..)`, `last_insert_id(..)`, `returning(..)`, `exec_with(..)` or `returning_error(..)`"]
pub struct ExecExpectation<E: EntityTrait> {
inner: ExpectationRef,
backend: DbBackend,
_entity: PhantomData<fn() -> E>,
}
impl<E: EntityTrait> ExecExpectation<E> {
pub(crate) fn new(inner: ExpectationRef, backend: DbBackend) -> Self {
Self { inner, backend, _entity: PhantomData }
}
matching_methods!();
pub fn rows_affected(self, n: u64) -> ExecResponse<E> {
ExecResponse::new(self.inner).rows_affected(n)
}
pub fn last_insert_id(self, id: u64) -> ExecResponse<E> {
self.inner.update(|e| e.exec_mut().rows_affected = 1);
ExecResponse::new(self.inner).last_insert_id(id)
}
pub fn last_insert_key(self, key: impl Into<KeyOf<E>>) -> ExecResponse<E> {
self.inner.update(|e| e.exec_mut().rows_affected = 1);
ExecResponse::new(self.inner).last_insert_key(key)
}
pub fn returning<M>(self, models: impl IntoIterator<Item = M>)
where
M: ModelTrait<Entity = E>,
{
let models: Vec<M> = models.into_iter().collect();
let last_id = models.last().and_then(integer_key);
let rows: Vec<_> = models.into_iter().map(into_proxy_row).collect();
let count = rows.len() as u64;
self.inner.update(|e| {
e.response_mut().rows = Some(Rows::Static(rows));
e.exec_mut().rows_affected = count;
if let Some(id) = last_id {
e.exec_mut().last_insert_id = id;
}
});
}
pub fn returning_with<M, F>(self, f: F)
where
M: ModelTrait<Entity = E>,
F: Fn(&Statement) -> Result<Vec<M>, DbErr> + Send + Sync + 'static,
{
let f = Arc::new(f);
let rows = {
let f = f.clone();
rows_with(move |stmt| f(stmt))
};
let exec = move |stmt: &Statement| {
let models = f(stmt)?;
let mut result = ProxyExecResult::new(0, models.len() as u64);
if let Some(id) = models.last().and_then(integer_key) {
result.last_insert_id = id;
}
Ok(result)
};
self.inner.update(|e| {
let response = e.response_mut();
response.rows = Some(rows);
response.exec = Some(Exec::Fn(Arc::new(exec)));
});
}
pub fn exec_with<F>(self, f: F)
where
F: Fn(&Statement) -> Result<ProxyExecResult, DbErr> + Send + Sync + 'static,
{
self.inner.update(|e| e.response_mut().exec = Some(Exec::Fn(Arc::new(f))));
}
}
pub struct ExecResponse<E: EntityTrait> {
inner: ExpectationRef,
_entity: PhantomData<fn() -> E>,
}
impl<E: EntityTrait> ExecResponse<E> {
fn new(inner: ExpectationRef) -> Self {
Self { inner, _entity: PhantomData }
}
pub fn rows_affected(self, n: u64) -> Self {
self.inner.update(|e| e.exec_mut().rows_affected = n);
self
}
pub fn last_insert_id(self, id: u64) -> Self {
let key = <KeyOf<E> as TryFromU64>::try_from_u64(id).expect("primary key cannot be built from a u64: use `last_insert_key` instead");
self.key(key.into_value_tuple().into_iter().collect(), Some(id))
}
pub fn last_insert_key(self, key: impl Into<KeyOf<E>>) -> Self {
let values: Vec<Value> = key.into().into_value_tuple().into_iter().collect();
let id = match values.as_slice() {
[value] => as_u64(value),
_ => None,
};
self.key(values, id)
}
fn key(self, values: Vec<Value>, id: Option<u64>) -> Self {
let row: BTreeMap<String, Value> = E::PrimaryKey::iter().map(|key| key.to_string()).zip(values).collect();
self.inner.update(|e| {
if let Some(id) = id {
e.exec_mut().last_insert_id = id;
}
e.response_mut().returning_pk = Some(ProxyRow::new(row));
});
self
}
}
#[must_use = "an expectation needs a result: call `returning_rows(..)`, `returning_with(..)`, `rows_affected(..)`, `last_insert_id(..)`, `exec_with(..)` or `returning_error(..)`"]
pub struct QueryExpectation {
inner: ExpectationRef,
backend: DbBackend,
}
impl QueryExpectation {
pub(crate) fn new(inner: ExpectationRef, backend: DbBackend) -> Self {
Self { inner, backend }
}
matching_methods!();
pub fn returning_rows<R: IntoMockRow>(self, rows: impl IntoIterator<Item = R>) {
let rows = rows.into_iter().map(into_proxy_row).collect();
self.inner.update(|e| {
let response = e.response_mut();
response.rows = Some(Rows::Static(rows));
response.raw_rows = true;
});
}
pub fn returning_with<R, F>(self, f: F)
where
R: IntoMockRow,
F: Fn(&Statement) -> Result<Vec<R>, DbErr> + Send + Sync + 'static,
{
self.inner.update(|e| e.response_mut().rows = Some(rows_with(f)));
}
pub fn rows_affected(self, n: u64) -> QueryResponse {
QueryResponse(self.inner).rows_affected(n)
}
pub fn last_insert_id(self, id: u64) -> QueryResponse {
QueryResponse(self.inner).last_insert_id(id)
}
pub fn exec_with<F>(self, f: F)
where
F: Fn(&Statement) -> Result<ProxyExecResult, DbErr> + Send + Sync + 'static,
{
self.inner.update(|e| e.response_mut().exec = Some(Exec::Fn(Arc::new(f))));
}
}
pub struct QueryResponse(ExpectationRef);
impl QueryResponse {
pub fn rows_affected(self, n: u64) -> Self {
self.0.update(|e| e.exec_mut().rows_affected = n);
self
}
pub fn last_insert_id(self, id: u64) -> Self {
self.0.update(|e| e.exec_mut().last_insert_id = id);
self
}
}
pub struct TransactionExpectation {
inner: ExpectationRef,
}
impl TransactionExpectation {
pub(crate) fn new(inner: ExpectationRef) -> Self {
Self { inner }
}
pub fn times(self, n: usize) -> Self {
self.inner.update(|e| e.times(n));
self
}
pub fn maybe(self) -> Self {
self.inner.update(Expectation::maybe);
self
}
}