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