analyze.c

Go to the documentation of this file.
00001 /*
00002 ** 2005 July 8
00003 **
00004 ** The author disclaims copyright to this source code.  In place of
00005 ** a legal notice, here is a blessing:
00006 **
00007 **    May you do good and not evil.
00008 **    May you find forgiveness for yourself and forgive others.
00009 **    May you share freely, never taking more than you give.
00010 **
00011 *************************************************************************
00012 ** This file contains code associated with the ANALYZE command.
00013 **
00014 ** @(#) $Id: analyze.c,v 1.44 2008/11/03 20:55:07 drh Exp $
00015 */
00016 #ifndef SQLITE_OMIT_ANALYZE
00017 #include "sqliteInt.h"
00018 
00019 /*
00020 ** This routine generates code that opens the sqlite_stat1 table on cursor
00021 ** iStatCur.
00022 **
00023 ** If the sqlite_stat1 tables does not previously exist, it is created.
00024 ** If it does previously exist, all entires associated with table zWhere
00025 ** are removed.  If zWhere==0 then all entries are removed.
00026 */
00027 static void openStatTable(
00028   Parse *pParse,          /* Parsing context */
00029   int iDb,                /* The database we are looking in */
00030   int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
00031   const char *zWhere      /* Delete entries associated with this table */
00032 ){
00033   sqlite3 *db = pParse->db;
00034   Db *pDb;
00035   int iRootPage;
00036   int createStat1 = 0;
00037   Table *pStat;
00038   Vdbe *v = sqlite3GetVdbe(pParse);
00039 
00040   if( v==0 ) return;
00041   assert( sqlite3BtreeHoldsAllMutexes(db) );
00042   assert( sqlite3VdbeDb(v)==db );
00043   pDb = &db->aDb[iDb];
00044   if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
00045     /* The sqlite_stat1 tables does not exist.  Create it.  
00046     ** Note that a side-effect of the CREATE TABLE statement is to leave
00047     ** the rootpage of the new table in register pParse->regRoot.  This is
00048     ** important because the OpenWrite opcode below will be needing it. */
00049     sqlite3NestedParse(pParse,
00050       "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
00051       pDb->zName
00052     );
00053     iRootPage = pParse->regRoot;
00054     createStat1 = 1;  /* Cause rootpage to be taken from top of stack */
00055   }else if( zWhere ){
00056     /* The sqlite_stat1 table exists.  Delete all entries associated with
00057     ** the table zWhere. */
00058     sqlite3NestedParse(pParse,
00059        "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
00060        pDb->zName, zWhere
00061     );
00062     iRootPage = pStat->tnum;
00063   }else{
00064     /* The sqlite_stat1 table already exists.  Delete all rows. */
00065     iRootPage = pStat->tnum;
00066     sqlite3VdbeAddOp2(v, OP_Clear, pStat->tnum, iDb);
00067   }
00068 
00069   /* Open the sqlite_stat1 table for writing. Unless it was created
00070   ** by this vdbe program, lock it for writing at the shared-cache level. 
00071   ** If this vdbe did create the sqlite_stat1 table, then it must have 
00072   ** already obtained a schema-lock, making the write-lock redundant.
00073   */
00074   if( !createStat1 ){
00075     sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
00076   }
00077   sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, 3);
00078   sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur, iRootPage, iDb);
00079   sqlite3VdbeChangeP5(v, createStat1);
00080 }
00081 
00082 /*
00083 ** Generate code to do an analysis of all indices associated with
00084 ** a single table.
00085 */
00086 static void analyzeOneTable(
00087   Parse *pParse,   /* Parser context */
00088   Table *pTab,     /* Table whose indices are to be analyzed */
00089   int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
00090   int iMem         /* Available memory locations begin here */
00091 ){
00092   Index *pIdx;     /* An index to being analyzed */
00093   int iIdxCur;     /* Index of VdbeCursor for index being analyzed */
00094   int nCol;        /* Number of columns in the index */
00095   Vdbe *v;         /* The virtual machine being built up */
00096   int i;           /* Loop counter */
00097   int topOfLoop;   /* The top of the loop */
00098   int endOfLoop;   /* The end of the loop */
00099   int addr;        /* The address of an instruction */
00100   int iDb;         /* Index of database containing pTab */
00101 
00102   v = sqlite3GetVdbe(pParse);
00103   if( v==0 || pTab==0 || pTab->pIndex==0 ){
00104     /* Do no analysis for tables that have no indices */
00105     return;
00106   }
00107   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
00108   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
00109   assert( iDb>=0 );
00110 #ifndef SQLITE_OMIT_AUTHORIZATION
00111   if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
00112       pParse->db->aDb[iDb].zName ) ){
00113     return;
00114   }
00115 #endif
00116 
00117   /* Establish a read-lock on the table at the shared-cache level. */
00118   sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
00119 
00120   iIdxCur = pParse->nTab;
00121   for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
00122     KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
00123     int regFields;    /* Register block for building records */
00124     int regRec;       /* Register holding completed record */
00125     int regTemp;      /* Temporary use register */
00126     int regCol;       /* Content of a column from the table being analyzed */
00127     int regRowid;     /* Rowid for the inserted record */
00128     int regF2;
00129 
00130     /* Open a cursor to the index to be analyzed
00131     */
00132     assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
00133     nCol = pIdx->nColumn;
00134     sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, nCol+1);
00135     sqlite3VdbeAddOp4(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb,
00136         (char *)pKey, P4_KEYINFO_HANDOFF);
00137     VdbeComment((v, "%s", pIdx->zName));
00138     regFields = iMem+nCol*2;
00139     regTemp = regRowid = regCol = regFields+3;
00140     regRec = regCol+1;
00141     if( regRec>pParse->nMem ){
00142       pParse->nMem = regRec;
00143     }
00144 
00145     /* Memory cells are used as follows:
00146     **
00147     **    mem[iMem]:             The total number of rows in the table.
00148     **    mem[iMem+1]:           Number of distinct values in column 1
00149     **    ...
00150     **    mem[iMem+nCol]:        Number of distinct values in column N
00151     **    mem[iMem+nCol+1]       Last observed value of column 1
00152     **    ...
00153     **    mem[iMem+nCol+nCol]:   Last observed value of column N
00154     **
00155     ** Cells iMem through iMem+nCol are initialized to 0.  The others
00156     ** are initialized to NULL.
00157     */
00158     for(i=0; i<=nCol; i++){
00159       sqlite3VdbeAddOp2(v, OP_Integer, 0, iMem+i);
00160     }
00161     for(i=0; i<nCol; i++){
00162       sqlite3VdbeAddOp2(v, OP_Null, 0, iMem+nCol+i+1);
00163     }
00164 
00165     /* Do the analysis.
00166     */
00167     endOfLoop = sqlite3VdbeMakeLabel(v);
00168     sqlite3VdbeAddOp2(v, OP_Rewind, iIdxCur, endOfLoop);
00169     topOfLoop = sqlite3VdbeCurrentAddr(v);
00170     sqlite3VdbeAddOp2(v, OP_AddImm, iMem, 1);
00171     for(i=0; i<nCol; i++){
00172       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regCol);
00173       sqlite3VdbeAddOp3(v, OP_Ne, regCol, 0, iMem+nCol+i+1);
00174       /**** TODO:  add collating sequence *****/
00175       sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
00176     }
00177     sqlite3VdbeAddOp2(v, OP_Goto, 0, endOfLoop);
00178     for(i=0; i<nCol; i++){
00179       sqlite3VdbeJumpHere(v, topOfLoop + 2*(i + 1));
00180       sqlite3VdbeAddOp2(v, OP_AddImm, iMem+i+1, 1);
00181       sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, iMem+nCol+i+1);
00182     }
00183     sqlite3VdbeResolveLabel(v, endOfLoop);
00184     sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, topOfLoop);
00185     sqlite3VdbeAddOp1(v, OP_Close, iIdxCur);
00186 
00187     /* Store the results.  
00188     **
00189     ** The result is a single row of the sqlite_stat1 table.  The first
00190     ** two columns are the names of the table and index.  The third column
00191     ** is a string composed of a list of integer statistics about the
00192     ** index.  The first integer in the list is the total number of entires
00193     ** in the index.  There is one additional integer in the list for each
00194     ** column of the table.  This additional integer is a guess of how many
00195     ** rows of the table the index will select.  If D is the count of distinct
00196     ** values and K is the total number of rows, then the integer is computed
00197     ** as:
00198     **
00199     **        I = (K+D-1)/D
00200     **
00201     ** If K==0 then no entry is made into the sqlite_stat1 table.  
00202     ** If K>0 then it is always the case the D>0 so division by zero
00203     ** is never possible.
00204     */
00205     addr = sqlite3VdbeAddOp1(v, OP_IfNot, iMem);
00206     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields, 0, pTab->zName, 0);
00207     sqlite3VdbeAddOp4(v, OP_String8, 0, regFields+1, 0, pIdx->zName, 0);
00208     regF2 = regFields+2;
00209     sqlite3VdbeAddOp2(v, OP_SCopy, iMem, regF2);
00210     for(i=0; i<nCol; i++){
00211       sqlite3VdbeAddOp4(v, OP_String8, 0, regTemp, 0, " ", 0);
00212       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
00213       sqlite3VdbeAddOp3(v, OP_Add, iMem, iMem+i+1, regTemp);
00214       sqlite3VdbeAddOp2(v, OP_AddImm, regTemp, -1);
00215       sqlite3VdbeAddOp3(v, OP_Divide, iMem+i+1, regTemp, regTemp);
00216       sqlite3VdbeAddOp1(v, OP_ToInt, regTemp);
00217       sqlite3VdbeAddOp3(v, OP_Concat, regTemp, regF2, regF2);
00218     }
00219     sqlite3VdbeAddOp4(v, OP_MakeRecord, regFields, 3, regRec, "aaa", 0);
00220     sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regRowid);
00221     sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regRec, regRowid);
00222     sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
00223     sqlite3VdbeJumpHere(v, addr);
00224   }
00225 }
00226 
00227 /*
00228 ** Generate code that will cause the most recent index analysis to
00229 ** be laoded into internal hash tables where is can be used.
00230 */
00231 static void loadAnalysis(Parse *pParse, int iDb){
00232   Vdbe *v = sqlite3GetVdbe(pParse);
00233   if( v ){
00234     sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
00235   }
00236 }
00237 
00238 /*
00239 ** Generate code that will do an analysis of an entire database
00240 */
00241 static void analyzeDatabase(Parse *pParse, int iDb){
00242   sqlite3 *db = pParse->db;
00243   Schema *pSchema = db->aDb[iDb].pSchema;    /* Schema of database iDb */
00244   HashElem *k;
00245   int iStatCur;
00246   int iMem;
00247 
00248   sqlite3BeginWriteOperation(pParse, 0, iDb);
00249   iStatCur = pParse->nTab++;
00250   openStatTable(pParse, iDb, iStatCur, 0);
00251   iMem = pParse->nMem+1;
00252   for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
00253     Table *pTab = (Table*)sqliteHashData(k);
00254     analyzeOneTable(pParse, pTab, iStatCur, iMem);
00255   }
00256   loadAnalysis(pParse, iDb);
00257 }
00258 
00259 /*
00260 ** Generate code that will do an analysis of a single table in
00261 ** a database.
00262 */
00263 static void analyzeTable(Parse *pParse, Table *pTab){
00264   int iDb;
00265   int iStatCur;
00266 
00267   assert( pTab!=0 );
00268   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
00269   iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
00270   sqlite3BeginWriteOperation(pParse, 0, iDb);
00271   iStatCur = pParse->nTab++;
00272   openStatTable(pParse, iDb, iStatCur, pTab->zName);
00273   analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem+1);
00274   loadAnalysis(pParse, iDb);
00275 }
00276 
00277 /*
00278 ** Generate code for the ANALYZE command.  The parser calls this routine
00279 ** when it recognizes an ANALYZE command.
00280 **
00281 **        ANALYZE                            -- 1
00282 **        ANALYZE  <database>                -- 2
00283 **        ANALYZE  ?<database>.?<tablename>  -- 3
00284 **
00285 ** Form 1 causes all indices in all attached databases to be analyzed.
00286 ** Form 2 analyzes all indices the single database named.
00287 ** Form 3 analyzes all indices associated with the named table.
00288 */
00289 void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
00290   sqlite3 *db = pParse->db;
00291   int iDb;
00292   int i;
00293   char *z, *zDb;
00294   Table *pTab;
00295   Token *pTableName;
00296 
00297   /* Read the database schema. If an error occurs, leave an error message
00298   ** and code in pParse and return NULL. */
00299   assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
00300   if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
00301     return;
00302   }
00303 
00304   if( pName1==0 ){
00305     /* Form 1:  Analyze everything */
00306     for(i=0; i<db->nDb; i++){
00307       if( i==1 ) continue;  /* Do not analyze the TEMP database */
00308       analyzeDatabase(pParse, i);
00309     }
00310   }else if( pName2==0 || pName2->n==0 ){
00311     /* Form 2:  Analyze the database or table named */
00312     iDb = sqlite3FindDb(db, pName1);
00313     if( iDb>=0 ){
00314       analyzeDatabase(pParse, iDb);
00315     }else{
00316       z = sqlite3NameFromToken(db, pName1);
00317       if( z ){
00318         pTab = sqlite3LocateTable(pParse, 0, z, 0);
00319         sqlite3DbFree(db, z);
00320         if( pTab ){
00321           analyzeTable(pParse, pTab);
00322         }
00323       }
00324     }
00325   }else{
00326     /* Form 3: Analyze the fully qualified table name */
00327     iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
00328     if( iDb>=0 ){
00329       zDb = db->aDb[iDb].zName;
00330       z = sqlite3NameFromToken(db, pTableName);
00331       if( z ){
00332         pTab = sqlite3LocateTable(pParse, 0, z, zDb);
00333         sqlite3DbFree(db, z);
00334         if( pTab ){
00335           analyzeTable(pParse, pTab);
00336         }
00337       }
00338     }   
00339   }
00340 }
00341 
00342 /*
00343 ** Used to pass information from the analyzer reader through to the
00344 ** callback routine.
00345 */
00346 typedef struct analysisInfo analysisInfo;
00347 struct analysisInfo {
00348   sqlite3 *db;
00349   const char *zDatabase;
00350 };
00351 
00352 /*
00353 ** This callback is invoked once for each index when reading the
00354 ** sqlite_stat1 table.  
00355 **
00356 **     argv[0] = name of the index
00357 **     argv[1] = results of analysis - on integer for each column
00358 */
00359 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
00360   analysisInfo *pInfo = (analysisInfo*)pData;
00361   Index *pIndex;
00362   int i, c;
00363   unsigned int v;
00364   const char *z;
00365 
00366   assert( argc==2 );
00367   if( argv==0 || argv[0]==0 || argv[1]==0 ){
00368     return 0;
00369   }
00370   pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
00371   if( pIndex==0 ){
00372     return 0;
00373   }
00374   z = argv[1];
00375   for(i=0; *z && i<=pIndex->nColumn; i++){
00376     v = 0;
00377     while( (c=z[0])>='0' && c<='9' ){
00378       v = v*10 + c - '0';
00379       z++;
00380     }
00381     pIndex->aiRowEst[i] = v;
00382     if( *z==' ' ) z++;
00383   }
00384   return 0;
00385 }
00386 
00387 /*
00388 ** Load the content of the sqlite_stat1 table into the index hash tables.
00389 */
00390 int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
00391   analysisInfo sInfo;
00392   HashElem *i;
00393   char *zSql;
00394   int rc;
00395 
00396   assert( iDb>=0 && iDb<db->nDb );
00397   assert( db->aDb[iDb].pBt!=0 );
00398   assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
00399 
00400   /* Clear any prior statistics */
00401   for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
00402     Index *pIdx = sqliteHashData(i);
00403     sqlite3DefaultRowEst(pIdx);
00404   }
00405 
00406   /* Check to make sure the sqlite_stat1 table existss */
00407   sInfo.db = db;
00408   sInfo.zDatabase = db->aDb[iDb].zName;
00409   if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
00410      return SQLITE_ERROR;
00411   }
00412 
00413 
00414   /* Load new statistics out of the sqlite_stat1 table */
00415   zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
00416                         sInfo.zDatabase);
00417   (void)sqlite3SafetyOff(db);
00418   rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
00419   (void)sqlite3SafetyOn(db);
00420   sqlite3DbFree(db, zSql);
00421   return rc;
00422 }
00423 
00424 
00425 #endif /* SQLITE_OMIT_ANALYZE */

ContextLogger2—ContextLogger2 Logger Daemon Internals—Generated on Mon May 2 13:49:51 2011 by Doxygen 1.6.1