picovolt 2.2.0

Embedded SQL database with MVCC history and single-file deployment
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
//! Best-effort import of a SQL dump (such as the output of `sqlite3 mydb .dump`)
//! into PicoVolt.
//!
//! PicoVolt's SQL is a subset, so the importer rewrites what it can and skips
//! the rest rather than aborting: `CREATE TABLE` is reduced to column names
//! (types and constraints are dropped, since PicoVolt tables are untyped),
//! quoted identifiers are preserved, and statement kinds the engine does not
//! support (PRAGMA, transactions, triggers, views, indexes, ALTER, ATTACH) are
//! skipped with a reason. Each statement that does run is reported, and a
//! statement that errors is collected rather than stopping the import.
//! Incomplete quotes, block comments or compound triggers reject the complete
//! dump before execution; this prevents a fragment from being run separately.

use crate::Database;

/// The outcome of [`Database::import_sql`].
#[derive(Debug, Default, Clone, PartialEq)]
pub struct ImportReport {
    /// Number of statements executed successfully.
    pub executed: usize,
    /// Statements intentionally skipped, each as "reason: statement preview".
    pub skipped: Vec<String>,
    /// Statements that failed, each as "error: statement preview".
    pub errors: Vec<String>,
}

impl Database {
    /// Import a SQL dump, returning an [`ImportReport`]. See the module docs for
    /// the rewriting and skipping rules.
    pub fn import_sql(&mut self, dump: &str) -> ImportReport {
        let mut report = ImportReport::default();
        let statements = match split_statements(dump) {
            Ok(statements) => statements,
            Err(error) => {
                report.errors.push(error);
                return report;
            }
        };
        for raw in statements {
            let stmt = raw.trim();
            if stmt.is_empty() {
                continue;
            }
            match rewrite_statement(stmt) {
                Rewrite::Run(sql) => match self.query(&sql) {
                    Ok(_) => report.executed += 1,
                    Err(e) => report.errors.push(format!("{e}: {}", preview(stmt))),
                },
                Rewrite::Skip(reason) => {
                    report.skipped.push(format!("{reason}: {}", preview(stmt)))
                }
            }
        }
        report
    }
}

enum Rewrite {
    Run(String),
    Skip(String),
}

fn preview(s: &str) -> String {
    let one: String = s.split_whitespace().collect::<Vec<_>>().join(" ");
    if one.chars().count() > 60 {
        format!("{}...", one.chars().take(60).collect::<String>())
    } else {
        one
    }
}

fn rewrite_statement(stmt: &str) -> Rewrite {
    if is_trigger(stmt) {
        return Rewrite::Skip("triggers not supported".to_string());
    }
    let upper = stmt.to_ascii_uppercase();
    for (kw, reason) in [
        ("PRAGMA", "pragma not supported"),
        ("BEGIN", "transactions not supported"),
        ("COMMIT", "transactions not supported"),
        ("ROLLBACK", "transactions not supported"),
        ("SAVEPOINT", "transactions not supported"),
        ("RELEASE", "transactions not supported"),
        ("CREATE TRIGGER", "triggers not supported"),
        ("CREATE VIEW", "views not supported"),
        ("CREATE INDEX", "dump index skipped"),
        ("CREATE UNIQUE INDEX", "dump index skipped"),
        ("ALTER", "ALTER not supported"),
        ("ATTACH", "ATTACH not supported"),
        ("DETACH", "DETACH not supported"),
        ("ANALYZE", "ANALYZE not supported"),
    ] {
        if upper.starts_with(kw) {
            return Rewrite::Skip(reason.to_string());
        }
    }
    if upper == "END" {
        return Rewrite::Skip("transactions not supported".to_string());
    }
    if upper.starts_with("CREATE TABLE") {
        return match rewrite_create_table(stmt) {
            Some(sql) => Rewrite::Run(sql),
            None => Rewrite::Skip("could not parse CREATE TABLE".to_string()),
        };
    }
    // INSERT/UPDATE/DELETE/DROP and plain statements pass through (identifiers
    // were already unquoted by the caller).
    Rewrite::Run(stmt.to_string())
}

/// `CREATE TABLE [IF NOT EXISTS] name (col TYPE constraints, ..., table-constraint)`
/// becomes `CREATE TABLE name (col, ...)`.
fn rewrite_create_table(stmt: &str) -> Option<String> {
    let open = first_unquoted_paren(stmt)?;
    let name = create_table_name(&stmt[..open])?;
    let close = matching_paren(stmt, open)?;
    let body = &stmt[open + 1..close];
    let cols = column_names(body);
    if cols.is_empty() {
        return None;
    }
    Some(format!("CREATE TABLE {} ({})", name, cols.join(", ")))
}

fn column_names(body: &str) -> Vec<String> {
    let mut cols = Vec::new();
    for item in split_top_level_commas(body) {
        let item = item.trim();
        if let Some((name, quoted, _)) = first_identifier(item) {
            let keyword = name.to_ascii_uppercase();
            if !quoted
                && matches!(
                    keyword.as_str(),
                    "PRIMARY" | "FOREIGN" | "UNIQUE" | "CHECK" | "CONSTRAINT" | "KEY"
                )
            {
                continue; // a table-level constraint, not a column definition
            }
            cols.push(name);
        }
    }
    cols
}

/// Return the first identifier as SQL source, whether it was delimited, and the
/// byte offset immediately after it. Keeping the delimiters means a quoted
/// keyword remains an identifier when the rewritten statement is parsed.
fn first_identifier(s: &str) -> Option<(String, bool, usize)> {
    let trimmed = s.trim_start();
    let leading = s.len() - trimmed.len();
    let mut chars = trimmed.char_indices().peekable();
    let (_, first) = chars.next()?;
    if let Some(closing) = quote_closing(first) {
        let mut has_content = false;
        while let Some((index, ch)) = chars.next() {
            if ch == closing {
                if chars.peek().is_some_and(|(_, next)| *next == closing) {
                    chars.next();
                    has_content = true;
                    continue;
                }
                if !has_content {
                    return None;
                }
                let end = index + ch.len_utf8();
                return Some((trimmed[..end].to_owned(), true, leading + end));
            }
            has_content = true;
        }
        None
    } else {
        if !(first.is_alphabetic() || first == '_') {
            return None;
        }
        let end = trimmed
            .char_indices()
            .take_while(|(_, ch)| ch.is_alphanumeric() || *ch == '_')
            .map(|(index, ch)| index + ch.len_utf8())
            .last()?;
        Some((trimmed[..end].to_owned(), false, leading + end))
    }
}

fn create_table_name(head: &str) -> Option<String> {
    let mut rest = strip_keyword(head, "CREATE")?;
    rest = strip_keyword(rest, "TABLE")?;
    if starts_keyword(rest, "IF") {
        rest = strip_keyword(rest, "IF")?;
        rest = strip_keyword(rest, "NOT")?;
        rest = strip_keyword(rest, "EXISTS")?;
    }
    let (name, _, consumed) = first_identifier(rest)?;
    if !rest[consumed..].trim().is_empty() {
        return None;
    }
    Some(name)
}

fn starts_keyword(input: &str, keyword: &str) -> bool {
    strip_keyword(input, keyword).is_some()
}

fn strip_keyword<'a>(input: &'a str, keyword: &str) -> Option<&'a str> {
    let trimmed = input.trim_start();
    let prefix = trimmed.get(..keyword.len())?;
    if !prefix.eq_ignore_ascii_case(keyword) {
        return None;
    }
    let rest = &trimmed[keyword.len()..];
    if rest
        .chars()
        .next()
        .is_some_and(|ch| ch.is_alphanumeric() || ch == '_')
    {
        return None;
    }
    Some(rest)
}

fn quote_closing(opening: char) -> Option<char> {
    match opening {
        '\'' => Some('\''),
        '"' => Some('"'),
        '`' => Some('`'),
        '[' => Some(']'),
        _ => None,
    }
}

fn first_unquoted_paren(sql: &str) -> Option<usize> {
    let mut quoted = None;
    let mut chars = sql.char_indices().peekable();
    while let Some((index, ch)) = chars.next() {
        if let Some(closing) = quoted {
            if ch == closing {
                if chars.peek().is_some_and(|(_, next)| *next == closing) {
                    chars.next();
                } else {
                    quoted = None;
                }
            }
        } else if let Some(closing) = quote_closing(ch) {
            quoted = Some(closing);
        } else if ch == '(' {
            return Some(index);
        }
    }
    None
}

fn is_trigger(sql: &str) -> bool {
    let Some(rest) = strip_keyword(sql, "CREATE") else {
        return false;
    };
    let rest = strip_keyword(rest, "TEMPORARY")
        .or_else(|| strip_keyword(rest, "TEMP"))
        .unwrap_or(rest);
    starts_keyword(rest, "TRIGGER")
}

// Preflight the entire dump before executing anything. Unsupported compound
// statements must remain indivisible, including when they are incomplete.
fn split_statements(sql: &str) -> Result<Vec<String>, String> {
    let mut out = Vec::new();
    let mut cur = String::new();
    let mut quoted = None;
    let mut trigger = false;
    let mut body_started = false;
    let mut depth = 0usize;
    let mut chars = sql.chars().peekable();
    while let Some(c) = chars.next() {
        if let Some(closing) = quoted {
            cur.push(c);
            if c == closing {
                if chars.peek() == Some(&closing) {
                    cur.push(closing);
                    chars.next();
                } else {
                    quoted = None;
                }
            }
        } else if c == '-' && chars.peek() == Some(&'-') {
            chars.next();
            for next in chars.by_ref() {
                if next == '\n' {
                    break;
                }
            }
            cur.push(' ');
        } else if c == '/' && chars.peek() == Some(&'*') {
            chars.next();
            let mut closed = false;
            while let Some(next) = chars.next() {
                if next == '*' && chars.peek() == Some(&'/') {
                    chars.next();
                    closed = true;
                    break;
                }
            }
            if !closed {
                return Err("unterminated SQL comment; no statements imported".into());
            }
            cur.push(' ');
        } else if let Some(closing) = quote_closing(c) {
            quoted = Some(closing);
            cur.push(c);
        } else if c.is_alphabetic() || c == '_' {
            let mut word = String::from(c);
            while chars
                .peek()
                .is_some_and(|ch| ch.is_alphanumeric() || *ch == '_')
            {
                word.push(chars.next().expect("peeked"));
            }
            cur.push_str(&word);
            trigger |= is_trigger(&cur);
            if trigger {
                match word.to_ascii_uppercase().as_str() {
                    "BEGIN" => {
                        body_started = true;
                        depth += 1;
                    }
                    "CASE" if body_started => depth += 1,
                    "END" if depth > 0 => depth -= 1,
                    _ => (),
                }
            }
        } else if c == ';' {
            if trigger && (!body_started || depth > 0) {
                cur.push(c);
            } else {
                out.push(std::mem::take(&mut cur));
                trigger = false;
                body_started = false;
            }
        } else {
            cur.push(c);
        }
    }
    if quoted.is_some() || (trigger && (!body_started || depth > 0)) {
        return Err("unterminated SQL quote or trigger; no statements imported".into());
    }
    if !cur.trim().is_empty() {
        out.push(cur);
    }
    Ok(out)
}

fn split_top_level_commas(body: &str) -> Vec<String> {
    let mut items = Vec::new();
    let mut cur = String::new();
    let mut depth = 0i32;
    let mut quoted = None;
    let mut chars = body.chars().peekable();
    while let Some(c) = chars.next() {
        if let Some(closing) = quoted {
            cur.push(c);
            if c == closing {
                if chars.peek() == Some(&closing) {
                    cur.push(closing);
                    chars.next();
                } else {
                    quoted = None;
                }
            }
        } else {
            match c {
                ch if quote_closing(ch).is_some() => {
                    quoted = quote_closing(ch);
                    cur.push(c);
                }
                '(' => {
                    depth += 1;
                    cur.push(c);
                }
                ')' => {
                    depth -= 1;
                    cur.push(c);
                }
                ',' if depth == 0 => items.push(std::mem::take(&mut cur)),
                _ => cur.push(c),
            }
        }
    }
    if !cur.trim().is_empty() {
        items.push(cur);
    }
    items
}

fn matching_paren(s: &str, open: usize) -> Option<usize> {
    let mut depth = 0i32;
    let mut quoted = None;
    let mut chars = s
        .char_indices()
        .skip_while(|(index, _)| *index < open)
        .peekable();
    while let Some((i, c)) = chars.next() {
        if let Some(closing) = quoted {
            if c == closing {
                if chars.peek().is_some_and(|(_, next)| *next == closing) {
                    chars.next();
                } else {
                    quoted = None;
                }
            }
        } else if let Some(closing) = quote_closing(c) {
            quoted = Some(closing);
        } else if c == '(' {
            depth += 1;
        } else if c == ')' {
            depth -= 1;
            if depth == 0 {
                return Some(i);
            }
        }
    }
    None
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::value::Value;

    #[test]
    fn imports_a_sqlite_style_dump() {
        let dump = r#"
PRAGMA foreign_keys=OFF;
BEGIN TRANSACTION;
CREATE TABLE "users" (
  "id" INTEGER PRIMARY KEY AUTOINCREMENT,
  "name" TEXT NOT NULL DEFAULT 'anon',
  "score" REAL,
  UNIQUE("name")
);
INSERT INTO "users" VALUES(1,'alice',9.5);
INSERT INTO "users" VALUES(2,'o''brien',3.0);
CREATE INDEX idx_name ON users(name);
CREATE TRIGGER t AFTER INSERT ON users BEGIN SELECT 1; END;
COMMIT;
"#;
        let mut db = Database::open_memory();
        let report = db.import_sql(dump);
        assert_eq!(report.executed, 3, "create + 2 inserts: {report:?}");
        assert!(report.errors.is_empty(), "{report:?}");
        // pragma, begin, index, trigger, commit are skipped.
        assert!(report.skipped.len() >= 4, "{report:?}");

        let rows = db
            .query("SELECT id, name FROM users ORDER BY id")
            .unwrap()
            .rows()
            .unwrap()
            .to_vec();
        assert_eq!(
            rows,
            vec![
                vec![Value::Int(1), Value::Text("alice".into())],
                vec![Value::Int(2), Value::Text("o'brien".into())],
            ]
        );
    }
}