use std::fmt;
use std::future::Future;
use std::marker::PhantomData;
use std::panic::{AssertUnwindSafe, catch_unwind};
use std::sync::Arc;
use serde::Serialize;
use serde::de::DeserializeOwned;
use super::oneshot::{Answer, Pending, pending};
use super::run;
use crate::polled;
use crate::pool::Pool;
use crate::sql::{self, Direction, Done, Migrations, Page, Paging, Parts, Rows, Sql, Tx, Upsert, Wanted, Write};
use crate::{Durability, Error, Result};
pub use each::Each;
impl super::Store {
pub fn database(&self, name: &str) -> DatabaseBuilder {
DatabaseBuilder { builder: self.blocking().database(name), pool: Arc::clone(self.pool()) }
}
}
#[derive(Debug)]
#[must_use = "a database opens with `open`"]
pub struct DatabaseBuilder {
builder: sql::DatabaseBuilder,
pool: Arc<Pool>,
}
impl DatabaseBuilder {
pub fn migrations(self, migrations: impl Into<Migrations>) -> Self {
DatabaseBuilder { builder: self.builder.migrations(migrations), pool: self.pool }
}
pub fn durability(self, durability: Durability) -> Self {
DatabaseBuilder { builder: self.builder.durability(durability), pool: self.pool }
}
pub fn open(self) -> Result<Database> {
self.builder.open().map(|db| Database { db, pool: self.pool })
}
}
#[derive(Clone)]
pub struct Database {
db: sql::Database,
pool: Arc<Pool>,
}
impl Database {
pub fn name(&self) -> &str {
self.db.name()
}
pub fn blocking(&self) -> &sql::Database {
&self.db
}
#[cfg(any(feature = "kv", feature = "jobs", feature = "blobs", feature = "records"))]
pub(crate) fn pool(&self) -> &Arc<Pool> {
&self.pool
}
pub fn all<T>(&self, statement: impl Into<Sql>) -> impl Future<Output = Result<Vec<T>>> + Send + 'static
where
T: DeserializeOwned + Send + 'static,
{
self.rows(statement.into(), Wanted::All, Rows::decode::<T>)
}
pub fn one<T>(&self, statement: impl Into<Sql>) -> impl Future<Output = Result<Option<T>>> + Send + 'static
where
T: DeserializeOwned + Send + 'static,
{
self.rows(statement.into(), Wanted::One, |rows| Ok(rows.decode::<T>()?.into_iter().next()))
}
pub fn scalar<T>(&self, statement: impl Into<Sql>) -> impl Future<Output = Result<T>> + Send + 'static
where
T: DeserializeOwned + Send + 'static,
{
self.rows(statement.into(), Wanted::Scalar, Rows::scalar::<T>)
}
pub fn each<T>(&self, statement: impl Into<Sql>) -> Each<T>
where
T: DeserializeOwned + Send + 'static,
{
Each::new(self.clone(), Ok(statement.into()), None, Arc::from([]))
}
pub fn exec(&self, statement: impl Into<Sql>) -> impl Future<Output = Result<Done>> + Send + 'static {
self.exec_of(Ok(statement.into()))
}
pub fn batch<I>(&self, writes: I) -> impl Future<Output = Result<Vec<Done>>> + Send + 'static
where
I: IntoIterator,
I::Item: Into<Write>,
{
let (db, writes) = (self.db.clone(), writes.into_iter().map(Into::into).collect::<Vec<Write>>());
run::write(&self.pool, self.what("a batch"), move |answer| {
db.batch_then(writes, move |done| answer.send(done));
})
}
pub fn tx<T, E, F>(&self, work: F) -> impl Future<Output = Result<T, E>> + Send + 'static
where
F: FnOnce(&Tx<'_>) -> Result<T, E> + Send + 'static,
T: Send + 'static,
E: From<Error> + Send + 'static,
{
let database = self.clone();
async move {
let started = database.db.now();
let ran = database.run_in_line("a transaction", move |db| Ok(db.tx_since(started, work)));
ran.await.unwrap_or_else(|error| Err(E::from(error)))
}
}
pub(crate) fn run_in_line<T, F>(
&self,
call: &str,
work: F,
) -> impl Future<Output = Result<T>> + Send + 'static + use<T, F>
where
F: FnOnce(&sql::Database) -> Result<T> + Send + 'static,
T: Send + 'static,
{
let db = self.db.clone();
run::blocking(&self.pool, Some(db.line()), self.what(call), move || work(&db))
}
pub fn table<T>(&self, name: &str) -> Table<T> {
Table { query: Query { database: self.clone(), parts: Parts::of_table(name), row: PhantomData } }
}
fn rows<A, F>(&self, statement: Sql, wanted: Wanted, finish: F) -> impl Future<Output = Result<A>> + Send + 'static
where
A: Send + 'static,
F: FnOnce(Rows) -> Result<A> + Send + 'static,
{
let start = if self.db.known_to_write(&statement) {
Start::Written(self.written(statement, wanted, finish))
} else {
let database = self.clone();
let read = move || database.probed((statement, wanted), finish);
Start::Read(run::read(&self.pool, self.what("a read"), read))
};
async move {
match start {
Start::Written(written) => written.await,
Start::Read(read) => match read.await? {
Probed::Answered(answer) => Ok(answer),
Probed::Queued(written) => written.await,
},
}
}
}
fn written<A, F>(
&self,
statement: Sql,
wanted: Wanted,
finish: F,
) -> impl Future<Output = Result<A>> + Send + 'static
where
A: Send + 'static,
F: FnOnce(Rows) -> Result<A> + Send + 'static,
{
let database = self.clone();
let queue = move |answer| database.queue_write((statement, wanted), finish, answer);
run::write(&self.pool, self.what("a write"), queue)
}
fn probed<A, F>(&self, (statement, wanted): (Sql, Wanted), finish: F) -> Result<Probed<A>>
where
A: Send + 'static,
F: FnOnce(Rows) -> Result<A> + Send + 'static,
{
let fail = self.db.failed_by(&statement);
match self.db.probed::<Rows>(&statement, wanted) {
Ok(Some(rows)) => finish(rows).map(Probed::Answered).map_err(fail),
Ok(None) => {
let (answer, answered) = pending(self.what("a write"));
polled::leading_on(&run::lead_on(&self.pool), || self.queue_write((statement, wanted), finish, answer));
Ok(Probed::Queued(answered))
}
Err(error) => Err(fail(error)),
}
}
fn queue_write<A, F>(&self, (statement, wanted): (Sql, Wanted), finish: F, answer: Answer<A>)
where
A: Send + 'static,
F: FnOnce(Rows) -> Result<A> + Send + 'static,
{
let (fail, pool) = (self.db.failed_by(&statement), Arc::clone(&self.pool));
self.db.written_rows_then(statement, wanted, move |rows: Result<Rows>| match rows {
Ok(rows) => pool.run_always(Box::new(move || {
if !answer.is_awaited() {
return;
}
match catch_unwind(AssertUnwindSafe(|| finish(rows).map_err(fail))) {
Ok(made) => answer.send(made),
Err(payload) => answer.panicked(payload),
}
})),
Err(error) => answer.send(Err(error)),
});
}
fn exec_of(&self, statement: Result<Sql>) -> impl Future<Output = Result<Done>> + Send + 'static {
let db = self.db.clone();
run::write(&self.pool, self.what("a write"), move |answer| match statement {
Ok(statement) => db.exec_then(statement, move |done| answer.send(done)),
Err(error) => answer.send(Err(error)),
})
}
fn what(&self, call: &str) -> String {
format!("{}: {call}", self.db.describe())
}
}
enum Start<R, W> {
Read(R),
Written(W),
}
enum Probed<A> {
Answered(A),
Queued(Pending<A>),
}
impl From<sql::Database> for Database {
fn from(db: sql::Database) -> Database {
let pool = db.store().map_or_else(|_| Pool::stopped(), |store| Pool::of_or_stopped(&store));
Database { db, pool }
}
}
impl fmt::Debug for Database {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.db, f)
}
}
pub struct Query<T> {
database: Database,
parts: Parts,
row: PhantomData<fn() -> T>,
}
pub struct Table<T> {
query: Query<T>,
}
impl<T> std::ops::Deref for Table<T> {
type Target = Query<T>;
fn deref(&self) -> &Query<T> {
&self.query
}
}
impl<T> Table<T> {
pub fn name(&self) -> &str {
self.query.parts.table()
}
}
impl<T: Serialize + DeserializeOwned + Send + 'static> Table<T> {
pub fn insert(&self, row: &T) -> impl Future<Output = Result<T>> + Send + 'static {
let inserted = self.insert_all(std::slice::from_ref(row));
async move { inserted.await?.pop().ok_or_else(|| Error::internal("an insert that gave back no row")) }
}
pub fn insert_all(&self, rows: &[T]) -> impl Future<Output = Result<Vec<T>>> + Send + 'static {
let statement = (!rows.is_empty()).then(|| sql::insert_sql(self.name(), rows)).transpose();
let written = statement.map(|statement| {
statement.map(|statement| self.query.database.written(statement, Wanted::All, Rows::decode::<T>))
});
async move {
match written? {
Some(written) => written.await,
None => Ok(Vec::new()),
}
}
}
pub fn upsert(&self, row: &T, upsert: Upsert) -> impl Future<Output = Result<Option<T>>> + Send + 'static {
let written = sql::upsert_sql(self.name(), std::slice::from_ref(row), upsert).map(|statement| {
self.query.database.written(statement, Wanted::One, |rows| Ok(rows.decode::<T>()?.into_iter().next()))
});
async move { written?.await }
}
pub fn upsert_all(&self, rows: &[T], upsert: Upsert) -> impl Future<Output = Result<Vec<T>>> + Send + 'static {
let statement = upsert
.check()
.and_then(|()| (!rows.is_empty()).then(|| sql::upsert_sql(self.name(), rows, upsert)).transpose());
let written = statement.map(|statement| {
statement.map(|statement| self.query.database.written(statement, Wanted::All, Rows::decode::<T>))
});
async move {
match written? {
Some(written) => written.await,
None => Ok(Vec::new()),
}
}
}
}
impl<T> Query<T> {
#[must_use]
pub fn filter(&self, condition: impl Into<Sql>) -> Self {
self.with(|parts| parts.filter(condition.into()))
}
pub fn select<S>(&self, columns: impl Into<Sql>) -> Query<S> {
let mut parts = self.parts.clone();
parts.select(columns.into());
Query { database: self.database.clone(), parts, row: PhantomData }
}
#[must_use]
pub fn include<C>(&self, name: &str, query: &Query<C>) -> Self {
self.with(|parts| parts.include(name, &query.parts))
}
#[must_use]
pub fn join(&self, table: &str, on: impl Into<Sql>) -> Self {
self.with(|parts| parts.join(table, on.into()))
}
#[must_use]
pub fn left_join(&self, table: &str, on: impl Into<Sql>) -> Self {
self.with(|parts| parts.left_join(table, on.into()))
}
#[must_use]
pub fn group_by<I: IntoIterator<Item = S>, S: AsRef<str>>(&self, columns: I) -> Self {
self.with(|parts| parts.group_by(columns))
}
#[must_use]
pub fn having(&self, condition: impl Into<Sql>) -> Self {
self.with(|parts| parts.having(condition.into()))
}
#[must_use]
pub fn order_by(&self, column: &str, direction: Direction) -> Self {
self.with(|parts| parts.order_by(column, direction))
}
#[must_use]
pub fn order_by_sql(&self, piece: impl Into<Sql>, direction: Direction) -> Self {
self.with(|parts| parts.order_by_sql(piece.into(), direction))
}
#[must_use]
pub fn limit(&self, rows: u64) -> Self {
self.with(|parts| parts.limit(rows))
}
#[must_use]
pub fn offset(&self, rows: u64) -> Self {
self.with(|parts| parts.offset(rows))
}
pub fn to_sql(&self) -> Result<Sql> {
self.parts.to_sql()
}
pub fn count(&self) -> impl Future<Output = Result<u64>> + Send + 'static {
let counted =
self.parts.count_sql().map(|statement| self.database.rows(statement, Wanted::Scalar, Rows::scalar));
async move { counted?.await }
}
pub fn explain(&self) -> impl Future<Output = Result<Vec<String>>> + Send + 'static {
let planned =
self.parts.explain_sql().map(|statement| self.database.rows(statement, Wanted::All, sql::plan_of));
async move { planned?.await }
}
pub fn update<I, S>(&self, sets: I) -> impl Future<Output = Result<Done>> + Send + 'static
where
I: IntoIterator<Item = (S, Sql)>,
S: AsRef<str>,
{
self.database.exec_of(self.parts.update_sql(sets))
}
pub fn delete(&self) -> impl Future<Output = Result<Done>> + Send + 'static {
self.database.exec_of(self.parts.delete_sql())
}
fn with(&self, change: impl FnOnce(&mut Parts)) -> Self {
let mut parts = self.parts.clone();
change(&mut parts);
Query { database: self.database.clone(), parts, row: PhantomData }
}
}
impl<T: DeserializeOwned + Send + 'static> Query<T> {
pub fn all(&self) -> impl Future<Output = Result<Vec<T>>> + Send + 'static {
let nested = self.parts.nested();
self.read(Wanted::All, move |rows| rows.nesting(nested).decode())
}
pub fn one(&self) -> impl Future<Output = Result<Option<T>>> + Send + 'static {
let nested = self.parts.nested();
self.read(Wanted::One, move |rows| Ok(rows.nesting(nested).decode::<T>()?.into_iter().next()))
}
pub fn scalar<V: DeserializeOwned + Send + 'static>(&self) -> impl Future<Output = Result<V>> + Send + 'static {
self.read(Wanted::Scalar, Rows::scalar::<V>)
}
pub fn list(&self, limit: u64, after: Option<&str>) -> impl Future<Output = Result<Page<T>>> + Send + 'static {
let page = self.parts.page_sql(limit, after).map(|(statement, paging): (Sql, Paging)| {
self.database.rows(statement, Wanted::All, move |rows| paging.page(rows))
});
async move { page?.await }
}
pub fn each(&self) -> Each<T> {
let nested: Arc<[sql::Nested]> = self.parts.nested().into();
Each::new(self.database.clone(), self.parts.to_sql(), self.parts.walk_key(), nested)
}
fn read<A, F>(&self, wanted: Wanted, finish: F) -> impl Future<Output = Result<A>> + Send + 'static
where
A: Send + 'static,
F: FnOnce(Rows) -> Result<A> + Send + 'static,
{
let read = self.parts.to_sql().map(|statement| self.database.rows(statement, wanted, finish));
async move { read?.await }
}
}
impl<T> Clone for Query<T> {
fn clone(&self) -> Self {
Query { database: self.database.clone(), parts: self.parts.clone(), row: PhantomData }
}
}
impl<T> Clone for Table<T> {
fn clone(&self) -> Self {
Table { query: self.query.clone() }
}
}
impl<T> fmt::Debug for Query<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Query").field("database", &self.database).field("parts", &self.parts).finish()
}
}
impl<T> fmt::Debug for Table<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Table").field("query", &self.query).finish()
}
}
#[path = "sql_each.rs"]
mod each;
#[cfg(test)]
#[path = "sql_tests.rs"]
mod tests;