blob: 3625efa1e368679b43f202de1b51d39976680781 [file] [log] [blame]
drh6c1f4ef2015-06-08 14:23:15 +00001/*
2** 2015-06-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 module contains C code that generates VDBE code used to process
13** the WHERE clause of SQL statements.
14**
15** This file was originally part of where.c but was split out to improve
16** readability and editabiliity. This file contains utility routines for
17** analyzing Expr objects in the WHERE clause.
18*/
19#include "sqliteInt.h"
20#include "whereInt.h"
21
22/* Forward declarations */
23static void exprAnalyze(SrcList*, WhereClause*, int);
24
25/*
26** Deallocate all memory associated with a WhereOrInfo object.
27*/
28static void whereOrInfoDelete(sqlite3 *db, WhereOrInfo *p){
29 sqlite3WhereClauseClear(&p->wc);
30 sqlite3DbFree(db, p);
31}
32
33/*
34** Deallocate all memory associated with a WhereAndInfo object.
35*/
36static void whereAndInfoDelete(sqlite3 *db, WhereAndInfo *p){
37 sqlite3WhereClauseClear(&p->wc);
38 sqlite3DbFree(db, p);
39}
40
41/*
42** Add a single new WhereTerm entry to the WhereClause object pWC.
43** The new WhereTerm object is constructed from Expr p and with wtFlags.
44** The index in pWC->a[] of the new WhereTerm is returned on success.
45** 0 is returned if the new WhereTerm could not be added due to a memory
46** allocation error. The memory allocation failure will be recorded in
47** the db->mallocFailed flag so that higher-level functions can detect it.
48**
49** This routine will increase the size of the pWC->a[] array as necessary.
50**
51** If the wtFlags argument includes TERM_DYNAMIC, then responsibility
52** for freeing the expression p is assumed by the WhereClause object pWC.
53** This is true even if this routine fails to allocate a new WhereTerm.
54**
55** WARNING: This routine might reallocate the space used to store
56** WhereTerms. All pointers to WhereTerms should be invalidated after
57** calling this routine. Such pointers may be reinitialized by referencing
58** the pWC->a[] array.
59*/
60static int whereClauseInsert(WhereClause *pWC, Expr *p, u16 wtFlags){
61 WhereTerm *pTerm;
62 int idx;
63 testcase( wtFlags & TERM_VIRTUAL );
64 if( pWC->nTerm>=pWC->nSlot ){
65 WhereTerm *pOld = pWC->a;
66 sqlite3 *db = pWC->pWInfo->pParse->db;
drh575fad62016-02-05 13:38:36 +000067 pWC->a = sqlite3DbMallocRawNN(db, sizeof(pWC->a[0])*pWC->nSlot*2 );
drh6c1f4ef2015-06-08 14:23:15 +000068 if( pWC->a==0 ){
69 if( wtFlags & TERM_DYNAMIC ){
70 sqlite3ExprDelete(db, p);
71 }
72 pWC->a = pOld;
73 return 0;
74 }
75 memcpy(pWC->a, pOld, sizeof(pWC->a[0])*pWC->nTerm);
76 if( pOld!=pWC->aStatic ){
77 sqlite3DbFree(db, pOld);
78 }
79 pWC->nSlot = sqlite3DbMallocSize(db, pWC->a)/sizeof(pWC->a[0]);
drh6c1f4ef2015-06-08 14:23:15 +000080 }
81 pTerm = &pWC->a[idx = pWC->nTerm++];
82 if( p && ExprHasProperty(p, EP_Unlikely) ){
83 pTerm->truthProb = sqlite3LogEst(p->iTable) - 270;
84 }else{
85 pTerm->truthProb = 1;
86 }
87 pTerm->pExpr = sqlite3ExprSkipCollate(p);
88 pTerm->wtFlags = wtFlags;
89 pTerm->pWC = pWC;
90 pTerm->iParent = -1;
drh87c05f02016-10-03 14:44:47 +000091 memset(&pTerm->eOperator, 0,
92 sizeof(WhereTerm) - offsetof(WhereTerm,eOperator));
drh6c1f4ef2015-06-08 14:23:15 +000093 return idx;
94}
95
96/*
97** Return TRUE if the given operator is one of the operators that is
98** allowed for an indexable WHERE clause term. The allowed operators are
dan71c57db2016-07-09 20:23:55 +000099** "=", "<", ">", "<=", ">=", "IN", "IS", and "IS NULL"
drh6c1f4ef2015-06-08 14:23:15 +0000100*/
101static int allowedOp(int op){
102 assert( TK_GT>TK_EQ && TK_GT<TK_GE );
103 assert( TK_LT>TK_EQ && TK_LT<TK_GE );
104 assert( TK_LE>TK_EQ && TK_LE<TK_GE );
105 assert( TK_GE==TK_EQ+4 );
106 return op==TK_IN || (op>=TK_EQ && op<=TK_GE) || op==TK_ISNULL || op==TK_IS;
107}
108
109/*
110** Commute a comparison operator. Expressions of the form "X op Y"
111** are converted into "Y op X".
112**
113** If left/right precedence rules come into play when determining the
114** collating sequence, then COLLATE operators are adjusted to ensure
115** that the collating sequence does not change. For example:
116** "Y collate NOCASE op X" becomes "X op Y" because any collation sequence on
117** the left hand side of a comparison overrides any collation sequence
118** attached to the right. For the same reason the EP_Collate flag
119** is not commuted.
120*/
121static void exprCommute(Parse *pParse, Expr *pExpr){
122 u16 expRight = (pExpr->pRight->flags & EP_Collate);
123 u16 expLeft = (pExpr->pLeft->flags & EP_Collate);
124 assert( allowedOp(pExpr->op) && pExpr->op!=TK_IN );
125 if( expRight==expLeft ){
126 /* Either X and Y both have COLLATE operator or neither do */
127 if( expRight ){
128 /* Both X and Y have COLLATE operators. Make sure X is always
129 ** used by clearing the EP_Collate flag from Y. */
130 pExpr->pRight->flags &= ~EP_Collate;
131 }else if( sqlite3ExprCollSeq(pParse, pExpr->pLeft)!=0 ){
132 /* Neither X nor Y have COLLATE operators, but X has a non-default
133 ** collating sequence. So add the EP_Collate marker on X to cause
134 ** it to be searched first. */
135 pExpr->pLeft->flags |= EP_Collate;
136 }
137 }
138 SWAP(Expr*,pExpr->pRight,pExpr->pLeft);
139 if( pExpr->op>=TK_GT ){
140 assert( TK_LT==TK_GT+2 );
141 assert( TK_GE==TK_LE+2 );
142 assert( TK_GT>TK_EQ );
143 assert( TK_GT<TK_LE );
144 assert( pExpr->op>=TK_GT && pExpr->op<=TK_GE );
145 pExpr->op = ((pExpr->op-TK_GT)^2)+TK_GT;
146 }
147}
148
149/*
150** Translate from TK_xx operator to WO_xx bitmask.
151*/
152static u16 operatorMask(int op){
153 u16 c;
154 assert( allowedOp(op) );
155 if( op==TK_IN ){
156 c = WO_IN;
157 }else if( op==TK_ISNULL ){
158 c = WO_ISNULL;
159 }else if( op==TK_IS ){
160 c = WO_IS;
161 }else{
162 assert( (WO_EQ<<(op-TK_EQ)) < 0x7fff );
163 c = (u16)(WO_EQ<<(op-TK_EQ));
164 }
165 assert( op!=TK_ISNULL || c==WO_ISNULL );
166 assert( op!=TK_IN || c==WO_IN );
167 assert( op!=TK_EQ || c==WO_EQ );
168 assert( op!=TK_LT || c==WO_LT );
169 assert( op!=TK_LE || c==WO_LE );
170 assert( op!=TK_GT || c==WO_GT );
171 assert( op!=TK_GE || c==WO_GE );
172 assert( op!=TK_IS || c==WO_IS );
173 return c;
174}
175
176
177#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
178/*
179** Check to see if the given expression is a LIKE or GLOB operator that
180** can be optimized using inequality constraints. Return TRUE if it is
181** so and false if not.
182**
183** In order for the operator to be optimizible, the RHS must be a string
184** literal that does not begin with a wildcard. The LHS must be a column
185** that may only be NULL, a string, or a BLOB, never a number. (This means
186** that virtual tables cannot participate in the LIKE optimization.) The
187** collating sequence for the column on the LHS must be appropriate for
188** the operator.
189*/
190static int isLikeOrGlob(
191 Parse *pParse, /* Parsing and code generating context */
192 Expr *pExpr, /* Test this expression */
193 Expr **ppPrefix, /* Pointer to TK_STRING expression with pattern prefix */
194 int *pisComplete, /* True if the only wildcard is % in the last character */
195 int *pnoCase /* True if uppercase is equivalent to lowercase */
196){
197 const char *z = 0; /* String on RHS of LIKE operator */
198 Expr *pRight, *pLeft; /* Right and left size of LIKE operator */
199 ExprList *pList; /* List of operands to the LIKE operator */
200 int c; /* One character in z[] */
201 int cnt; /* Number of non-wildcard prefix characters */
202 char wc[3]; /* Wildcard characters */
203 sqlite3 *db = pParse->db; /* Database connection */
204 sqlite3_value *pVal = 0;
205 int op; /* Opcode of pRight */
drhb8763632016-01-19 17:54:21 +0000206 int rc; /* Result code to return */
drh6c1f4ef2015-06-08 14:23:15 +0000207
208 if( !sqlite3IsLikeFunction(db, pExpr, pnoCase, wc) ){
209 return 0;
210 }
211#ifdef SQLITE_EBCDIC
212 if( *pnoCase ) return 0;
213#endif
214 pList = pExpr->x.pList;
215 pLeft = pList->a[1].pExpr;
drh6c1f4ef2015-06-08 14:23:15 +0000216
217 pRight = sqlite3ExprSkipCollate(pList->a[0].pExpr);
218 op = pRight->op;
219 if( op==TK_VARIABLE ){
220 Vdbe *pReprepare = pParse->pReprepare;
221 int iCol = pRight->iColumn;
222 pVal = sqlite3VdbeGetBoundValue(pReprepare, iCol, SQLITE_AFF_BLOB);
223 if( pVal && sqlite3_value_type(pVal)==SQLITE_TEXT ){
224 z = (char *)sqlite3_value_text(pVal);
225 }
226 sqlite3VdbeSetVarmask(pParse->pVdbe, iCol);
227 assert( pRight->op==TK_VARIABLE || pRight->op==TK_REGISTER );
228 }else if( op==TK_STRING ){
229 z = pRight->u.zToken;
230 }
231 if( z ){
drh1c84bd42017-02-10 21:37:57 +0000232
233 /* If the RHS begins with a digit or a minus sign, then the LHS must
234 ** be an ordinary column (not a virtual table column) with TEXT affinity.
235 ** Otherwise the LHS might be numeric and "lhs >= rhs" would be false
236 ** even though "lhs LIKE rhs" is true. But if the RHS does not start
237 ** with a digit or '-', then "lhs LIKE rhs" will always be false if
238 ** the LHS is numeric and so the optimization still works.
239 */
240 if( sqlite3Isdigit(z[0]) || z[0]=='-' ){
241 if( pLeft->op!=TK_COLUMN
242 || sqlite3ExprAffinity(pLeft)!=SQLITE_AFF_TEXT
243 || IsVirtual(pLeft->pTab) /* Value might be numeric */
244 ){
245 sqlite3ValueFree(pVal);
246 return 0;
247 }
248 }
drh6c1f4ef2015-06-08 14:23:15 +0000249 cnt = 0;
250 while( (c=z[cnt])!=0 && c!=wc[0] && c!=wc[1] && c!=wc[2] ){
251 cnt++;
252 }
253 if( cnt!=0 && 255!=(u8)z[cnt-1] ){
254 Expr *pPrefix;
255 *pisComplete = c==wc[0] && z[cnt+1]==0;
256 pPrefix = sqlite3Expr(db, TK_STRING, z);
257 if( pPrefix ) pPrefix->u.zToken[cnt] = 0;
258 *ppPrefix = pPrefix;
259 if( op==TK_VARIABLE ){
260 Vdbe *v = pParse->pVdbe;
261 sqlite3VdbeSetVarmask(v, pRight->iColumn);
262 if( *pisComplete && pRight->u.zToken[1] ){
263 /* If the rhs of the LIKE expression is a variable, and the current
264 ** value of the variable means there is no need to invoke the LIKE
265 ** function, then no OP_Variable will be added to the program.
266 ** This causes problems for the sqlite3_bind_parameter_name()
267 ** API. To work around them, add a dummy OP_Variable here.
268 */
269 int r1 = sqlite3GetTempReg(pParse);
270 sqlite3ExprCodeTarget(pParse, pRight, r1);
271 sqlite3VdbeChangeP3(v, sqlite3VdbeCurrentAddr(v)-1, 0);
272 sqlite3ReleaseTempReg(pParse, r1);
273 }
274 }
275 }else{
276 z = 0;
277 }
278 }
279
drhb8763632016-01-19 17:54:21 +0000280 rc = (z!=0);
drh6c1f4ef2015-06-08 14:23:15 +0000281 sqlite3ValueFree(pVal);
drhb8763632016-01-19 17:54:21 +0000282 return rc;
drh6c1f4ef2015-06-08 14:23:15 +0000283}
284#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
285
286
287#ifndef SQLITE_OMIT_VIRTUALTABLE
288/*
289** Check to see if the given expression is of the form
290**
dan43970dd2015-11-24 17:39:01 +0000291** column OP expr
292**
293** where OP is one of MATCH, GLOB, LIKE or REGEXP and "column" is a
294** column of a virtual table.
drh6c1f4ef2015-06-08 14:23:15 +0000295**
296** If it is then return TRUE. If not, return FALSE.
297*/
298static int isMatchOfColumn(
dan07bdba82015-11-23 21:09:54 +0000299 Expr *pExpr, /* Test this expression */
300 unsigned char *peOp2 /* OUT: 0 for MATCH, or else an op2 value */
drh6c1f4ef2015-06-08 14:23:15 +0000301){
drhe104dd32016-08-10 19:43:29 +0000302 static const struct Op2 {
dan07bdba82015-11-23 21:09:54 +0000303 const char *zOp;
304 unsigned char eOp2;
305 } aOp[] = {
dan43970dd2015-11-24 17:39:01 +0000306 { "match", SQLITE_INDEX_CONSTRAINT_MATCH },
307 { "glob", SQLITE_INDEX_CONSTRAINT_GLOB },
308 { "like", SQLITE_INDEX_CONSTRAINT_LIKE },
309 { "regexp", SQLITE_INDEX_CONSTRAINT_REGEXP }
dan07bdba82015-11-23 21:09:54 +0000310 };
drh6c1f4ef2015-06-08 14:23:15 +0000311 ExprList *pList;
dan43970dd2015-11-24 17:39:01 +0000312 Expr *pCol; /* Column reference */
dan07bdba82015-11-23 21:09:54 +0000313 int i;
drh6c1f4ef2015-06-08 14:23:15 +0000314
315 if( pExpr->op!=TK_FUNCTION ){
316 return 0;
317 }
drh6c1f4ef2015-06-08 14:23:15 +0000318 pList = pExpr->x.pList;
danff7b22b2015-11-24 18:16:15 +0000319 if( pList==0 || pList->nExpr!=2 ){
drh6c1f4ef2015-06-08 14:23:15 +0000320 return 0;
321 }
dan43970dd2015-11-24 17:39:01 +0000322 pCol = pList->a[1].pExpr;
323 if( pCol->op!=TK_COLUMN || !IsVirtual(pCol->pTab) ){
drh6c1f4ef2015-06-08 14:23:15 +0000324 return 0;
325 }
dan07bdba82015-11-23 21:09:54 +0000326 for(i=0; i<ArraySize(aOp); i++){
327 if( sqlite3StrICmp(pExpr->u.zToken, aOp[i].zOp)==0 ){
328 *peOp2 = aOp[i].eOp2;
329 return 1;
330 }
331 }
332 return 0;
drh6c1f4ef2015-06-08 14:23:15 +0000333}
334#endif /* SQLITE_OMIT_VIRTUALTABLE */
335
336/*
337** If the pBase expression originated in the ON or USING clause of
338** a join, then transfer the appropriate markings over to derived.
339*/
340static void transferJoinMarkings(Expr *pDerived, Expr *pBase){
341 if( pDerived ){
342 pDerived->flags |= pBase->flags & EP_FromJoin;
343 pDerived->iRightJoinTable = pBase->iRightJoinTable;
344 }
345}
346
347/*
348** Mark term iChild as being a child of term iParent
349*/
350static void markTermAsChild(WhereClause *pWC, int iChild, int iParent){
351 pWC->a[iChild].iParent = iParent;
352 pWC->a[iChild].truthProb = pWC->a[iParent].truthProb;
353 pWC->a[iParent].nChild++;
354}
355
356/*
357** Return the N-th AND-connected subterm of pTerm. Or if pTerm is not
358** a conjunction, then return just pTerm when N==0. If N is exceeds
359** the number of available subterms, return NULL.
360*/
361static WhereTerm *whereNthSubterm(WhereTerm *pTerm, int N){
362 if( pTerm->eOperator!=WO_AND ){
363 return N==0 ? pTerm : 0;
364 }
365 if( N<pTerm->u.pAndInfo->wc.nTerm ){
366 return &pTerm->u.pAndInfo->wc.a[N];
367 }
368 return 0;
369}
370
371/*
372** Subterms pOne and pTwo are contained within WHERE clause pWC. The
373** two subterms are in disjunction - they are OR-ed together.
374**
375** If these two terms are both of the form: "A op B" with the same
376** A and B values but different operators and if the operators are
377** compatible (if one is = and the other is <, for example) then
378** add a new virtual AND term to pWC that is the combination of the
379** two.
380**
381** Some examples:
382**
383** x<y OR x=y --> x<=y
384** x=y OR x=y --> x=y
385** x<=y OR x<y --> x<=y
386**
387** The following is NOT generated:
388**
389** x<y OR x>y --> x!=y
390*/
391static void whereCombineDisjuncts(
392 SrcList *pSrc, /* the FROM clause */
393 WhereClause *pWC, /* The complete WHERE clause */
394 WhereTerm *pOne, /* First disjunct */
395 WhereTerm *pTwo /* Second disjunct */
396){
397 u16 eOp = pOne->eOperator | pTwo->eOperator;
398 sqlite3 *db; /* Database connection (for malloc) */
399 Expr *pNew; /* New virtual expression */
400 int op; /* Operator for the combined expression */
401 int idxNew; /* Index in pWC of the next virtual term */
402
403 if( (pOne->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
404 if( (pTwo->eOperator & (WO_EQ|WO_LT|WO_LE|WO_GT|WO_GE))==0 ) return;
405 if( (eOp & (WO_EQ|WO_LT|WO_LE))!=eOp
406 && (eOp & (WO_EQ|WO_GT|WO_GE))!=eOp ) return;
407 assert( pOne->pExpr->pLeft!=0 && pOne->pExpr->pRight!=0 );
408 assert( pTwo->pExpr->pLeft!=0 && pTwo->pExpr->pRight!=0 );
409 if( sqlite3ExprCompare(pOne->pExpr->pLeft, pTwo->pExpr->pLeft, -1) ) return;
410 if( sqlite3ExprCompare(pOne->pExpr->pRight, pTwo->pExpr->pRight, -1) )return;
411 /* If we reach this point, it means the two subterms can be combined */
412 if( (eOp & (eOp-1))!=0 ){
413 if( eOp & (WO_LT|WO_LE) ){
414 eOp = WO_LE;
415 }else{
416 assert( eOp & (WO_GT|WO_GE) );
417 eOp = WO_GE;
418 }
419 }
420 db = pWC->pWInfo->pParse->db;
421 pNew = sqlite3ExprDup(db, pOne->pExpr, 0);
422 if( pNew==0 ) return;
423 for(op=TK_EQ; eOp!=(WO_EQ<<(op-TK_EQ)); op++){ assert( op<TK_GE ); }
424 pNew->op = op;
425 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
426 exprAnalyze(pSrc, pWC, idxNew);
427}
428
429#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
430/*
431** Analyze a term that consists of two or more OR-connected
432** subterms. So in:
433**
434** ... WHERE (a=5) AND (b=7 OR c=9 OR d=13) AND (d=13)
435** ^^^^^^^^^^^^^^^^^^^^
436**
437** This routine analyzes terms such as the middle term in the above example.
438** A WhereOrTerm object is computed and attached to the term under
439** analysis, regardless of the outcome of the analysis. Hence:
440**
441** WhereTerm.wtFlags |= TERM_ORINFO
442** WhereTerm.u.pOrInfo = a dynamically allocated WhereOrTerm object
443**
444** The term being analyzed must have two or more of OR-connected subterms.
445** A single subterm might be a set of AND-connected sub-subterms.
446** Examples of terms under analysis:
447**
448** (A) t1.x=t2.y OR t1.x=t2.z OR t1.y=15 OR t1.z=t3.a+5
449** (B) x=expr1 OR expr2=x OR x=expr3
450** (C) t1.x=t2.y OR (t1.x=t2.z AND t1.y=15)
451** (D) x=expr1 OR (y>11 AND y<22 AND z LIKE '*hello*')
452** (E) (p.a=1 AND q.b=2 AND r.c=3) OR (p.x=4 AND q.y=5 AND r.z=6)
453** (F) x>A OR (x=A AND y>=B)
454**
455** CASE 1:
456**
457** If all subterms are of the form T.C=expr for some single column of C and
458** a single table T (as shown in example B above) then create a new virtual
459** term that is an equivalent IN expression. In other words, if the term
460** being analyzed is:
461**
462** x = expr1 OR expr2 = x OR x = expr3
463**
464** then create a new virtual term like this:
465**
466** x IN (expr1,expr2,expr3)
467**
468** CASE 2:
469**
470** If there are exactly two disjuncts and one side has x>A and the other side
471** has x=A (for the same x and A) then add a new virtual conjunct term to the
472** WHERE clause of the form "x>=A". Example:
473**
474** x>A OR (x=A AND y>B) adds: x>=A
475**
476** The added conjunct can sometimes be helpful in query planning.
477**
478** CASE 3:
479**
480** If all subterms are indexable by a single table T, then set
481**
482** WhereTerm.eOperator = WO_OR
483** WhereTerm.u.pOrInfo->indexable |= the cursor number for table T
484**
485** A subterm is "indexable" if it is of the form
486** "T.C <op> <expr>" where C is any column of table T and
487** <op> is one of "=", "<", "<=", ">", ">=", "IS NULL", or "IN".
488** A subterm is also indexable if it is an AND of two or more
489** subsubterms at least one of which is indexable. Indexable AND
490** subterms have their eOperator set to WO_AND and they have
491** u.pAndInfo set to a dynamically allocated WhereAndTerm object.
492**
493** From another point of view, "indexable" means that the subterm could
494** potentially be used with an index if an appropriate index exists.
495** This analysis does not consider whether or not the index exists; that
496** is decided elsewhere. This analysis only looks at whether subterms
497** appropriate for indexing exist.
498**
499** All examples A through E above satisfy case 3. But if a term
500** also satisfies case 1 (such as B) we know that the optimizer will
501** always prefer case 1, so in that case we pretend that case 3 is not
502** satisfied.
503**
504** It might be the case that multiple tables are indexable. For example,
505** (E) above is indexable on tables P, Q, and R.
506**
507** Terms that satisfy case 3 are candidates for lookup by using
508** separate indices to find rowids for each subterm and composing
509** the union of all rowids using a RowSet object. This is similar
510** to "bitmap indices" in other database engines.
511**
512** OTHERWISE:
513**
514** If none of cases 1, 2, or 3 apply, then leave the eOperator set to
515** zero. This term is not useful for search.
516*/
517static void exprAnalyzeOrTerm(
518 SrcList *pSrc, /* the FROM clause */
519 WhereClause *pWC, /* the complete WHERE clause */
520 int idxTerm /* Index of the OR-term to be analyzed */
521){
522 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
523 Parse *pParse = pWInfo->pParse; /* Parser context */
524 sqlite3 *db = pParse->db; /* Database connection */
525 WhereTerm *pTerm = &pWC->a[idxTerm]; /* The term to be analyzed */
526 Expr *pExpr = pTerm->pExpr; /* The expression of the term */
527 int i; /* Loop counters */
528 WhereClause *pOrWc; /* Breakup of pTerm into subterms */
529 WhereTerm *pOrTerm; /* A Sub-term within the pOrWc */
530 WhereOrInfo *pOrInfo; /* Additional information associated with pTerm */
531 Bitmask chngToIN; /* Tables that might satisfy case 1 */
532 Bitmask indexable; /* Tables that are indexable, satisfying case 2 */
533
534 /*
535 ** Break the OR clause into its separate subterms. The subterms are
536 ** stored in a WhereClause structure containing within the WhereOrInfo
537 ** object that is attached to the original OR clause term.
538 */
539 assert( (pTerm->wtFlags & (TERM_DYNAMIC|TERM_ORINFO|TERM_ANDINFO))==0 );
540 assert( pExpr->op==TK_OR );
541 pTerm->u.pOrInfo = pOrInfo = sqlite3DbMallocZero(db, sizeof(*pOrInfo));
542 if( pOrInfo==0 ) return;
543 pTerm->wtFlags |= TERM_ORINFO;
544 pOrWc = &pOrInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000545 memset(pOrWc->aStatic, 0, sizeof(pOrWc->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000546 sqlite3WhereClauseInit(pOrWc, pWInfo);
547 sqlite3WhereSplit(pOrWc, pExpr, TK_OR);
548 sqlite3WhereExprAnalyze(pSrc, pOrWc);
549 if( db->mallocFailed ) return;
550 assert( pOrWc->nTerm>=2 );
551
552 /*
553 ** Compute the set of tables that might satisfy cases 1 or 3.
554 */
555 indexable = ~(Bitmask)0;
556 chngToIN = ~(Bitmask)0;
557 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0 && indexable; i--, pOrTerm++){
558 if( (pOrTerm->eOperator & WO_SINGLE)==0 ){
559 WhereAndInfo *pAndInfo;
560 assert( (pOrTerm->wtFlags & (TERM_ANDINFO|TERM_ORINFO))==0 );
561 chngToIN = 0;
drh575fad62016-02-05 13:38:36 +0000562 pAndInfo = sqlite3DbMallocRawNN(db, sizeof(*pAndInfo));
drh6c1f4ef2015-06-08 14:23:15 +0000563 if( pAndInfo ){
564 WhereClause *pAndWC;
565 WhereTerm *pAndTerm;
566 int j;
567 Bitmask b = 0;
568 pOrTerm->u.pAndInfo = pAndInfo;
569 pOrTerm->wtFlags |= TERM_ANDINFO;
570 pOrTerm->eOperator = WO_AND;
571 pAndWC = &pAndInfo->wc;
drh81fd3492016-02-19 14:10:44 +0000572 memset(pAndWC->aStatic, 0, sizeof(pAndWC->aStatic));
drh6c1f4ef2015-06-08 14:23:15 +0000573 sqlite3WhereClauseInit(pAndWC, pWC->pWInfo);
574 sqlite3WhereSplit(pAndWC, pOrTerm->pExpr, TK_AND);
575 sqlite3WhereExprAnalyze(pSrc, pAndWC);
576 pAndWC->pOuter = pWC;
drh6c1f4ef2015-06-08 14:23:15 +0000577 if( !db->mallocFailed ){
578 for(j=0, pAndTerm=pAndWC->a; j<pAndWC->nTerm; j++, pAndTerm++){
579 assert( pAndTerm->pExpr );
dandbd2dcb2016-05-28 18:53:55 +0000580 if( allowedOp(pAndTerm->pExpr->op)
581 || pAndTerm->eOperator==WO_MATCH
582 ){
drh6c1f4ef2015-06-08 14:23:15 +0000583 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pAndTerm->leftCursor);
584 }
585 }
586 }
587 indexable &= b;
588 }
589 }else if( pOrTerm->wtFlags & TERM_COPIED ){
590 /* Skip this term for now. We revisit it when we process the
591 ** corresponding TERM_VIRTUAL term */
592 }else{
593 Bitmask b;
594 b = sqlite3WhereGetMask(&pWInfo->sMaskSet, pOrTerm->leftCursor);
595 if( pOrTerm->wtFlags & TERM_VIRTUAL ){
596 WhereTerm *pOther = &pOrWc->a[pOrTerm->iParent];
597 b |= sqlite3WhereGetMask(&pWInfo->sMaskSet, pOther->leftCursor);
598 }
599 indexable &= b;
600 if( (pOrTerm->eOperator & WO_EQ)==0 ){
601 chngToIN = 0;
602 }else{
603 chngToIN &= b;
604 }
605 }
606 }
607
608 /*
609 ** Record the set of tables that satisfy case 3. The set might be
610 ** empty.
611 */
612 pOrInfo->indexable = indexable;
613 pTerm->eOperator = indexable==0 ? 0 : WO_OR;
614
615 /* For a two-way OR, attempt to implementation case 2.
616 */
617 if( indexable && pOrWc->nTerm==2 ){
618 int iOne = 0;
619 WhereTerm *pOne;
620 while( (pOne = whereNthSubterm(&pOrWc->a[0],iOne++))!=0 ){
621 int iTwo = 0;
622 WhereTerm *pTwo;
623 while( (pTwo = whereNthSubterm(&pOrWc->a[1],iTwo++))!=0 ){
624 whereCombineDisjuncts(pSrc, pWC, pOne, pTwo);
625 }
626 }
627 }
628
629 /*
630 ** chngToIN holds a set of tables that *might* satisfy case 1. But
631 ** we have to do some additional checking to see if case 1 really
632 ** is satisfied.
633 **
634 ** chngToIN will hold either 0, 1, or 2 bits. The 0-bit case means
635 ** that there is no possibility of transforming the OR clause into an
636 ** IN operator because one or more terms in the OR clause contain
637 ** something other than == on a column in the single table. The 1-bit
638 ** case means that every term of the OR clause is of the form
639 ** "table.column=expr" for some single table. The one bit that is set
640 ** will correspond to the common table. We still need to check to make
641 ** sure the same column is used on all terms. The 2-bit case is when
642 ** the all terms are of the form "table1.column=table2.column". It
643 ** might be possible to form an IN operator with either table1.column
644 ** or table2.column as the LHS if either is common to every term of
645 ** the OR clause.
646 **
647 ** Note that terms of the form "table.column1=table.column2" (the
648 ** same table on both sizes of the ==) cannot be optimized.
649 */
650 if( chngToIN ){
651 int okToChngToIN = 0; /* True if the conversion to IN is valid */
652 int iColumn = -1; /* Column index on lhs of IN operator */
653 int iCursor = -1; /* Table cursor common to all terms */
654 int j = 0; /* Loop counter */
655
656 /* Search for a table and column that appears on one side or the
657 ** other of the == operator in every subterm. That table and column
658 ** will be recorded in iCursor and iColumn. There might not be any
659 ** such table and column. Set okToChngToIN if an appropriate table
660 ** and column is found but leave okToChngToIN false if not found.
661 */
662 for(j=0; j<2 && !okToChngToIN; j++){
663 pOrTerm = pOrWc->a;
664 for(i=pOrWc->nTerm-1; i>=0; i--, pOrTerm++){
665 assert( pOrTerm->eOperator & WO_EQ );
666 pOrTerm->wtFlags &= ~TERM_OR_OK;
667 if( pOrTerm->leftCursor==iCursor ){
668 /* This is the 2-bit case and we are on the second iteration and
669 ** current term is from the first iteration. So skip this term. */
670 assert( j==1 );
671 continue;
672 }
673 if( (chngToIN & sqlite3WhereGetMask(&pWInfo->sMaskSet,
674 pOrTerm->leftCursor))==0 ){
675 /* This term must be of the form t1.a==t2.b where t2 is in the
676 ** chngToIN set but t1 is not. This term will be either preceded
677 ** or follwed by an inverted copy (t2.b==t1.a). Skip this term
678 ** and use its inversion. */
679 testcase( pOrTerm->wtFlags & TERM_COPIED );
680 testcase( pOrTerm->wtFlags & TERM_VIRTUAL );
681 assert( pOrTerm->wtFlags & (TERM_COPIED|TERM_VIRTUAL) );
682 continue;
683 }
684 iColumn = pOrTerm->u.leftColumn;
685 iCursor = pOrTerm->leftCursor;
686 break;
687 }
688 if( i<0 ){
689 /* No candidate table+column was found. This can only occur
690 ** on the second iteration */
691 assert( j==1 );
692 assert( IsPowerOfTwo(chngToIN) );
693 assert( chngToIN==sqlite3WhereGetMask(&pWInfo->sMaskSet, iCursor) );
694 break;
695 }
696 testcase( j==1 );
697
698 /* We have found a candidate table and column. Check to see if that
699 ** table and column is common to every term in the OR clause */
700 okToChngToIN = 1;
701 for(; i>=0 && okToChngToIN; i--, pOrTerm++){
702 assert( pOrTerm->eOperator & WO_EQ );
703 if( pOrTerm->leftCursor!=iCursor ){
704 pOrTerm->wtFlags &= ~TERM_OR_OK;
705 }else if( pOrTerm->u.leftColumn!=iColumn ){
706 okToChngToIN = 0;
707 }else{
708 int affLeft, affRight;
709 /* If the right-hand side is also a column, then the affinities
710 ** of both right and left sides must be such that no type
711 ** conversions are required on the right. (Ticket #2249)
712 */
713 affRight = sqlite3ExprAffinity(pOrTerm->pExpr->pRight);
714 affLeft = sqlite3ExprAffinity(pOrTerm->pExpr->pLeft);
715 if( affRight!=0 && affRight!=affLeft ){
716 okToChngToIN = 0;
717 }else{
718 pOrTerm->wtFlags |= TERM_OR_OK;
719 }
720 }
721 }
722 }
723
724 /* At this point, okToChngToIN is true if original pTerm satisfies
725 ** case 1. In that case, construct a new virtual term that is
726 ** pTerm converted into an IN operator.
727 */
728 if( okToChngToIN ){
729 Expr *pDup; /* A transient duplicate expression */
730 ExprList *pList = 0; /* The RHS of the IN operator */
731 Expr *pLeft = 0; /* The LHS of the IN operator */
732 Expr *pNew; /* The complete IN operator */
733
734 for(i=pOrWc->nTerm-1, pOrTerm=pOrWc->a; i>=0; i--, pOrTerm++){
735 if( (pOrTerm->wtFlags & TERM_OR_OK)==0 ) continue;
736 assert( pOrTerm->eOperator & WO_EQ );
737 assert( pOrTerm->leftCursor==iCursor );
738 assert( pOrTerm->u.leftColumn==iColumn );
739 pDup = sqlite3ExprDup(db, pOrTerm->pExpr->pRight, 0);
740 pList = sqlite3ExprListAppend(pWInfo->pParse, pList, pDup);
741 pLeft = pOrTerm->pExpr->pLeft;
742 }
743 assert( pLeft!=0 );
744 pDup = sqlite3ExprDup(db, pLeft, 0);
drhabfd35e2016-12-06 22:47:23 +0000745 pNew = sqlite3PExpr(pParse, TK_IN, pDup, 0);
drh6c1f4ef2015-06-08 14:23:15 +0000746 if( pNew ){
747 int idxNew;
748 transferJoinMarkings(pNew, pExpr);
749 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
750 pNew->x.pList = pList;
751 idxNew = whereClauseInsert(pWC, pNew, TERM_VIRTUAL|TERM_DYNAMIC);
752 testcase( idxNew==0 );
753 exprAnalyze(pSrc, pWC, idxNew);
754 pTerm = &pWC->a[idxTerm];
755 markTermAsChild(pWC, idxNew, idxTerm);
756 }else{
757 sqlite3ExprListDelete(db, pList);
758 }
759 pTerm->eOperator = WO_NOOP; /* case 1 trumps case 3 */
760 }
761 }
762}
763#endif /* !SQLITE_OMIT_OR_OPTIMIZATION && !SQLITE_OMIT_SUBQUERY */
764
765/*
766** We already know that pExpr is a binary operator where both operands are
767** column references. This routine checks to see if pExpr is an equivalence
768** relation:
769** 1. The SQLITE_Transitive optimization must be enabled
770** 2. Must be either an == or an IS operator
771** 3. Not originating in the ON clause of an OUTER JOIN
772** 4. The affinities of A and B must be compatible
773** 5a. Both operands use the same collating sequence OR
774** 5b. The overall collating sequence is BINARY
775** If this routine returns TRUE, that means that the RHS can be substituted
776** for the LHS anyplace else in the WHERE clause where the LHS column occurs.
777** This is an optimization. No harm comes from returning 0. But if 1 is
778** returned when it should not be, then incorrect answers might result.
779*/
780static int termIsEquivalence(Parse *pParse, Expr *pExpr){
781 char aff1, aff2;
782 CollSeq *pColl;
783 const char *zColl1, *zColl2;
784 if( !OptimizationEnabled(pParse->db, SQLITE_Transitive) ) return 0;
785 if( pExpr->op!=TK_EQ && pExpr->op!=TK_IS ) return 0;
786 if( ExprHasProperty(pExpr, EP_FromJoin) ) return 0;
787 aff1 = sqlite3ExprAffinity(pExpr->pLeft);
788 aff2 = sqlite3ExprAffinity(pExpr->pRight);
789 if( aff1!=aff2
790 && (!sqlite3IsNumericAffinity(aff1) || !sqlite3IsNumericAffinity(aff2))
791 ){
792 return 0;
793 }
794 pColl = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft, pExpr->pRight);
795 if( pColl==0 || sqlite3StrICmp(pColl->zName, "BINARY")==0 ) return 1;
796 pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
drha2fbe3b2016-06-28 22:27:56 +0000797 zColl1 = pColl ? pColl->zName : 0;
drh6c1f4ef2015-06-08 14:23:15 +0000798 pColl = sqlite3ExprCollSeq(pParse, pExpr->pRight);
drha2fbe3b2016-06-28 22:27:56 +0000799 zColl2 = pColl ? pColl->zName : 0;
800 return sqlite3_stricmp(zColl1, zColl2)==0;
drh6c1f4ef2015-06-08 14:23:15 +0000801}
802
803/*
804** Recursively walk the expressions of a SELECT statement and generate
805** a bitmask indicating which tables are used in that expression
806** tree.
807*/
808static Bitmask exprSelectUsage(WhereMaskSet *pMaskSet, Select *pS){
809 Bitmask mask = 0;
810 while( pS ){
811 SrcList *pSrc = pS->pSrc;
812 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pEList);
813 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pGroupBy);
814 mask |= sqlite3WhereExprListUsage(pMaskSet, pS->pOrderBy);
815 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pWhere);
816 mask |= sqlite3WhereExprUsage(pMaskSet, pS->pHaving);
817 if( ALWAYS(pSrc!=0) ){
818 int i;
819 for(i=0; i<pSrc->nSrc; i++){
820 mask |= exprSelectUsage(pMaskSet, pSrc->a[i].pSelect);
821 mask |= sqlite3WhereExprUsage(pMaskSet, pSrc->a[i].pOn);
822 }
823 }
824 pS = pS->pPrior;
825 }
826 return mask;
827}
828
829/*
drh47991422015-08-31 15:58:06 +0000830** Expression pExpr is one operand of a comparison operator that might
831** be useful for indexing. This routine checks to see if pExpr appears
832** in any index. Return TRUE (1) if pExpr is an indexed term and return
drhe97c9ff2017-04-11 18:06:48 +0000833** FALSE (0) if not. If TRUE is returned, also set aiCurCol[0] to the cursor
834** number of the table that is indexed and aiCurCol[1] to the column number
drh8d25cb92016-08-19 19:58:06 +0000835** of the column that is indexed, or XN_EXPR (-2) if an expression is being
836** indexed.
drh47991422015-08-31 15:58:06 +0000837**
838** If pExpr is a TK_COLUMN column reference, then this routine always returns
839** true even if that particular column is not indexed, because the column
840** might be added to an automatic index later.
841*/
drhe97c9ff2017-04-11 18:06:48 +0000842static SQLITE_NOINLINE int exprMightBeIndexed2(
drh47991422015-08-31 15:58:06 +0000843 SrcList *pFrom, /* The FROM clause */
844 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
drhe97c9ff2017-04-11 18:06:48 +0000845 int *aiCurCol, /* Write the referenced table cursor and column here */
846 Expr *pExpr /* An operand of a comparison operator */
drh47991422015-08-31 15:58:06 +0000847){
848 Index *pIdx;
849 int i;
850 int iCur;
drhe97c9ff2017-04-11 18:06:48 +0000851 for(i=0; mPrereq>1; i++, mPrereq>>=1){}
852 iCur = pFrom->a[i].iCursor;
853 for(pIdx=pFrom->a[i].pTab->pIndex; pIdx; pIdx=pIdx->pNext){
854 if( pIdx->aColExpr==0 ) continue;
855 for(i=0; i<pIdx->nKeyCol; i++){
856 if( pIdx->aiColumn[i]!=XN_EXPR ) continue;
857 if( sqlite3ExprCompareSkip(pExpr, pIdx->aColExpr->a[i].pExpr, iCur)==0 ){
858 aiCurCol[0] = iCur;
859 aiCurCol[1] = XN_EXPR;
860 return 1;
861 }
862 }
863 }
864 return 0;
865}
866static int exprMightBeIndexed(
867 SrcList *pFrom, /* The FROM clause */
868 Bitmask mPrereq, /* Bitmask of FROM clause terms referenced by pExpr */
869 int *aiCurCol, /* Write the referenced table cursor & column here */
870 Expr *pExpr, /* An operand of a comparison operator */
871 int op /* The specific comparison operator */
872){
dan71c57db2016-07-09 20:23:55 +0000873 /* If this expression is a vector to the left or right of a
874 ** inequality constraint (>, <, >= or <=), perform the processing
875 ** on the first element of the vector. */
876 assert( TK_GT+1==TK_LE && TK_GT+2==TK_LT && TK_GT+3==TK_GE );
drh64bcb8c2016-08-26 03:42:57 +0000877 assert( TK_IS<TK_GE && TK_ISNULL<TK_GE && TK_IN<TK_GE );
878 assert( op<=TK_GE );
879 if( pExpr->op==TK_VECTOR && (op>=TK_GT && ALWAYS(op<=TK_GE)) ){
dan71c57db2016-07-09 20:23:55 +0000880 pExpr = pExpr->x.pList->a[0].pExpr;
881 }
882
drh47991422015-08-31 15:58:06 +0000883 if( pExpr->op==TK_COLUMN ){
drhe97c9ff2017-04-11 18:06:48 +0000884 aiCurCol[0] = pExpr->iTable;
885 aiCurCol[1] = pExpr->iColumn;
drh47991422015-08-31 15:58:06 +0000886 return 1;
887 }
888 if( mPrereq==0 ) return 0; /* No table references */
889 if( (mPrereq&(mPrereq-1))!=0 ) return 0; /* Refs more than one table */
drhe97c9ff2017-04-11 18:06:48 +0000890 return exprMightBeIndexed2(pFrom,mPrereq,aiCurCol,pExpr);
drh47991422015-08-31 15:58:06 +0000891}
892
dan870a0702016-08-01 16:37:43 +0000893/*
drh6c1f4ef2015-06-08 14:23:15 +0000894** The input to this routine is an WhereTerm structure with only the
895** "pExpr" field filled in. The job of this routine is to analyze the
896** subexpression and populate all the other fields of the WhereTerm
897** structure.
898**
899** If the expression is of the form "<expr> <op> X" it gets commuted
900** to the standard form of "X <op> <expr>".
901**
902** If the expression is of the form "X <op> Y" where both X and Y are
903** columns, then the original expression is unchanged and a new virtual
904** term of the form "Y <op> X" is added to the WHERE clause and
905** analyzed separately. The original term is marked with TERM_COPIED
906** and the new term is marked with TERM_DYNAMIC (because it's pExpr
907** needs to be freed with the WhereClause) and TERM_VIRTUAL (because it
908** is a commuted copy of a prior term.) The original term has nChild=1
909** and the copy has idxParent set to the index of the original term.
910*/
911static void exprAnalyze(
912 SrcList *pSrc, /* the FROM clause */
913 WhereClause *pWC, /* the WHERE clause */
914 int idxTerm /* Index of the term to be analyzed */
915){
916 WhereInfo *pWInfo = pWC->pWInfo; /* WHERE clause processing context */
917 WhereTerm *pTerm; /* The term to be analyzed */
918 WhereMaskSet *pMaskSet; /* Set of table index masks */
919 Expr *pExpr; /* The expression to be analyzed */
920 Bitmask prereqLeft; /* Prerequesites of the pExpr->pLeft */
921 Bitmask prereqAll; /* Prerequesites of pExpr */
922 Bitmask extraRight = 0; /* Extra dependencies on LEFT JOIN */
923 Expr *pStr1 = 0; /* RHS of LIKE/GLOB operator */
924 int isComplete = 0; /* RHS of LIKE/GLOB ends with wildcard */
925 int noCase = 0; /* uppercase equivalent to lowercase */
926 int op; /* Top-level operator. pExpr->op */
927 Parse *pParse = pWInfo->pParse; /* Parsing context */
928 sqlite3 *db = pParse->db; /* Database connection */
dan07bdba82015-11-23 21:09:54 +0000929 unsigned char eOp2; /* op2 value for LIKE/REGEXP/GLOB */
drhd9bcb322017-01-10 15:08:06 +0000930 int nLeft; /* Number of elements on left side vector */
drh6c1f4ef2015-06-08 14:23:15 +0000931
932 if( db->mallocFailed ){
933 return;
934 }
935 pTerm = &pWC->a[idxTerm];
936 pMaskSet = &pWInfo->sMaskSet;
937 pExpr = pTerm->pExpr;
938 assert( pExpr->op!=TK_AS && pExpr->op!=TK_COLLATE );
939 prereqLeft = sqlite3WhereExprUsage(pMaskSet, pExpr->pLeft);
940 op = pExpr->op;
941 if( op==TK_IN ){
942 assert( pExpr->pRight==0 );
dan7b35a772016-07-28 19:47:15 +0000943 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
drh6c1f4ef2015-06-08 14:23:15 +0000944 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
945 pTerm->prereqRight = exprSelectUsage(pMaskSet, pExpr->x.pSelect);
946 }else{
947 pTerm->prereqRight = sqlite3WhereExprListUsage(pMaskSet, pExpr->x.pList);
948 }
949 }else if( op==TK_ISNULL ){
950 pTerm->prereqRight = 0;
951 }else{
952 pTerm->prereqRight = sqlite3WhereExprUsage(pMaskSet, pExpr->pRight);
953 }
954 prereqAll = sqlite3WhereExprUsage(pMaskSet, pExpr);
955 if( ExprHasProperty(pExpr, EP_FromJoin) ){
956 Bitmask x = sqlite3WhereGetMask(pMaskSet, pExpr->iRightJoinTable);
957 prereqAll |= x;
958 extraRight = x-1; /* ON clause terms may not be used with an index
959 ** on left table of a LEFT JOIN. Ticket #3015 */
drh8e36ddd2017-01-10 17:33:43 +0000960 if( (prereqAll>>1)>=x ){
961 sqlite3ErrorMsg(pParse, "ON clause references tables to its right");
962 return;
963 }
drh6c1f4ef2015-06-08 14:23:15 +0000964 }
965 pTerm->prereqAll = prereqAll;
966 pTerm->leftCursor = -1;
967 pTerm->iParent = -1;
968 pTerm->eOperator = 0;
969 if( allowedOp(op) ){
drhe97c9ff2017-04-11 18:06:48 +0000970 int aiCurCol[2];
drh6c1f4ef2015-06-08 14:23:15 +0000971 Expr *pLeft = sqlite3ExprSkipCollate(pExpr->pLeft);
972 Expr *pRight = sqlite3ExprSkipCollate(pExpr->pRight);
973 u16 opMask = (pTerm->prereqRight & prereqLeft)==0 ? WO_ALL : WO_EQUIV;
dan8da209b2016-07-26 18:06:08 +0000974
dan145b4ea2016-07-29 18:12:12 +0000975 if( pTerm->iField>0 ){
976 assert( op==TK_IN );
dan8da209b2016-07-26 18:06:08 +0000977 assert( pLeft->op==TK_VECTOR );
978 pLeft = pLeft->x.pList->a[pTerm->iField-1].pExpr;
979 }
980
drhe97c9ff2017-04-11 18:06:48 +0000981 if( exprMightBeIndexed(pSrc, prereqLeft, aiCurCol, pLeft, op) ){
982 pTerm->leftCursor = aiCurCol[0];
983 pTerm->u.leftColumn = aiCurCol[1];
drh6860e6f2015-08-27 18:24:02 +0000984 pTerm->eOperator = operatorMask(op) & opMask;
drh6c1f4ef2015-06-08 14:23:15 +0000985 }
986 if( op==TK_IS ) pTerm->wtFlags |= TERM_IS;
drh47991422015-08-31 15:58:06 +0000987 if( pRight
drhe97c9ff2017-04-11 18:06:48 +0000988 && exprMightBeIndexed(pSrc, pTerm->prereqRight, aiCurCol, pRight, op)
drh47991422015-08-31 15:58:06 +0000989 ){
drh6c1f4ef2015-06-08 14:23:15 +0000990 WhereTerm *pNew;
991 Expr *pDup;
992 u16 eExtraOp = 0; /* Extra bits for pNew->eOperator */
dan145b4ea2016-07-29 18:12:12 +0000993 assert( pTerm->iField==0 );
drh6c1f4ef2015-06-08 14:23:15 +0000994 if( pTerm->leftCursor>=0 ){
995 int idxNew;
996 pDup = sqlite3ExprDup(db, pExpr, 0);
997 if( db->mallocFailed ){
998 sqlite3ExprDelete(db, pDup);
999 return;
1000 }
1001 idxNew = whereClauseInsert(pWC, pDup, TERM_VIRTUAL|TERM_DYNAMIC);
1002 if( idxNew==0 ) return;
1003 pNew = &pWC->a[idxNew];
1004 markTermAsChild(pWC, idxNew, idxTerm);
1005 if( op==TK_IS ) pNew->wtFlags |= TERM_IS;
1006 pTerm = &pWC->a[idxTerm];
1007 pTerm->wtFlags |= TERM_COPIED;
1008
1009 if( termIsEquivalence(pParse, pDup) ){
1010 pTerm->eOperator |= WO_EQUIV;
1011 eExtraOp = WO_EQUIV;
1012 }
1013 }else{
1014 pDup = pExpr;
1015 pNew = pTerm;
1016 }
1017 exprCommute(pParse, pDup);
drhe97c9ff2017-04-11 18:06:48 +00001018 pNew->leftCursor = aiCurCol[0];
1019 pNew->u.leftColumn = aiCurCol[1];
drh6c1f4ef2015-06-08 14:23:15 +00001020 testcase( (prereqLeft | extraRight) != prereqLeft );
1021 pNew->prereqRight = prereqLeft | extraRight;
1022 pNew->prereqAll = prereqAll;
1023 pNew->eOperator = (operatorMask(pDup->op) + eExtraOp) & opMask;
1024 }
1025 }
1026
1027#ifndef SQLITE_OMIT_BETWEEN_OPTIMIZATION
1028 /* If a term is the BETWEEN operator, create two new virtual terms
1029 ** that define the range that the BETWEEN implements. For example:
1030 **
1031 ** a BETWEEN b AND c
1032 **
1033 ** is converted into:
1034 **
1035 ** (a BETWEEN b AND c) AND (a>=b) AND (a<=c)
1036 **
1037 ** The two new terms are added onto the end of the WhereClause object.
1038 ** The new terms are "dynamic" and are children of the original BETWEEN
1039 ** term. That means that if the BETWEEN term is coded, the children are
1040 ** skipped. Or, if the children are satisfied by an index, the original
1041 ** BETWEEN term is skipped.
1042 */
1043 else if( pExpr->op==TK_BETWEEN && pWC->op==TK_AND ){
1044 ExprList *pList = pExpr->x.pList;
1045 int i;
1046 static const u8 ops[] = {TK_GE, TK_LE};
1047 assert( pList!=0 );
1048 assert( pList->nExpr==2 );
1049 for(i=0; i<2; i++){
1050 Expr *pNewExpr;
1051 int idxNew;
1052 pNewExpr = sqlite3PExpr(pParse, ops[i],
1053 sqlite3ExprDup(db, pExpr->pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001054 sqlite3ExprDup(db, pList->a[i].pExpr, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001055 transferJoinMarkings(pNewExpr, pExpr);
1056 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1057 testcase( idxNew==0 );
1058 exprAnalyze(pSrc, pWC, idxNew);
1059 pTerm = &pWC->a[idxTerm];
1060 markTermAsChild(pWC, idxNew, idxTerm);
1061 }
1062 }
1063#endif /* SQLITE_OMIT_BETWEEN_OPTIMIZATION */
1064
1065#if !defined(SQLITE_OMIT_OR_OPTIMIZATION) && !defined(SQLITE_OMIT_SUBQUERY)
1066 /* Analyze a term that is composed of two or more subterms connected by
1067 ** an OR operator.
1068 */
1069 else if( pExpr->op==TK_OR ){
1070 assert( pWC->op==TK_AND );
1071 exprAnalyzeOrTerm(pSrc, pWC, idxTerm);
1072 pTerm = &pWC->a[idxTerm];
1073 }
1074#endif /* SQLITE_OMIT_OR_OPTIMIZATION */
1075
1076#ifndef SQLITE_OMIT_LIKE_OPTIMIZATION
1077 /* Add constraints to reduce the search space on a LIKE or GLOB
1078 ** operator.
1079 **
1080 ** A like pattern of the form "x LIKE 'aBc%'" is changed into constraints
1081 **
1082 ** x>='ABC' AND x<'abd' AND x LIKE 'aBc%'
1083 **
1084 ** The last character of the prefix "abc" is incremented to form the
1085 ** termination condition "abd". If case is not significant (the default
1086 ** for LIKE) then the lower-bound is made all uppercase and the upper-
1087 ** bound is made all lowercase so that the bounds also work when comparing
1088 ** BLOBs.
1089 */
1090 if( pWC->op==TK_AND
1091 && isLikeOrGlob(pParse, pExpr, &pStr1, &isComplete, &noCase)
1092 ){
1093 Expr *pLeft; /* LHS of LIKE/GLOB operator */
1094 Expr *pStr2; /* Copy of pStr1 - RHS of LIKE/GLOB operator */
1095 Expr *pNewExpr1;
1096 Expr *pNewExpr2;
1097 int idxNew1;
1098 int idxNew2;
1099 const char *zCollSeqName; /* Name of collating sequence */
1100 const u16 wtFlags = TERM_LIKEOPT | TERM_VIRTUAL | TERM_DYNAMIC;
1101
1102 pLeft = pExpr->x.pList->a[1].pExpr;
1103 pStr2 = sqlite3ExprDup(db, pStr1, 0);
1104
1105 /* Convert the lower bound to upper-case and the upper bound to
1106 ** lower-case (upper-case is less than lower-case in ASCII) so that
1107 ** the range constraints also work for BLOBs
1108 */
1109 if( noCase && !pParse->db->mallocFailed ){
1110 int i;
1111 char c;
1112 pTerm->wtFlags |= TERM_LIKE;
1113 for(i=0; (c = pStr1->u.zToken[i])!=0; i++){
1114 pStr1->u.zToken[i] = sqlite3Toupper(c);
1115 pStr2->u.zToken[i] = sqlite3Tolower(c);
1116 }
1117 }
1118
1119 if( !db->mallocFailed ){
1120 u8 c, *pC; /* Last character before the first wildcard */
1121 pC = (u8*)&pStr2->u.zToken[sqlite3Strlen30(pStr2->u.zToken)-1];
1122 c = *pC;
1123 if( noCase ){
1124 /* The point is to increment the last character before the first
1125 ** wildcard. But if we increment '@', that will push it into the
1126 ** alphabetic range where case conversions will mess up the
1127 ** inequality. To avoid this, make sure to also run the full
1128 ** LIKE on all candidate expressions by clearing the isComplete flag
1129 */
1130 if( c=='A'-1 ) isComplete = 0;
1131 c = sqlite3UpperToLower[c];
1132 }
1133 *pC = c + 1;
1134 }
1135 zCollSeqName = noCase ? "NOCASE" : "BINARY";
1136 pNewExpr1 = sqlite3ExprDup(db, pLeft, 0);
1137 pNewExpr1 = sqlite3PExpr(pParse, TK_GE,
1138 sqlite3ExprAddCollateString(pParse,pNewExpr1,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001139 pStr1);
drh6c1f4ef2015-06-08 14:23:15 +00001140 transferJoinMarkings(pNewExpr1, pExpr);
1141 idxNew1 = whereClauseInsert(pWC, pNewExpr1, wtFlags);
1142 testcase( idxNew1==0 );
1143 exprAnalyze(pSrc, pWC, idxNew1);
1144 pNewExpr2 = sqlite3ExprDup(db, pLeft, 0);
1145 pNewExpr2 = sqlite3PExpr(pParse, TK_LT,
1146 sqlite3ExprAddCollateString(pParse,pNewExpr2,zCollSeqName),
drhabfd35e2016-12-06 22:47:23 +00001147 pStr2);
drh6c1f4ef2015-06-08 14:23:15 +00001148 transferJoinMarkings(pNewExpr2, pExpr);
1149 idxNew2 = whereClauseInsert(pWC, pNewExpr2, wtFlags);
1150 testcase( idxNew2==0 );
1151 exprAnalyze(pSrc, pWC, idxNew2);
1152 pTerm = &pWC->a[idxTerm];
1153 if( isComplete ){
1154 markTermAsChild(pWC, idxNew1, idxTerm);
1155 markTermAsChild(pWC, idxNew2, idxTerm);
1156 }
1157 }
1158#endif /* SQLITE_OMIT_LIKE_OPTIMIZATION */
1159
1160#ifndef SQLITE_OMIT_VIRTUALTABLE
1161 /* Add a WO_MATCH auxiliary term to the constraint set if the
1162 ** current expression is of the form: column MATCH expr.
1163 ** This information is used by the xBestIndex methods of
1164 ** virtual tables. The native query optimizer does not attempt
1165 ** to do anything with MATCH functions.
1166 */
dandbd2dcb2016-05-28 18:53:55 +00001167 if( pWC->op==TK_AND && isMatchOfColumn(pExpr, &eOp2) ){
drh6c1f4ef2015-06-08 14:23:15 +00001168 int idxNew;
1169 Expr *pRight, *pLeft;
1170 WhereTerm *pNewTerm;
1171 Bitmask prereqColumn, prereqExpr;
1172
1173 pRight = pExpr->x.pList->a[0].pExpr;
1174 pLeft = pExpr->x.pList->a[1].pExpr;
1175 prereqExpr = sqlite3WhereExprUsage(pMaskSet, pRight);
1176 prereqColumn = sqlite3WhereExprUsage(pMaskSet, pLeft);
1177 if( (prereqExpr & prereqColumn)==0 ){
1178 Expr *pNewExpr;
1179 pNewExpr = sqlite3PExpr(pParse, TK_MATCH,
drhabfd35e2016-12-06 22:47:23 +00001180 0, sqlite3ExprDup(db, pRight, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001181 idxNew = whereClauseInsert(pWC, pNewExpr, TERM_VIRTUAL|TERM_DYNAMIC);
1182 testcase( idxNew==0 );
1183 pNewTerm = &pWC->a[idxNew];
1184 pNewTerm->prereqRight = prereqExpr;
1185 pNewTerm->leftCursor = pLeft->iTable;
1186 pNewTerm->u.leftColumn = pLeft->iColumn;
1187 pNewTerm->eOperator = WO_MATCH;
dan07bdba82015-11-23 21:09:54 +00001188 pNewTerm->eMatchOp = eOp2;
drh6c1f4ef2015-06-08 14:23:15 +00001189 markTermAsChild(pWC, idxNew, idxTerm);
1190 pTerm = &pWC->a[idxTerm];
1191 pTerm->wtFlags |= TERM_COPIED;
1192 pNewTerm->prereqAll = pTerm->prereqAll;
1193 }
1194 }
1195#endif /* SQLITE_OMIT_VIRTUALTABLE */
1196
dan95a08c02016-08-02 16:18:35 +00001197 /* If there is a vector == or IS term - e.g. "(a, b) == (?, ?)" - create
drh9e730f02016-08-20 12:00:05 +00001198 ** new terms for each component comparison - "a = ?" and "b = ?". The
1199 ** new terms completely replace the original vector comparison, which is
1200 ** no longer used.
1201 **
dan95a08c02016-08-02 16:18:35 +00001202 ** This is only required if at least one side of the comparison operation
1203 ** is not a sub-select. */
dan71c57db2016-07-09 20:23:55 +00001204 if( pWC->op==TK_AND
1205 && (pExpr->op==TK_EQ || pExpr->op==TK_IS)
drhd9bcb322017-01-10 15:08:06 +00001206 && (nLeft = sqlite3ExprVectorSize(pExpr->pLeft))>1
1207 && sqlite3ExprVectorSize(pExpr->pRight)==nLeft
dan71c57db2016-07-09 20:23:55 +00001208 && ( (pExpr->pLeft->flags & EP_xIsSelect)==0
drhd9bcb322017-01-10 15:08:06 +00001209 || (pExpr->pRight->flags & EP_xIsSelect)==0)
1210 ){
drhb29e60c2016-09-05 12:02:34 +00001211 int i;
drhb29e60c2016-09-05 12:02:34 +00001212 for(i=0; i<nLeft; i++){
1213 int idxNew;
1214 Expr *pNew;
1215 Expr *pLeft = sqlite3ExprForVectorField(pParse, pExpr->pLeft, i);
1216 Expr *pRight = sqlite3ExprForVectorField(pParse, pExpr->pRight, i);
dan71c57db2016-07-09 20:23:55 +00001217
drhabfd35e2016-12-06 22:47:23 +00001218 pNew = sqlite3PExpr(pParse, pExpr->op, pLeft, pRight);
drhc52496f2016-10-27 01:02:20 +00001219 transferJoinMarkings(pNew, pExpr);
drhb29e60c2016-09-05 12:02:34 +00001220 idxNew = whereClauseInsert(pWC, pNew, TERM_DYNAMIC);
1221 exprAnalyze(pSrc, pWC, idxNew);
dan71c57db2016-07-09 20:23:55 +00001222 }
drhb29e60c2016-09-05 12:02:34 +00001223 pTerm = &pWC->a[idxTerm];
1224 pTerm->wtFlags = TERM_CODED|TERM_VIRTUAL; /* Disable the original */
1225 pTerm->eOperator = 0;
dan71c57db2016-07-09 20:23:55 +00001226 }
1227
dan95a08c02016-08-02 16:18:35 +00001228 /* If there is a vector IN term - e.g. "(a, b) IN (SELECT ...)" - create
1229 ** a virtual term for each vector component. The expression object
1230 ** used by each such virtual term is pExpr (the full vector IN(...)
1231 ** expression). The WhereTerm.iField variable identifies the index within
drh14318072016-09-06 18:51:25 +00001232 ** the vector on the LHS that the virtual term represents.
1233 **
1234 ** This only works if the RHS is a simple SELECT, not a compound
1235 */
dan8da209b2016-07-26 18:06:08 +00001236 if( pWC->op==TK_AND && pExpr->op==TK_IN && pTerm->iField==0
1237 && pExpr->pLeft->op==TK_VECTOR
drh14318072016-09-06 18:51:25 +00001238 && pExpr->x.pSelect->pPrior==0
dan8da209b2016-07-26 18:06:08 +00001239 ){
1240 int i;
1241 for(i=0; i<sqlite3ExprVectorSize(pExpr->pLeft); i++){
1242 int idxNew;
1243 idxNew = whereClauseInsert(pWC, pExpr, TERM_VIRTUAL);
1244 pWC->a[idxNew].iField = i+1;
1245 exprAnalyze(pSrc, pWC, idxNew);
1246 markTermAsChild(pWC, idxNew, idxTerm);
1247 }
1248 }
1249
drh6c1f4ef2015-06-08 14:23:15 +00001250#ifdef SQLITE_ENABLE_STAT3_OR_STAT4
1251 /* When sqlite_stat3 histogram data is available an operator of the
1252 ** form "x IS NOT NULL" can sometimes be evaluated more efficiently
1253 ** as "x>NULL" if x is not an INTEGER PRIMARY KEY. So construct a
1254 ** virtual term of that form.
1255 **
1256 ** Note that the virtual term must be tagged with TERM_VNULL.
1257 */
1258 if( pExpr->op==TK_NOTNULL
1259 && pExpr->pLeft->op==TK_COLUMN
1260 && pExpr->pLeft->iColumn>=0
1261 && OptimizationEnabled(db, SQLITE_Stat34)
1262 ){
1263 Expr *pNewExpr;
1264 Expr *pLeft = pExpr->pLeft;
1265 int idxNew;
1266 WhereTerm *pNewTerm;
1267
1268 pNewExpr = sqlite3PExpr(pParse, TK_GT,
1269 sqlite3ExprDup(db, pLeft, 0),
drhabfd35e2016-12-06 22:47:23 +00001270 sqlite3ExprAlloc(db, TK_NULL, 0, 0));
drh6c1f4ef2015-06-08 14:23:15 +00001271
1272 idxNew = whereClauseInsert(pWC, pNewExpr,
1273 TERM_VIRTUAL|TERM_DYNAMIC|TERM_VNULL);
1274 if( idxNew ){
1275 pNewTerm = &pWC->a[idxNew];
1276 pNewTerm->prereqRight = 0;
1277 pNewTerm->leftCursor = pLeft->iTable;
1278 pNewTerm->u.leftColumn = pLeft->iColumn;
1279 pNewTerm->eOperator = WO_GT;
1280 markTermAsChild(pWC, idxNew, idxTerm);
1281 pTerm = &pWC->a[idxTerm];
1282 pTerm->wtFlags |= TERM_COPIED;
1283 pNewTerm->prereqAll = pTerm->prereqAll;
1284 }
1285 }
1286#endif /* SQLITE_ENABLE_STAT3_OR_STAT4 */
1287
1288 /* Prevent ON clause terms of a LEFT JOIN from being used to drive
1289 ** an index for tables to the left of the join.
1290 */
drh0f85b2f2016-11-20 12:00:27 +00001291 testcase( pTerm!=&pWC->a[idxTerm] );
1292 pTerm = &pWC->a[idxTerm];
drh6c1f4ef2015-06-08 14:23:15 +00001293 pTerm->prereqRight |= extraRight;
1294}
1295
1296/***************************************************************************
1297** Routines with file scope above. Interface to the rest of the where.c
1298** subsystem follows.
1299***************************************************************************/
1300
1301/*
1302** This routine identifies subexpressions in the WHERE clause where
1303** each subexpression is separated by the AND operator or some other
1304** operator specified in the op parameter. The WhereClause structure
1305** is filled with pointers to subexpressions. For example:
1306**
1307** WHERE a=='hello' AND coalesce(b,11)<10 AND (c+12!=d OR c==22)
1308** \________/ \_______________/ \________________/
1309** slot[0] slot[1] slot[2]
1310**
1311** The original WHERE clause in pExpr is unaltered. All this routine
1312** does is make slot[] entries point to substructure within pExpr.
1313**
1314** In the previous sentence and in the diagram, "slot[]" refers to
1315** the WhereClause.a[] array. The slot[] array grows as needed to contain
1316** all terms of the WHERE clause.
1317*/
1318void sqlite3WhereSplit(WhereClause *pWC, Expr *pExpr, u8 op){
1319 Expr *pE2 = sqlite3ExprSkipCollate(pExpr);
1320 pWC->op = op;
1321 if( pE2==0 ) return;
1322 if( pE2->op!=op ){
1323 whereClauseInsert(pWC, pExpr, 0);
1324 }else{
1325 sqlite3WhereSplit(pWC, pE2->pLeft, op);
1326 sqlite3WhereSplit(pWC, pE2->pRight, op);
1327 }
1328}
1329
1330/*
1331** Initialize a preallocated WhereClause structure.
1332*/
1333void sqlite3WhereClauseInit(
1334 WhereClause *pWC, /* The WhereClause to be initialized */
1335 WhereInfo *pWInfo /* The WHERE processing context */
1336){
1337 pWC->pWInfo = pWInfo;
1338 pWC->pOuter = 0;
1339 pWC->nTerm = 0;
1340 pWC->nSlot = ArraySize(pWC->aStatic);
1341 pWC->a = pWC->aStatic;
1342}
1343
1344/*
1345** Deallocate a WhereClause structure. The WhereClause structure
drh62aaa6c2015-11-21 17:27:42 +00001346** itself is not freed. This routine is the inverse of
1347** sqlite3WhereClauseInit().
drh6c1f4ef2015-06-08 14:23:15 +00001348*/
1349void sqlite3WhereClauseClear(WhereClause *pWC){
1350 int i;
1351 WhereTerm *a;
1352 sqlite3 *db = pWC->pWInfo->pParse->db;
1353 for(i=pWC->nTerm-1, a=pWC->a; i>=0; i--, a++){
1354 if( a->wtFlags & TERM_DYNAMIC ){
1355 sqlite3ExprDelete(db, a->pExpr);
1356 }
1357 if( a->wtFlags & TERM_ORINFO ){
1358 whereOrInfoDelete(db, a->u.pOrInfo);
1359 }else if( a->wtFlags & TERM_ANDINFO ){
1360 whereAndInfoDelete(db, a->u.pAndInfo);
1361 }
1362 }
1363 if( pWC->a!=pWC->aStatic ){
1364 sqlite3DbFree(db, pWC->a);
1365 }
1366}
1367
1368
1369/*
1370** These routines walk (recursively) an expression tree and generate
1371** a bitmask indicating which tables are used in that expression
1372** tree.
1373*/
1374Bitmask sqlite3WhereExprUsage(WhereMaskSet *pMaskSet, Expr *p){
drh93ca3932016-08-10 20:02:21 +00001375 Bitmask mask;
drh6c1f4ef2015-06-08 14:23:15 +00001376 if( p==0 ) return 0;
1377 if( p->op==TK_COLUMN ){
drhf43ce0b2017-05-25 00:08:48 +00001378 return sqlite3WhereGetMask(pMaskSet, p->iTable);
drh6c1f4ef2015-06-08 14:23:15 +00001379 }
drhf43ce0b2017-05-25 00:08:48 +00001380 mask = (p->op==TK_IF_NULL_ROW) ? sqlite3WhereGetMask(pMaskSet, p->iTable) : 0;
drh93ca3932016-08-10 20:02:21 +00001381 assert( !ExprHasProperty(p, EP_TokenOnly) );
drhf43ce0b2017-05-25 00:08:48 +00001382 if( p->pRight ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pRight);
drh926957f2016-04-12 00:00:33 +00001383 if( p->pLeft ) mask |= sqlite3WhereExprUsage(pMaskSet, p->pLeft);
drh6c1f4ef2015-06-08 14:23:15 +00001384 if( ExprHasProperty(p, EP_xIsSelect) ){
1385 mask |= exprSelectUsage(pMaskSet, p->x.pSelect);
drh926957f2016-04-12 00:00:33 +00001386 }else if( p->x.pList ){
drh6c1f4ef2015-06-08 14:23:15 +00001387 mask |= sqlite3WhereExprListUsage(pMaskSet, p->x.pList);
1388 }
1389 return mask;
1390}
1391Bitmask sqlite3WhereExprListUsage(WhereMaskSet *pMaskSet, ExprList *pList){
1392 int i;
1393 Bitmask mask = 0;
1394 if( pList ){
1395 for(i=0; i<pList->nExpr; i++){
1396 mask |= sqlite3WhereExprUsage(pMaskSet, pList->a[i].pExpr);
1397 }
1398 }
1399 return mask;
1400}
1401
1402
1403/*
1404** Call exprAnalyze on all terms in a WHERE clause.
1405**
1406** Note that exprAnalyze() might add new virtual terms onto the
1407** end of the WHERE clause. We do not want to analyze these new
1408** virtual terms, so start analyzing at the end and work forward
1409** so that the added virtual terms are never processed.
1410*/
1411void sqlite3WhereExprAnalyze(
1412 SrcList *pTabList, /* the FROM clause */
1413 WhereClause *pWC /* the WHERE clause to be analyzed */
1414){
1415 int i;
1416 for(i=pWC->nTerm-1; i>=0; i--){
1417 exprAnalyze(pTabList, pWC, i);
1418 }
1419}
drh01d230c2015-08-19 17:11:37 +00001420
1421/*
1422** For table-valued-functions, transform the function arguments into
1423** new WHERE clause terms.
1424**
1425** Each function argument translates into an equality constraint against
1426** a HIDDEN column in the table.
1427*/
1428void sqlite3WhereTabFuncArgs(
1429 Parse *pParse, /* Parsing context */
1430 struct SrcList_item *pItem, /* The FROM clause term to process */
1431 WhereClause *pWC /* Xfer function arguments to here */
1432){
1433 Table *pTab;
1434 int j, k;
1435 ExprList *pArgs;
1436 Expr *pColRef;
1437 Expr *pTerm;
1438 if( pItem->fg.isTabFunc==0 ) return;
1439 pTab = pItem->pTab;
1440 assert( pTab!=0 );
1441 pArgs = pItem->u1.pFuncArg;
drh20292312015-11-21 13:24:46 +00001442 if( pArgs==0 ) return;
drh01d230c2015-08-19 17:11:37 +00001443 for(j=k=0; j<pArgs->nExpr; j++){
drh62aaa6c2015-11-21 17:27:42 +00001444 while( k<pTab->nCol && (pTab->aCol[k].colFlags & COLFLAG_HIDDEN)==0 ){k++;}
drh01d230c2015-08-19 17:11:37 +00001445 if( k>=pTab->nCol ){
drhd8b1bfc2015-08-20 23:21:34 +00001446 sqlite3ErrorMsg(pParse, "too many arguments on %s() - max %d",
drh01d230c2015-08-19 17:11:37 +00001447 pTab->zName, j);
1448 return;
1449 }
drhe1c03b62016-09-23 20:59:31 +00001450 pColRef = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
drh01d230c2015-08-19 17:11:37 +00001451 if( pColRef==0 ) return;
1452 pColRef->iTable = pItem->iCursor;
1453 pColRef->iColumn = k++;
drh1f2fc282015-08-21 17:14:48 +00001454 pColRef->pTab = pTab;
drh01d230c2015-08-19 17:11:37 +00001455 pTerm = sqlite3PExpr(pParse, TK_EQ, pColRef,
drhabfd35e2016-12-06 22:47:23 +00001456 sqlite3ExprDup(pParse->db, pArgs->a[j].pExpr, 0));
drh01d230c2015-08-19 17:11:37 +00001457 whereClauseInsert(pWC, pTerm, TERM_DYNAMIC);
1458 }
1459}