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