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