4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
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.
16 #ifndef SQLITE_OMIT_ANALYZE
17 #include "sqliteInt.h"
20 ** This routine generates code that opens the sqlite_stat1 table on cursor
23 ** If the sqlite_stat1 tables does not previously exist, it is created.
24 ** If it does previously exist, all entires associated with table zWhere
25 ** are removed. If zWhere==0 then all entries are removed.
27 static void openStatTable(
28 Parse *pParse, /* Parsing context */
29 int iDb, /* The database we are looking in */
30 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
31 const char *zWhere /* Delete entries associated with this table */
33 sqlite3 *db = pParse->db;
37 Vdbe *v = sqlite3GetVdbe(pParse);
40 assert( sqlite3BtreeHoldsAllMutexes(db) );
41 assert( sqlite3VdbeDb(v)==db );
43 if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
44 /* The sqlite_stat1 tables does not exist. Create it.
45 ** Note that a side-effect of the CREATE TABLE statement is to leave
46 ** the rootpage of the new table on the top of the stack. This is
47 ** important because the OpenWrite opcode below will be needing it. */
48 sqlite3NestedParse(pParse,
49 "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
52 iRootPage = 0; /* Cause rootpage to be taken from top of stack */
54 /* The sqlite_stat1 table exists. Delete all entries associated with
55 ** the table zWhere. */
56 sqlite3NestedParse(pParse,
57 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
60 iRootPage = pStat->tnum;
62 /* The sqlite_stat1 table already exists. Delete all rows. */
63 iRootPage = pStat->tnum;
64 sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb);
67 /* Open the sqlite_stat1 table for writing. Unless it was created
68 ** by this vdbe program, lock it for writing at the shared-cache level.
69 ** If this vdbe did create the sqlite_stat1 table, then it must have
70 ** already obtained a schema-lock, making the write-lock redundant.
73 sqlite3TableLock(pParse, iDb, iRootPage, 1, "sqlite_stat1");
75 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
76 sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage);
77 sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3);
81 ** Generate code to do an analysis of all indices associated with
84 static void analyzeOneTable(
85 Parse *pParse, /* Parser context */
86 Table *pTab, /* Table whose indices are to be analyzed */
87 int iStatCur, /* Cursor that writes to the sqlite_stat1 table */
88 int iMem /* Available memory locations begin here */
90 Index *pIdx; /* An index to being analyzed */
91 int iIdxCur; /* Cursor number for index being analyzed */
92 int nCol; /* Number of columns in the index */
93 Vdbe *v; /* The virtual machine being built up */
94 int i; /* Loop counter */
95 int topOfLoop; /* The top of the loop */
96 int endOfLoop; /* The end of the loop */
97 int addr; /* The address of an instruction */
98 int iDb; /* Index of database containing pTab */
100 v = sqlite3GetVdbe(pParse);
101 if( v==0 || pTab==0 || pTab->pIndex==0 ){
102 /* Do no analysis for tables that have no indices */
105 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
106 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
108 #ifndef SQLITE_OMIT_AUTHORIZATION
109 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
110 pParse->db->aDb[iDb].zName ) ){
115 /* Establish a read-lock on the table at the shared-cache level. */
116 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
118 iIdxCur = pParse->nTab;
119 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
120 KeyInfo *pKey = sqlite3IndexKeyinfo(pParse, pIdx);
122 /* Open a cursor to the index to be analyzed
124 assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
125 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
126 VdbeComment((v, "# %s", pIdx->zName));
127 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum,
128 (char *)pKey, P3_KEYINFO_HANDOFF);
129 nCol = pIdx->nColumn;
130 if( iMem+nCol*2>=pParse->nMem ){
131 pParse->nMem = iMem+nCol*2+1;
133 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1);
135 /* Memory cells are used as follows:
137 ** mem[iMem]: The total number of rows in the table.
138 ** mem[iMem+1]: Number of distinct values in column 1
140 ** mem[iMem+nCol]: Number of distinct values in column N
141 ** mem[iMem+nCol+1] Last observed value of column 1
143 ** mem[iMem+nCol+nCol]: Last observed value of column N
145 ** Cells iMem through iMem+nCol are initialized to 0. The others
146 ** are initialized to NULL.
148 for(i=0; i<=nCol; i++){
149 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i);
151 for(i=0; i<nCol; i++){
152 sqlite3VdbeAddOp(v, OP_MemNull, iMem+nCol+i+1, 0);
157 endOfLoop = sqlite3VdbeMakeLabel(v);
158 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop);
159 topOfLoop = sqlite3VdbeCurrentAddr(v);
160 sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem);
161 for(i=0; i<nCol; i++){
162 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
163 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0);
164 sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0);
166 sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop);
167 for(i=0; i<nCol; i++){
168 addr = sqlite3VdbeAddOp(v, OP_MemIncr, 1, iMem+i+1);
169 sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr);
170 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
171 sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1);
173 sqlite3VdbeResolveLabel(v, endOfLoop);
174 sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
175 sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);
177 /* Store the results.
179 ** The result is a single row of the sqlite_stat1 table. The first
180 ** two columns are the names of the table and index. The third column
181 ** is a string composed of a list of integer statistics about the
182 ** index. The first integer in the list is the total number of entires
183 ** in the index. There is one additional integer in the list for each
184 ** column of the table. This additional integer is a guess of how many
185 ** rows of the table the index will select. If D is the count of distinct
186 ** values and K is the total number of rows, then the integer is computed
191 ** If K==0 then no entry is made into the sqlite_stat1 table.
192 ** If K>0 then it is always the case the D>0 so division by zero
193 ** is never possible.
195 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
196 addr = sqlite3VdbeAddOp(v, OP_IfNot, 0, 0);
197 sqlite3VdbeAddOp(v, OP_NewRowid, iStatCur, 0);
198 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
199 sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
200 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
201 sqlite3VdbeOp3(v, OP_String8, 0, 0, " ", 0);
202 for(i=0; i<nCol; i++){
203 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
204 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
205 sqlite3VdbeAddOp(v, OP_Add, 0, 0);
206 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
207 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
208 sqlite3VdbeAddOp(v, OP_Divide, 0, 0);
209 sqlite3VdbeAddOp(v, OP_ToInt, 0, 0);
211 sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0);
213 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
216 sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0);
217 sqlite3VdbeAddOp(v, OP_Insert, iStatCur, OPFLAG_APPEND);
218 sqlite3VdbeJumpHere(v, addr);
223 ** Generate code that will cause the most recent index analysis to
224 ** be laoded into internal hash tables where is can be used.
226 static void loadAnalysis(Parse *pParse, int iDb){
227 Vdbe *v = sqlite3GetVdbe(pParse);
229 sqlite3VdbeAddOp(v, OP_LoadAnalysis, iDb, 0);
234 ** Generate code that will do an analysis of an entire database
236 static void analyzeDatabase(Parse *pParse, int iDb){
237 sqlite3 *db = pParse->db;
238 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
243 sqlite3BeginWriteOperation(pParse, 0, iDb);
244 iStatCur = pParse->nTab++;
245 openStatTable(pParse, iDb, iStatCur, 0);
247 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
248 Table *pTab = (Table*)sqliteHashData(k);
249 analyzeOneTable(pParse, pTab, iStatCur, iMem);
251 loadAnalysis(pParse, iDb);
255 ** Generate code that will do an analysis of a single table in
258 static void analyzeTable(Parse *pParse, Table *pTab){
263 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
264 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
265 sqlite3BeginWriteOperation(pParse, 0, iDb);
266 iStatCur = pParse->nTab++;
267 openStatTable(pParse, iDb, iStatCur, pTab->zName);
268 analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem);
269 loadAnalysis(pParse, iDb);
273 ** Generate code for the ANALYZE command. The parser calls this routine
274 ** when it recognizes an ANALYZE command.
277 ** ANALYZE <database> -- 2
278 ** ANALYZE ?<database>.?<tablename> -- 3
280 ** Form 1 causes all indices in all attached databases to be analyzed.
281 ** Form 2 analyzes all indices the single database named.
282 ** Form 3 analyzes all indices associated with the named table.
284 void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
285 sqlite3 *db = pParse->db;
292 /* Read the database schema. If an error occurs, leave an error message
293 ** and code in pParse and return NULL. */
294 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
295 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
300 /* Form 1: Analyze everything */
301 for(i=0; i<db->nDb; i++){
302 if( i==1 ) continue; /* Do not analyze the TEMP database */
303 analyzeDatabase(pParse, i);
305 }else if( pName2==0 || pName2->n==0 ){
306 /* Form 2: Analyze the database or table named */
307 iDb = sqlite3FindDb(db, pName1);
309 analyzeDatabase(pParse, iDb);
311 z = sqlite3NameFromToken(db, pName1);
312 pTab = sqlite3LocateTable(pParse, z, 0);
315 analyzeTable(pParse, pTab);
319 /* Form 3: Analyze the fully qualified table name */
320 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
322 zDb = db->aDb[iDb].zName;
323 z = sqlite3NameFromToken(db, pTableName);
325 pTab = sqlite3LocateTable(pParse, z, zDb);
328 analyzeTable(pParse, pTab);
336 ** Used to pass information from the analyzer reader through to the
339 typedef struct analysisInfo analysisInfo;
340 struct analysisInfo {
342 const char *zDatabase;
346 ** This callback is invoked once for each index when reading the
347 ** sqlite_stat1 table.
349 ** argv[0] = name of the index
350 ** argv[1] = results of analysis - on integer for each column
352 static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
353 analysisInfo *pInfo = (analysisInfo*)pData;
360 if( argv==0 || argv[0]==0 || argv[1]==0 ){
363 pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
368 for(i=0; *z && i<=pIndex->nColumn; i++){
370 while( (c=z[0])>='0' && c<='9' ){
374 pIndex->aiRowEst[i] = v;
381 ** Load the content of the sqlite_stat1 table into the index hash tables.
383 int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
389 assert( iDb>=0 && iDb<db->nDb );
390 assert( db->aDb[iDb].pBt!=0 );
391 assert( sqlite3BtreeHoldsMutex(db->aDb[iDb].pBt) );
393 /* Clear any prior statistics */
394 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
395 Index *pIdx = sqliteHashData(i);
396 sqlite3DefaultRowEst(pIdx);
399 /* Check to make sure the sqlite_stat1 table existss */
401 sInfo.zDatabase = db->aDb[iDb].zName;
402 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
407 /* Load new statistics out of the sqlite_stat1 table */
408 zSql = sqlite3MPrintf(db, "SELECT idx, stat FROM %Q.sqlite_stat1",
410 sqlite3SafetyOff(db);
411 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
418 #endif /* SQLITE_OMIT_ANALYZE */