Debian Codegraph @

ext/misc/completion.c

raw
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 #ifndef IsAlnum
45 #define IsAlnum(X) isalnum((unsigned char)X)
46 #endif
47
48
49 /* completion_vtab is a subclass of sqlite3_vtab which will
50 ** serve as the underlying representation of a completion virtual table
51 */
52 typedef struct completion_vtab completion_vtab;
53 struct completion_vtab {
54 sqlite3_vtab base; /* Base class - must be first */
55 sqlite3 *db; /* Database connection for this completion vtab */
56 };
57
58 /* completion_cursor is a subclass of sqlite3_vtab_cursor which will
59 ** serve as the underlying representation of a cursor that scans
60 ** over rows of the result
61 */
62 typedef struct completion_cursor completion_cursor;
63 struct completion_cursor {
64 sqlite3_vtab_cursor base; /* Base class - must be first */
65 sqlite3 *db; /* Database connection for this cursor */
66 int nPrefix, nLine; /* Number of bytes in zPrefix and zLine */
67 char *zPrefix; /* The prefix for the word we want to complete */
68 char *zLine; /* The whole that we want to complete */
69 const char *zCurrentRow; /* Current output row */
70 int szRow; /* Length of the zCurrentRow string */
71 sqlite3_stmt *pStmt; /* Current statement */
72 sqlite3_int64 iRowid; /* The rowid */
73 int ePhase; /* Current phase */
74 int j; /* inter-phase counter */
75 };
76
77 /* Values for ePhase:
78 */
79 #define COMPLETION_FIRST_PHASE 1
80 #define COMPLETION_KEYWORDS 1
81 #define COMPLETION_PRAGMAS 2
82 #define COMPLETION_FUNCTIONS 3
83 #define COMPLETION_COLLATIONS 4
84 #define COMPLETION_INDEXES 5
85 #define COMPLETION_TRIGGERS 6
86 #define COMPLETION_DATABASES 7
87 #define COMPLETION_TABLES 8 /* Also VIEWs and TRIGGERs */
88 #define COMPLETION_COLUMNS 9
89 #define COMPLETION_MODULES 10
90 #define COMPLETION_EOF 11
91
92 /*
93 ** The completionConnect() method is invoked to create a new
94 ** completion_vtab that describes the completion virtual table.
95 **
96 ** Think of this routine as the constructor for completion_vtab objects.
97 **
98 ** All this routine needs to do is:
99 **
100 ** (1) Allocate the completion_vtab object and initialize all fields.
101 **
102 ** (2) Tell SQLite (via the sqlite3_declare_vtab() interface) what the
103 ** result set of queries against completion will look like.
104 */
105 static int completionConnect(
106 sqlite3 *db,
107 void *pAux,
108 int argc, const char *const*argv,
109 sqlite3_vtab **ppVtab,
110 char **pzErr
111 ){
112 completion_vtab *pNew;
113 int rc;
114
115 (void)(pAux); /* Unused parameter */
116 (void)(argc); /* Unused parameter */
117 (void)(argv); /* Unused parameter */
118 (void)(pzErr); /* Unused parameter */
119
120 /* Column numbers */
121 #define COMPLETION_COLUMN_CANDIDATE 0 /* Suggested completion of the input */
122 #define COMPLETION_COLUMN_PREFIX 1 /* Prefix of the word to be completed */
123 #define COMPLETION_COLUMN_WHOLELINE 2 /* Entire line seen so far */
124 #define COMPLETION_COLUMN_PHASE 3 /* ePhase - used for debugging only */
125
126 sqlite3_vtab_config(db, SQLITE_VTAB_INNOCUOUS);
127 rc = sqlite3_declare_vtab(db,
128 "CREATE TABLE x("
129 " candidate TEXT,"
130 " prefix TEXT HIDDEN,"
131 " wholeline TEXT HIDDEN,"
132 " phase INT HIDDEN" /* Used for debugging only */
133 ")");
134 if( rc==SQLITE_OK ){
135 pNew = sqlite3_malloc64( sizeof(*pNew) );
136 *ppVtab = (sqlite3_vtab*)pNew;
137 if( pNew==0 ) return SQLITE_NOMEM;
138 memset(pNew, 0, sizeof(*pNew));
139 pNew->db = db;
140 }
141 return rc;
142 }
143
144 /*
145 ** This method is the destructor for completion_cursor objects.
146 */
147 static int completionDisconnect(sqlite3_vtab *pVtab){
148 sqlite3_free(pVtab);
149 return SQLITE_OK;
150 }
151
152 /*
153 ** Constructor for a new completion_cursor object.
154 */
155 static int completionOpen(sqlite3_vtab *p, sqlite3_vtab_cursor **ppCursor){
156 completion_cursor *pCur;
157 pCur = sqlite3_malloc64( sizeof(*pCur) );
158 if( pCur==0 ) return SQLITE_NOMEM;
159 memset(pCur, 0, sizeof(*pCur));
160 pCur->db = ((completion_vtab*)p)->db;
161 *ppCursor = &pCur->base;
162 return SQLITE_OK;
163 }
164
165 /*
166 ** Reset the completion_cursor.
167 */
168 static void completionCursorReset(completion_cursor *pCur){
169 sqlite3_free(pCur->zPrefix); pCur->zPrefix = 0; pCur->nPrefix = 0;
170 sqlite3_free(pCur->zLine); pCur->zLine = 0; pCur->nLine = 0;
171 sqlite3_finalize(pCur->pStmt); pCur->pStmt = 0;
172 pCur->j = 0;
173 }
174
175 /*
176 ** Destructor for a completion_cursor.
177 */
178 static int completionClose(sqlite3_vtab_cursor *cur){
179 completionCursorReset((completion_cursor*)cur);
180 sqlite3_free(cur);
181 return SQLITE_OK;
182 }
183
184 /*
185 ** Advance a completion_cursor to its next row of output.
186 **
187 ** The ->ePhase, ->j, and ->pStmt fields of the completion_cursor object
188 ** record the current state of the scan. This routine sets ->zCurrentRow
189 ** to the current row of output and then returns. If no more rows remain,
190 ** then ->ePhase is set to COMPLETION_EOF which will signal the virtual
191 ** table that has reached the end of its scan.
192 **
193 ** The current implementation just lists potential identifiers and
194 ** keywords and filters them by zPrefix. Future enhancements should
195 ** take zLine into account to try to restrict the set of identifiers and
196 ** keywords based on what would be legal at the current point of input.
197 */
198 static int completionNext(sqlite3_vtab_cursor *cur){
199 completion_cursor *pCur = (completion_cursor*)cur;
200 int eNextPhase = 0; /* Next phase to try if current phase reaches end */
201 int iCol = -1; /* If >=0, step pCur->pStmt and use the i-th column */
202 int rc;
203 pCur->iRowid++;
204 while( pCur->ePhase!=COMPLETION_EOF ){
205 switch( pCur->ePhase ){
206 case COMPLETION_KEYWORDS: {
207 if( pCur->j >= sqlite3_keyword_count() ){
208 pCur->zCurrentRow = 0;
209 pCur->ePhase = COMPLETION_DATABASES;
210 }else{
211 sqlite3_keyword_name(pCur->j++, &pCur->zCurrentRow, &pCur->szRow);
212 }
213 iCol = -1;
214 break;
215 }
216 case COMPLETION_DATABASES: {
217 if( pCur->pStmt==0 ){
218 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1,
219 &pCur->pStmt, 0);
220 }
221 iCol = 1;
222 eNextPhase = COMPLETION_TABLES;
223 break;
224 }
225 case COMPLETION_TABLES: {
226 if( pCur->pStmt==0 ){
227 sqlite3_stmt *pS2;
228 sqlite3_str* pStr = sqlite3_str_new(pCur->db);
229 char *zSql = 0;
230 const char *zSep = "";
231 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
232 while( sqlite3_step(pS2)==SQLITE_ROW ){
233 const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
234 sqlite3_str_appendf(pStr,
235 "%s"
236 "SELECT name FROM \"%w\".sqlite_schema",
237 zSep, zDb
238 );
239 zSep = " UNION ";
240 }
241 rc = sqlite3_finalize(pS2);
242 zSql = sqlite3_str_finish(pStr);
243 if( zSql==0 ) return SQLITE_NOMEM;
244 if( rc==SQLITE_OK ){
245 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
246 }
247 sqlite3_free(zSql);
248 if( rc ) return rc;
249 }
250 iCol = 0;
251 eNextPhase = COMPLETION_COLUMNS;
252 break;
253 }
254 case COMPLETION_COLUMNS: {
255 if( pCur->pStmt==0 ){
256 sqlite3_stmt *pS2;
257 sqlite3_str *pStr = sqlite3_str_new(pCur->db);
258 char *zSql = 0;
259 const char *zSep = "";
260 sqlite3_prepare_v2(pCur->db, "PRAGMA database_list", -1, &pS2, 0);
261 while( sqlite3_step(pS2)==SQLITE_ROW ){
262 const char *zDb = (const char*)sqlite3_column_text(pS2, 1);
263 sqlite3_str_appendf(pStr,
264 "%s"
265 "SELECT pti.name FROM \"%w\".sqlite_schema AS sm"
266 " JOIN pragma_table_xinfo(sm.name,%Q) AS pti"
267 " WHERE sm.type='table'",
268 zSep, zDb, zDb
269 );
270 zSep = " UNION ";
271 }
272 rc = sqlite3_finalize(pS2);
273 zSql = sqlite3_str_finish(pStr);
274 if( zSql==0 ) return SQLITE_NOMEM;
275 if( rc==SQLITE_OK ){
276 sqlite3_prepare_v2(pCur->db, zSql, -1, &pCur->pStmt, 0);
277 }
278 sqlite3_free(zSql);
279 if( rc ) return rc;
280 }
281 iCol = 0;
282 eNextPhase = COMPLETION_EOF;
283 break;
284 }
285 }
286 if( iCol<0 ){
287 /* This case is when the phase presets zCurrentRow */
288 if( pCur->zCurrentRow==0 ) continue;
289 }else{
290 if( sqlite3_step(pCur->pStmt)==SQLITE_ROW ){
291 /* Extract the next row of content */
292 pCur->zCurrentRow = (const char*)sqlite3_column_text(pCur->pStmt, iCol);
293 pCur->szRow = sqlite3_column_bytes(pCur->pStmt, iCol);
294 }else{
295 /* When all rows are finished, advance to the next phase */
296 rc = sqlite3_finalize(pCur->pStmt);
297 pCur->pStmt = 0;
298 pCur->ePhase = eNextPhase;
299 if( rc ) return rc;
300 continue;
301 }
302 }
303 if( pCur->nPrefix==0 ) break;
304 if( pCur->nPrefix<=pCur->szRow
305 && sqlite3_strnicmp(pCur->zPrefix, pCur->zCurrentRow, pCur->nPrefix)==0
306 ){
307 break;
308 }
309 }
310
311 return SQLITE_OK;
312 }
313
314 /*
315 ** Return values of columns for the row at which the completion_cursor
316 ** is currently pointing.
317 */
318 static int completionColumn(
319 sqlite3_vtab_cursor *cur, /* The cursor */
320 sqlite3_context *ctx, /* First argument to sqlite3_result_...() */
321 int i /* Which column to return */
322 ){
323 completion_cursor *pCur = (completion_cursor*)cur;
324 switch( i ){
325 case COMPLETION_COLUMN_CANDIDATE: {
326 sqlite3_result_text(ctx, pCur->zCurrentRow, pCur->szRow,SQLITE_TRANSIENT);
327 break;
328 }
329 case COMPLETION_COLUMN_PREFIX: {
330 sqlite3_result_text(ctx, pCur->zPrefix, -1, SQLITE_TRANSIENT);
331 break;
332 }
333 case COMPLETION_COLUMN_WHOLELINE: {
334 sqlite3_result_text(ctx, pCur->zLine, -1, SQLITE_TRANSIENT);
335 break;
336 }
337 case COMPLETION_COLUMN_PHASE: {
338 sqlite3_result_int(ctx, pCur->ePhase);
339 break;
340 }
341 }
342 return SQLITE_OK;
343 }
344
345 /*
346 ** Return the rowid for the current row. In this implementation, the
347 ** rowid is the same as the output value.
348 */
349 static int completionRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
350 completion_cursor *pCur = (completion_cursor*)cur;
351 *pRowid = pCur->iRowid;
352 return SQLITE_OK;
353 }
354
355 /*
356 ** Return TRUE if the cursor has been moved off of the last
357 ** row of output.
358 */
359 static int completionEof(sqlite3_vtab_cursor *cur){
360 completion_cursor *pCur = (completion_cursor*)cur;
361 return pCur->ePhase >= COMPLETION_EOF;
362 }
363
364 /*
365 ** This method is called to "rewind" the completion_cursor object back
366 ** to the first row of output. This method is always called at least
367 ** once prior to any call to completionColumn() or completionRowid() or
368 ** completionEof().
369 */
370 static int completionFilter(
371 sqlite3_vtab_cursor *pVtabCursor,
372 int idxNum, const char *idxStr,
373 int argc, sqlite3_value **argv
374 ){
375 completion_cursor *pCur = (completion_cursor *)pVtabCursor;
376 int iArg = 0;
377 (void)(idxStr); /* Unused parameter */
378 (void)(argc); /* Unused parameter */
379 completionCursorReset(pCur);
380 if( idxNum & 1 ){
381 pCur->nPrefix = sqlite3_value_bytes(argv[iArg]);
382 if( pCur->nPrefix>0 ){
383 pCur->zPrefix = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
384 if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
385 pCur->nPrefix = (int)strlen(pCur->zPrefix);
386 }
387 iArg = 1;
388 }
389 if( idxNum & 2 ){
390 pCur->nLine = sqlite3_value_bytes(argv[iArg]);
391 if( pCur->nLine>0 ){
392 pCur->zLine = sqlite3_mprintf("%s", sqlite3_value_text(argv[iArg]));
393 if( pCur->zLine==0 ) return SQLITE_NOMEM;
394 pCur->nLine = (int)strlen(pCur->zLine);
395 }
396 }
397 if( pCur->zLine!=0 && pCur->zPrefix==0 ){
398 int i = pCur->nLine;
399 while( i>0 && (IsAlnum(pCur->zLine[i-1]) || pCur->zLine[i-1]=='_') ){
400 i--;
401 }
402 pCur->nPrefix = pCur->nLine - i;
403 if( pCur->nPrefix>0 ){
404 pCur->zPrefix = sqlite3_mprintf("%.*s", pCur->nPrefix, pCur->zLine + i);
405 if( pCur->zPrefix==0 ) return SQLITE_NOMEM;
406 pCur->nPrefix = (int)strlen(pCur->zPrefix);
407 }
408 }
409 pCur->iRowid = 0;
410 pCur->ePhase = COMPLETION_FIRST_PHASE;
411 return completionNext(pVtabCursor);
412 }
413
414 /*
415 ** SQLite will invoke this method one or more times while planning a query
416 ** that uses the completion virtual table. This routine needs to create
417 ** a query plan for each invocation and compute an estimated cost for that
418 ** plan.
419 **
420 ** There are two hidden parameters that act as arguments to the table-valued
421 ** function: "prefix" and "wholeline". Bit 0 of idxNum is set if "prefix"
422 ** is available and bit 1 is set if "wholeline" is available.
423 */
424 static int completionBestIndex(
425 sqlite3_vtab *tab,
426 sqlite3_index_info *pIdxInfo
427 ){
428 int i; /* Loop over constraints */
429 int idxNum = 0; /* The query plan bitmask */
430 int prefixIdx = -1; /* Index of the start= constraint, or -1 if none */
431 int wholelineIdx = -1; /* Index of the stop= constraint, or -1 if none */
432 int nArg = 0; /* Number of arguments that completeFilter() expects */
433 const struct sqlite3_index_constraint *pConstraint;
434
435 (void)(tab); /* Unused parameter */
436 pConstraint = pIdxInfo->aConstraint;
437 for(i=0; i<pIdxInfo->nConstraint; i++, pConstraint++){
438 if( pConstraint->usable==0 ) continue;
439 if( pConstraint->op!=SQLITE_INDEX_CONSTRAINT_EQ ) continue;
440 switch( pConstraint->iColumn ){
441 case COMPLETION_COLUMN_PREFIX:
442 prefixIdx = i;
443 idxNum |= 1;
444 break;
445 case COMPLETION_COLUMN_WHOLELINE:
446 wholelineIdx = i;
447 idxNum |= 2;
448 break;
449 }
450 }
451 if( prefixIdx>=0 ){
452 pIdxInfo->aConstraintUsage[prefixIdx].argvIndex = ++nArg;
453 pIdxInfo->aConstraintUsage[prefixIdx].omit = 1;
454 }
455 if( wholelineIdx>=0 ){
456 pIdxInfo->aConstraintUsage[wholelineIdx].argvIndex = ++nArg;
457 pIdxInfo->aConstraintUsage[wholelineIdx].omit = 1;
458 }
459 pIdxInfo->idxNum = idxNum;
460 pIdxInfo->estimatedCost = (double)5000 - 1000*nArg;
461 pIdxInfo->estimatedRows = 500 - 100*nArg;
462 return SQLITE_OK;
463 }
464
465 /*
466 ** This following structure defines all the methods for the
467 ** completion virtual table.
468 */
469 static sqlite3_module completionModule = {
470 0, /* iVersion */
471 0, /* xCreate */
472 completionConnect, /* xConnect */
473 completionBestIndex, /* xBestIndex */
474 completionDisconnect, /* xDisconnect */
475 0, /* xDestroy */
476 completionOpen, /* xOpen - open a cursor */
477 completionClose, /* xClose - close a cursor */
478 completionFilter, /* xFilter - configure scan constraints */
479 completionNext, /* xNext - advance a cursor */
480 completionEof, /* xEof - check for end of scan */
481 completionColumn, /* xColumn - read data */
482 completionRowid, /* xRowid - read data */
483 0, /* xUpdate */
484 0, /* xBegin */
485 0, /* xSync */
486 0, /* xCommit */
487 0, /* xRollback */
488 0, /* xFindMethod */
489 0, /* xRename */
490 0, /* xSavepoint */
491 0, /* xRelease */
492 0, /* xRollbackTo */
493 0, /* xShadowName */
494 0 /* xIntegrity */
495 };
496
497 #endif /* SQLITE_OMIT_VIRTUALTABLE */
498
499 int sqlite3CompletionVtabInit(sqlite3 *db){
500 int rc = SQLITE_OK;
501 #ifndef SQLITE_OMIT_VIRTUALTABLE
502 rc = sqlite3_create_module(db, "completion", &completionModule, 0);
503 #endif
504 return rc;
505 }
506
507 #ifdef _WIN32
508 __declspec(dllexport)
509 #endif
510 int sqlite3_completion_init(
511 sqlite3 *db,
512 char **pzErrMsg,
513 const sqlite3_api_routines *pApi
514 ){
515 int rc = SQLITE_OK;
516 SQLITE_EXTENSION_INIT2(pApi);
517 (void)(pzErrMsg); /* Unused parameter */
518 #ifndef SQLITE_OMIT_VIRTUALTABLE
519 rc = sqlite3CompletionVtabInit(db);
520 #endif
521 return rc;
522 }