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