rhiza-sql 0.2.0

SQLite materialized state machine for rhiza
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
use rhiza_core::{EntryType, LogEntry, LogHash};
use rhiza_sql::{
    encode_sql_command, restore_snapshot_file, sql_executor_fingerprint, Error, SqlBatchMember,
    SqlCommand, SqlStatement, SqlValue, SqliteStateMachine,
};
use rusqlite::Connection;

fn apply_command(
    db: &SqliteStateMachine,
    command: &SqlCommand,
    index: u64,
    prev_hash: LogHash,
) -> LogHash {
    let request = encode_sql_command(command).unwrap();
    let preparation = db
        .prepare_sql_batch_effect(
            &[SqlBatchMember {
                command,
                request_payload: &request,
            }],
            index - 1,
            prev_hash,
        )
        .unwrap();
    preparation.results.into_iter().next().unwrap().unwrap();
    let effect = preparation.effect.unwrap();
    let hash = LogEntry::calculate_hash(
        "cluster-a",
        1,
        1,
        index,
        EntryType::Command,
        prev_hash,
        &effect,
    );
    db.apply_entry(&LogEntry {
        cluster_id: "cluster-a".into(),
        epoch: 1,
        config_id: 1,
        index,
        entry_type: EntryType::Command,
        payload: effect,
        prev_hash,
        hash,
    })
    .unwrap();
    hash
}

#[test]
fn qsql_v2_rejects_a_mismatched_executor_fingerprint_before_preparation() {
    let dir = tempfile::tempdir().unwrap();
    let db = SqliteStateMachine::open(dir.path().join("state.sqlite"), "cluster-a", "node-1", 1, 1)
        .unwrap();
    let command = SqlCommand {
        request_id: "fingerprint".into(),
        statements: vec![SqlStatement {
            sql: "CREATE TABLE items(id INTEGER PRIMARY KEY)".into(),
            parameters: vec![],
        }],
    };
    let payload = encode_sql_command(&command).unwrap();
    let mut body: serde_json::Value =
        serde_json::from_slice(&payload[b"QSQL\0\x02".len()..]).unwrap();
    body["executor_fingerprint"] = serde_json::Value::String(LogHash::ZERO.to_hex());
    let mut tampered = b"QSQL\0\x02".to_vec();
    tampered.extend_from_slice(&serde_json::to_vec(&body).unwrap());

    assert_ne!(sql_executor_fingerprint().unwrap(), LogHash::ZERO);
    let preparation = db
        .prepare_sql_batch_effect(
            &[SqlBatchMember {
                command: &command,
                request_payload: &tampered,
            }],
            0,
            LogHash::ZERO,
        )
        .unwrap();
    assert!(preparation.effect.is_none());
    assert!(matches!(
        &preparation.results[0],
        Err(Error::InvalidCommand(_))
    ));
}

#[test]
fn sql_query_supports_sqlite_read_families_and_named_parameters() {
    let dir = tempfile::tempdir().unwrap();
    let db = SqliteStateMachine::open(dir.path().join("state.sqlite"), "cluster-a", "node-1", 1, 1)
        .unwrap();

    let values = db
        .query_sql(
            &SqlStatement {
                sql: "VALUES (1, 'one'), (2, 'two')".into(),
                parameters: vec![],
            },
            10,
            1024,
        )
        .unwrap();
    assert_eq!(values.columns, ["column1", "column2"]);
    assert_eq!(
        values.rows,
        [
            vec![SqlValue::Integer(1), SqlValue::Text("one".into())],
            vec![SqlValue::Integer(2), SqlValue::Text("two".into())],
        ]
    );

    let explain = db
        .query_sql(
            &SqlStatement {
                sql: "EXPLAIN QUERY PLAN SELECT 1".into(),
                parameters: vec![],
            },
            10,
            1024,
        )
        .unwrap();
    assert_eq!(explain.columns, ["id", "parent", "notused", "detail"]);
    assert_eq!(explain.rows.len(), 1);

    let recursive = db
        .query_sql(
            &SqlStatement {
                sql: "WITH RECURSIVE sequence(value) AS (VALUES (1) UNION ALL SELECT value + 1 FROM sequence WHERE value < 3) SELECT value FROM sequence".into(),
                parameters: vec![],
            },
            10,
            1024,
        )
        .unwrap();
    assert_eq!(
        recursive.rows,
        [
            vec![SqlValue::Integer(1)],
            vec![SqlValue::Integer(2)],
            vec![SqlValue::Integer(3)],
        ]
    );

    let window = db
        .query_sql(
            &SqlStatement {
                sql: "WITH input(value) AS (VALUES (3), (1), (2)) SELECT value, sum(value) OVER (ORDER BY value) FROM input ORDER BY value".into(),
                parameters: vec![],
            },
            10,
            1024,
        )
        .unwrap();
    assert_eq!(
        window.rows,
        [
            vec![SqlValue::Integer(1), SqlValue::Integer(1)],
            vec![SqlValue::Integer(2), SqlValue::Integer(3)],
            vec![SqlValue::Integer(3), SqlValue::Integer(6)],
        ]
    );

    let json = db
        .query_sql(
            &SqlStatement {
                sql: "SELECT json_extract('{\"name\":\"Ada\"}', '$.name'), (SELECT group_concat(value, ',') FROM json_each('[1,2,3]'))".into(),
                parameters: vec![],
            },
            10,
            1024,
        )
        .unwrap();
    assert_eq!(
        json.rows,
        [vec![
            SqlValue::Text("Ada".into()),
            SqlValue::Text("1,2,3".into()),
        ]]
    );

    let named = db
        .query_sql(
            &SqlStatement {
                sql: "SELECT :number, :text".into(),
                parameters: vec![SqlValue::Integer(42), SqlValue::Text("bound".into())],
            },
            10,
            1024,
        )
        .unwrap();
    assert_eq!(
        named.rows,
        [vec![SqlValue::Integer(42), SqlValue::Text("bound".into())]]
    );
}

#[test]
fn sql_query_allows_only_curated_observational_pragmas_without_state_changes() {
    let dir = tempfile::tempdir().unwrap();
    let path = dir.path().join("state.sqlite");
    let db = SqliteStateMachine::open(&path, "cluster-a", "node-1", 1, 1).unwrap();
    apply_command(
        &db,
        &SqlCommand {
            request_id: "pragma-setup".into(),
            statements: vec![SqlStatement {
                sql: "CREATE TABLE pragma_items(id INTEGER PRIMARY KEY, parent_id INTEGER REFERENCES pragma_items(id), value TEXT UNIQUE)".into(),
                parameters: vec![],
            }],
        },
        1,
        LogHash::ZERO,
    );

    for sql in [
        "PRAGMA foreign_key_check",
        "PRAGMA foreign_key_list(pragma_items)",
        "PRAGMA index_info(sqlite_autoindex_pragma_items_1)",
        "PRAGMA index_list(pragma_items)",
        "PRAGMA index_xinfo(sqlite_autoindex_pragma_items_1)",
        "PRAGMA integrity_check",
        "PRAGMA quick_check",
        "PRAGMA table_info(pragma_items)",
        "PrAgMa TaBlE_LiSt(pragma_items)",
        "PRAGMA table_xinfo(pragma_items)",
        "PRAGMA application_id",
        "PRAGMA analysis_limit",
        "PRAGMA auto_vacuum",
        "PRAGMA automatic_index",
        "PRAGMA busy_timeout",
        "PRAGMA cache_size",
        "PRAGMA cache_spill",
        "PRAGMA case_sensitive_like",
        "PRAGMA cell_size_check",
        "PRAGMA checkpoint_fullfsync",
        "PRAGMA collation_list",
        "PRAGMA compile_options",
        "PRAGMA count_changes",
        "PRAGMA data_version",
        "PRAGMA default_cache_size",
        "PRAGMA defer_foreign_keys",
        "PRAGMA empty_result_callbacks",
        "PRAGMA encoding",
        "PRAGMA freelist_count",
        "PRAGMA foreign_keys",
        "PRAGMA full_column_names",
        "PRAGMA fullfsync",
        "PRAGMA function_list",
        "PRAGMA hard_heap_limit",
        "PRAGMA ignore_check_constraints",
        "PRAGMA journal_size_limit",
        "PRAGMA legacy_alter_table",
        "PRAGMA locking_mode",
        "PRAGMA max_page_count",
        "PRAGMA mmap_size",
        "PRAGMA module_list",
        "PRAGMA page_count",
        "PRAGMA page_size",
        "PRAGMA pragma_list",
        "PRAGMA query_only",
        "PRAGMA read_uncommitted",
        "PRAGMA recursive_triggers",
        "PRAGMA reverse_unordered_selects",
        "PRAGMA schema_version",
        "PRAGMA secure_delete",
        "PRAGMA short_column_names",
        "PRAGMA soft_heap_limit",
        "PRAGMA synchronous",
        "PRAGMA temp_store",
        "PRAGMA threads",
        "PRAGMA trusted_schema",
        "PRAGMA user_version",
    ] {
        assert!(
            db.query_sql(
                &SqlStatement {
                    sql: sql.into(),
                    parameters: vec![],
                },
                1024,
                1024 * 1024,
            )
            .is_ok(),
            "rejected observational {sql}"
        );
    }

    let read_pragma = |sql: &str| {
        db.query_sql(
            &SqlStatement {
                sql: sql.into(),
                parameters: vec![],
            },
            10,
            1024,
        )
        .unwrap()
        .rows
    };
    let user_version = read_pragma("PRAGMA user_version");
    let journal_mode = Connection::open(&path)
        .unwrap()
        .query_row("PRAGMA journal_mode", [], |row| row.get::<_, String>(0))
        .unwrap();

    for sql in [
        "PRAGMA database_list",
        "PRAGMA table_info(__rhiza_kv)",
        "PRAGMA user_version = 7",
        "PRAGMA foreign_keys = OFF",
        "PRAGMA journal_mode = OFF",
    ] {
        assert!(
            db.query_sql(
                &SqlStatement {
                    sql: sql.into(),
                    parameters: vec![],
                },
                10,
                1024,
            )
            .is_err(),
            "accepted forbidden {sql}"
        );
    }

    assert_eq!(read_pragma("PRAGMA user_version"), user_version);
    assert_eq!(
        Connection::open(&path)
            .unwrap()
            .query_row("PRAGMA journal_mode", [], |row| row.get::<_, String>(0))
            .unwrap(),
        journal_mode
    );
}

#[test]
fn sql_query_enforces_row_byte_and_utf8_result_boundaries() {
    let dir = tempfile::tempdir().unwrap();
    let db = SqliteStateMachine::open(dir.path().join("state.sqlite"), "cluster-a", "node-1", 1, 1)
        .unwrap();
    for (sql, max_rows, max_bytes) in [
        (
            "WITH rows(value) AS (VALUES (1), (2)) SELECT value FROM rows",
            1,
            1024,
        ),
        ("SELECT zeroblob(32)", 10, 16),
        ("SELECT CAST(x'80' AS TEXT)", 10, 1024),
    ] {
        assert!(
            db.query_sql(
                &SqlStatement {
                    sql: sql.into(),
                    parameters: vec![],
                },
                max_rows,
                max_bytes,
            )
            .is_err(),
            "accepted unbounded or lossy query: {sql}"
        );
    }
}

#[test]
fn trigger_on_the_internal_table_is_rejected_without_changing_the_base() {
    let dir = tempfile::tempdir().unwrap();
    let db = SqliteStateMachine::open(dir.path().join("state.sqlite"), "cluster-a", "node-1", 1, 1)
        .unwrap();
    let initial = db.canonical_db_digest().unwrap();

    let command = SqlCommand {
        request_id: "reserved-trigger-target".into(),
        statements: vec![SqlStatement {
            sql: "CREATE TRIGGER user_trigger AFTER INSERT ON __rhiza_kv BEGIN SELECT 1; END"
                .into(),
            parameters: vec![],
        }],
    };
    let request = encode_sql_command(&command).unwrap();
    let preparation = db
        .prepare_sql_batch_effect(
            &[SqlBatchMember {
                command: &command,
                request_payload: &request,
            }],
            0,
            LogHash::ZERO,
        )
        .unwrap();
    assert!(preparation.effect.is_none());
    assert!(preparation.results[0].is_err());
    assert_eq!(db.canonical_db_digest().unwrap(), initial);
}

#[test]
fn restore_is_no_clobber_when_either_destination_file_exists() {
    let dir = tempfile::tempdir().unwrap();
    let source_path = dir.path().join("source.sqlite");
    let source = SqliteStateMachine::open(&source_path, "cluster-a", "node-1", 1, 1).unwrap();
    let hash = apply_command(
        &source,
        &SqlCommand {
            request_id: "snapshot".into(),
            statements: vec![SqlStatement {
                sql: "CREATE TABLE items(id INTEGER PRIMARY KEY)".into(),
                parameters: vec![],
            }],
        },
        1,
        LogHash::ZERO,
    );
    assert_eq!(source.applied_hash_value().unwrap(), hash);
    let snapshot = source.create_snapshot(1).unwrap();

    let target = dir.path().join("target.sqlite");
    std::fs::write(&target, b"do-not-clobber").unwrap();
    assert!(matches!(
        restore_snapshot_file(&target, &snapshot, "node-2"),
        Err(Error::InvalidSnapshot(_))
    ));
    assert_eq!(std::fs::read(&target).unwrap(), b"do-not-clobber");

    std::fs::remove_file(&target).unwrap();
    let control = target.with_extension("sqlite.control");
    std::fs::write(&control, b"do-not-clobber-control").unwrap();
    assert!(matches!(
        restore_snapshot_file(&target, &snapshot, "node-2"),
        Err(Error::InvalidSnapshot(_))
    ));
    assert_eq!(std::fs::read(&control).unwrap(), b"do-not-clobber-control");

    std::fs::remove_file(control).unwrap();
    let wal = target.with_file_name("target.sqlite-wal");
    std::fs::write(&wal, b"stale-wal").unwrap();
    assert!(matches!(
        restore_snapshot_file(&target, &snapshot, "node-2"),
        Err(Error::InvalidSnapshot(_))
    ));
    assert_eq!(std::fs::read(wal).unwrap(), b"stale-wal");
}