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