-
Notifications
You must be signed in to change notification settings - Fork 376
/
where.c
4888 lines (4675 loc) · 154 KB
/
where.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2010-2017, Tarantool AUTHORS, please see AUTHORS file.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the
* following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY <COPYRIGHT HOLDER> ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* <COPYRIGHT HOLDER> OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
/*
* This module contains C code that generates VDBE code used to process
* the WHERE clause of SQL statements. This module is responsible for
* generating the code that loops through a table looking for applicable
* rows. Indices are selected and used to speed the search when doing
* so is applicable. Because this module is responsible for selecting
* indices, you might also think of this module as the "query optimizer".
*/
#include "coll.h"
#include "sqliteInt.h"
#include "tarantoolInt.h"
#include "vdbeInt.h"
#include "whereInt.h"
#include "box/session.h"
#include "box/schema.h"
/* Forward declaration of methods */
static int whereLoopResize(sqlite3 *, WhereLoop *, int);
/* Test variable that can be set to enable WHERE tracing */
#ifdef WHERETRACE_ENABLED
/***/ int sqlite3WhereTrace = 0; /* -1; */
#endif
/*
* Return the estimated number of output rows from a WHERE clause
*/
LogEst
sqlite3WhereOutputRowCount(WhereInfo * pWInfo)
{
return pWInfo->nRowOut;
}
/*
* Return one of the WHERE_DISTINCT_xxxxx values to indicate how this
* WHERE clause returns outputs for DISTINCT processing.
*/
int
sqlite3WhereIsDistinct(WhereInfo * pWInfo)
{
return pWInfo->eDistinct;
}
/*
* Return TRUE if the WHERE clause returns rows in ORDER BY order.
* Return FALSE if the output needs to be sorted.
*/
int
sqlite3WhereIsOrdered(WhereInfo * pWInfo)
{
return pWInfo->nOBSat;
}
/*
* Return TRUE if the innermost loop of the WHERE clause implementation
* returns rows in ORDER BY order for complete run of the inner loop.
*
* Across multiple iterations of outer loops, the output rows need not be
* sorted. As long as rows are sorted for just the innermost loop, this
* routine can return TRUE.
*/
int
sqlite3WhereOrderedInnerLoop(WhereInfo * pWInfo)
{
return pWInfo->bOrderedInnerLoop;
}
/*
* Return the VDBE address or label to jump to in order to continue
* immediately with the next row of a WHERE clause.
*/
int
sqlite3WhereContinueLabel(WhereInfo * pWInfo)
{
assert(pWInfo->iContinue != 0);
return pWInfo->iContinue;
}
/*
* Return the VDBE address or label to jump to in order to break
* out of a WHERE loop.
*/
int
sqlite3WhereBreakLabel(WhereInfo * pWInfo)
{
return pWInfo->iBreak;
}
/*
* Return ONEPASS_OFF (0) if an UPDATE or DELETE statement is unable to
* operate directly on the rowis returned by a WHERE clause. Return
* ONEPASS_SINGLE (1) if the statement can operation directly because only
* a single row is to be changed. Return ONEPASS_MULTI (2) if the one-pass
* optimization can be used on multiple
*
* If the ONEPASS optimization is used (if this routine returns true)
* then also write the indices of open cursors used by ONEPASS
* into aiCur[0] and aiCur[1]. iaCur[0] gets the cursor of the data
* table and iaCur[1] gets the cursor used by an auxiliary index.
* Either value may be -1, indicating that cursor is not used.
* Any cursors returned will have been opened for writing.
*
* aiCur[0] and aiCur[1] both get -1 if the where-clause logic is
* unable to use the ONEPASS optimization.
*/
int
sqlite3WhereOkOnePass(WhereInfo * pWInfo, int *aiCur)
{
memcpy(aiCur, pWInfo->aiCurOnePass, sizeof(int) * 2);
/* Tarantool workaround: one pass is not working right now, since deleting tuple
* invalidates pointing iterator (which is used to go through table).
*/
if (pWInfo->eOnePass == ONEPASS_MULTI) {
pWInfo->eOnePass = ONEPASS_OFF;
}
#ifdef WHERETRACE_ENABLED
if (sqlite3WhereTrace && pWInfo->eOnePass != ONEPASS_OFF) {
sqlite3DebugPrintf("%s cursors: %d %d\n",
pWInfo->eOnePass ==
ONEPASS_SINGLE ? "ONEPASS_SINGLE" :
"ONEPASS_MULTI", aiCur[0], aiCur[1]);
}
#endif
return pWInfo->eOnePass;
}
/*
* Move the content of pSrc into pDest
*/
static void
whereOrMove(WhereOrSet * pDest, WhereOrSet * pSrc)
{
pDest->n = pSrc->n;
memcpy(pDest->a, pSrc->a, pDest->n * sizeof(pDest->a[0]));
}
/*
* Try to insert a new prerequisite/cost entry into the WhereOrSet pSet.
*
* The new entry might overwrite an existing entry, or it might be
* appended, or it might be discarded. Do whatever is the right thing
* so that pSet keeps the N_OR_COST best entries seen so far.
*/
static int
whereOrInsert(WhereOrSet * pSet, /* The WhereOrSet to be updated */
Bitmask prereq, /* Prerequisites of the new entry */
LogEst rRun, /* Run-cost of the new entry */
LogEst nOut) /* Number of outputs for the new entry */
{
u16 i;
WhereOrCost *p;
for (i = pSet->n, p = pSet->a; i > 0; i--, p++) {
if (rRun <= p->rRun && (prereq & p->prereq) == prereq) {
goto whereOrInsert_done;
}
if (p->rRun <= rRun && (p->prereq & prereq) == p->prereq) {
return 0;
}
}
if (pSet->n < N_OR_COST) {
p = &pSet->a[pSet->n++];
p->nOut = nOut;
} else {
p = pSet->a;
for (i = 1; i < pSet->n; i++) {
if (p->rRun > pSet->a[i].rRun)
p = pSet->a + i;
}
if (p->rRun <= rRun)
return 0;
}
whereOrInsert_done:
p->prereq = prereq;
p->rRun = rRun;
if (p->nOut > nOut)
p->nOut = nOut;
return 1;
}
/*
* Return the bitmask for the given cursor number. Return 0 if
* iCursor is not in the set.
*/
Bitmask
sqlite3WhereGetMask(WhereMaskSet * pMaskSet, int iCursor)
{
int i;
assert(pMaskSet->n <= (int)sizeof(Bitmask) * 8);
for (i = 0; i < pMaskSet->n; i++) {
if (pMaskSet->ix[i] == iCursor) {
return MASKBIT(i);
}
}
return 0;
}
/*
* Create a new mask for cursor iCursor.
*
* There is one cursor per table in the FROM clause. The number of
* tables in the FROM clause is limited by a test early in the
* sqlite3WhereBegin() routine. So we know that the pMaskSet->ix[]
* array will never overflow.
*/
static void
createMask(WhereMaskSet * pMaskSet, int iCursor)
{
assert(pMaskSet->n < ArraySize(pMaskSet->ix));
pMaskSet->ix[pMaskSet->n++] = iCursor;
}
/*
* Advance to the next WhereTerm that matches according to the criteria
* established when the pScan object was initialized by whereScanInit().
* Return NULL if there are no more matching WhereTerms.
*/
static WhereTerm *
whereScanNext(WhereScan * pScan)
{
int iCur; /* The cursor on the LHS of the term */
i16 iColumn; /* The column on the LHS of the term. -1 for IPK */
Expr *pX; /* An expression being tested */
WhereClause *pWC; /* Shorthand for pScan->pWC */
WhereTerm *pTerm; /* The term being tested */
int k = pScan->k; /* Where to start scanning */
assert(pScan->iEquiv <= pScan->nEquiv);
pWC = pScan->pWC;
while (1) {
iColumn = pScan->aiColumn[pScan->iEquiv - 1];
iCur = pScan->aiCur[pScan->iEquiv - 1];
assert(pWC != 0);
do {
for (pTerm = pWC->a + k; k < pWC->nTerm; k++, pTerm++) {
if (pTerm->leftCursor == iCur
&& pTerm->u.leftColumn == iColumn
&& (iColumn != XN_EXPR
|| sqlite3ExprCompare(pTerm->pExpr->
pLeft,
pScan->pIdxExpr,
iCur) == 0)
&& (pScan->iEquiv <= 1
|| !ExprHasProperty(pTerm->pExpr,
EP_FromJoin))
) {
if ((pTerm->eOperator & WO_EQUIV) != 0
&& pScan->nEquiv <
ArraySize(pScan->aiCur)
&& (pX =
sqlite3ExprSkipCollate(pTerm->
pExpr->
pRight))->
op == TK_COLUMN) {
int j;
for (j = 0; j < pScan->nEquiv; j++) {
if (pScan->aiCur[j] == pX->iTable
&& pScan->aiColumn[j] == pX->iColumn) {
break;
}
}
if (j == pScan->nEquiv) {
pScan->aiCur[j] =
pX->iTable;
pScan->aiColumn[j] =
pX->iColumn;
pScan->nEquiv++;
}
}
if ((pTerm->eOperator & pScan->
opMask) != 0) {
/* Verify the affinity and collating sequence match */
if ((pTerm->eOperator & WO_ISNULL) == 0) {
pX = pTerm->pExpr;
if (!sqlite3IndexAffinityOk(pX, pScan->idxaff))
continue;
if (pScan->is_column_seen) {
Parse *pParse =
pWC->pWInfo->pParse;
assert(pX->pLeft);
uint32_t id;
struct coll *coll =
sql_binary_compare_coll_seq(
pParse, pX->pLeft,
pX->pRight, &id);
if (coll != pScan->coll)
continue;
}
}
if ((pTerm->eOperator & WO_EQ) != 0
&& (pX = pTerm->pExpr->pRight)->op == TK_COLUMN
&& pX->iTable == pScan->aiCur[0]
&& pX->iColumn == pScan->aiColumn[0]) {
continue;
}
pScan->pWC = pWC;
pScan->k = k + 1;
return pTerm;
}
}
}
pWC = pWC->pOuter;
k = 0;
} while (pWC != 0);
if (pScan->iEquiv >= pScan->nEquiv)
break;
pWC = pScan->pOrigWC;
k = 0;
pScan->iEquiv++;
}
return 0;
}
/*
* Initialize a WHERE clause scanner object. Return a pointer to the
* first match. Return NULL if there are no matches.
*
* The scanner will be searching the WHERE clause pWC. It will look
* for terms of the form "X <op> <expr>" where X is column iColumn of table
* iCur. Or if pIdx!=0 then X is column iColumn of index pIdx. pIdx
* must be one of the indexes of table iCur.
*
* The <op> must be one of the operators described by opMask.
*
* If the search is for X and the WHERE clause contains terms of the
* form X=Y then this routine might also return terms of the form
* "Y <op> <expr>". The number of levels of transitivity is limited,
* but is enough to handle most commonly occurring SQL statements.
*
* If X is not the INTEGER PRIMARY KEY then X must be compatible with
* index pIdx.
*/
static WhereTerm *
whereScanInit(WhereScan * pScan, /* The WhereScan object being initialized */
WhereClause * pWC, /* The WHERE clause to be scanned */
int iCur, /* Cursor to scan for */
int iColumn, /* Column to scan for */
u32 opMask, /* Operator(s) to scan for */
Index * pIdx) /* Must be compatible with this index */
{
pScan->pOrigWC = pWC;
pScan->pWC = pWC;
pScan->pIdxExpr = 0;
pScan->idxaff = 0;
pScan->coll = NULL;
pScan->is_column_seen = false;
if (pIdx) {
int j = iColumn;
iColumn = pIdx->aiColumn[j];
if (iColumn == XN_EXPR) {
pScan->pIdxExpr = pIdx->aColExpr->a[j].pExpr;
} else if (iColumn >= 0) {
char affinity =
pIdx->pTable->def->fields[iColumn].affinity;
pScan->idxaff = affinity;
uint32_t id;
pScan->coll = sql_index_collation(pIdx, j, &id);
pScan->is_column_seen = true;
}
} else if (iColumn == XN_EXPR) {
return 0;
}
pScan->opMask = opMask;
pScan->k = 0;
pScan->aiCur[0] = iCur;
pScan->aiColumn[0] = iColumn;
pScan->nEquiv = 1;
pScan->iEquiv = 1;
return whereScanNext(pScan);
}
/*
* Search for a term in the WHERE clause that is of the form "X <op> <expr>"
* where X is a reference to the iColumn of table iCur or of index pIdx
* if pIdx!=0 and <op> is one of the WO_xx operator codes specified by
* the op parameter. Return a pointer to the term. Return 0 if not found.
*
* If pIdx!=0 then it must be one of the indexes of table iCur.
* Search for terms matching the iColumn-th column of pIdx
* rather than the iColumn-th column of table iCur.
*
* The term returned might by Y=<expr> if there is another constraint in
* the WHERE clause that specifies that X=Y. Any such constraints will be
* identified by the WO_EQUIV bit in the pTerm->eOperator field. The
* aiCur[]/iaColumn[] arrays hold X and all its equivalents. There are 11
* slots in aiCur[]/aiColumn[] so that means we can look for X plus up to 10
* other equivalent values. Hence a search for X will return <expr> if X=A1
* and A1=A2 and A2=A3 and ... and A9=A10 and A10=<expr>.
*
* If there are multiple terms in the WHERE clause of the form "X <op> <expr>"
* then try for the one with no dependencies on <expr> - in other words where
* <expr> is a constant expression of some kind. Only return entries of
* the form "X <op> Y" where Y is a column in another table if no terms of
* the form "X <op> <const-expr>" exist. If no terms with a constant RHS
* exist, try to return a term that does not use WO_EQUIV.
*/
WhereTerm *
sqlite3WhereFindTerm(WhereClause * pWC, /* The WHERE clause to be searched */
int iCur, /* Cursor number of LHS */
int iColumn, /* Column number of LHS */
Bitmask notReady, /* RHS must not overlap with this mask */
u32 op, /* Mask of WO_xx values describing operator */
Index * pIdx) /* Must be compatible with this index, if not NULL */
{
WhereTerm *pResult = 0;
WhereTerm *p;
WhereScan scan;
p = whereScanInit(&scan, pWC, iCur, iColumn, op, pIdx);
op &= WO_EQ;
while (p) {
if ((p->prereqRight & notReady) == 0) {
if (p->prereqRight == 0 && (p->eOperator & op) != 0)
return p;
if (pResult == 0)
pResult = p;
}
p = whereScanNext(&scan);
}
return pResult;
}
/*
* This function searches pList for an entry that matches the iCol-th column
* of index pIdx.
*
* If such an expression is found, its index in pList->a[] is returned. If
* no expression is found, -1 is returned.
*/
static int
findIndexCol(Parse * pParse, /* Parse context */
ExprList * pList, /* Expression list to search */
int iBase, /* Cursor for table associated with pIdx */
Index * pIdx, /* Index to match column of */
int iCol) /* Column of index to match */
{
for (int i = 0; i < pList->nExpr; i++) {
Expr *p = sqlite3ExprSkipCollate(pList->a[i].pExpr);
if (p->op == TK_COLUMN &&
p->iColumn == pIdx->aiColumn[iCol] &&
p->iTable == iBase) {
bool is_found;
uint32_t id;
struct coll *coll = sql_expr_coll(pParse,
pList->a[i].pExpr,
&is_found, &id);
if (is_found &&
coll == sql_index_collation(pIdx, iCol, &id)) {
return i;
}
}
}
return -1;
}
/*
* Return TRUE if the iCol-th column of index pIdx is NOT NULL
*/
static int
indexColumnNotNull(Index * pIdx, int iCol)
{
int j;
assert(pIdx != 0);
assert(iCol >= 0 && iCol < (int)index_column_count(pIdx));
j = pIdx->aiColumn[iCol];
if (j >= 0) {
return !pIdx->pTable->def->fields[j].is_nullable;
} else if (j == (-1)) {
return 1;
} else {
assert(j == (-2));
return 0; /* Assume an indexed expression can always yield a NULL */
}
}
/*
* Return true if the DISTINCT expression-list passed as the third argument
* is redundant.
*
* A DISTINCT list is redundant if any subset of the columns in the
* DISTINCT list are collectively unique and individually non-null.
*/
static int
isDistinctRedundant(Parse * pParse, /* Parsing context */
SrcList * pTabList, /* The FROM clause */
WhereClause * pWC, /* The WHERE clause */
ExprList * pDistinct) /* The result set that needs to be DISTINCT */
{
Table *pTab;
Index *pIdx;
int i;
int iBase;
/* If there is more than one table or sub-select in the FROM clause of
* this query, then it will not be possible to show that the DISTINCT
* clause is redundant.
*/
if (pTabList->nSrc != 1)
return 0;
iBase = pTabList->a[0].iCursor;
pTab = pTabList->a[0].pTab;
/* If any of the expressions is an IPK column on table iBase, then return
* true. Note: The (p->iTable==iBase) part of this test may be false if the
* current SELECT is a correlated sub-query.
*/
for (i = 0; i < pDistinct->nExpr; i++) {
Expr *p = sqlite3ExprSkipCollate(pDistinct->a[i].pExpr);
if (p->op == TK_COLUMN && p->iTable == iBase && p->iColumn < 0)
return 1;
}
/* Loop through all indices on the table, checking each to see if it makes
* the DISTINCT qualifier redundant. It does so if:
*
* 1. The index is itself UNIQUE, and
*
* 2. All of the columns in the index are either part of the pDistinct
* list, or else the WHERE clause contains a term of the form "col=X",
* where X is a constant value. The collation sequences of the
* comparison and select-list expressions must match those of the index.
*
* 3. All of those index columns for which the WHERE clause does not
* contain a "col=X" term are subject to a NOT NULL constraint.
*/
for (pIdx = pTab->pIndex; pIdx; pIdx = pIdx->pNext) {
if (!index_is_unique(pIdx))
continue;
int col_count = index_column_count(pIdx);
for (i = 0; i < col_count; i++) {
if (0 ==
sqlite3WhereFindTerm(pWC, iBase, i, ~(Bitmask) 0,
WO_EQ, pIdx)) {
if (findIndexCol
(pParse, pDistinct, iBase, pIdx, i) < 0)
break;
if (indexColumnNotNull(pIdx, i) == 0)
break;
}
}
if (i == (int)index_column_count(pIdx)) {
/* This index implies that the DISTINCT qualifier is redundant. */
return 1;
}
}
return 0;
}
/*
* Estimate the logarithm of the input value to base 2.
*/
static LogEst
estLog(LogEst N)
{
return N <= 10 ? 0 : sqlite3LogEst(N) - 33;
}
/*
* Convert OP_Column opcodes to OP_Copy in previously generated code.
*
* This routine runs over generated VDBE code and translates OP_Column
* opcodes into OP_Copy when the table is being accessed via co-routine
* instead of via table lookup.
*/
static void
translateColumnToCopy(Vdbe * v, /* The VDBE containing code to translate */
int iStart, /* Translate from this opcode to the end */
int iTabCur, /* OP_Column references to this table */
int iRegister) /* The first column is in this register */
{
VdbeOp *pOp = sqlite3VdbeGetOp(v, iStart);
int iEnd = sqlite3VdbeCurrentAddr(v);
for (; iStart < iEnd; iStart++, pOp++) {
if (pOp->p1 != iTabCur)
continue;
if (pOp->opcode == OP_Column) {
pOp->opcode = OP_Copy;
pOp->p1 = pOp->p2 + iRegister;
pOp->p2 = pOp->p3;
pOp->p3 = 0;
}
}
}
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
/*
* Return TRUE if the WHERE clause term pTerm is of a form where it
* could be used with an index to access pSrc, assuming an appropriate
* index existed.
*/
static int
termCanDriveIndex(WhereTerm * pTerm, /* WHERE clause term to check */
struct SrcList_item *pSrc, /* Table we are trying to access */
Bitmask notReady /* Tables in outer loops of the join */
)
{
char aff;
if (pTerm->leftCursor != pSrc->iCursor)
return 0;
if ((pTerm->eOperator & WO_EQ) == 0)
return 0;
if ((pTerm->prereqRight & notReady) != 0)
return 0;
if (pTerm->u.leftColumn < 0)
return 0;
aff = pSrc->pTab->aCol[pTerm->u.leftColumn].affinity;
if (!sqlite3IndexAffinityOk(pTerm->pExpr, aff))
return 0;
return 1;
}
#endif
#ifndef SQLITE_OMIT_AUTOMATIC_INDEX
/*
* Generate code to construct the Index object for an automatic index
* and to set up the WhereLevel object pLevel so that the code generator
* makes use of the automatic index.
*/
static void
constructAutomaticIndex(Parse * pParse, /* The parsing context */
WhereClause * pWC, /* The WHERE clause */
struct SrcList_item *pSrc, /* The FROM clause term to get the next index */
Bitmask notReady, /* Mask of cursors that are not available */
WhereLevel * pLevel) /* Write new index here */
{
int nKeyCol; /* Number of columns in the constructed index */
WhereTerm *pTerm; /* A single term of the WHERE clause */
WhereTerm *pWCEnd; /* End of pWC->a[] */
Index *pIdx; /* Object describing the transient index */
Vdbe *v; /* Prepared statement under construction */
int addrInit; /* Address of the initialization bypass jump */
Table *pTable; /* The table being indexed */
int addrTop; /* Top of the index fill loop */
int regRecord; /* Register holding an index record */
int n; /* Column counter */
int i; /* Loop counter */
int mxBitCol; /* Maximum column in pSrc->colUsed */
struct coll *pColl; /* Collating sequence to on a column */
WhereLoop *pLoop; /* The Loop object */
char *zNotUsed; /* Extra space on the end of pIdx */
Bitmask idxCols; /* Bitmap of columns used for indexing */
Bitmask extraCols; /* Bitmap of additional columns */
u8 sentWarning = 0; /* True if a warnning has been issued */
Expr *pPartial = 0; /* Partial Index Expression */
int iContinue = 0; /* Jump here to skip excluded rows */
struct SrcList_item *pTabItem; /* FROM clause term being indexed */
int addrCounter = 0; /* Address where integer counter is initialized */
int regBase; /* Array of registers where record is assembled */
/* Generate code to skip over the creation and initialization of the
* transient index on 2nd and subsequent iterations of the loop.
*/
v = pParse->pVdbe;
assert(v != 0);
addrInit = sqlite3VdbeAddOp0(v, OP_Once);
VdbeCoverage(v);
/* Count the number of columns that will be added to the index
* and used to match WHERE clause constraints
*/
nKeyCol = 0;
pTable = pSrc->pTab;
pWCEnd = &pWC->a[pWC->nTerm];
pLoop = pLevel->pWLoop;
idxCols = 0;
for (pTerm = pWC->a; pTerm < pWCEnd; pTerm++) {
Expr *pExpr = pTerm->pExpr;
assert(!ExprHasProperty(pExpr, EP_FromJoin) /* prereq always non-zero */
||pExpr->iRightJoinTable != pSrc->iCursor /* for the right-hand */
|| pLoop->prereq != 0); /* table of a LEFT JOIN */
if (pLoop->prereq == 0
&& (pTerm->wtFlags & TERM_VIRTUAL) == 0
&& !ExprHasProperty(pExpr, EP_FromJoin)
&& sqlite3ExprIsTableConstant(pExpr, pSrc->iCursor)) {
pPartial = sqlite3ExprAnd(pParse->db, pPartial,
sqlite3ExprDup(pParse->db,
pExpr, 0));
}
if (termCanDriveIndex(pTerm, pSrc, notReady)) {
int iCol = pTerm->u.leftColumn;
Bitmask cMask =
iCol >= BMS ? MASKBIT(BMS - 1) : MASKBIT(iCol);
testcase(iCol == BMS);
testcase(iCol == BMS - 1);
if (!sentWarning) {
sqlite3_log(SQLITE_WARNING_AUTOINDEX,
"automatic index on %s(%s)",
pTable->def->name,
pTable->aCol[iCol].zName);
sentWarning = 1;
}
if ((idxCols & cMask) == 0) {
if (whereLoopResize
(pParse->db, pLoop, nKeyCol + 1)) {
goto end_auto_index_create;
}
pLoop->aLTerm[nKeyCol++] = pTerm;
idxCols |= cMask;
}
}
}
assert(nKeyCol > 0);
pLoop->nEq = pLoop->nLTerm = nKeyCol;
pLoop->wsFlags = WHERE_COLUMN_EQ | WHERE_IDX_ONLY | WHERE_INDEXED
| WHERE_AUTO_INDEX;
/* Count the number of additional columns needed to create a
* covering index. A "covering index" is an index that contains all
* columns that are needed by the query. With a covering index, the
* original table never needs to be accessed. Automatic indices must
* be a covering index because the index will not be updated if the
* original table changes and the index and table cannot both be used
* if they go out of sync.
*/
extraCols = pSrc->colUsed & (~idxCols | MASKBIT(BMS - 1));
mxBitCol = MIN(BMS - 1, pTable->def->field_count);
testcase(pTable->def->field_count == BMS - 1);
testcase(pTable->def->field_count == BMS - 2);
for (i = 0; i < mxBitCol; i++) {
if (extraCols & MASKBIT(i))
nKeyCol++;
}
if (pSrc->colUsed & MASKBIT(BMS - 1)) {
nKeyCol += pTable->def->field_count - BMS + 1;
}
/* Construct the Index object to describe this index */
pIdx =
sqlite3AllocateIndexObject(pParse->db, nKeyCol + 1, 0, &zNotUsed);
if (pIdx == 0)
goto end_auto_index_create;
pLoop->pIndex = pIdx;
pIdx->zName = "auto-index";
pIdx->pTable = pTable;
n = 0;
idxCols = 0;
for (pTerm = pWC->a; pTerm < pWCEnd; pTerm++) {
if (termCanDriveIndex(pTerm, pSrc, notReady)) {
int iCol = pTerm->u.leftColumn;
Bitmask cMask =
iCol >= BMS ? MASKBIT(BMS - 1) : MASKBIT(iCol);
testcase(iCol == BMS - 1);
testcase(iCol == BMS);
if ((idxCols & cMask) == 0) {
Expr *pX = pTerm->pExpr;
idxCols |= cMask;
pIdx->aiColumn[n] = pTerm->u.leftColumn;
n++;
}
}
}
assert((u32) n == pLoop->nEq);
/* Add additional columns needed to make the automatic index into
* a covering index
*/
for (i = 0; i < mxBitCol; i++) {
if (extraCols & MASKBIT(i)) {
pIdx->aiColumn[n] = i;
n++;
}
}
if (pSrc->colUsed & MASKBIT(BMS - 1)) {
for (i = BMS - 1; i < (int)pTable->def->field_count; i++) {
pIdx->aiColumn[n] = i;
n++;
}
}
assert(n == nKeyCol);
pIdx->aiColumn[n] = XN_ROWID;
/* Create the automatic index */
assert(pLevel->iIdxCur >= 0);
pLevel->iIdxCur = pParse->nTab++;
sqlite3VdbeAddOp2(v, OP_OpenAutoindex, pLevel->iIdxCur, nKeyCol + 1);
sql_vdbe_set_p4_key_def(pParse, pIdx);
VdbeComment((v, "for %s", pTable->def->name));
/* Fill the automatic index with content */
sqlite3ExprCachePush(pParse);
pTabItem = &pWC->pWInfo->pTabList->a[pLevel->iFrom];
if (pTabItem->fg.viaCoroutine) {
int regYield = pTabItem->regReturn;
addrCounter = sqlite3VdbeAddOp2(v, OP_Integer, 0, 0);
sqlite3VdbeAddOp3(v, OP_InitCoroutine, regYield, 0,
pTabItem->addrFillSub);
addrTop = sqlite3VdbeAddOp1(v, OP_Yield, regYield);
VdbeCoverage(v);
VdbeComment((v, "next row of \"%s\"", pTabItem->pTab->zName));
} else {
addrTop = sqlite3VdbeAddOp1(v, OP_Rewind, pLevel->iTabCur);
VdbeCoverage(v);
}
if (pPartial) {
iContinue = sqlite3VdbeMakeLabel(v);
sqlite3ExprIfFalse(pParse, pPartial, iContinue,
SQLITE_JUMPIFNULL);
pLoop->wsFlags |= WHERE_PARTIALIDX;
}
regRecord = sqlite3GetTempReg(pParse);
regBase = sql_generate_index_key(pParse, pIdx, pLevel->iTabCur,
regRecord, NULL, NULL, 0);
sqlite3VdbeAddOp2(v, OP_IdxInsert, pLevel->iIdxCur, regRecord);
if (pPartial)
sql_resolve_part_idx_label(v, iContinue);
if (pTabItem->fg.viaCoroutine) {
sqlite3VdbeChangeP2(v, addrCounter, regBase + n);
translateColumnToCopy(v, addrTop, pLevel->iTabCur,
pTabItem->regResult, 1);
sqlite3VdbeGoto(v, addrTop);
pTabItem->fg.viaCoroutine = 0;
} else {
sqlite3VdbeAddOp2(v, OP_Next, pLevel->iTabCur, addrTop + 1);
VdbeCoverage(v);
}
sqlite3VdbeChangeP5(v, SQLITE_STMTSTATUS_AUTOINDEX);
sqlite3VdbeJumpHere(v, addrTop);
sqlite3ReleaseTempReg(pParse, regRecord);
sqlite3ExprCachePop(pParse);
/* Jump here when skipping the initialization */
sqlite3VdbeJumpHere(v, addrInit);
end_auto_index_create:
sqlite3ExprDelete(pParse->db, pPartial);
}
#endif /* SQLITE_OMIT_AUTOMATIC_INDEX */
/*
* Estimate the location of a particular key among all keys in an
* index. Store the results in aStat as follows:
*
* aStat[0] Est. number of rows less than pRec
* aStat[1] Est. number of rows equal to pRec
*
* Return the index of the sample that is the smallest sample that
* is greater than or equal to pRec. Note that this index is not an index
* into the aSample[] array - it is an index into a virtual set of samples
* based on the contents of aSample[] and the number of fields in record
* pRec.
*/
static int
whereKeyStats(Parse * pParse, /* Database connection */
Index * pIdx, /* Index to consider domain of */
UnpackedRecord * pRec, /* Vector of values to consider */
int roundUp, /* Round up if true. Round down if false */
tRowcnt * aStat) /* OUT: stats written here */
{
uint32_t space_id = SQLITE_PAGENO_TO_SPACEID(pIdx->tnum);
struct space *space = space_by_id(space_id);
assert(space != NULL);
uint32_t iid = SQLITE_PAGENO_TO_INDEXID(pIdx->tnum);
struct index *idx = space_index(space, iid);
assert(idx != NULL && idx->def->opts.stat != NULL);
struct index_sample *samples = idx->def->opts.stat->samples;
assert(idx->def->opts.stat->sample_count > 0);
assert(idx->def->opts.stat->samples != NULL);
assert(idx->def->opts.stat->sample_field_count >= pRec->nField);
int iCol; /* Index of required stats in anEq[] etc. */
int i; /* Index of first sample >= pRec */
int iSample; /* Smallest sample larger than or equal to pRec */
int iMin = 0; /* Smallest sample not yet tested */
int iTest; /* Next sample to test */
int res; /* Result of comparison operation */
int nField; /* Number of fields in pRec */
tRowcnt iLower = 0; /* anLt[] + anEq[] of largest sample pRec is > */
#ifndef SQLITE_DEBUG
UNUSED_PARAMETER(pParse);
#endif
assert(pRec != 0);
assert(pRec->nField > 0);
/* Do a binary search to find the first sample greater than or equal
* to pRec. If pRec contains a single field, the set of samples to search
* is simply the aSample[] array. If the samples in aSample[] contain more
* than one fields, all fields following the first are ignored.
*
* If pRec contains N fields, where N is more than one, then as well as the
* samples in aSample[] (truncated to N fields), the search also has to
* consider prefixes of those samples. For example, if the set of samples
* in aSample is:
*
* aSample[0] = (a, 5)
* aSample[1] = (a, 10)
* aSample[2] = (b, 5)
* aSample[3] = (c, 100)
* aSample[4] = (c, 105)
*
* Then the search space should ideally be the samples above and the
* unique prefixes [a], [b] and [c]. But since that is hard to organize,
* the code actually searches this set:
*
* 0: (a)
* 1: (a, 5)
* 2: (a, 10)
* 3: (a, 10)
* 4: (b)
* 5: (b, 5)
* 6: (c)
* 7: (c, 100)
* 8: (c, 105)
* 9: (c, 105)
*
* For each sample in the aSample[] array, N samples are present in the
* effective sample array. In the above, samples 0 and 1 are based on
* sample aSample[0]. Samples 2 and 3 on aSample[1] etc.
*
* Often, sample i of each block of N effective samples has (i+1) fields.
* Except, each sample may be extended to ensure that it is greater than or
* equal to the previous sample in the array. For example, in the above,
* sample 2 is the first sample of a block of N samples, so at first it
* appears that it should be 1 field in size. However, that would make it
* smaller than sample 1, so the binary search would not work. As a result,
* it is extended to two fields. The duplicates that this creates do not
* cause any problems.
*/
nField = pRec->nField;
iCol = 0;
uint32_t sample_count = idx->def->opts.stat->sample_count;
iSample = sample_count * nField;
do {
int iSamp; /* Index in aSample[] of test sample */
int n; /* Number of fields in test sample */
iTest = (iMin + iSample) / 2;
iSamp = iTest / nField;
if (iSamp > 0) {
/* The proposed effective sample is a prefix of sample aSample[iSamp].
* Specifically, the shortest prefix of at least (1 + iTest%nField)
* fields that is greater than the previous effective sample.
*/
for (n = (iTest % nField) + 1; n < nField; n++) {
if (samples[iSamp - 1].lt[n - 1] !=
samples[iSamp].lt[n - 1])
break;
}
} else {
n = iTest + 1;
}
pRec->nField = n;
res =
sqlite3VdbeRecordCompareMsgpack(samples[iSamp].sample_key,
pRec);
if (res < 0) {
iLower =
samples[iSamp].lt[n - 1] + samples[iSamp].eq[n - 1];
iMin = iTest + 1;
} else if (res == 0 && n < nField) {
iLower = samples[iSamp].lt[n - 1];
iMin = iTest + 1;
res = -1;
} else {
iSample = iTest;
iCol = n - 1;
}
} while (res && iMin < iSample);
i = iSample / nField;
#ifdef SQLITE_DEBUG
/* The following assert statements check that the binary search code
* above found the right answer. This block serves no purpose other
* than to invoke the asserts.
*/
if (pParse->db->mallocFailed == 0) {
if (res == 0) {