Skip to main content

rusqlite/vtab/
array.rs

1//! Array Virtual Table.
2//!
3//! Note: `rarray`, not `carray` is the name of the table valued function we
4//! define.
5//!
6//! Port of [carray](https://sqlite.org/src/file/ext/misc/carray.c)
7//! C extension: `https://www.sqlite.org/carray.html`
8//!
9//! # Example
10//!
11//! ```rust,no_run
12//! # use rusqlite::{types::Value, Connection, Result, params};
13//! # use std::rc::Rc;
14//! fn example(db: &Connection) -> Result<()> {
15//!     // Note: This should be done once (usually when opening the DB).
16//!     rusqlite::vtab::array::load_module(&db)?;
17//!     let v = [1i64, 2, 3, 4];
18//!     // Note: A `Rc<Vec<Value>>` must be used as the parameter.
19//!     let values = Rc::new(v.iter().copied().map(Value::from).collect::<Vec<Value>>());
20//!     let mut stmt = db.prepare("SELECT value from rarray(?1);")?;
21//!     let rows = stmt.query_map([values], |row| row.get::<_, i64>(0))?;
22//!     for value in rows {
23//!         println!("{}", value?);
24//!     }
25//!     Ok(())
26//! }
27//! ```
28
29use std::borrow::Cow;
30use std::ffi::{CStr, c_int};
31use std::marker::PhantomData;
32use std::rc::Rc;
33
34use crate::ffi;
35use crate::types::{ToSql, ToSqlOutput, Value};
36use crate::vtab::{
37    Context, Filters, IndexConstraintOp, IndexInfo, Module, VTab, VTabConnection, VTabCursor,
38};
39use crate::{Connection, Result};
40
41// http://sqlite.org/bindptr.html
42
43const ARRAY_TYPE: &CStr = c"rarray";
44const MODULE_NAME: &CStr = ARRAY_TYPE;
45
46/// Array parameter / pointer
47pub type Array = Rc<Vec<Value>>;
48
49impl ToSql for Array {
50    #[inline]
51    fn to_sql(&self) -> Result<ToSqlOutput<'_>> {
52        Ok(ToSqlOutput::from_rc(self.clone(), ARRAY_TYPE))
53    }
54}
55
56/// Register the "rarray" module.
57pub fn load_module(conn: &Connection) -> Result<()> {
58    const MODULE: Module<ArrayTab> = Module::eponymous_only_module();
59    let aux: Option<()> = None;
60    conn.create_module(MODULE_NAME, &MODULE, aux)
61}
62
63// Column numbers
64// const CARRAY_COLUMN_VALUE : c_int = 0;
65const CARRAY_COLUMN_POINTER: c_int = 1;
66
67/// An instance of the Array virtual table
68#[repr(C)]
69struct ArrayTab {
70    /// Base class. Must be first
71    base: ffi::sqlite3_vtab,
72}
73
74unsafe impl<'vtab> VTab<'vtab> for ArrayTab {
75    type Aux = ();
76    type Cursor = ArrayTabCursor<'vtab>;
77
78    fn connect(
79        _: &mut VTabConnection,
80        aux: Option<&()>,
81        module_name: &[u8],
82        _database_name: &[u8],
83        table_name: &[u8],
84        args: &[&[u8]],
85    ) -> Result<(Cow<'static, CStr>, Self)> {
86        debug_assert_eq!(aux, None);
87        debug_assert_eq!(module_name, MODULE_NAME.to_bytes());
88        debug_assert_eq!(table_name, MODULE_NAME.to_bytes());
89        debug_assert_eq!(args.len(), 0);
90        let vtab = Self {
91            base: ffi::sqlite3_vtab::default(),
92        };
93        Ok((Cow::Borrowed(c"CREATE TABLE x(value,pointer hidden)"), vtab))
94    }
95
96    fn best_index(&self, info: &mut IndexInfo) -> Result<bool> {
97        // Index of the pointer= constraint
98        let mut ptr_idx = false;
99        for (constraint, mut constraint_usage) in info.constraints_and_usages() {
100            if !constraint.is_usable() {
101                continue;
102            }
103            if constraint.operator() != IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_EQ {
104                continue;
105            }
106            if let CARRAY_COLUMN_POINTER = constraint.column() {
107                ptr_idx = true;
108                constraint_usage.set_argv_index(1);
109                constraint_usage.set_omit(true);
110            }
111        }
112        if ptr_idx {
113            info.set_estimated_cost(1_f64);
114            info.set_estimated_rows(100);
115            info.set_idx_num(1);
116        } else {
117            info.set_estimated_cost(2_147_483_647_f64);
118            info.set_estimated_rows(2_147_483_647);
119            info.set_idx_num(0);
120        }
121        Ok(true)
122    }
123
124    fn open(&mut self) -> Result<ArrayTabCursor<'_>> {
125        Ok(ArrayTabCursor::default())
126    }
127}
128
129/// A cursor for the Array virtual table
130#[derive(Default)]
131#[repr(C)]
132struct ArrayTabCursor<'vtab> {
133    /// Base class. Must be first
134    base: ffi::sqlite3_vtab_cursor,
135    /// The rowid
136    row_id: i64,
137    /// Pointer to the array of values ("pointer")
138    ptr: Option<&'vtab Vec<Value>>,
139    phantom: PhantomData<&'vtab ArrayTab>,
140}
141
142impl ArrayTabCursor<'_> {
143    fn len(&self) -> i64 {
144        match self.ptr {
145            Some(a) => a.len() as i64,
146            _ => 0,
147        }
148    }
149}
150unsafe impl VTabCursor for ArrayTabCursor<'_> {
151    fn filter(&mut self, idx_num: c_int, _idx_str: Option<&str>, args: &Filters<'_>) -> Result<()> {
152        if idx_num > 0 {
153            self.ptr = unsafe { args.get_pointer(0, ARRAY_TYPE) };
154        } else {
155            self.ptr = None;
156        }
157        self.row_id = 1;
158        Ok(())
159    }
160
161    fn next(&mut self) -> Result<()> {
162        self.row_id += 1;
163        Ok(())
164    }
165
166    fn eof(&self) -> bool {
167        self.row_id > self.len()
168    }
169
170    fn column(&self, ctx: &mut Context, i: c_int) -> Result<()> {
171        match i {
172            CARRAY_COLUMN_POINTER => Ok(()),
173            _ => {
174                if let Some(array) = self.ptr {
175                    let value = &array[(self.row_id - 1) as usize];
176                    ctx.set_result(value)
177                } else {
178                    Ok(())
179                }
180            }
181        }
182    }
183
184    fn rowid(&self) -> Result<i64> {
185        Ok(self.row_id)
186    }
187}
188
189#[cfg(all(test, not(miri)))]
190mod test {
191    #[cfg(all(target_family = "wasm", target_os = "unknown"))]
192    use wasm_bindgen_test::wasm_bindgen_test as test;
193
194    use crate::types::Value;
195    use crate::vtab::array;
196    use crate::{Connection, Result};
197    use std::rc::Rc;
198
199    #[test]
200    fn test_array_module() -> Result<()> {
201        let db = Connection::open_in_memory()?;
202        array::load_module(&db)?;
203
204        let v = vec![1i64, 2, 3, 4];
205        let values: Vec<Value> = v.into_iter().map(Value::from).collect();
206        let ptr = Rc::new(values);
207        {
208            let mut stmt = db.prepare("SELECT value from rarray(?1);")?;
209
210            let rows = stmt.query_map([&ptr], |row| row.get::<_, i64>(0))?;
211            assert_eq!(2, Rc::strong_count(&ptr));
212            let mut count = 0;
213            for (i, value) in rows.enumerate() {
214                assert_eq!(i as i64, value? - 1);
215                count += 1;
216            }
217            assert_eq!(4, count);
218        }
219        assert_eq!(1, Rc::strong_count(&ptr));
220        Ok(())
221    }
222}