1 /*
2 ** 2015-08-18
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 similar results to the eponymous function in PostgreSQL.
16 ** Examples:
17 **
18 ** SELECT * FROM generate_series(0,100,5);
19 **
20 ** The query above returns integers from 0 through 100 counting by steps
21 ** of 5.
22 **
23 ** SELECT * FROM generate_series(0,100);
24 **
25 ** Integers from 0 through 100 with a step size of 1.
26 **
27 ** SELECT * FROM generate_series(20) LIMIT 10;
28 **
29 ** Integers 20 through 29.
30 **
31 ** HOW IT WORKS
32 **
33 ** The generate_series "function" is really a virtual table with the
34 ** following schema:
35 **
36 ** CREATE TABLE generate_series(
37 ** value,
38 ** start HIDDEN,
39 ** stop HIDDEN,
40 ** step HIDDEN
41 ** );
42 **
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:
46 **
47 ** SELECT * FROM generate_series(0,100,5);
48 ** SELECT * FROM generate_series WHERE start=0 AND stop=100 AND step=5;
49 **
50 ** SELECT * FROM generate_series(0,100);
51 ** SELECT * FROM generate_series WHERE start=0 AND stop=100;
52 **
53 ** SELECT * FROM generate_series(20) LIMIT 10;
54 ** SELECT * FROM generate_series WHERE start=20 LIMIT 10;
55 **
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.
61 **
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.
70 */
71 #include "sqlite3ext.h"
72 SQLITE_EXTENSION_INIT1
73 #include <assert.h>
74 #include <string.h>
75
76 #ifndef SQLITE_OMIT_VIRTUALTABLE
77
78
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
82 */
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") */
92 };
93
94 /*
95 ** The seriesConnect() method is invoked to create a new
96 ** series_vtab that describes the generate_series virtual table.
97 **
98 ** Think of this routine as the constructor for series_vtab objects.
99 **
100 ** All this routine needs to do is:
101 **
102 ** (1) Allocate the series_vtab object and initialize all fields.
103 **
104 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
105 ** result set of queries against generate_series will look like.
106 */
seriesConnect(sqlite3 * db,void * pUnused,int argcUnused,const char * const * argvUnused,sqlite3_vtab ** ppVtab,char ** pzErrUnused)107 static int seriesConnect(
108 sqlite3 *db,
109 void *pUnused,
110 int argcUnused, const char *const*argvUnused,
111 sqlite3_vtab **ppVtab,
112 char **pzErrUnused
113 ){
114 sqlite3_vtab *pNew;
115 int rc;
116
117 /* Column numbers */
118 #define SERIES_COLUMN_VALUE 0
119 #define SERIES_COLUMN_START 1
120 #define SERIES_COLUMN_STOP 2
121 #define SERIES_COLUMN_STEP 3
122
123 (void)pUnused;
124 (void)argcUnused;
125 (void)argvUnused;
126 (void)pzErrUnused;
127 rc = sqlite3_declare_vtab(db,
128 "CREATE TABLE x(value,start hidden,stop hidden,step hidden)");
129 if( rc==SQLITE_OK ){
130 pNew = *ppVtab = sqlite3_malloc( sizeof(*pNew) );
131 if( pNew==0 ) return SQLITE_NOMEM;
132 memset(pNew, 0, sizeof(*pNew));
133 #ifdef SQLITE_VTAB_INNOCUOUS
134 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
135 #endif
136 }
137 return rc;
138 }
139
140 /*
141 ** This method is the destructor for series_cursor objects.
142 */
seriesDisconnect(sqlite3_vtab * pVtab)143 static int seriesDisconnect(sqlite3_vtab *pVtab){
144 sqlite3_free(pVtab);
145 return SQLITE_OK;
146 }
147
148 /*
149 ** Constructor for a new series_cursor object.
150 */
seriesOpen(sqlite3_vtab * pUnused,sqlite3_vtab_cursor ** ppCursor)151 static int seriesOpen(sqlite3_vtab *pUnused, sqlite3_vtab_cursor **ppCursor){
152 series_cursor *pCur;
153 (void)pUnused;
154 pCur = sqlite3_malloc( sizeof(*pCur) );
155 if( pCur==0 ) return SQLITE_NOMEM;
156 memset(pCur, 0, sizeof(*pCur));
157 *ppCursor = &pCur->base;
158 return SQLITE_OK;
159 }
160
161 /*
162 ** Destructor for a series_cursor.
163 */
seriesClose(sqlite3_vtab_cursor * cur)164 static int seriesClose(sqlite3_vtab_cursor *cur){
165 sqlite3_free(cur);
166 return SQLITE_OK;
167 }
168
169
170 /*
171 ** Advance a series_cursor to its next row of output.
172 */
seriesNext(sqlite3_vtab_cursor * cur)173 static int seriesNext(sqlite3_vtab_cursor *cur){
174 series_cursor *pCur = (series_cursor*)cur;
175 if( pCur->isDesc ){
176 pCur->iValue -= pCur->iStep;
177 }else{
178 pCur->iValue += pCur->iStep;
179 }
180 pCur->iRowid++;
181 return SQLITE_OK;
182 }
183
184 /*
185 ** Return values of columns for the row at which the series_cursor
186 ** is currently pointing.
187 */
seriesColumn(sqlite3_vtab_cursor * cur,sqlite3_context * ctx,int i)188 static int seriesColumn(
189 sqlite3_vtab_cursor *cur, /* The cursor */
190 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
191 int i /* Which column to return */
192 ){
193 series_cursor *pCur = (series_cursor*)cur;
194 sqlite3_int64 x = 0;
195 switch( i ){
196 case SERIES_COLUMN_START: x = pCur->mnValue; break;
197 case SERIES_COLUMN_STOP: x = pCur->mxValue; break;
198 case SERIES_COLUMN_STEP: x = pCur->iStep; break;
199 default: x = pCur->iValue; break;
200 }
201 sqlite3_result_int64(ctx, x);
202 return SQLITE_OK;
203 }
204
205 /*
206 ** Return the rowid for the current row. In this implementation, the
207 ** first row returned is assigned rowid value 1, and each subsequent
208 ** row a value 1 more than that of the previous.
209 */
seriesRowid(sqlite3_vtab_cursor * cur,sqlite_int64 * pRowid)210 static int seriesRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
211 series_cursor *pCur = (series_cursor*)cur;
212 *pRowid = pCur->iRowid;
213 return SQLITE_OK;
214 }
215
216 /*
217 ** Return TRUE if the cursor has been moved off of the last
218 ** row of output.
219 */
seriesEof(sqlite3_vtab_cursor * cur)220 static int seriesEof(sqlite3_vtab_cursor *cur){
221 series_cursor *pCur = (series_cursor*)cur;
222 if( pCur->isDesc ){
223 return pCur->iValue < pCur->mnValue;
224 }else{
225 return pCur->iValue > pCur->mxValue;
226 }
227 }
228
229 /* True to cause run-time checking of the start=, stop=, and/or step=
230 ** parameters. The only reason to do this is for testing the
231 ** constraint checking logic for virtual tables in the SQLite core.
232 */
233 #ifndef SQLITE_SERIES_CONSTRAINT_VERIFY
234 # define SQLITE_SERIES_CONSTRAINT_VERIFY 0
235 #endif
236
237 /*
238 ** This method is called to "rewind" the series_cursor object back
239 ** to the first row of output. This method is always called at least
240 ** once prior to any call to seriesColumn() or seriesRowid() or
241 ** seriesEof().
242 **
243 ** The query plan selected by seriesBestIndex is passed in the idxNum
244 ** parameter. (idxStr is not used in this implementation.) idxNum
245 ** is a bitmask showing which constraints are available:
246 **
247 ** 1: start=VALUE
248 ** 2: stop=VALUE
249 ** 4: step=VALUE
250 **
251 ** Also, if bit 8 is set, that means that the series should be output
252 ** in descending order rather than in ascending order. If bit 16 is
253 ** set, then output must appear in ascending order.
254 **
255 ** This routine should initialize the cursor and position it so that it
256 ** is pointing at the first row, or pointing off the end of the table
257 ** (so that seriesEof() will return true) if the table is empty.
258 */
seriesFilter(sqlite3_vtab_cursor * pVtabCursor,int idxNum,const char * idxStrUnused,int argc,sqlite3_value ** argv)259 static int seriesFilter(
260 sqlite3_vtab_cursor *pVtabCursor,
261 int idxNum, const char *idxStrUnused,
262 int argc, sqlite3_value **argv
263 ){
264 series_cursor *pCur = (series_cursor *)pVtabCursor;
265 int i = 0;
266 (void)idxStrUnused;
267 if( idxNum & 1 ){
268 pCur->mnValue = sqlite3_value_int64(argv[i++]);
269 }else{
270 pCur->mnValue = 0;
271 }
272 if( idxNum & 2 ){
273 pCur->mxValue = sqlite3_value_int64(argv[i++]);
274 }else{
275 pCur->mxValue = 0xffffffff;
276 }
277 if( idxNum & 4 ){
278 pCur->iStep = sqlite3_value_int64(argv[i++]);
279 if( pCur->iStep==0 ){
280 pCur->iStep = 1;
281 }else if( pCur->iStep<0 ){
282 pCur->iStep = -pCur->iStep;
283 if( (idxNum & 16)==0 ) idxNum |= 8;
284 }
285 }else{
286 pCur->iStep = 1;
287 }
288 for(i=0; i<argc; i++){
289 if( sqlite3_value_type(argv[i])==SQLITE_NULL ){
290 /* If any of the constraints have a NULL value, then return no rows.
291 ** See ticket https://www.sqlite.org/src/info/fac496b61722daf2 */
292 pCur->mnValue = 1;
293 pCur->mxValue = 0;
294 break;
295 }
296 }
297 if( idxNum & 8 ){
298 pCur->isDesc = 1;
299 pCur->iValue = pCur->mxValue;
300 if( pCur->iStep>0 ){
301 pCur->iValue -= (pCur->mxValue - pCur->mnValue)%pCur->iStep;
302 }
303 }else{
304 pCur->isDesc = 0;
305 pCur->iValue = pCur->mnValue;
306 }
307 pCur->iRowid = 1;
308 return SQLITE_OK;
309 }
310
311 /*
312 ** SQLite will invoke this method one or more times while planning a query
313 ** that uses the generate_series virtual table. This routine needs to create
314 ** a query plan for each invocation and compute an estimated cost for that
315 ** plan.
316 **
317 ** In this implementation idxNum is used to represent the
318 ** query plan. idxStr is unused.
319 **
320 ** The query plan is represented by bits in idxNum:
321 **
322 ** (1) start = $value -- constraint exists
323 ** (2) stop = $value -- constraint exists
324 ** (4) step = $value -- constraint exists
325 ** (8) output in descending order
326 */
seriesBestIndex(sqlite3_vtab * vtab,sqlite3_index_info * pIdxInfo)327 static int seriesBestIndex(
328 sqlite3_vtab *vtab,
329 sqlite3_index_info *pIdxInfo
330 ){
331 int i, j; /* Loop over constraints */
332 int idxNum = 0; /* The query plan bitmask */
333 int unusableMask = 0; /* Mask of unusable constraints */
334 int nArg = 0; /* Number of arguments that seriesFilter() expects */
335 int aIdx[3]; /* Constraints on start, stop, and step */
336 const struct sqlite3_index_constraint *pConstraint;
337
338 /* This implementation assumes that the start, stop, and step columns
339 ** are the last three columns in the virtual table. */
340 assert( SERIES_COLUMN_STOP == SERIES_COLUMN_START+1 );
341 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 );
350 iMask = 1 << iCol;
351 if( pConstraint->usable==0 ){
352 unusableMask |= iMask;
353 continue;
354 }else if( pConstraint->op==SQLITE_INDEX_CONSTRAINT_EQ ){
355 idxNum |= iMask;
356 aIdx[iCol] = i;
357 }
358 }
359 for(i=0; i<3; i++){
360 if( (j = aIdx[i])>=0 ){
361 pIdxInfo->aConstraintUsage[j].argvIndex = ++nArg;
362 pIdxInfo->aConstraintUsage[j].omit = !SQLITE_SERIES_CONSTRAINT_VERIFY;
363 }
364 }
365 if( (unusableMask & ~idxNum)!=0 ){
366 /* The start, stop, and step columns are inputs. Therefore if there
367 ** are unusable constraints on any of start, stop, or step then
368 ** this plan is unusable */
369 return SQLITE_CONSTRAINT;
370 }
371 if( (idxNum & 3)==3 ){
372 /* Both start= and stop= boundaries are available. This is the
373 ** the preferred case */
374 pIdxInfo->estimatedCost = (double)(2 - ((idxNum&4)!=0));
375 pIdxInfo->estimatedRows = 1000;
376 if( pIdxInfo->nOrderBy==1 ){
377 if( pIdxInfo->aOrderBy[0].desc ){
378 idxNum |= 8;
379 }else{
380 idxNum |= 16;
381 }
382 pIdxInfo->orderByConsumed = 1;
383 }
384 }else{
385 if (!(idxNum & 1)) {
386 vtab->zErrMsg = sqlite3_mprintf("the start parameter is required");
387 } else {
388 vtab->zErrMsg = sqlite3_mprintf("the stop parameter is required");
389 }
390 return SQLITE_ERROR;
391 }
392 pIdxInfo->idxNum = idxNum;
393 return SQLITE_OK;
394 }
395
396 /*
397 ** This following structure defines all the methods for the
398 ** generate_series virtual table.
399 */
400 static sqlite3_module seriesModule = {
401 0, /* iVersion */
402 0, /* xCreate */
403 seriesConnect, /* xConnect */
404 seriesBestIndex, /* xBestIndex */
405 seriesDisconnect, /* xDisconnect */
406 0, /* xDestroy */
407 seriesOpen, /* xOpen - open a cursor */
408 seriesClose, /* xClose - close a cursor */
409 seriesFilter, /* xFilter - configure scan constraints */
410 seriesNext, /* xNext - advance a cursor */
411 seriesEof, /* xEof - check for end of scan */
412 seriesColumn, /* xColumn - read data */
413 seriesRowid, /* xRowid - read data */
414 0, /* xUpdate */
415 0, /* xBegin */
416 0, /* xSync */
417 0, /* xCommit */
418 0, /* xRollback */
419 0, /* xFindMethod */
420 0, /* xRename */
421 0, /* xSavepoint */
422 0, /* xRelease */
423 0, /* xRollbackTo */
424 0 /* xShadowName */
425 };
426
427 #endif /* SQLITE_OMIT_VIRTUALTABLE */
428
429 #ifdef _WIN32
430 __declspec(dllexport)
431 #endif
sqlite3_series_init(sqlite3 * db,char ** pzErrMsg,const sqlite3_api_routines * pApi)432 int sqlite3_series_init(
433 sqlite3 *db,
434 char **pzErrMsg,
435 const sqlite3_api_routines *pApi
436 ){
437 int rc = SQLITE_OK;
438 SQLITE_EXTENSION_INIT2(pApi);
439 #ifndef SQLITE_OMIT_VIRTUALTABLE
440 if( sqlite3_libversion_number()<3008012 ){
441 *pzErrMsg = sqlite3_mprintf(
442 "generate_series() requires SQLite 3.8.12 or later");
443 return SQLITE_ERROR;
444 }
445 rc = sqlite3_create_module(db, "generate_series", &seriesModule, 0);
446 #endif
447 return rc;
448 }
449