tinystore 0.10.0

A small storage runtime for applications on SQLite: SQL, key-value state, durable jobs, files, search, logs and metrics in one directory
Documentation
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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
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 {
    /// The application's database `name`, `sql/<name>.db` in the store's
    /// directory, or `local/<name>.db` when no backup takes it, made the
    /// first time it opens:
    ///
    /// ```no_run
    /// # fn main() -> tinystore::Result<()> {
    /// # let store = tinystore::Store::open("data", Default::default())?;
    /// let db = store.database("app").migrations("migrations").open()?;
    /// # Ok(())
    /// # }
    /// ```
    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 }
    }
}

/// How a database opens; [`Store::database`] makes one.
#[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 {
    /// The migrations the file must have applied: opening applies those it
    /// has not, all in one transaction, and refuses a file that applied an
    /// edited, renamed or missing one, or more than the program has. Without
    /// them the file opens as it is.
    ///
    /// The newest may be drafts, named `0007_messages.draft.sql`: they apply
    /// in a transaction of their own once the file is copied to
    /// `sql/<name>.before-drafts`, and one edited since it was applied
    /// refuses the file, naming `tinystore migrate --redo-drafts`, which
    /// takes it back to the copy and applies them again. A draft renamed
    /// without `.draft`, its text the same, has shipped, and the copy goes.
    pub fn migrations(mut self, migrations: impl Into<Migrations>) -> Self {
        self.migrations = Some(migrations.into());
        self
    }

    /// How far this database's commits go before they return, where the
    /// store's own setting is not this file's: what may be lost to a power
    /// loss beside what may not. Its buckets and queues commit with it. A
    /// database open already keeps the durability it was opened with, and
    /// asking for another is `Invalid`.
    pub fn durability(mut self, durability: Durability) -> Self {
        self.durability = Some(durability);
        self
    }

    /// Whether backups take the database. `false` keeps its file and the
    /// bytes of its files in `local/<name>.db` and `local/<name>.blobs/`
    /// rather than `sql/`, where no backup looks, this release's or an older
    /// one's, open or not, and no node copies it: each node that opens it
    /// writes its own, and what a backup leaves out nothing else keeps. A
    /// name lives in one folder: one whose file lies in the other is
    /// `Invalid`, naming both.
    ///
    /// ```no_run
    /// # fn main() -> tinystore::Result<()> {
    /// # let store = tinystore::Store::open("data", Default::default())?;
    /// let uploads = store.database("uploads").backup(false).open()?;
    /// let pending = uploads.files("pending").ttl(std::time::Duration::from_secs(15 * 60)).open()?;
    /// # Ok(())
    /// # }
    /// ```
    pub fn backup(mut self, backup: bool) -> Self {
        self.backup = backup;
        self
    }

    /// Takes the database back to the copy kept from before its drafts, the
    /// migrations named `….draft.sql`, and applies them again: what was
    /// written since they were applied is gone. `tinystore migrate
    /// --redo-drafts` asks it; a program that asks it of its own open loses
    /// its data each time a draft changes, so it promises a program nothing.
    #[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))
    }

    /// Opens the database as the store holds it, for a connection that may
    /// only read: a file the store does not hold is `NotFound` rather than
    /// made, no migration runs, and no durability is bound for the program's
    /// own open.
    #[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))
    }
}

/// An application's database: its reads, its writes, its transactions.
/// Clones share the database, which closes with its store.
#[derive(Clone)]
pub struct Database {
    base: Arc<Base>,
}

/// What a write changed: the rows, and SQLite's rowid of the row it inserted,
/// `0` when it inserted none. The rowid is a table's key only for an `integer
/// primary key`.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Done {
    pub changes: u64,
    pub last_insert_rowid: i64,
}

/// The calls that read a statement's rows, the same on a database and in its
/// transaction: each type has `rows`, which reads them, and `base`.
macro_rules! reads {
    () => {
        /// The rows a statement gives, each read as a `T`: a struct by its
        /// columns' names, a tuple by their order, a single value when a row has
        /// one column. A write with `returning` runs on the writer and gives its
        /// rows once its commit is durable.
        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))
        }

        /// The one row a statement gives, or none; a statement that gives two is
        /// `invalid`, and a write that gave them rolls back.
        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))
        }

        /// The one value of the one row a statement gives, as `count(*)` does;
        /// `Option` takes a `NULL`, as `max` over no rows gives.
        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))
        }

        /// A statement's rows as SQLite keeps them, for a caller that is not
        /// Rust: the wire's.
        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!();

    /// The rows a statement gives, one at a time, each read as `all` reads
    /// it: read a part at a time from one snapshot, so that memory holds a
    /// part and not the rows, however many there are. The snapshot lasts
    /// five seconds at most: a walk that takes longer fails `limit`, and is
    /// read a page at a time with a table's `list`, or ordered by its key
    /// with a table's `each`, which reads on past it. A write with
    /// `returning` gives its rows as `all` does.
    ///
    /// ```no_run
    /// # #[derive(serde::Deserialize)] struct Order { id: i64 }
    /// # fn main() -> tinystore::Result<()> {
    /// # let db = tinystore::Store::open("data", Default::default())?.database("app").open()?;
    /// for order in db.each::<Order>("select * from orders")? {
    ///     let order = order?;
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn each<T: DeserializeOwned>(&self, statement: impl Into<Sql>) -> Result<Each<T>> {
        Each::walk(self, statement.into(), None, Arc::from([]))
    }

    /// Runs a write once it is durable. Writes from many callers share a
    /// commit, each in a savepoint of it: one that fails rolls back alone.
    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))
    }

    /// Runs writes known before they run as one, all of them or none, in one
    /// savepoint of the next shared commit: it costs what one write does, and
    /// gives what each did, in their order. A write is a statement, a job's
    /// add of a queue opened from the database, `queue.adding(&job)`, which
    /// commits with the rows and changes one job, or none when its id was
    /// taken, or an event's append of a stream opened from it,
    /// `audit.appending(name, &fields)`, written to the stream before the
    /// batch returns; see [`Write`].
    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))
    }

    /// Runs `work` in a transaction that holds the writer, for writes that
    /// depend on what its reads found: `Ok` commits, an error or a panic rolls
    /// back. It runs once. Past five seconds it rolls back and is `limit`.
    ///
    /// A bucket or a queue opened from the database joins it through
    /// `tx.with(&handle)`, so that its keys and jobs commit with the rows,
    /// and so does a stream opened from it: its events are written to the
    /// stream once the transaction commits, before this returns.
    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)
    }

    /// `tx`, its bound counted from `started`: when an awaited transaction
    /// was first polled, so that its wait in its database's line counts, as
    /// a blocking one's wait for the writer does.
    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)))
    }

    /// Passes statements to the home of the copy the database's file is, and
    /// gives what each did once this copy holds their commit.
    #[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)
    }

    /// The file the database lends to the buckets, queues, files and indexes
    /// opened from it.
    #[cfg(any(feature = "kv", feature = "jobs", feature = "blobs", feature = "search", feature = "records"))]
    pub(crate) fn shared(&self) -> &Arc<SharedFile> {
        &self.base.shared
    }

    /// `exec` without waiting: `done` is called on the thread that commits it.
    /// A copy passes it on to its home from a thread of its own, which waits
    /// for the home's answer.
    #[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)));
    }

    /// `batch` without waiting: `done` is called on the thread that commits it,
    /// or, on a copy, on the thread that waits for its home's answer.
    #[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)));
        // A stream's events move to records.db before the batch answers, and
        // the move waits for records.db's writer: on the pool, not here.
        #[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)))),
                    // a store that closed fails the move at once, which waits for nothing then
                    Err(_) => answer(Ok(ran)),
                },
                ran => answer(ran),
            }
        };
        self.base.file().submit(weight, write, answer);
    }

    /// `rows_of` without waiting for a commit: a read's rows come before this
    /// returns, and a write's once its commit ends, on the thread that
    /// commits it.
    #[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))),
        }
    }

    /// The rows of a statement known to write, once its commit ends, on the
    /// thread that commits it: `rows_then` past its read, and an awaited
    /// call's write once its read on the pool found that it writes.
    #[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)));
    }

    /// A statement's rows from a reader alone, for a connection that may not
    /// write: none when SQLite says the statement writes, or when it is not a
    /// query, since SQLite counts an ATTACH, which opens a file and stays on
    /// the shared reader, and a PRAGMA that changes the reader, as reads.
    #[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))
    }

    /// A statement's rows from a reader, or from the writer when SQLite says
    /// it writes; a statement known to write goes to the writer at once.
    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))
    }

    /// A statement's rows from a reader, or none when it writes: one known
    /// to write is not read, and one SQLite finds writes is remembered, so
    /// that the next goes to the writer at once.
    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)
            }
        }
    }

    /// Whether the database knows `statement` writes, so that a read of it
    /// goes to the writer without asking a reader first.
    pub(crate) fn known_to_write(&self, statement: &Sql) -> bool {
        self.base.writes(statement.text())
    }

    /// What names a failure of `statement`, to say it on another thread.
    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)
    }

    /// The line of the store's pool the database's transactions wait in, one
    /// at a time and in their order, whether a connection or an awaited call
    /// asked for them.
    #[cfg(any(feature = "wire", feature = "async"))]
    pub(crate) fn line(&self) -> String {
        self.base.describe()
    }

    /// The database as an error names it: `sql app`.
    #[cfg(feature = "async")]
    pub(crate) fn describe(&self) -> String {
        self.base.describe()
    }

    pub(crate) fn now(&self) -> SystemTime {
        self.base.now()
    }

    /// The store the database is open in, while it is open.
    pub(crate) fn store(&self) -> Result<Store> {
        self.base.shared.store()
    }

    /// The database's file, which a walk of its rows reads.
    pub(crate) fn file(&self) -> &crate::sqlite::File {
        self.base.file()
    }

    /// The store's memory, which the rows a call reads hold.
    pub(crate) fn memory(&self) -> &Arc<crate::Memory> {
        &self.base.memory
    }

    /// Remembers that `statement` writes, so that its next read goes to the
    /// writer at once: a walk found it does.
    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)
    }
}

/// A database's name is `[a-z0-9][a-z0-9_-]{0,63}`: lower case, so that it
/// cannot climb out of `sql/` or meet another on a file system that folds case.
fn check_name(name: &str) -> Result<()> {
    crate::text::check_name("a database's", name)
}

/// Refuses a new database whose name Windows reads as a device, on every
/// platform, so that a store's directory moves to Windows whole: there, before
/// Windows 11, `sql/nul.db` is the device NUL and not a file. A database the
/// store already holds under such a name opens, as the release that made it
/// opened it.
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"
    )))
}

/// Whether `folder`, `sql` or `local`, holds the file `<name>.db`, by the
/// folder's listing: Windows answers for a device by its name alone, and a
/// listing never shows one.
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())))
}

/// The command that takes a database back to before its drafts and applies
/// them again, as a refusal of an edited draft names it: its directory of
/// migrations where the program gave one, a stand-in where it gave the files.
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))
}

/// Whether a statement may be a query: its first word, past spaces and
/// comments, one a query begins with. A `with` begins a write too, which
/// SQLite tells when it compiles the statement.
///
/// ```text
/// "/* hourly */ with t as (select 1) select * from t"  → a query
/// "attach database 'other.db' as other"                 → not one
/// ```
#[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))
}