xref: /sqlite-3.40.0/ext/misc/completion.c (revision 56eb09bc)
1 /*
2 ** 2017-07-10
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 implements an eponymous virtual table that returns suggested
14 ** completions for a partial SQL input.
15 **
16 ** Suggested usage:
17 **
18 **     SELECT DISTINCT candidate COLLATE nocase
19 **       FROM completion($prefix,$wholeline)
20 **      ORDER BY 1;
21 **
22 ** The two query parameters are optional.  $prefix is the text of the
23 ** current word being typed and that is to be completed.  $wholeline is
24 ** the complete input line, used for context.
25 **
26 ** The raw completion() table might return the same candidate multiple
27 ** times, for example if the same column name is used to two or more
28 ** tables.  And the candidates are returned in an arbitrary order.  Hence,
29 ** the DISTINCT and ORDER BY are recommended.
30 **
31 ** This virtual table operates at the speed of human typing, and so there
32 ** is no attempt to make it fast.  Even a slow implementation will be much
33 ** faster than any human can type.
34 **
35 */
36 #include "sqlite3ext.h"
37 SQLITE_EXTENSION_INIT1
38 #include <assert.h>
39 #include <string.h>
40 #include <ctype.h>
41 
42 #ifndef SQLITE_OMIT_VIRTUALTABLE
43 
44 /* completion_vtab is a subclass of sqlite3_vtab which will
45 ** serve as the underlying representation of a completion virtual table
46 */
47 typedef struct completion_vtab completion_vtab;
48 struct completion_vtab {
49   sqlite3_vtab base;  /* Base class - must be first */
50   sqlite3 *db;        /* Database connection for this completion vtab */
51 };
52 
53 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
54 ** serve as the underlying representation of a cursor that scans
55 ** over rows of the result
56 */
57 typedef struct completion_cursor completion_cursor;
58 struct completion_cursor {
59   sqlite3_vtab_cursor base;  /* Base class - must be first */
60   sqlite3 *db;               /* Database connection for this cursor */
61   int nPrefix, nLine;        /* Number of bytes in zPrefix and zLine */
62   char *zPrefix;             /* The prefix for the word we want to complete */
63   char *zLine;               /* The whole that we want to complete */
64   const char *zCurrentRow;   /* Current output row */
65   sqlite3_stmt *pStmt;       /* Current statement */
66   sqlite3_int64 iRowid;      /* The rowid */
67   int ePhase;                /* Current phase */
68   int j;                     /* inter-phase counter */
69 };
70 
71 /* Values for ePhase:
72 */
73 #define COMPLETION_FIRST_PHASE   1
74 #define COMPLETION_KEYWORDS      1
75 #define COMPLETION_PRAGMAS       2
76 #define COMPLETION_FUNCTIONS     3
77 #define COMPLETION_COLLATIONS    4
78 #define COMPLETION_INDEXES       5
79 #define COMPLETION_TRIGGERS      6
80 #define COMPLETION_DATABASES     7
81 #define COMPLETION_TABLES        8
82 #define COMPLETION_COLUMNS       9
83 #define COMPLETION_MODULES       10
84 #define COMPLETION_EOF           11
85 
86 /*
87 ** The completionConnect() method is invoked to create a new
88 ** completion_vtab that describes the completion virtual table.
89 **
90 ** Think of this routine as the constructor for completion_vtab objects.
91 **
92 ** All this routine needs to do is:
93 **
94 **    (1) Allocate the completion_vtab object and initialize all fields.
95 **
96 **    (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
97 **        result set of queries against completion will look like.
98 */
99 static int completionConnect(
100   sqlite3 *db,
101   void *pAux,
102   int argc, const char *const*argv,
103   sqlite3_vtab **ppVtab,
104   char **pzErr
105 ){
106   completion_vtab *pNew;
107   int rc;
108 
109 /* Column numbers */
110 #define COMPLETION_COLUMN_CANDIDATE 0  /* Suggested completion of the input */
111 #define COMPLETION_COLUMN_PREFIX    1  /* Prefix of the word to be completed */
112 #define COMPLETION_COLUMN_WHOLELINE 2  /* Entire line seen so far */
113 #define COMPLETION_COLUMN_PHASE     3  /* ePhase - used for debugging only */
114 
115   rc = sqlite3_declare_vtab(db,
116       "CREATE TABLE x("
117       "  candidate TEXT,"
118       "  prefix TEXT HIDDEN,"
119       "  wholeline TEXT HIDDEN,"
120       "  phase INT HIDDEN"        /* Used for debugging only */
121       ")");
122   if( rc==SQLITE_OK ){
123     pNew = sqlite3_malloc( sizeof(*pNew) );
124     *ppVtab = (sqlite3_vtab*)pNew;
125     if( pNew==0 ) return SQLITE_NOMEM;
126     memset(pNew, 0, sizeof(*pNew));
127     pNew->db = db;
128   }
129   return rc;
130 }
131 
132 /*
133 ** This method is the destructor for completion_cursor objects.
134 */
135 static int completionDisconnect(sqlite3_vtab *pVtab){
136   sqlite3_free(pVtab);
137   return SQLITE_OK;
138 }
139 
140 /*
141 ** Constructor for a new completion_cursor object.
142 */
143 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
144   completion_cursor *pCur;
145   pCur = sqlite3_malloc( sizeof(*pCur) );
146   if( pCur==0 ) return SQLITE_NOMEM;
147   memset(pCur, 0, sizeof(*pCur));
148   pCur->db = ((completion_vtab*)p)->db;
149   *ppCursor = &pCur->base;
150   return SQLITE_OK;
151 }
152 
153 /*
154 ** Reset the completion_cursor.
155 */
156 static void completionCursorReset(completion_cursor *pCur){
157   sqlite3_free(pCur->zPrefix);   pCur->zPrefix = 0;  pCur->nPrefix = 0;
158   sqlite3_free(pCur->zLine);     pCur->zLine = 0;    pCur->nLine = 0;
159   sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
160   pCur->j = 0;
161 }
162 
163 /*
164 ** Destructor for a completion_cursor.
165 */
166 static int completionClose(sqlite3_vtab_cursor *cur){
167   completionCursorReset((completion_cursor*)cur);
168   sqlite3_free(cur);
169   return SQLITE_OK;
170 }
171 
172 /*
173 ** All SQL keywords understood by SQLite
174 */
175 static const char *completionKwrds[] = {
176   "ABORT", "ACTION", "ADD", "AFTER", "ALL", "ALTER", "ANALYZE", "AND", "AS",
177   "ASC", "ATTACH", "AUTOINCREMENT", "BEFORE", "BEGIN", "BETWEEN", "BY",
178   "CASCADE", "CASE", "CAST", "CHECK", "COLLATE", "COLUMN", "COMMIT",
179   "CONFLICT", "CONSTRAINT", "CREATE", "CROSS", "CURRENT_DATE",
180   "CURRENT_TIME", "CURRENT_TIMESTAMP", "DATABASE", "DEFAULT", "DEFERRABLE",
181   "DEFERRED", "DELETE", "DESC", "DETACH", "DISTINCT", "DROP", "EACH",
182   "ELSE", "END", "ESCAPE", "EXCEPT", "EXCLUSIVE", "EXISTS", "EXPLAIN",
183   "FAIL", "FOR", "FOREIGN", "FROM", "FULL", "GLOB", "GROUP", "HAVING", "IF",
184   "IGNORE", "IMMEDIATE", "IN", "INDEX", "INDEXED", "INITIALLY", "INNER",
185   "INSERT", "INSTEAD", "INTERSECT", "INTO", "IS", "ISNULL", "JOIN", "KEY",
186   "LEFT", "LIKE", "LIMIT", "MATCH", "NATURAL", "NO", "NOT", "NOTNULL",
187   "NULL", "OF", "OFFSET", "ON", "OR", "ORDER", "OUTER", "PLAN", "PRAGMA",
188   "PRIMARY", "QUERY", "RAISE", "RECURSIVE", "REFERENCES", "REGEXP",
189   "REINDEX", "RELEASE", "RENAME", "REPLACE", "RESTRICT", "RIGHT",
190   "ROLLBACK", "ROW", "SAVEPOINT", "SELECT", "SET", "TABLE", "TEMP",
191   "TEMPORARY", "THEN", "TO", "TRANSACTION", "TRIGGER", "UNION", "UNIQUE",
192   "UPDATE", "USING", "VACUUM", "VALUES", "VIEW", "VIRTUAL", "WHEN", "WHERE",
193   "WITH", "WITHOUT",
194 };
195 
196 /*
197 ** Advance a completion_cursor to its next row of output.
198 **
199 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
200 ** record the current state of the scan.  This routine sets ->zCurrentRow
201 ** to the current row of output and then returns.  If no more rows remain,
202 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
203 ** table that has reached the end of its scan.
204 **
205 ** The current implementation just lists potential identifiers and
206 ** keywords and filters them by zPrefix.  Future enhancements should
207 ** take zLine into account to try to restrict the set of identifiers and
208 ** keywords based on what would be legal at the current point of input.
209 */
210 static int completionNext(sqlite3_vtab_cursor *cur){
211   completion_cursor *pCur = (completion_cursor*)cur;
212   int eNextPhase = 0;  /* Next phase to try if current phase reaches end */
213   int iCol = -1;       /* If >=0, step pCur->pStmt and use the i-th column */
214   pCur->iRowid++;
215   while( pCur->ePhase!=COMPLETION_EOF ){
216     switch( pCur->ePhase ){
217       case COMPLETION_KEYWORDS: {
218         if( pCur->j >=  sizeof(completionKwrds)/sizeof(completionKwrds[0]) ){
219           pCur->zCurrentRow = 0;
220           pCur->ePhase = COMPLETION_DATABASES;
221         }else{
222           pCur->zCurrentRow = completionKwrds[pCur->j++];
223         }
224         iCol = -1;
225         break;
226       }
227       case COMPLETION_DATABASES: {
228         if( pCur->pStmt==0 ){
229           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
230                              &pCur->pStmt, 0);
231         }
232         iCol = 1;
233         eNextPhase = COMPLETION_TABLES;
234         break;
235       }
236       case COMPLETION_TABLES: {
237         if( pCur->pStmt==0 ){
238           sqlite3_stmt *pS2;
239           char *zSql = 0;
240           const char *zSep = "";
241           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
242           while( sqlite3_step(pS2)==SQLITE_ROW ){
243             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
244             zSql = sqlite3_mprintf(
245                "%z%s"
246                "SELECT name FROM \"%w\".sqlite_master"
247                " WHERE type='table'",
248                zSql, zSep, zDb
249             );
250             if( zSql==0 ) return SQLITE_NOMEM;
251             zSep = " UNION ";
252           }
253           sqlite3_finalize(pS2);
254           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
255           sqlite3_free(zSql);
256         }
257         iCol = 0;
258         eNextPhase = COMPLETION_COLUMNS;
259         break;
260       }
261       case COMPLETION_COLUMNS: {
262         if( pCur->pStmt==0 ){
263           sqlite3_stmt *pS2;
264           char *zSql = 0;
265           const char *zSep = "";
266           sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
267           while( sqlite3_step(pS2)==SQLITE_ROW ){
268             const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
269             zSql = sqlite3_mprintf(
270                "%z%s"
271                "SELECT pti.name FROM \"%w\".sqlite_master AS sm"
272                        " JOIN pragma_table_info(sm.name,%Q) AS pti"
273                " WHERE sm.type='table'",
274                zSql, zSep, zDb, zDb
275             );
276             if( zSql==0 ) return SQLITE_NOMEM;
277             zSep = " UNION ";
278           }
279           sqlite3_finalize(pS2);
280           sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
281           sqlite3_free(zSql);
282         }
283         iCol = 0;
284         eNextPhase = COMPLETION_EOF;
285         break;
286       }
287     }
288     if( iCol<0 ){
289       /* This case is when the phase presets zCurrentRow */
290       if( pCur->zCurrentRow==0 ) continue;
291     }else{
292       if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
293         /* Extract the next row of content */
294         pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
295       }else{
296         /* When all rows are finished, advance to the next phase */
297         sqlite3_finalize(pCur->pStmt);
298         pCur->pStmt = 0;
299         pCur->ePhase = eNextPhase;
300         continue;
301       }
302     }
303     if( pCur->nPrefix==0 ) break;
304     if( sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0 ){
305       break;
306     }
307   }
308 
309   return SQLITE_OK;
310 }
311 
312 /*
313 ** Return values of columns for the row at which the completion_cursor
314 ** is currently pointing.
315 */
316 static int completionColumn(
317   sqlite3_vtab_cursor *cur,   /* The cursor */
318   sqlite3_context *ctx,       /* First argument to sqlite3_result_...() */
319   int i                       /* Which column to return */
320 ){
321   completion_cursor *pCur = (completion_cursor*)cur;
322   switch( i ){
323     case COMPLETION_COLUMN_CANDIDATE: {
324       sqlite3_result_text(ctx, pCur->zCurrentRow, -1, SQLITE_TRANSIENT);
325       break;
326     }
327     case COMPLETION_COLUMN_PREFIX: {
328       sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
329       break;
330     }
331     case COMPLETION_COLUMN_WHOLELINE: {
332       sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
333       break;
334     }
335     case COMPLETION_COLUMN_PHASE: {
336       sqlite3_result_int(ctx, pCur->ePhase);
337       break;
338     }
339   }
340   return SQLITE_OK;
341 }
342 
343 /*
344 ** Return the rowid for the current row.  In this implementation, the
345 ** rowid is the same as the output value.
346 */
347 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
348   completion_cursor *pCur = (completion_cursor*)cur;
349   *pRowid = pCur->iRowid;
350   return SQLITE_OK;
351 }
352 
353 /*
354 ** Return TRUE if the cursor has been moved off of the last
355 ** row of output.
356 */
357 static int completionEof(sqlite3_vtab_cursor *cur){
358   completion_cursor *pCur = (completion_cursor*)cur;
359   return pCur->ePhase >= COMPLETION_EOF;
360 }
361 
362 /*
363 ** This method is called to "rewind" the completion_cursor object back
364 ** to the first row of output.  This method is always called at least
365 ** once prior to any call to completionColumn() or completionRowid() or
366 ** completionEof().
367 */
368 static int completionFilter(
369   sqlite3_vtab_cursor *pVtabCursor,
370   int idxNum, const char *idxStr,
371   int argc, sqlite3_value **argv
372 ){
373   completion_cursor *pCur = (completion_cursor *)pVtabCursor;
374   int iArg = 0;
375   completionCursorReset(pCur);
376   if( idxNum & 1 ){
377     pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
378     if( pCur->nPrefix>0 ){
379       pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
380       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
381     }
382     iArg++;
383   }
384   if( idxNum & 2 ){
385     pCur->nLine = sqlite3_value_bytes(argv[iArg]);
386     if( pCur->nLine>0 ){
387       pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
388       if( pCur->zLine==0 ) return SQLITE_NOMEM;
389     }
390     iArg++;
391   }
392   if( pCur->zLine!=0 && pCur->zPrefix==0 ){
393     int i = pCur->nLine;
394     while( i>0 && (isalnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
395       i--;
396     }
397     pCur->nPrefix = pCur->nLine - i;
398     if( pCur->nPrefix>0 ){
399       pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
400       if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
401     }
402   }
403   pCur->iRowid = 0;
404   pCur->ePhase = COMPLETION_FIRST_PHASE;
405   return completionNext(pVtabCursor);
406 }
407 
408 /*
409 ** SQLite will invoke this method one or more times while planning a query
410 ** that uses the completion virtual table.  This routine needs to create
411 ** a query plan for each invocation and compute an estimated cost for that
412 ** plan.
413 **
414 ** There are two hidden parameters that act as arguments to the table-valued
415 ** function:  "prefix" and "wholeline".  Bit 0 of idxNum is set if "prefix"
416 ** is available and bit 1 is set if "wholeline" is available.
417 */
418 static int completionBestIndex(
419   sqlite3_vtab *tab,
420   sqlite3_index_info *pIdxInfo
421 ){
422   int i;                 /* Loop over constraints */
423   int idxNum = 0;        /* The query plan bitmask */
424   int prefixIdx = -1;    /* Index of the start= constraint, or -1 if none */
425   int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
426   int nArg = 0;          /* Number of arguments that completeFilter() expects */
427   const struct sqlite3_index_constraint *pConstraint;
428 
429   pConstraint = pIdxInfo->aConstraint;
430   for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
431     if( pConstraint->usable==0 ) continue;
432     if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
433     switch( pConstraint->iColumn ){
434       case COMPLETION_COLUMN_PREFIX:
435         prefixIdx = i;
436         idxNum |= 1;
437         break;
438       case COMPLETION_COLUMN_WHOLELINE:
439         wholelineIdx = i;
440         idxNum |= 2;
441         break;
442     }
443   }
444   if( prefixIdx>=0 ){
445     pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
446     pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
447   }
448   if( wholelineIdx>=0 ){
449     pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
450     pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
451   }
452   pIdxInfo->idxNum = idxNum;
453   pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
454   pIdxInfo->estimatedRows = 500 - 100*nArg;
455   return SQLITE_OK;
456 }
457 
458 /*
459 ** This following structure defines all the methods for the
460 ** completion virtual table.
461 */
462 static sqlite3_module completionModule = {
463   0,                         /* iVersion */
464   0,                         /* xCreate */
465   completionConnect,         /* xConnect */
466   completionBestIndex,       /* xBestIndex */
467   completionDisconnect,      /* xDisconnect */
468   0,                         /* xDestroy */
469   completionOpen,            /* xOpen - open a cursor */
470   completionClose,           /* xClose - close a cursor */
471   completionFilter,          /* xFilter - configure scan constraints */
472   completionNext,            /* xNext - advance a cursor */
473   completionEof,             /* xEof - check for end of scan */
474   completionColumn,          /* xColumn - read data */
475   completionRowid,           /* xRowid - read data */
476   0,                         /* xUpdate */
477   0,                         /* xBegin */
478   0,                         /* xSync */
479   0,                         /* xCommit */
480   0,                         /* xRollback */
481   0,                         /* xFindMethod */
482   0,                         /* xRename */
483 };
484 
485 #endif /* SQLITE_OMIT_VIRTUALTABLE */
486 
487 int sqlite3CompletionVtabInit(sqlite3 *db){
488   int rc = SQLITE_OK;
489 #ifndef SQLITE_OMIT_VIRTUALTABLE
490   rc = sqlite3_create_module(db, "completion", &completionModule, 0);
491 #endif
492   return rc;
493 }
494 
495 #ifdef _WIN32
496 __declspec(dllexport)
497 #endif
498 int sqlite3_completion_init(
499   sqlite3 *db,
500   char **pzErrMsg,
501   const sqlite3_api_routines *pApi
502 ){
503   int rc = SQLITE_OK;
504   SQLITE_EXTENSION_INIT2(pApi);
505 #ifndef SQLITE_OMIT_VIRTUALTABLE
506   rc = sqlite3CompletionVtabInit(db);
507 #endif
508   return rc;
509 }
510