tinystore 0.11.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
//! The pieces a query's conditions are made of, each a piece of SQL with its
//! values, and the lexing that keeps them apart: a `?` counted outside quotes
//! and comments, an `and` or an `or` that would bind with a neighbour's.
//!
//! The Bun SDK's `sql` helpers write the same pieces; testdata/sql/queries.json
//! holds both to the same text.

use serde::Serialize;

use super::statement::Sql;
use super::values::{Value, to_value};

/// Conditions joined with `or`, in parentheses; an empty `or` finds nothing.
pub fn or<I>(conditions: I) -> Sql
where
    I: IntoIterator,
    I::Item: Into<Sql>,
{
    group(conditions, "or", "0")
}

/// Conditions joined with `and`, in parentheses, for a group inside an `or`;
/// an empty `and` finds everything.
pub fn and<I>(conditions: I) -> Sql
where
    I: IntoIterator,
    I::Item: Into<Sql>,
{
    group(conditions, "and", "1")
}

/// A column equal to a value, its name quoted; `None` is `is null`.
pub fn eq<T: Serialize + ?Sized>(column: &str, value: &T) -> Sql {
    let column = match quote(column) {
        Ok(column) => column,
        Err(why) => return Sql::refused(why),
    };
    match to_value(value) {
        Ok(Value::Null) => Sql::piece(format!("{column} is null"), Vec::new(), true),
        Ok(value) => Sql::piece(format!("{column} = ?"), vec![value], true),
        Err(why) => Sql::refused(format!("{column}: {why}")),
    }
}

/// A column holding one of `values`: `in (…)`, written as one value SQLite
/// reads with `json_each`, so a list of any length is the same statement and
/// an empty one finds nothing.
pub fn is_in<T: Serialize>(column: &str, values: &[T]) -> Sql {
    let column = match quote(column) {
        Ok(column) => column,
        Err(why) => return Sql::refused(why),
    };
    let listed = list(values);
    let (text, values, refused) = listed.into_parts();
    match refused {
        Some(why) => Sql::refused(why),
        None => Sql::piece(format!("{column} in {text}"), values, true),
    }
}

/// A list for `in (…)`, as one JSON value SQLite reads with `json_each`.
pub fn list<T: Serialize>(values: &[T]) -> Sql {
    match serde_json::to_string(values) {
        Ok(json) => Sql::piece("(select value from json_each(?))".to_owned(), vec![Value::Text(json)], false),
        Err(error) => Sql::refused(format!("a list's JSON: {error}")),
    }
}

/// A value kept as its JSON.
pub fn json<T: Serialize + ?Sized>(value: &T) -> Sql {
    match serde_json::to_string(value) {
        Ok(json) => Sql::piece("?".to_owned(), vec![Value::Text(json)], true),
        Err(error) => Sql::refused(format!("a value's JSON: {error}")),
    }
}

/// A name, quoted, never SQL: a column a request chooses.
pub fn ident(name: &str) -> Sql {
    match quote(name) {
        Ok(quoted) => Sql::piece(quoted, Vec::new(), true),
        Err(why) => Sql::refused(why),
    }
}

/// A JSON list in `column` holding `value`.
pub fn has<T: Serialize + ?Sized>(column: &str, value: &T) -> Sql {
    let column = match quote(column) {
        Ok(column) => column,
        Err(why) => return Sql::refused(why),
    };
    match to_value(value) {
        Ok(value) => {
            Sql::piece(format!("exists (select 1 from json_each({column}) where value = ?)"), vec![value], false)
        }
        Err(why) => Sql::refused(format!("{column}'s value: {why}")),
    }
}

/// A value as a piece of SQL, for a column an update sets.
pub fn value<T: Serialize + ?Sized>(value: &T) -> Sql {
    match to_value(value) {
        Ok(value) => Sql::piece("?".to_owned(), vec![value], true),
        Err(why) => Sql::refused(why),
    }
}

fn group<I>(conditions: I, joiner: &str, empty: &str) -> Sql
where
    I: IntoIterator,
    I::Item: Into<Sql>,
{
    let pieces: Vec<Sql> = conditions.into_iter().map(|condition| checked(condition.into())).collect();
    if pieces.is_empty() {
        return Sql::piece(empty.to_owned(), Vec::new(), false);
    }
    let joined = joined_with(pieces, joiner);
    let (text, values, refused) = joined.into_parts();
    match refused {
        Some(why) => Sql::refused(why),
        None => Sql::piece(format!("({text})"), values, false),
    }
}

/// A piece whose values are as many as its `?`s, counted outside quotes and
/// comments, and which names none; another is refused, since it would shift
/// the values of the pieces after it.
///
/// What the builder writes after a piece, an `and`, a `)`, a `desc` or a
/// `where`, must stay SQL: a piece that ends inside a `--` comment gets the
/// newline that ends it, and one that ends inside a `/*` comment, which only
/// a `*/` ends, is refused.
pub(crate) fn checked(piece: Sql) -> Sql {
    if piece.why_refused().is_some() {
        return piece;
    }
    let counted = placeholders(piece.text());
    if !counted.named.is_empty() || counted.numbered {
        return Sql::refused(format!("a piece of SQL takes its values at ? alone: {}", piece.text()));
    }
    if counted.positional != piece.values().len() {
        return Sql::refused(format!(
            "{} placeholders and {} values: each ? takes one value",
            counted.positional,
            piece.values().len()
        ));
    }
    match comment_at_end(piece.text()) {
        Some(Comment::Line) => {
            let bare = piece.is_bare();
            let (text, values, _) = piece.into_parts();
            Sql::piece(format!("{text}\n"), values, bare)
        }
        Some(Comment::Block) => Sql::refused(format!(
            "a piece of SQL ends inside a /* comment, which would hide what the query writes after it: {}",
            piece.text()
        )),
        None => piece,
    }
}

/// A comment a piece's text ends inside.
#[derive(Debug, PartialEq, Eq)]
enum Comment {
    /// `--`, which a newline ends.
    Line,
    /// `/*` with no `*/` after it.
    Block,
}

/// The comment `text` ends inside, outside quotes and brackets, if it ends
/// inside one: `a = 1 -- why` ends inside a line comment.
fn comment_at_end(text: &str) -> Option<Comment> {
    let chars: Vec<char> = text.chars().collect();
    let mut at = 0;
    while at < chars.len() {
        let end = match chars[at] {
            '[' => Some(find(&chars, at + 1, &[']']).unwrap_or(chars.len())),
            _ => quoted_or_comment_end(&chars, at),
        };
        match end {
            Some(end) if end >= chars.len() => {
                return match chars[at] {
                    '-' => Some(Comment::Line),
                    '/' => Some(Comment::Block),
                    _ => None,
                };
            }
            Some(end) => at = end + 1,
            None => at += 1,
        }
    }
    None
}

/// Pieces joined with `and` or `or`, each in parentheses unless it stands
/// alone; the first refused piece refuses them all.
pub(crate) fn joined_with(pieces: Vec<Sql>, joiner: &str) -> Sql {
    let several = pieces.len() > 1;
    let mut texts = Vec::with_capacity(pieces.len());
    let mut values = Vec::new();
    for piece in pieces {
        let wrapped = several && !piece.is_bare() && !stands_alone(piece.text());
        let (text, piece_values, refused) = piece.into_parts();
        if let Some(why) = refused {
            return Sql::refused(why);
        }
        texts.push(if wrapped { format!("({text})") } else { text });
        values.extend(piece_values);
    }
    Sql::piece(texts.join(&format!(" {joiner} ")), values, false)
}

/// A name as SQL quotes it: `"u"."created_at"`, each part on its own.
pub(crate) fn quote(name: &str) -> Result<String, String> {
    if name.is_empty() || name.contains('\0') {
        return Err(format!("the name {name:?}: a name is text without NUL"));
    }
    Ok(name.split('.').map(crate::sqlite::quote_ident).collect::<Vec<_>>().join("."))
}

/// Each of `names` as SQL quotes it, or why one cannot be a name.
pub(crate) fn quote_all<S: AsRef<str>>(names: &[S]) -> crate::Result<Vec<String>> {
    names.iter().map(|name| quote(name.as_ref())).collect::<Result<_, _>>().map_err(crate::Error::invalid)
}

/// What a text's placeholders are, outside quotes and comments.
#[derive(Debug, Default, PartialEq, Eq)]
pub(crate) struct Counted {
    pub(crate) positional: usize,
    pub(crate) named: Vec<String>,
    pub(crate) numbered: bool,
}

pub(crate) fn placeholders(text: &str) -> Counted {
    let mut counted = Counted::default();
    let chars: Vec<char> = text.chars().collect();
    let mut at = 0;
    while at < chars.len() {
        if let Some(end) = quoted_or_comment_end(&chars, at) {
            at = end + 1;
            continue;
        }
        match chars[at] {
            '[' => at = find(&chars, at + 1, &[']']).unwrap_or(chars.len()),
            '?' if chars.get(at + 1).is_some_and(char::is_ascii_digit) => counted.numbered = true,
            '?' => counted.positional += 1,
            ':' | '@' | '$' if chars.get(at + 1).is_some_and(|next| next.is_ascii_alphabetic() || *next == '_') => {
                let name: String =
                    chars[at + 1..].iter().take_while(|c| c.is_ascii_alphanumeric() || **c == '_').collect();
                at += name.chars().count();
                if !counted.named.contains(&name) {
                    counted.named.push(name);
                }
            }
            _ => {}
        }
        at += 1;
    }
    counted
}

/// Where the quoted text or the comment that begins at `at` ends, when one
/// begins there: what is inside it is no placeholder and no word of SQL.
fn quoted_or_comment_end(chars: &[char], at: usize) -> Option<usize> {
    match chars[at] {
        quote @ ('\'' | '"' | '`') => Some(closing(chars, at, quote)),
        '-' if chars.get(at + 1) == Some(&'-') => Some(find(chars, at, &['\n']).unwrap_or(chars.len())),
        '/' if chars.get(at + 1) == Some(&'*') => Some(find_pair(chars, at + 2).map_or(chars.len(), |end| end + 1)),
        _ => None,
    }
}

/// Whether a piece keeps its meaning beside others in an `and` or an `or`:
/// one group, or text with no `and` or `or` of its own outside quotes,
/// comments and parentheses, which would bind with its neighbours'.
pub(crate) fn stands_alone(text: &str) -> bool {
    if grouped(text) {
        return true;
    }
    let chars: Vec<char> = text.chars().collect();
    let mut depth = 0i32;
    let mut at = 0;
    while at < chars.len() {
        if let Some(end) = quoted_or_comment_end(&chars, at) {
            at = end + 1;
            continue;
        }
        match chars[at] {
            '(' => depth += 1,
            ')' => depth -= 1,
            c if depth == 0
                && c.is_ascii_alphabetic()
                && !word_char(at.checked_sub(1).and_then(|at| chars.get(at))) =>
            {
                let word: String =
                    chars[at..].iter().take_while(|c| c.is_ascii_alphanumeric() || **c == '_' || **c == '$').collect();
                if word.eq_ignore_ascii_case("and") || word.eq_ignore_ascii_case("or") {
                    return false;
                }
                at += word.chars().count() - 1;
            }
            _ => {}
        }
        at += 1;
    }
    true
}

/// Whether text is one group in parentheses, or a bare `0` or `1`.
pub(crate) fn grouped(text: &str) -> bool {
    if !text.starts_with('(') || !text.ends_with(')') {
        return text == "0" || text == "1";
    }
    // A parenthesis inside quotes or a comment counts for nothing: `('(') or
    // ('x')` is two groups, not one.
    let chars: Vec<char> = text.chars().collect();
    let (mut depth, mut at) = (0i32, 0);
    while at < chars.len() {
        if let Some(end) = quoted_or_comment_end(&chars, at) {
            at = end + 1;
            continue;
        }
        match chars[at] {
            '(' => depth += 1,
            ')' => depth -= 1,
            _ => {}
        }
        if depth == 0 && at < chars.len() - 1 {
            return false;
        }
        at += 1;
    }
    depth == 0
}

fn word_char(c: Option<&char>) -> bool {
    c.is_some_and(|c| c.is_ascii_alphanumeric() || *c == '_' || *c == '$')
}

/// The index of a quoted run's closing quote, a doubled quote inside kept.
fn closing(chars: &[char], at: usize, quote: char) -> usize {
    let mut next = at + 1;
    while next < chars.len() {
        if chars[next] == quote {
            if chars.get(next + 1) == Some(&quote) {
                next += 2;
                continue;
            }
            return next;
        }
        next += 1;
    }
    chars.len()
}

fn find(chars: &[char], from: usize, any: &[char]) -> Option<usize> {
    chars.get(from..)?.iter().position(|c| any.contains(c)).map(|at| from + at)
}

/// The index of the `*` of the `*/` that closes a comment.
fn find_pair(chars: &[char], from: usize) -> Option<usize> {
    (from..chars.len().saturating_sub(1)).find(|&at| chars[at] == '*' && chars[at + 1] == '/')
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn a_question_mark_in_a_string_or_a_comment_is_no_placeholder() {
        let counted = placeholders("a = ? and b = '?' -- why?\n and c = :c and d = ?3 /* ? */");
        assert_eq!(counted, Counted { positional: 1, named: vec!["c".to_owned()], numbered: true });
    }

    #[test]
    fn a_piece_with_an_and_or_an_or_of_its_own_does_not_stand_alone() {
        assert!(stands_alone("amount >= ?"));
        assert!(stands_alone("(a or b)"));
        assert!(stands_alone("title = 'this or that'"));
        assert!(stands_alone("lower(a) = ? -- and"));
        assert!(!stands_alone("a = 1 or b = 2"));
        assert!(!stands_alone("total between ? and ?"));
        assert!(!stands_alone("(a) or (b)"));
        assert!(!stands_alone("('(') or ('x')"), "a parenthesis in quotes opens nothing");
        assert!(stands_alone("(title = ')')"));
    }

    #[test]
    fn a_piece_that_ends_inside_a_comment_ends_at_a_newline_or_is_refused() {
        assert_eq!(comment_at_end("a = 1 -- why"), Some(Comment::Line));
        assert_eq!(comment_at_end("a = 1 -- a /* inside"), Some(Comment::Line));
        assert_eq!(comment_at_end("a = 1 /* open"), Some(Comment::Block));
        assert_eq!(comment_at_end("a = 1 /*/"), Some(Comment::Block));
        assert_eq!(comment_at_end("a = 1 /* a -- inside"), Some(Comment::Block));
        for closed in ["a = 1 -- why\n", "a = 1 /* why */", "a = '--' and b = '/*'", "[c--d] = 1", "a - 1 / 2"] {
            assert_eq!(comment_at_end(closed), None, "{closed:?}");
        }
        assert_eq!(checked(Sql::new("a = 1 -- why")).text(), "a = 1 -- why\n");
        assert_eq!(checked(Sql::new("a = 1 -- why\n")).text(), "a = 1 -- why\n", "an ended comment stays");
        let refused = checked(Sql::new("a = 1 /* open"));
        assert!(refused.why_refused().is_some_and(|why| why.contains("ends inside a /* comment")), "{refused:?}");
    }
}