Skip to main content

tinystore/
inside.rs

1//! kv, jobs, blobs, search and records inside an application's database: a
2//! bucket, a queue or a set of files opened from a database lives in its
3//! file, beside its tables, and commits with its rows in `db.tx`, and a
4//! queue's job in `db.batch` too; a table's index follows a table, changed in
5//! the commit that changes a row; a stream's events appended in either are
6//! kept in the file until they commit, then moved into records.db. This is
7//! the one place two engines meet, so that neither imports the other, and so
8//! the async API's database opens its own here.
9
10#[cfg(feature = "jobs")]
11use serde::Serialize;
12#[cfg(any(feature = "jobs", feature = "search"))]
13use serde::de::DeserializeOwned;
14
15use crate::sql::Database;
16
17#[cfg(feature = "kv")]
18impl Database {
19    /// A bucket of values by key kept in this database's file, as
20    /// [`Store::bucket`](crate::Store::bucket) keeps one in kv.db: the same
21    /// handle with the same calls, whose writes commit with the rows in
22    /// [`Database::tx`] through `tx.with(&bucket)`.
23    pub fn bucket<V: crate::kv::Value>(&self, name: &str) -> crate::kv::BucketBuilder<V> {
24        crate::kv::BucketBuilder::in_file(std::sync::Arc::clone(self.shared()), name)
25    }
26}
27
28#[cfg(feature = "jobs")]
29impl Database {
30    /// A queue of jobs kept in this database's file, as
31    /// [`Store::queue`](crate::Store::queue) keeps one in jobs.db: the same
32    /// handle with the same calls and workers, whose jobs commit with the rows
33    /// in [`Database::tx`] through `tx.with(&queue)`. It shares the database's
34    /// writer, which is the point and its cost.
35    pub fn queue<V>(&self, name: &str) -> crate::jobs::QueueBuilder<V>
36    where
37        V: Serialize + DeserializeOwned + Send + 'static,
38    {
39        crate::jobs::QueueBuilder::in_file(std::sync::Arc::clone(self.shared()), name)
40    }
41}
42
43#[cfg(feature = "jobs")]
44impl<V> crate::jobs::Queue<V>
45where
46    V: Serialize + DeserializeOwned + Send + 'static,
47{
48    /// A job's add for a batch of the database the queue was opened from:
49    /// in [`Database::batch`] it commits with the batch's rows or not at
50    /// all, and shares the commit with every other write of the file, where
51    /// [`Database::tx`] holds the writer and pays a sync of its own. It adds
52    /// as [`add`](crate::jobs::Queue::add) does, unless its id is taken; a
53    /// queue kept in another file fails the batch, `Invalid`.
54    ///
55    /// ```no_run
56    /// # #[derive(serde::Serialize, serde::Deserialize)]
57    /// # struct Index { note: i64 }
58    /// # fn main() -> tinystore::Result<()> {
59    /// # let store = tinystore::Store::open("data", Default::default())?;
60    /// # let note = 7;
61    /// let db = store.database("app").open()?;
62    /// let indexing = db.queue::<Index>("indexing").open()?;
63    /// db.batch([
64    ///     tinystore::sql!("update notes set version = version + 1 where id = ?", note).into(),
65    ///     indexing.adding(&Index { note }),
66    /// ])?;
67    /// # Ok(())
68    /// # }
69    /// ```
70    pub fn adding(&self, value: &V) -> crate::sql::Write {
71        crate::jobs::JobCall::new(self, None).adding(value)
72    }
73}
74
75#[cfg(feature = "jobs")]
76impl<V> crate::jobs::JobCall<'_, V>
77where
78    V: Serialize + DeserializeOwned + Send + 'static,
79{
80    /// The job's add for a batch of the database the queue was opened from,
81    /// with what the call asks beside its value; see
82    /// [`Queue::adding`](crate::jobs::Queue::adding).
83    pub fn adding(self, value: &V) -> crate::sql::Write {
84        crate::sql::Write::lent(self.lent(crate::jobs::Change::Add, value))
85    }
86}
87
88#[cfg(feature = "blobs")]
89impl Database {
90    /// A set of files kept in this database's file, as
91    /// [`Store::files`](crate::Store::files) keeps one in blobs.db: the same
92    /// handle with the same calls, whose writes commit with the rows in
93    /// [`Database::tx`] through `tx.with(&files)`. The bytes too large to keep
94    /// inline lie in the folder beside the file, `sql/app.blobs/`.
95    ///
96    /// ```no_run
97    /// # fn main() -> tinystore::Result<()> {
98    /// # let store = tinystore::Store::open("data", Default::default())?;
99    /// let db = store.database("app").open()?;
100    /// let packages = db.files("packages").open()?;
101    /// db.tx(|tx| {
102    ///     tx.exec(tinystore::sql!("insert into plugins (file) values (?)", "stripe-1.0.0.js"))?;
103    ///     tx.with(&packages).put("stripe-1.0.0.js", b"export const charges = 1")?;
104    ///     Ok::<_, tinystore::Error>(())
105    /// })?;
106    /// # Ok(())
107    /// # }
108    /// ```
109    pub fn files(&self, name: &str) -> crate::blobs::FilesBuilder<'static> {
110        crate::blobs::FilesBuilder::in_file(std::sync::Arc::clone(self.shared()), name)
111    }
112}
113
114#[cfg(feature = "search")]
115impl Database {
116    /// An index of a table of this database, kept in its file: the table's
117    /// rows found again by their words, their vectors or both, as
118    /// [`Store::index`](crate::Store::index) finds documents, each hit's value
119    /// its row as [`Database::all`] reads one. The table owns the rows and the
120    /// index follows them: every change of a row, by any statement, trigger
121    /// or migration, reaches the index in the commit that makes it or not at
122    /// all, and one by a process beside the store at the store's next write
123    /// or within a second.
124    ///
125    /// ```no_run
126    /// # #[derive(serde::Deserialize)]
127    /// # struct Article { id: i64, title: String, body: String }
128    /// # fn main() -> tinystore::Result<()> {
129    /// # let store = tinystore::Store::open("data", Default::default())?;
130    /// let db = store.database("app").migrations("migrations").open()?;
131    /// let articles =
132    ///     db.search_index::<Article>("articles_search").table("articles").field("title", 2.0).field("body", 1.0).open()?;
133    /// let found = articles.search("новый заголовок").run()?;
134    /// # Ok(())
135    /// # }
136    /// ```
137    pub fn search_index<T: DeserializeOwned + 'static>(&self, name: &str) -> crate::search::TableIndexBuilder<T> {
138        let read_rows: crate::search::ReadRows<T> = std::sync::Arc::new(crate::sql::rows_on::<T>);
139        crate::search::TableIndexBuilder::in_file(std::sync::Arc::clone(self.shared()), name, read_rows)
140    }
141
142    /// Drops the table's index `name` this database keeps: its triggers come
143    /// off the table in one commit and its rows go in the background; says
144    /// whether there was one. A handle of it is refused from then on.
145    pub fn drop_search_index(&self, name: &str) -> crate::Result<bool> {
146        crate::search::drop_in_file(self.shared(), name)
147    }
148}
149
150/// A statement's rows as a table's index's `where` holds them, as SQL's `in
151/// (select …)` does: `search::is_in("id", sql!("select user_id from members
152/// where course_id = ?", course))`, read in the search's snapshot.
153#[cfg(feature = "search")]
154impl crate::search::Values for crate::sql::Sql {
155    fn listing(self) -> crate::search::Listing {
156        let described = self.describe();
157        let read = move |connection: &rusqlite::Connection, most: usize| crate::sql::column_on(connection, &self, most);
158        crate::search::Listing::rows(described, std::sync::Arc::new(read))
159    }
160}
161
162#[cfg(feature = "search")]
163impl crate::search::Values for &crate::sql::Sql {
164    fn listing(self) -> crate::search::Listing {
165        self.clone().listing()
166    }
167}
168
169#[cfg(feature = "records")]
170impl Database {
171    /// The store's stream of events `stream`, opened through this database:
172    /// the same handle as [`Store::events`](crate::Store::events) opens, with
173    /// the same calls and reads, the stream in records.db where every stream
174    /// lives. Its appends inside [`Database::tx`], through `tx.with(&audit)`,
175    /// and in [`Database::batch`], through
176    /// [`appending`](crate::records::Events::appending), are kept in this
177    /// database's file with the rows and written to the stream once they
178    /// commit, before the call returns: an event exists exactly when the
179    /// change it records does. An append outside them goes to the stream at
180    /// once, and no write is atomic across two files.
181    ///
182    /// ```no_run
183    /// # #[derive(serde::Serialize)]
184    /// # struct RoleChanged { user_id: i64, role: &'static str }
185    /// # fn main() -> tinystore::Result<()> {
186    /// # let store = tinystore::Store::open("data", Default::default())?;
187    /// let db = store.database("app").open()?;
188    /// let audit = db.events("audit").open()?;
189    /// db.tx(|tx| {
190    ///     tx.exec(tinystore::sql!("update roles set role = ? where user_id = ?", "admin", 42))?;
191    ///     tx.with(&audit).append("role.changed", &RoleChanged { user_id: 42, role: "admin" })?;
192    ///     Ok::<_, tinystore::Error>(())
193    /// })?;
194    /// let page = audit.list().newest().limit(50).page()?; // the line is in the stream
195    /// # Ok(())
196    /// # }
197    /// ```
198    pub fn events(&self, stream: &str) -> crate::records::EventsBuilder<'static> {
199        crate::records::EventsBuilder::in_file(std::sync::Arc::clone(self.shared()), stream)
200    }
201}
202
203#[cfg(feature = "records")]
204impl crate::records::Events {
205    /// An event's append for a batch of the database the stream was opened
206    /// from: in [`Database::batch`] it is kept with the batch's rows and
207    /// written to the stream once the batch commits, before the batch
208    /// returns. A stream opened from the store, or from another database,
209    /// fails the batch, `Invalid`.
210    ///
211    /// ```no_run
212    /// # fn main() -> tinystore::Result<()> {
213    /// # let store = tinystore::Store::open("data", Default::default())?;
214    /// let db = store.database("app").open()?;
215    /// let audit = db.events("audit").open()?;
216    /// db.batch([
217    ///     tinystore::sql!("update roles set role = ? where user_id = ?", "admin", 42).into(),
218    ///     audit.appending("role.changed", &serde_json::json!({ "user_id": 42, "role": "admin" })),
219    /// ])?;
220    /// # Ok(())
221    /// # }
222    /// ```
223    pub fn appending(&self, name: &str, fields: &impl serde::Serialize) -> crate::sql::Write {
224        self.event(name).appending(fields)
225    }
226}
227
228#[cfg(feature = "records")]
229impl crate::records::EventCall<'_> {
230    /// The event's append for a batch of the database its stream was opened
231    /// from, with what the call carries beside its fields, its id, its time;
232    /// see [`Events::appending`](crate::records::Events::appending). One made
233    /// through a transaction runs in it, and fails the batch.
234    pub fn appending(self, fields: &impl serde::Serialize) -> crate::sql::Write {
235        crate::sql::Write::lent(self.lent(fields))
236    }
237}
238
239#[cfg(all(feature = "kv", feature = "async"))]
240impl crate::aio::sql::Database {
241    /// A bucket kept in this database's file, as [`Database::bucket`] opens
242    /// one, its calls awaited: its writes commit with the rows in
243    /// [`tx`](crate::aio::sql::Database::tx) through `tx.with(&bucket)`.
244    pub fn bucket<V: crate::kv::Value>(&self, name: &str) -> crate::aio::kv::BucketBuilder<V> {
245        crate::aio::kv::BucketBuilder::new(self.blocking().bucket(name), std::sync::Arc::clone(self.pool()))
246    }
247}
248
249#[cfg(all(feature = "records", feature = "async"))]
250impl crate::aio::sql::Database {
251    /// The store's stream `stream` opened through this database, as
252    /// [`Database::events`] opens it, its calls awaited: its appends commit
253    /// with the rows in [`tx`](crate::aio::sql::Database::tx) through
254    /// `tx.with(&audit)`, and in [`batch`](crate::aio::sql::Database::batch)
255    /// through [`appending`](crate::aio::records::Events::appending).
256    pub fn events(&self, stream: &str) -> crate::aio::records::EventsBuilder<'_> {
257        crate::aio::records::EventsBuilder::new(self.blocking().events(stream), self.pool())
258    }
259}
260
261#[cfg(all(feature = "records", feature = "async"))]
262impl crate::aio::records::Events {
263    /// An event's append for a batch of the database the stream was opened
264    /// from, as [`Events::appending`](crate::records::Events::appending)
265    /// makes one: it checks the event, with no I/O, and the batch is awaited.
266    pub fn appending(&self, name: &str, fields: &impl serde::Serialize) -> crate::sql::Write {
267        self.blocking().appending(name, fields)
268    }
269}
270
271#[cfg(all(feature = "records", feature = "async"))]
272impl crate::aio::records::EventCall<'_> {
273    /// The event's append for a batch of the database its stream was opened
274    /// from, with what the call carries beside its fields; see
275    /// [`Events::appending`](crate::records::Events::appending).
276    pub fn appending(self, fields: &impl serde::Serialize) -> crate::sql::Write {
277        self.into_blocking().appending(fields)
278    }
279}
280
281#[cfg(all(feature = "blobs", feature = "async"))]
282impl crate::aio::sql::Database {
283    /// A set of files kept in this database's file, as [`Database::files`]
284    /// opens one, its calls awaited: its writes commit with the rows in
285    /// [`tx`](crate::aio::sql::Database::tx) through `tx.with(&files)`.
286    pub fn files(&self, name: &str) -> crate::aio::blobs::FilesBuilder<'_> {
287        crate::aio::blobs::FilesBuilder::new(self.blocking().files(name), self.pool())
288    }
289}
290
291#[cfg(all(feature = "jobs", feature = "async"))]
292impl crate::aio::sql::Database {
293    /// A queue kept in this database's file, as [`Database::queue`] opens
294    /// one, its calls awaited: its jobs commit with the rows in
295    /// [`tx`](crate::aio::sql::Database::tx) through `tx.with(&queue)`, and
296    /// in [`batch`](crate::aio::sql::Database::batch) through
297    /// [`adding`](crate::aio::jobs::Queue::adding).
298    pub fn queue<V>(&self, name: &str) -> crate::aio::jobs::QueueBuilder<V>
299    where
300        V: Serialize + DeserializeOwned + Send + 'static,
301    {
302        crate::aio::jobs::QueueBuilder::new(self.blocking().queue(name), std::sync::Arc::clone(self.pool()))
303    }
304}
305
306#[cfg(all(feature = "jobs", feature = "async"))]
307impl<V> crate::aio::jobs::Queue<V>
308where
309    V: Serialize + DeserializeOwned + Send + 'static,
310{
311    /// A job's add for a batch of the database the queue was opened from, as
312    /// [`Queue::adding`](crate::jobs::Queue::adding) makes one: it checks the
313    /// call and encodes its value, with no I/O, and the batch is awaited.
314    pub fn adding(&self, value: &V) -> crate::sql::Write {
315        self.blocking().adding(value)
316    }
317}
318
319#[cfg(all(feature = "jobs", feature = "async"))]
320impl<V> crate::aio::jobs::JobCall<'_, V>
321where
322    V: Serialize + DeserializeOwned + Send + 'static,
323{
324    /// The job's add for a batch of the database the queue was opened from,
325    /// with what the call asks beside its value; see
326    /// [`Queue::adding`](crate::jobs::Queue::adding).
327    pub fn adding(self, value: &V) -> crate::sql::Write {
328        self.into_blocking().adding(value)
329    }
330}
331
332#[cfg(all(feature = "search", feature = "async"))]
333impl crate::aio::sql::Database {
334    /// An index of a table of this database, as [`Database::search_index`]
335    /// opens one, its calls awaited. Its rows change with the table's, in
336    /// their commit; a search inside [`tx`](crate::aio::sql::Database::tx)
337    /// goes through `tx.with(&index)` and sees what the transaction wrote.
338    pub fn search_index<T: DeserializeOwned + Send + 'static>(
339        &self,
340        name: &str,
341    ) -> crate::aio::search::TableIndexBuilder<T> {
342        self.blocking().search_index(name).into()
343    }
344
345    /// Drops the table's index `name` this database keeps, as
346    /// [`Database::drop_search_index`] does. It runs in one transaction, so
347    /// it waits in the database's line with its transactions, on no thread,
348    /// and once polled it runs to its end: the triggers come off the table
349    /// in one commit or not at all, whether or not its future is still awaited.
350    pub fn drop_search_index(
351        &self,
352        name: &str,
353    ) -> impl std::future::Future<Output = crate::Result<bool>> + Send + 'static {
354        let name = name.to_owned();
355        self.run_in_line(&format!("index {name}: its drop"), move |db| db.drop_search_index(&name))
356    }
357}
358
359#[cfg(all(test, feature = "kv", feature = "jobs"))]
360#[path = "inside_tests.rs"]
361mod tests;