blob: 4dcd7e8b8ff48507eb56f89fc790c0dc49fadd73 [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
drh0ae4f142013-10-14 14:21:59 +000034** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later. It is
drh9fecc542013-08-27 20:16:48 +000035** 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
drh0ae4f142013-10-14 14:21:59 +0000110** binary encoding of a key from the index. The nEq column is a
111** list of integers. The first integer is the approximate number
112** of entries in the index whose left-most column exactly matches
113** the left-most column of the sample. The second integer in nEq
114** is the approximate number of entries in the index where the
115** 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) );
drh261c02d2013-10-25 14:46:15 +0000247 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], iDb, 3);
drh1435a9a2013-08-27 23:15:44 +0000248 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
danielk1977c00da102006-01-07 13:21:04 +0000249 }
drhff2d5ea2005-07-23 00:41:48 +0000250}
251
252/*
danf52bb8d2013-08-03 20:24:58 +0000253** Recommended number of samples for sqlite_stat4
drhfaacf172011-08-12 01:51:45 +0000254*/
danf52bb8d2013-08-03 20:24:58 +0000255#ifndef SQLITE_STAT4_SAMPLES
256# define SQLITE_STAT4_SAMPLES 24
drhfaacf172011-08-12 01:51:45 +0000257#endif
258
259/*
danf00e9022013-08-14 19:54:12 +0000260** Three SQL functions - stat_init(), stat_push(), and stat_get() -
drhade3add2011-08-13 00:58:05 +0000261** share an instance of the following structure to hold their state
262** information.
263*/
danf52bb8d2013-08-03 20:24:58 +0000264typedef struct Stat4Accum Stat4Accum;
danf00e9022013-08-14 19:54:12 +0000265typedef struct Stat4Sample Stat4Sample;
266struct Stat4Sample {
danf00e9022013-08-14 19:54:12 +0000267 tRowcnt *anEq; /* sqlite_stat4.nEq */
danf00e9022013-08-14 19:54:12 +0000268 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
drh1435a9a2013-08-27 23:15:44 +0000269#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000270 tRowcnt *anLt; /* sqlite_stat4.nLt */
drhda475b82013-11-04 21:44:54 +0000271 union {
272 i64 iRowid; /* Rowid in main table of the key */
273 u8 *aRowid; /* Key for WITHOUT ROWID tables */
274 } u;
drhebe25af2013-11-02 18:46:04 +0000275 u32 nRowid; /* Sizeof aRowid[] */
danf00e9022013-08-14 19:54:12 +0000276 u8 isPSample; /* True if a periodic sample */
277 int iCol; /* If !isPSample, the reason for inclusion */
278 u32 iHash; /* Tiebreaker hash */
drh9fecc542013-08-27 20:16:48 +0000279#endif
danf00e9022013-08-14 19:54:12 +0000280};
danf52bb8d2013-08-03 20:24:58 +0000281struct Stat4Accum {
drhade3add2011-08-13 00:58:05 +0000282 tRowcnt nRow; /* Number of rows in the entire table */
283 tRowcnt nPSample; /* How often to do a periodic sample */
danf00e9022013-08-14 19:54:12 +0000284 int nCol; /* Number of columns in index + rowid */
drhade3add2011-08-13 00:58:05 +0000285 int mxSample; /* Maximum number of samples to accumulate */
danf00e9022013-08-14 19:54:12 +0000286 Stat4Sample current; /* Current row as a Stat4Sample */
drhf404c862011-08-13 15:25:10 +0000287 u32 iPrn; /* Pseudo-random number used for sampling */
drhebe25af2013-11-02 18:46:04 +0000288 Stat4Sample *aBest; /* Array of nCol best samples */
danf00e9022013-08-14 19:54:12 +0000289 int iMin; /* Index in a[] of entry with minimum score */
290 int nSample; /* Current number of samples */
291 int iGet; /* Index of current sample accessed by stat_get() */
292 Stat4Sample *a; /* Array of mxSample Stat4Sample objects */
drhebe25af2013-11-02 18:46:04 +0000293 sqlite3 *db; /* Database connection, for malloc() */
drhade3add2011-08-13 00:58:05 +0000294};
295
drhebe25af2013-11-02 18:46:04 +0000296/* Reclaim memory used by a Stat4Sample
297*/
298#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
299static void sampleClear(sqlite3 *db, Stat4Sample *p){
drhda475b82013-11-04 21:44:54 +0000300 assert( db!=0 );
301 if( p->nRowid ){
302 sqlite3DbFree(db, p->u.aRowid);
303 p->nRowid = 0;
304 }
drhebe25af2013-11-02 18:46:04 +0000305}
306#endif
307
drhda475b82013-11-04 21:44:54 +0000308/* Initialize the BLOB value of a ROWID
drhebe25af2013-11-02 18:46:04 +0000309*/
310#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhda475b82013-11-04 21:44:54 +0000311static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
312 assert( db!=0 );
313 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
314 p->u.aRowid = sqlite3DbMallocRaw(db, n);
315 if( p->u.aRowid ){
316 p->nRowid = n;
317 memcpy(p->u.aRowid, pData, n);
318 }else{
319 p->nRowid = 0;
320 }
321}
322#endif
323
324/* Initialize the INTEGER value of a ROWID.
325*/
326#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
327static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
328 assert( db!=0 );
329 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
330 p->nRowid = 0;
331 p->u.iRowid = iRowid;
332}
333#endif
334
335
336/*
337** Copy the contents of object (*pFrom) into (*pTo).
338*/
339#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
340static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
341 pTo->isPSample = pFrom->isPSample;
342 pTo->iCol = pFrom->iCol;
343 pTo->iHash = pFrom->iHash;
344 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
345 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
346 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
347 if( pFrom->nRowid ){
348 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
349 }else{
350 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
drhebe25af2013-11-02 18:46:04 +0000351 }
352}
353#endif
354
355/*
356** Reclaim all memory of a Stat4Accum structure.
357*/
358static void stat4Destructor(void *pOld){
359 Stat4Accum *p = (Stat4Accum*)pOld;
360#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
361 int i;
362 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
363 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
drhda475b82013-11-04 21:44:54 +0000364 sampleClear(p->db, &p->current);
drhebe25af2013-11-02 18:46:04 +0000365#endif
366 sqlite3DbFree(p->db, p);
367}
368
drhade3add2011-08-13 00:58:05 +0000369/*
drh9fecc542013-08-27 20:16:48 +0000370** Implementation of the stat_init(N,C) SQL function. The two parameters
drh59b08dd2013-08-27 14:14:14 +0000371** are the number of rows in the table or index (C) and the number of columns
drh9fecc542013-08-27 20:16:48 +0000372** in the index (N). The second argument (C) is only used for STAT3 and STAT4.
drhade3add2011-08-13 00:58:05 +0000373**
danf52bb8d2013-08-03 20:24:58 +0000374** This routine allocates the Stat4Accum object in heap memory. The return
375** value is a pointer to the the Stat4Accum object encoded as a blob (i.e.
376** the size of the blob is sizeof(void*) bytes).
drhade3add2011-08-13 00:58:05 +0000377*/
danf00e9022013-08-14 19:54:12 +0000378static void statInit(
drhade3add2011-08-13 00:58:05 +0000379 sqlite3_context *context,
380 int argc,
381 sqlite3_value **argv
382){
danf52bb8d2013-08-03 20:24:58 +0000383 Stat4Accum *p;
danf52bb8d2013-08-03 20:24:58 +0000384 int nCol; /* Number of columns in index being sampled */
drh9fecc542013-08-27 20:16:48 +0000385 int nColUp; /* nCol rounded up for alignment */
danf52bb8d2013-08-03 20:24:58 +0000386 int n; /* Bytes of space to allocate */
drhebe25af2013-11-02 18:46:04 +0000387 sqlite3 *db; /* Database connection */
drh1435a9a2013-08-27 23:15:44 +0000388#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000389 int mxSample = SQLITE_STAT4_SAMPLES;
390#endif
drhade3add2011-08-13 00:58:05 +0000391
danf52bb8d2013-08-03 20:24:58 +0000392 /* Decode the three function arguments */
drh68257192011-08-16 17:06:21 +0000393 UNUSED_PARAMETER(argc);
drh9fecc542013-08-27 20:16:48 +0000394 nCol = sqlite3_value_int(argv[0]);
dandd6e1f12013-08-10 19:08:30 +0000395 assert( nCol>1 ); /* >1 because it includes the rowid column */
drh9fecc542013-08-27 20:16:48 +0000396 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
danf52bb8d2013-08-03 20:24:58 +0000397
398 /* Allocate the space required for the Stat4Accum object */
danf00e9022013-08-14 19:54:12 +0000399 n = sizeof(*p)
drh9fecc542013-08-27 20:16:48 +0000400 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anEq */
401 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anDLt */
drh1435a9a2013-08-27 23:15:44 +0000402#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000403 + sizeof(tRowcnt)*nColUp /* Stat4Accum.anLt */
drhebe25af2013-11-02 18:46:04 +0000404 + sizeof(Stat4Sample)*(nCol+mxSample) /* Stat4Accum.aBest[], a[] */
drh9fecc542013-08-27 20:16:48 +0000405 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
406#endif
407 ;
drhebe25af2013-11-02 18:46:04 +0000408 db = sqlite3_context_db_handle(context);
409 p = sqlite3DbMallocZero(db, n);
drhade3add2011-08-13 00:58:05 +0000410 if( p==0 ){
411 sqlite3_result_error_nomem(context);
412 return;
413 }
danf52bb8d2013-08-03 20:24:58 +0000414
drhebe25af2013-11-02 18:46:04 +0000415 p->db = db;
drh9fecc542013-08-27 20:16:48 +0000416 p->nRow = 0;
danf52bb8d2013-08-03 20:24:58 +0000417 p->nCol = nCol;
danf00e9022013-08-14 19:54:12 +0000418 p->current.anDLt = (tRowcnt*)&p[1];
drh9fecc542013-08-27 20:16:48 +0000419 p->current.anEq = &p->current.anDLt[nColUp];
danf00e9022013-08-14 19:54:12 +0000420
drh1435a9a2013-08-27 23:15:44 +0000421#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000422 {
423 u8 *pSpace; /* Allocated space not yet assigned */
424 int i; /* Used to iterate through p->aSample[] */
danf52bb8d2013-08-03 20:24:58 +0000425
drh9fecc542013-08-27 20:16:48 +0000426 p->iGet = -1;
427 p->mxSample = mxSample;
danad4c7aa2013-08-30 20:19:52 +0000428 p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[1])/(mxSample/3+1) + 1);
drh9fecc542013-08-27 20:16:48 +0000429 p->current.anLt = &p->current.anEq[nColUp];
drh1d2b3c12013-09-10 01:41:25 +0000430 p->iPrn = nCol*0x689e962d ^ sqlite3_value_int(argv[1])*0xd0944565;
drh9fecc542013-08-27 20:16:48 +0000431
432 /* Set up the Stat4Accum.a[] and aBest[] arrays */
433 p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
434 p->aBest = &p->a[mxSample];
435 pSpace = (u8*)(&p->a[mxSample+nCol]);
436 for(i=0; i<(mxSample+nCol); i++){
437 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
438 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
439 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
440 }
441 assert( (pSpace - (u8*)p)==n );
442
443 for(i=0; i<nCol; i++){
444 p->aBest[i].iCol = i;
445 }
danf00e9022013-08-14 19:54:12 +0000446 }
drh9fecc542013-08-27 20:16:48 +0000447#endif
danf00e9022013-08-14 19:54:12 +0000448
danf52bb8d2013-08-03 20:24:58 +0000449 /* Return a pointer to the allocated object to the caller */
drhebe25af2013-11-02 18:46:04 +0000450 sqlite3_result_blob(context, p, sizeof(p), stat4Destructor);
drhade3add2011-08-13 00:58:05 +0000451}
danf00e9022013-08-14 19:54:12 +0000452static const FuncDef statInitFuncdef = {
drh9fecc542013-08-27 20:16:48 +0000453 1+IsStat34, /* nArg */
drhd36e1042013-09-06 13:10:12 +0000454 SQLITE_UTF8, /* funcFlags */
danf00e9022013-08-14 19:54:12 +0000455 0, /* pUserData */
456 0, /* pNext */
457 statInit, /* xFunc */
458 0, /* xStep */
459 0, /* xFinalize */
460 "stat_init", /* zName */
461 0, /* pHash */
462 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000463};
464
danb13af4c2013-09-03 14:43:12 +0000465#ifdef SQLITE_ENABLE_STAT4
466/*
467** pNew and pOld are both candidate non-periodic samples selected for
468** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
469** considering only any trailing columns and the sample hash value, this
470** function returns true if sample pNew is to be preferred over pOld.
471** In other words, if we assume that the cardinalities of the selected
472** column for pNew and pOld are equal, is pNew to be preferred over pOld.
473**
474** This function assumes that for each argument sample, the contents of
475** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
476*/
477static int sampleIsBetterPost(
478 Stat4Accum *pAccum,
479 Stat4Sample *pNew,
480 Stat4Sample *pOld
481){
482 int nCol = pAccum->nCol;
483 int i;
484 assert( pNew->iCol==pOld->iCol );
485 for(i=pNew->iCol+1; i<nCol; i++){
486 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
487 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
488 }
489 if( pNew->iHash>pOld->iHash ) return 1;
490 return 0;
491}
492#endif
493
drh1435a9a2013-08-27 23:15:44 +0000494#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000495/*
496** Return true if pNew is to be preferred over pOld.
danb13af4c2013-09-03 14:43:12 +0000497**
498** This function assumes that for each argument sample, the contents of
499** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
danf00e9022013-08-14 19:54:12 +0000500*/
danb13af4c2013-09-03 14:43:12 +0000501static int sampleIsBetter(
502 Stat4Accum *pAccum,
503 Stat4Sample *pNew,
504 Stat4Sample *pOld
505){
danf00e9022013-08-14 19:54:12 +0000506 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
507 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
508
509 assert( pOld->isPSample==0 && pNew->isPSample==0 );
510 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
511
danb13af4c2013-09-03 14:43:12 +0000512 if( (nEqNew>nEqOld) ) return 1;
513#ifdef SQLITE_ENABLE_STAT4
514 if( nEqNew==nEqOld ){
515 if( pNew->iCol<pOld->iCol ) return 1;
516 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
danf00e9022013-08-14 19:54:12 +0000517 }
518 return 0;
danb13af4c2013-09-03 14:43:12 +0000519#else
520 return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
521#endif
danf00e9022013-08-14 19:54:12 +0000522}
drhade3add2011-08-13 00:58:05 +0000523
524/*
danf00e9022013-08-14 19:54:12 +0000525** Copy the contents of sample *pNew into the p->a[] array. If necessary,
526** remove the least desirable sample from p->a[] to make room.
527*/
528static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
drhd2694612013-11-04 22:04:17 +0000529 Stat4Sample *pSample = 0;
danf52bb8d2013-08-03 20:24:58 +0000530 int i;
danf52bb8d2013-08-03 20:24:58 +0000531
danf00e9022013-08-14 19:54:12 +0000532 assert( IsStat4 || nEqZero==0 );
danf52bb8d2013-08-03 20:24:58 +0000533
drh30f07042013-09-04 02:07:38 +0000534#ifdef SQLITE_ENABLE_STAT4
danf00e9022013-08-14 19:54:12 +0000535 if( pNew->isPSample==0 ){
dan1f616ad2013-08-15 14:39:09 +0000536 Stat4Sample *pUpgrade = 0;
danf00e9022013-08-14 19:54:12 +0000537 assert( pNew->anEq[pNew->iCol]>0 );
drhade3add2011-08-13 00:58:05 +0000538
danf00e9022013-08-14 19:54:12 +0000539 /* This sample is being added because the prefix that ends in column
540 ** iCol occurs many times in the table. However, if we have already
541 ** added a sample that shares this prefix, there is no need to add
dan1f616ad2013-08-15 14:39:09 +0000542 ** this one. Instead, upgrade the priority of the highest priority
543 ** existing sample that shares this prefix. */
danf00e9022013-08-14 19:54:12 +0000544 for(i=p->nSample-1; i>=0; i--){
545 Stat4Sample *pOld = &p->a[i];
546 if( pOld->anEq[pNew->iCol]==0 ){
dan1f616ad2013-08-15 14:39:09 +0000547 if( pOld->isPSample ) return;
danb13af4c2013-09-03 14:43:12 +0000548 assert( pOld->iCol>pNew->iCol );
549 assert( sampleIsBetter(p, pNew, pOld) );
550 if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
dan1f616ad2013-08-15 14:39:09 +0000551 pUpgrade = pOld;
danf00e9022013-08-14 19:54:12 +0000552 }
dan1f28ead2013-08-07 16:15:32 +0000553 }
554 }
dan1f616ad2013-08-15 14:39:09 +0000555 if( pUpgrade ){
556 pUpgrade->iCol = pNew->iCol;
557 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
558 goto find_new_min;
559 }
drhade3add2011-08-13 00:58:05 +0000560 }
drh30f07042013-09-04 02:07:38 +0000561#endif
danf52bb8d2013-08-03 20:24:58 +0000562
danf00e9022013-08-14 19:54:12 +0000563 /* If necessary, remove sample iMin to make room for the new sample. */
564 if( p->nSample>=p->mxSample ){
565 Stat4Sample *pMin = &p->a[p->iMin];
danc55521a2013-08-05 05:34:30 +0000566 tRowcnt *anEq = pMin->anEq;
danc55521a2013-08-05 05:34:30 +0000567 tRowcnt *anLt = pMin->anLt;
danf00e9022013-08-14 19:54:12 +0000568 tRowcnt *anDLt = pMin->anDLt;
drhda475b82013-11-04 21:44:54 +0000569 sampleClear(p->db, pMin);
danf00e9022013-08-14 19:54:12 +0000570 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
drhf404c862011-08-13 15:25:10 +0000571 pSample = &p->a[p->nSample-1];
drhd2694612013-11-04 22:04:17 +0000572 pSample->nRowid = 0;
danc55521a2013-08-05 05:34:30 +0000573 pSample->anEq = anEq;
574 pSample->anDLt = anDLt;
575 pSample->anLt = anLt;
danf00e9022013-08-14 19:54:12 +0000576 p->nSample = p->mxSample-1;
dan8ad169a2013-08-12 20:14:04 +0000577 }
drhade3add2011-08-13 00:58:05 +0000578
danb49d1042013-09-02 18:58:11 +0000579 /* The "rows less-than" for the rowid column must be greater than that
580 ** for the last sample in the p->a[] array. Otherwise, the samples would
581 ** be out of order. */
582#ifdef SQLITE_ENABLE_STAT4
583 assert( p->nSample==0
584 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
585#endif
586
587 /* Insert the new sample */
588 pSample = &p->a[p->nSample];
589 sampleCopy(p, pSample, pNew);
590 p->nSample++;
591
danf00e9022013-08-14 19:54:12 +0000592 /* Zero the first nEqZero entries in the anEq[] array. */
593 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
594
mistachkinc2cfb512013-09-04 04:04:08 +0000595#ifdef SQLITE_ENABLE_STAT4
danf00e9022013-08-14 19:54:12 +0000596 find_new_min:
mistachkinc2cfb512013-09-04 04:04:08 +0000597#endif
danf00e9022013-08-14 19:54:12 +0000598 if( p->nSample>=p->mxSample ){
599 int iMin = -1;
danf52bb8d2013-08-03 20:24:58 +0000600 for(i=0; i<p->mxSample; i++){
601 if( p->a[i].isPSample ) continue;
danb13af4c2013-09-03 14:43:12 +0000602 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
drhade3add2011-08-13 00:58:05 +0000603 iMin = i;
drhade3add2011-08-13 00:58:05 +0000604 }
605 }
danf52bb8d2013-08-03 20:24:58 +0000606 assert( iMin>=0 );
drhade3add2011-08-13 00:58:05 +0000607 p->iMin = iMin;
608 }
609}
drh1435a9a2013-08-27 23:15:44 +0000610#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danf00e9022013-08-14 19:54:12 +0000611
612/*
613** Field iChng of the index being scanned has changed. So at this point
614** p->current contains a sample that reflects the previous row of the
615** index. The value of anEq[iChng] and subsequent anEq[] elements are
616** correct at this point.
617*/
618static void samplePushPrevious(Stat4Accum *p, int iChng){
drh92707ac2013-08-17 18:57:15 +0000619#ifdef SQLITE_ENABLE_STAT4
620 int i;
danf00e9022013-08-14 19:54:12 +0000621
drh92707ac2013-08-17 18:57:15 +0000622 /* Check if any samples from the aBest[] array should be pushed
623 ** into IndexSample.a[] at this point. */
624 for(i=(p->nCol-2); i>=iChng; i--){
625 Stat4Sample *pBest = &p->aBest[i];
danb13af4c2013-09-03 14:43:12 +0000626 pBest->anEq[i] = p->current.anEq[i];
627 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
drh92707ac2013-08-17 18:57:15 +0000628 sampleInsert(p, pBest, i);
danf00e9022013-08-14 19:54:12 +0000629 }
630 }
631
drh92707ac2013-08-17 18:57:15 +0000632 /* Update the anEq[] fields of any samples already collected. */
633 for(i=p->nSample-1; i>=0; i--){
634 int j;
635 for(j=iChng; j<p->nCol; j++){
636 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
637 }
638 }
639#endif
640
641#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
642 if( iChng==0 ){
danf00e9022013-08-14 19:54:12 +0000643 tRowcnt nLt = p->current.anLt[0];
644 tRowcnt nEq = p->current.anEq[0];
645
646 /* Check if this is to be a periodic sample. If so, add it. */
647 if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
648 p->current.isPSample = 1;
649 sampleInsert(p, &p->current, 0);
650 p->current.isPSample = 0;
651 }else
652
653 /* Or if it is a non-periodic sample. Add it in this case too. */
danb13af4c2013-09-03 14:43:12 +0000654 if( p->nSample<p->mxSample
655 || sampleIsBetter(p, &p->current, &p->a[p->iMin])
656 ){
danf00e9022013-08-14 19:54:12 +0000657 sampleInsert(p, &p->current, 0);
658 }
659 }
drh92707ac2013-08-17 18:57:15 +0000660#endif
drh4f991892013-10-11 15:05:05 +0000661
662#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
663 UNUSED_PARAMETER( p );
664 UNUSED_PARAMETER( iChng );
665#endif
danf00e9022013-08-14 19:54:12 +0000666}
667
668/*
drhebe25af2013-11-02 18:46:04 +0000669** Implementation of the stat_push SQL function: stat_push(P,C,R)
drh9fecc542013-08-27 20:16:48 +0000670** Arguments:
danf00e9022013-08-14 19:54:12 +0000671**
drh9fecc542013-08-27 20:16:48 +0000672** P Pointer to the Stat4Accum object created by stat_init()
673** C Index of left-most column to differ from previous row
drhebe25af2013-11-02 18:46:04 +0000674** R Rowid for the current row. Might be a key record for
675** WITHOUT ROWID tables.
danf00e9022013-08-14 19:54:12 +0000676**
drh9fecc542013-08-27 20:16:48 +0000677** The SQL function always returns NULL.
678**
drhebe25af2013-11-02 18:46:04 +0000679** The R parameter is only used for STAT3 and STAT4
danf00e9022013-08-14 19:54:12 +0000680*/
681static void statPush(
682 sqlite3_context *context,
683 int argc,
684 sqlite3_value **argv
685){
686 int i;
687
688 /* The three function arguments */
689 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
drh9fecc542013-08-27 20:16:48 +0000690 int iChng = sqlite3_value_int(argv[1]);
danf00e9022013-08-14 19:54:12 +0000691
drh4f991892013-10-11 15:05:05 +0000692 UNUSED_PARAMETER( argc );
693 UNUSED_PARAMETER( context );
danf00e9022013-08-14 19:54:12 +0000694 assert( p->nCol>1 ); /* Includes rowid field */
695 assert( iChng<p->nCol );
696
drh9fecc542013-08-27 20:16:48 +0000697 if( p->nRow==0 ){
danb49d1042013-09-02 18:58:11 +0000698 /* This is the first call to this function. Do initialization. */
drh9fecc542013-08-27 20:16:48 +0000699 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
700 }else{
701 /* Second and subsequent calls get processed here */
danf00e9022013-08-14 19:54:12 +0000702 samplePushPrevious(p, iChng);
703
704 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
705 ** to the current row of the index. */
706 for(i=0; i<iChng; i++){
707 p->current.anEq[i]++;
708 }
709 for(i=iChng; i<p->nCol; i++){
710 p->current.anDLt[i]++;
drh1435a9a2013-08-27 23:15:44 +0000711#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000712 p->current.anLt[i] += p->current.anEq[i];
drh9fecc542013-08-27 20:16:48 +0000713#endif
danf00e9022013-08-14 19:54:12 +0000714 p->current.anEq[i] = 1;
715 }
danf00e9022013-08-14 19:54:12 +0000716 }
drh9fecc542013-08-27 20:16:48 +0000717 p->nRow++;
drh1435a9a2013-08-27 23:15:44 +0000718#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drhebe25af2013-11-02 18:46:04 +0000719 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
drhda475b82013-11-04 21:44:54 +0000720 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
drhebe25af2013-11-02 18:46:04 +0000721 }else{
drhda475b82013-11-04 21:44:54 +0000722 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
723 sqlite3_value_blob(argv[2]));
drhebe25af2013-11-02 18:46:04 +0000724 }
drh9fecc542013-08-27 20:16:48 +0000725 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
726#endif
danf00e9022013-08-14 19:54:12 +0000727
drh92707ac2013-08-17 18:57:15 +0000728#ifdef SQLITE_ENABLE_STAT4
729 {
danf00e9022013-08-14 19:54:12 +0000730 tRowcnt nLt = p->current.anLt[p->nCol-1];
731
732 /* Check if this is to be a periodic sample. If so, add it. */
733 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
734 p->current.isPSample = 1;
735 p->current.iCol = 0;
736 sampleInsert(p, &p->current, p->nCol-1);
737 p->current.isPSample = 0;
738 }
739
740 /* Update the aBest[] array. */
741 for(i=0; i<(p->nCol-1); i++){
742 p->current.iCol = i;
danb13af4c2013-09-03 14:43:12 +0000743 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
danf00e9022013-08-14 19:54:12 +0000744 sampleCopy(p, &p->aBest[i], &p->current);
745 }
746 }
747 }
drh92707ac2013-08-17 18:57:15 +0000748#endif
danf00e9022013-08-14 19:54:12 +0000749}
750static const FuncDef statPushFuncdef = {
drh9fecc542013-08-27 20:16:48 +0000751 2+IsStat34, /* nArg */
drhd36e1042013-09-06 13:10:12 +0000752 SQLITE_UTF8, /* funcFlags */
danf00e9022013-08-14 19:54:12 +0000753 0, /* pUserData */
754 0, /* pNext */
755 statPush, /* xFunc */
756 0, /* xStep */
757 0, /* xFinalize */
758 "stat_push", /* zName */
759 0, /* pHash */
760 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000761};
762
danf00e9022013-08-14 19:54:12 +0000763#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
764#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
765#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
766#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
767#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
768
drhade3add2011-08-13 00:58:05 +0000769/*
drh92707ac2013-08-17 18:57:15 +0000770** Implementation of the stat_get(P,J) SQL function. This routine is
771** used to query the results. Content is returned for parameter J
772** which is one of the STAT_GET_xxxx values defined above.
drhade3add2011-08-13 00:58:05 +0000773**
drh92707ac2013-08-17 18:57:15 +0000774** If neither STAT3 nor STAT4 are enabled, then J is always
775** STAT_GET_STAT1 and is hence omitted and this routine becomes
776** a one-parameter function, stat_get(P), that always returns the
777** stat1 table entry information.
drhade3add2011-08-13 00:58:05 +0000778*/
danf00e9022013-08-14 19:54:12 +0000779static void statGet(
drhade3add2011-08-13 00:58:05 +0000780 sqlite3_context *context,
781 int argc,
782 sqlite3_value **argv
783){
danf52bb8d2013-08-03 20:24:58 +0000784 Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
drh1435a9a2013-08-27 23:15:44 +0000785#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh92707ac2013-08-17 18:57:15 +0000786 /* STAT3 and STAT4 have a parameter on this routine. */
danf00e9022013-08-14 19:54:12 +0000787 int eCall = sqlite3_value_int(argv[1]);
drh92707ac2013-08-17 18:57:15 +0000788 assert( argc==2 );
danf00e9022013-08-14 19:54:12 +0000789 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
790 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
791 || eCall==STAT_GET_NDLT
792 );
drh92707ac2013-08-17 18:57:15 +0000793 if( eCall==STAT_GET_STAT1 )
794#else
795 assert( argc==1 );
796#endif
797 {
danf00e9022013-08-14 19:54:12 +0000798 /* Return the value to store in the "stat" column of the sqlite_stat1
799 ** table for this index.
800 **
801 ** The value is a string composed of a list of integers describing
802 ** the index. The first integer in the list is the total number of
803 ** entries in the index. There is one additional integer in the list
804 ** for each indexed column. This additional integer is an estimate of
805 ** the number of rows matched by a stabbing query on the index using
806 ** a key with the corresponding number of fields. In other words,
807 ** if the index is on columns (a,b) and the sqlite_stat1 value is
808 ** "100 10 2", then SQLite estimates that:
809 **
810 ** * the index contains 100 rows,
811 ** * "WHERE a=?" matches 10 rows, and
812 ** * "WHERE a=? AND b=?" matches 2 rows.
813 **
814 ** If D is the count of distinct values and K is the total number of
815 ** rows, then each estimate is computed as:
816 **
817 ** I = (K+D-1)/D
818 */
819 char *z;
820 int i;
821
822 char *zRet = sqlite3MallocZero(p->nCol * 25);
823 if( zRet==0 ){
824 sqlite3_result_error_nomem(context);
825 return;
826 }
827
drh26586e72013-10-09 19:07:22 +0000828 sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
danf00e9022013-08-14 19:54:12 +0000829 z = zRet + sqlite3Strlen30(zRet);
830 for(i=0; i<(p->nCol-1); i++){
drh26586e72013-10-09 19:07:22 +0000831 u64 nDistinct = p->current.anDLt[i] + 1;
832 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
833 sqlite3_snprintf(24, z, " %llu", iVal);
danf00e9022013-08-14 19:54:12 +0000834 z += sqlite3Strlen30(z);
835 assert( p->current.anEq[i] );
836 }
837 assert( z[0]=='\0' && z>zRet );
838
839 sqlite3_result_text(context, zRet, -1, sqlite3_free);
drh92707ac2013-08-17 18:57:15 +0000840 }
drh1435a9a2013-08-27 23:15:44 +0000841#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh92707ac2013-08-17 18:57:15 +0000842 else if( eCall==STAT_GET_ROWID ){
danf00e9022013-08-14 19:54:12 +0000843 if( p->iGet<0 ){
844 samplePushPrevious(p, 0);
845 p->iGet = 0;
846 }
847 if( p->iGet<p->nSample ){
drhebe25af2013-11-02 18:46:04 +0000848 Stat4Sample *pS = p->a + p->iGet;
849 if( pS->nRowid==0 ){
drhda475b82013-11-04 21:44:54 +0000850 sqlite3_result_int64(context, pS->u.iRowid);
drhebe25af2013-11-02 18:46:04 +0000851 }else{
drhda475b82013-11-04 21:44:54 +0000852 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
853 SQLITE_TRANSIENT);
drhebe25af2013-11-02 18:46:04 +0000854 }
danf00e9022013-08-14 19:54:12 +0000855 }
856 }else{
danf52bb8d2013-08-03 20:24:58 +0000857 tRowcnt *aCnt = 0;
danf00e9022013-08-14 19:54:12 +0000858
859 assert( p->iGet<p->nSample );
860 switch( eCall ){
861 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
862 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
863 default: {
864 aCnt = p->a[p->iGet].anDLt;
865 p->iGet++;
866 break;
867 }
danf52bb8d2013-08-03 20:24:58 +0000868 }
869
dan8ad169a2013-08-12 20:14:04 +0000870 if( IsStat3 ){
871 sqlite3_result_int64(context, (i64)aCnt[0]);
danf52bb8d2013-08-03 20:24:58 +0000872 }else{
danf00e9022013-08-14 19:54:12 +0000873 char *zRet = sqlite3MallocZero(p->nCol * 25);
dan8ad169a2013-08-12 20:14:04 +0000874 if( zRet==0 ){
875 sqlite3_result_error_nomem(context);
876 }else{
877 int i;
878 char *z = zRet;
879 for(i=0; i<p->nCol; i++){
drh26586e72013-10-09 19:07:22 +0000880 sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
dan8ad169a2013-08-12 20:14:04 +0000881 z += sqlite3Strlen30(z);
882 }
883 assert( z[0]=='\0' && z>zRet );
884 z[-1] = '\0';
885 sqlite3_result_text(context, zRet, -1, sqlite3_free);
danf52bb8d2013-08-03 20:24:58 +0000886 }
danf52bb8d2013-08-03 20:24:58 +0000887 }
drhade3add2011-08-13 00:58:05 +0000888 }
drh1435a9a2013-08-27 23:15:44 +0000889#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drh4f991892013-10-11 15:05:05 +0000890#ifndef SQLITE_DEBUG
891 UNUSED_PARAMETER( argc );
892#endif
drhade3add2011-08-13 00:58:05 +0000893}
danf00e9022013-08-14 19:54:12 +0000894static const FuncDef statGetFuncdef = {
drh9fecc542013-08-27 20:16:48 +0000895 1+IsStat34, /* nArg */
drhd36e1042013-09-06 13:10:12 +0000896 SQLITE_UTF8, /* funcFlags */
danf00e9022013-08-14 19:54:12 +0000897 0, /* pUserData */
898 0, /* pNext */
899 statGet, /* xFunc */
900 0, /* xStep */
901 0, /* xFinalize */
902 "stat_get", /* zName */
903 0, /* pHash */
904 0 /* pDestructor */
drhade3add2011-08-13 00:58:05 +0000905};
drhade3add2011-08-13 00:58:05 +0000906
danf00e9022013-08-14 19:54:12 +0000907static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
908 assert( regOut!=regStat4 && regOut!=regStat4+1 );
drh1435a9a2013-08-27 23:15:44 +0000909#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
danf00e9022013-08-14 19:54:12 +0000910 sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
drh4f991892013-10-11 15:05:05 +0000911#elif SQLITE_DEBUG
drh92707ac2013-08-17 18:57:15 +0000912 assert( iParam==STAT_GET_STAT1 );
drh4f991892013-10-11 15:05:05 +0000913#else
914 UNUSED_PARAMETER( iParam );
drh92707ac2013-08-17 18:57:15 +0000915#endif
danf00e9022013-08-14 19:54:12 +0000916 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4, regOut);
917 sqlite3VdbeChangeP4(v, -1, (char*)&statGetFuncdef, P4_FUNCDEF);
drh9fecc542013-08-27 20:16:48 +0000918 sqlite3VdbeChangeP5(v, 1 + IsStat34);
danf00e9022013-08-14 19:54:12 +0000919}
drhade3add2011-08-13 00:58:05 +0000920
921/*
drhff2d5ea2005-07-23 00:41:48 +0000922** Generate code to do an analysis of all indices associated with
923** a single table.
924*/
925static void analyzeOneTable(
926 Parse *pParse, /* Parser context */
927 Table *pTab, /* Table whose indices are to be analyzed */
drha071bc52011-03-31 02:03:28 +0000928 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
drhdfe88ec2008-11-03 20:55:06 +0000929 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
danc6129702013-08-05 19:04:07 +0000930 int iMem, /* Available memory locations begin here */
931 int iTab /* Next available cursor */
drhff2d5ea2005-07-23 00:41:48 +0000932){
dan0f9a34e2009-08-19 16:34:31 +0000933 sqlite3 *db = pParse->db; /* Database handle */
dan69188d92009-08-19 08:18:32 +0000934 Index *pIdx; /* An index to being analyzed */
935 int iIdxCur; /* Cursor open on index being analyzed */
danc6129702013-08-05 19:04:07 +0000936 int iTabCur; /* Table cursor */
dan69188d92009-08-19 08:18:32 +0000937 Vdbe *v; /* The virtual machine being built up */
938 int i; /* Loop counter */
drhf6cf1ff2011-03-30 14:54:05 +0000939 int jZeroRows = -1; /* Jump from here if number of rows is zero */
dan69188d92009-08-19 08:18:32 +0000940 int iDb; /* Index of database containing pTab */
drh721dfcf2013-08-01 04:39:17 +0000941 u8 needTableCnt = 1; /* True to count the table */
danf00e9022013-08-14 19:54:12 +0000942 int regNewRowid = iMem++; /* Rowid for the inserted record */
943 int regStat4 = iMem++; /* Register to hold Stat4Accum object */
danf00e9022013-08-14 19:54:12 +0000944 int regChng = iMem++; /* Index of changed index field */
drh1435a9a2013-08-27 23:15:44 +0000945#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +0000946 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
947#endif
danf00e9022013-08-14 19:54:12 +0000948 int regTemp = iMem++; /* Temporary use register */
dane275dc32009-08-18 16:24:58 +0000949 int regTabname = iMem++; /* Register containing table name */
950 int regIdxname = iMem++; /* Register containing index name */
danf00e9022013-08-14 19:54:12 +0000951 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
952 int regPrev = iMem; /* MUST BE LAST (see below) */
dan68c4dbb2009-08-20 09:11:06 +0000953
drhf0459fc2013-08-15 16:15:00 +0000954 pParse->nMem = MAX(pParse->nMem, iMem);
drhff2d5ea2005-07-23 00:41:48 +0000955 v = sqlite3GetVdbe(pParse);
drh15564052010-09-25 22:32:56 +0000956 if( v==0 || NEVER(pTab==0) ){
957 return;
958 }
drhf39d29c2010-09-28 17:34:46 +0000959 if( pTab->tnum==0 ){
960 /* Do not gather statistics on views or virtual tables */
drh15564052010-09-25 22:32:56 +0000961 return;
962 }
drh503a6862013-03-01 01:07:17 +0000963 if( sqlite3_strnicmp(pTab->zName, "sqlite_", 7)==0 ){
drh15564052010-09-25 22:32:56 +0000964 /* Do not gather statistics on system tables */
drhff2d5ea2005-07-23 00:41:48 +0000965 return;
966 }
dan0f9a34e2009-08-19 16:34:31 +0000967 assert( sqlite3BtreeHoldsAllMutexes(db) );
968 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977da184232006-01-05 11:34:32 +0000969 assert( iDb>=0 );
drh21206082011-04-04 18:22:02 +0000970 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhe6e04962005-07-23 02:17:03 +0000971#ifndef SQLITE_OMIT_AUTHORIZATION
972 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
dan0f9a34e2009-08-19 16:34:31 +0000973 db->aDb[iDb].zName ) ){
drhe6e04962005-07-23 02:17:03 +0000974 return;
975 }
976#endif
977
dane0432012013-08-05 18:00:56 +0000978 /* Establish a read-lock on the table at the shared-cache level.
danf00e9022013-08-14 19:54:12 +0000979 ** Open a read-only cursor on the table. Also allocate a cursor number
980 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
981 ** this time though. */
danielk1977c00da102006-01-07 13:21:04 +0000982 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danc6129702013-08-05 19:04:07 +0000983 iTabCur = iTab++;
danf00e9022013-08-14 19:54:12 +0000984 iIdxCur = iTab++;
danc6129702013-08-05 19:04:07 +0000985 pParse->nTab = MAX(pParse->nTab, iTab);
dane0432012013-08-05 18:00:56 +0000986 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
drh15564052010-09-25 22:32:56 +0000987 sqlite3VdbeAddOp4(v, OP_String8, 0, regTabname, 0, pTab->zName, 0);
dane0432012013-08-05 18:00:56 +0000988
drhff2d5ea2005-07-23 00:41:48 +0000989 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
danf52bb8d2013-08-03 20:24:58 +0000990 int nCol; /* Number of columns indexed by pIdx */
danf00e9022013-08-14 19:54:12 +0000991 int *aGotoChng; /* Array of jump instruction addresses */
992 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
993 int addrGotoChng0; /* Address of "Goto addr_chng_0" */
994 int addrNextRow; /* Address of "next_row:" */
drhce95d112013-11-02 19:34:38 +0000995 const char *zIdxName; /* Name of the index */
danielk1977b3bf5562006-01-10 17:58:23 +0000996
drha071bc52011-03-31 02:03:28 +0000997 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
drh721dfcf2013-08-01 04:39:17 +0000998 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
drhfaacf172011-08-12 01:51:45 +0000999 VdbeNoopComment((v, "Begin analysis of %s", pIdx->zName));
drhbbbdc832013-10-22 18:01:40 +00001000 nCol = pIdx->nKeyCol;
danf00e9022013-08-14 19:54:12 +00001001 aGotoChng = sqlite3DbMallocRaw(db, sizeof(int)*(nCol+1));
1002 if( aGotoChng==0 ) continue;
dane275dc32009-08-18 16:24:58 +00001003
drh15564052010-09-25 22:32:56 +00001004 /* Populate the register containing the index name. */
drh48dd1d82014-05-27 18:18:58 +00001005 if( IsPrimaryKeyIndex(pIdx) && !HasRowid(pTab) ){
drhce95d112013-11-02 19:34:38 +00001006 zIdxName = pTab->zName;
1007 }else{
1008 zIdxName = pIdx->zName;
1009 }
1010 sqlite3VdbeAddOp4(v, OP_String8, 0, regIdxname, 0, zIdxName, 0);
dan69188d92009-08-19 08:18:32 +00001011
dane0432012013-08-05 18:00:56 +00001012 /*
danf00e9022013-08-14 19:54:12 +00001013 ** Pseudo-code for loop that calls stat_push():
dane0432012013-08-05 18:00:56 +00001014 **
danf00e9022013-08-14 19:54:12 +00001015 ** Rewind csr
1016 ** if eof(csr) goto end_of_scan;
1017 ** regChng = 0
1018 ** goto chng_addr_0;
dane0432012013-08-05 18:00:56 +00001019 **
dandd6e1f12013-08-10 19:08:30 +00001020 ** next_row:
danf00e9022013-08-14 19:54:12 +00001021 ** regChng = 0
1022 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
1023 ** regChng = 1
1024 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
1025 ** ...
1026 ** regChng = N
1027 ** goto chng_addr_N
dane0432012013-08-05 18:00:56 +00001028 **
danf00e9022013-08-14 19:54:12 +00001029 ** chng_addr_0:
1030 ** regPrev(0) = idx(0)
1031 ** chng_addr_1:
1032 ** regPrev(1) = idx(1)
1033 ** ...
dane0432012013-08-05 18:00:56 +00001034 **
danf00e9022013-08-14 19:54:12 +00001035 ** chng_addr_N:
1036 ** regRowid = idx(rowid)
drh9fecc542013-08-27 20:16:48 +00001037 ** stat_push(P, regChng, regRowid)
danf00e9022013-08-14 19:54:12 +00001038 ** Next csr
1039 ** if !eof(csr) goto next_row;
dane0432012013-08-05 18:00:56 +00001040 **
danf00e9022013-08-14 19:54:12 +00001041 ** end_of_scan:
dane0432012013-08-05 18:00:56 +00001042 */
danf00e9022013-08-14 19:54:12 +00001043
1044 /* Make sure there are enough memory cells allocated to accommodate
1045 ** the regPrev array and a trailing rowid (the rowid slot is required
1046 ** when building a record to insert into the sample column of
1047 ** the sqlite_stat4 table. */
danc6129702013-08-05 19:04:07 +00001048 pParse->nMem = MAX(pParse->nMem, regPrev+nCol);
dan02fa4692009-08-17 17:06:58 +00001049
danf00e9022013-08-14 19:54:12 +00001050 /* Open a read-only cursor on the index being analyzed. */
dane0432012013-08-05 18:00:56 +00001051 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
danf00e9022013-08-14 19:54:12 +00001052 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
drh2ec2fb22013-11-06 19:59:23 +00001053 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danf00e9022013-08-14 19:54:12 +00001054 VdbeComment((v, "%s", pIdx->zName));
dane0432012013-08-05 18:00:56 +00001055
danf00e9022013-08-14 19:54:12 +00001056 /* Invoke the stat_init() function. The arguments are:
danf52bb8d2013-08-03 20:24:58 +00001057 **
drh9fecc542013-08-27 20:16:48 +00001058 ** (1) the number of columns in the index including the rowid,
1059 ** (2) the number of rows in the index,
1060 **
1061 ** The second argument is only used for STAT3 and STAT4
danf52bb8d2013-08-03 20:24:58 +00001062 */
drh1435a9a2013-08-27 23:15:44 +00001063#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +00001064 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+2);
1065#endif
1066 sqlite3VdbeAddOp2(v, OP_Integer, nCol+1, regStat4+1);
danf52bb8d2013-08-03 20:24:58 +00001067 sqlite3VdbeAddOp3(v, OP_Function, 0, regStat4+1, regStat4);
danf00e9022013-08-14 19:54:12 +00001068 sqlite3VdbeChangeP4(v, -1, (char*)&statInitFuncdef, P4_FUNCDEF);
drh9fecc542013-08-27 20:16:48 +00001069 sqlite3VdbeChangeP5(v, 1+IsStat34);
danf52bb8d2013-08-03 20:24:58 +00001070
danf00e9022013-08-14 19:54:12 +00001071 /* Implementation of the following:
1072 **
1073 ** Rewind csr
1074 ** if eof(csr) goto end_of_scan;
1075 ** regChng = 0
1076 ** goto next_push_0;
1077 **
dandd6e1f12013-08-10 19:08:30 +00001078 */
danf00e9022013-08-14 19:54:12 +00001079 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
drh688852a2014-02-17 22:40:43 +00001080 VdbeCoverage(v);
danf00e9022013-08-14 19:54:12 +00001081 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
1082 addrGotoChng0 = sqlite3VdbeAddOp0(v, OP_Goto);
danf52bb8d2013-08-03 20:24:58 +00001083
danf00e9022013-08-14 19:54:12 +00001084 /*
1085 ** next_row:
1086 ** regChng = 0
1087 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
1088 ** regChng = 1
1089 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
1090 ** ...
1091 ** regChng = N
1092 ** goto chng_addr_N
1093 */
1094 addrNextRow = sqlite3VdbeCurrentAddr(v);
dandd6e1f12013-08-10 19:08:30 +00001095 for(i=0; i<nCol; i++){
dane0432012013-08-05 18:00:56 +00001096 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
danf00e9022013-08-14 19:54:12 +00001097 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
1098 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
1099 aGotoChng[i] =
1100 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
dane0432012013-08-05 18:00:56 +00001101 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
drh688852a2014-02-17 22:40:43 +00001102 VdbeCoverage(v);
dane0432012013-08-05 18:00:56 +00001103 }
danf00e9022013-08-14 19:54:12 +00001104 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regChng);
1105 aGotoChng[nCol] = sqlite3VdbeAddOp0(v, OP_Goto);
dane0432012013-08-05 18:00:56 +00001106
danf00e9022013-08-14 19:54:12 +00001107 /*
1108 ** chng_addr_0:
1109 ** regPrev(0) = idx(0)
1110 ** chng_addr_1:
1111 ** regPrev(1) = idx(1)
1112 ** ...
drhff2d5ea2005-07-23 00:41:48 +00001113 */
danf00e9022013-08-14 19:54:12 +00001114 sqlite3VdbeJumpHere(v, addrGotoChng0);
drhff2d5ea2005-07-23 00:41:48 +00001115 for(i=0; i<nCol; i++){
danf00e9022013-08-14 19:54:12 +00001116 sqlite3VdbeJumpHere(v, aGotoChng[i]);
1117 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
drhff2d5ea2005-07-23 00:41:48 +00001118 }
danf00e9022013-08-14 19:54:12 +00001119
1120 /*
1121 ** chng_addr_N:
drh9fecc542013-08-27 20:16:48 +00001122 ** regRowid = idx(rowid) // STAT34 only
1123 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT34 only
danf00e9022013-08-14 19:54:12 +00001124 ** Next csr
1125 ** if !eof(csr) goto next_row;
1126 */
1127 sqlite3VdbeJumpHere(v, aGotoChng[nCol]);
drh1435a9a2013-08-27 23:15:44 +00001128#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +00001129 assert( regRowid==(regStat4+2) );
drhebe25af2013-11-02 18:46:04 +00001130 if( HasRowid(pTab) ){
1131 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
1132 }else{
1133 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1134 int j, k, regKey;
1135 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1136 for(j=0; j<pPk->nKeyCol; j++){
1137 k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1138 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
1139 VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
1140 }
1141 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
1142 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
1143 }
drh9fecc542013-08-27 20:16:48 +00001144#endif
1145 assert( regChng==(regStat4+1) );
danf00e9022013-08-14 19:54:12 +00001146 sqlite3VdbeAddOp3(v, OP_Function, 1, regStat4, regTemp);
1147 sqlite3VdbeChangeP4(v, -1, (char*)&statPushFuncdef, P4_FUNCDEF);
drh9fecc542013-08-27 20:16:48 +00001148 sqlite3VdbeChangeP5(v, 2+IsStat34);
drh688852a2014-02-17 22:40:43 +00001149 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
danf00e9022013-08-14 19:54:12 +00001150
1151 /* Add the entry to the stat1 table. */
1152 callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
1153 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drhade3add2011-08-13 00:58:05 +00001154 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001155 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh2d401ab2008-01-10 23:50:11 +00001156 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
danf00e9022013-08-14 19:54:12 +00001157
1158 /* Add the entries to the stat3 or stat4 table. */
drh1435a9a2013-08-27 23:15:44 +00001159#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
drh9fecc542013-08-27 20:16:48 +00001160 {
danf00e9022013-08-14 19:54:12 +00001161 int regEq = regStat1;
1162 int regLt = regStat1+1;
1163 int regDLt = regStat1+2;
1164 int regSample = regStat1+3;
1165 int regCol = regStat1+4;
1166 int regSampleRowid = regCol + nCol;
1167 int addrNext;
1168 int addrIsNull;
drhebe25af2013-11-02 18:46:04 +00001169 u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
danf00e9022013-08-14 19:54:12 +00001170
1171 pParse->nMem = MAX(pParse->nMem, regCol+nCol+1);
1172
1173 addrNext = sqlite3VdbeCurrentAddr(v);
1174 callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
1175 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
drh688852a2014-02-17 22:40:43 +00001176 VdbeCoverage(v);
danf00e9022013-08-14 19:54:12 +00001177 callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
1178 callStatGet(v, regStat4, STAT_GET_NLT, regLt);
1179 callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
drhebe25af2013-11-02 18:46:04 +00001180 sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
drhfe705102014-03-06 13:38:37 +00001181 /* We know that the regSampleRowid row exists because it was read by
1182 ** the previous loop. Thus the not-found jump of seekOp will never
1183 ** be taken */
1184 VdbeCoverageNeverTaken(v);
drh9fecc542013-08-27 20:16:48 +00001185#ifdef SQLITE_ENABLE_STAT3
1186 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur,
1187 pIdx->aiColumn[0], regSample);
1188#else
1189 for(i=0; i<nCol; i++){
drhbbbdc832013-10-22 18:01:40 +00001190 i16 iCol = pIdx->aiColumn[i];
drh9fecc542013-08-27 20:16:48 +00001191 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTabCur, iCol, regCol+i);
danf00e9022013-08-14 19:54:12 +00001192 }
drh9fecc542013-08-27 20:16:48 +00001193 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol+1, regSample);
1194#endif
drh57bf4a82014-02-17 14:59:22 +00001195 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
danf00e9022013-08-14 19:54:12 +00001196 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
1197 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
drhfe705102014-03-06 13:38:37 +00001198 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
danf00e9022013-08-14 19:54:12 +00001199 sqlite3VdbeJumpHere(v, addrIsNull);
1200 }
drh1435a9a2013-08-27 23:15:44 +00001201#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
danf00e9022013-08-14 19:54:12 +00001202
drh9fecc542013-08-27 20:16:48 +00001203 /* End of analysis */
danf00e9022013-08-14 19:54:12 +00001204 sqlite3VdbeJumpHere(v, addrRewind);
1205 sqlite3DbFree(db, aGotoChng);
drh15564052010-09-25 22:32:56 +00001206 }
1207
danf00e9022013-08-14 19:54:12 +00001208
drh721dfcf2013-08-01 04:39:17 +00001209 /* Create a single sqlite_stat1 entry containing NULL as the index
1210 ** name and the row count as the content.
drh15564052010-09-25 22:32:56 +00001211 */
drh721dfcf2013-08-01 04:39:17 +00001212 if( pOnlyIdx==0 && needTableCnt ){
drh15564052010-09-25 22:32:56 +00001213 VdbeComment((v, "%s", pTab->zName));
dane0432012013-08-05 18:00:56 +00001214 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
drh688852a2014-02-17 22:40:43 +00001215 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
drh721dfcf2013-08-01 04:39:17 +00001216 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
danf00e9022013-08-14 19:54:12 +00001217 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "aaa", 0);
drh721dfcf2013-08-01 04:39:17 +00001218 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001219 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh721dfcf2013-08-01 04:39:17 +00001220 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
drh15564052010-09-25 22:32:56 +00001221 sqlite3VdbeJumpHere(v, jZeroRows);
1222 }
drhff2d5ea2005-07-23 00:41:48 +00001223}
1224
drhfaacf172011-08-12 01:51:45 +00001225
drhff2d5ea2005-07-23 00:41:48 +00001226/*
drh497e4462005-07-23 03:18:40 +00001227** Generate code that will cause the most recent index analysis to
drh15564052010-09-25 22:32:56 +00001228** be loaded into internal hash tables where is can be used.
drh497e4462005-07-23 03:18:40 +00001229*/
1230static void loadAnalysis(Parse *pParse, int iDb){
1231 Vdbe *v = sqlite3GetVdbe(pParse);
drhcf1be452007-05-12 12:08:51 +00001232 if( v ){
drh66a51672008-01-03 00:01:23 +00001233 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
drhcf1be452007-05-12 12:08:51 +00001234 }
drh497e4462005-07-23 03:18:40 +00001235}
1236
1237/*
drhff2d5ea2005-07-23 00:41:48 +00001238** Generate code that will do an analysis of an entire database
1239*/
1240static void analyzeDatabase(Parse *pParse, int iDb){
1241 sqlite3 *db = pParse->db;
danielk1977e501b892006-01-09 06:29:47 +00001242 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
drhff2d5ea2005-07-23 00:41:48 +00001243 HashElem *k;
1244 int iStatCur;
1245 int iMem;
danc6129702013-08-05 19:04:07 +00001246 int iTab;
drhff2d5ea2005-07-23 00:41:48 +00001247
1248 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001249 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001250 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001251 openStatTable(pParse, iDb, iStatCur, 0, 0);
drh0a07c102008-01-03 18:03:08 +00001252 iMem = pParse->nMem+1;
danc6129702013-08-05 19:04:07 +00001253 iTab = pParse->nTab;
drh21206082011-04-04 18:22:02 +00001254 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001255 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
drhff2d5ea2005-07-23 00:41:48 +00001256 Table *pTab = (Table*)sqliteHashData(k);
danc6129702013-08-05 19:04:07 +00001257 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
drhff2d5ea2005-07-23 00:41:48 +00001258 }
drh497e4462005-07-23 03:18:40 +00001259 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001260}
1261
1262/*
1263** Generate code that will do an analysis of a single table in
drha071bc52011-03-31 02:03:28 +00001264** a database. If pOnlyIdx is not NULL then it is a single index
1265** in pTab that should be analyzed.
drhff2d5ea2005-07-23 00:41:48 +00001266*/
drha071bc52011-03-31 02:03:28 +00001267static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
drhff2d5ea2005-07-23 00:41:48 +00001268 int iDb;
1269 int iStatCur;
1270
1271 assert( pTab!=0 );
drh1fee73e2007-08-29 04:00:57 +00001272 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +00001273 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhff2d5ea2005-07-23 00:41:48 +00001274 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001275 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001276 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001277 if( pOnlyIdx ){
1278 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
1279 }else{
1280 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
1281 }
danc6129702013-08-05 19:04:07 +00001282 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
drh497e4462005-07-23 03:18:40 +00001283 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001284}
1285
1286/*
1287** Generate code for the ANALYZE command. The parser calls this routine
1288** when it recognizes an ANALYZE command.
drh9f18e8a2005-07-08 12:13:04 +00001289**
1290** ANALYZE -- 1
drhff2d5ea2005-07-23 00:41:48 +00001291** ANALYZE <database> -- 2
drh9f18e8a2005-07-08 12:13:04 +00001292** ANALYZE ?<database>.?<tablename> -- 3
1293**
1294** Form 1 causes all indices in all attached databases to be analyzed.
1295** Form 2 analyzes all indices the single database named.
1296** Form 3 analyzes all indices associated with the named table.
1297*/
1298void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
drhff2d5ea2005-07-23 00:41:48 +00001299 sqlite3 *db = pParse->db;
1300 int iDb;
1301 int i;
1302 char *z, *zDb;
1303 Table *pTab;
drha071bc52011-03-31 02:03:28 +00001304 Index *pIdx;
drhff2d5ea2005-07-23 00:41:48 +00001305 Token *pTableName;
1306
1307 /* Read the database schema. If an error occurs, leave an error message
1308 ** and code in pParse and return NULL. */
drh1fee73e2007-08-29 04:00:57 +00001309 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhff2d5ea2005-07-23 00:41:48 +00001310 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1311 return;
1312 }
1313
drh05800a12009-04-16 17:45:47 +00001314 assert( pName2!=0 || pName1==0 );
drhff2d5ea2005-07-23 00:41:48 +00001315 if( pName1==0 ){
1316 /* Form 1: Analyze everything */
1317 for(i=0; i<db->nDb; i++){
1318 if( i==1 ) continue; /* Do not analyze the TEMP database */
1319 analyzeDatabase(pParse, i);
1320 }
drh05800a12009-04-16 17:45:47 +00001321 }else if( pName2->n==0 ){
drhff2d5ea2005-07-23 00:41:48 +00001322 /* Form 2: Analyze the database or table named */
1323 iDb = sqlite3FindDb(db, pName1);
1324 if( iDb>=0 ){
1325 analyzeDatabase(pParse, iDb);
drhe6e04962005-07-23 02:17:03 +00001326 }else{
drh17435752007-08-16 04:30:38 +00001327 z = sqlite3NameFromToken(db, pName1);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001328 if( z ){
drha071bc52011-03-31 02:03:28 +00001329 if( (pIdx = sqlite3FindIndex(db, z, 0))!=0 ){
1330 analyzeTable(pParse, pIdx->pTable, pIdx);
1331 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, 0))!=0 ){
1332 analyzeTable(pParse, pTab, 0);
danielk1977b8b4bfa2007-11-15 13:10:22 +00001333 }
drha071bc52011-03-31 02:03:28 +00001334 sqlite3DbFree(db, z);
drhe6e04962005-07-23 02:17:03 +00001335 }
drhff2d5ea2005-07-23 00:41:48 +00001336 }
drhff2d5ea2005-07-23 00:41:48 +00001337 }else{
1338 /* Form 3: Analyze the fully qualified table name */
1339 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
1340 if( iDb>=0 ){
1341 zDb = db->aDb[iDb].zName;
drh17435752007-08-16 04:30:38 +00001342 z = sqlite3NameFromToken(db, pTableName);
drhcf1be452007-05-12 12:08:51 +00001343 if( z ){
drha071bc52011-03-31 02:03:28 +00001344 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
1345 analyzeTable(pParse, pIdx->pTable, pIdx);
1346 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
1347 analyzeTable(pParse, pTab, 0);
drhcf1be452007-05-12 12:08:51 +00001348 }
drha071bc52011-03-31 02:03:28 +00001349 sqlite3DbFree(db, z);
drhff2d5ea2005-07-23 00:41:48 +00001350 }
1351 }
1352 }
drh9f18e8a2005-07-08 12:13:04 +00001353}
1354
drh497e4462005-07-23 03:18:40 +00001355/*
1356** Used to pass information from the analyzer reader through to the
1357** callback routine.
1358*/
1359typedef struct analysisInfo analysisInfo;
1360struct analysisInfo {
1361 sqlite3 *db;
1362 const char *zDatabase;
1363};
1364
1365/*
danf52bb8d2013-08-03 20:24:58 +00001366** The first argument points to a nul-terminated string containing a
1367** list of space separated integers. Read the first nOut of these into
1368** the array aOut[].
1369*/
1370static void decodeIntArray(
drhc28c4e52013-10-03 19:21:41 +00001371 char *zIntArray, /* String containing int array to decode */
1372 int nOut, /* Number of slots in aOut[] */
1373 tRowcnt *aOut, /* Store integers here */
dancfc9df72014-04-25 15:01:01 +00001374 LogEst *aLog, /* Or, if aOut==0, here */
drhc28c4e52013-10-03 19:21:41 +00001375 Index *pIndex /* Handle extra flags for this index, if not NULL */
danf52bb8d2013-08-03 20:24:58 +00001376){
1377 char *z = zIntArray;
1378 int c;
1379 int i;
1380 tRowcnt v;
drh1435a9a2013-08-27 23:15:44 +00001381
drh6d57bbf2013-08-28 11:43:49 +00001382#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1383 if( z==0 ) z = "";
1384#else
drh1435a9a2013-08-27 23:15:44 +00001385 if( NEVER(z==0) ) z = "";
drh6d57bbf2013-08-28 11:43:49 +00001386#endif
danf52bb8d2013-08-03 20:24:58 +00001387 for(i=0; *z && i<nOut; i++){
1388 v = 0;
1389 while( (c=z[0])>='0' && c<='9' ){
1390 v = v*10 + c - '0';
1391 z++;
1392 }
drhc5f246e2014-05-01 20:24:21 +00001393#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dancfc9df72014-04-25 15:01:01 +00001394 if( aOut ){
1395 aOut[i] = v;
drhc5f246e2014-05-01 20:24:21 +00001396 }else
1397#else
1398 assert( aOut==0 );
1399 UNUSED_PARAMETER(aOut);
1400#endif
1401 {
dancfc9df72014-04-25 15:01:01 +00001402 aLog[i] = sqlite3LogEst(v);
1403 }
danf52bb8d2013-08-03 20:24:58 +00001404 if( *z==' ' ) z++;
1405 }
drh1f1fc0c2013-10-08 23:16:48 +00001406#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
1407 assert( pIndex!=0 );
1408#else
1409 if( pIndex )
1410#endif
1411 {
drhd3037a42013-10-04 18:29:25 +00001412 if( strcmp(z, "unordered")==0 ){
1413 pIndex->bUnordered = 1;
drhe13e9f52013-10-05 19:18:00 +00001414 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
drhd3037a42013-10-04 18:29:25 +00001415 int v32 = 0;
drhe13e9f52013-10-05 19:18:00 +00001416 sqlite3GetInt32(z+3, &v32);
1417 pIndex->szIdxRow = sqlite3LogEst(v32);
drhc28c4e52013-10-03 19:21:41 +00001418 }
danf52bb8d2013-08-03 20:24:58 +00001419 }
1420}
1421
1422/*
drh497e4462005-07-23 03:18:40 +00001423** This callback is invoked once for each index when reading the
1424** sqlite_stat1 table.
1425**
drh15564052010-09-25 22:32:56 +00001426** argv[0] = name of the table
1427** argv[1] = name of the index (might be NULL)
1428** argv[2] = results of analysis - on integer for each column
1429**
1430** Entries for which argv[1]==NULL simply record the number of rows in
1431** the table.
drh497e4462005-07-23 03:18:40 +00001432*/
danielk197762c14b32008-11-19 09:05:26 +00001433static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
drh497e4462005-07-23 03:18:40 +00001434 analysisInfo *pInfo = (analysisInfo*)pData;
1435 Index *pIndex;
drh15564052010-09-25 22:32:56 +00001436 Table *pTable;
drh497e4462005-07-23 03:18:40 +00001437 const char *z;
1438
drh15564052010-09-25 22:32:56 +00001439 assert( argc==3 );
danielk1977f3d3c272008-11-19 16:52:44 +00001440 UNUSED_PARAMETER2(NotUsed, argc);
1441
drh15564052010-09-25 22:32:56 +00001442 if( argv==0 || argv[0]==0 || argv[2]==0 ){
drh497e4462005-07-23 03:18:40 +00001443 return 0;
1444 }
drh15564052010-09-25 22:32:56 +00001445 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
1446 if( pTable==0 ){
drh497e4462005-07-23 03:18:40 +00001447 return 0;
1448 }
drhc2b23e72013-11-13 15:32:15 +00001449 if( argv[1]==0 ){
drh15564052010-09-25 22:32:56 +00001450 pIndex = 0;
drhc2b23e72013-11-13 15:32:15 +00001451 }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
1452 pIndex = sqlite3PrimaryKeyIndex(pTable);
1453 }else{
1454 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
drh15564052010-09-25 22:32:56 +00001455 }
drh15564052010-09-25 22:32:56 +00001456 z = argv[2];
danf52bb8d2013-08-03 20:24:58 +00001457
1458 if( pIndex ){
dancfc9df72014-04-25 15:01:01 +00001459 decodeIntArray((char*)z, pIndex->nKeyCol+1, 0, pIndex->aiRowLogEst, pIndex);
1460 if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
danf52bb8d2013-08-03 20:24:58 +00001461 }else{
drh52f6c912013-10-06 22:12:41 +00001462 Index fakeIdx;
1463 fakeIdx.szIdxRow = pTable->szTabRow;
dancfc9df72014-04-25 15:01:01 +00001464 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
drh52f6c912013-10-06 22:12:41 +00001465 pTable->szTabRow = fakeIdx.szIdxRow;
drh497e4462005-07-23 03:18:40 +00001466 }
danf52bb8d2013-08-03 20:24:58 +00001467
drh497e4462005-07-23 03:18:40 +00001468 return 0;
1469}
1470
1471/*
dan85c165c2009-08-19 14:34:54 +00001472** If the Index.aSample variable is not NULL, delete the aSample[] array
1473** and its contents.
1474*/
dand46def72010-07-24 11:28:28 +00001475void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
drh1435a9a2013-08-27 23:15:44 +00001476#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan85c165c2009-08-19 14:34:54 +00001477 if( pIdx->aSample ){
1478 int j;
drhfaacf172011-08-12 01:51:45 +00001479 for(j=0; j<pIdx->nSample; j++){
dan85c165c2009-08-19 14:34:54 +00001480 IndexSample *p = &pIdx->aSample[j];
danf52bb8d2013-08-03 20:24:58 +00001481 sqlite3DbFree(db, p->p);
dan85c165c2009-08-19 14:34:54 +00001482 }
drh8e3937f2011-08-18 13:45:23 +00001483 sqlite3DbFree(db, pIdx->aSample);
dan85c165c2009-08-19 14:34:54 +00001484 }
drh8e3937f2011-08-18 13:45:23 +00001485 if( db && db->pnBytesFreed==0 ){
1486 pIdx->nSample = 0;
1487 pIdx->aSample = 0;
1488 }
shanecea72b22009-09-07 04:38:36 +00001489#else
drh43b18e12010-08-17 19:40:08 +00001490 UNUSED_PARAMETER(db);
shanecea72b22009-09-07 04:38:36 +00001491 UNUSED_PARAMETER(pIdx);
drh1435a9a2013-08-27 23:15:44 +00001492#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
dan85c165c2009-08-19 14:34:54 +00001493}
1494
drh1435a9a2013-08-27 23:15:44 +00001495#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan0adbed82013-08-15 19:56:32 +00001496/*
1497** Populate the pIdx->aAvgEq[] array based on the samples currently
1498** stored in pIdx->aSample[].
1499*/
1500static void initAvgEq(Index *pIdx){
1501 if( pIdx ){
1502 IndexSample *aSample = pIdx->aSample;
1503 IndexSample *pFinal = &aSample[pIdx->nSample-1];
1504 int iCol;
drhbbbdc832013-10-22 18:01:40 +00001505 for(iCol=0; iCol<pIdx->nKeyCol; iCol++){
dan0adbed82013-08-15 19:56:32 +00001506 int i; /* Used to iterate through samples */
1507 tRowcnt sumEq = 0; /* Sum of the nEq values */
danad4c7aa2013-08-30 20:19:52 +00001508 tRowcnt nSum = 0; /* Number of terms contributing to sumEq */
dan0adbed82013-08-15 19:56:32 +00001509 tRowcnt avgEq = 0;
1510 tRowcnt nDLt = pFinal->anDLt[iCol];
1511
1512 /* Set nSum to the number of distinct (iCol+1) field prefixes that
1513 ** occur in the stat4 table for this index before pFinal. Set
1514 ** sumEq to the sum of the nEq values for column iCol for the same
1515 ** set (adding the value only once where there exist dupicate
1516 ** prefixes). */
1517 for(i=0; i<(pIdx->nSample-1); i++){
1518 if( aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] ){
1519 sumEq += aSample[i].anEq[iCol];
1520 nSum++;
1521 }
1522 }
1523 if( nDLt>nSum ){
1524 avgEq = (pFinal->anLt[iCol] - sumEq)/(nDLt - nSum);
1525 }
1526 if( avgEq==0 ) avgEq = 1;
1527 pIdx->aAvgEq[iCol] = avgEq;
1528 if( pIdx->nSampleCol==1 ) break;
1529 }
1530 }
1531}
1532
dan0106e372013-08-12 16:34:32 +00001533/*
drhce95d112013-11-02 19:34:38 +00001534** Look up an index by name. Or, if the name of a WITHOUT ROWID table
1535** is supplied instead, find the PRIMARY KEY index for that table.
1536*/
1537static Index *findIndexOrPrimaryKey(
1538 sqlite3 *db,
1539 const char *zName,
1540 const char *zDb
1541){
1542 Index *pIdx = sqlite3FindIndex(db, zName, zDb);
1543 if( pIdx==0 ){
1544 Table *pTab = sqlite3FindTable(db, zName, zDb);
1545 if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
1546 }
1547 return pIdx;
1548}
1549
1550/*
dan0106e372013-08-12 16:34:32 +00001551** Load the content from either the sqlite_stat4 or sqlite_stat3 table
1552** into the relevant Index.aSample[] arrays.
1553**
1554** Arguments zSql1 and zSql2 must point to SQL statements that return
1555** data equivalent to the following (statements are different for stat3,
1556** see the caller of this function for details):
1557**
1558** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1559** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1560**
1561** where %Q is replaced with the database name before the SQL is executed.
1562*/
1563static int loadStatTbl(
1564 sqlite3 *db, /* Database handle */
1565 int bStat3, /* Assume single column records only */
1566 const char *zSql1, /* SQL statement 1 (see above) */
1567 const char *zSql2, /* SQL statement 2 (see above) */
1568 const char *zDb /* Database name (e.g. "main") */
1569){
drhfaacf172011-08-12 01:51:45 +00001570 int rc; /* Result codes from subroutines */
1571 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
1572 char *zSql; /* Text of the SQL statement */
1573 Index *pPrevIdx = 0; /* Previous index in the loop */
drhfaacf172011-08-12 01:51:45 +00001574 IndexSample *pSample; /* A slot in pIdx->aSample[] */
1575
dan0d1614c2012-03-19 10:21:37 +00001576 assert( db->lookaside.bEnabled==0 );
dan0106e372013-08-12 16:34:32 +00001577 zSql = sqlite3MPrintf(db, zSql1, zDb);
drhfaacf172011-08-12 01:51:45 +00001578 if( !zSql ){
1579 return SQLITE_NOMEM;
1580 }
1581 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1582 sqlite3DbFree(db, zSql);
1583 if( rc ) return rc;
1584
1585 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001586 int nIdxCol = 1; /* Number of columns in stat4 records */
1587 int nAvgCol = 1; /* Number of entries in Index.aAvgEq */
1588
drhfaacf172011-08-12 01:51:45 +00001589 char *zIndex; /* Index name */
1590 Index *pIdx; /* Pointer to the index object */
1591 int nSample; /* Number of samples */
danf52bb8d2013-08-03 20:24:58 +00001592 int nByte; /* Bytes of space required */
1593 int i; /* Bytes of space required */
1594 tRowcnt *pSpace;
drhfaacf172011-08-12 01:51:45 +00001595
1596 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1597 if( zIndex==0 ) continue;
1598 nSample = sqlite3_column_int(pStmt, 1);
drhce95d112013-11-02 19:34:38 +00001599 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
dan86f69d92013-08-12 17:31:32 +00001600 assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
1601 /* Index.nSample is non-zero at this point if data has already been
1602 ** loaded from the stat4 table. In this case ignore stat3 data. */
1603 if( pIdx==0 || pIdx->nSample ) continue;
dan0106e372013-08-12 16:34:32 +00001604 if( bStat3==0 ){
drhbbbdc832013-10-22 18:01:40 +00001605 nIdxCol = pIdx->nKeyCol+1;
1606 nAvgCol = pIdx->nKeyCol;
dan0106e372013-08-12 16:34:32 +00001607 }
dan8ad169a2013-08-12 20:14:04 +00001608 pIdx->nSampleCol = nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001609 nByte = sizeof(IndexSample) * nSample;
dan0106e372013-08-12 16:34:32 +00001610 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
1611 nByte += nAvgCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
danf52bb8d2013-08-03 20:24:58 +00001612
1613 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
drhfaacf172011-08-12 01:51:45 +00001614 if( pIdx->aSample==0 ){
drhfaacf172011-08-12 01:51:45 +00001615 sqlite3_finalize(pStmt);
1616 return SQLITE_NOMEM;
1617 }
danf52bb8d2013-08-03 20:24:58 +00001618 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
dan0106e372013-08-12 16:34:32 +00001619 pIdx->aAvgEq = pSpace; pSpace += nAvgCol;
dan0adbed82013-08-15 19:56:32 +00001620 for(i=0; i<nSample; i++){
dan0106e372013-08-12 16:34:32 +00001621 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1622 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1623 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001624 }
1625 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
drhfaacf172011-08-12 01:51:45 +00001626 }
drh8e3937f2011-08-18 13:45:23 +00001627 rc = sqlite3_finalize(pStmt);
1628 if( rc ) return rc;
drhfaacf172011-08-12 01:51:45 +00001629
dan0106e372013-08-12 16:34:32 +00001630 zSql = sqlite3MPrintf(db, zSql2, zDb);
drhfaacf172011-08-12 01:51:45 +00001631 if( !zSql ){
1632 return SQLITE_NOMEM;
1633 }
1634 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1635 sqlite3DbFree(db, zSql);
1636 if( rc ) return rc;
1637
1638 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001639 char *zIndex; /* Index name */
1640 Index *pIdx; /* Pointer to the index object */
dan0106e372013-08-12 16:34:32 +00001641 int nCol = 1; /* Number of columns in index */
drhfaacf172011-08-12 01:51:45 +00001642
1643 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1644 if( zIndex==0 ) continue;
drhce95d112013-11-02 19:34:38 +00001645 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
drhfaacf172011-08-12 01:51:45 +00001646 if( pIdx==0 ) continue;
dan86f69d92013-08-12 17:31:32 +00001647 /* This next condition is true if data has already been loaded from
1648 ** the sqlite_stat4 table. In this case ignore stat3 data. */
dan0adbed82013-08-15 19:56:32 +00001649 nCol = pIdx->nSampleCol;
1650 if( bStat3 && nCol>1 ) continue;
1651 if( pIdx!=pPrevIdx ){
1652 initAvgEq(pPrevIdx);
1653 pPrevIdx = pIdx;
dan0106e372013-08-12 16:34:32 +00001654 }
danc367d4c2013-08-16 14:09:43 +00001655 pSample = &pIdx->aSample[pIdx->nSample];
dancfc9df72014-04-25 15:01:01 +00001656 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
1657 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
1658 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
danf52bb8d2013-08-03 20:24:58 +00001659
danc367d4c2013-08-16 14:09:43 +00001660 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
1661 ** This is in case the sample record is corrupted. In that case, the
1662 ** sqlite3VdbeRecordCompare() may read up to two varints past the
1663 ** end of the allocated buffer before it realizes it is dealing with
1664 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
1665 ** a buffer overread. */
danf52bb8d2013-08-03 20:24:58 +00001666 pSample->n = sqlite3_column_bytes(pStmt, 4);
danc367d4c2013-08-16 14:09:43 +00001667 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
danf52bb8d2013-08-03 20:24:58 +00001668 if( pSample->p==0 ){
1669 sqlite3_finalize(pStmt);
1670 return SQLITE_NOMEM;
drhfaacf172011-08-12 01:51:45 +00001671 }
danf52bb8d2013-08-03 20:24:58 +00001672 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
danc367d4c2013-08-16 14:09:43 +00001673 pIdx->nSample++;
drhfaacf172011-08-12 01:51:45 +00001674 }
drh61b34402013-08-16 13:34:50 +00001675 rc = sqlite3_finalize(pStmt);
1676 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
1677 return rc;
drhfaacf172011-08-12 01:51:45 +00001678}
dan0106e372013-08-12 16:34:32 +00001679
1680/*
1681** Load content from the sqlite_stat4 and sqlite_stat3 tables into
1682** the Index.aSample[] arrays of all indices.
1683*/
1684static int loadStat4(sqlite3 *db, const char *zDb){
1685 int rc = SQLITE_OK; /* Result codes from subroutines */
1686
1687 assert( db->lookaside.bEnabled==0 );
1688 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
1689 rc = loadStatTbl(db, 0,
1690 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
1691 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1692 zDb
1693 );
1694 }
1695
1696 if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
1697 rc = loadStatTbl(db, 1,
1698 "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx",
1699 "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
1700 zDb
1701 );
1702 }
1703
1704 return rc;
1705}
drh1435a9a2013-08-27 23:15:44 +00001706#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
drhfaacf172011-08-12 01:51:45 +00001707
1708/*
drh92707ac2013-08-17 18:57:15 +00001709** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
dan85c165c2009-08-19 14:34:54 +00001710** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
drh92707ac2013-08-17 18:57:15 +00001711** arrays. The contents of sqlite_stat3/4 are used to populate the
dan85c165c2009-08-19 14:34:54 +00001712** Index.aSample[] arrays.
1713**
1714** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
drh92707ac2013-08-17 18:57:15 +00001715** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined
1716** during compilation and the sqlite_stat3/4 table is present, no data is
dan85c165c2009-08-19 14:34:54 +00001717** read from it.
1718**
drh92707ac2013-08-17 18:57:15 +00001719** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the
danf52bb8d2013-08-03 20:24:58 +00001720** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
dan85c165c2009-08-19 14:34:54 +00001721** returned. However, in this case, data is read from the sqlite_stat1
1722** table (if it is present) before returning.
1723**
1724** If an OOM error occurs, this function always sets db->mallocFailed.
1725** This means if the caller does not care about other errors, the return
1726** code may be ignored.
drh497e4462005-07-23 03:18:40 +00001727*/
drhcf1be452007-05-12 12:08:51 +00001728int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
drh497e4462005-07-23 03:18:40 +00001729 analysisInfo sInfo;
1730 HashElem *i;
1731 char *zSql;
drhcf1be452007-05-12 12:08:51 +00001732 int rc;
drh497e4462005-07-23 03:18:40 +00001733
drhff0587c2007-08-29 17:43:19 +00001734 assert( iDb>=0 && iDb<db->nDb );
1735 assert( db->aDb[iDb].pBt!=0 );
drh1fee73e2007-08-29 04:00:57 +00001736
drh497e4462005-07-23 03:18:40 +00001737 /* Clear any prior statistics */
drh21206082011-04-04 18:22:02 +00001738 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
danielk1977da184232006-01-05 11:34:32 +00001739 for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
drh497e4462005-07-23 03:18:40 +00001740 Index *pIdx = sqliteHashData(i);
drh51147ba2005-07-23 22:59:55 +00001741 sqlite3DefaultRowEst(pIdx);
drh1435a9a2013-08-27 23:15:44 +00001742#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dand46def72010-07-24 11:28:28 +00001743 sqlite3DeleteIndexSamples(db, pIdx);
1744 pIdx->aSample = 0;
drhfaacf172011-08-12 01:51:45 +00001745#endif
drh497e4462005-07-23 03:18:40 +00001746 }
1747
dan85c165c2009-08-19 14:34:54 +00001748 /* Check to make sure the sqlite_stat1 table exists */
drh497e4462005-07-23 03:18:40 +00001749 sInfo.db = db;
1750 sInfo.zDatabase = db->aDb[iDb].zName;
1751 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)==0 ){
dan85c165c2009-08-19 14:34:54 +00001752 return SQLITE_ERROR;
drh497e4462005-07-23 03:18:40 +00001753 }
1754
drh497e4462005-07-23 03:18:40 +00001755 /* Load new statistics out of the sqlite_stat1 table */
dan85c165c2009-08-19 14:34:54 +00001756 zSql = sqlite3MPrintf(db,
drhfaacf172011-08-12 01:51:45 +00001757 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
drhf16ce3b2009-02-13 16:59:53 +00001758 if( zSql==0 ){
1759 rc = SQLITE_NOMEM;
1760 }else{
drhf16ce3b2009-02-13 16:59:53 +00001761 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
drhf16ce3b2009-02-13 16:59:53 +00001762 sqlite3DbFree(db, zSql);
drhf16ce3b2009-02-13 16:59:53 +00001763 }
dan02fa4692009-08-17 17:06:58 +00001764
dan85c165c2009-08-19 14:34:54 +00001765
danf52bb8d2013-08-03 20:24:58 +00001766 /* Load the statistics from the sqlite_stat4 table. */
drh1435a9a2013-08-27 23:15:44 +00001767#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
dan02fa4692009-08-17 17:06:58 +00001768 if( rc==SQLITE_OK ){
dan0d1614c2012-03-19 10:21:37 +00001769 int lookasideEnabled = db->lookaside.bEnabled;
1770 db->lookaside.bEnabled = 0;
danf52bb8d2013-08-03 20:24:58 +00001771 rc = loadStat4(db, sInfo.zDatabase);
dan0d1614c2012-03-19 10:21:37 +00001772 db->lookaside.bEnabled = lookasideEnabled;
dan02fa4692009-08-17 17:06:58 +00001773 }
dan69188d92009-08-19 08:18:32 +00001774#endif
dan02fa4692009-08-17 17:06:58 +00001775
dane275dc32009-08-18 16:24:58 +00001776 if( rc==SQLITE_NOMEM ){
1777 db->mallocFailed = 1;
1778 }
drhcf1be452007-05-12 12:08:51 +00001779 return rc;
drh497e4462005-07-23 03:18:40 +00001780}
drh9f18e8a2005-07-08 12:13:04 +00001781
drhff2d5ea2005-07-23 00:41:48 +00001782
drh9f18e8a2005-07-08 12:13:04 +00001783#endif /* SQLITE_OMIT_ANALYZE */