• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

tarantool / tarantool / 8976

pending completion
8976

push

travis-ci

TheAviat0r
sql: TEMP db removal

- Remove TEMP database, remove possibility to attach new databases:
  Only main database with id = 0 exists.
- Remove TEMP triggers.
- Remove TEMP tables.
- Remove TEMP views.
- Remove TEMP indexes.
- Modify SQL parser, any kind of statement with TEMP word gives syntax
  error.
- Regenerate SQL parser and keywordhash.h, opcodes.h
- Replace Db * aDb with Db mdb in sqlite3 structure

Closes #2168 , #2169

internal commit with comments

1312 of 1312 new or added lines in 28 files covered. (100.0%)

54767 of 72200 relevant lines covered (75.85%)

1202729.72 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

5.79
/src/box/sql/analyze.c
1
/*
2
** 2005-07-08
3
**
4
** The author disclaims copyright to this source code.  In place of
5
** a legal notice, here is a blessing:
6
**
7
**    May you do good and not evil.
8
**    May you find forgiveness for yourself and forgive others.
9
**    May you share freely, never taking more than you give.
10
**
11
*************************************************************************
12
** This file contains code associated with the ANALYZE command.
13
**
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);
22
**    CREATE TABLE sqlite_stat3(tbl, idx, nEq, nLt, nDLt, sample);
23
**    CREATE TABLE sqlite_stat4(tbl, idx, nEq, nLt, nDLt, sample);
24
**
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
27
** is between 3.6.18 and 3.7.8, inclusive, and unless SQLite is compiled
28
** with SQLITE_ENABLE_STAT2.  The sqlite_stat2 table is deprecated.
29
** The sqlite_stat2 table is superseded by sqlite_stat3, which is only
30
** created and used by SQLite versions 3.7.9 and later and with
31
** SQLITE_ENABLE_STAT3 defined.  The functionality of sqlite_stat3
32
** is a superset of sqlite_stat2.  The sqlite_stat4 is an enhanced
33
** version of sqlite_stat3 and is only available when compiled with
34
** SQLITE_ENABLE_STAT4 and in SQLite versions 3.8.1 and later.  It is
35
** not possible to enable both STAT3 and STAT4 at the same time.  If they
36
** are both enabled, then STAT4 takes precedence.
37
**
38
** For most applications, sqlite_stat1 provides all the statistics required
39
** for the query planner to make good choices.
40
**
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
47
** 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
49
** 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
71
** 3.6.18 and 3.7.8.  The "stat2" table contains additional information
72
** 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
**
77
** The sqlite_stat2 entries for an index that have sampleno between 0 and 9
78
** 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
**
95
** 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.
98
**
99
** 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.
107
** 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
109
** of the INTEGER PRIMARY KEY.  The sample column is a blob which is the
110
** 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.
116
** 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
118
** 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.
125
**
126
** There can be an arbitrary number of sqlite_stat4 entries per index.
127
** The ANALYZE command will typically generate sqlite_stat4 tables
128
** that contain between 10 and 40 samples which are distributed across
129
** the key space, though not uniformly, and which include samples with
130
** 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.
141
*/
142
#ifndef SQLITE_OMIT_ANALYZE
143
#include "sqliteInt.h"
144

145
#if defined(SQLITE_ENABLE_STAT4)
146
# define IsStat4     1
147
# define IsStat3     0
148
#elif defined(SQLITE_ENABLE_STAT3)
149
# define IsStat4     0
150
# define IsStat3     1
151
#else
152
# define IsStat4     0
153
# define IsStat3     0
154
# undef SQLITE_STAT4_SAMPLES
155
# define SQLITE_STAT4_SAMPLES 1
156
#endif
157
#define IsStat34    (IsStat3+IsStat4)  /* 1 for STAT3 or STAT4. 0 otherwise */
158

159
/*
160
** This routine generates code that opens the sqlite_statN tables.
161
** The sqlite_stat1 table is always relevant.  sqlite_stat2 is now
162
** obsolete.  sqlite_stat3 and sqlite_stat4 are only opened when
163
** appropriate compile-time options are provided.
164
**
165
** If the sqlite_statN tables do not previously exist, it is created.
166
**
167
** Argument zWhere may be a pointer to a buffer containing a table name,
168
** or it may be a NULL pointer. If it is not NULL, then all entries in
169
** the sqlite_statN tables associated with the named table are deleted.
170
** If zWhere==0, then code is generated to delete all stat table entries.
171
*/
172
static void openStatTable(
×
173
  Parse *pParse,          /* Parsing context */
174
  int iStatCur,           /* Open the sqlite_stat1 table on this cursor */
175
  const char *zWhere,     /* Delete entries for this table or index */
176
  const char *zWhereType  /* Either "tbl" or "idx" */
177
){
178
  static const struct {
179
    const char *zName;
180
    const char *zCols;
181
  } aTable[] = {
182
    { "sqlite_stat1", "tbl,idx,stat" },
183
#if defined(SQLITE_ENABLE_STAT4)
184
    { "sqlite_stat4", "tbl,idx,neq,nlt,ndlt,sample" },
185
    { "sqlite_stat3", 0 },
186
#elif defined(SQLITE_ENABLE_STAT3)
187
    { "sqlite_stat3", "tbl,idx,neq,nlt,ndlt,sample" },
188
    { "sqlite_stat4", 0 },
189
#else
190
    { "sqlite_stat3", 0 },
191
    { "sqlite_stat4", 0 },
192
#endif
193
  };
194
  int i;
195
  sqlite3 *db = pParse->db;
×
196
  Db *pDb;
197
  Vdbe *v = sqlite3GetVdbe(pParse);
×
198
  int aRoot[ArraySize(aTable)];
199
  u8 aCreateTbl[ArraySize(aTable)];
200

201
  if( v==0 ) return;
×
202
  assert( sqlite3BtreeHoldsAllMutexes(db) );
×
203
  assert( sqlite3VdbeDb(v)==db );
×
204
  pDb = &db->mdb;
×
205

206
  /* Create new statistic tables if they do not exist, or clear them
207
  ** if they do already exist.
208
  */
209
  for(i=0; i<ArraySize(aTable); i++){
×
210
    const char *zTab = aTable[i].zName;
×
211
    Table *pStat;
212
    if( (pStat = sqlite3FindTable(db, zTab))==0 ){
×
213
      if( aTable[i].zCols ){
×
214
        /* The sqlite_statN table does not exist. Create it. Note that a 
215
        ** side-effect of the CREATE TABLE statement is to leave the rootpage 
216
        ** of the new table in register pParse->regRoot. This is important 
217
        ** because the OpenWrite opcode below will be needing it. */
218
        sqlite3NestedParse(pParse,
×
219
            "CREATE TABLE %Q.%s(%s)", pDb->zDbSName, zTab, aTable[i].zCols
220
        );
221
        aRoot[i] = pParse->regRoot;
×
222
        aCreateTbl[i] = OPFLAG_P2ISREG;
×
223
      }
224
    }else{
225
      /* The table already exists. If zWhere is not NULL, delete all entries 
226
      ** associated with the table zWhere. If zWhere is NULL, delete the
227
      ** entire contents of the table. */
228
      aRoot[i] = pStat->tnum;
×
229
      aCreateTbl[i] = 0;
×
230
      sqlite3TableLock(pParse, aRoot[i], 1, zTab);
×
231
      if( zWhere ){
×
232
        sqlite3NestedParse(pParse,
×
233
           "DELETE FROM %Q.%s WHERE %s=%Q",
234
           pDb->zDbSName, zTab, zWhereType, zWhere
235
        );
236
      }else{
237
        /* The sqlite_stat[134] table already exists.  Delete all rows. */
238
        sqlite3VdbeAddOp2(v, OP_Clear, aRoot[i], 0);
×
239
      }
240
    }
241
  }
242

243
  /* Open the sqlite_stat[134] tables for writing. */
244
  for(i=0; aTable[i].zCols; i++){
×
245
    assert( i<ArraySize(aTable) );
×
246
    sqlite3VdbeAddOp4Int(v, OP_OpenWrite, iStatCur+i, aRoot[i], 0, 3);
×
247
    sqlite3VdbeChangeP5(v, aCreateTbl[i]);
×
248
    VdbeComment((v, aTable[i].zName));
×
249
  }
250
}
251

252
/*
253
** Recommended number of samples for sqlite_stat4
254
*/
255
#ifndef SQLITE_STAT4_SAMPLES
256
# define SQLITE_STAT4_SAMPLES 24
257
#endif
258

259
/*
260
** Three SQL functions - stat_init(), stat_push(), and stat_get() -
261
** share an instance of the following structure to hold their state
262
** information.
263
*/
264
typedef struct Stat4Accum Stat4Accum;
265
typedef struct Stat4Sample Stat4Sample;
266
struct Stat4Sample {
267
  tRowcnt *anEq;                  /* sqlite_stat4.nEq */
268
  tRowcnt *anDLt;                 /* sqlite_stat4.nDLt */
269
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
270
  tRowcnt *anLt;                  /* sqlite_stat4.nLt */
271
  union {
272
    i64 iRowid;                     /* Rowid in main table of the key */
273
    u8 *aRowid;                     /* Key for WITHOUT ROWID tables */
274
  } u;
275
  u32 nRowid;                     /* Sizeof aRowid[] */
276
  u8 isPSample;                   /* True if a periodic sample */
277
  int iCol;                       /* If !isPSample, the reason for inclusion */
278
  u32 iHash;                      /* Tiebreaker hash */
279
#endif
280
};                                                    
281
struct Stat4Accum {
282
  tRowcnt nRow;             /* Number of rows in the entire table */
283
  tRowcnt nPSample;         /* How often to do a periodic sample */
284
  int nCol;                 /* Number of columns in index + pk/rowid */
285
  int nKeyCol;              /* Number of index columns w/o the pk/rowid */
286
  int mxSample;             /* Maximum number of samples to accumulate */
287
  Stat4Sample current;      /* Current row as a Stat4Sample */
288
  u32 iPrn;                 /* Pseudo-random number used for sampling */
289
  Stat4Sample *aBest;       /* Array of nCol best samples */
290
  int iMin;                 /* Index in a[] of entry with minimum score */
291
  int nSample;              /* Current number of samples */
292
  int iGet;                 /* Index of current sample accessed by stat_get() */
293
  Stat4Sample *a;           /* Array of mxSample Stat4Sample objects */
294
  sqlite3 *db;              /* Database connection, for malloc() */
295
};
296

297
/* Reclaim memory used by a Stat4Sample
298
*/
299
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
300
static void sampleClear(sqlite3 *db, Stat4Sample *p){
301
  assert( db!=0 );
302
  if( p->nRowid ){
303
    sqlite3DbFree(db, p->u.aRowid);
304
    p->nRowid = 0;
305
  }
306
}
307
#endif
308

309
/* Initialize the BLOB value of a ROWID
310
*/
311
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
312
static void sampleSetRowid(sqlite3 *db, Stat4Sample *p, int n, const u8 *pData){
313
  assert( db!=0 );
314
  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
315
  p->u.aRowid = sqlite3DbMallocRawNN(db, n);
316
  if( p->u.aRowid ){
317
    p->nRowid = n;
318
    memcpy(p->u.aRowid, pData, n);
319
  }else{
320
    p->nRowid = 0;
321
  }
322
}
323
#endif
324

325
/* Initialize the INTEGER value of a ROWID.
326
*/
327
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
328
static void sampleSetRowidInt64(sqlite3 *db, Stat4Sample *p, i64 iRowid){
329
  assert( db!=0 );
330
  if( p->nRowid ) sqlite3DbFree(db, p->u.aRowid);
331
  p->nRowid = 0;
332
  p->u.iRowid = iRowid;
333
}
334
#endif
335

336

337
/*
338
** Copy the contents of object (*pFrom) into (*pTo).
339
*/
340
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
341
static void sampleCopy(Stat4Accum *p, Stat4Sample *pTo, Stat4Sample *pFrom){
342
  pTo->isPSample = pFrom->isPSample;
343
  pTo->iCol = pFrom->iCol;
344
  pTo->iHash = pFrom->iHash;
345
  memcpy(pTo->anEq, pFrom->anEq, sizeof(tRowcnt)*p->nCol);
346
  memcpy(pTo->anLt, pFrom->anLt, sizeof(tRowcnt)*p->nCol);
347
  memcpy(pTo->anDLt, pFrom->anDLt, sizeof(tRowcnt)*p->nCol);
348
  if( pFrom->nRowid ){
349
    sampleSetRowid(p->db, pTo, pFrom->nRowid, pFrom->u.aRowid);
350
  }else{
351
    sampleSetRowidInt64(p->db, pTo, pFrom->u.iRowid);
352
  }
353
}
354
#endif
355

356
/*
357
** Reclaim all memory of a Stat4Accum structure.
358
*/
359
static void stat4Destructor(void *pOld){
×
360
  Stat4Accum *p = (Stat4Accum*)pOld;
×
361
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
362
  int i;
363
  for(i=0; i<p->nCol; i++) sampleClear(p->db, p->aBest+i);
364
  for(i=0; i<p->mxSample; i++) sampleClear(p->db, p->a+i);
365
  sampleClear(p->db, &p->current);
366
#endif
367
  sqlite3DbFree(p->db, p);
×
368
}
×
369

370
/*
371
** Implementation of the stat_init(N,K,C) SQL function. The three parameters
372
** are:
373
**     N:    The number of columns in the index including the rowid/pk (note 1)
374
**     K:    The number of columns in the index excluding the rowid/pk.
375
**     C:    The number of rows in the index (note 2)
376
**
377
** Note 1:  In the special case of the covering index that implements a
378
** WITHOUT ROWID table, N is the number of PRIMARY KEY columns, not the
379
** total number of columns in the table.
380
**
381
** Note 2:  C is only used for STAT3 and STAT4.
382
**
383
** For indexes on ordinary rowid tables, N==K+1.  But for indexes on
384
** WITHOUT ROWID tables, N=K+P where P is the number of columns in the
385
** PRIMARY KEY of the table.  The covering index that implements the
386
** original WITHOUT ROWID table as N==K as a special case.
387
**
388
** This routine allocates the Stat4Accum object in heap memory. The return 
389
** value is a pointer to the Stat4Accum object.  The datatype of the
390
** return value is BLOB, but it is really just a pointer to the Stat4Accum
391
** object.
392
*/
393
static void statInit(
×
394
  sqlite3_context *context,
395
  int argc,
396
  sqlite3_value **argv
397
){
398
  Stat4Accum *p;
399
  int nCol;                       /* Number of columns in index being sampled */
400
  int nKeyCol;                    /* Number of key columns */
401
  int nColUp;                     /* nCol rounded up for alignment */
402
  int n;                          /* Bytes of space to allocate */
403
  sqlite3 *db;                    /* Database connection */
404
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
405
  int mxSample = SQLITE_STAT4_SAMPLES;
406
#endif
407

408
  /* Decode the three function arguments */
409
  UNUSED_PARAMETER(argc);
410
  nCol = sqlite3_value_int(argv[0]);
×
411
  assert( nCol>0 );
×
412
  nColUp = sizeof(tRowcnt)<8 ? (nCol+1)&~1 : nCol;
×
413
  nKeyCol = sqlite3_value_int(argv[1]);
×
414
  assert( nKeyCol<=nCol );
×
415
  assert( nKeyCol>0 );
×
416

417
  /* Allocate the space required for the Stat4Accum object */
418
  n = sizeof(*p) 
×
419
    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anEq */
420
    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anDLt */
421
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
422
    + sizeof(tRowcnt)*nColUp                  /* Stat4Accum.anLt */
423
    + sizeof(Stat4Sample)*(nCol+mxSample)     /* Stat4Accum.aBest[], a[] */
424
    + sizeof(tRowcnt)*3*nColUp*(nCol+mxSample)
425
#endif
426
  ;
427
  db = sqlite3_context_db_handle(context);
×
428
  p = sqlite3DbMallocZero(db, n);
×
429
  if( p==0 ){
×
430
    sqlite3_result_error_nomem(context);
×
431
    return;
×
432
  }
433

434
  p->db = db;
×
435
  p->nRow = 0;
×
436
  p->nCol = nCol;
×
437
  p->nKeyCol = nKeyCol;
×
438
  p->current.anDLt = (tRowcnt*)&p[1];
×
439
  p->current.anEq = &p->current.anDLt[nColUp];
×
440

441
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
442
  {
443
    u8 *pSpace;                     /* Allocated space not yet assigned */
444
    int i;                          /* Used to iterate through p->aSample[] */
445

446
    p->iGet = -1;
447
    p->mxSample = mxSample;
448
    p->nPSample = (tRowcnt)(sqlite3_value_int64(argv[2])/(mxSample/3+1) + 1);
449
    p->current.anLt = &p->current.anEq[nColUp];
450
    p->iPrn = 0x689e962d*(u32)nCol ^ 0xd0944565*(u32)sqlite3_value_int(argv[2]);
451
  
452
    /* Set up the Stat4Accum.a[] and aBest[] arrays */
453
    p->a = (struct Stat4Sample*)&p->current.anLt[nColUp];
454
    p->aBest = &p->a[mxSample];
455
    pSpace = (u8*)(&p->a[mxSample+nCol]);
456
    for(i=0; i<(mxSample+nCol); i++){
457
      p->a[i].anEq = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
458
      p->a[i].anLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
459
      p->a[i].anDLt = (tRowcnt *)pSpace; pSpace += (sizeof(tRowcnt) * nColUp);
460
    }
461
    assert( (pSpace - (u8*)p)==n );
462
  
463
    for(i=0; i<nCol; i++){
464
      p->aBest[i].iCol = i;
465
    }
466
  }
467
#endif
468

469
  /* Return a pointer to the allocated object to the caller.  Note that
470
  ** only the pointer (the 2nd parameter) matters.  The size of the object
471
  ** (given by the 3rd parameter) is never used and can be any positive
472
  ** value. */
473
  sqlite3_result_blob(context, p, sizeof(*p), stat4Destructor);
×
474
}
475
static const FuncDef statInitFuncdef = {
476
  2+IsStat34,      /* nArg */
477
  SQLITE_UTF8,     /* funcFlags */
478
  0,               /* pUserData */
479
  0,               /* pNext */
480
  statInit,        /* xSFunc */
481
  0,               /* xFinalize */
482
  "stat_init",     /* zName */
483
  {0}
484
};
485

486
#ifdef SQLITE_ENABLE_STAT4
487
/*
488
** pNew and pOld are both candidate non-periodic samples selected for 
489
** the same column (pNew->iCol==pOld->iCol). Ignoring this column and 
490
** considering only any trailing columns and the sample hash value, this
491
** function returns true if sample pNew is to be preferred over pOld.
492
** In other words, if we assume that the cardinalities of the selected
493
** column for pNew and pOld are equal, is pNew to be preferred over pOld.
494
**
495
** This function assumes that for each argument sample, the contents of
496
** the anEq[] array from pSample->anEq[pSample->iCol+1] onwards are valid. 
497
*/
498
static int sampleIsBetterPost(
499
  Stat4Accum *pAccum, 
500
  Stat4Sample *pNew, 
501
  Stat4Sample *pOld
502
){
503
  int nCol = pAccum->nCol;
504
  int i;
505
  assert( pNew->iCol==pOld->iCol );
506
  for(i=pNew->iCol+1; i<nCol; i++){
507
    if( pNew->anEq[i]>pOld->anEq[i] ) return 1;
508
    if( pNew->anEq[i]<pOld->anEq[i] ) return 0;
509
  }
510
  if( pNew->iHash>pOld->iHash ) return 1;
511
  return 0;
512
}
513
#endif
514

515
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
516
/*
517
** Return true if pNew is to be preferred over pOld.
518
**
519
** This function assumes that for each argument sample, the contents of
520
** the anEq[] array from pSample->anEq[pSample->iCol] onwards are valid. 
521
*/
522
static int sampleIsBetter(
523
  Stat4Accum *pAccum, 
524
  Stat4Sample *pNew, 
525
  Stat4Sample *pOld
526
){
527
  tRowcnt nEqNew = pNew->anEq[pNew->iCol];
528
  tRowcnt nEqOld = pOld->anEq[pOld->iCol];
529

530
  assert( pOld->isPSample==0 && pNew->isPSample==0 );
531
  assert( IsStat4 || (pNew->iCol==0 && pOld->iCol==0) );
532

533
  if( (nEqNew>nEqOld) ) return 1;
534
#ifdef SQLITE_ENABLE_STAT4
535
  if( nEqNew==nEqOld ){
536
    if( pNew->iCol<pOld->iCol ) return 1;
537
    return (pNew->iCol==pOld->iCol && sampleIsBetterPost(pAccum, pNew, pOld));
538
  }
539
  return 0;
540
#else
541
  return (nEqNew==nEqOld && pNew->iHash>pOld->iHash);
542
#endif
543
}
544

545
/*
546
** Copy the contents of sample *pNew into the p->a[] array. If necessary,
547
** remove the least desirable sample from p->a[] to make room.
548
*/
549
static void sampleInsert(Stat4Accum *p, Stat4Sample *pNew, int nEqZero){
550
  Stat4Sample *pSample = 0;
551
  int i;
552

553
  assert( IsStat4 || nEqZero==0 );
554

555
#ifdef SQLITE_ENABLE_STAT4
556
  if( pNew->isPSample==0 ){
557
    Stat4Sample *pUpgrade = 0;
558
    assert( pNew->anEq[pNew->iCol]>0 );
559

560
    /* This sample is being added because the prefix that ends in column 
561
    ** iCol occurs many times in the table. However, if we have already
562
    ** added a sample that shares this prefix, there is no need to add
563
    ** this one. Instead, upgrade the priority of the highest priority
564
    ** existing sample that shares this prefix.  */
565
    for(i=p->nSample-1; i>=0; i--){
566
      Stat4Sample *pOld = &p->a[i];
567
      if( pOld->anEq[pNew->iCol]==0 ){
568
        if( pOld->isPSample ) return;
569
        assert( pOld->iCol>pNew->iCol );
570
        assert( sampleIsBetter(p, pNew, pOld) );
571
        if( pUpgrade==0 || sampleIsBetter(p, pOld, pUpgrade) ){
572
          pUpgrade = pOld;
573
        }
574
      }
575
    }
576
    if( pUpgrade ){
577
      pUpgrade->iCol = pNew->iCol;
578
      pUpgrade->anEq[pUpgrade->iCol] = pNew->anEq[pUpgrade->iCol];
579
      goto find_new_min;
580
    }
581
  }
582
#endif
583

584
  /* If necessary, remove sample iMin to make room for the new sample. */
585
  if( p->nSample>=p->mxSample ){
586
    Stat4Sample *pMin = &p->a[p->iMin];
587
    tRowcnt *anEq = pMin->anEq;
588
    tRowcnt *anLt = pMin->anLt;
589
    tRowcnt *anDLt = pMin->anDLt;
590
    sampleClear(p->db, pMin);
591
    memmove(pMin, &pMin[1], sizeof(p->a[0])*(p->nSample-p->iMin-1));
592
    pSample = &p->a[p->nSample-1];
593
    pSample->nRowid = 0;
594
    pSample->anEq = anEq;
595
    pSample->anDLt = anDLt;
596
    pSample->anLt = anLt;
597
    p->nSample = p->mxSample-1;
598
  }
599

600
  /* The "rows less-than" for the rowid column must be greater than that
601
  ** for the last sample in the p->a[] array. Otherwise, the samples would
602
  ** be out of order. */
603
#ifdef SQLITE_ENABLE_STAT4
604
  assert( p->nSample==0 
605
       || pNew->anLt[p->nCol-1] > p->a[p->nSample-1].anLt[p->nCol-1] );
606
#endif
607

608
  /* Insert the new sample */
609
  pSample = &p->a[p->nSample];
610
  sampleCopy(p, pSample, pNew);
611
  p->nSample++;
612

613
  /* Zero the first nEqZero entries in the anEq[] array. */
614
  memset(pSample->anEq, 0, sizeof(tRowcnt)*nEqZero);
615

616
#ifdef SQLITE_ENABLE_STAT4
617
 find_new_min:
618
#endif
619
  if( p->nSample>=p->mxSample ){
620
    int iMin = -1;
621
    for(i=0; i<p->mxSample; i++){
622
      if( p->a[i].isPSample ) continue;
623
      if( iMin<0 || sampleIsBetter(p, &p->a[iMin], &p->a[i]) ){
624
        iMin = i;
625
      }
626
    }
627
    assert( iMin>=0 );
628
    p->iMin = iMin;
629
  }
630
}
631
#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
632

633
/*
634
** Field iChng of the index being scanned has changed. So at this point
635
** p->current contains a sample that reflects the previous row of the
636
** index. The value of anEq[iChng] and subsequent anEq[] elements are
637
** correct at this point.
638
*/
639
static void samplePushPrevious(Stat4Accum *p, int iChng){
×
640
#ifdef SQLITE_ENABLE_STAT4
641
  int i;
642

643
  /* Check if any samples from the aBest[] array should be pushed
644
  ** into IndexSample.a[] at this point.  */
645
  for(i=(p->nCol-2); i>=iChng; i--){
646
    Stat4Sample *pBest = &p->aBest[i];
647
    pBest->anEq[i] = p->current.anEq[i];
648
    if( p->nSample<p->mxSample || sampleIsBetter(p, pBest, &p->a[p->iMin]) ){
649
      sampleInsert(p, pBest, i);
650
    }
651
  }
652

653
  /* Update the anEq[] fields of any samples already collected. */
654
  for(i=p->nSample-1; i>=0; i--){
655
    int j;
656
    for(j=iChng; j<p->nCol; j++){
657
      if( p->a[i].anEq[j]==0 ) p->a[i].anEq[j] = p->current.anEq[j];
658
    }
659
  }
660
#endif
661

662
#if defined(SQLITE_ENABLE_STAT3) && !defined(SQLITE_ENABLE_STAT4)
663
  if( iChng==0 ){
664
    tRowcnt nLt = p->current.anLt[0];
665
    tRowcnt nEq = p->current.anEq[0];
666

667
    /* Check if this is to be a periodic sample. If so, add it. */
668
    if( (nLt/p->nPSample)!=(nLt+nEq)/p->nPSample ){
669
      p->current.isPSample = 1;
670
      sampleInsert(p, &p->current, 0);
671
      p->current.isPSample = 0;
672
    }else 
673

674
    /* Or if it is a non-periodic sample. Add it in this case too. */
675
    if( p->nSample<p->mxSample 
676
     || sampleIsBetter(p, &p->current, &p->a[p->iMin]) 
677
    ){
678
      sampleInsert(p, &p->current, 0);
679
    }
680
  }
681
#endif
682

683
#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
684
  UNUSED_PARAMETER( p );
685
  UNUSED_PARAMETER( iChng );
686
#endif
687
}
×
688

689
/*
690
** Implementation of the stat_push SQL function:  stat_push(P,C,R)
691
** Arguments:
692
**
693
**    P     Pointer to the Stat4Accum object created by stat_init()
694
**    C     Index of left-most column to differ from previous row
695
**    R     Rowid for the current row.  Might be a key record for
696
**          WITHOUT ROWID tables.
697
**
698
** This SQL function always returns NULL.  It's purpose it to accumulate
699
** statistical data and/or samples in the Stat4Accum object about the
700
** index being analyzed.  The stat_get() SQL function will later be used to
701
** extract relevant information for constructing the sqlite_statN tables.
702
**
703
** The R parameter is only used for STAT3 and STAT4
704
*/
705
static void statPush(
×
706
  sqlite3_context *context,
707
  int argc,
708
  sqlite3_value **argv
709
){
710
  int i;
711

712
  /* The three function arguments */
713
  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
×
714
  int iChng = sqlite3_value_int(argv[1]);
×
715

716
  UNUSED_PARAMETER( argc );
717
  UNUSED_PARAMETER( context );
718
  assert( p->nCol>0 );
×
719
  assert( iChng<p->nCol );
×
720

721
  if( p->nRow==0 ){
×
722
    /* This is the first call to this function. Do initialization. */
723
    for(i=0; i<p->nCol; i++) p->current.anEq[i] = 1;
×
724
  }else{
725
    /* Second and subsequent calls get processed here */
726
    samplePushPrevious(p, iChng);
×
727

728
    /* Update anDLt[], anLt[] and anEq[] to reflect the values that apply
729
    ** to the current row of the index. */
730
    for(i=0; i<iChng; i++){
×
731
      p->current.anEq[i]++;
×
732
    }
733
    for(i=iChng; i<p->nCol; i++){
×
734
      p->current.anDLt[i]++;
×
735
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
736
      p->current.anLt[i] += p->current.anEq[i];
737
#endif
738
      p->current.anEq[i] = 1;
×
739
    }
740
  }
741
  p->nRow++;
×
742
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
743
  if( sqlite3_value_type(argv[2])==SQLITE_INTEGER ){
744
    sampleSetRowidInt64(p->db, &p->current, sqlite3_value_int64(argv[2]));
745
  }else{
746
    sampleSetRowid(p->db, &p->current, sqlite3_value_bytes(argv[2]),
747
                                       sqlite3_value_blob(argv[2]));
748
  }
749
  p->current.iHash = p->iPrn = p->iPrn*1103515245 + 12345;
750
#endif
751

752
#ifdef SQLITE_ENABLE_STAT4
753
  {
754
    tRowcnt nLt = p->current.anLt[p->nCol-1];
755

756
    /* Check if this is to be a periodic sample. If so, add it. */
757
    if( (nLt/p->nPSample)!=(nLt+1)/p->nPSample ){
758
      p->current.isPSample = 1;
759
      p->current.iCol = 0;
760
      sampleInsert(p, &p->current, p->nCol-1);
761
      p->current.isPSample = 0;
762
    }
763

764
    /* Update the aBest[] array. */
765
    for(i=0; i<(p->nCol-1); i++){
766
      p->current.iCol = i;
767
      if( i>=iChng || sampleIsBetterPost(p, &p->current, &p->aBest[i]) ){
768
        sampleCopy(p, &p->aBest[i], &p->current);
769
      }
770
    }
771
  }
772
#endif
773
}
×
774
static const FuncDef statPushFuncdef = {
775
  2+IsStat34,      /* nArg */
776
  SQLITE_UTF8,     /* funcFlags */
777
  0,               /* pUserData */
778
  0,               /* pNext */
779
  statPush,        /* xSFunc */
780
  0,               /* xFinalize */
781
  "stat_push",     /* zName */
782
  {0}
783
};
784

785
#define STAT_GET_STAT1 0          /* "stat" column of stat1 table */
786
#define STAT_GET_ROWID 1          /* "rowid" column of stat[34] entry */
787
#define STAT_GET_NEQ   2          /* "neq" column of stat[34] entry */
788
#define STAT_GET_NLT   3          /* "nlt" column of stat[34] entry */
789
#define STAT_GET_NDLT  4          /* "ndlt" column of stat[34] entry */
790

791
/*
792
** Implementation of the stat_get(P,J) SQL function.  This routine is
793
** used to query statistical information that has been gathered into
794
** the Stat4Accum object by prior calls to stat_push().  The P parameter
795
** has type BLOB but it is really just a pointer to the Stat4Accum object.
796
** The content to returned is determined by the parameter J
797
** which is one of the STAT_GET_xxxx values defined above.
798
**
799
** If neither STAT3 nor STAT4 are enabled, then J is always
800
** STAT_GET_STAT1 and is hence omitted and this routine becomes
801
** a one-parameter function, stat_get(P), that always returns the
802
** stat1 table entry information.
803
*/
804
static void statGet(
×
805
  sqlite3_context *context,
806
  int argc,
807
  sqlite3_value **argv
808
){
809
  Stat4Accum *p = (Stat4Accum*)sqlite3_value_blob(argv[0]);
×
810
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
811
  /* STAT3 and STAT4 have a parameter on this routine. */
812
  int eCall = sqlite3_value_int(argv[1]);
813
  assert( argc==2 );
814
  assert( eCall==STAT_GET_STAT1 || eCall==STAT_GET_NEQ 
815
       || eCall==STAT_GET_ROWID || eCall==STAT_GET_NLT
816
       || eCall==STAT_GET_NDLT 
817
  );
818
  if( eCall==STAT_GET_STAT1 )
819
#else
820
  assert( argc==1 );
×
821
#endif
822
  {
823
    /* Return the value to store in the "stat" column of the sqlite_stat1
824
    ** table for this index.
825
    **
826
    ** The value is a string composed of a list of integers describing 
827
    ** the index. The first integer in the list is the total number of 
828
    ** entries in the index. There is one additional integer in the list 
829
    ** for each indexed column. This additional integer is an estimate of
830
    ** the number of rows matched by a stabbing query on the index using
831
    ** a key with the corresponding number of fields. In other words,
832
    ** if the index is on columns (a,b) and the sqlite_stat1 value is 
833
    ** "100 10 2", then SQLite estimates that:
834
    **
835
    **   * the index contains 100 rows,
836
    **   * "WHERE a=?" matches 10 rows, and
837
    **   * "WHERE a=? AND b=?" matches 2 rows.
838
    **
839
    ** If D is the count of distinct values and K is the total number of 
840
    ** rows, then each estimate is computed as:
841
    **
842
    **        I = (K+D-1)/D
843
    */
844
    char *z;
845
    int i;
846

847
    char *zRet = sqlite3MallocZero( (p->nKeyCol+1)*25 );
×
848
    if( zRet==0 ){
×
849
      sqlite3_result_error_nomem(context);
×
850
      return;
×
851
    }
852

853
    sqlite3_snprintf(24, zRet, "%llu", (u64)p->nRow);
×
854
    z = zRet + sqlite3Strlen30(zRet);
×
855
    for(i=0; i<p->nKeyCol; i++){
×
856
      u64 nDistinct = p->current.anDLt[i] + 1;
×
857
      u64 iVal = (p->nRow + nDistinct - 1) / nDistinct;
×
858
      sqlite3_snprintf(24, z, " %llu", iVal);
×
859
      z += sqlite3Strlen30(z);
×
860
      assert( p->current.anEq[i] );
×
861
    }
862
    assert( z[0]=='\0' && z>zRet );
×
863

864
    sqlite3_result_text(context, zRet, -1, sqlite3_free);
×
865
  }
866
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
867
  else if( eCall==STAT_GET_ROWID ){
868
    if( p->iGet<0 ){
869
      samplePushPrevious(p, 0);
870
      p->iGet = 0;
871
    }
872
    if( p->iGet<p->nSample ){
873
      Stat4Sample *pS = p->a + p->iGet;
874
      if( pS->nRowid==0 ){
875
        sqlite3_result_int64(context, pS->u.iRowid);
876
      }else{
877
        sqlite3_result_blob(context, pS->u.aRowid, pS->nRowid,
878
                            SQLITE_TRANSIENT);
879
      }
880
    }
881
  }else{
882
    tRowcnt *aCnt = 0;
883

884
    assert( p->iGet<p->nSample );
885
    switch( eCall ){
886
      case STAT_GET_NEQ:  aCnt = p->a[p->iGet].anEq; break;
887
      case STAT_GET_NLT:  aCnt = p->a[p->iGet].anLt; break;
888
      default: {
889
        aCnt = p->a[p->iGet].anDLt; 
890
        p->iGet++;
891
        break;
892
      }
893
    }
894

895
    if( IsStat3 ){
896
      sqlite3_result_int64(context, (i64)aCnt[0]);
897
    }else{
898
      char *zRet = sqlite3MallocZero(p->nCol * 25);
899
      if( zRet==0 ){
900
        sqlite3_result_error_nomem(context);
901
      }else{
902
        int i;
903
        char *z = zRet;
904
        for(i=0; i<p->nCol; i++){
905
          sqlite3_snprintf(24, z, "%llu ", (u64)aCnt[i]);
906
          z += sqlite3Strlen30(z);
907
        }
908
        assert( z[0]=='\0' && z>zRet );
909
        z[-1] = '\0';
910
        sqlite3_result_text(context, zRet, -1, sqlite3_free);
911
      }
912
    }
913
  }
914
#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
915
#ifndef SQLITE_DEBUG
916
  UNUSED_PARAMETER( argc );
917
#endif
918
}
919
static const FuncDef statGetFuncdef = {
920
  1+IsStat34,      /* nArg */
921
  SQLITE_UTF8,     /* funcFlags */
922
  0,               /* pUserData */
923
  0,               /* pNext */
924
  statGet,         /* xSFunc */
925
  0,               /* xFinalize */
926
  "stat_get",      /* zName */
927
  {0}
928
};
929

930
static void callStatGet(Vdbe *v, int regStat4, int iParam, int regOut){
×
931
  assert( regOut!=regStat4 && regOut!=regStat4+1 );
×
932
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
933
  sqlite3VdbeAddOp2(v, OP_Integer, iParam, regStat4+1);
934
#elif SQLITE_DEBUG
935
  assert( iParam==STAT_GET_STAT1 );
×
936
#else
937
  UNUSED_PARAMETER( iParam );
938
#endif
939
  sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4, regOut,
×
940
                    (char*)&statGetFuncdef, P4_FUNCDEF);
941
  sqlite3VdbeChangeP5(v, 1 + IsStat34);
×
942
}
×
943

944
/*
945
** Generate code to do an analysis of all indices associated with
946
** a single table.
947
*/
948
static void analyzeOneTable(
×
949
  Parse *pParse,   /* Parser context */
950
  Table *pTab,     /* Table whose indices are to be analyzed */
951
  Index *pOnlyIdx, /* If not NULL, only analyze this one index */
952
  int iStatCur,    /* Index of VdbeCursor that writes the sqlite_stat1 table */
953
  int iMem,        /* Available memory locations begin here */
954
  int iTab         /* Next available cursor */
955
){
956
  sqlite3 *db = pParse->db;    /* Database handle */
×
957
  Index *pIdx;                 /* An index to being analyzed */
958
  int iIdxCur;                 /* Cursor open on index being analyzed */
959
  int iTabCur;                 /* Table cursor */
960
  Vdbe *v;                     /* The virtual machine being built up */
961
  int i;                       /* Loop counter */
962
  int jZeroRows = -1;          /* Jump from here if number of rows is zero */
×
963
  u8 needTableCnt = 1;         /* True to count the table */
×
964
  int regNewRowid = iMem++;    /* Rowid for the inserted record */
×
965
  int regStat4 = iMem++;       /* Register to hold Stat4Accum object */
×
966
  int regChng = iMem++;        /* Index of changed index field */
×
967
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
968
  int regRowid = iMem++;       /* Rowid argument passed to stat_push() */
969
#endif
970
  int regTemp = iMem++;        /* Temporary use register */
×
971
  int regTabname = iMem++;     /* Register containing table name */
×
972
  int regIdxname = iMem++;     /* Register containing index name */
×
973
  int regStat1 = iMem++;       /* Value for the stat column of sqlite_stat1 */
×
974
  int regPrev = iMem;          /* MUST BE LAST (see below) */
×
975

976
  pParse->nMem = MAX(pParse->nMem, iMem);
×
977
  v = sqlite3GetVdbe(pParse);
×
978
  if( v==0 || NEVER(pTab==0) ){
×
979
    return;
×
980
  }
981
  if( pTab->tnum==0 ){
×
982
    /* Do not gather statistics on views or virtual tables */
983
    return;
×
984
  }
985
  if( sqlite3_strlike("sqlite_%", pTab->zName, 0)==0 ){
×
986
    /* Do not gather statistics on system tables */
987
    return;
×
988
  }
989
  assert( sqlite3BtreeHoldsAllMutexes(db) );
×
990
  assert( sqlite3SchemaToIndex(db, pTab->pSchema)==0 );
×
991
  assert( sqlite3SchemaMutexHeld(db, 0) );
×
992
#ifndef SQLITE_OMIT_AUTHORIZATION
993
  if( sqlite3AuthCheck(pParse, SQLITE_ANALYZE, pTab->zName, 0,
×
994
      db->mdb.zDbSName ) ){
×
995
    return;
×
996
  }
997
#endif
998

999
  /* Establish a read-lock on the table at the shared-cache level. 
1000
  ** Open a read-only cursor on the table. Also allocate a cursor number
1001
  ** to use for scanning indexes (iIdxCur). No index cursor is opened at
1002
  ** this time though.  */
1003
  sqlite3TableLock(pParse, pTab->tnum, 0, pTab->zName);
×
1004
  iTabCur = iTab++;
×
1005
  iIdxCur = iTab++;
×
1006
  pParse->nTab = MAX(pParse->nTab, iTab);
×
1007
  sqlite3OpenTable(pParse, iTabCur, pTab, OP_OpenRead);
×
1008
  sqlite3VdbeLoadString(v, regTabname, pTab->zName);
×
1009

1010
  for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
×
1011
    int nCol;                     /* Number of columns in pIdx. "N" */
1012
    int addrRewind;               /* Address of "OP_Rewind iIdxCur" */
1013
    int addrNextRow;              /* Address of "next_row:" */
1014
    const char *zIdxName;         /* Name of the index */
1015
    int nColTest;                 /* Number of columns to test for changes */
1016

1017
    if( pOnlyIdx && pOnlyIdx!=pIdx ) continue;
×
1018
    if( pIdx->pPartIdxWhere==0 ) needTableCnt = 0;
×
1019
    if( !HasRowid(pTab) && IsPrimaryKeyIndex(pIdx) ){
×
1020
      nCol = pIdx->nKeyCol;
×
1021
      zIdxName = pTab->zName;
×
1022
      nColTest = nCol - 1;
×
1023
    }else{
1024
      nCol = pIdx->nColumn;
×
1025
      zIdxName = pIdx->zName;
×
1026
      nColTest = pIdx->uniqNotNull ? pIdx->nKeyCol-1 : nCol-1;
×
1027
    }
1028

1029
    /* Populate the register containing the index name. */
1030
    sqlite3VdbeLoadString(v, regIdxname, zIdxName);
×
1031
    VdbeComment((v, "Analysis for %s.%s", pTab->zName, zIdxName));
×
1032

1033
    /*
1034
    ** Pseudo-code for loop that calls stat_push():
1035
    **
1036
    **   Rewind csr
1037
    **   if eof(csr) goto end_of_scan;
1038
    **   regChng = 0
1039
    **   goto chng_addr_0;
1040
    **
1041
    **  next_row:
1042
    **   regChng = 0
1043
    **   if( idx(0) != regPrev(0) ) goto chng_addr_0
1044
    **   regChng = 1
1045
    **   if( idx(1) != regPrev(1) ) goto chng_addr_1
1046
    **   ...
1047
    **   regChng = N
1048
    **   goto chng_addr_N
1049
    **
1050
    **  chng_addr_0:
1051
    **   regPrev(0) = idx(0)
1052
    **  chng_addr_1:
1053
    **   regPrev(1) = idx(1)
1054
    **  ...
1055
    **
1056
    **  endDistinctTest:
1057
    **   regRowid = idx(rowid)
1058
    **   stat_push(P, regChng, regRowid)
1059
    **   Next csr
1060
    **   if !eof(csr) goto next_row;
1061
    **
1062
    **  end_of_scan:
1063
    */
1064

1065
    /* Make sure there are enough memory cells allocated to accommodate 
1066
    ** the regPrev array and a trailing rowid (the rowid slot is required
1067
    ** when building a record to insert into the sample column of 
1068
    ** the sqlite_stat4 table.  */
1069
    pParse->nMem = MAX(pParse->nMem, regPrev+nColTest);
×
1070

1071
    /* Open a read-only cursor on the index being analyzed. */
1072
    assert( sqlite3SchemaToIndex(db, pIdx->pSchema)==0 );
×
1073
    sqlite3VdbeAddOp3(v, OP_OpenRead, iIdxCur, pIdx->tnum, 0);
×
1074
    sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
×
1075
    VdbeComment((v, "%s", pIdx->zName));
×
1076

1077
    /* Invoke the stat_init() function. The arguments are:
1078
    ** 
1079
    **    (1) the number of columns in the index including the rowid
1080
    **        (or for a WITHOUT ROWID table, the number of PK columns),
1081
    **    (2) the number of columns in the key without the rowid/pk
1082
    **    (3) the number of rows in the index,
1083
    **
1084
    **
1085
    ** The third argument is only used for STAT3 and STAT4
1086
    */
1087
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1088
    sqlite3VdbeAddOp2(v, OP_Count, iIdxCur, regStat4+3);
1089
#endif
1090
    sqlite3VdbeAddOp2(v, OP_Integer, nCol, regStat4+1);
×
1091
    sqlite3VdbeAddOp2(v, OP_Integer, pIdx->nKeyCol, regStat4+2);
×
1092
    sqlite3VdbeAddOp4(v, OP_Function0, 0, regStat4+1, regStat4,
×
1093
                     (char*)&statInitFuncdef, P4_FUNCDEF);
1094
    sqlite3VdbeChangeP5(v, 2+IsStat34);
×
1095

1096
    /* Implementation of the following:
1097
    **
1098
    **   Rewind csr
1099
    **   if eof(csr) goto end_of_scan;
1100
    **   regChng = 0
1101
    **   goto next_push_0;
1102
    **
1103
    */
1104
    addrRewind = sqlite3VdbeAddOp1(v, OP_Rewind, iIdxCur);
×
1105
    VdbeCoverage(v);
1106
    sqlite3VdbeAddOp2(v, OP_Integer, 0, regChng);
×
1107
    addrNextRow = sqlite3VdbeCurrentAddr(v);
×
1108

1109
    if( nColTest>0 ){
×
1110
      int endDistinctTest = sqlite3VdbeMakeLabel(v);
×
1111
      int *aGotoChng;               /* Array of jump instruction addresses */
1112
      aGotoChng = sqlite3DbMallocRawNN(db, sizeof(int)*nColTest);
×
1113
      if( aGotoChng==0 ) continue;
×
1114

1115
      /*
1116
      **  next_row:
1117
      **   regChng = 0
1118
      **   if( idx(0) != regPrev(0) ) goto chng_addr_0
1119
      **   regChng = 1
1120
      **   if( idx(1) != regPrev(1) ) goto chng_addr_1
1121
      **   ...
1122
      **   regChng = N
1123
      **   goto endDistinctTest
1124
      */
1125
      sqlite3VdbeAddOp0(v, OP_Goto);
×
1126
      addrNextRow = sqlite3VdbeCurrentAddr(v);
×
1127
      if( nColTest==1 && pIdx->nKeyCol==1 && IsUniqueIndex(pIdx) ){
×
1128
        /* For a single-column UNIQUE index, once we have found a non-NULL
1129
        ** row, we know that all the rest will be distinct, so skip 
1130
        ** subsequent distinctness tests. */
1131
        sqlite3VdbeAddOp2(v, OP_NotNull, regPrev, endDistinctTest);
×
1132
        VdbeCoverage(v);
1133
      }
1134
      for(i=0; i<nColTest; i++){
×
1135
        char *pColl = (char*)sqlite3LocateCollSeq(pParse, pIdx->azColl[i]);
×
1136
        sqlite3VdbeAddOp2(v, OP_Integer, i, regChng);
×
1137
        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regTemp);
×
1138
        aGotoChng[i] = 
×
1139
        sqlite3VdbeAddOp4(v, OP_Ne, regTemp, 0, regPrev+i, pColl, P4_COLLSEQ);
×
1140
        sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
×
1141
        VdbeCoverage(v);
1142
      }
1143
      sqlite3VdbeAddOp2(v, OP_Integer, nColTest, regChng);
×
1144
      sqlite3VdbeGoto(v, endDistinctTest);
×
1145
  
1146
  
1147
      /*
1148
      **  chng_addr_0:
1149
      **   regPrev(0) = idx(0)
1150
      **  chng_addr_1:
1151
      **   regPrev(1) = idx(1)
1152
      **  ...
1153
      */
1154
      sqlite3VdbeJumpHere(v, addrNextRow-1);
×
1155
      for(i=0; i<nColTest; i++){
×
1156
        sqlite3VdbeJumpHere(v, aGotoChng[i]);
×
1157
        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, i, regPrev+i);
×
1158
      }
1159
      sqlite3VdbeResolveLabel(v, endDistinctTest);
×
1160
      sqlite3DbFree(db, aGotoChng);
×
1161
    }
1162
  
1163
    /*
1164
    **  chng_addr_N:
1165
    **   regRowid = idx(rowid)            // STAT34 only
1166
    **   stat_push(P, regChng, regRowid)  // 3rd parameter STAT34 only
1167
    **   Next csr
1168
    **   if !eof(csr) goto next_row;
1169
    */
1170
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1171
    assert( regRowid==(regStat4+2) );
1172
    if( HasRowid(pTab) ){
1173
      sqlite3VdbeAddOp2(v, OP_IdxRowid, iIdxCur, regRowid);
1174
    }else{
1175
      Index *pPk = sqlite3PrimaryKeyIndex(pIdx->pTable);
1176
      int j, k, regKey;
1177
      regKey = sqlite3GetTempRange(pParse, pPk->nKeyCol);
1178
      for(j=0; j<pPk->nKeyCol; j++){
1179
        k = sqlite3ColumnOfIndex(pIdx, pPk->aiColumn[j]);
1180
        assert( k>=0 && k<pTab->nCol );
1181
        sqlite3VdbeAddOp3(v, OP_Column, iIdxCur, k, regKey+j);
1182
        VdbeComment((v, "%s", pTab->aCol[pPk->aiColumn[j]].zName));
1183
      }
1184
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regKey, pPk->nKeyCol, regRowid);
1185
      sqlite3ReleaseTempRange(pParse, regKey, pPk->nKeyCol);
1186
    }
1187
#endif
1188
    assert( regChng==(regStat4+1) );
×
1189
    sqlite3VdbeAddOp4(v, OP_Function0, 1, regStat4, regTemp,
×
1190
                     (char*)&statPushFuncdef, P4_FUNCDEF);
1191
    sqlite3VdbeChangeP5(v, 2+IsStat34);
×
1192
    sqlite3VdbeAddOp2(v, OP_Next, iIdxCur, addrNextRow); VdbeCoverage(v);
×
1193

1194
    /* Add the entry to the stat1 table. */
1195
    callStatGet(v, regStat4, STAT_GET_STAT1, regStat1);
×
1196
    assert( "BBB"[0]==SQLITE_AFF_TEXT );
×
1197
    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
×
1198
    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
×
1199
    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
×
1200
    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
×
1201

1202
    /* Add the entries to the stat3 or stat4 table. */
1203
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1204
    {
1205
      int regEq = regStat1;
1206
      int regLt = regStat1+1;
1207
      int regDLt = regStat1+2;
1208
      int regSample = regStat1+3;
1209
      int regCol = regStat1+4;
1210
      int regSampleRowid = regCol + nCol;
1211
      int addrNext;
1212
      int addrIsNull;
1213
      u8 seekOp = HasRowid(pTab) ? OP_NotExists : OP_NotFound;
1214

1215
      pParse->nMem = MAX(pParse->nMem, regCol+nCol);
1216

1217
      addrNext = sqlite3VdbeCurrentAddr(v);
1218
      callStatGet(v, regStat4, STAT_GET_ROWID, regSampleRowid);
1219
      addrIsNull = sqlite3VdbeAddOp1(v, OP_IsNull, regSampleRowid);
1220
      VdbeCoverage(v);
1221
      callStatGet(v, regStat4, STAT_GET_NEQ, regEq);
1222
      callStatGet(v, regStat4, STAT_GET_NLT, regLt);
1223
      callStatGet(v, regStat4, STAT_GET_NDLT, regDLt);
1224
      sqlite3VdbeAddOp4Int(v, seekOp, iTabCur, addrNext, regSampleRowid, 0);
1225
      /* We know that the regSampleRowid row exists because it was read by
1226
      ** the previous loop.  Thus the not-found jump of seekOp will never
1227
      ** be taken */
1228
      VdbeCoverageNeverTaken(v);
1229
#ifdef SQLITE_ENABLE_STAT3
1230
      sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, 0, regSample);
1231
#else
1232
      for(i=0; i<nCol; i++){
1233
        sqlite3ExprCodeLoadIndexColumn(pParse, pIdx, iTabCur, i, regCol+i);
1234
      }
1235
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regCol, nCol, regSample);
1236
#endif
1237
      sqlite3VdbeAddOp3(v, OP_MakeRecord, regTabname, 6, regTemp);
1238
      sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur+1, regNewRowid);
1239
      sqlite3VdbeAddOp3(v, OP_Insert, iStatCur+1, regTemp, regNewRowid);
1240
      sqlite3VdbeAddOp2(v, OP_Goto, 1, addrNext); /* P1==1 for end-of-loop */
1241
      sqlite3VdbeJumpHere(v, addrIsNull);
1242
    }
1243
#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1244

1245
    /* End of analysis */
1246
    sqlite3VdbeJumpHere(v, addrRewind);
×
1247
  }
1248

1249

1250
  /* Create a single sqlite_stat1 entry containing NULL as the index
1251
  ** name and the row count as the content.
1252
  */
1253
  if( pOnlyIdx==0 && needTableCnt ){
×
1254
    VdbeComment((v, "%s", pTab->zName));
×
1255
    sqlite3VdbeAddOp2(v, OP_Count, iTabCur, regStat1);
×
1256
    jZeroRows = sqlite3VdbeAddOp1(v, OP_IfNot, regStat1); VdbeCoverage(v);
×
1257
    sqlite3VdbeAddOp2(v, OP_Null, 0, regIdxname);
×
1258
    assert( "BBB"[0]==SQLITE_AFF_TEXT );
×
1259
    sqlite3VdbeAddOp4(v, OP_MakeRecord, regTabname, 3, regTemp, "BBB", 0);
×
1260
    sqlite3VdbeAddOp2(v, OP_NewRowid, iStatCur, regNewRowid);
×
1261
    sqlite3VdbeAddOp3(v, OP_Insert, iStatCur, regTemp, regNewRowid);
×
1262
    sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
×
1263
    sqlite3VdbeJumpHere(v, jZeroRows);
×
1264
  }
1265
}
1266

1267

1268
/*
1269
** Generate code that will cause the most recent index analysis to
1270
** be loaded into internal hash tables where is can be used.
1271
*/
1272
static void loadAnalysis(Parse *pParse){
×
1273
  Vdbe *v = sqlite3GetVdbe(pParse);
×
1274
  if( v ){
×
1275
    sqlite3VdbeAddOp1(v, OP_LoadAnalysis, 0);
×
1276
  }
1277
}
×
1278

1279
/*
1280
** Generate code that will do an analysis of an entire database
1281
*/
1282
static void analyzeDatabase(Parse *pParse){
×
1283
  sqlite3 *db = pParse->db;
×
1284
  Schema *pSchema = db->mdb.pSchema;    /* Schema of database iDb */
×
1285
  HashElem *k;
1286
  int iStatCur;
1287
  int iMem;
1288
  int iTab;
1289

1290
  sqlite3BeginWriteOperation(pParse, 0);
×
1291
  iStatCur = pParse->nTab;
×
1292
  pParse->nTab += 3;
×
1293
  openStatTable(pParse, iStatCur, 0, 0);
×
1294
  iMem = pParse->nMem+1;
×
1295
  iTab = pParse->nTab;
×
1296
  assert( sqlite3SchemaMutexHeld(db, 0) );
×
1297
  for(k=sqliteHashFirst(&pSchema->tblHash); k; k=sqliteHashNext(k)){
×
1298
    Table *pTab = (Table*)sqliteHashData(k);
×
1299
    analyzeOneTable(pParse, pTab, 0, iStatCur, iMem, iTab);
×
1300
  }
1301
  loadAnalysis(pParse);
×
1302
}
×
1303

1304
/*
1305
** Generate code that will do an analysis of a single table in
1306
** a database.  If pOnlyIdx is not NULL then it is a single index
1307
** in pTab that should be analyzed.
1308
*/
1309
static void analyzeTable(Parse *pParse, Table *pTab, Index *pOnlyIdx){
×
1310
  int iStatCur;
1311

1312
  assert( pTab!=0 );
×
1313
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
×
1314
  assert( sqlite3SchemaToIndex(pParse->db, pTab->pSchema)==0 );
×
1315
  sqlite3BeginWriteOperation(pParse, 0);
×
1316
  iStatCur = pParse->nTab;
×
1317
  pParse->nTab += 3;
×
1318
  if( pOnlyIdx ){
×
1319
    openStatTable(pParse, iStatCur, pOnlyIdx->zName, "idx");
×
1320
  }else{
1321
    openStatTable(pParse, iStatCur, pTab->zName, "tbl");
×
1322
  }
1323
  analyzeOneTable(pParse, pTab, pOnlyIdx, iStatCur,pParse->nMem+1,pParse->nTab);
×
1324
  loadAnalysis(pParse);
×
1325
}
×
1326

1327
/*
1328
** Generate code for the ANALYZE command.  The parser calls this routine
1329
** when it recognizes an ANALYZE command.
1330
**
1331
**        ANALYZE                            -- 1
1332
**        ANALYZE  <database>                -- 2
1333
**        ANALYZE  ?<database>.?<tablename>  -- 3
1334
**
1335
** Form 1 causes all indices in all attached databases to be analyzed.
1336
** Form 2 analyzes all indices the single database named.
1337
** Form 3 analyzes all indices associated with the named table.
1338
*/
1339
void sqlite3Analyze(Parse *pParse, Token *pName1, Token *pName2){
×
1340
  sqlite3 *db = pParse->db;
×
1341
  int iDb;
1342
  int i;
1343
  char *z, *zDb;
1344
  Table *pTab;
1345
  Index *pIdx;
1346
  Token *pTableName;
1347
  Vdbe *v;
1348

1349
  /* Read the database schema. If an error occurs, leave an error message
1350
  ** and code in pParse and return NULL. */
1351
  assert( sqlite3BtreeHoldsAllMutexes(pParse->db) );
×
1352
  if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
×
1353
    return;
×
1354
  }
1355

1356
  assert( pName2!=0 || pName1==0 );
×
1357
  if( pName1==0 ){
×
1358
    /* Form 1:  Analyze everything */
1359
    analyzeDatabase(pParse);
×
1360
  }else if( pName2->n==0 ){
×
1361
    /* Form 2:  Analyze the database or table named */
1362
    iDb = sqlite3FindDb(db, pName1);
×
1363
    if( iDb==0 ){
×
1364
      analyzeDatabase(pParse);
×
1365
    }else{
1366
      z = sqlite3NameFromToken(db, pName1);
×
1367
      if( z ){
×
1368
        if( (pIdx = sqlite3FindIndex(db, z))!=0 ){
×
1369
          analyzeTable(pParse, pIdx->pTable, pIdx);
×
1370
        }else if( (pTab = sqlite3LocateTable(pParse, 0, z))!=0 ){
×
1371
          analyzeTable(pParse, pTab, 0);
×
1372
        }
1373
        sqlite3DbFree(db, z);
×
1374
      }
1375
    }
1376
  }else{
1377
    /* Form 3: Analyze the fully qualified table name */
1378
    iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pTableName);
×
1379
    if( iDb>=0 ){
×
1380
      zDb = db->mdb.zDbSName;
×
1381
      z = sqlite3NameFromToken(db, pTableName);
×
1382
      if( z ){
×
1383
        if( (pIdx = sqlite3FindIndex(db, z))!=0 ){
×
1384
          analyzeTable(pParse, pIdx->pTable, pIdx);
×
1385
        }else if( (pTab = sqlite3LocateTable(pParse, 0, z))!=0 ){
×
1386
          analyzeTable(pParse, pTab, 0);
×
1387
        }
1388
        sqlite3DbFree(db, z);
×
1389
      }
1390
    }   
1391
  }
1392
  v = sqlite3GetVdbe(pParse);
×
1393
  if( v ) sqlite3VdbeAddOp0(v, OP_Expire);
×
1394
}
1395

1396
/*
1397
** Used to pass information from the analyzer reader through to the
1398
** callback routine.
1399
*/
1400
typedef struct analysisInfo analysisInfo;
1401
struct analysisInfo {
1402
  sqlite3 *db;
1403
  const char *zDatabase;
1404
};
1405

1406
/*
1407
** The first argument points to a nul-terminated string containing a
1408
** list of space separated integers. Read the first nOut of these into
1409
** the array aOut[].
1410
*/
1411
static void decodeIntArray(
×
1412
  char *zIntArray,       /* String containing int array to decode */
1413
  int nOut,              /* Number of slots in aOut[] */
1414
  tRowcnt *aOut,         /* Store integers here */
1415
  LogEst *aLog,          /* Or, if aOut==0, here */
1416
  Index *pIndex          /* Handle extra flags for this index, if not NULL */
1417
){
1418
  char *z = zIntArray;
×
1419
  int c;
1420
  int i;
1421
  tRowcnt v;
1422

1423
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1424
  if( z==0 ) z = "";
1425
#else
1426
  assert( z!=0 );
×
1427
#endif
1428
  for(i=0; *z && i<nOut; i++){
×
1429
    v = 0;
×
1430
    while( (c=z[0])>='0' && c<='9' ){
×
1431
      v = v*10 + c - '0';
×
1432
      z++;
×
1433
    }
1434
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1435
    if( aOut ) aOut[i] = v;
1436
    if( aLog ) aLog[i] = sqlite3LogEst(v);
1437
#else
1438
    assert( aOut==0 );
×
1439
    UNUSED_PARAMETER(aOut);
1440
    assert( aLog!=0 );
×
1441
    aLog[i] = sqlite3LogEst(v);
×
1442
#endif
1443
    if( *z==' ' ) z++;
×
1444
  }
1445
#ifndef SQLITE_ENABLE_STAT3_OR_STAT4
1446
  assert( pIndex!=0 ); {
×
1447
#else
1448
  if( pIndex ){
1449
#endif
1450
    pIndex->bUnordered = 0;
×
1451
    pIndex->noSkipScan = 0;
×
1452
    while( z[0] ){
×
1453
      if( sqlite3_strglob("unordered*", z)==0 ){
×
1454
        pIndex->bUnordered = 1;
×
1455
      }else if( sqlite3_strglob("sz=[0-9]*", z)==0 ){
×
1456
        pIndex->szIdxRow = sqlite3LogEst(sqlite3Atoi(z+3));
×
1457
      }else if( sqlite3_strglob("noskipscan*", z)==0 ){
×
1458
        pIndex->noSkipScan = 1;
×
1459
      }
1460
#ifdef SQLITE_ENABLE_COSTMULT
1461
      else if( sqlite3_strglob("costmult=[0-9]*",z)==0 ){
1462
        pIndex->pTable->costMult = sqlite3LogEst(sqlite3Atoi(z+9));
1463
      }
1464
#endif
1465
      while( z[0]!=0 && z[0]!=' ' ) z++;
×
1466
      while( z[0]==' ' ) z++;
×
1467
    }
1468
  }
1469
}
×
1470

1471
/*
1472
** This callback is invoked once for each index when reading the
1473
** sqlite_stat1 table.  
1474
**
1475
**     argv[0] = name of the table
1476
**     argv[1] = name of the index (might be NULL)
1477
**     argv[2] = results of analysis - on integer for each column
1478
**
1479
** Entries for which argv[1]==NULL simply record the number of rows in
1480
** the table.
1481
*/
1482
static int analysisLoader(void *pData, int argc, char **argv, char **NotUsed){
×
1483
  analysisInfo *pInfo = (analysisInfo*)pData;
×
1484
  Index *pIndex;
1485
  Table *pTable;
1486
  const char *z;
1487

1488
  assert( argc==3 );
×
1489
  UNUSED_PARAMETER2(NotUsed, argc);
1490

1491
  if( argv==0 || argv[0]==0 || argv[2]==0 ){
×
1492
    return 0;
×
1493
  }
1494
  pTable = sqlite3FindTable(pInfo->db, argv[0]);
×
1495
  if( pTable==0 ){
×
1496
    return 0;
×
1497
  }
1498
  if( argv[1]==0 ){
×
1499
    pIndex = 0;
×
1500
  }else if( sqlite3_stricmp(argv[0],argv[1])==0 ){
×
1501
    pIndex = sqlite3PrimaryKeyIndex(pTable);
×
1502
  }else{
1503
    pIndex = sqlite3FindIndex(pInfo->db, argv[1]);
×
1504
  }
1505
  z = argv[2];
×
1506

1507
  if( pIndex ){
×
1508
    tRowcnt *aiRowEst = 0;
×
1509
    int nCol = pIndex->nKeyCol+1;
×
1510
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1511
    /* Index.aiRowEst may already be set here if there are duplicate 
1512
    ** sqlite_stat1 entries for this index. In that case just clobber
1513
    ** the old data with the new instead of allocating a new array.  */
1514
    if( pIndex->aiRowEst==0 ){
1515
      pIndex->aiRowEst = (tRowcnt*)sqlite3MallocZero(sizeof(tRowcnt) * nCol);
1516
      if( pIndex->aiRowEst==0 ) sqlite3OomFault(pInfo->db);
1517
    }
1518
    aiRowEst = pIndex->aiRowEst;
1519
#endif
1520
    pIndex->bUnordered = 0;
×
1521
    decodeIntArray((char*)z, nCol, aiRowEst, pIndex->aiRowLogEst, pIndex);
×
1522
    if( pIndex->pPartIdxWhere==0 ) pTable->nRowLogEst = pIndex->aiRowLogEst[0];
×
1523
  }else{
1524
    Index fakeIdx;
1525
    fakeIdx.szIdxRow = pTable->szTabRow;
×
1526
#ifdef SQLITE_ENABLE_COSTMULT
1527
    fakeIdx.pTable = pTable;
1528
#endif
1529
    decodeIntArray((char*)z, 1, 0, &pTable->nRowLogEst, &fakeIdx);
×
1530
    pTable->szTabRow = fakeIdx.szIdxRow;
×
1531
  }
1532

1533
  return 0;
×
1534
}
1535

1536
/*
1537
** If the Index.aSample variable is not NULL, delete the aSample[] array
1538
** and its contents.
1539
*/
1540
void sqlite3DeleteIndexSamples(sqlite3 *db, Index *pIdx){
6,913✔
1541
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1542
  if( pIdx->aSample ){
1543
    int j;
1544
    for(j=0; j<pIdx->nSample; j++){
1545
      IndexSample *p = &pIdx->aSample[j];
1546
      sqlite3DbFree(db, p->p);
1547
    }
1548
    sqlite3DbFree(db, pIdx->aSample);
1549
  }
1550
  if( db && db->pnBytesFreed==0 ){
1551
    pIdx->nSample = 0;
1552
    pIdx->aSample = 0;
1553
  }
1554
#else
1555
  UNUSED_PARAMETER(db);
1556
  UNUSED_PARAMETER(pIdx);
1557
#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1558
}
6,913✔
1559

1560
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1561
/*
1562
** Populate the pIdx->aAvgEq[] array based on the samples currently
1563
** stored in pIdx->aSample[]. 
1564
*/
1565
static void initAvgEq(Index *pIdx){
1566
  if( pIdx ){
1567
    IndexSample *aSample = pIdx->aSample;
1568
    IndexSample *pFinal = &aSample[pIdx->nSample-1];
1569
    int iCol;
1570
    int nCol = 1;
1571
    if( pIdx->nSampleCol>1 ){
1572
      /* If this is stat4 data, then calculate aAvgEq[] values for all
1573
      ** sample columns except the last. The last is always set to 1, as
1574
      ** once the trailing PK fields are considered all index keys are
1575
      ** unique.  */
1576
      nCol = pIdx->nSampleCol-1;
1577
      pIdx->aAvgEq[nCol] = 1;
1578
    }
1579
    for(iCol=0; iCol<nCol; iCol++){
1580
      int nSample = pIdx->nSample;
1581
      int i;                    /* Used to iterate through samples */
1582
      tRowcnt sumEq = 0;        /* Sum of the nEq values */
1583
      tRowcnt avgEq = 0;
1584
      tRowcnt nRow;             /* Number of rows in index */
1585
      i64 nSum100 = 0;          /* Number of terms contributing to sumEq */
1586
      i64 nDist100;             /* Number of distinct values in index */
1587

1588
      if( !pIdx->aiRowEst || iCol>=pIdx->nKeyCol || pIdx->aiRowEst[iCol+1]==0 ){
1589
        nRow = pFinal->anLt[iCol];
1590
        nDist100 = (i64)100 * pFinal->anDLt[iCol];
1591
        nSample--;
1592
      }else{
1593
        nRow = pIdx->aiRowEst[0];
1594
        nDist100 = ((i64)100 * pIdx->aiRowEst[0]) / pIdx->aiRowEst[iCol+1];
1595
      }
1596
      pIdx->nRowEst0 = nRow;
1597

1598
      /* Set nSum to the number of distinct (iCol+1) field prefixes that
1599
      ** occur in the stat4 table for this index. Set sumEq to the sum of 
1600
      ** the nEq values for column iCol for the same set (adding the value 
1601
      ** only once where there exist duplicate prefixes).  */
1602
      for(i=0; i<nSample; i++){
1603
        if( i==(pIdx->nSample-1)
1604
         || aSample[i].anDLt[iCol]!=aSample[i+1].anDLt[iCol] 
1605
        ){
1606
          sumEq += aSample[i].anEq[iCol];
1607
          nSum100 += 100;
1608
        }
1609
      }
1610

1611
      if( nDist100>nSum100 ){
1612
        avgEq = ((i64)100 * (nRow - sumEq))/(nDist100 - nSum100);
1613
      }
1614
      if( avgEq==0 ) avgEq = 1;
1615
      pIdx->aAvgEq[iCol] = avgEq;
1616
    }
1617
  }
1618
}
1619

1620
/*
1621
** Look up an index by name.  Or, if the name of a WITHOUT ROWID table
1622
** is supplied instead, find the PRIMARY KEY index for that table.
1623
*/
1624
static Index *findIndexOrPrimaryKey(
1625
  sqlite3 *db,
1626
  const char *zName,
1627
  const char *zDb
1628
){
1629
  Index *pIdx = sqlite3FindIndex(db, zName, zDb);
1630
  if( pIdx==0 ){
1631
    Table *pTab = sqlite3FindTable(db, zName, zDb);
1632
    if( pTab && !HasRowid(pTab) ) pIdx = sqlite3PrimaryKeyIndex(pTab);
1633
  }
1634
  return pIdx;
1635
}
1636

1637
/*
1638
** Load the content from either the sqlite_stat4 or sqlite_stat3 table 
1639
** into the relevant Index.aSample[] arrays.
1640
**
1641
** Arguments zSql1 and zSql2 must point to SQL statements that return
1642
** data equivalent to the following (statements are different for stat3,
1643
** see the caller of this function for details):
1644
**
1645
**    zSql1: SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx
1646
**    zSql2: SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4
1647
**
1648
** where %Q is replaced with the database name before the SQL is executed.
1649
*/
1650
static int loadStatTbl(
1651
  sqlite3 *db,                  /* Database handle */
1652
  int bStat3,                   /* Assume single column records only */
1653
  const char *zSql1,            /* SQL statement 1 (see above) */
1654
  const char *zSql2,            /* SQL statement 2 (see above) */
1655
  const char *zDb               /* Database name (e.g. "main") */
1656
){
1657
  int rc;                       /* Result codes from subroutines */
1658
  sqlite3_stmt *pStmt = 0;      /* An SQL statement being run */
1659
  char *zSql;                   /* Text of the SQL statement */
1660
  Index *pPrevIdx = 0;          /* Previous index in the loop */
1661
  IndexSample *pSample;         /* A slot in pIdx->aSample[] */
1662

1663
  assert( db->lookaside.bDisable );
1664
  zSql = sqlite3MPrintf(db, zSql1, zDb);
1665
  if( !zSql ){
1666
    return SQLITE_NOMEM_BKPT;
1667
  }
1668
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1669
  sqlite3DbFree(db, zSql);
1670
  if( rc ) return rc;
1671

1672
  while( sqlite3_step(pStmt)==SQLITE_ROW ){
1673
    int nIdxCol = 1;              /* Number of columns in stat4 records */
1674

1675
    char *zIndex;   /* Index name */
1676
    Index *pIdx;    /* Pointer to the index object */
1677
    int nSample;    /* Number of samples */
1678
    int nByte;      /* Bytes of space required */
1679
    int i;          /* Bytes of space required */
1680
    tRowcnt *pSpace;
1681

1682
    zIndex = (char *)sqlite3_column_text(pStmt, 0);
1683
    if( zIndex==0 ) continue;
1684
    nSample = sqlite3_column_int(pStmt, 1);
1685
    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
1686
    assert( pIdx==0 || bStat3 || pIdx->nSample==0 );
1687
    /* Index.nSample is non-zero at this point if data has already been
1688
    ** loaded from the stat4 table. In this case ignore stat3 data.  */
1689
    if( pIdx==0 || pIdx->nSample ) continue;
1690
    if( bStat3==0 ){
1691
      assert( !HasRowid(pIdx->pTable) || pIdx->nColumn==pIdx->nKeyCol+1 );
1692
      if( !HasRowid(pIdx->pTable) && IsPrimaryKeyIndex(pIdx) ){
1693
        nIdxCol = pIdx->nKeyCol;
1694
      }else{
1695
        nIdxCol = pIdx->nColumn;
1696
      }
1697
    }
1698
    pIdx->nSampleCol = nIdxCol;
1699
    nByte = sizeof(IndexSample) * nSample;
1700
    nByte += sizeof(tRowcnt) * nIdxCol * 3 * nSample;
1701
    nByte += nIdxCol * sizeof(tRowcnt);     /* Space for Index.aAvgEq[] */
1702

1703
    pIdx->aSample = sqlite3DbMallocZero(db, nByte);
1704
    if( pIdx->aSample==0 ){
1705
      sqlite3_finalize(pStmt);
1706
      return SQLITE_NOMEM_BKPT;
1707
    }
1708
    pSpace = (tRowcnt*)&pIdx->aSample[nSample];
1709
    pIdx->aAvgEq = pSpace; pSpace += nIdxCol;
1710
    for(i=0; i<nSample; i++){
1711
      pIdx->aSample[i].anEq = pSpace; pSpace += nIdxCol;
1712
      pIdx->aSample[i].anLt = pSpace; pSpace += nIdxCol;
1713
      pIdx->aSample[i].anDLt = pSpace; pSpace += nIdxCol;
1714
    }
1715
    assert( ((u8*)pSpace)-nByte==(u8*)(pIdx->aSample) );
1716
  }
1717
  rc = sqlite3_finalize(pStmt);
1718
  if( rc ) return rc;
1719

1720
  zSql = sqlite3MPrintf(db, zSql2, zDb);
1721
  if( !zSql ){
1722
    return SQLITE_NOMEM_BKPT;
1723
  }
1724
  rc = sqlite3_prepare(db, zSql, -1, &pStmt, 0);
1725
  sqlite3DbFree(db, zSql);
1726
  if( rc ) return rc;
1727

1728
  while( sqlite3_step(pStmt)==SQLITE_ROW ){
1729
    char *zIndex;                 /* Index name */
1730
    Index *pIdx;                  /* Pointer to the index object */
1731
    int nCol = 1;                 /* Number of columns in index */
1732

1733
    zIndex = (char *)sqlite3_column_text(pStmt, 0);
1734
    if( zIndex==0 ) continue;
1735
    pIdx = findIndexOrPrimaryKey(db, zIndex, zDb);
1736
    if( pIdx==0 ) continue;
1737
    /* This next condition is true if data has already been loaded from 
1738
    ** the sqlite_stat4 table. In this case ignore stat3 data.  */
1739
    nCol = pIdx->nSampleCol;
1740
    if( bStat3 && nCol>1 ) continue;
1741
    if( pIdx!=pPrevIdx ){
1742
      initAvgEq(pPrevIdx);
1743
      pPrevIdx = pIdx;
1744
    }
1745
    pSample = &pIdx->aSample[pIdx->nSample];
1746
    decodeIntArray((char*)sqlite3_column_text(pStmt,1),nCol,pSample->anEq,0,0);
1747
    decodeIntArray((char*)sqlite3_column_text(pStmt,2),nCol,pSample->anLt,0,0);
1748
    decodeIntArray((char*)sqlite3_column_text(pStmt,3),nCol,pSample->anDLt,0,0);
1749

1750
    /* Take a copy of the sample. Add two 0x00 bytes the end of the buffer.
1751
    ** This is in case the sample record is corrupted. In that case, the
1752
    ** sqlite3VdbeRecordCompare() may read up to two varints past the
1753
    ** end of the allocated buffer before it realizes it is dealing with
1754
    ** a corrupt record. Adding the two 0x00 bytes prevents this from causing
1755
    ** a buffer overread.  */
1756
    pSample->n = sqlite3_column_bytes(pStmt, 4);
1757
    pSample->p = sqlite3DbMallocZero(db, pSample->n + 2);
1758
    if( pSample->p==0 ){
1759
      sqlite3_finalize(pStmt);
1760
      return SQLITE_NOMEM_BKPT;
1761
    }
1762
    if( pSample->n ){
1763
      memcpy(pSample->p, sqlite3_column_blob(pStmt, 4), pSample->n);
1764
    }
1765
    pIdx->nSample++;
1766
  }
1767
  rc = sqlite3_finalize(pStmt);
1768
  if( rc==SQLITE_OK ) initAvgEq(pPrevIdx);
1769
  return rc;
1770
}
1771

1772
/*
1773
** Load content from the sqlite_stat4 and sqlite_stat3 tables into 
1774
** the Index.aSample[] arrays of all indices.
1775
*/
1776
static int loadStat4(sqlite3 *db, const char *zDb){
1777
  int rc = SQLITE_OK;             /* Result codes from subroutines */
1778

1779
  assert( db->lookaside.bDisable );
1780
  if( sqlite3FindTable(db, "sqlite_stat4", zDb) ){
1781
    rc = loadStatTbl(db, 0,
1782
      "SELECT idx,count(*) FROM %Q.sqlite_stat4 GROUP BY idx", 
1783
      "SELECT idx,neq,nlt,ndlt,sample FROM %Q.sqlite_stat4",
1784
      zDb
1785
    );
1786
  }
1787

1788
  if( rc==SQLITE_OK && sqlite3FindTable(db, "sqlite_stat3", zDb) ){
1789
    rc = loadStatTbl(db, 1,
1790
      "SELECT idx,count(*) FROM %Q.sqlite_stat3 GROUP BY idx", 
1791
      "SELECT idx,neq,nlt,ndlt,sqlite_record(sample) FROM %Q.sqlite_stat3",
1792
      zDb
1793
    );
1794
  }
1795

1796
  return rc;
1797
}
1798
#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1799

1800
/*
1801
** Load the content of the sqlite_stat1 and sqlite_stat3/4 tables. The
1802
** contents of sqlite_stat1 are used to populate the Index.aiRowEst[]
1803
** arrays. The contents of sqlite_stat3/4 are used to populate the
1804
** Index.aSample[] arrays.
1805
**
1806
** If the sqlite_stat1 table is not present in the database, SQLITE_ERROR
1807
** is returned. In this case, even if SQLITE_ENABLE_STAT3/4 was defined 
1808
** during compilation and the sqlite_stat3/4 table is present, no data is 
1809
** read from it.
1810
**
1811
** If SQLITE_ENABLE_STAT3/4 was defined during compilation and the 
1812
** sqlite_stat4 table is not present in the database, SQLITE_ERROR is
1813
** returned. However, in this case, data is read from the sqlite_stat1
1814
** table (if it is present) before returning.
1815
**
1816
** If an OOM error occurs, this function always sets db->mallocFailed.
1817
** This means if the caller does not care about other errors, the return
1818
** code may be ignored.
1819
*/
1820
int sqlite3AnalysisLoad(sqlite3 *db, int iDb){
659✔
1821
  analysisInfo sInfo;
1822
  HashElem *i;
1823
  char *zSql;
1824
  int rc = SQLITE_OK;
659✔
1825

1826
  assert( iDb==0 );
659✔
1827
  assert( db->mdb.pBt!=0 );
659✔
1828

1829
  /* Clear any prior statistics */
1830
  assert( sqlite3SchemaMutexHeld(db, 0) );
659✔
1831
  for(i=sqliteHashFirst(&db->mdb.pSchema->idxHash);i;i=sqliteHashNext(i)){
3,959✔
1832
    Index *pIdx = sqliteHashData(i);
3,300✔
1833
    pIdx->aiRowLogEst[0] = 0;
3,300✔
1834
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1835
    sqlite3DeleteIndexSamples(db, pIdx);
1836
    pIdx->aSample = 0;
1837
#endif
1838
  }
1839

1840
  /* Load new statistics out of the sqlite_stat1 table */
1841
  sInfo.db = db;
659✔
1842
  sInfo.zDatabase = db->mdb.zDbSName;
659✔
1843
  if( sqlite3FindTable(db, "sqlite_stat1")!=0 ){
659✔
1844
    zSql = sqlite3MPrintf(db, 
×
1845
        "SELECT tbl,idx,stat FROM %Q.sqlite_stat1", sInfo.zDatabase);
1846
    if( zSql==0 ){
×
1847
      rc = SQLITE_NOMEM_BKPT;
×
1848
    }else{
1849
      rc = sqlite3_exec(db, zSql, analysisLoader, &sInfo, 0);
×
1850
      sqlite3DbFree(db, zSql);
×
1851
    }
1852
  }
1853

1854
  /* Set appropriate defaults on all indexes not in the sqlite_stat1 table */
1855
  assert( sqlite3SchemaMutexHeld(db, 0) );
659✔
1856
  for(i=sqliteHashFirst(&db->mdb.pSchema->idxHash);i;i=sqliteHashNext(i)){
3,959✔
1857
    Index *pIdx = sqliteHashData(i);
3,300✔
1858
    if( pIdx->aiRowLogEst[0]==0 ) sqlite3DefaultRowEst(pIdx);
3,300✔
1859
  }
1860

1861
  /* Load the statistics from the sqlite_stat4 table. */
1862
#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1863
  if( rc==SQLITE_OK && OptimizationEnabled(db, SQLITE_Stat34) ){
1864
    db->lookaside.bDisable++;
1865
    rc = loadStat4(db, sInfo.zDatabase);
1866
    db->lookaside.bDisable--;
1867
  }
1868
  for(i=sqliteHashFirst(&db->aDb[iDb].pSchema->idxHash);i;i=sqliteHashNext(i)){
1869
    Index *pIdx = sqliteHashData(i);
1870
    sqlite3_free(pIdx->aiRowEst);
1871
    pIdx->aiRowEst = 0;
1872
  }
1873
#endif
1874

1875
  if( rc==SQLITE_NOMEM ){
659✔
1876
    sqlite3OomFault(db);
×
1877
  }
1878
  return rc;
659✔
1879
}
1880

1881

1882
#endif /* SQLITE_OMIT_ANALYZE */
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2025 Coveralls, Inc