Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/sqlite/blob/master/ext/misc/series.c # sqlite [Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `sqlite / ext / misc / series.c` 988 lines ยท 32469 bytes Raw Blame History 1 /* 2 ** 2015-08-18, 2023-04-28 3 ** 4 ** The author disclaims copyright to this source code. In place of 5 ** a legal notice, here is a blessing: 6 ** 7 ** May you do good and not evil. 8 ** May you find forgiveness for yourself and forgive others. 9 ** May you share freely, never taking more than you give. 10 ** 11 ************************************************************************* 12 ** 13 ** This file demonstrates how to create a table-valued-function using 14 ** a virtual table. This demo implements the generate_series() function 15 ** which gives the same results as the eponymous function in PostgreSQL, 16 ** within the limitation that its arguments are signed 64-bit integers. 17 ** 18 ** Considering its equivalents to generate_series(start,stop,step): A 19 ** value V[n] sequence is produced for integer n ascending from 0 where 20 ** ( V[n] == start + n * step && sgn(V[n] - stop) * sgn(step) >= 0 ) 21 ** for each produced value (independent of production time ordering.) 22 ** 23 ** All parameters must be either integer or convertable to integer. 24 ** The start parameter is required. 25 ** The stop parameter defaults to (1<<32)-1 (aka `4294967295` or 0xffffffff) 26 ** The step parameter defaults to 1 and 0 is treated as 1. 27 ** 28 ** Examples: 29 ** 30 ** SELECT * FROM generate_series(0,100,5); 31 ** 32 ** The query above returns integers from 0 through 100 counting by steps 33 ** of 5. In other words, 0, 5, 10, 15, ..., 90, 95, 100. There are a total 34 ** of 21 rows. 35 ** 36 ** SELECT * FROM generate_series(0,100); 37 ** 38 ** Integers from 0 through 100 with a step size of 1. 101 rows. 39 ** 40 ** SELECT * FROM generate_series(20) LIMIT 10; 41 ** 42 ** Integers 20 through 29. 10 rows. 43 ** 44 ** SELECT * FROM generate_series(0,-100,-5); 45 ** 46 ** Integers 0 -5 -10 ... -100. 21 rows. 47 ** 48 ** SELECT * FROM generate_series(0,-1); 49 ** 50 ** Empty sequence. 51 ** 52 ** HOW IT WORKS 53 ** 54 ** The generate_series "function" is really a virtual table with the 55 ** following schema: 56 ** 57 ** CREATE TABLE generate_series( 58 ** value, 59 ** start HIDDEN, 60 ** stop HIDDEN, 61 ** step HIDDEN 62 ** ); 63 ** 64 ** The virtual table also has a rowid which is an alias for the value. 65 ** 66 ** Function arguments in queries against this virtual table are translated 67 ** into equality constraints against successive hidden columns. In other 68 ** words, the following pairs of queries are equivalent to each other: 69 ** 70 ** SELECT * FROM generate_series(0,100,5); 71 ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5; 72 ** 73 ** SELECT * FROM generate_series(0,100); 74 ** SELECT * FROM generate_series WHERE start=0 AND stop=100; 75 ** 76 ** SELECT * FROM generate_series(20) LIMIT 10; 77 ** SELECT * FROM generate_series WHERE start=20 LIMIT 10; 78 ** 79 ** The generate_series virtual table implementation leaves the xCreate method 80 ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL 81 ** TABLE command with "generate_series" as the USING argument. Instead, there 82 ** is a single generate_series virtual table that is always available without 83 ** having to be created first. 84 ** 85 ** The xBestIndex method looks for equality constraints against the hidden 86 ** start, stop, and step columns, and if present, it uses those constraints 87 ** to bound the sequence of generated values. If the equality constraints 88 ** are missing, it uses 0 for start, `4294967295` for stop, and 1 for step. 89 ** xBestIndex returns a small cost when both start and stop are available, 90 ** and a very large cost if either start or stop are unavailable. This 91 ** encourages the query planner to order joins such that the bounds of the 92 ** series are well-defined. 93 ** 94 ** Update on 2024-08-22: 95 ** xBestIndex now also looks for equality and inequality constraints against 96 ** the value column and uses those constraints as additional bounds against 97 ** the sequence range. Thus, a query like this: 98 ** 99 ** SELECT value FROM generate_series($SA,$EA) 100 ** WHERE value BETWEEN $SB AND $EB; 101 ** 102 ** Is logically the same as: 103 ** 104 ** SELECT value FROM generate_series(max($SA,$SB),min($EA,$EB)); 105 ** 106 ** Constraints on the value column can server as substitutes for constraints 107 ** on the hidden start and stop columns. So, the following two queries 108 ** are equivalent: 109 ** 110 ** SELECT value FROM generate_series($S,$E); 111 ** SELECT value FROM generate_series WHERE value BETWEEN $S and $E; 112 ** 113 */ 114 #include "sqlite3ext.h" 115 SQLITE_EXTENSION_INIT1 116 #include 117 #include 118 #include 119 #include 120 121 #ifndef SQLITE_OMIT_VIRTUALTABLE 122 123 /* series_cursor is a subclass of sqlite3_vtab_cursor which will 124 ** serve as the underlying representation of a cursor that scans 125 ** over rows of the result. 126 ** 127 ** iOBase, iOTerm, and iOStep are the original values of the 128 ** start=, stop=, and step= constraints on the query. These are 129 ** the values reported by the start, stop, and step columns of the 130 ** virtual table. 131 ** 132 ** iBase, iTerm, iStep, and bDescp are the actual values used to generate 133 ** the sequence. These might be different from the iOxxxx values. 134 ** For example in 135 ** 136 ** SELECT value FROM generate_series(1,11,2) 137 ** WHERE value BETWEEN 4 AND 8; 138 ** 139 ** The iOBase is 1, but the iBase is 5. iOTerm is 11 but iTerm is 7. 140 ** Another example: 141 ** 142 ** SELECT value FROM generate_series(1,15,3) ORDER BY value DESC; 143 ** 144 ** The cursor initialization for the above query is: 145 ** 146 ** iOBase = 1 iBase = 13 147 ** iOTerm = 15 iTerm = 1 148 ** iOStep = 3 iStep = 3 bDesc = 1 149 ** 150 ** The actual step size is unsigned so that can have a value of 151 ** +`9223372036854775808` which is needed for querys like this: 152 ** 153 ** SELECT value 154 ** FROM generate_series(`9223372036854775807`, 155 ** -`9223372036854775808`, 156 ** -`9223372036854775808`) 157 ** ORDER BY value ASC; 158 ** 159 ** The setup for the previous query will be: 160 ** 161 ** iOBase = `9223372036854775807` iBase = -1 162 ** iOTerm = -`9223372036854775808` iTerm = `9223372036854775807` 163 ** iOStep = -`9223372036854775808` iStep = `9223372036854775808` bDesc = 0 164 */ 165 typedef unsigned char u8; 166 typedef struct series_cursor series_cursor; 167 struct series_cursor { 168 sqlite3_vtab_cursor base; /* Base class - must be first */ 169 sqlite3_int64 iOBase; /* Original starting value ("start") */ 170 sqlite3_int64 iOTerm; /* Original terminal value ("stop") */ 171 sqlite3_int64 iOStep; /* Original step value */ 172 sqlite3_int64 iBase; /* Starting value to actually use */ 173 sqlite3_int64 iTerm; /* Terminal value to actually use */ 174 sqlite3_uint64 iStep; /* The step size */ 175 sqlite3_int64 iValue; /* Current value */ 176 u8 bDesc; /* iStep is really negative */ 177 u8 bDone; /* True if stepped past last element */ 178 u8 bLimit; /* There exists a limit clause */ 179 }; 180 181 /* 182 ** Computed the difference between two 64-bit signed integers using a 183 ** convoluted computation designed to work around the silly restriction 184 ** against signed integer overflow in C. 185 */ 186 static sqlite3_uint64 span64(sqlite3_int64 a, sqlite3_int64 b){ 187 assert( a>=b ); 188 return (*(sqlite3_uint64*)&a) - (*(sqlite3_uint64*)&b); 189 } 190 191 /* 192 ** Add or substract an unsigned 64-bit integer from a signed 64-bit integer 193 ** and return the new signed 64-bit integer. 194 */ 195 static sqlite3_int64 add64(sqlite3_int64 a, sqlite3_uint64 b){ 196 sqlite3_uint64 x = *(sqlite3_uint64*)&a; 197 x += b; 198 return *(sqlite3_int64*)&x; 199 } 200 static sqlite3_int64 sub64(sqlite3_int64 a, sqlite3_uint64 b){ 201 sqlite3_uint64 x = *(sqlite3_uint64*)&a; 202 x -= b; 203 return *(sqlite3_int64*)&x; 204 } 205 206 /* 207 ** The seriesConnect() method is invoked to create a new 208 ** series_vtab that describes the generate_series virtual table. 209 ** 210 ** Think of this routine as the constructor for series_vtab objects. 211 ** 212 ** All this routine needs to do is: 213 ** 214 ** (1) Allocate the series_vtab object and initialize all fields. 215 ** 216 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the 217 ** result set of queries against generate_series will look like. 218 */ 219 static int seriesConnect( 220 sqlite3 *db, 221 void *pUnused, 222 int argcUnused, const char *const*argvUnused, 223 sqlite3_vtab **ppVtab, 224 char **pzErrUnused 225 ){ 226 sqlite3_vtab *pNew; 227 int rc; 228 229 /* Column numbers */ 230 #define SERIES_COLUMN_ROWID (-1) 231 #define SERIES_COLUMN_VALUE 0 232 #define SERIES_COLUMN_START 1 233 #define SERIES_COLUMN_STOP 2 234 #define SERIES_COLUMN_STEP 3 235 236 (void)pUnused; 237 (void)argcUnused; 238 (void)argvUnused; 239 (void)pzErrUnused; 240 rc = sqlite3_declare_vtab(db, 241 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)"); 242 if( rc==SQLITE_OK ){ 243 pNew = *ppVtab = sqlite3_malloc64( sizeof(*pNew) ); 244 if( pNew==0 ) return SQLITE_NOMEM; 245 memset(pNew, 0, sizeof(*pNew)); 246 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS); 247 } 248 return rc; 249 } 250 251 /* 252 ** This method is the destructor for series_cursor objects. 253 */ 254 static int seriesDisconnect(sqlite3_vtab *pVtab){ 255 sqlite3_free(pVtab); 256 return SQLITE_OK; 257 } 258 259 /* 260 ** Constructor for a new series_cursor object. 261 */ 262 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){ 263 series_cursor *pCur; 264 (void)pUnused; 265 pCur = sqlite3_malloc64( sizeof(*pCur) ); 266 if( pCur==0 ) return SQLITE_NOMEM; 267 memset(pCur, 0, sizeof(*pCur)); 268 *ppCursor = &pCur->base; 269 return SQLITE_OK; 270 } 271 272 /* 273 ** Destructor for a series_cursor. 274 */ 275 static int seriesClose(sqlite3_vtab_cursor *cur){ 276 sqlite3_free(cur); 277 return SQLITE_OK; 278 } 279 280 281 /* 282 ** Advance a series_cursor to its next row of output. 283 */ 284 static int seriesNext(sqlite3_vtab_cursor *cur){ 285 series_cursor *pCur = (series_cursor*)cur; 286 if( pCur->iValue==pCur->iTerm ){ 287 pCur->bDone = 1; 288 }else if( pCur->bDesc ){ 289 pCur->iValue = sub64(pCur->iValue, pCur->iStep); 290 assert( pCur->iValue>=pCur->iTerm || pCur->bLimit ); 291 }else{ 292 pCur->iValue = add64(pCur->iValue, pCur->iStep); 293 assert( pCur->iValue<=pCur->iTerm || pCur->bLimit ); 294 } 295 return SQLITE_OK; 296 } 297 298 /* 299 ** Return values of columns for the row at which the series_cursor 300 ** is currently pointing. 301 */ 302 static int seriesColumn( 303 sqlite3_vtab_cursor *cur, /* The cursor */ 304 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */ 305 int i /* Which column to return */ 306 ){ 307 series_cursor *pCur = (series_cursor*)cur; 308 sqlite3_int64 x = 0; 309 switch( i ){ 310 case SERIES_COLUMN_START: x = pCur->iOBase; break; 311 case SERIES_COLUMN_STOP: x = pCur->iOTerm; break; 312 case SERIES_COLUMN_STEP: x = pCur->iOStep; break; 313 default: x = pCur->iValue; break; 314 } 315 sqlite3_result_int64(ctx, x); 316 return SQLITE_OK; 317 } 318 319 #ifndef LARGEST_UINT64 320 #define LARGEST_INT64 ((sqlite3_int64)0x7fffffffffffffffLL) 321 #define LARGEST_UINT64 ((sqlite3_uint64)0xffffffffffffffffULL) 322 #define SMALLEST_INT64 ((sqlite3_int64)0x8000000000000000LL) 323 #endif 324 325 /* 326 ** The rowid is the same as the value. 327 */ 328 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){ 329 series_cursor *pCur = (series_cursor*)cur; 330 *pRowid = pCur->iValue; 331 return SQLITE_OK; 332 } 333 334 /* 335 ** Return TRUE if the cursor has been moved off of the last 336 ** row of output. 337 */ 338 static int seriesEof(sqlite3_vtab_cursor *cur){ 339 series_cursor *pCur = (series_cursor*)cur; 340 return pCur->bDone; 341 } 342 343 /* True to cause run-time checking of the start=, stop=, and/or step= 344 ** parameters. The only reason to do this is for testing the 345 ** constraint checking logic for virtual tables in the SQLite core. 346 */ 347 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY 348 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0 349 #endif 350 351 /* 352 ** Return the number of steps between pCur->iBase and pCur->iTerm if 353 ** the step width is pCur->iStep. 354 */ 355 static sqlite3_uint64 seriesSteps(series_cursor *pCur){ 356 if( pCur->bDesc ){ 357 assert( pCur->iBase >= pCur->iTerm ); 358 return span64(pCur->iBase, pCur->iTerm)/pCur->iStep; 359 }else{ 360 assert( pCur->iBase <= pCur->iTerm ); 361 return span64(pCur->iTerm, pCur->iBase)/pCur->iStep; 362 } 363 } 364 365 #if defined(SQLITE_ENABLE_MATH_FUNCTIONS) || defined(_WIN32) 366 /* 367 ** Case 1 (the most common case): 368 ** The standard math library is available so use ceil() and floor() from there. 369 */ 370 static double seriesCeil(double r){ return ceil(r); } 371 static double seriesFloor(double r){ return floor(r); } 372 #elif defined(__GNUC__) && !defined(SQLITE_DISABLE_INTRINSIC) 373 /* 374 ** Case 2 (2nd most common): Use GCC/Clang builtins 375 */ 376 static double seriesCeil(double r){ return __builtin_ceil(r); } 377 static double seriesFloor(double r){ return __builtin_floor(r); } 378 #else 379 /* 380 ** Case 3 (rarely happens): Use home-grown ceil() and floor() routines. 381 */ 382 static double seriesCeil(double r){ 383 sqlite3_int64 x; 384 if( r!=r ) return r; 385 if( r<=(-`4503599627370496`.0) ) return r; 386 if( r>=(+`4503599627370496`.0) ) return r; 387 x = (sqlite3_int64)r; 388 if( r==(double)x ) return r; 389 if( r>(double)x ) x++; 390 return (double)x; 391 } 392 static double seriesFloor(double r){ 393 sqlite3_int64 x; 394 if( r!=r ) return r; 395 if( r<=(-`4503599627370496`.0) ) return r; 396 if( r>=(+`4503599627370496`.0) ) return r; 397 x = (sqlite3_int64)r; 398 if( r==(double)x ) return r; 399 if( r<(double)x ) x--; 400 return (double)x; 401 } 402 #endif 403 404 /* Convert a floating point value to its closest integer. Do so in 405 ** a way that avoids 'outside the range of representable values' warnings 406 ** from UBSAN. 407 */ 408 static sqlite3_int64 seriesRealToI64(double r){ 409 if( r<-`9223372036854774784`.0 ) return SMALLEST_INT64; 410 if( r>+`9223372036854774784`.0 ) return LARGEST_INT64; 411 return (sqlite3_int64)r; 412 } 413 414 /* Return true if the type of the value is TEXT or BLOB. 415 */ 416 static int seriesIsTextOrBlob(sqlite3_value *pVal){ 417 int eType = sqlite3_value_type(pVal); 418 return eType==SQLITE_TEXT || eType==SQLITE_BLOB; 419 } 420 421 /* 422 ** This method is called to "rewind" the series_cursor object back 423 ** to the first row of output. This method is always called at least 424 ** once prior to any call to seriesColumn() or seriesRowid() or 425 ** seriesEof(). 426 ** 427 ** The query plan selected by seriesBestIndex is passed in the idxNum 428 ** parameter. (idxStr is not used in this implementation.) idxNum 429 ** is a bitmask showing which constraints are available: 430 ** 431 ** 0x0001: start=VALUE 432 ** 0x0002: stop=VALUE 433 ** 0x0004: step=VALUE 434 ** 0x0008: descending order 435 ** 0x0010: ascending order 436 ** 0x0020: LIMIT VALUE 437 ** 0x0040: OFFSET VALUE 438 ** 0x0080: value=VALUE 439 ** 0x0100: value>=VALUE 440 ** 0x0200: value>VALUE 441 ** 0x1000: value<=VALUE 442 ** 0x2000: value0, the value of the LIMIT */ 459 sqlite3_int64 iOffset = 0; /* if >0, the value of the OFFSET */ 460 461 (void)idxStrUnused; 462 463 /* If any constraints have a NULL value, then return no rows. 464 ** See ticket https://sqlite.org/src/info/`fac496b61722daf2` 465 */ 466 for(i=0; i