interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

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"
115SQLITE_EXTENSION_INIT1
116#include <assert.h>
117#include <string.h>
118#include <limits.h>
119#include <math.h>
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*/
165typedef unsigned char u8;
166typedef struct series_cursor series_cursor;
167struct 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*/
186static 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*/
195static 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}
200static 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*/
219static 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*/
254static 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*/
262static 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*/
275static 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*/
284static 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*/
302static 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*/
328static 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*/
338static 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*/
355static 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*/
370static double seriesCeil(double r){ return ceil(r); }
371static 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*/
376static double seriesCeil(double r){ return __builtin_ceil(r); }
377static double seriesFloor(double r){ return __builtin_floor(r); }
378#else
379/*
380** Case 3 (rarely happens): Use home-grown ceil() and floor() routines.
381*/
382static 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}
392static 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*/
408static 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*/
416static 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: value<VALUE
443**
444** This routine should initialize the cursor and position it so that it
445** is pointing at the first row, or pointing off the end of the table
446** (so that seriesEof() will return true) if the table is empty.
447*/
448static int seriesFilter(
449 sqlite3_vtab_cursor *pVtabCursor,
450 int idxNum, const char *idxStrUnused,
451 int argc, sqlite3_value **argv
452){
453 series_cursor *pCur = (series_cursor *)pVtabCursor;
454 int iArg = 0; /* Arguments used so far */
455 int i; /* Loop counter */
456 sqlite3_int64 iMin = SMALLEST_INT64; /* Smallest allowed output value */
457 sqlite3_int64 iMax = LARGEST_INT64; /* Largest allowed output value */
458 sqlite3_int64 iLimit = 0; /* if >0, 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<argc; i++){
467 if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
468 goto series_no_rows;
469 }
470 }
471
472 /* Capture the three HIDDEN parameters to the virtual table and insert
473 ** default values for any parameters that are omitted.
474 */
475 if( idxNum & 0x01 ){
476 pCur->iOBase = sqlite3_value_int64(argv[iArg++]);
477 }else{
478 pCur->iOBase = 0;
479 }
480 if( idxNum & 0x02 ){
481 pCur->iOTerm = sqlite3_value_int64(argv[iArg++]);
482 }else{
483 pCur->iOTerm = 0xffffffff;
484 }
485 if( idxNum & 0x04 ){
486 pCur->iOStep = sqlite3_value_int64(argv[iArg++]);
487 if( pCur->iOStep==0 ) pCur->iOStep = 1;
488 }else{
489 pCur->iOStep = 1;
490 }
491
492 /* If there are constraints on the value column but there are
493 ** no constraints on the start, stop, and step columns, then
494 ** initialize the default range to be the entire range of 64-bit signed
495 ** integers. This range will contracted by the value column constraints
496 ** further below.
497 */
498 if( (idxNum & 0x05)==0 && (idxNum & 0x0380)!=0 ){
499 pCur->iOBase = SMALLEST_INT64;
500 }
501 if( (idxNum & 0x06)==0 && (idxNum & 0x3080)!=0 ){
502 pCur->iOTerm = LARGEST_INT64;
503 }
504 pCur->iBase = pCur->iOBase;
505 pCur->iTerm = pCur->iOTerm;
506 if( pCur->iOStep>0 ){
507 pCur->iStep = pCur->iOStep;
508 }else if( pCur->iOStep>SMALLEST_INT64 ){
509 pCur->iStep = -pCur->iOStep;
510 }else{
511 pCur->iStep = LARGEST_INT64;
512 pCur->iStep++;
513 }
514 pCur->bDesc = pCur->iOStep<0;
515 if( pCur->bDesc==0 && pCur->iBase>pCur->iTerm ){
516 goto series_no_rows;
517 }
518 if( pCur->bDesc!=0 && pCur->iBase<pCur->iTerm ){
519 goto series_no_rows;
520 }
521
522 /* Extract the LIMIT and OFFSET values, but do not apply them yet.
523 ** The range must first be constrained by the limits on value.
524 */
525 if( idxNum & 0x20 ){
526 iLimit = sqlite3_value_int64(argv[iArg++]);
527 if( idxNum & 0x40 ){
528 iOffset = sqlite3_value_int64(argv[iArg++]);
529 }
530 if( iLimit>0 ) pCur->bLimit = 1;
531 }
532
533 /* Narrow the range of iMin and iMax (the minimum and maximum outputs)
534 ** based on equality and inequality constraints on the "value" column.
535 **
536 ** The "value" column has no affinity, so a TEXT or BLOB operand X is
537 ** not converted into a number. Every INTEGER is less than any TEXT
538 ** or BLOB, so "value=X", "value>X" and "value>=X" are never true and
539 ** "value<X" and "value<=X" are always true. The type must be checked
540 ** before sqlite3_value_numeric_type(), which would convert a TEXT
541 ** value such as '3' into a number.
542 */
543 if( idxNum & 0x3380 ){
544 if( idxNum & 0x0080 ){ /* value=X */
545 if( seriesIsTextOrBlob(argv[iArg]) ){
546 goto series_no_rows;
547 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
548 double r = sqlite3_value_double(argv[iArg++]);
549 if( r==seriesCeil(r)
550 && r>=(double)SMALLEST_INT64
551 && r<=(double)LARGEST_INT64
552 ){
553 iMin = iMax = seriesRealToI64(r);
554 }else{
555 goto series_no_rows;
556 }
557 }else{
558 iMin = iMax = sqlite3_value_int64(argv[iArg++]);
559 }
560 }else{
561 if( idxNum & 0x0300 ){ /* value>X (0x200) or value>=X (0x100) */
562 if( seriesIsTextOrBlob(argv[iArg]) ){
563 goto series_no_rows;
564 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
565 double r = sqlite3_value_double(argv[iArg++]);
566 if( r<=(double)SMALLEST_INT64 ){
567 iMin = SMALLEST_INT64;
568 }else if( r>(double)LARGEST_INT64 ){
569 goto series_no_rows;
570 }else{
571 iMin = seriesRealToI64(seriesCeil(r));
572 if( (idxNum & 0x0200)!=0 && r==seriesCeil(r) ){
573 if( iMin==LARGEST_INT64 ) goto series_no_rows;
574 iMin++;
575 }
576 }
577 }else{
578 iMin = sqlite3_value_int64(argv[iArg++]);
579 if( (idxNum & 0x0200)!=0 ){
580 if( iMin==LARGEST_INT64 ){
581 goto series_no_rows;
582 }else{
583 iMin++;
584 }
585 }
586 }
587 }
588 if( idxNum & 0x3000 ){ /* value<X (0x2000) or value<=X (0x1000) */
589 if( seriesIsTextOrBlob(argv[iArg]) ){
590 iArg++; /* No upper bound */
591 }else if( sqlite3_value_numeric_type(argv[iArg])==SQLITE_FLOAT ){
592 double r = sqlite3_value_double(argv[iArg++]);
593 if( r>=(double)LARGEST_INT64 ){
594 iMax = LARGEST_INT64;
595 }else if( r<=(double)SMALLEST_INT64 ){
596 goto series_no_rows;
597 }else{
598 iMax = seriesRealToI64(seriesFloor(r));
599 if( (idxNum & 0x2000)!=0 && r==seriesFloor(r) ){
600 if( iMax==SMALLEST_INT64 ) goto series_no_rows;
601 iMax--;
602 }
603 }
604 }else{
605 iMax = sqlite3_value_int64(argv[iArg++]);
606 if( idxNum & 0x2000 ){
607 if( iMax==SMALLEST_INT64 ){
608 goto series_no_rows;
609 }else{
610 iMax--;
611 }
612 }
613 }
614 }
615 if( iMin>iMax ){
616 goto series_no_rows;
617 }
618 }
619
620 /* Try to reduce the range of values to be generated based on
621 ** constraints on the "value" column.
622 */
623 if( pCur->bDesc==0 ){
624 if( pCur->iBase<iMin ){
625 sqlite3_uint64 span = span64(iMin,pCur->iBase);
626 pCur->iBase = add64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
627 if( pCur->iBase<iMin ){
628 if( pCur->iBase > sub64(LARGEST_INT64, pCur->iStep) ){
629 goto series_no_rows;
630 }
631 pCur->iBase = add64(pCur->iBase, pCur->iStep);
632 }
633 }
634 if( pCur->iTerm>iMax ){
635 pCur->iTerm = iMax;
636 }
637 }else{
638 if( pCur->iBase>iMax ){
639 sqlite3_uint64 span = span64(pCur->iBase,iMax);
640 pCur->iBase = sub64(pCur->iBase, (span/pCur->iStep)*pCur->iStep);
641 if( pCur->iBase>iMax ){
642 if( pCur->iBase < add64(SMALLEST_INT64, pCur->iStep) ){
643 goto series_no_rows;
644 }
645 pCur->iBase = sub64(pCur->iBase, pCur->iStep);
646 }
647 }
648 if( pCur->iTerm<iMin ){
649 pCur->iTerm = iMin;
650 }
651 }
652 }
653
654 /* Adjust iTerm so that it is exactly the last value of the series.
655 */
656 if( pCur->bDesc==0 ){
657 if( pCur->iBase>pCur->iTerm ){
658 goto series_no_rows;
659 }
660 pCur->iTerm = sub64(pCur->iTerm,
661 span64(pCur->iTerm,pCur->iBase) % pCur->iStep);
662 }else{
663 if( pCur->iBase<pCur->iTerm ){
664 goto series_no_rows;
665 }
666 pCur->iTerm = add64(pCur->iTerm,
667 span64(pCur->iBase,pCur->iTerm) % pCur->iStep);
668 }
669
670 /* Transform the series generator to output values in the requested
671 ** order.
672 */
673 if( ((idxNum & 0x0008)!=0 && pCur->bDesc==0)
674 || ((idxNum & 0x0010)!=0 && pCur->bDesc!=0)
675 ){
676 sqlite3_int64 tmp = pCur->iBase;
677 pCur->iBase = pCur->iTerm;
678 pCur->iTerm = tmp;
679 pCur->bDesc = !pCur->bDesc;
680 }
681
682 /* Apply LIMIT and OFFSET constraints, if any */
683 assert( pCur->iStep!=0 );
684 if( idxNum & 0x20 ){
685 if( iOffset>0 ){
686 if( seriesSteps(pCur) < (sqlite3_uint64)iOffset ){
687 goto series_no_rows;
688 }else if( pCur->bDesc ){
689 pCur->iBase = sub64(pCur->iBase, pCur->iStep*iOffset);
690 }else{
691 pCur->iBase = add64(pCur->iBase, pCur->iStep*iOffset);
692 }
693 }
694 if( iLimit>=0 && seriesSteps(pCur) > (sqlite3_uint64)iLimit ){
695 pCur->iTerm = add64(pCur->iBase, (iLimit - 1)*pCur->iStep);
696 }
697 }
698 pCur->iValue = pCur->iBase;
699 pCur->bDone = 0;
700 return SQLITE_OK;
701
702series_no_rows:
703 pCur->iBase = 0;
704 pCur->iTerm = 0;
705 pCur->iStep = 1;
706 pCur->bDesc = 0;
707 pCur->bDone = 1;
708 return SQLITE_OK;
709}
710
711/*
712** SQLite will invoke this method one or more times while planning a query
713** that uses the generate_series virtual table. This routine needs to create
714** a query plan for each invocation and compute an estimated cost for that
715** plan.
716**
717** In this implementation idxNum is used to represent the
718** query plan. idxStr is unused.
719**
720** The query plan is represented by bits in idxNum:
721**
722** 0x0001 start = $num
723** 0x0002 stop = $num
724** 0x0004 step = $num
725** 0x0008 output is in descending order
726** 0x0010 output is in ascending order
727** 0x0020 LIMIT $num
728** 0x0040 OFFSET $num
729** 0x0080 value = $num
730** 0x0100 value >= $num
731** 0x0200 value > $num
732** 0x1000 value <= $num
733** 0x2000 value < $num
734**
735** Only one of 0x0100 or 0x0200 will be returned. Similarly, only
736** one of 0x1000 or 0x2000 will be returned. If the 0x0080 is set, then
737** none of the 0xff00 bits will be set.
738**
739** The order of parameters passed to xFilter is as follows:
740**
741** * The argument to start= if bit 0x0001 is in the idxNum mask
742** * The argument to stop= if bit 0x0002 is in the idxNum mask
743** * The argument to step= if bit 0x0004 is in the idxNum mask
744** * The argument to LIMIT if bit 0x0020 is in the idxNum mask
745** * The argument to OFFSET if bit 0x0040 is in the idxNum mask
746** * The argument to value=, or value>= or value> if any of
747** bits 0x0380 are in the idxNum mask
748** * The argument to value<= or value< if either of bits 0x3000
749** are in the mask
750**
751*/
752static int seriesBestIndex(
753 sqlite3_vtab *pVTab,
754 sqlite3_index_info *pIdxInfo
755){
756 int i, j; /* Loop over constraints */
757 int idxNum = 0; /* The query plan bitmask */
758#ifndef ZERO_ARGUMENT_GENERATE_SERIES
759 int bStartSeen = 0; /* EQ constraint seen on the START column */
760#endif
761 int unusableMask = 0; /* Mask of unusable constraints */
762 int nArg = 0; /* Number of arguments that seriesFilter() expects */
763 int aIdx[7]; /* Constraints on start, stop, step, LIMIT, OFFSET,
764 ** and value. aIdx[5] covers value=, value>=, and
765 ** value>, aIdx[6] covers value<= and value< */
766 const struct sqlite3_index_constraint *pConstraint;
767
768 /* This implementation assumes that the start, stop, and step columns
769 ** are the last three columns in the virtual table. */
770 assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
771 assert( SERIES_COLUMN_STEP == SERIES_COLUMN_START+2 );
772
773 aIdx[0] = aIdx[1] = aIdx[2] = aIdx[3] = aIdx[4] = aIdx[5] = aIdx[6] = -1;
774 pConstraint = pIdxInfo->aConstraint;
775 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
776 int iCol; /* 0 for start, 1 for stop, 2 for step */
777 int iMask; /* bitmask for those column */
778 int op = pConstraint->op;
779 if( op>=SQLITE_INDEX_CONSTRAINT_LIMIT
780 && op<=SQLITE_INDEX_CONSTRAINT_OFFSET
781 ){
782 if( pConstraint->usable==0 ){
783 /* do nothing */
784 }else if( op==SQLITE_INDEX_CONSTRAINT_LIMIT ){
785 aIdx[3] = i;
786 idxNum |= 0x20;
787 }else{
788 assert( op==SQLITE_INDEX_CONSTRAINT_OFFSET );
789 aIdx[4] = i;
790 idxNum |= 0x40;
791 }
792 continue;
793 }
794 if( pConstraint->iColumn<SERIES_COLUMN_START ){
795 if( (pConstraint->iColumn==SERIES_COLUMN_VALUE ||
796 pConstraint->iColumn==SERIES_COLUMN_ROWID)
797 && pConstraint->usable
798 ){
799 switch( op ){
800 case SQLITE_INDEX_CONSTRAINT_EQ:
801 case SQLITE_INDEX_CONSTRAINT_IS: {
802 idxNum |= 0x0080;
803 idxNum &= ~0x3300;
804 aIdx[5] = i;
805 aIdx[6] = -1;
806#ifndef ZERO_ARGUMENT_GENERATE_SERIES
807 bStartSeen = 1;
808#endif
809 break;
810 }
811 case SQLITE_INDEX_CONSTRAINT_GE: {
812 if( idxNum & 0x0080 ) break;
813 idxNum |= 0x0100;
814 idxNum &= ~0x0200;
815 aIdx[5] = i;
816#ifndef ZERO_ARGUMENT_GENERATE_SERIES
817 bStartSeen = 1;
818#endif
819 break;
820 }
821 case SQLITE_INDEX_CONSTRAINT_GT: {
822 if( idxNum & 0x0080 ) break;
823 idxNum |= 0x0200;
824 idxNum &= ~0x0100;
825 aIdx[5] = i;
826#ifndef ZERO_ARGUMENT_GENERATE_SERIES
827 bStartSeen = 1;
828#endif
829 break;
830 }
831 case SQLITE_INDEX_CONSTRAINT_LE: {
832 if( idxNum & 0x0080 ) break;
833 idxNum |= 0x1000;
834 idxNum &= ~0x2000;
835 aIdx[6] = i;
836 break;
837 }
838 case SQLITE_INDEX_CONSTRAINT_LT: {
839 if( idxNum & 0x0080 ) break;
840 idxNum |= 0x2000;
841 idxNum &= ~0x1000;
842 aIdx[6] = i;
843 break;
844 }
845 }
846 }
847 continue;
848 }
849 iCol = pConstraint->iColumn - SERIES_COLUMN_START;
850 assert( iCol>=0 && iCol<=2 );
851 iMask = 1 << iCol;
852#ifndef ZERO_ARGUMENT_GENERATE_SERIES
853 if( iCol==0 && op==SQLITE_INDEX_CONSTRAINT_EQ ){
854 bStartSeen = 1;
855 }
856#endif
857 if( pConstraint->usable==0 ){
858 unusableMask |= iMask;
859 continue;
860 }else if( op==SQLITE_INDEX_CONSTRAINT_EQ ){
861 idxNum |= iMask;
862 aIdx[iCol] = i;
863 }
864 }
865 if( pIdxInfo->nOrderBy>=1 ){
866 int iOB = pIdxInfo->aOrderBy[0].iColumn;
867 if( iOB==SERIES_COLUMN_VALUE || iOB==SERIES_COLUMN_ROWID ){
868 /* The rowid is an alias for value, and both are unique, so the
869 ** series can be generated in the requested order regardless of any
870 ** subsequent ORDER BY terms. */
871 if( pIdxInfo->aOrderBy[0].desc ){
872 idxNum |= 0x08;
873 }else{
874 idxNum |= 0x10;
875 }
876 pIdxInfo->orderByConsumed = 1;
877 }else{
878 /* The core will sort the output, so it needs to see every row.
879 ** A LIMIT or OFFSET applied here would discard rows before the sort */
880 idxNum &= ~0x60;
881 aIdx[3] = aIdx[4] = -1;
882 }
883 }
884 if( aIdx[3]==0 ){
885 /* Ignore OFFSET if LIMIT is omitted */
886 idxNum &= ~0x60;
887 aIdx[4] = 0;
888 }
889 for(i=0; i<7; i++){
890 if( (j = aIdx[i])>=0 ){
891 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
892 pIdxInfo->aConstraintUsage[j].omit =
893 !SQLITE_SERIES_CONSTRAINT_VERIFY || i>=3;
894 }
895 }
896 /* The current generate_column() implementation requires at least one
897 ** argument (the START value). Legacy versions assumed START=0 if the
898 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
899 ** to obtain the legacy behavior */
900#ifndef ZERO_ARGUMENT_GENERATE_SERIES
901 if( !bStartSeen ){
902 sqlite3_free(pVTab->zErrMsg);
903 pVTab->zErrMsg = sqlite3_mprintf(
904 "first argument to \"generate_series()\" missing or unusable");
905 return SQLITE_ERROR;
906 }
907#endif
908 if( (unusableMask & ~idxNum)!=0 ){
909 /* The start, stop, and step columns are inputs. Therefore if there
910 ** are unusable constraints on any of start, stop, or step then
911 ** this plan is unusable */
912 return SQLITE_CONSTRAINT;
913 }
914 if( (idxNum & 0x03)==0x03 ){
915 /* Both start= and stop= boundaries are available. This is the
916 ** the preferred case */
917 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
918 pIdxInfo->estimatedRows = 1000;
919 }else if( (idxNum & 0x21)==0x21 ){
920 /* We have start= and LIMIT */
921 pIdxInfo->estimatedRows = 2500;
922 }else{
923 /* If either boundary is missing, we have to generate a huge span
924 ** of numbers. Make this case very expensive so that the query
925 ** planner will work hard to avoid it. */
926 pIdxInfo->estimatedRows = 2147483647;
927 }
928 pIdxInfo->idxNum = idxNum;
929#ifdef SQLITE_INDEX_SCAN_HEX
930 pIdxInfo->idxFlags = SQLITE_INDEX_SCAN_HEX;
931#endif
932 return SQLITE_OK;
933}
934
935/*
936** This following structure defines all the methods for the
937** generate_series virtual table.
938*/
939static sqlite3_module seriesModule = {
940 0, /* iVersion */
941 0, /* xCreate */
942 seriesConnect, /* xConnect */
943 seriesBestIndex, /* xBestIndex */
944 seriesDisconnect, /* xDisconnect */
945 0, /* xDestroy */
946 seriesOpen, /* xOpen - open a cursor */
947 seriesClose, /* xClose - close a cursor */
948 seriesFilter, /* xFilter - configure scan constraints */
949 seriesNext, /* xNext - advance a cursor */
950 seriesEof, /* xEof - check for end of scan */
951 seriesColumn, /* xColumn - read data */
952 seriesRowid, /* xRowid - read data */
953 0, /* xUpdate */
954 0, /* xBegin */
955 0, /* xSync */
956 0, /* xCommit */
957 0, /* xRollback */
958 0, /* xFindMethod */
959 0, /* xRename */
960 0, /* xSavepoint */
961 0, /* xRelease */
962 0, /* xRollbackTo */
963 0, /* xShadowName */
964 0 /* xIntegrity */
965};
966
967#endif /* SQLITE_OMIT_VIRTUALTABLE */
968
969#ifdef _WIN32
970__declspec(dllexport)
971#endif
972int sqlite3_series_init(
973 sqlite3 *db,
974 char **pzErrMsg,
975 const sqlite3_api_routines *pApi
976){
977 int rc = SQLITE_OK;
978 SQLITE_EXTENSION_INIT2(pApi);
979#ifndef SQLITE_OMIT_VIRTUALTABLE
980 if( sqlite3_libversion_number()<3008012 && pzErrMsg!=0 ){
981 *pzErrMsg = sqlite3_mprintf(
982 "generate_series() requires SQLite 3.8.12 or later");
983 return SQLITE_ERROR;
984 }
985 rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
986#endif
987 return rc;
988}