Skip to main content

sqlite_plugin/
vfs.rs

1use crate::flags::{AccessFlags, LockLevel, OpenOpts, ShmLockMode};
2use crate::logger::SqliteLogger;
3use crate::vars::SQLITE_ERROR;
4use crate::{ffi, vars};
5use alloc::borrow::Cow;
6use alloc::boxed::Box;
7use alloc::ffi::CString;
8use alloc::format;
9use alloc::string::String;
10use core::mem::{ManuallyDrop, size_of};
11use core::slice;
12use core::{
13    ffi::{CStr, c_char, c_int, c_void},
14    ptr::{NonNull, null_mut},
15};
16
17/// The minimim supported `SQLite` version.
18// If you need to make this earlier, make sure the tests are testing the earlier version
19pub const MIN_SQLITE_VERSION_NUMBER: i32 = 3043000;
20
21const DEFAULT_MAX_PATH_LEN: i32 = 512;
22pub const DEFAULT_SECTOR_SIZE: i32 = 4096;
23
24pub const DEFAULT_DEVICE_CHARACTERISTICS: i32 =
25    // writes of any size are atomic
26    vars::SQLITE_IOCAP_ATOMIC |
27    // after reboot following a crash or power loss, the only bytes in a file that were written
28    // at the application level might have changed and that adjacent bytes, even bytes within
29    // the same sector are guaranteed to be unchanged
30    vars::SQLITE_IOCAP_POWERSAFE_OVERWRITE |
31    // when data is appended to a file, the data is appended first then the size of the file is
32    // extended, never the other way around
33    vars::SQLITE_IOCAP_SAFE_APPEND |
34    // information is written to disk in the same order as calls to xWrite()
35    vars::SQLITE_IOCAP_SEQUENTIAL;
36
37/// A `SQLite3` extended error code
38pub type SqliteErr = i32;
39
40pub type VfsResult<T> = Result<T, SqliteErr>;
41
42// FileWrapper needs to be repr(C) and have sqlite3_file as it's first member
43// because it's a "subclass" of sqlite3_file
44#[repr(C)]
45struct FileWrapper<Handle> {
46    file: ffi::sqlite3_file,
47    vfs: *mut ffi::sqlite3_vfs,
48    handle: Handle,
49}
50
51struct AppData<Vfs> {
52    base_vfs: *mut ffi::sqlite3_vfs,
53    vfs: Vfs,
54    io_methods: ffi::sqlite3_io_methods,
55    sqlite_api: SqliteApi,
56}
57
58#[derive(Debug)]
59pub struct Pragma<'a> {
60    pub name: &'a str,
61    pub arg: Option<&'a str>,
62}
63
64#[derive(Debug)]
65pub enum PragmaErr {
66    NotFound,
67    Fail(SqliteErr, Option<String>),
68}
69
70impl PragmaErr {
71    pub fn required_arg(p: &Pragma<'_>) -> Self {
72        PragmaErr::Fail(
73            SQLITE_ERROR,
74            Some(format!(
75                "argument required (e.g. `pragma {} = ...`)",
76                p.name
77            )),
78        )
79    }
80}
81
82fn fallible(mut cb: impl FnMut() -> Result<i32, SqliteErr>) -> i32 {
83    cb().unwrap_or_else(|err| err)
84}
85
86unsafe fn lossy_cstr<'a>(p: *const c_char) -> VfsResult<Cow<'a, str>> {
87    unsafe {
88        p.as_ref()
89            .map(|p| CStr::from_ptr(p).to_string_lossy())
90            .ok_or(vars::SQLITE_INTERNAL)
91    }
92}
93
94macro_rules! unwrap_appdata {
95    ($p_vfs:expr, $t_vfs:ty) => {
96        unsafe {
97            let out: VfsResult<&AppData<$t_vfs>> = (*$p_vfs)
98                .pAppData
99                .cast::<AppData<$t_vfs>>()
100                .as_ref()
101                .ok_or(vars::SQLITE_INTERNAL);
102            out
103        }
104    };
105}
106
107macro_rules! unwrap_vfs {
108    ($p_vfs:expr, $t_vfs:ty) => {{
109        let out: VfsResult<&$t_vfs> = unwrap_appdata!($p_vfs, $t_vfs).map(|app_data| &app_data.vfs);
110        out
111    }};
112}
113
114macro_rules! unwrap_base_vfs {
115    ($p_vfs:expr, $t_vfs:ty) => {{
116        let out: VfsResult<&mut ffi::sqlite3_vfs> =
117            unwrap_appdata!($p_vfs, $t_vfs).and_then(|app_data| {
118                unsafe { app_data.base_vfs.as_mut() }.ok_or(vars::SQLITE_INTERNAL)
119            });
120        out
121    }};
122}
123
124macro_rules! unwrap_file {
125    ($p_file:expr, $t_vfs:ty) => {
126        unsafe {
127            let out: VfsResult<&mut FileWrapper<<$t_vfs>::Handle>> = $p_file
128                .cast::<FileWrapper<<$t_vfs>::Handle>>()
129                .as_mut()
130                .ok_or(vars::SQLITE_INTERNAL);
131            out
132        }
133    };
134}
135
136pub trait VfsHandle: Send {
137    fn readonly(&self) -> bool;
138    fn in_memory(&self) -> bool;
139}
140
141#[allow(unused_variables)]
142pub trait Vfs: Send + Sync {
143    type Handle: VfsHandle;
144
145    /// construct a canonical version of the given path
146    fn canonical_path<'a>(&self, path: Cow<'a, str>) -> VfsResult<Cow<'a, str>> {
147        Ok(path)
148    }
149
150    // file system operations
151    fn open(&self, path: Option<&str>, opts: OpenOpts) -> VfsResult<Self::Handle>;
152    fn delete(&self, path: &str) -> VfsResult<()>;
153    fn access(&self, path: &str, flags: AccessFlags) -> VfsResult<bool>;
154
155    // file operations
156    fn file_size(&self, handle: &mut Self::Handle) -> VfsResult<usize>;
157    fn truncate(&self, handle: &mut Self::Handle, size: usize) -> VfsResult<()>;
158    fn write(&self, handle: &mut Self::Handle, offset: usize, data: &[u8]) -> VfsResult<usize>;
159    fn read(&self, handle: &mut Self::Handle, offset: usize, data: &mut [u8]) -> VfsResult<usize>;
160
161    fn lock(&self, handle: &mut Self::Handle, level: LockLevel) -> VfsResult<()>;
162
163    fn unlock(&self, handle: &mut Self::Handle, level: LockLevel) -> VfsResult<()>;
164
165    fn check_reserved_lock(&self, handle: &mut Self::Handle) -> VfsResult<bool>;
166
167    fn sync(&self, handle: &mut Self::Handle) -> VfsResult<()> {
168        Ok(())
169    }
170
171    fn close(&self, handle: Self::Handle) -> VfsResult<()>;
172
173    fn pragma(
174        &self,
175        handle: &mut Self::Handle,
176        pragma: Pragma<'_>,
177    ) -> Result<Option<String>, PragmaErr> {
178        Err(PragmaErr::NotFound)
179    }
180
181    // system queries
182    fn sector_size(&self, handle: &mut Self::Handle) -> VfsResult<i32> {
183        Ok(DEFAULT_SECTOR_SIZE)
184    }
185
186    fn device_characteristics(&self, handle: &mut Self::Handle) -> VfsResult<i32> {
187        Ok(DEFAULT_DEVICE_CHARACTERISTICS)
188    }
189
190    fn shm_map(
191        &self,
192        handle: &mut Self::Handle,
193        region_idx: usize,
194        region_size: usize,
195        extend: bool,
196    ) -> VfsResult<Option<NonNull<u8>>> {
197        Err(vars::SQLITE_READONLY_CANTINIT)
198    }
199
200    fn shm_lock(
201        &self,
202        handle: &mut Self::Handle,
203        offset: u32,
204        count: u32,
205        mode: ShmLockMode,
206    ) -> VfsResult<()> {
207        Err(vars::SQLITE_IOERR)
208    }
209
210    fn shm_barrier(&self, handle: &mut Self::Handle) {}
211
212    fn shm_unmap(&self, handle: &mut Self::Handle, delete: bool) -> VfsResult<()> {
213        Err(vars::SQLITE_IOERR)
214    }
215
216    /// Memory-mapped page read (xFetch). Return a pointer to `amt` bytes of
217    /// the file starting at `offset`, or `Ok(None)` to decline and have `SQLite`
218    /// fall back to `xRead`.
219    ///
220    /// The default implementation declines all mmap requests. Override this to
221    /// enable memory-mapped I/O for your VFS (e.g. mmap the database file).
222    ///
223    /// # Safety contract
224    ///
225    /// The returned pointer must remain valid until `unfetch` is called with
226    /// the same offset. `SQLite` may read from the pointer concurrently from
227    /// multiple threads.
228    fn fetch(
229        &self,
230        handle: &mut Self::Handle,
231        offset: i64,
232        amt: usize,
233    ) -> VfsResult<Option<NonNull<u8>>> {
234        Ok(None)
235    }
236
237    /// Release a memory-mapped page previously returned by `fetch`.
238    ///
239    /// If `ptr` is null, this is a hint that the VFS should reduce its
240    /// memory-mapped footprint (`SQLite` calls this when shrinking mmap).
241    /// The default implementation is a no-op.
242    fn unfetch(&self, handle: &mut Self::Handle, offset: i64, ptr: *mut u8) -> VfsResult<()> {
243        Ok(())
244    }
245}
246
247#[derive(Clone)]
248pub struct SqliteApi {
249    register: unsafe extern "C" fn(arg1: *mut ffi::sqlite3_vfs, arg2: c_int) -> c_int,
250    find: unsafe extern "C" fn(arg1: *const c_char) -> *mut ffi::sqlite3_vfs,
251    mprintf: unsafe extern "C" fn(arg1: *const c_char, ...) -> *mut c_char,
252    log: unsafe extern "C" fn(arg1: c_int, arg2: *const c_char, ...),
253    libversion_number: unsafe extern "C" fn() -> c_int,
254}
255
256impl SqliteApi {
257    #[cfg(feature = "static")]
258    pub fn new_static() -> Self {
259        Self {
260            register: ffi::sqlite3_vfs_register,
261            find: ffi::sqlite3_vfs_find,
262            mprintf: ffi::sqlite3_mprintf,
263            log: ffi::sqlite3_log,
264            libversion_number: ffi::sqlite3_libversion_number,
265        }
266    }
267
268    /// Initializes SqliteApi from a filled `sqlite3_api_routines` object.
269    /// # Safety
270    /// `api` must be a valid, aligned pointer to a `sqlite3_api_routines` struct
271    #[cfg(feature = "dynamic")]
272    pub unsafe fn new_dynamic(api: &ffi::sqlite3_api_routines) -> VfsResult<Self> {
273        Ok(Self {
274            register: api.vfs_register.ok_or(vars::SQLITE_INTERNAL)?,
275            find: api.vfs_find.ok_or(vars::SQLITE_INTERNAL)?,
276            mprintf: api.mprintf.ok_or(vars::SQLITE_INTERNAL)?,
277            log: api.log.ok_or(vars::SQLITE_INTERNAL)?,
278            libversion_number: api.libversion_number.ok_or(vars::SQLITE_INTERNAL)?,
279        })
280    }
281
282    /// Copies the provided string into a memory buffer allocated by `sqlite3_mprintf`.
283    /// Writes the pointer to the memory buffer to `out` if `out` is not null.
284    /// # Safety
285    /// 1. the out pointer must not be null
286    /// 2. it is the callers responsibility to eventually free the allocated buffer
287    pub unsafe fn mprintf(&self, s: &str, out: *mut *const c_char) -> VfsResult<()> {
288        let s = CString::new(s).map_err(|_| vars::SQLITE_INTERNAL)?;
289        let p = unsafe { (self.mprintf)(s.as_ptr()) };
290        if p.is_null() {
291            Err(vars::SQLITE_NOMEM)
292        } else {
293            unsafe {
294                *out = p;
295            }
296            Ok(())
297        }
298    }
299}
300
301pub struct RegisterOpts {
302    /// If true, make this vfs the default vfs for `SQLite`.
303    pub make_default: bool,
304}
305
306#[cfg(feature = "static")]
307pub fn register_static<T: Vfs>(
308    name: CString,
309    vfs: T,
310    opts: RegisterOpts,
311) -> VfsResult<SqliteLogger> {
312    register_inner(SqliteApi::new_static(), name, vfs, opts)
313}
314
315/// Register a vfs with `SQLite` using the dynamic API. This API is available when
316/// `SQLite` is initializing extensions.
317/// # Safety
318/// `p_api` must be a valid, aligned pointer to a `sqlite3_api_routines` struct
319#[cfg(feature = "dynamic")]
320pub unsafe fn register_dynamic<T: Vfs>(
321    p_api: *mut ffi::sqlite3_api_routines,
322    name: CString,
323    vfs: T,
324    opts: RegisterOpts,
325) -> VfsResult<SqliteLogger> {
326    let api = unsafe { p_api.as_ref() }.ok_or(vars::SQLITE_INTERNAL)?;
327    let sqlite_api = unsafe { SqliteApi::new_dynamic(api)? };
328    register_inner(sqlite_api, name, vfs, opts)
329}
330
331fn register_inner<T: Vfs>(
332    sqlite_api: SqliteApi,
333    name: CString,
334    vfs: T,
335    opts: RegisterOpts,
336) -> VfsResult<SqliteLogger> {
337    let version = unsafe { (sqlite_api.libversion_number)() };
338    if version < MIN_SQLITE_VERSION_NUMBER {
339        panic!(
340            "sqlite3 must be at least version {}, found version {}",
341            MIN_SQLITE_VERSION_NUMBER, version
342        );
343    }
344
345    let io_methods = ffi::sqlite3_io_methods {
346        iVersion: 3,
347        xClose: Some(x_close::<T>),
348        xRead: Some(x_read::<T>),
349        xWrite: Some(x_write::<T>),
350        xTruncate: Some(x_truncate::<T>),
351        xSync: Some(x_sync::<T>),
352        xFileSize: Some(x_file_size::<T>),
353        xLock: Some(x_lock::<T>),
354        xUnlock: Some(x_unlock::<T>),
355        xCheckReservedLock: Some(x_check_reserved_lock::<T>),
356        xFileControl: Some(x_file_control::<T>),
357        xSectorSize: Some(x_sector_size::<T>),
358        xDeviceCharacteristics: Some(x_device_characteristics::<T>),
359        xShmMap: Some(x_shm_map::<T>),
360        xShmLock: Some(x_shm_lock::<T>),
361        xShmBarrier: Some(x_shm_barrier::<T>),
362        xShmUnmap: Some(x_shm_unmap::<T>),
363        xFetch: Some(x_fetch::<T>),
364        xUnfetch: Some(x_unfetch::<T>),
365    };
366
367    let logger = SqliteLogger::new(sqlite_api.log);
368
369    let p_name = ManuallyDrop::new(name).as_ptr();
370    let base_vfs = unsafe { (sqlite_api.find)(null_mut()) };
371    let vfs_register = sqlite_api.register;
372    let p_appdata = Box::into_raw(Box::new(AppData { base_vfs, vfs, io_methods, sqlite_api }));
373
374    let filewrapper_size: c_int = size_of::<FileWrapper<T::Handle>>()
375        .try_into()
376        .map_err(|_| vars::SQLITE_INTERNAL)?;
377
378    let p_vfs = Box::into_raw(Box::new(ffi::sqlite3_vfs {
379        iVersion: 3,
380        szOsFile: filewrapper_size,
381        mxPathname: DEFAULT_MAX_PATH_LEN,
382        pNext: null_mut(),
383        zName: p_name,
384        pAppData: p_appdata.cast(),
385        xOpen: Some(x_open::<T>),
386        xDelete: Some(x_delete::<T>),
387        xAccess: Some(x_access::<T>),
388        xFullPathname: Some(x_full_pathname::<T>),
389        xDlOpen: Some(x_dlopen::<T>),
390        xDlError: Some(x_dlerror::<T>),
391        xDlSym: Some(x_dlsym::<T>),
392        xDlClose: Some(x_dlclose::<T>),
393        xRandomness: Some(x_randomness::<T>),
394        xSleep: Some(x_sleep::<T>),
395        xCurrentTime: Some(x_current_time::<T>),
396        xGetLastError: None,
397        xCurrentTimeInt64: Some(x_current_time_int64::<T>),
398        xSetSystemCall: None,
399        xGetSystemCall: None,
400        xNextSystemCall: None,
401    }));
402
403    let result = unsafe { vfs_register(p_vfs, opts.make_default.into()) };
404    if result != vars::SQLITE_OK {
405        // cleanup memory
406        unsafe {
407            drop(Box::from_raw(p_vfs));
408            drop(Box::from_raw(p_appdata));
409            drop(CString::from_raw(p_name as *mut c_char));
410        };
411        Err(result)
412    } else {
413        Ok(logger)
414    }
415}
416
417unsafe extern "C" fn x_open<T: Vfs>(
418    p_vfs: *mut ffi::sqlite3_vfs,
419    z_name: ffi::sqlite3_filename,
420    p_file: *mut ffi::sqlite3_file,
421    flags: c_int,
422    p_out_flags: *mut c_int,
423) -> c_int {
424    fallible(|| {
425        let opts = flags.into();
426        let name = unsafe { lossy_cstr(z_name) }.ok();
427        let vfs = unwrap_vfs!(p_vfs, T)?;
428        let handle = vfs.open(name.as_ref().map(|s| s.as_ref()), opts)?;
429
430        let appdata = unwrap_appdata!(p_vfs, T)?;
431
432        if let Some(p_out_flags) = unsafe { p_out_flags.as_mut() } {
433            let mut out_flags = flags;
434            if handle.readonly() {
435                out_flags |= vars::SQLITE_OPEN_READONLY;
436            }
437            if handle.in_memory() {
438                out_flags |= vars::SQLITE_OPEN_MEMORY;
439            }
440            *p_out_flags = out_flags;
441        }
442
443        let out_file = p_file.cast::<FileWrapper<T::Handle>>();
444        // Safety: SQLite owns the heap allocation backing p_file (it handles malloc/free).
445        // We use ptr::write to initialize that allocation directly.
446        unsafe {
447            core::ptr::write(
448                out_file,
449                FileWrapper {
450                    file: ffi::sqlite3_file { pMethods: &appdata.io_methods },
451                    vfs: p_vfs,
452                    handle,
453                },
454            );
455        }
456
457        Ok(vars::SQLITE_OK)
458    })
459}
460
461unsafe extern "C" fn x_delete<T: Vfs>(
462    p_vfs: *mut ffi::sqlite3_vfs,
463    z_name: ffi::sqlite3_filename,
464    _sync_dir: c_int,
465) -> c_int {
466    fallible(|| {
467        let name = unsafe { lossy_cstr(z_name)? };
468        let vfs = unwrap_vfs!(p_vfs, T)?;
469        vfs.delete(&name)?;
470        Ok(vars::SQLITE_OK)
471    })
472}
473
474unsafe extern "C" fn x_access<T: Vfs>(
475    p_vfs: *mut ffi::sqlite3_vfs,
476    z_name: ffi::sqlite3_filename,
477    flags: c_int,
478    p_res_out: *mut c_int,
479) -> c_int {
480    fallible(|| {
481        let name = unsafe { lossy_cstr(z_name)? };
482        let vfs = unwrap_vfs!(p_vfs, T)?;
483        let result = vfs.access(&name, flags.into())?;
484        let out = unsafe { p_res_out.as_mut() }.ok_or(vars::SQLITE_IOERR_ACCESS)?;
485        *out = result as i32;
486        Ok(vars::SQLITE_OK)
487    })
488}
489
490unsafe extern "C" fn x_full_pathname<T: Vfs>(
491    p_vfs: *mut ffi::sqlite3_vfs,
492    z_name: ffi::sqlite3_filename,
493    n_out: c_int,
494    z_out: *mut c_char,
495) -> c_int {
496    fallible(|| {
497        let name = unsafe { lossy_cstr(z_name)? };
498        let vfs = unwrap_vfs!(p_vfs, T)?;
499        let full_name = vfs.canonical_path(name)?;
500        let n_out = n_out.try_into().map_err(|_| vars::SQLITE_INTERNAL)?;
501        let out = unsafe { slice::from_raw_parts_mut(z_out as *mut u8, n_out) };
502        let from = &full_name.as_bytes()[..full_name.len().min(n_out - 1)];
503        // copy the name into the output buffer
504        out[..from.len()].copy_from_slice(from);
505        // add the trailing null byte
506        out[from.len()] = 0;
507        Ok(vars::SQLITE_OK)
508    })
509}
510
511// file operations
512
513unsafe extern "C" fn x_close<T: Vfs>(p_file: *mut ffi::sqlite3_file) -> c_int {
514    fallible(|| {
515        // Safety: SQLite owns the heap allocation backing p_file (it handles
516        // malloc/free). We use ptr::read to copy our Handle out of that
517        // allocation so it can be passed to vfs.close() and properly dropped.
518        // SQLite will not call any other file methods after x_close without
519        // first calling x_open to reinitialize the handle.
520        let (vfs, handle) = unsafe {
521            // verify p_file is not null and get a mutable reference
522            let p_file_ref = p_file.as_mut().ok_or(vars::SQLITE_INTERNAL)?;
523            // set pMethods to null, signaling to SQLite that the file is closed
524            p_file_ref.pMethods = core::ptr::null();
525
526            // extract a copy of the FileWrapper
527            let file = core::ptr::read(p_file.cast::<FileWrapper<T::Handle>>());
528            (file.vfs, file.handle)
529        };
530
531        let vfs = unwrap_vfs!(vfs, T)?;
532        vfs.close(handle)?;
533        Ok(vars::SQLITE_OK)
534    })
535}
536
537unsafe extern "C" fn x_read<T: Vfs>(
538    p_file: *mut ffi::sqlite3_file,
539    buf: *mut c_void,
540    i_amt: c_int,
541    i_ofst: ffi::sqlite_int64,
542) -> c_int {
543    fallible(|| {
544        let file = unwrap_file!(p_file, T)?;
545        let vfs = unwrap_vfs!(file.vfs, T)?;
546        let buf_len: usize = i_amt.try_into().map_err(|_| vars::SQLITE_IOERR_READ)?;
547        let offset: usize = i_ofst.try_into().map_err(|_| vars::SQLITE_IOERR_READ)?;
548        let buf = unsafe { slice::from_raw_parts_mut(buf.cast::<u8>(), buf_len) };
549        vfs.read(&mut file.handle, offset, buf)?;
550        Ok(vars::SQLITE_OK)
551    })
552}
553
554unsafe extern "C" fn x_write<T: Vfs>(
555    p_file: *mut ffi::sqlite3_file,
556    buf: *const c_void,
557    i_amt: c_int,
558    i_ofst: ffi::sqlite_int64,
559) -> c_int {
560    fallible(|| {
561        let file = unwrap_file!(p_file, T)?;
562        let vfs = unwrap_vfs!(file.vfs, T)?;
563        let buf_len: usize = i_amt.try_into().map_err(|_| vars::SQLITE_IOERR_WRITE)?;
564        let offset: usize = i_ofst.try_into().map_err(|_| vars::SQLITE_IOERR_WRITE)?;
565        let buf = unsafe { slice::from_raw_parts(buf.cast::<u8>(), buf_len) };
566        let n = vfs.write(&mut file.handle, offset, buf)?;
567        if n != buf_len {
568            return Err(vars::SQLITE_IOERR_WRITE);
569        }
570        Ok(vars::SQLITE_OK)
571    })
572}
573
574unsafe extern "C" fn x_truncate<T: Vfs>(
575    p_file: *mut ffi::sqlite3_file,
576    size: ffi::sqlite_int64,
577) -> c_int {
578    fallible(|| {
579        let file = unwrap_file!(p_file, T)?;
580        let vfs = unwrap_vfs!(file.vfs, T)?;
581        let size: usize = size.try_into().map_err(|_| vars::SQLITE_IOERR_TRUNCATE)?;
582        vfs.truncate(&mut file.handle, size)?;
583        Ok(vars::SQLITE_OK)
584    })
585}
586
587unsafe extern "C" fn x_sync<T: Vfs>(p_file: *mut ffi::sqlite3_file, _flags: c_int) -> c_int {
588    fallible(|| {
589        let file = unwrap_file!(p_file, T)?;
590        let vfs = unwrap_vfs!(file.vfs, T)?;
591        vfs.sync(&mut file.handle)?;
592        Ok(vars::SQLITE_OK)
593    })
594}
595
596unsafe extern "C" fn x_file_size<T: Vfs>(
597    p_file: *mut ffi::sqlite3_file,
598    p_size: *mut ffi::sqlite3_int64,
599) -> c_int {
600    fallible(|| {
601        let file = unwrap_file!(p_file, T)?;
602        let vfs = unwrap_vfs!(file.vfs, T)?;
603        let size = vfs.file_size(&mut file.handle)?;
604        let p_size = unsafe { p_size.as_mut() }.ok_or(vars::SQLITE_INTERNAL)?;
605        *p_size = size.try_into().map_err(|_| vars::SQLITE_IOERR_FSTAT)?;
606        Ok(vars::SQLITE_OK)
607    })
608}
609
610unsafe extern "C" fn x_lock<T: Vfs>(p_file: *mut ffi::sqlite3_file, raw_lock: c_int) -> c_int {
611    fallible(|| {
612        let level: LockLevel = raw_lock.into();
613        let file = unwrap_file!(p_file, T)?;
614        let vfs = unwrap_vfs!(file.vfs, T)?;
615        vfs.lock(&mut file.handle, level)?;
616        Ok(vars::SQLITE_OK)
617    })
618}
619
620unsafe extern "C" fn x_unlock<T: Vfs>(p_file: *mut ffi::sqlite3_file, raw_lock: c_int) -> c_int {
621    fallible(|| {
622        let level: LockLevel = raw_lock.into();
623        let file = unwrap_file!(p_file, T)?;
624        let vfs = unwrap_vfs!(file.vfs, T)?;
625        vfs.unlock(&mut file.handle, level)?;
626        Ok(vars::SQLITE_OK)
627    })
628}
629
630unsafe extern "C" fn x_check_reserved_lock<T: Vfs>(
631    p_file: *mut ffi::sqlite3_file,
632    p_out: *mut c_int,
633) -> c_int {
634    fallible(|| {
635        let file = unwrap_file!(p_file, T)?;
636        let vfs = unwrap_vfs!(file.vfs, T)?;
637        unsafe {
638            *p_out = vfs.check_reserved_lock(&mut file.handle)? as c_int;
639        }
640        Ok(vars::SQLITE_OK)
641    })
642}
643
644unsafe extern "C" fn x_file_control<T: Vfs>(
645    p_file: *mut ffi::sqlite3_file,
646    op: c_int,
647    p_arg: *mut c_void,
648) -> c_int {
649    /*
650    Other interesting ops:
651    SIZE_HINT: hint of how large the database will grow during the current transaction
652    COMMIT_PHASETWO: after transaction commits before file unlocks (only used in WAL mode)
653    VFS_NAME: should return this vfs's name + / + base vfs's name
654
655    Atomic write support: (requires SQLITE_IOCAP_BATCH_ATOMIC device characteristic)
656    Docs: https://www3.sqlite.org/cgi/src/technote/714f6cbbf78c8a1351cbd48af2b438f7f824b336
657    BEGIN_ATOMIC_WRITE: start an atomic write operation
658    COMMIT_ATOMIC_WRITE: commit an atomic write operation
659    ROLLBACK_ATOMIC_WRITE: rollback an atomic write operation
660    */
661
662    if op == vars::SQLITE_FCNTL_PRAGMA {
663        return fallible(|| {
664            let file = unwrap_file!(p_file, T)?;
665            let vfs = unwrap_vfs!(file.vfs, T)?;
666
667            // p_arg is a pointer to an array of strings
668            // the second value is the pragma name
669            // the third value is either null or the pragma arg
670            let args = p_arg.cast::<*const c_char>();
671            let name = unsafe { lossy_cstr(*args.add(1)) }?;
672            let arg = unsafe {
673                (*args.add(2))
674                    .as_ref()
675                    .map(|p| CStr::from_ptr(p).to_string_lossy())
676            };
677            let pragma = Pragma { name: &name, arg: arg.as_deref() };
678
679            let (result, msg) = match vfs.pragma(&mut file.handle, pragma) {
680                Ok(msg) => (Ok(vars::SQLITE_OK), msg),
681                Err(PragmaErr::NotFound) => (Err(vars::SQLITE_NOTFOUND), None),
682                Err(PragmaErr::Fail(err, msg)) => (Err(err), msg),
683            };
684
685            if let Some(msg) = msg {
686                // write the msg back to the first element of the args array.
687                // SQLite is responsible for eventually freeing the result
688                let appdata = unwrap_appdata!(file.vfs, T)?;
689                unsafe { appdata.sqlite_api.mprintf(&msg, args)? };
690            }
691
692            result
693        });
694    }
695    vars::SQLITE_NOTFOUND
696}
697
698// system queries
699
700unsafe extern "C" fn x_sector_size<T: Vfs>(p_file: *mut ffi::sqlite3_file) -> c_int {
701    fallible(|| {
702        let file = unwrap_file!(p_file, T)?;
703        let vfs = unwrap_vfs!(file.vfs, T)?;
704        vfs.sector_size(&mut file.handle)
705    })
706}
707
708unsafe extern "C" fn x_device_characteristics<T: Vfs>(p_file: *mut ffi::sqlite3_file) -> c_int {
709    fallible(|| {
710        let file = unwrap_file!(p_file, T)?;
711        let vfs = unwrap_vfs!(file.vfs, T)?;
712        vfs.device_characteristics(&mut file.handle)
713    })
714}
715
716unsafe extern "C" fn x_shm_map<T: Vfs>(
717    p_file: *mut ffi::sqlite3_file,
718    pg: c_int,
719    pgsz: c_int,
720    extend: c_int,
721    p_page: *mut *mut c_void,
722) -> c_int {
723    fallible(|| {
724        let file = unwrap_file!(p_file, T)?;
725        let vfs = unwrap_vfs!(file.vfs, T)?;
726        if let Some(region) = vfs.shm_map(
727            &mut file.handle,
728            pg.try_into().map_err(|_| vars::SQLITE_IOERR)?,
729            pgsz.try_into().map_err(|_| vars::SQLITE_IOERR)?,
730            extend != 0,
731        )? {
732            unsafe { *p_page = region.as_ptr() as *mut c_void }
733        } else {
734            unsafe { *p_page = null_mut() }
735        }
736        Ok(vars::SQLITE_OK)
737    })
738}
739
740unsafe extern "C" fn x_shm_lock<T: Vfs>(
741    p_file: *mut ffi::sqlite3_file,
742    offset: c_int,
743    n: c_int,
744    flags: c_int,
745) -> c_int {
746    fallible(|| {
747        let file = unwrap_file!(p_file, T)?;
748        let vfs = unwrap_vfs!(file.vfs, T)?;
749        vfs.shm_lock(
750            &mut file.handle,
751            offset.try_into().map_err(|_| vars::SQLITE_IOERR)?,
752            n.try_into().map_err(|_| vars::SQLITE_IOERR)?,
753            ShmLockMode::try_from(flags)?,
754        )?;
755        Ok(vars::SQLITE_OK)
756    })
757}
758
759unsafe extern "C" fn x_shm_barrier<T: Vfs>(p_file: *mut ffi::sqlite3_file) {
760    if let Ok(file) = unwrap_file!(p_file, T) {
761        if let Ok(vfs) = unwrap_vfs!(file.vfs, T) {
762            vfs.shm_barrier(&mut file.handle)
763        }
764    }
765}
766
767unsafe extern "C" fn x_shm_unmap<T: Vfs>(
768    p_file: *mut ffi::sqlite3_file,
769    delete_flag: c_int,
770) -> c_int {
771    fallible(|| {
772        let file = unwrap_file!(p_file, T)?;
773        let vfs = unwrap_vfs!(file.vfs, T)?;
774        vfs.shm_unmap(&mut file.handle, delete_flag != 0)?;
775        Ok(vars::SQLITE_OK)
776    })
777}
778
779unsafe extern "C" fn x_fetch<T: Vfs>(
780    p_file: *mut ffi::sqlite3_file,
781    i_ofst: ffi::sqlite3_int64,
782    i_amt: c_int,
783    pp: *mut *mut c_void,
784) -> c_int {
785    fallible(|| {
786        let file = unwrap_file!(p_file, T)?;
787        let vfs = unwrap_vfs!(file.vfs, T)?;
788        let amt: usize = i_amt.try_into().map_err(|_| vars::SQLITE_IOERR)?;
789        if let Some(ptr) = vfs.fetch(&mut file.handle, i_ofst, amt)? {
790            unsafe { *pp = ptr.as_ptr() as *mut c_void }
791        } else {
792            unsafe { *pp = null_mut() }
793        }
794        Ok(vars::SQLITE_OK)
795    })
796}
797
798unsafe extern "C" fn x_unfetch<T: Vfs>(
799    p_file: *mut ffi::sqlite3_file,
800    i_ofst: ffi::sqlite3_int64,
801    p: *mut c_void,
802) -> c_int {
803    fallible(|| {
804        let file = unwrap_file!(p_file, T)?;
805        let vfs = unwrap_vfs!(file.vfs, T)?;
806        vfs.unfetch(&mut file.handle, i_ofst, p as *mut u8)?;
807        Ok(vars::SQLITE_OK)
808    })
809}
810
811// the following functions are wrappers around the base vfs functions
812
813unsafe extern "C" fn x_dlopen<T: Vfs>(
814    p_vfs: *mut ffi::sqlite3_vfs,
815    z_path: *const c_char,
816) -> *mut c_void {
817    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
818        if let Some(x_dlopen) = vfs.xDlOpen {
819            return unsafe { x_dlopen(vfs, z_path) };
820        }
821    }
822    null_mut()
823}
824
825unsafe extern "C" fn x_dlerror<T: Vfs>(
826    p_vfs: *mut ffi::sqlite3_vfs,
827    n_byte: c_int,
828    z_err_msg: *mut c_char,
829) {
830    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
831        if let Some(x_dlerror) = vfs.xDlError {
832            unsafe { x_dlerror(vfs, n_byte, z_err_msg) };
833        }
834    }
835}
836
837unsafe extern "C" fn x_dlsym<T: Vfs>(
838    p_vfs: *mut ffi::sqlite3_vfs,
839    p_handle: *mut c_void,
840    z_symbol: *const c_char,
841) -> Option<unsafe extern "C" fn(arg1: *mut ffi::sqlite3_vfs, arg2: *mut c_void, arg3: *const c_char)>
842{
843    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
844        if let Some(x_dlsym) = vfs.xDlSym {
845            return unsafe { x_dlsym(vfs, p_handle, z_symbol) };
846        }
847    }
848    None
849}
850
851unsafe extern "C" fn x_dlclose<T: Vfs>(p_vfs: *mut ffi::sqlite3_vfs, p_handle: *mut c_void) {
852    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
853        if let Some(x_dlclose) = vfs.xDlClose {
854            unsafe { x_dlclose(vfs, p_handle) };
855        }
856    }
857}
858
859unsafe extern "C" fn x_randomness<T: Vfs>(
860    p_vfs: *mut ffi::sqlite3_vfs,
861    n_byte: c_int,
862    z_out: *mut c_char,
863) -> c_int {
864    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
865        if let Some(x_randomness) = vfs.xRandomness {
866            return unsafe { x_randomness(vfs, n_byte, z_out) };
867        }
868    }
869    vars::SQLITE_INTERNAL
870}
871
872unsafe extern "C" fn x_sleep<T: Vfs>(p_vfs: *mut ffi::sqlite3_vfs, microseconds: c_int) -> c_int {
873    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
874        if let Some(x_sleep) = vfs.xSleep {
875            return unsafe { x_sleep(vfs, microseconds) };
876        }
877    }
878    vars::SQLITE_INTERNAL
879}
880
881unsafe extern "C" fn x_current_time<T: Vfs>(
882    p_vfs: *mut ffi::sqlite3_vfs,
883    p_time: *mut f64,
884) -> c_int {
885    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
886        if let Some(x_current_time) = vfs.xCurrentTime {
887            return unsafe { x_current_time(vfs, p_time) };
888        }
889    }
890    vars::SQLITE_INTERNAL
891}
892
893unsafe extern "C" fn x_current_time_int64<T: Vfs>(
894    p_vfs: *mut ffi::sqlite3_vfs,
895    p_time: *mut i64,
896) -> c_int {
897    if let Ok(vfs) = unwrap_base_vfs!(p_vfs, T) {
898        if let Some(x_current_time_int64) = vfs.xCurrentTimeInt64 {
899            return unsafe { x_current_time_int64(vfs, p_time) };
900        }
901    }
902    vars::SQLITE_INTERNAL
903}
904
905#[cfg(test)]
906mod tests {
907    // tests use std
908    extern crate std;
909
910    use super::*;
911    use crate::{
912        flags::{CreateMode, OpenKind, OpenMode},
913        mock::*,
914    };
915    use alloc::{sync::Arc, vec::Vec};
916    use parking_lot::Mutex;
917    use rusqlite::{Connection, OpenFlags};
918    use std::{boxed::Box, io::Write, println};
919
920    fn log_handler(_: i32, arg2: &str) {
921        println!("{arg2}");
922    }
923
924    #[test]
925    fn sanity() -> Result<(), Box<dyn std::error::Error>> {
926        unsafe {
927            rusqlite::trace::config_log(Some(log_handler)).unwrap();
928        }
929
930        struct H {}
931        impl Hooks for H {
932            fn open(&mut self, path: &Option<&str>, opts: &OpenOpts) {
933                let path = path.unwrap();
934                if path == "main.db" {
935                    assert!(!opts.delete_on_close());
936                    assert_eq!(opts.kind(), OpenKind::MainDb);
937                    assert_eq!(
938                        opts.mode(),
939                        OpenMode::ReadWrite { create: CreateMode::Create }
940                    );
941                } else if path == "main.db-journal" {
942                    assert!(!opts.delete_on_close());
943                    assert_eq!(opts.kind(), OpenKind::MainJournal);
944                    assert_eq!(
945                        opts.mode(),
946                        OpenMode::ReadWrite { create: CreateMode::Create }
947                    );
948                } else {
949                    panic!("unexpected path: {}", path);
950                }
951            }
952        }
953
954        let shared = Arc::new(Mutex::new(MockState::new(Box::new(H {}))));
955        let vfs = MockVfs::new(shared.clone());
956        let logger = register_static(
957            CString::new("mock").unwrap(),
958            vfs,
959            RegisterOpts { make_default: true },
960        )
961        .map_err(|_| "failed to register vfs")?;
962
963        // setup the logger
964        shared.lock().setup_logger(logger);
965
966        // create a sqlite connection using the mock vfs
967        let conn = Connection::open_with_flags_and_vfs(
968            "main.db",
969            OpenFlags::SQLITE_OPEN_READ_WRITE | OpenFlags::SQLITE_OPEN_CREATE,
970            "mock",
971        )?;
972
973        conn.execute("create table t (val int)", [])?;
974        conn.execute("insert into t (val) values (1)", [])?;
975        conn.execute("insert into t (val) values (2)", [])?;
976
977        conn.execute("pragma mock_test", [])?;
978
979        let n: i64 = conn.query_row("select sum(val) from t", [], |row| row.get(0))?;
980        assert_eq!(n, 3);
981
982        // the blob api is interesting and stress tests reading/writing pages and journaling
983        conn.execute("create table b (data blob)", [])?;
984        println!("inserting zero blob");
985        conn.execute("insert into b values (zeroblob(8192))", [])?;
986        let rowid = conn.last_insert_rowid();
987        let mut blob = conn.blob_open(rusqlite::MAIN_DB, "b", "data", rowid, false)?;
988
989        // write some data to the blob
990        println!("writing to blob");
991        let n = blob.write(b"hello")?;
992        assert_eq!(n, 5);
993
994        blob.close()?;
995
996        // query the table for the blob and print it
997        let mut stmt = conn.prepare("select data from b")?;
998        let mut rows = stmt.query([])?;
999        while let Some(row) = rows.next()? {
1000            let data: Vec<u8> = row.get(0)?;
1001            assert_eq!(&data[0..5], b"hello");
1002        }
1003        drop(rows);
1004        drop(stmt);
1005
1006        conn.close().expect("failed to close connection");
1007
1008        Ok(())
1009    }
1010}