-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathwhere_c.cs
More file actions
executable file
·5831 lines (5560 loc) · 204 KB
/
where_c.cs
File metadata and controls
executable file
·5831 lines (5560 loc) · 204 KB
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
using System;
using System.Diagnostics;
using System.Text;
using Bitmask = System.UInt64;
using i16 = System.Int16;
using u8 = System.Byte;
using u16 = System.UInt16;
using u32 = System.UInt32;
using sqlite3_int64 = System.Int64;
namespace System.Data.SQLite
{
using sqlite3_value = Sqlite3.Mem;
public partial class Sqlite3
{
/*
** 2001 September 15
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** 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".
*************************************************************************
** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart
** C#-SQLite is an independent reimplementation of the SQLite software library
**
** SQLITE_SOURCE_ID: 2011-05-19 13:26:54 ed1da510a239ea767a01dc332b667119fa3c908ecd7
**
*************************************************************************
*/
//#include "sqliteInt.h"
/*
** Trace output macros
*/
#if (SQLITE_TEST) || (SQLITE_DEBUG)
static bool sqlite3WhereTrace = false;
#endif
#if (SQLITE_TEST) && (SQLITE_DEBUG) && TRACE
//# define WHERETRACE(X) if(sqlite3WhereTrace) sqlite3DebugPrintf X
static void WHERETRACE( string X, params object[] ap ) { if ( sqlite3WhereTrace ) sqlite3DebugPrintf( X, ap ); }
#else
//# define WHERETRACE(X)
static void WHERETRACE(string X, params object[] ap)
{
}
#endif
/* Forward reference
*/
//typedef struct WhereClause WhereClause;
//typedef struct WhereMaskSet WhereMaskSet;
//typedef struct WhereOrInfo WhereOrInfo;
//typedef struct WhereAndInfo WhereAndInfo;
//typedef struct WhereCost WhereCost;
/*
** The query generator uses an array of instances of this structure to
** help it analyze the subexpressions of the WHERE clause. Each WHERE
** clause subexpression is separated from the others by AND operators,
** usually, or sometimes subexpressions separated by OR.
**
** All WhereTerms are collected into a single WhereClause structure.
** The following identity holds:
**
** WhereTerm.pWC.a[WhereTerm.idx] == WhereTerm
**
** When a term is of the form:
**
** X <op> <expr>
**
** where X is a column name and <op> is one of certain operators,
** then WhereTerm.leftCursor and WhereTerm.u.leftColumn record the
** cursor number and column number for X. WhereTerm.eOperator records
** the <op> using a bitmask encoding defined by WO_xxx below. The
** use of a bitmask encoding for the operator allows us to search
** quickly for terms that match any of several different operators.
**
** A WhereTerm might also be two or more subterms connected by OR:
**
** (t1.X <op> <expr>) OR (t1.Y <op> <expr>) OR ....
**
** In this second case, wtFlag as the TERM_ORINFO set and eOperator==WO_OR
** and the WhereTerm.u.pOrInfo field points to auxiliary information that
** is collected about the
**
** If a term in the WHERE clause does not match either of the two previous
** categories, then eOperator==0. The WhereTerm.pExpr field is still set
** to the original subexpression content and wtFlags is set up appropriately
** but no other fields in the WhereTerm object are meaningful.
**
** When eOperator!=0, prereqRight and prereqAll record sets of cursor numbers,
** but they do so indirectly. A single WhereMaskSet structure translates
** cursor number into bits and the translated bit is stored in the prereq
** fields. The translation is used in order to maximize the number of
** bits that will fit in a Bitmask. The VDBE cursor numbers might be
** spread out over the non-negative integers. For example, the cursor
** numbers might be 3, 8, 9, 10, 20, 23, 41, and 45. The WhereMaskSet
** translates these sparse cursor numbers into consecutive integers
** beginning with 0 in order to make the best possible use of the available
** bits in the Bitmask. So, in the example above, the cursor numbers
** would be mapped into integers 0 through 7.
**
** The number of terms in a join is limited by the number of bits
** in prereqRight and prereqAll. The default is 64 bits, hence SQLite
** is only able to process joins with 64 or fewer tables.
*/
//typedef struct WhereTerm WhereTerm;
public class WhereTerm
{
public Expr pExpr; /* Pointer to the subexpression that is this term */
public int iParent; /* Disable pWC.a[iParent] when this term disabled */
public int leftCursor; /* Cursor number of X in "X <op> <expr>" */
public class _u
{
public int leftColumn; /* Column number of X in "X <op> <expr>" */
public WhereOrInfo pOrInfo; /* Extra information if eOperator==WO_OR */
public WhereAndInfo pAndInfo; /* Extra information if eOperator==WO_AND */
}
public _u u = new _u();
public u16 eOperator; /* A WO_xx value describing <op> */
public u8 wtFlags; /* TERM_xxx bit flags. See below */
public u8 nChild; /* Number of children that must disable us */
public WhereClause pWC; /* The clause this term is part of */
public Bitmask prereqRight; /* Bitmask of tables used by pExpr.pRight */
public Bitmask prereqAll; /* Bitmask of tables referenced by pExpr */
};
/*
** Allowed values of WhereTerm.wtFlags
*/
//#define TERM_DYNAMIC 0x01 /* Need to call sqlite3ExprDelete(db, ref pExpr) */
//#define TERM_VIRTUAL 0x02 /* Added by the optimizer. Do not code */
//#define TERM_CODED 0x04 /* This term is already coded */
//#define TERM_COPIED 0x08 /* Has a child */
//#define TERM_ORINFO 0x10 /* Need to free the WhereTerm.u.pOrInfo object */
//#define TERM_ANDINFO 0x20 /* Need to free the WhereTerm.u.pAndInfo obj */
//#define TERM_OR_OK 0x40 /* Used during OR-clause processing */
#if SQLITE_ENABLE_STAT2
//# define TERM_VNULL 0x80 /* Manufactured x>NULL or x<=NULL term */
#else
//# define TERM_VNULL 0x00 /* Disabled if not using stat2 */
#endif
const int TERM_DYNAMIC = 0x01; /* Need to call sqlite3ExprDelete(db, ref pExpr) */
const int TERM_VIRTUAL = 0x02; /* Added by the optimizer. Do not code */
const int TERM_CODED = 0x04; /* This term is already coded */
const int TERM_COPIED = 0x08; /* Has a child */
const int TERM_ORINFO = 0x10; /* Need to free the WhereTerm.u.pOrInfo object */
const int TERM_ANDINFO = 0x20; /* Need to free the WhereTerm.u.pAndInfo obj */
const int TERM_OR_OK = 0x40; /* Used during OR-clause processing */
#if SQLITE_ENABLE_STAT2
const int TERM_VNULL = 0x80; /* Manufactured x>NULL or x<=NULL term */
#else
const int TERM_VNULL = 0x00; /* Disabled if not using stat2 */
#endif
/*
** An instance of the following structure holds all information about a
** WHERE clause. Mostly this is a container for one or more WhereTerms.
*/
public class WhereClause
{
public Parse pParse; /* The parser context */
public WhereMaskSet pMaskSet; /* Mapping of table cursor numbers to bitmasks */
public Bitmask vmask; /* Bitmask identifying virtual table cursors */
public u8 op; /* Split operator. TK_AND or TK_OR */
public int nTerm; /* Number of terms */
public int nSlot; /* Number of entries in a[] */
public WhereTerm[] a; /* Each a[] describes a term of the WHERE cluase */
#if (SQLITE_SMALL_STACK)
public WhereTerm[] aStatic = new WhereTerm[1]; /* Initial static space for a[] */
#else
public WhereTerm[] aStatic = new WhereTerm[8]; /* Initial static space for a[] */
#endif
public void CopyTo(WhereClause wc)
{
wc.pParse = this.pParse;
wc.pMaskSet = new WhereMaskSet();
this.pMaskSet.CopyTo(wc.pMaskSet);
wc.op = this.op;
wc.nTerm = this.nTerm;
wc.nSlot = this.nSlot;
wc.a = (WhereTerm[])this.a.Clone();
wc.aStatic = (WhereTerm[])this.aStatic.Clone();
}
};
/*
** A WhereTerm with eOperator==WO_OR has its u.pOrInfo pointer set to
** a dynamically allocated instance of the following structure.
*/
public class WhereOrInfo
{
public WhereClause wc = new WhereClause();/* Decomposition into subterms */
public Bitmask indexable; /* Bitmask of all indexable tables in the clause */
};
/*
** A WhereTerm with eOperator==WO_AND has its u.pAndInfo pointer set to
** a dynamically allocated instance of the following structure.
*/
public class WhereAndInfo
{
public WhereClause wc = new WhereClause(); /* The subexpression broken out */
};
/*
** An instance of the following structure keeps track of a mapping
** between VDBE cursor numbers and bits of the bitmasks in WhereTerm.
**
** The VDBE cursor numbers are small integers contained in
** SrcList_item.iCursor and Expr.iTable fields. For any given WHERE
** clause, the cursor numbers might not begin with 0 and they might
** contain gaps in the numbering sequence. But we want to make maximum
** use of the bits in our bitmasks. This structure provides a mapping
** from the sparse cursor numbers into consecutive integers beginning
** with 0.
**
** If WhereMaskSet.ix[A]==B it means that The A-th bit of a Bitmask
** corresponds VDBE cursor number B. The A-th bit of a bitmask is 1<<A.
**
** For example, if the WHERE clause expression used these VDBE
** cursors: 4, 5, 8, 29, 57, 73. Then the WhereMaskSet structure
** would map those cursor numbers into bits 0 through 5.
**
** Note that the mapping is not necessarily ordered. In the example
** above, the mapping might go like this: 4.3, 5.1, 8.2, 29.0,
** 57.5, 73.4. Or one of 719 other combinations might be used. It
** does not really matter. What is important is that sparse cursor
** numbers all get mapped into bit numbers that begin with 0 and contain
** no gaps.
*/
public class WhereMaskSet
{
public int n; /* Number of Debug.Assigned cursor values */
public int[] ix = new int[BMS]; /* Cursor Debug.Assigned to each bit */
public void CopyTo(WhereMaskSet wms)
{
wms.n = this.n;
wms.ix = (int[])this.ix.Clone();
}
}
/*
** A WhereCost object records a lookup strategy and the estimated
** cost of pursuing that strategy.
*/
public class WhereCost
{
public WherePlan plan = new WherePlan();/* The lookup strategy */
public double rCost; /* Overall cost of pursuing this search strategy */
public Bitmask used; /* Bitmask of cursors used by this plan */
public void Clear()
{
plan.Clear();
rCost = 0;
used = 0;
}
};
/*
** Bitmasks for the operators that indices are able to exploit. An
** OR-ed combination of these values can be used when searching for
** terms in the where clause.
*/
//#define WO_IN 0x001
//#define WO_EQ 0x002
//#define WO_LT (WO_EQ<<(TK_LT-TK_EQ))
//#define WO_LE (WO_EQ<<(TK_LE-TK_EQ))
//#define WO_GT (WO_EQ<<(TK_GT-TK_EQ))
//#define WO_GE (WO_EQ<<(TK_GE-TK_EQ))
//#define WO_MATCH 0x040
//#define WO_ISNULL 0x080
//#define WO_OR 0x100 /* Two or more OR-connected terms */
//#define WO_AND 0x200 /* Two or more AND-connected terms */
//#define WO_NOOP 0x800 /* This term does not restrict search space */
//#define WO_ALL 0xfff /* Mask of all possible WO_* values */
//#define WO_SINGLE 0x0ff /* Mask of all non-compound WO_* values */
const int WO_IN = 0x001;
const int WO_EQ = 0x002;
const int WO_LT = (WO_EQ << (TK_LT - TK_EQ));
const int WO_LE = (WO_EQ << (TK_LE - TK_EQ));
const int WO_GT = (WO_EQ << (TK_GT - TK_EQ));
const int WO_GE = (WO_EQ << (TK_GE - TK_EQ));
const int WO_MATCH = 0x040;
const int WO_ISNULL = 0x080;
const int WO_OR = 0x100; /* Two or more OR-connected terms */
const int WO_AND = 0x200; /* Two or more AND-connected terms */
const int WO_NOOP = 0x800; /* This term does not restrict search space */
const int WO_ALL = 0xfff; /* Mask of all possible WO_* values */
const int WO_SINGLE = 0x0ff; /* Mask of all non-compound WO_* values */
/*
** Value for wsFlags returned by bestIndex() and stored in
** WhereLevel.wsFlags. These flags determine which search
** strategies are appropriate.
**
** The least significant 12 bits is reserved as a mask for WO_ values above.
** The WhereLevel.wsFlags field is usually set to WO_IN|WO_EQ|WO_ISNULL.
** But if the table is the right table of a left join, WhereLevel.wsFlags
** is set to WO_IN|WO_EQ. The WhereLevel.wsFlags field can then be used as
** the "op" parameter to findTerm when we are resolving equality constraints.
** ISNULL constraints will then not be used on the right table of a left
** join. Tickets #2177 and #2189.
*/
//#define WHERE_ROWID_EQ 0x00001000 /* rowid=EXPR or rowid IN (...) */
//#define WHERE_ROWID_RANGE 0x00002000 /* rowid<EXPR and/or rowid>EXPR */
//#define WHERE_COLUMN_EQ 0x00010000 /* x=EXPR or x IN (...) or x IS NULL */
//#define WHERE_COLUMN_RANGE 0x00020000 /* x<EXPR and/or x>EXPR */
//#define WHERE_COLUMN_IN 0x00040000 /* x IN (...) */
//#define WHERE_COLUMN_NULL 0x00080000 /* x IS NULL */
//#define WHERE_INDEXED 0x000f0000 /* Anything that uses an index */
//#define WHERE_IN_ABLE 0x000f1000 /* Able to support an IN operator */
//#define WHERE_NOT_FULLSCAN 0x100f3000 /* Does not do a full table scan */
//#define WHERE_TOP_LIMIT 0x00100000 /* x<EXPR or x<=EXPR constraint */
//#define WHERE_BTM_LIMIT 0x00200000 /* x>EXPR or x>=EXPR constraint */
//#define WHERE_BOTH_LIMIT 0x00300000 /* Both x>EXPR and x<EXPR */
//#define WHERE_IDX_ONLY 0x00800000 /* Use index only - omit table */
//#define WHERE_ORDERBY 0x01000000 /* Output will appear in correct order */
//#define WHERE_REVERSE 0x02000000 /* Scan in reverse order */
//#define WHERE_UNIQUE 0x04000000 /* Selects no more than one row */
//#define WHERE_VIRTUALTABLE 0x08000000 /* Use virtual-table processing */
//#define WHERE_MULTI_OR 0x10000000 /* OR using multiple indices */
//#define WHERE_TEMP_INDEX 0x20000000 /* Uses an ephemeral index */
const int WHERE_ROWID_EQ = 0x00001000;
const int WHERE_ROWID_RANGE = 0x00002000;
const int WHERE_COLUMN_EQ = 0x00010000;
const int WHERE_COLUMN_RANGE = 0x00020000;
const int WHERE_COLUMN_IN = 0x00040000;
const int WHERE_COLUMN_NULL = 0x00080000;
const int WHERE_INDEXED = 0x000f0000;
const int WHERE_IN_ABLE = 0x000f1000;
const int WHERE_NOT_FULLSCAN = 0x100f3000;
const int WHERE_TOP_LIMIT = 0x00100000;
const int WHERE_BTM_LIMIT = 0x00200000;
const int WHERE_BOTH_LIMIT = 0x00300000;
const int WHERE_IDX_ONLY = 0x00800000;
const int WHERE_ORDERBY = 0x01000000;
const int WHERE_REVERSE = 0x02000000;
const int WHERE_UNIQUE = 0x04000000;
const int WHERE_VIRTUALTABLE = 0x08000000;
const int WHERE_MULTI_OR = 0x10000000;
const int WHERE_TEMP_INDEX = 0x20000000;
/*
** Initialize a preallocated WhereClause structure.
*/
static void whereClauseInit(
WhereClause pWC, /* The WhereClause to be initialized */
Parse pParse, /* The parsing context */
WhereMaskSet pMaskSet /* Mapping from table cursor numbers to bitmasks */
)
{
pWC.pParse = pParse;
pWC.pMaskSet = pMaskSet;
pWC.nTerm = 0;
pWC.nSlot = ArraySize(pWC.aStatic) - 1;
pWC.a = pWC.aStatic;
pWC.vmask = 0;
}
/* Forward reference */
//static void whereClauseClear(WhereClause);
/*
** Deallocate all memory Debug.Associated with a WhereOrInfo object.
*/
static void whereOrInfoDelete(sqlite3 db, WhereOrInfo p)
{
whereClauseClear(p.wc);
sqlite3DbFree(db, ref p);
}
/*
** Deallocate all memory Debug.Associated with a WhereAndInfo object.
*/
static void whereAndInfoDelete(sqlite3 db, WhereAndInfo p)
{
whereClauseClear(p.wc);
sqlite3DbFree(db, ref p);
}
/*
** Deallocate a WhereClause structure. The WhereClause structure
** itself is not freed. This routine is the inverse of whereClauseInit().
*/
static void whereClauseClear(WhereClause pWC)
{
int i;
WhereTerm a;
sqlite3 db = pWC.pParse.db;
for (i = pWC.nTerm - 1; i >= 0; i--)//, a++)
{
a = pWC.a[i];
if ((a.wtFlags & TERM_DYNAMIC) != 0)
{
sqlite3ExprDelete(db, ref a.pExpr);
}
if ((a.wtFlags & TERM_ORINFO) != 0)
{
whereOrInfoDelete(db, a.u.pOrInfo);
}
else if ((a.wtFlags & TERM_ANDINFO) != 0)
{
whereAndInfoDelete(db, a.u.pAndInfo);
}
}
if (pWC.a != pWC.aStatic)
{
sqlite3DbFree(db, ref pWC.a);
}
}
/*
** Add a single new WhereTerm entry to the WhereClause object pWC.
** The new WhereTerm object is constructed from Expr p and with wtFlags.
** The index in pWC.a[] of the new WhereTerm is returned on success.
** 0 is returned if the new WhereTerm could not be added due to a memory
** allocation error. The memory allocation failure will be recorded in
** the db.mallocFailed flag so that higher-level functions can detect it.
**
** This routine will increase the size of the pWC.a[] array as necessary.
**
** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
** for freeing the expression p is Debug.Assumed by the WhereClause object pWC.
** This is true even if this routine fails to allocate a new WhereTerm.
**
** WARNING: This routine might reallocate the space used to store
** WhereTerms. All pointers to WhereTerms should be invalidated after
** calling this routine. Such pointers may be reinitialized by referencing
** the pWC.a[] array.
*/
static int whereClauseInsert(WhereClause pWC, Expr p, u8 wtFlags)
{
WhereTerm pTerm;
int idx;
testcase(wtFlags & TERM_VIRTUAL); /* EV: R-00211-15100 */
if (pWC.nTerm >= pWC.nSlot)
{
Array.Resize(ref pWC.a, pWC.nSlot * 2);
pWC.nSlot = pWC.a.Length - 1;
}
pWC.a[idx = pWC.nTerm++] = new WhereTerm();
pTerm = pWC.a[idx];
pTerm.pExpr = p;
pTerm.wtFlags = wtFlags;
pTerm.pWC = pWC;
pTerm.iParent = -1;
return idx;
}
/*
** This routine identifies subexpressions in the WHERE clause where
** each subexpression is separated by the AND operator or some other
** operator specified in the op parameter. The WhereClause structure
** is filled with pointers to subexpressions. For example:
**
** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
** \________/ \_______________/ \________________/
** slot[0] slot[1] slot[2]
**
** The original WHERE clause in pExpr is unaltered. All this routine
** does is make slot[] entries point to substructure within pExpr.
**
** In the previous sentence and in the diagram, "slot[]" refers to
** the WhereClause.a[] array. The slot[] array grows as needed to contain
** all terms of the WHERE clause.
*/
static void whereSplit(WhereClause pWC, Expr pExpr, int op)
{
pWC.op = (u8)op;
if (pExpr == null)
return;
if (pExpr.op != op)
{
whereClauseInsert(pWC, pExpr, 0);
}
else
{
whereSplit(pWC, pExpr.pLeft, op);
whereSplit(pWC, pExpr.pRight, op);
}
}
/*
** Initialize an expression mask set (a WhereMaskSet object)
*/
//#define initMaskSet(P) memset(P, 0, sizeof(*P))
/*
** Return the bitmask for the given cursor number. Return 0 if
** iCursor is not in the set.
*/
static Bitmask getMask(WhereMaskSet pMaskSet, int iCursor)
{
int i;
Debug.Assert(pMaskSet.n <= (int)sizeof(Bitmask) * 8);
for (i = 0; i < pMaskSet.n; i++)
{
if (pMaskSet.ix[i] == iCursor)
{
return ((Bitmask)1) << 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)
{
Debug.Assert(pMaskSet.n < ArraySize(pMaskSet.ix));
pMaskSet.ix[pMaskSet.n++] = iCursor;
}
/*
** This routine walks (recursively) an expression tree and generates
** a bitmask indicating which tables are used in that expression
** tree.
**
** In order for this routine to work, the calling function must have
** previously invoked sqlite3ResolveExprNames() on the expression. See
** the header comment on that routine for additional information.
** The sqlite3ResolveExprNames() routines looks for column names and
** sets their opcodes to TK_COLUMN and their Expr.iTable fields to
** the VDBE cursor number of the table. This routine just has to
** translate the cursor numbers into bitmask values and OR all
** the bitmasks together.
*/
//static Bitmask exprListTableUsage(WhereMaskSet*, ExprList);
//static Bitmask exprSelectTableUsage(WhereMaskSet*, Select);
static Bitmask exprTableUsage(WhereMaskSet pMaskSet, Expr p)
{
Bitmask mask = 0;
if (p == null)
return 0;
if (p.op == TK_COLUMN)
{
mask = getMask(pMaskSet, p.iTable);
return mask;
}
mask = exprTableUsage(pMaskSet, p.pRight);
mask |= exprTableUsage(pMaskSet, p.pLeft);
if (ExprHasProperty(p, EP_xIsSelect))
{
mask |= exprSelectTableUsage(pMaskSet, p.x.pSelect);
}
else
{
mask |= exprListTableUsage(pMaskSet, p.x.pList);
}
return mask;
}
static Bitmask exprListTableUsage(WhereMaskSet pMaskSet, ExprList pList)
{
int i;
Bitmask mask = 0;
if (pList != null)
{
for (i = 0; i < pList.nExpr; i++)
{
mask |= exprTableUsage(pMaskSet, pList.a[i].pExpr);
}
}
return mask;
}
static Bitmask exprSelectTableUsage(WhereMaskSet pMaskSet, Select pS)
{
Bitmask mask = 0;
while (pS != null)
{
mask |= exprListTableUsage(pMaskSet, pS.pEList);
mask |= exprListTableUsage(pMaskSet, pS.pGroupBy);
mask |= exprListTableUsage(pMaskSet, pS.pOrderBy);
mask |= exprTableUsage(pMaskSet, pS.pWhere);
mask |= exprTableUsage(pMaskSet, pS.pHaving);
pS = pS.pPrior;
}
return mask;
}
/*
** Return TRUE if the given operator is one of the operators that is
** allowed for an indexable WHERE clause term. The allowed operators are
** "=", "<", ">", "<=", ">=", and "IN".
**
** IMPLEMENTATION-OF: R-59926-26393 To be usable by an index a term must be
** of one of the following forms: column = expression column > expression
** column >= expression column < expression column <= expression
** expression = column expression > column expression >= column
** expression < column expression <= column column IN
** (expression-list) column IN (subquery) column IS NULL
*/
static bool allowedOp(int op)
{
Debug.Assert(TK_GT > TK_EQ && TK_GT < TK_GE);
Debug.Assert(TK_LT > TK_EQ && TK_LT < TK_GE);
Debug.Assert(TK_LE > TK_EQ && TK_LE < TK_GE);
Debug.Assert(TK_GE == TK_EQ + 4);
return op == TK_IN || (op >= TK_EQ && op <= TK_GE) || op == TK_ISNULL;
}
/*
** Swap two objects of type TYPE.
*/
//#define SWAP(TYPE,A,B) {TYPE t=A; A=B; B=t;}
/*
** Commute a comparison operator. Expressions of the form "X op Y"
** are converted into "Y op X".
**
** If a collation sequence is Debug.Associated with either the left or right
** side of the comparison, it remains Debug.Associated with the same side after
** the commutation. So "Y collate NOCASE op X" becomes
** "X collate NOCASE op Y". This is because any collation sequence on
** the left hand side of a comparison overrides any collation sequence
** attached to the right. For the same reason the EP_ExpCollate flag
** is not commuted.
*/
static void exprCommute(Parse pParse, Expr pExpr)
{
u16 expRight = (u16)(pExpr.pRight.flags & EP_ExpCollate);
u16 expLeft = (u16)(pExpr.pLeft.flags & EP_ExpCollate);
Debug.Assert(allowedOp(pExpr.op) && pExpr.op != TK_IN);
pExpr.pRight.pColl = sqlite3ExprCollSeq(pParse, pExpr.pRight);
pExpr.pLeft.pColl = sqlite3ExprCollSeq(pParse, pExpr.pLeft);
SWAP(ref pExpr.pRight.pColl, ref pExpr.pLeft.pColl);
pExpr.pRight.flags = (u16)((pExpr.pRight.flags & ~EP_ExpCollate) | expLeft);
pExpr.pLeft.flags = (u16)((pExpr.pLeft.flags & ~EP_ExpCollate) | expRight);
SWAP(ref pExpr.pRight, ref pExpr.pLeft);
if (pExpr.op >= TK_GT)
{
Debug.Assert(TK_LT == TK_GT + 2);
Debug.Assert(TK_GE == TK_LE + 2);
Debug.Assert(TK_GT > TK_EQ);
Debug.Assert(TK_GT < TK_LE);
Debug.Assert(pExpr.op >= TK_GT && pExpr.op <= TK_GE);
pExpr.op = (u8)(((pExpr.op - TK_GT) ^ 2) + TK_GT);
}
}
/*
** Translate from TK_xx operator to WO_xx bitmask.
*/
static u16 operatorMask(int op)
{
u16 c;
Debug.Assert(allowedOp(op));
if (op == TK_IN)
{
c = WO_IN;
}
else if (op == TK_ISNULL)
{
c = WO_ISNULL;
}
else
{
Debug.Assert((WO_EQ << (op - TK_EQ)) < 0x7fff);
c = (u16)(WO_EQ << (op - TK_EQ));
}
Debug.Assert(op != TK_ISNULL || c == WO_ISNULL);
Debug.Assert(op != TK_IN || c == WO_IN);
Debug.Assert(op != TK_EQ || c == WO_EQ);
Debug.Assert(op != TK_LT || c == WO_LT);
Debug.Assert(op != TK_LE || c == WO_LE);
Debug.Assert(op != TK_GT || c == WO_GT);
Debug.Assert(op != TK_GE || c == WO_GE);
return c;
}
/*
** 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 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.
*/
static WhereTerm findTerm(
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 pTerm;
int k;
Debug.Assert(iCur >= 0);
op &= WO_ALL;
for (k = pWC.nTerm; k != 0; k--)//, pTerm++)
{
pTerm = pWC.a[pWC.nTerm - k];
if (pTerm.leftCursor == iCur
&& (pTerm.prereqRight & notReady) == 0
&& pTerm.u.leftColumn == iColumn
&& (pTerm.eOperator & op) != 0
)
{
if (pIdx != null && pTerm.eOperator != WO_ISNULL)
{
Expr pX = pTerm.pExpr;
CollSeq pColl;
char idxaff;
int j;
Parse pParse = pWC.pParse;
idxaff = pIdx.pTable.aCol[iColumn].affinity;
if (!sqlite3IndexAffinityOk(pX, idxaff))
continue;
/* Figure out the collation sequence required from an index for
** it to be useful for optimising expression pX. Store this
** value in variable pColl.
*/
Debug.Assert(pX.pLeft != null);
pColl = sqlite3BinaryCompareCollSeq(pParse, pX.pLeft, pX.pRight);
Debug.Assert(pColl != null || pParse.nErr != 0);
for (j = 0; pIdx.aiColumn[j] != iColumn; j++)
{
if (NEVER(j >= pIdx.nColumn))
return null;
}
if (pColl != null && !pColl.zName.Equals(pIdx.azColl[j], StringComparison.InvariantCultureIgnoreCase))
continue;
}
return pTerm;
}
}
return null;
}
/* Forward reference */
//static void exprAnalyze(SrcList*, WhereClause*, int);
/*
** Call exprAnalyze on all terms in a WHERE clause.
**
**
*/
static void exprAnalyzeAll(
SrcList pTabList, /* the FROM clause */
WhereClause pWC /* the WHERE clause to be analyzed */
)
{
int i;
for (i = pWC.nTerm - 1; i >= 0; i--)
{
exprAnalyze(pTabList, pWC, i);
}
}
#if !SQLITE_OMIT_LIKE_OPTIMIZATION
/*
** Check to see if the given expression is a LIKE or GLOB operator that
** can be optimized using inequality constraints. Return TRUE if it is
** so and false if not.
**
** In order for the operator to be optimizible, the RHS must be a string
** literal that does not begin with a wildcard.
*/
static int isLikeOrGlob(
Parse pParse, /* Parsing and code generating context */
Expr pExpr, /* Test this expression */
ref Expr ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
ref bool pisComplete, /* True if the only wildcard is % in the last character */
ref bool pnoCase /* True if uppercase is equivalent to lowercase */
)
{
string z = null; /* String on RHS of LIKE operator */
Expr pRight, pLeft; /* Right and left size of LIKE operator */
ExprList pList; /* List of operands to the LIKE operator */
int c = 0; /* One character in z[] */
int cnt; /* Number of non-wildcard prefix characters */
char[] wc = new char[3]; /* Wildcard characters */
sqlite3 db = pParse.db; /* Data_base connection */
sqlite3_value pVal = null;
int op; /* Opcode of pRight */
if (!sqlite3IsLikeFunction(db, pExpr, ref pnoCase, wc))
{
return 0;
}
//#if SQLITE_EBCDIC
//if( pnoCase ) return 0;
//#endif
pList = pExpr.x.pList;
pLeft = pList.a[1].pExpr;
if (pLeft.op != TK_COLUMN || sqlite3ExprAffinity(pLeft) != SQLITE_AFF_TEXT)
{
/* IMP: R-02065-49465 The left-hand side of the LIKE or GLOB operator must
** be the name of an indexed column with TEXT affinity. */
return 0;
}
Debug.Assert(pLeft.iColumn != (-1)); /* Because IPK never has AFF_TEXT */
pRight = pList.a[0].pExpr;
op = pRight.op;
if (op == TK_REGISTER)
{
op = pRight.op2;
}
if (op == TK_VARIABLE)
{
Vdbe pReprepare = pParse.pReprepare;
int iCol = pRight.iColumn;
pVal = sqlite3VdbeGetValue(pReprepare, iCol, (byte)SQLITE_AFF_NONE);
if (pVal != null && sqlite3_value_type(pVal) == SQLITE_TEXT)
{
z = sqlite3_value_text(pVal);
}
sqlite3VdbeSetVarmask(pParse.pVdbe, iCol); /* IMP: R-23257-02778 */
Debug.Assert(pRight.op == TK_VARIABLE || pRight.op == TK_REGISTER);
}
else if (op == TK_STRING)
{
z = pRight.u.zToken;
}
if (!String.IsNullOrEmpty(z))
{
cnt = 0;
while (cnt < z.Length && (c = z[cnt]) != 0 && c != wc[0] && c != wc[1] && c != wc[2])
{
cnt++;
}
if (cnt != 0 && 255 != (u8)z[cnt - 1])
{
Expr pPrefix;
pisComplete = c == wc[0] && cnt == z.Length - 1;
pPrefix = sqlite3Expr(db, TK_STRING, z);
if (pPrefix != null)
pPrefix.u.zToken = pPrefix.u.zToken.Substring(0, cnt);
ppPrefix = pPrefix;
if (op == TK_VARIABLE)
{
Vdbe v = pParse.pVdbe;
sqlite3VdbeSetVarmask(v, pRight.iColumn); /* IMP: R-23257-02778 */
if (pisComplete && pRight.u.zToken.Length > 1)
{
/* If the rhs of the LIKE expression is a variable, and the current
** value of the variable means there is no need to invoke the LIKE
** function, then no OP_Variable will be added to the program.
** This causes problems for the sqlite3_bind_parameter_name()
** API. To workaround them, add a dummy OP_Variable here.
*/
int r1 = sqlite3GetTempReg(pParse);
sqlite3ExprCodeTarget(pParse, pRight, r1);
sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v) - 1, 0);
sqlite3ReleaseTempReg(pParse, r1);
}
}
}
else
{
z = null;
}
}
sqlite3ValueFree(ref pVal);
return (z != null) ? 1 : 0;
}
#endif //* SQLITE_OMIT_LIKE_OPTIMIZATION */
#if !SQLITE_OMIT_VIRTUALTABLE
/*
** Check to see if the given expression is of the form
**
** column MATCH expr
**
** If it is then return TRUE. If not, return FALSE.
*/
static int isMatchOfColumn(
Expr pExpr /* Test this expression */
)
{
ExprList pList;
if (pExpr.op != TK_FUNCTION)
{
return 0;
}
if (!pExpr.u.zToken.Equals("match", StringComparison.InvariantCultureIgnoreCase))
{
return 0;
}
pList = pExpr.x.pList;
if (pList.nExpr != 2)
{
return 0;
}
if (pList.a[1].pExpr.op != TK_COLUMN)
{
return 0;
}
return 1;
}
#endif //* SQLITE_OMIT_VIRTUALTABLE */
/*
** If the pBase expression originated in the ON or USING clause of
** a join, then transfer the appropriate markings over to derived.
*/
static void transferJoinMarkings(Expr pDerived, Expr pBase)
{
pDerived.flags = (u16)(pDerived.flags | pBase.flags & EP_FromJoin);
pDerived.iRightJoinTable = pBase.iRightJoinTable;
}
#if !(SQLITE_OMIT_OR_OPTIMIZATION) && !(SQLITE_OMIT_SUBQUERY)
/*
** Analyze a term that consists of two or more OR-connected
** subterms. So in:
**
** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
** ^^^^^^^^^^^^^^^^^^^^
**
** This routine analyzes terms such as the middle term in the above example.
** A WhereOrTerm object is computed and attached to the term under
** analysis, regardless of the outcome of the analysis. Hence:
**
** WhereTerm.wtFlags |= TERM_ORINFO
** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
**
** The term being analyzed must have two or more of OR-connected subterms.
** A single subterm might be a set of AND-connected sub-subterms.
** Examples of terms under analysis:
**
** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
** (B) x=expr1 OR expr2=x OR x=expr3
** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
**
** CASE 1:
**
** If all subterms are of the form T.C=expr for some single column of C
** a single table T (as shown in example B above) then create a new virtual
** term that is an equivalent IN expression. In other words, if the term
** being analyzed is:
**
** x = expr1 OR expr2 = x OR x = expr3
**
** then create a new virtual term like this:
**
** x IN (expr1,expr2,expr3)
**
** CASE 2:
**
** If all subterms are indexable by a single table T, then set
**
** WhereTerm.eOperator = WO_OR
** WhereTerm.u.pOrInfo.indexable |= the cursor number for table T
**
** A subterm is "indexable" if it is of the form
** "T.C <op> <expr>" where C is any column of table T and
** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
** A subterm is also indexable if it is an AND of two or more
** subsubterms at least one of which is indexable. Indexable AND
** subterms have their eOperator set to WO_AND and they have
** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
**
** From another point of view, "indexable" means that the subterm could
** potentially be used with an index if an appropriate index exists.
** This analysis does not consider whether or not the index exists; that
** is something the bestIndex() routine will determine. This analysis
** only looks at whether subterms appropriate for indexing exist.
**
** All examples A through E above all satisfy case 2. But if a term
** also statisfies case 1 (such as B) we know that the optimizer will
** always prefer case 1, so in that case we pretend that case 2 is not
** satisfied.
**
** It might be the case that multiple tables are indexable. For example,
** (E) above is indexable on tables P, Q, and R.