xref: /sqlite-3.40.0/src/analyze.c (revision e85e1da0)
1 /*
2 ** 2005-07-08
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 ** This file contains code associated with the ANALYZE command.
13 **
14 ** The ANALYZE command gather statistics about the content of tables
15 ** and indices.  These statistics are made available to the query planner
16 ** to help it make better decisions about how to perform queries.
17 **
18 ** The following system tables are or have been supported:
19 **
20 **    CREATE TABLE sqlite_stat1(tbl, idx, stat);
21 **    CREATE TABLE sqlite_stat2(tbl, idx, sampleno, sample);
22 **    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
23 **    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
24 **
25 ** Additional tables might be added in future releases of SQLite.
26 ** The sqlite_stat2 table is not created or used unless the SQLite version
27 ** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
28 ** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
29 ** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
30 ** created and used by SQLite versions 3.7.9 through 3.29.0 when
31 ** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
32 ** is a superset of sqlite_stat2 and is also now deprecated.  The
33 ** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
34 ** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite
35 ** versions 3.8.1 and later.  STAT4 is the only variant that is still
36 ** supported.
37 **
38 ** For most applications, sqlite_stat1 provides all the statistics required
39 ** for the query planner to make good choices.
40 **
41 ** Format of sqlite_stat1:
42 **
43 ** There is normally one row per index, with the index identified by the
44 ** name in the idx column.  The tbl column is the name of the table to
45 ** which the index belongs.  In each such row, the stat column will be
46 ** a string consisting of a list of integers.  The first integer in this
47 ** list is the number of rows in the index.  (This is the same as the
48 ** number of rows in the table, except for partial indices.)  The second
49 ** integer is the average number of rows in the index that have the same
50 ** value in the first column of the index.  The third integer is the average
51 ** number of rows in the index that have the same value for the first two
52 ** columns.  The N-th integer (for N>1) is the average number of rows in
53 ** the index which have the same value for the first N-1 columns.  For
54 ** a K-column index, there will be K+1 integers in the stat column.  If
55 ** the index is unique, then the last integer will be 1.
56 **
57 ** The list of integers in the stat column can optionally be followed
58 ** by the keyword "unordered".  The "unordered" keyword, if it is present,
59 ** must be separated from the last integer by a single space.  If the
60 ** "unordered" keyword is present, then the query planner assumes that
61 ** the index is unordered and will not use the index for a range query.
62 **
63 ** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
64 ** column contains a single integer which is the (estimated) number of
65 ** rows in the table identified by sqlite_stat1.tbl.
66 **
67 ** Format of sqlite_stat2:
68 **
69 ** The sqlite_stat2 is only created and is only used if SQLite is compiled
70 ** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
71 ** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
72 ** about the distribution of keys within an index.  The index is identified by
73 ** the "idx" column and the "tbl" column is the name of the table to which
74 ** the index belongs.  There are usually 10 rows in the sqlite_stat2
75 ** table for each index.
76 **
77 ** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
78 ** inclusive are samples of the left-most key value in the index taken at
79 ** evenly spaced points along the index.  Let the number of samples be S
80 ** (10 in the standard build) and let C be the number of rows in the index.
81 ** Then the sampled rows are given by:
82 **
83 **     rownumber = (i*C*2 + C)/(S*2)
84 **
85 ** For i between 0 and S-1.  Conceptually, the index space is divided into
86 ** S uniform buckets and the samples are the middle row from each bucket.
87 **
88 ** The format for sqlite_stat2 is recorded here for legacy reference.  This
89 ** version of SQLite does not support sqlite_stat2.  It neither reads nor
90 ** writes the sqlite_stat2 table.  This version of SQLite only supports
91 ** sqlite_stat3.
92 **
93 ** Format for sqlite_stat3:
94 **
95 ** The sqlite_stat3 format is a subset of sqlite_stat4.  Hence, the
96 ** sqlite_stat4 format will be described first.  Further information
97 ** about sqlite_stat3 follows the sqlite_stat4 description.
98 **
99 ** Format for sqlite_stat4:
100 **
101 ** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
102 ** to aid the query planner in choosing good indices based on the values
103 ** that indexed columns are compared against in the WHERE clauses of
104 ** queries.
105 **
106 ** The sqlite_stat4 table contains multiple entries for each index.
107 ** The idx column names the index and the tbl column is the table of the
108 ** index.  If the idx and tbl columns are the same, then the sample is
109 ** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
110 ** binary encoding of a key from the index.  The nEq column is a
111 ** list of integers.  The first integer is the approximate number
112 ** of entries in the index whose left-most column exactly matches
113 ** the left-most column of the sample.  The second integer in nEq
114 ** is the approximate number of entries in the index where the
115 ** first two columns match the first two columns of the sample.
116 ** And so forth.  nLt is another list of integers that show the approximate
117 ** number of entries that are strictly less than the sample.  The first
118 ** integer in nLt contains the number of entries in the index where the
119 ** left-most column is less than the left-most column of the sample.
120 ** The K-th integer in the nLt entry is the number of index entries
121 ** where the first K columns are less than the first K columns of the
122 ** sample.  The nDLt column is like nLt except that it contains the
123 ** number of distinct entries in the index that are less than the
124 ** sample.
125 **
126 ** There can be an arbitrary number of sqlite_stat4 entries per index.
127 ** The ANALYZE command will typically generate sqlite_stat4 tables
128 ** that contain between 10 and 40 samples which are distributed across
129 ** the key space, though not uniformly, and which include samples with
130 ** large nEq values.
131 **
132 ** Format for sqlite_stat3 redux:
133 **
134 ** The sqlite_stat3 table is like sqlite_stat4 except that it only
135 ** looks at the left-most column of the index.  The sqlite_stat3.sample
136 ** column contains the actual value of the left-most column instead
137 ** of a blob encoding of the complete index key as is found in
138 ** sqlite_stat4.sample.  The nEq, nLt, and nDLt entries of sqlite_stat3
139 ** all contain just a single integer which is the same as the first
140 ** integer in the equivalent columns in sqlite_stat4.
141 */
142 #ifndef SQLITE_OMIT_ANALYZE
143 #include "sqliteInt.h"
144 
145 #if defined(SQLITE_ENABLE_STAT4)
146 # define IsStat4     1
147 #else
148 # define IsStat4     0
149 # undef SQLITE_STAT4_SAMPLES
150 # define SQLITE_STAT4_SAMPLES 1
151 #endif
152 
153 /*
154 ** This routine generates code that opens the sqlite_statN tables.
155 ** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
156 ** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
157 ** appropriate compile-time options are provided.
158 **
159 ** If the sqlite_statN tables do not previously exist, it is created.
160 **
161 ** Argument zWhere may be a pointer to a buffer containing a table name,
162 ** or it may be a NULL pointer. If it is not NULL, then all entries in
163 ** the sqlite_statN tables associated with the named table are deleted.
164 ** If zWhere==0, then code is generated to delete all stat table entries.
165 */
166 static void openStatTable(
167   Parse *pParse,          /* Parsing context */
168   int iDb,                /* The database we are looking in */
169   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
170   const char *zWhere,     /* Delete entries for this table or index */
171   const char *zWhereType  /* Either "tbl" or "idx" */
172 ){
173   static const struct {
174     const char *zName;
175     const char *zCols;
176   } aTable[] = {
177     { "sqlite_stat1", "tbl,idx,stat" },
178 #if defined(SQLITE_ENABLE_STAT4)
179     { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
180 #else
181     { "sqlite_stat4", 0 },
182 #endif
183     { "sqlite_stat3", 0 },
184   };
185   int i;
186   sqlite3 *db = pParse->db;
187   Db *pDb;
188   Vdbe *v = sqlite3GetVdbe(pParse);
189   u32 aRoot[ArraySize(aTable)];
190   u8 aCreateTbl[ArraySize(aTable)];
191 #ifdef SQLITE_ENABLE_STAT4
192   const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;
193 #else
194   const int nToOpen = 1;
195 #endif
196 
197   if( v==0 ) return;
198   assert( sqlite3BtreeHoldsAllMutexes(db) );
199   assert( sqlite3VdbeDb(v)==db );
200   pDb = &db->aDb[iDb];
201 
202   /* Create new statistic tables if they do not exist, or clear them
203   ** if they do already exist.
204   */
205   for(i=0; i<ArraySize(aTable); i++){
206     const char *zTab = aTable[i].zName;
207     Table *pStat;
208     aCreateTbl[i] = 0;
209     if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
210       if( i<nToOpen ){
211         /* The sqlite_statN table does not exist. Create it. Note that a
212         ** side-effect of the CREATE TABLE statement is to leave the rootpage
213         ** of the new table in register pParse->regRoot. This is important
214         ** because the OpenWrite opcode below will be needing it. */
215         sqlite3NestedParse(pParse,
216             "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
217         );
218         aRoot[i] = (u32)pParse->regRoot;
219         aCreateTbl[i] = OPFLAG_P2ISREG;
220       }
221     }else{
222       /* The table already exists. If zWhere is not NULL, delete all entries
223       ** associated with the table zWhere. If zWhere is NULL, delete the
224       ** entire contents of the table. */
225       aRoot[i] = pStat->tnum;
226       sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
227       if( zWhere ){
228         sqlite3NestedParse(pParse,
229            "DELETE FROM %Q.%s WHERE %s=%Q",
230            pDb->zDbSName, zTab, zWhereType, zWhere
231         );
232 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
233       }else if( db->xPreUpdateCallback ){
234         sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
235 #endif
236       }else{
237         /* The sqlite_stat[134] table already exists.  Delete all rows. */
238         sqlite3VdbeAddOp2(v, OP_Clear, (int)aRoot[i], iDb);
239       }
240     }
241   }
242 
243   /* Open the sqlite_stat[134] tables for writing. */
244   for(i=0; i<nToOpen; i++){
245     assert( i<ArraySize(aTable) );
246     sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, (int)aRoot[i], iDb, 3);
247     sqlite3VdbeChangeP5(v, aCreateTbl[i]);
248     VdbeComment((v, aTable[i].zName));
249   }
250 }
251 
252 /*
253 ** Recommended number of samples for sqlite_stat4
254 */
255 #ifndef SQLITE_STAT4_SAMPLES
256 # define SQLITE_STAT4_SAMPLES 24
257 #endif
258 
259 /*
260 ** Three SQL functions - stat_init(), stat_push(), and stat_get() -
261 ** share an instance of the following structure to hold their state
262 ** information.
263 */
264 typedef struct StatAccum StatAccum;
265 typedef struct StatSample StatSample;
266 struct StatSample {
267   tRowcnt *anEq;                  /* sqlite_stat4.nEq */
268   tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
269 #ifdef SQLITE_ENABLE_STAT4
270   tRowcnt *anLt;                  /* sqlite_stat4.nLt */
271   union {
272     i64 iRowid;                     /* Rowid in main table of the key */
273     u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
274   } u;
275   u32 nRowid;                     /* Sizeof aRowid[] */
276   u8 isPSample;                   /* True if a periodic sample */
277   int iCol;                       /* If !isPSample, the reason for inclusion */
278   u32 iHash;                      /* Tiebreaker hash */
279 #endif
280 };
281 struct StatAccum {
282   sqlite3 *db;              /* Database connection, for malloc() */
283   tRowcnt nEst;             /* Estimated number of rows */
284   tRowcnt nRow;             /* Number of rows visited so far */
285   int nLimit;               /* Analysis row-scan limit */
286   int nCol;                 /* Number of columns in index + pk/rowid */
287   int nKeyCol;              /* Number of index columns w/o the pk/rowid */
288   u8 nSkipAhead;            /* Number of times of skip-ahead */
289   StatSample current;       /* Current row as a StatSample */
290 #ifdef SQLITE_ENABLE_STAT4
291   tRowcnt nPSample;         /* How often to do a periodic sample */
292   int mxSample;             /* Maximum number of samples to accumulate */
293   u32 iPrn;                 /* Pseudo-random number used for sampling */
294   StatSample *aBest;        /* Array of nCol best samples */
295   int iMin;                 /* Index in a[] of entry with minimum score */
296   int nSample;              /* Current number of samples */
297   int nMaxEqZero;           /* Max leading 0 in anEq[] for any a[] entry */
298   int iGet;                 /* Index of current sample accessed by stat_get() */
299   StatSample *a;            /* Array of mxSample StatSample objects */
300 #endif
301 };
302 
303 /* Reclaim memory used by a StatSample
304 */
305 #ifdef SQLITE_ENABLE_STAT4
306 static void sampleClear(sqlite3 *db, StatSample *p){
307   assert( db!=0 );
308   if( p->nRowid ){
309     sqlite3DbFree(db, p->u.aRowid);
310     p->nRowid = 0;
311   }
312 }
313 #endif
314 
315 /* Initialize the BLOB value of a ROWID
316 */
317 #ifdef SQLITE_ENABLE_STAT4
318 static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){
319   assert( db!=0 );
320   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
321   p->u.aRowid = sqlite3DbMallocRawNN(db, n);
322   if( p->u.aRowid ){
323     p->nRowid = n;
324     memcpy(p->u.aRowid, pData, n);
325   }else{
326     p->nRowid = 0;
327   }
328 }
329 #endif
330 
331 /* Initialize the INTEGER value of a ROWID.
332 */
333 #ifdef SQLITE_ENABLE_STAT4
334 static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){
335   assert( db!=0 );
336   if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
337   p->nRowid = 0;
338   p->u.iRowid = iRowid;
339 }
340 #endif
341 
342 
343 /*
344 ** Copy the contents of object (*pFrom) into (*pTo).
345 */
346 #ifdef SQLITE_ENABLE_STAT4
347 static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){
348   pTo->isPSample = pFrom->isPSample;
349   pTo->iCol = pFrom->iCol;
350   pTo->iHash = pFrom->iHash;
351   memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
352   memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
353   memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
354   if( pFrom->nRowid ){
355     sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
356   }else{
357     sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
358   }
359 }
360 #endif
361 
362 /*
363 ** Reclaim all memory of a StatAccum structure.
364 */
365 static void statAccumDestructor(void *pOld){
366   StatAccum *p = (StatAccum*)pOld;
367 #ifdef SQLITE_ENABLE_STAT4
368   if( p->mxSample ){
369     int i;
370     for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
371     for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
372     sampleClear(p->db, &p->current);
373   }
374 #endif
375   sqlite3DbFree(p->db, p);
376 }
377 
378 /*
379 ** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters
380 ** are:
381 **     N:    The number of columns in the index including the rowid/pk (note 1)
382 **     K:    The number of columns in the index excluding the rowid/pk.
383 **     C:    Estimated number of rows in the index
384 **     L:    A limit on the number of rows to scan, or 0 for no-limit
385 **
386 ** Note 1:  In the special case of the covering index that implements a
387 ** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
388 ** total number of columns in the table.
389 **
390 ** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
391 ** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
392 ** PRIMARY KEY of the table.  The covering index that implements the
393 ** original WITHOUT ROWID table as N==K as a special case.
394 **
395 ** This routine allocates the StatAccum object in heap memory. The return
396 ** value is a pointer to the StatAccum object.  The datatype of the
397 ** return value is BLOB, but it is really just a pointer to the StatAccum
398 ** object.
399 */
400 static void statInit(
401   sqlite3_context *context,
402   int argc,
403   sqlite3_value **argv
404 ){
405   StatAccum *p;
406   int nCol;                       /* Number of columns in index being sampled */
407   int nKeyCol;                    /* Number of key columns */
408   int nColUp;                     /* nCol rounded up for alignment */
409   int n;                          /* Bytes of space to allocate */
410   sqlite3 *db = sqlite3_context_db_handle(context);   /* Database connection */
411 #ifdef SQLITE_ENABLE_STAT4
412   /* Maximum number of samples.  0 if STAT4 data is not collected */
413   int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;
414 #endif
415 
416   /* Decode the three function arguments */
417   UNUSED_PARAMETER(argc);
418   nCol = sqlite3_value_int(argv[0]);
419   assert( nCol>0 );
420   nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
421   nKeyCol = sqlite3_value_int(argv[1]);
422   assert( nKeyCol<=nCol );
423   assert( nKeyCol>0 );
424 
425   /* Allocate the space required for the StatAccum object */
426   n = sizeof(*p)
427     + sizeof(tRowcnt)*nColUp                  /* StatAccum.anEq */
428     + sizeof(tRowcnt)*nColUp;                 /* StatAccum.anDLt */
429 #ifdef SQLITE_ENABLE_STAT4
430   if( mxSample ){
431     n += sizeof(tRowcnt)*nColUp                  /* StatAccum.anLt */
432       + sizeof(StatSample)*(nCol+mxSample)       /* StatAccum.aBest[], a[] */
433       + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
434   }
435 #endif
436   p = sqlite3DbMallocZero(db, n);
437   if( p==0 ){
438     sqlite3_result_error_nomem(context);
439     return;
440   }
441 
442   p->db = db;
443   p->nEst = sqlite3_value_int64(argv[2]);
444   p->nRow = 0;
445   p->nLimit = sqlite3_value_int64(argv[3]);
446   p->nCol = nCol;
447   p->nKeyCol = nKeyCol;
448   p->nSkipAhead = 0;
449   p->current.anDLt = (tRowcnt*)&p[1];
450   p->current.anEq = &p->current.anDLt[nColUp];
451 
452 #ifdef SQLITE_ENABLE_STAT4
453   p->mxSample = p->nLimit==0 ? mxSample : 0;
454   if( mxSample ){
455     u8 *pSpace;                     /* Allocated space not yet assigned */
456     int i;                          /* Used to iterate through p->aSample[] */
457 
458     p->iGet = -1;
459     p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
460     p->current.anLt = &p->current.anEq[nColUp];
461     p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
462 
463     /* Set up the StatAccum.a[] and aBest[] arrays */
464     p->a = (struct StatSample*)&p->current.anLt[nColUp];
465     p->aBest = &p->a[mxSample];
466     pSpace = (u8*)(&p->a[mxSample+nCol]);
467     for(i=0; i<(mxSample+nCol); i++){
468       p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
469       p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
470       p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
471     }
472     assert( (pSpace - (u8*)p)==n );
473 
474     for(i=0; i<nCol; i++){
475       p->aBest[i].iCol = i;
476     }
477   }
478 #endif
479 
480   /* Return a pointer to the allocated object to the caller.  Note that
481   ** only the pointer (the 2nd parameter) matters.  The size of the object
482   ** (given by the 3rd parameter) is never used and can be any positive
483   ** value. */
484   sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);
485 }
486 static const FuncDef statInitFuncdef = {
487   4,               /* nArg */
488   SQLITE_UTF8,     /* funcFlags */
489   0,               /* pUserData */
490   0,               /* pNext */
491   statInit,        /* xSFunc */
492   0,               /* xFinalize */
493   0, 0,            /* xValue, xInverse */
494   "stat_init",     /* zName */
495   {0}
496 };
497 
498 #ifdef SQLITE_ENABLE_STAT4
499 /*
500 ** pNew and pOld are both candidate non-periodic samples selected for
501 ** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
502 ** considering only any trailing columns and the sample hash value, this
503 ** function returns true if sample pNew is to be preferred over pOld.
504 ** In other words, if we assume that the cardinalities of the selected
505 ** column for pNew and pOld are equal, is pNew to be preferred over pOld.
506 **
507 ** This function assumes that for each argument sample, the contents of
508 ** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
509 */
510 static int sampleIsBetterPost(
511   StatAccum *pAccum,
512   StatSample *pNew,
513   StatSample *pOld
514 ){
515   int nCol = pAccum->nCol;
516   int i;
517   assert( pNew->iCol==pOld->iCol );
518   for(i=pNew->iCol+1; i<nCol; i++){
519     if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
520     if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
521   }
522   if( pNew->iHash>pOld->iHash ) return 1;
523   return 0;
524 }
525 #endif
526 
527 #ifdef SQLITE_ENABLE_STAT4
528 /*
529 ** Return true if pNew is to be preferred over pOld.
530 **
531 ** This function assumes that for each argument sample, the contents of
532 ** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
533 */
534 static int sampleIsBetter(
535   StatAccum *pAccum,
536   StatSample *pNew,
537   StatSample *pOld
538 ){
539   tRowcnt nEqNew = pNew->anEq[pNew->iCol];
540   tRowcnt nEqOld = pOld->anEq[pOld->iCol];
541 
542   assert( pOld->isPSample==0 && pNew->isPSample==0 );
543   assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
544 
545   if( (nEqNew>nEqOld) ) return 1;
546   if( nEqNew==nEqOld ){
547     if( pNew->iCol<pOld->iCol ) return 1;
548     return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
549   }
550   return 0;
551 }
552 
553 /*
554 ** Copy the contents of sample *pNew into the p->a[] array. If necessary,
555 ** remove the least desirable sample from p->a[] to make room.
556 */
557 static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){
558   StatSample *pSample = 0;
559   int i;
560 
561   assert( IsStat4 || nEqZero==0 );
562 
563   /* StatAccum.nMaxEqZero is set to the maximum number of leading 0
564   ** values in the anEq[] array of any sample in StatAccum.a[]. In
565   ** other words, if nMaxEqZero is n, then it is guaranteed that there
566   ** are no samples with StatSample.anEq[m]==0 for (m>=n). */
567   if( nEqZero>p->nMaxEqZero ){
568     p->nMaxEqZero = nEqZero;
569   }
570   if( pNew->isPSample==0 ){
571     StatSample *pUpgrade = 0;
572     assert( pNew->anEq[pNew->iCol]>0 );
573 
574     /* This sample is being added because the prefix that ends in column
575     ** iCol occurs many times in the table. However, if we have already
576     ** added a sample that shares this prefix, there is no need to add
577     ** this one. Instead, upgrade the priority of the highest priority
578     ** existing sample that shares this prefix.  */
579     for(i=p->nSample-1; i>=0; i--){
580       StatSample *pOld = &p->a[i];
581       if( pOld->anEq[pNew->iCol]==0 ){
582         if( pOld->isPSample ) return;
583         assert( pOld->iCol>pNew->iCol );
584         assert( sampleIsBetter(p, pNew, pOld) );
585         if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
586           pUpgrade = pOld;
587         }
588       }
589     }
590     if( pUpgrade ){
591       pUpgrade->iCol = pNew->iCol;
592       pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
593       goto find_new_min;
594     }
595   }
596 
597   /* If necessary, remove sample iMin to make room for the new sample. */
598   if( p->nSample>=p->mxSample ){
599     StatSample *pMin = &p->a[p->iMin];
600     tRowcnt *anEq = pMin->anEq;
601     tRowcnt *anLt = pMin->anLt;
602     tRowcnt *anDLt = pMin->anDLt;
603     sampleClear(p->db, pMin);
604     memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
605     pSample = &p->a[p->nSample-1];
606     pSample->nRowid = 0;
607     pSample->anEq = anEq;
608     pSample->anDLt = anDLt;
609     pSample->anLt = anLt;
610     p->nSample = p->mxSample-1;
611   }
612 
613   /* The "rows less-than" for the rowid column must be greater than that
614   ** for the last sample in the p->a[] array. Otherwise, the samples would
615   ** be out of order. */
616   assert( p->nSample==0
617        || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
618 
619   /* Insert the new sample */
620   pSample = &p->a[p->nSample];
621   sampleCopy(p, pSample, pNew);
622   p->nSample++;
623 
624   /* Zero the first nEqZero entries in the anEq[] array. */
625   memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
626 
627 find_new_min:
628   if( p->nSample>=p->mxSample ){
629     int iMin = -1;
630     for(i=0; i<p->mxSample; i++){
631       if( p->a[i].isPSample ) continue;
632       if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
633         iMin = i;
634       }
635     }
636     assert( iMin>=0 );
637     p->iMin = iMin;
638   }
639 }
640 #endif /* SQLITE_ENABLE_STAT4 */
641 
642 #ifdef SQLITE_ENABLE_STAT4
643 /*
644 ** Field iChng of the index being scanned has changed. So at this point
645 ** p->current contains a sample that reflects the previous row of the
646 ** index. The value of anEq[iChng] and subsequent anEq[] elements are
647 ** correct at this point.
648 */
649 static void samplePushPrevious(StatAccum *p, int iChng){
650   int i;
651 
652   /* Check if any samples from the aBest[] array should be pushed
653   ** into IndexSample.a[] at this point.  */
654   for(i=(p->nCol-2); i>=iChng; i--){
655     StatSample *pBest = &p->aBest[i];
656     pBest->anEq[i] = p->current.anEq[i];
657     if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
658       sampleInsert(p, pBest, i);
659     }
660   }
661 
662   /* Check that no sample contains an anEq[] entry with an index of
663   ** p->nMaxEqZero or greater set to zero. */
664   for(i=p->nSample-1; i>=0; i--){
665     int j;
666     for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
667   }
668 
669   /* Update the anEq[] fields of any samples already collected. */
670   if( iChng<p->nMaxEqZero ){
671     for(i=p->nSample-1; i>=0; i--){
672       int j;
673       for(j=iChng; j<p->nCol; j++){
674         if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
675       }
676     }
677     p->nMaxEqZero = iChng;
678   }
679 }
680 #endif /* SQLITE_ENABLE_STAT4 */
681 
682 /*
683 ** Implementation of the stat_push SQL function:  stat_push(P,C,R)
684 ** Arguments:
685 **
686 **    P     Pointer to the StatAccum object created by stat_init()
687 **    C     Index of left-most column to differ from previous row
688 **    R     Rowid for the current row.  Might be a key record for
689 **          WITHOUT ROWID tables.
690 **
691 ** The purpose of this routine is to collect statistical data and/or
692 ** samples from the index being analyzed into the StatAccum object.
693 ** The stat_get() SQL function will be used afterwards to
694 ** retrieve the information gathered.
695 **
696 ** This SQL function usually returns NULL, but might return an integer
697 ** if it wants the byte-code to do special processing.
698 **
699 ** The R parameter is only used for STAT4
700 */
701 static void statPush(
702   sqlite3_context *context,
703   int argc,
704   sqlite3_value **argv
705 ){
706   int i;
707 
708   /* The three function arguments */
709   StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
710   int iChng = sqlite3_value_int(argv[1]);
711 
712   UNUSED_PARAMETER( argc );
713   UNUSED_PARAMETER( context );
714   assert( p->nCol>0 );
715   assert( iChng<p->nCol );
716 
717   if( p->nRow==0 ){
718     /* This is the first call to this function. Do initialization. */
719     for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
720   }else{
721     /* Second and subsequent calls get processed here */
722 #ifdef SQLITE_ENABLE_STAT4
723     if( p->mxSample ) samplePushPrevious(p, iChng);
724 #endif
725 
726     /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
727     ** to the current row of the index. */
728     for(i=0; i<iChng; i++){
729       p->current.anEq[i]++;
730     }
731     for(i=iChng; i<p->nCol; i++){
732       p->current.anDLt[i]++;
733 #ifdef SQLITE_ENABLE_STAT4
734       if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
735 #endif
736       p->current.anEq[i] = 1;
737     }
738   }
739 
740   p->nRow++;
741 #ifdef SQLITE_ENABLE_STAT4
742   if( p->mxSample ){
743     tRowcnt nLt;
744     if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
745       sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
746     }else{
747       sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
748                                          sqlite3_value_blob(argv[2]));
749     }
750     p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
751 
752     nLt = p->current.anLt[p->nCol-1];
753     /* Check if this is to be a periodic sample. If so, add it. */
754     if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
755       p->current.isPSample = 1;
756       p->current.iCol = 0;
757       sampleInsert(p, &p->current, p->nCol-1);
758       p->current.isPSample = 0;
759     }
760 
761     /* Update the aBest[] array. */
762     for(i=0; i<(p->nCol-1); i++){
763       p->current.iCol = i;
764       if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
765         sampleCopy(p, &p->aBest[i], &p->current);
766       }
767     }
768   }else
769 #endif
770   if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
771     p->nSkipAhead++;
772     sqlite3_result_int(context, p->current.anDLt[0]>0);
773   }
774 }
775 
776 static const FuncDef statPushFuncdef = {
777   2+IsStat4,       /* nArg */
778   SQLITE_UTF8,     /* funcFlags */
779   0,               /* pUserData */
780   0,               /* pNext */
781   statPush,        /* xSFunc */
782   0,               /* xFinalize */
783   0, 0,            /* xValue, xInverse */
784   "stat_push",     /* zName */
785   {0}
786 };
787 
788 #define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
789 #define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
790 #define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
791 #define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
792 #define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
793 
794 /*
795 ** Implementation of the stat_get(P,J) SQL function.  This routine is
796 ** used to query statistical information that has been gathered into
797 ** the StatAccum object by prior calls to stat_push().  The P parameter
798 ** has type BLOB but it is really just a pointer to the StatAccum object.
799 ** The content to returned is determined by the parameter J
800 ** which is one of the STAT_GET_xxxx values defined above.
801 **
802 ** The stat_get(P,J) function is not available to generic SQL.  It is
803 ** inserted as part of a manually constructed bytecode program.  (See
804 ** the callStatGet() routine below.)  It is guaranteed that the P
805 ** parameter will always be a pointer to a StatAccum object, never a
806 ** NULL.
807 **
808 ** If STAT4 is not enabled, then J is always
809 ** STAT_GET_STAT1 and is hence omitted and this routine becomes
810 ** a one-parameter function, stat_get(P), that always returns the
811 ** stat1 table entry information.
812 */
813 static void statGet(
814   sqlite3_context *context,
815   int argc,
816   sqlite3_value **argv
817 ){
818   StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
819 #ifdef SQLITE_ENABLE_STAT4
820   /* STAT4 has a parameter on this routine. */
821   int eCall = sqlite3_value_int(argv[1]);
822   assert( argc==2 );
823   assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
824        || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
825        || eCall==STAT_GET_NDLT
826   );
827   assert( eCall==STAT_GET_STAT1 || p->mxSample );
828   if( eCall==STAT_GET_STAT1 )
829 #else
830   assert( argc==1 );
831 #endif
832   {
833     /* Return the value to store in the "stat" column of the sqlite_stat1
834     ** table for this index.
835     **
836     ** The value is a string composed of a list of integers describing
837     ** the index. The first integer in the list is the total number of
838     ** entries in the index. There is one additional integer in the list
839     ** for each indexed column. This additional integer is an estimate of
840     ** the number of rows matched by a equality query on the index using
841     ** a key with the corresponding number of fields. In other words,
842     ** if the index is on columns (a,b) and the sqlite_stat1 value is
843     ** "100 10 2", then SQLite estimates that:
844     **
845     **   * the index contains 100 rows,
846     **   * "WHERE a=?" matches 10 rows, and
847     **   * "WHERE a=? AND b=?" matches 2 rows.
848     **
849     ** If D is the count of distinct values and K is the total number of
850     ** rows, then each estimate is computed as:
851     **
852     **        I = (K+D-1)/D
853     */
854     char *z;
855     int i;
856 
857     char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
858     if( zRet==0 ){
859       sqlite3_result_error_nomem(context);
860       return;
861     }
862 
863     sqlite3_snprintf(24, zRet, "%llu",
864         p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
865     z = zRet + sqlite3Strlen30(zRet);
866     for(i=0; i<p->nKeyCol; i++){
867       u64 nDistinct = p->current.anDLt[i] + 1;
868       u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
869       sqlite3_snprintf(24, z, " %llu", iVal);
870       z += sqlite3Strlen30(z);
871       assert( p->current.anEq[i] );
872     }
873     assert( z[0]=='\0' && z>zRet );
874 
875     sqlite3_result_text(context, zRet, -1, sqlite3_free);
876   }
877 #ifdef SQLITE_ENABLE_STAT4
878   else if( eCall==STAT_GET_ROWID ){
879     if( p->iGet<0 ){
880       samplePushPrevious(p, 0);
881       p->iGet = 0;
882     }
883     if( p->iGet<p->nSample ){
884       StatSample *pS = p->a + p->iGet;
885       if( pS->nRowid==0 ){
886         sqlite3_result_int64(context, pS->u.iRowid);
887       }else{
888         sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
889                             SQLITE_TRANSIENT);
890       }
891     }
892   }else{
893     tRowcnt *aCnt = 0;
894 
895     assert( p->iGet<p->nSample );
896     switch( eCall ){
897       case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
898       case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
899       default: {
900         aCnt = p->a[p->iGet].anDLt;
901         p->iGet++;
902         break;
903       }
904     }
905 
906     {
907       char *zRet = sqlite3MallocZero(p->nCol * 25);
908       if( zRet==0 ){
909         sqlite3_result_error_nomem(context);
910       }else{
911         int i;
912         char *z = zRet;
913         for(i=0; i<p->nCol; i++){
914           sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
915           z += sqlite3Strlen30(z);
916         }
917         assert( z[0]=='\0' && z>zRet );
918         z[-1] = '\0';
919         sqlite3_result_text(context, zRet, -1, sqlite3_free);
920       }
921     }
922   }
923 #endif /* SQLITE_ENABLE_STAT4 */
924 #ifndef SQLITE_DEBUG
925   UNUSED_PARAMETER( argc );
926 #endif
927 }
928 static const FuncDef statGetFuncdef = {
929   1+IsStat4,       /* nArg */
930   SQLITE_UTF8,     /* funcFlags */
931   0,               /* pUserData */
932   0,               /* pNext */
933   statGet,         /* xSFunc */
934   0,               /* xFinalize */
935   0, 0,            /* xValue, xInverse */
936   "stat_get",      /* zName */
937   {0}
938 };
939 
940 static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){
941 #ifdef SQLITE_ENABLE_STAT4
942   sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
943 #elif SQLITE_DEBUG
944   assert( iParam==STAT_GET_STAT1 );
945 #else
946   UNUSED_PARAMETER( iParam );
947 #endif
948   assert( regOut!=regStat && regOut!=regStat+1 );
949   sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,
950                              &statGetFuncdef, 0);
951 }
952 
953 #ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
954 /* Add a comment to the most recent VDBE opcode that is the name
955 ** of the k-th column of the pIdx index.
956 */
957 static void analyzeVdbeCommentIndexWithColumnName(
958   Vdbe *v,         /* Prepared statement under construction */
959   Index *pIdx,     /* Index whose column is being loaded */
960   int k            /* Which column index */
961 ){
962   int i;           /* Index of column in the table */
963   assert( k>=0 && k<pIdx->nColumn );
964   i = pIdx->aiColumn[k];
965   if( NEVER(i==XN_ROWID) ){
966     VdbeComment((v,"%s.rowid",pIdx->zName));
967   }else if( i==XN_EXPR ){
968     VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
969   }else{
970     VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zCnName));
971   }
972 }
973 #else
974 # define analyzeVdbeCommentIndexWithColumnName(a,b,c)
975 #endif /* SQLITE_DEBUG */
976 
977 /*
978 ** Generate code to do an analysis of all indices associated with
979 ** a single table.
980 */
981 static void analyzeOneTable(
982   Parse *pParse,   /* Parser context */
983   Table *pTab,     /* Table whose indices are to be analyzed */
984   Index *pOnlyIdx, /* If not NULL, only analyze this one index */
985   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
986   int iMem,        /* Available memory locations begin here */
987   int iTab         /* Next available cursor */
988 ){
989   sqlite3 *db = pParse->db;    /* Database handle */
990   Index *pIdx;                 /* An index to being analyzed */
991   int iIdxCur;                 /* Cursor open on index being analyzed */
992   int iTabCur;                 /* Table cursor */
993   Vdbe *v;                     /* The virtual machine being built up */
994   int i;                       /* Loop counter */
995   int jZeroRows = -1;          /* Jump from here if number of rows is zero */
996   int iDb;                     /* Index of database containing pTab */
997   u8 needTableCnt = 1;         /* True to count the table */
998   int regNewRowid = iMem++;    /* Rowid for the inserted record */
999   int regStat = iMem++;        /* Register to hold StatAccum object */
1000   int regChng = iMem++;        /* Index of changed index field */
1001   int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
1002   int regTemp = iMem++;        /* Temporary use register */
1003   int regTemp2 = iMem++;       /* Second temporary use register */
1004   int regTabname = iMem++;     /* Register containing table name */
1005   int regIdxname = iMem++;     /* Register containing index name */
1006   int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
1007   int regPrev = iMem;          /* MUST BE LAST (see below) */
1008 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1009   Table *pStat1 = 0;
1010 #endif
1011 
1012   pParse->nMem = MAX(pParse->nMem, iMem);
1013   v = sqlite3GetVdbe(pParse);
1014   if( v==0 || NEVER(pTab==0) ){
1015     return;
1016   }
1017   if( pTab->tnum==0 ){
1018     /* Do not gather statistics on views or virtual tables */
1019     return;
1020   }
1021   if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
1022     /* Do not gather statistics on system tables */
1023     return;
1024   }
1025   assert( sqlite3BtreeHoldsAllMutexes(db) );
1026   iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1027   assert( iDb>=0 );
1028   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1029 #ifndef SQLITE_OMIT_AUTHORIZATION
1030   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
1031       db->aDb[iDb].zDbSName ) ){
1032     return;
1033   }
1034 #endif
1035 
1036 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1037   if( db->xPreUpdateCallback ){
1038     pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
1039     if( pStat1==0 ) return;
1040     pStat1->zName = (char*)&pStat1[1];
1041     memcpy(pStat1->zName, "sqlite_stat1", 13);
1042     pStat1->nCol = 3;
1043     pStat1->iPKey = -1;
1044     sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
1045   }
1046 #endif
1047 
1048   /* Establish a read-lock on the table at the shared-cache level.
1049   ** Open a read-only cursor on the table. Also allocate a cursor number
1050   ** to use for scanning indexes (iIdxCur). No index cursor is opened at
1051   ** this time though.  */
1052   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1053   iTabCur = iTab++;
1054   iIdxCur = iTab++;
1055   pParse->nTab = MAX(pParse->nTab, iTab);
1056   sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
1057   sqlite3VdbeLoadString(v, regTabname, pTab->zName);
1058 
1059   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
1060     int nCol;                     /* Number of columns in pIdx. "N" */
1061     int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
1062     int addrNextRow;              /* Address of "next_row:" */
1063     const char *zIdxName;         /* Name of the index */
1064     int nColTest;                 /* Number of columns to test for changes */
1065 
1066     if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
1067     if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
1068     if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
1069       nCol = pIdx->nKeyCol;
1070       zIdxName = pTab->zName;
1071       nColTest = nCol - 1;
1072     }else{
1073       nCol = pIdx->nColumn;
1074       zIdxName = pIdx->zName;
1075       nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
1076     }
1077 
1078     /* Populate the register containing the index name. */
1079     sqlite3VdbeLoadString(v, regIdxname, zIdxName);
1080     VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
1081 
1082     /*
1083     ** Pseudo-code for loop that calls stat_push():
1084     **
1085     **   Rewind csr
1086     **   if eof(csr) goto end_of_scan;
1087     **   regChng = 0
1088     **   goto chng_addr_0;
1089     **
1090     **  next_row:
1091     **   regChng = 0
1092     **   if( idx(0) != regPrev(0) ) goto chng_addr_0
1093     **   regChng = 1
1094     **   if( idx(1) != regPrev(1) ) goto chng_addr_1
1095     **   ...
1096     **   regChng = N
1097     **   goto chng_addr_N
1098     **
1099     **  chng_addr_0:
1100     **   regPrev(0) = idx(0)
1101     **  chng_addr_1:
1102     **   regPrev(1) = idx(1)
1103     **  ...
1104     **
1105     **  endDistinctTest:
1106     **   regRowid = idx(rowid)
1107     **   stat_push(P, regChng, regRowid)
1108     **   Next csr
1109     **   if !eof(csr) goto next_row;
1110     **
1111     **  end_of_scan:
1112     */
1113 
1114     /* Make sure there are enough memory cells allocated to accommodate
1115     ** the regPrev array and a trailing rowid (the rowid slot is required
1116     ** when building a record to insert into the sample column of
1117     ** the sqlite_stat4 table.  */
1118     pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
1119 
1120     /* Open a read-only cursor on the index being analyzed. */
1121     assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
1122     sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
1123     sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
1124     VdbeComment((v, "%s", pIdx->zName));
1125 
1126     /* Invoke the stat_init() function. The arguments are:
1127     **
1128     **    (1) the number of columns in the index including the rowid
1129     **        (or for a WITHOUT ROWID table, the number of PK columns),
1130     **    (2) the number of columns in the key without the rowid/pk
1131     **    (3) estimated number of rows in the index,
1132     */
1133     sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);
1134     assert( regRowid==regStat+2 );
1135     sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
1136 #ifdef SQLITE_ENABLE_STAT4
1137     if( OptimizationEnabled(db, SQLITE_Stat4) ){
1138       sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp);
1139       addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
1140       VdbeCoverage(v);
1141     }else
1142 #endif
1143     {
1144       addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
1145       VdbeCoverage(v);
1146       sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1);
1147     }
1148     assert( regTemp2==regStat+4 );
1149     sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
1150     sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,
1151                                &statInitFuncdef, 0);
1152 
1153     /* Implementation of the following:
1154     **
1155     **   Rewind csr
1156     **   if eof(csr) goto end_of_scan;
1157     **   regChng = 0
1158     **   goto next_push_0;
1159     **
1160     */
1161     sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
1162     addrNextRow = sqlite3VdbeCurrentAddr(v);
1163 
1164     if( nColTest>0 ){
1165       int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
1166       int *aGotoChng;               /* Array of jump instruction addresses */
1167       aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
1168       if( aGotoChng==0 ) continue;
1169 
1170       /*
1171       **  next_row:
1172       **   regChng = 0
1173       **   if( idx(0) != regPrev(0) ) goto chng_addr_0
1174       **   regChng = 1
1175       **   if( idx(1) != regPrev(1) ) goto chng_addr_1
1176       **   ...
1177       **   regChng = N
1178       **   goto endDistinctTest
1179       */
1180       sqlite3VdbeAddOp0(v, OP_Goto);
1181       addrNextRow = sqlite3VdbeCurrentAddr(v);
1182       if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
1183         /* For a single-column UNIQUE index, once we have found a non-NULL
1184         ** row, we know that all the rest will be distinct, so skip
1185         ** subsequent distinctness tests. */
1186         sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
1187         VdbeCoverage(v);
1188       }
1189       for(i=0; i<nColTest; i++){
1190         char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
1191         sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
1192         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
1193         analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
1194         aGotoChng[i] =
1195         sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
1196         sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
1197         VdbeCoverage(v);
1198       }
1199       sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
1200       sqlite3VdbeGoto(v, endDistinctTest);
1201 
1202 
1203       /*
1204       **  chng_addr_0:
1205       **   regPrev(0) = idx(0)
1206       **  chng_addr_1:
1207       **   regPrev(1) = idx(1)
1208       **  ...
1209       */
1210       sqlite3VdbeJumpHere(v, addrNextRow-1);
1211       for(i=0; i<nColTest; i++){
1212         sqlite3VdbeJumpHere(v, aGotoChng[i]);
1213         sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
1214         analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
1215       }
1216       sqlite3VdbeResolveLabel(v, endDistinctTest);
1217       sqlite3DbFree(db, aGotoChng);
1218     }
1219 
1220     /*
1221     **  chng_addr_N:
1222     **   regRowid = idx(rowid)            // STAT4 only
1223     **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT4 only
1224     **   Next csr
1225     **   if !eof(csr) goto next_row;
1226     */
1227 #ifdef SQLITE_ENABLE_STAT4
1228     if( OptimizationEnabled(db, SQLITE_Stat4) ){
1229       assert( regRowid==(regStat+2) );
1230       if( HasRowid(pTab) ){
1231         sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
1232       }else{
1233         Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1234         int j, k, regKey;
1235         regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1236         for(j=0; j<pPk->nKeyCol; j++){
1237           k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
1238           assert( k>=0 && k<pIdx->nColumn );
1239           sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
1240           analyzeVdbeCommentIndexWithColumnName(v,pIdx,k);
1241         }
1242         sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
1243         sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
1244       }
1245     }
1246 #endif
1247     assert( regChng==(regStat+1) );
1248     {
1249       sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,
1250                                  &statPushFuncdef, 0);
1251       if( db->nAnalysisLimit ){
1252         int j1, j2, j3;
1253         j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);
1254         j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);
1255         j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);
1256         VdbeCoverage(v);
1257         sqlite3VdbeJumpHere(v, j1);
1258         sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
1259         sqlite3VdbeJumpHere(v, j2);
1260         sqlite3VdbeJumpHere(v, j3);
1261       }else{
1262         sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
1263       }
1264     }
1265 
1266     /* Add the entry to the stat1 table. */
1267     callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);
1268     assert( "BBB"[0]==SQLITE_AFF_TEXT );
1269     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
1270     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
1271     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
1272 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1273     sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
1274 #endif
1275     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1276 
1277     /* Add the entries to the stat4 table. */
1278 #ifdef SQLITE_ENABLE_STAT4
1279     if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
1280       int regEq = regStat1;
1281       int regLt = regStat1+1;
1282       int regDLt = regStat1+2;
1283       int regSample = regStat1+3;
1284       int regCol = regStat1+4;
1285       int regSampleRowid = regCol + nCol;
1286       int addrNext;
1287       int addrIsNull;
1288       u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
1289 
1290       pParse->nMem = MAX(pParse->nMem, regCol+nCol);
1291 
1292       addrNext = sqlite3VdbeCurrentAddr(v);
1293       callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
1294       addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
1295       VdbeCoverage(v);
1296       callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
1297       callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
1298       callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);
1299       sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
1300       VdbeCoverage(v);
1301       for(i=0; i<nCol; i++){
1302         sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
1303       }
1304       sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
1305       sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
1306       sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
1307       sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
1308       sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
1309       sqlite3VdbeJumpHere(v, addrIsNull);
1310     }
1311 #endif /* SQLITE_ENABLE_STAT4 */
1312 
1313     /* End of analysis */
1314     sqlite3VdbeJumpHere(v, addrRewind);
1315   }
1316 
1317 
1318   /* Create a single sqlite_stat1 entry containing NULL as the index
1319   ** name and the row count as the content.
1320   */
1321   if( pOnlyIdx==0 && needTableCnt ){
1322     VdbeComment((v, "%s", pTab->zName));
1323     sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
1324     jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
1325     sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
1326     assert( "BBB"[0]==SQLITE_AFF_TEXT );
1327     sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
1328     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
1329     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
1330     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1331 #ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1332     sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
1333 #endif
1334     sqlite3VdbeJumpHere(v, jZeroRows);
1335   }
1336 }
1337 
1338 
1339 /*
1340 ** Generate code that will cause the most recent index analysis to
1341 ** be loaded into internal hash tables where is can be used.
1342 */
1343 static void loadAnalysis(Parse *pParse, int iDb){
1344   Vdbe *v = sqlite3GetVdbe(pParse);
1345   if( v ){
1346     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
1347   }
1348 }
1349 
1350 /*
1351 ** Generate code that will do an analysis of an entire database
1352 */
1353 static void analyzeDatabase(Parse *pParse, int iDb){
1354   sqlite3 *db = pParse->db;
1355   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
1356   HashElem *k;
1357   int iStatCur;
1358   int iMem;
1359   int iTab;
1360 
1361   sqlite3BeginWriteOperation(pParse, 0, iDb);
1362   iStatCur = pParse->nTab;
1363   pParse->nTab += 3;
1364   openStatTable(pParse, iDb, iStatCur, 0, 0);
1365   iMem = pParse->nMem+1;
1366   iTab = pParse->nTab;
1367   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1368   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
1369     Table *pTab = (Table*)sqliteHashData(k);
1370     analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
1371   }
1372   loadAnalysis(pParse, iDb);
1373 }
1374 
1375 /*
1376 ** Generate code that will do an analysis of a single table in
1377 ** a database.  If pOnlyIdx is not NULL then it is a single index
1378 ** in pTab that should be analyzed.
1379 */
1380 static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
1381   int iDb;
1382   int iStatCur;
1383 
1384   assert( pTab!=0 );
1385   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
1386   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1387   sqlite3BeginWriteOperation(pParse, 0, iDb);
1388   iStatCur = pParse->nTab;
1389   pParse->nTab += 3;
1390   if( pOnlyIdx ){
1391     openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
1392   }else{
1393     openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
1394   }
1395   analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
1396   loadAnalysis(pParse, iDb);
1397 }
1398 
1399 /*
1400 ** Generate code for the ANALYZE command.  The parser calls this routine
1401 ** when it recognizes an ANALYZE command.
1402 **
1403 **        ANALYZE                            -- 1
1404 **        ANALYZE  <database>                -- 2
1405 **        ANALYZE  ?<database>.?<tablename>  -- 3
1406 **
1407 ** Form 1 causes all indices in all attached databases to be analyzed.
1408 ** Form 2 analyzes all indices the single database named.
1409 ** Form 3 analyzes all indices associated with the named table.
1410 */
1411 void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
1412   sqlite3 *db = pParse->db;
1413   int iDb;
1414   int i;
1415   char *z, *zDb;
1416   Table *pTab;
1417   Index *pIdx;
1418   Token *pTableName;
1419   Vdbe *v;
1420 
1421   /* Read the database schema. If an error occurs, leave an error message
1422   ** and code in pParse and return NULL. */
1423   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
1424   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1425     return;
1426   }
1427 
1428   assert( pName2!=0 || pName1==0 );
1429   if( pName1==0 ){
1430     /* Form 1:  Analyze everything */
1431     for(i=0; i<db->nDb; i++){
1432       if( i==1 ) continue;  /* Do not analyze the TEMP database */
1433       analyzeDatabase(pParse, i);
1434     }
1435   }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
1436     /* Analyze the schema named as the argument */
1437     analyzeDatabase(pParse, iDb);
1438   }else{
1439     /* Form 3: Analyze the table or index named as an argument */
1440     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
1441     if( iDb>=0 ){
1442       zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
1443       z = sqlite3NameFromToken(db, pTableName);
1444       if( z ){
1445         if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
1446           analyzeTable(pParse, pIdx->pTable, pIdx);
1447         }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
1448           analyzeTable(pParse, pTab, 0);
1449         }
1450         sqlite3DbFree(db, z);
1451       }
1452     }
1453   }
1454   if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
1455     sqlite3VdbeAddOp0(v, OP_Expire);
1456   }
1457 }
1458 
1459 /*
1460 ** Used to pass information from the analyzer reader through to the
1461 ** callback routine.
1462 */
1463 typedef struct analysisInfo analysisInfo;
1464 struct analysisInfo {
1465   sqlite3 *db;
1466   const char *zDatabase;
1467 };
1468 
1469 /*
1470 ** The first argument points to a nul-terminated string containing a
1471 ** list of space separated integers. Read the first nOut of these into
1472 ** the array aOut[].
1473 */
1474 static void decodeIntArray(
1475   char *zIntArray,       /* String containing int array to decode */
1476   int nOut,              /* Number of slots in aOut[] */
1477   tRowcnt *aOut,         /* Store integers here */
1478   LogEst *aLog,          /* Or, if aOut==0, here */
1479   Index *pIndex          /* Handle extra flags for this index, if not NULL */
1480 ){
1481   char *z = zIntArray;
1482   int c;
1483   int i;
1484   tRowcnt v;
1485 
1486 #ifdef SQLITE_ENABLE_STAT4
1487   if( z==0 ) z = "";
1488 #else
1489   assert( z!=0 );
1490 #endif
1491   for(i=0; *z && i<nOut; i++){
1492     v = 0;
1493     while( (c=z[0])>='0' && c<='9' ){
1494       v = v*10 + c - '0';
1495       z++;
1496     }
1497 #ifdef SQLITE_ENABLE_STAT4
1498     if( aOut ) aOut[i] = v;
1499     if( aLog ) aLog[i] = sqlite3LogEst(v);
1500 #else
1501     assert( aOut==0 );
1502     UNUSED_PARAMETER(aOut);
1503     assert( aLog!=0 );
1504     aLog[i] = sqlite3LogEst(v);
1505 #endif
1506     if( *z==' ' ) z++;
1507   }
1508 #ifndef SQLITE_ENABLE_STAT4
1509   assert( pIndex!=0 ); {
1510 #else
1511   if( pIndex ){
1512 #endif
1513     pIndex->bUnordered = 0;
1514     pIndex->noSkipScan = 0;
1515     while( z[0] ){
1516       if( sqlite3_strglob("unordered*", z)==0 ){
1517         pIndex->bUnordered = 1;
1518       }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
1519         int sz = sqlite3Atoi(z+3);
1520         if( sz<2 ) sz = 2;
1521         pIndex->szIdxRow = sqlite3LogEst(sz);
1522       }else if( sqlite3_strglob("noskipscan*", z)==0 ){
1523         pIndex->noSkipScan = 1;
1524       }
1525 #ifdef SQLITE_ENABLE_COSTMULT
1526       else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
1527         pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
1528       }
1529 #endif
1530       while( z[0]!=0 && z[0]!=' ' ) z++;
1531       while( z[0]==' ' ) z++;
1532     }
1533   }
1534 }
1535 
1536 /*
1537 ** This callback is invoked once for each index when reading the
1538 ** sqlite_stat1 table.
1539 **
1540 **     argv[0] = name of the table
1541 **     argv[1] = name of the index (might be NULL)
1542 **     argv[2] = results of analysis - on integer for each column
1543 **
1544 ** Entries for which argv[1]==NULL simply record the number of rows in
1545 ** the table.
1546 */
1547 static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
1548   analysisInfo *pInfo = (analysisInfo*)pData;
1549   Index *pIndex;
1550   Table *pTable;
1551   const char *z;
1552 
1553   assert( argc==3 );
1554   UNUSED_PARAMETER2(NotUsed, argc);
1555 
1556   if( argv==0 || argv[0]==0 || argv[2]==0 ){
1557     return 0;
1558   }
1559   pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
1560   if( pTable==0 ){
1561     return 0;
1562   }
1563   if( argv[1]==0 ){
1564     pIndex = 0;
1565   }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
1566     pIndex = sqlite3PrimaryKeyIndex(pTable);
1567   }else{
1568     pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
1569   }
1570   z = argv[2];
1571 
1572   if( pIndex ){
1573     tRowcnt *aiRowEst = 0;
1574     int nCol = pIndex->nKeyCol+1;
1575 #ifdef SQLITE_ENABLE_STAT4
1576     /* Index.aiRowEst may already be set here if there are duplicate
1577     ** sqlite_stat1 entries for this index. In that case just clobber
1578     ** the old data with the new instead of allocating a new array.  */
1579     if( pIndex->aiRowEst==0 ){
1580       pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
1581       if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
1582     }
1583     aiRowEst = pIndex->aiRowEst;
1584 #endif
1585     pIndex->bUnordered = 0;
1586     decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
1587     pIndex->hasStat1 = 1;
1588     if( pIndex->pPartIdxWhere==0 ){
1589       pTable->nRowLogEst = pIndex->aiRowLogEst[0];
1590       pTable->tabFlags |= TF_HasStat1;
1591     }
1592   }else{
1593     Index fakeIdx;
1594     fakeIdx.szIdxRow = pTable->szTabRow;
1595 #ifdef SQLITE_ENABLE_COSTMULT
1596     fakeIdx.pTable = pTable;
1597 #endif
1598     decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
1599     pTable->szTabRow = fakeIdx.szIdxRow;
1600     pTable->tabFlags |= TF_HasStat1;
1601   }
1602 
1603   return 0;
1604 }
1605 
1606 /*
1607 ** If the Index.aSample variable is not NULL, delete the aSample[] array
1608 ** and its contents.
1609 */
1610 void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
1611 #ifdef SQLITE_ENABLE_STAT4
1612   if( pIdx->aSample ){
1613     int j;
1614     for(j=0; j<pIdx->nSample; j++){
1615       IndexSample *p = &pIdx->aSample[j];
1616       sqlite3DbFree(db, p->p);
1617     }
1618     sqlite3DbFree(db, pIdx->aSample);
1619   }
1620   if( db && db->pnBytesFreed==0 ){
1621     pIdx->nSample = 0;
1622     pIdx->aSample = 0;
1623   }
1624 #else
1625   UNUSED_PARAMETER(db);
1626   UNUSED_PARAMETER(pIdx);
1627 #endif /* SQLITE_ENABLE_STAT4 */
1628 }
1629 
1630 #ifdef SQLITE_ENABLE_STAT4
1631 /*
1632 ** Populate the pIdx->aAvgEq[] array based on the samples currently
1633 ** stored in pIdx->aSample[].
1634 */
1635 static void initAvgEq(Index *pIdx){
1636   if( pIdx ){
1637     IndexSample *aSample = pIdx->aSample;
1638     IndexSample *pFinal = &aSample[pIdx->nSample-1];
1639     int iCol;
1640     int nCol = 1;
1641     if( pIdx->nSampleCol>1 ){
1642       /* If this is stat4 data, then calculate aAvgEq[] values for all
1643       ** sample columns except the last. The last is always set to 1, as
1644       ** once the trailing PK fields are considered all index keys are
1645       ** unique.  */
1646       nCol = pIdx->nSampleCol-1;
1647       pIdx->aAvgEq[nCol] = 1;
1648     }
1649     for(iCol=0; iCol<nCol; iCol++){
1650       int nSample = pIdx->nSample;
1651       int i;                    /* Used to iterate through samples */
1652       tRowcnt sumEq = 0;        /* Sum of the nEq values */
1653       tRowcnt avgEq = 0;
1654       tRowcnt nRow;             /* Number of rows in index */
1655       i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
1656       i64 nDist100;             /* Number of distinct values in index */
1657 
1658       if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
1659         nRow = pFinal->anLt[iCol];
1660         nDist100 = (i64)100 * pFinal->anDLt[iCol];
1661         nSample--;
1662       }else{
1663         nRow = pIdx->aiRowEst[0];
1664         nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
1665       }
1666       pIdx->nRowEst0 = nRow;
1667 
1668       /* Set nSum to the number of distinct (iCol+1) field prefixes that
1669       ** occur in the stat4 table for this index. Set sumEq to the sum of
1670       ** the nEq values for column iCol for the same set (adding the value
1671       ** only once where there exist duplicate prefixes).  */
1672       for(i=0; i<nSample; i++){
1673         if( i==(pIdx->nSample-1)
1674          || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
1675         ){
1676           sumEq += aSample[i].anEq[iCol];
1677           nSum100 += 100;
1678         }
1679       }
1680 
1681       if( nDist100>nSum100 && sumEq<nRow ){
1682         avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
1683       }
1684       if( avgEq==0 ) avgEq = 1;
1685       pIdx->aAvgEq[iCol] = avgEq;
1686     }
1687   }
1688 }
1689 
1690 /*
1691 ** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
1692 ** is supplied instead, find the PRIMARY KEY index for that table.
1693 */
1694 static Index *findIndexOrPrimaryKey(
1695   sqlite3 *db,
1696   const char *zName,
1697   const char *zDb
1698 ){
1699   Index *pIdx = sqlite3FindIndex(db, zName, zDb);
1700   if( pIdx==0 ){
1701     Table *pTab = sqlite3FindTable(db, zName, zDb);
1702     if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
1703   }
1704   return pIdx;
1705 }
1706 
1707 /*
1708 ** Load the content from either the sqlite_stat4
1709 ** into the relevant Index.aSample[] arrays.
1710 **
1711 ** Arguments zSql1 and zSql2 must point to SQL statements that return
1712 ** data equivalent to the following:
1713 **
1714 **    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1715 **    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1716 **
1717 ** where %Q is replaced with the database name before the SQL is executed.
1718 */
1719 static int loadStatTbl(
1720   sqlite3 *db,                  /* Database handle */
1721   const char *zSql1,            /* SQL statement 1 (see above) */
1722   const char *zSql2,            /* SQL statement 2 (see above) */
1723   const char *zDb               /* Database name (e.g. "main") */
1724 ){
1725   int rc;                       /* Result codes from subroutines */
1726   sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
1727   char *zSql;                   /* Text of the SQL statement */
1728   Index *pPrevIdx = 0;          /* Previous index in the loop */
1729   IndexSample *pSample;         /* A slot in pIdx->aSample[] */
1730 
1731   assert( db->lookaside.bDisable );
1732   zSql = sqlite3MPrintf(db, zSql1, zDb);
1733   if( !zSql ){
1734     return SQLITE_NOMEM_BKPT;
1735   }
1736   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1737   sqlite3DbFree(db, zSql);
1738   if( rc ) return rc;
1739 
1740   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1741     int nIdxCol = 1;              /* Number of columns in stat4 records */
1742 
1743     char *zIndex;   /* Index name */
1744     Index *pIdx;    /* Pointer to the index object */
1745     int nSample;    /* Number of samples */
1746     int nByte;      /* Bytes of space required */
1747     int i;          /* Bytes of space required */
1748     tRowcnt *pSpace;
1749 
1750     zIndex = (char *)sqlite3_column_text(pStmt, 0);
1751     if( zIndex==0 ) continue;
1752     nSample = sqlite3_column_int(pStmt, 1);
1753     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
1754     assert( pIdx==0 || pIdx->nSample==0 );
1755     if( pIdx==0 ) continue;
1756     assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
1757     if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
1758       nIdxCol = pIdx->nKeyCol;
1759     }else{
1760       nIdxCol = pIdx->nColumn;
1761     }
1762     pIdx->nSampleCol = nIdxCol;
1763     nByte = sizeof(IndexSample) * nSample;
1764     nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
1765     nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
1766 
1767     pIdx->aSample = sqlite3DbMallocZero(db, nByte);
1768     if( pIdx->aSample==0 ){
1769       sqlite3_finalize(pStmt);
1770       return SQLITE_NOMEM_BKPT;
1771     }
1772     pSpace = (tRowcnt*)&pIdx->aSample[nSample];
1773     pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
1774     pIdx->pTable->tabFlags |= TF_HasStat4;
1775     for(i=0; i<nSample; i++){
1776       pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1777       pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1778       pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
1779     }
1780     assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
1781   }
1782   rc = sqlite3_finalize(pStmt);
1783   if( rc ) return rc;
1784 
1785   zSql = sqlite3MPrintf(db, zSql2, zDb);
1786   if( !zSql ){
1787     return SQLITE_NOMEM_BKPT;
1788   }
1789   rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1790   sqlite3DbFree(db, zSql);
1791   if( rc ) return rc;
1792 
1793   while( sqlite3_step(pStmt)==SQLITE_ROW ){
1794     char *zIndex;                 /* Index name */
1795     Index *pIdx;                  /* Pointer to the index object */
1796     int nCol = 1;                 /* Number of columns in index */
1797 
1798     zIndex = (char *)sqlite3_column_text(pStmt, 0);
1799     if( zIndex==0 ) continue;
1800     pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
1801     if( pIdx==0 ) continue;
1802     /* This next condition is true if data has already been loaded from
1803     ** the sqlite_stat4 table. */
1804     nCol = pIdx->nSampleCol;
1805     if( pIdx!=pPrevIdx ){
1806       initAvgEq(pPrevIdx);
1807       pPrevIdx = pIdx;
1808     }
1809     pSample = &pIdx->aSample[pIdx->nSample];
1810     decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
1811     decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
1812     decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
1813 
1814     /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
1815     ** This is in case the sample record is corrupted. In that case, the
1816     ** sqlite3VdbeRecordCompare() may read up to two varints past the
1817     ** end of the allocated buffer before it realizes it is dealing with
1818     ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
1819     ** a buffer overread.  */
1820     pSample->n = sqlite3_column_bytes(pStmt, 4);
1821     pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
1822     if( pSample->p==0 ){
1823       sqlite3_finalize(pStmt);
1824       return SQLITE_NOMEM_BKPT;
1825     }
1826     if( pSample->n ){
1827       memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
1828     }
1829     pIdx->nSample++;
1830   }
1831   rc = sqlite3_finalize(pStmt);
1832   if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
1833   return rc;
1834 }
1835 
1836 /*
1837 ** Load content from the sqlite_stat4 table into
1838 ** the Index.aSample[] arrays of all indices.
1839 */
1840 static int loadStat4(sqlite3 *db, const char *zDb){
1841   int rc = SQLITE_OK;             /* Result codes from subroutines */
1842   const Table *pStat4;
1843 
1844   assert( db->lookaside.bDisable );
1845   if( (pStat4 = sqlite3FindTable(db, "sqlite_stat4", zDb))!=0
1846    && IsOrdinaryTable(pStat4)
1847   ){
1848     rc = loadStatTbl(db,
1849       "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
1850       "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1851       zDb
1852     );
1853   }
1854   return rc;
1855 }
1856 #endif /* SQLITE_ENABLE_STAT4 */
1857 
1858 /*
1859 ** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
1860 ** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
1861 ** arrays. The contents of sqlite_stat4 are used to populate the
1862 ** Index.aSample[] arrays.
1863 **
1864 ** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
1865 ** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
1866 ** during compilation and the sqlite_stat4 table is present, no data is
1867 ** read from it.
1868 **
1869 ** If SQLITE_ENABLE_STAT4 was defined during compilation and the
1870 ** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
1871 ** returned. However, in this case, data is read from the sqlite_stat1
1872 ** table (if it is present) before returning.
1873 **
1874 ** If an OOM error occurs, this function always sets db->mallocFailed.
1875 ** This means if the caller does not care about other errors, the return
1876 ** code may be ignored.
1877 */
1878 int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
1879   analysisInfo sInfo;
1880   HashElem *i;
1881   char *zSql;
1882   int rc = SQLITE_OK;
1883   Schema *pSchema = db->aDb[iDb].pSchema;
1884   const Table *pStat1;
1885 
1886   assert( iDb>=0 && iDb<db->nDb );
1887   assert( db->aDb[iDb].pBt!=0 );
1888 
1889   /* Clear any prior statistics */
1890   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1891   for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
1892     Table *pTab = sqliteHashData(i);
1893     pTab->tabFlags &= ~TF_HasStat1;
1894   }
1895   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
1896     Index *pIdx = sqliteHashData(i);
1897     pIdx->hasStat1 = 0;
1898 #ifdef SQLITE_ENABLE_STAT4
1899     sqlite3DeleteIndexSamples(db, pIdx);
1900     pIdx->aSample = 0;
1901 #endif
1902   }
1903 
1904   /* Load new statistics out of the sqlite_stat1 table */
1905   sInfo.db = db;
1906   sInfo.zDatabase = db->aDb[iDb].zDbSName;
1907   if( (pStat1 = sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase))
1908    && IsOrdinaryTable(pStat1)
1909   ){
1910     zSql = sqlite3MPrintf(db,
1911         "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
1912     if( zSql==0 ){
1913       rc = SQLITE_NOMEM_BKPT;
1914     }else{
1915       rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
1916       sqlite3DbFree(db, zSql);
1917     }
1918   }
1919 
1920   /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
1921   assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1922   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
1923     Index *pIdx = sqliteHashData(i);
1924     if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
1925   }
1926 
1927   /* Load the statistics from the sqlite_stat4 table. */
1928 #ifdef SQLITE_ENABLE_STAT4
1929   if( rc==SQLITE_OK ){
1930     DisableLookaside;
1931     rc = loadStat4(db, sInfo.zDatabase);
1932     EnableLookaside;
1933   }
1934   for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
1935     Index *pIdx = sqliteHashData(i);
1936     sqlite3_free(pIdx->aiRowEst);
1937     pIdx->aiRowEst = 0;
1938   }
1939 #endif
1940 
1941   if( rc==SQLITE_NOMEM ){
1942     sqlite3OomFault(db);
1943   }
1944   return rc;
1945 }
1946 
1947 
1948 #endif /* SQLITE_OMIT_ANALYZE */
1949