blob: 3bcc8add4110c483913e2452e598af232bbcd879 [file] [log] [blame]
drh9f18e8a2005-07-08 12:13:04 +00001/*
2** 2005 July 8
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**
danielk1977da184232006-01-05 11:34:32 +000014** @(#) $Id: analyze.c,v 1.12 2006/01/05 11:34:33 danielk1977 Exp $
drh9f18e8a2005-07-08 12:13:04 +000015*/
16#ifndef SQLITE_OMIT_ANALYZE
17#include "sqliteInt.h"
18
19/*
drhff2d5ea2005-07-23 00:41:48 +000020** This routine generates code that opens the sqlite_stat1 table on cursor
21** iStatCur.
22**
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.
26*/
27static 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 */
32){
33 sqlite3 *db = pParse->db;
34 Db *pDb;
35 int iRootPage;
36 Table *pStat;
37 Vdbe *v = sqlite3GetVdbe(pParse);
38
39 pDb = &db->aDb[iDb];
40 if( (pStat = sqlite3FindTable(db, "sqlite_stat1", pDb->zName))==0 ){
41 /* The sqlite_stat1 tables does not exist. Create it.
42 ** Note that a side-effect of the CREATE TABLE statement is to leave
43 ** the rootpage of the new table on the top of the stack. This is
44 ** important because the OpenWrite opcode below will be needing it. */
45 sqlite3NestedParse(pParse,
46 "CREATE TABLE %Q.sqlite_stat1(tbl,idx,stat)",
47 pDb->zName
48 );
49 iRootPage = 0; /* Cause rootpage to be taken from top of stack */
50 }else if( zWhere ){
51 /* The sqlite_stat1 table exists. Delete all entries associated with
52 ** the table zWhere. */
53 sqlite3NestedParse(pParse,
54 "DELETE FROM %Q.sqlite_stat1 WHERE tbl=%Q",
55 pDb->zName, zWhere
56 );
57 iRootPage = pStat->tnum;
58 }else{
59 /* The sqlite_stat1 table already exists. Delete all rows. */
60 iRootPage = pStat->tnum;
61 sqlite3VdbeAddOp(v, OP_Clear, pStat->tnum, iDb);
62 }
63
64 /* Open the sqlite_stat1 table for writing.
65 */
66 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drhe6e04962005-07-23 02:17:03 +000067 sqlite3VdbeAddOp(v, OP_OpenWrite, iStatCur, iRootPage);
drhff2d5ea2005-07-23 00:41:48 +000068 sqlite3VdbeAddOp(v, OP_SetNumColumns, iStatCur, 3);
69}
70
71/*
72** Generate code to do an analysis of all indices associated with
73** a single table.
74*/
75static void analyzeOneTable(
76 Parse *pParse, /* Parser context */
77 Table *pTab, /* Table whose indices are to be analyzed */
78 int iStatCur, /* Cursor that writes to the sqlite_stat1 table */
79 int iMem /* Available memory locations begin here */
80){
81 Index *pIdx; /* An index to being analyzed */
82 int iIdxCur; /* Cursor number for index being analyzed */
83 int nCol; /* Number of columns in the index */
84 Vdbe *v; /* The virtual machine being built up */
85 int i; /* Loop counter */
86 int topOfLoop; /* The top of the loop */
87 int endOfLoop; /* The end of the loop */
88 int addr; /* The address of an instruction */
danielk1977da184232006-01-05 11:34:32 +000089 int iDb; /* Index of database containing pTab */
drhff2d5ea2005-07-23 00:41:48 +000090
91 v = sqlite3GetVdbe(pParse);
drh0c356672005-09-10 22:40:53 +000092 if( pTab==0 || pTab->pIndex==0 ){
93 /* Do no analysis for tables that have no indices */
drhff2d5ea2005-07-23 00:41:48 +000094 return;
95 }
drhe6e04962005-07-23 02:17:03 +000096
danielk1977da184232006-01-05 11:34:32 +000097 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
98 assert( iDb>=0 );
drhe6e04962005-07-23 02:17:03 +000099#ifndef SQLITE_OMIT_AUTHORIZATION
100 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
danielk1977da184232006-01-05 11:34:32 +0000101 pParse->db->aDb[iDb].zName ) ){
drhe6e04962005-07-23 02:17:03 +0000102 return;
103 }
104#endif
105
drhff2d5ea2005-07-23 00:41:48 +0000106 iIdxCur = pParse->nTab;
107 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
108 /* Open a cursor to the index to be analyzed
109 */
danielk1977da184232006-01-05 11:34:32 +0000110 assert( iDb==sqlite3SchemaToIndex(pParse->db, pIdx->pSchema) );
111 sqlite3VdbeAddOp(v, OP_Integer, iDb, 0);
drhff2d5ea2005-07-23 00:41:48 +0000112 VdbeComment((v, "# %s", pIdx->zName));
113 sqlite3VdbeOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum,
114 (char*)&pIdx->keyInfo, P3_KEYINFO);
115 nCol = pIdx->nColumn;
116 if( iMem+nCol*2>=pParse->nMem ){
117 pParse->nMem = iMem+nCol*2+1;
118 }
119 sqlite3VdbeAddOp(v, OP_SetNumColumns, iIdxCur, nCol+1);
120
121 /* Memory cells are used as follows:
122 **
123 ** mem[iMem]: The total number of rows in the table.
124 ** mem[iMem+1]: Number of distinct values in column 1
125 ** ...
126 ** mem[iMem+nCol]: Number of distinct values in column N
127 ** mem[iMem+nCol+1] Last observed value of column 1
128 ** ...
129 ** mem[iMem+nCol+nCol]: Last observed value of column N
130 **
131 ** Cells iMem through iMem+nCol are initialized to 0. The others
132 ** are initialized to NULL.
133 */
drhff2d5ea2005-07-23 00:41:48 +0000134 for(i=0; i<=nCol; i++){
drhd654be82005-09-20 17:42:23 +0000135 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem+i);
drhff2d5ea2005-07-23 00:41:48 +0000136 }
drhff2d5ea2005-07-23 00:41:48 +0000137 for(i=0; i<nCol; i++){
drhd654be82005-09-20 17:42:23 +0000138 sqlite3VdbeAddOp(v, OP_MemNull, iMem+nCol+i+1, 0);
drhff2d5ea2005-07-23 00:41:48 +0000139 }
140
141 /* Do the analysis.
142 */
drhff2d5ea2005-07-23 00:41:48 +0000143 endOfLoop = sqlite3VdbeMakeLabel(v);
drhe6e04962005-07-23 02:17:03 +0000144 sqlite3VdbeAddOp(v, OP_Rewind, iIdxCur, endOfLoop);
145 topOfLoop = sqlite3VdbeCurrentAddr(v);
drhff2d5ea2005-07-23 00:41:48 +0000146 sqlite3VdbeAddOp(v, OP_MemIncr, iMem, 0);
147 for(i=0; i<nCol; i++){
148 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
149 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+nCol+i+1, 0);
150 sqlite3VdbeAddOp(v, OP_Ne, 0x100, 0);
151 }
152 sqlite3VdbeAddOp(v, OP_Goto, 0, endOfLoop);
153 for(i=0; i<nCol; i++){
154 addr = sqlite3VdbeAddOp(v, OP_MemIncr, iMem+i+1, 0);
155 sqlite3VdbeChangeP2(v, topOfLoop + 3*i + 3, addr);
156 sqlite3VdbeAddOp(v, OP_Column, iIdxCur, i);
157 sqlite3VdbeAddOp(v, OP_MemStore, iMem+nCol+i+1, 1);
158 }
159 sqlite3VdbeResolveLabel(v, endOfLoop);
160 sqlite3VdbeAddOp(v, OP_Next, iIdxCur, topOfLoop);
161 sqlite3VdbeAddOp(v, OP_Close, iIdxCur, 0);
162
163 /* Store the results.
164 **
165 ** The result is a single row of the sqlite_stmt1 table. The first
166 ** two columns are the names of the table and index. The third column
167 ** is a string composed of a list of integer statistics about the
drh17a18f22005-07-23 14:52:12 +0000168 ** index. The first integer in the list is the total number of entires
169 ** in the index. There is one additional integer in the list for each
170 ** column of the table. This additional integer is a guess of how many
171 ** rows of the table the index will select. If D is the count of distinct
172 ** values and K is the total number of rows, then the integer is computed
173 ** as:
drhff2d5ea2005-07-23 00:41:48 +0000174 **
175 ** I = (K+D-1)/D
176 **
177 ** If K==0 then no entry is made into the sqlite_stat1 table.
178 ** If K>0 then it is always the case the D>0 so division by zero
179 ** is never possible.
180 */
181 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
182 addr = sqlite3VdbeAddOp(v, OP_IfNot, 0, 0);
183 sqlite3VdbeAddOp(v, OP_NewRowid, iStatCur, 0);
184 sqlite3VdbeOp3(v, OP_String8, 0, 0, pTab->zName, 0);
185 sqlite3VdbeOp3(v, OP_String8, 0, 0, pIdx->zName, 0);
drh17a18f22005-07-23 14:52:12 +0000186 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
187 sqlite3VdbeOp3(v, OP_String8, 0, 0, " ", 0);
drhff2d5ea2005-07-23 00:41:48 +0000188 for(i=0; i<nCol; i++){
189 sqlite3VdbeAddOp(v, OP_MemLoad, iMem, 0);
190 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
191 sqlite3VdbeAddOp(v, OP_Add, 0, 0);
192 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
193 sqlite3VdbeAddOp(v, OP_MemLoad, iMem+i+1, 0);
194 sqlite3VdbeAddOp(v, OP_Divide, 0, 0);
drh8df447f2005-11-01 15:48:24 +0000195 sqlite3VdbeAddOp(v, OP_ToInt, 0, 0);
drhff2d5ea2005-07-23 00:41:48 +0000196 if( i==nCol-1 ){
drh17a18f22005-07-23 14:52:12 +0000197 sqlite3VdbeAddOp(v, OP_Concat, nCol*2-1, 0);
drhff2d5ea2005-07-23 00:41:48 +0000198 }else{
drh17a18f22005-07-23 14:52:12 +0000199 sqlite3VdbeAddOp(v, OP_Dup, 1, 0);
drhff2d5ea2005-07-23 00:41:48 +0000200 }
201 }
drh8a512562005-11-14 22:29:05 +0000202 sqlite3VdbeOp3(v, OP_MakeRecord, 3, 0, "aaa", 0);
drhff2d5ea2005-07-23 00:41:48 +0000203 sqlite3VdbeAddOp(v, OP_Insert, iStatCur, 0);
drhd654be82005-09-20 17:42:23 +0000204 sqlite3VdbeJumpHere(v, addr);
drhff2d5ea2005-07-23 00:41:48 +0000205 }
206}
207
208/*
drh497e4462005-07-23 03:18:40 +0000209** Generate code that will cause the most recent index analysis to
210** be laoded into internal hash tables where is can be used.
211*/
212static void loadAnalysis(Parse *pParse, int iDb){
213 Vdbe *v = sqlite3GetVdbe(pParse);
214 sqlite3VdbeAddOp(v, OP_LoadAnalysis, iDb, 0);
215}
216
217/*
drhff2d5ea2005-07-23 00:41:48 +0000218** Generate code that will do an analysis of an entire database
219*/
220static void analyzeDatabase(Parse *pParse, int iDb){
221 sqlite3 *db = pParse->db;
danielk1977da184232006-01-05 11:34:32 +0000222 DbSchema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
drhff2d5ea2005-07-23 00:41:48 +0000223 HashElem *k;
224 int iStatCur;
225 int iMem;
226
227 sqlite3BeginWriteOperation(pParse, 0, iDb);
228 iStatCur = pParse->nTab++;
229 openStatTable(pParse, iDb, iStatCur, 0);
230 iMem = pParse->nMem;
danielk1977da184232006-01-05 11:34:32 +0000231 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
drhff2d5ea2005-07-23 00:41:48 +0000232 Table *pTab = (Table*)sqliteHashData(k);
233 analyzeOneTable(pParse, pTab, iStatCur, iMem);
234 }
drh497e4462005-07-23 03:18:40 +0000235 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +0000236}
237
238/*
239** Generate code that will do an analysis of a single table in
240** a database.
241*/
242static void analyzeTable(Parse *pParse, Table *pTab){
243 int iDb;
244 int iStatCur;
245
246 assert( pTab!=0 );
danielk1977da184232006-01-05 11:34:32 +0000247 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhff2d5ea2005-07-23 00:41:48 +0000248 sqlite3BeginWriteOperation(pParse, 0, iDb);
249 iStatCur = pParse->nTab++;
250 openStatTable(pParse, iDb, iStatCur, pTab->zName);
251 analyzeOneTable(pParse, pTab, iStatCur, pParse->nMem);
drh497e4462005-07-23 03:18:40 +0000252 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +0000253}
254
255/*
256** Generate code for the ANALYZE command. The parser calls this routine
257** when it recognizes an ANALYZE command.
drh9f18e8a2005-07-08 12:13:04 +0000258**
259** ANALYZE -- 1
drhff2d5ea2005-07-23 00:41:48 +0000260** ANALYZE <database> -- 2
drh9f18e8a2005-07-08 12:13:04 +0000261** ANALYZE ?<database>.?<tablename> -- 3
262**
263** Form 1 causes all indices in all attached databases to be analyzed.
264** Form 2 analyzes all indices the single database named.
265** Form 3 analyzes all indices associated with the named table.
266*/
267void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
drhff2d5ea2005-07-23 00:41:48 +0000268 sqlite3 *db = pParse->db;
269 int iDb;
270 int i;
271 char *z, *zDb;
272 Table *pTab;
273 Token *pTableName;
274
275 /* Read the database schema. If an error occurs, leave an error message
276 ** and code in pParse and return NULL. */
277 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
278 return;
279 }
280
281 if( pName1==0 ){
282 /* Form 1: Analyze everything */
283 for(i=0; i<db->nDb; i++){
284 if( i==1 ) continue; /* Do not analyze the TEMP database */
285 analyzeDatabase(pParse, i);
286 }
drhe6e04962005-07-23 02:17:03 +0000287 }else if( pName2==0 || pName2->n==0 ){
drhff2d5ea2005-07-23 00:41:48 +0000288 /* Form 2: Analyze the database or table named */
289 iDb = sqlite3FindDb(db, pName1);
290 if( iDb>=0 ){
291 analyzeDatabase(pParse, iDb);
drhe6e04962005-07-23 02:17:03 +0000292 }else{
293 z = sqlite3NameFromToken(pName1);
294 pTab = sqlite3LocateTable(pParse, z, 0);
295 sqliteFree(z);
296 if( pTab ){
297 analyzeTable(pParse, pTab);
298 }
drhff2d5ea2005-07-23 00:41:48 +0000299 }
drhff2d5ea2005-07-23 00:41:48 +0000300 }else{
301 /* Form 3: Analyze the fully qualified table name */
302 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
303 if( iDb>=0 ){
304 zDb = db->aDb[iDb].zName;
305 z = sqlite3NameFromToken(pTableName);
306 pTab = sqlite3LocateTable(pParse, z, zDb);
307 sqliteFree(z);
308 if( pTab ){
309 analyzeTable(pParse, pTab);
310 }
311 }
312 }
drh9f18e8a2005-07-08 12:13:04 +0000313}
314
drh497e4462005-07-23 03:18:40 +0000315/*
316** Used to pass information from the analyzer reader through to the
317** callback routine.
318*/
319typedef struct analysisInfo analysisInfo;
320struct analysisInfo {
321 sqlite3 *db;
322 const char *zDatabase;
323};
324
325/*
326** This callback is invoked once for each index when reading the
327** sqlite_stat1 table.
328**
329** argv[0] = name of the index
330** argv[1] = results of analysis - on integer for each column
331*/
332static int analysisLoader(void *pData, int argc, char **argv, char **azNotUsed){
333 analysisInfo *pInfo = (analysisInfo*)pData;
334 Index *pIndex;
335 int i, c;
336 unsigned int v;
337 const char *z;
338
339 assert( argc==2 );
drh1ec43c92005-09-06 10:26:47 +0000340 if( argv==0 || argv[0]==0 || argv[1]==0 ){
drh497e4462005-07-23 03:18:40 +0000341 return 0;
342 }
343 pIndex = sqlite3FindIndex(pInfo->db, argv[0], pInfo->zDatabase);
344 if( pIndex==0 ){
345 return 0;
346 }
347 z = argv[1];
drh17a18f22005-07-23 14:52:12 +0000348 for(i=0; *z && i<=pIndex->nColumn; i++){
drh497e4462005-07-23 03:18:40 +0000349 v = 0;
350 while( (c=z[0])>='0' && c<='9' ){
351 v = v*10 + c - '0';
352 z++;
353 }
354 pIndex->aiRowEst[i] = v;
355 if( *z==' ' ) z++;
356 }
357 return 0;
358}
359
360/*
361** Load the content of the sqlite_stat1 table into the index hash tables.
362*/
363void sqlite3AnalysisLoad(sqlite3 *db, int iDb){
364 analysisInfo sInfo;
365 HashElem *i;
366 char *zSql;
367
368 /* Clear any prior statistics */
danielk1977da184232006-01-05 11:34:32 +0000369 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
drh497e4462005-07-23 03:18:40 +0000370 Index *pIdx = sqliteHashData(i);
drh51147ba2005-07-23 22:59:55 +0000371 sqlite3DefaultRowEst(pIdx);
drh497e4462005-07-23 03:18:40 +0000372 }
373
374 /* Check to make sure the sqlite_stat1 table existss */
375 sInfo.db = db;
376 sInfo.zDatabase = db->aDb[iDb].zName;
377 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
378 return;
379 }
380
381
382 /* Load new statistics out of the sqlite_stat1 table */
383 zSql = sqlite3MPrintf("SELECT idx, stat FROM %Q.sqlite_stat1",
384 sInfo.zDatabase);
385 sqlite3SafetyOff(db);
386 sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
387 sqlite3SafetyOn(db);
388 sqliteFree(zSql);
389}
drh9f18e8a2005-07-08 12:13:04 +0000390
drhff2d5ea2005-07-23 00:41:48 +0000391
drh9f18e8a2005-07-08 12:13:04 +0000392#endif /* SQLITE_OMIT_ANALYZE */