blob: ac9ba5edebd190cf23bf334d06104ff73d296a7e [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.
drhfaacf172011-08-12 01:51:45 +000013**
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);
drhf404c862011-08-13 15:25:10 +000022** CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
drhc8af8502013-08-09 14:07:55 +000023** CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
drhfaacf172011-08-12 01:51:45 +000024**
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
drhd3ed7342011-09-21 00:09:41 +000027** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
drhfaacf172011-08-12 01:51:45 +000028** with SQLITE_ENABLE_STAT2. The sqlite_stat2 table is deprecated.
drhf7b54962013-05-28 12:11:54 +000029** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
drhd3ed7342011-09-21 00:09:41 +000030** created and used by SQLite versions 3.7.9 and later and with
drhc8af8502013-08-09 14:07:55 +000031** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
32** is a superset of sqlite_stat2. The sqlite_stat4 is an enhanced
33** version of sqlite_stat3 and is only available when compiled with
34** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.0 and later.
35**
36** For most applications, sqlite_stat1 provides all the statisics required
37** for the query planner to make good choices.
drhfaacf172011-08-12 01:51:45 +000038**
39** Format of sqlite_stat1:
40**
41** There is normally one row per index, with the index identified by the
42** name in the idx column. The tbl column is the name of the table to
43** which the index belongs. In each such row, the stat column will be
44** a string consisting of a list of integers. The first integer in this
drhc8af8502013-08-09 14:07:55 +000045** list is the number of rows in the index. (This is the same as the
46** number of rows in the table, except for partial indices.) The second
drhfaacf172011-08-12 01:51:45 +000047** integer is the average number of rows in the index that have the same
48** value in the first column of the index. The third integer is the average
49** number of rows in the index that have the same value for the first two
50** columns. The N-th integer (for N>1) is the average number of rows in
51** the index which have the same value for the first N-1 columns. For
52** a K-column index, there will be K+1 integers in the stat column. If
53** the index is unique, then the last integer will be 1.
54**
55** The list of integers in the stat column can optionally be followed
56** by the keyword "unordered". The "unordered" keyword, if it is present,
57** must be separated from the last integer by a single space. If the
58** "unordered" keyword is present, then the query planner assumes that
59** the index is unordered and will not use the index for a range query.
60**
61** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
62** column contains a single integer which is the (estimated) number of
63** rows in the table identified by sqlite_stat1.tbl.
64**
65** Format of sqlite_stat2:
66**
67** The sqlite_stat2 is only created and is only used if SQLite is compiled
68** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
drhd3ed7342011-09-21 00:09:41 +000069** 3.6.18 and 3.7.8. The "stat2" table contains additional information
drhfaacf172011-08-12 01:51:45 +000070** about the distribution of keys within an index. The index is identified by
71** the "idx" column and the "tbl" column is the name of the table to which
72** the index belongs. There are usually 10 rows in the sqlite_stat2
73** table for each index.
74**
dan23e7c4d2011-08-15 12:02:21 +000075** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
drhfaacf172011-08-12 01:51:45 +000076** inclusive are samples of the left-most key value in the index taken at
77** evenly spaced points along the index. Let the number of samples be S
78** (10 in the standard build) and let C be the number of rows in the index.
79** Then the sampled rows are given by:
80**
81** rownumber = (i*C*2 + C)/(S*2)
82**
83** For i between 0 and S-1. Conceptually, the index space is divided into
84** S uniform buckets and the samples are the middle row from each bucket.
85**
86** The format for sqlite_stat2 is recorded here for legacy reference. This
87** version of SQLite does not support sqlite_stat2. It neither reads nor
88** writes the sqlite_stat2 table. This version of SQLite only supports
89** sqlite_stat3.
90**
91** Format for sqlite_stat3:
92**
drhc8af8502013-08-09 14:07:55 +000093** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
94** sqlite_stat4 format will be described first. Further information
95** about sqlite_stat3 follows the sqlite_stat4 description.
drhfaacf172011-08-12 01:51:45 +000096**
drhc8af8502013-08-09 14:07:55 +000097** Format for sqlite_stat4:
98**
99** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
100** to aid the query planner in choosing good indices based on the values
101** that indexed columns are compared against in the WHERE clauses of
102** queries.
103**
104** The sqlite_stat4 table contains multiple entries for each index.
drhd3ed7342011-09-21 00:09:41 +0000105** The idx column names the index and the tbl column is the table of the
106** index. If the idx and tbl columns are the same, then the sample is
drhc8af8502013-08-09 14:07:55 +0000107** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
108** binary encoding of a key from the index, with the trailing rowid
109** omitted. The nEq column is a list of integers. The first integer
dan84d4fcc2013-08-09 19:04:07 +0000110** is the approximate number of entries in the index whose left-most
111** column exactly matches the left-most column of the sample. The second
112** integer in nEq is the approximate number of entries in the index where
drhc8af8502013-08-09 14:07:55 +0000113** the first two columns match the first two columns of the sample.
dan84d4fcc2013-08-09 19:04:07 +0000114** And so forth. nLt is another list of integers that show the approximate
115** number of entries that are strictly less than the sample. The first
drhc8af8502013-08-09 14:07:55 +0000116** integer in nLt contains the number of entries in the index where the
117** left-most column is less than the left-most column of the sample.
118** The K-th integer in the nLt entry is the number of index entries
119** where the first K columns are less than the first K columns of the
120** sample. The nDLt column is like nLt except that it contains the
121** number of distinct entries in the index that are less than the
122** sample.
drhfaacf172011-08-12 01:51:45 +0000123**
drhc8af8502013-08-09 14:07:55 +0000124** There can be an arbitrary number of sqlite_stat4 entries per index.
dan84d4fcc2013-08-09 19:04:07 +0000125** The ANALYZE command will typically generate sqlite_stat4 tables
drhfaacf172011-08-12 01:51:45 +0000126** that contain between 10 and 40 samples which are distributed across
127** the key space, though not uniformly, and which include samples with
drhc8af8502013-08-09 14:07:55 +0000128** large nEq values.
129**
130** Format for sqlite_stat3 redux:
131**
132** The sqlite_stat3 table is like sqlite_stat4 except that it only
133** looks at the left-most column of the index. The sqlite_stat3.sample
134** column contains the actual value of the left-most column instead
135** of a blob encoding of the complete index key as is found in
136** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
137** all contain just a single integer which is the same as the first
138** integer in the equivalent columns in sqlite_stat4.
drh9f18e8a2005-07-08 12:13:04 +0000139*/
140#ifndef SQLITE_OMIT_ANALYZE
141#include "sqliteInt.h"
142
danf00e9022013-08-14 19:54:12 +0000143#if defined(SQLITE_ENABLE_STAT4)
144# define IsStat4 1
dan8ad169a2013-08-12 20:14:04 +0000145# define IsStat3 0
danf00e9022013-08-14 19:54:12 +0000146#elif defined(SQLITE_ENABLE_STAT3)
147# define IsStat4 0
dan8ad169a2013-08-12 20:14:04 +0000148# define IsStat3 1
danf00e9022013-08-14 19:54:12 +0000149#else
150# define IsStat4 0
151# define IsStat3 0
dan8ad169a2013-08-12 20:14:04 +0000152#endif
153
drh9f18e8a2005-07-08 12:13:04 +0000154/*
dan02fa4692009-08-17 17:06:58 +0000155** This routine generates code that opens the sqlite_stat1 table for
dan69188d92009-08-19 08:18:32 +0000156** writing with cursor iStatCur. If the library was built with the
danf52bb8d2013-08-03 20:24:58 +0000157** SQLITE_ENABLE_STAT4 macro defined, then the sqlite_stat4 table is
dan69188d92009-08-19 08:18:32 +0000158** opened for writing using cursor (iStatCur+1)
drhff2d5ea2005-07-23 00:41:48 +0000159**
160** If the sqlite_stat1 tables does not previously exist, it is created.
danf52bb8d2013-08-03 20:24:58 +0000161** Similarly, if the sqlite_stat4 table does not exist and the library
162** is compiled with SQLITE_ENABLE_STAT4 defined, it is created.
dan69188d92009-08-19 08:18:32 +0000163**
164** Argument zWhere may be a pointer to a buffer containing a table name,
165** or it may be a NULL pointer. If it is not NULL, then all entries in
danf52bb8d2013-08-03 20:24:58 +0000166** the sqlite_stat1 and (if applicable) sqlite_stat4 tables associated
dan69188d92009-08-19 08:18:32 +0000167** with the named table are deleted. If zWhere==0, then code is generated
168** to delete all stat table entries.
drhff2d5ea2005-07-23 00:41:48 +0000169*/
170static void openStatTable(
171 Parse *pParse, /* Parsing context */
172 int iDb, /* The database we are looking in */
173 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
drha071bc52011-03-31 02:03:28 +0000174 const char *zWhere, /* Delete entries for this table or index */
175 const char *zWhereType /* Either "tbl" or "idx" */
drhff2d5ea2005-07-23 00:41:48 +0000176){
dan558814f2010-06-02 05:53:53 +0000177 static const struct {
dan69188d92009-08-19 08:18:32 +0000178 const char *zName;
179 const char *zCols;
180 } aTable[] = {
181 { "sqlite_stat1", "tbl,idx,stat" },
dan0106e372013-08-12 16:34:32 +0000182#if defined(SQLITE_ENABLE_STAT4)
danf52bb8d2013-08-03 20:24:58 +0000183 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
dan8ad169a2013-08-12 20:14:04 +0000184 { "sqlite_stat3", 0 },
dan0106e372013-08-12 16:34:32 +0000185#elif defined(SQLITE_ENABLE_STAT3)
186 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
dan8ad169a2013-08-12 20:14:04 +0000187 { "sqlite_stat4", 0 },
drhfaacf172011-08-12 01:51:45 +0000188#endif
189 };
dan69188d92009-08-19 08:18:32 +0000190
dan02fa4692009-08-17 17:06:58 +0000191 int aRoot[] = {0, 0};
shanecea72b22009-09-07 04:38:36 +0000192 u8 aCreateTbl[] = {0, 0};
dan02fa4692009-08-17 17:06:58 +0000193
194 int i;
drhff2d5ea2005-07-23 00:41:48 +0000195 sqlite3 *db = pParse->db;
196 Db *pDb;
drhff2d5ea2005-07-23 00:41:48 +0000197 Vdbe *v = sqlite3GetVdbe(pParse);
drhcf1be452007-05-12 12:08:51 +0000198 if( v==0 ) return;
drh1fee73e2007-08-29 04:00:57 +0000199 assert( sqlite3BtreeHoldsAllMutexes(db) );
200 assert( sqlite3VdbeDb(v)==db );
drhff2d5ea2005-07-23 00:41:48 +0000201 pDb = &db->aDb[iDb];
dan02fa4692009-08-17 17:06:58 +0000202
drhfaacf172011-08-12 01:51:45 +0000203 /* Create new statistic tables if they do not exist, or clear them
204 ** if they do already exist.
205 */
dan69188d92009-08-19 08:18:32 +0000206 for(i=0; i<ArraySize(aTable); i++){
207 const char *zTab = aTable[i].zName;
dan02fa4692009-08-17 17:06:58 +0000208 Table *pStat;
dan69188d92009-08-19 08:18:32 +0000209 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
dan8ad169a2013-08-12 20:14:04 +0000210 if( aTable[i].zCols ){
211 /* The sqlite_stat[12] 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->zName, zTab, aTable[i].zCols
217 );
218 aRoot[i] = pParse->regRoot;
219 aCreateTbl[i] = OPFLAG_P2ISREG;
220 }
dan02fa4692009-08-17 17:06:58 +0000221 }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;
dan69188d92009-08-19 08:18:32 +0000226 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
dan02fa4692009-08-17 17:06:58 +0000227 if( zWhere ){
228 sqlite3NestedParse(pParse,
drha071bc52011-03-31 02:03:28 +0000229 "DELETE FROM %Q.%s WHERE %s=%Q", pDb->zName, zTab, zWhereType, zWhere
dan02fa4692009-08-17 17:06:58 +0000230 );
231 }else{
dan8ad169a2013-08-12 20:14:04 +0000232 /* The sqlite_stat[134] table already exists. Delete all rows. */
dan02fa4692009-08-17 17:06:58 +0000233 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
234 }
235 }
drhff2d5ea2005-07-23 00:41:48 +0000236 }
237
danf00e9022013-08-14 19:54:12 +0000238 /* Open the sqlite_stat[134] tables for writing. */
dan8ad169a2013-08-12 20:14:04 +0000239 for(i=0; i<ArraySize(aRoot); i++){
dan02fa4692009-08-17 17:06:58 +0000240 sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
241 sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
242 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
danf00e9022013-08-14 19:54:12 +0000243 if( !IsStat3 && !IsStat4 ) break;
danielk1977c00da102006-01-07 13:21:04 +0000244 }
drhff2d5ea2005-07-23 00:41:48 +0000245}
246
247/*
danf52bb8d2013-08-03 20:24:58 +0000248** Recommended number of samples for sqlite_stat4
drhfaacf172011-08-12 01:51:45 +0000249*/
danf52bb8d2013-08-03 20:24:58 +0000250#ifndef SQLITE_STAT4_SAMPLES
251# define SQLITE_STAT4_SAMPLES 24
drhfaacf172011-08-12 01:51:45 +0000252#endif
253
254/*
danf00e9022013-08-14 19:54:12 +0000255** Three SQL functions - stat_init(), stat_push(), and stat_get() -
drhade3add2011-08-13 00:58:05 +0000256** share an instance of the following structure to hold their state
257** information.
258*/
danf52bb8d2013-08-03 20:24:58 +0000259typedef struct Stat4Accum Stat4Accum;
danf00e9022013-08-14 19:54:12 +0000260typedef struct Stat4Sample Stat4Sample;
261struct Stat4Sample {
262 i64 iRowid; /* Rowid in main table of the key */
263 tRowcnt *anEq; /* sqlite_stat4.nEq */
264 tRowcnt *anLt; /* sqlite_stat4.nLt */
265 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
266 u8 isPSample; /* True if a periodic sample */
267 int iCol; /* If !isPSample, the reason for inclusion */
268 u32 iHash; /* Tiebreaker hash */
269};
danf52bb8d2013-08-03 20:24:58 +0000270struct Stat4Accum {
drhade3add2011-08-13 00:58:05 +0000271 tRowcnt nRow; /* Number of rows in the entire table */
272 tRowcnt nPSample; /* How often to do a periodic sample */
danf00e9022013-08-14 19:54:12 +0000273 int nCol; /* Number of columns in index + rowid */
drhade3add2011-08-13 00:58:05 +0000274 int mxSample; /* Maximum number of samples to accumulate */
danf00e9022013-08-14 19:54:12 +0000275 Stat4Sample current; /* Current row as a Stat4Sample */
drhf404c862011-08-13 15:25:10 +0000276 u32 iPrn; /* Pseudo-random number used for sampling */
danf00e9022013-08-14 19:54:12 +0000277 Stat4Sample *aBest; /* Array of (nCol-1) best samples */
278 int iMin; /* Index in a[] of entry with minimum score */
279 int nSample; /* Current number of samples */
280 int iGet; /* Index of current sample accessed by stat_get() */
281 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
drhade3add2011-08-13 00:58:05 +0000282};
283
drhade3add2011-08-13 00:58:05 +0000284/*
danf00e9022013-08-14 19:54:12 +0000285** Implementation of the stat_init(C,N,S) SQL function. The three parameters
danf52bb8d2013-08-03 20:24:58 +0000286** are the number of rows in the table or index (C), the number of columns
287** in the index (N) and the number of samples to accumulate (S).
drhade3add2011-08-13 00:58:05 +0000288**
danf52bb8d2013-08-03 20:24:58 +0000289** This routine allocates the Stat4Accum object in heap memory. The return
290** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
291** the size of the blob is sizeof(void*) bytes).
drhade3add2011-08-13 00:58:05 +0000292*/
danf00e9022013-08-14 19:54:12 +0000293static void statInit(
drhade3add2011-08-13 00:58:05 +0000294 sqlite3_context *context,
295 int argc,
296 sqlite3_value **argv
297){
danf52bb8d2013-08-03 20:24:58 +0000298 Stat4Accum *p;
299 u8 *pSpace; /* Allocated space not yet assigned */
300 tRowcnt nRow; /* Number of rows in table (C) */
301 int mxSample; /* Maximum number of samples collected */
302 int nCol; /* Number of columns in index being sampled */
303 int n; /* Bytes of space to allocate */
304 int i; /* Used to iterate through p->aSample[] */
drhade3add2011-08-13 00:58:05 +0000305
danf52bb8d2013-08-03 20:24:58 +0000306 /* Decode the three function arguments */
drh68257192011-08-16 17:06:21 +0000307 UNUSED_PARAMETER(argc);
drhade3add2011-08-13 00:58:05 +0000308 nRow = (tRowcnt)sqlite3_value_int64(argv[0]);
danf52bb8d2013-08-03 20:24:58 +0000309 mxSample = sqlite3_value_int(argv[2]);
dan8ad169a2013-08-12 20:14:04 +0000310 nCol = sqlite3_value_int(argv[1]);
dandd6e1f12013-08-10 19:08:30 +0000311 assert( nCol>1 ); /* >1 because it includes the rowid column */
danf52bb8d2013-08-03 20:24:58 +0000312
313 /* Allocate the space required for the Stat4Accum object */
danf00e9022013-08-14 19:54:12 +0000314 n = sizeof(*p)
315 + sizeof(tRowcnt)*nCol /* Stat4Accum.anEq */
316 + sizeof(tRowcnt)*nCol /* Stat4Accum.anLt */
317 + sizeof(tRowcnt)*nCol /* Stat4Accum.anDLt */
318 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
319 + sizeof(tRowcnt)*3*nCol*(nCol+mxSample);
320 p = sqlite3MallocZero(n);
drhade3add2011-08-13 00:58:05 +0000321 if( p==0 ){
322 sqlite3_result_error_nomem(context);
323 return;
324 }
danf52bb8d2013-08-03 20:24:58 +0000325
drhade3add2011-08-13 00:58:05 +0000326 p->nRow = nRow;
danf52bb8d2013-08-03 20:24:58 +0000327 p->nCol = nCol;
drhade3add2011-08-13 00:58:05 +0000328 p->mxSample = mxSample;
drhf404c862011-08-13 15:25:10 +0000329 p->nPSample = p->nRow/(mxSample/3+1) + 1;
danf00e9022013-08-14 19:54:12 +0000330 p->iGet = -1;
331
332 p->current.anDLt = (tRowcnt*)&p[1];
333 p->current.anEq = &p->current.anDLt[nCol];
334 p->current.anLt = &p->current.anEq[nCol];
drhf404c862011-08-13 15:25:10 +0000335 sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
danf00e9022013-08-14 19:54:12 +0000336
337 /* Set up the Stat4Accum.a[] and aBest[] arrays */
338 p->a = (struct Stat4Sample*)&p->current.anLt[nCol];
339 p->aBest = &p->a[mxSample];
340 pSpace = (u8*)(&p->a[mxSample+nCol]);
341 for(i=0; i<(mxSample+nCol); i++){
danf52bb8d2013-08-03 20:24:58 +0000342 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nCol);
343 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nCol);
344 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nCol);
345 }
346 assert( (pSpace - (u8*)p)==n );
347
danf00e9022013-08-14 19:54:12 +0000348 for(i=0; i<nCol; i++){
349 p->aBest[i].iCol = i;
350 }
351
danf52bb8d2013-08-03 20:24:58 +0000352 /* Return a pointer to the allocated object to the caller */
drhade3add2011-08-13 00:58:05 +0000353 sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
354}
danf00e9022013-08-14 19:54:12 +0000355static const FuncDef statInitFuncdef = {
356 3, /* nArg */
357 SQLITE_UTF8, /* iPrefEnc */
358 0, /* flags */
359 0, /* pUserData */
360 0, /* pNext */
361 statInit, /* xFunc */
362 0, /* xStep */
363 0, /* xFinalize */
364 "stat_init", /* zName */
365 0, /* pHash */
366 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000367};
368
danf00e9022013-08-14 19:54:12 +0000369/*
370** Return true if pNew is to be preferred over pOld.
371*/
372static int sampleIsBetter(Stat4Sample *pNew, Stat4Sample *pOld){
373 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
374 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
375
376 assert( pOld->isPSample==0 && pNew->isPSample==0 );
377 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
378
379 if( (nEqNew>nEqOld)
380 || (nEqNew==nEqOld && pNew->iCol<pOld->iCol)
381 || (nEqNew==nEqOld && pNew->iCol==pOld->iCol && pNew->iHash>pOld->iHash)
382 ){
383 return 1;
384 }
385 return 0;
386}
drhade3add2011-08-13 00:58:05 +0000387
388/*
danf00e9022013-08-14 19:54:12 +0000389** Copy the contents of object (*pFrom) into (*pTo).
drhade3add2011-08-13 00:58:05 +0000390*/
danf00e9022013-08-14 19:54:12 +0000391void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
392 pTo->iRowid = pFrom->iRowid;
393 pTo->isPSample = pFrom->isPSample;
394 pTo->iCol = pFrom->iCol;
395 pTo->iHash = pFrom->iHash;
396 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
397 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
398 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
399}
400
401/*
402** Copy the contents of sample *pNew into the p->a[] array. If necessary,
403** remove the least desirable sample from p->a[] to make room.
404*/
405static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
406 Stat4Sample *pSample;
danf52bb8d2013-08-03 20:24:58 +0000407 int i;
danf00e9022013-08-14 19:54:12 +0000408 i64 iSeq;
409 i64 iPos;
danf52bb8d2013-08-03 20:24:58 +0000410
danf00e9022013-08-14 19:54:12 +0000411 assert( IsStat4 || nEqZero==0 );
danf52bb8d2013-08-03 20:24:58 +0000412
danf00e9022013-08-14 19:54:12 +0000413 if( pNew->isPSample==0 ){
dan1f616ad2013-08-15 14:39:09 +0000414 Stat4Sample *pUpgrade = 0;
danf00e9022013-08-14 19:54:12 +0000415 assert( pNew->anEq[pNew->iCol]>0 );
drhade3add2011-08-13 00:58:05 +0000416
danf00e9022013-08-14 19:54:12 +0000417 /* This sample is being added because the prefix that ends in column
418 ** iCol occurs many times in the table. However, if we have already
419 ** added a sample that shares this prefix, there is no need to add
dan1f616ad2013-08-15 14:39:09 +0000420 ** this one. Instead, upgrade the priority of the highest priority
421 ** existing sample that shares this prefix. */
danf00e9022013-08-14 19:54:12 +0000422 for(i=p->nSample-1; i>=0; i--){
423 Stat4Sample *pOld = &p->a[i];
424 if( pOld->anEq[pNew->iCol]==0 ){
dan1f616ad2013-08-15 14:39:09 +0000425 if( pOld->isPSample ) return;
426 assert( sampleIsBetter(pNew, pOld) );
427 if( pUpgrade==0 || sampleIsBetter(pOld, pUpgrade) ){
428 pUpgrade = pOld;
danf00e9022013-08-14 19:54:12 +0000429 }
dan1f28ead2013-08-07 16:15:32 +0000430 }
431 }
dan1f616ad2013-08-15 14:39:09 +0000432 if( pUpgrade ){
433 pUpgrade->iCol = pNew->iCol;
434 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
435 goto find_new_min;
436 }
drhade3add2011-08-13 00:58:05 +0000437 }
danf52bb8d2013-08-03 20:24:58 +0000438
danf00e9022013-08-14 19:54:12 +0000439 /* If necessary, remove sample iMin to make room for the new sample. */
440 if( p->nSample>=p->mxSample ){
441 Stat4Sample *pMin = &p->a[p->iMin];
danc55521a2013-08-05 05:34:30 +0000442 tRowcnt *anEq = pMin->anEq;
danc55521a2013-08-05 05:34:30 +0000443 tRowcnt *anLt = pMin->anLt;
danf00e9022013-08-14 19:54:12 +0000444 tRowcnt *anDLt = pMin->anDLt;
445 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
drhf404c862011-08-13 15:25:10 +0000446 pSample = &p->a[p->nSample-1];
danc55521a2013-08-05 05:34:30 +0000447 pSample->anEq = anEq;
448 pSample->anDLt = anDLt;
449 pSample->anLt = anLt;
danf00e9022013-08-14 19:54:12 +0000450 p->nSample = p->mxSample-1;
dan8ad169a2013-08-12 20:14:04 +0000451 }
drhade3add2011-08-13 00:58:05 +0000452
danf00e9022013-08-14 19:54:12 +0000453 /* Figure out where in the a[] array the new sample should be inserted. */
454 iSeq = pNew->anLt[p->nCol-1];
455 for(iPos=p->nSample; iPos>0; iPos--){
456 if( iSeq>p->a[iPos-1].anLt[p->nCol-1] ) break;
457 }
458
459 /* Insert the new sample */
460 pSample = &p->a[iPos];
461 if( iPos!=p->nSample ){
462 Stat4Sample *pEnd = &p->a[p->nSample];
463 tRowcnt *anEq = pEnd->anEq;
464 tRowcnt *anLt = pEnd->anLt;
465 tRowcnt *anDLt = pEnd->anDLt;
466 memmove(&p->a[iPos], &p->a[iPos+1], (p->nSample-iPos)*sizeof(p->a[0]));
467 pSample->anEq = anEq;
468 pSample->anDLt = anDLt;
469 pSample->anLt = anLt;
470 }
471 p->nSample++;
472 sampleCopy(p, pSample, pNew);
473
474 /* Zero the first nEqZero entries in the anEq[] array. */
475 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
476
477 find_new_min:
478 if( p->nSample>=p->mxSample ){
479 int iMin = -1;
danf52bb8d2013-08-03 20:24:58 +0000480 for(i=0; i<p->mxSample; i++){
481 if( p->a[i].isPSample ) continue;
danf00e9022013-08-14 19:54:12 +0000482 if( iMin<0 || sampleIsBetter(&p->a[iMin], &p->a[i]) ){
drhade3add2011-08-13 00:58:05 +0000483 iMin = i;
drhade3add2011-08-13 00:58:05 +0000484 }
485 }
danf52bb8d2013-08-03 20:24:58 +0000486 assert( iMin>=0 );
drhade3add2011-08-13 00:58:05 +0000487 p->iMin = iMin;
488 }
489}
danf00e9022013-08-14 19:54:12 +0000490
491/*
492** Field iChng of the index being scanned has changed. So at this point
493** p->current contains a sample that reflects the previous row of the
494** index. The value of anEq[iChng] and subsequent anEq[] elements are
495** correct at this point.
496*/
497static void samplePushPrevious(Stat4Accum *p, int iChng){
498 if( IsStat4 ){
499 int i;
500
501 /* Check if any samples from the aBest[] array should be pushed
502 ** into IndexSample.a[] at this point. */
503 for(i=(p->nCol-2); i>=iChng; i--){
504 Stat4Sample *pBest = &p->aBest[i];
505 if( p->nSample<p->mxSample
506 || sampleIsBetter(pBest, &p->a[p->iMin])
507 ){
508 sampleInsert(p, pBest, i);
509 }
510 }
511
512 /* Update the anEq[] fields of any samples already collected. */
513 for(i=p->nSample-1; i>=0; i--){
514 int j;
515 for(j=iChng; j<p->nCol; j++){
516 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
517 }
518 }
519 }
520
521 if( IsStat3 && iChng==0 ){
522 tRowcnt nLt = p->current.anLt[0];
523 tRowcnt nEq = p->current.anEq[0];
524
525 /* Check if this is to be a periodic sample. If so, add it. */
526 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
527 p->current.isPSample = 1;
528 sampleInsert(p, &p->current, 0);
529 p->current.isPSample = 0;
530 }else
531
532 /* Or if it is a non-periodic sample. Add it in this case too. */
533 if( p->nSample<p->mxSample || sampleIsBetter(&p->current, &p->a[p->iMin]) ){
534 sampleInsert(p, &p->current, 0);
535 }
536 }
537}
538
539/*
540** Implementation of the stat_push SQL function.
541**
542** stat_push(P,R,C)
543**
544** The return value is always NULL.
545*/
546static void statPush(
547 sqlite3_context *context,
548 int argc,
549 sqlite3_value **argv
550){
551 int i;
552
553 /* The three function arguments */
554 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
555 i64 rowid = sqlite3_value_int64(argv[1]);
556 int iChng = sqlite3_value_int(argv[2]);
557
558 assert( p->nCol>1 ); /* Includes rowid field */
559 assert( iChng<p->nCol );
560
561 /* p->current.anEq[0] is false the first time this function is called. */
562 if( p->current.anEq[0] ){
563
564 samplePushPrevious(p, iChng);
565
566 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
567 ** to the current row of the index. */
568 for(i=0; i<iChng; i++){
569 p->current.anEq[i]++;
570 }
571 for(i=iChng; i<p->nCol; i++){
572 p->current.anDLt[i]++;
573 p->current.anLt[i] += p->current.anEq[i];
574 p->current.anEq[i] = 1;
575 }
576
577 }else{
578 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
579 }
580
581 if( IsStat4 || IsStat3 ){
582 p->current.iRowid = rowid;
583 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
584 }
585
586 if( IsStat4 ){
587 tRowcnt nLt = p->current.anLt[p->nCol-1];
588
589 /* Check if this is to be a periodic sample. If so, add it. */
590 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
591 p->current.isPSample = 1;
592 p->current.iCol = 0;
593 sampleInsert(p, &p->current, p->nCol-1);
594 p->current.isPSample = 0;
595 }
596
597 /* Update the aBest[] array. */
598 for(i=0; i<(p->nCol-1); i++){
599 p->current.iCol = i;
600 if( i>=iChng || sampleIsBetter(&p->current, &p->aBest[i]) ){
601 sampleCopy(p, &p->aBest[i], &p->current);
602 }
603 }
604 }
605}
606static const FuncDef statPushFuncdef = {
607 3, /* nArg */
608 SQLITE_UTF8, /* iPrefEnc */
609 0, /* flags */
610 0, /* pUserData */
611 0, /* pNext */
612 statPush, /* xFunc */
613 0, /* xStep */
614 0, /* xFinalize */
615 "stat_push", /* zName */
616 0, /* pHash */
617 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000618};
619
danf00e9022013-08-14 19:54:12 +0000620#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
621#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
622#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
623#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
624#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
625
drhade3add2011-08-13 00:58:05 +0000626/*
627** Implementation of the stat3_get(P,N,...) SQL function. This routine is
628** used to query the results. Content is returned for the Nth sqlite_stat3
629** row where N is between 0 and S-1 and S is the number of samples. The
630** value returned depends on the number of arguments.
631**
632** argc==2 result: rowid
633** argc==3 result: nEq
634** argc==4 result: nLt
drhf404c862011-08-13 15:25:10 +0000635** argc==5 result: nDLt
drhade3add2011-08-13 00:58:05 +0000636*/
danf00e9022013-08-14 19:54:12 +0000637static void statGet(
drhade3add2011-08-13 00:58:05 +0000638 sqlite3_context *context,
639 int argc,
640 sqlite3_value **argv
641){
danf52bb8d2013-08-03 20:24:58 +0000642 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
danf00e9022013-08-14 19:54:12 +0000643 int eCall = sqlite3_value_int(argv[1]);
644 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
645 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
646 || eCall==STAT_GET_NDLT
647 );
drhade3add2011-08-13 00:58:05 +0000648
danf00e9022013-08-14 19:54:12 +0000649 if( eCall==STAT_GET_STAT1 ){
650 /* Return the value to store in the "stat" column of the sqlite_stat1
651 ** table for this index.
652 **
653 ** The value is a string composed of a list of integers describing
654 ** the index. The first integer in the list is the total number of
655 ** entries in the index. There is one additional integer in the list
656 ** for each indexed column. This additional integer is an estimate of
657 ** the number of rows matched by a stabbing query on the index using
658 ** a key with the corresponding number of fields. In other words,
659 ** if the index is on columns (a,b) and the sqlite_stat1 value is
660 ** "100 10 2", then SQLite estimates that:
661 **
662 ** * the index contains 100 rows,
663 ** * "WHERE a=?" matches 10 rows, and
664 ** * "WHERE a=? AND b=?" matches 2 rows.
665 **
666 ** If D is the count of distinct values and K is the total number of
667 ** rows, then each estimate is computed as:
668 **
669 ** I = (K+D-1)/D
670 */
671 char *z;
672 int i;
673
674 char *zRet = sqlite3MallocZero(p->nCol * 25);
675 if( zRet==0 ){
676 sqlite3_result_error_nomem(context);
677 return;
678 }
679
680 sqlite3_snprintf(24, zRet, "%lld", p->nRow);
681 z = zRet + sqlite3Strlen30(zRet);
682 for(i=0; i<(p->nCol-1); i++){
683 i64 nDistinct = p->current.anDLt[i] + 1;
684 i64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
685 sqlite3_snprintf(24, z, " %lld", iVal);
686 z += sqlite3Strlen30(z);
687 assert( p->current.anEq[i] );
688 }
689 assert( z[0]=='\0' && z>zRet );
690
691 sqlite3_result_text(context, zRet, -1, sqlite3_free);
692 }else if( eCall==STAT_GET_ROWID ){
693 if( p->iGet<0 ){
694 samplePushPrevious(p, 0);
695 p->iGet = 0;
696 }
697 if( p->iGet<p->nSample ){
698 sqlite3_result_int64(context, p->a[p->iGet].iRowid);
699 }
700 }else{
danf52bb8d2013-08-03 20:24:58 +0000701 tRowcnt *aCnt = 0;
danf00e9022013-08-14 19:54:12 +0000702
703 assert( p->iGet<p->nSample );
704 switch( eCall ){
705 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
706 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
707 default: {
708 aCnt = p->a[p->iGet].anDLt;
709 p->iGet++;
710 break;
711 }
danf52bb8d2013-08-03 20:24:58 +0000712 }
713
dan8ad169a2013-08-12 20:14:04 +0000714 if( IsStat3 ){
715 sqlite3_result_int64(context, (i64)aCnt[0]);
danf52bb8d2013-08-03 20:24:58 +0000716 }else{
danf00e9022013-08-14 19:54:12 +0000717 char *zRet = sqlite3MallocZero(p->nCol * 25);
dan8ad169a2013-08-12 20:14:04 +0000718 if( zRet==0 ){
719 sqlite3_result_error_nomem(context);
720 }else{
721 int i;
722 char *z = zRet;
723 for(i=0; i<p->nCol; i++){
724 sqlite3_snprintf(24, z, "%lld ", aCnt[i]);
725 z += sqlite3Strlen30(z);
726 }
727 assert( z[0]=='\0' && z>zRet );
728 z[-1] = '\0';
729 sqlite3_result_text(context, zRet, -1, sqlite3_free);
danf52bb8d2013-08-03 20:24:58 +0000730 }
danf52bb8d2013-08-03 20:24:58 +0000731 }
drhade3add2011-08-13 00:58:05 +0000732 }
733}
danf00e9022013-08-14 19:54:12 +0000734static const FuncDef statGetFuncdef = {
735 2, /* nArg */
736 SQLITE_UTF8, /* iPrefEnc */
737 0, /* flags */
738 0, /* pUserData */
739 0, /* pNext */
740 statGet, /* xFunc */
741 0, /* xStep */
742 0, /* xFinalize */
743 "stat_get", /* zName */
744 0, /* pHash */
745 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000746};
drhade3add2011-08-13 00:58:05 +0000747
danf00e9022013-08-14 19:54:12 +0000748static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
749 assert( regOut!=regStat4 && regOut!=regStat4+1 );
750 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
751 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
752 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
753 sqlite3VdbeChangeP5(v, 2);
754}
drhade3add2011-08-13 00:58:05 +0000755
756/*
drhff2d5ea2005-07-23 00:41:48 +0000757** Generate code to do an analysis of all indices associated with
758** a single table.
759*/
760static void analyzeOneTable(
761 Parse *pParse, /* Parser context */
762 Table *pTab, /* Table whose indices are to be analyzed */
drha071bc52011-03-31 02:03:28 +0000763 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
drhdfe88ec2008-11-03 20:55:06 +0000764 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
danc6129702013-08-05 19:04:07 +0000765 int iMem, /* Available memory locations begin here */
766 int iTab /* Next available cursor */
drhff2d5ea2005-07-23 00:41:48 +0000767){
dan0f9a34e2009-08-19 16:34:31 +0000768 sqlite3 *db = pParse->db; /* Database handle */
dan69188d92009-08-19 08:18:32 +0000769 Index *pIdx; /* An index to being analyzed */
770 int iIdxCur; /* Cursor open on index being analyzed */
danc6129702013-08-05 19:04:07 +0000771 int iTabCur; /* Table cursor */
dan69188d92009-08-19 08:18:32 +0000772 Vdbe *v; /* The virtual machine being built up */
773 int i; /* Loop counter */
drhf6cf1ff2011-03-30 14:54:05 +0000774 int jZeroRows = -1; /* Jump from here if number of rows is zero */
dan69188d92009-08-19 08:18:32 +0000775 int iDb; /* Index of database containing pTab */
drh721dfcf2013-08-01 04:39:17 +0000776 u8 needTableCnt = 1; /* True to count the table */
danf00e9022013-08-14 19:54:12 +0000777 int regNewRowid = iMem++; /* Rowid for the inserted record */
778 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
779 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
780 int regChng = iMem++; /* Index of changed index field */
781 int regTemp = iMem++; /* Temporary use register */
dane275dc32009-08-18 16:24:58 +0000782 int regTabname = iMem++; /* Register containing table name */
783 int regIdxname = iMem++; /* Register containing index name */
danf00e9022013-08-14 19:54:12 +0000784 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
785 int regPrev = iMem; /* MUST BE LAST (see below) */
dan68c4dbb2009-08-20 09:11:06 +0000786
danf00e9022013-08-14 19:54:12 +0000787 pParse->nMem = MAX(pParse->nMem, regChng);
drhff2d5ea2005-07-23 00:41:48 +0000788 v = sqlite3GetVdbe(pParse);
drh15564052010-09-25 22:32:56 +0000789 if( v==0 || NEVER(pTab==0) ){
790 return;
791 }
drhf39d29c2010-09-28 17:34:46 +0000792 if( pTab->tnum==0 ){
793 /* Do not gather statistics on views or virtual tables */
drh15564052010-09-25 22:32:56 +0000794 return;
795 }
drh503a6862013-03-01 01:07:17 +0000796 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
drh15564052010-09-25 22:32:56 +0000797 /* Do not gather statistics on system tables */
drhff2d5ea2005-07-23 00:41:48 +0000798 return;
799 }
dan0f9a34e2009-08-19 16:34:31 +0000800 assert( sqlite3BtreeHoldsAllMutexes(db) );
801 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977da184232006-01-05 11:34:32 +0000802 assert( iDb>=0 );
drh21206082011-04-04 18:22:02 +0000803 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhe6e04962005-07-23 02:17:03 +0000804#ifndef SQLITE_OMIT_AUTHORIZATION
805 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
dan0f9a34e2009-08-19 16:34:31 +0000806 db->aDb[iDb].zName ) ){
drhe6e04962005-07-23 02:17:03 +0000807 return;
808 }
809#endif
810
dane0432012013-08-05 18:00:56 +0000811 /* Establish a read-lock on the table at the shared-cache level.
danf00e9022013-08-14 19:54:12 +0000812 ** Open a read-only cursor on the table. Also allocate a cursor number
813 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
814 ** this time though. */
danielk1977c00da102006-01-07 13:21:04 +0000815 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danc6129702013-08-05 19:04:07 +0000816 iTabCur = iTab++;
danf00e9022013-08-14 19:54:12 +0000817 iIdxCur = iTab++;
danc6129702013-08-05 19:04:07 +0000818 pParse->nTab = MAX(pParse->nTab, iTab);
dane0432012013-08-05 18:00:56 +0000819 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
drh15564052010-09-25 22:32:56 +0000820 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
dane0432012013-08-05 18:00:56 +0000821
drhff2d5ea2005-07-23 00:41:48 +0000822 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
danf52bb8d2013-08-03 20:24:58 +0000823 int nCol; /* Number of columns indexed by pIdx */
824 KeyInfo *pKey; /* KeyInfo structure for pIdx */
danf00e9022013-08-14 19:54:12 +0000825 int *aGotoChng; /* Array of jump instruction addresses */
826 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
827 int addrGotoChng0; /* Address of "Goto addr_chng_0" */
828 int addrNextRow; /* Address of "next_row:" */
danielk1977b3bf5562006-01-10 17:58:23 +0000829
drha071bc52011-03-31 02:03:28 +0000830 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
drh721dfcf2013-08-01 04:39:17 +0000831 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
drhfaacf172011-08-12 01:51:45 +0000832 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
drha071bc52011-03-31 02:03:28 +0000833 nCol = pIdx->nColumn;
danf00e9022013-08-14 19:54:12 +0000834 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
835 if( aGotoChng==0 ) continue;
drha071bc52011-03-31 02:03:28 +0000836 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
dane275dc32009-08-18 16:24:58 +0000837
drh15564052010-09-25 22:32:56 +0000838 /* Populate the register containing the index name. */
dan69188d92009-08-19 08:18:32 +0000839 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
840
dane0432012013-08-05 18:00:56 +0000841 /*
danf00e9022013-08-14 19:54:12 +0000842 ** Pseudo-code for loop that calls stat_push():
dane0432012013-08-05 18:00:56 +0000843 **
danf00e9022013-08-14 19:54:12 +0000844 ** Rewind csr
845 ** if eof(csr) goto end_of_scan;
846 ** regChng = 0
847 ** goto chng_addr_0;
dane0432012013-08-05 18:00:56 +0000848 **
dandd6e1f12013-08-10 19:08:30 +0000849 ** next_row:
danf00e9022013-08-14 19:54:12 +0000850 ** regChng = 0
851 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
852 ** regChng = 1
853 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
854 ** ...
855 ** regChng = N
856 ** goto chng_addr_N
dane0432012013-08-05 18:00:56 +0000857 **
danf00e9022013-08-14 19:54:12 +0000858 ** chng_addr_0:
859 ** regPrev(0) = idx(0)
860 ** chng_addr_1:
861 ** regPrev(1) = idx(1)
862 ** ...
dane0432012013-08-05 18:00:56 +0000863 **
danf00e9022013-08-14 19:54:12 +0000864 ** chng_addr_N:
865 ** regRowid = idx(rowid)
866 ** stat_push(P, regRowid, regChng)
867 ** Next csr
868 ** if !eof(csr) goto next_row;
dane0432012013-08-05 18:00:56 +0000869 **
danf00e9022013-08-14 19:54:12 +0000870 ** end_of_scan:
dane0432012013-08-05 18:00:56 +0000871 */
danf00e9022013-08-14 19:54:12 +0000872
873 /* Make sure there are enough memory cells allocated to accommodate
874 ** the regPrev array and a trailing rowid (the rowid slot is required
875 ** when building a record to insert into the sample column of
876 ** the sqlite_stat4 table. */
danc6129702013-08-05 19:04:07 +0000877 pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
dan02fa4692009-08-17 17:06:58 +0000878
danf00e9022013-08-14 19:54:12 +0000879 /* Open a read-only cursor on the index being analyzed. */
dane0432012013-08-05 18:00:56 +0000880 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
danf00e9022013-08-14 19:54:12 +0000881 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
882 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
883 VdbeComment((v, "%s", pIdx->zName));
dane0432012013-08-05 18:00:56 +0000884
danf00e9022013-08-14 19:54:12 +0000885 /* Invoke the stat_init() function. The arguments are:
danf52bb8d2013-08-03 20:24:58 +0000886 **
887 ** * the number of rows in the index,
dandd6e1f12013-08-10 19:08:30 +0000888 ** * the number of columns in the index including the rowid,
danf00e9022013-08-14 19:54:12 +0000889 ** * the recommended number of samples for the stat3/stat4 table.
danf52bb8d2013-08-03 20:24:58 +0000890 */
891 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+1);
dandd6e1f12013-08-10 19:08:30 +0000892 sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+2);
danf52bb8d2013-08-03 20:24:58 +0000893 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT4_SAMPLES, regStat4+3);
894 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
danf00e9022013-08-14 19:54:12 +0000895 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
danf52bb8d2013-08-03 20:24:58 +0000896 sqlite3VdbeChangeP5(v, 3);
danf52bb8d2013-08-03 20:24:58 +0000897
danf00e9022013-08-14 19:54:12 +0000898 /* Implementation of the following:
899 **
900 ** Rewind csr
901 ** if eof(csr) goto end_of_scan;
902 ** regChng = 0
903 ** goto next_push_0;
904 **
dandd6e1f12013-08-10 19:08:30 +0000905 */
danf00e9022013-08-14 19:54:12 +0000906 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
907 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
908 addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
danf52bb8d2013-08-03 20:24:58 +0000909
danf00e9022013-08-14 19:54:12 +0000910 /*
911 ** next_row:
912 ** regChng = 0
913 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
914 ** regChng = 1
915 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
916 ** ...
917 ** regChng = N
918 ** goto chng_addr_N
919 */
920 addrNextRow = sqlite3VdbeCurrentAddr(v);
dandd6e1f12013-08-10 19:08:30 +0000921 for(i=0; i<nCol; i++){
dane0432012013-08-05 18:00:56 +0000922 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
danf00e9022013-08-14 19:54:12 +0000923 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
924 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
925 aGotoChng[i] =
926 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
dane0432012013-08-05 18:00:56 +0000927 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
928 }
danf00e9022013-08-14 19:54:12 +0000929 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
930 aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
dane0432012013-08-05 18:00:56 +0000931
danf00e9022013-08-14 19:54:12 +0000932 /*
933 ** chng_addr_0:
934 ** regPrev(0) = idx(0)
935 ** chng_addr_1:
936 ** regPrev(1) = idx(1)
937 ** ...
drhff2d5ea2005-07-23 00:41:48 +0000938 */
danf00e9022013-08-14 19:54:12 +0000939 sqlite3VdbeJumpHere(v, addrGotoChng0);
drhff2d5ea2005-07-23 00:41:48 +0000940 for(i=0; i<nCol; i++){
danf00e9022013-08-14 19:54:12 +0000941 sqlite3VdbeJumpHere(v, aGotoChng[i]);
942 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
drhff2d5ea2005-07-23 00:41:48 +0000943 }
danf00e9022013-08-14 19:54:12 +0000944
945 /*
946 ** chng_addr_N:
947 ** regRowid = idx(rowid)
948 ** stat_push(P, regRowid, regChng)
949 ** Next csr
950 ** if !eof(csr) goto next_row;
951 */
952 sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
953 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
954 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
955 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
956 sqlite3VdbeChangeP5(v, 3);
957 assert( regRowid==(regStat4+1) && regChng==(regStat4+2) );
958 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
959
960 /* Add the entry to the stat1 table. */
961 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
962 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drhade3add2011-08-13 00:58:05 +0000963 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +0000964 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh2d401ab2008-01-10 23:50:11 +0000965 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
danf00e9022013-08-14 19:54:12 +0000966
967 /* Add the entries to the stat3 or stat4 table. */
968 if( IsStat3 || IsStat4 ){
969 int regEq = regStat1;
970 int regLt = regStat1+1;
971 int regDLt = regStat1+2;
972 int regSample = regStat1+3;
973 int regCol = regStat1+4;
974 int regSampleRowid = regCol + nCol;
975 int addrNext;
976 int addrIsNull;
977
978 pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
979
980 addrNext = sqlite3VdbeCurrentAddr(v);
981 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
982 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
983 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
984 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
985 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
986 sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
987 if( IsStat3 ){
988 int iCol = pIdx->aiColumn[0];
989 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regSample);
990 }else{
991 for(i=0; i<nCol; i++){
992 int iCol = pIdx->aiColumn[i];
993 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
994 }
995 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
996 }
997
998 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
999 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
1000 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
1001 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
1002 sqlite3VdbeJumpHere(v, addrIsNull);
1003 }
1004
1005 /* Jump here if the index is empty */
1006 sqlite3VdbeJumpHere(v, addrRewind);
1007 sqlite3DbFree(db, aGotoChng);
drh15564052010-09-25 22:32:56 +00001008 }
1009
danf00e9022013-08-14 19:54:12 +00001010
drh721dfcf2013-08-01 04:39:17 +00001011 /* Create a single sqlite_stat1 entry containing NULL as the index
1012 ** name and the row count as the content.
drh15564052010-09-25 22:32:56 +00001013 */
drh721dfcf2013-08-01 04:39:17 +00001014 if( pOnlyIdx==0 && needTableCnt ){
drh15564052010-09-25 22:32:56 +00001015 VdbeComment((v, "%s", pTab->zName));
dane0432012013-08-05 18:00:56 +00001016 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
drhfaacf172011-08-12 01:51:45 +00001017 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
drh721dfcf2013-08-01 04:39:17 +00001018 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
danf00e9022013-08-14 19:54:12 +00001019 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drh721dfcf2013-08-01 04:39:17 +00001020 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001021 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh721dfcf2013-08-01 04:39:17 +00001022 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh15564052010-09-25 22:32:56 +00001023 sqlite3VdbeJumpHere(v, jZeroRows);
1024 }
drhff2d5ea2005-07-23 00:41:48 +00001025}
1026
drhfaacf172011-08-12 01:51:45 +00001027
drhff2d5ea2005-07-23 00:41:48 +00001028/*
drh497e4462005-07-23 03:18:40 +00001029** Generate code that will cause the most recent index analysis to
drh15564052010-09-25 22:32:56 +00001030** be loaded into internal hash tables where is can be used.
drh497e4462005-07-23 03:18:40 +00001031*/
1032static void loadAnalysis(Parse *pParse, int iDb){
1033 Vdbe *v = sqlite3GetVdbe(pParse);
drhcf1be452007-05-12 12:08:51 +00001034 if( v ){
drh66a51672008-01-03 00:01:23 +00001035 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
drhcf1be452007-05-12 12:08:51 +00001036 }
drh497e4462005-07-23 03:18:40 +00001037}
1038
1039/*
drhff2d5ea2005-07-23 00:41:48 +00001040** Generate code that will do an analysis of an entire database
1041*/
1042static void analyzeDatabase(Parse *pParse, int iDb){
1043 sqlite3 *db = pParse->db;
danielk1977e501b892006-01-09 06:29:47 +00001044 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
drhff2d5ea2005-07-23 00:41:48 +00001045 HashElem *k;
1046 int iStatCur;
1047 int iMem;
danc6129702013-08-05 19:04:07 +00001048 int iTab;
drhff2d5ea2005-07-23 00:41:48 +00001049
1050 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001051 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001052 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001053 openStatTable(pParse, iDb, iStatCur, 0, 0);
drh0a07c102008-01-03 18:03:08 +00001054 iMem = pParse->nMem+1;
danc6129702013-08-05 19:04:07 +00001055 iTab = pParse->nTab;
drh21206082011-04-04 18:22:02 +00001056 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001057 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
drhff2d5ea2005-07-23 00:41:48 +00001058 Table *pTab = (Table*)sqliteHashData(k);
danc6129702013-08-05 19:04:07 +00001059 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
drhff2d5ea2005-07-23 00:41:48 +00001060 }
drh497e4462005-07-23 03:18:40 +00001061 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001062}
1063
1064/*
1065** Generate code that will do an analysis of a single table in
drha071bc52011-03-31 02:03:28 +00001066** a database. If pOnlyIdx is not NULL then it is a single index
1067** in pTab that should be analyzed.
drhff2d5ea2005-07-23 00:41:48 +00001068*/
drha071bc52011-03-31 02:03:28 +00001069static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
drhff2d5ea2005-07-23 00:41:48 +00001070 int iDb;
1071 int iStatCur;
1072
1073 assert( pTab!=0 );
drh1fee73e2007-08-29 04:00:57 +00001074 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +00001075 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhff2d5ea2005-07-23 00:41:48 +00001076 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001077 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001078 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001079 if( pOnlyIdx ){
1080 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
1081 }else{
1082 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
1083 }
danc6129702013-08-05 19:04:07 +00001084 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
drh497e4462005-07-23 03:18:40 +00001085 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001086}
1087
1088/*
1089** Generate code for the ANALYZE command. The parser calls this routine
1090** when it recognizes an ANALYZE command.
drh9f18e8a2005-07-08 12:13:04 +00001091**
1092** ANALYZE -- 1
drhff2d5ea2005-07-23 00:41:48 +00001093** ANALYZE <database> -- 2
drh9f18e8a2005-07-08 12:13:04 +00001094** ANALYZE ?<database>.?<tablename> -- 3
1095**
1096** Form 1 causes all indices in all attached databases to be analyzed.
1097** Form 2 analyzes all indices the single database named.
1098** Form 3 analyzes all indices associated with the named table.
1099*/
1100void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
drhff2d5ea2005-07-23 00:41:48 +00001101 sqlite3 *db = pParse->db;
1102 int iDb;
1103 int i;
1104 char *z, *zDb;
1105 Table *pTab;
drha071bc52011-03-31 02:03:28 +00001106 Index *pIdx;
drhff2d5ea2005-07-23 00:41:48 +00001107 Token *pTableName;
1108
1109 /* Read the database schema. If an error occurs, leave an error message
1110 ** and code in pParse and return NULL. */
drh1fee73e2007-08-29 04:00:57 +00001111 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhff2d5ea2005-07-23 00:41:48 +00001112 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1113 return;
1114 }
1115
drh05800a12009-04-16 17:45:47 +00001116 assert( pName2!=0 || pName1==0 );
drhff2d5ea2005-07-23 00:41:48 +00001117 if( pName1==0 ){
1118 /* Form 1: Analyze everything */
1119 for(i=0; i<db->nDb; i++){
1120 if( i==1 ) continue; /* Do not analyze the TEMP database */
1121 analyzeDatabase(pParse, i);
1122 }
drh05800a12009-04-16 17:45:47 +00001123 }else if( pName2->n==0 ){
drhff2d5ea2005-07-23 00:41:48 +00001124 /* Form 2: Analyze the database or table named */
1125 iDb = sqlite3FindDb(db, pName1);
1126 if( iDb>=0 ){
1127 analyzeDatabase(pParse, iDb);
drhe6e04962005-07-23 02:17:03 +00001128 }else{
drh17435752007-08-16 04:30:38 +00001129 z = sqlite3NameFromToken(db, pName1);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001130 if( z ){
drha071bc52011-03-31 02:03:28 +00001131 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
1132 analyzeTable(pParse, pIdx->pTable, pIdx);
1133 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
1134 analyzeTable(pParse, pTab, 0);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001135 }
drha071bc52011-03-31 02:03:28 +00001136 sqlite3DbFree(db, z);
drhe6e04962005-07-23 02:17:03 +00001137 }
drhff2d5ea2005-07-23 00:41:48 +00001138 }
drhff2d5ea2005-07-23 00:41:48 +00001139 }else{
1140 /* Form 3: Analyze the fully qualified table name */
1141 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
1142 if( iDb>=0 ){
1143 zDb = db->aDb[iDb].zName;
drh17435752007-08-16 04:30:38 +00001144 z = sqlite3NameFromToken(db, pTableName);
drhcf1be452007-05-12 12:08:51 +00001145 if( z ){
drha071bc52011-03-31 02:03:28 +00001146 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
1147 analyzeTable(pParse, pIdx->pTable, pIdx);
1148 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
1149 analyzeTable(pParse, pTab, 0);
drhcf1be452007-05-12 12:08:51 +00001150 }
drha071bc52011-03-31 02:03:28 +00001151 sqlite3DbFree(db, z);
drhff2d5ea2005-07-23 00:41:48 +00001152 }
1153 }
1154 }
drh9f18e8a2005-07-08 12:13:04 +00001155}
1156
drh497e4462005-07-23 03:18:40 +00001157/*
1158** Used to pass information from the analyzer reader through to the
1159** callback routine.
1160*/
1161typedef struct analysisInfo analysisInfo;
1162struct analysisInfo {
1163 sqlite3 *db;
1164 const char *zDatabase;
1165};
1166
1167/*
danf52bb8d2013-08-03 20:24:58 +00001168** The first argument points to a nul-terminated string containing a
1169** list of space separated integers. Read the first nOut of these into
1170** the array aOut[].
1171*/
1172static void decodeIntArray(
1173 char *zIntArray,
1174 int nOut,
1175 tRowcnt *aOut,
1176 int *pbUnordered
1177){
1178 char *z = zIntArray;
1179 int c;
1180 int i;
1181 tRowcnt v;
1182
1183 assert( pbUnordered==0 || *pbUnordered==0 );
drh6b0ae912013-08-12 17:00:08 +00001184
1185 if( z==0 ) z = "";
danf52bb8d2013-08-03 20:24:58 +00001186 for(i=0; *z && i<nOut; i++){
1187 v = 0;
1188 while( (c=z[0])>='0' && c<='9' ){
1189 v = v*10 + c - '0';
1190 z++;
1191 }
1192 aOut[i] = v;
1193 if( *z==' ' ) z++;
1194 }
1195 if( pbUnordered && strcmp(z, "unordered")==0 ){
1196 *pbUnordered = 1;
1197 }
1198}
1199
1200/*
drh497e4462005-07-23 03:18:40 +00001201** This callback is invoked once for each index when reading the
1202** sqlite_stat1 table.
1203**
drh15564052010-09-25 22:32:56 +00001204** argv[0] = name of the table
1205** argv[1] = name of the index (might be NULL)
1206** argv[2] = results of analysis - on integer for each column
1207**
1208** Entries for which argv[1]==NULL simply record the number of rows in
1209** the table.
drh497e4462005-07-23 03:18:40 +00001210*/
danielk197762c14b32008-11-19 09:05:26 +00001211static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
drh497e4462005-07-23 03:18:40 +00001212 analysisInfo *pInfo = (analysisInfo*)pData;
1213 Index *pIndex;
drh15564052010-09-25 22:32:56 +00001214 Table *pTable;
drh497e4462005-07-23 03:18:40 +00001215 const char *z;
1216
drh15564052010-09-25 22:32:56 +00001217 assert( argc==3 );
danielk1977f3d3c272008-11-19 16:52:44 +00001218 UNUSED_PARAMETER2(NotUsed, argc);
1219
drh15564052010-09-25 22:32:56 +00001220 if( argv==0 || argv[0]==0 || argv[2]==0 ){
drh497e4462005-07-23 03:18:40 +00001221 return 0;
1222 }
drh15564052010-09-25 22:32:56 +00001223 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
1224 if( pTable==0 ){
drh497e4462005-07-23 03:18:40 +00001225 return 0;
1226 }
drh15564052010-09-25 22:32:56 +00001227 if( argv[1] ){
1228 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
1229 }else{
1230 pIndex = 0;
1231 }
drh15564052010-09-25 22:32:56 +00001232 z = argv[2];
danf52bb8d2013-08-03 20:24:58 +00001233
1234 if( pIndex ){
1235 int bUnordered = 0;
danc55521a2013-08-05 05:34:30 +00001236 decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, &bUnordered);
danf52bb8d2013-08-03 20:24:58 +00001237 if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
1238 pIndex->bUnordered = bUnordered;
1239 }else{
1240 decodeIntArray((char*)z, 1, &pTable->nRowEst, 0);
drh497e4462005-07-23 03:18:40 +00001241 }
danf52bb8d2013-08-03 20:24:58 +00001242
drh497e4462005-07-23 03:18:40 +00001243 return 0;
1244}
1245
1246/*
dan85c165c2009-08-19 14:34:54 +00001247** If the Index.aSample variable is not NULL, delete the aSample[] array
1248** and its contents.
1249*/
dand46def72010-07-24 11:28:28 +00001250void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
dan8ad169a2013-08-12 20:14:04 +00001251#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dan85c165c2009-08-19 14:34:54 +00001252 if( pIdx->aSample ){
1253 int j;
drhfaacf172011-08-12 01:51:45 +00001254 for(j=0; j<pIdx->nSample; j++){
dan85c165c2009-08-19 14:34:54 +00001255 IndexSample *p = &pIdx->aSample[j];
danf52bb8d2013-08-03 20:24:58 +00001256 sqlite3DbFree(db, p->p);
dan85c165c2009-08-19 14:34:54 +00001257 }
drh8e3937f2011-08-18 13:45:23 +00001258 sqlite3DbFree(db, pIdx->aSample);
dan85c165c2009-08-19 14:34:54 +00001259 }
drh8e3937f2011-08-18 13:45:23 +00001260 if( db && db->pnBytesFreed==0 ){
1261 pIdx->nSample = 0;
1262 pIdx->aSample = 0;
1263 }
shanecea72b22009-09-07 04:38:36 +00001264#else
drh43b18e12010-08-17 19:40:08 +00001265 UNUSED_PARAMETER(db);
shanecea72b22009-09-07 04:38:36 +00001266 UNUSED_PARAMETER(pIdx);
dan85c165c2009-08-19 14:34:54 +00001267#endif
1268}
1269
dan8ad169a2013-08-12 20:14:04 +00001270#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dan0106e372013-08-12 16:34:32 +00001271/*
1272** Load the content from either the sqlite_stat4 or sqlite_stat3 table
1273** into the relevant Index.aSample[] arrays.
1274**
1275** Arguments zSql1 and zSql2 must point to SQL statements that return
1276** data equivalent to the following (statements are different for stat3,
1277** see the caller of this function for details):
1278**
1279** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1280** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1281**
1282** where %Q is replaced with the database name before the SQL is executed.
1283*/
1284static int loadStatTbl(
1285 sqlite3 *db, /* Database handle */
1286 int bStat3, /* Assume single column records only */
1287 const char *zSql1, /* SQL statement 1 (see above) */
1288 const char *zSql2, /* SQL statement 2 (see above) */
1289 const char *zDb /* Database name (e.g. "main") */
1290){
drhfaacf172011-08-12 01:51:45 +00001291 int rc; /* Result codes from subroutines */
1292 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
1293 char *zSql; /* Text of the SQL statement */
1294 Index *pPrevIdx = 0; /* Previous index in the loop */
drh68257192011-08-16 17:06:21 +00001295 int idx = 0; /* slot in pIdx->aSample[] for next sample */
drhfaacf172011-08-12 01:51:45 +00001296 IndexSample *pSample; /* A slot in pIdx->aSample[] */
1297
dan0d1614c2012-03-19 10:21:37 +00001298 assert( db->lookaside.bEnabled==0 );
dan0106e372013-08-12 16:34:32 +00001299 zSql = sqlite3MPrintf(db, zSql1, zDb);
drhfaacf172011-08-12 01:51:45 +00001300 if( !zSql ){
1301 return SQLITE_NOMEM;
1302 }
1303 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1304 sqlite3DbFree(db, zSql);
1305 if( rc ) return rc;
1306
1307 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001308 int nIdxCol = 1; /* Number of columns in stat4 records */
1309 int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
1310
drhfaacf172011-08-12 01:51:45 +00001311 char *zIndex; /* Index name */
1312 Index *pIdx; /* Pointer to the index object */
1313 int nSample; /* Number of samples */
danf52bb8d2013-08-03 20:24:58 +00001314 int nByte; /* Bytes of space required */
1315 int i; /* Bytes of space required */
1316 tRowcnt *pSpace;
drhfaacf172011-08-12 01:51:45 +00001317
1318 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1319 if( zIndex==0 ) continue;
1320 nSample = sqlite3_column_int(pStmt, 1);
drhfaacf172011-08-12 01:51:45 +00001321 pIdx = sqlite3FindIndex(db, zIndex, zDb);
dan86f69d92013-08-12 17:31:32 +00001322 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
1323 /* Index.nSample is non-zero at this point if data has already been
1324 ** loaded from the stat4 table. In this case ignore stat3 data. */
1325 if( pIdx==0 || pIdx->nSample ) continue;
dan0106e372013-08-12 16:34:32 +00001326 if( bStat3==0 ){
1327 nIdxCol = pIdx->nColumn+1;
1328 nAvgCol = pIdx->nColumn;
1329 }
dan8ad169a2013-08-12 20:14:04 +00001330 pIdx->nSampleCol = nIdxCol;
drh2b9cf662011-09-22 20:52:56 +00001331 pIdx->nSample = nSample;
danf52bb8d2013-08-03 20:24:58 +00001332 nByte = sizeof(IndexSample) * nSample;
dan0106e372013-08-12 16:34:32 +00001333 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
1334 nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
danf52bb8d2013-08-03 20:24:58 +00001335
1336 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
drhfaacf172011-08-12 01:51:45 +00001337 if( pIdx->aSample==0 ){
drhfaacf172011-08-12 01:51:45 +00001338 sqlite3_finalize(pStmt);
1339 return SQLITE_NOMEM;
1340 }
danf52bb8d2013-08-03 20:24:58 +00001341 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
dan0106e372013-08-12 16:34:32 +00001342 pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
danf52bb8d2013-08-03 20:24:58 +00001343 for(i=0; i<pIdx->nSample; i++){
dan0106e372013-08-12 16:34:32 +00001344 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1345 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1346 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001347 }
1348 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
drhfaacf172011-08-12 01:51:45 +00001349 }
drh8e3937f2011-08-18 13:45:23 +00001350 rc = sqlite3_finalize(pStmt);
1351 if( rc ) return rc;
drhfaacf172011-08-12 01:51:45 +00001352
dan0106e372013-08-12 16:34:32 +00001353 zSql = sqlite3MPrintf(db, zSql2, zDb);
drhfaacf172011-08-12 01:51:45 +00001354 if( !zSql ){
1355 return SQLITE_NOMEM;
1356 }
1357 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1358 sqlite3DbFree(db, zSql);
1359 if( rc ) return rc;
1360
1361 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001362 char *zIndex; /* Index name */
1363 Index *pIdx; /* Pointer to the index object */
1364 int i; /* Loop counter */
1365 int nCol = 1; /* Number of columns in index */
drhfaacf172011-08-12 01:51:45 +00001366
1367 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1368 if( zIndex==0 ) continue;
1369 pIdx = sqlite3FindIndex(db, zIndex, zDb);
1370 if( pIdx==0 ) continue;
1371 if( pIdx==pPrevIdx ){
1372 idx++;
1373 }else{
1374 pPrevIdx = pIdx;
1375 idx = 0;
1376 }
1377 assert( idx<pIdx->nSample );
dan86f69d92013-08-12 17:31:32 +00001378 /* This next condition is true if data has already been loaded from
1379 ** the sqlite_stat4 table. In this case ignore stat3 data. */
1380 if( bStat3 && pIdx->aSample[idx].anEq[0] ) continue;
drhfaacf172011-08-12 01:51:45 +00001381 pSample = &pIdx->aSample[idx];
danf52bb8d2013-08-03 20:24:58 +00001382
dan0106e372013-08-12 16:34:32 +00001383 if( bStat3==0 ){
1384 nCol = pIdx->nColumn+1;
1385 }
danf52bb8d2013-08-03 20:24:58 +00001386 decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
1387 decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
1388 decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
1389
drh4e50c5e2011-08-13 19:35:19 +00001390 if( idx==pIdx->nSample-1 ){
dan5133c782013-08-12 11:21:10 +00001391 IndexSample *aSample = pIdx->aSample;
daneea568d2013-08-07 19:46:15 +00001392 int iCol;
1393 for(iCol=0; iCol<pIdx->nColumn; iCol++){
dan5133c782013-08-12 11:21:10 +00001394 tRowcnt sumEq = 0; /* Sum of the nEq values */
1395 int nSum = 0; /* Number of terms contributing to sumEq */
daneea568d2013-08-07 19:46:15 +00001396 tRowcnt avgEq = 0;
1397 tRowcnt nDLt = pSample->anDLt[iCol];
dan5133c782013-08-12 11:21:10 +00001398
1399 /* Set nSum to the number of distinct (iCol+1) field prefixes that
1400 ** occur in the stat4 table for this index before pSample. Set
1401 ** sumEq to the sum of the nEq values for column iCol for the same
1402 ** set (adding the value only once where there exist dupicate
1403 ** prefixes). */
1404 for(i=0; i<(pIdx->nSample-1); i++){
1405 if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
1406 sumEq += aSample[i].anEq[iCol];
1407 nSum++;
1408 }
1409 }
1410 if( nDLt>nSum ){
1411 avgEq = (pSample->anLt[iCol] - sumEq)/(nDLt - nSum);
daneea568d2013-08-07 19:46:15 +00001412 }
1413 if( avgEq==0 ) avgEq = 1;
1414 pIdx->aAvgEq[iCol] = avgEq;
dan0106e372013-08-12 16:34:32 +00001415 if( bStat3 ) break;
drh4e50c5e2011-08-13 19:35:19 +00001416 }
drh4e50c5e2011-08-13 19:35:19 +00001417 }
danf52bb8d2013-08-03 20:24:58 +00001418
1419 pSample->n = sqlite3_column_bytes(pStmt, 4);
1420 pSample->p = sqlite3DbMallocZero(db, pSample->n);
1421 if( pSample->p==0 ){
1422 sqlite3_finalize(pStmt);
1423 return SQLITE_NOMEM;
drhfaacf172011-08-12 01:51:45 +00001424 }
danf52bb8d2013-08-03 20:24:58 +00001425 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
drhfaacf172011-08-12 01:51:45 +00001426 }
1427 return sqlite3_finalize(pStmt);
1428}
dan0106e372013-08-12 16:34:32 +00001429
1430/*
1431** Load content from the sqlite_stat4 and sqlite_stat3 tables into
1432** the Index.aSample[] arrays of all indices.
1433*/
1434static int loadStat4(sqlite3 *db, const char *zDb){
1435 int rc = SQLITE_OK; /* Result codes from subroutines */
1436
1437 assert( db->lookaside.bEnabled==0 );
1438 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
1439 rc = loadStatTbl(db, 0,
1440 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
1441 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1442 zDb
1443 );
1444 }
1445
1446 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
1447 rc = loadStatTbl(db, 1,
1448 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
1449 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
1450 zDb
1451 );
1452 }
1453
1454 return rc;
1455}
danf52bb8d2013-08-03 20:24:58 +00001456#endif /* SQLITE_ENABLE_STAT4 */
drhfaacf172011-08-12 01:51:45 +00001457
1458/*
danf52bb8d2013-08-03 20:24:58 +00001459** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
dan85c165c2009-08-19 14:34:54 +00001460** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
danf52bb8d2013-08-03 20:24:58 +00001461** arrays. The contents of sqlite_stat4 are used to populate the
dan85c165c2009-08-19 14:34:54 +00001462** Index.aSample[] arrays.
1463**
1464** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
danf52bb8d2013-08-03 20:24:58 +00001465** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
1466** during compilation and the sqlite_stat4 table is present, no data is
dan85c165c2009-08-19 14:34:54 +00001467** read from it.
1468**
danf52bb8d2013-08-03 20:24:58 +00001469** If SQLITE_ENABLE_STAT4 was defined during compilation and the
1470** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
dan85c165c2009-08-19 14:34:54 +00001471** returned. However, in this case, data is read from the sqlite_stat1
1472** table (if it is present) before returning.
1473**
1474** If an OOM error occurs, this function always sets db->mallocFailed.
1475** This means if the caller does not care about other errors, the return
1476** code may be ignored.
drh497e4462005-07-23 03:18:40 +00001477*/
drhcf1be452007-05-12 12:08:51 +00001478int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
drh497e4462005-07-23 03:18:40 +00001479 analysisInfo sInfo;
1480 HashElem *i;
1481 char *zSql;
drhcf1be452007-05-12 12:08:51 +00001482 int rc;
drh497e4462005-07-23 03:18:40 +00001483
drhff0587c2007-08-29 17:43:19 +00001484 assert( iDb>=0 && iDb<db->nDb );
1485 assert( db->aDb[iDb].pBt!=0 );
drh1fee73e2007-08-29 04:00:57 +00001486
drh497e4462005-07-23 03:18:40 +00001487 /* Clear any prior statistics */
drh21206082011-04-04 18:22:02 +00001488 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001489 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
drh497e4462005-07-23 03:18:40 +00001490 Index *pIdx = sqliteHashData(i);
drh51147ba2005-07-23 22:59:55 +00001491 sqlite3DefaultRowEst(pIdx);
dan8ad169a2013-08-12 20:14:04 +00001492#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dand46def72010-07-24 11:28:28 +00001493 sqlite3DeleteIndexSamples(db, pIdx);
1494 pIdx->aSample = 0;
drhfaacf172011-08-12 01:51:45 +00001495#endif
drh497e4462005-07-23 03:18:40 +00001496 }
1497
dan85c165c2009-08-19 14:34:54 +00001498 /* Check to make sure the sqlite_stat1 table exists */
drh497e4462005-07-23 03:18:40 +00001499 sInfo.db = db;
1500 sInfo.zDatabase = db->aDb[iDb].zName;
1501 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
dan85c165c2009-08-19 14:34:54 +00001502 return SQLITE_ERROR;
drh497e4462005-07-23 03:18:40 +00001503 }
1504
drh497e4462005-07-23 03:18:40 +00001505 /* Load new statistics out of the sqlite_stat1 table */
dan85c165c2009-08-19 14:34:54 +00001506 zSql = sqlite3MPrintf(db,
drhfaacf172011-08-12 01:51:45 +00001507 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
drhf16ce3b2009-02-13 16:59:53 +00001508 if( zSql==0 ){
1509 rc = SQLITE_NOMEM;
1510 }else{
drhf16ce3b2009-02-13 16:59:53 +00001511 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
drhf16ce3b2009-02-13 16:59:53 +00001512 sqlite3DbFree(db, zSql);
drhf16ce3b2009-02-13 16:59:53 +00001513 }
dan02fa4692009-08-17 17:06:58 +00001514
dan85c165c2009-08-19 14:34:54 +00001515
danf52bb8d2013-08-03 20:24:58 +00001516 /* Load the statistics from the sqlite_stat4 table. */
dan8ad169a2013-08-12 20:14:04 +00001517#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dan02fa4692009-08-17 17:06:58 +00001518 if( rc==SQLITE_OK ){
dan0d1614c2012-03-19 10:21:37 +00001519 int lookasideEnabled = db->lookaside.bEnabled;
1520 db->lookaside.bEnabled = 0;
danf52bb8d2013-08-03 20:24:58 +00001521 rc = loadStat4(db, sInfo.zDatabase);
dan0d1614c2012-03-19 10:21:37 +00001522 db->lookaside.bEnabled = lookasideEnabled;
dan02fa4692009-08-17 17:06:58 +00001523 }
dan69188d92009-08-19 08:18:32 +00001524#endif
dan02fa4692009-08-17 17:06:58 +00001525
dane275dc32009-08-18 16:24:58 +00001526 if( rc==SQLITE_NOMEM ){
1527 db->mallocFailed = 1;
1528 }
drhcf1be452007-05-12 12:08:51 +00001529 return rc;
drh497e4462005-07-23 03:18:40 +00001530}
drh9f18e8a2005-07-08 12:13:04 +00001531
drhff2d5ea2005-07-23 00:41:48 +00001532
drh9f18e8a2005-07-08 12:13:04 +00001533#endif /* SQLITE_OMIT_ANALYZE */