ic-sqlite-vfs 0.2.2

SQLite VFS backed directly by Internet Computer stable memory
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
//! Public SQLite database facade for canister methods.
//!
//! Update paths accept only synchronous closures, which prevents holding a DB
//! transaction across `await`. Query paths open SQLite in read-only/query-only mode.

pub mod connection;
pub mod migrate;
pub mod pragmas;
pub mod row;
pub mod statement;
pub mod transaction;
pub mod value;

use crate::sqlite_vfs::stable_blob;
use crate::stable::memory::{self, ContextId, DbMemory};
use crate::stable::meta::Superblock;
use connection::Connection;
pub use row::{FromColumn, Row, TextLen};
pub use stable_blob::ChecksumRefresh;
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::ffi::c_int;
use std::rc::Rc;
pub use transaction::UpdateConnection;
pub use value::{Null, ToSql, Value, NULL};

thread_local! {
    static READ_CONNECTIONS: RefCell<BTreeMap<ContextId, Rc<Connection>>> = const { RefCell::new(BTreeMap::new()) };
    static WRITE_CONNECTIONS: RefCell<BTreeMap<ContextId, Rc<Connection>>> = const { RefCell::new(BTreeMap::new()) };
    static ACTIVE_READ_CONNECTIONS: RefCell<Vec<(ContextId, usize)>> = const { RefCell::new(Vec::new()) };
}

#[derive(Debug, thiserror::Error)]
pub enum DbError {
    #[error("sqlite error {0}: {1}")]
    Sqlite(c_int, String),
    #[error("sqlite constraint failed: {0}")]
    Constraint(String),
    #[error("query returned no rows")]
    NotFound,
    #[error("column {index} has type {actual}, expected {expected}")]
    TypeMismatch {
        index: usize,
        expected: &'static str,
        actual: &'static str,
    },
    #[error("column index {index} out of range for {count} columns")]
    ColumnOutOfRange { index: usize, count: usize },
    #[error("stable memory error: {0}")]
    Stable(#[from] crate::stable::memory::StableMemoryError),
    #[error("stable memory backend is not initialized; call Db::init(memory) first")]
    StableMemoryNotInitialized,
    #[error("stable memory backend is already initialized")]
    StableMemoryAlreadyInitialized,
    #[error("cannot mutate database while a query connection is active")]
    ReadConnectionInUse,
    #[error("migration version exceeds SQLite INTEGER range: {0}")]
    MigrationVersionOutOfRange(u64),
    #[error("duplicate migration version: {0}")]
    DuplicateMigrationVersion(u64),
    #[error("SQL contains an interior NUL byte")]
    InteriorNul,
    #[error("SQL contains no statement")]
    EmptySql,
    #[error("SQL contains trailing text after the first statement")]
    TrailingSql,
    #[error("text value too large")]
    TextTooLarge,
    #[error("blob value too large")]
    BlobTooLarge,
    #[error("too many SQL parameters")]
    TooManyParameters,
    #[error("SQL parameter count mismatch: expected {expected}, actual {actual}")]
    ParameterCountMismatch { expected: usize, actual: usize },
    #[error("named bind cannot be used with anonymous SQL parameter at index {index}")]
    AnonymousParameterInNamedBind { index: usize },
    #[error("SQL parameter not found: {0}")]
    ParameterNotFound(String),
}

pub struct Db;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DbHandle {
    context: ContextId,
}

impl Db {
    pub fn init(memory: DbMemory) -> Result<(), DbError> {
        let context = memory::init(memory).map_err(|error| match error {
            crate::stable::memory::StableMemoryError::AlreadyInitialized => {
                DbError::StableMemoryAlreadyInitialized
            }
            crate::stable::memory::StableMemoryError::NotInitialized => {
                DbError::StableMemoryNotInitialized
            }
            error => DbError::Stable(error),
        })?;
        clear_read_connection(context);
        clear_write_connection(context);
        let handle = DbHandle::from_context(context);
        let result = handle.initialize();
        if result.is_err() {
            clear_read_connection(context);
            clear_write_connection(context);
            memory::clear_failed_initialization(context);
        }
        result
    }

    fn default_handle() -> Result<DbHandle, DbError> {
        memory::default_context()
            .map(DbHandle::from_context)
            .ok_or(DbError::StableMemoryNotInitialized)
    }

    pub fn update<T, F>(f: F) -> Result<T, DbError>
    where
        F: FnOnce(&mut UpdateConnection<'_>) -> Result<T, DbError>,
    {
        Self::default_handle()?.update(f)
    }

    pub fn query<T, F>(f: F) -> Result<T, DbError>
    where
        F: FnOnce(&Connection) -> Result<T, DbError>,
    {
        Self::default_handle()?.query(f)
    }

    pub fn migrate(migrations: &[migrate::Migration]) -> Result<(), DbError> {
        Self::default_handle()?.migrate(migrations)
    }

    pub fn integrity_check() -> Result<String, DbError> {
        Self::default_handle()?.integrity_check()
    }

    pub fn export_chunk(offset: u64, len: u64) -> Result<Vec<u8>, DbError> {
        Self::default_handle()?.export_chunk(offset, len)
    }

    pub fn db_checksum() -> Result<u64, DbError> {
        Self::default_handle()?.db_checksum()
    }

    pub fn refresh_checksum() -> Result<u64, DbError> {
        Self::default_handle()?.refresh_checksum()
    }

    pub fn refresh_checksum_chunk(max_bytes: u64) -> Result<ChecksumRefresh, DbError> {
        Self::default_handle()?.refresh_checksum_chunk(max_bytes)
    }

    pub fn begin_import(total_size: u64, expected_checksum: u64) -> Result<(), DbError> {
        Self::default_handle()?.begin_import(total_size, expected_checksum)
    }

    pub fn import_chunk(offset: u64, bytes: &[u8]) -> Result<(), DbError> {
        Self::default_handle()?.import_chunk(offset, bytes)
    }

    pub fn finish_import() -> Result<(), DbError> {
        Self::default_handle()?.finish_import()
    }

    pub fn cancel_import() -> Result<(), DbError> {
        Self::default_handle()?.cancel_import()
    }

    pub fn compact() -> Result<(), DbError> {
        Self::default_handle()?.compact()
    }
}

impl DbHandle {
    pub fn init(memory: DbMemory) -> Result<Self, DbError> {
        let handle = Self::from_context(memory::init_context(memory));
        clear_read_connection(handle.context);
        clear_write_connection(handle.context);
        if let Err(error) = handle.initialize() {
            clear_read_connection(handle.context);
            clear_write_connection(handle.context);
            memory::clear_failed_initialization(handle.context);
            return Err(error);
        }
        Ok(handle)
    }

    fn from_context(context: ContextId) -> Self {
        Self { context }
    }

    fn initialize(self) -> Result<(), DbError> {
        self.with_context(|| {
            crate::sqlite_vfs::register();
            Superblock::load()?;
            stable_blob::ensure_page_map_layout()?;
            Ok(())
        })
    }

    fn with_context<T>(self, f: impl FnOnce() -> Result<T, DbError>) -> Result<T, DbError> {
        memory::with_context(self.context, f)
    }

    pub fn update<T, F>(self, f: F) -> Result<T, DbError>
    where
        F: FnOnce(&mut UpdateConnection<'_>) -> Result<T, DbError>,
    {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            let db_size = stable_blob::begin_update()?;
            let _overlay_guard = OverlayGuard;
            let connection = write_connection(self.context, db_size)?;
            let result = transaction::run_immediate(&connection, f);
            clear_read_connection(self.context);
            if result.is_err() {
                clear_write_connection(self.context);
            }
            result
        })
    }

    pub fn query<T, F>(self, f: F) -> Result<T, DbError>
    where
        F: FnOnce(&Connection) -> Result<T, DbError>,
    {
        self.with_context(|| with_read_connection(self.context, f))
    }

    pub fn migrate(self, migrations: &[migrate::Migration]) -> Result<(), DbError> {
        self.update(|connection| migrate::apply(connection, migrations))?;
        self.with_context(|| {
            let target_version = migrations
                .iter()
                .map(|migration| migration.version)
                .max()
                .unwrap_or(0);
            let mut block = Superblock::load()?;
            if block.schema_version < target_version {
                clear_read_connection(self.context);
                block.schema_version = target_version;
                block.store()?;
            }
            Ok(())
        })
    }

    pub fn integrity_check(self) -> Result<String, DbError> {
        self.query(|connection| {
            connection.query_scalar::<String>("PRAGMA integrity_check", crate::params![])
        })
    }

    pub fn export_chunk(self, offset: u64, len: u64) -> Result<Vec<u8>, DbError> {
        self.with_context(|| stable_blob::export_chunk(offset, len).map_err(DbError::from))
    }

    pub fn db_checksum(self) -> Result<u64, DbError> {
        self.with_context(|| stable_blob::checksum().map_err(DbError::from))
    }

    pub fn refresh_checksum(self) -> Result<u64, DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            stable_blob::refresh_checksum().map_err(DbError::from)
        })
    }

    pub fn refresh_checksum_chunk(self, max_bytes: u64) -> Result<ChecksumRefresh, DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            stable_blob::refresh_checksum_chunk(max_bytes).map_err(DbError::from)
        })
    }

    pub fn begin_import(self, total_size: u64, expected_checksum: u64) -> Result<(), DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            clear_write_connection(self.context);
            stable_blob::begin_import(total_size, expected_checksum).map_err(DbError::from)
        })
    }

    pub fn import_chunk(self, offset: u64, bytes: &[u8]) -> Result<(), DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            stable_blob::import_chunk(offset, bytes).map_err(DbError::from)
        })
    }

    pub fn finish_import(self) -> Result<(), DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            clear_write_connection(self.context);
            stable_blob::finish_import().map_err(DbError::from)
        })
    }

    pub fn cancel_import(self) -> Result<(), DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            clear_write_connection(self.context);
            stable_blob::cancel_import().map_err(DbError::from)
        })
    }

    pub fn compact(self) -> Result<(), DbError> {
        self.with_context(|| {
            reject_active_read_connection(self.context)?;
            clear_read_connection(self.context);
            clear_write_connection(self.context);
            stable_blob::compact().map_err(DbError::from)
        })
    }
}

fn write_connection(context: ContextId, db_size: u64) -> Result<Rc<Connection>, DbError> {
    WRITE_CONNECTIONS.with(|slot| {
        let cached = { slot.borrow().get(&context).cloned() };
        if let Some(connection) = cached {
            return Ok(connection);
        }
        let connection = if db_size == 0 {
            connection::open_read_write()?
        } else {
            connection::open_read_write_existing()?
        };
        let connection = Rc::new(connection);
        slot.borrow_mut().insert(context, Rc::clone(&connection));
        Ok(connection)
    })
}

fn with_read_connection<T>(
    context: ContextId,
    f: impl FnOnce(&Connection) -> Result<T, DbError>,
) -> Result<T, DbError> {
    READ_CONNECTIONS.with(|slot| {
        let cached = { slot.borrow().get(&context).cloned() };
        let connection = if let Some(connection) = cached {
            connection
        } else {
            let connection = Rc::new(connection::open_read_only()?);
            slot.borrow_mut().insert(context, Rc::clone(&connection));
            connection
        };
        let _guard = ReadGuard::enter(context);
        f(&connection)
    })
}

fn reject_active_read_connection(context: ContextId) -> Result<(), DbError> {
    ACTIVE_READ_CONNECTIONS.with(|slot| {
        let slot = slot.borrow();
        let active = active_read_index(&slot, context)
            .map(|index| slot[index].1)
            .unwrap_or(0);
        if active == 0 {
            Ok(())
        } else {
            Err(DbError::ReadConnectionInUse)
        }
    })
}

fn clear_read_connection(context: ContextId) {
    READ_CONNECTIONS.with(|slot| {
        slot.borrow_mut().remove(&context);
    });
}

fn clear_write_connection(context: ContextId) {
    WRITE_CONNECTIONS.with(|slot| {
        slot.borrow_mut().remove(&context);
    });
}

struct ReadGuard {
    context: ContextId,
}

impl ReadGuard {
    fn enter(context: ContextId) -> Self {
        ACTIVE_READ_CONNECTIONS.with(|slot| {
            let mut slot = slot.borrow_mut();
            if slot.is_empty() {
                slot.push((context, 1));
                return;
            }
            if let Some(index) = active_read_index(&slot, context) {
                slot[index].1 += 1;
            } else {
                slot.push((context, 1));
            }
        });
        Self { context }
    }
}

impl Drop for ReadGuard {
    fn drop(&mut self) {
        ACTIVE_READ_CONNECTIONS.with(|slot| {
            let mut slot = slot.borrow_mut();
            if slot.len() == 1 && slot[0].0 == self.context {
                let depth = &mut slot[0].1;
                *depth = depth.saturating_sub(1);
                if *depth == 0 {
                    slot.clear();
                }
                return;
            }
            let Some(index) = active_read_index(&slot, self.context) else {
                return;
            };
            let depth = &mut slot[index].1;
            *depth = depth.saturating_sub(1);
            if *depth == 0 {
                slot.swap_remove(index);
            }
        });
    }
}

fn active_read_index(entries: &[(ContextId, usize)], context: ContextId) -> Option<usize> {
    entries
        .iter()
        .position(|(stored_context, _)| *stored_context == context)
}

struct OverlayGuard;

impl Drop for OverlayGuard {
    fn drop(&mut self) {
        stable_blob::rollback_update();
    }
}