use std::fmt;
use std::path::Path;
use std::sync::Arc;
use std::time::SystemTime;
use serde::de::DeserializeOwned;
use super::batch::{Batch, Ran, Write};
use super::each::Each;
use super::engine::{Base, Databases, Opening, folder_of};
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", feature = "records"))]
use crate::engine::SharedFile;
use crate::sqlite::Drafts;
use crate::text::is_device;
use crate::{Durability, Error, Result, Store, Transaction};
impl Store {
pub fn database(&self, name: &str) -> DatabaseBuilder {
let name = name.to_owned();
DatabaseBuilder { store: self.clone(), name, migrations: None, durability: None, backup: true, redo: false }
}
}
#[derive(Debug)]
#[must_use = "a database opens with `open`"]
pub struct DatabaseBuilder {
store: Store,
name: String,
migrations: Option<Migrations>,
durability: Option<Durability>,
backup: bool,
redo: bool,
}
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 backup(mut self, backup: bool) -> Self {
self.backup = backup;
self
}
#[doc(hidden)]
pub fn redo_drafts(mut self) -> Self {
self.redo = true;
self
}
pub fn open(self) -> Result<Database> {
let describe = super::engine::described(&self.name);
let (durability, backup, name) = (self.durability, self.backup, &self.name);
let folder = folder_of(backup);
let drafts = |migrations: &Migrations| Drafts {
copy: self.store.dir().join(folder).join(format!("{name}.before-drafts")),
redo: self.redo,
command: redo_command(self.store.dir(), name, migrations),
};
let opened = check_name(name)
.and_then(|()| refuse_a_device(self.store.dir(), folder, name))
.and_then(|()| self.migrations.map(|migrations| Ok((drafts(&migrations), migrations.load()?))).transpose())
.and_then(|migrations| {
let opening = Opening { name, backup, migrations, durability };
Databases::of(&self.store)?.open(&self.store, opening)
});
opened.map(|base| Database { base }).map_err(|error| error.within(describe))
}
#[cfg(feature = "wire")]
pub(crate) fn open_as_it_is(self) -> Result<Database> {
let describe = super::engine::described(&self.name);
let (store, name) = (&self.store, &self.name);
let opened = check_name(name).and_then(|()| Databases::of(store)?.open_as_it_is(store, name, self.backup));
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 each<T: DeserializeOwned>(&self, statement: impl Into<Sql>) -> Result<Each<T>> {
Each::walk(self, statement.into(), None, Arc::from([]))
}
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", feature = "records"))]
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 answer = move |ran: Result<Ran>| done(ran.map(Ran::finish).map_err(|error| error.within(owner)));
#[cfg(feature = "records")]
let answer = {
let shared = Arc::clone(&self.base.shared);
move |ran: Result<Ran>| match ran {
Ok(ran) if ran.waits() => match shared.store().and_then(|store| crate::pool::Pool::of(&store)) {
Ok(pool) => pool.run(Box::new(move || answer(Ok(ran)))),
Err(_) => answer(Ok(ran)),
},
ran => answer(ran),
}
};
self.base.file().submit(weight, write, answer);
}
#[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)
}
}
}
pub(crate) fn known_to_write(&self, statement: &Sql) -> bool {
self.base.writes(statement.text())
}
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()
}
pub(crate) fn now(&self) -> SystemTime {
self.base.now()
}
pub(crate) fn store(&self) -> Result<Store> {
self.base.shared.store()
}
pub(crate) fn file(&self) -> &crate::sqlite::File {
self.base.file()
}
pub(crate) fn memory(&self) -> &Arc<crate::Memory> {
&self.base.memory
}
pub(crate) fn remember_write(&self, statement: &Sql) {
self.base.remember_write(statement.text());
}
}
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)
}
fn refuse_a_device(dir: &Path, folder: &str, name: &str) -> Result<()> {
if !is_device(name) || holds_file(dir, folder, name) {
return Ok(());
}
Err(Error::invalid(format!(
"a database's name {name:?}: Windows reads it as a device, not a file: name it otherwise"
)))
}
pub(super) fn holds_file(dir: &Path, folder: &str, name: &str) -> bool {
let file = format!("{name}.db");
let listed = std::fs::read_dir(dir.join(folder));
listed.is_ok_and(|entries| entries.flatten().any(|entry| entry.file_name().to_str() == Some(file.as_str())))
}
fn redo_command(dir: &Path, name: &str, migrations: &Migrations) -> String {
let quoted = |path: &Path| {
let text = path.display().to_string();
if text.contains(char::is_whitespace) { format!("\"{text}\"") } else { text }
};
let folder = match migrations {
Migrations::Dir(folder) => quoted(folder),
Migrations::Files(_) => "<migrations>".to_owned(),
};
format!("tinystore migrate {} {name} {folder} --redo-drafts", quoted(dir))
}
#[cfg(any(feature = "wire", test))]
pub(crate) 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))
}