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