interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / ext / expert / sqlite3expert.c

2252 lines · 64209 bytes Raw Blame History
1/*
2** 2017 April 09
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#include "sqlite3expert.h"
14#include <assert.h>
15#include <string.h>
16#include <stdio.h>
17
18#if !defined(SQLITE_AMALGAMATION)
19#if defined(SQLITE_COVERAGE_TEST) || defined(SQLITE_MUTATION_TEST)
20# define SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS 1
21#endif
22#if defined(SQLITE_OMIT_AUXILIARY_SAFETY_CHECKS)
23# define ALWAYS(X) (1)
24# define NEVER(X) (0)
25#elif !defined(NDEBUG)
26# define ALWAYS(X) ((X)?1:(assert(0),0))
27# define NEVER(X) ((X)?(assert(0),1):0)
28#else
29# define ALWAYS(X) (X)
30# define NEVER(X) (X)
31#endif
32#endif /* !defined(SQLITE_AMALGAMATION) */
33
34
35#ifndef SQLITE_OMIT_VIRTUALTABLE
36
37typedef sqlite3_int64 i64;
38typedef sqlite3_uint64 u64;
39
40typedef struct IdxColumn IdxColumn;
41typedef struct IdxConstraint IdxConstraint;
42typedef struct IdxScan IdxScan;
43typedef struct IdxStatement IdxStatement;
44typedef struct IdxTable IdxTable;
45typedef struct IdxWrite IdxWrite;
46
47#define STRLEN (int)strlen
48
49/*
50** A temp table name that we assume no user database will actually use.
51** If this assumption proves incorrect triggers on the table with the
52** conflicting name will be ignored.
53*/
54#define UNIQUE_TABLE_NAME "t592690916721053953805701627921227776"
55
56/*
57** A single constraint. Equivalent to either "col = ?" or "col < ?" (or
58** any other type of single-ended range constraint on a column).
59**
60** pLink:
61** Used to temporarily link IdxConstraint objects into lists while
62** creating candidate indexes.
63*/
64struct IdxConstraint {
65 char *zColl; /* Collation sequence */
66 int bRange; /* True for range, false for eq */
67 int iCol; /* Constrained table column */
68 int bFlag; /* Used by idxFindCompatible() */
69 int bDesc; /* True if ORDER BY <expr> DESC */
70 IdxConstraint *pNext; /* Next constraint in pEq or pRange list */
71 IdxConstraint *pLink; /* See above */
72};
73
74/*
75** A single scan of a single table.
76*/
77struct IdxScan {
78 IdxTable *pTab; /* Associated table object */
79 int iDb; /* Database containing table zTable */
80 i64 covering; /* Mask of columns required for cov. index */
81 IdxConstraint *pOrder; /* ORDER BY columns */
82 IdxConstraint *pEq; /* List of == constraints */
83 IdxConstraint *pRange; /* List of < constraints */
84 IdxScan *pNextScan; /* Next IdxScan object for same analysis */
85};
86
87/*
88** Information regarding a single database table. Extracted from
89** "PRAGMA table_info" by function idxGetTableInfo().
90*/
91struct IdxColumn {
92 char *zName;
93 char *zColl;
94 int iPk;
95};
96struct IdxTable {
97 int nCol;
98 char *zName; /* Table name */
99 IdxColumn *aCol;
100 IdxTable *pNext; /* Next table in linked list of all tables */
101};
102
103/*
104** An object of the following type is created for each unique table/write-op
105** seen. The objects are stored in a singly-linked list beginning at
106** sqlite3expert.pWrite.
107*/
108struct IdxWrite {
109 IdxTable *pTab;
110 int eOp; /* SQLITE_UPDATE, DELETE or INSERT */
111 IdxWrite *pNext;
112};
113
114/*
115** Each statement being analyzed is represented by an instance of this
116** structure.
117*/
118struct IdxStatement {
119 int iId; /* Statement number */
120 char *zSql; /* SQL statement */
121 char *zIdx; /* Indexes */
122 char *zEQP; /* Plan */
123 IdxStatement *pNext;
124};
125
126
127/*
128** A hash table for storing strings. With space for a payload string
129** with each entry. Methods are:
130**
131** idxHashInit()
132** idxHashClear()
133** idxHashAdd()
134** idxHashSearch()
135*/
136#define IDX_HASH_SIZE 1023
137typedef struct IdxHashEntry IdxHashEntry;
138typedef struct IdxHash IdxHash;
139struct IdxHashEntry {
140 char *zKey; /* nul-terminated key */
141 char *zVal; /* nul-terminated value string */
142 char *zVal2; /* nul-terminated value string 2 */
143 IdxHashEntry *pHashNext; /* Next entry in same hash bucket */
144 IdxHashEntry *pNext; /* Next entry in hash */
145};
146struct IdxHash {
147 IdxHashEntry *pFirst;
148 IdxHashEntry *aHash[IDX_HASH_SIZE];
149};
150
151/*
152** sqlite3expert object.
153*/
154struct sqlite3expert {
155 int iSample; /* Percentage of tables to sample for stat1 */
156 sqlite3 *db; /* User database */
157 sqlite3 *dbm; /* In-memory db for this analysis */
158 sqlite3 *dbv; /* Vtab schema for this analysis */
159 IdxTable *pTable; /* List of all IdxTable objects */
160 IdxScan *pScan; /* List of scan objects */
161 IdxWrite *pWrite; /* List of write objects */
162 IdxStatement *pStatement; /* List of IdxStatement objects */
163 int bRun; /* True once analysis has run */
164 char **pzErrmsg;
165 int rc; /* Error code from whereinfo hook */
166 IdxHash hIdx; /* Hash containing all candidate indexes */
167 char *zCandidates; /* For EXPERT_REPORT_CANDIDATES */
168};
169
170
171/*
172** Allocate and return nByte bytes of zeroed memory using sqlite3_malloc().
173** If the allocation fails, set *pRc to SQLITE_NOMEM and return NULL.
174*/
175static void *idxMalloc(int *pRc, i64 nByte){
176 void *pRet;
177 assert( *pRc==SQLITE_OK );
178 assert( nByte>0 );
179 pRet = sqlite3_malloc64(nByte);
180 if( pRet ){
181 memset(pRet, 0, nByte);
182 }else{
183 *pRc = SQLITE_NOMEM;
184 }
185 return pRet;
186}
187
188/*
189** Initialize an IdxHash hash table.
190*/
191static void idxHashInit(IdxHash *pHash){
192 memset(pHash, 0, sizeof(IdxHash));
193}
194
195/*
196** Reset an IdxHash hash table.
197*/
198static void idxHashClear(IdxHash *pHash){
199 int i;
200 for(i=0; i<IDX_HASH_SIZE; i++){
201 IdxHashEntry *pEntry;
202 IdxHashEntry *pNext;
203 for(pEntry=pHash->aHash[i]; pEntry; pEntry=pNext){
204 pNext = pEntry->pHashNext;
205 sqlite3_free(pEntry->zVal2);
206 sqlite3_free(pEntry);
207 }
208 }
209 memset(pHash, 0, sizeof(IdxHash));
210}
211
212/*
213** Return the index of the hash bucket that the string specified by the
214** arguments to this function belongs.
215*/
216static int idxHashString(const char *z, int n){
217 unsigned int ret = 0;
218 int i;
219 for(i=0; i<n; i++){
220 ret += (ret<<3) + (unsigned char)(z[i]);
221 }
222 return (int)(ret % IDX_HASH_SIZE);
223}
224
225/*
226** If zKey is already present in the hash table, return non-zero and do
227** nothing. Otherwise, add an entry with key zKey and payload string zVal to
228** the hash table passed as the second argument.
229*/
230static int idxHashAdd(
231 int *pRc,
232 IdxHash *pHash,
233 const char *zKey,
234 const char *zVal
235){
236 int nKey = STRLEN(zKey);
237 int iHash = idxHashString(zKey, nKey);
238 int nVal = (zVal ? STRLEN(zVal) : 0);
239 IdxHashEntry *pEntry;
240 assert( iHash>=0 );
241 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
242 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
243 return 1;
244 }
245 }
246 pEntry = idxMalloc(pRc, sizeof(IdxHashEntry) + (i64)nKey+1 + (i64)nVal+1);
247 if( pEntry ){
248 pEntry->zKey = (char*)&pEntry[1];
249 memcpy(pEntry->zKey, zKey, nKey);
250 if( zVal ){
251 pEntry->zVal = &pEntry->zKey[nKey+1];
252 memcpy(pEntry->zVal, zVal, nVal);
253 }
254 pEntry->pHashNext = pHash->aHash[iHash];
255 pHash->aHash[iHash] = pEntry;
256
257 pEntry->pNext = pHash->pFirst;
258 pHash->pFirst = pEntry;
259 }
260 return 0;
261}
262
263/*
264** If zKey/nKey is present in the hash table, return a pointer to the
265** hash-entry object.
266*/
267static IdxHashEntry *idxHashFind(IdxHash *pHash, const char *zKey, int nKey){
268 int iHash;
269 IdxHashEntry *pEntry;
270 if( nKey<0 ) nKey = STRLEN(zKey);
271 iHash = idxHashString(zKey, nKey);
272 assert( iHash>=0 );
273 for(pEntry=pHash->aHash[iHash]; pEntry; pEntry=pEntry->pHashNext){
274 if( STRLEN(pEntry->zKey)==nKey && 0==memcmp(pEntry->zKey, zKey, nKey) ){
275 return pEntry;
276 }
277 }
278 return 0;
279}
280
281/*
282** If the hash table contains an entry with a key equal to the string
283** passed as the final two arguments to this function, return a pointer
284** to the payload string. Otherwise, if zKey/nKey is not present in the
285** hash table, return NULL.
286*/
287static const char *idxHashSearch(IdxHash *pHash, const char *zKey, int nKey){
288 IdxHashEntry *pEntry = idxHashFind(pHash, zKey, nKey);
289 if( pEntry ) return pEntry->zVal;
290 return 0;
291}
292
293/*
294** Allocate and return a new IdxConstraint object. Set the IdxConstraint.zColl
295** variable to point to a copy of nul-terminated string zColl.
296*/
297static IdxConstraint *idxNewConstraint(int *pRc, const char *zColl){
298 IdxConstraint *pNew;
299 int nColl = STRLEN(zColl);
300
301 assert( *pRc==SQLITE_OK );
302 pNew = (IdxConstraint*)idxMalloc(pRc, sizeof(IdxConstraint) + nColl + 1);
303 if( pNew ){
304 pNew->zColl = (char*)&pNew[1];
305 memcpy(pNew->zColl, zColl, nColl+1);
306 }
307 return pNew;
308}
309
310/*
311** An error associated with database handle db has just occurred. Pass
312** the error message to callback function xOut.
313*/
314static void idxDatabaseError(
315 sqlite3 *db, /* Database handle */
316 char **pzErrmsg /* Write error here */
317){
318 *pzErrmsg = sqlite3_mprintf("%s", sqlite3_errmsg(db));
319}
320
321/*
322** Prepare an SQL statement.
323*/
324static int idxPrepareStmt(
325 sqlite3 *db, /* Database handle to compile against */
326 sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
327 char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
328 const char *zSql /* SQL statement to compile */
329){
330 int rc = sqlite3_prepare_v2(db, zSql, -1, ppStmt, 0);
331 if( rc!=SQLITE_OK ){
332 *ppStmt = 0;
333 idxDatabaseError(db, pzErrmsg);
334 }
335 return rc;
336}
337
338/*
339** Prepare an SQL statement using the results of a printf() formatting.
340*/
341static int idxPrintfPrepareStmt(
342 sqlite3 *db, /* Database handle to compile against */
343 sqlite3_stmt **ppStmt, /* OUT: Compiled SQL statement */
344 char **pzErrmsg, /* OUT: sqlite3_malloc()ed error message */
345 const char *zFmt, /* printf() format of SQL statement */
346 ... /* Trailing printf() arguments */
347){
348 va_list ap;
349 int rc;
350 char *zSql;
351 va_start(ap, zFmt);
352 zSql = sqlite3_vmprintf(zFmt, ap);
353 if( zSql==0 ){
354 rc = SQLITE_NOMEM;
355 }else{
356 rc = idxPrepareStmt(db, ppStmt, pzErrmsg, zSql);
357 sqlite3_free(zSql);
358 }
359 va_end(ap);
360 return rc;
361}
362
363
364/*************************************************************************
365** Beginning of virtual table implementation.
366*/
367typedef struct ExpertVtab ExpertVtab;
368struct ExpertVtab {
369 sqlite3_vtab base;
370 IdxTable *pTab;
371 sqlite3expert *pExpert;
372};
373
374typedef struct ExpertCsr ExpertCsr;
375struct ExpertCsr {
376 sqlite3_vtab_cursor base;
377 sqlite3_stmt *pData;
378};
379
380static char *expertDequote(const char *zIn){
381 i64 n = STRLEN(zIn);
382 char *zRet = sqlite3_malloc64(n);
383
384 assert( zIn[0]=='\'' );
385 assert( zIn[n-1]=='\'' );
386
387 if( zRet ){
388 i64 iOut = 0;
389 i64 iIn = 0;
390 for(iIn=1; iIn<(n-1); iIn++){
391 if( zIn[iIn]=='\'' ){
392 assert( zIn[iIn+1]=='\'' );
393 iIn++;
394 }
395 zRet[iOut++] = zIn[iIn];
396 }
397 zRet[iOut] = '\0';
398 }
399
400 return zRet;
401}
402
403/*
404** This function is the implementation of both the xConnect and xCreate
405** methods of the r-tree virtual table.
406**
407** argv[0] -> module name
408** argv[1] -> database name
409** argv[2] -> table name
410** argv[...] -> column names...
411*/
412static int expertConnect(
413 sqlite3 *db,
414 void *pAux,
415 int argc, const char *const*argv,
416 sqlite3_vtab **ppVtab,
417 char **pzErr
418){
419 sqlite3expert *pExpert = (sqlite3expert*)pAux;
420 ExpertVtab *p = 0;
421 int rc;
422
423 if( argc!=4 ){
424 *pzErr = sqlite3_mprintf("internal error!");
425 rc = SQLITE_ERROR;
426 }else{
427 char *zCreateTable = expertDequote(argv[3]);
428 if( zCreateTable ){
429 rc = sqlite3_declare_vtab(db, zCreateTable);
430 if( rc==SQLITE_OK ){
431 p = idxMalloc(&rc, sizeof(ExpertVtab));
432 }
433 if( rc==SQLITE_OK ){
434 p->pExpert = pExpert;
435 p->pTab = pExpert->pTable;
436 assert( sqlite3_stricmp(p->pTab->zName, argv[2])==0 );
437 }
438 sqlite3_free(zCreateTable);
439 }else{
440 rc = SQLITE_NOMEM;
441 }
442 }
443
444 *ppVtab = (sqlite3_vtab*)p;
445 return rc;
446}
447
448static int expertDisconnect(sqlite3_vtab *pVtab){
449 ExpertVtab *p = (ExpertVtab*)pVtab;
450 sqlite3_free(p);
451 return SQLITE_OK;
452}
453
454static int expertBestIndex(sqlite3_vtab *pVtab, sqlite3_index_info *pIdxInfo){
455 ExpertVtab *p = (ExpertVtab*)pVtab;
456 int rc = SQLITE_OK;
457 int n = 0;
458 IdxScan *pScan;
459 const int opmask =
460 SQLITE_INDEX_CONSTRAINT_EQ | SQLITE_INDEX_CONSTRAINT_GT |
461 SQLITE_INDEX_CONSTRAINT_LT | SQLITE_INDEX_CONSTRAINT_GE |
462 SQLITE_INDEX_CONSTRAINT_LE;
463
464 pScan = idxMalloc(&rc, sizeof(IdxScan));
465 if( pScan ){
466 int i;
467
468 /* Link the new scan object into the list */
469 pScan->pTab = p->pTab;
470 pScan->pNextScan = p->pExpert->pScan;
471 p->pExpert->pScan = pScan;
472
473 /* Add the constraints to the IdxScan object */
474 for(i=0; i<pIdxInfo->nConstraint; i++){
475 struct sqlite3_index_constraint *pCons = &pIdxInfo->aConstraint[i];
476 if( pCons->usable
477 && pCons->iColumn>=0
478 && p->pTab->aCol[pCons->iColumn].iPk==0
479 && (pCons->op & opmask)
480 ){
481 IdxConstraint *pNew;
482 const char *zColl = sqlite3_vtab_collation(pIdxInfo, i);
483 pNew = idxNewConstraint(&rc, zColl);
484 if( pNew ){
485 pNew->iCol = pCons->iColumn;
486 if( pCons->op==SQLITE_INDEX_CONSTRAINT_EQ ){
487 pNew->pNext = pScan->pEq;
488 pScan->pEq = pNew;
489 }else{
490 pNew->bRange = 1;
491 pNew->pNext = pScan->pRange;
492 pScan->pRange = pNew;
493 }
494 }
495 n++;
496 pIdxInfo->aConstraintUsage[i].argvIndex = n;
497 }
498 }
499
500 /* Add the ORDER BY to the IdxScan object */
501 for(i=pIdxInfo->nOrderBy-1; i>=0; i--){
502 int iCol = pIdxInfo->aOrderBy[i].iColumn;
503 if( iCol>=0 ){
504 IdxConstraint *pNew = idxNewConstraint(&rc, p->pTab->aCol[iCol].zColl);
505 if( pNew ){
506 pNew->iCol = iCol;
507 pNew->bDesc = pIdxInfo->aOrderBy[i].desc;
508 pNew->pNext = pScan->pOrder;
509 pNew->pLink = pScan->pOrder;
510 pScan->pOrder = pNew;
511 n++;
512 }
513 }
514 }
515 }
516
517 pIdxInfo->estimatedCost = 1000000.0 / (n+1);
518 return rc;
519}
520
521static int expertUpdate(
522 sqlite3_vtab *pVtab,
523 int nData,
524 sqlite3_value **azData,
525 sqlite_int64 *pRowid
526){
527 (void)pVtab;
528 (void)nData;
529 (void)azData;
530 (void)pRowid;
531 return SQLITE_OK;
532}
533
534/*
535** Virtual table module xOpen method.
536*/
537static int expertOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor){
538 int rc = SQLITE_OK;
539 ExpertCsr *pCsr;
540 (void)pVTab;
541 pCsr = idxMalloc(&rc, sizeof(ExpertCsr));
542 *ppCursor = (sqlite3_vtab_cursor*)pCsr;
543 return rc;
544}
545
546/*
547** Virtual table module xClose method.
548*/
549static int expertClose(sqlite3_vtab_cursor *cur){
550 ExpertCsr *pCsr = (ExpertCsr*)cur;
551 sqlite3_finalize(pCsr->pData);
552 sqlite3_free(pCsr);
553 return SQLITE_OK;
554}
555
556/*
557** Virtual table module xEof method.
558**
559** Return non-zero if the cursor does not currently point to a valid
560** record (i.e if the scan has finished), or zero otherwise.
561*/
562static int expertEof(sqlite3_vtab_cursor *cur){
563 ExpertCsr *pCsr = (ExpertCsr*)cur;
564 return pCsr->pData==0;
565}
566
567/*
568** Virtual table module xNext method.
569*/
570static int expertNext(sqlite3_vtab_cursor *cur){
571 ExpertCsr *pCsr = (ExpertCsr*)cur;
572 int rc = SQLITE_OK;
573
574 assert( pCsr->pData );
575 rc = sqlite3_step(pCsr->pData);
576 if( rc!=SQLITE_ROW ){
577 rc = sqlite3_finalize(pCsr->pData);
578 pCsr->pData = 0;
579 }else{
580 rc = SQLITE_OK;
581 }
582
583 return rc;
584}
585
586/*
587** Virtual table module xRowid method.
588*/
589static int expertRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid){
590 (void)cur;
591 *pRowid = 0;
592 return SQLITE_OK;
593}
594
595/*
596** Virtual table module xColumn method.
597*/
598static int expertColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int i){
599 ExpertCsr *pCsr = (ExpertCsr*)cur;
600 sqlite3_value *pVal;
601 pVal = sqlite3_column_value(pCsr->pData, i);
602 if( pVal ){
603 sqlite3_result_value(ctx, pVal);
604 }
605 return SQLITE_OK;
606}
607
608/*
609** Virtual table module xFilter method.
610*/
611static int expertFilter(
612 sqlite3_vtab_cursor *cur,
613 int idxNum, const char *idxStr,
614 int argc, sqlite3_value **argv
615){
616 ExpertCsr *pCsr = (ExpertCsr*)cur;
617 ExpertVtab *pVtab = (ExpertVtab*)(cur->pVtab);
618 sqlite3expert *pExpert = pVtab->pExpert;
619 int rc;
620
621 (void)idxNum;
622 (void)idxStr;
623 (void)argc;
624 (void)argv;
625 rc = sqlite3_finalize(pCsr->pData);
626 pCsr->pData = 0;
627 if( rc==SQLITE_OK ){
628 rc = idxPrintfPrepareStmt(pExpert->db, &pCsr->pData, &pVtab->base.zErrMsg,
629 "SELECT * FROM main.%Q WHERE sqlite_expert_sample()", pVtab->pTab->zName
630 );
631 }
632
633 if( rc==SQLITE_OK ){
634 rc = expertNext(cur);
635 }
636 return rc;
637}
638
639static int idxRegisterVtab(sqlite3expert *p){
640 static sqlite3_module expertModule = {
641 2, /* iVersion */
642 expertConnect, /* xCreate - create a table */
643 expertConnect, /* xConnect - connect to an existing table */
644 expertBestIndex, /* xBestIndex - Determine search strategy */
645 expertDisconnect, /* xDisconnect - Disconnect from a table */
646 expertDisconnect, /* xDestroy - Drop a table */
647 expertOpen, /* xOpen - open a cursor */
648 expertClose, /* xClose - close a cursor */
649 expertFilter, /* xFilter - configure scan constraints */
650 expertNext, /* xNext - advance a cursor */
651 expertEof, /* xEof */
652 expertColumn, /* xColumn - read data */
653 expertRowid, /* xRowid - read data */
654 expertUpdate, /* xUpdate - write data */
655 0, /* xBegin - begin transaction */
656 0, /* xSync - sync transaction */
657 0, /* xCommit - commit transaction */
658 0, /* xRollback - rollback transaction */
659 0, /* xFindFunction - function overloading */
660 0, /* xRename - rename the table */
661 0, /* xSavepoint */
662 0, /* xRelease */
663 0, /* xRollbackTo */
664 0, /* xShadowName */
665 0, /* xIntegrity */
666 };
667
668 return sqlite3_create_module(p->dbv, "expert", &expertModule, (void*)p);
669}
670/*
671** End of virtual table implementation.
672*************************************************************************/
673/*
674** Finalize SQL statement pStmt. If (*pRc) is SQLITE_OK when this function
675** is called, set it to the return value of sqlite3_finalize() before
676** returning. Otherwise, discard the sqlite3_finalize() return value.
677*/
678static void idxFinalize(int *pRc, sqlite3_stmt *pStmt){
679 int rc = sqlite3_finalize(pStmt);
680 if( *pRc==SQLITE_OK ) *pRc = rc;
681}
682
683/*
684** Attempt to allocate an IdxTable structure corresponding to table zTab
685** in the main database of connection db. If successful, set (*ppOut) to
686** point to the new object and return SQLITE_OK. Otherwise, return an
687** SQLite error code and set (*ppOut) to NULL. In this case *pzErrmsg may be
688** set to point to an error string.
689**
690** It is the responsibility of the caller to eventually free either the
691** IdxTable object or error message using sqlite3_free().
692*/
693static int idxGetTableInfo(
694 sqlite3 *db, /* Database connection to read details from */
695 const char *zTab, /* Table name */
696 IdxTable **ppOut, /* OUT: New object (if successful) */
697 char **pzErrmsg /* OUT: Error message (if not) */
698){
699 sqlite3_stmt *p1 = 0;
700 int nCol = 0;
701 int nTab;
702 i64 nByte;
703 IdxTable *pNew = 0;
704 int rc, rc2;
705 char *pCsr = 0;
706 int nPk = 0;
707
708 *ppOut = 0;
709 if( zTab==0 ) return SQLITE_ERROR;
710 nTab = STRLEN(zTab);
711 nByte = sizeof(IdxTable) + nTab + 1;
712 rc = idxPrintfPrepareStmt(db, &p1, pzErrmsg, "PRAGMA table_xinfo=%Q", zTab);
713 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
714 const char *zCol = (const char*)sqlite3_column_text(p1, 1);
715 const char *zColSeq = 0;
716 if( zCol==0 ){
717 rc = SQLITE_ERROR;
718 break;
719 }
720 nByte += 1 + STRLEN(zCol);
721 rc = sqlite3_table_column_metadata(
722 db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
723 );
724 if( zColSeq==0 ) zColSeq = "binary";
725 nByte += 1 + STRLEN(zColSeq);
726 nCol++;
727 nPk += (sqlite3_column_int(p1, 5)>0);
728 }
729 rc2 = sqlite3_reset(p1);
730 if( rc==SQLITE_OK ) rc = rc2;
731
732 nByte += sizeof(IdxColumn) * nCol;
733 if( rc==SQLITE_OK ){
734 pNew = idxMalloc(&rc, nByte);
735 }
736 if( rc==SQLITE_OK ){
737 pNew->aCol = (IdxColumn*)&pNew[1];
738 pNew->nCol = nCol;
739 pCsr = (char*)&pNew->aCol[nCol];
740 }
741
742 nCol = 0;
743 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(p1) ){
744 const char *zCol = (const char*)sqlite3_column_text(p1, 1);
745 const char *zColSeq = 0;
746 int nCopy;
747 if( zCol==0 ) continue;
748 nCopy = STRLEN(zCol) + 1;
749 pNew->aCol[nCol].zName = pCsr;
750 pNew->aCol[nCol].iPk = (sqlite3_column_int(p1, 5)==1 && nPk==1);
751 memcpy(pCsr, zCol, nCopy);
752 pCsr += nCopy;
753
754 rc = sqlite3_table_column_metadata(
755 db, "main", zTab, zCol, 0, &zColSeq, 0, 0, 0
756 );
757 if( rc==SQLITE_OK ){
758 if( zColSeq==0 ) zColSeq = "binary";
759 nCopy = STRLEN(zColSeq) + 1;
760 pNew->aCol[nCol].zColl = pCsr;
761 memcpy(pCsr, zColSeq, nCopy);
762 pCsr += nCopy;
763 }
764
765 nCol++;
766 }
767 idxFinalize(&rc, p1);
768
769 if( rc!=SQLITE_OK ){
770 sqlite3_free(pNew);
771 pNew = 0;
772 }else if( ALWAYS(pNew!=0) ){
773 pNew->zName = pCsr;
774 if( ALWAYS(pNew->zName!=0) ) memcpy(pNew->zName, zTab, nTab+1);
775 }
776
777 *ppOut = pNew;
778 return rc;
779}
780
781/*
782** This function is a no-op if *pRc is set to anything other than
783** SQLITE_OK when it is called.
784**
785** If *pRc is initially set to SQLITE_OK, then the text specified by
786** the printf() style arguments is appended to zIn and the result returned
787** in a buffer allocated by sqlite3_malloc(). sqlite3_free() is called on
788** zIn before returning.
789*/
790static char *idxAppendText(int *pRc, char *zIn, const char *zFmt, ...){
791 va_list ap;
792 char *zAppend = 0;
793 char *zRet = 0;
794 i64 nIn = zIn ? STRLEN(zIn) : 0;
795 i64 nAppend = 0;
796 va_start(ap, zFmt);
797 if( *pRc==SQLITE_OK ){
798 zAppend = sqlite3_vmprintf(zFmt, ap);
799 if( zAppend ){
800 nAppend = STRLEN(zAppend);
801 zRet = (char*)sqlite3_malloc64(nIn + nAppend + 1);
802 }
803 if( zAppend && zRet ){
804 if( nIn ) memcpy(zRet, zIn, nIn);
805 memcpy(&zRet[nIn], zAppend, nAppend+1);
806 }else{
807 sqlite3_free(zRet);
808 zRet = 0;
809 *pRc = SQLITE_NOMEM;
810 }
811 sqlite3_free(zAppend);
812 sqlite3_free(zIn);
813 }
814 va_end(ap);
815 return zRet;
816}
817
818/*
819** Return true if zId must be quoted in order to use it as an SQL
820** identifier, or false otherwise.
821*/
822static int idxIdentifierRequiresQuotes(const char *zId){
823 int i;
824 int nId = STRLEN(zId);
825
826 if( nId==0 ) return 1;
827 if( zId[0]>='0' && zId[0]<='9' ) return 1;
828 if( sqlite3_keyword_check(zId, nId) ) return 1;
829
830 for(i=0; zId[i]; i++){
831 if( !(zId[i]=='_')
832 && !(zId[i]>='0' && zId[i]<='9')
833 && !(zId[i]>='a' && zId[i]<='z')
834 && !(zId[i]>='A' && zId[i]<='Z')
835 ){
836 return 1;
837 }
838 }
839 return 0;
840}
841
842/*
843** This function appends an index column definition suitable for constraint
844** pCons to the string passed as zIn and returns the result.
845*/
846static char *idxAppendColDefn(
847 int *pRc, /* IN/OUT: Error code */
848 char *zIn, /* Column defn accumulated so far */
849 IdxTable *pTab, /* Table index will be created on */
850 IdxConstraint *pCons
851){
852 char *zRet = zIn;
853 IdxColumn *p = &pTab->aCol[pCons->iCol];
854 if( zRet ) zRet = idxAppendText(pRc, zRet, ", ");
855
856 if( idxIdentifierRequiresQuotes(p->zName) ){
857 zRet = idxAppendText(pRc, zRet, "%Q", p->zName);
858 }else{
859 zRet = idxAppendText(pRc, zRet, "%s", p->zName);
860 }
861
862 if( sqlite3_stricmp(p->zColl, pCons->zColl) ){
863 if( idxIdentifierRequiresQuotes(pCons->zColl) ){
864 zRet = idxAppendText(pRc, zRet, " COLLATE %Q", pCons->zColl);
865 }else{
866 zRet = idxAppendText(pRc, zRet, " COLLATE %s", pCons->zColl);
867 }
868 }
869
870 if( pCons->bDesc ){
871 zRet = idxAppendText(pRc, zRet, " DESC");
872 }
873 return zRet;
874}
875
876/*
877** Search database dbm for an index compatible with the one idxCreateFromCons()
878** would create from arguments pScan, pEq and pTail. If no error occurs and
879** such an index is found, return non-zero. Or, if no such index is found,
880** return zero.
881**
882** If an error occurs, set *pRc to an SQLite error code and return zero.
883*/
884static int idxFindCompatible(
885 int *pRc, /* OUT: Error code */
886 sqlite3* dbm, /* Database to search */
887 IdxScan *pScan, /* Scan for table to search for index on */
888 IdxConstraint *pEq, /* List of == constraints */
889 IdxConstraint *pTail /* List of range constraints */
890){
891 const char *zTbl = pScan->pTab->zName;
892 sqlite3_stmt *pIdxList = 0;
893 IdxConstraint *pIter;
894 int nEq = 0; /* Number of elements in pEq */
895 int rc;
896
897 /* Count the elements in list pEq */
898 for(pIter=pEq; pIter; pIter=pIter->pLink) nEq++;
899
900 rc = idxPrintfPrepareStmt(dbm, &pIdxList, 0, "PRAGMA index_list=%Q", zTbl);
901 while( rc==SQLITE_OK && sqlite3_step(pIdxList)==SQLITE_ROW ){
902 int bMatch = 1;
903 IdxConstraint *pT = pTail;
904 sqlite3_stmt *pInfo = 0;
905 const char *zIdx = (const char*)sqlite3_column_text(pIdxList, 1);
906 if( zIdx==0 ) continue;
907
908 /* Zero the IdxConstraint.bFlag values in the pEq list */
909 for(pIter=pEq; pIter; pIter=pIter->pLink) pIter->bFlag = 0;
910
911 rc = idxPrintfPrepareStmt(dbm, &pInfo, 0, "PRAGMA index_xInfo=%Q", zIdx);
912 while( rc==SQLITE_OK && sqlite3_step(pInfo)==SQLITE_ROW ){
913 int iIdx = sqlite3_column_int(pInfo, 0);
914 int iCol = sqlite3_column_int(pInfo, 1);
915 const char *zColl = (const char*)sqlite3_column_text(pInfo, 4);
916
917 if( iIdx<nEq ){
918 for(pIter=pEq; pIter; pIter=pIter->pLink){
919 if( pIter->bFlag ) continue;
920 if( pIter->iCol!=iCol ) continue;
921 if( sqlite3_stricmp(pIter->zColl, zColl) ) continue;
922 pIter->bFlag = 1;
923 break;
924 }
925 if( pIter==0 ){
926 bMatch = 0;
927 break;
928 }
929 }else{
930 if( pT ){
931 if( pT->iCol!=iCol || sqlite3_stricmp(pT->zColl, zColl) ){
932 bMatch = 0;
933 break;
934 }
935 pT = pT->pLink;
936 }
937 }
938 }
939 idxFinalize(&rc, pInfo);
940
941 if( rc==SQLITE_OK && bMatch ){
942 sqlite3_finalize(pIdxList);
943 return 1;
944 }
945 }
946 idxFinalize(&rc, pIdxList);
947
948 *pRc = rc;
949 return 0;
950}
951
952/* Callback for sqlite3_exec() with query with leading count(*) column.
953 * The first argument is expected to be an int*, referent to be incremented
954 * if that leading column is not exactly '0'.
955 */
956static int countNonzeros(void* pCount, int nc,
957 char* azResults[], char* azColumns[]){
958 (void)azColumns; /* Suppress unused parameter warning */
959 if( nc>0 && (azResults[0][0]!='0' || azResults[0][1]!=0) ){
960 *((int *)pCount) += 1;
961 }
962 return 0;
963}
964
965static int idxCreateFromCons(
966 sqlite3expert *p,
967 IdxScan *pScan,
968 IdxConstraint *pEq,
969 IdxConstraint *pTail
970){
971 sqlite3 *dbm = p->dbm;
972 int rc = SQLITE_OK;
973 if( (pEq || pTail) && 0==idxFindCompatible(&rc, dbm, pScan, pEq, pTail) ){
974 IdxTable *pTab = pScan->pTab;
975 char *zCols = 0;
976 char *zIdx = 0;
977 IdxConstraint *pCons;
978 unsigned int h = 0;
979 const char *zFmt;
980
981 for(pCons=pEq; pCons; pCons=pCons->pLink){
982 zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
983 }
984 for(pCons=pTail; pCons; pCons=pCons->pLink){
985 zCols = idxAppendColDefn(&rc, zCols, pTab, pCons);
986 }
987
988 if( rc==SQLITE_OK ){
989 /* Hash the list of columns to come up with a name for the index */
990 const char *zTable = pScan->pTab->zName;
991 int quoteTable = idxIdentifierRequiresQuotes(zTable);
992 char *zName = 0; /* Index name */
993 int collisions = 0;
994 do{
995 int i;
996 char *zFind;
997
998 sqlite3_free(zName);
999 if( collisions<10 ){
1000 for(i=0; zCols[i]; i++){
1001 h += ((h<<3) + zCols[i]);
1002 }
1003 zName = sqlite3_mprintf("%s_idx_%08x", zTable, h);
1004 }else{
1005 /* After several hash attempts, generate a random name */
1006 sqlite3_uint64 u;
1007 sqlite3_randomness(sizeof(u), &u);
1008 zName = sqlite3_mprintf("%s_idx_%llx", zTable, u);
1009 }
1010 if( zName==0 ) break;
1011
1012 /* Is is unique among table, view and index names? */
1013 zFmt = "SELECT count(*) FROM sqlite_schema WHERE name=%Q"
1014 " AND type in ('index','table','view')";
1015 zFind = sqlite3_mprintf(zFmt, zName);
1016 i = 0;
1017 rc = sqlite3_exec(dbm, zFind, countNonzeros, &i, 0);
1018 assert(rc==SQLITE_OK);
1019 sqlite3_free(zFind);
1020 if( i==0 ){
1021 collisions = 0;
1022 break;
1023 }
1024 ++collisions;
1025 }while( ALWAYS(collisions<500) && zName!=0 );
1026 if( NEVER(collisions) ){
1027 /* This return means "Gave up trying to find a unique index name." */
1028 rc = SQLITE_BUSY_TIMEOUT;
1029 }else if( zName==0 ){
1030 rc = SQLITE_NOMEM;
1031 }else{
1032 if( quoteTable ){
1033 zFmt = "CREATE INDEX \"%w\" ON \"%w\"(%s)";
1034 }else{
1035 zFmt = "CREATE INDEX %s ON %s(%s)";
1036 }
1037 zIdx = sqlite3_mprintf(zFmt, zName, zTable, zCols);
1038 if( !zIdx ){
1039 rc = SQLITE_NOMEM;
1040 }else{
1041 rc = sqlite3_exec(dbm, zIdx, 0, 0, p->pzErrmsg);
1042 if( rc==SQLITE_OK ){
1043 idxHashAdd(&rc, &p->hIdx, zName, zIdx);
1044 }
1045 }
1046 sqlite3_free(zIdx);
1047 }
1048 sqlite3_free(zName);
1049 }
1050
1051 sqlite3_free(zCols);
1052 }
1053 return rc;
1054}
1055
1056/*
1057** Return true if list pList (linked by IdxConstraint.pLink) contains
1058** a constraint compatible with *p. Otherwise return false.
1059*/
1060static int idxFindConstraint(IdxConstraint *pList, IdxConstraint *p){
1061 IdxConstraint *pCmp;
1062 for(pCmp=pList; pCmp; pCmp=pCmp->pLink){
1063 if( p->iCol==pCmp->iCol ) return 1;
1064 }
1065 return 0;
1066}
1067
1068static int idxCreateFromWhere(
1069 sqlite3expert *p,
1070 IdxScan *pScan, /* Create indexes for this scan */
1071 IdxConstraint *pTail /* range/ORDER BY constraints for inclusion */
1072){
1073 IdxConstraint *p1 = 0;
1074 IdxConstraint *pCon;
1075 int rc;
1076
1077 /* Gather up all the == constraints. */
1078 for(pCon=pScan->pEq; pCon; pCon=pCon->pNext){
1079 if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
1080 pCon->pLink = p1;
1081 p1 = pCon;
1082 }
1083 }
1084
1085 /* Create an index using the == constraints collected above. And the
1086 ** range constraint/ORDER BY terms passed in by the caller, if any. */
1087 rc = idxCreateFromCons(p, pScan, p1, pTail);
1088
1089 /* If no range/ORDER BY passed by the caller, create a version of the
1090 ** index for each range constraint. */
1091 if( pTail==0 ){
1092 for(pCon=pScan->pRange; rc==SQLITE_OK && pCon; pCon=pCon->pNext){
1093 assert( pCon->pLink==0 );
1094 if( !idxFindConstraint(p1, pCon) && !idxFindConstraint(pTail, pCon) ){
1095 rc = idxCreateFromCons(p, pScan, p1, pCon);
1096 }
1097 }
1098 }
1099
1100 return rc;
1101}
1102
1103/*
1104** Create candidate indexes in database [dbm] based on the data in
1105** linked-list pScan.
1106*/
1107static int idxCreateCandidates(sqlite3expert *p){
1108 int rc = SQLITE_OK;
1109 IdxScan *pIter;
1110
1111 for(pIter=p->pScan; pIter && rc==SQLITE_OK; pIter=pIter->pNextScan){
1112 rc = idxCreateFromWhere(p, pIter, 0);
1113 if( rc==SQLITE_OK && pIter->pOrder ){
1114 rc = idxCreateFromWhere(p, pIter, pIter->pOrder);
1115 }
1116 }
1117
1118 return rc;
1119}
1120
1121/*
1122** Free all elements of the linked list starting at pConstraint.
1123*/
1124static void idxConstraintFree(IdxConstraint *pConstraint){
1125 IdxConstraint *pNext;
1126 IdxConstraint *p;
1127
1128 for(p=pConstraint; p; p=pNext){
1129 pNext = p->pNext;
1130 sqlite3_free(p);
1131 }
1132}
1133
1134/*
1135** Free all elements of the linked list starting from pScan up until pLast
1136** (pLast is not freed).
1137*/
1138static void idxScanFree(IdxScan *pScan, IdxScan *pLast){
1139 IdxScan *p;
1140 IdxScan *pNext;
1141 for(p=pScan; p!=pLast; p=pNext){
1142 pNext = p->pNextScan;
1143 idxConstraintFree(p->pOrder);
1144 idxConstraintFree(p->pEq);
1145 idxConstraintFree(p->pRange);
1146 sqlite3_free(p);
1147 }
1148}
1149
1150/*
1151** Free all elements of the linked list starting from pStatement up
1152** until pLast (pLast is not freed).
1153*/
1154static void idxStatementFree(IdxStatement *pStatement, IdxStatement *pLast){
1155 IdxStatement *p;
1156 IdxStatement *pNext;
1157 for(p=pStatement; p!=pLast; p=pNext){
1158 pNext = p->pNext;
1159 sqlite3_free(p->zEQP);
1160 sqlite3_free(p->zIdx);
1161 sqlite3_free(p);
1162 }
1163}
1164
1165/*
1166** Free the linked list of IdxTable objects starting at pTab.
1167*/
1168static void idxTableFree(IdxTable *pTab){
1169 IdxTable *pIter;
1170 IdxTable *pNext;
1171 for(pIter=pTab; pIter; pIter=pNext){
1172 pNext = pIter->pNext;
1173 sqlite3_free(pIter);
1174 }
1175}
1176
1177/*
1178** Free the linked list of IdxWrite objects starting at pTab.
1179*/
1180static void idxWriteFree(IdxWrite *pTab){
1181 IdxWrite *pIter;
1182 IdxWrite *pNext;
1183 for(pIter=pTab; pIter; pIter=pNext){
1184 pNext = pIter->pNext;
1185 sqlite3_free(pIter);
1186 }
1187}
1188
1189
1190
1191/*
1192** This function is called after candidate indexes have been created. It
1193** runs all the queries to see which indexes they prefer, and populates
1194** IdxStatement.zIdx and IdxStatement.zEQP with the results.
1195*/
1196static int idxFindIndexes(
1197 sqlite3expert *p,
1198 char **pzErr /* OUT: Error message (sqlite3_malloc) */
1199){
1200 IdxStatement *pStmt;
1201 sqlite3 *dbm = p->dbm;
1202 int rc = SQLITE_OK;
1203
1204 IdxHash hIdx;
1205 idxHashInit(&hIdx);
1206
1207 for(pStmt=p->pStatement; rc==SQLITE_OK && pStmt; pStmt=pStmt->pNext){
1208 IdxHashEntry *pEntry;
1209 sqlite3_stmt *pExplain = 0;
1210 idxHashClear(&hIdx);
1211 rc = idxPrintfPrepareStmt(dbm, &pExplain, pzErr,
1212 "EXPLAIN QUERY PLAN %s", pStmt->zSql
1213 );
1214 while( rc==SQLITE_OK && sqlite3_step(pExplain)==SQLITE_ROW ){
1215 /* int iId = sqlite3_column_int(pExplain, 0); */
1216 /* int iParent = sqlite3_column_int(pExplain, 1); */
1217 /* int iNotUsed = sqlite3_column_int(pExplain, 2); */
1218 const char *zDetail = (const char*)sqlite3_column_text(pExplain, 3);
1219 int nDetail;
1220 int i;
1221
1222 if( !zDetail ) continue;
1223 nDetail = STRLEN(zDetail);
1224
1225 for(i=0; i<nDetail; i++){
1226 const char *zIdx = 0;
1227 if( i+13<nDetail && memcmp(&zDetail[i], " USING INDEX ", 13)==0 ){
1228 zIdx = &zDetail[i+13];
1229 }else if( i+22<nDetail
1230 && memcmp(&zDetail[i], " USING COVERING INDEX ", 22)==0
1231 ){
1232 zIdx = &zDetail[i+22];
1233 }
1234 if( zIdx ){
1235 const char *zSql;
1236 int nIdx = 0;
1237 while( zIdx[nIdx]!='\0' && (zIdx[nIdx]!=' ' || zIdx[nIdx+1]!='(') ){
1238 nIdx++;
1239 }
1240 zSql = idxHashSearch(&p->hIdx, zIdx, nIdx);
1241 if( zSql ){
1242 idxHashAdd(&rc, &hIdx, zSql, 0);
1243 if( rc ) goto find_indexes_out;
1244 }
1245 break;
1246 }
1247 }
1248
1249 if( zDetail[0]!='-' ){
1250 pStmt->zEQP = idxAppendText(&rc, pStmt->zEQP, "%s\n", zDetail);
1251 }
1252 }
1253
1254 for(pEntry=hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
1255 pStmt->zIdx = idxAppendText(&rc, pStmt->zIdx, "%s;\n", pEntry->zKey);
1256 }
1257
1258 idxFinalize(&rc, pExplain);
1259 }
1260
1261 find_indexes_out:
1262 idxHashClear(&hIdx);
1263 return rc;
1264}
1265
1266static int idxAuthCallback(
1267 void *pCtx,
1268 int eOp,
1269 const char *z3,
1270 const char *z4,
1271 const char *zDb,
1272 const char *zTrigger
1273){
1274 int rc = SQLITE_OK;
1275 (void)z4;
1276 (void)zTrigger;
1277 if( eOp==SQLITE_INSERT || eOp==SQLITE_UPDATE || eOp==SQLITE_DELETE ){
1278 if( sqlite3_stricmp(zDb, "main")==0 ){
1279 sqlite3expert *p = (sqlite3expert*)pCtx;
1280 IdxTable *pTab;
1281 for(pTab=p->pTable; pTab; pTab=pTab->pNext){
1282 if( 0==sqlite3_stricmp(z3, pTab->zName) ) break;
1283 }
1284 if( pTab ){
1285 IdxWrite *pWrite;
1286 for(pWrite=p->pWrite; pWrite; pWrite=pWrite->pNext){
1287 if( pWrite->pTab==pTab && pWrite->eOp==eOp ) break;
1288 }
1289 if( pWrite==0 ){
1290 pWrite = idxMalloc(&rc, sizeof(IdxWrite));
1291 if( rc==SQLITE_OK ){
1292 pWrite->pTab = pTab;
1293 pWrite->eOp = eOp;
1294 pWrite->pNext = p->pWrite;
1295 p->pWrite = pWrite;
1296 }
1297 }
1298 }
1299 }
1300 }
1301 return rc;
1302}
1303
1304static int idxProcessOneTrigger(
1305 sqlite3expert *p,
1306 IdxWrite *pWrite,
1307 char **pzErr
1308){
1309 static const char *zInt = UNIQUE_TABLE_NAME;
1310 static const char *zDrop = "DROP TABLE " UNIQUE_TABLE_NAME;
1311 IdxTable *pTab = pWrite->pTab;
1312 const char *zTab = pTab->zName;
1313 const char *zSql =
1314 "SELECT 'CREATE TEMP' || substr(sql, 7) FROM sqlite_schema "
1315 "WHERE tbl_name = %Q AND type IN ('table', 'trigger') "
1316 "ORDER BY type;";
1317 sqlite3_stmt *pSelect = 0;
1318 int rc = SQLITE_OK;
1319 char *zWrite = 0;
1320
1321 /* Create the table and its triggers in the temp schema */
1322 rc = idxPrintfPrepareStmt(p->db, &pSelect, pzErr, zSql, zTab, zTab);
1323 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSelect) ){
1324 const char *zCreate = (const char*)sqlite3_column_text(pSelect, 0);
1325 if( zCreate==0 ) continue;
1326 rc = sqlite3_exec(p->dbv, zCreate, 0, 0, pzErr);
1327 }
1328 idxFinalize(&rc, pSelect);
1329
1330 /* Rename the table in the temp schema to zInt */
1331 if( rc==SQLITE_OK ){
1332 char *z = sqlite3_mprintf("ALTER TABLE temp.%Q RENAME TO %Q", zTab, zInt);
1333 if( z==0 ){
1334 rc = SQLITE_NOMEM;
1335 }else{
1336 rc = sqlite3_exec(p->dbv, z, 0, 0, pzErr);
1337 sqlite3_free(z);
1338 }
1339 }
1340
1341 switch( pWrite->eOp ){
1342 case SQLITE_INSERT: {
1343 int i;
1344 zWrite = idxAppendText(&rc, zWrite, "INSERT INTO %Q VALUES(", zInt);
1345 for(i=0; i<pTab->nCol; i++){
1346 zWrite = idxAppendText(&rc, zWrite, "%s?", i==0 ? "" : ", ");
1347 }
1348 zWrite = idxAppendText(&rc, zWrite, ")");
1349 break;
1350 }
1351 case SQLITE_UPDATE: {
1352 int i;
1353 zWrite = idxAppendText(&rc, zWrite, "UPDATE %Q SET ", zInt);
1354 for(i=0; i<pTab->nCol; i++){
1355 zWrite = idxAppendText(&rc, zWrite, "%s%Q=?", i==0 ? "" : ", ",
1356 pTab->aCol[i].zName
1357 );
1358 }
1359 break;
1360 }
1361 default: {
1362 assert( pWrite->eOp==SQLITE_DELETE );
1363 if( rc==SQLITE_OK ){
1364 zWrite = sqlite3_mprintf("DELETE FROM %Q", zInt);
1365 if( zWrite==0 ) rc = SQLITE_NOMEM;
1366 }
1367 }
1368 }
1369
1370 if( rc==SQLITE_OK ){
1371 sqlite3_stmt *pX = 0;
1372 rc = sqlite3_prepare_v2(p->dbv, zWrite, -1, &pX, 0);
1373 idxFinalize(&rc, pX);
1374 if( rc!=SQLITE_OK ){
1375 idxDatabaseError(p->dbv, pzErr);
1376 }
1377 }
1378 sqlite3_free(zWrite);
1379
1380 if( rc==SQLITE_OK ){
1381 rc = sqlite3_exec(p->dbv, zDrop, 0, 0, pzErr);
1382 }
1383
1384 return rc;
1385}
1386
1387static int idxProcessTriggers(sqlite3expert *p, char **pzErr){
1388 int rc = SQLITE_OK;
1389 IdxWrite *pEnd = 0;
1390 IdxWrite *pFirst = p->pWrite;
1391
1392 while( rc==SQLITE_OK && pFirst!=pEnd ){
1393 IdxWrite *pIter;
1394 for(pIter=pFirst; rc==SQLITE_OK && pIter!=pEnd; pIter=pIter->pNext){
1395 rc = idxProcessOneTrigger(p, pIter, pzErr);
1396 }
1397 pEnd = pFirst;
1398 pFirst = p->pWrite;
1399 }
1400
1401 return rc;
1402}
1403
1404/*
1405** This function tests if the schema of the main database of database handle
1406** db contains an object named zTab. Assuming no error occurs, output parameter
1407** (*pbContains) is set to true if zTab exists, or false if it does not.
1408**
1409** Or, if an error occurs, an SQLite error code is returned. The final value
1410** of (*pbContains) is undefined in this case.
1411*/
1412static int expertDbContainsObject(
1413 sqlite3 *db,
1414 const char *zTab,
1415 int *pbContains /* OUT: True if object exists */
1416){
1417 const char *zSql = "SELECT 1 FROM sqlite_schema WHERE name = ?";
1418 sqlite3_stmt *pSql = 0;
1419 int rc = SQLITE_OK;
1420 int ret = 0;
1421
1422 rc = sqlite3_prepare_v2(db, zSql, -1, &pSql, 0);
1423 if( rc==SQLITE_OK ){
1424 sqlite3_bind_text(pSql, 1, zTab, -1, SQLITE_STATIC);
1425 if( SQLITE_ROW==sqlite3_step(pSql) ){
1426 ret = 1;
1427 }
1428 rc = sqlite3_finalize(pSql);
1429 }
1430
1431 *pbContains = ret;
1432 return rc;
1433}
1434
1435/*
1436** Execute SQL command zSql using database handle db. If no error occurs,
1437** set (*pzErr) to NULL and return SQLITE_OK.
1438**
1439** If an error does occur, return an SQLite error code and set (*pzErr) to
1440** point to a buffer containing an English language error message. Except,
1441** if the error message begins with "no such module:", then ignore the
1442** error and return as if the SQL statement had succeeded.
1443**
1444** This is used to copy as much of the database schema as possible while
1445** ignoring any errors related to missing virtual table modules.
1446*/
1447static int expertSchemaSql(sqlite3 *db, const char *zSql, char **pzErr){
1448 int rc = SQLITE_OK;
1449 char *zErr = 0;
1450
1451 rc = sqlite3_exec(db, zSql, 0, 0, &zErr);
1452 if( rc!=SQLITE_OK && zErr ){
1453 int nErr = STRLEN(zErr);
1454 if( nErr>=15 && memcmp(zErr, "no such module:", 15)==0 ){
1455 sqlite3_free(zErr);
1456 rc = SQLITE_OK;
1457 zErr = 0;
1458 }
1459 }
1460
1461 *pzErr = zErr;
1462 return rc;
1463}
1464
1465static int idxCreateVtabSchema(sqlite3expert *p, char **pzErrmsg){
1466 int rc = idxRegisterVtab(p);
1467 sqlite3_stmt *pSchema = 0;
1468
1469 /* For each table in the main db schema:
1470 **
1471 ** 1) Add an entry to the p->pTable list, and
1472 ** 2) Create the equivalent virtual table in dbv.
1473 */
1474 rc = idxPrepareStmt(p->db, &pSchema, pzErrmsg,
1475 "SELECT type, name, sql, 1, "
1476 " substr(sql,1,14)=='create virtual' COLLATE nocase "
1477 "FROM sqlite_schema "
1478 "WHERE type IN ('table','view') AND "
1479 " substr(name,1,7)!='sqlite_' COLLATE nocase "
1480 " UNION ALL "
1481 "SELECT type, name, sql, 2, 0 FROM sqlite_schema "
1482 "WHERE type = 'trigger'"
1483 " AND tbl_name IN(SELECT name FROM sqlite_schema WHERE type = 'view') "
1484 "ORDER BY 4, 5 DESC, 1"
1485 );
1486 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSchema) ){
1487 const char *zType = (const char*)sqlite3_column_text(pSchema, 0);
1488 const char *zName = (const char*)sqlite3_column_text(pSchema, 1);
1489 const char *zSql = (const char*)sqlite3_column_text(pSchema, 2);
1490 int bVirtual = sqlite3_column_int(pSchema, 4);
1491 int bExists = 0;
1492
1493 if( zType==0 || zName==0 ) continue;
1494 rc = expertDbContainsObject(p->dbv, zName, &bExists);
1495 if( rc || bExists ) continue;
1496
1497 if( zType[0]=='v' || zType[1]=='r' || bVirtual ){
1498 /* A view. Or a trigger on a view. */
1499 if( zSql ) rc = expertSchemaSql(p->dbv, zSql, pzErrmsg);
1500 }else{
1501 IdxTable *pTab;
1502 rc = idxGetTableInfo(p->db, zName, &pTab, pzErrmsg);
1503 if( rc==SQLITE_OK && ALWAYS(pTab!=0) ){
1504 int i;
1505 char *zInner = 0;
1506 char *zOuter = 0;
1507 pTab->pNext = p->pTable;
1508 p->pTable = pTab;
1509
1510 /* The statement the vtab will pass to sqlite3_declare_vtab() */
1511 zInner = idxAppendText(&rc, 0, "CREATE TABLE x(");
1512 for(i=0; i<pTab->nCol; i++){
1513 zInner = idxAppendText(&rc, zInner, "%s%Q COLLATE %Q",
1514 (i==0 ? "" : ", "), pTab->aCol[i].zName, pTab->aCol[i].zColl
1515 );
1516 }
1517 zInner = idxAppendText(&rc, zInner, ")");
1518
1519 /* The CVT statement to create the vtab */
1520 zOuter = idxAppendText(&rc, 0,
1521 "CREATE VIRTUAL TABLE %Q USING expert(%Q)", zName, zInner
1522 );
1523 if( rc==SQLITE_OK ){
1524 rc = sqlite3_exec(p->dbv, zOuter, 0, 0, pzErrmsg);
1525 }
1526 sqlite3_free(zInner);
1527 sqlite3_free(zOuter);
1528 }
1529 }
1530 }
1531 idxFinalize(&rc, pSchema);
1532 return rc;
1533}
1534
1535struct IdxSampleCtx {
1536 int iTarget;
1537 double target; /* Target nRet/nRow value */
1538 double nRow; /* Number of rows seen */
1539 double nRet; /* Number of rows returned */
1540};
1541
1542static void idxSampleFunc(
1543 sqlite3_context *pCtx,
1544 int argc,
1545 sqlite3_value **argv
1546){
1547 struct IdxSampleCtx *p = (struct IdxSampleCtx*)sqlite3_user_data(pCtx);
1548 int bRet;
1549
1550 (void)argv;
1551 assert( argc==0 );
1552 if( p->nRow==0.0 ){
1553 bRet = 1;
1554 }else{
1555 bRet = (p->nRet / p->nRow) <= p->target;
1556 if( bRet==0 ){
1557 unsigned short rnd;
1558 sqlite3_randomness(2, (void*)&rnd);
1559 bRet = ((int)rnd % 100) <= p->iTarget;
1560 }
1561 }
1562
1563 sqlite3_result_int(pCtx, bRet);
1564 p->nRow += 1.0;
1565 p->nRet += (double)bRet;
1566}
1567
1568struct IdxRemCtx {
1569 int nSlot;
1570 struct IdxRemSlot {
1571 int eType; /* SQLITE_NULL, INTEGER, REAL, TEXT, BLOB */
1572 i64 iVal; /* SQLITE_INTEGER value */
1573 double rVal; /* SQLITE_FLOAT value */
1574 i64 nByte; /* Bytes of space allocated at z */
1575 i64 n; /* Size of buffer z */
1576 char *z; /* SQLITE_TEXT/BLOB value */
1577 } aSlot[1];
1578};
1579
1580/*
1581** Implementation of scalar function sqlite_expert_rem().
1582*/
1583static void idxRemFunc(
1584 sqlite3_context *pCtx,
1585 int argc,
1586 sqlite3_value **argv
1587){
1588 struct IdxRemCtx *p = (struct IdxRemCtx*)sqlite3_user_data(pCtx);
1589 struct IdxRemSlot *pSlot;
1590 int iSlot;
1591 assert( argc==2 );
1592
1593 iSlot = sqlite3_value_int(argv[0]);
1594 if( iSlot<0 || iSlot>=p->nSlot ){
1595 sqlite3_result_error(pCtx, "index out of range.", -1);
1596 return;
1597 }
1598 pSlot = &p->aSlot[iSlot];
1599
1600 switch( pSlot->eType ){
1601 case SQLITE_NULL:
1602 /* no-op */
1603 break;
1604
1605 case SQLITE_INTEGER:
1606 sqlite3_result_int64(pCtx, pSlot->iVal);
1607 break;
1608
1609 case SQLITE_FLOAT:
1610 sqlite3_result_double(pCtx, pSlot->rVal);
1611 break;
1612
1613 case SQLITE_BLOB:
1614 assert( pSlot->n <= 0x7fffffff );
1615 sqlite3_result_blob(pCtx, pSlot->z, (int)pSlot->n, SQLITE_TRANSIENT);
1616 break;
1617
1618 case SQLITE_TEXT:
1619 assert( pSlot->n <= 0x7fffffff );
1620 sqlite3_result_text(pCtx, pSlot->z, (int)pSlot->n, SQLITE_TRANSIENT);
1621 break;
1622 }
1623
1624 pSlot->eType = sqlite3_value_type(argv[1]);
1625 switch( pSlot->eType ){
1626 case SQLITE_NULL:
1627 /* no-op */
1628 break;
1629
1630 case SQLITE_INTEGER:
1631 pSlot->iVal = sqlite3_value_int64(argv[1]);
1632 break;
1633
1634 case SQLITE_FLOAT:
1635 pSlot->rVal = sqlite3_value_double(argv[1]);
1636 break;
1637
1638 case SQLITE_BLOB:
1639 case SQLITE_TEXT: {
1640 i64 nByte = sqlite3_value_bytes(argv[1]);
1641 const void *pData = 0;
1642 if( nByte>pSlot->nByte ){
1643 char *zNew = (char*)sqlite3_realloc64(pSlot->z, nByte*2);
1644 if( zNew==0 ){
1645 sqlite3_result_error_nomem(pCtx);
1646 return;
1647 }
1648 pSlot->nByte = nByte*2;
1649 pSlot->z = zNew;
1650 }
1651 pSlot->n = nByte;
1652 if( pSlot->eType==SQLITE_BLOB ){
1653 pData = sqlite3_value_blob(argv[1]);
1654 if( pData ) memcpy(pSlot->z, pData, nByte);
1655 }else{
1656 pData = sqlite3_value_text(argv[1]);
1657 memcpy(pSlot->z, pData, nByte);
1658 }
1659 break;
1660 }
1661 }
1662}
1663
1664static int idxLargestIndex(sqlite3 *db, int *pnMax, char **pzErr){
1665 int rc = SQLITE_OK;
1666 const char *zMax =
1667 "SELECT max(i.seqno) FROM "
1668 " sqlite_schema AS s, "
1669 " pragma_index_list(s.name) AS l, "
1670 " pragma_index_info(l.name) AS i "
1671 "WHERE s.type = 'table'";
1672 sqlite3_stmt *pMax = 0;
1673
1674 *pnMax = 0;
1675 rc = idxPrepareStmt(db, &pMax, pzErr, zMax);
1676 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pMax) ){
1677 *pnMax = sqlite3_column_int(pMax, 0) + 1;
1678 }
1679 idxFinalize(&rc, pMax);
1680
1681 return rc;
1682}
1683
1684static int idxPopulateOneStat1(
1685 sqlite3expert *p,
1686 sqlite3_stmt *pIndexXInfo,
1687 sqlite3_stmt *pWriteStat,
1688 const char *zTab,
1689 const char *zIdx,
1690 char **pzErr
1691){
1692 char *zCols = 0;
1693 char *zOrder = 0;
1694 char *zQuery = 0;
1695 int nCol = 0;
1696 int i;
1697 sqlite3_stmt *pQuery = 0;
1698 i64 *aStat = 0;
1699 int rc = SQLITE_OK;
1700
1701 assert( p->iSample>0 );
1702
1703 /* Formulate the query text */
1704 sqlite3_bind_text(pIndexXInfo, 1, zIdx, -1, SQLITE_STATIC);
1705 while( SQLITE_OK==rc && SQLITE_ROW==sqlite3_step(pIndexXInfo) ){
1706 const char *zComma = zCols==0 ? "" : ", ";
1707 const char *zName = (const char*)sqlite3_column_text(pIndexXInfo, 0);
1708 const char *zColl = (const char*)sqlite3_column_text(pIndexXInfo, 1);
1709 if( zName==0 ){
1710 /* This index contains an expression. Ignore it. */
1711 sqlite3_free(zCols);
1712 sqlite3_free(zOrder);
1713 return sqlite3_reset(pIndexXInfo);
1714 }
1715 zCols = idxAppendText(&rc, zCols,
1716 "%sx.%Q IS sqlite_expert_rem(%d, x.%Q) COLLATE %Q",
1717 zComma, zName, nCol, zName, zColl
1718 );
1719 zOrder = idxAppendText(&rc, zOrder, "%s%d", zComma, ++nCol);
1720 }
1721 sqlite3_reset(pIndexXInfo);
1722 if( rc==SQLITE_OK ){
1723 if( p->iSample==100 ){
1724 zQuery = sqlite3_mprintf(
1725 "SELECT %s FROM %Q x ORDER BY %s", zCols, zTab, zOrder
1726 );
1727 }else{
1728 zQuery = sqlite3_mprintf(
1729 "SELECT %s FROM temp."UNIQUE_TABLE_NAME" x ORDER BY %s", zCols, zOrder
1730 );
1731 }
1732 }
1733 sqlite3_free(zCols);
1734 sqlite3_free(zOrder);
1735
1736 /* Formulate the query text */
1737 if( rc==SQLITE_OK ){
1738 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
1739 rc = idxPrepareStmt(dbrem, &pQuery, pzErr, zQuery);
1740 }
1741 sqlite3_free(zQuery);
1742
1743 if( rc==SQLITE_OK ){
1744 aStat = (i64*)idxMalloc(&rc, sizeof(i64)*(nCol+1));
1745 }
1746 if( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
1747 IdxHashEntry *pEntry;
1748 char *zStat = 0;
1749 for(i=0; i<=nCol; i++) aStat[i] = 1;
1750 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pQuery) ){
1751 aStat[0]++;
1752 for(i=0; i<nCol; i++){
1753 if( sqlite3_column_int(pQuery, i)==0 ) break;
1754 }
1755 for(/*no-op*/; i<nCol; i++){
1756 aStat[i+1]++;
1757 }
1758 }
1759
1760 if( rc==SQLITE_OK ){
1761 i64 s0 = aStat[0];
1762 zStat = sqlite3_mprintf("%lld", s0);
1763 if( zStat==0 ) rc = SQLITE_NOMEM;
1764 for(i=1; rc==SQLITE_OK && i<=nCol; i++){
1765 zStat = idxAppendText(&rc, zStat, " %lld", (s0+aStat[i]/2) / aStat[i]);
1766 }
1767 }
1768
1769 if( rc==SQLITE_OK ){
1770 sqlite3_bind_text(pWriteStat, 1, zTab, -1, SQLITE_STATIC);
1771 sqlite3_bind_text(pWriteStat, 2, zIdx, -1, SQLITE_STATIC);
1772 sqlite3_bind_text(pWriteStat, 3, zStat, -1, SQLITE_STATIC);
1773 sqlite3_step(pWriteStat);
1774 rc = sqlite3_reset(pWriteStat);
1775 }
1776
1777 pEntry = idxHashFind(&p->hIdx, zIdx, STRLEN(zIdx));
1778 if( pEntry ){
1779 assert( pEntry->zVal2==0 );
1780 pEntry->zVal2 = zStat;
1781 }else{
1782 sqlite3_free(zStat);
1783 }
1784 }
1785 sqlite3_free(aStat);
1786 idxFinalize(&rc, pQuery);
1787
1788 return rc;
1789}
1790
1791static int idxBuildSampleTable(sqlite3expert *p, const char *zTab){
1792 int rc;
1793 char *zSql;
1794
1795 rc = sqlite3_exec(p->dbv,"DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
1796 if( rc!=SQLITE_OK ) return rc;
1797
1798 zSql = sqlite3_mprintf(
1799 "CREATE TABLE temp." UNIQUE_TABLE_NAME " AS SELECT * FROM %Q", zTab
1800 );
1801 if( zSql==0 ) return SQLITE_NOMEM;
1802 rc = sqlite3_exec(p->dbv, zSql, 0, 0, 0);
1803 sqlite3_free(zSql);
1804
1805 return rc;
1806}
1807
1808/*
1809** This function is called as part of sqlite3_expert_analyze(). Candidate
1810** indexes have already been created in database sqlite3expert.dbm, this
1811** function populates sqlite_stat1 table in the same database.
1812**
1813** The stat1 data is generated by querying the
1814*/
1815static int idxPopulateStat1(sqlite3expert *p, char **pzErr){
1816 int rc = SQLITE_OK;
1817 int nMax =0;
1818 struct IdxRemCtx *pCtx = 0;
1819 struct IdxSampleCtx samplectx;
1820 int i;
1821 i64 iPrev = -100000;
1822 sqlite3_stmt *pAllIndex = 0;
1823 sqlite3_stmt *pIndexXInfo = 0;
1824 sqlite3_stmt *pWrite = 0;
1825
1826 const char *zAllIndex =
1827 "SELECT s.rowid, s.name, l.name FROM "
1828 " sqlite_schema AS s, "
1829 " pragma_index_list(s.name) AS l "
1830 "WHERE s.type = 'table'";
1831 const char *zIndexXInfo =
1832 "SELECT name, coll FROM pragma_index_xinfo(?) WHERE key";
1833 const char *zWrite = "INSERT INTO sqlite_stat1 VALUES(?, ?, ?)";
1834
1835 /* If iSample==0, no sqlite_stat1 data is required. */
1836 if( p->iSample==0 ) return SQLITE_OK;
1837
1838 rc = idxLargestIndex(p->dbm, &nMax, pzErr);
1839 if( nMax<=0 || rc!=SQLITE_OK ) return rc;
1840
1841 rc = sqlite3_exec(p->dbm, "ANALYZE; PRAGMA writable_schema=1", 0, 0, 0);
1842
1843 if( rc==SQLITE_OK ){
1844 i64 nByte = sizeof(struct IdxRemCtx) + (sizeof(struct IdxRemSlot) * nMax);
1845 pCtx = (struct IdxRemCtx*)idxMalloc(&rc, nByte);
1846 }
1847
1848 if( rc==SQLITE_OK ){
1849 sqlite3 *dbrem = (p->iSample==100 ? p->db : p->dbv);
1850 rc = sqlite3_create_function(dbrem, "sqlite_expert_rem",
1851 2, SQLITE_UTF8, (void*)pCtx, idxRemFunc, 0, 0
1852 );
1853 }
1854 if( rc==SQLITE_OK ){
1855 rc = sqlite3_create_function(p->db, "sqlite_expert_sample",
1856 0, SQLITE_UTF8, (void*)&samplectx, idxSampleFunc, 0, 0
1857 );
1858 }
1859
1860 if( rc==SQLITE_OK ){
1861 pCtx->nSlot = (i64)nMax+1;
1862 rc = idxPrepareStmt(p->dbm, &pAllIndex, pzErr, zAllIndex);
1863 }
1864 if( rc==SQLITE_OK ){
1865 rc = idxPrepareStmt(p->dbm, &pIndexXInfo, pzErr, zIndexXInfo);
1866 }
1867 if( rc==SQLITE_OK ){
1868 rc = idxPrepareStmt(p->dbm, &pWrite, pzErr, zWrite);
1869 }
1870
1871 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pAllIndex) ){
1872 i64 iRowid = sqlite3_column_int64(pAllIndex, 0);
1873 const char *zTab = (const char*)sqlite3_column_text(pAllIndex, 1);
1874 const char *zIdx = (const char*)sqlite3_column_text(pAllIndex, 2);
1875 if( zTab==0 || zIdx==0 ) continue;
1876 if( p->iSample<100 && iPrev!=iRowid ){
1877 samplectx.target = (double)p->iSample / 100.0;
1878 samplectx.iTarget = p->iSample;
1879 samplectx.nRow = 0.0;
1880 samplectx.nRet = 0.0;
1881 rc = idxBuildSampleTable(p, zTab);
1882 if( rc!=SQLITE_OK ) break;
1883 }
1884 rc = idxPopulateOneStat1(p, pIndexXInfo, pWrite, zTab, zIdx, pzErr);
1885 iPrev = iRowid;
1886 }
1887 if( rc==SQLITE_OK && p->iSample<100 ){
1888 rc = sqlite3_exec(p->dbv,
1889 "DROP TABLE IF EXISTS temp." UNIQUE_TABLE_NAME, 0,0,0
1890 );
1891 }
1892
1893 idxFinalize(&rc, pAllIndex);
1894 idxFinalize(&rc, pIndexXInfo);
1895 idxFinalize(&rc, pWrite);
1896
1897 if( pCtx ){
1898 for(i=0; i<pCtx->nSlot; i++){
1899 sqlite3_free(pCtx->aSlot[i].z);
1900 }
1901 sqlite3_free(pCtx);
1902 }
1903
1904 if( rc==SQLITE_OK ){
1905 rc = sqlite3_exec(p->dbm, "ANALYZE sqlite_schema", 0, 0, 0);
1906 }
1907
1908 sqlite3_create_function(p->db, "sqlite_expert_rem", 2, SQLITE_UTF8, 0,0,0,0);
1909 sqlite3_create_function(p->db, "sqlite_expert_sample", 0,SQLITE_UTF8,0,0,0,0);
1910
1911 sqlite3_exec(p->db, "DROP TABLE IF EXISTS temp."UNIQUE_TABLE_NAME,0,0,0);
1912 return rc;
1913}
1914
1915/*
1916** Define and possibly pretend to use a useless collation sequence.
1917** This pretense allows expert to accept SQL using custom collations.
1918*/
1919int dummyCompare(void *up1, int up2, const void *up3, int up4, const void *up5){
1920 (void)up1;
1921 (void)up2;
1922 (void)up3;
1923 (void)up4;
1924 (void)up5;
1925 assert(0); /* VDBE should never be run. */
1926 return 0;
1927}
1928/* And a callback to register above upon actual need */
1929void useDummyCS(void *up1, sqlite3 *db, int etr, const char *zName){
1930 (void)up1;
1931 sqlite3_create_collation_v2(db, zName, etr, 0, dummyCompare, 0);
1932}
1933
1934#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
1935 && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
1936/*
1937** dummy functions for no-op implementation of UDFs during expert's work
1938*/
1939void dummyUDF(sqlite3_context *up1, int up2, sqlite3_value **up3){
1940 (void)up1;
1941 (void)up2;
1942 (void)up3;
1943 assert(0); /* VDBE should never be run. */
1944}
1945void dummyUDFvalue(sqlite3_context *up1){
1946 (void)up1;
1947 assert(0); /* VDBE should never be run. */
1948}
1949
1950/*
1951** Register UDFs from user database with another.
1952*/
1953int registerUDFs(sqlite3 *dbSrc, sqlite3 *dbDst){
1954 sqlite3_stmt *pStmt;
1955 int rc = sqlite3_prepare_v2(dbSrc,
1956 "SELECT name,type,enc,narg,flags "
1957 "FROM pragma_function_list() "
1958 "WHERE builtin==0", -1, &pStmt, 0);
1959 if( rc==SQLITE_OK ){
1960 while( SQLITE_ROW==(rc = sqlite3_step(pStmt)) ){
1961 int nargs = sqlite3_column_int(pStmt,3);
1962 int flags = sqlite3_column_int(pStmt,4);
1963 const char *name = (char*)sqlite3_column_text(pStmt,0);
1964 const char *type = (char*)sqlite3_column_text(pStmt,1);
1965 const char *enc = (char*)sqlite3_column_text(pStmt,2);
1966 if( name==0 || type==0 || enc==0 ){
1967 /* no-op. Only happens on OOM */
1968 }else{
1969 int ienc = SQLITE_UTF8;
1970 int rcf = SQLITE_ERROR;
1971 if( strcmp(enc,"utf16le")==0 ) ienc = SQLITE_UTF16LE;
1972 else if( strcmp(enc,"utf16be")==0 ) ienc = SQLITE_UTF16BE;
1973 ienc |= (flags & (SQLITE_DETERMINISTIC|SQLITE_DIRECTONLY));
1974 if( strcmp(type,"w")==0 ){
1975 rcf = sqlite3_create_window_function(dbDst,name,nargs,ienc,0,
1976 dummyUDF,dummyUDFvalue,0,0,0);
1977 }else if( strcmp(type,"a")==0 ){
1978 rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
1979 0,dummyUDF,dummyUDFvalue);
1980 }else if( strcmp(type,"s")==0 ){
1981 rcf = sqlite3_create_function(dbDst,name,nargs,ienc,0,
1982 dummyUDF,0,0);
1983 }
1984 if( rcf!=SQLITE_OK ){
1985 rc = rcf;
1986 break;
1987 }
1988 }
1989 }
1990 sqlite3_finalize(pStmt);
1991 if( rc==SQLITE_DONE ) rc = SQLITE_OK;
1992 }
1993 return rc;
1994}
1995#endif
1996
1997/*
1998** Allocate a new sqlite3expert object.
1999*/
2000sqlite3expert *sqlite3_expert_new(sqlite3 *db, char **pzErrmsg){
2001 int rc = SQLITE_OK;
2002 sqlite3expert *pNew;
2003
2004 pNew = (sqlite3expert*)idxMalloc(&rc, sizeof(sqlite3expert));
2005
2006 /* Open two in-memory databases to work with. The "vtab database" (dbv)
2007 ** will contain a virtual table corresponding to each real table in
2008 ** the user database schema, and a copy of each view. It is used to
2009 ** collect information regarding the WHERE, ORDER BY and other clauses
2010 ** of the user's query.
2011 */
2012 if( rc==SQLITE_OK ){
2013 pNew->db = db;
2014 pNew->iSample = 100;
2015 rc = sqlite3_open(":memory:", &pNew->dbv);
2016 }
2017 if( rc==SQLITE_OK ){
2018 rc = sqlite3_open(":memory:", &pNew->dbm);
2019 if( rc==SQLITE_OK ){
2020 sqlite3_db_config(pNew->dbm, SQLITE_DBCONFIG_TRIGGER_EQP, 1, (int*)0);
2021 }
2022 }
2023
2024 /* Allow custom collations to be dealt with through prepare. */
2025 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbm,0,useDummyCS);
2026 if( rc==SQLITE_OK ) rc = sqlite3_collation_needed(pNew->dbv,0,useDummyCS);
2027
2028#if !defined(SQLITE_OMIT_SCHEMA_PRAGMAS) \
2029 && !defined(SQLITE_OMIT_INTROSPECTION_PRAGMAS)
2030 /* Register UDFs from database [db] with [dbm] and [dbv]. */
2031 if( rc==SQLITE_OK ){
2032 rc = registerUDFs(pNew->db, pNew->dbm);
2033 }
2034 if( rc==SQLITE_OK ){
2035 rc = registerUDFs(pNew->db, pNew->dbv);
2036 }
2037#endif
2038
2039 /* Copy the entire schema of database [db] into [dbm]. */
2040 if( rc==SQLITE_OK ){
2041 sqlite3_stmt *pSql = 0;
2042 rc = idxPrintfPrepareStmt(pNew->db, &pSql, pzErrmsg,
2043 "SELECT sql, name, substr(sql,1,14)=='create virtual' COLLATE nocase"
2044 " FROM sqlite_schema WHERE substr(name,1,7)!='sqlite_' COLLATE nocase"
2045 " ORDER BY 3 DESC, rowid"
2046 );
2047 while( rc==SQLITE_OK && SQLITE_ROW==sqlite3_step(pSql) ){
2048 const char *zSql = (const char*)sqlite3_column_text(pSql, 0);
2049 const char *zName = (const char*)sqlite3_column_text(pSql, 1);
2050 int bExists = 0;
2051 rc = expertDbContainsObject(pNew->dbm, zName, &bExists);
2052 if( rc==SQLITE_OK && zSql && bExists==0 ){
2053 rc = expertSchemaSql(pNew->dbm, zSql, pzErrmsg);
2054 }
2055 }
2056 idxFinalize(&rc, pSql);
2057 }
2058
2059 /* Create the vtab schema */
2060 if( rc==SQLITE_OK ){
2061 rc = idxCreateVtabSchema(pNew, pzErrmsg);
2062 }
2063
2064 /* Register the auth callback with dbv */
2065 if( rc==SQLITE_OK ){
2066 sqlite3_set_authorizer(pNew->dbv, idxAuthCallback, (void*)pNew);
2067 }
2068
2069 /* If an error has occurred, free the new object and return NULL. Otherwise,
2070 ** return the new sqlite3expert handle. */
2071 if( rc!=SQLITE_OK ){
2072 sqlite3_expert_destroy(pNew);
2073 pNew = 0;
2074 }
2075 return pNew;
2076}
2077
2078/*
2079** Configure an sqlite3expert object.
2080*/
2081int sqlite3_expert_config(sqlite3expert *p, int op, ...){
2082 int rc = SQLITE_OK;
2083 va_list ap;
2084 va_start(ap, op);
2085 switch( op ){
2086 case EXPERT_CONFIG_SAMPLE: {
2087 int iVal = va_arg(ap, int);
2088 if( iVal<0 ) iVal = 0;
2089 if( iVal>100 ) iVal = 100;
2090 p->iSample = iVal;
2091 break;
2092 }
2093 default:
2094 rc = SQLITE_NOTFOUND;
2095 break;
2096 }
2097
2098 va_end(ap);
2099 return rc;
2100}
2101
2102/*
2103** Add an SQL statement to the analysis.
2104*/
2105int sqlite3_expert_sql(
2106 sqlite3expert *p, /* From sqlite3_expert_new() */
2107 const char *zSql, /* SQL statement to add */
2108 char **pzErr /* OUT: Error message (if any) */
2109){
2110 IdxScan *pScanOrig = p->pScan;
2111 IdxStatement *pStmtOrig = p->pStatement;
2112 int rc = SQLITE_OK;
2113 const char *zStmt = zSql;
2114
2115 if( p->bRun ) return SQLITE_MISUSE;
2116
2117 while( rc==SQLITE_OK && zStmt && zStmt[0] ){
2118 sqlite3_stmt *pStmt = 0;
2119 /* Ensure that the provided statement compiles against user's DB. */
2120 rc = idxPrepareStmt(p->db, &pStmt, pzErr, zStmt);
2121 if( rc!=SQLITE_OK ) break;
2122 sqlite3_finalize(pStmt);
2123 rc = sqlite3_prepare_v2(p->dbv, zStmt, -1, &pStmt, &zStmt);
2124 if( rc==SQLITE_OK ){
2125 if( pStmt ){
2126 IdxStatement *pNew;
2127 const char *z = sqlite3_sql(pStmt);
2128 i64 n = STRLEN(z);
2129 pNew = (IdxStatement*)idxMalloc(&rc, sizeof(IdxStatement) + n+1);
2130 if( rc==SQLITE_OK ){
2131 pNew->zSql = (char*)&pNew[1];
2132 memcpy(pNew->zSql, z, n+1);
2133 pNew->pNext = p->pStatement;
2134 if( p->pStatement ) pNew->iId = p->pStatement->iId+1;
2135 p->pStatement = pNew;
2136 }
2137 sqlite3_finalize(pStmt);
2138 }
2139 }else{
2140 idxDatabaseError(p->dbv, pzErr);
2141 }
2142 }
2143
2144 if( rc!=SQLITE_OK ){
2145 idxScanFree(p->pScan, pScanOrig);
2146 idxStatementFree(p->pStatement, pStmtOrig);
2147 p->pScan = pScanOrig;
2148 p->pStatement = pStmtOrig;
2149 }
2150
2151 return rc;
2152}
2153
2154int sqlite3_expert_analyze(sqlite3expert *p, char **pzErr){
2155 int rc;
2156 IdxHashEntry *pEntry;
2157
2158 /* Do trigger processing to collect any extra IdxScan structures */
2159 rc = idxProcessTriggers(p, pzErr);
2160
2161 /* Create candidate indexes within the in-memory database file */
2162 if( rc==SQLITE_OK ){
2163 p->pzErrmsg = pzErr;
2164 rc = idxCreateCandidates(p);
2165 p->pzErrmsg = 0;
2166 if( rc==SQLITE_BUSY_TIMEOUT ){
2167 if( pzErr ){
2168 *pzErr = sqlite3_mprintf("Cannot find a unique index name to propose.");
2169 }
2170 return rc;
2171 }
2172 }
2173
2174 /* Generate the stat1 data */
2175 if( rc==SQLITE_OK ){
2176 rc = idxPopulateStat1(p, pzErr);
2177 }
2178
2179 /* Formulate the EXPERT_REPORT_CANDIDATES text */
2180 for(pEntry=p->hIdx.pFirst; pEntry; pEntry=pEntry->pNext){
2181 p->zCandidates = idxAppendText(&rc, p->zCandidates,
2182 "%s;%s%s\n", pEntry->zVal,
2183 pEntry->zVal2 ? " -- stat1: " : "", pEntry->zVal2
2184 );
2185 }
2186
2187 /* Figure out which of the candidate indexes are preferred by the query
2188 ** planner and report the results to the user. */
2189 if( rc==SQLITE_OK ){
2190 rc = idxFindIndexes(p, pzErr);
2191 }
2192
2193 if( rc==SQLITE_OK ){
2194 p->bRun = 1;
2195 }
2196 return rc;
2197}
2198
2199/*
2200** Return the total number of statements that have been added to this
2201** sqlite3expert using sqlite3_expert_sql().
2202*/
2203int sqlite3_expert_count(sqlite3expert *p){
2204 int nRet = 0;
2205 if( p->pStatement ) nRet = p->pStatement->iId+1;
2206 return nRet;
2207}
2208
2209/*
2210** Return a component of the report.
2211*/
2212const char *sqlite3_expert_report(sqlite3expert *p, int iStmt, int eReport){
2213 const char *zRet = 0;
2214 IdxStatement *pStmt;
2215
2216 if( p->bRun==0 ) return 0;
2217 for(pStmt=p->pStatement; pStmt && pStmt->iId!=iStmt; pStmt=pStmt->pNext);
2218 switch( eReport ){
2219 case EXPERT_REPORT_SQL:
2220 if( pStmt ) zRet = pStmt->zSql;
2221 break;
2222 case EXPERT_REPORT_INDEXES:
2223 if( pStmt ) zRet = pStmt->zIdx;
2224 break;
2225 case EXPERT_REPORT_PLAN:
2226 if( pStmt ) zRet = pStmt->zEQP;
2227 break;
2228 case EXPERT_REPORT_CANDIDATES:
2229 zRet = p->zCandidates;
2230 break;
2231 }
2232 return zRet;
2233}
2234
2235/*
2236** Free an sqlite3expert object.
2237*/
2238void sqlite3_expert_destroy(sqlite3expert *p){
2239 if( p ){
2240 sqlite3_close(p->dbm);
2241 sqlite3_close(p->dbv);
2242 idxScanFree(p->pScan, 0);
2243 idxStatementFree(p->pStatement, 0);
2244 idxTableFree(p->pTable);
2245 idxWriteFree(p->pWrite);
2246 idxHashClear(&p->hIdx);
2247 sqlite3_free(p->zCandidates);
2248 sqlite3_free(p);
2249 }
2250}
2251
2252#endif /* ifndef SQLITE_OMIT_VIRTUALTABLE */