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