use std::fmt;
use std::sync::Arc;
use std::time::SystemTime;
use serde::de::DeserializeOwned;
use super::batch::{Batch, Ran, Write};
use super::engine::{Base, Databases};
use super::migrations::Migrations;
use super::rows::{Answer, Held, Rows};
use super::run::{self, Read, Wanted};
use super::statement::Sql;
use super::tx::Tx;
#[cfg(any(feature = "kv", feature = "jobs", feature = "blobs", feature = "search"))]
use crate::engine::SharedFile;
use crate::{Durability, Error, Result, Store, Transaction};
impl Store {
pub fn database(&self, name: &str) -> DatabaseBuilder {
DatabaseBuilder { store: self.clone(), name: name.to_owned(), migrations: None, durability: None }
}
}
#[derive(Debug)]
#[must_use = "a database opens with `open`"]
pub struct DatabaseBuilder {
store: Store,
name: String,
migrations: Option<Migrations>,
durability: Option<Durability>,
}
impl DatabaseBuilder {
pub fn migrations(mut self, migrations: impl Into<Migrations>) -> Self {
self.migrations = Some(migrations.into());
self
}
pub fn durability(mut self, durability: Durability) -> Self {
self.durability = Some(durability);
self
}
pub fn open(self) -> Result<Database> {
let describe = super::engine::described(&self.name);
let durability = self.durability;
let opened = check_name(&self.name)
.and_then(|()| self.migrations.map(Migrations::load).transpose())
.and_then(|migrations| Databases::of(&self.store)?.open(&self.store, &self.name, migrations, durability));
opened.map(|base| Database { base }).map_err(|error| error.within(describe))
}
}
#[derive(Clone)]
pub struct Database {
base: Arc<Base>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Done {
pub changes: u64,
pub last_insert_rowid: i64,
}
macro_rules! reads {
() => {
pub fn all<T: DeserializeOwned>(&self, statement: impl Into<Sql>) -> Result<Vec<T>> {
let statement = statement.into();
self.rows(&statement, Wanted::All)
.and_then(Rows::decode)
.map_err(|error| self.base.failed(&statement, error))
}
pub fn one<T: DeserializeOwned>(&self, statement: impl Into<Sql>) -> Result<Option<T>> {
let statement = statement.into();
let rows = self.rows(&statement, Wanted::One).and_then(Rows::decode);
rows.map(|rows: Vec<T>| rows.into_iter().next()).map_err(|error| self.base.failed(&statement, error))
}
pub fn scalar<T: DeserializeOwned>(&self, statement: impl Into<Sql>) -> Result<T> {
let statement = statement.into();
self.rows(&statement, Wanted::Scalar)
.and_then(Rows::scalar)
.map_err(|error| self.base.failed(&statement, error))
}
pub(crate) fn rows_of(&self, statement: &Sql, wanted: Wanted) -> Result<Rows> {
self.rows(statement, wanted).map_err(|error| self.base.failed(statement, error))
}
};
}
pub(super) use reads;
impl Database {
pub fn name(&self) -> &str {
&self.base.name
}
reads!();
pub fn exec(&self, statement: impl Into<Sql>) -> Result<Done> {
let statement = statement.into();
#[cfg(feature = "replication")]
if self.base.file().is_copy() {
let done = self.pass_on(std::slice::from_ref(&statement), false)?;
return done.into_iter().next().ok_or_else(|| Error::internal("a write's home answered no result"));
}
let weight = statement.weight();
let running = statement.clone();
self.base
.file()
.write(weight, move |tx| run::exec(tx, &running))
.map_err(|error| self.base.failed(&statement, error))
}
pub fn batch<I>(&self, writes: I) -> Result<Vec<Done>>
where
I: IntoIterator,
I::Item: Into<Write>,
{
let owner = self.base.describe();
let writes = writes.into_iter().map(Into::into).collect();
let batch = Batch::checked(writes, self.base.file(), &owner).map_err(|error| error.within(&owner))?;
#[cfg(feature = "replication")]
if self.base.file().is_copy() {
let statements = batch.statements();
let done = self.pass_on(&statements, true)?;
if done.len() != statements.len() {
let why = format!("a batch of {} statements answered with {} results", statements.len(), done.len());
return Err(Error::internal(why));
}
return Ok(done);
}
let (weight, write) = batch.write();
self.base.file().write(weight, write).map(Ran::finish).map_err(|error| error.within(owner))
}
pub fn tx<T, E: From<Error>>(&self, work: impl FnOnce(&Tx<'_>) -> Result<T, E>) -> Result<T, E> {
self.tx_since(self.base.now(), work)
}
pub(crate) fn tx_since<T, E: From<Error>>(
&self,
started: SystemTime,
work: impl FnOnce(&Tx<'_>) -> Result<T, E>,
) -> Result<T, E> {
let bound = || self.base.within_bound(started);
let owner = self.base.describe();
Transaction::run(self.base.file(), &owner, Some(&bound), |transaction| work(&Tx::new(transaction, &self.base)))
}
#[cfg(feature = "replication")]
fn pass_on(&self, statements: &[Sql], batch: bool) -> Result<Vec<Done>> {
let store = self.base.shared.store().map_err(|error| error.within(self.base.describe()))?;
super::forward::pass_on(&store, &self.base.name, statements, batch)
}
#[cfg(any(feature = "kv", feature = "jobs", feature = "blobs", feature = "search"))]
pub(crate) fn shared(&self) -> &Arc<SharedFile> {
&self.base.shared
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn exec_then(&self, statement: Sql, done: impl FnOnce(Result<Done>) + Send + 'static) {
#[cfg(feature = "replication")]
if self.base.file().is_copy() {
let db = self.clone();
std::thread::spawn(move || done(db.exec(statement)));
return;
}
let (weight, fail) = (statement.weight(), self.failed_by(&statement));
self.base.file().submit(weight, move |tx| run::exec(tx, &statement), move |ran| done(ran.map_err(fail)));
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn batch_then(&self, writes: Vec<Write>, done: impl FnOnce(Result<Vec<Done>>) + Send + 'static) {
#[cfg(feature = "replication")]
if self.base.file().is_copy() {
let db = self.clone();
std::thread::spawn(move || done(db.batch(writes)));
return;
}
let owner = self.base.describe();
let (weight, write) = match Batch::checked(writes, self.base.file(), &owner) {
Ok(batch) => batch.write(),
Err(error) => return done(Err(error.within(owner))),
};
let ran = move |ran: Result<Ran>| done(ran.map(Ran::finish).map_err(|error| error.within(owner)));
self.base.file().submit(weight, write, ran);
}
#[cfg(feature = "wire")]
pub(crate) fn rows_then<A: Answer + Send + 'static>(
&self,
statement: Sql,
wanted: Wanted,
done: impl FnOnce(Result<A>) + Send + 'static,
) {
match self.probed(&statement, wanted) {
Ok(Some(rows)) => done(Ok(rows)),
Ok(None) => self.written_rows_then(statement, wanted, done),
Err(error) => done(Err(self.failed_by(&statement)(error))),
}
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn written_rows_then<A: Answer + Send + 'static>(
&self,
statement: Sql,
wanted: Wanted,
done: impl FnOnce(Result<A>) + Send + 'static,
) {
let (fail, weight, held) = (self.failed_by(&statement), statement.weight(), Held::of(&self.base.memory));
let write = move |tx: &crate::sqlite::Tx<'_>| run::write(tx, &statement, wanted, held);
self.base.file().submit(weight, write, move |rows| done(rows.map_err(fail)));
}
#[cfg(feature = "wire")]
pub(crate) fn read<A: Answer>(&self, statement: &Sql, wanted: Wanted) -> Result<Option<A>> {
if !is_query(statement.text()) {
return Ok(None);
}
self.probed(statement, wanted).map_err(|error| self.base.failed(statement, error))
}
fn rows(&self, statement: &Sql, wanted: Wanted) -> Result<Rows> {
if let Some(rows) = self.probed(statement, wanted)? {
return Ok(rows);
}
let (running, held) = (statement.clone(), Held::of(&self.base.memory));
self.base.file().write(statement.weight(), move |tx| run::write(tx, &running, wanted, held))
}
pub(crate) fn probed<A: Answer>(&self, statement: &Sql, wanted: Wanted) -> Result<Option<A>> {
if self.base.writes(statement.text()) {
return Ok(None);
}
let held = Held::of(&self.base.memory);
match self.base.file().read(|connection| run::read(connection, statement, wanted, held))? {
Read::Rows(rows) => Ok(Some(rows)),
Read::Writes => {
self.base.remember_write(statement.text());
Ok(None)
}
}
}
#[cfg(feature = "async")]
pub(crate) fn known_to_write(&self, statement: &Sql) -> bool {
self.base.writes(statement.text())
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn failed_by(&self, statement: &Sql) -> impl Fn(Error) -> Error + Clone + Send + Sync + use<> {
let (statement, database) = (statement.describe(), self.base.describe());
move |error| error.within(&statement).within(&database)
}
#[cfg(any(feature = "wire", feature = "async"))]
pub(crate) fn line(&self) -> String {
self.base.describe()
}
#[cfg(feature = "async")]
pub(crate) fn describe(&self) -> String {
self.base.describe()
}
#[cfg(feature = "async")]
pub(crate) fn now(&self) -> SystemTime {
self.base.now()
}
#[cfg(feature = "async")]
pub(crate) fn store(&self) -> Result<Store> {
self.base.shared.store()
}
}
impl fmt::Debug for Database {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "Database({})", self.base.name)
}
}
fn check_name(name: &str) -> Result<()> {
crate::text::check_name("a database's", name)
}
#[cfg(any(feature = "wire", test))]
pub(super) fn is_query(text: &str) -> bool {
let mut rest = text;
loop {
rest = rest.trim_start();
if let Some(line) = rest.strip_prefix("--") {
rest = line.split_once('\n').map_or("", |(_, after)| after);
} else if let Some(block) = rest.strip_prefix("/*") {
rest = block.split_once("*/").map_or("", |(_, after)| after);
} else {
break;
}
}
let word: String = rest.chars().take_while(char::is_ascii_alphabetic).collect();
["select", "with", "values", "explain"].iter().any(|query| word.eq_ignore_ascii_case(query))
}