ic_sqlite_features/
lib.rs

1pub mod vfs;
2
3use std::sync::{Mutex, Arc};
4use lazy_static::lazy_static;
5use sqlite_vfs::register;
6use ic_cdk::api::stable::{stable64_size, stable64_grow, StableMemoryError};
7
8pub use rusqlite::*;
9lazy_static! {
10    pub static ref CONN: Arc<Mutex<Connection>> = {
11        register("vfs", vfs::PagesVfs::default(), true).unwrap();
12        let conn = Connection::open_with_flags_and_vfs(
13            "main.db",
14            OpenFlags::SQLITE_OPEN_READ_WRITE
15                | OpenFlags::SQLITE_OPEN_CREATE
16                | OpenFlags::SQLITE_OPEN_NO_MUTEX,
17            "vfs",
18        ).unwrap();
19        conn.execute_batch(
20            r#"
21            PRAGMA page_size=4096;
22            PRAGMA journal_mode=MEMORY;
23            "#,
24        ).unwrap();
25
26        return Arc::new(Mutex::new(conn));
27    };
28}
29
30const WASM_PAGE_SIZE_IN_BYTES: u64 = 64 * 1024; // 64KB
31
32/// Gets capacity of the stable memory in bytes.
33pub fn stable_capacity() -> u64 {
34    stable64_size() << 16
35}
36
37/// Attempts to grow the memory by adding new pages.
38pub fn stable_grow_bytes(size: u64) -> Result<u64, StableMemoryError> {
39    let added_pages = (size as f64 / WASM_PAGE_SIZE_IN_BYTES as f64).ceil() as u64;
40    stable64_grow(added_pages)
41}