| 1 |
//! Generate series virtual table. |
| 2 |
//! |
| 3 |
//! Port of C [generate series |
| 4 |
//! "function"](http://www.sqlite.org/cgi/src/finfo?name=ext/misc/series.c): |
| 5 |
//! `https://www.sqlite.org/series.html` |
| 6 |
use std::marker::PhantomData; |
| 7 |
use std::os::raw::c_int; |
| 8 |
|
| 9 |
use crate::ffi; |
| 10 |
use crate::types::Type; |
| 11 |
use crate::vtab::{ |
| 12 |
eponymous_only_module, Context, IndexConstraintOp, IndexInfo, VTab, VTabConfig, VTabConnection, |
| 13 |
VTabCursor, Values, |
| 14 |
}; |
| 15 |
use crate::{error::error_from_sqlite_code, Connection, Result}; |
| 16 |
|
| 17 |
/// Register the `generate_series` module. |
| 18 |
pub fn load_module(conn: &Connection) -> Result<()> { |
| 19 |
let aux: Option<()> = None; |
| 20 |
conn.create_module("generate_series", eponymous_only_module::<SeriesTab>(), aux) |
| 21 |
} |
| 22 |
|
| 23 |
// Column numbers |
| 24 |
// const SERIES_COLUMN_VALUE : c_int = 0; |
| 25 |
const SERIES_COLUMN_START: c_int = 1; |
| 26 |
const SERIES_COLUMN_STOP: c_int = 2; |
| 27 |
const SERIES_COLUMN_STEP: c_int = 3; |
| 28 |
|
| 29 |
bitflags::bitflags! { |
| 30 |
#[derive(Clone, Copy)] |
| 31 |
#[repr(C)] |
| 32 |
struct QueryPlanFlags: c_int { |
| 33 |
// start = $value -- constraint exists |
| 34 |
const START = 1; |
| 35 |
// stop = $value -- constraint exists |
| 36 |
const STOP = 2; |
| 37 |
// step = $value -- constraint exists |
| 38 |
const STEP = 4; |
| 39 |
// output in descending order |
| 40 |
const DESC = 8; |
| 41 |
// output in ascending order |
| 42 |
const ASC = 16; |
| 43 |
// Both start and stop |
| 44 |
const BOTH = QueryPlanFlags::START.bits() | QueryPlanFlags::STOP.bits(); |
| 45 |
} |
| 46 |
} |
| 47 |
|
| 48 |
/// An instance of the Series virtual table |
| 49 |
#[repr(C)] |
| 50 |
struct SeriesTab { |
| 51 |
/// Base class. Must be first |
| 52 |
base: ffi::sqlite3_vtab, |
| 53 |
} |
| 54 |
|
| 55 |
unsafe impl<'vtab> VTab<'vtab> for SeriesTab { |
| 56 |
type Aux = (); |
| 57 |
type Cursor = SeriesTabCursor<'vtab>; |
| 58 |
|
| 59 |
fn connect( |
| 60 |
db: &mut VTabConnection, |
| 61 |
_aux: Option<&()>, |
| 62 |
_args: &[&[u8]], |
| 63 |
) -> Result<(String, Self)> { |
| 64 |
let vtab = Self { |
| 65 |
base: ffi::sqlite3_vtab::default(), |
| 66 |
}; |
| 67 |
db.config(VTabConfig::Innocuous)?; |
| 68 |
Ok(( |
| 69 |
"CREATE TABLE x(value,start hidden,stop hidden,step hidden)".to_owned(), |
| 70 |
vtab, |
| 71 |
)) |
| 72 |
} |
| 73 |
|
| 74 |
fn best_index(&self, info: &mut IndexInfo) -> Result<()> { |
| 75 |
// The query plan bitmask |
| 76 |
let mut idx_num: QueryPlanFlags = QueryPlanFlags::empty(); |
| 77 |
// Mask of unusable constraints |
| 78 |
let mut unusable_mask: QueryPlanFlags = QueryPlanFlags::empty(); |
| 79 |
// Constraints on start, stop, and step |
| 80 |
let mut a_idx: [Option<usize>; 3] = [None, None, None]; |
| 81 |
for (i, constraint) in info.constraints().enumerate() { |
| 82 |
if constraint.column() < SERIES_COLUMN_START { |
| 83 |
continue; |
| 84 |
} |
| 85 |
let (i_col, i_mask) = match constraint.column() { |
| 86 |
SERIES_COLUMN_START => (0, QueryPlanFlags::START), |
| 87 |
SERIES_COLUMN_STOP => (1, QueryPlanFlags::STOP), |
| 88 |
SERIES_COLUMN_STEP => (2, QueryPlanFlags::STEP), |
| 89 |
_ => { |
| 90 |
unreachable!() |
| 91 |
} |
| 92 |
}; |
| 93 |
if !constraint.is_usable() { |
| 94 |
unusable_mask |= i_mask; |
| 95 |
} else if constraint.operator() == IndexConstraintOp::SQLITE_INDEX_CONSTRAINT_EQ { |
| 96 |
idx_num |= i_mask; |
| 97 |
a_idx[i_col] = Some(i); |
| 98 |
} |
| 99 |
} |
| 100 |
// Number of arguments that SeriesTabCursor::filter expects |
| 101 |
let mut n_arg = 0; |
| 102 |
for j in a_idx.iter().flatten() { |
| 103 |
n_arg += 1; |
| 104 |
let mut constraint_usage = info.constraint_usage(*j); |
| 105 |
constraint_usage.set_argv_index(n_arg); |
| 106 |
constraint_usage.set_omit(true); |
| 107 |
#[cfg(all(test, feature = "modern_sqlite"))] |
| 108 |
debug_assert_eq!(Ok("BINARY"), info.collation(*j)); |
| 109 |
} |
| 110 |
if !(unusable_mask & !idx_num).is_empty() { |
| 111 |
return Err(error_from_sqlite_code(ffi::SQLITE_CONSTRAINT, None)); |
| 112 |
} |
| 113 |
if idx_num.contains(QueryPlanFlags::BOTH) { |
| 114 |
// Both start= and stop= boundaries are available. |
| 115 |
#[expect(clippy::bool_to_int_with_if)] |
| 116 |
info.set_estimated_cost(f64::from( |
| 117 |
2 - if idx_num.contains(QueryPlanFlags::STEP) { |
| 118 |
1 |
| 119 |
} else { |
| 120 |
0 |
| 121 |
}, |
| 122 |
)); |
| 123 |
info.set_estimated_rows(1000); |
| 124 |
let order_by_consumed = { |
| 125 |
let mut order_bys = info.order_bys(); |
| 126 |
if let Some(order_by) = order_bys.next() { |
| 127 |
if order_by.column() == 0 { |
| 128 |
if order_by.is_order_by_desc() { |
| 129 |
idx_num |= QueryPlanFlags::DESC; |
| 130 |
} else { |
| 131 |
idx_num |= QueryPlanFlags::ASC; |
| 132 |
} |
| 133 |
true |
| 134 |
} else { |
| 135 |
false |
| 136 |
} |
| 137 |
} else { |
| 138 |
false |
| 139 |
} |
| 140 |
}; |
| 141 |
if order_by_consumed { |
| 142 |
info.set_order_by_consumed(true); |
| 143 |
} |
| 144 |
} else { |
| 145 |
// If either boundary is missing, we have to generate a huge span |
| 146 |
// of numbers. Make this case very expensive so that the query |
| 147 |
// planner will work hard to avoid it. |
| 148 |
info.set_estimated_rows(2_147_483_647); |
| 149 |
} |
| 150 |
info.set_idx_num(idx_num.bits()); |
| 151 |
Ok(()) |
| 152 |
} |
| 153 |
|
| 154 |
fn open(&mut self) -> Result<SeriesTabCursor<'_>> { |
| 155 |
Ok(SeriesTabCursor::new()) |
| 156 |
} |
| 157 |
} |
| 158 |
|
| 159 |
/// A cursor for the Series virtual table |
| 160 |
#[repr(C)] |
| 161 |
struct SeriesTabCursor<'vtab> { |
| 162 |
/// Base class. Must be first |
| 163 |
base: ffi::sqlite3_vtab_cursor, |
| 164 |
/// True to count down rather than up |
| 165 |
is_desc: bool, |
| 166 |
/// The rowid |
| 167 |
row_id: i64, |
| 168 |
/// Current value ("value") |
| 169 |
value: i64, |
| 170 |
/// Minimum value ("start") |
| 171 |
min_value: i64, |
| 172 |
/// Maximum value ("stop") |
| 173 |
max_value: i64, |
| 174 |
/// Increment ("step") |
| 175 |
step: i64, |
| 176 |
phantom: PhantomData<&'vtab SeriesTab>, |
| 177 |
} |
| 178 |
|
| 179 |
impl SeriesTabCursor<'_> { |
| 180 |
fn new<'vtab>() -> SeriesTabCursor<'vtab> { |
| 181 |
SeriesTabCursor { |
| 182 |
base: ffi::sqlite3_vtab_cursor::default(), |
| 183 |
is_desc: false, |
| 184 |
row_id: 0, |
| 185 |
value: 0, |
| 186 |
min_value: 0, |
| 187 |
max_value: 0, |
| 188 |
step: 0, |
| 189 |
phantom: PhantomData, |
| 190 |
} |
| 191 |
} |
| 192 |
} |
| 193 |
#[expect(clippy::comparison_chain)] |
| 194 |
unsafe impl VTabCursor for SeriesTabCursor<'_> { |
| 195 |
fn filter(&mut self, idx_num: c_int, _idx_str: Option<&str>, args: &Values<'_>) -> Result<()> { |
| 196 |
let mut idx_num = QueryPlanFlags::from_bits_truncate(idx_num); |
| 197 |
let mut i = 0; |
| 198 |
if idx_num.contains(QueryPlanFlags::START) { |
| 199 |
self.min_value = args.get::<Option<_>>(i)?.unwrap_or_default(); |
| 200 |
i += 1; |
| 201 |
} else { |
| 202 |
self.min_value = 0; |
| 203 |
} |
| 204 |
if idx_num.contains(QueryPlanFlags::STOP) { |
| 205 |
self.max_value = args.get::<Option<_>>(i)?.unwrap_or_default(); |
| 206 |
i += 1; |
| 207 |
} else { |
| 208 |
self.max_value = 0xffff_ffff; |
| 209 |
} |
| 210 |
if idx_num.contains(QueryPlanFlags::STEP) { |
| 211 |
self.step = args.get::<Option<_>>(i)?.unwrap_or_default(); |
| 212 |
if self.step == 0 { |
| 213 |
self.step = 1; |
| 214 |
} else if self.step < 0 { |
| 215 |
self.step = -self.step; |
| 216 |
if !idx_num.contains(QueryPlanFlags::ASC) { |
| 217 |
idx_num |= QueryPlanFlags::DESC; |
| 218 |
} |
| 219 |
} |
| 220 |
} else { |
| 221 |
self.step = 1; |
| 222 |
}; |
| 223 |
for arg in args.iter() { |
| 224 |
if arg.data_type() == Type::Null { |
| 225 |
// If any of the constraints have a NULL value, then return no rows. |
| 226 |
self.min_value = 1; |
| 227 |
self.max_value = 0; |
| 228 |
break; |
| 229 |
} |
| 230 |
} |
| 231 |
self.is_desc = idx_num.contains(QueryPlanFlags::DESC); |
| 232 |
if self.is_desc { |
| 233 |
self.value = self.max_value; |
| 234 |
if self.step > 0 { |
| 235 |
self.value -= (self.max_value - self.min_value) % self.step; |
| 236 |
} |
| 237 |
} else { |
| 238 |
self.value = self.min_value; |
| 239 |
} |
| 240 |
self.row_id = 1; |
| 241 |
Ok(()) |
| 242 |
} |
| 243 |
|
| 244 |
fn next(&mut self) -> Result<()> { |
| 245 |
if self.is_desc { |
| 246 |
self.value -= self.step; |
| 247 |
} else { |
| 248 |
self.value += self.step; |
| 249 |
} |
| 250 |
self.row_id += 1; |
| 251 |
Ok(()) |
| 252 |
} |
| 253 |
|
| 254 |
fn eof(&self) -> bool { |
| 255 |
if self.is_desc { |
| 256 |
self.value < self.min_value |
| 257 |
} else { |
| 258 |
self.value > self.max_value |
| 259 |
} |
| 260 |
} |
| 261 |
|
| 262 |
fn column(&self, ctx: &mut Context, i: c_int) -> Result<()> { |
| 263 |
let x = match i { |
| 264 |
SERIES_COLUMN_START => self.min_value, |
| 265 |
SERIES_COLUMN_STOP => self.max_value, |
| 266 |
SERIES_COLUMN_STEP => self.step, |
| 267 |
_ => self.value, |
| 268 |
}; |
| 269 |
ctx.set_result(&x) |
| 270 |
} |
| 271 |
|
| 272 |
fn rowid(&self) -> Result<i64> { |
| 273 |
Ok(self.row_id) |
| 274 |
} |
| 275 |
} |
| 276 |
|
| 277 |
#[cfg(test)] |
| 278 |
mod test { |
| 279 |
use crate::ffi; |
| 280 |
use crate::vtab::series; |
| 281 |
use crate::{Connection, Result}; |
| 282 |
use fallible_iterator::FallibleIterator; |
| 283 |
|
| 284 |
#[test] |
| 285 |
fn test_series_module() -> Result<()> { |
| 286 |
let version = unsafe { ffi::sqlite3_libversion_number() }; |
| 287 |
if version < 3_008_012 { |
| 288 |
return Ok(()); |
| 289 |
} |
| 290 |
|
| 291 |
let db = Connection::open_in_memory()?; |
| 292 |
series::load_module(&db)?; |
| 293 |
|
| 294 |
let mut s = db.prepare("SELECT * FROM generate_series(0,20,5)")?; |
| 295 |
|
| 296 |
let series = s.query_map([], |row| row.get::<_, i32>(0))?; |
| 297 |
|
| 298 |
let mut expected = 0; |
| 299 |
for value in series { |
| 300 |
assert_eq!(expected, value?); |
| 301 |
expected += 5; |
| 302 |
} |
| 303 |
|
| 304 |
let mut s = |
| 305 |
db.prepare("SELECT * FROM generate_series WHERE start=1 AND stop=9 AND step=2")?; |
| 306 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 307 |
assert_eq!(vec![1, 3, 5, 7, 9], series); |
| 308 |
let mut s = db.prepare("SELECT * FROM generate_series LIMIT 5")?; |
| 309 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 310 |
assert_eq!(vec![0, 1, 2, 3, 4], series); |
| 311 |
let mut s = db.prepare("SELECT * FROM generate_series(0,32,5) ORDER BY value DESC")?; |
| 312 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 313 |
assert_eq!(vec![30, 25, 20, 15, 10, 5, 0], series); |
| 314 |
|
| 315 |
let mut s = db.prepare("SELECT * FROM generate_series(NULL)")?; |
| 316 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 317 |
let empty = Vec::<i32>::new(); |
| 318 |
assert_eq!(empty, series); |
| 319 |
let mut s = db.prepare("SELECT * FROM generate_series(5,NULL)")?; |
| 320 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 321 |
assert_eq!(empty, series); |
| 322 |
let mut s = db.prepare("SELECT * FROM generate_series(5,10,NULL)")?; |
| 323 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 324 |
assert_eq!(empty, series); |
| 325 |
let mut s = db.prepare("SELECT * FROM generate_series(NULL,10,2)")?; |
| 326 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 327 |
assert_eq!(empty, series); |
| 328 |
let mut s = db.prepare("SELECT * FROM generate_series(5,NULL,2)")?; |
| 329 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 330 |
assert_eq!(empty, series); |
| 331 |
let mut s = db.prepare("SELECT * FROM generate_series(NULL) ORDER BY value DESC")?; |
| 332 |
let series: Vec<i32> = s.query([])?.map(|r| r.get(0)).collect()?; |
| 333 |
assert_eq!(empty, series); |
| 334 |
|
| 335 |
Ok(()) |
| 336 |
} |
| 337 |
} |