Skip to main content

rusqlite/vtab/
mod.rs

1//! Create virtual tables.
2//!
3//! Follow these steps to create your own virtual table:
4//! 1. Write implementation of [`VTab`] and [`VTabCursor`] traits.
5//! 2. Create an instance of the [`Module`] structure specialized for [`VTab`]
6//!    impl. from step 1.
7//! 3. Register your [`Module`] structure using [`Connection::create_module`].
8//! 4. Run a `CREATE VIRTUAL TABLE` command that specifies the new module in the
9//!    `USING` clause.
10//!
11//! (See [SQLite doc](http://sqlite.org/vtab.html))
12use std::borrow::Cow::{self, Borrowed, Owned};
13use std::ffi::{CStr, c_char, c_int, c_uint, c_void};
14use std::marker::PhantomData;
15use std::ops::Deref;
16use std::ptr;
17use std::slice;
18
19use crate::ffi::{sqlite3_context, sqlite3_free, sqlite3_value};
20
21use crate::context::set_result;
22use crate::error::{check, error_from_sqlite_code, to_sqlite_error};
23use crate::ffi;
24pub use crate::ffi::{sqlite3_vtab, sqlite3_vtab_cursor};
25use crate::types::{FromSql, FromSqlError, ToSql, ValueRef};
26use crate::util::{alloc, free_boxed_value};
27use crate::{Connection, Error, InnerConnection, Name, Result, str_to_cstring};
28
29// let conn: Connection = ...;
30// let mod: Module = ...; // VTab builder
31// conn.create_module("module", mod);
32//
33// conn.execute("CREATE VIRTUAL TABLE foo USING module(...)");
34// \-> Module::xcreate
35//  |-> let vtab: VTab = ...; // on the heap
36//  \-> conn.declare_vtab("CREATE TABLE foo (...)");
37// conn = Connection::open(...);
38// \-> Module::xconnect
39//  |-> let vtab: VTab = ...; // on the heap
40//  \-> conn.declare_vtab("CREATE TABLE foo (...)");
41//
42// conn.close();
43// \-> vtab.xdisconnect
44// conn.execute("DROP TABLE foo");
45// \-> vtab.xDestroy
46//
47// let stmt = conn.prepare("SELECT ... FROM foo WHERE ...");
48// \-> vtab.xbestindex
49// stmt.query().next();
50// \-> vtab.xopen
51//  |-> let cursor: VTabCursor = ...; // on the heap
52//  |-> cursor.xfilter or xnext
53//  |-> cursor.xeof
54//  \-> if not eof { cursor.column or xrowid } else { cursor.xclose }
55//
56
57// db: *mut ffi::sqlite3 => VTabConnection
58// module: *const ffi::sqlite3_module => Module
59// aux: *mut c_void => Module::Aux
60// ffi::sqlite3_vtab => VTab
61// ffi::sqlite3_vtab_cursor => VTabCursor
62
63/// Virtual table kind
64pub enum VTabKind {
65    /// Non-eponymous
66    Default,
67    /// [`create`](CreateVTab::create) == [`connect`](VTab::connect)
68    ///
69    /// See [SQLite doc](https://sqlite.org/vtab.html#eponymous_virtual_tables)
70    Eponymous,
71    /// No [`create`](CreateVTab::create) / [`destroy`](CreateVTab::destroy) or
72    /// not used
73    ///
74    /// SQLite >= 3.9.0
75    ///
76    /// See [SQLite doc](https://sqlite.org/vtab.html#eponymous_only_virtual_tables)
77    EponymousOnly,
78}
79
80/// Virtual table module
81///
82/// (See [SQLite doc](https://sqlite.org/c3ref/module.html))
83#[repr(transparent)]
84pub struct Module<'vtab, T: VTab<'vtab>> {
85    base: ffi::sqlite3_module,
86    phantom: PhantomData<&'vtab T>,
87}
88
89union ModuleZeroHack {
90    bytes: [u8; size_of::<ffi::sqlite3_module>()],
91    module: ffi::sqlite3_module,
92}
93
94// Used as a trailing initializer for sqlite3_module -- this way we avoid having
95// the build fail if buildtime_bindgen is on. This is safe, as bindgen-generated
96// structs are allowed to be zeroed.
97const ZERO_MODULE: ffi::sqlite3_module = unsafe {
98    ModuleZeroHack {
99        bytes: [0_u8; size_of::<ffi::sqlite3_module>()],
100    }
101    .module
102};
103
104impl<'vtab, T: VTab<'vtab>> Module<'vtab, T> {
105    /// Create an eponymous only virtual table implementation.
106    ///
107    /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
108    #[must_use]
109    pub const fn eponymous_only_module() -> Self {
110        //  For eponymous-only virtual tables, the xCreate method is NULL
111        Module {
112            base: ffi::sqlite3_module {
113                // We don't use methods provided by versions > 1
114                iVersion: 1,
115                xCreate: None,
116                xConnect: Some(rust_connect::<T>),
117                xBestIndex: Some(rust_best_index::<T>),
118                xDisconnect: Some(rust_disconnect::<T>),
119                xDestroy: None,
120                xOpen: Some(rust_open::<T>),
121                xClose: Some(rust_close::<T::Cursor>),
122                xFilter: Some(rust_filter::<T::Cursor>),
123                xNext: Some(rust_next::<T::Cursor>),
124                xEof: Some(rust_eof::<T::Cursor>),
125                xColumn: Some(rust_column::<T::Cursor>),
126                xRowid: Some(rust_rowid::<T::Cursor>),
127                xUpdate: None,
128                xBegin: None,
129                xSync: None,
130                xCommit: None,
131                xRollback: None,
132                xFindFunction: None,
133                xRename: None,
134                ..ZERO_MODULE
135            },
136            phantom: PhantomData::<&'vtab T>,
137        }
138    }
139
140    /// Create a read-only virtual table implementation.
141    ///
142    /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
143    #[must_use]
144    pub const fn read_only_module() -> Self
145    where
146        T: CreateVTab<'vtab>,
147    {
148        let mut module = Self::eponymous_only_module();
149        match T::KIND {
150            VTabKind::EponymousOnly => module,
151            VTabKind::Eponymous => {
152                // A virtual table is eponymous if its xCreate method is the exact same function
153                // as the xConnect method
154                module.base.xCreate = module.base.xConnect;
155                module.base.xDestroy = module.base.xDisconnect;
156                module
157            }
158            _ => {
159                // The xConnect and xCreate methods may do the same thing, but they must be
160                // different so that the virtual table is not an eponymous virtual table.
161                module.base.xCreate = Some(rust_create::<T>);
162                module.base.xDestroy = Some(rust_destroy::<T>);
163                module
164            }
165        }
166    }
167
168    /// Create a modifiable virtual table implementation.
169    ///
170    /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
171    #[must_use]
172    pub const fn update_module() -> Self
173    where
174        T: UpdateVTab<'vtab>,
175    {
176        let mut module = Self::read_only_module();
177        module.base.xUpdate = Some(rust_update::<T>);
178        module
179    }
180
181    /// Create a modifiable virtual table implementation with support for transactions.
182    ///
183    /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
184    #[must_use]
185    pub const fn update_module_with_tx() -> Self
186    where
187        T: TransactionVTab<'vtab>,
188    {
189        let mut module = Self::update_module();
190        module.base.xBegin = Some(rust_begin::<T>);
191        module.base.xSync = Some(rust_sync::<T>);
192        module.base.xCommit = Some(rust_commit::<T>);
193        module.base.xRollback = Some(rust_rollback::<T>);
194        module
195    }
196
197    /// No `xRowid`
198    #[must_use]
199    pub const fn without_rowid(mut self) -> Self {
200        self.base.xRowid = None;
201        self
202    }
203
204    /// No `xSync`
205    #[must_use]
206    pub const fn without_sync(mut self) -> Self
207    where
208        T: TransactionVTab<'vtab>,
209    {
210        self.base.xSync = None;
211        self
212    }
213}
214
215/// Virtual table configuration options
216#[repr(i32)]
217#[non_exhaustive]
218#[derive(Debug, Clone, Copy, Eq, PartialEq)]
219pub enum VTabConfig {
220    /// Equivalent to `SQLITE_VTAB_CONSTRAINT_SUPPORT`
221    ConstraintSupport = 1,
222    /// Equivalent to `SQLITE_VTAB_INNOCUOUS`
223    Innocuous = 2,
224    /// Equivalent to `SQLITE_VTAB_DIRECTONLY`
225    DirectOnly = 3,
226    /// Equivalent to `SQLITE_VTAB_USES_ALL_SCHEMAS`
227    UsesAllSchemas = 4,
228}
229
230/// `feature = "vtab"`
231pub struct VTabConnection(*mut ffi::sqlite3);
232
233impl VTabConnection {
234    /// Configure various facets of the virtual table interface
235    pub fn config(&mut self, config: VTabConfig) -> Result<()> {
236        check(unsafe { ffi::sqlite3_vtab_config(self.0, config as c_int) })
237    }
238
239    /// Get access to the underlying SQLite database connection handle.
240    ///
241    /// # Warning
242    ///
243    /// You should not need to use this function. If you do need to, please
244    /// [open an issue on the rusqlite repository](https://github.com/rusqlite/rusqlite/issues) and describe
245    /// your use case.
246    ///
247    /// # Safety
248    ///
249    /// This function is unsafe because it gives you raw access
250    /// to the SQLite connection, and what you do with it could impact the
251    /// safety of this `Connection`.
252    pub unsafe fn handle(&mut self) -> *mut ffi::sqlite3 {
253        self.0
254    }
255}
256
257/// Eponymous-only virtual table instance trait.
258///
259/// # Safety
260///
261/// The first item in a struct implementing `VTab` must be
262/// `rusqlite::sqlite3_vtab`, and the struct must be `#[repr(C)]`.
263///
264/// ```rust,ignore
265/// #[repr(C)]
266/// struct MyTab {
267///    /// Base class. Must be first
268///    base: rusqlite::vtab::sqlite3_vtab,
269///    /* Virtual table implementations will typically add additional fields */
270/// }
271/// ```
272///
273/// (See [SQLite doc](https://sqlite.org/c3ref/vtab.html))
274pub unsafe trait VTab<'vtab>: Sized {
275    /// Client data passed to [`Connection::create_module`].
276    type Aux: Send + Sync + 'static;
277    /// Specific cursor implementation
278    type Cursor: VTabCursor;
279
280    /// Establish a new connection to an existing virtual table.
281    ///
282    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xconnect_method))
283    fn connect(
284        db: &mut VTabConnection,
285        aux: Option<&Self::Aux>,
286        module_name: &[u8],
287        database_name: &[u8],
288        table_name: &[u8],
289        args: &[&[u8]],
290    ) -> Result<(Cow<'static, CStr>, Self)>;
291
292    /// Determine the best way to access the virtual table.
293    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xbestindex_method))
294    /// Returning `Ok(false)` means unusable / `SQLITE_CONSTRAINT`.
295    fn best_index(&self, info: &mut IndexInfo) -> Result<bool>;
296
297    /// Create a new cursor used for accessing a virtual table.
298    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xopen_method))
299    fn open(&'vtab mut self) -> Result<Self::Cursor>;
300}
301
302/// Read-only virtual table instance trait.
303///
304/// (See [SQLite doc](https://sqlite.org/c3ref/vtab.html))
305pub trait CreateVTab<'vtab>: VTab<'vtab> {
306    /// For [`EponymousOnly`](VTabKind::EponymousOnly),
307    /// [`create`](CreateVTab::create) and [`destroy`](CreateVTab::destroy) are
308    /// not called
309    const KIND: VTabKind;
310    /// Create a new instance of a virtual table in response to a CREATE VIRTUAL
311    /// TABLE statement. The `db` parameter is a pointer to the SQLite
312    /// database connection that is executing the CREATE VIRTUAL TABLE
313    /// statement.
314    ///
315    /// Call [`connect`](VTab::connect) by default.
316    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xcreate_method))
317    fn create(
318        db: &mut VTabConnection,
319        aux: Option<&Self::Aux>,
320        module_name: &[u8],
321        database_name: &[u8],
322        table_name: &[u8],
323        args: &[&[u8]],
324    ) -> Result<(Cow<'static, CStr>, Self)> {
325        Self::connect(db, aux, module_name, database_name, table_name, args)
326    }
327
328    /// Destroy the underlying table implementation. This method undoes the work
329    /// of [`create`](CreateVTab::create).
330    ///
331    /// Do nothing by default.
332    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xdestroy_method))
333    fn destroy(&self) -> Result<()> {
334        Ok(())
335    }
336}
337
338/// Writable virtual table instance trait.
339///
340/// (See [SQLite doc](https://sqlite.org/vtab.html#xupdate))
341pub trait UpdateVTab<'vtab>: CreateVTab<'vtab> {
342    /// Delete rowid or PK
343    fn delete(&mut self, arg: ValueRef<'_>) -> Result<()>;
344    /// Insert: `args[0] == NULL: old rowid or PK, args[1]: new rowid or PK,
345    /// args[2]: ...`
346    ///
347    /// Return the new rowid.
348    // TODO Make the distinction between argv[1] == NULL and argv[1] != NULL ?
349    fn insert(&mut self, args: &Inserts<'_>) -> Result<i64>;
350    /// Update: `args[0] != NULL: old rowid or PK, args[1]: new row id or PK,
351    /// args[2]: ...`
352    fn update(&mut self, args: &Updates<'_>) -> Result<()>;
353}
354
355/// Writable virtual table instance with transaction support trait.
356///
357/// See [SQLite doc](https://sqlite.org/vtab.html#the_xbegin_method)
358pub trait TransactionVTab<'vtab>: UpdateVTab<'vtab> {
359    /// Start a new transaction
360    fn begin(&mut self) -> Result<()> {
361        Ok(())
362    }
363    /// Begin two-phase commit
364    fn sync(&mut self) -> Result<()> {
365        Ok(())
366    }
367    /// Commit the current transaction
368    fn commit(&mut self) -> Result<()> {
369        Ok(())
370    }
371    /// Abandon the current transaction
372    fn rollback(&mut self) -> Result<()> {
373        Ok(())
374    }
375}
376
377/// Index constraint operator.
378/// See [Virtual Table Constraint Operator Codes](https://sqlite.org/c3ref/c_index_constraint_eq.html) for details.
379#[derive(Debug, Eq, PartialEq)]
380#[allow(missing_docs)]
381#[expect(non_camel_case_types)]
382pub enum IndexConstraintOp {
383    SQLITE_INDEX_CONSTRAINT_EQ,
384    SQLITE_INDEX_CONSTRAINT_GT,
385    SQLITE_INDEX_CONSTRAINT_LE,
386    SQLITE_INDEX_CONSTRAINT_LT,
387    SQLITE_INDEX_CONSTRAINT_GE,
388    SQLITE_INDEX_CONSTRAINT_MATCH,
389    SQLITE_INDEX_CONSTRAINT_LIKE,         // 3.10.0
390    SQLITE_INDEX_CONSTRAINT_GLOB,         // 3.10.0
391    SQLITE_INDEX_CONSTRAINT_REGEXP,       // 3.10.0
392    SQLITE_INDEX_CONSTRAINT_NE,           // 3.21.0
393    SQLITE_INDEX_CONSTRAINT_ISNOT,        // 3.21.0
394    SQLITE_INDEX_CONSTRAINT_ISNOTNULL,    // 3.21.0
395    SQLITE_INDEX_CONSTRAINT_ISNULL,       // 3.21.0
396    SQLITE_INDEX_CONSTRAINT_IS,           // 3.21.0
397    SQLITE_INDEX_CONSTRAINT_LIMIT,        // 3.38.0
398    SQLITE_INDEX_CONSTRAINT_OFFSET,       // 3.38.0
399    SQLITE_INDEX_CONSTRAINT_FUNCTION(u8), // 3.25.0
400}
401
402impl From<u8> for IndexConstraintOp {
403    fn from(code: u8) -> Self {
404        match code {
405            2 => Self::SQLITE_INDEX_CONSTRAINT_EQ,
406            4 => Self::SQLITE_INDEX_CONSTRAINT_GT,
407            8 => Self::SQLITE_INDEX_CONSTRAINT_LE,
408            16 => Self::SQLITE_INDEX_CONSTRAINT_LT,
409            32 => Self::SQLITE_INDEX_CONSTRAINT_GE,
410            64 => Self::SQLITE_INDEX_CONSTRAINT_MATCH,
411            65 => Self::SQLITE_INDEX_CONSTRAINT_LIKE,
412            66 => Self::SQLITE_INDEX_CONSTRAINT_GLOB,
413            67 => Self::SQLITE_INDEX_CONSTRAINT_REGEXP,
414            68 => Self::SQLITE_INDEX_CONSTRAINT_NE,
415            69 => Self::SQLITE_INDEX_CONSTRAINT_ISNOT,
416            70 => Self::SQLITE_INDEX_CONSTRAINT_ISNOTNULL,
417            71 => Self::SQLITE_INDEX_CONSTRAINT_ISNULL,
418            72 => Self::SQLITE_INDEX_CONSTRAINT_IS,
419            73 => Self::SQLITE_INDEX_CONSTRAINT_LIMIT,
420            74 => Self::SQLITE_INDEX_CONSTRAINT_OFFSET,
421            v => Self::SQLITE_INDEX_CONSTRAINT_FUNCTION(v),
422        }
423    }
424}
425
426bitflags::bitflags! {
427    /// Virtual table scan flags
428    /// See [Function Flags](https://sqlite.org/c3ref/c_index_scan_unique.html) for details.
429    #[repr(C)]
430    #[derive(Copy, Clone, Debug)]
431    pub struct IndexFlags: c_int {
432        /// Default
433        const NONE     = 0;
434        /// Scan visits at most 1 row.
435        const SQLITE_INDEX_SCAN_UNIQUE  = ffi::SQLITE_INDEX_SCAN_UNIQUE;
436        /// Display idxNum as hex in EXPLAIN QUERY PLAN
437        const SQLITE_INDEX_SCAN_HEX  = 0x0000_0002; // 3.47.0
438    }
439}
440
441/// Pass information into and receive the reply from the
442/// [`VTab::best_index`] method.
443///
444/// (See [SQLite doc](http://sqlite.org/c3ref/index_info.html))
445#[derive(Debug)]
446pub struct IndexInfo(*mut ffi::sqlite3_index_info);
447
448impl IndexInfo {
449    /// Iterate on index constraint and its associated usage.
450    #[inline]
451    pub fn constraints_and_usages(&mut self) -> IndexConstraintAndUsageIter<'_> {
452        let constraints =
453            unsafe { slice::from_raw_parts((*self.0).aConstraint, (*self.0).nConstraint as usize) };
454        let constraint_usages = unsafe {
455            slice::from_raw_parts_mut((*self.0).aConstraintUsage, (*self.0).nConstraint as usize)
456        };
457        IndexConstraintAndUsageIter {
458            iter: constraints.iter().zip(constraint_usages.iter_mut()),
459        }
460    }
461
462    /// Record WHERE clause constraints.
463    #[inline]
464    #[must_use]
465    pub fn constraints(&self) -> IndexConstraintIter<'_> {
466        let constraints =
467            unsafe { slice::from_raw_parts((*self.0).aConstraint, (*self.0).nConstraint as usize) };
468        IndexConstraintIter {
469            iter: constraints.iter(),
470        }
471    }
472
473    /// Information about the ORDER BY clause.
474    #[inline]
475    #[must_use]
476    pub fn order_bys(&self) -> OrderByIter<'_> {
477        let order_bys =
478            unsafe { slice::from_raw_parts((*self.0).aOrderBy, (*self.0).nOrderBy as usize) };
479        OrderByIter {
480            iter: order_bys.iter(),
481        }
482    }
483
484    /// Number of terms in the ORDER BY clause
485    #[inline]
486    #[must_use]
487    pub fn num_of_order_by(&self) -> usize {
488        unsafe { (*self.0).nOrderBy as usize }
489    }
490
491    /// Information about what parameters to pass to [`VTabCursor::filter`].
492    #[inline]
493    pub fn constraint_usage(&mut self, constraint_idx: usize) -> IndexConstraintUsage<'_> {
494        let constraint_usages = unsafe {
495            slice::from_raw_parts_mut((*self.0).aConstraintUsage, (*self.0).nConstraint as usize)
496        };
497        IndexConstraintUsage(&mut constraint_usages[constraint_idx])
498    }
499
500    /// Number used to identify the index
501    #[inline]
502    pub fn set_idx_num(&mut self, idx_num: c_int) {
503        unsafe {
504            (*self.0).idxNum = idx_num;
505        }
506    }
507
508    /// String used to identify the index
509    pub fn set_idx_str(&mut self, idx_str: &str) {
510        unsafe {
511            if (*self.0).needToFreeIdxStr == 1 {
512                sqlite3_free((*self.0).idxStr.cast());
513            }
514            (*self.0).idxStr = alloc(idx_str);
515            (*self.0).needToFreeIdxStr = 1;
516        }
517    }
518
519    /// String used to identify the index
520    pub fn set_idx_cstr(&mut self, idx_str: &'static CStr) {
521        unsafe {
522            if (*self.0).needToFreeIdxStr == 1 {
523                sqlite3_free((*self.0).idxStr.cast());
524            }
525            (*self.0).idxStr = idx_str.as_ptr().cast_mut();
526            (*self.0).needToFreeIdxStr = 0;
527        }
528    }
529
530    /// True if output is already ordered
531    #[inline]
532    pub fn set_order_by_consumed(&mut self, order_by_consumed: bool) {
533        unsafe {
534            (*self.0).orderByConsumed = c_int::from(order_by_consumed);
535        }
536    }
537
538    /// Estimated cost of using this index
539    #[inline]
540    pub fn set_estimated_cost(&mut self, estimated_ost: f64) {
541        unsafe {
542            (*self.0).estimatedCost = estimated_ost;
543        }
544    }
545
546    /// Estimated number of rows returned.
547    #[inline]
548    pub fn set_estimated_rows(&mut self, estimated_rows: i64) {
549        unsafe {
550            (*self.0).estimatedRows = estimated_rows;
551        }
552    }
553
554    /// Mask of `SQLITE_INDEX_SCAN_*` flags.
555    #[inline]
556    pub fn set_idx_flags(&mut self, flags: IndexFlags) {
557        unsafe { (*self.0).idxFlags = flags.bits() };
558    }
559
560    /// Mask of columns used by statement
561    #[inline]
562    #[must_use]
563    pub fn col_used(&self) -> u64 {
564        unsafe { (*self.0).colUsed }
565    }
566
567    /// Determine the collation for a virtual table constraint
568    pub fn collation(&self, constraint_idx: usize) -> Result<&str> {
569        let idx = constraint_idx as c_int;
570        let collation = unsafe { ffi::sqlite3_vtab_collation(self.0, idx) };
571        if collation.is_null() {
572            return Err(err!(ffi::SQLITE_MISUSE, "{constraint_idx} is out of range"));
573        }
574        Ok(unsafe { CStr::from_ptr(collation) }.to_str()?)
575    }
576
577    /// Determine if a virtual table query is DISTINCT
578    #[must_use]
579    pub fn distinct(&self) -> DistinctMode {
580        match unsafe { ffi::sqlite3_vtab_distinct(self.0) } {
581            0 => DistinctMode::Ordered,
582            1 => DistinctMode::Grouped,
583            2 => DistinctMode::Distinct,
584            3 => DistinctMode::DistinctOrdered,
585            _ => DistinctMode::Ordered,
586        }
587    }
588
589    /// Constraint value
590    pub fn rhs_value(&self, constraint_idx: usize) -> Result<Option<ValueRef<'_>>> {
591        let idx = constraint_idx as c_int;
592        let mut p_value: *mut sqlite3_value = ptr::null_mut();
593        let rc = unsafe { ffi::sqlite3_vtab_rhs_value(self.0, idx, &raw mut p_value) };
594        if rc == ffi::SQLITE_NOTFOUND {
595            return Ok(None);
596        }
597        check(rc)?;
598        assert!(!p_value.is_null());
599        Ok(Some(unsafe { ValueRef::from_value(p_value) }))
600    }
601
602    /// Identify IN constraints
603    pub fn is_in_constraint(&self, constraint_idx: usize) -> Result<bool> {
604        self.check_constraint_index(constraint_idx)?;
605        let idx = constraint_idx as c_int;
606        Ok(unsafe { ffi::sqlite3_vtab_in(self.0, idx, -1) != 0 })
607    }
608
609    /// Handle IN constraints
610    pub fn set_in_constraint(&mut self, constraint_idx: usize, filter_all: bool) -> Result<bool> {
611        self.check_constraint_index(constraint_idx)?;
612        let idx = constraint_idx as c_int;
613        Ok(unsafe { ffi::sqlite3_vtab_in(self.0, idx, c_int::from(filter_all)) != 0 })
614    }
615
616    fn check_constraint_index(&self, idx: usize) -> Result<()> {
617        if idx >= unsafe { (*self.0).nConstraint } as usize {
618            return Err(err!(ffi::SQLITE_MISUSE, "{idx} is out of range"));
619        }
620        Ok(())
621    }
622}
623
624/// Determine if a virtual table query is DISTINCT
625#[non_exhaustive]
626#[derive(Debug, Eq, PartialEq)]
627pub enum DistinctMode {
628    /// This is the default expectation.
629    Ordered,
630    /// This mode is used when the query planner is doing a GROUP BY.
631    Grouped,
632    /// This mode is used for a DISTINCT query.
633    Distinct,
634    /// This mode is used for queries that have both DISTINCT and ORDER BY clauses.
635    DistinctOrdered,
636}
637
638/// Iterate on index constraint and its associated usage.
639pub struct IndexConstraintAndUsageIter<'a> {
640    iter: std::iter::Zip<
641        slice::Iter<'a, ffi::sqlite3_index_constraint>,
642        slice::IterMut<'a, ffi::sqlite3_index_constraint_usage>,
643    >,
644}
645
646impl<'a> Iterator for IndexConstraintAndUsageIter<'a> {
647    type Item = (IndexConstraint<'a>, IndexConstraintUsage<'a>);
648
649    #[inline]
650    fn next(&mut self) -> Option<(IndexConstraint<'a>, IndexConstraintUsage<'a>)> {
651        self.iter
652            .next()
653            .map(|raw| (IndexConstraint(raw.0), IndexConstraintUsage(raw.1)))
654    }
655
656    #[inline]
657    fn size_hint(&self) -> (usize, Option<usize>) {
658        self.iter.size_hint()
659    }
660}
661
662/// `feature = "vtab"`
663pub struct IndexConstraintIter<'a> {
664    iter: slice::Iter<'a, ffi::sqlite3_index_constraint>,
665}
666
667impl<'a> Iterator for IndexConstraintIter<'a> {
668    type Item = IndexConstraint<'a>;
669
670    #[inline]
671    fn next(&mut self) -> Option<IndexConstraint<'a>> {
672        self.iter.next().map(IndexConstraint)
673    }
674
675    #[inline]
676    fn size_hint(&self) -> (usize, Option<usize>) {
677        self.iter.size_hint()
678    }
679}
680
681/// WHERE clause constraint.
682pub struct IndexConstraint<'a>(&'a ffi::sqlite3_index_constraint);
683
684impl IndexConstraint<'_> {
685    /// Column constrained.  -1 for ROWID
686    #[inline]
687    #[must_use]
688    pub fn column(&self) -> c_int {
689        self.0.iColumn
690    }
691
692    /// Constraint operator
693    #[inline]
694    #[must_use]
695    pub fn operator(&self) -> IndexConstraintOp {
696        IndexConstraintOp::from(self.0.op)
697    }
698
699    /// True if this constraint is usable
700    #[inline]
701    #[must_use]
702    pub fn is_usable(&self) -> bool {
703        self.0.usable != 0
704    }
705}
706
707/// Information about what parameters to pass to
708/// [`VTabCursor::filter`].
709pub struct IndexConstraintUsage<'a>(&'a mut ffi::sqlite3_index_constraint_usage);
710
711impl IndexConstraintUsage<'_> {
712    /// if `argv_index` > 0, constraint is part of argv to
713    /// [`VTabCursor::filter`]
714    #[inline]
715    pub fn set_argv_index(&mut self, argv_index: c_int) {
716        self.0.argvIndex = argv_index;
717    }
718
719    /// if `omit`, do not code a test for this constraint
720    #[inline]
721    pub fn set_omit(&mut self, omit: bool) {
722        self.0.omit = std::ffi::c_uchar::from(omit);
723    }
724}
725
726/// `feature = "vtab"`
727pub struct OrderByIter<'a> {
728    iter: slice::Iter<'a, ffi::sqlite3_index_orderby>,
729}
730
731impl<'a> Iterator for OrderByIter<'a> {
732    type Item = OrderBy<'a>;
733
734    #[inline]
735    fn next(&mut self) -> Option<OrderBy<'a>> {
736        self.iter.next().map(OrderBy)
737    }
738
739    #[inline]
740    fn size_hint(&self) -> (usize, Option<usize>) {
741        self.iter.size_hint()
742    }
743}
744
745/// A column of the ORDER BY clause.
746pub struct OrderBy<'a>(&'a ffi::sqlite3_index_orderby);
747
748impl OrderBy<'_> {
749    /// Column number
750    #[inline]
751    #[must_use]
752    pub fn column(&self) -> c_int {
753        self.0.iColumn
754    }
755
756    /// True for DESC.  False for ASC.
757    #[inline]
758    #[must_use]
759    pub fn is_order_by_desc(&self) -> bool {
760        self.0.desc != 0
761    }
762}
763
764/// Virtual table cursor trait.
765///
766/// # Safety
767///
768/// Implementations must be like:
769/// ```rust,ignore
770/// #[repr(C)]
771/// struct MyTabCursor {
772///    /// Base class. Must be first
773///    base: rusqlite::vtab::sqlite3_vtab_cursor,
774///    /* Virtual table implementations will typically add additional fields */
775/// }
776/// ```
777///
778/// (See [SQLite doc](https://sqlite.org/c3ref/vtab_cursor.html))
779pub unsafe trait VTabCursor: Sized {
780    /// Begin a search of a virtual table.
781    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xfilter_method))
782    fn filter(&mut self, idx_num: c_int, idx_str: Option<&str>, args: &Filters<'_>) -> Result<()>;
783    /// Advance cursor to the next row of a result set initiated by
784    /// [`filter`](VTabCursor::filter). (See [SQLite doc](https://sqlite.org/vtab.html#the_xnext_method))
785    fn next(&mut self) -> Result<()>;
786    /// Must return `false` if the cursor currently points to a valid row of
787    /// data, or `true` otherwise.
788    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xeof_method))
789    fn eof(&self) -> bool;
790    /// Find the value for the `i`-th column of the current row.
791    /// `i` is zero-based so the first column is numbered 0.
792    /// May return its result back to SQLite using one of the specified `ctx`.
793    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xcolumn_method))
794    fn column(&self, ctx: &mut Context, i: c_int) -> Result<()>;
795    /// Return the rowid of row that the cursor is currently pointing at.
796    /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xrowid_method))
797    fn rowid(&self) -> Result<i64>;
798}
799
800/// Context is used by [`VTabCursor::column`] to specify the
801/// cell value.
802pub struct Context(*mut sqlite3_context);
803
804impl Context {
805    /// Set current cell value
806    #[inline]
807    pub fn set_result<T: ToSql>(&mut self, value: T) -> Result<()> {
808        let t = value.to_sql()?;
809        unsafe { set_result(self.0, &[], t) }
810    }
811
812    /// Determine if column access is for UPDATE
813    #[inline]
814    #[must_use]
815    pub fn no_change(&self) -> bool {
816        unsafe { ffi::sqlite3_vtab_nochange(self.0) != 0 }
817    }
818
819    /// Get the db connection handle via [sqlite3_context_db_handle](https://www.sqlite.org/c3ref/context_db_handle.html)
820    ///
821    /// # Safety
822    ///
823    /// This function is unsafe because improper use may impact the Connection.
824    pub unsafe fn get_connection(&self) -> Result<ConnectionRef<'_>> {
825        Ok(ConnectionRef {
826            conn: unsafe {
827                let handle = ffi::sqlite3_context_db_handle(self.0);
828                Connection::from_handle(handle)?
829            },
830            phantom: PhantomData,
831        })
832    }
833}
834
835/// A reference to a connection handle with a lifetime bound to context.
836pub struct ConnectionRef<'ctx> {
837    // comes from Connection::from_handle(sqlite3_context_db_handle(...))
838    // and is non-owning
839    conn: Connection,
840    phantom: PhantomData<&'ctx Context>,
841}
842
843impl Deref for ConnectionRef<'_> {
844    type Target = Connection;
845
846    #[inline]
847    fn deref(&self) -> &Connection {
848        &self.conn
849    }
850}
851
852/// Wrapper to [`VTabCursor::filter`] arguments, the values
853/// requested by [`VTab::best_index`].
854pub struct Filters<'a> {
855    values: Values<'a>,
856}
857impl<'a> Deref for Filters<'a> {
858    type Target = Values<'a>;
859
860    fn deref(&self) -> &Self::Target {
861        &self.values
862    }
863}
864impl Filters<'_> {
865    /// Find all elements on the right-hand side of an IN constraint
866    pub fn in_values(&self, idx: usize) -> Result<InValues<'_>> {
867        let list = self.args[idx];
868        Ok(InValues {
869            list,
870            phantom: PhantomData,
871            first: true,
872        })
873    }
874}
875
876/// IN values
877pub struct InValues<'a> {
878    list: *mut sqlite3_value,
879    phantom: PhantomData<Filters<'a>>,
880    first: bool,
881}
882impl<'a> fallible_iterator::FallibleIterator for InValues<'a> {
883    type Error = Error;
884    type Item = ValueRef<'a>;
885
886    fn next(&mut self) -> Result<Option<Self::Item>> {
887        let mut val: *mut sqlite3_value = ptr::null_mut();
888        let rc = unsafe {
889            if self.first {
890                self.first = false;
891                ffi::sqlite3_vtab_in_first(self.list, &raw mut val)
892            } else {
893                ffi::sqlite3_vtab_in_next(self.list, &raw mut val)
894            }
895        };
896        match rc {
897            ffi::SQLITE_OK => Ok(Some(unsafe { ValueRef::from_value(val) })),
898            ffi::SQLITE_DONE => Ok(None),
899            _ => Err(error_from_sqlite_code(rc, None)),
900        }
901    }
902}
903
904/// Wrapper to [`ffi::sqlite3_value`]s
905pub struct Values<'a> {
906    args: &'a [*mut sqlite3_value],
907}
908
909impl Values<'_> {
910    /// Returns the number of values.
911    #[inline]
912    #[must_use]
913    pub fn len(&self) -> usize {
914        self.args.len()
915    }
916
917    /// Returns `true` if there is no value.
918    #[inline]
919    #[must_use]
920    pub fn is_empty(&self) -> bool {
921        self.args.is_empty()
922    }
923
924    /// Returns value at `idx`
925    pub fn get<T: FromSql>(&self, idx: usize) -> Result<T> {
926        let arg = self.args[idx];
927        let value = unsafe { ValueRef::from_value(arg) };
928        FromSql::column_result(value).map_err(|err| match err {
929            FromSqlError::InvalidType => Error::InvalidFilterParameterType(idx, value.data_type()),
930            FromSqlError::Other(err) => {
931                Error::FromSqlConversionFailure(idx, value.data_type(), err)
932            }
933            FromSqlError::InvalidBlobSize { .. } => {
934                Error::FromSqlConversionFailure(idx, value.data_type(), Box::new(err))
935            }
936            FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i),
937            FromSqlError::Utf8Error(err) => Error::Utf8Error(idx, err),
938        })
939    }
940
941    /// Returns the subtype of value at `idx`.
942    ///
943    /// # Failure
944    ///
945    /// Will panic if `idx` is greater than or equal to
946    /// [`self.len()`](Values::len).
947    #[inline]
948    #[must_use]
949    pub fn get_subtype(&self, idx: usize) -> c_uint {
950        let arg = self.args[idx];
951        unsafe { ffi::sqlite3_value_subtype(arg) }
952    }
953
954    /// Return raw pointer at `idx`
955    /// # Safety
956    /// This function is unsafe because it uses raw pointer and cast
957    // `sqlite3_value_type` returns `SQLITE_NULL` for pointer.
958    // So it seems not possible to enhance `ValueRef::from_value`.
959    #[cfg(feature = "pointer")]
960    #[must_use]
961    pub unsafe fn get_pointer<'a, T: 'static>(
962        &self,
963        idx: usize,
964        ptr_type: &'static CStr,
965    ) -> Option<&'a T> {
966        let arg = self.args[idx];
967        debug_assert_eq!(unsafe { ffi::sqlite3_value_type(arg) }, ffi::SQLITE_NULL);
968        unsafe {
969            ffi::sqlite3_value_pointer(arg, ptr_type.as_ptr())
970                .cast::<T>()
971                .as_ref()
972        }
973    }
974
975    /// Turns `Values` into an iterator.
976    #[inline]
977    #[must_use]
978    pub fn iter(&self) -> ValueIter<'_> {
979        ValueIter {
980            iter: self.args.iter(),
981        }
982    }
983}
984
985impl<'a> IntoIterator for &'a Values<'a> {
986    type IntoIter = ValueIter<'a>;
987    type Item = ValueRef<'a>;
988
989    #[inline]
990    fn into_iter(self) -> ValueIter<'a> {
991        self.iter()
992    }
993}
994
995/// [`Values`] iterator.
996pub struct ValueIter<'a> {
997    iter: slice::Iter<'a, *mut sqlite3_value>,
998}
999
1000impl<'a> Iterator for ValueIter<'a> {
1001    type Item = ValueRef<'a>;
1002
1003    #[inline]
1004    fn next(&mut self) -> Option<ValueRef<'a>> {
1005        self.iter
1006            .next()
1007            .map(|&raw| unsafe { ValueRef::from_value(raw) })
1008    }
1009
1010    #[inline]
1011    fn size_hint(&self) -> (usize, Option<usize>) {
1012        self.iter.size_hint()
1013    }
1014}
1015
1016/// Wrapper to [`UpdateVTab::insert`] arguments
1017pub struct Inserts<'a> {
1018    values: Values<'a>,
1019}
1020impl<'a> Deref for Inserts<'a> {
1021    type Target = Values<'a>;
1022
1023    fn deref(&self) -> &Self::Target {
1024        &self.values
1025    }
1026}
1027impl Inserts<'_> {
1028    /// Determine the virtual table conflict policy
1029    ///
1030    /// # Safety
1031    /// This function is unsafe because it uses raw pointer
1032    #[must_use]
1033    pub unsafe fn on_conflict(&self, db: *mut ffi::sqlite3) -> ConflictMode {
1034        ConflictMode::from(unsafe { ffi::sqlite3_vtab_on_conflict(db) })
1035    }
1036}
1037
1038/// Wrapper to [`UpdateVTab::update`] arguments
1039pub struct Updates<'a> {
1040    values: Values<'a>,
1041}
1042impl<'a> Deref for Updates<'a> {
1043    type Target = Values<'a>;
1044
1045    fn deref(&self) -> &Self::Target {
1046        &self.values
1047    }
1048}
1049impl Updates<'_> {
1050    /// Returns `true` if and only
1051    /// - if the column corresponding to `idx` is unchanged by the UPDATE operation that the [`UpdateVTab::update`] method call was invoked to implement
1052    /// - and if and the prior [`VTabCursor::column`] method call that was invoked to extract the value for that column returned without setting a result.
1053    #[inline]
1054    #[must_use]
1055    pub fn no_change(&self, idx: usize) -> bool {
1056        unsafe { ffi::sqlite3_value_nochange(self.values.args[idx]) != 0 }
1057    }
1058
1059    /// Determine the virtual table conflict policy
1060    ///
1061    /// # Safety
1062    /// This function is unsafe because it uses raw pointer
1063    #[must_use]
1064    pub unsafe fn on_conflict(&self, db: *mut ffi::sqlite3) -> ConflictMode {
1065        ConflictMode::from(unsafe { ffi::sqlite3_vtab_on_conflict(db) })
1066    }
1067}
1068
1069/// Conflict resolution modes
1070#[non_exhaustive]
1071#[derive(Debug, Eq, PartialEq)]
1072pub enum ConflictMode {
1073    /// `SQLITE_ROLLBACK`
1074    Rollback,
1075    /// `SQLITE_IGNORE`
1076    Ignore,
1077    /// `SQLITE_FAIL`
1078    Fail,
1079    /// `SQLITE_ABORT`
1080    Abort,
1081    /// `SQLITE_REPLACE`
1082    Replace,
1083}
1084impl From<c_int> for ConflictMode {
1085    fn from(value: c_int) -> Self {
1086        match value {
1087            ffi::SQLITE_ROLLBACK => ConflictMode::Rollback,
1088            ffi::SQLITE_IGNORE => ConflictMode::Ignore,
1089            ffi::SQLITE_FAIL => ConflictMode::Fail,
1090            ffi::SQLITE_ABORT => ConflictMode::Abort,
1091            ffi::SQLITE_REPLACE => ConflictMode::Replace,
1092            _ => unreachable!("sqlite3_vtab_on_conflict returned invalid value"),
1093        }
1094    }
1095}
1096
1097impl Connection {
1098    /// Register a virtual table implementation.
1099    ///
1100    /// Step 3 of [Creating New Virtual Table
1101    /// Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
1102    #[inline]
1103    pub fn create_module<'vtab, T: VTab<'vtab>, M: Name>(
1104        &self,
1105        module_name: M,
1106        module: &'static Module<'vtab, T>,
1107        aux: Option<T::Aux>,
1108    ) -> Result<()> {
1109        self.db.borrow_mut().create_module(module_name, module, aux)
1110    }
1111}
1112
1113impl InnerConnection {
1114    fn create_module<'vtab, T: VTab<'vtab>, M: Name>(
1115        &mut self,
1116        module_name: M,
1117        module: &'static Module<'vtab, T>,
1118        aux: Option<T::Aux>,
1119    ) -> Result<()> {
1120        use crate::version;
1121        if version::version_number() < 3_009_000 && module.base.xCreate.is_none() {
1122            return Err(Error::ModuleError(format!(
1123                "Eponymous-only virtual table not supported by SQLite version {}",
1124                version::version()
1125            )));
1126        }
1127        let c_name = module_name.as_cstr()?;
1128        let r = match aux {
1129            Some(aux) => {
1130                let boxed_aux: *mut T::Aux = Box::into_raw(Box::new(aux));
1131                unsafe {
1132                    ffi::sqlite3_create_module_v2(
1133                        self.db(),
1134                        c_name.as_ptr(),
1135                        &raw const module.base,
1136                        boxed_aux.cast::<c_void>(),
1137                        Some(free_boxed_value::<T::Aux>),
1138                    )
1139                }
1140            }
1141            None => unsafe {
1142                ffi::sqlite3_create_module_v2(
1143                    self.db(),
1144                    c_name.as_ptr(),
1145                    &raw const module.base,
1146                    ptr::null_mut(),
1147                    None,
1148                )
1149            },
1150        };
1151        self.decode_result(r)
1152    }
1153}
1154
1155/// Escape double-quote (`"`) character occurrences by
1156/// doubling them (`""`).
1157#[must_use]
1158pub fn escape_double_quote(identifier: &str) -> Cow<'_, str> {
1159    if identifier.contains('"') {
1160        // escape quote by doubling them
1161        Owned(identifier.replace('"', "\"\""))
1162    } else {
1163        Borrowed(identifier)
1164    }
1165}
1166/// Dequote string
1167#[must_use]
1168pub fn dequote(mut s: &str) -> Cow<'_, str> {
1169    let mut chars = s.chars();
1170    let (Some(first), Some(last)) = (chars.next(), chars.next_back()) else {
1171        return Borrowed(s);
1172    };
1173    if (first == '"' || first == '\'' || first == '`' || first == '[')
1174        && (last == first || first == '[' && last == ']')
1175    {
1176        s = chars.as_str();
1177        if first != '[' && s.contains(first) {
1178            // handle inner escaped quote(s)
1179            let mut owned = String::with_capacity(s.len());
1180            let mut escaped = false;
1181            for c in s.chars() {
1182                if c == first {
1183                    if !escaped {
1184                        escaped = true;
1185                        continue;
1186                    }
1187                    escaped = false;
1188                } else if escaped {
1189                    // not properly escaped
1190                    return Borrowed(s);
1191                }
1192                owned.push(c);
1193            }
1194            if !escaped {
1195                return Owned(owned);
1196            }
1197        }
1198    }
1199    Borrowed(s)
1200}
1201/// The boolean can be one of:
1202/// ```text
1203/// 1 yes true on
1204/// 0 no false off
1205/// ```
1206#[must_use]
1207pub fn parse_boolean(s: &str) -> Option<bool> {
1208    if s.eq_ignore_ascii_case("yes")
1209        || s.eq_ignore_ascii_case("on")
1210        || s.eq_ignore_ascii_case("true")
1211        || s.eq("1")
1212    {
1213        Some(true)
1214    } else if s.eq_ignore_ascii_case("no")
1215        || s.eq_ignore_ascii_case("off")
1216        || s.eq_ignore_ascii_case("false")
1217        || s.eq("0")
1218    {
1219        Some(false)
1220    } else {
1221        None
1222    }
1223}
1224
1225/// `<param_name>=['"`[]?<param_value>['"`]]?` => `(<param_name>, <param_value>)`
1226pub fn parameter(c_slice: &[u8]) -> Result<(&str, Cow<'_, str>)> {
1227    let arg = std::str::from_utf8(c_slice)?.trim();
1228    match arg.split_once('=') {
1229        Some((key, value)) => {
1230            let param = key.trim();
1231            let value = dequote(value.trim());
1232            Ok((param, value))
1233        }
1234        _ => Err(Error::ModuleError(format!("illegal argument: '{arg}'"))),
1235    }
1236}
1237
1238unsafe extern "C" fn rust_create<'vtab, T>(
1239    db: *mut ffi::sqlite3,
1240    aux: *mut c_void,
1241    argc: c_int,
1242    argv: *const *const c_char,
1243    pp_vtab: *mut *mut sqlite3_vtab,
1244    err_msg: *mut *mut c_char,
1245) -> c_int
1246where
1247    T: CreateVTab<'vtab>,
1248{
1249    let mut conn = VTabConnection(db);
1250    let aux = aux.cast::<T::Aux>();
1251    unsafe {
1252        let args = slice::from_raw_parts(argv, argc as usize);
1253        let vec = args
1254            .iter()
1255            .map(|&cs| CStr::from_ptr(cs).to_bytes()) // FIXME .to_str() -> Result<&str, Utf8Error>
1256            .collect::<Vec<_>>();
1257        match T::create(&mut conn, aux.as_ref(), vec[0], vec[1], vec[2], &vec[3..]) {
1258            Ok((sql, vtab)) => {
1259                let rc = ffi::sqlite3_declare_vtab(db, sql.as_ptr());
1260                if rc == ffi::SQLITE_OK {
1261                    let boxed_vtab: *mut T = Box::into_raw(Box::new(vtab));
1262                    *pp_vtab = boxed_vtab.cast::<sqlite3_vtab>();
1263                    ffi::SQLITE_OK
1264                } else {
1265                    let err = error_from_sqlite_code(rc, None);
1266                    to_sqlite_error(&err, err_msg)
1267                }
1268            }
1269            Err(err) => to_sqlite_error(&err, err_msg),
1270        }
1271    }
1272}
1273
1274unsafe extern "C" fn rust_connect<'vtab, T>(
1275    db: *mut ffi::sqlite3,
1276    aux: *mut c_void,
1277    argc: c_int,
1278    argv: *const *const c_char,
1279    pp_vtab: *mut *mut sqlite3_vtab,
1280    err_msg: *mut *mut c_char,
1281) -> c_int
1282where
1283    T: VTab<'vtab>,
1284{
1285    let mut conn = VTabConnection(db);
1286    let aux = aux.cast::<T::Aux>();
1287    unsafe {
1288        let args = slice::from_raw_parts(argv, argc as usize);
1289        let vec = args
1290            .iter()
1291            .map(|&cs| CStr::from_ptr(cs).to_bytes()) // FIXME .to_str() -> Result<&str, Utf8Error>
1292            .collect::<Vec<_>>();
1293        match T::connect(&mut conn, aux.as_ref(), vec[0], vec[1], vec[2], &vec[3..]) {
1294            Ok((sql, vtab)) => {
1295                let rc = ffi::sqlite3_declare_vtab(db, sql.as_ptr());
1296                if rc == ffi::SQLITE_OK {
1297                    let boxed_vtab: *mut T = Box::into_raw(Box::new(vtab));
1298                    *pp_vtab = boxed_vtab.cast::<sqlite3_vtab>();
1299                    ffi::SQLITE_OK
1300                } else {
1301                    let err = error_from_sqlite_code(rc, None);
1302                    to_sqlite_error(&err, err_msg)
1303                }
1304            }
1305            Err(err) => to_sqlite_error(&err, err_msg),
1306        }
1307    }
1308}
1309
1310unsafe extern "C" fn rust_best_index<'vtab, T>(
1311    vtab: *mut sqlite3_vtab,
1312    info: *mut ffi::sqlite3_index_info,
1313) -> c_int
1314where
1315    T: VTab<'vtab>,
1316{
1317    let vt = vtab.cast::<T>();
1318    let mut idx_info = IndexInfo(info);
1319    unsafe {
1320        match (*vt).best_index(&mut idx_info) {
1321            Ok(true) => ffi::SQLITE_OK,
1322            Ok(false) => ffi::SQLITE_CONSTRAINT,
1323            err => vtab_error(vtab, err),
1324        }
1325    }
1326}
1327
1328unsafe extern "C" fn rust_disconnect<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1329where
1330    T: VTab<'vtab>,
1331{
1332    if vtab.is_null() {
1333        return ffi::SQLITE_OK;
1334    }
1335    let vtab = vtab.cast::<T>();
1336    drop(unsafe { Box::from_raw(vtab) });
1337    ffi::SQLITE_OK
1338}
1339
1340unsafe extern "C" fn rust_destroy<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1341where
1342    T: CreateVTab<'vtab>,
1343{
1344    if vtab.is_null() {
1345        return ffi::SQLITE_OK;
1346    }
1347    let vt = vtab.cast::<T>();
1348    unsafe {
1349        match (*vt).destroy() {
1350            Ok(()) => {
1351                drop(Box::from_raw(vt));
1352                ffi::SQLITE_OK
1353            }
1354            err => vtab_error(vtab, err),
1355        }
1356    }
1357}
1358
1359unsafe extern "C" fn rust_open<'vtab, T>(
1360    vtab: *mut sqlite3_vtab,
1361    pp_cursor: *mut *mut sqlite3_vtab_cursor,
1362) -> c_int
1363where
1364    T: VTab<'vtab> + 'vtab,
1365{
1366    let vt = vtab.cast::<T>();
1367    unsafe {
1368        match (*vt).open() {
1369            Ok(cursor) => {
1370                let boxed_cursor: *mut T::Cursor = Box::into_raw(Box::new(cursor));
1371                *pp_cursor = boxed_cursor.cast::<sqlite3_vtab_cursor>();
1372                ffi::SQLITE_OK
1373            }
1374            err => vtab_error(vtab, err),
1375        }
1376    }
1377}
1378
1379unsafe extern "C" fn rust_close<C>(cursor: *mut sqlite3_vtab_cursor) -> c_int
1380where
1381    C: VTabCursor,
1382{
1383    let cr = cursor.cast::<C>();
1384    drop(unsafe { Box::from_raw(cr) });
1385    ffi::SQLITE_OK
1386}
1387
1388unsafe extern "C" fn rust_filter<C>(
1389    cursor: *mut sqlite3_vtab_cursor,
1390    idx_num: c_int,
1391    idx_str: *const c_char,
1392    argc: c_int,
1393    argv: *mut *mut sqlite3_value,
1394) -> c_int
1395where
1396    C: VTabCursor,
1397{
1398    use std::str;
1399    unsafe {
1400        let idx_name = if idx_str.is_null() {
1401            None
1402        } else {
1403            let c_slice = CStr::from_ptr(idx_str).to_bytes();
1404            Some(str::from_utf8_unchecked(c_slice))
1405        };
1406        let args = slice::from_raw_parts_mut(argv, argc as usize);
1407        let values = Values { args };
1408        let cr = cursor.cast::<C>();
1409        cursor_error(cursor, (*cr).filter(idx_num, idx_name, &Filters { values }))
1410    }
1411}
1412
1413unsafe extern "C" fn rust_next<C>(cursor: *mut sqlite3_vtab_cursor) -> c_int
1414where
1415    C: VTabCursor,
1416{
1417    let cr = cursor.cast::<C>();
1418    unsafe { cursor_error(cursor, (*cr).next()) }
1419}
1420
1421unsafe extern "C" fn rust_eof<C>(cursor: *mut sqlite3_vtab_cursor) -> c_int
1422where
1423    C: VTabCursor,
1424{
1425    let cr = cursor.cast::<C>();
1426    unsafe { c_int::from((*cr).eof()) }
1427}
1428
1429unsafe extern "C" fn rust_column<C>(
1430    cursor: *mut sqlite3_vtab_cursor,
1431    ctx: *mut sqlite3_context,
1432    i: c_int,
1433) -> c_int
1434where
1435    C: VTabCursor,
1436{
1437    let cr = cursor.cast::<C>();
1438    let mut ctxt = Context(ctx);
1439    unsafe { result_error(ctx, (*cr).column(&mut ctxt, i)) }
1440}
1441
1442unsafe extern "C" fn rust_rowid<C>(
1443    cursor: *mut sqlite3_vtab_cursor,
1444    p_rowid: *mut ffi::sqlite3_int64,
1445) -> c_int
1446where
1447    C: VTabCursor,
1448{
1449    let cr = cursor.cast::<C>();
1450    unsafe {
1451        match (*cr).rowid() {
1452            Ok(rowid) => {
1453                *p_rowid = rowid;
1454                ffi::SQLITE_OK
1455            }
1456            err => cursor_error(cursor, err),
1457        }
1458    }
1459}
1460
1461unsafe extern "C" fn rust_update<'vtab, T>(
1462    vtab: *mut sqlite3_vtab,
1463    argc: c_int,
1464    argv: *mut *mut sqlite3_value,
1465    p_rowid: *mut ffi::sqlite3_int64,
1466) -> c_int
1467where
1468    T: UpdateVTab<'vtab> + 'vtab,
1469{
1470    assert!(argc >= 1);
1471    let vt = vtab.cast::<T>();
1472    unsafe {
1473        let args = slice::from_raw_parts_mut(argv, argc as usize);
1474        let r = if args.len() == 1 {
1475            (*vt).delete(ValueRef::from_value(args[0]))
1476        } else if ffi::sqlite3_value_type(args[0]) == ffi::SQLITE_NULL {
1477            // TODO Make the distinction between argv[1] == NULL and argv[1] != NULL ?
1478            let values = Values { args };
1479            match (*vt).insert(&Inserts { values }) {
1480                Ok(rowid) => {
1481                    *p_rowid = rowid;
1482                    Ok(())
1483                }
1484                Err(e) => Err(e),
1485            }
1486        } else {
1487            let values = Values { args };
1488            (*vt).update(&Updates { values })
1489        };
1490        vtab_error(vtab, r)
1491    }
1492}
1493
1494unsafe extern "C" fn rust_begin<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1495where
1496    T: TransactionVTab<'vtab>,
1497{
1498    let vt = vtab.cast::<T>();
1499    unsafe { vtab_error(vtab, (*vt).begin()) }
1500}
1501unsafe extern "C" fn rust_sync<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1502where
1503    T: TransactionVTab<'vtab>,
1504{
1505    let vt = vtab.cast::<T>();
1506    unsafe { vtab_error(vtab, (*vt).sync()) }
1507}
1508unsafe extern "C" fn rust_commit<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1509where
1510    T: TransactionVTab<'vtab>,
1511{
1512    let vt = vtab.cast::<T>();
1513    unsafe { vtab_error(vtab, (*vt).commit()) }
1514}
1515unsafe extern "C" fn rust_rollback<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1516where
1517    T: TransactionVTab<'vtab>,
1518{
1519    let vt = vtab.cast::<T>();
1520    unsafe { vtab_error(vtab, (*vt).rollback()) }
1521}
1522
1523/// Virtual table cursors can set an error message by assigning a string to
1524/// `zErrMsg`.
1525unsafe fn cursor_error<T>(cursor: *mut sqlite3_vtab_cursor, result: Result<T>) -> c_int {
1526    unsafe { vtab_error((*cursor).pVtab, result) }
1527}
1528
1529/// Virtual tables can set an error message by assigning a string to
1530/// `zErrMsg`.
1531unsafe fn vtab_error<T>(vtab: *mut sqlite3_vtab, result: Result<T>) -> c_int {
1532    unsafe {
1533        match result {
1534            Ok(_) => ffi::SQLITE_OK,
1535            Err(Error::SqliteFailure(err, s)) => {
1536                if let Some(err_msg) = s {
1537                    set_err_msg(vtab, &err_msg);
1538                }
1539                err.extended_code
1540            }
1541            Err(err) => {
1542                set_err_msg(vtab, &err.to_string());
1543                ffi::SQLITE_ERROR
1544            }
1545        }
1546    }
1547}
1548
1549/// Virtual tables methods can set an error message by assigning a string to
1550/// `zErrMsg`.
1551#[cold]
1552unsafe fn set_err_msg(vtab: *mut sqlite3_vtab, err_msg: &str) {
1553    unsafe {
1554        if !(*vtab).zErrMsg.is_null() {
1555            sqlite3_free((*vtab).zErrMsg.cast::<c_void>());
1556        }
1557        (*vtab).zErrMsg = alloc(err_msg);
1558    }
1559}
1560
1561/// To raise an error, the `column` method should use this method to set the
1562/// error message and return the error code.
1563#[cold]
1564unsafe fn result_error<T>(ctx: *mut sqlite3_context, result: Result<T>) -> c_int {
1565    unsafe {
1566        match result {
1567            Ok(_) => ffi::SQLITE_OK,
1568            Err(Error::SqliteFailure(err, s)) => {
1569                match err.extended_code {
1570                    ffi::SQLITE_TOOBIG => {
1571                        ffi::sqlite3_result_error_toobig(ctx);
1572                    }
1573                    ffi::SQLITE_NOMEM => {
1574                        ffi::sqlite3_result_error_nomem(ctx);
1575                    }
1576                    code => {
1577                        ffi::sqlite3_result_error_code(ctx, code);
1578                        if let Some(Ok(cstr)) = s.map(|s| str_to_cstring(&s)) {
1579                            ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
1580                        }
1581                    }
1582                }
1583                err.extended_code
1584            }
1585            Err(err) => {
1586                ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_ERROR);
1587                if let Ok(cstr) = str_to_cstring(&err.to_string()) {
1588                    ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
1589                }
1590                ffi::SQLITE_ERROR
1591            }
1592        }
1593    }
1594}
1595
1596#[cfg(feature = "array")]
1597pub mod array;
1598#[cfg(feature = "csvtab")]
1599pub mod csvtab;
1600#[cfg(feature = "series")]
1601pub mod series; // SQLite >= 3.9.0
1602#[cfg(all(test, not(miri)))]
1603mod vtablog;
1604
1605#[cfg(test)]
1606mod test {
1607    use std::borrow::Cow;
1608
1609    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
1610    use wasm_bindgen_test::wasm_bindgen_test as test;
1611
1612    #[test]
1613    fn test_dequote() {
1614        assert_eq!("", super::dequote(""));
1615        assert_eq!("'", super::dequote("'"));
1616        assert_eq!("\"", super::dequote("\""));
1617
1618        assert_eq!("'\"", super::dequote("'\""));
1619
1620        assert_eq!("", super::dequote("''"));
1621        assert_eq!("", super::dequote("\"\""));
1622        assert_eq!("", super::dequote("``"));
1623        assert_eq!("", super::dequote("[]"));
1624
1625        assert_eq!("x", super::dequote("'x'"));
1626        assert_eq!("x", super::dequote("\"x\""));
1627        assert_eq!("x", super::dequote("x"));
1628        assert_eq!("x", super::dequote("`x`"));
1629        assert_eq!("x", super::dequote("[x]"));
1630
1631        assert_eq!("x'", super::dequote("'x'''"));
1632        assert_eq!("x`", super::dequote("`x```"));
1633
1634        assert_eq!("x'", super::dequote("'x''"));
1635        assert_eq!("x`", super::dequote("`x``"));
1636    }
1637    #[test]
1638    fn test_parse_boolean() {
1639        assert_eq!(None, super::parse_boolean(""));
1640        assert_eq!(Some(true), super::parse_boolean("1"));
1641        assert_eq!(Some(true), super::parse_boolean("yes"));
1642        assert_eq!(Some(true), super::parse_boolean("on"));
1643        assert_eq!(Some(true), super::parse_boolean("true"));
1644        assert_eq!(Some(false), super::parse_boolean("0"));
1645        assert_eq!(Some(false), super::parse_boolean("no"));
1646        assert_eq!(Some(false), super::parse_boolean("off"));
1647        assert_eq!(Some(false), super::parse_boolean("false"));
1648    }
1649    #[test]
1650    fn test_parse_parameters() {
1651        assert_eq!(
1652            Ok(("key", Cow::Borrowed("value"))),
1653            super::parameter(b"key='value'")
1654        );
1655        assert_eq!(
1656            Ok(("key", Cow::Borrowed("foo=bar"))),
1657            super::parameter(b"key='foo=bar'")
1658        );
1659    }
1660
1661    #[cfg(all(feature = "functions", not(miri)))]
1662    #[test]
1663    fn test_values_get_subtype() -> crate::Result<()> {
1664        use std::ffi::{CStr, c_int, c_uint};
1665        use std::sync::atomic::{AtomicU32, Ordering};
1666
1667        use crate::ffi;
1668        use crate::functions::{FunctionFlags, SqlFnArg, SubType};
1669        use crate::types::Value;
1670        use crate::vtab::{
1671            Context, CreateVTab, Filters, IndexConstraintOp, IndexInfo, Inserts, Module,
1672            UpdateVTab, Updates, VTab, VTabConnection, VTabCursor, VTabKind,
1673        };
1674        use crate::{Connection, Result};
1675
1676        static FILTER_SUBTYPE: AtomicU32 = AtomicU32::new(0);
1677        static INSERT_SUBTYPE: AtomicU32 = AtomicU32::new(0);
1678
1679        fn set_subtype(ctx: &crate::functions::Context<'_>) -> Result<(SqlFnArg, SubType)> {
1680            let value = ctx.get_arg(0);
1681            let sub_type = ctx.get::<c_uint>(1)?;
1682            Ok((value, Some(sub_type)))
1683        }
1684
1685        #[repr(C)]
1686        struct SubTypeVTab {
1687            base: ffi::sqlite3_vtab,
1688        }
1689        #[repr(C)]
1690        struct SubTypeVTabCursor {
1691            base: ffi::sqlite3_vtab_cursor,
1692        }
1693
1694        unsafe impl<'vtab> VTab<'vtab> for SubTypeVTab {
1695            type Aux = ();
1696            type Cursor = SubTypeVTabCursor;
1697
1698            fn connect(
1699                _db: &mut VTabConnection,
1700                _aux: Option<&Self::Aux>,
1701                _module_name: &[u8],
1702                _database_name: &[u8],
1703                _table_name: &[u8],
1704                _args: &[&[u8]],
1705            ) -> Result<(Cow<'static, CStr>, Self)> {
1706                Ok((
1707                    Cow::Borrowed(c"CREATE TABLE x(value BLOB)"),
1708                    Self {
1709                        base: ffi::sqlite3_vtab::default(),
1710                    },
1711                ))
1712            }
1713
1714            fn best_index(&self, info: &mut IndexInfo) -> Result<bool> {
1715                let mut argv_index = 1;
1716                let mut usable_constraints = Vec::new();
1717                for (i, constraint) in info.constraints().enumerate() {
1718                    if constraint.is_usable()
1719                        && constraint.operator() == IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_EQ
1720                    {
1721                        usable_constraints.push(i);
1722                    }
1723                }
1724                for i in usable_constraints {
1725                    let mut usage = info.constraint_usage(i);
1726                    usage.set_argv_index(argv_index);
1727                    usage.set_omit(true);
1728                    argv_index += 1;
1729                }
1730                info.set_estimated_cost(1.0);
1731                Ok(true)
1732            }
1733
1734            fn open(&'vtab mut self) -> Result<Self::Cursor> {
1735                Ok(SubTypeVTabCursor {
1736                    base: ffi::sqlite3_vtab_cursor::default(),
1737                })
1738            }
1739        }
1740
1741        impl CreateVTab<'_> for SubTypeVTab {
1742            const KIND: VTabKind = VTabKind::Default;
1743        }
1744
1745        impl UpdateVTab<'_> for SubTypeVTab {
1746            fn delete(&mut self, _arg: crate::types::ValueRef<'_>) -> Result<()> {
1747                Ok(())
1748            }
1749
1750            fn insert(&mut self, args: &Inserts<'_>) -> Result<i64> {
1751                // args[0]: old rowid (NULL for new rows)
1752                // args[1]: new rowid
1753                // args[2]: first column value
1754                INSERT_SUBTYPE.store(args.get_subtype(2), Ordering::SeqCst);
1755                Ok(0)
1756            }
1757
1758            fn update(&mut self, _args: &Updates<'_>) -> Result<()> {
1759                Ok(())
1760            }
1761        }
1762
1763        unsafe impl VTabCursor for SubTypeVTabCursor {
1764            fn filter(
1765                &mut self,
1766                _idx_num: c_int,
1767                _idx_str: Option<&str>,
1768                args: &Filters<'_>,
1769            ) -> Result<()> {
1770                FILTER_SUBTYPE.store(args.get_subtype(0), Ordering::SeqCst);
1771                Ok(())
1772            }
1773
1774            fn next(&mut self) -> Result<()> {
1775                Ok(())
1776            }
1777
1778            fn eof(&self) -> bool {
1779                true
1780            }
1781
1782            fn column(&self, ctx: &mut Context, _i: c_int) -> Result<()> {
1783                ctx.set_result(Value::Null)
1784            }
1785
1786            fn rowid(&self) -> Result<i64> {
1787                Ok(0)
1788            }
1789        }
1790
1791        let db = Connection::open_in_memory()?;
1792        db.create_scalar_function(
1793            c"set_subtype",
1794            2,
1795            FunctionFlags::SQLITE_UTF8 | FunctionFlags::SQLITE_RESULT_SUBTYPE,
1796            set_subtype,
1797        )?;
1798        const MODULE: Module<SubTypeVTab> = Module::update_module();
1799        db.create_module(c"subtype_vtab", &MODULE, None)?;
1800
1801        db.execute("CREATE VIRTUAL TABLE st USING subtype_vtab()", [])?;
1802
1803        FILTER_SUBTYPE.store(0, Ordering::SeqCst);
1804        INSERT_SUBTYPE.store(0, Ordering::SeqCst);
1805
1806        // Test filter callback can read subtype from scalar function result.
1807        let _: Result<String> = db.query_row(
1808            "SELECT value FROM st WHERE value = set_subtype('a', 223)",
1809            [],
1810            |row| row.get(0),
1811        );
1812        assert_eq!(FILTER_SUBTYPE.load(Ordering::SeqCst), 223);
1813
1814        // Test insert callback can read subtype from scalar function result.
1815        // Use a BLOB literal as input so the value remains a BLOB when inserted.
1816        db.execute(
1817            "INSERT INTO st(rowid, value) VALUES (1, set_subtype(X'62', 225))",
1818            [],
1819        )?;
1820        assert_eq!(INSERT_SUBTYPE.load(Ordering::SeqCst), 225);
1821
1822        Ok(())
1823    }
1824}