tinystore 0.12.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
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
//! Filters: a document's values of each filter field, kept as keys of the
//! filter's part beside its words, and the documents a search's conditions
//! pass. [`eq`], [`is_in`], [`or`] and [`and`] make conditions as `sql::eq`,
//! `sql::is_in`, `sql::or` and `sql::and` make a query's, [`range`] one of
//! numbers between two bounds, and [`missing`] one of no value.
//!
//! A value is a key's term by its type, so that the text "42" and the
//! number 42 never pass for each other, and a document with no value, no
//! such field, null or an empty list, holds the term of none, which
//! [`missing`] asks for:
//!
//! ```text
//! "shoes" → t:shoes     42, 42.0 → i:42     true → b:true     none → n:
//! ```
//!
//! A number is also kept at eight precisions, as Lucene's numeric fields
//! were: its place among all numbers as a u64 that sorts as they do, and that
//! place with its last 8, 16, … 56 bits dropped, `r0:` to `r7:`. A range is
//! then whole blocks of numbers at the coarsest precision that fits and
//! single numbers only at its edges: up to 255 keys on each side at each of
//! the seven finer precisions and 255 at the coarsest, 3,825 at most and a
//! few hundred for most ranges, which the bound on a filter's values leaves
//! out.
//!
//! A key's postings are a word's, packed and purged with them, a frequency of
//! 1 each, and the key counts the documents that hold it. A search reads every
//! posting of the keys its conditions name, the head's and the blocks', its
//! documents gone left out, and joins them: `or` and a list's values by their
//! union, `and` and a search's conditions by their intersection.

use std::collections::HashSet;
use std::ops::{Bound, RangeBounds};
use std::sync::Arc;

use rusqlite::Connection;
use rusqlite::types::Value as SqlValue;
use serde::Serialize;
use serde_json::Value;

use super::legacy;
use super::merge;
use super::score::Part;
use super::segments;
use super::settings::Settings;
use super::table::key_id;
use crate::limits::{FILTER_CONDITIONS, FILTER_ROWS, FILTER_TEXT, FILTER_VALUES};
use crate::sqlite::sql_error;
use crate::typos::meant;
use crate::{Error, Result};

/// The keys of a filter's terms, a JSON list of them, in one statement.
const FIND_KEYS: &str = "select id from _tinystore_search_keys
    where index_id = ?1 and part = ?2 and term in (select value from json_each(?3))";
/// The documents of a table's index whose rows' keys, as text, are a JSON
/// list's.
const FIND_IDS: &str = "select doc from _tinystore_search_docs
    where index_id = ?1 and id in (select value from json_each(?2))";

/// The longest text a filter keeps as a value.
pub(crate) const MOST_VALUE: usize = FILTER_TEXT.bound as usize;
/// The conditions a search holds at most, `or` and `and` counting those
/// inside them.
pub(crate) const MOST_CONDITIONS: usize = FILTER_CONDITIONS.bound as usize;
/// The values the lists of a search's conditions hold at most.
pub(crate) const MOST_VALUES: usize = FILTER_VALUES.bound as usize;
/// The rows a statement of a condition gives at most.
const MOST_ROWS: usize = FILTER_ROWS.bound as usize;
const DOCUMENTS_HAVE_NO_TABLES: &str = "a where by a statement is a table index's: an index of documents has no tables";
/// The term of no value.
const NONE: &str = "n:";
/// A number's precisions, each 8 bits coarser than the one before.
const LEVELS: u32 = 8;
const STEP: u32 = 8;

/// A condition of a search, given to [`SearchCall::filter`](super::SearchCall::filter).
#[derive(Clone, Debug)]
pub struct Condition(Node);

#[derive(Clone, Debug)]
enum Node {
    /// One of a filter's values, or one of a list of them.
    Values {
        path: String,
        values: std::result::Result<Value, String>,
        list: bool,
    },
    /// One of the values a statement's rows give.
    Rows {
        path: String,
        rows: Rows,
    },
    /// No value.
    Missing {
        path: String,
    },
    /// A number between two bounds.
    Range {
        path: String,
        low: Bound<Value>,
        high: Bound<Value>,
    },
    Or(Vec<Condition>),
    And(Vec<Condition>),
}

/// A filter equal to `value`: a document passes when it holds it, or one of
/// its list is it. Values match exactly, case and type: the text "50" is not
/// the number 50, and 42.0 is 42. `None` is `invalid`, so that an absent id
/// never asks for documents without one; [`missing`] asks for those.
pub fn eq<T: Serialize + ?Sized>(path: &str, value: &T) -> Condition {
    let values = serde_json::to_value(value).map_err(|error| error.to_string());
    Condition(Node::Values { path: path.to_owned(), values, list: false })
}

/// A filter holding one of `values`, as SQL's `in (…)`; an empty list passes
/// nothing. A search's filter holds 8 conditions and 100 values in its lists
/// at most.
///
/// For a table's index, `values` may be a statement of its database that
/// gives one column, as SQL's `in (select …)`: `is_in("id", sql!("select
/// user_id from members where course_id = ?", course))`. Its rows are read
/// in the snapshot the search reads, 100,000 at most, and count toward no
/// bound on values; on the table's key the column needs no filter.
pub fn is_in(path: &str, values: impl Values) -> Condition {
    let path = path.to_owned();
    Condition(match values.listing().0 {
        Listed::Values(values) => Node::Values { path, values, list: true },
        Listed::Rows(rows) => Node::Rows { path, rows },
    })
}

/// What [`is_in`] keeps a filter to: a list of values, `&["shoes", "boots"]`
/// or `&ids`, or for a table's index a statement of its database, `sql!(…)`.
pub trait Values {
    #[doc(hidden)]
    fn listing(self) -> Listing;
}

/// A list of values or a statement's rows, as [`is_in`] holds them.
#[doc(hidden)]
#[derive(Clone, Debug)]
pub struct Listing(Listed);

#[derive(Clone, Debug)]
enum Listed {
    Values(std::result::Result<Value, String>),
    #[cfg_attr(not(feature = "sql"), expect(dead_code, reason = "only a statement of a database makes one"))]
    Rows(Rows),
}

impl<T: Serialize> Values for &[T] {
    fn listing(self) -> Listing {
        Listing(Listed::Values(serde_json::to_value(self).map_err(|error| error.to_string())))
    }
}

impl<T: Serialize, const N: usize> Values for &[T; N] {
    fn listing(self) -> Listing {
        self.as_slice().listing()
    }
}

impl<T: Serialize> Values for &Vec<T> {
    fn listing(self) -> Listing {
        self.as_slice().listing()
    }
}

/// How a statement's rows are read on the connection of the snapshot a
/// search reads: `most` of them and one more at most, so that the search can
/// say its bound was passed. The database lends it, since a statement runs
/// as its reads run.
pub(crate) type ReadColumn = Arc<dyn Fn(&Connection, usize) -> Result<Vec<SqlValue>> + Send + Sync>;

/// A statement whose one column's values a condition holds: how an error
/// names it, and how its rows are read.
#[derive(Clone)]
pub(crate) struct Rows {
    described: String,
    read: ReadColumn,
}

impl std::fmt::Debug for Rows {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.described)
    }
}

impl Values for Listing {
    fn listing(self) -> Listing {
        self
    }
}

impl Listing {
    /// The rows of the statement `described`, which `read` reads.
    #[cfg(feature = "sql")]
    pub(crate) fn rows(described: String, read: ReadColumn) -> Listing {
        Listing(Listed::Rows(Rows { described, read }))
    }
}

/// A filter holding a number within `bounds`, any of Rust's ranges:
/// `range("price", 10..100)` holds 10 and not 100, `range("at", since..)`.
/// A document with no number there never passes. Numbers compare as f64,
/// so whole numbers past 2⁵³ compare by the nearest f64, where `eq` is
/// exact.
pub fn range<T: Serialize>(path: &str, bounds: impl RangeBounds<T>) -> Condition {
    let value = |bound: Bound<&T>| match bound {
        Bound::Included(value) => Bound::Included(serde_json::to_value(value).unwrap_or(Value::Null)),
        Bound::Excluded(value) => Bound::Excluded(serde_json::to_value(value).unwrap_or(Value::Null)),
        Bound::Unbounded => Bound::Unbounded,
    };
    Condition(Node::Range { path: path.to_owned(), low: value(bounds.start_bound()), high: value(bounds.end_bound()) })
}

/// A filter with no value: no such field, null or an empty list.
pub fn missing(path: &str) -> Condition {
    Condition(Node::Missing { path: path.to_owned() })
}

/// Any of `conditions`, in parentheses; an empty `or` passes nothing.
pub fn or(conditions: impl IntoIterator<Item = Condition>) -> Condition {
    Condition(Node::Or(conditions.into_iter().collect()))
}

/// Every one of `conditions`, for a group inside an `or`; an empty `and`
/// passes everything.
pub fn and(conditions: impl IntoIterator<Item = Condition>) -> Condition {
    Condition(Node::And(conditions.into_iter().collect()))
}

/// The conditions a search's `where` writes over the wire, each one of
///
/// ```text
/// {"eq": [path, value]}   {"in": [path, [values]]}   {"missing": path}
/// {"range": [path, {"gt" | "gte" | "lt" | "lte": number, …}]}
/// {"or": [conditions]}    {"and": [conditions]}       {"in": [path, {"statement": n}]}
/// ```
///
/// a list of them joined by and, as the Bun SDK writes its `where` object;
/// `{"statement": n}` is the `n`th of `statements`, in a list's place.
#[cfg(feature = "wire")]
pub(crate) fn from_json(text: &str, statements: &[Listing]) -> Result<Vec<Condition>> {
    let value: Value = serde_json::from_str(text).map_err(|error| Error::invalid(format!("a where: {error}")))?;
    let condition_of = |value: &Value| condition_of(value, statements);
    match value {
        Value::Array(items) => items.iter().map(condition_of).collect(),
        one => Ok(vec![condition_of(&one)?]),
    }
}

#[cfg(feature = "wire")]
fn condition_of(value: &Value, statements: &[Listing]) -> Result<Condition> {
    let refused = || Error::invalid(format!("a where's condition {value}"));
    let Some((kind, given)) = value.as_object().filter(|object| object.len() == 1).and_then(|o| o.iter().next()) else {
        return Err(refused());
    };
    let path_and = |given: &Value| -> Result<(String, Value)> {
        match given.as_array().map(Vec::as_slice) {
            Some([Value::String(path), operand]) => Ok((path.clone(), operand.clone())),
            _ => Err(refused()),
        }
    };
    match kind.as_str() {
        "eq" => path_and(given).map(|(path, operand)| eq(&path, &operand)),
        "in" => match path_and(given)? {
            (path, Value::Array(values)) => Ok(is_in(&path, &values)),
            (path, Value::Object(named)) if named.len() == 1 => {
                let at = named.get("statement").and_then(Value::as_u64).ok_or_else(refused)?;
                let statement = usize::try_from(at).ok().and_then(|at| statements.get(at)).ok_or_else(|| {
                    Error::invalid(format!("a where's statement {at}, of {} the query holds", statements.len()))
                })?;
                Ok(is_in(&path, statement.clone()))
            }
            _ => Err(refused()),
        },
        "missing" => given.as_str().map(missing).ok_or_else(refused),
        "range" => {
            let (path, bounds) = path_and(given)?;
            let bound = |strict: &str, loose: &str| match (bounds.get(strict), bounds.get(loose)) {
                (Some(value), _) => Bound::Excluded(value.clone()),
                (None, Some(value)) => Bound::Included(value.clone()),
                (None, None) => Bound::Unbounded,
            };
            Ok(Condition(Node::Range { path, low: bound("gt", "gte"), high: bound("lt", "lte") }))
        }
        "or" | "and" => {
            let parts = given.as_array().ok_or_else(refused)?.iter().map(|part| condition_of(part, statements));
            let parts: Vec<Condition> = parts.collect::<Result<_>>()?;
            Ok(if kind == "or" { or(parts) } else { and(parts) })
        }
        _ => Err(refused()),
    }
}

/// A condition as a search reads it: the keys of a filter one of which a
/// document holds, or its parts joined.
#[derive(Clone, Debug)]
pub(crate) enum Asked {
    Terms {
        path: String,
        terms: Vec<String>,
    },
    /// The values a statement's rows give, read in the search's snapshot.
    Rows {
        path: String,
        rows: Rows,
    },
    Or(Vec<Asked>),
    And(Vec<Asked>),
}

/// How many conditions and values a search's filter holds.
#[derive(Default)]
struct Counted {
    conditions: usize,
    values: usize,
}

/// The search's conditions as it reads them, within their bounds.
pub(crate) fn asked(conditions: &[Condition]) -> Result<Asked> {
    let mut counted = Counted::default();
    let asked = conditions.iter().map(|condition| condition.asked(&mut counted)).collect::<Result<Vec<_>>>()?;
    if counted.conditions > MOST_CONDITIONS {
        let refused = format!("a filter of {} conditions, past {MOST_CONDITIONS}", counted.conditions);
        return Err(FILTER_CONDITIONS.refuse(counted.conditions as u64, refused));
    }
    if counted.values > MOST_VALUES {
        let refused = format!("a filter of {} values, past {MOST_VALUES}", counted.values);
        return Err(FILTER_VALUES.refuse(counted.values as u64, refused));
    }
    Ok(Asked::And(asked))
}

impl Condition {
    fn asked(&self, counted: &mut Counted) -> Result<Asked> {
        match &self.0 {
            Node::Values { path, values, list } => {
                counted.conditions += 1;
                let values = values.as_ref().map_err(|why| Error::invalid(format!("filter {path}: {why}")))?;
                let terms = match (values, list) {
                    (Value::Array(_), false) => {
                        return Err(Error::invalid(format!("filter {path}: eq takes one value, and is_in a list")));
                    }
                    (Value::Array(items), true) => items.iter().map(|item| term(item, path)).collect::<Result<_>>()?,
                    (value, _) => vec![term(value, path)?],
                };
                counted.values += terms.len();
                Ok(Asked::Terms { path: path.clone(), terms })
            }
            Node::Range { path, low, high } => {
                counted.conditions += 1;
                Ok(Asked::Terms { path: path.clone(), terms: range_terms(path, low, high)? })
            }
            Node::Missing { path } => {
                counted.conditions += 1;
                Ok(Asked::Terms { path: path.clone(), terms: vec![NONE.to_owned()] })
            }
            Node::Rows { path, rows } => {
                counted.conditions += 1;
                Ok(Asked::Rows { path: path.clone(), rows: rows.clone() })
            }
            Node::Or(conditions) => Ok(Asked::Or(conditions.iter().map(|c| c.asked(counted)).collect::<Result<_>>()?)),
            Node::And(conditions) => {
                Ok(Asked::And(conditions.iter().map(|c| c.asked(counted)).collect::<Result<_>>()?))
            }
        }
    }
}

/// The terms a document holds at `path`: its value's, or each of its list's,
/// and the term of none where it holds none.
pub(crate) fn held(document: &Value, path: &str) -> Result<Vec<String>> {
    let values: Vec<&Value> = match at(document, path) {
        Value::Array(items) => items.iter().filter(|item| !item.is_null()).collect(),
        Value::Null => Vec::new(),
        value => vec![value],
    };
    let mut terms = Vec::with_capacity(values.len() * (1 + LEVELS as usize));
    for value in values {
        terms.push(term(value, path)?);
        if let Some(number) = value.as_f64() {
            terms.extend((0..LEVELS).map(|level| precise(level, sortable(number) >> (STEP * level))));
        }
    }
    if terms.is_empty() {
        terms.push(NONE.to_owned());
    }
    terms.sort_unstable();
    terms.dedup();
    Ok(terms)
}

/// A value's term: text, a whole number or a boolean; a number with a
/// fraction is its place at the finest precision, so that an equal one
/// passes.
fn term(value: &Value, path: &str) -> Result<String> {
    let refused =
        |what: &str| Error::invalid(format!("filter {path} holds {what}: a filter keeps text, numbers and booleans"));
    match value {
        Value::Null => Err(Error::invalid(format!(
            "filter {path}: a value of None or null; missing({path:?}) asks for a document with none"
        ))),
        Value::String(text) if text.len() > MOST_VALUE => {
            let refused = format!("filter {path} holds {} bytes of text, past {MOST_VALUE}", text.len());
            Err(FILTER_TEXT.refuse(text.len() as u64, refused))
        }
        Value::String(text) => Ok(format!("t:{text}")),
        Value::Bool(on) => Ok(format!("b:{on}")),
        Value::Number(number) => match (number.as_i64(), number.as_u64(), number.as_f64()) {
            (Some(whole), _, _) => Ok(format!("i:{whole}")),
            (None, Some(whole), _) => Ok(format!("i:{whole}")),
            (None, None, Some(float)) if float.fract() == 0.0 && float.abs() < 9.2e18 => {
                Ok(format!("i:{}", float as i64))
            }
            (None, None, Some(float)) => Ok(precise(0, sortable(float))),
            _ => Err(refused(&format!("{number}"))),
        },
        Value::Array(_) => Err(refused("a list in a list")),
        Value::Object(_) => Err(refused("an object")),
    }
}

/// A number's place among all numbers, as a u64 that sorts as they do;
/// −0 is 0.
fn sortable(number: f64) -> u64 {
    let bits = if number == 0.0 { 0.0f64.to_bits() } else { number.to_bits() };
    if bits >> 63 == 1 { !bits } else { bits | 1 << 63 }
}

/// The term of a number's place at a precision, its last `STEP × level`
/// bits dropped.
fn precise(level: u32, prefix: u64) -> String {
    format!("r{level}:{prefix:x}")
}

/// The terms whose numbers together are those within a range's bounds.
fn range_terms(path: &str, low: &Bound<Value>, high: &Bound<Value>) -> Result<Vec<String>> {
    let place = |value: &Value| match value.as_f64() {
        Some(number) if number.is_finite() => Ok(sortable(number)),
        _ => Err(Error::invalid(format!("filter {path}: a range is of numbers, not {value}"))),
    };
    let low = match low {
        Bound::Included(value) => Some(place(value)?),
        Bound::Excluded(value) => place(value)?.checked_add(1),
        Bound::Unbounded => Some(0),
    };
    let high = match high {
        Bound::Included(value) => Some(place(value)?),
        Bound::Excluded(value) => place(value)?.checked_sub(1),
        Bound::Unbounded => Some(u64::MAX),
    };
    let (Some(low), Some(high)) = (low, high) else { return Ok(Vec::new()) };
    Ok(blocks(low, high).into_iter().map(|(level, prefix)| precise(level, prefix)).collect())
}

/// The fewest prefixes whose places together are `low..=high`: at each
/// precision, the places from the edges to the next coarser block's bounds,
/// and the blocks between at the coarser one.
fn blocks(low: u64, high: u64) -> Vec<(u32, u64)> {
    let (mut low, mut high) = (u128::from(low), u128::from(high) + 1);
    let mut blocks = Vec::new();
    let mut take = |level: u32, from: u128, to: u128| {
        let shift = STEP * level;
        blocks.extend(((from >> shift)..(to >> shift)).map(|prefix| (level, prefix as u64)));
    };
    for level in 0..LEVELS {
        let coarser = 1u128 << (STEP * (level + 1));
        let (up, down) = (low.div_ceil(coarser) * coarser, high / coarser * coarser);
        if low >= high {
            break;
        }
        if level == LEVELS - 1 || up >= down {
            take(level, low, high);
            break;
        }
        take(level, low, up);
        take(level, down, high);
        (low, high) = (up, down);
    }
    blocks
}

/// The value at `path` in a document, null where it has none.
fn at<'v>(document: &'v Value, path: &str) -> &'v Value {
    let mut at = document;
    for name in path.split('.') {
        match at.get(name) {
            Some(value) => at = value,
            None => return &Value::Null,
        }
    }
    at
}

/// The documents a filter passes: every one, or these, in their order.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum Docs {
    All,
    Only(Vec<u32>),
}

/// What a search reads its conditions' documents from.
pub(crate) struct Reader<'a> {
    pub(crate) connection: &'a Connection,
    pub(crate) index: i64,
    pub(crate) settings: &'a Settings,
    pub(crate) gone: &'a HashSet<u32>,
}

impl Reader<'_> {
    /// The documents `asked` passes.
    pub(crate) fn passing(&self, asked: &Asked) -> Result<Docs> {
        match asked {
            Asked::Terms { path, terms } => self.holding(path, terms).map(Docs::Only),
            Asked::Rows { path, rows } => self.among(path, rows).map(Docs::Only),
            Asked::Or(parts) => {
                let mut passing = Docs::Only(Vec::new());
                for part in parts {
                    passing = match (passing, self.passing(part)?) {
                        (Docs::All, _) | (_, Docs::All) => return Ok(Docs::All),
                        (Docs::Only(a), Docs::Only(b)) => Docs::Only(union(&a, &b)),
                    };
                }
                Ok(passing)
            }
            Asked::And(parts) => {
                let mut passing = Docs::All;
                for part in parts {
                    passing = match (passing, self.passing(part)?) {
                        (Docs::All, other) | (other, Docs::All) => other,
                        (Docs::Only(a), Docs::Only(b)) => Docs::Only(intersection(&a, &b)),
                    };
                    if passing == Docs::Only(Vec::new()) {
                        break;
                    }
                }
                Ok(passing)
            }
        }
    }

    /// The documents that hold any of `terms` of the filter at `path`,
    /// gathered from every key and then sorted once: joining each key's into
    /// the running list would copy that list once a value, n² for n values.
    fn holding(&self, path: &str, terms: &[String]) -> Result<Vec<u32>> {
        let Some(filter) = self.settings.filter(path) else {
            let paths = self.settings.filters.iter().map(|filter| filter.path.as_str());
            let meant = meant(path, paths).map(|meant| format!("; did you mean {meant}?")).unwrap_or_default();
            return Err(Error::invalid(format!("a filter on {path}, which the index was not opened with{meant}")));
        };
        let segments = segments::of_index(self.connection, self.index)?;
        let mut holding = Vec::new();
        for key in self.keys(Part::filter(filter.number), terms)? {
            holding.extend(self.docs_of(key, &segments)?);
        }
        Ok(self.sorted(holding))
    }

    /// The documents whose `path` holds one of the values a statement's rows
    /// give, read in this snapshot: on the table's key by the rows' ids in
    /// one statement, and on a filter as a list's values are.
    fn among(&self, path: &str, rows: &Rows) -> Result<Vec<u32>> {
        let Some(table) = &self.settings.table else { return Err(Error::invalid(DOCUMENTS_HAVE_NO_TABLES)) };
        let within = |error: Error| error.within(format!("filter {path}: {}", rows.described));
        let values = (rows.read)(self.connection, MOST_ROWS).map_err(within)?;
        if values.len() > MOST_ROWS {
            let refused = format!("filter {path}: a statement of more than {MOST_ROWS} rows");
            return Err(FILTER_ROWS.refuse(values.len() as u64, refused));
        }
        if table.key == [path] {
            return self.keyed(&values);
        }
        let values = values.into_iter().filter_map(|value| value_of(value, path).transpose());
        let terms = values.map(|value| term(&value?, path)).collect::<Result<Vec<_>>>()?;
        self.holding(path, &terms)
    }

    /// The documents of the rows keyed by `keys`; a key of no row passes none.
    fn keyed(&self, keys: &[SqlValue]) -> Result<Vec<u32>> {
        let ids: Vec<String> = keys.iter().filter_map(|key| key_id(key).ok()).collect();
        let ids = Value::from(ids).to_string();
        let failed = |error| sql_error("find the rows of a where's statement", error);
        let mut select = self.connection.prepare_cached(FIND_IDS).map_err(failed)?;
        let docs = select.query_map((self.index, ids), |row| row.get(0));
        Ok(self.sorted(docs.and_then(Iterator::collect).map_err(failed)?))
    }

    /// Documents in their order, each once, those gone left out.
    fn sorted(&self, mut docs: Vec<u32>) -> Vec<u32> {
        docs.sort_unstable();
        docs.dedup();
        docs.retain(|doc| !self.gone.contains(doc));
        docs
    }

    /// A term as the index keeps it: a table's rows hold a boolean as SQLite
    /// does, the integer 1 or 0, so that `eq("done", &true)` passes them.
    fn as_kept<'t>(&self, term: &'t str) -> &'t str {
        match term {
            "b:true" if self.settings.table.is_some() => "i:1",
            "b:false" if self.settings.table.is_some() => "i:0",
            term => term,
        }
    }

    /// The keys of `part` the index holds of `terms`, in one statement.
    fn keys(&self, part: Part, terms: &[String]) -> Result<Vec<i64>> {
        let kept: Vec<&str> = terms.iter().map(|term| self.as_kept(term)).collect();
        let failed = |error| sql_error("find a filter's values", error);
        let mut select = self.connection.prepare_cached(FIND_KEYS).map_err(failed)?;
        let keys = select.query_map((self.index, part.0, Value::from(kept).to_string()), |row| row.get(0));
        keys.and_then(Iterator::collect).map_err(failed)
    }

    /// Every document a key's postings hold, gone ones too, in order: a list
    /// a release before 0002 wrote, then its pieces in `segments`.
    fn docs_of(&self, key: i64, segments: &[segments::Segment]) -> Result<Vec<u32>> {
        let within = |error: Error| error.within(format!("key {key}"));
        let mut docs = legacy::documents(self.connection, self.index, key).map_err(within)?;
        for segment in segments {
            if let Some((_, piece)) = segments::piece(self.connection, segment, key).map_err(within)? {
                docs.extend(merge::documents(self.connection, &piece).map_err(within)?);
            }
        }
        if !docs.is_sorted_by(|a, b| a < b) {
            return Err(Error::corrupt(format!("key {key}'s documents are out of their order")));
        }
        Ok(docs)
    }
}

/// A value a statement's row gives as a filter's term reads it: none for a
/// null, which passes nothing, as `in (select …)` passes nothing for one.
fn value_of(value: SqlValue, path: &str) -> Result<Option<Value>> {
    match value {
        SqlValue::Null => Ok(None),
        SqlValue::Integer(number) => Ok(Some(Value::from(number))),
        SqlValue::Real(number) => Ok(Some(Value::from(number))),
        SqlValue::Text(text) => Ok(Some(Value::String(text))),
        SqlValue::Blob(_) => {
            Err(Error::invalid(format!("filter {path} holds a blob: a filter keeps text, numbers and booleans")))
        }
    }
}

/// The documents of either list, each once, in order.
fn union(a: &[u32], b: &[u32]) -> Vec<u32> {
    let mut joined = Vec::with_capacity(a.len() + b.len());
    let (mut i, mut j) = (0, 0);
    loop {
        let next = match (a.get(i), b.get(j)) {
            (Some(x), Some(y)) => *x.min(y),
            (Some(x), None) => *x,
            (None, Some(y)) => *y,
            (None, None) => return joined,
        };
        joined.push(next);
        i += usize::from(a.get(i) == Some(&next));
        j += usize::from(b.get(j) == Some(&next));
    }
}

/// The documents of both lists, in order.
fn intersection(a: &[u32], b: &[u32]) -> Vec<u32> {
    let mut both = Vec::with_capacity(a.len().min(b.len()));
    let (mut i, mut j) = (0, 0);
    while let (Some(x), Some(y)) = (a.get(i), b.get(j)) {
        match x.cmp(y) {
            std::cmp::Ordering::Less => i += 1,
            std::cmp::Ordering::Greater => j += 1,
            std::cmp::Ordering::Equal => {
                both.push(*x);
                (i, j) = (i + 1, j + 1);
            }
        }
    }
    both
}

#[cfg(test)]
#[path = "filter_tests.rs"]
mod tests;