4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
11 *************************************************************************
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 similar results to the eponymous function in PostgreSQL.
18 ** SELECT * FROM generate_series(0,100,5);
20 ** The query above returns integers from 0 through 100 counting by steps
23 ** SELECT * FROM generate_series(0,100);
25 ** Integers from 0 through 100 with a step size of 1.
27 ** SELECT * FROM generate_series(20) LIMIT 10;
29 ** Integers 20 through 29.
33 ** The generate_series "function" is really a virtual table with the
36 ** CREATE TABLE generate_series(
43 ** Function arguments in queries against this virtual table are translated
44 ** into equality constraints against successive hidden columns. In other
45 ** words, the following pairs of queries are equivalent to each other:
47 ** SELECT * FROM generate_series(0,100,5);
48 ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
50 ** SELECT * FROM generate_series(0,100);
51 ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
53 ** SELECT * FROM generate_series(20) LIMIT 10;
54 ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
56 ** The generate_series virtual table implementation leaves the xCreate method
57 ** set to NULL. This means that it is not possible to do a CREATE VIRTUAL
58 ** TABLE command with "generate_series" as the USING argument. Instead, there
59 ** is a single generate_series virtual table that is always available without
60 ** having to be created first.
62 ** The xBestIndex method looks for equality constraints against the hidden
63 ** start, stop, and step columns, and if present, it uses those constraints
64 ** to bound the sequence of generated values. If the equality constraints
65 ** are missing, it uses 0 for start, 4294967295 for stop, and 1 for step.
66 ** xBestIndex returns a small cost when both start and stop are available,
67 ** and a very large cost if either start or stop are unavailable. This
68 ** encourages the query planner to order joins such that the bounds of the
69 ** series are well-defined.
71 #include "sqlite3ext.h"
72 SQLITE_EXTENSION_INIT1
76 #ifndef SQLITE_OMIT_VIRTUALTABLE
79 /* series_cursor is a subclass of sqlite3_vtab_cursor which will
80 ** serve as the underlying representation of a cursor that scans
81 ** over rows of the result
83 typedef struct series_cursor series_cursor
;
84 struct series_cursor
{
85 sqlite3_vtab_cursor base
; /* Base class - must be first */
86 int isDesc
; /* True to count down rather than up */
87 sqlite3_int64 iRowid
; /* The rowid */
88 sqlite3_int64 iValue
; /* Current value ("value") */
89 sqlite3_int64 mnValue
; /* Mimimum value ("start") */
90 sqlite3_int64 mxValue
; /* Maximum value ("stop") */
91 sqlite3_int64 iStep
; /* Increment ("step") */
95 ** The seriesConnect() method is invoked to create a new
96 ** series_vtab that describes the generate_series virtual table.
98 ** Think of this routine as the constructor for series_vtab objects.
100 ** All this routine needs to do is:
102 ** (1) Allocate the series_vtab object and initialize all fields.
104 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
105 ** result set of queries against generate_series will look like.
107 static int seriesConnect(
110 int argcUnused
, const char *const*argvUnused
,
111 sqlite3_vtab
**ppVtab
,
118 #define SERIES_COLUMN_VALUE 0
119 #define SERIES_COLUMN_START 1
120 #define SERIES_COLUMN_STOP 2
121 #define SERIES_COLUMN_STEP 3
127 rc
= sqlite3_declare_vtab(db
,
128 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
130 pNew
= *ppVtab
= sqlite3_malloc( sizeof(*pNew
) );
131 if( pNew
==0 ) return SQLITE_NOMEM
;
132 memset(pNew
, 0, sizeof(*pNew
));
133 sqlite3_vtab_config(db
, SQLITE_VTAB_INNOCUOUS
);
139 ** This method is the destructor for series_cursor objects.
141 static int seriesDisconnect(sqlite3_vtab
*pVtab
){
147 ** Constructor for a new series_cursor object.
149 static int seriesOpen(sqlite3_vtab
*pUnused
, sqlite3_vtab_cursor
**ppCursor
){
152 pCur
= sqlite3_malloc( sizeof(*pCur
) );
153 if( pCur
==0 ) return SQLITE_NOMEM
;
154 memset(pCur
, 0, sizeof(*pCur
));
155 *ppCursor
= &pCur
->base
;
160 ** Destructor for a series_cursor.
162 static int seriesClose(sqlite3_vtab_cursor
*cur
){
169 ** Advance a series_cursor to its next row of output.
171 static int seriesNext(sqlite3_vtab_cursor
*cur
){
172 series_cursor
*pCur
= (series_cursor
*)cur
;
174 pCur
->iValue
-= pCur
->iStep
;
176 pCur
->iValue
+= pCur
->iStep
;
183 ** Return values of columns for the row at which the series_cursor
184 ** is currently pointing.
186 static int seriesColumn(
187 sqlite3_vtab_cursor
*cur
, /* The cursor */
188 sqlite3_context
*ctx
, /* First argument to sqlite3_result_...() */
189 int i
/* Which column to return */
191 series_cursor
*pCur
= (series_cursor
*)cur
;
194 case SERIES_COLUMN_START
: x
= pCur
->mnValue
; break;
195 case SERIES_COLUMN_STOP
: x
= pCur
->mxValue
; break;
196 case SERIES_COLUMN_STEP
: x
= pCur
->iStep
; break;
197 default: x
= pCur
->iValue
; break;
199 sqlite3_result_int64(ctx
, x
);
204 ** Return the rowid for the current row. In this implementation, the
205 ** first row returned is assigned rowid value 1, and each subsequent
206 ** row a value 1 more than that of the previous.
208 static int seriesRowid(sqlite3_vtab_cursor
*cur
, sqlite_int64
*pRowid
){
209 series_cursor
*pCur
= (series_cursor
*)cur
;
210 *pRowid
= pCur
->iRowid
;
215 ** Return TRUE if the cursor has been moved off of the last
218 static int seriesEof(sqlite3_vtab_cursor
*cur
){
219 series_cursor
*pCur
= (series_cursor
*)cur
;
221 return pCur
->iValue
< pCur
->mnValue
;
223 return pCur
->iValue
> pCur
->mxValue
;
227 /* True to cause run-time checking of the start=, stop=, and/or step=
228 ** parameters. The only reason to do this is for testing the
229 ** constraint checking logic for virtual tables in the SQLite core.
231 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
232 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
236 ** This method is called to "rewind" the series_cursor object back
237 ** to the first row of output. This method is always called at least
238 ** once prior to any call to seriesColumn() or seriesRowid() or
241 ** The query plan selected by seriesBestIndex is passed in the idxNum
242 ** parameter. (idxStr is not used in this implementation.) idxNum
243 ** is a bitmask showing which constraints are available:
249 ** Also, if bit 8 is set, that means that the series should be output
250 ** in descending order rather than in ascending order. If bit 16 is
251 ** set, then output must appear in ascending order.
253 ** This routine should initialize the cursor and position it so that it
254 ** is pointing at the first row, or pointing off the end of the table
255 ** (so that seriesEof() will return true) if the table is empty.
257 static int seriesFilter(
258 sqlite3_vtab_cursor
*pVtabCursor
,
259 int idxNum
, const char *idxStrUnused
,
260 int argc
, sqlite3_value
**argv
262 series_cursor
*pCur
= (series_cursor
*)pVtabCursor
;
266 pCur
->mnValue
= sqlite3_value_int64(argv
[i
++]);
271 pCur
->mxValue
= sqlite3_value_int64(argv
[i
++]);
273 pCur
->mxValue
= 0xffffffff;
276 pCur
->iStep
= sqlite3_value_int64(argv
[i
++]);
277 if( pCur
->iStep
==0 ){
279 }else if( pCur
->iStep
<0 ){
280 pCur
->iStep
= -pCur
->iStep
;
281 if( (idxNum
& 16)==0 ) idxNum
|= 8;
286 for(i
=0; i
<argc
; i
++){
287 if( sqlite3_value_type(argv
[i
])==SQLITE_NULL
){
288 /* If any of the constraints have a NULL value, then return no rows.
289 ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
297 pCur
->iValue
= pCur
->mxValue
;
299 pCur
->iValue
-= (pCur
->mxValue
- pCur
->mnValue
)%pCur
->iStep
;
303 pCur
->iValue
= pCur
->mnValue
;
310 ** SQLite will invoke this method one or more times while planning a query
311 ** that uses the generate_series virtual table. This routine needs to create
312 ** a query plan for each invocation and compute an estimated cost for that
315 ** In this implementation idxNum is used to represent the
316 ** query plan. idxStr is unused.
318 ** The query plan is represented by bits in idxNum:
320 ** (1) start = $value -- constraint exists
321 ** (2) stop = $value -- constraint exists
322 ** (4) step = $value -- constraint exists
323 ** (8) output in descending order
325 static int seriesBestIndex(
327 sqlite3_index_info
*pIdxInfo
329 int i
, j
; /* Loop over constraints */
330 int idxNum
= 0; /* The query plan bitmask */
331 int bStartSeen
= 0; /* EQ constraint seen on the START column */
332 int unusableMask
= 0; /* Mask of unusable constraints */
333 int nArg
= 0; /* Number of arguments that seriesFilter() expects */
334 int aIdx
[3]; /* Constraints on start, stop, and step */
335 const struct sqlite3_index_constraint
*pConstraint
;
337 /* This implementation assumes that the start, stop, and step columns
338 ** are the last three columns in the virtual table. */
339 assert( SERIES_COLUMN_STOP
== SERIES_COLUMN_START
+1 );
340 assert( SERIES_COLUMN_STEP
== SERIES_COLUMN_START
+2 );
342 aIdx
[0] = aIdx
[1] = aIdx
[2] = -1;
343 pConstraint
= pIdxInfo
->aConstraint
;
344 for(i
=0; i
<pIdxInfo
->nConstraint
; i
++, pConstraint
++){
345 int iCol
; /* 0 for start, 1 for stop, 2 for step */
346 int iMask
; /* bitmask for those column */
347 if( pConstraint
->iColumn
<SERIES_COLUMN_START
) continue;
348 iCol
= pConstraint
->iColumn
- SERIES_COLUMN_START
;
349 assert( iCol
>=0 && iCol
<=2 );
351 if( iCol
==0 ) bStartSeen
= 1;
352 if( pConstraint
->usable
==0 ){
353 unusableMask
|= iMask
;
355 }else if( pConstraint
->op
==SQLITE_INDEX_CONSTRAINT_EQ
){
361 if( (j
= aIdx
[i
])>=0 ){
362 pIdxInfo
->aConstraintUsage
[j
].argvIndex
= ++nArg
;
363 pIdxInfo
->aConstraintUsage
[j
].omit
= !SQLITE_SERIES_CONSTRAINT_VERIFY
;
366 /* The current generate_column() implementation requires at least one
367 ** argument (the START value). Legacy versions assumed START=0 if the
368 ** first argument was omitted. Compile with -DZERO_ARGUMENT_GENERATE_SERIES
369 ** to obtain the legacy behavior */
370 #ifndef ZERO_ARGUMENT_GENERATE_SERIES
372 sqlite3_free(pVTab
->zErrMsg
);
373 pVTab
->zErrMsg
= sqlite3_mprintf(
374 "first argument to \"generate_series()\" missing or unusable");
378 if( (unusableMask
& ~idxNum
)!=0 ){
379 /* The start, stop, and step columns are inputs. Therefore if there
380 ** are unusable constraints on any of start, stop, or step then
381 ** this plan is unusable */
382 return SQLITE_CONSTRAINT
;
384 if( (idxNum
& 3)==3 ){
385 /* Both start= and stop= boundaries are available. This is the
386 ** the preferred case */
387 pIdxInfo
->estimatedCost
= (double)(2 - ((idxNum
&4)!=0));
388 pIdxInfo
->estimatedRows
= 1000;
389 if( pIdxInfo
->nOrderBy
==1 ){
390 if( pIdxInfo
->aOrderBy
[0].desc
){
395 pIdxInfo
->orderByConsumed
= 1;
398 /* If either boundary is missing, we have to generate a huge span
399 ** of numbers. Make this case very expensive so that the query
400 ** planner will work hard to avoid it. */
401 pIdxInfo
->estimatedRows
= 2147483647;
403 pIdxInfo
->idxNum
= idxNum
;
408 ** This following structure defines all the methods for the
409 ** generate_series virtual table.
411 static sqlite3_module seriesModule
= {
414 seriesConnect
, /* xConnect */
415 seriesBestIndex
, /* xBestIndex */
416 seriesDisconnect
, /* xDisconnect */
418 seriesOpen
, /* xOpen - open a cursor */
419 seriesClose
, /* xClose - close a cursor */
420 seriesFilter
, /* xFilter - configure scan constraints */
421 seriesNext
, /* xNext - advance a cursor */
422 seriesEof
, /* xEof - check for end of scan */
423 seriesColumn
, /* xColumn - read data */
424 seriesRowid
, /* xRowid - read data */
438 #endif /* SQLITE_OMIT_VIRTUALTABLE */
441 __declspec(dllexport
)
443 int sqlite3_series_init(
446 const sqlite3_api_routines
*pApi
449 SQLITE_EXTENSION_INIT2(pApi
);
450 #ifndef SQLITE_OMIT_VIRTUALTABLE
451 if( sqlite3_libversion_number()<3008012 && pzErrMsg
!=0 ){
452 *pzErrMsg
= sqlite3_mprintf(
453 "generate_series() requires SQLite 3.8.12 or later");
456 rc
= sqlite3_create_module(db
, "generate_series", &seriesModule
, 0);