blob: d8edadf88576939d47a0b9850b796e131bcbd641 [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 ){
414 assert( pNew->anEq[pNew->iCol]>0 );
drhade3add2011-08-13 00:58:05 +0000415
danf00e9022013-08-14 19:54:12 +0000416 /* This sample is being added because the prefix that ends in column
417 ** iCol occurs many times in the table. However, if we have already
418 ** added a sample that shares this prefix, there is no need to add
419 ** this one. Instead, upgrade the priority of the existing sample. */
420 for(i=p->nSample-1; i>=0; i--){
421 Stat4Sample *pOld = &p->a[i];
422 if( pOld->anEq[pNew->iCol]==0 ){
423 if( pOld->isPSample==0 ){
424 assert( sampleIsBetter(pNew, pOld) );
425 assert( pOld->iCol>pNew->iCol );
426 pOld->iCol = pNew->iCol;
427 }
428 goto find_new_min;
dan1f28ead2013-08-07 16:15:32 +0000429 }
430 }
drhade3add2011-08-13 00:58:05 +0000431 }
danf52bb8d2013-08-03 20:24:58 +0000432
danf00e9022013-08-14 19:54:12 +0000433 /* If necessary, remove sample iMin to make room for the new sample. */
434 if( p->nSample>=p->mxSample ){
435 Stat4Sample *pMin = &p->a[p->iMin];
danc55521a2013-08-05 05:34:30 +0000436 tRowcnt *anEq = pMin->anEq;
danc55521a2013-08-05 05:34:30 +0000437 tRowcnt *anLt = pMin->anLt;
danf00e9022013-08-14 19:54:12 +0000438 tRowcnt *anDLt = pMin->anDLt;
439 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
drhf404c862011-08-13 15:25:10 +0000440 pSample = &p->a[p->nSample-1];
danc55521a2013-08-05 05:34:30 +0000441 pSample->anEq = anEq;
442 pSample->anDLt = anDLt;
443 pSample->anLt = anLt;
danf00e9022013-08-14 19:54:12 +0000444 p->nSample = p->mxSample-1;
dan8ad169a2013-08-12 20:14:04 +0000445 }
drhade3add2011-08-13 00:58:05 +0000446
danf00e9022013-08-14 19:54:12 +0000447 /* Figure out where in the a[] array the new sample should be inserted. */
448 iSeq = pNew->anLt[p->nCol-1];
449 for(iPos=p->nSample; iPos>0; iPos--){
450 if( iSeq>p->a[iPos-1].anLt[p->nCol-1] ) break;
451 }
452
453 /* Insert the new sample */
454 pSample = &p->a[iPos];
455 if( iPos!=p->nSample ){
456 Stat4Sample *pEnd = &p->a[p->nSample];
457 tRowcnt *anEq = pEnd->anEq;
458 tRowcnt *anLt = pEnd->anLt;
459 tRowcnt *anDLt = pEnd->anDLt;
460 memmove(&p->a[iPos], &p->a[iPos+1], (p->nSample-iPos)*sizeof(p->a[0]));
461 pSample->anEq = anEq;
462 pSample->anDLt = anDLt;
463 pSample->anLt = anLt;
464 }
465 p->nSample++;
466 sampleCopy(p, pSample, pNew);
467
468 /* Zero the first nEqZero entries in the anEq[] array. */
469 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
470
471 find_new_min:
472 if( p->nSample>=p->mxSample ){
473 int iMin = -1;
danf52bb8d2013-08-03 20:24:58 +0000474 for(i=0; i<p->mxSample; i++){
475 if( p->a[i].isPSample ) continue;
danf00e9022013-08-14 19:54:12 +0000476 if( iMin<0 || sampleIsBetter(&p->a[iMin], &p->a[i]) ){
drhade3add2011-08-13 00:58:05 +0000477 iMin = i;
drhade3add2011-08-13 00:58:05 +0000478 }
479 }
danf52bb8d2013-08-03 20:24:58 +0000480 assert( iMin>=0 );
drhade3add2011-08-13 00:58:05 +0000481 p->iMin = iMin;
482 }
483}
danf00e9022013-08-14 19:54:12 +0000484
485/*
486** Field iChng of the index being scanned has changed. So at this point
487** p->current contains a sample that reflects the previous row of the
488** index. The value of anEq[iChng] and subsequent anEq[] elements are
489** correct at this point.
490*/
491static void samplePushPrevious(Stat4Accum *p, int iChng){
492 if( IsStat4 ){
493 int i;
494
495 /* Check if any samples from the aBest[] array should be pushed
496 ** into IndexSample.a[] at this point. */
497 for(i=(p->nCol-2); i>=iChng; i--){
498 Stat4Sample *pBest = &p->aBest[i];
499 if( p->nSample<p->mxSample
500 || sampleIsBetter(pBest, &p->a[p->iMin])
501 ){
502 sampleInsert(p, pBest, i);
503 }
504 }
505
506 /* Update the anEq[] fields of any samples already collected. */
507 for(i=p->nSample-1; i>=0; i--){
508 int j;
509 for(j=iChng; j<p->nCol; j++){
510 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
511 }
512 }
513 }
514
515 if( IsStat3 && iChng==0 ){
516 tRowcnt nLt = p->current.anLt[0];
517 tRowcnt nEq = p->current.anEq[0];
518
519 /* Check if this is to be a periodic sample. If so, add it. */
520 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
521 p->current.isPSample = 1;
522 sampleInsert(p, &p->current, 0);
523 p->current.isPSample = 0;
524 }else
525
526 /* Or if it is a non-periodic sample. Add it in this case too. */
527 if( p->nSample<p->mxSample || sampleIsBetter(&p->current, &p->a[p->iMin]) ){
528 sampleInsert(p, &p->current, 0);
529 }
530 }
531}
532
533/*
534** Implementation of the stat_push SQL function.
535**
536** stat_push(P,R,C)
537**
538** The return value is always NULL.
539*/
540static void statPush(
541 sqlite3_context *context,
542 int argc,
543 sqlite3_value **argv
544){
545 int i;
546
547 /* The three function arguments */
548 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
549 i64 rowid = sqlite3_value_int64(argv[1]);
550 int iChng = sqlite3_value_int(argv[2]);
551
552 assert( p->nCol>1 ); /* Includes rowid field */
553 assert( iChng<p->nCol );
554
555 /* p->current.anEq[0] is false the first time this function is called. */
556 if( p->current.anEq[0] ){
557
558 samplePushPrevious(p, iChng);
559
560 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
561 ** to the current row of the index. */
562 for(i=0; i<iChng; i++){
563 p->current.anEq[i]++;
564 }
565 for(i=iChng; i<p->nCol; i++){
566 p->current.anDLt[i]++;
567 p->current.anLt[i] += p->current.anEq[i];
568 p->current.anEq[i] = 1;
569 }
570
571 }else{
572 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
573 }
574
575 if( IsStat4 || IsStat3 ){
576 p->current.iRowid = rowid;
577 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
578 }
579
580 if( IsStat4 ){
581 tRowcnt nLt = p->current.anLt[p->nCol-1];
582
583 /* Check if this is to be a periodic sample. If so, add it. */
584 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
585 p->current.isPSample = 1;
586 p->current.iCol = 0;
587 sampleInsert(p, &p->current, p->nCol-1);
588 p->current.isPSample = 0;
589 }
590
591 /* Update the aBest[] array. */
592 for(i=0; i<(p->nCol-1); i++){
593 p->current.iCol = i;
594 if( i>=iChng || sampleIsBetter(&p->current, &p->aBest[i]) ){
595 sampleCopy(p, &p->aBest[i], &p->current);
596 }
597 }
598 }
599}
600static const FuncDef statPushFuncdef = {
601 3, /* nArg */
602 SQLITE_UTF8, /* iPrefEnc */
603 0, /* flags */
604 0, /* pUserData */
605 0, /* pNext */
606 statPush, /* xFunc */
607 0, /* xStep */
608 0, /* xFinalize */
609 "stat_push", /* zName */
610 0, /* pHash */
611 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000612};
613
danf00e9022013-08-14 19:54:12 +0000614#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
615#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
616#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
617#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
618#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
619
drhade3add2011-08-13 00:58:05 +0000620/*
621** Implementation of the stat3_get(P,N,...) SQL function. This routine is
622** used to query the results. Content is returned for the Nth sqlite_stat3
623** row where N is between 0 and S-1 and S is the number of samples. The
624** value returned depends on the number of arguments.
625**
626** argc==2 result: rowid
627** argc==3 result: nEq
628** argc==4 result: nLt
drhf404c862011-08-13 15:25:10 +0000629** argc==5 result: nDLt
drhade3add2011-08-13 00:58:05 +0000630*/
danf00e9022013-08-14 19:54:12 +0000631static void statGet(
drhade3add2011-08-13 00:58:05 +0000632 sqlite3_context *context,
633 int argc,
634 sqlite3_value **argv
635){
danf52bb8d2013-08-03 20:24:58 +0000636 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
danf00e9022013-08-14 19:54:12 +0000637 int eCall = sqlite3_value_int(argv[1]);
638 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
639 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
640 || eCall==STAT_GET_NDLT
641 );
drhade3add2011-08-13 00:58:05 +0000642
danf00e9022013-08-14 19:54:12 +0000643 if( eCall==STAT_GET_STAT1 ){
644 /* Return the value to store in the "stat" column of the sqlite_stat1
645 ** table for this index.
646 **
647 ** The value is a string composed of a list of integers describing
648 ** the index. The first integer in the list is the total number of
649 ** entries in the index. There is one additional integer in the list
650 ** for each indexed column. This additional integer is an estimate of
651 ** the number of rows matched by a stabbing query on the index using
652 ** a key with the corresponding number of fields. In other words,
653 ** if the index is on columns (a,b) and the sqlite_stat1 value is
654 ** "100 10 2", then SQLite estimates that:
655 **
656 ** * the index contains 100 rows,
657 ** * "WHERE a=?" matches 10 rows, and
658 ** * "WHERE a=? AND b=?" matches 2 rows.
659 **
660 ** If D is the count of distinct values and K is the total number of
661 ** rows, then each estimate is computed as:
662 **
663 ** I = (K+D-1)/D
664 */
665 char *z;
666 int i;
667
668 char *zRet = sqlite3MallocZero(p->nCol * 25);
669 if( zRet==0 ){
670 sqlite3_result_error_nomem(context);
671 return;
672 }
673
674 sqlite3_snprintf(24, zRet, "%lld", p->nRow);
675 z = zRet + sqlite3Strlen30(zRet);
676 for(i=0; i<(p->nCol-1); i++){
677 i64 nDistinct = p->current.anDLt[i] + 1;
678 i64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
679 sqlite3_snprintf(24, z, " %lld", iVal);
680 z += sqlite3Strlen30(z);
681 assert( p->current.anEq[i] );
682 }
683 assert( z[0]=='\0' && z>zRet );
684
685 sqlite3_result_text(context, zRet, -1, sqlite3_free);
686 }else if( eCall==STAT_GET_ROWID ){
687 if( p->iGet<0 ){
688 samplePushPrevious(p, 0);
689 p->iGet = 0;
690 }
691 if( p->iGet<p->nSample ){
692 sqlite3_result_int64(context, p->a[p->iGet].iRowid);
693 }
694 }else{
danf52bb8d2013-08-03 20:24:58 +0000695 tRowcnt *aCnt = 0;
danf00e9022013-08-14 19:54:12 +0000696
697 assert( p->iGet<p->nSample );
698 switch( eCall ){
699 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
700 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
701 default: {
702 aCnt = p->a[p->iGet].anDLt;
703 p->iGet++;
704 break;
705 }
danf52bb8d2013-08-03 20:24:58 +0000706 }
707
dan8ad169a2013-08-12 20:14:04 +0000708 if( IsStat3 ){
709 sqlite3_result_int64(context, (i64)aCnt[0]);
danf52bb8d2013-08-03 20:24:58 +0000710 }else{
danf00e9022013-08-14 19:54:12 +0000711 char *zRet = sqlite3MallocZero(p->nCol * 25);
dan8ad169a2013-08-12 20:14:04 +0000712 if( zRet==0 ){
713 sqlite3_result_error_nomem(context);
714 }else{
715 int i;
716 char *z = zRet;
717 for(i=0; i<p->nCol; i++){
718 sqlite3_snprintf(24, z, "%lld ", aCnt[i]);
719 z += sqlite3Strlen30(z);
720 }
721 assert( z[0]=='\0' && z>zRet );
722 z[-1] = '\0';
723 sqlite3_result_text(context, zRet, -1, sqlite3_free);
danf52bb8d2013-08-03 20:24:58 +0000724 }
danf52bb8d2013-08-03 20:24:58 +0000725 }
drhade3add2011-08-13 00:58:05 +0000726 }
727}
danf00e9022013-08-14 19:54:12 +0000728static const FuncDef statGetFuncdef = {
729 2, /* nArg */
730 SQLITE_UTF8, /* iPrefEnc */
731 0, /* flags */
732 0, /* pUserData */
733 0, /* pNext */
734 statGet, /* xFunc */
735 0, /* xStep */
736 0, /* xFinalize */
737 "stat_get", /* zName */
738 0, /* pHash */
739 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000740};
drhade3add2011-08-13 00:58:05 +0000741
danf00e9022013-08-14 19:54:12 +0000742static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
743 assert( regOut!=regStat4 && regOut!=regStat4+1 );
744 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
745 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
746 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
747 sqlite3VdbeChangeP5(v, 2);
748}
drhade3add2011-08-13 00:58:05 +0000749
750/*
drhff2d5ea2005-07-23 00:41:48 +0000751** Generate code to do an analysis of all indices associated with
752** a single table.
753*/
754static void analyzeOneTable(
755 Parse *pParse, /* Parser context */
756 Table *pTab, /* Table whose indices are to be analyzed */
drha071bc52011-03-31 02:03:28 +0000757 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
drhdfe88ec2008-11-03 20:55:06 +0000758 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
danc6129702013-08-05 19:04:07 +0000759 int iMem, /* Available memory locations begin here */
760 int iTab /* Next available cursor */
drhff2d5ea2005-07-23 00:41:48 +0000761){
dan0f9a34e2009-08-19 16:34:31 +0000762 sqlite3 *db = pParse->db; /* Database handle */
dan69188d92009-08-19 08:18:32 +0000763 Index *pIdx; /* An index to being analyzed */
764 int iIdxCur; /* Cursor open on index being analyzed */
danc6129702013-08-05 19:04:07 +0000765 int iTabCur; /* Table cursor */
dan69188d92009-08-19 08:18:32 +0000766 Vdbe *v; /* The virtual machine being built up */
767 int i; /* Loop counter */
drhf6cf1ff2011-03-30 14:54:05 +0000768 int jZeroRows = -1; /* Jump from here if number of rows is zero */
dan69188d92009-08-19 08:18:32 +0000769 int iDb; /* Index of database containing pTab */
drh721dfcf2013-08-01 04:39:17 +0000770 u8 needTableCnt = 1; /* True to count the table */
danf00e9022013-08-14 19:54:12 +0000771 int regNewRowid = iMem++; /* Rowid for the inserted record */
772 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
773 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
774 int regChng = iMem++; /* Index of changed index field */
775 int regTemp = iMem++; /* Temporary use register */
dane275dc32009-08-18 16:24:58 +0000776 int regTabname = iMem++; /* Register containing table name */
777 int regIdxname = iMem++; /* Register containing index name */
danf00e9022013-08-14 19:54:12 +0000778 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
779 int regPrev = iMem; /* MUST BE LAST (see below) */
dan68c4dbb2009-08-20 09:11:06 +0000780
danf00e9022013-08-14 19:54:12 +0000781 pParse->nMem = MAX(pParse->nMem, regChng);
drhff2d5ea2005-07-23 00:41:48 +0000782 v = sqlite3GetVdbe(pParse);
drh15564052010-09-25 22:32:56 +0000783 if( v==0 || NEVER(pTab==0) ){
784 return;
785 }
drhf39d29c2010-09-28 17:34:46 +0000786 if( pTab->tnum==0 ){
787 /* Do not gather statistics on views or virtual tables */
drh15564052010-09-25 22:32:56 +0000788 return;
789 }
drh503a6862013-03-01 01:07:17 +0000790 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
drh15564052010-09-25 22:32:56 +0000791 /* Do not gather statistics on system tables */
drhff2d5ea2005-07-23 00:41:48 +0000792 return;
793 }
dan0f9a34e2009-08-19 16:34:31 +0000794 assert( sqlite3BtreeHoldsAllMutexes(db) );
795 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977da184232006-01-05 11:34:32 +0000796 assert( iDb>=0 );
drh21206082011-04-04 18:22:02 +0000797 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhe6e04962005-07-23 02:17:03 +0000798#ifndef SQLITE_OMIT_AUTHORIZATION
799 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
dan0f9a34e2009-08-19 16:34:31 +0000800 db->aDb[iDb].zName ) ){
drhe6e04962005-07-23 02:17:03 +0000801 return;
802 }
803#endif
804
dane0432012013-08-05 18:00:56 +0000805 /* Establish a read-lock on the table at the shared-cache level.
danf00e9022013-08-14 19:54:12 +0000806 ** Open a read-only cursor on the table. Also allocate a cursor number
807 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
808 ** this time though. */
danielk1977c00da102006-01-07 13:21:04 +0000809 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danc6129702013-08-05 19:04:07 +0000810 iTabCur = iTab++;
danf00e9022013-08-14 19:54:12 +0000811 iIdxCur = iTab++;
danc6129702013-08-05 19:04:07 +0000812 pParse->nTab = MAX(pParse->nTab, iTab);
dane0432012013-08-05 18:00:56 +0000813 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
drh15564052010-09-25 22:32:56 +0000814 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
dane0432012013-08-05 18:00:56 +0000815
drhff2d5ea2005-07-23 00:41:48 +0000816 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
danf52bb8d2013-08-03 20:24:58 +0000817 int nCol; /* Number of columns indexed by pIdx */
818 KeyInfo *pKey; /* KeyInfo structure for pIdx */
danf00e9022013-08-14 19:54:12 +0000819 int *aGotoChng; /* Array of jump instruction addresses */
820 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
821 int addrGotoChng0; /* Address of "Goto addr_chng_0" */
822 int addrNextRow; /* Address of "next_row:" */
danielk1977b3bf5562006-01-10 17:58:23 +0000823
drha071bc52011-03-31 02:03:28 +0000824 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
drh721dfcf2013-08-01 04:39:17 +0000825 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
drhfaacf172011-08-12 01:51:45 +0000826 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
drha071bc52011-03-31 02:03:28 +0000827 nCol = pIdx->nColumn;
danf00e9022013-08-14 19:54:12 +0000828 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
829 if( aGotoChng==0 ) continue;
drha071bc52011-03-31 02:03:28 +0000830 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
dane275dc32009-08-18 16:24:58 +0000831
drh15564052010-09-25 22:32:56 +0000832 /* Populate the register containing the index name. */
dan69188d92009-08-19 08:18:32 +0000833 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
834
dane0432012013-08-05 18:00:56 +0000835 /*
danf00e9022013-08-14 19:54:12 +0000836 ** Pseudo-code for loop that calls stat_push():
dane0432012013-08-05 18:00:56 +0000837 **
danf00e9022013-08-14 19:54:12 +0000838 ** Rewind csr
839 ** if eof(csr) goto end_of_scan;
840 ** regChng = 0
841 ** goto chng_addr_0;
dane0432012013-08-05 18:00:56 +0000842 **
dandd6e1f12013-08-10 19:08:30 +0000843 ** next_row:
danf00e9022013-08-14 19:54:12 +0000844 ** regChng = 0
845 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
846 ** regChng = 1
847 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
848 ** ...
849 ** regChng = N
850 ** goto chng_addr_N
dane0432012013-08-05 18:00:56 +0000851 **
danf00e9022013-08-14 19:54:12 +0000852 ** chng_addr_0:
853 ** regPrev(0) = idx(0)
854 ** chng_addr_1:
855 ** regPrev(1) = idx(1)
856 ** ...
dane0432012013-08-05 18:00:56 +0000857 **
danf00e9022013-08-14 19:54:12 +0000858 ** chng_addr_N:
859 ** regRowid = idx(rowid)
860 ** stat_push(P, regRowid, regChng)
861 ** Next csr
862 ** if !eof(csr) goto next_row;
dane0432012013-08-05 18:00:56 +0000863 **
danf00e9022013-08-14 19:54:12 +0000864 ** end_of_scan:
dane0432012013-08-05 18:00:56 +0000865 */
danf00e9022013-08-14 19:54:12 +0000866
867 /* Make sure there are enough memory cells allocated to accommodate
868 ** the regPrev array and a trailing rowid (the rowid slot is required
869 ** when building a record to insert into the sample column of
870 ** the sqlite_stat4 table. */
danc6129702013-08-05 19:04:07 +0000871 pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
dan02fa4692009-08-17 17:06:58 +0000872
danf00e9022013-08-14 19:54:12 +0000873 /* Open a read-only cursor on the index being analyzed. */
dane0432012013-08-05 18:00:56 +0000874 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
danf00e9022013-08-14 19:54:12 +0000875 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
876 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
877 VdbeComment((v, "%s", pIdx->zName));
dane0432012013-08-05 18:00:56 +0000878
danf00e9022013-08-14 19:54:12 +0000879 /* Invoke the stat_init() function. The arguments are:
danf52bb8d2013-08-03 20:24:58 +0000880 **
881 ** * the number of rows in the index,
dandd6e1f12013-08-10 19:08:30 +0000882 ** * the number of columns in the index including the rowid,
danf00e9022013-08-14 19:54:12 +0000883 ** * the recommended number of samples for the stat3/stat4 table.
danf52bb8d2013-08-03 20:24:58 +0000884 */
885 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+1);
dandd6e1f12013-08-10 19:08:30 +0000886 sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+2);
danf52bb8d2013-08-03 20:24:58 +0000887 sqlite3VdbeAddOp2(v, OP_Integer, SQLITE_STAT4_SAMPLES, regStat4+3);
888 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
danf00e9022013-08-14 19:54:12 +0000889 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
danf52bb8d2013-08-03 20:24:58 +0000890 sqlite3VdbeChangeP5(v, 3);
danf52bb8d2013-08-03 20:24:58 +0000891
danf00e9022013-08-14 19:54:12 +0000892 /* Implementation of the following:
893 **
894 ** Rewind csr
895 ** if eof(csr) goto end_of_scan;
896 ** regChng = 0
897 ** goto next_push_0;
898 **
dandd6e1f12013-08-10 19:08:30 +0000899 */
danf00e9022013-08-14 19:54:12 +0000900 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
901 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
902 addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
danf52bb8d2013-08-03 20:24:58 +0000903
danf00e9022013-08-14 19:54:12 +0000904 /*
905 ** next_row:
906 ** regChng = 0
907 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
908 ** regChng = 1
909 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
910 ** ...
911 ** regChng = N
912 ** goto chng_addr_N
913 */
914 addrNextRow = sqlite3VdbeCurrentAddr(v);
dandd6e1f12013-08-10 19:08:30 +0000915 for(i=0; i<nCol; i++){
dane0432012013-08-05 18:00:56 +0000916 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
danf00e9022013-08-14 19:54:12 +0000917 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
918 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
919 aGotoChng[i] =
920 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
dane0432012013-08-05 18:00:56 +0000921 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
922 }
danf00e9022013-08-14 19:54:12 +0000923 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
924 aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
dane0432012013-08-05 18:00:56 +0000925
danf00e9022013-08-14 19:54:12 +0000926 /*
927 ** chng_addr_0:
928 ** regPrev(0) = idx(0)
929 ** chng_addr_1:
930 ** regPrev(1) = idx(1)
931 ** ...
drhff2d5ea2005-07-23 00:41:48 +0000932 */
danf00e9022013-08-14 19:54:12 +0000933 sqlite3VdbeJumpHere(v, addrGotoChng0);
drhff2d5ea2005-07-23 00:41:48 +0000934 for(i=0; i<nCol; i++){
danf00e9022013-08-14 19:54:12 +0000935 sqlite3VdbeJumpHere(v, aGotoChng[i]);
936 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
drhff2d5ea2005-07-23 00:41:48 +0000937 }
danf00e9022013-08-14 19:54:12 +0000938
939 /*
940 ** chng_addr_N:
941 ** regRowid = idx(rowid)
942 ** stat_push(P, regRowid, regChng)
943 ** Next csr
944 ** if !eof(csr) goto next_row;
945 */
946 sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
947 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
948 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
949 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
950 sqlite3VdbeChangeP5(v, 3);
951 assert( regRowid==(regStat4+1) && regChng==(regStat4+2) );
952 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
953
954 /* Add the entry to the stat1 table. */
955 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
956 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drhade3add2011-08-13 00:58:05 +0000957 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +0000958 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh2d401ab2008-01-10 23:50:11 +0000959 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
danf00e9022013-08-14 19:54:12 +0000960
961 /* Add the entries to the stat3 or stat4 table. */
962 if( IsStat3 || IsStat4 ){
963 int regEq = regStat1;
964 int regLt = regStat1+1;
965 int regDLt = regStat1+2;
966 int regSample = regStat1+3;
967 int regCol = regStat1+4;
968 int regSampleRowid = regCol + nCol;
969 int addrNext;
970 int addrIsNull;
971
972 pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
973
974 addrNext = sqlite3VdbeCurrentAddr(v);
975 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
976 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
977 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
978 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
979 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
980 sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
981 if( IsStat3 ){
982 int iCol = pIdx->aiColumn[0];
983 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regSample);
984 }else{
985 for(i=0; i<nCol; i++){
986 int iCol = pIdx->aiColumn[i];
987 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
988 }
989 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
990 }
991
992 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
993 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
994 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
995 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
996 sqlite3VdbeJumpHere(v, addrIsNull);
997 }
998
999 /* Jump here if the index is empty */
1000 sqlite3VdbeJumpHere(v, addrRewind);
1001 sqlite3DbFree(db, aGotoChng);
drh15564052010-09-25 22:32:56 +00001002 }
1003
danf00e9022013-08-14 19:54:12 +00001004
drh721dfcf2013-08-01 04:39:17 +00001005 /* Create a single sqlite_stat1 entry containing NULL as the index
1006 ** name and the row count as the content.
drh15564052010-09-25 22:32:56 +00001007 */
drh721dfcf2013-08-01 04:39:17 +00001008 if( pOnlyIdx==0 && needTableCnt ){
drh15564052010-09-25 22:32:56 +00001009 VdbeComment((v, "%s", pTab->zName));
dane0432012013-08-05 18:00:56 +00001010 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
drhfaacf172011-08-12 01:51:45 +00001011 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
drh721dfcf2013-08-01 04:39:17 +00001012 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
danf00e9022013-08-14 19:54:12 +00001013 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drh721dfcf2013-08-01 04:39:17 +00001014 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001015 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh721dfcf2013-08-01 04:39:17 +00001016 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh15564052010-09-25 22:32:56 +00001017 sqlite3VdbeJumpHere(v, jZeroRows);
1018 }
drhff2d5ea2005-07-23 00:41:48 +00001019}
1020
drhfaacf172011-08-12 01:51:45 +00001021
drhff2d5ea2005-07-23 00:41:48 +00001022/*
drh497e4462005-07-23 03:18:40 +00001023** Generate code that will cause the most recent index analysis to
drh15564052010-09-25 22:32:56 +00001024** be loaded into internal hash tables where is can be used.
drh497e4462005-07-23 03:18:40 +00001025*/
1026static void loadAnalysis(Parse *pParse, int iDb){
1027 Vdbe *v = sqlite3GetVdbe(pParse);
drhcf1be452007-05-12 12:08:51 +00001028 if( v ){
drh66a51672008-01-03 00:01:23 +00001029 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
drhcf1be452007-05-12 12:08:51 +00001030 }
drh497e4462005-07-23 03:18:40 +00001031}
1032
1033/*
drhff2d5ea2005-07-23 00:41:48 +00001034** Generate code that will do an analysis of an entire database
1035*/
1036static void analyzeDatabase(Parse *pParse, int iDb){
1037 sqlite3 *db = pParse->db;
danielk1977e501b892006-01-09 06:29:47 +00001038 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
drhff2d5ea2005-07-23 00:41:48 +00001039 HashElem *k;
1040 int iStatCur;
1041 int iMem;
danc6129702013-08-05 19:04:07 +00001042 int iTab;
drhff2d5ea2005-07-23 00:41:48 +00001043
1044 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001045 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001046 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001047 openStatTable(pParse, iDb, iStatCur, 0, 0);
drh0a07c102008-01-03 18:03:08 +00001048 iMem = pParse->nMem+1;
danc6129702013-08-05 19:04:07 +00001049 iTab = pParse->nTab;
drh21206082011-04-04 18:22:02 +00001050 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001051 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
drhff2d5ea2005-07-23 00:41:48 +00001052 Table *pTab = (Table*)sqliteHashData(k);
danc6129702013-08-05 19:04:07 +00001053 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
drhff2d5ea2005-07-23 00:41:48 +00001054 }
drh497e4462005-07-23 03:18:40 +00001055 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001056}
1057
1058/*
1059** Generate code that will do an analysis of a single table in
drha071bc52011-03-31 02:03:28 +00001060** a database. If pOnlyIdx is not NULL then it is a single index
1061** in pTab that should be analyzed.
drhff2d5ea2005-07-23 00:41:48 +00001062*/
drha071bc52011-03-31 02:03:28 +00001063static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
drhff2d5ea2005-07-23 00:41:48 +00001064 int iDb;
1065 int iStatCur;
1066
1067 assert( pTab!=0 );
drh1fee73e2007-08-29 04:00:57 +00001068 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +00001069 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhff2d5ea2005-07-23 00:41:48 +00001070 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001071 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001072 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001073 if( pOnlyIdx ){
1074 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
1075 }else{
1076 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
1077 }
danc6129702013-08-05 19:04:07 +00001078 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
drh497e4462005-07-23 03:18:40 +00001079 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001080}
1081
1082/*
1083** Generate code for the ANALYZE command. The parser calls this routine
1084** when it recognizes an ANALYZE command.
drh9f18e8a2005-07-08 12:13:04 +00001085**
1086** ANALYZE -- 1
drhff2d5ea2005-07-23 00:41:48 +00001087** ANALYZE <database> -- 2
drh9f18e8a2005-07-08 12:13:04 +00001088** ANALYZE ?<database>.?<tablename> -- 3
1089**
1090** Form 1 causes all indices in all attached databases to be analyzed.
1091** Form 2 analyzes all indices the single database named.
1092** Form 3 analyzes all indices associated with the named table.
1093*/
1094void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
drhff2d5ea2005-07-23 00:41:48 +00001095 sqlite3 *db = pParse->db;
1096 int iDb;
1097 int i;
1098 char *z, *zDb;
1099 Table *pTab;
drha071bc52011-03-31 02:03:28 +00001100 Index *pIdx;
drhff2d5ea2005-07-23 00:41:48 +00001101 Token *pTableName;
1102
1103 /* Read the database schema. If an error occurs, leave an error message
1104 ** and code in pParse and return NULL. */
drh1fee73e2007-08-29 04:00:57 +00001105 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhff2d5ea2005-07-23 00:41:48 +00001106 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1107 return;
1108 }
1109
drh05800a12009-04-16 17:45:47 +00001110 assert( pName2!=0 || pName1==0 );
drhff2d5ea2005-07-23 00:41:48 +00001111 if( pName1==0 ){
1112 /* Form 1: Analyze everything */
1113 for(i=0; i<db->nDb; i++){
1114 if( i==1 ) continue; /* Do not analyze the TEMP database */
1115 analyzeDatabase(pParse, i);
1116 }
drh05800a12009-04-16 17:45:47 +00001117 }else if( pName2->n==0 ){
drhff2d5ea2005-07-23 00:41:48 +00001118 /* Form 2: Analyze the database or table named */
1119 iDb = sqlite3FindDb(db, pName1);
1120 if( iDb>=0 ){
1121 analyzeDatabase(pParse, iDb);
drhe6e04962005-07-23 02:17:03 +00001122 }else{
drh17435752007-08-16 04:30:38 +00001123 z = sqlite3NameFromToken(db, pName1);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001124 if( z ){
drha071bc52011-03-31 02:03:28 +00001125 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
1126 analyzeTable(pParse, pIdx->pTable, pIdx);
1127 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
1128 analyzeTable(pParse, pTab, 0);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001129 }
drha071bc52011-03-31 02:03:28 +00001130 sqlite3DbFree(db, z);
drhe6e04962005-07-23 02:17:03 +00001131 }
drhff2d5ea2005-07-23 00:41:48 +00001132 }
drhff2d5ea2005-07-23 00:41:48 +00001133 }else{
1134 /* Form 3: Analyze the fully qualified table name */
1135 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
1136 if( iDb>=0 ){
1137 zDb = db->aDb[iDb].zName;
drh17435752007-08-16 04:30:38 +00001138 z = sqlite3NameFromToken(db, pTableName);
drhcf1be452007-05-12 12:08:51 +00001139 if( z ){
drha071bc52011-03-31 02:03:28 +00001140 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
1141 analyzeTable(pParse, pIdx->pTable, pIdx);
1142 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
1143 analyzeTable(pParse, pTab, 0);
drhcf1be452007-05-12 12:08:51 +00001144 }
drha071bc52011-03-31 02:03:28 +00001145 sqlite3DbFree(db, z);
drhff2d5ea2005-07-23 00:41:48 +00001146 }
1147 }
1148 }
drh9f18e8a2005-07-08 12:13:04 +00001149}
1150
drh497e4462005-07-23 03:18:40 +00001151/*
1152** Used to pass information from the analyzer reader through to the
1153** callback routine.
1154*/
1155typedef struct analysisInfo analysisInfo;
1156struct analysisInfo {
1157 sqlite3 *db;
1158 const char *zDatabase;
1159};
1160
1161/*
danf52bb8d2013-08-03 20:24:58 +00001162** The first argument points to a nul-terminated string containing a
1163** list of space separated integers. Read the first nOut of these into
1164** the array aOut[].
1165*/
1166static void decodeIntArray(
1167 char *zIntArray,
1168 int nOut,
1169 tRowcnt *aOut,
1170 int *pbUnordered
1171){
1172 char *z = zIntArray;
1173 int c;
1174 int i;
1175 tRowcnt v;
1176
1177 assert( pbUnordered==0 || *pbUnordered==0 );
drh6b0ae912013-08-12 17:00:08 +00001178
1179 if( z==0 ) z = "";
danf52bb8d2013-08-03 20:24:58 +00001180 for(i=0; *z && i<nOut; i++){
1181 v = 0;
1182 while( (c=z[0])>='0' && c<='9' ){
1183 v = v*10 + c - '0';
1184 z++;
1185 }
1186 aOut[i] = v;
1187 if( *z==' ' ) z++;
1188 }
1189 if( pbUnordered && strcmp(z, "unordered")==0 ){
1190 *pbUnordered = 1;
1191 }
1192}
1193
1194/*
drh497e4462005-07-23 03:18:40 +00001195** This callback is invoked once for each index when reading the
1196** sqlite_stat1 table.
1197**
drh15564052010-09-25 22:32:56 +00001198** argv[0] = name of the table
1199** argv[1] = name of the index (might be NULL)
1200** argv[2] = results of analysis - on integer for each column
1201**
1202** Entries for which argv[1]==NULL simply record the number of rows in
1203** the table.
drh497e4462005-07-23 03:18:40 +00001204*/
danielk197762c14b32008-11-19 09:05:26 +00001205static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
drh497e4462005-07-23 03:18:40 +00001206 analysisInfo *pInfo = (analysisInfo*)pData;
1207 Index *pIndex;
drh15564052010-09-25 22:32:56 +00001208 Table *pTable;
drh497e4462005-07-23 03:18:40 +00001209 const char *z;
1210
drh15564052010-09-25 22:32:56 +00001211 assert( argc==3 );
danielk1977f3d3c272008-11-19 16:52:44 +00001212 UNUSED_PARAMETER2(NotUsed, argc);
1213
drh15564052010-09-25 22:32:56 +00001214 if( argv==0 || argv[0]==0 || argv[2]==0 ){
drh497e4462005-07-23 03:18:40 +00001215 return 0;
1216 }
drh15564052010-09-25 22:32:56 +00001217 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
1218 if( pTable==0 ){
drh497e4462005-07-23 03:18:40 +00001219 return 0;
1220 }
drh15564052010-09-25 22:32:56 +00001221 if( argv[1] ){
1222 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
1223 }else{
1224 pIndex = 0;
1225 }
drh15564052010-09-25 22:32:56 +00001226 z = argv[2];
danf52bb8d2013-08-03 20:24:58 +00001227
1228 if( pIndex ){
1229 int bUnordered = 0;
danc55521a2013-08-05 05:34:30 +00001230 decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst, &bUnordered);
danf52bb8d2013-08-03 20:24:58 +00001231 if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
1232 pIndex->bUnordered = bUnordered;
1233 }else{
1234 decodeIntArray((char*)z, 1, &pTable->nRowEst, 0);
drh497e4462005-07-23 03:18:40 +00001235 }
danf52bb8d2013-08-03 20:24:58 +00001236
drh497e4462005-07-23 03:18:40 +00001237 return 0;
1238}
1239
1240/*
dan85c165c2009-08-19 14:34:54 +00001241** If the Index.aSample variable is not NULL, delete the aSample[] array
1242** and its contents.
1243*/
dand46def72010-07-24 11:28:28 +00001244void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
dan8ad169a2013-08-12 20:14:04 +00001245#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dan85c165c2009-08-19 14:34:54 +00001246 if( pIdx->aSample ){
1247 int j;
drhfaacf172011-08-12 01:51:45 +00001248 for(j=0; j<pIdx->nSample; j++){
dan85c165c2009-08-19 14:34:54 +00001249 IndexSample *p = &pIdx->aSample[j];
danf52bb8d2013-08-03 20:24:58 +00001250 sqlite3DbFree(db, p->p);
dan85c165c2009-08-19 14:34:54 +00001251 }
drh8e3937f2011-08-18 13:45:23 +00001252 sqlite3DbFree(db, pIdx->aSample);
dan85c165c2009-08-19 14:34:54 +00001253 }
drh8e3937f2011-08-18 13:45:23 +00001254 if( db && db->pnBytesFreed==0 ){
1255 pIdx->nSample = 0;
1256 pIdx->aSample = 0;
1257 }
shanecea72b22009-09-07 04:38:36 +00001258#else
drh43b18e12010-08-17 19:40:08 +00001259 UNUSED_PARAMETER(db);
shanecea72b22009-09-07 04:38:36 +00001260 UNUSED_PARAMETER(pIdx);
dan85c165c2009-08-19 14:34:54 +00001261#endif
1262}
1263
dan8ad169a2013-08-12 20:14:04 +00001264#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dan0106e372013-08-12 16:34:32 +00001265/*
1266** Load the content from either the sqlite_stat4 or sqlite_stat3 table
1267** into the relevant Index.aSample[] arrays.
1268**
1269** Arguments zSql1 and zSql2 must point to SQL statements that return
1270** data equivalent to the following (statements are different for stat3,
1271** see the caller of this function for details):
1272**
1273** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1274** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1275**
1276** where %Q is replaced with the database name before the SQL is executed.
1277*/
1278static int loadStatTbl(
1279 sqlite3 *db, /* Database handle */
1280 int bStat3, /* Assume single column records only */
1281 const char *zSql1, /* SQL statement 1 (see above) */
1282 const char *zSql2, /* SQL statement 2 (see above) */
1283 const char *zDb /* Database name (e.g. "main") */
1284){
drhfaacf172011-08-12 01:51:45 +00001285 int rc; /* Result codes from subroutines */
1286 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
1287 char *zSql; /* Text of the SQL statement */
1288 Index *pPrevIdx = 0; /* Previous index in the loop */
drh68257192011-08-16 17:06:21 +00001289 int idx = 0; /* slot in pIdx->aSample[] for next sample */
drhfaacf172011-08-12 01:51:45 +00001290 IndexSample *pSample; /* A slot in pIdx->aSample[] */
1291
dan0d1614c2012-03-19 10:21:37 +00001292 assert( db->lookaside.bEnabled==0 );
dan0106e372013-08-12 16:34:32 +00001293 zSql = sqlite3MPrintf(db, zSql1, zDb);
drhfaacf172011-08-12 01:51:45 +00001294 if( !zSql ){
1295 return SQLITE_NOMEM;
1296 }
1297 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1298 sqlite3DbFree(db, zSql);
1299 if( rc ) return rc;
1300
1301 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001302 int nIdxCol = 1; /* Number of columns in stat4 records */
1303 int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
1304
drhfaacf172011-08-12 01:51:45 +00001305 char *zIndex; /* Index name */
1306 Index *pIdx; /* Pointer to the index object */
1307 int nSample; /* Number of samples */
danf52bb8d2013-08-03 20:24:58 +00001308 int nByte; /* Bytes of space required */
1309 int i; /* Bytes of space required */
1310 tRowcnt *pSpace;
drhfaacf172011-08-12 01:51:45 +00001311
1312 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1313 if( zIndex==0 ) continue;
1314 nSample = sqlite3_column_int(pStmt, 1);
drhfaacf172011-08-12 01:51:45 +00001315 pIdx = sqlite3FindIndex(db, zIndex, zDb);
dan86f69d92013-08-12 17:31:32 +00001316 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
1317 /* Index.nSample is non-zero at this point if data has already been
1318 ** loaded from the stat4 table. In this case ignore stat3 data. */
1319 if( pIdx==0 || pIdx->nSample ) continue;
dan0106e372013-08-12 16:34:32 +00001320 if( bStat3==0 ){
1321 nIdxCol = pIdx->nColumn+1;
1322 nAvgCol = pIdx->nColumn;
1323 }
dan8ad169a2013-08-12 20:14:04 +00001324 pIdx->nSampleCol = nIdxCol;
drh2b9cf662011-09-22 20:52:56 +00001325 pIdx->nSample = nSample;
danf52bb8d2013-08-03 20:24:58 +00001326 nByte = sizeof(IndexSample) * nSample;
dan0106e372013-08-12 16:34:32 +00001327 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
1328 nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
danf52bb8d2013-08-03 20:24:58 +00001329
1330 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
drhfaacf172011-08-12 01:51:45 +00001331 if( pIdx->aSample==0 ){
drhfaacf172011-08-12 01:51:45 +00001332 sqlite3_finalize(pStmt);
1333 return SQLITE_NOMEM;
1334 }
danf52bb8d2013-08-03 20:24:58 +00001335 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
dan0106e372013-08-12 16:34:32 +00001336 pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
danf52bb8d2013-08-03 20:24:58 +00001337 for(i=0; i<pIdx->nSample; i++){
dan0106e372013-08-12 16:34:32 +00001338 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1339 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1340 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001341 }
1342 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
drhfaacf172011-08-12 01:51:45 +00001343 }
drh8e3937f2011-08-18 13:45:23 +00001344 rc = sqlite3_finalize(pStmt);
1345 if( rc ) return rc;
drhfaacf172011-08-12 01:51:45 +00001346
dan0106e372013-08-12 16:34:32 +00001347 zSql = sqlite3MPrintf(db, zSql2, zDb);
drhfaacf172011-08-12 01:51:45 +00001348 if( !zSql ){
1349 return SQLITE_NOMEM;
1350 }
1351 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1352 sqlite3DbFree(db, zSql);
1353 if( rc ) return rc;
1354
1355 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001356 char *zIndex; /* Index name */
1357 Index *pIdx; /* Pointer to the index object */
1358 int i; /* Loop counter */
1359 int nCol = 1; /* Number of columns in index */
drhfaacf172011-08-12 01:51:45 +00001360
1361 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1362 if( zIndex==0 ) continue;
1363 pIdx = sqlite3FindIndex(db, zIndex, zDb);
1364 if( pIdx==0 ) continue;
1365 if( pIdx==pPrevIdx ){
1366 idx++;
1367 }else{
1368 pPrevIdx = pIdx;
1369 idx = 0;
1370 }
1371 assert( idx<pIdx->nSample );
dan86f69d92013-08-12 17:31:32 +00001372 /* This next condition is true if data has already been loaded from
1373 ** the sqlite_stat4 table. In this case ignore stat3 data. */
1374 if( bStat3 && pIdx->aSample[idx].anEq[0] ) continue;
drhfaacf172011-08-12 01:51:45 +00001375 pSample = &pIdx->aSample[idx];
danf52bb8d2013-08-03 20:24:58 +00001376
dan0106e372013-08-12 16:34:32 +00001377 if( bStat3==0 ){
1378 nCol = pIdx->nColumn+1;
1379 }
danf52bb8d2013-08-03 20:24:58 +00001380 decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
1381 decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
1382 decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
1383
drh4e50c5e2011-08-13 19:35:19 +00001384 if( idx==pIdx->nSample-1 ){
dan5133c782013-08-12 11:21:10 +00001385 IndexSample *aSample = pIdx->aSample;
daneea568d2013-08-07 19:46:15 +00001386 int iCol;
1387 for(iCol=0; iCol<pIdx->nColumn; iCol++){
dan5133c782013-08-12 11:21:10 +00001388 tRowcnt sumEq = 0; /* Sum of the nEq values */
1389 int nSum = 0; /* Number of terms contributing to sumEq */
daneea568d2013-08-07 19:46:15 +00001390 tRowcnt avgEq = 0;
1391 tRowcnt nDLt = pSample->anDLt[iCol];
dan5133c782013-08-12 11:21:10 +00001392
1393 /* Set nSum to the number of distinct (iCol+1) field prefixes that
1394 ** occur in the stat4 table for this index before pSample. Set
1395 ** sumEq to the sum of the nEq values for column iCol for the same
1396 ** set (adding the value only once where there exist dupicate
1397 ** prefixes). */
1398 for(i=0; i<(pIdx->nSample-1); i++){
1399 if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
1400 sumEq += aSample[i].anEq[iCol];
1401 nSum++;
1402 }
1403 }
1404 if( nDLt>nSum ){
1405 avgEq = (pSample->anLt[iCol] - sumEq)/(nDLt - nSum);
daneea568d2013-08-07 19:46:15 +00001406 }
1407 if( avgEq==0 ) avgEq = 1;
1408 pIdx->aAvgEq[iCol] = avgEq;
dan0106e372013-08-12 16:34:32 +00001409 if( bStat3 ) break;
drh4e50c5e2011-08-13 19:35:19 +00001410 }
drh4e50c5e2011-08-13 19:35:19 +00001411 }
danf52bb8d2013-08-03 20:24:58 +00001412
1413 pSample->n = sqlite3_column_bytes(pStmt, 4);
1414 pSample->p = sqlite3DbMallocZero(db, pSample->n);
1415 if( pSample->p==0 ){
1416 sqlite3_finalize(pStmt);
1417 return SQLITE_NOMEM;
drhfaacf172011-08-12 01:51:45 +00001418 }
danf52bb8d2013-08-03 20:24:58 +00001419 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
drhfaacf172011-08-12 01:51:45 +00001420 }
1421 return sqlite3_finalize(pStmt);
1422}
dan0106e372013-08-12 16:34:32 +00001423
1424/*
1425** Load content from the sqlite_stat4 and sqlite_stat3 tables into
1426** the Index.aSample[] arrays of all indices.
1427*/
1428static int loadStat4(sqlite3 *db, const char *zDb){
1429 int rc = SQLITE_OK; /* Result codes from subroutines */
1430
1431 assert( db->lookaside.bEnabled==0 );
1432 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
1433 rc = loadStatTbl(db, 0,
1434 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
1435 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1436 zDb
1437 );
1438 }
1439
1440 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
1441 rc = loadStatTbl(db, 1,
1442 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
1443 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
1444 zDb
1445 );
1446 }
1447
1448 return rc;
1449}
danf52bb8d2013-08-03 20:24:58 +00001450#endif /* SQLITE_ENABLE_STAT4 */
drhfaacf172011-08-12 01:51:45 +00001451
1452/*
danf52bb8d2013-08-03 20:24:58 +00001453** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
dan85c165c2009-08-19 14:34:54 +00001454** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
danf52bb8d2013-08-03 20:24:58 +00001455** arrays. The contents of sqlite_stat4 are used to populate the
dan85c165c2009-08-19 14:34:54 +00001456** Index.aSample[] arrays.
1457**
1458** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
danf52bb8d2013-08-03 20:24:58 +00001459** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
1460** during compilation and the sqlite_stat4 table is present, no data is
dan85c165c2009-08-19 14:34:54 +00001461** read from it.
1462**
danf52bb8d2013-08-03 20:24:58 +00001463** If SQLITE_ENABLE_STAT4 was defined during compilation and the
1464** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
dan85c165c2009-08-19 14:34:54 +00001465** returned. However, in this case, data is read from the sqlite_stat1
1466** table (if it is present) before returning.
1467**
1468** If an OOM error occurs, this function always sets db->mallocFailed.
1469** This means if the caller does not care about other errors, the return
1470** code may be ignored.
drh497e4462005-07-23 03:18:40 +00001471*/
drhcf1be452007-05-12 12:08:51 +00001472int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
drh497e4462005-07-23 03:18:40 +00001473 analysisInfo sInfo;
1474 HashElem *i;
1475 char *zSql;
drhcf1be452007-05-12 12:08:51 +00001476 int rc;
drh497e4462005-07-23 03:18:40 +00001477
drhff0587c2007-08-29 17:43:19 +00001478 assert( iDb>=0 && iDb<db->nDb );
1479 assert( db->aDb[iDb].pBt!=0 );
drh1fee73e2007-08-29 04:00:57 +00001480
drh497e4462005-07-23 03:18:40 +00001481 /* Clear any prior statistics */
drh21206082011-04-04 18:22:02 +00001482 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001483 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
drh497e4462005-07-23 03:18:40 +00001484 Index *pIdx = sqliteHashData(i);
drh51147ba2005-07-23 22:59:55 +00001485 sqlite3DefaultRowEst(pIdx);
dan8ad169a2013-08-12 20:14:04 +00001486#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dand46def72010-07-24 11:28:28 +00001487 sqlite3DeleteIndexSamples(db, pIdx);
1488 pIdx->aSample = 0;
drhfaacf172011-08-12 01:51:45 +00001489#endif
drh497e4462005-07-23 03:18:40 +00001490 }
1491
dan85c165c2009-08-19 14:34:54 +00001492 /* Check to make sure the sqlite_stat1 table exists */
drh497e4462005-07-23 03:18:40 +00001493 sInfo.db = db;
1494 sInfo.zDatabase = db->aDb[iDb].zName;
1495 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
dan85c165c2009-08-19 14:34:54 +00001496 return SQLITE_ERROR;
drh497e4462005-07-23 03:18:40 +00001497 }
1498
drh497e4462005-07-23 03:18:40 +00001499 /* Load new statistics out of the sqlite_stat1 table */
dan85c165c2009-08-19 14:34:54 +00001500 zSql = sqlite3MPrintf(db,
drhfaacf172011-08-12 01:51:45 +00001501 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
drhf16ce3b2009-02-13 16:59:53 +00001502 if( zSql==0 ){
1503 rc = SQLITE_NOMEM;
1504 }else{
drhf16ce3b2009-02-13 16:59:53 +00001505 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
drhf16ce3b2009-02-13 16:59:53 +00001506 sqlite3DbFree(db, zSql);
drhf16ce3b2009-02-13 16:59:53 +00001507 }
dan02fa4692009-08-17 17:06:58 +00001508
dan85c165c2009-08-19 14:34:54 +00001509
danf52bb8d2013-08-03 20:24:58 +00001510 /* Load the statistics from the sqlite_stat4 table. */
dan8ad169a2013-08-12 20:14:04 +00001511#if defined(SQLITE_ENABLE_STAT4) || defined(SQLITE_ENABLE_STAT3)
dan02fa4692009-08-17 17:06:58 +00001512 if( rc==SQLITE_OK ){
dan0d1614c2012-03-19 10:21:37 +00001513 int lookasideEnabled = db->lookaside.bEnabled;
1514 db->lookaside.bEnabled = 0;
danf52bb8d2013-08-03 20:24:58 +00001515 rc = loadStat4(db, sInfo.zDatabase);
dan0d1614c2012-03-19 10:21:37 +00001516 db->lookaside.bEnabled = lookasideEnabled;
dan02fa4692009-08-17 17:06:58 +00001517 }
dan69188d92009-08-19 08:18:32 +00001518#endif
dan02fa4692009-08-17 17:06:58 +00001519
dane275dc32009-08-18 16:24:58 +00001520 if( rc==SQLITE_NOMEM ){
1521 db->mallocFailed = 1;
1522 }
drhcf1be452007-05-12 12:08:51 +00001523 return rc;
drh497e4462005-07-23 03:18:40 +00001524}
drh9f18e8a2005-07-08 12:13:04 +00001525
drhff2d5ea2005-07-23 00:41:48 +00001526
drh9f18e8a2005-07-08 12:13:04 +00001527#endif /* SQLITE_OMIT_ANALYZE */