blob: dc77220a53c515784bcdd2e01e69ca274f95ae4c [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
drh175b8f02019-08-08 15:24:17 +000030** created and used by SQLite versions 3.7.9 through 3.29.0 when
drhc8af8502013-08-09 14:07:55 +000031** SQLITE_ENABLE_STAT3 defined. The functionality of sqlite_stat3
drh175b8f02019-08-08 15:24:17 +000032** is a superset of sqlite_stat2 and is also now deprecated. The
33** sqlite_stat4 is an enhanced version of sqlite_stat3 and is only
34** available when compiled with SQLITE_ENABLE_STAT4 and in SQLite
35** versions 3.8.1 and later. STAT4 is the only variant that is still
36** supported.
drhc8af8502013-08-09 14:07:55 +000037**
peter.d.reid60ec9142014-09-06 16:39:46 +000038** For most applications, sqlite_stat1 provides all the statistics required
drhc8af8502013-08-09 14:07:55 +000039** 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
danf00e9022013-08-14 19:54:12 +0000147#else
drh92707ac2013-08-17 18:57:15 +0000148# define IsStat4 0
drh9fecc542013-08-27 20:16:48 +0000149# undef SQLITE_STAT4_SAMPLES
150# define SQLITE_STAT4_SAMPLES 1
dan8ad169a2013-08-12 20:14:04 +0000151#endif
152
drh9f18e8a2005-07-08 12:13:04 +0000153/*
drh9fecc542013-08-27 20:16:48 +0000154** This routine generates code that opens the sqlite_statN tables.
155** The sqlite_stat1 table is always relevant. sqlite_stat2 is now
156** obsolete. sqlite_stat3 and sqlite_stat4 are only opened when
157** appropriate compile-time options are provided.
drhff2d5ea2005-07-23 00:41:48 +0000158**
drh9fecc542013-08-27 20:16:48 +0000159** If the sqlite_statN tables do not previously exist, it is created.
dan69188d92009-08-19 08:18:32 +0000160**
161** Argument zWhere may be a pointer to a buffer containing a table name,
162** or it may be a NULL pointer. If it is not NULL, then all entries in
drh9fecc542013-08-27 20:16:48 +0000163** the sqlite_statN tables associated with the named table are deleted.
164** If zWhere==0, then code is generated to delete all stat table entries.
drhff2d5ea2005-07-23 00:41:48 +0000165*/
166static void openStatTable(
167 Parse *pParse, /* Parsing context */
168 int iDb, /* The database we are looking in */
169 int iStatCur, /* Open the sqlite_stat1 table on this cursor */
drha071bc52011-03-31 02:03:28 +0000170 const char *zWhere, /* Delete entries for this table or index */
171 const char *zWhereType /* Either "tbl" or "idx" */
drhff2d5ea2005-07-23 00:41:48 +0000172){
dan558814f2010-06-02 05:53:53 +0000173 static const struct {
dan69188d92009-08-19 08:18:32 +0000174 const char *zName;
175 const char *zCols;
176 } aTable[] = {
177 { "sqlite_stat1", "tbl,idx,stat" },
dan0106e372013-08-12 16:34:32 +0000178#if defined(SQLITE_ENABLE_STAT4)
danf52bb8d2013-08-03 20:24:58 +0000179 { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
drh9fecc542013-08-27 20:16:48 +0000180#else
drh9fecc542013-08-27 20:16:48 +0000181 { "sqlite_stat4", 0 },
drhfaacf172011-08-12 01:51:45 +0000182#endif
drh175b8f02019-08-08 15:24:17 +0000183 { "sqlite_stat3", 0 },
drhfaacf172011-08-12 01:51:45 +0000184 };
dan02fa4692009-08-17 17:06:58 +0000185 int i;
drhff2d5ea2005-07-23 00:41:48 +0000186 sqlite3 *db = pParse->db;
187 Db *pDb;
drhff2d5ea2005-07-23 00:41:48 +0000188 Vdbe *v = sqlite3GetVdbe(pParse);
drhabc38152020-07-22 13:38:04 +0000189 u32 aRoot[ArraySize(aTable)];
drh9fecc542013-08-27 20:16:48 +0000190 u8 aCreateTbl[ArraySize(aTable)];
drh9d33d9e2020-03-10 01:24:13 +0000191#ifdef SQLITE_ENABLE_STAT4
192 const int nToOpen = OptimizationEnabled(db,SQLITE_Stat4) ? 2 : 1;
193#else
194 const int nToOpen = 1;
195#endif
drh9fecc542013-08-27 20:16:48 +0000196
drhcf1be452007-05-12 12:08:51 +0000197 if( v==0 ) return;
drh1fee73e2007-08-29 04:00:57 +0000198 assert( sqlite3BtreeHoldsAllMutexes(db) );
199 assert( sqlite3VdbeDb(v)==db );
drhff2d5ea2005-07-23 00:41:48 +0000200 pDb = &db->aDb[iDb];
dan02fa4692009-08-17 17:06:58 +0000201
drhfaacf172011-08-12 01:51:45 +0000202 /* Create new statistic tables if they do not exist, or clear them
203 ** if they do already exist.
204 */
dan69188d92009-08-19 08:18:32 +0000205 for(i=0; i<ArraySize(aTable); i++){
206 const char *zTab = aTable[i].zName;
dan02fa4692009-08-17 17:06:58 +0000207 Table *pStat;
drh9d33d9e2020-03-10 01:24:13 +0000208 aCreateTbl[i] = 0;
drh69c33822016-08-18 14:33:11 +0000209 if( (pStat = sqlite3FindTable(db, zTab, pDb->zDbSName))==0 ){
drh9d33d9e2020-03-10 01:24:13 +0000210 if( i<nToOpen ){
drh9fecc542013-08-27 20:16:48 +0000211 /* The sqlite_statN table does not exist. Create it. Note that a
dan8ad169a2013-08-12 20:14:04 +0000212 ** side-effect of the CREATE TABLE statement is to leave the rootpage
213 ** of the new table in register pParse->regRoot. This is important
214 ** because the OpenWrite opcode below will be needing it. */
215 sqlite3NestedParse(pParse,
drh69c33822016-08-18 14:33:11 +0000216 "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
dan8ad169a2013-08-12 20:14:04 +0000217 );
drhabc38152020-07-22 13:38:04 +0000218 aRoot[i] = (u32)pParse->regRoot;
dan8ad169a2013-08-12 20:14:04 +0000219 aCreateTbl[i] = OPFLAG_P2ISREG;
220 }
dan02fa4692009-08-17 17:06:58 +0000221 }else{
222 /* The table already exists. If zWhere is not NULL, delete all entries
223 ** associated with the table zWhere. If zWhere is NULL, delete the
224 ** entire contents of the table. */
225 aRoot[i] = pStat->tnum;
dan69188d92009-08-19 08:18:32 +0000226 sqlite3TableLock(pParse, iDb, aRoot[i], 1, zTab);
dan02fa4692009-08-17 17:06:58 +0000227 if( zWhere ){
228 sqlite3NestedParse(pParse,
drh1435a9a2013-08-27 23:15:44 +0000229 "DELETE FROM %Q.%s WHERE %s=%Q",
drh69c33822016-08-18 14:33:11 +0000230 pDb->zDbSName, zTab, zWhereType, zWhere
dan02fa4692009-08-17 17:06:58 +0000231 );
dan614efe22018-01-12 16:44:29 +0000232#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
233 }else if( db->xPreUpdateCallback ){
234 sqlite3NestedParse(pParse, "DELETE FROM %Q.%s", pDb->zDbSName, zTab);
235#endif
dan02fa4692009-08-17 17:06:58 +0000236 }else{
dan8ad169a2013-08-12 20:14:04 +0000237 /* The sqlite_stat[134] table already exists. Delete all rows. */
drhabc38152020-07-22 13:38:04 +0000238 sqlite3VdbeAddOp2(v, OP_Clear, (int)aRoot[i], iDb);
dan02fa4692009-08-17 17:06:58 +0000239 }
240 }
drhff2d5ea2005-07-23 00:41:48 +0000241 }
242
danf00e9022013-08-14 19:54:12 +0000243 /* Open the sqlite_stat[134] tables for writing. */
drh9d33d9e2020-03-10 01:24:13 +0000244 for(i=0; i<nToOpen; i++){
drh1435a9a2013-08-27 23:15:44 +0000245 assert( i<ArraySize(aTable) );
drhabc38152020-07-22 13:38:04 +0000246 sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, (int)aRoot[i], iDb, 3);
drh1435a9a2013-08-27 23:15:44 +0000247 sqlite3VdbeChangeP5(v, aCreateTbl[i]);
drhec9e55d2014-06-30 17:07:39 +0000248 VdbeComment((v, aTable[i].zName));
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*/
drhafa1eca2020-03-09 18:26:11 +0000264typedef struct StatAccum StatAccum;
265typedef struct StatSample StatSample;
266struct StatSample {
danf00e9022013-08-14 19:54:12 +0000267 tRowcnt *anEq; /* sqlite_stat4.nEq */
danf00e9022013-08-14 19:54:12 +0000268 tRowcnt *anDLt; /* sqlite_stat4.nDLt */
drh175b8f02019-08-08 15:24:17 +0000269#ifdef SQLITE_ENABLE_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};
drhafa1eca2020-03-09 18:26:11 +0000281struct StatAccum {
282 sqlite3 *db; /* Database connection, for malloc() */
drh9f274632020-03-17 17:11:23 +0000283 tRowcnt nEst; /* Estimated number of rows */
284 tRowcnt nRow; /* Number of rows visited so far */
drh49a76a82020-03-31 20:57:06 +0000285 int nLimit; /* Analysis row-scan limit */
drhec9e55d2014-06-30 17:07:39 +0000286 int nCol; /* Number of columns in index + pk/rowid */
287 int nKeyCol; /* Number of index columns w/o the pk/rowid */
drh59a8cb72020-03-18 14:43:05 +0000288 u8 nSkipAhead; /* Number of times of skip-ahead */
drhafa1eca2020-03-09 18:26:11 +0000289 StatSample current; /* Current row as a StatSample */
290#ifdef SQLITE_ENABLE_STAT4
291 tRowcnt nPSample; /* How often to do a periodic sample */
drhade3add2011-08-13 00:58:05 +0000292 int mxSample; /* Maximum number of samples to accumulate */
drhf404c862011-08-13 15:25:10 +0000293 u32 iPrn; /* Pseudo-random number used for sampling */
drhafa1eca2020-03-09 18:26:11 +0000294 StatSample *aBest; /* Array of nCol best samples */
danf00e9022013-08-14 19:54:12 +0000295 int iMin; /* Index in a[] of entry with minimum score */
296 int nSample; /* Current number of samples */
danbd1d2702017-02-22 19:27:51 +0000297 int nMaxEqZero; /* Max leading 0 in anEq[] for any a[] entry */
danf00e9022013-08-14 19:54:12 +0000298 int iGet; /* Index of current sample accessed by stat_get() */
drhafa1eca2020-03-09 18:26:11 +0000299 StatSample *a; /* Array of mxSample StatSample objects */
300#endif
drhade3add2011-08-13 00:58:05 +0000301};
302
drhafa1eca2020-03-09 18:26:11 +0000303/* Reclaim memory used by a StatSample
drhebe25af2013-11-02 18:46:04 +0000304*/
drh175b8f02019-08-08 15:24:17 +0000305#ifdef SQLITE_ENABLE_STAT4
drhafa1eca2020-03-09 18:26:11 +0000306static void sampleClear(sqlite3 *db, StatSample *p){
drhda475b82013-11-04 21:44:54 +0000307 assert( db!=0 );
308 if( p->nRowid ){
309 sqlite3DbFree(db, p->u.aRowid);
310 p->nRowid = 0;
311 }
drhebe25af2013-11-02 18:46:04 +0000312}
313#endif
314
drhda475b82013-11-04 21:44:54 +0000315/* Initialize the BLOB value of a ROWID
drhebe25af2013-11-02 18:46:04 +0000316*/
drh175b8f02019-08-08 15:24:17 +0000317#ifdef SQLITE_ENABLE_STAT4
drhafa1eca2020-03-09 18:26:11 +0000318static void sampleSetRowid(sqlite3 *db, StatSample *p, int n, const u8 *pData){
drhda475b82013-11-04 21:44:54 +0000319 assert( db!=0 );
320 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
drh575fad62016-02-05 13:38:36 +0000321 p->u.aRowid = sqlite3DbMallocRawNN(db, n);
drhda475b82013-11-04 21:44:54 +0000322 if( p->u.aRowid ){
323 p->nRowid = n;
324 memcpy(p->u.aRowid, pData, n);
325 }else{
326 p->nRowid = 0;
327 }
328}
329#endif
330
331/* Initialize the INTEGER value of a ROWID.
332*/
drh175b8f02019-08-08 15:24:17 +0000333#ifdef SQLITE_ENABLE_STAT4
drhafa1eca2020-03-09 18:26:11 +0000334static void sampleSetRowidInt64(sqlite3 *db, StatSample *p, i64 iRowid){
drhda475b82013-11-04 21:44:54 +0000335 assert( db!=0 );
336 if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
337 p->nRowid = 0;
338 p->u.iRowid = iRowid;
339}
340#endif
341
342
343/*
344** Copy the contents of object (*pFrom) into (*pTo).
345*/
drh175b8f02019-08-08 15:24:17 +0000346#ifdef SQLITE_ENABLE_STAT4
drhafa1eca2020-03-09 18:26:11 +0000347static void sampleCopy(StatAccum *p, StatSample *pTo, StatSample *pFrom){
drhda475b82013-11-04 21:44:54 +0000348 pTo->isPSample = pFrom->isPSample;
349 pTo->iCol = pFrom->iCol;
350 pTo->iHash = pFrom->iHash;
351 memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
352 memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
353 memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
354 if( pFrom->nRowid ){
355 sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
356 }else{
357 sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
drhebe25af2013-11-02 18:46:04 +0000358 }
359}
360#endif
361
362/*
drhafa1eca2020-03-09 18:26:11 +0000363** Reclaim all memory of a StatAccum structure.
drhebe25af2013-11-02 18:46:04 +0000364*/
drhafa1eca2020-03-09 18:26:11 +0000365static void statAccumDestructor(void *pOld){
366 StatAccum *p = (StatAccum*)pOld;
drh175b8f02019-08-08 15:24:17 +0000367#ifdef SQLITE_ENABLE_STAT4
drh9d33d9e2020-03-10 01:24:13 +0000368 if( p->mxSample ){
369 int i;
370 for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
371 for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
372 sampleClear(p->db, &p->current);
373 }
drhebe25af2013-11-02 18:46:04 +0000374#endif
375 sqlite3DbFree(p->db, p);
376}
377
drhade3add2011-08-13 00:58:05 +0000378/*
drh49a76a82020-03-31 20:57:06 +0000379** Implementation of the stat_init(N,K,C,L) SQL function. The four parameters
drhec9e55d2014-06-30 17:07:39 +0000380** are:
drh553818a2014-07-23 18:36:55 +0000381** N: The number of columns in the index including the rowid/pk (note 1)
382** K: The number of columns in the index excluding the rowid/pk.
drh9f274632020-03-17 17:11:23 +0000383** C: Estimated number of rows in the index
drh49a76a82020-03-31 20:57:06 +0000384** L: A limit on the number of rows to scan, or 0 for no-limit
drhec9e55d2014-06-30 17:07:39 +0000385**
drh553818a2014-07-23 18:36:55 +0000386** Note 1: In the special case of the covering index that implements a
387** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
388** total number of columns in the table.
drhec9e55d2014-06-30 17:07:39 +0000389**
drh553818a2014-07-23 18:36:55 +0000390** For indexes on ordinary rowid tables, N==K+1. But for indexes on
391** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
392** PRIMARY KEY of the table. The covering index that implements the
393** original WITHOUT ROWID table as N==K as a special case.
drhade3add2011-08-13 00:58:05 +0000394**
drhafa1eca2020-03-09 18:26:11 +0000395** This routine allocates the StatAccum object in heap memory. The return
396** value is a pointer to the StatAccum object. The datatype of the
397** return value is BLOB, but it is really just a pointer to the StatAccum
drhf8ede572014-09-01 23:06:44 +0000398** object.
drhade3add2011-08-13 00:58:05 +0000399*/
danf00e9022013-08-14 19:54:12 +0000400static void statInit(
drhade3add2011-08-13 00:58:05 +0000401 sqlite3_context *context,
402 int argc,
403 sqlite3_value **argv
404){
drhafa1eca2020-03-09 18:26:11 +0000405 StatAccum *p;
danf52bb8d2013-08-03 20:24:58 +0000406 int nCol; /* Number of columns in index being sampled */
drhec9e55d2014-06-30 17:07:39 +0000407 int nKeyCol; /* Number of key columns */
drh9fecc542013-08-27 20:16:48 +0000408 int nColUp; /* nCol rounded up for alignment */
danf52bb8d2013-08-03 20:24:58 +0000409 int n; /* Bytes of space to allocate */
drh59a8cb72020-03-18 14:43:05 +0000410 sqlite3 *db = sqlite3_context_db_handle(context); /* Database connection */
drh175b8f02019-08-08 15:24:17 +0000411#ifdef SQLITE_ENABLE_STAT4
drhe50478d2020-03-17 13:41:51 +0000412 /* Maximum number of samples. 0 if STAT4 data is not collected */
drh59a8cb72020-03-18 14:43:05 +0000413 int mxSample = OptimizationEnabled(db,SQLITE_Stat4) ?SQLITE_STAT4_SAMPLES :0;
drh9fecc542013-08-27 20:16:48 +0000414#endif
drhade3add2011-08-13 00:58:05 +0000415
danf52bb8d2013-08-03 20:24:58 +0000416 /* Decode the three function arguments */
drh68257192011-08-16 17:06:21 +0000417 UNUSED_PARAMETER(argc);
drh9fecc542013-08-27 20:16:48 +0000418 nCol = sqlite3_value_int(argv[0]);
drhec9e55d2014-06-30 17:07:39 +0000419 assert( nCol>0 );
drh9fecc542013-08-27 20:16:48 +0000420 nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
drhec9e55d2014-06-30 17:07:39 +0000421 nKeyCol = sqlite3_value_int(argv[1]);
422 assert( nKeyCol<=nCol );
423 assert( nKeyCol>0 );
danf52bb8d2013-08-03 20:24:58 +0000424
drhafa1eca2020-03-09 18:26:11 +0000425 /* Allocate the space required for the StatAccum object */
danf00e9022013-08-14 19:54:12 +0000426 n = sizeof(*p)
drhafa1eca2020-03-09 18:26:11 +0000427 + sizeof(tRowcnt)*nColUp /* StatAccum.anEq */
drhe50478d2020-03-17 13:41:51 +0000428 + sizeof(tRowcnt)*nColUp; /* StatAccum.anDLt */
drh175b8f02019-08-08 15:24:17 +0000429#ifdef SQLITE_ENABLE_STAT4
drhe50478d2020-03-17 13:41:51 +0000430 if( mxSample ){
431 n += sizeof(tRowcnt)*nColUp /* StatAccum.anLt */
432 + sizeof(StatSample)*(nCol+mxSample) /* StatAccum.aBest[], a[] */
433 + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample);
434 }
drh9fecc542013-08-27 20:16:48 +0000435#endif
drhebe25af2013-11-02 18:46:04 +0000436 db = sqlite3_context_db_handle(context);
437 p = sqlite3DbMallocZero(db, n);
drhade3add2011-08-13 00:58:05 +0000438 if( p==0 ){
439 sqlite3_result_error_nomem(context);
440 return;
441 }
danf52bb8d2013-08-03 20:24:58 +0000442
drhebe25af2013-11-02 18:46:04 +0000443 p->db = db;
drh9f274632020-03-17 17:11:23 +0000444 p->nEst = sqlite3_value_int64(argv[2]);
drh9fecc542013-08-27 20:16:48 +0000445 p->nRow = 0;
drh49a76a82020-03-31 20:57:06 +0000446 p->nLimit = sqlite3_value_int64(argv[3]);
danf52bb8d2013-08-03 20:24:58 +0000447 p->nCol = nCol;
drhec9e55d2014-06-30 17:07:39 +0000448 p->nKeyCol = nKeyCol;
drh59a8cb72020-03-18 14:43:05 +0000449 p->nSkipAhead = 0;
danf00e9022013-08-14 19:54:12 +0000450 p->current.anDLt = (tRowcnt*)&p[1];
drh9fecc542013-08-27 20:16:48 +0000451 p->current.anEq = &p->current.anDLt[nColUp];
danf00e9022013-08-14 19:54:12 +0000452
drh175b8f02019-08-08 15:24:17 +0000453#ifdef SQLITE_ENABLE_STAT4
drh31e37442020-04-01 01:15:16 +0000454 p->mxSample = p->nLimit==0 ? mxSample : 0;
drh9d33d9e2020-03-10 01:24:13 +0000455 if( mxSample ){
drh9fecc542013-08-27 20:16:48 +0000456 u8 *pSpace; /* Allocated space not yet assigned */
457 int i; /* Used to iterate through p->aSample[] */
danf52bb8d2013-08-03 20:24:58 +0000458
drh9fecc542013-08-27 20:16:48 +0000459 p->iGet = -1;
drh9f274632020-03-17 17:11:23 +0000460 p->nPSample = (tRowcnt)(p->nEst/(mxSample/3+1) + 1);
drh9fecc542013-08-27 20:16:48 +0000461 p->current.anLt = &p->current.anEq[nColUp];
drh4081d5d2015-01-01 23:02:01 +0000462 p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
drh9fecc542013-08-27 20:16:48 +0000463
drhafa1eca2020-03-09 18:26:11 +0000464 /* Set up the StatAccum.a[] and aBest[] arrays */
465 p->a = (struct StatSample*)&p->current.anLt[nColUp];
drh9fecc542013-08-27 20:16:48 +0000466 p->aBest = &p->a[mxSample];
467 pSpace = (u8*)(&p->a[mxSample+nCol]);
468 for(i=0; i<(mxSample+nCol); i++){
469 p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
470 p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
471 p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
472 }
473 assert( (pSpace - (u8*)p)==n );
474
475 for(i=0; i<nCol; i++){
476 p->aBest[i].iCol = i;
477 }
danf00e9022013-08-14 19:54:12 +0000478 }
drh9fecc542013-08-27 20:16:48 +0000479#endif
danf00e9022013-08-14 19:54:12 +0000480
drhf8ede572014-09-01 23:06:44 +0000481 /* Return a pointer to the allocated object to the caller. Note that
482 ** only the pointer (the 2nd parameter) matters. The size of the object
483 ** (given by the 3rd parameter) is never used and can be any positive
484 ** value. */
drhafa1eca2020-03-09 18:26:11 +0000485 sqlite3_result_blob(context, p, sizeof(*p), statAccumDestructor);
drhade3add2011-08-13 00:58:05 +0000486}
danf00e9022013-08-14 19:54:12 +0000487static const FuncDef statInitFuncdef = {
drh31e37442020-04-01 01:15:16 +0000488 4, /* nArg */
drhd36e1042013-09-06 13:10:12 +0000489 SQLITE_UTF8, /* funcFlags */
danf00e9022013-08-14 19:54:12 +0000490 0, /* pUserData */
491 0, /* pNext */
drh2d801512016-01-14 22:19:58 +0000492 statInit, /* xSFunc */
danf00e9022013-08-14 19:54:12 +0000493 0, /* xFinalize */
dan980cf252018-06-10 07:42:35 +0000494 0, 0, /* xValue, xInverse */
danf00e9022013-08-14 19:54:12 +0000495 "stat_init", /* zName */
drh80738d92016-02-15 00:34:16 +0000496 {0}
drhade3add2011-08-13 00:58:05 +0000497};
498
danb13af4c2013-09-03 14:43:12 +0000499#ifdef SQLITE_ENABLE_STAT4
500/*
501** pNew and pOld are both candidate non-periodic samples selected for
502** the same column (pNew->iCol==pOld->iCol). Ignoring this column and
503** considering only any trailing columns and the sample hash value, this
504** function returns true if sample pNew is to be preferred over pOld.
505** In other words, if we assume that the cardinalities of the selected
506** column for pNew and pOld are equal, is pNew to be preferred over pOld.
507**
508** This function assumes that for each argument sample, the contents of
509** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid.
510*/
511static int sampleIsBetterPost(
drhafa1eca2020-03-09 18:26:11 +0000512 StatAccum *pAccum,
513 StatSample *pNew,
514 StatSample *pOld
danb13af4c2013-09-03 14:43:12 +0000515){
516 int nCol = pAccum->nCol;
517 int i;
518 assert( pNew->iCol==pOld->iCol );
519 for(i=pNew->iCol+1; i<nCol; i++){
520 if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
521 if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
522 }
523 if( pNew->iHash>pOld->iHash ) return 1;
524 return 0;
525}
526#endif
527
drh175b8f02019-08-08 15:24:17 +0000528#ifdef SQLITE_ENABLE_STAT4
danf00e9022013-08-14 19:54:12 +0000529/*
530** Return true if pNew is to be preferred over pOld.
danb13af4c2013-09-03 14:43:12 +0000531**
532** This function assumes that for each argument sample, the contents of
533** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid.
danf00e9022013-08-14 19:54:12 +0000534*/
danb13af4c2013-09-03 14:43:12 +0000535static int sampleIsBetter(
drhafa1eca2020-03-09 18:26:11 +0000536 StatAccum *pAccum,
537 StatSample *pNew,
538 StatSample *pOld
danb13af4c2013-09-03 14:43:12 +0000539){
danf00e9022013-08-14 19:54:12 +0000540 tRowcnt nEqNew = pNew->anEq[pNew->iCol];
541 tRowcnt nEqOld = pOld->anEq[pOld->iCol];
542
543 assert( pOld->isPSample==0 && pNew->isPSample==0 );
544 assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
545
danb13af4c2013-09-03 14:43:12 +0000546 if( (nEqNew>nEqOld) ) return 1;
danb13af4c2013-09-03 14:43:12 +0000547 if( nEqNew==nEqOld ){
548 if( pNew->iCol<pOld->iCol ) return 1;
549 return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
danf00e9022013-08-14 19:54:12 +0000550 }
551 return 0;
552}
drhade3add2011-08-13 00:58:05 +0000553
554/*
danf00e9022013-08-14 19:54:12 +0000555** Copy the contents of sample *pNew into the p->a[] array. If necessary,
556** remove the least desirable sample from p->a[] to make room.
557*/
drhafa1eca2020-03-09 18:26:11 +0000558static void sampleInsert(StatAccum *p, StatSample *pNew, int nEqZero){
559 StatSample *pSample = 0;
danf52bb8d2013-08-03 20:24:58 +0000560 int i;
danf52bb8d2013-08-03 20:24:58 +0000561
danf00e9022013-08-14 19:54:12 +0000562 assert( IsStat4 || nEqZero==0 );
danf52bb8d2013-08-03 20:24:58 +0000563
drhafa1eca2020-03-09 18:26:11 +0000564 /* StatAccum.nMaxEqZero is set to the maximum number of leading 0
565 ** values in the anEq[] array of any sample in StatAccum.a[]. In
danbd1d2702017-02-22 19:27:51 +0000566 ** other words, if nMaxEqZero is n, then it is guaranteed that there
drhafa1eca2020-03-09 18:26:11 +0000567 ** are no samples with StatSample.anEq[m]==0 for (m>=n). */
danbd1d2702017-02-22 19:27:51 +0000568 if( nEqZero>p->nMaxEqZero ){
569 p->nMaxEqZero = nEqZero;
570 }
danf00e9022013-08-14 19:54:12 +0000571 if( pNew->isPSample==0 ){
drhafa1eca2020-03-09 18:26:11 +0000572 StatSample *pUpgrade = 0;
danf00e9022013-08-14 19:54:12 +0000573 assert( pNew->anEq[pNew->iCol]>0 );
drhade3add2011-08-13 00:58:05 +0000574
danf00e9022013-08-14 19:54:12 +0000575 /* This sample is being added because the prefix that ends in column
576 ** iCol occurs many times in the table. However, if we have already
577 ** added a sample that shares this prefix, there is no need to add
dan1f616ad2013-08-15 14:39:09 +0000578 ** this one. Instead, upgrade the priority of the highest priority
579 ** existing sample that shares this prefix. */
danf00e9022013-08-14 19:54:12 +0000580 for(i=p->nSample-1; i>=0; i--){
drhafa1eca2020-03-09 18:26:11 +0000581 StatSample *pOld = &p->a[i];
danf00e9022013-08-14 19:54:12 +0000582 if( pOld->anEq[pNew->iCol]==0 ){
dan1f616ad2013-08-15 14:39:09 +0000583 if( pOld->isPSample ) return;
danb13af4c2013-09-03 14:43:12 +0000584 assert( pOld->iCol>pNew->iCol );
585 assert( sampleIsBetter(p, pNew, pOld) );
586 if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
dan1f616ad2013-08-15 14:39:09 +0000587 pUpgrade = pOld;
danf00e9022013-08-14 19:54:12 +0000588 }
dan1f28ead2013-08-07 16:15:32 +0000589 }
590 }
dan1f616ad2013-08-15 14:39:09 +0000591 if( pUpgrade ){
592 pUpgrade->iCol = pNew->iCol;
593 pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
594 goto find_new_min;
595 }
drhade3add2011-08-13 00:58:05 +0000596 }
danf52bb8d2013-08-03 20:24:58 +0000597
danf00e9022013-08-14 19:54:12 +0000598 /* If necessary, remove sample iMin to make room for the new sample. */
599 if( p->nSample>=p->mxSample ){
drhafa1eca2020-03-09 18:26:11 +0000600 StatSample *pMin = &p->a[p->iMin];
danc55521a2013-08-05 05:34:30 +0000601 tRowcnt *anEq = pMin->anEq;
danc55521a2013-08-05 05:34:30 +0000602 tRowcnt *anLt = pMin->anLt;
danf00e9022013-08-14 19:54:12 +0000603 tRowcnt *anDLt = pMin->anDLt;
drhda475b82013-11-04 21:44:54 +0000604 sampleClear(p->db, pMin);
danf00e9022013-08-14 19:54:12 +0000605 memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
drhf404c862011-08-13 15:25:10 +0000606 pSample = &p->a[p->nSample-1];
drhd2694612013-11-04 22:04:17 +0000607 pSample->nRowid = 0;
danc55521a2013-08-05 05:34:30 +0000608 pSample->anEq = anEq;
609 pSample->anDLt = anDLt;
610 pSample->anLt = anLt;
danf00e9022013-08-14 19:54:12 +0000611 p->nSample = p->mxSample-1;
dan8ad169a2013-08-12 20:14:04 +0000612 }
drhade3add2011-08-13 00:58:05 +0000613
danb49d1042013-09-02 18:58:11 +0000614 /* The "rows less-than" for the rowid column must be greater than that
615 ** for the last sample in the p->a[] array. Otherwise, the samples would
616 ** be out of order. */
danb49d1042013-09-02 18:58:11 +0000617 assert( p->nSample==0
618 || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
danb49d1042013-09-02 18:58:11 +0000619
620 /* Insert the new sample */
621 pSample = &p->a[p->nSample];
622 sampleCopy(p, pSample, pNew);
623 p->nSample++;
624
danf00e9022013-08-14 19:54:12 +0000625 /* Zero the first nEqZero entries in the anEq[] array. */
626 memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
627
drh175b8f02019-08-08 15:24:17 +0000628find_new_min:
danf00e9022013-08-14 19:54:12 +0000629 if( p->nSample>=p->mxSample ){
630 int iMin = -1;
danf52bb8d2013-08-03 20:24:58 +0000631 for(i=0; i<p->mxSample; i++){
632 if( p->a[i].isPSample ) continue;
danb13af4c2013-09-03 14:43:12 +0000633 if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
drhade3add2011-08-13 00:58:05 +0000634 iMin = i;
drhade3add2011-08-13 00:58:05 +0000635 }
636 }
danf52bb8d2013-08-03 20:24:58 +0000637 assert( iMin>=0 );
drhade3add2011-08-13 00:58:05 +0000638 p->iMin = iMin;
639 }
640}
drh175b8f02019-08-08 15:24:17 +0000641#endif /* SQLITE_ENABLE_STAT4 */
danf00e9022013-08-14 19:54:12 +0000642
drhafa1eca2020-03-09 18:26:11 +0000643#ifdef SQLITE_ENABLE_STAT4
danf00e9022013-08-14 19:54:12 +0000644/*
645** Field iChng of the index being scanned has changed. So at this point
646** p->current contains a sample that reflects the previous row of the
647** index. The value of anEq[iChng] and subsequent anEq[] elements are
648** correct at this point.
649*/
drhafa1eca2020-03-09 18:26:11 +0000650static void samplePushPrevious(StatAccum *p, int iChng){
drh92707ac2013-08-17 18:57:15 +0000651 int i;
danf00e9022013-08-14 19:54:12 +0000652
drh92707ac2013-08-17 18:57:15 +0000653 /* Check if any samples from the aBest[] array should be pushed
654 ** into IndexSample.a[] at this point. */
655 for(i=(p->nCol-2); i>=iChng; i--){
drhafa1eca2020-03-09 18:26:11 +0000656 StatSample *pBest = &p->aBest[i];
danb13af4c2013-09-03 14:43:12 +0000657 pBest->anEq[i] = p->current.anEq[i];
658 if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
drh92707ac2013-08-17 18:57:15 +0000659 sampleInsert(p, pBest, i);
danf00e9022013-08-14 19:54:12 +0000660 }
661 }
662
danbd1d2702017-02-22 19:27:51 +0000663 /* Check that no sample contains an anEq[] entry with an index of
664 ** p->nMaxEqZero or greater set to zero. */
drh92707ac2013-08-17 18:57:15 +0000665 for(i=p->nSample-1; i>=0; i--){
666 int j;
danbd1d2702017-02-22 19:27:51 +0000667 for(j=p->nMaxEqZero; j<p->nCol; j++) assert( p->a[i].anEq[j]>0 );
668 }
669
670 /* Update the anEq[] fields of any samples already collected. */
671 if( iChng<p->nMaxEqZero ){
672 for(i=p->nSample-1; i>=0; i--){
673 int j;
674 for(j=iChng; j<p->nCol; j++){
675 if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
676 }
drh92707ac2013-08-17 18:57:15 +0000677 }
danbd1d2702017-02-22 19:27:51 +0000678 p->nMaxEqZero = iChng;
drh92707ac2013-08-17 18:57:15 +0000679 }
danf00e9022013-08-14 19:54:12 +0000680}
drhafa1eca2020-03-09 18:26:11 +0000681#endif /* SQLITE_ENABLE_STAT4 */
danf00e9022013-08-14 19:54:12 +0000682
683/*
drhebe25af2013-11-02 18:46:04 +0000684** Implementation of the stat_push SQL function: stat_push(P,C,R)
drh9fecc542013-08-27 20:16:48 +0000685** Arguments:
danf00e9022013-08-14 19:54:12 +0000686**
drhafa1eca2020-03-09 18:26:11 +0000687** P Pointer to the StatAccum object created by stat_init()
drh9fecc542013-08-27 20:16:48 +0000688** C Index of left-most column to differ from previous row
drhebe25af2013-11-02 18:46:04 +0000689** R Rowid for the current row. Might be a key record for
690** WITHOUT ROWID tables.
danf00e9022013-08-14 19:54:12 +0000691**
drh59a8cb72020-03-18 14:43:05 +0000692** The purpose of this routine is to collect statistical data and/or
693** samples from the index being analyzed into the StatAccum object.
694** The stat_get() SQL function will be used afterwards to
695** retrieve the information gathered.
696**
697** This SQL function usually returns NULL, but might return an integer
698** if it wants the byte-code to do special processing.
drh9fecc542013-08-27 20:16:48 +0000699**
drh175b8f02019-08-08 15:24:17 +0000700** The R parameter is only used for STAT4
danf00e9022013-08-14 19:54:12 +0000701*/
702static void statPush(
703 sqlite3_context *context,
704 int argc,
705 sqlite3_value **argv
706){
707 int i;
708
709 /* The three function arguments */
drhafa1eca2020-03-09 18:26:11 +0000710 StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
drh9fecc542013-08-27 20:16:48 +0000711 int iChng = sqlite3_value_int(argv[1]);
danf00e9022013-08-14 19:54:12 +0000712
drh4f991892013-10-11 15:05:05 +0000713 UNUSED_PARAMETER( argc );
714 UNUSED_PARAMETER( context );
drhec9e55d2014-06-30 17:07:39 +0000715 assert( p->nCol>0 );
danf00e9022013-08-14 19:54:12 +0000716 assert( iChng<p->nCol );
717
drh9fecc542013-08-27 20:16:48 +0000718 if( p->nRow==0 ){
danb49d1042013-09-02 18:58:11 +0000719 /* This is the first call to this function. Do initialization. */
drh9fecc542013-08-27 20:16:48 +0000720 for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
721 }else{
722 /* Second and subsequent calls get processed here */
drhafa1eca2020-03-09 18:26:11 +0000723#ifdef SQLITE_ENABLE_STAT4
drh9d33d9e2020-03-10 01:24:13 +0000724 if( p->mxSample ) samplePushPrevious(p, iChng);
drhafa1eca2020-03-09 18:26:11 +0000725#endif
danf00e9022013-08-14 19:54:12 +0000726
727 /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
728 ** to the current row of the index. */
729 for(i=0; i<iChng; i++){
730 p->current.anEq[i]++;
731 }
732 for(i=iChng; i<p->nCol; i++){
733 p->current.anDLt[i]++;
drh175b8f02019-08-08 15:24:17 +0000734#ifdef SQLITE_ENABLE_STAT4
drh9d33d9e2020-03-10 01:24:13 +0000735 if( p->mxSample ) p->current.anLt[i] += p->current.anEq[i];
drh9fecc542013-08-27 20:16:48 +0000736#endif
danf00e9022013-08-14 19:54:12 +0000737 p->current.anEq[i] = 1;
738 }
danf00e9022013-08-14 19:54:12 +0000739 }
drh59a8cb72020-03-18 14:43:05 +0000740
drh9fecc542013-08-27 20:16:48 +0000741 p->nRow++;
drh175b8f02019-08-08 15:24:17 +0000742#ifdef SQLITE_ENABLE_STAT4
drh9d33d9e2020-03-10 01:24:13 +0000743 if( p->mxSample ){
744 tRowcnt nLt;
745 if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
746 sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
747 }else{
748 sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
749 sqlite3_value_blob(argv[2]));
750 }
751 p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
danf00e9022013-08-14 19:54:12 +0000752
drh9d33d9e2020-03-10 01:24:13 +0000753 nLt = p->current.anLt[p->nCol-1];
danf00e9022013-08-14 19:54:12 +0000754 /* Check if this is to be a periodic sample. If so, add it. */
755 if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
756 p->current.isPSample = 1;
757 p->current.iCol = 0;
758 sampleInsert(p, &p->current, p->nCol-1);
759 p->current.isPSample = 0;
760 }
761
762 /* Update the aBest[] array. */
763 for(i=0; i<(p->nCol-1); i++){
764 p->current.iCol = i;
danb13af4c2013-09-03 14:43:12 +0000765 if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
danf00e9022013-08-14 19:54:12 +0000766 sampleCopy(p, &p->aBest[i], &p->current);
767 }
768 }
drh59a8cb72020-03-18 14:43:05 +0000769 }else
770#endif
drh3d42fb72020-05-04 19:52:00 +0000771 if( p->nLimit && p->nRow>(tRowcnt)p->nLimit*(p->nSkipAhead+1) ){
drh59a8cb72020-03-18 14:43:05 +0000772 p->nSkipAhead++;
773 sqlite3_result_int(context, p->current.anDLt[0]>0);
danf00e9022013-08-14 19:54:12 +0000774 }
775}
drh59a8cb72020-03-18 14:43:05 +0000776
danf00e9022013-08-14 19:54:12 +0000777static const FuncDef statPushFuncdef = {
drh175b8f02019-08-08 15:24:17 +0000778 2+IsStat4, /* nArg */
drhd36e1042013-09-06 13:10:12 +0000779 SQLITE_UTF8, /* funcFlags */
danf00e9022013-08-14 19:54:12 +0000780 0, /* pUserData */
781 0, /* pNext */
drh2d801512016-01-14 22:19:58 +0000782 statPush, /* xSFunc */
danf00e9022013-08-14 19:54:12 +0000783 0, /* xFinalize */
dan980cf252018-06-10 07:42:35 +0000784 0, 0, /* xValue, xInverse */
danf00e9022013-08-14 19:54:12 +0000785 "stat_push", /* zName */
drh80738d92016-02-15 00:34:16 +0000786 {0}
drhade3add2011-08-13 00:58:05 +0000787};
788
danf00e9022013-08-14 19:54:12 +0000789#define STAT_GET_STAT1 0 /* "stat" column of stat1 table */
790#define STAT_GET_ROWID 1 /* "rowid" column of stat[34] entry */
791#define STAT_GET_NEQ 2 /* "neq" column of stat[34] entry */
792#define STAT_GET_NLT 3 /* "nlt" column of stat[34] entry */
793#define STAT_GET_NDLT 4 /* "ndlt" column of stat[34] entry */
794
drhade3add2011-08-13 00:58:05 +0000795/*
drh92707ac2013-08-17 18:57:15 +0000796** Implementation of the stat_get(P,J) SQL function. This routine is
drh553818a2014-07-23 18:36:55 +0000797** used to query statistical information that has been gathered into
drhafa1eca2020-03-09 18:26:11 +0000798** the StatAccum object by prior calls to stat_push(). The P parameter
799** has type BLOB but it is really just a pointer to the StatAccum object.
drh553818a2014-07-23 18:36:55 +0000800** The content to returned is determined by the parameter J
drh92707ac2013-08-17 18:57:15 +0000801** which is one of the STAT_GET_xxxx values defined above.
drhade3add2011-08-13 00:58:05 +0000802**
drh35497fc2017-02-01 01:34:15 +0000803** The stat_get(P,J) function is not available to generic SQL. It is
804** inserted as part of a manually constructed bytecode program. (See
805** the callStatGet() routine below.) It is guaranteed that the P
drhafa1eca2020-03-09 18:26:11 +0000806** parameter will always be a pointer to a StatAccum object, never a
drh35497fc2017-02-01 01:34:15 +0000807** NULL.
808**
drh175b8f02019-08-08 15:24:17 +0000809** If STAT4 is not enabled, then J is always
drh92707ac2013-08-17 18:57:15 +0000810** STAT_GET_STAT1 and is hence omitted and this routine becomes
811** a one-parameter function, stat_get(P), that always returns the
812** stat1 table entry information.
drhade3add2011-08-13 00:58:05 +0000813*/
danf00e9022013-08-14 19:54:12 +0000814static void statGet(
drhade3add2011-08-13 00:58:05 +0000815 sqlite3_context *context,
816 int argc,
817 sqlite3_value **argv
818){
drhafa1eca2020-03-09 18:26:11 +0000819 StatAccum *p = (StatAccum*)sqlite3_value_blob(argv[0]);
drh175b8f02019-08-08 15:24:17 +0000820#ifdef SQLITE_ENABLE_STAT4
821 /* STAT4 has a parameter on this routine. */
danf00e9022013-08-14 19:54:12 +0000822 int eCall = sqlite3_value_int(argv[1]);
drh92707ac2013-08-17 18:57:15 +0000823 assert( argc==2 );
danf00e9022013-08-14 19:54:12 +0000824 assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ
825 || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
826 || eCall==STAT_GET_NDLT
827 );
drh9d33d9e2020-03-10 01:24:13 +0000828 assert( eCall==STAT_GET_STAT1 || p->mxSample );
drh92707ac2013-08-17 18:57:15 +0000829 if( eCall==STAT_GET_STAT1 )
830#else
831 assert( argc==1 );
832#endif
833 {
danf00e9022013-08-14 19:54:12 +0000834 /* Return the value to store in the "stat" column of the sqlite_stat1
835 ** table for this index.
836 **
837 ** The value is a string composed of a list of integers describing
838 ** the index. The first integer in the list is the total number of
839 ** entries in the index. There is one additional integer in the list
840 ** for each indexed column. This additional integer is an estimate of
drhafa1eca2020-03-09 18:26:11 +0000841 ** the number of rows matched by a equality query on the index using
danf00e9022013-08-14 19:54:12 +0000842 ** a key with the corresponding number of fields. In other words,
843 ** if the index is on columns (a,b) and the sqlite_stat1 value is
844 ** "100 10 2", then SQLite estimates that:
845 **
846 ** * the index contains 100 rows,
847 ** * "WHERE a=?" matches 10 rows, and
848 ** * "WHERE a=? AND b=?" matches 2 rows.
849 **
850 ** If D is the count of distinct values and K is the total number of
851 ** rows, then each estimate is computed as:
852 **
853 ** I = (K+D-1)/D
854 */
855 char *z;
856 int i;
857
drhec9e55d2014-06-30 17:07:39 +0000858 char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
danf00e9022013-08-14 19:54:12 +0000859 if( zRet==0 ){
860 sqlite3_result_error_nomem(context);
861 return;
862 }
863
drh59a8cb72020-03-18 14:43:05 +0000864 sqlite3_snprintf(24, zRet, "%llu",
865 p->nSkipAhead ? (u64)p->nEst : (u64)p->nRow);
danf00e9022013-08-14 19:54:12 +0000866 z = zRet + sqlite3Strlen30(zRet);
drhec9e55d2014-06-30 17:07:39 +0000867 for(i=0; i<p->nKeyCol; i++){
drh26586e72013-10-09 19:07:22 +0000868 u64 nDistinct = p->current.anDLt[i] + 1;
869 u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
870 sqlite3_snprintf(24, z, " %llu", iVal);
danf00e9022013-08-14 19:54:12 +0000871 z += sqlite3Strlen30(z);
872 assert( p->current.anEq[i] );
873 }
874 assert( z[0]=='\0' && z>zRet );
875
876 sqlite3_result_text(context, zRet, -1, sqlite3_free);
drh92707ac2013-08-17 18:57:15 +0000877 }
drh175b8f02019-08-08 15:24:17 +0000878#ifdef SQLITE_ENABLE_STAT4
drh92707ac2013-08-17 18:57:15 +0000879 else if( eCall==STAT_GET_ROWID ){
danf00e9022013-08-14 19:54:12 +0000880 if( p->iGet<0 ){
881 samplePushPrevious(p, 0);
882 p->iGet = 0;
883 }
884 if( p->iGet<p->nSample ){
drhafa1eca2020-03-09 18:26:11 +0000885 StatSample *pS = p->a + p->iGet;
drhebe25af2013-11-02 18:46:04 +0000886 if( pS->nRowid==0 ){
drhda475b82013-11-04 21:44:54 +0000887 sqlite3_result_int64(context, pS->u.iRowid);
drhebe25af2013-11-02 18:46:04 +0000888 }else{
drhda475b82013-11-04 21:44:54 +0000889 sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
890 SQLITE_TRANSIENT);
drhebe25af2013-11-02 18:46:04 +0000891 }
danf00e9022013-08-14 19:54:12 +0000892 }
893 }else{
danf52bb8d2013-08-03 20:24:58 +0000894 tRowcnt *aCnt = 0;
danf00e9022013-08-14 19:54:12 +0000895
896 assert( p->iGet<p->nSample );
897 switch( eCall ){
898 case STAT_GET_NEQ: aCnt = p->a[p->iGet].anEq; break;
899 case STAT_GET_NLT: aCnt = p->a[p->iGet].anLt; break;
900 default: {
901 aCnt = p->a[p->iGet].anDLt;
902 p->iGet++;
903 break;
904 }
danf52bb8d2013-08-03 20:24:58 +0000905 }
906
drh175b8f02019-08-08 15:24:17 +0000907 {
danf00e9022013-08-14 19:54:12 +0000908 char *zRet = sqlite3MallocZero(p->nCol * 25);
dan8ad169a2013-08-12 20:14:04 +0000909 if( zRet==0 ){
910 sqlite3_result_error_nomem(context);
911 }else{
912 int i;
913 char *z = zRet;
914 for(i=0; i<p->nCol; i++){
drh26586e72013-10-09 19:07:22 +0000915 sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
dan8ad169a2013-08-12 20:14:04 +0000916 z += sqlite3Strlen30(z);
917 }
918 assert( z[0]=='\0' && z>zRet );
919 z[-1] = '\0';
920 sqlite3_result_text(context, zRet, -1, sqlite3_free);
danf52bb8d2013-08-03 20:24:58 +0000921 }
danf52bb8d2013-08-03 20:24:58 +0000922 }
drhade3add2011-08-13 00:58:05 +0000923 }
drh175b8f02019-08-08 15:24:17 +0000924#endif /* SQLITE_ENABLE_STAT4 */
drh4f991892013-10-11 15:05:05 +0000925#ifndef SQLITE_DEBUG
926 UNUSED_PARAMETER( argc );
927#endif
drhade3add2011-08-13 00:58:05 +0000928}
danf00e9022013-08-14 19:54:12 +0000929static const FuncDef statGetFuncdef = {
drh175b8f02019-08-08 15:24:17 +0000930 1+IsStat4, /* nArg */
drhd36e1042013-09-06 13:10:12 +0000931 SQLITE_UTF8, /* funcFlags */
danf00e9022013-08-14 19:54:12 +0000932 0, /* pUserData */
933 0, /* pNext */
drh2d801512016-01-14 22:19:58 +0000934 statGet, /* xSFunc */
danf00e9022013-08-14 19:54:12 +0000935 0, /* xFinalize */
dan980cf252018-06-10 07:42:35 +0000936 0, 0, /* xValue, xInverse */
danf00e9022013-08-14 19:54:12 +0000937 "stat_get", /* zName */
drh80738d92016-02-15 00:34:16 +0000938 {0}
drhade3add2011-08-13 00:58:05 +0000939};
drhade3add2011-08-13 00:58:05 +0000940
drh9f274632020-03-17 17:11:23 +0000941static void callStatGet(Parse *pParse, int regStat, int iParam, int regOut){
drh175b8f02019-08-08 15:24:17 +0000942#ifdef SQLITE_ENABLE_STAT4
drh9f274632020-03-17 17:11:23 +0000943 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Integer, iParam, regStat+1);
drh4f991892013-10-11 15:05:05 +0000944#elif SQLITE_DEBUG
drh92707ac2013-08-17 18:57:15 +0000945 assert( iParam==STAT_GET_STAT1 );
drh4f991892013-10-11 15:05:05 +0000946#else
947 UNUSED_PARAMETER( iParam );
drh92707ac2013-08-17 18:57:15 +0000948#endif
drh9f274632020-03-17 17:11:23 +0000949 assert( regOut!=regStat && regOut!=regStat+1 );
950 sqlite3VdbeAddFunctionCall(pParse, 0, regStat, regOut, 1+IsStat4,
drh920cf592019-10-30 16:29:02 +0000951 &statGetFuncdef, 0);
danf00e9022013-08-14 19:54:12 +0000952}
drhade3add2011-08-13 00:58:05 +0000953
drhe557b012020-05-30 00:30:08 +0000954#ifdef SQLITE_ENABLE_EXPLAIN_COMMENTS
955/* Add a comment to the most recent VDBE opcode that is the name
956** of the k-th column of the pIdx index.
957*/
958static void analyzeVdbeCommentIndexWithColumnName(
959 Vdbe *v, /* Prepared statement under construction */
960 Index *pIdx, /* Index whose column is being loaded */
961 int k /* Which column index */
962){
963 int i; /* Index of column in the table */
964 assert( k>=0 && k<pIdx->nColumn );
965 i = pIdx->aiColumn[k];
966 if( NEVER(i==XN_ROWID) ){
967 VdbeComment((v,"%s.rowid",pIdx->zName));
968 }else if( i==XN_EXPR ){
969 VdbeComment((v,"%s.expr(%d)",pIdx->zName, k));
970 }else{
971 VdbeComment((v,"%s.%s", pIdx->zName, pIdx->pTable->aCol[i].zName));
972 }
973}
974#else
975# define analyzeVdbeCommentIndexWithColumnName(a,b,c)
976#endif /* SQLITE_DEBUG */
977
drhade3add2011-08-13 00:58:05 +0000978/*
drhff2d5ea2005-07-23 00:41:48 +0000979** Generate code to do an analysis of all indices associated with
980** a single table.
981*/
982static void analyzeOneTable(
983 Parse *pParse, /* Parser context */
984 Table *pTab, /* Table whose indices are to be analyzed */
drha071bc52011-03-31 02:03:28 +0000985 Index *pOnlyIdx, /* If not NULL, only analyze this one index */
drhdfe88ec2008-11-03 20:55:06 +0000986 int iStatCur, /* Index of VdbeCursor that writes the sqlite_stat1 table */
danc6129702013-08-05 19:04:07 +0000987 int iMem, /* Available memory locations begin here */
drh4a54bb52017-02-18 15:58:52 +0000988 int iTab /* Next available cursor */
drhff2d5ea2005-07-23 00:41:48 +0000989){
dan0f9a34e2009-08-19 16:34:31 +0000990 sqlite3 *db = pParse->db; /* Database handle */
dan69188d92009-08-19 08:18:32 +0000991 Index *pIdx; /* An index to being analyzed */
992 int iIdxCur; /* Cursor open on index being analyzed */
danc6129702013-08-05 19:04:07 +0000993 int iTabCur; /* Table cursor */
dan69188d92009-08-19 08:18:32 +0000994 Vdbe *v; /* The virtual machine being built up */
995 int i; /* Loop counter */
drhf6cf1ff2011-03-30 14:54:05 +0000996 int jZeroRows = -1; /* Jump from here if number of rows is zero */
dan69188d92009-08-19 08:18:32 +0000997 int iDb; /* Index of database containing pTab */
drh721dfcf2013-08-01 04:39:17 +0000998 u8 needTableCnt = 1; /* True to count the table */
danf00e9022013-08-14 19:54:12 +0000999 int regNewRowid = iMem++; /* Rowid for the inserted record */
drh9f274632020-03-17 17:11:23 +00001000 int regStat = iMem++; /* Register to hold StatAccum object */
danf00e9022013-08-14 19:54:12 +00001001 int regChng = iMem++; /* Index of changed index field */
drh9fecc542013-08-27 20:16:48 +00001002 int regRowid = iMem++; /* Rowid argument passed to stat_push() */
danf00e9022013-08-14 19:54:12 +00001003 int regTemp = iMem++; /* Temporary use register */
drh49a76a82020-03-31 20:57:06 +00001004 int regTemp2 = iMem++; /* Second temporary use register */
dane275dc32009-08-18 16:24:58 +00001005 int regTabname = iMem++; /* Register containing table name */
1006 int regIdxname = iMem++; /* Register containing index name */
danf00e9022013-08-14 19:54:12 +00001007 int regStat1 = iMem++; /* Value for the stat column of sqlite_stat1 */
1008 int regPrev = iMem; /* MUST BE LAST (see below) */
dan614efe22018-01-12 16:44:29 +00001009#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1010 Table *pStat1 = 0;
1011#endif
dan68c4dbb2009-08-20 09:11:06 +00001012
drhf0459fc2013-08-15 16:15:00 +00001013 pParse->nMem = MAX(pParse->nMem, iMem);
drhff2d5ea2005-07-23 00:41:48 +00001014 v = sqlite3GetVdbe(pParse);
drh15564052010-09-25 22:32:56 +00001015 if( v==0 || NEVER(pTab==0) ){
1016 return;
1017 }
drhf39d29c2010-09-28 17:34:46 +00001018 if( pTab->tnum==0 ){
1019 /* Do not gather statistics on views or virtual tables */
drh15564052010-09-25 22:32:56 +00001020 return;
1021 }
drhcedfecf2018-03-23 12:59:10 +00001022 if( sqlite3_strlike("sqlite\\_%", pTab->zName, '\\')==0 ){
drh15564052010-09-25 22:32:56 +00001023 /* Do not gather statistics on system tables */
drhff2d5ea2005-07-23 00:41:48 +00001024 return;
1025 }
dan0f9a34e2009-08-19 16:34:31 +00001026 assert( sqlite3BtreeHoldsAllMutexes(db) );
1027 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977da184232006-01-05 11:34:32 +00001028 assert( iDb>=0 );
drh21206082011-04-04 18:22:02 +00001029 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drhe6e04962005-07-23 02:17:03 +00001030#ifndef SQLITE_OMIT_AUTHORIZATION
1031 if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
drh69c33822016-08-18 14:33:11 +00001032 db->aDb[iDb].zDbSName ) ){
drhe6e04962005-07-23 02:17:03 +00001033 return;
1034 }
1035#endif
1036
dan614efe22018-01-12 16:44:29 +00001037#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1038 if( db->xPreUpdateCallback ){
1039 pStat1 = (Table*)sqlite3DbMallocZero(db, sizeof(Table) + 13);
1040 if( pStat1==0 ) return;
1041 pStat1->zName = (char*)&pStat1[1];
1042 memcpy(pStat1->zName, "sqlite_stat1", 13);
1043 pStat1->nCol = 3;
1044 pStat1->iPKey = -1;
1045 sqlite3VdbeAddOp4(pParse->pVdbe, OP_Noop, 0, 0, 0,(char*)pStat1,P4_DYNBLOB);
1046 }
1047#endif
1048
dane0432012013-08-05 18:00:56 +00001049 /* Establish a read-lock on the table at the shared-cache level.
danf00e9022013-08-14 19:54:12 +00001050 ** Open a read-only cursor on the table. Also allocate a cursor number
1051 ** to use for scanning indexes (iIdxCur). No index cursor is opened at
1052 ** this time though. */
danielk1977c00da102006-01-07 13:21:04 +00001053 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danc6129702013-08-05 19:04:07 +00001054 iTabCur = iTab++;
danf00e9022013-08-14 19:54:12 +00001055 iIdxCur = iTab++;
danc6129702013-08-05 19:04:07 +00001056 pParse->nTab = MAX(pParse->nTab, iTab);
dane0432012013-08-05 18:00:56 +00001057 sqlite3OpenTable(pParse, iTabCur, iDb, pTab, OP_OpenRead);
drh076e85f2015-09-03 13:46:12 +00001058 sqlite3VdbeLoadString(v, regTabname, pTab->zName);
dane0432012013-08-05 18:00:56 +00001059
drhff2d5ea2005-07-23 00:41:48 +00001060 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
drh553818a2014-07-23 18:36:55 +00001061 int nCol; /* Number of columns in pIdx. "N" */
danf00e9022013-08-14 19:54:12 +00001062 int addrRewind; /* Address of "OP_Rewind iIdxCur" */
danf00e9022013-08-14 19:54:12 +00001063 int addrNextRow; /* Address of "next_row:" */
drhce95d112013-11-02 19:34:38 +00001064 const char *zIdxName; /* Name of the index */
drh553818a2014-07-23 18:36:55 +00001065 int nColTest; /* Number of columns to test for changes */
danielk1977b3bf5562006-01-10 17:58:23 +00001066
drha071bc52011-03-31 02:03:28 +00001067 if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
drh721dfcf2013-08-01 04:39:17 +00001068 if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
drhec9e55d2014-06-30 17:07:39 +00001069 if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
1070 nCol = pIdx->nKeyCol;
1071 zIdxName = pTab->zName;
drh553818a2014-07-23 18:36:55 +00001072 nColTest = nCol - 1;
drhec9e55d2014-06-30 17:07:39 +00001073 }else{
1074 nCol = pIdx->nColumn;
1075 zIdxName = pIdx->zName;
drh6861b8a2014-07-23 19:37:21 +00001076 nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
drhec9e55d2014-06-30 17:07:39 +00001077 }
dane275dc32009-08-18 16:24:58 +00001078
drh15564052010-09-25 22:32:56 +00001079 /* Populate the register containing the index name. */
drh076e85f2015-09-03 13:46:12 +00001080 sqlite3VdbeLoadString(v, regIdxname, zIdxName);
drhec9e55d2014-06-30 17:07:39 +00001081 VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
dan69188d92009-08-19 08:18:32 +00001082
dane0432012013-08-05 18:00:56 +00001083 /*
danf00e9022013-08-14 19:54:12 +00001084 ** Pseudo-code for loop that calls stat_push():
dane0432012013-08-05 18:00:56 +00001085 **
danf00e9022013-08-14 19:54:12 +00001086 ** Rewind csr
1087 ** if eof(csr) goto end_of_scan;
1088 ** regChng = 0
1089 ** goto chng_addr_0;
dane0432012013-08-05 18:00:56 +00001090 **
dandd6e1f12013-08-10 19:08:30 +00001091 ** next_row:
danf00e9022013-08-14 19:54:12 +00001092 ** regChng = 0
1093 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
1094 ** regChng = 1
1095 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
1096 ** ...
1097 ** regChng = N
1098 ** goto chng_addr_N
dane0432012013-08-05 18:00:56 +00001099 **
danf00e9022013-08-14 19:54:12 +00001100 ** chng_addr_0:
1101 ** regPrev(0) = idx(0)
1102 ** chng_addr_1:
1103 ** regPrev(1) = idx(1)
1104 ** ...
dane0432012013-08-05 18:00:56 +00001105 **
drh9d793322014-07-24 19:54:20 +00001106 ** endDistinctTest:
danf00e9022013-08-14 19:54:12 +00001107 ** regRowid = idx(rowid)
drh9fecc542013-08-27 20:16:48 +00001108 ** stat_push(P, regChng, regRowid)
danf00e9022013-08-14 19:54:12 +00001109 ** Next csr
1110 ** if !eof(csr) goto next_row;
dane0432012013-08-05 18:00:56 +00001111 **
danf00e9022013-08-14 19:54:12 +00001112 ** end_of_scan:
dane0432012013-08-05 18:00:56 +00001113 */
danf00e9022013-08-14 19:54:12 +00001114
1115 /* Make sure there are enough memory cells allocated to accommodate
1116 ** the regPrev array and a trailing rowid (the rowid slot is required
1117 ** when building a record to insert into the sample column of
1118 ** the sqlite_stat4 table. */
drh553818a2014-07-23 18:36:55 +00001119 pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
dan02fa4692009-08-17 17:06:58 +00001120
danf00e9022013-08-14 19:54:12 +00001121 /* Open a read-only cursor on the index being analyzed. */
dane0432012013-08-05 18:00:56 +00001122 assert( iDb==sqlite3SchemaToIndex(db, pIdx->pSchema) );
danf00e9022013-08-14 19:54:12 +00001123 sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, iDb);
drh2ec2fb22013-11-06 19:59:23 +00001124 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danf00e9022013-08-14 19:54:12 +00001125 VdbeComment((v, "%s", pIdx->zName));
dane0432012013-08-05 18:00:56 +00001126
danf00e9022013-08-14 19:54:12 +00001127 /* Invoke the stat_init() function. The arguments are:
danf52bb8d2013-08-03 20:24:58 +00001128 **
drh553818a2014-07-23 18:36:55 +00001129 ** (1) the number of columns in the index including the rowid
1130 ** (or for a WITHOUT ROWID table, the number of PK columns),
1131 ** (2) the number of columns in the key without the rowid/pk
drh9f274632020-03-17 17:11:23 +00001132 ** (3) estimated number of rows in the index,
danf52bb8d2013-08-03 20:24:58 +00001133 */
drh9f274632020-03-17 17:11:23 +00001134 sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat+1);
1135 assert( regRowid==regStat+2 );
1136 sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regRowid);
drh175b8f02019-08-08 15:24:17 +00001137#ifdef SQLITE_ENABLE_STAT4
drh9d33d9e2020-03-10 01:24:13 +00001138 if( OptimizationEnabled(db, SQLITE_Stat4) ){
drh9f274632020-03-17 17:11:23 +00001139 sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regTemp);
1140 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
1141 VdbeCoverage(v);
1142 }else
drh9fecc542013-08-27 20:16:48 +00001143#endif
drh9f274632020-03-17 17:11:23 +00001144 {
1145 addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
1146 VdbeCoverage(v);
1147 sqlite3VdbeAddOp3(v, OP_Count, iIdxCur, regTemp, 1);
1148 }
drh49a76a82020-03-31 20:57:06 +00001149 assert( regTemp2==regStat+4 );
1150 sqlite3VdbeAddOp2(v, OP_Integer, db->nAnalysisLimit, regTemp2);
1151 sqlite3VdbeAddFunctionCall(pParse, 0, regStat+1, regStat, 4,
drh920cf592019-10-30 16:29:02 +00001152 &statInitFuncdef, 0);
danf52bb8d2013-08-03 20:24:58 +00001153
danf00e9022013-08-14 19:54:12 +00001154 /* Implementation of the following:
1155 **
1156 ** Rewind csr
1157 ** if eof(csr) goto end_of_scan;
1158 ** regChng = 0
1159 ** goto next_push_0;
1160 **
dandd6e1f12013-08-10 19:08:30 +00001161 */
danf00e9022013-08-14 19:54:12 +00001162 sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
danf00e9022013-08-14 19:54:12 +00001163 addrNextRow = sqlite3VdbeCurrentAddr(v);
dane0432012013-08-05 18:00:56 +00001164
drh553818a2014-07-23 18:36:55 +00001165 if( nColTest>0 ){
drhec4ccdb2018-12-29 02:26:59 +00001166 int endDistinctTest = sqlite3VdbeMakeLabel(pParse);
drhb12879f2014-07-24 20:25:16 +00001167 int *aGotoChng; /* Array of jump instruction addresses */
drh575fad62016-02-05 13:38:36 +00001168 aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
drhb12879f2014-07-24 20:25:16 +00001169 if( aGotoChng==0 ) continue;
danf00e9022013-08-14 19:54:12 +00001170
drh553818a2014-07-23 18:36:55 +00001171 /*
1172 ** next_row:
1173 ** regChng = 0
1174 ** if( idx(0) != regPrev(0) ) goto chng_addr_0
1175 ** regChng = 1
1176 ** if( idx(1) != regPrev(1) ) goto chng_addr_1
1177 ** ...
1178 ** regChng = N
drh9d793322014-07-24 19:54:20 +00001179 ** goto endDistinctTest
drh553818a2014-07-23 18:36:55 +00001180 */
1181 sqlite3VdbeAddOp0(v, OP_Goto);
1182 addrNextRow = sqlite3VdbeCurrentAddr(v);
drh5f1d1d92014-07-31 22:59:04 +00001183 if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
drh9d793322014-07-24 19:54:20 +00001184 /* For a single-column UNIQUE index, once we have found a non-NULL
1185 ** row, we know that all the rest will be distinct, so skip
1186 ** subsequent distinctness tests. */
1187 sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
1188 VdbeCoverage(v);
1189 }
drh553818a2014-07-23 18:36:55 +00001190 for(i=0; i<nColTest; i++){
1191 char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
1192 sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
1193 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
drhe557b012020-05-30 00:30:08 +00001194 analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
drh553818a2014-07-23 18:36:55 +00001195 aGotoChng[i] =
1196 sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
1197 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
1198 VdbeCoverage(v);
1199 }
1200 sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
drh076e85f2015-09-03 13:46:12 +00001201 sqlite3VdbeGoto(v, endDistinctTest);
drh553818a2014-07-23 18:36:55 +00001202
1203
1204 /*
1205 ** chng_addr_0:
1206 ** regPrev(0) = idx(0)
1207 ** chng_addr_1:
1208 ** regPrev(1) = idx(1)
1209 ** ...
1210 */
1211 sqlite3VdbeJumpHere(v, addrNextRow-1);
1212 for(i=0; i<nColTest; i++){
1213 sqlite3VdbeJumpHere(v, aGotoChng[i]);
1214 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
drhe557b012020-05-30 00:30:08 +00001215 analyzeVdbeCommentIndexWithColumnName(v,pIdx,i);
drh553818a2014-07-23 18:36:55 +00001216 }
drh9d793322014-07-24 19:54:20 +00001217 sqlite3VdbeResolveLabel(v, endDistinctTest);
drhb12879f2014-07-24 20:25:16 +00001218 sqlite3DbFree(db, aGotoChng);
drhff2d5ea2005-07-23 00:41:48 +00001219 }
drh553818a2014-07-23 18:36:55 +00001220
danf00e9022013-08-14 19:54:12 +00001221 /*
1222 ** chng_addr_N:
drh175b8f02019-08-08 15:24:17 +00001223 ** regRowid = idx(rowid) // STAT4 only
1224 ** stat_push(P, regChng, regRowid) // 3rd parameter STAT4 only
danf00e9022013-08-14 19:54:12 +00001225 ** Next csr
1226 ** if !eof(csr) goto next_row;
1227 */
drh175b8f02019-08-08 15:24:17 +00001228#ifdef SQLITE_ENABLE_STAT4
drh9d33d9e2020-03-10 01:24:13 +00001229 if( OptimizationEnabled(db, SQLITE_Stat4) ){
drh9f274632020-03-17 17:11:23 +00001230 assert( regRowid==(regStat+2) );
drh9d33d9e2020-03-10 01:24:13 +00001231 if( HasRowid(pTab) ){
1232 sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
1233 }else{
1234 Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1235 int j, k, regKey;
1236 regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1237 for(j=0; j<pPk->nKeyCol; j++){
1238 k = sqlite3TableColumnToIndex(pIdx, pPk->aiColumn[j]);
1239 assert( k>=0 && k<pIdx->nColumn );
1240 sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
drhe557b012020-05-30 00:30:08 +00001241 analyzeVdbeCommentIndexWithColumnName(v,pIdx,k);
drh9d33d9e2020-03-10 01:24:13 +00001242 }
1243 sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
1244 sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
drhebe25af2013-11-02 18:46:04 +00001245 }
drhebe25af2013-11-02 18:46:04 +00001246 }
drh9fecc542013-08-27 20:16:48 +00001247#endif
drh9f274632020-03-17 17:11:23 +00001248 assert( regChng==(regStat+1) );
drh59a8cb72020-03-18 14:43:05 +00001249 {
drh59a8cb72020-03-18 14:43:05 +00001250 sqlite3VdbeAddFunctionCall(pParse, 1, regStat, regTemp, 2+IsStat4,
1251 &statPushFuncdef, 0);
drh49a76a82020-03-31 20:57:06 +00001252 if( db->nAnalysisLimit ){
1253 int j1, j2, j3;
1254 j1 = sqlite3VdbeAddOp1(v, OP_IsNull, regTemp); VdbeCoverage(v);
1255 j2 = sqlite3VdbeAddOp1(v, OP_If, regTemp); VdbeCoverage(v);
1256 j3 = sqlite3VdbeAddOp4Int(v, OP_SeekGT, iIdxCur, 0, regPrev, 1);
drhf72981f2020-05-02 03:29:21 +00001257 VdbeCoverage(v);
drh49a76a82020-03-31 20:57:06 +00001258 sqlite3VdbeJumpHere(v, j1);
1259 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
1260 sqlite3VdbeJumpHere(v, j2);
1261 sqlite3VdbeJumpHere(v, j3);
1262 }else{
1263 sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
1264 }
drh59a8cb72020-03-18 14:43:05 +00001265 }
danf00e9022013-08-14 19:54:12 +00001266
1267 /* Add the entry to the stat1 table. */
drh9f274632020-03-17 17:11:23 +00001268 callStatGet(pParse, regStat, STAT_GET_STAT1, regStat1);
drh4583c372014-09-19 20:13:25 +00001269 assert( "BBB"[0]==SQLITE_AFF_TEXT );
1270 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
drhade3add2011-08-13 00:58:05 +00001271 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001272 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
dan614efe22018-01-12 16:44:29 +00001273#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1274 sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
1275#endif
drh2d401ab2008-01-10 23:50:11 +00001276 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
danf00e9022013-08-14 19:54:12 +00001277
drh175b8f02019-08-08 15:24:17 +00001278 /* Add the entries to the stat4 table. */
1279#ifdef SQLITE_ENABLE_STAT4
drh31e37442020-04-01 01:15:16 +00001280 if( OptimizationEnabled(db, SQLITE_Stat4) && db->nAnalysisLimit==0 ){
danf00e9022013-08-14 19:54:12 +00001281 int regEq = regStat1;
1282 int regLt = regStat1+1;
1283 int regDLt = regStat1+2;
1284 int regSample = regStat1+3;
1285 int regCol = regStat1+4;
1286 int regSampleRowid = regCol + nCol;
1287 int addrNext;
1288 int addrIsNull;
drhebe25af2013-11-02 18:46:04 +00001289 u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
danf00e9022013-08-14 19:54:12 +00001290
drhec9e55d2014-06-30 17:07:39 +00001291 pParse->nMem = MAX(pParse->nMem, regCol+nCol);
danf00e9022013-08-14 19:54:12 +00001292
1293 addrNext = sqlite3VdbeCurrentAddr(v);
drh9f274632020-03-17 17:11:23 +00001294 callStatGet(pParse, regStat, STAT_GET_ROWID, regSampleRowid);
danf00e9022013-08-14 19:54:12 +00001295 addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
drh688852a2014-02-17 22:40:43 +00001296 VdbeCoverage(v);
drh9f274632020-03-17 17:11:23 +00001297 callStatGet(pParse, regStat, STAT_GET_NEQ, regEq);
1298 callStatGet(pParse, regStat, STAT_GET_NLT, regLt);
1299 callStatGet(pParse, regStat, STAT_GET_NDLT, regDLt);
drhebe25af2013-11-02 18:46:04 +00001300 sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
drh6ccbd272018-07-10 17:10:44 +00001301 VdbeCoverage(v);
drhec9e55d2014-06-30 17:07:39 +00001302 for(i=0; i<nCol; i++){
drh1f9ca2c2015-08-25 16:57:52 +00001303 sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
danf00e9022013-08-14 19:54:12 +00001304 }
drhec9e55d2014-06-30 17:07:39 +00001305 sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
drh57bf4a82014-02-17 14:59:22 +00001306 sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
danf00e9022013-08-14 19:54:12 +00001307 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
1308 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
drhfe705102014-03-06 13:38:37 +00001309 sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
danf00e9022013-08-14 19:54:12 +00001310 sqlite3VdbeJumpHere(v, addrIsNull);
1311 }
drh175b8f02019-08-08 15:24:17 +00001312#endif /* SQLITE_ENABLE_STAT4 */
danf00e9022013-08-14 19:54:12 +00001313
drh9fecc542013-08-27 20:16:48 +00001314 /* End of analysis */
danf00e9022013-08-14 19:54:12 +00001315 sqlite3VdbeJumpHere(v, addrRewind);
drh15564052010-09-25 22:32:56 +00001316 }
1317
danf00e9022013-08-14 19:54:12 +00001318
drh721dfcf2013-08-01 04:39:17 +00001319 /* Create a single sqlite_stat1 entry containing NULL as the index
1320 ** name and the row count as the content.
drh15564052010-09-25 22:32:56 +00001321 */
drh721dfcf2013-08-01 04:39:17 +00001322 if( pOnlyIdx==0 && needTableCnt ){
drh15564052010-09-25 22:32:56 +00001323 VdbeComment((v, "%s", pTab->zName));
dane0432012013-08-05 18:00:56 +00001324 sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
drh688852a2014-02-17 22:40:43 +00001325 jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
drh721dfcf2013-08-01 04:39:17 +00001326 sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
drh4583c372014-09-19 20:13:25 +00001327 assert( "BBB"[0]==SQLITE_AFF_TEXT );
1328 sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
drh721dfcf2013-08-01 04:39:17 +00001329 sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
danf00e9022013-08-14 19:54:12 +00001330 sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
drh721dfcf2013-08-01 04:39:17 +00001331 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
dan3739f292018-01-17 20:57:20 +00001332#ifdef SQLITE_ENABLE_PREUPDATE_HOOK
1333 sqlite3VdbeChangeP4(v, -1, (char*)pStat1, P4_TABLE);
1334#endif
drh15564052010-09-25 22:32:56 +00001335 sqlite3VdbeJumpHere(v, jZeroRows);
1336 }
drhff2d5ea2005-07-23 00:41:48 +00001337}
1338
drh72052a72017-02-17 16:26:34 +00001339
1340/*
drh4a54bb52017-02-18 15:58:52 +00001341** Generate code that will cause the most recent index analysis to
1342** be loaded into internal hash tables where is can be used.
drh72052a72017-02-17 16:26:34 +00001343*/
drh4a54bb52017-02-18 15:58:52 +00001344static void loadAnalysis(Parse *pParse, int iDb){
drh182e84c2017-02-18 02:19:02 +00001345 Vdbe *v = sqlite3GetVdbe(pParse);
drh4a54bb52017-02-18 15:58:52 +00001346 if( v ){
1347 sqlite3VdbeAddOp1(v, OP_LoadAnalysis, iDb);
1348 }
1349}
drhff2d5ea2005-07-23 00:41:48 +00001350
drh4a54bb52017-02-18 15:58:52 +00001351/*
1352** Generate code that will do an analysis of an entire database
1353*/
1354static void analyzeDatabase(Parse *pParse, int iDb){
1355 sqlite3 *db = pParse->db;
1356 Schema *pSchema = db->aDb[iDb].pSchema; /* Schema of database iDb */
1357 HashElem *k;
1358 int iStatCur;
1359 int iMem;
1360 int iTab;
1361
1362 sqlite3BeginWriteOperation(pParse, 0, iDb);
1363 iStatCur = pParse->nTab;
1364 pParse->nTab += 3;
1365 openStatTable(pParse, iDb, iStatCur, 0, 0);
1366 iMem = pParse->nMem+1;
1367 iTab = pParse->nTab;
1368 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
1369 for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
1370 Table *pTab = (Table*)sqliteHashData(k);
1371 analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
drhff2d5ea2005-07-23 00:41:48 +00001372 }
drh4a54bb52017-02-18 15:58:52 +00001373 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001374}
1375
1376/*
1377** Generate code that will do an analysis of a single table in
drha071bc52011-03-31 02:03:28 +00001378** a database. If pOnlyIdx is not NULL then it is a single index
1379** in pTab that should be analyzed.
drhff2d5ea2005-07-23 00:41:48 +00001380*/
drha071bc52011-03-31 02:03:28 +00001381static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
drhff2d5ea2005-07-23 00:41:48 +00001382 int iDb;
1383 int iStatCur;
1384
1385 assert( pTab!=0 );
drh1fee73e2007-08-29 04:00:57 +00001386 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
danielk1977da184232006-01-05 11:34:32 +00001387 iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
drhff2d5ea2005-07-23 00:41:48 +00001388 sqlite3BeginWriteOperation(pParse, 0, iDb);
dan02fa4692009-08-17 17:06:58 +00001389 iStatCur = pParse->nTab;
drhade3add2011-08-13 00:58:05 +00001390 pParse->nTab += 3;
drha071bc52011-03-31 02:03:28 +00001391 if( pOnlyIdx ){
1392 openStatTable(pParse, iDb, iStatCur, pOnlyIdx->zName, "idx");
1393 }else{
1394 openStatTable(pParse, iDb, iStatCur, pTab->zName, "tbl");
1395 }
drh4a54bb52017-02-18 15:58:52 +00001396 analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
1397 loadAnalysis(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001398}
1399
1400/*
1401** Generate code for the ANALYZE command. The parser calls this routine
1402** when it recognizes an ANALYZE command.
drh9f18e8a2005-07-08 12:13:04 +00001403**
1404** ANALYZE -- 1
drhff2d5ea2005-07-23 00:41:48 +00001405** ANALYZE <database> -- 2
drh9f18e8a2005-07-08 12:13:04 +00001406** ANALYZE ?<database>.?<tablename> -- 3
1407**
1408** Form 1 causes all indices in all attached databases to be analyzed.
1409** Form 2 analyzes all indices the single database named.
1410** Form 3 analyzes all indices associated with the named table.
1411*/
drh182e84c2017-02-18 02:19:02 +00001412void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
drhff2d5ea2005-07-23 00:41:48 +00001413 sqlite3 *db = pParse->db;
1414 int iDb;
drh4a54bb52017-02-18 15:58:52 +00001415 int i;
drhff2d5ea2005-07-23 00:41:48 +00001416 char *z, *zDb;
1417 Table *pTab;
drha071bc52011-03-31 02:03:28 +00001418 Index *pIdx;
drhff2d5ea2005-07-23 00:41:48 +00001419 Token *pTableName;
drh4a54bb52017-02-18 15:58:52 +00001420 Vdbe *v;
drhff2d5ea2005-07-23 00:41:48 +00001421
1422 /* Read the database schema. If an error occurs, leave an error message
1423 ** and code in pParse and return NULL. */
drh1fee73e2007-08-29 04:00:57 +00001424 assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
drhff2d5ea2005-07-23 00:41:48 +00001425 if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
1426 return;
1427 }
1428
drh05800a12009-04-16 17:45:47 +00001429 assert( pName2!=0 || pName1==0 );
drhff2d5ea2005-07-23 00:41:48 +00001430 if( pName1==0 ){
1431 /* Form 1: Analyze everything */
drh4a54bb52017-02-18 15:58:52 +00001432 for(i=0; i<db->nDb; i++){
1433 if( i==1 ) continue; /* Do not analyze the TEMP database */
1434 analyzeDatabase(pParse, i);
1435 }
drhbce04142017-02-23 00:58:36 +00001436 }else if( pName2->n==0 && (iDb = sqlite3FindDb(db, pName1))>=0 ){
1437 /* Analyze the schema named as the argument */
1438 analyzeDatabase(pParse, iDb);
drhff2d5ea2005-07-23 00:41:48 +00001439 }else{
drhbce04142017-02-23 00:58:36 +00001440 /* Form 3: Analyze the table or index named as an argument */
drhff2d5ea2005-07-23 00:41:48 +00001441 iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
1442 if( iDb>=0 ){
drhbce04142017-02-23 00:58:36 +00001443 zDb = pName2->n ? db->aDb[iDb].zDbSName : 0;
drh17435752007-08-16 04:30:38 +00001444 z = sqlite3NameFromToken(db, pTableName);
drhcf1be452007-05-12 12:08:51 +00001445 if( z ){
drha071bc52011-03-31 02:03:28 +00001446 if( (pIdx = sqlite3FindIndex(db, z, zDb))!=0 ){
1447 analyzeTable(pParse, pIdx->pTable, pIdx);
1448 }else if( (pTab = sqlite3LocateTable(pParse, 0, z, zDb))!=0 ){
1449 analyzeTable(pParse, pTab, 0);
drhcf1be452007-05-12 12:08:51 +00001450 }
drha071bc52011-03-31 02:03:28 +00001451 sqlite3DbFree(db, z);
drhff2d5ea2005-07-23 00:41:48 +00001452 }
drhbce04142017-02-23 00:58:36 +00001453 }
drhff2d5ea2005-07-23 00:41:48 +00001454 }
drhbce04142017-02-23 00:58:36 +00001455 if( db->nSqlExec==0 && (v = sqlite3GetVdbe(pParse))!=0 ){
1456 sqlite3VdbeAddOp0(v, OP_Expire);
1457 }
drh9f18e8a2005-07-08 12:13:04 +00001458}
1459
drh497e4462005-07-23 03:18:40 +00001460/*
1461** Used to pass information from the analyzer reader through to the
1462** callback routine.
1463*/
1464typedef struct analysisInfo analysisInfo;
1465struct analysisInfo {
1466 sqlite3 *db;
1467 const char *zDatabase;
1468};
1469
1470/*
danf52bb8d2013-08-03 20:24:58 +00001471** The first argument points to a nul-terminated string containing a
1472** list of space separated integers. Read the first nOut of these into
1473** the array aOut[].
1474*/
1475static void decodeIntArray(
drhc28c4e52013-10-03 19:21:41 +00001476 char *zIntArray, /* String containing int array to decode */
1477 int nOut, /* Number of slots in aOut[] */
1478 tRowcnt *aOut, /* Store integers here */
dancfc9df72014-04-25 15:01:01 +00001479 LogEst *aLog, /* Or, if aOut==0, here */
drhc28c4e52013-10-03 19:21:41 +00001480 Index *pIndex /* Handle extra flags for this index, if not NULL */
danf52bb8d2013-08-03 20:24:58 +00001481){
1482 char *z = zIntArray;
1483 int c;
1484 int i;
1485 tRowcnt v;
drh1435a9a2013-08-27 23:15:44 +00001486
drh175b8f02019-08-08 15:24:17 +00001487#ifdef SQLITE_ENABLE_STAT4
drh6d57bbf2013-08-28 11:43:49 +00001488 if( z==0 ) z = "";
1489#else
drh85d117b2014-10-06 18:33:49 +00001490 assert( z!=0 );
drh6d57bbf2013-08-28 11:43:49 +00001491#endif
danf52bb8d2013-08-03 20:24:58 +00001492 for(i=0; *z && i<nOut; i++){
1493 v = 0;
1494 while( (c=z[0])>='0' && c<='9' ){
1495 v = v*10 + c - '0';
1496 z++;
1497 }
drh175b8f02019-08-08 15:24:17 +00001498#ifdef SQLITE_ENABLE_STAT4
drh85d117b2014-10-06 18:33:49 +00001499 if( aOut ) aOut[i] = v;
1500 if( aLog ) aLog[i] = sqlite3LogEst(v);
drhc5f246e2014-05-01 20:24:21 +00001501#else
1502 assert( aOut==0 );
1503 UNUSED_PARAMETER(aOut);
drh85d117b2014-10-06 18:33:49 +00001504 assert( aLog!=0 );
1505 aLog[i] = sqlite3LogEst(v);
drhc5f246e2014-05-01 20:24:21 +00001506#endif
danf52bb8d2013-08-03 20:24:58 +00001507 if( *z==' ' ) z++;
1508 }
drh175b8f02019-08-08 15:24:17 +00001509#ifndef SQLITE_ENABLE_STAT4
drh0da10d322014-11-22 21:37:00 +00001510 assert( pIndex!=0 ); {
drh1f1fc0c2013-10-08 23:16:48 +00001511#else
drh0da10d322014-11-22 21:37:00 +00001512 if( pIndex ){
drh1f1fc0c2013-10-08 23:16:48 +00001513#endif
drh0da10d322014-11-22 21:37:00 +00001514 pIndex->bUnordered = 0;
1515 pIndex->noSkipScan = 0;
1516 while( z[0] ){
1517 if( sqlite3_strglob("unordered*", z)==0 ){
1518 pIndex->bUnordered = 1;
1519 }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
drh725dd722019-08-15 14:35:45 +00001520 int sz = sqlite3Atoi(z+3);
1521 if( sz<2 ) sz = 2;
1522 pIndex->szIdxRow = sqlite3LogEst(sz);
drh0da10d322014-11-22 21:37:00 +00001523 }else if( sqlite3_strglob("noskipscan*", z)==0 ){
1524 pIndex->noSkipScan = 1;
1525 }
drhdbd94862014-07-23 23:57:42 +00001526#ifdef SQLITE_ENABLE_COSTMULT
drh0da10d322014-11-22 21:37:00 +00001527 else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
1528 pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
1529 }
drhdbd94862014-07-23 23:57:42 +00001530#endif
drh0da10d322014-11-22 21:37:00 +00001531 while( z[0]!=0 && z[0]!=' ' ) z++;
1532 while( z[0]==' ' ) z++;
1533 }
danf52bb8d2013-08-03 20:24:58 +00001534 }
1535}
1536
1537/*
drh497e4462005-07-23 03:18:40 +00001538** This callback is invoked once for each index when reading the
1539** sqlite_stat1 table.
1540**
drh15564052010-09-25 22:32:56 +00001541** argv[0] = name of the table
1542** argv[1] = name of the index (might be NULL)
1543** argv[2] = results of analysis - on integer for each column
1544**
1545** Entries for which argv[1]==NULL simply record the number of rows in
1546** the table.
drh497e4462005-07-23 03:18:40 +00001547*/
danielk197762c14b32008-11-19 09:05:26 +00001548static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
drh497e4462005-07-23 03:18:40 +00001549 analysisInfo *pInfo = (analysisInfo*)pData;
1550 Index *pIndex;
drh15564052010-09-25 22:32:56 +00001551 Table *pTable;
drh497e4462005-07-23 03:18:40 +00001552 const char *z;
1553
drh15564052010-09-25 22:32:56 +00001554 assert( argc==3 );
danielk1977f3d3c272008-11-19 16:52:44 +00001555 UNUSED_PARAMETER2(NotUsed, argc);
1556
drh15564052010-09-25 22:32:56 +00001557 if( argv==0 || argv[0]==0 || argv[2]==0 ){
drh497e4462005-07-23 03:18:40 +00001558 return 0;
1559 }
drh15564052010-09-25 22:32:56 +00001560 pTable = sqlite3FindTable(pInfo->db, argv[0], pInfo->zDatabase);
1561 if( pTable==0 ){
drh497e4462005-07-23 03:18:40 +00001562 return 0;
1563 }
drhc2b23e72013-11-13 15:32:15 +00001564 if( argv[1]==0 ){
drh15564052010-09-25 22:32:56 +00001565 pIndex = 0;
drhc2b23e72013-11-13 15:32:15 +00001566 }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
1567 pIndex = sqlite3PrimaryKeyIndex(pTable);
1568 }else{
1569 pIndex = sqlite3FindIndex(pInfo->db, argv[1], pInfo->zDatabase);
drh15564052010-09-25 22:32:56 +00001570 }
drh15564052010-09-25 22:32:56 +00001571 z = argv[2];
danf52bb8d2013-08-03 20:24:58 +00001572
1573 if( pIndex ){
dan4eed0532015-04-20 15:13:08 +00001574 tRowcnt *aiRowEst = 0;
dan43085d72014-10-03 19:16:53 +00001575 int nCol = pIndex->nKeyCol+1;
drh175b8f02019-08-08 15:24:17 +00001576#ifdef SQLITE_ENABLE_STAT4
dan4eed0532015-04-20 15:13:08 +00001577 /* Index.aiRowEst may already be set here if there are duplicate
1578 ** sqlite_stat1 entries for this index. In that case just clobber
1579 ** the old data with the new instead of allocating a new array. */
1580 if( pIndex->aiRowEst==0 ){
1581 pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
drh4a642b62016-02-05 01:55:27 +00001582 if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
dan4eed0532015-04-20 15:13:08 +00001583 }
1584 aiRowEst = pIndex->aiRowEst;
dan43085d72014-10-03 19:16:53 +00001585#endif
drh25df48d2014-07-22 14:58:12 +00001586 pIndex->bUnordered = 0;
dan43085d72014-10-03 19:16:53 +00001587 decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
drh33bec3f2017-02-17 13:38:15 +00001588 pIndex->hasStat1 = 1;
1589 if( pIndex->pPartIdxWhere==0 ){
1590 pTable->nRowLogEst = pIndex->aiRowLogEst[0];
1591 pTable->tabFlags |= TF_HasStat1;
1592 }
danf52bb8d2013-08-03 20:24:58 +00001593 }else{
drh52f6c912013-10-06 22:12:41 +00001594 Index fakeIdx;
1595 fakeIdx.szIdxRow = pTable->szTabRow;
drhdbd94862014-07-23 23:57:42 +00001596#ifdef SQLITE_ENABLE_COSTMULT
1597 fakeIdx.pTable = pTable;
1598#endif
dancfc9df72014-04-25 15:01:01 +00001599 decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
drh52f6c912013-10-06 22:12:41 +00001600 pTable->szTabRow = fakeIdx.szIdxRow;
drh33bec3f2017-02-17 13:38:15 +00001601 pTable->tabFlags |= TF_HasStat1;
drh497e4462005-07-23 03:18:40 +00001602 }
danf52bb8d2013-08-03 20:24:58 +00001603
drh497e4462005-07-23 03:18:40 +00001604 return 0;
1605}
1606
1607/*
dan85c165c2009-08-19 14:34:54 +00001608** If the Index.aSample variable is not NULL, delete the aSample[] array
1609** and its contents.
1610*/
dand46def72010-07-24 11:28:28 +00001611void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
drh175b8f02019-08-08 15:24:17 +00001612#ifdef SQLITE_ENABLE_STAT4
dan85c165c2009-08-19 14:34:54 +00001613 if( pIdx->aSample ){
1614 int j;
drhfaacf172011-08-12 01:51:45 +00001615 for(j=0; j<pIdx->nSample; j++){
dan85c165c2009-08-19 14:34:54 +00001616 IndexSample *p = &pIdx->aSample[j];
danf52bb8d2013-08-03 20:24:58 +00001617 sqlite3DbFree(db, p->p);
dan85c165c2009-08-19 14:34:54 +00001618 }
drh8e3937f2011-08-18 13:45:23 +00001619 sqlite3DbFree(db, pIdx->aSample);
dan85c165c2009-08-19 14:34:54 +00001620 }
drh8e3937f2011-08-18 13:45:23 +00001621 if( db && db->pnBytesFreed==0 ){
1622 pIdx->nSample = 0;
1623 pIdx->aSample = 0;
1624 }
shanecea72b22009-09-07 04:38:36 +00001625#else
drh43b18e12010-08-17 19:40:08 +00001626 UNUSED_PARAMETER(db);
shanecea72b22009-09-07 04:38:36 +00001627 UNUSED_PARAMETER(pIdx);
drh175b8f02019-08-08 15:24:17 +00001628#endif /* SQLITE_ENABLE_STAT4 */
dan85c165c2009-08-19 14:34:54 +00001629}
1630
drh175b8f02019-08-08 15:24:17 +00001631#ifdef SQLITE_ENABLE_STAT4
dan0adbed82013-08-15 19:56:32 +00001632/*
1633** Populate the pIdx->aAvgEq[] array based on the samples currently
1634** stored in pIdx->aSample[].
1635*/
1636static void initAvgEq(Index *pIdx){
1637 if( pIdx ){
1638 IndexSample *aSample = pIdx->aSample;
1639 IndexSample *pFinal = &aSample[pIdx->nSample-1];
1640 int iCol;
dan39caccf2014-07-01 11:54:02 +00001641 int nCol = 1;
1642 if( pIdx->nSampleCol>1 ){
1643 /* If this is stat4 data, then calculate aAvgEq[] values for all
1644 ** sample columns except the last. The last is always set to 1, as
1645 ** once the trailing PK fields are considered all index keys are
1646 ** unique. */
1647 nCol = pIdx->nSampleCol-1;
1648 pIdx->aAvgEq[nCol] = 1;
1649 }
1650 for(iCol=0; iCol<nCol; iCol++){
dan43085d72014-10-03 19:16:53 +00001651 int nSample = pIdx->nSample;
dan0adbed82013-08-15 19:56:32 +00001652 int i; /* Used to iterate through samples */
1653 tRowcnt sumEq = 0; /* Sum of the nEq values */
dan0adbed82013-08-15 19:56:32 +00001654 tRowcnt avgEq = 0;
dan43085d72014-10-03 19:16:53 +00001655 tRowcnt nRow; /* Number of rows in index */
1656 i64 nSum100 = 0; /* Number of terms contributing to sumEq */
1657 i64 nDist100; /* Number of distinct values in index */
1658
dan5cca94e2014-12-05 21:04:26 +00001659 if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
dan43085d72014-10-03 19:16:53 +00001660 nRow = pFinal->anLt[iCol];
1661 nDist100 = (i64)100 * pFinal->anDLt[iCol];
1662 nSample--;
1663 }else{
1664 nRow = pIdx->aiRowEst[0];
1665 nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
1666 }
drh9f07cf72014-10-22 15:27:05 +00001667 pIdx->nRowEst0 = nRow;
dan0adbed82013-08-15 19:56:32 +00001668
1669 /* Set nSum to the number of distinct (iCol+1) field prefixes that
dan43085d72014-10-03 19:16:53 +00001670 ** occur in the stat4 table for this index. Set sumEq to the sum of
1671 ** the nEq values for column iCol for the same set (adding the value
1672 ** only once where there exist duplicate prefixes). */
1673 for(i=0; i<nSample; i++){
1674 if( i==(pIdx->nSample-1)
1675 || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol]
1676 ){
dan0adbed82013-08-15 19:56:32 +00001677 sumEq += aSample[i].anEq[iCol];
dan43085d72014-10-03 19:16:53 +00001678 nSum100 += 100;
dan0adbed82013-08-15 19:56:32 +00001679 }
1680 }
dan43085d72014-10-03 19:16:53 +00001681
drh785d8ed2017-01-11 14:15:29 +00001682 if( nDist100>nSum100 && sumEq<nRow ){
dan43085d72014-10-03 19:16:53 +00001683 avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
dan0adbed82013-08-15 19:56:32 +00001684 }
1685 if( avgEq==0 ) avgEq = 1;
1686 pIdx->aAvgEq[iCol] = avgEq;
dan0adbed82013-08-15 19:56:32 +00001687 }
1688 }
1689}
1690
dan0106e372013-08-12 16:34:32 +00001691/*
drhce95d112013-11-02 19:34:38 +00001692** Look up an index by name. Or, if the name of a WITHOUT ROWID table
1693** is supplied instead, find the PRIMARY KEY index for that table.
1694*/
1695static Index *findIndexOrPrimaryKey(
1696 sqlite3 *db,
1697 const char *zName,
1698 const char *zDb
1699){
1700 Index *pIdx = sqlite3FindIndex(db, zName, zDb);
1701 if( pIdx==0 ){
1702 Table *pTab = sqlite3FindTable(db, zName, zDb);
1703 if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
1704 }
1705 return pIdx;
1706}
1707
1708/*
drh175b8f02019-08-08 15:24:17 +00001709** Load the content from either the sqlite_stat4
dan0106e372013-08-12 16:34:32 +00001710** into the relevant Index.aSample[] arrays.
1711**
1712** Arguments zSql1 and zSql2 must point to SQL statements that return
drh175b8f02019-08-08 15:24:17 +00001713** data equivalent to the following:
dan0106e372013-08-12 16:34:32 +00001714**
1715** zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1716** zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1717**
1718** where %Q is replaced with the database name before the SQL is executed.
1719*/
1720static int loadStatTbl(
1721 sqlite3 *db, /* Database handle */
dan0106e372013-08-12 16:34:32 +00001722 const char *zSql1, /* SQL statement 1 (see above) */
1723 const char *zSql2, /* SQL statement 2 (see above) */
1724 const char *zDb /* Database name (e.g. "main") */
1725){
drhfaacf172011-08-12 01:51:45 +00001726 int rc; /* Result codes from subroutines */
1727 sqlite3_stmt *pStmt = 0; /* An SQL statement being run */
1728 char *zSql; /* Text of the SQL statement */
1729 Index *pPrevIdx = 0; /* Previous index in the loop */
drhfaacf172011-08-12 01:51:45 +00001730 IndexSample *pSample; /* A slot in pIdx->aSample[] */
1731
drh4a642b62016-02-05 01:55:27 +00001732 assert( db->lookaside.bDisable );
dan0106e372013-08-12 16:34:32 +00001733 zSql = sqlite3MPrintf(db, zSql1, zDb);
drhfaacf172011-08-12 01:51:45 +00001734 if( !zSql ){
mistachkinfad30392016-02-13 23:43:46 +00001735 return SQLITE_NOMEM_BKPT;
drhfaacf172011-08-12 01:51:45 +00001736 }
1737 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1738 sqlite3DbFree(db, zSql);
1739 if( rc ) return rc;
1740
1741 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001742 int nIdxCol = 1; /* Number of columns in stat4 records */
dan0106e372013-08-12 16:34:32 +00001743
drhfaacf172011-08-12 01:51:45 +00001744 char *zIndex; /* Index name */
1745 Index *pIdx; /* Pointer to the index object */
1746 int nSample; /* Number of samples */
danf52bb8d2013-08-03 20:24:58 +00001747 int nByte; /* Bytes of space required */
1748 int i; /* Bytes of space required */
1749 tRowcnt *pSpace;
drhfaacf172011-08-12 01:51:45 +00001750
1751 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1752 if( zIndex==0 ) continue;
1753 nSample = sqlite3_column_int(pStmt, 1);
drhce95d112013-11-02 19:34:38 +00001754 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
drh175b8f02019-08-08 15:24:17 +00001755 assert( pIdx==0 || pIdx->nSample==0 );
drh5eae1d12019-08-08 16:23:12 +00001756 if( pIdx==0 ) continue;
drh175b8f02019-08-08 15:24:17 +00001757 assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
1758 if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
1759 nIdxCol = pIdx->nKeyCol;
1760 }else{
1761 nIdxCol = pIdx->nColumn;
dan0106e372013-08-12 16:34:32 +00001762 }
dan8ad169a2013-08-12 20:14:04 +00001763 pIdx->nSampleCol = nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001764 nByte = sizeof(IndexSample) * nSample;
dan0106e372013-08-12 16:34:32 +00001765 nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
dan39caccf2014-07-01 11:54:02 +00001766 nByte += nIdxCol * sizeof(tRowcnt); /* Space for Index.aAvgEq[] */
danf52bb8d2013-08-03 20:24:58 +00001767
1768 pIdx->aSample = sqlite3DbMallocZero(db, nByte);
drhfaacf172011-08-12 01:51:45 +00001769 if( pIdx->aSample==0 ){
drhfaacf172011-08-12 01:51:45 +00001770 sqlite3_finalize(pStmt);
mistachkinfad30392016-02-13 23:43:46 +00001771 return SQLITE_NOMEM_BKPT;
drhfaacf172011-08-12 01:51:45 +00001772 }
danf52bb8d2013-08-03 20:24:58 +00001773 pSpace = (tRowcnt*)&pIdx->aSample[nSample];
dan39caccf2014-07-01 11:54:02 +00001774 pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
drh40386962020-10-22 15:47:48 +00001775 pIdx->pTable->tabFlags |= TF_HasStat4;
dan0adbed82013-08-15 19:56:32 +00001776 for(i=0; i<nSample; i++){
dan0106e372013-08-12 16:34:32 +00001777 pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1778 pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1779 pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
danf52bb8d2013-08-03 20:24:58 +00001780 }
1781 assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
drhfaacf172011-08-12 01:51:45 +00001782 }
drh8e3937f2011-08-18 13:45:23 +00001783 rc = sqlite3_finalize(pStmt);
1784 if( rc ) return rc;
drhfaacf172011-08-12 01:51:45 +00001785
dan0106e372013-08-12 16:34:32 +00001786 zSql = sqlite3MPrintf(db, zSql2, zDb);
drhfaacf172011-08-12 01:51:45 +00001787 if( !zSql ){
mistachkinfad30392016-02-13 23:43:46 +00001788 return SQLITE_NOMEM_BKPT;
drhfaacf172011-08-12 01:51:45 +00001789 }
1790 rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1791 sqlite3DbFree(db, zSql);
1792 if( rc ) return rc;
1793
1794 while( sqlite3_step(pStmt)==SQLITE_ROW ){
dan0106e372013-08-12 16:34:32 +00001795 char *zIndex; /* Index name */
1796 Index *pIdx; /* Pointer to the index object */
dan0106e372013-08-12 16:34:32 +00001797 int nCol = 1; /* Number of columns in index */
drhfaacf172011-08-12 01:51:45 +00001798
1799 zIndex = (char *)sqlite3_column_text(pStmt, 0);
1800 if( zIndex==0 ) continue;
drhce95d112013-11-02 19:34:38 +00001801 pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
drhfaacf172011-08-12 01:51:45 +00001802 if( pIdx==0 ) continue;
dan86f69d92013-08-12 17:31:32 +00001803 /* This next condition is true if data has already been loaded from
drh175b8f02019-08-08 15:24:17 +00001804 ** the sqlite_stat4 table. */
dan0adbed82013-08-15 19:56:32 +00001805 nCol = pIdx->nSampleCol;
dan0adbed82013-08-15 19:56:32 +00001806 if( pIdx!=pPrevIdx ){
1807 initAvgEq(pPrevIdx);
1808 pPrevIdx = pIdx;
dan0106e372013-08-12 16:34:32 +00001809 }
danc367d4c2013-08-16 14:09:43 +00001810 pSample = &pIdx->aSample[pIdx->nSample];
dancfc9df72014-04-25 15:01:01 +00001811 decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
1812 decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
1813 decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
danf52bb8d2013-08-03 20:24:58 +00001814
danc367d4c2013-08-16 14:09:43 +00001815 /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
1816 ** This is in case the sample record is corrupted. In that case, the
1817 ** sqlite3VdbeRecordCompare() may read up to two varints past the
1818 ** end of the allocated buffer before it realizes it is dealing with
1819 ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
1820 ** a buffer overread. */
danf52bb8d2013-08-03 20:24:58 +00001821 pSample->n = sqlite3_column_bytes(pStmt, 4);
danc367d4c2013-08-16 14:09:43 +00001822 pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
danf52bb8d2013-08-03 20:24:58 +00001823 if( pSample->p==0 ){
1824 sqlite3_finalize(pStmt);
mistachkinfad30392016-02-13 23:43:46 +00001825 return SQLITE_NOMEM_BKPT;
drhfaacf172011-08-12 01:51:45 +00001826 }
dan895decf2016-12-30 14:15:56 +00001827 if( pSample->n ){
1828 memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
1829 }
danc367d4c2013-08-16 14:09:43 +00001830 pIdx->nSample++;
drhfaacf172011-08-12 01:51:45 +00001831 }
drh61b34402013-08-16 13:34:50 +00001832 rc = sqlite3_finalize(pStmt);
1833 if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
1834 return rc;
drhfaacf172011-08-12 01:51:45 +00001835}
dan0106e372013-08-12 16:34:32 +00001836
1837/*
drh175b8f02019-08-08 15:24:17 +00001838** Load content from the sqlite_stat4 table into
dan0106e372013-08-12 16:34:32 +00001839** the Index.aSample[] arrays of all indices.
1840*/
1841static int loadStat4(sqlite3 *db, const char *zDb){
1842 int rc = SQLITE_OK; /* Result codes from subroutines */
1843
drh4a642b62016-02-05 01:55:27 +00001844 assert( db->lookaside.bDisable );
dan0106e372013-08-12 16:34:32 +00001845 if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
drh175b8f02019-08-08 15:24:17 +00001846 rc = loadStatTbl(db,
dan0106e372013-08-12 16:34:32 +00001847 "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx",
1848 "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1849 zDb
1850 );
1851 }
dan0106e372013-08-12 16:34:32 +00001852 return rc;
1853}
drh175b8f02019-08-08 15:24:17 +00001854#endif /* SQLITE_ENABLE_STAT4 */
drhfaacf172011-08-12 01:51:45 +00001855
1856/*
drh175b8f02019-08-08 15:24:17 +00001857** Load the content of the sqlite_stat1 and sqlite_stat4 tables. The
dan85c165c2009-08-19 14:34:54 +00001858** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
drh175b8f02019-08-08 15:24:17 +00001859** arrays. The contents of sqlite_stat4 are used to populate the
dan85c165c2009-08-19 14:34:54 +00001860** Index.aSample[] arrays.
1861**
1862** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
drh175b8f02019-08-08 15:24:17 +00001863** is returned. In this case, even if SQLITE_ENABLE_STAT4 was defined
1864** during compilation and the sqlite_stat4 table is present, no data is
dan85c165c2009-08-19 14:34:54 +00001865** read from it.
1866**
drh175b8f02019-08-08 15:24:17 +00001867** If SQLITE_ENABLE_STAT4 was defined during compilation and the
danf52bb8d2013-08-03 20:24:58 +00001868** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
dan85c165c2009-08-19 14:34:54 +00001869** returned. However, in this case, data is read from the sqlite_stat1
1870** table (if it is present) before returning.
1871**
1872** If an OOM error occurs, this function always sets db->mallocFailed.
1873** This means if the caller does not care about other errors, the return
1874** code may be ignored.
drh497e4462005-07-23 03:18:40 +00001875*/
drhcf1be452007-05-12 12:08:51 +00001876int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
drh497e4462005-07-23 03:18:40 +00001877 analysisInfo sInfo;
1878 HashElem *i;
1879 char *zSql;
drh51b55a32016-04-04 12:38:05 +00001880 int rc = SQLITE_OK;
drh33bec3f2017-02-17 13:38:15 +00001881 Schema *pSchema = db->aDb[iDb].pSchema;
drh497e4462005-07-23 03:18:40 +00001882
drhff0587c2007-08-29 17:43:19 +00001883 assert( iDb>=0 && iDb<db->nDb );
1884 assert( db->aDb[iDb].pBt!=0 );
drh1fee73e2007-08-29 04:00:57 +00001885
drh497e4462005-07-23 03:18:40 +00001886 /* Clear any prior statistics */
drh21206082011-04-04 18:22:02 +00001887 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh33bec3f2017-02-17 13:38:15 +00001888 for(i=sqliteHashFirst(&pSchema->tblHash); i; i=sqliteHashNext(i)){
1889 Table *pTab = sqliteHashData(i);
1890 pTab->tabFlags &= ~TF_HasStat1;
1891 }
1892 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
drh497e4462005-07-23 03:18:40 +00001893 Index *pIdx = sqliteHashData(i);
drh33bec3f2017-02-17 13:38:15 +00001894 pIdx->hasStat1 = 0;
drh175b8f02019-08-08 15:24:17 +00001895#ifdef SQLITE_ENABLE_STAT4
dand46def72010-07-24 11:28:28 +00001896 sqlite3DeleteIndexSamples(db, pIdx);
1897 pIdx->aSample = 0;
drhfaacf172011-08-12 01:51:45 +00001898#endif
drh497e4462005-07-23 03:18:40 +00001899 }
1900
drhf6661a82016-04-01 12:35:22 +00001901 /* Load new statistics out of the sqlite_stat1 table */
drh497e4462005-07-23 03:18:40 +00001902 sInfo.db = db;
drh69c33822016-08-18 14:33:11 +00001903 sInfo.zDatabase = db->aDb[iDb].zDbSName;
drhf6661a82016-04-01 12:35:22 +00001904 if( sqlite3FindTable(db, "sqlite_stat1", sInfo.zDatabase)!=0 ){
1905 zSql = sqlite3MPrintf(db,
1906 "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
1907 if( zSql==0 ){
1908 rc = SQLITE_NOMEM_BKPT;
1909 }else{
1910 rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
1911 sqlite3DbFree(db, zSql);
1912 }
drh497e4462005-07-23 03:18:40 +00001913 }
1914
drhf6661a82016-04-01 12:35:22 +00001915 /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
1916 assert( sqlite3SchemaMutexHeld(db, iDb, 0) );
drh33bec3f2017-02-17 13:38:15 +00001917 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
drhf6661a82016-04-01 12:35:22 +00001918 Index *pIdx = sqliteHashData(i);
drh33bec3f2017-02-17 13:38:15 +00001919 if( !pIdx->hasStat1 ) sqlite3DefaultRowEst(pIdx);
drhf16ce3b2009-02-13 16:59:53 +00001920 }
dan02fa4692009-08-17 17:06:58 +00001921
danf52bb8d2013-08-03 20:24:58 +00001922 /* Load the statistics from the sqlite_stat4 table. */
drh175b8f02019-08-08 15:24:17 +00001923#ifdef SQLITE_ENABLE_STAT4
drh72d03a62018-07-20 19:24:02 +00001924 if( rc==SQLITE_OK ){
drh31f69622019-10-05 14:39:36 +00001925 DisableLookaside;
danf52bb8d2013-08-03 20:24:58 +00001926 rc = loadStat4(db, sInfo.zDatabase);
drh31f69622019-10-05 14:39:36 +00001927 EnableLookaside;
dan02fa4692009-08-17 17:06:58 +00001928 }
drh33bec3f2017-02-17 13:38:15 +00001929 for(i=sqliteHashFirst(&pSchema->idxHash); i; i=sqliteHashNext(i)){
dan43085d72014-10-03 19:16:53 +00001930 Index *pIdx = sqliteHashData(i);
drh75b170b2014-10-04 00:07:44 +00001931 sqlite3_free(pIdx->aiRowEst);
dan43085d72014-10-03 19:16:53 +00001932 pIdx->aiRowEst = 0;
1933 }
dan69188d92009-08-19 08:18:32 +00001934#endif
dan02fa4692009-08-17 17:06:58 +00001935
dane275dc32009-08-18 16:24:58 +00001936 if( rc==SQLITE_NOMEM ){
drh4a642b62016-02-05 01:55:27 +00001937 sqlite3OomFault(db);
dane275dc32009-08-18 16:24:58 +00001938 }
drhcf1be452007-05-12 12:08:51 +00001939 return rc;
drh497e4462005-07-23 03:18:40 +00001940}
drh9f18e8a2005-07-08 12:13:04 +00001941
drhff2d5ea2005-07-23 00:41:48 +00001942
drh9f18e8a2005-07-08 12:13:04 +00001943#endif /* SQLITE_OMIT_ANALYZE */