rusqlite/tests/vtab.rs

101 lines
2.5 KiB
Rust
Raw Normal View History

//! Ensure Virtual tables can be declared outside `rusqlite` crate.
#[cfg(feature = "vtab")]
#[test]
2020-11-06 05:14:00 +08:00
fn test_dummy_module() -> rusqlite::Result<()> {
2018-07-15 01:21:03 +08:00
use rusqlite::vtab::{
eponymous_only_module, sqlite3_vtab, sqlite3_vtab_cursor, Context, IndexInfo, VTab,
VTabConnection, VTabCursor, Values,
2018-07-15 01:21:03 +08:00
};
use rusqlite::{version_number, Connection, Result};
use std::marker::PhantomData;
2018-07-15 00:47:52 +08:00
use std::os::raw::c_int;
2020-04-14 22:09:50 +08:00
let module = eponymous_only_module::<DummyTab>();
#[repr(C)]
2018-07-15 00:47:52 +08:00
struct DummyTab {
/// Base class. Must be first
base: sqlite3_vtab,
2018-07-15 00:47:52 +08:00
}
unsafe impl<'vtab> VTab<'vtab> for DummyTab {
type Aux = ();
type Cursor = DummyTabCursor<'vtab>;
fn connect(
_: &mut VTabConnection,
_aux: Option<&()>,
_args: &[&[u8]],
) -> Result<(String, DummyTab)> {
let vtab = DummyTab {
base: sqlite3_vtab::default(),
};
Ok(("CREATE TABLE x(value)".to_owned(), vtab))
}
fn best_index(&self, info: &mut IndexInfo) -> Result<()> {
info.set_estimated_cost(1.);
Ok(())
}
fn open(&'vtab self) -> Result<DummyTabCursor<'vtab>> {
Ok(DummyTabCursor::default())
}
}
#[derive(Default)]
#[repr(C)]
struct DummyTabCursor<'vtab> {
/// Base class. Must be first
base: sqlite3_vtab_cursor,
/// The rowid
row_id: i64,
phantom: PhantomData<&'vtab DummyTab>,
}
unsafe impl VTabCursor for DummyTabCursor<'_> {
fn filter(
&mut self,
_idx_num: c_int,
_idx_str: Option<&str>,
2018-12-08 04:57:04 +08:00
_args: &Values<'_>,
) -> Result<()> {
self.row_id = 1;
Ok(())
}
2018-08-17 00:29:46 +08:00
fn next(&mut self) -> Result<()> {
self.row_id += 1;
Ok(())
}
2018-08-17 00:29:46 +08:00
fn eof(&self) -> bool {
self.row_id > 1
}
2018-08-17 00:29:46 +08:00
fn column(&self, ctx: &mut Context, _: c_int) -> Result<()> {
ctx.set_result(&self.row_id)
}
2018-08-17 00:29:46 +08:00
fn rowid(&self) -> Result<i64> {
Ok(self.row_id)
}
}
2020-11-06 05:14:00 +08:00
let db = Connection::open_in_memory()?;
2021-06-17 01:22:31 +08:00
db.create_module::<DummyTab>("dummy", module, None)?;
let version = version_number();
2019-02-02 18:37:26 +08:00
if version < 3_008_012 {
2020-11-06 05:14:00 +08:00
return Ok(());
2018-07-14 17:28:43 +08:00
}
2020-11-06 05:14:00 +08:00
let mut s = db.prepare("SELECT * FROM dummy()")?;
2021-01-20 04:16:08 +08:00
let dummy = s.query_row([], |row| row.get::<_, i32>(0))?;
assert_eq!(1, dummy);
2020-11-06 05:14:00 +08:00
Ok(())
}