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