use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::task::{Context, Poll};
use std::time::Duration;
use chrono::{DateTime, Utc};
use futures::stream::{BoxStream, Stream, StreamExt};
use navree_contracts::Clock;
use navree_db::{
ChangeEvent, DEFAULT_CONNECTION, Db, DbError, Executed, Executor as DbExecutor, Pool,
Row as DbRow, Transaction, Uow,
};
use navree_kernel::{AppContext, BoxFuture};
use crate::driver::{DocumentDriver, InsertOutcome};
use crate::error::OrmError;
use crate::ir::{Aggregate, DeleteIr, InsertIr, QueryIr, UpdateIr};
use crate::row::Row;
use crate::sql::{self, Dialect, Statement, Syntax};
use crate::streams::{StreamingGuard, ensure_free};
use crate::value::{Field, Kind, Value};
pub type RowsStream<'a> = BoxStream<'a, Result<Row, OrmError>>;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Access {
Read,
Write,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Route<'a> {
connection: Option<&'a str>,
model: Option<&'a str>,
writer: bool,
}
impl<'a> Route<'a> {
pub const fn new() -> Self {
Route {
connection: None,
model: None,
writer: false,
}
}
#[must_use]
pub const fn on(self, name: Option<&'a str>) -> Self {
Route {
connection: name,
..self
}
}
#[must_use]
pub const fn for_model(self, name: Option<&'a str>) -> Self {
Route {
model: name,
..self
}
}
#[must_use]
pub const fn writer(self, writer: bool) -> Self {
Route { writer, ..self }
}
pub const fn connection(&self) -> Option<&'a str> {
self.connection
}
pub const fn model_connection(&self) -> Option<&'a str> {
self.model
}
pub const fn reads_from_writer(&self) -> bool {
self.writer
}
pub fn connection_for(&self, own: &str) -> Option<&'a str> {
let wanted = match self.connection {
Some(name) => Some(name),
None if own == DEFAULT_CONNECTION => self.model,
None => None,
};
wanted.filter(|name| *name != own)
}
}
tokio::task_local! {
static USING_CONNECTION: Arc<str>;
}
pub async fn using_connection<F: Future>(name: &str, future: F) -> F::Output {
USING_CONNECTION.scope(Arc::from(name), future).await
}
pub fn scoped_connection() -> Option<Arc<str>> {
USING_CONNECTION.try_with(Arc::clone).ok()
}
pub async fn using_writer<F: Future>(future: F) -> F::Output {
Db::using_writer(future).await
}
pub trait Executor: Send + Sync {
fn target(&self, access: Access) -> impl Future<Output = Result<Target<'_>, OrmError>> + Send;
fn target_routed(
&self,
access: Access,
route: Route<'_>,
) -> impl Future<Output = Result<Target<'_>, OrmError>> + Send {
let _ = route;
self.target(access)
}
}
pub enum Target<'a> {
Sql(SqlTarget<'a>),
Document(DocumentTarget),
}
pub struct SqlTarget<'a> {
conn: SqlConn<'a>,
dialect: Dialect,
syntax: Syntax,
uow: Option<Uow>,
app: Option<AppContext>,
}
enum SqlConn<'a> {
Pool(Pool),
Uow(Uow),
Tx(&'a Transaction),
}
pub(crate) struct OwnTransaction(Transaction);
impl OwnTransaction {
pub(crate) async fn commit(self) -> Result<(), OrmError> {
self.0.commit().await.map_err(OrmError::from)
}
pub(crate) async fn rollback(self) -> Result<(), OrmError> {
self.0.rollback().await.map_err(OrmError::from)
}
fn conn(&self) -> SqlConn<'_> {
SqlConn::Tx(&self.0)
}
}
pub trait ChangeRecorder: Send + Sync + 'static {
fn record_change(&self, event: ChangeEvent);
}
#[derive(Clone)]
pub struct DocumentTarget {
driver: Arc<dyn DocumentDriver>,
app: Option<AppContext>,
uow: Option<Uow>,
changes: Option<Arc<dyn ChangeRecorder>>,
}
impl DocumentTarget {
pub fn new(driver: Arc<dyn DocumentDriver>, app: Option<AppContext>) -> Self {
DocumentTarget {
driver,
app,
uow: None,
changes: None,
}
}
pub fn with_uow(mut self, uow: Uow) -> Self {
self.uow = Some(uow);
self
}
pub fn recording_changes(mut self, recorder: Arc<dyn ChangeRecorder>) -> Self {
self.changes = Some(recorder);
self
}
pub fn driver(&self) -> &dyn DocumentDriver {
&*self.driver
}
pub fn app(&self) -> Option<&AppContext> {
self.app.as_ref()
}
pub fn uow(&self) -> Option<&Uow> {
self.uow.as_ref()
}
}
#[derive(Clone)]
pub struct ExecContext {
app: Option<AppContext>,
uow: Option<Uow>,
dialect: Option<Dialect>,
driver: Option<&'static str>,
time_precision: u32,
}
const MICROSECONDS: u32 = 6;
impl Default for ExecContext {
fn default() -> Self {
ExecContext {
app: None,
uow: None,
dialect: None,
driver: None,
time_precision: MICROSECONDS,
}
}
}
impl ExecContext {
pub fn app(&self) -> Option<&AppContext> {
self.app.as_ref()
}
pub fn uow(&self) -> Option<&Uow> {
self.uow.as_ref()
}
pub fn dialect(&self) -> Option<Dialect> {
self.dialect
}
pub fn database(&self) -> &'static str {
match (self.dialect, self.driver) {
(Some(dialect), _) => dialect.name(),
(None, Some(driver)) => driver,
(None, None) => "the database",
}
}
pub fn time_precision(&self) -> u32 {
self.time_precision
}
pub async fn now(&self) -> DateTime<Utc> {
let now = match &self.app {
Some(app) => match app.try_get::<dyn Clock>().await {
Some(clock) => clock.now(),
None => Utc::now(),
},
None => Utc::now(),
};
truncate_to(now, self.time_precision)
}
}
impl fmt::Debug for ExecContext {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ExecContext")
.field("database", &self.database())
.field("uow", &self.uow)
.field("app", &self.app.is_some())
.field("time_precision", &self.time_precision)
.finish()
}
}
pub(crate) fn truncate_to_micros(at: DateTime<Utc>) -> DateTime<Utc> {
truncate_to(at, MICROSECONDS)
}
pub(crate) fn truncate_to(at: DateTime<Utc>, digits: u32) -> DateTime<Utc> {
let unit = 10_u32.pow(9 - digits.min(9));
let nanos = at.timestamp_subsec_nanos();
DateTime::from_timestamp(at.timestamp(), nanos - nanos % unit).unwrap_or(at)
}
impl Target<'_> {
pub fn context(&self) -> ExecContext {
match self {
Target::Sql(sql) => ExecContext {
app: sql.app.clone(),
uow: sql.uow.clone(),
dialect: Some(sql.dialect),
driver: None,
time_precision: MICROSECONDS,
},
Target::Document(document) => ExecContext {
app: document.app.clone(),
uow: document.uow.clone(),
dialect: None,
driver: Some(document.driver.name()),
time_precision: document.driver.time_precision().min(9),
},
}
}
pub fn uow(&self) -> Option<&Uow> {
match self {
Target::Sql(sql) => sql.uow.as_ref(),
Target::Document(document) => document.uow.as_ref(),
}
}
pub fn record_change(&self, event: ChangeEvent) {
match self {
Target::Sql(sql) => {
if let Some(uow) = &sql.uow {
uow.record_change(event);
}
}
Target::Document(document) => match (&document.uow, &document.changes) {
(Some(uow), _) => uow.record_change(event),
(None, Some(recorder)) => recorder.record_change(event),
(None, None) => {}
},
}
}
pub fn dialect(&self) -> Option<Dialect> {
match self {
Target::Sql(sql) => Some(sql.dialect),
Target::Document(_) => None,
}
}
pub(crate) async fn begin_savepoint(&self) -> Result<Option<OwnTransaction>, OrmError> {
match self {
Target::Sql(sql) if sql.in_transaction() => sql.begin_atomic().await.map(Some),
Target::Sql(_) | Target::Document(_) => Ok(None),
}
}
pub(crate) async fn begin_atomic(&self) -> Result<Option<OwnTransaction>, OrmError> {
match self {
Target::Sql(sql) => sql.begin_atomic().await.map(Some),
Target::Document(_) => Ok(None),
}
}
pub(crate) async fn begin_transaction(&self) -> Result<Option<OwnTransaction>, OrmError> {
match self {
Target::Sql(sql) if !sql.in_transaction() => sql.begin_atomic().await.map(Some),
Target::Sql(_) | Target::Document(_) => Ok(None),
}
}
pub(crate) fn on_transaction<'b>(&self, tx: &'b OwnTransaction) -> Target<'b> {
match self {
Target::Sql(sql) => Target::Sql(SqlTarget::new(
tx.conn(),
sql.syntax,
sql.uow.clone(),
sql.app.clone(),
)),
Target::Document(document) => Target::Document(document.clone()),
}
}
pub async fn fetch(&self, query: &QueryIr) -> Result<Vec<Row>, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_select(query, sql.syntax)?;
Ok(sql
.query_all_timed(&statement, query.timeout)
.await?
.into_iter()
.map(Row::from_sql)
.collect())
}
Target::Document(document) => {
crate::testing::note_statement();
document.driver.find(query).await
}
}
}
pub async fn stream<'s>(&'s self, query: &'s QueryIr) -> Result<RowsStream<'s>, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_select(query, sql.syntax)?;
let Some(timeout) = query.timeout else {
return sql.stream(&statement).await;
};
match sql.dialect {
Dialect::MySql => Ok(sql
.stream(&statement)
.await
.map_err(|error| error.timed_out(timeout))?
.map(move |row| row.map_err(|error| error.timed_out(timeout)))
.boxed()),
dialect => Err(OrmError::unsupported(
"a statement timeout on a cursor",
dialect.name(),
)),
}
}
Target::Document(document) => {
crate::testing::note_statement();
let rows = document.driver.stream(query).await?;
Ok(rows)
}
}
}
pub async fn aggregate(
&self,
query: &QueryIr,
aggregate: &Aggregate,
) -> Result<Value, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_aggregate(query, aggregate, sql.syntax)?;
match sql.query_one_timed(&statement, query.timeout).await? {
Some(row) => Row::from_sql(row).value("aggregate"),
None => Ok(Value::Null(Kind::I64)),
}
}
Target::Document(document) => {
crate::testing::note_statement();
document.driver.aggregate(query, aggregate).await
}
}
}
pub async fn exists(&self, query: &QueryIr) -> Result<bool, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_exists(query, sql.syntax)?;
match sql.query_one_timed(&statement, query.timeout).await? {
Some(row) => {
let value = Row::from_sql(row).value("exists")?;
bool::from_value(value).map_err(|error| {
crate::row::decode_error("EXISTS", "exists", "bool".into(), &error)
})
}
None => Ok(false),
}
}
Target::Document(document) => {
crate::testing::note_statement();
document.driver.exists(query).await
}
}
}
pub async fn insert(&self, insert: &InsertIr) -> Result<InsertOutcome, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_insert(insert, sql.syntax)?;
if !insert.returning.is_empty() && sql.dialect.supports_returning() {
let rows: Vec<Row> = sql
.query_all(&statement)
.await?
.into_iter()
.map(Row::from_sql)
.collect();
Ok(InsertOutcome {
rows_affected: rows.len() as u64,
returned: rows,
last_insert_id: None,
})
} else {
let result = sql.execute(&statement).await?;
Ok(InsertOutcome {
rows_affected: result.rows_affected,
returned: Vec::new(),
last_insert_id: result
.last_insert_id
.filter(|_| sql.dialect == Dialect::MySql),
})
}
}
Target::Document(document) => {
crate::testing::note_statement();
document.driver.insert(insert).await
}
}
}
pub async fn update(&self, update: &UpdateIr) -> Result<u64, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_update(update, sql.syntax)?;
Ok(sql.execute(&statement).await?.rows_affected)
}
Target::Document(document) => {
crate::testing::note_statement();
document.driver.update(update).await
}
}
}
pub async fn delete(&self, delete: &DeleteIr) -> Result<u64, OrmError> {
match self {
Target::Sql(sql) => {
let statement = sql::render_delete(delete, sql.syntax)?;
Ok(sql.execute(&statement).await?.rows_affected)
}
Target::Document(document) => {
crate::testing::note_statement();
document.driver.delete(delete).await
}
}
}
}
impl<'a> SqlTarget<'a> {
fn new(conn: SqlConn<'a>, syntax: Syntax, uow: Option<Uow>, app: Option<AppContext>) -> Self {
SqlTarget {
conn,
dialect: syntax.dialect(),
syntax,
uow,
app,
}
}
pub fn dialect(&self) -> Dialect {
self.dialect
}
pub fn syntax(&self) -> Syntax {
self.syntax
}
pub fn in_transaction(&self) -> bool {
self.conn.transaction_id().is_some()
}
pub async fn query_all(&self, statement: &Statement) -> Result<Vec<DbRow>, OrmError> {
ensure_free(self.conn.transaction_id())?;
crate::testing::note_statement();
let statement = statement.to_db();
let exec = self.conn.executor();
let rows = if self.conn.on_pool() {
read_again_if_lost(|| exec.get().fetch_all(&statement)).await
} else {
exec.get().fetch_all(&statement).await
};
rows.map_err(|error| self.error(error))
}
pub async fn query_one(&self, statement: &Statement) -> Result<Option<DbRow>, OrmError> {
ensure_free(self.conn.transaction_id())?;
crate::testing::note_statement();
let statement = statement.to_db();
let exec = self.conn.executor();
let row = if self.conn.on_pool() {
read_again_if_lost(|| exec.get().fetch_optional(&statement)).await
} else {
exec.get().fetch_optional(&statement).await
};
row.map_err(|error| self.error(error))
}
pub async fn execute(&self, statement: &Statement) -> Result<Executed, OrmError> {
ensure_free(self.conn.transaction_id())?;
crate::testing::note_statement();
let statement = statement.to_db();
let exec = self.conn.executor();
exec.get()
.execute(&statement)
.await
.map_err(|error| self.error(error))
}
fn error(&self, error: DbError) -> OrmError {
if self.dialect == Dialect::Sqlite
&& error
.message()
.to_ascii_lowercase()
.contains("no such function: regexp")
{
return OrmError::unsupported(
"a regular expression without a `regexp` function registered on the connection",
"SQLite",
);
}
OrmError::Db(error)
}
pub async fn execute_unprepared(&self, sql: &str) -> Result<Executed, OrmError> {
ensure_free(self.conn.transaction_id())?;
let exec = self.conn.executor();
Ok(exec.get().execute_script(sql).await?)
}
pub async fn stream(&self, statement: &Statement) -> Result<RowsStream<'_>, OrmError> {
let id = self.conn.transaction_id();
ensure_free(id)?;
crate::testing::note_statement();
let statement = statement.to_db();
let rows = self.conn.executor().get().fetch(&statement).await?;
Ok(Guarded::new(rows, id).boxed())
}
fn begin_atomic(&self) -> BoxFuture<'_, Result<OwnTransaction, OrmError>> {
Box::pin(async move {
ensure_free(self.conn.transaction_id())?;
let tx = match &self.conn {
SqlConn::Pool(pool) => pool.begin().await?,
SqlConn::Uow(uow) => uow.savepoint().await?,
SqlConn::Tx(tx) => tx.savepoint().await?,
};
Ok(OwnTransaction(tx))
})
}
pub(crate) async fn query_all_timed(
&self,
statement: &Statement,
timeout: Option<Duration>,
) -> Result<Vec<DbRow>, OrmError> {
match self.timed(TimedRead::All(statement), timeout).await? {
TimedRows::All(rows) => Ok(rows),
TimedRows::One(row) => Ok(row.into_iter().collect()),
}
}
pub(crate) async fn query_one_timed(
&self,
statement: &Statement,
timeout: Option<Duration>,
) -> Result<Option<DbRow>, OrmError> {
match self.timed(TimedRead::One(statement), timeout).await? {
TimedRows::One(row) => Ok(row),
TimedRows::All(rows) => Ok(rows.into_iter().next()),
}
}
async fn read(&self, read: TimedRead<'_>) -> Result<TimedRows, OrmError> {
match read {
TimedRead::All(statement) => self.query_all(statement).await.map(TimedRows::All),
TimedRead::One(statement) => self.query_one(statement).await.map(TimedRows::One),
}
}
async fn timed(
&self,
read: TimedRead<'_>,
timeout: Option<Duration>,
) -> Result<TimedRows, OrmError> {
let Some(timeout) = timeout else {
return self.read(read).await;
};
match self.dialect {
Dialect::MySql => self
.read(read)
.await
.map_err(|error| error.timed_out(timeout)),
Dialect::Postgres => self.postgres_timed(read, timeout).await,
Dialect::Sqlite => Err(OrmError::unsupported("a statement timeout", "SQLite")),
}
}
async fn postgres_timed(
&self,
read: TimedRead<'_>,
timeout: Duration,
) -> Result<TimedRows, OrmError> {
let in_transaction = self.in_transaction();
let tx = self.begin_atomic().await?;
let nested = SqlTarget::new(tx.conn(), self.syntax, self.uow.clone(), self.app.clone());
let result = async {
let previous = if in_transaction {
let current = Statement {
sql: "SELECT current_setting('statement_timeout') AS previous".to_owned(),
values: Vec::new(),
dialect: Dialect::Postgres,
};
match nested.query_one(¤t).await? {
Some(row) => Some(row.get::<String>("previous")?),
None => None,
}
} else {
None
};
nested
.execute_unprepared(&format!(
"SET LOCAL statement_timeout = {}",
sql::timeout_millis(timeout)
))
.await?;
let rows = nested
.read(read)
.await
.map_err(|error| error.timed_out(timeout))?;
if let Some(previous) = previous {
nested
.execute(&Statement {
sql: "SELECT set_config('statement_timeout', $1, true)".to_owned(),
values: vec![Value::from(previous)],
dialect: Dialect::Postgres,
})
.await?;
}
Ok::<_, OrmError>(rows)
}
.await;
drop(nested);
match result {
Ok(rows) => {
tx.commit().await?;
Ok(rows)
}
Err(error) => {
if let Err(rollback) = tx.rollback().await {
tracing::warn!(target: "navree_orm", error = %rollback, "rolling back a timed-out statement failed");
}
Err(error)
}
}
}
}
async fn read_again_if_lost<'r, T, F>(read: F) -> Result<T, DbError>
where
F: Fn() -> BoxFuture<'r, Result<T, DbError>>,
{
match read().await {
Err(error) if crate::error::lost_connection(&error) => {
tracing::warn!(target: "navree_orm", %error, "the connection was lost under a read; reading again");
read().await
}
result => result,
}
}
enum TimedRead<'s> {
All(&'s Statement),
One(&'s Statement),
}
enum TimedRows {
All(Vec<DbRow>),
One(Option<DbRow>),
}
struct ConnExecutor<'x>(&'x dyn DbExecutor);
impl ConnExecutor<'_> {
fn get(&self) -> &dyn DbExecutor {
self.0
}
}
impl SqlConn<'_> {
fn transaction_id(&self) -> Option<usize> {
match self {
SqlConn::Pool(_) => None,
SqlConn::Uow(uow) => Some(std::ptr::from_ref::<Db>(uow.db()) as usize),
SqlConn::Tx(tx) => Some(std::ptr::from_ref::<Transaction>(tx) as usize),
}
}
fn on_pool(&self) -> bool {
self.transaction_id().is_none()
}
fn executor(&self) -> ConnExecutor<'_> {
match self {
SqlConn::Pool(pool) => ConnExecutor(pool),
SqlConn::Uow(uow) => ConnExecutor(uow),
SqlConn::Tx(tx) => ConnExecutor(*tx),
}
}
fn reborrow(&self) -> SqlConn<'_> {
match self {
SqlConn::Pool(pool) => SqlConn::Pool(pool.clone()),
SqlConn::Uow(uow) => SqlConn::Uow(uow.clone()),
SqlConn::Tx(tx) => SqlConn::Tx(tx),
}
}
}
struct Guarded<S> {
rows: Pin<Box<S>>,
_busy: Option<StreamingGuard>,
}
impl<S> Guarded<S> {
fn new(rows: S, transaction: Option<usize>) -> Self {
Guarded {
rows: Box::pin(rows),
_busy: transaction.map(StreamingGuard::new),
}
}
}
impl<S, E> Stream for Guarded<S>
where
S: Stream<Item = Result<DbRow, E>>,
OrmError: From<E>,
{
type Item = Result<Row, OrmError>;
fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
self.rows
.as_mut()
.poll_next(cx)
.map(|row| row.map(|row| row.map(Row::from_sql).map_err(OrmError::from)))
}
}
fn same_pool(db: &Db, uow: &Uow) -> bool {
db.same_as(uow.db())
}
fn pool_conn(db: &Db, writer: bool) -> SqlConn<'static> {
let pool = if writer {
db.pool()
} else {
db.task_read_pool()
};
SqlConn::Pool(pool.clone())
}
async fn db_target(db: &Db, access: Access, writer: bool) -> Result<Target<'static>, OrmError> {
let dialect = syntax_of(db).await?;
let app = db.app();
let current = Uow::current().filter(|uow| same_pool(db, uow));
let target = match access {
Access::Read => match current {
Some(uow) if uow.has_open_transaction().await => {
SqlTarget::new(SqlConn::Uow(uow.clone()), dialect, Some(uow), app)
}
_ => SqlTarget::new(pool_conn(db, writer), dialect, None, app),
},
Access::Write => match current {
Some(uow) => {
uow.mark_modified();
if uow.is_finished().await {
SqlTarget::new(pool_conn(db, true), dialect, None, app)
} else {
SqlTarget::new(SqlConn::Uow(uow.clone()), dialect, Some(uow), app)
}
}
None => SqlTarget::new(pool_conn(db, true), dialect, None, app),
},
};
Ok(Target::Sql(target))
}
fn connection_error(name: &str, message: impl Into<String>) -> OrmError {
OrmError::Connection {
connection: name.to_owned().into(),
message: message.into(),
}
}
impl Executor for Db {
async fn target(&self, access: Access) -> Result<Target<'_>, OrmError> {
self.target_routed(access, Route::new()).await
}
async fn target_routed(
&self,
access: Access,
route: Route<'_>,
) -> Result<Target<'_>, OrmError> {
let scoped = if route.connection.is_none() && self.is_default() {
scoped_connection()
} else {
None
};
let route = match &scoped {
Some(name) if route.model.is_none() => route.for_model(Some(&**name)),
_ => route,
};
match route.connection_for(self.name()) {
Some(name) => {
let db = self
.connection(name)
.await
.map_err(|error| connection_error(name, error.message().to_owned()))?;
db_target(&db, access, route.writer).await
}
None => db_target(self, access, route.writer).await,
}
}
}
fn syntax_of(db: &Db) -> BoxFuture<'_, Result<Syntax, OrmError>> {
Box::pin(async move {
let dialect = Dialect::from(DbExecutor::backend(db));
if dialect != Dialect::MySql {
return Ok(Syntax::from(dialect));
}
Ok(Syntax::of(dialect, db.mariadb_version().await?))
})
}
impl Executor for Uow {
async fn target(&self, access: Access) -> Result<Target<'_>, OrmError> {
if access == Access::Write {
self.mark_modified();
}
Ok(Target::Sql(SqlTarget::new(
SqlConn::Uow(self.clone()),
syntax_of(self.db()).await?,
Some(self.clone()),
self.db().app(),
)))
}
async fn target_routed(
&self,
access: Access,
route: Route<'_>,
) -> Result<Target<'_>, OrmError> {
let own = self.db().name();
if let Some(name) = route.connection_for(own) {
return Err(connection_error(
name,
format!(
"the unit of work runs on connection `{own}`, and a unit of work spans one connection; pass a `Db` (it runs the operation on `{name}`) or a unit of work of `{name}`"
),
));
}
self.target(access).await
}
}
impl Executor for Target<'_> {
async fn target(&self, _access: Access) -> Result<Target<'_>, OrmError> {
Ok(self.reborrow())
}
}
impl Target<'_> {
pub fn reborrow(&self) -> Target<'_> {
match self {
Target::Sql(sql) => Target::Sql(SqlTarget::new(
sql.conn.reborrow(),
sql.syntax,
sql.uow.clone(),
sql.app.clone(),
)),
Target::Document(document) => Target::Document(document.clone()),
}
}
}
impl<E: Executor + ?Sized> Executor for Arc<E> {
fn target(&self, access: Access) -> impl Future<Output = Result<Target<'_>, OrmError>> + Send {
(**self).target(access)
}
fn target_routed(
&self,
access: Access,
route: Route<'_>,
) -> impl Future<Output = Result<Target<'_>, OrmError>> + Send {
(**self).target_routed(access, route)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn timestamps_keep_the_precision_asked_for() {
let at = DateTime::from_timestamp(1_700_000_000, 123_456_789).unwrap();
assert_eq!(truncate_to(at, 6).timestamp_subsec_nanos(), 123_456_000);
assert_eq!(truncate_to(at, 3).timestamp_subsec_nanos(), 123_000_000);
assert_eq!(truncate_to(at, 0).timestamp_subsec_nanos(), 0);
assert_eq!(truncate_to(at, 9), at);
assert_eq!(truncate_to(at, 12), at, "more than nanoseconds keeps all");
assert_eq!(ExecContext::default().time_precision(), 6);
}
}