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
use std::ffi::{c_int, CStr};
use std::num::NonZeroU32;

pub use crate::ffi::Error;
use crate::ffi::*;

pub use sqlite3_wal::{Sqlite3Wal, Sqlite3WalManager};

pub(crate) mod ffi;
mod sqlite3_wal;
pub mod wrapper;

pub type Result<T, E = Error> = std::result::Result<T, E>;
pub use ffi::make_wal_manager;

pub trait WalManager {
    type Wal: Wal;

    fn use_shared_memory(&self) -> bool;

    fn open(
        &self,
        vfs: &mut Vfs,
        file: &mut Sqlite3File,
        no_shm_mode: c_int,
        max_log_size: i64,
        db_path: &CStr,
    ) -> Result<Self::Wal>;
    fn close(
        &self,
        wal: &mut Self::Wal,
        db: &mut Sqlite3Db,
        sync_flags: c_int,
        scratch: Option<&mut [u8]>,
    ) -> Result<()>;

    fn destroy_log(&self, vfs: &mut Vfs, db_path: &CStr) -> Result<()>;
    fn log_exists(&self, vfs: &mut Vfs, db_path: &CStr) -> Result<bool>;

    fn destroy(self)
    where
        Self: Sized;
}

/// Wrapper type around `*mut sqlite3`, to seal the pointer from extern usage.
pub struct Sqlite3Db {
    inner: *mut sqlite3,
}

impl Sqlite3Db {
    pub(crate) fn as_ptr(&mut self) -> *mut sqlite3 {
        self.inner
    }
}

/// Wrapper type around `*mut sqlite3_file`, to seal the pointer from extern usage.
#[repr(transparent)]
pub struct Sqlite3File {
    inner: *mut sqlite3_file,
}

impl Sqlite3File {
    pub(crate) fn as_ptr(&mut self) -> *mut sqlite3_file {
        self.inner
    }

    pub fn read_at(&mut self, buf: &mut [u8], offset: u64) -> Result<()> {
        unsafe {
            assert!(!self.inner.is_null());
            let inner = &mut *self.inner;
            assert!(!inner.pMethods.is_null());
            let io_methods = &*inner.pMethods;

            let read = io_methods.xRead.unwrap();

            let rc = read(
                self.inner,
                buf.as_mut_ptr() as *mut _,
                buf.len() as _,
                offset as _,
            );

            if rc == 0 {
                Ok(())
            } else {
                Err(Error::new(rc))
            }
        }
    }
}

/// Wrapper type around `*mut sqlite3_vfs`, to seal the pointer from extern usage.
pub struct Vfs {
    vfs: *mut sqlite3_vfs,
}

impl Vfs {
    pub(crate) fn as_ptr(&mut self) -> *mut sqlite3_vfs {
        self.vfs
    }
}

pub struct PageHeaders {
    inner: *mut libsql_pghdr,
}

impl PageHeaders {
    pub(crate) fn as_ptr(&self) -> *const libsql_pghdr {
        self.inner
    }

    pub(crate) fn as_mut_ptr(&mut self) -> *mut libsql_pghdr {
        self.inner
    }

    /// # Safety
    /// caller must ensure the headers list validity.
    pub unsafe fn from_raw(inner: *mut libsql_pghdr) -> Self {
        Self { inner }
    }

    pub fn iter(&self) -> PageHdrIter {
        // TODO: move LIBSQL_PAGE_SIZE
        PageHdrIter::new(self.as_ptr(), 4096)
    }
}

pub trait BusyHandler {
    // Handle busy, and returns whether a retry should be performed
    fn handle_busy(&mut self) -> bool;
}

pub trait UndoHandler {
    fn handle_undo(&mut self, page_no: u32) -> Result<()>;
}

#[derive(PartialEq, Eq, PartialOrd, Ord, Debug)]
#[repr(i32)]
pub enum CheckpointMode {
    Passive = SQLITE_CHECKPOINT_PASSIVE,
    Full = SQLITE_CHECKPOINT_FULL,
    Restart = SQLITE_CHECKPOINT_RESTART,
    Truncate = SQLITE_CHECKPOINT_TRUNCATE,
}

pub trait Wal {
    /// Set the WAL limit in pages
    fn limit(&mut self, size: i64);
    /// start a read transaction. Returns whether the in-memory page cache should be invalidated.
    fn begin_read_txn(&mut self) -> Result<bool>;
    fn end_read_txn(&mut self);

    /// locate the frame containing page `page_no`
    fn find_frame(&mut self, page_no: NonZeroU32) -> Result<Option<NonZeroU32>>;
    /// reads frame `frame_no` into buffer.
    fn read_frame(&mut self, frame_no: NonZeroU32, buffer: &mut [u8]) -> Result<()>;

    fn db_size(&self) -> u32;

    fn begin_write_txn(&mut self) -> Result<()>;
    fn end_write_txn(&mut self) -> Result<()>;

    fn undo<U: UndoHandler>(&mut self, handler: Option<&mut U>) -> Result<()>;

    fn savepoint(&mut self, rollback_data: &mut [u32]);
    fn savepoint_undo(&mut self, rollback_data: &mut [u32]) -> Result<()>;

    fn insert_frames(
        &mut self,
        page_size: c_int,
        page_headers: &mut PageHeaders,
        size_after: u32,
        is_commit: bool,
        sync_flags: c_int,
    ) -> Result<()>;

    /// Returns the number of frames in the log and the number of checkpointed frames in the WAL.
    fn checkpoint<B: BusyHandler>(
        &mut self,
        db: &mut Sqlite3Db,
        mode: CheckpointMode,
        busy_handler: Option<&mut B>,
        sync_flags: u32,
        // temporary scratch buffer
        buf: &mut [u8],
    ) -> Result<(u32, u32)>;

    fn exclusive_mode(&mut self, op: c_int) -> Result<()>;
    fn uses_heap_memory(&self) -> bool;
    fn set_db(&mut self, db: &mut Sqlite3Db);

    /// Return the value to pass to a sqlite3_wal_hook callback, the
    /// number of frames in the WAL at the point of the last commit since
    /// sqlite3WalCallback() was called.  If no commits have occurred since
    /// the last call, then return 0.
    fn callback(&self) -> i32;

    fn last_fame_index(&self) -> u32;
}