blob: d70f77e779a82b7f0952e274910e68ed5104f475 [file] [log] [blame]
drh9f18e8a2005-07-08 12:13:04 +00001/*
drh9fecc542013-08-27 20:16:48 +00002** 2005-07-08
drh9f18e8a2005-07-08 12:13:04 +00003**
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
drh9fecc542013-08-27 20:16:48 +000034** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.0 and later. It is
35** not possible to enable both STAT3 and STAT4 at the same time. If they
mistachkin79e84452013-08-30 19:59:48 +000036** are both enabled, then STAT4 takes precedence.
drhc8af8502013-08-09 14:07:55 +000037**
38** For most applications, sqlite_stat1 provides all the statisics required
39** for the query planner to make good choices.
drhfaacf172011-08-12 01:51:45 +000040**
41** Format of sqlite_stat1:
42**
43** There is normally one row per index, with the index identified by the
44** name in the idx column. The tbl column is the name of the table to
45** which the index belongs. In each such row, the stat column will be
46** a string consisting of a list of integers. The first integer in this
drhc8af8502013-08-09 14:07:55 +000047** list is the number of rows in the index. (This is the same as the
48** number of rows in the table, except for partial indices.) The second
drhfaacf172011-08-12 01:51:45 +000049** integer is the average number of rows in the index that have the same
50** value in the first column of the index. The third integer is the average
51** number of rows in the index that have the same value for the first two
52** columns. The N-th integer (for N>1) is the average number of rows in
53** the index which have the same value for the first N-1 columns. For
54** a K-column index, there will be K+1 integers in the stat column. If
55** the index is unique, then the last integer will be 1.
56**
57** The list of integers in the stat column can optionally be followed
58** by the keyword "unordered". The "unordered" keyword, if it is present,
59** must be separated from the last integer by a single space. If the
60** "unordered" keyword is present, then the query planner assumes that
61** the index is unordered and will not use the index for a range query.
62**
63** If the sqlite_stat1.idx column is NULL, then the sqlite_stat1.stat
64** column contains a single integer which is the (estimated) number of
65** rows in the table identified by sqlite_stat1.tbl.
66**
67** Format of sqlite_stat2:
68**
69** The sqlite_stat2 is only created and is only used if SQLite is compiled
70** with SQLITE_ENABLE_STAT2 and if the SQLite version number is between
drhd3ed7342011-09-21 00:09:41 +000071** 3.6.18 and 3.7.8. The "stat2" table contains additional information
drhfaacf172011-08-12 01:51:45 +000072** about the distribution of keys within an index. The index is identified by
73** the "idx" column and the "tbl" column is the name of the table to which
74** the index belongs. There are usually 10 rows in the sqlite_stat2
75** table for each index.
76**
dan23e7c4d2011-08-15 12:02:21 +000077** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
drhfaacf172011-08-12 01:51:45 +000078** inclusive are samples of the left-most key value in the index taken at
79** evenly spaced points along the index. Let the number of samples be S
80** (10 in the standard build) and let C be the number of rows in the index.
81** Then the sampled rows are given by:
82**
83** rownumber = (i*C*2 + C)/(S*2)
84**
85** For i between 0 and S-1. Conceptually, the index space is divided into
86** S uniform buckets and the samples are the middle row from each bucket.
87**
88** The format for sqlite_stat2 is recorded here for legacy reference. This
89** version of SQLite does not support sqlite_stat2. It neither reads nor
90** writes the sqlite_stat2 table. This version of SQLite only supports
91** sqlite_stat3.
92**
93** Format for sqlite_stat3:
94**
drhc8af8502013-08-09 14:07:55 +000095** The sqlite_stat3 format is a subset of sqlite_stat4. Hence, the
96** sqlite_stat4 format will be described first. Further information
97** about sqlite_stat3 follows the sqlite_stat4 description.
drhfaacf172011-08-12 01:51:45 +000098**
drhc8af8502013-08-09 14:07:55 +000099** Format for sqlite_stat4:
100**
101** As with sqlite_stat2, the sqlite_stat4 table contains histogram data
102** to aid the query planner in choosing good indices based on the values
103** that indexed columns are compared against in the WHERE clauses of
104** queries.
105**
106** The sqlite_stat4 table contains multiple entries for each index.
drhd3ed7342011-09-21 00:09:41 +0000107** The idx column names the index and the tbl column is the table of the
108** index. If the idx and tbl columns are the same, then the sample is
drhc8af8502013-08-09 14:07:55 +0000109** of the INTEGER PRIMARY KEY. The sample column is a blob which is the
110** binary encoding of a key from the index, with the trailing rowid
111** omitted. The nEq column is a list of integers. The first integer
dan84d4fcc2013-08-09 19:04:07 +0000112** is the approximate number of entries in the index whose left-most
113** column exactly matches the left-most column of the sample. The second
114** integer in nEq is the approximate number of entries in the index where
drhc8af8502013-08-09 14:07:55 +0000115** the first two columns match the first two columns of the sample.
dan84d4fcc2013-08-09 19:04:07 +0000116** And so forth. nLt is another list of integers that show the approximate
117** number of entries that are strictly less than the sample. The first
drhc8af8502013-08-09 14:07:55 +0000118** integer in nLt contains the number of entries in the index where the
119** left-most column is less than the left-most column of the sample.
120** The K-th integer in the nLt entry is the number of index entries
121** where the first K columns are less than the first K columns of the
122** sample. The nDLt column is like nLt except that it contains the
123** number of distinct entries in the index that are less than the
124** sample.
drhfaacf172011-08-12 01:51:45 +0000125**
drhc8af8502013-08-09 14:07:55 +0000126** There can be an arbitrary number of sqlite_stat4 entries per index.
dan84d4fcc2013-08-09 19:04:07 +0000127** The ANALYZE command will typically generate sqlite_stat4 tables
drhfaacf172011-08-12 01:51:45 +0000128** that contain between 10 and 40 samples which are distributed across
129** the key space, though not uniformly, and which include samples with
drhc8af8502013-08-09 14:07:55 +0000130** large nEq values.
131**
132** Format for sqlite_stat3 redux:
133**
134** The sqlite_stat3 table is like sqlite_stat4 except that it only
135** looks at the left-most column of the index. The sqlite_stat3.sample
136** column contains the actual value of the left-most column instead
137** of a blob encoding of the complete index key as is found in
138** sqlite_stat4.sample. The nEq, nLt, and nDLt entries of sqlite_stat3
139** all contain just a single integer which is the same as the first
140** integer in the equivalent columns in sqlite_stat4.
drh9f18e8a2005-07-08 12:13:04 +0000141*/
142#ifndef SQLITE_OMIT_ANALYZE
143#include "sqliteInt.h"
144
danf00e9022013-08-14 19:54:12 +0000145#if defined(SQLITE_ENABLE_STAT4)
drh92707ac2013-08-17 18:57:15 +0000146# define IsStat4 1
147# define IsStat3 0
danf00e9022013-08-14 19:54:12 +0000148#elif defined(SQLITE_ENABLE_STAT3)
drh92707ac2013-08-17 18:57:15 +0000149# define IsStat4 0
150# define IsStat3 1
danf00e9022013-08-14 19:54:12 +0000151#else
drh92707ac2013-08-17 18:57:15 +0000152# define IsStat4 0
153# define IsStat3 0
drh9fecc542013-08-27 20:16:48 +0000154# undef SQLITE_STAT4_SAMPLES
155# define SQLITE_STAT4_SAMPLES 1
dan8ad169a2013-08-12 20:14:04 +0000156#endif
drh9fecc542013-08-27 20:16:48 +0000157#define IsStat34 (IsStat3+IsStat4) /* 1 for STAT3 or STAT4. 0 otherwise */
dan8ad169a2013-08-12 20:14:04 +0000158
drh9f18e8a2005-07-08 12:13:04 +0000159/*
drh9fecc542013-08-27 20:16:48 +0000160** This routine generates code that opens the sqlite_statN tables.
161** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
162** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
163** appropriate compile-time options are provided.
drhff2d5ea2005-07-23 00:41:48 +0000164**
drh9fecc542013-08-27 20:16:48 +0000165** If the sqlite_statN tables do not previously exist, it is created.
dan69188d92009-08-19 08:18:32 +0000166**
167** Argument zWhere may be a pointer to a buffer containing a table name,
168** or it may be a NULL pointer. If it is not NULL, then all entries in
drh9fecc542013-08-27 20:16:48 +0000169** the sqlite_statN tables associated with the named table are deleted.
170** If zWhere==0, then code is generated to delete all stat table entries.
drhff2d5ea2005-07-23 00:41:48 +0000171*/
172static void openStatTable(
173 Parse *pParse, /* Parsing context */
174 int iDb, /* The database we are looking in */
175 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
drha071bc52011-03-31 02:03:28 +0000176 const char *zWhere, /* Delete entries for this table or index */
177 const char *zWhereType /* Either "tbl" or "idx" */
drhff2d5ea2005-07-23 00:41:48 +0000178){
dan558814f2010-06-02 05:53:53 +0000179 static const struct {
dan69188d92009-08-19 08:18:32 +0000180 const char *zName;
181 const char *zCols;
182 } aTable[] = {
183 { "sqlite_stat1", "tbl,idx,stat" },
dan0106e372013-08-12 16:34:32 +0000184#if defined(SQLITE_ENABLE_STAT4)
danf52bb8d2013-08-03 20:24:58 +0000185 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
dan8ad169a2013-08-12 20:14:04 +0000186 { "sqlite_stat3", 0 },
dan0106e372013-08-12 16:34:32 +0000187#elif defined(SQLITE_ENABLE_STAT3)
188 { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
dan8ad169a2013-08-12 20:14:04 +0000189 { "sqlite_stat4", 0 },
drh9fecc542013-08-27 20:16:48 +0000190#else
191 { "sqlite_stat3", 0 },
192 { "sqlite_stat4", 0 },
drhfaacf172011-08-12 01:51:45 +0000193#endif
194 };
dan02fa4692009-08-17 17:06:58 +0000195 int i;
drhff2d5ea2005-07-23 00:41:48 +0000196 sqlite3 *db = pParse->db;
197 Db *pDb;
drhff2d5ea2005-07-23 00:41:48 +0000198 Vdbe *v = sqlite3GetVdbe(pParse);
drh9fecc542013-08-27 20:16:48 +0000199 int aRoot[ArraySize(aTable)];
200 u8 aCreateTbl[ArraySize(aTable)];
201
drhcf1be452007-05-12 12:08:51 +0000202 if( v==0 ) return;
drh1fee73e2007-08-29 04:00:57 +0000203 assert( sqlite3BtreeHoldsAllMutexes(db) );
204 assert( sqlite3VdbeDb(v)==db );
drhff2d5ea2005-07-23 00:41:48 +0000205 pDb = &db->aDb[iDb];
dan02fa4692009-08-17 17:06:58 +0000206
drhfaacf172011-08-12 01:51:45 +0000207 /* Create new statistic tables if they do not exist, or clear them
208 ** if they do already exist.
209 */
dan69188d92009-08-19 08:18:32 +0000210 for(i=0; i<ArraySize(aTable); i++){
211 const char *zTab = aTable[i].zName;
dan02fa4692009-08-17 17:06:58 +0000212 Table *pStat;
dan69188d92009-08-19 08:18:32 +0000213 if( (pStat = sqlite3FindTable(db, zTab, pDb->zName))==0 ){
dan8ad169a2013-08-12 20:14:04 +0000214 if( aTable[i].zCols ){
drh9fecc542013-08-27 20:16:48 +0000215 /* The sqlite_statN table does not exist. Create it. Note that a
dan8ad169a2013-08-12 20:14:04 +0000216 ** side-effect of the CREATE TABLE statement is to leave the rootpage
217 ** of the new table in register pParse->regRoot. This is important
218 ** because the OpenWrite opcode below will be needing it. */
219 sqlite3NestedParse(pParse,
220 "CREATE TABLE %Q.%s(%s)", pDb->zName, zTab, aTable[i].zCols
221 );
222 aRoot[i] = pParse->regRoot;
223 aCreateTbl[i] = OPFLAG_P2ISREG;
224 }
dan02fa4692009-08-17 17:06:58 +0000225 }else{
226 /* The table already exists. If zWhere is not NULL, delete all entries
227 ** associated with the table zWhere. If zWhere is NULL, delete the
228 ** entire contents of the table. */
229 aRoot[i] = pStat->tnum;
drh9fecc542013-08-27 20:16:48 +0000230 aCreateTbl[i] = 0;
dan69188d92009-08-19 08:18:32 +0000231 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
dan02fa4692009-08-17 17:06:58 +0000232 if( zWhere ){
233 sqlite3NestedParse(pParse,
drh1435a9a2013-08-27 23:15:44 +0000234 "DELETE FROM %Q.%s WHERE %s=%Q",
235 pDb->zName, zTab, zWhereType, zWhere
dan02fa4692009-08-17 17:06:58 +0000236 );
237 }else{
dan8ad169a2013-08-12 20:14:04 +0000238 /* The sqlite_stat[134] table already exists. Delete all rows. */
dan02fa4692009-08-17 17:06:58 +0000239 sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], iDb);
240 }
241 }
drhff2d5ea2005-07-23 00:41:48 +0000242 }
243
danf00e9022013-08-14 19:54:12 +0000244 /* Open the sqlite_stat[134] tables for writing. */
drh1435a9a2013-08-27 23:15:44 +0000245 for(i=0; aTable[i].zCols; i++){
246 assert( i<ArraySize(aTable) );
247 sqlite3VdbeAddOp3(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb);
248 sqlite3VdbeChangeP4(v, -1, (char *)3, P4_INT32);
249 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
danielk1977c00da102006-01-07 13:21:04 +0000250 }
drhff2d5ea2005-07-23 00:41:48 +0000251}
252
253/*
danf52bb8d2013-08-03 20:24:58 +0000254** Recommended number of samples for sqlite_stat4
drhfaacf172011-08-12 01:51:45 +0000255*/
danf52bb8d2013-08-03 20:24:58 +0000256#ifndef SQLITE_STAT4_SAMPLES
257# define SQLITE_STAT4_SAMPLES 24
drhfaacf172011-08-12 01:51:45 +0000258#endif
259
260/*
danf00e9022013-08-14 19:54:12 +0000261** Three SQL functions - stat_init(), stat_push(), and stat_get() -
drhade3add2011-08-13 00:58:05 +0000262** share an instance of the following structure to hold their state
263** information.
264*/
danf52bb8d2013-08-03 20:24:58 +0000265typedef struct Stat4Accum Stat4Accum;
danf00e9022013-08-14 19:54:12 +0000266typedef struct Stat4Sample Stat4Sample;
267struct Stat4Sample {
danf00e9022013-08-14 19:54:12 +0000268 tRowcnt *anEq; /* sqlite_stat4.nEq */
danf00e9022013-08-14 19:54:12 +0000269 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
drh1435a9a2013-08-27 23:15:44 +0000270#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000271 tRowcnt *anLt; /* sqlite_stat4.nLt */
272 i64 iRowid; /* Rowid in main table of the key */
danf00e9022013-08-14 19:54:12 +0000273 u8 isPSample; /* True if a periodic sample */
274 int iCol; /* If !isPSample, the reason for inclusion */
275 u32 iHash; /* Tiebreaker hash */
drh9fecc542013-08-27 20:16:48 +0000276#endif
danf00e9022013-08-14 19:54:12 +0000277};
danf52bb8d2013-08-03 20:24:58 +0000278struct Stat4Accum {
drhade3add2011-08-13 00:58:05 +0000279 tRowcnt nRow; /* Number of rows in the entire table */
280 tRowcnt nPSample; /* How often to do a periodic sample */
danf00e9022013-08-14 19:54:12 +0000281 int nCol; /* Number of columns in index + rowid */
drhade3add2011-08-13 00:58:05 +0000282 int mxSample; /* Maximum number of samples to accumulate */
danf00e9022013-08-14 19:54:12 +0000283 Stat4Sample current; /* Current row as a Stat4Sample */
drhf404c862011-08-13 15:25:10 +0000284 u32 iPrn; /* Pseudo-random number used for sampling */
danf00e9022013-08-14 19:54:12 +0000285 Stat4Sample *aBest; /* Array of (nCol-1) best samples */
286 int iMin; /* Index in a[] of entry with minimum score */
287 int nSample; /* Current number of samples */
288 int iGet; /* Index of current sample accessed by stat_get() */
289 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
drhade3add2011-08-13 00:58:05 +0000290};
291
drhade3add2011-08-13 00:58:05 +0000292/*
drh9fecc542013-08-27 20:16:48 +0000293** Implementation of the stat_init(N,C) SQL function. The two parameters
drh59b08dd2013-08-27 14:14:14 +0000294** are the number of rows in the table or index (C) and the number of columns
drh9fecc542013-08-27 20:16:48 +0000295** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
drhade3add2011-08-13 00:58:05 +0000296**
danf52bb8d2013-08-03 20:24:58 +0000297** This routine allocates the Stat4Accum object in heap memory. The return
298** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
299** the size of the blob is sizeof(void*) bytes).
drhade3add2011-08-13 00:58:05 +0000300*/
danf00e9022013-08-14 19:54:12 +0000301static void statInit(
drhade3add2011-08-13 00:58:05 +0000302 sqlite3_context *context,
303 int argc,
304 sqlite3_value **argv
305){
danf52bb8d2013-08-03 20:24:58 +0000306 Stat4Accum *p;
danf52bb8d2013-08-03 20:24:58 +0000307 int nCol; /* Number of columns in index being sampled */
drh9fecc542013-08-27 20:16:48 +0000308 int nColUp; /* nCol rounded up for alignment */
danf52bb8d2013-08-03 20:24:58 +0000309 int n; /* Bytes of space to allocate */
drh1435a9a2013-08-27 23:15:44 +0000310#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000311 int mxSample = SQLITE_STAT4_SAMPLES;
312#endif
drhade3add2011-08-13 00:58:05 +0000313
danf52bb8d2013-08-03 20:24:58 +0000314 /* Decode the three function arguments */
drh68257192011-08-16 17:06:21 +0000315 UNUSED_PARAMETER(argc);
drh9fecc542013-08-27 20:16:48 +0000316 nCol = sqlite3_value_int(argv[0]);
dandd6e1f12013-08-10 19:08:30 +0000317 assert( nCol>1 ); /* >1 because it includes the rowid column */
drh9fecc542013-08-27 20:16:48 +0000318 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
danf52bb8d2013-08-03 20:24:58 +0000319
320 /* Allocate the space required for the Stat4Accum object */
danf00e9022013-08-14 19:54:12 +0000321 n = sizeof(*p)
drh9fecc542013-08-27 20:16:48 +0000322 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
323 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
drh1435a9a2013-08-27 23:15:44 +0000324#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000325 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
326 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
327 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
328#endif
329 ;
danf00e9022013-08-14 19:54:12 +0000330 p = sqlite3MallocZero(n);
drhade3add2011-08-13 00:58:05 +0000331 if( p==0 ){
332 sqlite3_result_error_nomem(context);
333 return;
334 }
danf52bb8d2013-08-03 20:24:58 +0000335
drh9fecc542013-08-27 20:16:48 +0000336 p->nRow = 0;
danf52bb8d2013-08-03 20:24:58 +0000337 p->nCol = nCol;
danf00e9022013-08-14 19:54:12 +0000338 p->current.anDLt = (tRowcnt*)&p[1];
drh9fecc542013-08-27 20:16:48 +0000339 p->current.anEq = &p->current.anDLt[nColUp];
danf00e9022013-08-14 19:54:12 +0000340
drh1435a9a2013-08-27 23:15:44 +0000341#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000342 {
343 u8 *pSpace; /* Allocated space not yet assigned */
344 int i; /* Used to iterate through p->aSample[] */
danf52bb8d2013-08-03 20:24:58 +0000345
drh9fecc542013-08-27 20:16:48 +0000346 p->iGet = -1;
347 p->mxSample = mxSample;
danad4c7aa2013-08-30 20:19:52 +0000348 p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
drh9fecc542013-08-27 20:16:48 +0000349 p->current.anLt = &p->current.anEq[nColUp];
350 sqlite3_randomness(sizeof(p->iPrn), &p->iPrn);
351
352 /* Set up the Stat4Accum.a[] and aBest[] arrays */
353 p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
354 p->aBest = &p->a[mxSample];
355 pSpace = (u8*)(&p->a[mxSample+nCol]);
356 for(i=0; i<(mxSample+nCol); i++){
357 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
358 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
359 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
360 }
361 assert( (pSpace - (u8*)p)==n );
362
363 for(i=0; i<nCol; i++){
364 p->aBest[i].iCol = i;
365 }
danf00e9022013-08-14 19:54:12 +0000366 }
drh9fecc542013-08-27 20:16:48 +0000367#endif
danf00e9022013-08-14 19:54:12 +0000368
danf52bb8d2013-08-03 20:24:58 +0000369 /* Return a pointer to the allocated object to the caller */
drhade3add2011-08-13 00:58:05 +0000370 sqlite3_result_blob(context, p, sizeof(p), sqlite3_free);
371}
danf00e9022013-08-14 19:54:12 +0000372static const FuncDef statInitFuncdef = {
drh9fecc542013-08-27 20:16:48 +0000373 1+IsStat34, /* nArg */
danf00e9022013-08-14 19:54:12 +0000374 SQLITE_UTF8, /* iPrefEnc */
375 0, /* flags */
376 0, /* pUserData */
377 0, /* pNext */
378 statInit, /* xFunc */
379 0, /* xStep */
380 0, /* xFinalize */
381 "stat_init", /* zName */
382 0, /* pHash */
383 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000384};
385
drh1435a9a2013-08-27 23:15:44 +0000386#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000387/*
388** Return true if pNew is to be preferred over pOld.
389*/
390static int sampleIsBetter(Stat4Sample *pNew, Stat4Sample *pOld){
391 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
392 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
393
394 assert( pOld->isPSample==0 && pNew->isPSample==0 );
395 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
396
397 if( (nEqNew>nEqOld)
398 || (nEqNew==nEqOld && pNew->iCol<pOld->iCol)
399 || (nEqNew==nEqOld && pNew->iCol==pOld->iCol && pNew->iHash>pOld->iHash)
400 ){
401 return 1;
402 }
403 return 0;
404}
drhade3add2011-08-13 00:58:05 +0000405
406/*
danf00e9022013-08-14 19:54:12 +0000407** Copy the contents of object (*pFrom) into (*pTo).
drhade3add2011-08-13 00:58:05 +0000408*/
danf00e9022013-08-14 19:54:12 +0000409void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
410 pTo->iRowid = pFrom->iRowid;
411 pTo->isPSample = pFrom->isPSample;
412 pTo->iCol = pFrom->iCol;
413 pTo->iHash = pFrom->iHash;
414 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
415 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
416 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
417}
418
419/*
420** Copy the contents of sample *pNew into the p->a[] array. If necessary,
421** remove the least desirable sample from p->a[] to make room.
422*/
423static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
424 Stat4Sample *pSample;
danf52bb8d2013-08-03 20:24:58 +0000425 int i;
danf00e9022013-08-14 19:54:12 +0000426 i64 iSeq;
danad4c7aa2013-08-30 20:19:52 +0000427 int iPos;
danf52bb8d2013-08-03 20:24:58 +0000428
danf00e9022013-08-14 19:54:12 +0000429 assert( IsStat4 || nEqZero==0 );
danf52bb8d2013-08-03 20:24:58 +0000430
danf00e9022013-08-14 19:54:12 +0000431 if( pNew->isPSample==0 ){
dan1f616ad2013-08-15 14:39:09 +0000432 Stat4Sample *pUpgrade = 0;
danf00e9022013-08-14 19:54:12 +0000433 assert( pNew->anEq[pNew->iCol]>0 );
drhade3add2011-08-13 00:58:05 +0000434
danf00e9022013-08-14 19:54:12 +0000435 /* This sample is being added because the prefix that ends in column
436 ** iCol occurs many times in the table. However, if we have already
437 ** added a sample that shares this prefix, there is no need to add
dan1f616ad2013-08-15 14:39:09 +0000438 ** this one. Instead, upgrade the priority of the highest priority
439 ** existing sample that shares this prefix. */
danf00e9022013-08-14 19:54:12 +0000440 for(i=p->nSample-1; i>=0; i--){
441 Stat4Sample *pOld = &p->a[i];
442 if( pOld->anEq[pNew->iCol]==0 ){
dan1f616ad2013-08-15 14:39:09 +0000443 if( pOld->isPSample ) return;
444 assert( sampleIsBetter(pNew, pOld) );
445 if( pUpgrade==0 || sampleIsBetter(pOld, pUpgrade) ){
446 pUpgrade = pOld;
danf00e9022013-08-14 19:54:12 +0000447 }
dan1f28ead2013-08-07 16:15:32 +0000448 }
449 }
dan1f616ad2013-08-15 14:39:09 +0000450 if( pUpgrade ){
451 pUpgrade->iCol = pNew->iCol;
452 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
453 goto find_new_min;
454 }
drhade3add2011-08-13 00:58:05 +0000455 }
danf52bb8d2013-08-03 20:24:58 +0000456
danf00e9022013-08-14 19:54:12 +0000457 /* If necessary, remove sample iMin to make room for the new sample. */
458 if( p->nSample>=p->mxSample ){
459 Stat4Sample *pMin = &p->a[p->iMin];
danc55521a2013-08-05 05:34:30 +0000460 tRowcnt *anEq = pMin->anEq;
danc55521a2013-08-05 05:34:30 +0000461 tRowcnt *anLt = pMin->anLt;
danf00e9022013-08-14 19:54:12 +0000462 tRowcnt *anDLt = pMin->anDLt;
463 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
drhf404c862011-08-13 15:25:10 +0000464 pSample = &p->a[p->nSample-1];
danc55521a2013-08-05 05:34:30 +0000465 pSample->anEq = anEq;
466 pSample->anDLt = anDLt;
467 pSample->anLt = anLt;
danf00e9022013-08-14 19:54:12 +0000468 p->nSample = p->mxSample-1;
dan8ad169a2013-08-12 20:14:04 +0000469 }
drhade3add2011-08-13 00:58:05 +0000470
danf00e9022013-08-14 19:54:12 +0000471 /* Figure out where in the a[] array the new sample should be inserted. */
472 iSeq = pNew->anLt[p->nCol-1];
473 for(iPos=p->nSample; iPos>0; iPos--){
474 if( iSeq>p->a[iPos-1].anLt[p->nCol-1] ) break;
475 }
476
477 /* Insert the new sample */
478 pSample = &p->a[iPos];
479 if( iPos!=p->nSample ){
480 Stat4Sample *pEnd = &p->a[p->nSample];
481 tRowcnt *anEq = pEnd->anEq;
482 tRowcnt *anLt = pEnd->anLt;
483 tRowcnt *anDLt = pEnd->anDLt;
484 memmove(&p->a[iPos], &p->a[iPos+1], (p->nSample-iPos)*sizeof(p->a[0]));
485 pSample->anEq = anEq;
486 pSample->anDLt = anDLt;
487 pSample->anLt = anLt;
488 }
489 p->nSample++;
490 sampleCopy(p, pSample, pNew);
491
492 /* Zero the first nEqZero entries in the anEq[] array. */
493 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
494
495 find_new_min:
496 if( p->nSample>=p->mxSample ){
497 int iMin = -1;
danf52bb8d2013-08-03 20:24:58 +0000498 for(i=0; i<p->mxSample; i++){
499 if( p->a[i].isPSample ) continue;
danf00e9022013-08-14 19:54:12 +0000500 if( iMin<0 || sampleIsBetter(&p->a[iMin], &p->a[i]) ){
drhade3add2011-08-13 00:58:05 +0000501 iMin = i;
drhade3add2011-08-13 00:58:05 +0000502 }
503 }
danf52bb8d2013-08-03 20:24:58 +0000504 assert( iMin>=0 );
drhade3add2011-08-13 00:58:05 +0000505 p->iMin = iMin;
506 }
507}
drh1435a9a2013-08-27 23:15:44 +0000508#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danf00e9022013-08-14 19:54:12 +0000509
510/*
511** Field iChng of the index being scanned has changed. So at this point
512** p->current contains a sample that reflects the previous row of the
513** index. The value of anEq[iChng] and subsequent anEq[] elements are
514** correct at this point.
515*/
516static void samplePushPrevious(Stat4Accum *p, int iChng){
drh92707ac2013-08-17 18:57:15 +0000517#ifdef SQLITE_ENABLE_STAT4
518 int i;
danf00e9022013-08-14 19:54:12 +0000519
drh92707ac2013-08-17 18:57:15 +0000520 /* Check if any samples from the aBest[] array should be pushed
521 ** into IndexSample.a[] at this point. */
522 for(i=(p->nCol-2); i>=iChng; i--){
523 Stat4Sample *pBest = &p->aBest[i];
524 if( p->nSample<p->mxSample
525 || sampleIsBetter(pBest, &p->a[p->iMin])
526 ){
527 sampleInsert(p, pBest, i);
danf00e9022013-08-14 19:54:12 +0000528 }
529 }
530
drh92707ac2013-08-17 18:57:15 +0000531 /* Update the anEq[] fields of any samples already collected. */
532 for(i=p->nSample-1; i>=0; i--){
533 int j;
534 for(j=iChng; j<p->nCol; j++){
535 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
536 }
537 }
538#endif
539
540#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
541 if( iChng==0 ){
danf00e9022013-08-14 19:54:12 +0000542 tRowcnt nLt = p->current.anLt[0];
543 tRowcnt nEq = p->current.anEq[0];
544
545 /* Check if this is to be a periodic sample. If so, add it. */
546 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
547 p->current.isPSample = 1;
548 sampleInsert(p, &p->current, 0);
549 p->current.isPSample = 0;
550 }else
551
552 /* Or if it is a non-periodic sample. Add it in this case too. */
553 if( p->nSample<p->mxSample || sampleIsBetter(&p->current, &p->a[p->iMin]) ){
554 sampleInsert(p, &p->current, 0);
555 }
556 }
drh92707ac2013-08-17 18:57:15 +0000557#endif
danf00e9022013-08-14 19:54:12 +0000558}
559
560/*
drh9fecc542013-08-27 20:16:48 +0000561** Implementation of the stat_push SQL function: stat_push(P,R,C)
562** Arguments:
danf00e9022013-08-14 19:54:12 +0000563**
drh9fecc542013-08-27 20:16:48 +0000564** P Pointer to the Stat4Accum object created by stat_init()
565** C Index of left-most column to differ from previous row
566** R Rowid for the current row
danf00e9022013-08-14 19:54:12 +0000567**
drh9fecc542013-08-27 20:16:48 +0000568** The SQL function always returns NULL.
569**
570** The R parameter is only used for STAT3 and STAT4.
danf00e9022013-08-14 19:54:12 +0000571*/
572static void statPush(
573 sqlite3_context *context,
574 int argc,
575 sqlite3_value **argv
576){
577 int i;
578
579 /* The three function arguments */
580 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
drh9fecc542013-08-27 20:16:48 +0000581 int iChng = sqlite3_value_int(argv[1]);
danf00e9022013-08-14 19:54:12 +0000582
583 assert( p->nCol>1 ); /* Includes rowid field */
584 assert( iChng<p->nCol );
585
drh9fecc542013-08-27 20:16:48 +0000586 if( p->nRow==0 ){
587 /* anEq[0] is only zero for the very first call to this function. Do
588 ** appropriate initialization */
589 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
590 }else{
591 /* Second and subsequent calls get processed here */
danf00e9022013-08-14 19:54:12 +0000592 samplePushPrevious(p, iChng);
593
594 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
595 ** to the current row of the index. */
596 for(i=0; i<iChng; i++){
597 p->current.anEq[i]++;
598 }
599 for(i=iChng; i<p->nCol; i++){
600 p->current.anDLt[i]++;
drh1435a9a2013-08-27 23:15:44 +0000601#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000602 p->current.anLt[i] += p->current.anEq[i];
drh9fecc542013-08-27 20:16:48 +0000603#endif
danf00e9022013-08-14 19:54:12 +0000604 p->current.anEq[i] = 1;
605 }
danf00e9022013-08-14 19:54:12 +0000606 }
drh9fecc542013-08-27 20:16:48 +0000607 p->nRow++;
drh1435a9a2013-08-27 23:15:44 +0000608#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000609 p->current.iRowid = sqlite3_value_int64(argv[2]);
610 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
611#endif
danf00e9022013-08-14 19:54:12 +0000612
drh92707ac2013-08-17 18:57:15 +0000613#ifdef SQLITE_ENABLE_STAT4
614 {
danf00e9022013-08-14 19:54:12 +0000615 tRowcnt nLt = p->current.anLt[p->nCol-1];
616
617 /* Check if this is to be a periodic sample. If so, add it. */
618 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
619 p->current.isPSample = 1;
620 p->current.iCol = 0;
621 sampleInsert(p, &p->current, p->nCol-1);
622 p->current.isPSample = 0;
623 }
624
625 /* Update the aBest[] array. */
626 for(i=0; i<(p->nCol-1); i++){
627 p->current.iCol = i;
628 if( i>=iChng || sampleIsBetter(&p->current, &p->aBest[i]) ){
629 sampleCopy(p, &p->aBest[i], &p->current);
630 }
631 }
632 }
drh92707ac2013-08-17 18:57:15 +0000633#endif
danf00e9022013-08-14 19:54:12 +0000634}
635static const FuncDef statPushFuncdef = {
drh9fecc542013-08-27 20:16:48 +0000636 2+IsStat34, /* nArg */
danf00e9022013-08-14 19:54:12 +0000637 SQLITE_UTF8, /* iPrefEnc */
638 0, /* flags */
639 0, /* pUserData */
640 0, /* pNext */
641 statPush, /* xFunc */
642 0, /* xStep */
643 0, /* xFinalize */
644 "stat_push", /* zName */
645 0, /* pHash */
646 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000647};
648
danf00e9022013-08-14 19:54:12 +0000649#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
650#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
651#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
652#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
653#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
654
drhade3add2011-08-13 00:58:05 +0000655/*
drh92707ac2013-08-17 18:57:15 +0000656** Implementation of the stat_get(P,J) SQL function. This routine is
657** used to query the results. Content is returned for parameter J
658** which is one of the STAT_GET_xxxx values defined above.
drhade3add2011-08-13 00:58:05 +0000659**
drh92707ac2013-08-17 18:57:15 +0000660** If neither STAT3 nor STAT4 are enabled, then J is always
661** STAT_GET_STAT1 and is hence omitted and this routine becomes
662** a one-parameter function, stat_get(P), that always returns the
663** stat1 table entry information.
drhade3add2011-08-13 00:58:05 +0000664*/
danf00e9022013-08-14 19:54:12 +0000665static void statGet(
drhade3add2011-08-13 00:58:05 +0000666 sqlite3_context *context,
667 int argc,
668 sqlite3_value **argv
669){
danf52bb8d2013-08-03 20:24:58 +0000670 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
drh1435a9a2013-08-27 23:15:44 +0000671#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh92707ac2013-08-17 18:57:15 +0000672 /* STAT3 and STAT4 have a parameter on this routine. */
danf00e9022013-08-14 19:54:12 +0000673 int eCall = sqlite3_value_int(argv[1]);
drh92707ac2013-08-17 18:57:15 +0000674 assert( argc==2 );
danf00e9022013-08-14 19:54:12 +0000675 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
676 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
677 || eCall==STAT_GET_NDLT
678 );
drh92707ac2013-08-17 18:57:15 +0000679 if( eCall==STAT_GET_STAT1 )
680#else
681 assert( argc==1 );
682#endif
683 {
danf00e9022013-08-14 19:54:12 +0000684 /* Return the value to store in the "stat" column of the sqlite_stat1
685 ** table for this index.
686 **
687 ** The value is a string composed of a list of integers describing
688 ** the index. The first integer in the list is the total number of
689 ** entries in the index. There is one additional integer in the list
690 ** for each indexed column. This additional integer is an estimate of
691 ** the number of rows matched by a stabbing query on the index using
692 ** a key with the corresponding number of fields. In other words,
693 ** if the index is on columns (a,b) and the sqlite_stat1 value is
694 ** "100 10 2", then SQLite estimates that:
695 **
696 ** * the index contains 100 rows,
697 ** * "WHERE a=?" matches 10 rows, and
698 ** * "WHERE a=? AND b=?" matches 2 rows.
699 **
700 ** If D is the count of distinct values and K is the total number of
701 ** rows, then each estimate is computed as:
702 **
703 ** I = (K+D-1)/D
704 */
705 char *z;
706 int i;
707
708 char *zRet = sqlite3MallocZero(p->nCol * 25);
709 if( zRet==0 ){
710 sqlite3_result_error_nomem(context);
711 return;
712 }
713
714 sqlite3_snprintf(24, zRet, "%lld", p->nRow);
715 z = zRet + sqlite3Strlen30(zRet);
716 for(i=0; i<(p->nCol-1); i++){
717 i64 nDistinct = p->current.anDLt[i] + 1;
718 i64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
719 sqlite3_snprintf(24, z, " %lld", iVal);
720 z += sqlite3Strlen30(z);
721 assert( p->current.anEq[i] );
722 }
723 assert( z[0]=='\0' && z>zRet );
724
725 sqlite3_result_text(context, zRet, -1, sqlite3_free);
drh92707ac2013-08-17 18:57:15 +0000726 }
drh1435a9a2013-08-27 23:15:44 +0000727#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh92707ac2013-08-17 18:57:15 +0000728 else if( eCall==STAT_GET_ROWID ){
danf00e9022013-08-14 19:54:12 +0000729 if( p->iGet<0 ){
730 samplePushPrevious(p, 0);
731 p->iGet = 0;
732 }
733 if( p->iGet<p->nSample ){
734 sqlite3_result_int64(context, p->a[p->iGet].iRowid);
735 }
736 }else{
danf52bb8d2013-08-03 20:24:58 +0000737 tRowcnt *aCnt = 0;
danf00e9022013-08-14 19:54:12 +0000738
739 assert( p->iGet<p->nSample );
740 switch( eCall ){
741 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
742 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
743 default: {
744 aCnt = p->a[p->iGet].anDLt;
745 p->iGet++;
746 break;
747 }
danf52bb8d2013-08-03 20:24:58 +0000748 }
749
dan8ad169a2013-08-12 20:14:04 +0000750 if( IsStat3 ){
751 sqlite3_result_int64(context, (i64)aCnt[0]);
danf52bb8d2013-08-03 20:24:58 +0000752 }else{
danf00e9022013-08-14 19:54:12 +0000753 char *zRet = sqlite3MallocZero(p->nCol * 25);
dan8ad169a2013-08-12 20:14:04 +0000754 if( zRet==0 ){
755 sqlite3_result_error_nomem(context);
756 }else{
757 int i;
758 char *z = zRet;
759 for(i=0; i<p->nCol; i++){
760 sqlite3_snprintf(24, z, "%lld ", aCnt[i]);
761 z += sqlite3Strlen30(z);
762 }
763 assert( z[0]=='\0' && z>zRet );
764 z[-1] = '\0';
765 sqlite3_result_text(context, zRet, -1, sqlite3_free);
danf52bb8d2013-08-03 20:24:58 +0000766 }
danf52bb8d2013-08-03 20:24:58 +0000767 }
drhade3add2011-08-13 00:58:05 +0000768 }
drh1435a9a2013-08-27 23:15:44 +0000769#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drhade3add2011-08-13 00:58:05 +0000770}
danf00e9022013-08-14 19:54:12 +0000771static const FuncDef statGetFuncdef = {
drh9fecc542013-08-27 20:16:48 +0000772 1+IsStat34, /* nArg */
danf00e9022013-08-14 19:54:12 +0000773 SQLITE_UTF8, /* iPrefEnc */
774 0, /* flags */
775 0, /* pUserData */
776 0, /* pNext */
777 statGet, /* xFunc */
778 0, /* xStep */
779 0, /* xFinalize */
780 "stat_get", /* zName */
781 0, /* pHash */
782 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000783};
drhade3add2011-08-13 00:58:05 +0000784
danf00e9022013-08-14 19:54:12 +0000785static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
786 assert( regOut!=regStat4 && regOut!=regStat4+1 );
drh1435a9a2013-08-27 23:15:44 +0000787#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000788 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
drh92707ac2013-08-17 18:57:15 +0000789#else
790 assert( iParam==STAT_GET_STAT1 );
791#endif
danf00e9022013-08-14 19:54:12 +0000792 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
793 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
drh9fecc542013-08-27 20:16:48 +0000794 sqlite3VdbeChangeP5(v, 1 + IsStat34);
danf00e9022013-08-14 19:54:12 +0000795}
drhade3add2011-08-13 00:58:05 +0000796
797/*
drhff2d5ea2005-07-23 00:41:48 +0000798** Generate code to do an analysis of all indices associated with
799** a single table.
800*/
801static void analyzeOneTable(
802 Parse *pParse, /* Parser context */
803 Table *pTab, /* Table whose indices are to be analyzed */
drha071bc52011-03-31 02:03:28 +0000804 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
drhdfe88ec2008-11-03 20:55:06 +0000805 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
danc6129702013-08-05 19:04:07 +0000806 int iMem, /* Available memory locations begin here */
807 int iTab /* Next available cursor */
drhff2d5ea2005-07-23 00:41:48 +0000808){
dan0f9a34e2009-08-19 16:34:31 +0000809 sqlite3 *db = pParse->db; /* Database handle */
dan69188d92009-08-19 08:18:32 +0000810 Index *pIdx; /* An index to being analyzed */
811 int iIdxCur; /* Cursor open on index being analyzed */
danc6129702013-08-05 19:04:07 +0000812 int iTabCur; /* Table cursor */
dan69188d92009-08-19 08:18:32 +0000813 Vdbe *v; /* The virtual machine being built up */
814 int i; /* Loop counter */
drhf6cf1ff2011-03-30 14:54:05 +0000815 int jZeroRows = -1; /* Jump from here if number of rows is zero */
dan69188d92009-08-19 08:18:32 +0000816 int iDb; /* Index of database containing pTab */
drh721dfcf2013-08-01 04:39:17 +0000817 u8 needTableCnt = 1; /* True to count the table */
danf00e9022013-08-14 19:54:12 +0000818 int regNewRowid = iMem++; /* Rowid for the inserted record */
819 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
danf00e9022013-08-14 19:54:12 +0000820 int regChng = iMem++; /* Index of changed index field */
drh1435a9a2013-08-27 23:15:44 +0000821#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000822 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
823#endif
danf00e9022013-08-14 19:54:12 +0000824 int regTemp = iMem++; /* Temporary use register */
dane275dc32009-08-18 16:24:58 +0000825 int regTabname = iMem++; /* Register containing table name */
826 int regIdxname = iMem++; /* Register containing index name */
danf00e9022013-08-14 19:54:12 +0000827 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
828 int regPrev = iMem; /* MUST BE LAST (see below) */
dan68c4dbb2009-08-20 09:11:06 +0000829
drhf0459fc2013-08-15 16:15:00 +0000830 pParse->nMem = MAX(pParse->nMem, iMem);
drhff2d5ea2005-07-23 00:41:48 +0000831 v = sqlite3GetVdbe(pParse);
drh15564052010-09-25 22:32:56 +0000832 if( v==0 || NEVER(pTab==0) ){
833 return;
834 }
drhf39d29c2010-09-28 17:34:46 +0000835 if( pTab->tnum==0 ){
836 /* Do not gather statistics on views or virtual tables */
drh15564052010-09-25 22:32:56 +0000837 return;
838 }
drh503a6862013-03-01 01:07:17 +0000839 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
drh15564052010-09-25 22:32:56 +0000840 /* Do not gather statistics on system tables */
drhff2d5ea2005-07-23 00:41:48 +0000841 return;
842 }
dan0f9a34e2009-08-19 16:34:31 +0000843 assert( sqlite3BtreeHoldsAllMutexes(db) );
844 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977da184232006-01-05 11:34:32 +0000845 assert( iDb>=0 );
drh21206082011-04-04 18:22:02 +0000846 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhe6e04962005-07-23 02:17:03 +0000847#ifndef SQLITE_OMIT_AUTHORIZATION
848 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
dan0f9a34e2009-08-19 16:34:31 +0000849 db->aDb[iDb].zName ) ){
drhe6e04962005-07-23 02:17:03 +0000850 return;
851 }
852#endif
853
dane0432012013-08-05 18:00:56 +0000854 /* Establish a read-lock on the table at the shared-cache level.
danf00e9022013-08-14 19:54:12 +0000855 ** Open a read-only cursor on the table. Also allocate a cursor number
856 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
857 ** this time though. */
danielk1977c00da102006-01-07 13:21:04 +0000858 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danc6129702013-08-05 19:04:07 +0000859 iTabCur = iTab++;
danf00e9022013-08-14 19:54:12 +0000860 iIdxCur = iTab++;
danc6129702013-08-05 19:04:07 +0000861 pParse->nTab = MAX(pParse->nTab, iTab);
dane0432012013-08-05 18:00:56 +0000862 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
drh15564052010-09-25 22:32:56 +0000863 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
dane0432012013-08-05 18:00:56 +0000864
drhff2d5ea2005-07-23 00:41:48 +0000865 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
danf52bb8d2013-08-03 20:24:58 +0000866 int nCol; /* Number of columns indexed by pIdx */
867 KeyInfo *pKey; /* KeyInfo structure for pIdx */
danf00e9022013-08-14 19:54:12 +0000868 int *aGotoChng; /* Array of jump instruction addresses */
869 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
870 int addrGotoChng0; /* Address of "Goto addr_chng_0" */
871 int addrNextRow; /* Address of "next_row:" */
danielk1977b3bf5562006-01-10 17:58:23 +0000872
drha071bc52011-03-31 02:03:28 +0000873 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
drh721dfcf2013-08-01 04:39:17 +0000874 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
drhfaacf172011-08-12 01:51:45 +0000875 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
drha071bc52011-03-31 02:03:28 +0000876 nCol = pIdx->nColumn;
danf00e9022013-08-14 19:54:12 +0000877 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
878 if( aGotoChng==0 ) continue;
drha071bc52011-03-31 02:03:28 +0000879 pKey = sqlite3IndexKeyinfo(pParse, pIdx);
dane275dc32009-08-18 16:24:58 +0000880
drh15564052010-09-25 22:32:56 +0000881 /* Populate the register containing the index name. */
dan69188d92009-08-19 08:18:32 +0000882 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, pIdx->zName, 0);
883
dane0432012013-08-05 18:00:56 +0000884 /*
danf00e9022013-08-14 19:54:12 +0000885 ** Pseudo-code for loop that calls stat_push():
dane0432012013-08-05 18:00:56 +0000886 **
danf00e9022013-08-14 19:54:12 +0000887 ** Rewind csr
888 ** if eof(csr) goto end_of_scan;
889 ** regChng = 0
890 ** goto chng_addr_0;
dane0432012013-08-05 18:00:56 +0000891 **
dandd6e1f12013-08-10 19:08:30 +0000892 ** next_row:
danf00e9022013-08-14 19:54:12 +0000893 ** regChng = 0
894 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
895 ** regChng = 1
896 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
897 ** ...
898 ** regChng = N
899 ** goto chng_addr_N
dane0432012013-08-05 18:00:56 +0000900 **
danf00e9022013-08-14 19:54:12 +0000901 ** chng_addr_0:
902 ** regPrev(0) = idx(0)
903 ** chng_addr_1:
904 ** regPrev(1) = idx(1)
905 ** ...
dane0432012013-08-05 18:00:56 +0000906 **
danf00e9022013-08-14 19:54:12 +0000907 ** chng_addr_N:
908 ** regRowid = idx(rowid)
drh9fecc542013-08-27 20:16:48 +0000909 ** stat_push(P, regChng, regRowid)
danf00e9022013-08-14 19:54:12 +0000910 ** Next csr
911 ** if !eof(csr) goto next_row;
dane0432012013-08-05 18:00:56 +0000912 **
danf00e9022013-08-14 19:54:12 +0000913 ** end_of_scan:
dane0432012013-08-05 18:00:56 +0000914 */
danf00e9022013-08-14 19:54:12 +0000915
916 /* Make sure there are enough memory cells allocated to accommodate
917 ** the regPrev array and a trailing rowid (the rowid slot is required
918 ** when building a record to insert into the sample column of
919 ** the sqlite_stat4 table. */
danc6129702013-08-05 19:04:07 +0000920 pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
dan02fa4692009-08-17 17:06:58 +0000921
danf00e9022013-08-14 19:54:12 +0000922 /* Open a read-only cursor on the index being analyzed. */
dane0432012013-08-05 18:00:56 +0000923 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
danf00e9022013-08-14 19:54:12 +0000924 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
925 sqlite3VdbeChangeP4(v, -1, (char*)pKey, P4_KEYINFO_HANDOFF);
926 VdbeComment((v, "%s", pIdx->zName));
dane0432012013-08-05 18:00:56 +0000927
danf00e9022013-08-14 19:54:12 +0000928 /* Invoke the stat_init() function. The arguments are:
danf52bb8d2013-08-03 20:24:58 +0000929 **
drh9fecc542013-08-27 20:16:48 +0000930 ** (1) the number of columns in the index including the rowid,
931 ** (2) the number of rows in the index,
932 **
933 ** The second argument is only used for STAT3 and STAT4
danf52bb8d2013-08-03 20:24:58 +0000934 */
drh1435a9a2013-08-27 23:15:44 +0000935#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000936 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
937#endif
938 sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
danf52bb8d2013-08-03 20:24:58 +0000939 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
danf00e9022013-08-14 19:54:12 +0000940 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
drh9fecc542013-08-27 20:16:48 +0000941 sqlite3VdbeChangeP5(v, 1+IsStat34);
danf52bb8d2013-08-03 20:24:58 +0000942
danf00e9022013-08-14 19:54:12 +0000943 /* Implementation of the following:
944 **
945 ** Rewind csr
946 ** if eof(csr) goto end_of_scan;
947 ** regChng = 0
948 ** goto next_push_0;
949 **
dandd6e1f12013-08-10 19:08:30 +0000950 */
danf00e9022013-08-14 19:54:12 +0000951 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
952 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
953 addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
danf52bb8d2013-08-03 20:24:58 +0000954
danf00e9022013-08-14 19:54:12 +0000955 /*
956 ** next_row:
957 ** regChng = 0
958 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
959 ** regChng = 1
960 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
961 ** ...
962 ** regChng = N
963 ** goto chng_addr_N
964 */
965 addrNextRow = sqlite3VdbeCurrentAddr(v);
dandd6e1f12013-08-10 19:08:30 +0000966 for(i=0; i<nCol; i++){
dane0432012013-08-05 18:00:56 +0000967 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
danf00e9022013-08-14 19:54:12 +0000968 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
969 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
970 aGotoChng[i] =
971 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
dane0432012013-08-05 18:00:56 +0000972 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
973 }
danf00e9022013-08-14 19:54:12 +0000974 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
975 aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
dane0432012013-08-05 18:00:56 +0000976
danf00e9022013-08-14 19:54:12 +0000977 /*
978 ** chng_addr_0:
979 ** regPrev(0) = idx(0)
980 ** chng_addr_1:
981 ** regPrev(1) = idx(1)
982 ** ...
drhff2d5ea2005-07-23 00:41:48 +0000983 */
danf00e9022013-08-14 19:54:12 +0000984 sqlite3VdbeJumpHere(v, addrGotoChng0);
drhff2d5ea2005-07-23 00:41:48 +0000985 for(i=0; i<nCol; i++){
danf00e9022013-08-14 19:54:12 +0000986 sqlite3VdbeJumpHere(v, aGotoChng[i]);
987 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
drhff2d5ea2005-07-23 00:41:48 +0000988 }
danf00e9022013-08-14 19:54:12 +0000989
990 /*
991 ** chng_addr_N:
drh9fecc542013-08-27 20:16:48 +0000992 ** regRowid = idx(rowid) // STAT34 only
993 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
danf00e9022013-08-14 19:54:12 +0000994 ** Next csr
995 ** if !eof(csr) goto next_row;
996 */
997 sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
drh1435a9a2013-08-27 23:15:44 +0000998#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000999 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
drh9fecc542013-08-27 20:16:48 +00001000 assert( regRowid==(regStat4+2) );
1001#endif
1002 assert( regChng==(regStat4+1) );
danf00e9022013-08-14 19:54:12 +00001003 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
1004 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
drh9fecc542013-08-27 20:16:48 +00001005 sqlite3VdbeChangeP5(v, 2+IsStat34);
danf00e9022013-08-14 19:54:12 +00001006 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow);
1007
1008 /* Add the entry to the stat1 table. */
1009 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
1010 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drhade3add2011-08-13 00:58:05 +00001011 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001012 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh2d401ab2008-01-10 23:50:11 +00001013 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
danf00e9022013-08-14 19:54:12 +00001014
1015 /* Add the entries to the stat3 or stat4 table. */
drh1435a9a2013-08-27 23:15:44 +00001016#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +00001017 {
danf00e9022013-08-14 19:54:12 +00001018 int regEq = regStat1;
1019 int regLt = regStat1+1;
1020 int regDLt = regStat1+2;
1021 int regSample = regStat1+3;
1022 int regCol = regStat1+4;
1023 int regSampleRowid = regCol + nCol;
1024 int addrNext;
1025 int addrIsNull;
1026
1027 pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
1028
1029 addrNext = sqlite3VdbeCurrentAddr(v);
1030 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
1031 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
1032 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
1033 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
1034 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
1035 sqlite3VdbeAddOp3(v, OP_NotExists, iTabCur, addrNext, regSampleRowid);
drh9fecc542013-08-27 20:16:48 +00001036#ifdef SQLITE_ENABLE_STAT3
1037 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
1038 pIdx->aiColumn[0], regSample);
1039#else
1040 for(i=0; i<nCol; i++){
1041 int iCol = pIdx->aiColumn[i];
1042 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
danf00e9022013-08-14 19:54:12 +00001043 }
drh9fecc542013-08-27 20:16:48 +00001044 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
1045#endif
danf00e9022013-08-14 19:54:12 +00001046 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 6, regTemp, "bbbbbb", 0);
1047 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
1048 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
1049 sqlite3VdbeAddOp2(v, OP_Goto, 0, addrNext);
1050 sqlite3VdbeJumpHere(v, addrIsNull);
1051 }
drh1435a9a2013-08-27 23:15:44 +00001052#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danf00e9022013-08-14 19:54:12 +00001053
drh9fecc542013-08-27 20:16:48 +00001054 /* End of analysis */
danf00e9022013-08-14 19:54:12 +00001055 sqlite3VdbeJumpHere(v, addrRewind);
1056 sqlite3DbFree(db, aGotoChng);
drh15564052010-09-25 22:32:56 +00001057 }
1058
danf00e9022013-08-14 19:54:12 +00001059
drh721dfcf2013-08-01 04:39:17 +00001060 /* Create a single sqlite_stat1 entry containing NULL as the index
1061 ** name and the row count as the content.
drh15564052010-09-25 22:32:56 +00001062 */
drh721dfcf2013-08-01 04:39:17 +00001063 if( pOnlyIdx==0 && needTableCnt ){
drh15564052010-09-25 22:32:56 +00001064 VdbeComment((v, "%s", pTab->zName));
dane0432012013-08-05 18:00:56 +00001065 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
drhfaacf172011-08-12 01:51:45 +00001066 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1);
drh721dfcf2013-08-01 04:39:17 +00001067 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
danf00e9022013-08-14 19:54:12 +00001068 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drh721dfcf2013-08-01 04:39:17 +00001069 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001070 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh721dfcf2013-08-01 04:39:17 +00001071 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh15564052010-09-25 22:32:56 +00001072 sqlite3VdbeJumpHere(v, jZeroRows);
1073 }
drhff2d5ea2005-07-23 00:41:48 +00001074}
1075
drhfaacf172011-08-12 01:51:45 +00001076
drhff2d5ea2005-07-23 00:41:48 +00001077/*
drh497e4462005-07-23 03:18:40 +00001078** Generate code that will cause the most recent index analysis to
drh15564052010-09-25 22:32:56 +00001079** be loaded into internal hash tables where is can be used.
drh497e4462005-07-23 03:18:40 +00001080*/
1081static void loadAnalysis(Parse *pParse, int iDb){
1082 Vdbe *v = sqlite3GetVdbe(pParse);
drhcf1be452007-05-12 12:08:51 +00001083 if( v ){
drh66a51672008-01-03 00:01:23 +00001084 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
drhcf1be452007-05-12 12:08:51 +00001085 }
drh497e4462005-07-23 03:18:40 +00001086}
1087
1088/*
drhff2d5ea2005-07-23 00:41:48 +00001089** Generate code that will do an analysis of an entire database
1090*/
1091static void analyzeDatabase(Parse *pParse, int iDb){
1092 sqlite3 *db = pParse->db;
danielk1977e501b892006-01-09 06:29:47 +00001093 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
drhff2d5ea2005-07-23 00:41:48 +00001094 HashElem *k;
1095 int iStatCur;
1096 int iMem;
danc6129702013-08-05 19:04:07 +00001097 int iTab;
drhff2d5ea2005-07-23 00:41:48 +00001098
1099 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001100 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001101 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001102 openStatTable(pParse, iDb, iStatCur, 0, 0);
drh0a07c102008-01-03 18:03:08 +00001103 iMem = pParse->nMem+1;
danc6129702013-08-05 19:04:07 +00001104 iTab = pParse->nTab;
drh21206082011-04-04 18:22:02 +00001105 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001106 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
drhff2d5ea2005-07-23 00:41:48 +00001107 Table *pTab = (Table*)sqliteHashData(k);
danc6129702013-08-05 19:04:07 +00001108 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
drhff2d5ea2005-07-23 00:41:48 +00001109 }
drh497e4462005-07-23 03:18:40 +00001110 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001111}
1112
1113/*
1114** Generate code that will do an analysis of a single table in
drha071bc52011-03-31 02:03:28 +00001115** a database. If pOnlyIdx is not NULL then it is a single index
1116** in pTab that should be analyzed.
drhff2d5ea2005-07-23 00:41:48 +00001117*/
drha071bc52011-03-31 02:03:28 +00001118static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
drhff2d5ea2005-07-23 00:41:48 +00001119 int iDb;
1120 int iStatCur;
1121
1122 assert( pTab!=0 );
drh1fee73e2007-08-29 04:00:57 +00001123 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +00001124 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhff2d5ea2005-07-23 00:41:48 +00001125 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001126 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001127 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001128 if( pOnlyIdx ){
1129 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
1130 }else{
1131 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
1132 }
danc6129702013-08-05 19:04:07 +00001133 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
drh497e4462005-07-23 03:18:40 +00001134 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001135}
1136
1137/*
1138** Generate code for the ANALYZE command. The parser calls this routine
1139** when it recognizes an ANALYZE command.
drh9f18e8a2005-07-08 12:13:04 +00001140**
1141** ANALYZE -- 1
drhff2d5ea2005-07-23 00:41:48 +00001142** ANALYZE <database> -- 2
drh9f18e8a2005-07-08 12:13:04 +00001143** ANALYZE ?<database>.?<tablename> -- 3
1144**
1145** Form 1 causes all indices in all attached databases to be analyzed.
1146** Form 2 analyzes all indices the single database named.
1147** Form 3 analyzes all indices associated with the named table.
1148*/
1149void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
drhff2d5ea2005-07-23 00:41:48 +00001150 sqlite3 *db = pParse->db;
1151 int iDb;
1152 int i;
1153 char *z, *zDb;
1154 Table *pTab;
drha071bc52011-03-31 02:03:28 +00001155 Index *pIdx;
drhff2d5ea2005-07-23 00:41:48 +00001156 Token *pTableName;
1157
1158 /* Read the database schema. If an error occurs, leave an error message
1159 ** and code in pParse and return NULL. */
drh1fee73e2007-08-29 04:00:57 +00001160 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhff2d5ea2005-07-23 00:41:48 +00001161 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1162 return;
1163 }
1164
drh05800a12009-04-16 17:45:47 +00001165 assert( pName2!=0 || pName1==0 );
drhff2d5ea2005-07-23 00:41:48 +00001166 if( pName1==0 ){
1167 /* Form 1: Analyze everything */
1168 for(i=0; i<db->nDb; i++){
1169 if( i==1 ) continue; /* Do not analyze the TEMP database */
1170 analyzeDatabase(pParse, i);
1171 }
drh05800a12009-04-16 17:45:47 +00001172 }else if( pName2->n==0 ){
drhff2d5ea2005-07-23 00:41:48 +00001173 /* Form 2: Analyze the database or table named */
1174 iDb = sqlite3FindDb(db, pName1);
1175 if( iDb>=0 ){
1176 analyzeDatabase(pParse, iDb);
drhe6e04962005-07-23 02:17:03 +00001177 }else{
drh17435752007-08-16 04:30:38 +00001178 z = sqlite3NameFromToken(db, pName1);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001179 if( z ){
drha071bc52011-03-31 02:03:28 +00001180 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
1181 analyzeTable(pParse, pIdx->pTable, pIdx);
1182 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
1183 analyzeTable(pParse, pTab, 0);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001184 }
drha071bc52011-03-31 02:03:28 +00001185 sqlite3DbFree(db, z);
drhe6e04962005-07-23 02:17:03 +00001186 }
drhff2d5ea2005-07-23 00:41:48 +00001187 }
drhff2d5ea2005-07-23 00:41:48 +00001188 }else{
1189 /* Form 3: Analyze the fully qualified table name */
1190 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
1191 if( iDb>=0 ){
1192 zDb = db->aDb[iDb].zName;
drh17435752007-08-16 04:30:38 +00001193 z = sqlite3NameFromToken(db, pTableName);
drhcf1be452007-05-12 12:08:51 +00001194 if( z ){
drha071bc52011-03-31 02:03:28 +00001195 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
1196 analyzeTable(pParse, pIdx->pTable, pIdx);
1197 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
1198 analyzeTable(pParse, pTab, 0);
drhcf1be452007-05-12 12:08:51 +00001199 }
drha071bc52011-03-31 02:03:28 +00001200 sqlite3DbFree(db, z);
drhff2d5ea2005-07-23 00:41:48 +00001201 }
1202 }
1203 }
drh9f18e8a2005-07-08 12:13:04 +00001204}
1205
drh497e4462005-07-23 03:18:40 +00001206/*
1207** Used to pass information from the analyzer reader through to the
1208** callback routine.
1209*/
1210typedef struct analysisInfo analysisInfo;
1211struct analysisInfo {
1212 sqlite3 *db;
1213 const char *zDatabase;
1214};
1215
1216/*
danf52bb8d2013-08-03 20:24:58 +00001217** The first argument points to a nul-terminated string containing a
1218** list of space separated integers. Read the first nOut of these into
1219** the array aOut[].
1220*/
1221static void decodeIntArray(
1222 char *zIntArray,
1223 int nOut,
1224 tRowcnt *aOut,
1225 int *pbUnordered
1226){
1227 char *z = zIntArray;
1228 int c;
1229 int i;
1230 tRowcnt v;
1231
1232 assert( pbUnordered==0 || *pbUnordered==0 );
drh1435a9a2013-08-27 23:15:44 +00001233
drh6d57bbf2013-08-28 11:43:49 +00001234#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1235 if( z==0 ) z = "";
1236#else
drh1435a9a2013-08-27 23:15:44 +00001237 if( NEVER(z==0) ) z = "";
drh6d57bbf2013-08-28 11:43:49 +00001238#endif
danf52bb8d2013-08-03 20:24:58 +00001239 for(i=0; *z && i<nOut; i++){
1240 v = 0;
1241 while( (c=z[0])>='0' && c<='9' ){
1242 v = v*10 + c - '0';
1243 z++;
1244 }
1245 aOut[i] = v;
1246 if( *z==' ' ) z++;
1247 }
1248 if( pbUnordered && strcmp(z, "unordered")==0 ){
1249 *pbUnordered = 1;
1250 }
1251}
1252
1253/*
drh497e4462005-07-23 03:18:40 +00001254** This callback is invoked once for each index when reading the
1255** sqlite_stat1 table.
1256**
drh15564052010-09-25 22:32:56 +00001257** argv[0] = name of the table
1258** argv[1] = name of the index (might be NULL)
1259** argv[2] = results of analysis - on integer for each column
1260**
1261** Entries for which argv[1]==NULL simply record the number of rows in
1262** the table.
drh497e4462005-07-23 03:18:40 +00001263*/
danielk197762c14b32008-11-19 09:05:26 +00001264static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
drh497e4462005-07-23 03:18:40 +00001265 analysisInfo *pInfo = (analysisInfo*)pData;
1266 Index *pIndex;
drh15564052010-09-25 22:32:56 +00001267 Table *pTable;
drh497e4462005-07-23 03:18:40 +00001268 const char *z;
1269
drh15564052010-09-25 22:32:56 +00001270 assert( argc==3 );
danielk1977f3d3c272008-11-19 16:52:44 +00001271 UNUSED_PARAMETER2(NotUsed, argc);
1272
drh15564052010-09-25 22:32:56 +00001273 if( argv==0 || argv[0]==0 || argv[2]==0 ){
drh497e4462005-07-23 03:18:40 +00001274 return 0;
1275 }
drh15564052010-09-25 22:32:56 +00001276 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
1277 if( pTable==0 ){
drh497e4462005-07-23 03:18:40 +00001278 return 0;
1279 }
drh15564052010-09-25 22:32:56 +00001280 if( argv[1] ){
1281 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
1282 }else{
1283 pIndex = 0;
1284 }
drh15564052010-09-25 22:32:56 +00001285 z = argv[2];
danf52bb8d2013-08-03 20:24:58 +00001286
1287 if( pIndex ){
1288 int bUnordered = 0;
drh1435a9a2013-08-27 23:15:44 +00001289 decodeIntArray((char*)z, pIndex->nColumn+1, pIndex->aiRowEst,&bUnordered);
danf52bb8d2013-08-03 20:24:58 +00001290 if( pIndex->pPartIdxWhere==0 ) pTable->nRowEst = pIndex->aiRowEst[0];
1291 pIndex->bUnordered = bUnordered;
1292 }else{
1293 decodeIntArray((char*)z, 1, &pTable->nRowEst, 0);
drh497e4462005-07-23 03:18:40 +00001294 }
danf52bb8d2013-08-03 20:24:58 +00001295
drh497e4462005-07-23 03:18:40 +00001296 return 0;
1297}
1298
1299/*
dan85c165c2009-08-19 14:34:54 +00001300** If the Index.aSample variable is not NULL, delete the aSample[] array
1301** and its contents.
1302*/
dand46def72010-07-24 11:28:28 +00001303void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
drh1435a9a2013-08-27 23:15:44 +00001304#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan85c165c2009-08-19 14:34:54 +00001305 if( pIdx->aSample ){
1306 int j;
drhfaacf172011-08-12 01:51:45 +00001307 for(j=0; j<pIdx->nSample; j++){
dan85c165c2009-08-19 14:34:54 +00001308 IndexSample *p = &pIdx->aSample[j];
danf52bb8d2013-08-03 20:24:58 +00001309 sqlite3DbFree(db, p->p);
dan85c165c2009-08-19 14:34:54 +00001310 }
drh8e3937f2011-08-18 13:45:23 +00001311 sqlite3DbFree(db, pIdx->aSample);
dan85c165c2009-08-19 14:34:54 +00001312 }
drh8e3937f2011-08-18 13:45:23 +00001313 if( db && db->pnBytesFreed==0 ){
1314 pIdx->nSample = 0;
1315 pIdx->aSample = 0;
1316 }
shanecea72b22009-09-07 04:38:36 +00001317#else
drh43b18e12010-08-17 19:40:08 +00001318 UNUSED_PARAMETER(db);
shanecea72b22009-09-07 04:38:36 +00001319 UNUSED_PARAMETER(pIdx);
drh1435a9a2013-08-27 23:15:44 +00001320#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan85c165c2009-08-19 14:34:54 +00001321}
1322
drh1435a9a2013-08-27 23:15:44 +00001323#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan0adbed82013-08-15 19:56:32 +00001324/*
1325** Populate the pIdx->aAvgEq[] array based on the samples currently
1326** stored in pIdx->aSample[].
1327*/
1328static void initAvgEq(Index *pIdx){
1329 if( pIdx ){
1330 IndexSample *aSample = pIdx->aSample;
1331 IndexSample *pFinal = &aSample[pIdx->nSample-1];
1332 int iCol;
1333 for(iCol=0; iCol<pIdx->nColumn; iCol++){
1334 int i; /* Used to iterate through samples */
1335 tRowcnt sumEq = 0; /* Sum of the nEq values */
danad4c7aa2013-08-30 20:19:52 +00001336 tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
dan0adbed82013-08-15 19:56:32 +00001337 tRowcnt avgEq = 0;
1338 tRowcnt nDLt = pFinal->anDLt[iCol];
1339
1340 /* Set nSum to the number of distinct (iCol+1) field prefixes that
1341 ** occur in the stat4 table for this index before pFinal. Set
1342 ** sumEq to the sum of the nEq values for column iCol for the same
1343 ** set (adding the value only once where there exist dupicate
1344 ** prefixes). */
1345 for(i=0; i<(pIdx->nSample-1); i++){
1346 if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
1347 sumEq += aSample[i].anEq[iCol];
1348 nSum++;
1349 }
1350 }
1351 if( nDLt>nSum ){
1352 avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
1353 }
1354 if( avgEq==0 ) avgEq = 1;
1355 pIdx->aAvgEq[iCol] = avgEq;
1356 if( pIdx->nSampleCol==1 ) break;
1357 }
1358 }
1359}
1360
dan0106e372013-08-12 16:34:32 +00001361/*
1362** Load the content from either the sqlite_stat4 or sqlite_stat3 table
1363** into the relevant Index.aSample[] arrays.
1364**
1365** Arguments zSql1 and zSql2 must point to SQL statements that return
1366** data equivalent to the following (statements are different for stat3,
1367** see the caller of this function for details):
1368**
1369** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1370** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1371**
1372** where %Q is replaced with the database name before the SQL is executed.
1373*/
1374static int loadStatTbl(
1375 sqlite3 *db, /* Database handle */
1376 int bStat3, /* Assume single column records only */
1377 const char *zSql1, /* SQL statement 1 (see above) */
1378 const char *zSql2, /* SQL statement 2 (see above) */
1379 const char *zDb /* Database name (e.g. "main") */
1380){
drhfaacf172011-08-12 01:51:45 +00001381 int rc; /* Result codes from subroutines */
1382 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
1383 char *zSql; /* Text of the SQL statement */
1384 Index *pPrevIdx = 0; /* Previous index in the loop */
drhfaacf172011-08-12 01:51:45 +00001385 IndexSample *pSample; /* A slot in pIdx->aSample[] */
1386
dan0d1614c2012-03-19 10:21:37 +00001387 assert( db->lookaside.bEnabled==0 );
dan0106e372013-08-12 16:34:32 +00001388 zSql = sqlite3MPrintf(db, zSql1, zDb);
drhfaacf172011-08-12 01:51:45 +00001389 if( !zSql ){
1390 return SQLITE_NOMEM;
1391 }
1392 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1393 sqlite3DbFree(db, zSql);
1394 if( rc ) return rc;
1395
1396 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001397 int nIdxCol = 1; /* Number of columns in stat4 records */
1398 int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
1399
drhfaacf172011-08-12 01:51:45 +00001400 char *zIndex; /* Index name */
1401 Index *pIdx; /* Pointer to the index object */
1402 int nSample; /* Number of samples */
danf52bb8d2013-08-03 20:24:58 +00001403 int nByte; /* Bytes of space required */
1404 int i; /* Bytes of space required */
1405 tRowcnt *pSpace;
drhfaacf172011-08-12 01:51:45 +00001406
1407 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1408 if( zIndex==0 ) continue;
1409 nSample = sqlite3_column_int(pStmt, 1);
drhfaacf172011-08-12 01:51:45 +00001410 pIdx = sqlite3FindIndex(db, zIndex, zDb);
dan86f69d92013-08-12 17:31:32 +00001411 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
1412 /* Index.nSample is non-zero at this point if data has already been
1413 ** loaded from the stat4 table. In this case ignore stat3 data. */
1414 if( pIdx==0 || pIdx->nSample ) continue;
dan0106e372013-08-12 16:34:32 +00001415 if( bStat3==0 ){
1416 nIdxCol = pIdx->nColumn+1;
1417 nAvgCol = pIdx->nColumn;
1418 }
dan8ad169a2013-08-12 20:14:04 +00001419 pIdx->nSampleCol = nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001420 nByte = sizeof(IndexSample) * nSample;
dan0106e372013-08-12 16:34:32 +00001421 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
1422 nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
danf52bb8d2013-08-03 20:24:58 +00001423
1424 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
drhfaacf172011-08-12 01:51:45 +00001425 if( pIdx->aSample==0 ){
drhfaacf172011-08-12 01:51:45 +00001426 sqlite3_finalize(pStmt);
1427 return SQLITE_NOMEM;
1428 }
danf52bb8d2013-08-03 20:24:58 +00001429 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
dan0106e372013-08-12 16:34:32 +00001430 pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
dan0adbed82013-08-15 19:56:32 +00001431 for(i=0; i<nSample; i++){
dan0106e372013-08-12 16:34:32 +00001432 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1433 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1434 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001435 }
1436 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
drhfaacf172011-08-12 01:51:45 +00001437 }
drh8e3937f2011-08-18 13:45:23 +00001438 rc = sqlite3_finalize(pStmt);
1439 if( rc ) return rc;
drhfaacf172011-08-12 01:51:45 +00001440
dan0106e372013-08-12 16:34:32 +00001441 zSql = sqlite3MPrintf(db, zSql2, zDb);
drhfaacf172011-08-12 01:51:45 +00001442 if( !zSql ){
1443 return SQLITE_NOMEM;
1444 }
1445 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1446 sqlite3DbFree(db, zSql);
1447 if( rc ) return rc;
1448
1449 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001450 char *zIndex; /* Index name */
1451 Index *pIdx; /* Pointer to the index object */
dan0106e372013-08-12 16:34:32 +00001452 int nCol = 1; /* Number of columns in index */
drhfaacf172011-08-12 01:51:45 +00001453
1454 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1455 if( zIndex==0 ) continue;
1456 pIdx = sqlite3FindIndex(db, zIndex, zDb);
1457 if( pIdx==0 ) continue;
dan86f69d92013-08-12 17:31:32 +00001458 /* This next condition is true if data has already been loaded from
1459 ** the sqlite_stat4 table. In this case ignore stat3 data. */
dan0adbed82013-08-15 19:56:32 +00001460 nCol = pIdx->nSampleCol;
1461 if( bStat3 && nCol>1 ) continue;
1462 if( pIdx!=pPrevIdx ){
1463 initAvgEq(pPrevIdx);
1464 pPrevIdx = pIdx;
dan0106e372013-08-12 16:34:32 +00001465 }
danc367d4c2013-08-16 14:09:43 +00001466 pSample = &pIdx->aSample[pIdx->nSample];
danf52bb8d2013-08-03 20:24:58 +00001467 decodeIntArray((char*)sqlite3_column_text(pStmt,1), nCol, pSample->anEq, 0);
1468 decodeIntArray((char*)sqlite3_column_text(pStmt,2), nCol, pSample->anLt, 0);
1469 decodeIntArray((char*)sqlite3_column_text(pStmt,3), nCol, pSample->anDLt,0);
1470
danc367d4c2013-08-16 14:09:43 +00001471 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
1472 ** This is in case the sample record is corrupted. In that case, the
1473 ** sqlite3VdbeRecordCompare() may read up to two varints past the
1474 ** end of the allocated buffer before it realizes it is dealing with
1475 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
1476 ** a buffer overread. */
danf52bb8d2013-08-03 20:24:58 +00001477 pSample->n = sqlite3_column_bytes(pStmt, 4);
danc367d4c2013-08-16 14:09:43 +00001478 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
danf52bb8d2013-08-03 20:24:58 +00001479 if( pSample->p==0 ){
1480 sqlite3_finalize(pStmt);
1481 return SQLITE_NOMEM;
drhfaacf172011-08-12 01:51:45 +00001482 }
danf52bb8d2013-08-03 20:24:58 +00001483 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
danc367d4c2013-08-16 14:09:43 +00001484 pIdx->nSample++;
drhfaacf172011-08-12 01:51:45 +00001485 }
drh61b34402013-08-16 13:34:50 +00001486 rc = sqlite3_finalize(pStmt);
1487 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
1488 return rc;
drhfaacf172011-08-12 01:51:45 +00001489}
dan0106e372013-08-12 16:34:32 +00001490
1491/*
1492** Load content from the sqlite_stat4 and sqlite_stat3 tables into
1493** the Index.aSample[] arrays of all indices.
1494*/
1495static int loadStat4(sqlite3 *db, const char *zDb){
1496 int rc = SQLITE_OK; /* Result codes from subroutines */
1497
1498 assert( db->lookaside.bEnabled==0 );
1499 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
1500 rc = loadStatTbl(db, 0,
1501 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
1502 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1503 zDb
1504 );
1505 }
1506
1507 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
1508 rc = loadStatTbl(db, 1,
1509 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
1510 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
1511 zDb
1512 );
1513 }
1514
1515 return rc;
1516}
drh1435a9a2013-08-27 23:15:44 +00001517#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drhfaacf172011-08-12 01:51:45 +00001518
1519/*
drh92707ac2013-08-17 18:57:15 +00001520** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
dan85c165c2009-08-19 14:34:54 +00001521** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
drh92707ac2013-08-17 18:57:15 +00001522** arrays. The contents of sqlite_stat3/4 are used to populate the
dan85c165c2009-08-19 14:34:54 +00001523** Index.aSample[] arrays.
1524**
1525** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
drh92707ac2013-08-17 18:57:15 +00001526** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
1527** during compilation and the sqlite_stat3/4 table is present, no data is
dan85c165c2009-08-19 14:34:54 +00001528** read from it.
1529**
drh92707ac2013-08-17 18:57:15 +00001530** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
danf52bb8d2013-08-03 20:24:58 +00001531** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
dan85c165c2009-08-19 14:34:54 +00001532** returned. However, in this case, data is read from the sqlite_stat1
1533** table (if it is present) before returning.
1534**
1535** If an OOM error occurs, this function always sets db->mallocFailed.
1536** This means if the caller does not care about other errors, the return
1537** code may be ignored.
drh497e4462005-07-23 03:18:40 +00001538*/
drhcf1be452007-05-12 12:08:51 +00001539int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
drh497e4462005-07-23 03:18:40 +00001540 analysisInfo sInfo;
1541 HashElem *i;
1542 char *zSql;
drhcf1be452007-05-12 12:08:51 +00001543 int rc;
drh497e4462005-07-23 03:18:40 +00001544
drhff0587c2007-08-29 17:43:19 +00001545 assert( iDb>=0 && iDb<db->nDb );
1546 assert( db->aDb[iDb].pBt!=0 );
drh1fee73e2007-08-29 04:00:57 +00001547
drh497e4462005-07-23 03:18:40 +00001548 /* Clear any prior statistics */
drh21206082011-04-04 18:22:02 +00001549 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001550 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
drh497e4462005-07-23 03:18:40 +00001551 Index *pIdx = sqliteHashData(i);
drh51147ba2005-07-23 22:59:55 +00001552 sqlite3DefaultRowEst(pIdx);
drh1435a9a2013-08-27 23:15:44 +00001553#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dand46def72010-07-24 11:28:28 +00001554 sqlite3DeleteIndexSamples(db, pIdx);
1555 pIdx->aSample = 0;
drhfaacf172011-08-12 01:51:45 +00001556#endif
drh497e4462005-07-23 03:18:40 +00001557 }
1558
dan85c165c2009-08-19 14:34:54 +00001559 /* Check to make sure the sqlite_stat1 table exists */
drh497e4462005-07-23 03:18:40 +00001560 sInfo.db = db;
1561 sInfo.zDatabase = db->aDb[iDb].zName;
1562 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
dan85c165c2009-08-19 14:34:54 +00001563 return SQLITE_ERROR;
drh497e4462005-07-23 03:18:40 +00001564 }
1565
drh497e4462005-07-23 03:18:40 +00001566 /* Load new statistics out of the sqlite_stat1 table */
dan85c165c2009-08-19 14:34:54 +00001567 zSql = sqlite3MPrintf(db,
drhfaacf172011-08-12 01:51:45 +00001568 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
drhf16ce3b2009-02-13 16:59:53 +00001569 if( zSql==0 ){
1570 rc = SQLITE_NOMEM;
1571 }else{
drhf16ce3b2009-02-13 16:59:53 +00001572 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
drhf16ce3b2009-02-13 16:59:53 +00001573 sqlite3DbFree(db, zSql);
drhf16ce3b2009-02-13 16:59:53 +00001574 }
dan02fa4692009-08-17 17:06:58 +00001575
dan85c165c2009-08-19 14:34:54 +00001576
danf52bb8d2013-08-03 20:24:58 +00001577 /* Load the statistics from the sqlite_stat4 table. */
drh1435a9a2013-08-27 23:15:44 +00001578#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan02fa4692009-08-17 17:06:58 +00001579 if( rc==SQLITE_OK ){
dan0d1614c2012-03-19 10:21:37 +00001580 int lookasideEnabled = db->lookaside.bEnabled;
1581 db->lookaside.bEnabled = 0;
danf52bb8d2013-08-03 20:24:58 +00001582 rc = loadStat4(db, sInfo.zDatabase);
dan0d1614c2012-03-19 10:21:37 +00001583 db->lookaside.bEnabled = lookasideEnabled;
dan02fa4692009-08-17 17:06:58 +00001584 }
dan69188d92009-08-19 08:18:32 +00001585#endif
dan02fa4692009-08-17 17:06:58 +00001586
dane275dc32009-08-18 16:24:58 +00001587 if( rc==SQLITE_NOMEM ){
1588 db->mallocFailed = 1;
1589 }
drhcf1be452007-05-12 12:08:51 +00001590 return rc;
drh497e4462005-07-23 03:18:40 +00001591}
drh9f18e8a2005-07-08 12:13:04 +00001592
drhff2d5ea2005-07-23 00:41:48 +00001593
drh9f18e8a2005-07-08 12:13:04 +00001594#endif /* SQLITE_OMIT_ANALYZE */