Debian Codegraph @

third_party/rust/rusqlite/src/vtab/mod.rs

raw
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))
12 use std::borrow::Cow::{self, Borrowed, Owned};
13 use std::marker::PhantomData;
14 use std::os::raw::{c_char, c_int, c_void};
15 use std::ptr;
16 use std::slice;
17
18 use crate::context::set_result;
19 use crate::error::{error_from_sqlite_code, to_sqlite_error};
20 use crate::ffi;
21 pub use crate::ffi::{sqlite3_vtab, sqlite3_vtab_cursor};
22 use crate::types::{FromSql, FromSqlError, ToSql, ValueRef};
23 use crate::util::alloc;
24 use crate::{str_to_cstring, Connection, Error, InnerConnection, Result};
25
26 // let conn: Connection = ...;
27 // let mod: Module = ...; // VTab builder
28 // conn.create_module("module", mod);
29 //
30 // conn.execute("CREATE VIRTUAL TABLE foo USING module(...)");
31 // \-> Module::xcreate
32 // |-> let vtab: VTab = ...; // on the heap
33 // \-> conn.declare_vtab("CREATE TABLE foo (...)");
34 // conn = Connection::open(...);
35 // \-> Module::xconnect
36 // |-> let vtab: VTab = ...; // on the heap
37 // \-> conn.declare_vtab("CREATE TABLE foo (...)");
38 //
39 // conn.close();
40 // \-> vtab.xdisconnect
41 // conn.execute("DROP TABLE foo");
42 // \-> vtab.xDestroy
43 //
44 // let stmt = conn.prepare("SELECT ... FROM foo WHERE ...");
45 // \-> vtab.xbestindex
46 // stmt.query().next();
47 // \-> vtab.xopen
48 // |-> let cursor: VTabCursor = ...; // on the heap
49 // |-> cursor.xfilter or xnext
50 // |-> cursor.xeof
51 // \-> if not eof { cursor.column or xrowid } else { cursor.xclose }
52 //
53
54 // db: *mut ffi::sqlite3 => VTabConnection
55 // module: *const ffi::sqlite3_module => Module
56 // aux: *mut c_void => Module::Aux
57 // ffi::sqlite3_vtab => VTab
58 // ffi::sqlite3_vtab_cursor => VTabCursor
59
60 /// Virtual table kind
61 pub enum VTabKind {
62 /// Non-eponymous
63 Default,
64 /// [`create`](CreateVTab::create) == [`connect`](VTab::connect)
65 ///
66 /// See [SQLite doc](https://sqlite.org/vtab.html#eponymous_virtual_tables)
67 Eponymous,
68 /// No [`create`](CreateVTab::create) / [`destroy`](CreateVTab::destroy) or
69 /// not used
70 ///
71 /// SQLite >= 3.9.0
72 ///
73 /// See [SQLite doc](https://sqlite.org/vtab.html#eponymous_only_virtual_tables)
74 EponymousOnly,
75 }
76
77 /// Virtual table module
78 ///
79 /// (See [SQLite doc](https://sqlite.org/c3ref/module.html))
80 #[repr(transparent)]
81 pub struct Module<'vtab, T: VTab<'vtab>> {
82 base: ffi::sqlite3_module,
83 phantom: PhantomData<&'vtab T>,
84 }
85
86 unsafe impl<'vtab, T: VTab<'vtab>> Send for Module<'vtab, T> {}
87 unsafe impl<'vtab, T: VTab<'vtab>> Sync for Module<'vtab, T> {}
88
89 union 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.
97 const ZERO_MODULE: ffi::sqlite3_module = unsafe {
98 ModuleZeroHack {
99 bytes: [0_u8; size_of::<ffi::sqlite3_module>()],
100 }
101 .module
102 };
103
104 macro_rules! module {
105 ($lt:lifetime, $vt:ty, $ct:ty, $xc:expr, $xd:expr, $xu:expr) => {
106 &Module {
107 base: ffi::sqlite3_module {
108 // We don't use V3
109 iVersion: 2,
110 xCreate: $xc,
111 xConnect: Some(rust_connect::<$vt>),
112 xBestIndex: Some(rust_best_index::<$vt>),
113 xDisconnect: Some(rust_disconnect::<$vt>),
114 xDestroy: $xd,
115 xOpen: Some(rust_open::<$vt>),
116 xClose: Some(rust_close::<$ct>),
117 xFilter: Some(rust_filter::<$ct>),
118 xNext: Some(rust_next::<$ct>),
119 xEof: Some(rust_eof::<$ct>),
120 xColumn: Some(rust_column::<$ct>),
121 xRowid: Some(rust_rowid::<$ct>), // FIXME optional
122 xUpdate: $xu,
123 xBegin: None,
124 xSync: None,
125 xCommit: None,
126 xRollback: None,
127 xFindFunction: None,
128 xRename: None,
129 xSavepoint: None,
130 xRelease: None,
131 xRollbackTo: None,
132 ..ZERO_MODULE
133 },
134 phantom: PhantomData::<&$lt $vt>,
135 }
136 };
137 }
138
139 /// Create a modifiable virtual table implementation.
140 ///
141 /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
142 #[must_use]
143 pub fn update_module<'vtab, T: UpdateVTab<'vtab>>() -> &'static Module<'vtab, T> {
144 match T::KIND {
145 VTabKind::EponymousOnly => {
146 module!('vtab, T, T::Cursor, None, None, Some(rust_update::<T>))
147 }
148 VTabKind::Eponymous => {
149 module!('vtab, T, T::Cursor, Some(rust_connect::<T>), Some(rust_disconnect::<T>), Some(rust_update::<T>))
150 }
151 _ => {
152 module!('vtab, T, T::Cursor, Some(rust_create::<T>), Some(rust_destroy::<T>), Some(rust_update::<T>))
153 }
154 }
155 }
156
157 /// Create a read-only virtual table implementation.
158 ///
159 /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
160 #[must_use]
161 pub fn read_only_module<'vtab, T: CreateVTab<'vtab>>() -> &'static Module<'vtab, T> {
162 match T::KIND {
163 VTabKind::EponymousOnly => eponymous_only_module(),
164 VTabKind::Eponymous => {
165 // A virtual table is eponymous if its xCreate method is the exact same function
166 // as the xConnect method
167 module!('vtab, T, T::Cursor, Some(rust_connect::<T>), Some(rust_disconnect::<T>), None)
168 }
169 _ => {
170 // The xConnect and xCreate methods may do the same thing, but they must be
171 // different so that the virtual table is not an eponymous virtual table.
172 module!('vtab, T, T::Cursor, Some(rust_create::<T>), Some(rust_destroy::<T>), None)
173 }
174 }
175 }
176
177 /// Create an eponymous only virtual table implementation.
178 ///
179 /// Step 2 of [Creating New Virtual Table Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
180 #[must_use]
181 pub fn eponymous_only_module<'vtab, T: VTab<'vtab>>() -> &'static Module<'vtab, T> {
182 // For eponymous-only virtual tables, the xCreate method is NULL
183 module!('vtab, T, T::Cursor, None, None, None)
184 }
185
186 /// Virtual table configuration options
187 #[repr(i32)]
188 #[non_exhaustive]
189 #[derive(Debug, Clone, Copy, Eq, PartialEq)]
190 pub enum VTabConfig {
191 /// Equivalent to `SQLITE_VTAB_CONSTRAINT_SUPPORT`
192 ConstraintSupport = 1,
193 /// Equivalent to `SQLITE_VTAB_INNOCUOUS`
194 Innocuous = 2,
195 /// Equivalent to `SQLITE_VTAB_DIRECTONLY`
196 DirectOnly = 3,
197 /// Equivalent to `SQLITE_VTAB_USES_ALL_SCHEMAS`
198 UsesAllSchemas = 4,
199 }
200
201 /// `feature = "vtab"`
202 pub struct VTabConnection(*mut ffi::sqlite3);
203
204 impl VTabConnection {
205 /// Configure various facets of the virtual table interface
206 pub fn config(&mut self, config: VTabConfig) -> Result<()> {
207 crate::error::check(unsafe { ffi::sqlite3_vtab_config(self.0, config as c_int) })
208 }
209
210 // TODO sqlite3_vtab_on_conflict (http://sqlite.org/c3ref/vtab_on_conflict.html) & xUpdate
211
212 /// Get access to the underlying SQLite database connection handle.
213 ///
214 /// # Warning
215 ///
216 /// You should not need to use this function. If you do need to, please
217 /// [open an issue on the rusqlite repository](https://github.com/rusqlite/rusqlite/issues) and describe
218 /// your use case.
219 ///
220 /// # Safety
221 ///
222 /// This function is unsafe because it gives you raw access
223 /// to the SQLite connection, and what you do with it could impact the
224 /// safety of this `Connection`.
225 pub unsafe fn handle(&mut self) -> *mut ffi::sqlite3 {
226 self.0
227 }
228 }
229
230 /// Eponymous-only virtual table instance trait.
231 ///
232 /// # Safety
233 ///
234 /// The first item in a struct implementing `VTab` must be
235 /// `rusqlite::sqlite3_vtab`, and the struct must be `#[repr(C)]`.
236 ///
237 /// ```rust,ignore
238 /// #[repr(C)]
239 /// struct MyTab {
240 /// /// Base class. Must be first
241 /// base: rusqlite::vtab::sqlite3_vtab,
242 /// /* Virtual table implementations will typically add additional fields */
243 /// }
244 /// ```
245 ///
246 /// (See [SQLite doc](https://sqlite.org/c3ref/vtab.html))
247 pub unsafe trait VTab<'vtab>: Sized {
248 /// Client data passed to [`Connection::create_module`].
249 type Aux;
250 /// Specific cursor implementation
251 type Cursor: VTabCursor;
252
253 /// Establish a new connection to an existing virtual table.
254 ///
255 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xconnect_method))
256 fn connect(
257 db: &mut VTabConnection,
258 aux: Option<&Self::Aux>,
259 args: &[&[u8]],
260 ) -> Result<(String, Self)>;
261
262 /// Determine the best way to access the virtual table.
263 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xbestindex_method))
264 fn best_index(&self, info: &mut IndexInfo) -> Result<()>;
265
266 /// Create a new cursor used for accessing a virtual table.
267 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xopen_method))
268 fn open(&'vtab mut self) -> Result<Self::Cursor>;
269 }
270
271 /// Read-only virtual table instance trait.
272 ///
273 /// (See [SQLite doc](https://sqlite.org/c3ref/vtab.html))
274 pub trait CreateVTab<'vtab>: VTab<'vtab> {
275 /// For [`EponymousOnly`](VTabKind::EponymousOnly),
276 /// [`create`](CreateVTab::create) and [`destroy`](CreateVTab::destroy) are
277 /// not called
278 const KIND: VTabKind;
279 /// Create a new instance of a virtual table in response to a CREATE VIRTUAL
280 /// TABLE statement. The `db` parameter is a pointer to the SQLite
281 /// database connection that is executing the CREATE VIRTUAL TABLE
282 /// statement.
283 ///
284 /// Call [`connect`](VTab::connect) by default.
285 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xcreate_method))
286 fn create(
287 db: &mut VTabConnection,
288 aux: Option<&Self::Aux>,
289 args: &[&[u8]],
290 ) -> Result<(String, Self)> {
291 Self::connect(db, aux, args)
292 }
293
294 /// Destroy the underlying table implementation. This method undoes the work
295 /// of [`create`](CreateVTab::create).
296 ///
297 /// Do nothing by default.
298 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xdestroy_method))
299 fn destroy(&self) -> Result<()> {
300 Ok(())
301 }
302 }
303
304 /// Writable virtual table instance trait.
305 ///
306 /// (See [SQLite doc](https://sqlite.org/vtab.html#xupdate))
307 pub trait UpdateVTab<'vtab>: CreateVTab<'vtab> {
308 /// Delete rowid or PK
309 fn delete(&mut self, arg: ValueRef<'_>) -> Result<()>;
310 /// Insert: `args[0] == NULL: old rowid or PK, args[1]: new rowid or PK,
311 /// args[2]: ...`
312 ///
313 /// Return the new rowid.
314 // TODO Make the distinction between argv[1] == NULL and argv[1] != NULL ?
315 fn insert(&mut self, args: &Values<'_>) -> Result<i64>;
316 /// Update: `args[0] != NULL: old rowid or PK, args[1]: new row id or PK,
317 /// args[2]: ...`
318 fn update(&mut self, args: &Values<'_>) -> Result<()>;
319 }
320
321 /// Index constraint operator.
322 /// See [Virtual Table Constraint Operator Codes](https://sqlite.org/c3ref/c_index_constraint_eq.html) for details.
323 #[derive(Debug, Eq, PartialEq)]
324 #[allow(missing_docs)]
325 #[expect(non_camel_case_types)]
326 pub enum IndexConstraintOp {
327 SQLITE_INDEX_CONSTRAINT_EQ,
328 SQLITE_INDEX_CONSTRAINT_GT,
329 SQLITE_INDEX_CONSTRAINT_LE,
330 SQLITE_INDEX_CONSTRAINT_LT,
331 SQLITE_INDEX_CONSTRAINT_GE,
332 SQLITE_INDEX_CONSTRAINT_MATCH,
333 SQLITE_INDEX_CONSTRAINT_LIKE, // 3.10.0
334 SQLITE_INDEX_CONSTRAINT_GLOB, // 3.10.0
335 SQLITE_INDEX_CONSTRAINT_REGEXP, // 3.10.0
336 SQLITE_INDEX_CONSTRAINT_NE, // 3.21.0
337 SQLITE_INDEX_CONSTRAINT_ISNOT, // 3.21.0
338 SQLITE_INDEX_CONSTRAINT_ISNOTNULL, // 3.21.0
339 SQLITE_INDEX_CONSTRAINT_ISNULL, // 3.21.0
340 SQLITE_INDEX_CONSTRAINT_IS, // 3.21.0
341 SQLITE_INDEX_CONSTRAINT_LIMIT, // 3.38.0
342 SQLITE_INDEX_CONSTRAINT_OFFSET, // 3.38.0
343 SQLITE_INDEX_CONSTRAINT_FUNCTION(u8), // 3.25.0
344 }
345
346 impl From<u8> for IndexConstraintOp {
347 fn from(code: u8) -> Self {
348 match code {
349 2 => Self::SQLITE_INDEX_CONSTRAINT_EQ,
350 4 => Self::SQLITE_INDEX_CONSTRAINT_GT,
351 8 => Self::SQLITE_INDEX_CONSTRAINT_LE,
352 16 => Self::SQLITE_INDEX_CONSTRAINT_LT,
353 32 => Self::SQLITE_INDEX_CONSTRAINT_GE,
354 64 => Self::SQLITE_INDEX_CONSTRAINT_MATCH,
355 65 => Self::SQLITE_INDEX_CONSTRAINT_LIKE,
356 66 => Self::SQLITE_INDEX_CONSTRAINT_GLOB,
357 67 => Self::SQLITE_INDEX_CONSTRAINT_REGEXP,
358 68 => Self::SQLITE_INDEX_CONSTRAINT_NE,
359 69 => Self::SQLITE_INDEX_CONSTRAINT_ISNOT,
360 70 => Self::SQLITE_INDEX_CONSTRAINT_ISNOTNULL,
361 71 => Self::SQLITE_INDEX_CONSTRAINT_ISNULL,
362 72 => Self::SQLITE_INDEX_CONSTRAINT_IS,
363 73 => Self::SQLITE_INDEX_CONSTRAINT_LIMIT,
364 74 => Self::SQLITE_INDEX_CONSTRAINT_OFFSET,
365 v => Self::SQLITE_INDEX_CONSTRAINT_FUNCTION(v),
366 }
367 }
368 }
369
370 bitflags::bitflags! {
371 /// Virtual table scan flags
372 /// See [Function Flags](https://sqlite.org/c3ref/c_index_scan_unique.html) for details.
373 #[repr(C)]
374 #[derive(Copy, Clone, Debug)]
375 pub struct IndexFlags: c_int {
376 /// Default
377 const NONE = 0;
378 /// Scan visits at most 1 row.
379 const SQLITE_INDEX_SCAN_UNIQUE = ffi::SQLITE_INDEX_SCAN_UNIQUE;
380 /// Display idxNum as hex in EXPLAIN QUERY PLAN
381 const SQLITE_INDEX_SCAN_HEX = 0x0000_0002; // 3.47.0
382 }
383 }
384
385 /// Pass information into and receive the reply from the
386 /// [`VTab::best_index`] method.
387 ///
388 /// (See [SQLite doc](http://sqlite.org/c3ref/index_info.html))
389 #[derive(Debug)]
390 pub struct IndexInfo(*mut ffi::sqlite3_index_info);
391
392 impl IndexInfo {
393 /// Iterate on index constraint and its associated usage.
394 #[inline]
395 pub fn constraints_and_usages(&mut self) -> IndexConstraintAndUsageIter<'_> {
396 let constraints =
397 unsafe { slice::from_raw_parts((*self.0).aConstraint, (*self.0).nConstraint as usize) };
398 let constraint_usages = unsafe {
399 slice::from_raw_parts_mut((*self.0).aConstraintUsage, (*self.0).nConstraint as usize)
400 };
401 IndexConstraintAndUsageIter {
402 iter: constraints.iter().zip(constraint_usages.iter_mut()),
403 }
404 }
405
406 /// Record WHERE clause constraints.
407 #[inline]
408 #[must_use]
409 pub fn constraints(&self) -> IndexConstraintIter<'_> {
410 let constraints =
411 unsafe { slice::from_raw_parts((*self.0).aConstraint, (*self.0).nConstraint as usize) };
412 IndexConstraintIter {
413 iter: constraints.iter(),
414 }
415 }
416
417 /// Information about the ORDER BY clause.
418 #[inline]
419 #[must_use]
420 pub fn order_bys(&self) -> OrderByIter<'_> {
421 let order_bys =
422 unsafe { slice::from_raw_parts((*self.0).aOrderBy, (*self.0).nOrderBy as usize) };
423 OrderByIter {
424 iter: order_bys.iter(),
425 }
426 }
427
428 /// Number of terms in the ORDER BY clause
429 #[inline]
430 #[must_use]
431 pub fn num_of_order_by(&self) -> usize {
432 unsafe { (*self.0).nOrderBy as usize }
433 }
434
435 /// Information about what parameters to pass to [`VTabCursor::filter`].
436 #[inline]
437 pub fn constraint_usage(&mut self, constraint_idx: usize) -> IndexConstraintUsage<'_> {
438 let constraint_usages = unsafe {
439 slice::from_raw_parts_mut((*self.0).aConstraintUsage, (*self.0).nConstraint as usize)
440 };
441 IndexConstraintUsage(&mut constraint_usages[constraint_idx])
442 }
443
444 /// Number used to identify the index
445 #[inline]
446 pub fn set_idx_num(&mut self, idx_num: c_int) {
447 unsafe {
448 (*self.0).idxNum = idx_num;
449 }
450 }
451
452 /// String used to identify the index
453 pub fn set_idx_str(&mut self, idx_str: &str) {
454 unsafe {
455 (*self.0).idxStr = alloc(idx_str);
456 (*self.0).needToFreeIdxStr = 1;
457 }
458 }
459
460 /// True if output is already ordered
461 #[inline]
462 pub fn set_order_by_consumed(&mut self, order_by_consumed: bool) {
463 unsafe {
464 (*self.0).orderByConsumed = order_by_consumed as c_int;
465 }
466 }
467
468 /// Estimated cost of using this index
469 #[inline]
470 pub fn set_estimated_cost(&mut self, estimated_ost: f64) {
471 unsafe {
472 (*self.0).estimatedCost = estimated_ost;
473 }
474 }
475
476 /// Estimated number of rows returned.
477 #[inline]
478 pub fn set_estimated_rows(&mut self, estimated_rows: i64) {
479 unsafe {
480 (*self.0).estimatedRows = estimated_rows;
481 }
482 }
483
484 /// Mask of `SQLITE_INDEX_SCAN_*` flags.
485 #[inline]
486 pub fn set_idx_flags(&mut self, flags: IndexFlags) {
487 unsafe { (*self.0).idxFlags = flags.bits() };
488 }
489
490 /// Mask of columns used by statement
491 #[inline]
492 pub fn col_used(&self) -> u64 {
493 unsafe { (*self.0).colUsed }
494 }
495
496 /// Determine the collation for a virtual table constraint
497 #[cfg(feature = "modern_sqlite")] // SQLite >= 3.22.0
498 #[cfg_attr(docsrs, doc(cfg(feature = "modern_sqlite")))]
499 pub fn collation(&self, constraint_idx: usize) -> Result<&str> {
500 use std::ffi::CStr;
501 let idx = constraint_idx as c_int;
502 let collation = unsafe { ffi::sqlite3_vtab_collation(self.0, idx) };
503 if collation.is_null() {
504 return Err(err!(ffi::SQLITE_MISUSE, "{constraint_idx} is out of range"));
505 }
506 Ok(unsafe { CStr::from_ptr(collation) }.to_str()?)
507 }
508
509 /*/// Determine if a virtual table query is DISTINCT
510 #[cfg(feature = "modern_sqlite")] // SQLite >= 3.38.0
511 #[cfg_attr(docsrs, doc(cfg(feature = "modern_sqlite")))]
512 pub fn distinct(&self) -> c_int {
513 unsafe { ffi::sqlite3_vtab_distinct(self.0) }
514 }
515
516 /// Constraint values
517 #[cfg(feature = "modern_sqlite")] // SQLite >= 3.38.0
518 #[cfg_attr(docsrs, doc(cfg(feature = "modern_sqlite")))]
519 pub fn set_rhs_value(&mut self, constraint_idx: c_int, value: ValueRef) -> Result<()> {
520 // TODO ValueRef to sqlite3_value
521 crate::error::check(unsafe { ffi::sqlite3_vtab_rhs_value(self.O, constraint_idx, value) })
522 }
523
524 /// Identify and handle IN constraints
525 #[cfg(feature = "modern_sqlite")] // SQLite >= 3.38.0
526 #[cfg_attr(docsrs, doc(cfg(feature = "modern_sqlite")))]
527 pub fn set_in_constraint(&mut self, constraint_idx: c_int, b_handle: c_int) -> bool {
528 unsafe { ffi::sqlite3_vtab_in(self.0, constraint_idx, b_handle) != 0 }
529 } // TODO sqlite3_vtab_in_first / sqlite3_vtab_in_next https://sqlite.org/c3ref/vtab_in_first.html
530 */
531 }
532
533 /// Iterate on index constraint and its associated usage.
534 pub struct IndexConstraintAndUsageIter<'a> {
535 iter: std::iter::Zip<
536 slice::Iter<'a, ffi::sqlite3_index_constraint>,
537 slice::IterMut<'a, ffi::sqlite3_index_constraint_usage>,
538 >,
539 }
540
541 impl<'a> Iterator for IndexConstraintAndUsageIter<'a> {
542 type Item = (IndexConstraint<'a>, IndexConstraintUsage<'a>);
543
544 #[inline]
545 fn next(&mut self) -> Option<(IndexConstraint<'a>, IndexConstraintUsage<'a>)> {
546 self.iter
547 .next()
548 .map(|raw| (IndexConstraint(raw.0), IndexConstraintUsage(raw.1)))
549 }
550
551 #[inline]
552 fn size_hint(&self) -> (usize, Option<usize>) {
553 self.iter.size_hint()
554 }
555 }
556
557 /// `feature = "vtab"`
558 pub struct IndexConstraintIter<'a> {
559 iter: slice::Iter<'a, ffi::sqlite3_index_constraint>,
560 }
561
562 impl<'a> Iterator for IndexConstraintIter<'a> {
563 type Item = IndexConstraint<'a>;
564
565 #[inline]
566 fn next(&mut self) -> Option<IndexConstraint<'a>> {
567 self.iter.next().map(IndexConstraint)
568 }
569
570 #[inline]
571 fn size_hint(&self) -> (usize, Option<usize>) {
572 self.iter.size_hint()
573 }
574 }
575
576 /// WHERE clause constraint.
577 pub struct IndexConstraint<'a>(&'a ffi::sqlite3_index_constraint);
578
579 impl IndexConstraint<'_> {
580 /// Column constrained. -1 for ROWID
581 #[inline]
582 #[must_use]
583 pub fn column(&self) -> c_int {
584 self.0.iColumn
585 }
586
587 /// Constraint operator
588 #[inline]
589 #[must_use]
590 pub fn operator(&self) -> IndexConstraintOp {
591 IndexConstraintOp::from(self.0.op)
592 }
593
594 /// True if this constraint is usable
595 #[inline]
596 #[must_use]
597 pub fn is_usable(&self) -> bool {
598 self.0.usable != 0
599 }
600 }
601
602 /// Information about what parameters to pass to
603 /// [`VTabCursor::filter`].
604 pub struct IndexConstraintUsage<'a>(&'a mut ffi::sqlite3_index_constraint_usage);
605
606 impl IndexConstraintUsage<'_> {
607 /// if `argv_index` > 0, constraint is part of argv to
608 /// [`VTabCursor::filter`]
609 #[inline]
610 pub fn set_argv_index(&mut self, argv_index: c_int) {
611 self.0.argvIndex = argv_index;
612 }
613
614 /// if `omit`, do not code a test for this constraint
615 #[inline]
616 pub fn set_omit(&mut self, omit: bool) {
617 self.0.omit = omit as std::os::raw::c_uchar;
618 }
619 }
620
621 /// `feature = "vtab"`
622 pub struct OrderByIter<'a> {
623 iter: slice::Iter<'a, ffi::sqlite3_index_orderby>,
624 }
625
626 impl<'a> Iterator for OrderByIter<'a> {
627 type Item = OrderBy<'a>;
628
629 #[inline]
630 fn next(&mut self) -> Option<OrderBy<'a>> {
631 self.iter.next().map(OrderBy)
632 }
633
634 #[inline]
635 fn size_hint(&self) -> (usize, Option<usize>) {
636 self.iter.size_hint()
637 }
638 }
639
640 /// A column of the ORDER BY clause.
641 pub struct OrderBy<'a>(&'a ffi::sqlite3_index_orderby);
642
643 impl OrderBy<'_> {
644 /// Column number
645 #[inline]
646 #[must_use]
647 pub fn column(&self) -> c_int {
648 self.0.iColumn
649 }
650
651 /// True for DESC. False for ASC.
652 #[inline]
653 #[must_use]
654 pub fn is_order_by_desc(&self) -> bool {
655 self.0.desc != 0
656 }
657 }
658
659 /// Virtual table cursor trait.
660 ///
661 /// # Safety
662 ///
663 /// Implementations must be like:
664 /// ```rust,ignore
665 /// #[repr(C)]
666 /// struct MyTabCursor {
667 /// /// Base class. Must be first
668 /// base: rusqlite::vtab::sqlite3_vtab_cursor,
669 /// /* Virtual table implementations will typically add additional fields */
670 /// }
671 /// ```
672 ///
673 /// (See [SQLite doc](https://sqlite.org/c3ref/vtab_cursor.html))
674 pub unsafe trait VTabCursor: Sized {
675 /// Begin a search of a virtual table.
676 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xfilter_method))
677 fn filter(&mut self, idx_num: c_int, idx_str: Option<&str>, args: &Values<'_>) -> Result<()>;
678 /// Advance cursor to the next row of a result set initiated by
679 /// [`filter`](VTabCursor::filter). (See [SQLite doc](https://sqlite.org/vtab.html#the_xnext_method))
680 fn next(&mut self) -> Result<()>;
681 /// Must return `false` if the cursor currently points to a valid row of
682 /// data, or `true` otherwise.
683 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xeof_method))
684 fn eof(&self) -> bool;
685 /// Find the value for the `i`-th column of the current row.
686 /// `i` is zero-based so the first column is numbered 0.
687 /// May return its result back to SQLite using one of the specified `ctx`.
688 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xcolumn_method))
689 fn column(&self, ctx: &mut Context, i: c_int) -> Result<()>;
690 /// Return the rowid of row that the cursor is currently pointing at.
691 /// (See [SQLite doc](https://sqlite.org/vtab.html#the_xrowid_method))
692 fn rowid(&self) -> Result<i64>;
693 }
694
695 /// Context is used by [`VTabCursor::column`] to specify the
696 /// cell value.
697 pub struct Context(*mut ffi::sqlite3_context);
698
699 impl Context {
700 /// Set current cell value
701 #[inline]
702 pub fn set_result<T: ToSql>(&mut self, value: &T) -> Result<()> {
703 let t = value.to_sql()?;
704 unsafe { set_result(self.0, &[], &t) };
705 Ok(())
706 }
707
708 // TODO sqlite3_vtab_nochange (http://sqlite.org/c3ref/vtab_nochange.html) // 3.22.0 & xColumn
709 }
710
711 /// Wrapper to [`VTabCursor::filter`] arguments, the values
712 /// requested by [`VTab::best_index`].
713 pub struct Values<'a> {
714 args: &'a [*mut ffi::sqlite3_value],
715 }
716
717 impl Values<'_> {
718 /// Returns the number of values.
719 #[inline]
720 #[must_use]
721 pub fn len(&self) -> usize {
722 self.args.len()
723 }
724
725 /// Returns `true` if there is no value.
726 #[inline]
727 #[must_use]
728 pub fn is_empty(&self) -> bool {
729 self.args.is_empty()
730 }
731
732 /// Returns value at `idx`
733 pub fn get<T: FromSql>(&self, idx: usize) -> Result<T> {
734 let arg = self.args[idx];
735 let value = unsafe { ValueRef::from_value(arg) };
736 FromSql::column_result(value).map_err(|err| match err {
737 FromSqlError::InvalidType => Error::InvalidFilterParameterType(idx, value.data_type()),
738 FromSqlError::Other(err) => {
739 Error::FromSqlConversionFailure(idx, value.data_type(), err)
740 }
741 FromSqlError::InvalidBlobSize { .. } => {
742 Error::FromSqlConversionFailure(idx, value.data_type(), Box::new(err))
743 }
744 FromSqlError::OutOfRange(i) => Error::IntegralValueOutOfRange(idx, i),
745 })
746 }
747
748 // `sqlite3_value_type` returns `SQLITE_NULL` for pointer.
749 // So it seems not possible to enhance `ValueRef::from_value`.
750 #[cfg(feature = "array")]
751 #[cfg_attr(docsrs, doc(cfg(feature = "array")))]
752 fn get_array(&self, idx: usize) -> Option<array::Array> {
753 use crate::types::Value;
754 let arg = self.args[idx];
755 let ptr = unsafe { ffi::sqlite3_value_pointer(arg, array::ARRAY_TYPE) };
756 if ptr.is_null() {
757 None
758 } else {
759 Some(unsafe {
760 let ptr = ptr as *const Vec<Value>;
761 array::Array::increment_strong_count(ptr); // don't consume it
762 array::Array::from_raw(ptr)
763 })
764 }
765 }
766
767 /// Turns `Values` into an iterator.
768 #[inline]
769 #[must_use]
770 pub fn iter(&self) -> ValueIter<'_> {
771 ValueIter {
772 iter: self.args.iter(),
773 }
774 }
775 // TODO sqlite3_vtab_in_first / sqlite3_vtab_in_next https://sqlite.org/c3ref/vtab_in_first.html & 3.38.0
776 }
777
778 impl<'a> IntoIterator for &'a Values<'a> {
779 type IntoIter = ValueIter<'a>;
780 type Item = ValueRef<'a>;
781
782 #[inline]
783 fn into_iter(self) -> ValueIter<'a> {
784 self.iter()
785 }
786 }
787
788 /// [`Values`] iterator.
789 pub struct ValueIter<'a> {
790 iter: slice::Iter<'a, *mut ffi::sqlite3_value>,
791 }
792
793 impl<'a> Iterator for ValueIter<'a> {
794 type Item = ValueRef<'a>;
795
796 #[inline]
797 fn next(&mut self) -> Option<ValueRef<'a>> {
798 self.iter
799 .next()
800 .map(|&raw| unsafe { ValueRef::from_value(raw) })
801 }
802
803 #[inline]
804 fn size_hint(&self) -> (usize, Option<usize>) {
805 self.iter.size_hint()
806 }
807 }
808
809 impl Connection {
810 /// Register a virtual table implementation.
811 ///
812 /// Step 3 of [Creating New Virtual Table
813 /// Implementations](https://sqlite.org/vtab.html#creating_new_virtual_table_implementations).
814 #[inline]
815 pub fn create_module<'vtab, T: VTab<'vtab>>(
816 &self,
817 module_name: &str,
818 module: &'static Module<'vtab, T>,
819 aux: Option<T::Aux>,
820 ) -> Result<()> {
821 self.db.borrow_mut().create_module(module_name, module, aux)
822 }
823 }
824
825 impl InnerConnection {
826 fn create_module<'vtab, T: VTab<'vtab>>(
827 &mut self,
828 module_name: &str,
829 module: &'static Module<'vtab, T>,
830 aux: Option<T::Aux>,
831 ) -> Result<()> {
832 use crate::version;
833 if version::version_number() < 3_009_000 && module.base.xCreate.is_none() {
834 return Err(Error::ModuleError(format!(
835 "Eponymous-only virtual table not supported by SQLite version {}",
836 version::version()
837 )));
838 }
839 let c_name = str_to_cstring(module_name)?;
840 let r = match aux {
841 Some(aux) => {
842 let boxed_aux: *mut T::Aux = Box::into_raw(Box::new(aux));
843 unsafe {
844 ffi::sqlite3_create_module_v2(
845 self.db(),
846 c_name.as_ptr(),
847 &module.base,
848 boxed_aux.cast::<c_void>(),
849 Some(free_boxed_value::<T::Aux>),
850 )
851 }
852 }
853 None => unsafe {
854 ffi::sqlite3_create_module_v2(
855 self.db(),
856 c_name.as_ptr(),
857 &module.base,
858 ptr::null_mut(),
859 None,
860 )
861 },
862 };
863 self.decode_result(r)
864 }
865 }
866
867 /// Escape double-quote (`"`) character occurrences by
868 /// doubling them (`""`).
869 #[must_use]
870 pub fn escape_double_quote(identifier: &str) -> Cow<'_, str> {
871 if identifier.contains('"') {
872 // escape quote by doubling them
873 Owned(identifier.replace('"', "\"\""))
874 } else {
875 Borrowed(identifier)
876 }
877 }
878 /// Dequote string
879 #[must_use]
880 pub fn dequote(s: &str) -> &str {
881 if s.len() < 2 {
882 return s;
883 }
884 match s.bytes().next() {
885 Some(b) if b == b'"' || b == b'\'' => match s.bytes().next_back() {
886 Some(e) if e == b => &s[1..s.len() - 1], // FIXME handle inner escaped quote(s)
887 _ => s,
888 },
889 _ => s,
890 }
891 }
892 /// The boolean can be one of:
893 /// ```text
894 /// 1 yes true on
895 /// 0 no false off
896 /// ```
897 #[must_use]
898 pub fn parse_boolean(s: &str) -> Option<bool> {
899 if s.eq_ignore_ascii_case("yes")
900 || s.eq_ignore_ascii_case("on")
901 || s.eq_ignore_ascii_case("true")
902 || s.eq("1")
903 {
904 Some(true)
905 } else if s.eq_ignore_ascii_case("no")
906 || s.eq_ignore_ascii_case("off")
907 || s.eq_ignore_ascii_case("false")
908 || s.eq("0")
909 {
910 Some(false)
911 } else {
912 None
913 }
914 }
915
916 /// `<param_name>=['"]?<param_value>['"]?` => `(<param_name>, <param_value>)`
917 pub fn parameter(c_slice: &[u8]) -> Result<(&str, &str)> {
918 let arg = std::str::from_utf8(c_slice)?.trim();
919 let mut split = arg.split('=');
920 if let Some(key) = split.next() {
921 if let Some(value) = split.next() {
922 let param = key.trim();
923 let value = dequote(value.trim());
924 return Ok((param, value));
925 }
926 }
927 Err(Error::ModuleError(format!("illegal argument: '{arg}'")))
928 }
929
930 // FIXME copy/paste from function.rs
931 unsafe extern "C" fn free_boxed_value<T>(p: *mut c_void) {
932 drop(Box::from_raw(p.cast::<T>()));
933 }
934
935 unsafe extern "C" fn rust_create<'vtab, T>(
936 db: *mut ffi::sqlite3,
937 aux: *mut c_void,
938 argc: c_int,
939 argv: *const *const c_char,
940 pp_vtab: *mut *mut sqlite3_vtab,
941 err_msg: *mut *mut c_char,
942 ) -> c_int
943 where
944 T: CreateVTab<'vtab>,
945 {
946 use std::ffi::CStr;
947
948 let mut conn = VTabConnection(db);
949 let aux = aux.cast::<T::Aux>();
950 let args = slice::from_raw_parts(argv, argc as usize);
951 let vec = args
952 .iter()
953 .map(|&cs| CStr::from_ptr(cs).to_bytes()) // FIXME .to_str() -> Result<&str, Utf8Error>
954 .collect::<Vec<_>>();
955 match T::create(&mut conn, aux.as_ref(), &vec[..]) {
956 Ok((sql, vtab)) => match std::ffi::CString::new(sql) {
957 Ok(c_sql) => {
958 let rc = ffi::sqlite3_declare_vtab(db, c_sql.as_ptr());
959 if rc == ffi::SQLITE_OK {
960 let boxed_vtab: *mut T = Box::into_raw(Box::new(vtab));
961 *pp_vtab = boxed_vtab.cast::<sqlite3_vtab>();
962 ffi::SQLITE_OK
963 } else {
964 let err = error_from_sqlite_code(rc, None);
965 to_sqlite_error(&err, err_msg)
966 }
967 }
968 Err(err) => {
969 *err_msg = alloc(&err.to_string());
970 ffi::SQLITE_ERROR
971 }
972 },
973 Err(err) => to_sqlite_error(&err, err_msg),
974 }
975 }
976
977 unsafe extern "C" fn rust_connect<'vtab, T>(
978 db: *mut ffi::sqlite3,
979 aux: *mut c_void,
980 argc: c_int,
981 argv: *const *const c_char,
982 pp_vtab: *mut *mut sqlite3_vtab,
983 err_msg: *mut *mut c_char,
984 ) -> c_int
985 where
986 T: VTab<'vtab>,
987 {
988 use std::ffi::CStr;
989
990 let mut conn = VTabConnection(db);
991 let aux = aux.cast::<T::Aux>();
992 let args = slice::from_raw_parts(argv, argc as usize);
993 let vec = args
994 .iter()
995 .map(|&cs| CStr::from_ptr(cs).to_bytes()) // FIXME .to_str() -> Result<&str, Utf8Error>
996 .collect::<Vec<_>>();
997 match T::connect(&mut conn, aux.as_ref(), &vec[..]) {
998 Ok((sql, vtab)) => match std::ffi::CString::new(sql) {
999 Ok(c_sql) => {
1000 let rc = ffi::sqlite3_declare_vtab(db, c_sql.as_ptr());
1001 if rc == ffi::SQLITE_OK {
1002 let boxed_vtab: *mut T = Box::into_raw(Box::new(vtab));
1003 *pp_vtab = boxed_vtab.cast::<sqlite3_vtab>();
1004 ffi::SQLITE_OK
1005 } else {
1006 let err = error_from_sqlite_code(rc, None);
1007 to_sqlite_error(&err, err_msg)
1008 }
1009 }
1010 Err(err) => {
1011 *err_msg = alloc(&err.to_string());
1012 ffi::SQLITE_ERROR
1013 }
1014 },
1015 Err(err) => to_sqlite_error(&err, err_msg),
1016 }
1017 }
1018
1019 unsafe extern "C" fn rust_best_index<'vtab, T>(
1020 vtab: *mut sqlite3_vtab,
1021 info: *mut ffi::sqlite3_index_info,
1022 ) -> c_int
1023 where
1024 T: VTab<'vtab>,
1025 {
1026 let vt = vtab.cast::<T>();
1027 let mut idx_info = IndexInfo(info);
1028 match (*vt).best_index(&mut idx_info) {
1029 Ok(_) => ffi::SQLITE_OK,
1030 Err(Error::SqliteFailure(err, s)) => {
1031 if let Some(err_msg) = s {
1032 set_err_msg(vtab, &err_msg);
1033 }
1034 err.extended_code
1035 }
1036 Err(err) => {
1037 set_err_msg(vtab, &err.to_string());
1038 ffi::SQLITE_ERROR
1039 }
1040 }
1041 }
1042
1043 unsafe extern "C" fn rust_disconnect<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1044 where
1045 T: VTab<'vtab>,
1046 {
1047 if vtab.is_null() {
1048 return ffi::SQLITE_OK;
1049 }
1050 let vtab = vtab.cast::<T>();
1051 drop(Box::from_raw(vtab));
1052 ffi::SQLITE_OK
1053 }
1054
1055 unsafe extern "C" fn rust_destroy<'vtab, T>(vtab: *mut sqlite3_vtab) -> c_int
1056 where
1057 T: CreateVTab<'vtab>,
1058 {
1059 if vtab.is_null() {
1060 return ffi::SQLITE_OK;
1061 }
1062 let vt = vtab.cast::<T>();
1063 match (*vt).destroy() {
1064 Ok(_) => {
1065 drop(Box::from_raw(vt));
1066 ffi::SQLITE_OK
1067 }
1068 Err(Error::SqliteFailure(err, s)) => {
1069 if let Some(err_msg) = s {
1070 set_err_msg(vtab, &err_msg);
1071 }
1072 err.extended_code
1073 }
1074 Err(err) => {
1075 set_err_msg(vtab, &err.to_string());
1076 ffi::SQLITE_ERROR
1077 }
1078 }
1079 }
1080
1081 unsafe extern "C" fn rust_open<'vtab, T>(
1082 vtab: *mut sqlite3_vtab,
1083 pp_cursor: *mut *mut sqlite3_vtab_cursor,
1084 ) -> c_int
1085 where
1086 T: VTab<'vtab> + 'vtab,
1087 {
1088 let vt = vtab.cast::<T>();
1089 match (*vt).open() {
1090 Ok(cursor) => {
1091 let boxed_cursor: *mut T::Cursor = Box::into_raw(Box::new(cursor));
1092 *pp_cursor = boxed_cursor.cast::<sqlite3_vtab_cursor>();
1093 ffi::SQLITE_OK
1094 }
1095 Err(Error::SqliteFailure(err, s)) => {
1096 if let Some(err_msg) = s {
1097 set_err_msg(vtab, &err_msg);
1098 }
1099 err.extended_code
1100 }
1101 Err(err) => {
1102 set_err_msg(vtab, &err.to_string());
1103 ffi::SQLITE_ERROR
1104 }
1105 }
1106 }
1107
1108 unsafe extern "C" fn rust_close<C>(cursor: *mut sqlite3_vtab_cursor) -> c_int
1109 where
1110 C: VTabCursor,
1111 {
1112 let cr = cursor.cast::<C>();
1113 drop(Box::from_raw(cr));
1114 ffi::SQLITE_OK
1115 }
1116
1117 unsafe extern "C" fn rust_filter<C>(
1118 cursor: *mut sqlite3_vtab_cursor,
1119 idx_num: c_int,
1120 idx_str: *const c_char,
1121 argc: c_int,
1122 argv: *mut *mut ffi::sqlite3_value,
1123 ) -> c_int
1124 where
1125 C: VTabCursor,
1126 {
1127 use std::ffi::CStr;
1128 use std::str;
1129 let idx_name = if idx_str.is_null() {
1130 None
1131 } else {
1132 let c_slice = CStr::from_ptr(idx_str).to_bytes();
1133 Some(str::from_utf8_unchecked(c_slice))
1134 };
1135 let args = slice::from_raw_parts_mut(argv, argc as usize);
1136 let values = Values { args };
1137 let cr = cursor as *mut C;
1138 cursor_error(cursor, (*cr).filter(idx_num, idx_name, &values))
1139 }
1140
1141 unsafe extern "C" fn rust_next<C>(cursor: *mut sqlite3_vtab_cursor) -> c_int
1142 where
1143 C: VTabCursor,
1144 {
1145 let cr = cursor as *mut C;
1146 cursor_error(cursor, (*cr).next())
1147 }
1148
1149 unsafe extern "C" fn rust_eof<C>(cursor: *mut sqlite3_vtab_cursor) -> c_int
1150 where
1151 C: VTabCursor,
1152 {
1153 let cr = cursor.cast::<C>();
1154 (*cr).eof() as c_int
1155 }
1156
1157 unsafe extern "C" fn rust_column<C>(
1158 cursor: *mut sqlite3_vtab_cursor,
1159 ctx: *mut ffi::sqlite3_context,
1160 i: c_int,
1161 ) -> c_int
1162 where
1163 C: VTabCursor,
1164 {
1165 let cr = cursor.cast::<C>();
1166 let mut ctxt = Context(ctx);
1167 result_error(ctx, (*cr).column(&mut ctxt, i))
1168 }
1169
1170 unsafe extern "C" fn rust_rowid<C>(
1171 cursor: *mut sqlite3_vtab_cursor,
1172 p_rowid: *mut ffi::sqlite3_int64,
1173 ) -> c_int
1174 where
1175 C: VTabCursor,
1176 {
1177 let cr = cursor.cast::<C>();
1178 match (*cr).rowid() {
1179 Ok(rowid) => {
1180 *p_rowid = rowid;
1181 ffi::SQLITE_OK
1182 }
1183 err => cursor_error(cursor, err),
1184 }
1185 }
1186
1187 unsafe extern "C" fn rust_update<'vtab, T>(
1188 vtab: *mut sqlite3_vtab,
1189 argc: c_int,
1190 argv: *mut *mut ffi::sqlite3_value,
1191 p_rowid: *mut ffi::sqlite3_int64,
1192 ) -> c_int
1193 where
1194 T: UpdateVTab<'vtab> + 'vtab,
1195 {
1196 assert!(argc >= 1);
1197 let args = slice::from_raw_parts_mut(argv, argc as usize);
1198 let vt = vtab.cast::<T>();
1199 let r = if args.len() == 1 {
1200 (*vt).delete(ValueRef::from_value(args[0]))
1201 } else if ffi::sqlite3_value_type(args[0]) == ffi::SQLITE_NULL {
1202 // TODO Make the distinction between argv[1] == NULL and argv[1] != NULL ?
1203 let values = Values { args };
1204 match (*vt).insert(&values) {
1205 Ok(rowid) => {
1206 *p_rowid = rowid;
1207 Ok(())
1208 }
1209 Err(e) => Err(e),
1210 }
1211 } else {
1212 let values = Values { args };
1213 (*vt).update(&values)
1214 };
1215 match r {
1216 Ok(_) => ffi::SQLITE_OK,
1217 Err(Error::SqliteFailure(err, s)) => {
1218 if let Some(err_msg) = s {
1219 set_err_msg(vtab, &err_msg);
1220 }
1221 err.extended_code
1222 }
1223 Err(err) => {
1224 set_err_msg(vtab, &err.to_string());
1225 ffi::SQLITE_ERROR
1226 }
1227 }
1228 }
1229
1230 /// Virtual table cursors can set an error message by assigning a string to
1231 /// `zErrMsg`.
1232 #[cold]
1233 unsafe fn cursor_error<T>(cursor: *mut sqlite3_vtab_cursor, result: Result<T>) -> c_int {
1234 match result {
1235 Ok(_) => ffi::SQLITE_OK,
1236 Err(Error::SqliteFailure(err, s)) => {
1237 if let Some(err_msg) = s {
1238 set_err_msg((*cursor).pVtab, &err_msg);
1239 }
1240 err.extended_code
1241 }
1242 Err(err) => {
1243 set_err_msg((*cursor).pVtab, &err.to_string());
1244 ffi::SQLITE_ERROR
1245 }
1246 }
1247 }
1248
1249 /// Virtual tables methods can set an error message by assigning a string to
1250 /// `zErrMsg`.
1251 #[cold]
1252 unsafe fn set_err_msg(vtab: *mut sqlite3_vtab, err_msg: &str) {
1253 if !(*vtab).zErrMsg.is_null() {
1254 ffi::sqlite3_free((*vtab).zErrMsg.cast::<c_void>());
1255 }
1256 (*vtab).zErrMsg = alloc(err_msg);
1257 }
1258
1259 /// To raise an error, the `column` method should use this method to set the
1260 /// error message and return the error code.
1261 #[cold]
1262 unsafe fn result_error<T>(ctx: *mut ffi::sqlite3_context, result: Result<T>) -> c_int {
1263 match result {
1264 Ok(_) => ffi::SQLITE_OK,
1265 Err(Error::SqliteFailure(err, s)) => {
1266 match err.extended_code {
1267 ffi::SQLITE_TOOBIG => {
1268 ffi::sqlite3_result_error_toobig(ctx);
1269 }
1270 ffi::SQLITE_NOMEM => {
1271 ffi::sqlite3_result_error_nomem(ctx);
1272 }
1273 code => {
1274 ffi::sqlite3_result_error_code(ctx, code);
1275 if let Some(Ok(cstr)) = s.map(|s| str_to_cstring(&s)) {
1276 ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
1277 }
1278 }
1279 };
1280 err.extended_code
1281 }
1282 Err(err) => {
1283 ffi::sqlite3_result_error_code(ctx, ffi::SQLITE_ERROR);
1284 if let Ok(cstr) = str_to_cstring(&err.to_string()) {
1285 ffi::sqlite3_result_error(ctx, cstr.as_ptr(), -1);
1286 }
1287 ffi::SQLITE_ERROR
1288 }
1289 }
1290 }
1291
1292 #[cfg(feature = "array")]
1293 #[cfg_attr(docsrs, doc(cfg(feature = "array")))]
1294 pub mod array;
1295 #[cfg(feature = "csvtab")]
1296 #[cfg_attr(docsrs, doc(cfg(feature = "csvtab")))]
1297 pub mod csvtab;
1298 #[cfg(feature = "series")]
1299 #[cfg_attr(docsrs, doc(cfg(feature = "series")))]
1300 pub mod series; // SQLite >= 3.9.0
1301 #[cfg(all(test, feature = "modern_sqlite"))]
1302 mod vtablog;
1303
1304 #[cfg(test)]
1305 mod test {
1306 #[test]
1307 fn test_dequote() {
1308 assert_eq!("", super::dequote(""));
1309 assert_eq!("'", super::dequote("'"));
1310 assert_eq!("\"", super::dequote("\""));
1311 assert_eq!("'\"", super::dequote("'\""));
1312 assert_eq!("", super::dequote("''"));
1313 assert_eq!("", super::dequote("\"\""));
1314 assert_eq!("x", super::dequote("'x'"));
1315 assert_eq!("x", super::dequote("\"x\""));
1316 assert_eq!("x", super::dequote("x"));
1317 }
1318 #[test]
1319 fn test_parse_boolean() {
1320 assert_eq!(None, super::parse_boolean(""));
1321 assert_eq!(Some(true), super::parse_boolean("1"));
1322 assert_eq!(Some(true), super::parse_boolean("yes"));
1323 assert_eq!(Some(true), super::parse_boolean("on"));
1324 assert_eq!(Some(true), super::parse_boolean("true"));
1325 assert_eq!(Some(false), super::parse_boolean("0"));
1326 assert_eq!(Some(false), super::parse_boolean("no"));
1327 assert_eq!(Some(false), super::parse_boolean("off"));
1328 assert_eq!(Some(false), super::parse_boolean("false"));
1329 }
1330 }