Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(2)

Side by Side Diff: third_party/sqlite/sqlite-src-3170000/src/expr.c

Issue 2747283002: [sql] Import reference version of SQLite 3.17.. (Closed)
Patch Set: Created 3 years, 9 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
10 **
11 *************************************************************************
12 ** This file contains routines used for analyzing expressions and
13 ** for generating VDBE code that evaluates expressions in SQLite.
14 */
15 #include "sqliteInt.h"
16
17 /* Forward declarations */
18 static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19 static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
20
21 /*
22 ** Return the affinity character for a single column of a table.
23 */
24 char sqlite3TableColumnAffinity(Table *pTab, int iCol){
25 assert( iCol<pTab->nCol );
26 return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
27 }
28
29 /*
30 ** Return the 'affinity' of the expression pExpr if any.
31 **
32 ** If pExpr is a column, a reference to a column via an 'AS' alias,
33 ** or a sub-select with a column as the return value, then the
34 ** affinity of that column is returned. Otherwise, 0x00 is returned,
35 ** indicating no affinity for the expression.
36 **
37 ** i.e. the WHERE clause expressions in the following statements all
38 ** have an affinity:
39 **
40 ** CREATE TABLE t1(a);
41 ** SELECT * FROM t1 WHERE a;
42 ** SELECT a AS b FROM t1 WHERE b;
43 ** SELECT * FROM t1 WHERE (select a from t1);
44 */
45 char sqlite3ExprAffinity(Expr *pExpr){
46 int op;
47 pExpr = sqlite3ExprSkipCollate(pExpr);
48 if( pExpr->flags & EP_Generic ) return 0;
49 op = pExpr->op;
50 if( op==TK_SELECT ){
51 assert( pExpr->flags&EP_xIsSelect );
52 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
53 }
54 if( op==TK_REGISTER ) op = pExpr->op2;
55 #ifndef SQLITE_OMIT_CAST
56 if( op==TK_CAST ){
57 assert( !ExprHasProperty(pExpr, EP_IntValue) );
58 return sqlite3AffinityType(pExpr->u.zToken, 0);
59 }
60 #endif
61 if( op==TK_AGG_COLUMN || op==TK_COLUMN ){
62 return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
63 }
64 if( op==TK_SELECT_COLUMN ){
65 assert( pExpr->pLeft->flags&EP_xIsSelect );
66 return sqlite3ExprAffinity(
67 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
68 );
69 }
70 return pExpr->affinity;
71 }
72
73 /*
74 ** Set the collating sequence for expression pExpr to be the collating
75 ** sequence named by pToken. Return a pointer to a new Expr node that
76 ** implements the COLLATE operator.
77 **
78 ** If a memory allocation error occurs, that fact is recorded in pParse->db
79 ** and the pExpr parameter is returned unchanged.
80 */
81 Expr *sqlite3ExprAddCollateToken(
82 Parse *pParse, /* Parsing context */
83 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
84 const Token *pCollName, /* Name of collating sequence */
85 int dequote /* True to dequote pCollName */
86 ){
87 if( pCollName->n>0 ){
88 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
89 if( pNew ){
90 pNew->pLeft = pExpr;
91 pNew->flags |= EP_Collate|EP_Skip;
92 pExpr = pNew;
93 }
94 }
95 return pExpr;
96 }
97 Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
98 Token s;
99 assert( zC!=0 );
100 sqlite3TokenInit(&s, (char*)zC);
101 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
102 }
103
104 /*
105 ** Skip over any TK_COLLATE operators and any unlikely()
106 ** or likelihood() function at the root of an expression.
107 */
108 Expr *sqlite3ExprSkipCollate(Expr *pExpr){
109 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
110 if( ExprHasProperty(pExpr, EP_Unlikely) ){
111 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
112 assert( pExpr->x.pList->nExpr>0 );
113 assert( pExpr->op==TK_FUNCTION );
114 pExpr = pExpr->x.pList->a[0].pExpr;
115 }else{
116 assert( pExpr->op==TK_COLLATE );
117 pExpr = pExpr->pLeft;
118 }
119 }
120 return pExpr;
121 }
122
123 /*
124 ** Return the collation sequence for the expression pExpr. If
125 ** there is no defined collating sequence, return NULL.
126 **
127 ** The collating sequence might be determined by a COLLATE operator
128 ** or by the presence of a column with a defined collating sequence.
129 ** COLLATE operators take first precedence. Left operands take
130 ** precedence over right operands.
131 */
132 CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
133 sqlite3 *db = pParse->db;
134 CollSeq *pColl = 0;
135 Expr *p = pExpr;
136 while( p ){
137 int op = p->op;
138 if( p->flags & EP_Generic ) break;
139 if( op==TK_CAST || op==TK_UPLUS ){
140 p = p->pLeft;
141 continue;
142 }
143 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
144 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
145 break;
146 }
147 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
148 || op==TK_REGISTER || op==TK_TRIGGER)
149 && p->pTab!=0
150 ){
151 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
152 ** a TK_COLUMN but was previously evaluated and cached in a register */
153 int j = p->iColumn;
154 if( j>=0 ){
155 const char *zColl = p->pTab->aCol[j].zColl;
156 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
157 }
158 break;
159 }
160 if( p->flags & EP_Collate ){
161 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
162 p = p->pLeft;
163 }else{
164 Expr *pNext = p->pRight;
165 /* The Expr.x union is never used at the same time as Expr.pRight */
166 assert( p->x.pList==0 || p->pRight==0 );
167 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
168 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
169 ** least one EP_Collate. Thus the following two ALWAYS. */
170 if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
171 int i;
172 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
173 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
174 pNext = p->x.pList->a[i].pExpr;
175 break;
176 }
177 }
178 }
179 p = pNext;
180 }
181 }else{
182 break;
183 }
184 }
185 if( sqlite3CheckCollSeq(pParse, pColl) ){
186 pColl = 0;
187 }
188 return pColl;
189 }
190
191 /*
192 ** pExpr is an operand of a comparison operator. aff2 is the
193 ** type affinity of the other operand. This routine returns the
194 ** type affinity that should be used for the comparison operator.
195 */
196 char sqlite3CompareAffinity(Expr *pExpr, char aff2){
197 char aff1 = sqlite3ExprAffinity(pExpr);
198 if( aff1 && aff2 ){
199 /* Both sides of the comparison are columns. If one has numeric
200 ** affinity, use that. Otherwise use no affinity.
201 */
202 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
203 return SQLITE_AFF_NUMERIC;
204 }else{
205 return SQLITE_AFF_BLOB;
206 }
207 }else if( !aff1 && !aff2 ){
208 /* Neither side of the comparison is a column. Compare the
209 ** results directly.
210 */
211 return SQLITE_AFF_BLOB;
212 }else{
213 /* One side is a column, the other is not. Use the columns affinity. */
214 assert( aff1==0 || aff2==0 );
215 return (aff1 + aff2);
216 }
217 }
218
219 /*
220 ** pExpr is a comparison operator. Return the type affinity that should
221 ** be applied to both operands prior to doing the comparison.
222 */
223 static char comparisonAffinity(Expr *pExpr){
224 char aff;
225 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
226 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
227 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
228 assert( pExpr->pLeft );
229 aff = sqlite3ExprAffinity(pExpr->pLeft);
230 if( pExpr->pRight ){
231 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
232 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
233 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
234 }else if( aff==0 ){
235 aff = SQLITE_AFF_BLOB;
236 }
237 return aff;
238 }
239
240 /*
241 ** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
242 ** idx_affinity is the affinity of an indexed column. Return true
243 ** if the index with affinity idx_affinity may be used to implement
244 ** the comparison in pExpr.
245 */
246 int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
247 char aff = comparisonAffinity(pExpr);
248 switch( aff ){
249 case SQLITE_AFF_BLOB:
250 return 1;
251 case SQLITE_AFF_TEXT:
252 return idx_affinity==SQLITE_AFF_TEXT;
253 default:
254 return sqlite3IsNumericAffinity(idx_affinity);
255 }
256 }
257
258 /*
259 ** Return the P5 value that should be used for a binary comparison
260 ** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
261 */
262 static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
263 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
264 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
265 return aff;
266 }
267
268 /*
269 ** Return a pointer to the collation sequence that should be used by
270 ** a binary comparison operator comparing pLeft and pRight.
271 **
272 ** If the left hand expression has a collating sequence type, then it is
273 ** used. Otherwise the collation sequence for the right hand expression
274 ** is used, or the default (BINARY) if neither expression has a collating
275 ** type.
276 **
277 ** Argument pRight (but not pLeft) may be a null pointer. In this case,
278 ** it is not considered.
279 */
280 CollSeq *sqlite3BinaryCompareCollSeq(
281 Parse *pParse,
282 Expr *pLeft,
283 Expr *pRight
284 ){
285 CollSeq *pColl;
286 assert( pLeft );
287 if( pLeft->flags & EP_Collate ){
288 pColl = sqlite3ExprCollSeq(pParse, pLeft);
289 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
290 pColl = sqlite3ExprCollSeq(pParse, pRight);
291 }else{
292 pColl = sqlite3ExprCollSeq(pParse, pLeft);
293 if( !pColl ){
294 pColl = sqlite3ExprCollSeq(pParse, pRight);
295 }
296 }
297 return pColl;
298 }
299
300 /*
301 ** Generate code for a comparison operator.
302 */
303 static int codeCompare(
304 Parse *pParse, /* The parsing (and code generating) context */
305 Expr *pLeft, /* The left operand */
306 Expr *pRight, /* The right operand */
307 int opcode, /* The comparison opcode */
308 int in1, int in2, /* Register holding operands */
309 int dest, /* Jump here if true. */
310 int jumpIfNull /* If true, jump if either operand is NULL */
311 ){
312 int p5;
313 int addr;
314 CollSeq *p4;
315
316 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
317 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
318 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
319 (void*)p4, P4_COLLSEQ);
320 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
321 return addr;
322 }
323
324 /*
325 ** Return true if expression pExpr is a vector, or false otherwise.
326 **
327 ** A vector is defined as any expression that results in two or more
328 ** columns of result. Every TK_VECTOR node is an vector because the
329 ** parser will not generate a TK_VECTOR with fewer than two entries.
330 ** But a TK_SELECT might be either a vector or a scalar. It is only
331 ** considered a vector if it has two or more result columns.
332 */
333 int sqlite3ExprIsVector(Expr *pExpr){
334 return sqlite3ExprVectorSize(pExpr)>1;
335 }
336
337 /*
338 ** If the expression passed as the only argument is of type TK_VECTOR
339 ** return the number of expressions in the vector. Or, if the expression
340 ** is a sub-select, return the number of columns in the sub-select. For
341 ** any other type of expression, return 1.
342 */
343 int sqlite3ExprVectorSize(Expr *pExpr){
344 u8 op = pExpr->op;
345 if( op==TK_REGISTER ) op = pExpr->op2;
346 if( op==TK_VECTOR ){
347 return pExpr->x.pList->nExpr;
348 }else if( op==TK_SELECT ){
349 return pExpr->x.pSelect->pEList->nExpr;
350 }else{
351 return 1;
352 }
353 }
354
355 #ifndef SQLITE_OMIT_SUBQUERY
356 /*
357 ** Return a pointer to a subexpression of pVector that is the i-th
358 ** column of the vector (numbered starting with 0). The caller must
359 ** ensure that i is within range.
360 **
361 ** If pVector is really a scalar (and "scalar" here includes subqueries
362 ** that return a single column!) then return pVector unmodified.
363 **
364 ** pVector retains ownership of the returned subexpression.
365 **
366 ** If the vector is a (SELECT ...) then the expression returned is
367 ** just the expression for the i-th term of the result set, and may
368 ** not be ready for evaluation because the table cursor has not yet
369 ** been positioned.
370 */
371 Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
372 assert( i<sqlite3ExprVectorSize(pVector) );
373 if( sqlite3ExprIsVector(pVector) ){
374 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
375 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
376 return pVector->x.pSelect->pEList->a[i].pExpr;
377 }else{
378 return pVector->x.pList->a[i].pExpr;
379 }
380 }
381 return pVector;
382 }
383 #endif /* !defined(SQLITE_OMIT_SUBQUERY) */
384
385 #ifndef SQLITE_OMIT_SUBQUERY
386 /*
387 ** Compute and return a new Expr object which when passed to
388 ** sqlite3ExprCode() will generate all necessary code to compute
389 ** the iField-th column of the vector expression pVector.
390 **
391 ** It is ok for pVector to be a scalar (as long as iField==0).
392 ** In that case, this routine works like sqlite3ExprDup().
393 **
394 ** The caller owns the returned Expr object and is responsible for
395 ** ensuring that the returned value eventually gets freed.
396 **
397 ** The caller retains ownership of pVector. If pVector is a TK_SELECT,
398 ** then the returned object will reference pVector and so pVector must remain
399 ** valid for the life of the returned object. If pVector is a TK_VECTOR
400 ** or a scalar expression, then it can be deleted as soon as this routine
401 ** returns.
402 **
403 ** A trick to cause a TK_SELECT pVector to be deleted together with
404 ** the returned Expr object is to attach the pVector to the pRight field
405 ** of the returned TK_SELECT_COLUMN Expr object.
406 */
407 Expr *sqlite3ExprForVectorField(
408 Parse *pParse, /* Parsing context */
409 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
410 int iField /* Which column of the vector to return */
411 ){
412 Expr *pRet;
413 if( pVector->op==TK_SELECT ){
414 assert( pVector->flags & EP_xIsSelect );
415 /* The TK_SELECT_COLUMN Expr node:
416 **
417 ** pLeft: pVector containing TK_SELECT. Not deleted.
418 ** pRight: not used. But recursively deleted.
419 ** iColumn: Index of a column in pVector
420 ** iTable: 0 or the number of columns on the LHS of an assignment
421 ** pLeft->iTable: First in an array of register holding result, or 0
422 ** if the result is not yet computed.
423 **
424 ** sqlite3ExprDelete() specifically skips the recursive delete of
425 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
426 ** can be attached to pRight to cause this node to take ownership of
427 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
428 ** with the same pLeft pointer to the pVector, but only one of them
429 ** will own the pVector.
430 */
431 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
432 if( pRet ){
433 pRet->iColumn = iField;
434 pRet->pLeft = pVector;
435 }
436 assert( pRet==0 || pRet->iTable==0 );
437 }else{
438 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
439 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
440 }
441 return pRet;
442 }
443 #endif /* !define(SQLITE_OMIT_SUBQUERY) */
444
445 /*
446 ** If expression pExpr is of type TK_SELECT, generate code to evaluate
447 ** it. Return the register in which the result is stored (or, if the
448 ** sub-select returns more than one column, the first in an array
449 ** of registers in which the result is stored).
450 **
451 ** If pExpr is not a TK_SELECT expression, return 0.
452 */
453 static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
454 int reg = 0;
455 #ifndef SQLITE_OMIT_SUBQUERY
456 if( pExpr->op==TK_SELECT ){
457 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
458 }
459 #endif
460 return reg;
461 }
462
463 /*
464 ** Argument pVector points to a vector expression - either a TK_VECTOR
465 ** or TK_SELECT that returns more than one column. This function returns
466 ** the register number of a register that contains the value of
467 ** element iField of the vector.
468 **
469 ** If pVector is a TK_SELECT expression, then code for it must have
470 ** already been generated using the exprCodeSubselect() routine. In this
471 ** case parameter regSelect should be the first in an array of registers
472 ** containing the results of the sub-select.
473 **
474 ** If pVector is of type TK_VECTOR, then code for the requested field
475 ** is generated. In this case (*pRegFree) may be set to the number of
476 ** a temporary register to be freed by the caller before returning.
477 **
478 ** Before returning, output parameter (*ppExpr) is set to point to the
479 ** Expr object corresponding to element iElem of the vector.
480 */
481 static int exprVectorRegister(
482 Parse *pParse, /* Parse context */
483 Expr *pVector, /* Vector to extract element from */
484 int iField, /* Field to extract from pVector */
485 int regSelect, /* First in array of registers */
486 Expr **ppExpr, /* OUT: Expression element */
487 int *pRegFree /* OUT: Temp register to free */
488 ){
489 u8 op = pVector->op;
490 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
491 if( op==TK_REGISTER ){
492 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
493 return pVector->iTable+iField;
494 }
495 if( op==TK_SELECT ){
496 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
497 return regSelect+iField;
498 }
499 *ppExpr = pVector->x.pList->a[iField].pExpr;
500 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
501 }
502
503 /*
504 ** Expression pExpr is a comparison between two vector values. Compute
505 ** the result of the comparison (1, 0, or NULL) and write that
506 ** result into register dest.
507 **
508 ** The caller must satisfy the following preconditions:
509 **
510 ** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
511 ** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
512 ** otherwise: op==pExpr->op and p5==0
513 */
514 static void codeVectorCompare(
515 Parse *pParse, /* Code generator context */
516 Expr *pExpr, /* The comparison operation */
517 int dest, /* Write results into this register */
518 u8 op, /* Comparison operator */
519 u8 p5 /* SQLITE_NULLEQ or zero */
520 ){
521 Vdbe *v = pParse->pVdbe;
522 Expr *pLeft = pExpr->pLeft;
523 Expr *pRight = pExpr->pRight;
524 int nLeft = sqlite3ExprVectorSize(pLeft);
525 int i;
526 int regLeft = 0;
527 int regRight = 0;
528 u8 opx = op;
529 int addrDone = sqlite3VdbeMakeLabel(v);
530
531 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
532 sqlite3ErrorMsg(pParse, "row value misused");
533 return;
534 }
535 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
536 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
537 || pExpr->op==TK_LT || pExpr->op==TK_GT
538 || pExpr->op==TK_LE || pExpr->op==TK_GE
539 );
540 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
541 || (pExpr->op==TK_ISNOT && op==TK_NE) );
542 assert( p5==0 || pExpr->op!=op );
543 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
544
545 p5 |= SQLITE_STOREP2;
546 if( opx==TK_LE ) opx = TK_LT;
547 if( opx==TK_GE ) opx = TK_GT;
548
549 regLeft = exprCodeSubselect(pParse, pLeft);
550 regRight = exprCodeSubselect(pParse, pRight);
551
552 for(i=0; 1 /*Loop exits by "break"*/; i++){
553 int regFree1 = 0, regFree2 = 0;
554 Expr *pL, *pR;
555 int r1, r2;
556 assert( i>=0 && i<nLeft );
557 if( i>0 ) sqlite3ExprCachePush(pParse);
558 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
559 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
560 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
561 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
562 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
563 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
564 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
565 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
566 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
567 sqlite3ReleaseTempReg(pParse, regFree1);
568 sqlite3ReleaseTempReg(pParse, regFree2);
569 if( i>0 ) sqlite3ExprCachePop(pParse);
570 if( i==nLeft-1 ){
571 break;
572 }
573 if( opx==TK_EQ ){
574 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
575 p5 |= SQLITE_KEEPNULL;
576 }else if( opx==TK_NE ){
577 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
578 p5 |= SQLITE_KEEPNULL;
579 }else{
580 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
581 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
582 VdbeCoverageIf(v, op==TK_LT);
583 VdbeCoverageIf(v, op==TK_GT);
584 VdbeCoverageIf(v, op==TK_LE);
585 VdbeCoverageIf(v, op==TK_GE);
586 if( i==nLeft-2 ) opx = op;
587 }
588 }
589 sqlite3VdbeResolveLabel(v, addrDone);
590 }
591
592 #if SQLITE_MAX_EXPR_DEPTH>0
593 /*
594 ** Check that argument nHeight is less than or equal to the maximum
595 ** expression depth allowed. If it is not, leave an error message in
596 ** pParse.
597 */
598 int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
599 int rc = SQLITE_OK;
600 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
601 if( nHeight>mxHeight ){
602 sqlite3ErrorMsg(pParse,
603 "Expression tree is too large (maximum depth %d)", mxHeight
604 );
605 rc = SQLITE_ERROR;
606 }
607 return rc;
608 }
609
610 /* The following three functions, heightOfExpr(), heightOfExprList()
611 ** and heightOfSelect(), are used to determine the maximum height
612 ** of any expression tree referenced by the structure passed as the
613 ** first argument.
614 **
615 ** If this maximum height is greater than the current value pointed
616 ** to by pnHeight, the second parameter, then set *pnHeight to that
617 ** value.
618 */
619 static void heightOfExpr(Expr *p, int *pnHeight){
620 if( p ){
621 if( p->nHeight>*pnHeight ){
622 *pnHeight = p->nHeight;
623 }
624 }
625 }
626 static void heightOfExprList(ExprList *p, int *pnHeight){
627 if( p ){
628 int i;
629 for(i=0; i<p->nExpr; i++){
630 heightOfExpr(p->a[i].pExpr, pnHeight);
631 }
632 }
633 }
634 static void heightOfSelect(Select *p, int *pnHeight){
635 if( p ){
636 heightOfExpr(p->pWhere, pnHeight);
637 heightOfExpr(p->pHaving, pnHeight);
638 heightOfExpr(p->pLimit, pnHeight);
639 heightOfExpr(p->pOffset, pnHeight);
640 heightOfExprList(p->pEList, pnHeight);
641 heightOfExprList(p->pGroupBy, pnHeight);
642 heightOfExprList(p->pOrderBy, pnHeight);
643 heightOfSelect(p->pPrior, pnHeight);
644 }
645 }
646
647 /*
648 ** Set the Expr.nHeight variable in the structure passed as an
649 ** argument. An expression with no children, Expr.pList or
650 ** Expr.pSelect member has a height of 1. Any other expression
651 ** has a height equal to the maximum height of any other
652 ** referenced Expr plus one.
653 **
654 ** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
655 ** if appropriate.
656 */
657 static void exprSetHeight(Expr *p){
658 int nHeight = 0;
659 heightOfExpr(p->pLeft, &nHeight);
660 heightOfExpr(p->pRight, &nHeight);
661 if( ExprHasProperty(p, EP_xIsSelect) ){
662 heightOfSelect(p->x.pSelect, &nHeight);
663 }else if( p->x.pList ){
664 heightOfExprList(p->x.pList, &nHeight);
665 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
666 }
667 p->nHeight = nHeight + 1;
668 }
669
670 /*
671 ** Set the Expr.nHeight variable using the exprSetHeight() function. If
672 ** the height is greater than the maximum allowed expression depth,
673 ** leave an error in pParse.
674 **
675 ** Also propagate all EP_Propagate flags from the Expr.x.pList into
676 ** Expr.flags.
677 */
678 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
679 if( pParse->nErr ) return;
680 exprSetHeight(p);
681 sqlite3ExprCheckHeight(pParse, p->nHeight);
682 }
683
684 /*
685 ** Return the maximum height of any expression tree referenced
686 ** by the select statement passed as an argument.
687 */
688 int sqlite3SelectExprHeight(Select *p){
689 int nHeight = 0;
690 heightOfSelect(p, &nHeight);
691 return nHeight;
692 }
693 #else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
694 /*
695 ** Propagate all EP_Propagate flags from the Expr.x.pList into
696 ** Expr.flags.
697 */
698 void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
699 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
700 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
701 }
702 }
703 #define exprSetHeight(y)
704 #endif /* SQLITE_MAX_EXPR_DEPTH>0 */
705
706 /*
707 ** This routine is the core allocator for Expr nodes.
708 **
709 ** Construct a new expression node and return a pointer to it. Memory
710 ** for this node and for the pToken argument is a single allocation
711 ** obtained from sqlite3DbMalloc(). The calling function
712 ** is responsible for making sure the node eventually gets freed.
713 **
714 ** If dequote is true, then the token (if it exists) is dequoted.
715 ** If dequote is false, no dequoting is performed. The deQuote
716 ** parameter is ignored if pToken is NULL or if the token does not
717 ** appear to be quoted. If the quotes were of the form "..." (double-quotes)
718 ** then the EP_DblQuoted flag is set on the expression node.
719 **
720 ** Special case: If op==TK_INTEGER and pToken points to a string that
721 ** can be translated into a 32-bit integer, then the token is not
722 ** stored in u.zToken. Instead, the integer values is written
723 ** into u.iValue and the EP_IntValue flag is set. No extra storage
724 ** is allocated to hold the integer text and the dequote flag is ignored.
725 */
726 Expr *sqlite3ExprAlloc(
727 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
728 int op, /* Expression opcode */
729 const Token *pToken, /* Token argument. Might be NULL */
730 int dequote /* True to dequote */
731 ){
732 Expr *pNew;
733 int nExtra = 0;
734 int iValue = 0;
735
736 assert( db!=0 );
737 if( pToken ){
738 if( op!=TK_INTEGER || pToken->z==0
739 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
740 nExtra = pToken->n+1;
741 assert( iValue>=0 );
742 }
743 }
744 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
745 if( pNew ){
746 memset(pNew, 0, sizeof(Expr));
747 pNew->op = (u8)op;
748 pNew->iAgg = -1;
749 if( pToken ){
750 if( nExtra==0 ){
751 pNew->flags |= EP_IntValue;
752 pNew->u.iValue = iValue;
753 }else{
754 pNew->u.zToken = (char*)&pNew[1];
755 assert( pToken->z!=0 || pToken->n==0 );
756 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
757 pNew->u.zToken[pToken->n] = 0;
758 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
759 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
760 sqlite3Dequote(pNew->u.zToken);
761 }
762 }
763 }
764 #if SQLITE_MAX_EXPR_DEPTH>0
765 pNew->nHeight = 1;
766 #endif
767 }
768 return pNew;
769 }
770
771 /*
772 ** Allocate a new expression node from a zero-terminated token that has
773 ** already been dequoted.
774 */
775 Expr *sqlite3Expr(
776 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
777 int op, /* Expression opcode */
778 const char *zToken /* Token argument. Might be NULL */
779 ){
780 Token x;
781 x.z = zToken;
782 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
783 return sqlite3ExprAlloc(db, op, &x, 0);
784 }
785
786 /*
787 ** Attach subtrees pLeft and pRight to the Expr node pRoot.
788 **
789 ** If pRoot==NULL that means that a memory allocation error has occurred.
790 ** In that case, delete the subtrees pLeft and pRight.
791 */
792 void sqlite3ExprAttachSubtrees(
793 sqlite3 *db,
794 Expr *pRoot,
795 Expr *pLeft,
796 Expr *pRight
797 ){
798 if( pRoot==0 ){
799 assert( db->mallocFailed );
800 sqlite3ExprDelete(db, pLeft);
801 sqlite3ExprDelete(db, pRight);
802 }else{
803 if( pRight ){
804 pRoot->pRight = pRight;
805 pRoot->flags |= EP_Propagate & pRight->flags;
806 }
807 if( pLeft ){
808 pRoot->pLeft = pLeft;
809 pRoot->flags |= EP_Propagate & pLeft->flags;
810 }
811 exprSetHeight(pRoot);
812 }
813 }
814
815 /*
816 ** Allocate an Expr node which joins as many as two subtrees.
817 **
818 ** One or both of the subtrees can be NULL. Return a pointer to the new
819 ** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
820 ** free the subtrees and return NULL.
821 */
822 Expr *sqlite3PExpr(
823 Parse *pParse, /* Parsing context */
824 int op, /* Expression opcode */
825 Expr *pLeft, /* Left operand */
826 Expr *pRight /* Right operand */
827 ){
828 Expr *p;
829 if( op==TK_AND && pParse->nErr==0 ){
830 /* Take advantage of short-circuit false optimization for AND */
831 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
832 }else{
833 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
834 if( p ){
835 memset(p, 0, sizeof(Expr));
836 p->op = op & TKFLG_MASK;
837 p->iAgg = -1;
838 }
839 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
840 }
841 if( p ) {
842 sqlite3ExprCheckHeight(pParse, p->nHeight);
843 }
844 return p;
845 }
846
847 /*
848 ** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
849 ** do a memory allocation failure) then delete the pSelect object.
850 */
851 void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
852 if( pExpr ){
853 pExpr->x.pSelect = pSelect;
854 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
855 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
856 }else{
857 assert( pParse->db->mallocFailed );
858 sqlite3SelectDelete(pParse->db, pSelect);
859 }
860 }
861
862
863 /*
864 ** If the expression is always either TRUE or FALSE (respectively),
865 ** then return 1. If one cannot determine the truth value of the
866 ** expression at compile-time return 0.
867 **
868 ** This is an optimization. If is OK to return 0 here even if
869 ** the expression really is always false or false (a false negative).
870 ** But it is a bug to return 1 if the expression might have different
871 ** boolean values in different circumstances (a false positive.)
872 **
873 ** Note that if the expression is part of conditional for a
874 ** LEFT JOIN, then we cannot determine at compile-time whether or not
875 ** is it true or false, so always return 0.
876 */
877 static int exprAlwaysTrue(Expr *p){
878 int v = 0;
879 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
880 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
881 return v!=0;
882 }
883 static int exprAlwaysFalse(Expr *p){
884 int v = 0;
885 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
886 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
887 return v==0;
888 }
889
890 /*
891 ** Join two expressions using an AND operator. If either expression is
892 ** NULL, then just return the other expression.
893 **
894 ** If one side or the other of the AND is known to be false, then instead
895 ** of returning an AND expression, just return a constant expression with
896 ** a value of false.
897 */
898 Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
899 if( pLeft==0 ){
900 return pRight;
901 }else if( pRight==0 ){
902 return pLeft;
903 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
904 sqlite3ExprDelete(db, pLeft);
905 sqlite3ExprDelete(db, pRight);
906 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
907 }else{
908 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
909 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
910 return pNew;
911 }
912 }
913
914 /*
915 ** Construct a new expression node for a function with multiple
916 ** arguments.
917 */
918 Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
919 Expr *pNew;
920 sqlite3 *db = pParse->db;
921 assert( pToken );
922 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
923 if( pNew==0 ){
924 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
925 return 0;
926 }
927 pNew->x.pList = pList;
928 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
929 sqlite3ExprSetHeightAndFlags(pParse, pNew);
930 return pNew;
931 }
932
933 /*
934 ** Assign a variable number to an expression that encodes a wildcard
935 ** in the original SQL statement.
936 **
937 ** Wildcards consisting of a single "?" are assigned the next sequential
938 ** variable number.
939 **
940 ** Wildcards of the form "?nnn" are assigned the number "nnn". We make
941 ** sure "nnn" is not too big to avoid a denial of service attack when
942 ** the SQL statement comes from an external source.
943 **
944 ** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
945 ** as the previous instance of the same wildcard. Or if this is the first
946 ** instance of the wildcard, the next sequential variable number is
947 ** assigned.
948 */
949 void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
950 sqlite3 *db = pParse->db;
951 const char *z;
952 ynVar x;
953
954 if( pExpr==0 ) return;
955 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
956 z = pExpr->u.zToken;
957 assert( z!=0 );
958 assert( z[0]!=0 );
959 assert( n==sqlite3Strlen30(z) );
960 if( z[1]==0 ){
961 /* Wildcard of the form "?". Assign the next variable number */
962 assert( z[0]=='?' );
963 x = (ynVar)(++pParse->nVar);
964 }else{
965 int doAdd = 0;
966 if( z[0]=='?' ){
967 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
968 ** use it as the variable number */
969 i64 i;
970 int bOk;
971 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
972 i = z[1]-'0'; /* The common case of ?N for a single digit N */
973 bOk = 1;
974 }else{
975 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
976 }
977 testcase( i==0 );
978 testcase( i==1 );
979 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
980 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
981 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
982 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
983 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
984 return;
985 }
986 x = (ynVar)i;
987 if( x>pParse->nVar ){
988 pParse->nVar = (int)x;
989 doAdd = 1;
990 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
991 doAdd = 1;
992 }
993 }else{
994 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
995 ** number as the prior appearance of the same name, or if the name
996 ** has never appeared before, reuse the same variable number
997 */
998 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
999 if( x==0 ){
1000 x = (ynVar)(++pParse->nVar);
1001 doAdd = 1;
1002 }
1003 }
1004 if( doAdd ){
1005 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1006 }
1007 }
1008 pExpr->iColumn = x;
1009 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1010 sqlite3ErrorMsg(pParse, "too many SQL variables");
1011 }
1012 }
1013
1014 /*
1015 ** Recursively delete an expression tree.
1016 */
1017 static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1018 assert( p!=0 );
1019 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1020 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
1021 #ifdef SQLITE_DEBUG
1022 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1023 assert( p->pLeft==0 );
1024 assert( p->pRight==0 );
1025 assert( p->x.pSelect==0 );
1026 }
1027 #endif
1028 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
1029 /* The Expr.x union is never used at the same time as Expr.pRight */
1030 assert( p->x.pList==0 || p->pRight==0 );
1031 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
1032 sqlite3ExprDelete(db, p->pRight);
1033 if( ExprHasProperty(p, EP_xIsSelect) ){
1034 sqlite3SelectDelete(db, p->x.pSelect);
1035 }else{
1036 sqlite3ExprListDelete(db, p->x.pList);
1037 }
1038 }
1039 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
1040 if( !ExprHasProperty(p, EP_Static) ){
1041 sqlite3DbFree(db, p);
1042 }
1043 }
1044 void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1045 if( p ) sqlite3ExprDeleteNN(db, p);
1046 }
1047
1048 /*
1049 ** Return the number of bytes allocated for the expression structure
1050 ** passed as the first argument. This is always one of EXPR_FULLSIZE,
1051 ** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1052 */
1053 static int exprStructSize(Expr *p){
1054 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
1055 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1056 return EXPR_FULLSIZE;
1057 }
1058
1059 /*
1060 ** The dupedExpr*Size() routines each return the number of bytes required
1061 ** to store a copy of an expression or expression tree. They differ in
1062 ** how much of the tree is measured.
1063 **
1064 ** dupedExprStructSize() Size of only the Expr structure
1065 ** dupedExprNodeSize() Size of Expr + space for token
1066 ** dupedExprSize() Expr + token + subtree components
1067 **
1068 ***************************************************************************
1069 **
1070 ** The dupedExprStructSize() function returns two values OR-ed together:
1071 ** (1) the space required for a copy of the Expr structure only and
1072 ** (2) the EP_xxx flags that indicate what the structure size should be.
1073 ** The return values is always one of:
1074 **
1075 ** EXPR_FULLSIZE
1076 ** EXPR_REDUCEDSIZE | EP_Reduced
1077 ** EXPR_TOKENONLYSIZE | EP_TokenOnly
1078 **
1079 ** The size of the structure can be found by masking the return value
1080 ** of this routine with 0xfff. The flags can be found by masking the
1081 ** return value with EP_Reduced|EP_TokenOnly.
1082 **
1083 ** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1084 ** (unreduced) Expr objects as they or originally constructed by the parser.
1085 ** During expression analysis, extra information is computed and moved into
1086 ** later parts of teh Expr object and that extra information might get chopped
1087 ** off if the expression is reduced. Note also that it does not work to
1088 ** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
1089 ** to reduce a pristine expression tree from the parser. The implementation
1090 ** of dupedExprStructSize() contain multiple assert() statements that attempt
1091 ** to enforce this constraint.
1092 */
1093 static int dupedExprStructSize(Expr *p, int flags){
1094 int nSize;
1095 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
1096 assert( EXPR_FULLSIZE<=0xfff );
1097 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
1098 if( 0==flags || p->op==TK_SELECT_COLUMN ){
1099 nSize = EXPR_FULLSIZE;
1100 }else{
1101 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
1102 assert( !ExprHasProperty(p, EP_FromJoin) );
1103 assert( !ExprHasProperty(p, EP_MemToken) );
1104 assert( !ExprHasProperty(p, EP_NoReduce) );
1105 if( p->pLeft || p->x.pList ){
1106 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1107 }else{
1108 assert( p->pRight==0 );
1109 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1110 }
1111 }
1112 return nSize;
1113 }
1114
1115 /*
1116 ** This function returns the space in bytes required to store the copy
1117 ** of the Expr structure and a copy of the Expr.u.zToken string (if that
1118 ** string is defined.)
1119 */
1120 static int dupedExprNodeSize(Expr *p, int flags){
1121 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1122 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1123 nByte += sqlite3Strlen30(p->u.zToken)+1;
1124 }
1125 return ROUND8(nByte);
1126 }
1127
1128 /*
1129 ** Return the number of bytes required to create a duplicate of the
1130 ** expression passed as the first argument. The second argument is a
1131 ** mask containing EXPRDUP_XXX flags.
1132 **
1133 ** The value returned includes space to create a copy of the Expr struct
1134 ** itself and the buffer referred to by Expr.u.zToken, if any.
1135 **
1136 ** If the EXPRDUP_REDUCE flag is set, then the return value includes
1137 ** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1138 ** and Expr.pRight variables (but not for any structures pointed to or
1139 ** descended from the Expr.x.pList or Expr.x.pSelect variables).
1140 */
1141 static int dupedExprSize(Expr *p, int flags){
1142 int nByte = 0;
1143 if( p ){
1144 nByte = dupedExprNodeSize(p, flags);
1145 if( flags&EXPRDUP_REDUCE ){
1146 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
1147 }
1148 }
1149 return nByte;
1150 }
1151
1152 /*
1153 ** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1154 ** is not NULL then *pzBuffer is assumed to point to a buffer large enough
1155 ** to store the copy of expression p, the copies of p->u.zToken
1156 ** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
1157 ** if any. Before returning, *pzBuffer is set to the first byte past the
1158 ** portion of the buffer copied into by this function.
1159 */
1160 static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1161 Expr *pNew; /* Value to return */
1162 u8 *zAlloc; /* Memory space from which to build Expr object */
1163 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1164
1165 assert( db!=0 );
1166 assert( p );
1167 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1168 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
1169
1170 /* Figure out where to write the new Expr structure. */
1171 if( pzBuffer ){
1172 zAlloc = *pzBuffer;
1173 staticFlag = EP_Static;
1174 }else{
1175 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1176 staticFlag = 0;
1177 }
1178 pNew = (Expr *)zAlloc;
1179
1180 if( pNew ){
1181 /* Set nNewSize to the size allocated for the structure pointed to
1182 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1183 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1184 ** by the copy of the p->u.zToken string (if any).
1185 */
1186 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1187 const int nNewSize = nStructSize & 0xfff;
1188 int nToken;
1189 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1190 nToken = sqlite3Strlen30(p->u.zToken) + 1;
1191 }else{
1192 nToken = 0;
1193 }
1194 if( dupFlags ){
1195 assert( ExprHasProperty(p, EP_Reduced)==0 );
1196 memcpy(zAlloc, p, nNewSize);
1197 }else{
1198 u32 nSize = (u32)exprStructSize(p);
1199 memcpy(zAlloc, p, nSize);
1200 if( nSize<EXPR_FULLSIZE ){
1201 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1202 }
1203 }
1204
1205 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1206 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1207 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1208 pNew->flags |= staticFlag;
1209
1210 /* Copy the p->u.zToken string, if any. */
1211 if( nToken ){
1212 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1213 memcpy(zToken, p->u.zToken, nToken);
1214 }
1215
1216 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
1217 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1218 if( ExprHasProperty(p, EP_xIsSelect) ){
1219 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1220 }else{
1221 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1222 }
1223 }
1224
1225 /* Fill in pNew->pLeft and pNew->pRight. */
1226 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1227 zAlloc += dupedExprNodeSize(p, dupFlags);
1228 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
1229 pNew->pLeft = p->pLeft ?
1230 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1231 pNew->pRight = p->pRight ?
1232 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
1233 }
1234 if( pzBuffer ){
1235 *pzBuffer = zAlloc;
1236 }
1237 }else{
1238 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
1239 if( pNew->op==TK_SELECT_COLUMN ){
1240 pNew->pLeft = p->pLeft;
1241 assert( p->iColumn==0 || p->pRight==0 );
1242 assert( p->pRight==0 || p->pRight==p->pLeft );
1243 }else{
1244 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1245 }
1246 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
1247 }
1248 }
1249 }
1250 return pNew;
1251 }
1252
1253 /*
1254 ** Create and return a deep copy of the object passed as the second
1255 ** argument. If an OOM condition is encountered, NULL is returned
1256 ** and the db->mallocFailed flag set.
1257 */
1258 #ifndef SQLITE_OMIT_CTE
1259 static With *withDup(sqlite3 *db, With *p){
1260 With *pRet = 0;
1261 if( p ){
1262 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1263 pRet = sqlite3DbMallocZero(db, nByte);
1264 if( pRet ){
1265 int i;
1266 pRet->nCte = p->nCte;
1267 for(i=0; i<p->nCte; i++){
1268 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1269 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1270 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1271 }
1272 }
1273 }
1274 return pRet;
1275 }
1276 #else
1277 # define withDup(x,y) 0
1278 #endif
1279
1280 /*
1281 ** The following group of routines make deep copies of expressions,
1282 ** expression lists, ID lists, and select statements. The copies can
1283 ** be deleted (by being passed to their respective ...Delete() routines)
1284 ** without effecting the originals.
1285 **
1286 ** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1287 ** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
1288 ** by subsequent calls to sqlite*ListAppend() routines.
1289 **
1290 ** Any tables that the SrcList might point to are not duplicated.
1291 **
1292 ** The flags parameter contains a combination of the EXPRDUP_XXX flags.
1293 ** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1294 ** truncated version of the usual Expr structure that will be stored as
1295 ** part of the in-memory representation of the database schema.
1296 */
1297 Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
1298 assert( flags==0 || flags==EXPRDUP_REDUCE );
1299 return p ? exprDup(db, p, flags, 0) : 0;
1300 }
1301 ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
1302 ExprList *pNew;
1303 struct ExprList_item *pItem, *pOldItem;
1304 int i;
1305 Expr *pPriorSelectCol = 0;
1306 assert( db!=0 );
1307 if( p==0 ) return 0;
1308 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1309 if( pNew==0 ) return 0;
1310 pNew->nExpr = i = p->nExpr;
1311 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
1312 pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
1313 if( pItem==0 ){
1314 sqlite3DbFree(db, pNew);
1315 return 0;
1316 }
1317 pOldItem = p->a;
1318 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
1319 Expr *pOldExpr = pOldItem->pExpr;
1320 Expr *pNewExpr;
1321 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
1322 if( pOldExpr
1323 && pOldExpr->op==TK_SELECT_COLUMN
1324 && (pNewExpr = pItem->pExpr)!=0
1325 ){
1326 assert( pNewExpr->iColumn==0 || i>0 );
1327 if( pNewExpr->iColumn==0 ){
1328 assert( pOldExpr->pLeft==pOldExpr->pRight );
1329 pPriorSelectCol = pNewExpr->pLeft = pNewExpr->pRight;
1330 }else{
1331 assert( i>0 );
1332 assert( pItem[-1].pExpr!=0 );
1333 assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1334 assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1335 pNewExpr->pLeft = pPriorSelectCol;
1336 }
1337 }
1338 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1339 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
1340 pItem->sortOrder = pOldItem->sortOrder;
1341 pItem->done = 0;
1342 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
1343 pItem->u = pOldItem->u;
1344 }
1345 return pNew;
1346 }
1347
1348 /*
1349 ** If cursors, triggers, views and subqueries are all omitted from
1350 ** the build, then none of the following routines, except for
1351 ** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1352 ** called with a NULL argument.
1353 */
1354 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1355 || !defined(SQLITE_OMIT_SUBQUERY)
1356 SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
1357 SrcList *pNew;
1358 int i;
1359 int nByte;
1360 assert( db!=0 );
1361 if( p==0 ) return 0;
1362 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
1363 pNew = sqlite3DbMallocRawNN(db, nByte );
1364 if( pNew==0 ) return 0;
1365 pNew->nSrc = pNew->nAlloc = p->nSrc;
1366 for(i=0; i<p->nSrc; i++){
1367 struct SrcList_item *pNewItem = &pNew->a[i];
1368 struct SrcList_item *pOldItem = &p->a[i];
1369 Table *pTab;
1370 pNewItem->pSchema = pOldItem->pSchema;
1371 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1372 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1373 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
1374 pNewItem->fg = pOldItem->fg;
1375 pNewItem->iCursor = pOldItem->iCursor;
1376 pNewItem->addrFillSub = pOldItem->addrFillSub;
1377 pNewItem->regReturn = pOldItem->regReturn;
1378 if( pNewItem->fg.isIndexedBy ){
1379 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1380 }
1381 pNewItem->pIBIndex = pOldItem->pIBIndex;
1382 if( pNewItem->fg.isTabFunc ){
1383 pNewItem->u1.pFuncArg =
1384 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1385 }
1386 pTab = pNewItem->pTab = pOldItem->pTab;
1387 if( pTab ){
1388 pTab->nTabRef++;
1389 }
1390 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1391 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
1392 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
1393 pNewItem->colUsed = pOldItem->colUsed;
1394 }
1395 return pNew;
1396 }
1397 IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
1398 IdList *pNew;
1399 int i;
1400 assert( db!=0 );
1401 if( p==0 ) return 0;
1402 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
1403 if( pNew==0 ) return 0;
1404 pNew->nId = p->nId;
1405 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
1406 if( pNew->a==0 ){
1407 sqlite3DbFree(db, pNew);
1408 return 0;
1409 }
1410 /* Note that because the size of the allocation for p->a[] is not
1411 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1412 ** on the duplicate created by this function. */
1413 for(i=0; i<p->nId; i++){
1414 struct IdList_item *pNewItem = &pNew->a[i];
1415 struct IdList_item *pOldItem = &p->a[i];
1416 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1417 pNewItem->idx = pOldItem->idx;
1418 }
1419 return pNew;
1420 }
1421 Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1422 Select *pRet = 0;
1423 Select *pNext = 0;
1424 Select **pp = &pRet;
1425 Select *p;
1426
1427 assert( db!=0 );
1428 for(p=pDup; p; p=p->pPrior){
1429 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1430 if( pNew==0 ) break;
1431 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1432 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1433 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1434 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1435 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1436 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1437 pNew->op = p->op;
1438 pNew->pNext = pNext;
1439 pNew->pPrior = 0;
1440 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1441 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
1442 pNew->iLimit = 0;
1443 pNew->iOffset = 0;
1444 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1445 pNew->addrOpenEphm[0] = -1;
1446 pNew->addrOpenEphm[1] = -1;
1447 pNew->nSelectRow = p->nSelectRow;
1448 pNew->pWith = withDup(db, p->pWith);
1449 sqlite3SelectSetName(pNew, p->zSelName);
1450 *pp = pNew;
1451 pp = &pNew->pPrior;
1452 pNext = pNew;
1453 }
1454
1455 return pRet;
1456 }
1457 #else
1458 Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
1459 assert( p==0 );
1460 return 0;
1461 }
1462 #endif
1463
1464
1465 /*
1466 ** Add a new element to the end of an expression list. If pList is
1467 ** initially NULL, then create a new expression list.
1468 **
1469 ** If a memory allocation error occurs, the entire list is freed and
1470 ** NULL is returned. If non-NULL is returned, then it is guaranteed
1471 ** that the new entry was successfully appended.
1472 */
1473 ExprList *sqlite3ExprListAppend(
1474 Parse *pParse, /* Parsing context */
1475 ExprList *pList, /* List to which to append. Might be NULL */
1476 Expr *pExpr /* Expression to be appended. Might be NULL */
1477 ){
1478 sqlite3 *db = pParse->db;
1479 assert( db!=0 );
1480 if( pList==0 ){
1481 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
1482 if( pList==0 ){
1483 goto no_mem;
1484 }
1485 pList->nExpr = 0;
1486 pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
1487 if( pList->a==0 ) goto no_mem;
1488 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
1489 struct ExprList_item *a;
1490 assert( pList->nExpr>0 );
1491 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
1492 if( a==0 ){
1493 goto no_mem;
1494 }
1495 pList->a = a;
1496 }
1497 assert( pList->a!=0 );
1498 if( 1 ){
1499 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1500 memset(pItem, 0, sizeof(*pItem));
1501 pItem->pExpr = pExpr;
1502 }
1503 return pList;
1504
1505 no_mem:
1506 /* Avoid leaking memory if malloc has failed. */
1507 sqlite3ExprDelete(db, pExpr);
1508 sqlite3ExprListDelete(db, pList);
1509 return 0;
1510 }
1511
1512 /*
1513 ** pColumns and pExpr form a vector assignment which is part of the SET
1514 ** clause of an UPDATE statement. Like this:
1515 **
1516 ** (a,b,c) = (expr1,expr2,expr3)
1517 ** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1518 **
1519 ** For each term of the vector assignment, append new entries to the
1520 ** expression list pList. In the case of a subquery on the RHS, append
1521 ** TK_SELECT_COLUMN expressions.
1522 */
1523 ExprList *sqlite3ExprListAppendVector(
1524 Parse *pParse, /* Parsing context */
1525 ExprList *pList, /* List to which to append. Might be NULL */
1526 IdList *pColumns, /* List of names of LHS of the assignment */
1527 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1528 ){
1529 sqlite3 *db = pParse->db;
1530 int n;
1531 int i;
1532 int iFirst = pList ? pList->nExpr : 0;
1533 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1534 ** exit prior to this routine being invoked */
1535 if( NEVER(pColumns==0) ) goto vector_append_error;
1536 if( pExpr==0 ) goto vector_append_error;
1537
1538 /* If the RHS is a vector, then we can immediately check to see that
1539 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1540 ** wildcards ("*") in the result set of the SELECT must be expanded before
1541 ** we can do the size check, so defer the size check until code generation.
1542 */
1543 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
1544 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1545 pColumns->nId, n);
1546 goto vector_append_error;
1547 }
1548
1549 for(i=0; i<pColumns->nId; i++){
1550 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1551 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1552 if( pList ){
1553 assert( pList->nExpr==iFirst+i+1 );
1554 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1555 pColumns->a[i].zName = 0;
1556 }
1557 }
1558
1559 if( pExpr->op==TK_SELECT ){
1560 if( pList && pList->a[iFirst].pExpr ){
1561 Expr *pFirst = pList->a[iFirst].pExpr;
1562 assert( pFirst->op==TK_SELECT_COLUMN );
1563
1564 /* Store the SELECT statement in pRight so it will be deleted when
1565 ** sqlite3ExprListDelete() is called */
1566 pFirst->pRight = pExpr;
1567 pExpr = 0;
1568
1569 /* Remember the size of the LHS in iTable so that we can check that
1570 ** the RHS and LHS sizes match during code generation. */
1571 pFirst->iTable = pColumns->nId;
1572 }
1573 }
1574
1575 vector_append_error:
1576 sqlite3ExprDelete(db, pExpr);
1577 sqlite3IdListDelete(db, pColumns);
1578 return pList;
1579 }
1580
1581 /*
1582 ** Set the sort order for the last element on the given ExprList.
1583 */
1584 void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1585 if( p==0 ) return;
1586 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1587 assert( p->nExpr>0 );
1588 if( iSortOrder<0 ){
1589 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1590 return;
1591 }
1592 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
1593 }
1594
1595 /*
1596 ** Set the ExprList.a[].zName element of the most recently added item
1597 ** on the expression list.
1598 **
1599 ** pList might be NULL following an OOM error. But pName should never be
1600 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1601 ** is set.
1602 */
1603 void sqlite3ExprListSetName(
1604 Parse *pParse, /* Parsing context */
1605 ExprList *pList, /* List to which to add the span. */
1606 Token *pName, /* Name to be added */
1607 int dequote /* True to cause the name to be dequoted */
1608 ){
1609 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1610 if( pList ){
1611 struct ExprList_item *pItem;
1612 assert( pList->nExpr>0 );
1613 pItem = &pList->a[pList->nExpr-1];
1614 assert( pItem->zName==0 );
1615 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1616 if( dequote ) sqlite3Dequote(pItem->zName);
1617 }
1618 }
1619
1620 /*
1621 ** Set the ExprList.a[].zSpan element of the most recently added item
1622 ** on the expression list.
1623 **
1624 ** pList might be NULL following an OOM error. But pSpan should never be
1625 ** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1626 ** is set.
1627 */
1628 void sqlite3ExprListSetSpan(
1629 Parse *pParse, /* Parsing context */
1630 ExprList *pList, /* List to which to add the span. */
1631 ExprSpan *pSpan /* The span to be added */
1632 ){
1633 sqlite3 *db = pParse->db;
1634 assert( pList!=0 || db->mallocFailed!=0 );
1635 if( pList ){
1636 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1637 assert( pList->nExpr>0 );
1638 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1639 sqlite3DbFree(db, pItem->zSpan);
1640 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1641 (int)(pSpan->zEnd - pSpan->zStart));
1642 }
1643 }
1644
1645 /*
1646 ** If the expression list pEList contains more than iLimit elements,
1647 ** leave an error message in pParse.
1648 */
1649 void sqlite3ExprListCheckLength(
1650 Parse *pParse,
1651 ExprList *pEList,
1652 const char *zObject
1653 ){
1654 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1655 testcase( pEList && pEList->nExpr==mx );
1656 testcase( pEList && pEList->nExpr==mx+1 );
1657 if( pEList && pEList->nExpr>mx ){
1658 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1659 }
1660 }
1661
1662 /*
1663 ** Delete an entire expression list.
1664 */
1665 static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
1666 int i;
1667 struct ExprList_item *pItem;
1668 assert( pList->a!=0 || pList->nExpr==0 );
1669 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1670 sqlite3ExprDelete(db, pItem->pExpr);
1671 sqlite3DbFree(db, pItem->zName);
1672 sqlite3DbFree(db, pItem->zSpan);
1673 }
1674 sqlite3DbFree(db, pList->a);
1675 sqlite3DbFree(db, pList);
1676 }
1677 void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1678 if( pList ) exprListDeleteNN(db, pList);
1679 }
1680
1681 /*
1682 ** Return the bitwise-OR of all Expr.flags fields in the given
1683 ** ExprList.
1684 */
1685 u32 sqlite3ExprListFlags(const ExprList *pList){
1686 int i;
1687 u32 m = 0;
1688 if( pList ){
1689 for(i=0; i<pList->nExpr; i++){
1690 Expr *pExpr = pList->a[i].pExpr;
1691 assert( pExpr!=0 );
1692 m |= pExpr->flags;
1693 }
1694 }
1695 return m;
1696 }
1697
1698 /*
1699 ** These routines are Walker callbacks used to check expressions to
1700 ** see if they are "constant" for some definition of constant. The
1701 ** Walker.eCode value determines the type of "constant" we are looking
1702 ** for.
1703 **
1704 ** These callback routines are used to implement the following:
1705 **
1706 ** sqlite3ExprIsConstant() pWalker->eCode==1
1707 ** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
1708 ** sqlite3ExprIsTableConstant() pWalker->eCode==3
1709 ** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
1710 **
1711 ** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1712 ** is found to not be a constant.
1713 **
1714 ** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
1715 ** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1716 ** an existing schema and 4 when processing a new statement. A bound
1717 ** parameter raises an error for new statements, but is silently converted
1718 ** to NULL for existing schemas. This allows sqlite_master tables that
1719 ** contain a bound parameter because they were generated by older versions
1720 ** of SQLite to be parsed by newer versions of SQLite without raising a
1721 ** malformed schema error.
1722 */
1723 static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1724
1725 /* If pWalker->eCode is 2 then any term of the expression that comes from
1726 ** the ON or USING clauses of a left join disqualifies the expression
1727 ** from being considered constant. */
1728 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1729 pWalker->eCode = 0;
1730 return WRC_Abort;
1731 }
1732
1733 switch( pExpr->op ){
1734 /* Consider functions to be constant if all their arguments are constant
1735 ** and either pWalker->eCode==4 or 5 or the function has the
1736 ** SQLITE_FUNC_CONST flag. */
1737 case TK_FUNCTION:
1738 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
1739 return WRC_Continue;
1740 }else{
1741 pWalker->eCode = 0;
1742 return WRC_Abort;
1743 }
1744 case TK_ID:
1745 case TK_COLUMN:
1746 case TK_AGG_FUNCTION:
1747 case TK_AGG_COLUMN:
1748 testcase( pExpr->op==TK_ID );
1749 testcase( pExpr->op==TK_COLUMN );
1750 testcase( pExpr->op==TK_AGG_FUNCTION );
1751 testcase( pExpr->op==TK_AGG_COLUMN );
1752 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1753 return WRC_Continue;
1754 }else{
1755 pWalker->eCode = 0;
1756 return WRC_Abort;
1757 }
1758 case TK_VARIABLE:
1759 if( pWalker->eCode==5 ){
1760 /* Silently convert bound parameters that appear inside of CREATE
1761 ** statements into a NULL when parsing the CREATE statement text out
1762 ** of the sqlite_master table */
1763 pExpr->op = TK_NULL;
1764 }else if( pWalker->eCode==4 ){
1765 /* A bound parameter in a CREATE statement that originates from
1766 ** sqlite3_prepare() causes an error */
1767 pWalker->eCode = 0;
1768 return WRC_Abort;
1769 }
1770 /* Fall through */
1771 default:
1772 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1773 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
1774 return WRC_Continue;
1775 }
1776 }
1777 static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1778 UNUSED_PARAMETER(NotUsed);
1779 pWalker->eCode = 0;
1780 return WRC_Abort;
1781 }
1782 static int exprIsConst(Expr *p, int initFlag, int iCur){
1783 Walker w;
1784 memset(&w, 0, sizeof(w));
1785 w.eCode = initFlag;
1786 w.xExprCallback = exprNodeIsConstant;
1787 w.xSelectCallback = selectNodeIsConstant;
1788 w.u.iCur = iCur;
1789 sqlite3WalkExpr(&w, p);
1790 return w.eCode;
1791 }
1792
1793 /*
1794 ** Walk an expression tree. Return non-zero if the expression is constant
1795 ** and 0 if it involves variables or function calls.
1796 **
1797 ** For the purposes of this function, a double-quoted string (ex: "abc")
1798 ** is considered a variable but a single-quoted string (ex: 'abc') is
1799 ** a constant.
1800 */
1801 int sqlite3ExprIsConstant(Expr *p){
1802 return exprIsConst(p, 1, 0);
1803 }
1804
1805 /*
1806 ** Walk an expression tree. Return non-zero if the expression is constant
1807 ** that does no originate from the ON or USING clauses of a join.
1808 ** Return 0 if it involves variables or function calls or terms from
1809 ** an ON or USING clause.
1810 */
1811 int sqlite3ExprIsConstantNotJoin(Expr *p){
1812 return exprIsConst(p, 2, 0);
1813 }
1814
1815 /*
1816 ** Walk an expression tree. Return non-zero if the expression is constant
1817 ** for any single row of the table with cursor iCur. In other words, the
1818 ** expression must not refer to any non-deterministic function nor any
1819 ** table other than iCur.
1820 */
1821 int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1822 return exprIsConst(p, 3, iCur);
1823 }
1824
1825 /*
1826 ** Walk an expression tree. Return non-zero if the expression is constant
1827 ** or a function call with constant arguments. Return and 0 if there
1828 ** are any variables.
1829 **
1830 ** For the purposes of this function, a double-quoted string (ex: "abc")
1831 ** is considered a variable but a single-quoted string (ex: 'abc') is
1832 ** a constant.
1833 */
1834 int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1835 assert( isInit==0 || isInit==1 );
1836 return exprIsConst(p, 4+isInit, 0);
1837 }
1838
1839 #ifdef SQLITE_ENABLE_CURSOR_HINTS
1840 /*
1841 ** Walk an expression tree. Return 1 if the expression contains a
1842 ** subquery of some kind. Return 0 if there are no subqueries.
1843 */
1844 int sqlite3ExprContainsSubquery(Expr *p){
1845 Walker w;
1846 memset(&w, 0, sizeof(w));
1847 w.eCode = 1;
1848 w.xExprCallback = sqlite3ExprWalkNoop;
1849 w.xSelectCallback = selectNodeIsConstant;
1850 sqlite3WalkExpr(&w, p);
1851 return w.eCode==0;
1852 }
1853 #endif
1854
1855 /*
1856 ** If the expression p codes a constant integer that is small enough
1857 ** to fit in a 32-bit integer, return 1 and put the value of the integer
1858 ** in *pValue. If the expression is not an integer or if it is too big
1859 ** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1860 */
1861 int sqlite3ExprIsInteger(Expr *p, int *pValue){
1862 int rc = 0;
1863
1864 /* If an expression is an integer literal that fits in a signed 32-bit
1865 ** integer, then the EP_IntValue flag will have already been set */
1866 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1867 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1868
1869 if( p->flags & EP_IntValue ){
1870 *pValue = p->u.iValue;
1871 return 1;
1872 }
1873 switch( p->op ){
1874 case TK_UPLUS: {
1875 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1876 break;
1877 }
1878 case TK_UMINUS: {
1879 int v;
1880 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1881 assert( v!=(-2147483647-1) );
1882 *pValue = -v;
1883 rc = 1;
1884 }
1885 break;
1886 }
1887 default: break;
1888 }
1889 return rc;
1890 }
1891
1892 /*
1893 ** Return FALSE if there is no chance that the expression can be NULL.
1894 **
1895 ** If the expression might be NULL or if the expression is too complex
1896 ** to tell return TRUE.
1897 **
1898 ** This routine is used as an optimization, to skip OP_IsNull opcodes
1899 ** when we know that a value cannot be NULL. Hence, a false positive
1900 ** (returning TRUE when in fact the expression can never be NULL) might
1901 ** be a small performance hit but is otherwise harmless. On the other
1902 ** hand, a false negative (returning FALSE when the result could be NULL)
1903 ** will likely result in an incorrect answer. So when in doubt, return
1904 ** TRUE.
1905 */
1906 int sqlite3ExprCanBeNull(const Expr *p){
1907 u8 op;
1908 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1909 op = p->op;
1910 if( op==TK_REGISTER ) op = p->op2;
1911 switch( op ){
1912 case TK_INTEGER:
1913 case TK_STRING:
1914 case TK_FLOAT:
1915 case TK_BLOB:
1916 return 0;
1917 case TK_COLUMN:
1918 assert( p->pTab!=0 );
1919 return ExprHasProperty(p, EP_CanBeNull) ||
1920 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
1921 default:
1922 return 1;
1923 }
1924 }
1925
1926 /*
1927 ** Return TRUE if the given expression is a constant which would be
1928 ** unchanged by OP_Affinity with the affinity given in the second
1929 ** argument.
1930 **
1931 ** This routine is used to determine if the OP_Affinity operation
1932 ** can be omitted. When in doubt return FALSE. A false negative
1933 ** is harmless. A false positive, however, can result in the wrong
1934 ** answer.
1935 */
1936 int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1937 u8 op;
1938 if( aff==SQLITE_AFF_BLOB ) return 1;
1939 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1940 op = p->op;
1941 if( op==TK_REGISTER ) op = p->op2;
1942 switch( op ){
1943 case TK_INTEGER: {
1944 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1945 }
1946 case TK_FLOAT: {
1947 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1948 }
1949 case TK_STRING: {
1950 return aff==SQLITE_AFF_TEXT;
1951 }
1952 case TK_BLOB: {
1953 return 1;
1954 }
1955 case TK_COLUMN: {
1956 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1957 return p->iColumn<0
1958 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
1959 }
1960 default: {
1961 return 0;
1962 }
1963 }
1964 }
1965
1966 /*
1967 ** Return TRUE if the given string is a row-id column name.
1968 */
1969 int sqlite3IsRowid(const char *z){
1970 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1971 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1972 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1973 return 0;
1974 }
1975
1976 /*
1977 ** pX is the RHS of an IN operator. If pX is a SELECT statement
1978 ** that can be simplified to a direct table access, then return
1979 ** a pointer to the SELECT statement. If pX is not a SELECT statement,
1980 ** or if the SELECT statement needs to be manifested into a transient
1981 ** table, then return NULL.
1982 */
1983 #ifndef SQLITE_OMIT_SUBQUERY
1984 static Select *isCandidateForInOpt(Expr *pX){
1985 Select *p;
1986 SrcList *pSrc;
1987 ExprList *pEList;
1988 Table *pTab;
1989 int i;
1990 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1991 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1992 p = pX->x.pSelect;
1993 if( p->pPrior ) return 0; /* Not a compound SELECT */
1994 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1995 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1996 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1997 return 0; /* No DISTINCT keyword and no aggregate functions */
1998 }
1999 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
2000 if( p->pLimit ) return 0; /* Has no LIMIT clause */
2001 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
2002 if( p->pWhere ) return 0; /* Has no WHERE clause */
2003 pSrc = p->pSrc;
2004 assert( pSrc!=0 );
2005 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
2006 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
2007 pTab = pSrc->a[0].pTab;
2008 assert( pTab!=0 );
2009 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
2010 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2011 pEList = p->pEList;
2012 assert( pEList!=0 );
2013 /* All SELECT results must be columns. */
2014 for(i=0; i<pEList->nExpr; i++){
2015 Expr *pRes = pEList->a[i].pExpr;
2016 if( pRes->op!=TK_COLUMN ) return 0;
2017 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
2018 }
2019 return p;
2020 }
2021 #endif /* SQLITE_OMIT_SUBQUERY */
2022
2023 #ifndef SQLITE_OMIT_SUBQUERY
2024 /*
2025 ** Generate code that checks the left-most column of index table iCur to see if
2026 ** it contains any NULL entries. Cause the register at regHasNull to be set
2027 ** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2028 ** to be set to NULL if iCur contains one or more NULL values.
2029 */
2030 static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
2031 int addr1;
2032 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
2033 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
2034 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2035 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
2036 VdbeComment((v, "first_entry_in(%d)", iCur));
2037 sqlite3VdbeJumpHere(v, addr1);
2038 }
2039 #endif
2040
2041
2042 #ifndef SQLITE_OMIT_SUBQUERY
2043 /*
2044 ** The argument is an IN operator with a list (not a subquery) on the
2045 ** right-hand side. Return TRUE if that list is constant.
2046 */
2047 static int sqlite3InRhsIsConstant(Expr *pIn){
2048 Expr *pLHS;
2049 int res;
2050 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2051 pLHS = pIn->pLeft;
2052 pIn->pLeft = 0;
2053 res = sqlite3ExprIsConstant(pIn);
2054 pIn->pLeft = pLHS;
2055 return res;
2056 }
2057 #endif
2058
2059 /*
2060 ** This function is used by the implementation of the IN (...) operator.
2061 ** The pX parameter is the expression on the RHS of the IN operator, which
2062 ** might be either a list of expressions or a subquery.
2063 **
2064 ** The job of this routine is to find or create a b-tree object that can
2065 ** be used either to test for membership in the RHS set or to iterate through
2066 ** all members of the RHS set, skipping duplicates.
2067 **
2068 ** A cursor is opened on the b-tree object that is the RHS of the IN operator
2069 ** and pX->iTable is set to the index of that cursor.
2070 **
2071 ** The returned value of this function indicates the b-tree type, as follows:
2072 **
2073 ** IN_INDEX_ROWID - The cursor was opened on a database table.
2074 ** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2075 ** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2076 ** IN_INDEX_EPH - The cursor was opened on a specially created and
2077 ** populated epheremal table.
2078 ** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2079 ** implemented as a sequence of comparisons.
2080 **
2081 ** An existing b-tree might be used if the RHS expression pX is a simple
2082 ** subquery such as:
2083 **
2084 ** SELECT <column1>, <column2>... FROM <table>
2085 **
2086 ** If the RHS of the IN operator is a list or a more complex subquery, then
2087 ** an ephemeral table might need to be generated from the RHS and then
2088 ** pX->iTable made to point to the ephemeral table instead of an
2089 ** existing table.
2090 **
2091 ** The inFlags parameter must contain exactly one of the bits
2092 ** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
2093 ** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
2094 ** fast membership test. When the IN_INDEX_LOOP bit is set, the
2095 ** IN index will be used to loop over all values of the RHS of the
2096 ** IN operator.
2097 **
2098 ** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2099 ** through the set members) then the b-tree must not contain duplicates.
2100 ** An epheremal table must be used unless the selected columns are guaranteed
2101 ** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2102 ** a UNIQUE constraint or index.
2103 **
2104 ** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2105 ** for fast set membership tests) then an epheremal table must
2106 ** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2107 ** index can be found with the specified <columns> as its left-most.
2108 **
2109 ** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2110 ** if the RHS of the IN operator is a list (not a subquery) then this
2111 ** routine might decide that creating an ephemeral b-tree for membership
2112 ** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2113 ** calling routine should implement the IN operator using a sequence
2114 ** of Eq or Ne comparison operations.
2115 **
2116 ** When the b-tree is being used for membership tests, the calling function
2117 ** might need to know whether or not the RHS side of the IN operator
2118 ** contains a NULL. If prRhsHasNull is not a NULL pointer and
2119 ** if there is any chance that the (...) might contain a NULL value at
2120 ** runtime, then a register is allocated and the register number written
2121 ** to *prRhsHasNull. If there is no chance that the (...) contains a
2122 ** NULL value, then *prRhsHasNull is left unchanged.
2123 **
2124 ** If a register is allocated and its location stored in *prRhsHasNull, then
2125 ** the value in that register will be NULL if the b-tree contains one or more
2126 ** NULL values, and it will be some non-NULL value if the b-tree contains no
2127 ** NULL values.
2128 **
2129 ** If the aiMap parameter is not NULL, it must point to an array containing
2130 ** one element for each column returned by the SELECT statement on the RHS
2131 ** of the IN(...) operator. The i'th entry of the array is populated with the
2132 ** offset of the index column that matches the i'th column returned by the
2133 ** SELECT. For example, if the expression and selected index are:
2134 **
2135 ** (?,?,?) IN (SELECT a, b, c FROM t1)
2136 ** CREATE INDEX i1 ON t1(b, c, a);
2137 **
2138 ** then aiMap[] is populated with {2, 0, 1}.
2139 */
2140 #ifndef SQLITE_OMIT_SUBQUERY
2141 int sqlite3FindInIndex(
2142 Parse *pParse, /* Parsing context */
2143 Expr *pX, /* The right-hand side (RHS) of the IN operator */
2144 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2145 int *prRhsHasNull, /* Register holding NULL status. See notes */
2146 int *aiMap /* Mapping from Index fields to RHS fields */
2147 ){
2148 Select *p; /* SELECT to the right of IN operator */
2149 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2150 int iTab = pParse->nTab++; /* Cursor of the RHS table */
2151 int mustBeUnique; /* True if RHS must be unique */
2152 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
2153
2154 assert( pX->op==TK_IN );
2155 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
2156
2157 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2158 ** whether or not the SELECT result contains NULL values, check whether
2159 ** or not NULL is actually possible (it may not be, for example, due
2160 ** to NOT NULL constraints in the schema). If no NULL values are possible,
2161 ** set prRhsHasNull to 0 before continuing. */
2162 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2163 int i;
2164 ExprList *pEList = pX->x.pSelect->pEList;
2165 for(i=0; i<pEList->nExpr; i++){
2166 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2167 }
2168 if( i==pEList->nExpr ){
2169 prRhsHasNull = 0;
2170 }
2171 }
2172
2173 /* Check to see if an existing table or index can be used to
2174 ** satisfy the query. This is preferable to generating a new
2175 ** ephemeral table. */
2176 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
2177 sqlite3 *db = pParse->db; /* Database connection */
2178 Table *pTab; /* Table <table>. */
2179 i16 iDb; /* Database idx for pTab */
2180 ExprList *pEList = p->pEList;
2181 int nExpr = pEList->nExpr;
2182
2183 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2184 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2185 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2186 pTab = p->pSrc->a[0].pTab;
2187
2188 /* Code an OP_Transaction and OP_TableLock for <table>. */
2189 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2190 sqlite3CodeVerifySchema(pParse, iDb);
2191 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
2192
2193 assert(v); /* sqlite3GetVdbe() has always been previously called */
2194 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
2195 /* The "x IN (SELECT rowid FROM table)" case */
2196 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
2197 VdbeCoverage(v);
2198
2199 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2200 eType = IN_INDEX_ROWID;
2201
2202 sqlite3VdbeJumpHere(v, iAddr);
2203 }else{
2204 Index *pIdx; /* Iterator variable */
2205 int affinity_ok = 1;
2206 int i;
2207
2208 /* Check that the affinity that will be used to perform each
2209 ** comparison is the same as the affinity of each column in table
2210 ** on the RHS of the IN operator. If it not, it is not possible to
2211 ** use any index of the RHS table. */
2212 for(i=0; i<nExpr && affinity_ok; i++){
2213 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2214 int iCol = pEList->a[i].pExpr->iColumn;
2215 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
2216 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2217 testcase( cmpaff==SQLITE_AFF_BLOB );
2218 testcase( cmpaff==SQLITE_AFF_TEXT );
2219 switch( cmpaff ){
2220 case SQLITE_AFF_BLOB:
2221 break;
2222 case SQLITE_AFF_TEXT:
2223 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2224 ** other has no affinity and the other side is TEXT. Hence,
2225 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2226 ** and for the term on the LHS of the IN to have no affinity. */
2227 assert( idxaff==SQLITE_AFF_TEXT );
2228 break;
2229 default:
2230 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2231 }
2232 }
2233
2234 if( affinity_ok ){
2235 /* Search for an existing index that will work for this IN operator */
2236 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2237 Bitmask colUsed; /* Columns of the index used */
2238 Bitmask mCol; /* Mask for the current column */
2239 if( pIdx->nColumn<nExpr ) continue;
2240 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2241 ** BITMASK(nExpr) without overflowing */
2242 testcase( pIdx->nColumn==BMS-2 );
2243 testcase( pIdx->nColumn==BMS-1 );
2244 if( pIdx->nColumn>=BMS-1 ) continue;
2245 if( mustBeUnique ){
2246 if( pIdx->nKeyCol>nExpr
2247 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2248 ){
2249 continue; /* This index is not unique over the IN RHS columns */
2250 }
2251 }
2252
2253 colUsed = 0; /* Columns of index used so far */
2254 for(i=0; i<nExpr; i++){
2255 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2256 Expr *pRhs = pEList->a[i].pExpr;
2257 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2258 int j;
2259
2260 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2261 for(j=0; j<nExpr; j++){
2262 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2263 assert( pIdx->azColl[j] );
2264 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2265 continue;
2266 }
2267 break;
2268 }
2269 if( j==nExpr ) break;
2270 mCol = MASKBIT(j);
2271 if( mCol & colUsed ) break; /* Each column used only once */
2272 colUsed |= mCol;
2273 if( aiMap ) aiMap[i] = j;
2274 }
2275
2276 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2277 if( colUsed==(MASKBIT(nExpr)-1) ){
2278 /* If we reach this point, that means the index pIdx is usable */
2279 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2280 #ifndef SQLITE_OMIT_EXPLAIN
2281 sqlite3VdbeAddOp4(v, OP_Explain, 0, 0, 0,
2282 sqlite3MPrintf(db, "USING INDEX %s FOR IN-OPERATOR",pIdx->zName),
2283 P4_DYNAMIC);
2284 #endif
2285 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2286 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2287 VdbeComment((v, "%s", pIdx->zName));
2288 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2289 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2290
2291 if( prRhsHasNull ){
2292 #ifdef SQLITE_ENABLE_COLUMN_USED_MASK
2293 i64 mask = (1<<nExpr)-1;
2294 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2295 iTab, 0, 0, (u8*)&mask, P4_INT64);
2296 #endif
2297 *prRhsHasNull = ++pParse->nMem;
2298 if( nExpr==1 ){
2299 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2300 }
2301 }
2302 sqlite3VdbeJumpHere(v, iAddr);
2303 }
2304 } /* End loop over indexes */
2305 } /* End if( affinity_ok ) */
2306 } /* End if not an rowid index */
2307 } /* End attempt to optimize using an index */
2308
2309 /* If no preexisting index is available for the IN clause
2310 ** and IN_INDEX_NOOP is an allowed reply
2311 ** and the RHS of the IN operator is a list, not a subquery
2312 ** and the RHS is not constant or has two or fewer terms,
2313 ** then it is not worth creating an ephemeral table to evaluate
2314 ** the IN operator so return IN_INDEX_NOOP.
2315 */
2316 if( eType==0
2317 && (inFlags & IN_INDEX_NOOP_OK)
2318 && !ExprHasProperty(pX, EP_xIsSelect)
2319 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2320 ){
2321 eType = IN_INDEX_NOOP;
2322 }
2323
2324 if( eType==0 ){
2325 /* Could not find an existing table or index to use as the RHS b-tree.
2326 ** We will have to generate an ephemeral table to do the job.
2327 */
2328 u32 savedNQueryLoop = pParse->nQueryLoop;
2329 int rMayHaveNull = 0;
2330 eType = IN_INDEX_EPH;
2331 if( inFlags & IN_INDEX_LOOP ){
2332 pParse->nQueryLoop = 0;
2333 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
2334 eType = IN_INDEX_ROWID;
2335 }
2336 }else if( prRhsHasNull ){
2337 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
2338 }
2339 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
2340 pParse->nQueryLoop = savedNQueryLoop;
2341 }else{
2342 pX->iTable = iTab;
2343 }
2344
2345 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2346 int i, n;
2347 n = sqlite3ExprVectorSize(pX->pLeft);
2348 for(i=0; i<n; i++) aiMap[i] = i;
2349 }
2350 return eType;
2351 }
2352 #endif
2353
2354 #ifndef SQLITE_OMIT_SUBQUERY
2355 /*
2356 ** Argument pExpr is an (?, ?...) IN(...) expression. This
2357 ** function allocates and returns a nul-terminated string containing
2358 ** the affinities to be used for each column of the comparison.
2359 **
2360 ** It is the responsibility of the caller to ensure that the returned
2361 ** string is eventually freed using sqlite3DbFree().
2362 */
2363 static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2364 Expr *pLeft = pExpr->pLeft;
2365 int nVal = sqlite3ExprVectorSize(pLeft);
2366 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
2367 char *zRet;
2368
2369 assert( pExpr->op==TK_IN );
2370 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2371 if( zRet ){
2372 int i;
2373 for(i=0; i<nVal; i++){
2374 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
2375 char a = sqlite3ExprAffinity(pA);
2376 if( pSelect ){
2377 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2378 }else{
2379 zRet[i] = a;
2380 }
2381 }
2382 zRet[nVal] = '\0';
2383 }
2384 return zRet;
2385 }
2386 #endif
2387
2388 #ifndef SQLITE_OMIT_SUBQUERY
2389 /*
2390 ** Load the Parse object passed as the first argument with an error
2391 ** message of the form:
2392 **
2393 ** "sub-select returns N columns - expected M"
2394 */
2395 void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2396 const char *zFmt = "sub-select returns %d columns - expected %d";
2397 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2398 }
2399 #endif
2400
2401 /*
2402 ** Expression pExpr is a vector that has been used in a context where
2403 ** it is not permitted. If pExpr is a sub-select vector, this routine
2404 ** loads the Parse object with a message of the form:
2405 **
2406 ** "sub-select returns N columns - expected 1"
2407 **
2408 ** Or, if it is a regular scalar vector:
2409 **
2410 ** "row value misused"
2411 */
2412 void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2413 #ifndef SQLITE_OMIT_SUBQUERY
2414 if( pExpr->flags & EP_xIsSelect ){
2415 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2416 }else
2417 #endif
2418 {
2419 sqlite3ErrorMsg(pParse, "row value misused");
2420 }
2421 }
2422
2423 /*
2424 ** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2425 ** or IN operators. Examples:
2426 **
2427 ** (SELECT a FROM b) -- subquery
2428 ** EXISTS (SELECT a FROM b) -- EXISTS subquery
2429 ** x IN (4,5,11) -- IN operator with list on right-hand side
2430 ** x IN (SELECT a FROM b) -- IN operator with subquery on the right
2431 **
2432 ** The pExpr parameter describes the expression that contains the IN
2433 ** operator or subquery.
2434 **
2435 ** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2436 ** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2437 ** to some integer key column of a table B-Tree. In this case, use an
2438 ** intkey B-Tree to store the set of IN(...) values instead of the usual
2439 ** (slower) variable length keys B-Tree.
2440 **
2441 ** If rMayHaveNull is non-zero, that means that the operation is an IN
2442 ** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
2443 ** All this routine does is initialize the register given by rMayHaveNull
2444 ** to NULL. Calling routines will take care of changing this register
2445 ** value to non-NULL if the RHS is NULL-free.
2446 **
2447 ** For a SELECT or EXISTS operator, return the register that holds the
2448 ** result. For a multi-column SELECT, the result is stored in a contiguous
2449 ** array of registers and the return value is the register of the left-most
2450 ** result column. Return 0 for IN operators or if an error occurs.
2451 */
2452 #ifndef SQLITE_OMIT_SUBQUERY
2453 int sqlite3CodeSubselect(
2454 Parse *pParse, /* Parsing context */
2455 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
2456 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
2457 int isRowid /* If true, LHS of IN operator is a rowid */
2458 ){
2459 int jmpIfDynamic = -1; /* One-time test address */
2460 int rReg = 0; /* Register storing resulting */
2461 Vdbe *v = sqlite3GetVdbe(pParse);
2462 if( NEVER(v==0) ) return 0;
2463 sqlite3ExprCachePush(pParse);
2464
2465 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2466 ** is encountered if any of the following is true:
2467 **
2468 ** * The right-hand side is a correlated subquery
2469 ** * The right-hand side is an expression list containing variables
2470 ** * We are inside a trigger
2471 **
2472 ** If all of the above are false, then we can run this code just once
2473 ** save the results, and reuse the same result on subsequent invocations.
2474 */
2475 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
2476 jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
2477 }
2478
2479 #ifndef SQLITE_OMIT_EXPLAIN
2480 if( pParse->explain==2 ){
2481 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2482 jmpIfDynamic>=0?"":"CORRELATED ",
2483 pExpr->op==TK_IN?"LIST":"SCALAR",
2484 pParse->iNextSelectId
2485 );
2486 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2487 }
2488 #endif
2489
2490 switch( pExpr->op ){
2491 case TK_IN: {
2492 int addr; /* Address of OP_OpenEphemeral instruction */
2493 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
2494 KeyInfo *pKeyInfo = 0; /* Key information */
2495 int nVal; /* Size of vector pLeft */
2496
2497 nVal = sqlite3ExprVectorSize(pLeft);
2498 assert( !isRowid || nVal==1 );
2499
2500 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
2501 ** expression it is handled the same way. An ephemeral table is
2502 ** filled with index keys representing the results from the
2503 ** SELECT or the <exprlist>.
2504 **
2505 ** If the 'x' expression is a column value, or the SELECT...
2506 ** statement returns a column value, then the affinity of that
2507 ** column is used to build the index keys. If both 'x' and the
2508 ** SELECT... statement are columns, then numeric affinity is used
2509 ** if either column has NUMERIC or INTEGER affinity. If neither
2510 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2511 ** is used.
2512 */
2513 pExpr->iTable = pParse->nTab++;
2514 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2515 pExpr->iTable, (isRowid?0:nVal));
2516 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
2517
2518 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
2519 /* Case 1: expr IN (SELECT ...)
2520 **
2521 ** Generate code to write the results of the select into the temporary
2522 ** table allocated and opened above.
2523 */
2524 Select *pSelect = pExpr->x.pSelect;
2525 ExprList *pEList = pSelect->pEList;
2526
2527 assert( !isRowid );
2528 /* If the LHS and RHS of the IN operator do not match, that
2529 ** error will have been caught long before we reach this point. */
2530 if( ALWAYS(pEList->nExpr==nVal) ){
2531 SelectDest dest;
2532 int i;
2533 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2534 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2535 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2536 pSelect->iLimit = 0;
2537 testcase( pSelect->selFlags & SF_Distinct );
2538 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2539 if( sqlite3Select(pParse, pSelect, &dest) ){
2540 sqlite3DbFree(pParse->db, dest.zAffSdst);
2541 sqlite3KeyInfoUnref(pKeyInfo);
2542 return 0;
2543 }
2544 sqlite3DbFree(pParse->db, dest.zAffSdst);
2545 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2546 assert( pEList!=0 );
2547 assert( pEList->nExpr>0 );
2548 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2549 for(i=0; i<nVal; i++){
2550 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
2551 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2552 pParse, p, pEList->a[i].pExpr
2553 );
2554 }
2555 }
2556 }else if( ALWAYS(pExpr->x.pList!=0) ){
2557 /* Case 2: expr IN (exprlist)
2558 **
2559 ** For each expression, build an index key from the evaluation and
2560 ** store it in the temporary table. If <expr> is a column, then use
2561 ** that columns affinity when building index keys. If <expr> is not
2562 ** a column, use numeric affinity.
2563 */
2564 char affinity; /* Affinity of the LHS of the IN */
2565 int i;
2566 ExprList *pList = pExpr->x.pList;
2567 struct ExprList_item *pItem;
2568 int r1, r2, r3;
2569
2570 affinity = sqlite3ExprAffinity(pLeft);
2571 if( !affinity ){
2572 affinity = SQLITE_AFF_BLOB;
2573 }
2574 if( pKeyInfo ){
2575 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2576 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2577 }
2578
2579 /* Loop through each expression in <exprlist>. */
2580 r1 = sqlite3GetTempReg(pParse);
2581 r2 = sqlite3GetTempReg(pParse);
2582 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
2583 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2584 Expr *pE2 = pItem->pExpr;
2585 int iValToIns;
2586
2587 /* If the expression is not constant then we will need to
2588 ** disable the test that was generated above that makes sure
2589 ** this code only executes once. Because for a non-constant
2590 ** expression we need to rerun this code each time.
2591 */
2592 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2593 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2594 jmpIfDynamic = -1;
2595 }
2596
2597 /* Evaluate the expression and insert it into the temp table */
2598 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2599 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
2600 }else{
2601 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2602 if( isRowid ){
2603 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2604 sqlite3VdbeCurrentAddr(v)+2);
2605 VdbeCoverage(v);
2606 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2607 }else{
2608 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2609 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2610 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
2611 }
2612 }
2613 }
2614 sqlite3ReleaseTempReg(pParse, r1);
2615 sqlite3ReleaseTempReg(pParse, r2);
2616 }
2617 if( pKeyInfo ){
2618 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
2619 }
2620 break;
2621 }
2622
2623 case TK_EXISTS:
2624 case TK_SELECT:
2625 default: {
2626 /* Case 3: (SELECT ... FROM ...)
2627 ** or: EXISTS(SELECT ... FROM ...)
2628 **
2629 ** For a SELECT, generate code to put the values for all columns of
2630 ** the first row into an array of registers and return the index of
2631 ** the first register.
2632 **
2633 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2634 ** into a register and return that register number.
2635 **
2636 ** In both cases, the query is augmented with "LIMIT 1". Any
2637 ** preexisting limit is discarded in place of the new LIMIT 1.
2638 */
2639 Select *pSel; /* SELECT statement to encode */
2640 SelectDest dest; /* How to deal with SELECT result */
2641 int nReg; /* Registers to allocate */
2642
2643 testcase( pExpr->op==TK_EXISTS );
2644 testcase( pExpr->op==TK_SELECT );
2645 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
2646 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
2647
2648 pSel = pExpr->x.pSelect;
2649 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2650 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2651 pParse->nMem += nReg;
2652 if( pExpr->op==TK_SELECT ){
2653 dest.eDest = SRT_Mem;
2654 dest.iSdst = dest.iSDParm;
2655 dest.nSdst = nReg;
2656 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
2657 VdbeComment((v, "Init subquery result"));
2658 }else{
2659 dest.eDest = SRT_Exists;
2660 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
2661 VdbeComment((v, "Init EXISTS result"));
2662 }
2663 sqlite3ExprDelete(pParse->db, pSel->pLimit);
2664 pSel->pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,
2665 &sqlite3IntTokens[1], 0);
2666 pSel->iLimit = 0;
2667 pSel->selFlags &= ~SF_MultiValue;
2668 if( sqlite3Select(pParse, pSel, &dest) ){
2669 return 0;
2670 }
2671 rReg = dest.iSDParm;
2672 ExprSetVVAProperty(pExpr, EP_NoReduce);
2673 break;
2674 }
2675 }
2676
2677 if( rHasNullFlag ){
2678 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
2679 }
2680
2681 if( jmpIfDynamic>=0 ){
2682 sqlite3VdbeJumpHere(v, jmpIfDynamic);
2683 }
2684 sqlite3ExprCachePop(pParse);
2685
2686 return rReg;
2687 }
2688 #endif /* SQLITE_OMIT_SUBQUERY */
2689
2690 #ifndef SQLITE_OMIT_SUBQUERY
2691 /*
2692 ** Expr pIn is an IN(...) expression. This function checks that the
2693 ** sub-select on the RHS of the IN() operator has the same number of
2694 ** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2695 ** a sub-query, that the LHS is a vector of size 1.
2696 */
2697 int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2698 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2699 if( (pIn->flags & EP_xIsSelect) ){
2700 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2701 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2702 return 1;
2703 }
2704 }else if( nVector!=1 ){
2705 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
2706 return 1;
2707 }
2708 return 0;
2709 }
2710 #endif
2711
2712 #ifndef SQLITE_OMIT_SUBQUERY
2713 /*
2714 ** Generate code for an IN expression.
2715 **
2716 ** x IN (SELECT ...)
2717 ** x IN (value, value, ...)
2718 **
2719 ** The left-hand side (LHS) is a scalar or vector expression. The
2720 ** right-hand side (RHS) is an array of zero or more scalar values, or a
2721 ** subquery. If the RHS is a subquery, the number of result columns must
2722 ** match the number of columns in the vector on the LHS. If the RHS is
2723 ** a list of values, the LHS must be a scalar.
2724 **
2725 ** The IN operator is true if the LHS value is contained within the RHS.
2726 ** The result is false if the LHS is definitely not in the RHS. The
2727 ** result is NULL if the presence of the LHS in the RHS cannot be
2728 ** determined due to NULLs.
2729 **
2730 ** This routine generates code that jumps to destIfFalse if the LHS is not
2731 ** contained within the RHS. If due to NULLs we cannot determine if the LHS
2732 ** is contained in the RHS then jump to destIfNull. If the LHS is contained
2733 ** within the RHS then fall through.
2734 **
2735 ** See the separate in-operator.md documentation file in the canonical
2736 ** SQLite source tree for additional information.
2737 */
2738 static void sqlite3ExprCodeIN(
2739 Parse *pParse, /* Parsing and code generating context */
2740 Expr *pExpr, /* The IN expression */
2741 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2742 int destIfNull /* Jump here if the results are unknown due to NULLs */
2743 ){
2744 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
2745 int eType; /* Type of the RHS */
2746 int rLhs; /* Register(s) holding the LHS values */
2747 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
2748 Vdbe *v; /* Statement under construction */
2749 int *aiMap = 0; /* Map from vector field to index column */
2750 char *zAff = 0; /* Affinity string for comparisons */
2751 int nVector; /* Size of vectors for this IN operator */
2752 int iDummy; /* Dummy parameter to exprCodeVector() */
2753 Expr *pLeft; /* The LHS of the IN operator */
2754 int i; /* loop counter */
2755 int destStep2; /* Where to jump when NULLs seen in step 2 */
2756 int destStep6 = 0; /* Start of code for Step 6 */
2757 int addrTruthOp; /* Address of opcode that determines the IN is true */
2758 int destNotNull; /* Jump here if a comparison is not true in step 6 */
2759 int addrTop; /* Top of the step-6 loop */
2760
2761 pLeft = pExpr->pLeft;
2762 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
2763 zAff = exprINAffinity(pParse, pExpr);
2764 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2765 aiMap = (int*)sqlite3DbMallocZero(
2766 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2767 );
2768 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
2769
2770 /* Attempt to compute the RHS. After this step, if anything other than
2771 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2772 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2773 ** the RHS has not yet been coded. */
2774 v = pParse->pVdbe;
2775 assert( v!=0 ); /* OOM detected prior to this routine */
2776 VdbeNoopComment((v, "begin IN expr"));
2777 eType = sqlite3FindInIndex(pParse, pExpr,
2778 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
2779 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
2780
2781 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2782 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2783 );
2784 #ifdef SQLITE_DEBUG
2785 /* Confirm that aiMap[] contains nVector integer values between 0 and
2786 ** nVector-1. */
2787 for(i=0; i<nVector; i++){
2788 int j, cnt;
2789 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
2790 assert( cnt==1 );
2791 }
2792 #endif
2793
2794 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2795 ** vector, then it is stored in an array of nVector registers starting
2796 ** at r1.
2797 **
2798 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
2799 ** so that the fields are in the same order as an existing index. The
2800 ** aiMap[] array contains a mapping from the original LHS field order to
2801 ** the field order that matches the RHS index.
2802 */
2803 sqlite3ExprCachePush(pParse);
2804 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
2805 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
2806 if( i==nVector ){
2807 /* LHS fields are not reordered */
2808 rLhs = rLhsOrig;
2809 }else{
2810 /* Need to reorder the LHS fields according to aiMap */
2811 rLhs = sqlite3GetTempRange(pParse, nVector);
2812 for(i=0; i<nVector; i++){
2813 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
2814 }
2815 }
2816
2817 /* If sqlite3FindInIndex() did not find or create an index that is
2818 ** suitable for evaluating the IN operator, then evaluate using a
2819 ** sequence of comparisons.
2820 **
2821 ** This is step (1) in the in-operator.md optimized algorithm.
2822 */
2823 if( eType==IN_INDEX_NOOP ){
2824 ExprList *pList = pExpr->x.pList;
2825 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2826 int labelOk = sqlite3VdbeMakeLabel(v);
2827 int r2, regToFree;
2828 int regCkNull = 0;
2829 int ii;
2830 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2831 if( destIfNull!=destIfFalse ){
2832 regCkNull = sqlite3GetTempReg(pParse);
2833 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
2834 }
2835 for(ii=0; ii<pList->nExpr; ii++){
2836 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
2837 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
2838 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2839 }
2840 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2841 sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
2842 (void*)pColl, P4_COLLSEQ);
2843 VdbeCoverageIf(v, ii<pList->nExpr-1);
2844 VdbeCoverageIf(v, ii==pList->nExpr-1);
2845 sqlite3VdbeChangeP5(v, zAff[0]);
2846 }else{
2847 assert( destIfNull==destIfFalse );
2848 sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
2849 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
2850 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
2851 }
2852 sqlite3ReleaseTempReg(pParse, regToFree);
2853 }
2854 if( regCkNull ){
2855 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
2856 sqlite3VdbeGoto(v, destIfFalse);
2857 }
2858 sqlite3VdbeResolveLabel(v, labelOk);
2859 sqlite3ReleaseTempReg(pParse, regCkNull);
2860 goto sqlite3ExprCodeIN_finished;
2861 }
2862
2863 /* Step 2: Check to see if the LHS contains any NULL columns. If the
2864 ** LHS does contain NULLs then the result must be either FALSE or NULL.
2865 ** We will then skip the binary search of the RHS.
2866 */
2867 if( destIfNull==destIfFalse ){
2868 destStep2 = destIfFalse;
2869 }else{
2870 destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
2871 }
2872 for(i=0; i<nVector; i++){
2873 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
2874 if( sqlite3ExprCanBeNull(p) ){
2875 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
2876 VdbeCoverage(v);
2877 }
2878 }
2879
2880 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
2881 ** of the RHS using the LHS as a probe. If found, the result is
2882 ** true.
2883 */
2884 if( eType==IN_INDEX_ROWID ){
2885 /* In this case, the RHS is the ROWID of table b-tree and so we also
2886 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
2887 ** into a single opcode. */
2888 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
2889 VdbeCoverage(v);
2890 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
2891 }else{
2892 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
2893 if( destIfFalse==destIfNull ){
2894 /* Combine Step 3 and Step 5 into a single opcode */
2895 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
2896 rLhs, nVector); VdbeCoverage(v);
2897 goto sqlite3ExprCodeIN_finished;
2898 }
2899 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
2900 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
2901 rLhs, nVector); VdbeCoverage(v);
2902 }
2903
2904 /* Step 4. If the RHS is known to be non-NULL and we did not find
2905 ** an match on the search above, then the result must be FALSE.
2906 */
2907 if( rRhsHasNull && nVector==1 ){
2908 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
2909 VdbeCoverage(v);
2910 }
2911
2912 /* Step 5. If we do not care about the difference between NULL and
2913 ** FALSE, then just return false.
2914 */
2915 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
2916
2917 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
2918 ** If any comparison is NULL, then the result is NULL. If all
2919 ** comparisons are FALSE then the final result is FALSE.
2920 **
2921 ** For a scalar LHS, it is sufficient to check just the first row
2922 ** of the RHS.
2923 */
2924 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
2925 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2926 VdbeCoverage(v);
2927 if( nVector>1 ){
2928 destNotNull = sqlite3VdbeMakeLabel(v);
2929 }else{
2930 /* For nVector==1, combine steps 6 and 7 by immediately returning
2931 ** FALSE if the first comparison is not NULL */
2932 destNotNull = destIfFalse;
2933 }
2934 for(i=0; i<nVector; i++){
2935 Expr *p;
2936 CollSeq *pColl;
2937 int r3 = sqlite3GetTempReg(pParse);
2938 p = sqlite3VectorFieldSubexpr(pLeft, i);
2939 pColl = sqlite3ExprCollSeq(pParse, p);
2940 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
2941 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
2942 (void*)pColl, P4_COLLSEQ);
2943 VdbeCoverage(v);
2944 sqlite3ReleaseTempReg(pParse, r3);
2945 }
2946 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
2947 if( nVector>1 ){
2948 sqlite3VdbeResolveLabel(v, destNotNull);
2949 sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
2950 VdbeCoverage(v);
2951
2952 /* Step 7: If we reach this point, we know that the result must
2953 ** be false. */
2954 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2955 }
2956
2957 /* Jumps here in order to return true. */
2958 sqlite3VdbeJumpHere(v, addrTruthOp);
2959
2960 sqlite3ExprCodeIN_finished:
2961 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
2962 sqlite3ExprCachePop(pParse);
2963 VdbeComment((v, "end IN expr"));
2964 sqlite3ExprCodeIN_oom_error:
2965 sqlite3DbFree(pParse->db, aiMap);
2966 sqlite3DbFree(pParse->db, zAff);
2967 }
2968 #endif /* SQLITE_OMIT_SUBQUERY */
2969
2970 #ifndef SQLITE_OMIT_FLOATING_POINT
2971 /*
2972 ** Generate an instruction that will put the floating point
2973 ** value described by z[0..n-1] into register iMem.
2974 **
2975 ** The z[] string will probably not be zero-terminated. But the
2976 ** z[n] character is guaranteed to be something that does not look
2977 ** like the continuation of the number.
2978 */
2979 static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
2980 if( ALWAYS(z!=0) ){
2981 double value;
2982 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
2983 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2984 if( negateFlag ) value = -value;
2985 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
2986 }
2987 }
2988 #endif
2989
2990
2991 /*
2992 ** Generate an instruction that will put the integer describe by
2993 ** text z[0..n-1] into register iMem.
2994 **
2995 ** Expr.u.zToken is always UTF8 and zero-terminated.
2996 */
2997 static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2998 Vdbe *v = pParse->pVdbe;
2999 if( pExpr->flags & EP_IntValue ){
3000 int i = pExpr->u.iValue;
3001 assert( i>=0 );
3002 if( negFlag ) i = -i;
3003 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
3004 }else{
3005 int c;
3006 i64 value;
3007 const char *z = pExpr->u.zToken;
3008 assert( z!=0 );
3009 c = sqlite3DecOrHexToI64(z, &value);
3010 if( c==1 || (c==2 && !negFlag) || (negFlag && value==SMALLEST_INT64)){
3011 #ifdef SQLITE_OMIT_FLOATING_POINT
3012 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3013 #else
3014 #ifndef SQLITE_OMIT_HEX_INTEGER
3015 if( sqlite3_strnicmp(z,"0x",2)==0 ){
3016 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
3017 }else
3018 #endif
3019 {
3020 codeReal(v, z, negFlag, iMem);
3021 }
3022 #endif
3023 }else{
3024 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
3025 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
3026 }
3027 }
3028 }
3029
3030 /*
3031 ** Erase column-cache entry number i
3032 */
3033 static void cacheEntryClear(Parse *pParse, int i){
3034 if( pParse->aColCache[i].tempReg ){
3035 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
3036 pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
3037 }
3038 }
3039 pParse->nColCache--;
3040 if( i<pParse->nColCache ){
3041 pParse->aColCache[i] = pParse->aColCache[pParse->nColCache];
3042 }
3043 }
3044
3045
3046 /*
3047 ** Record in the column cache that a particular column from a
3048 ** particular table is stored in a particular register.
3049 */
3050 void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
3051 int i;
3052 int minLru;
3053 int idxLru;
3054 struct yColCache *p;
3055
3056 /* Unless an error has occurred, register numbers are always positive. */
3057 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
3058 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
3059
3060 /* The SQLITE_ColumnCache flag disables the column cache. This is used
3061 ** for testing only - to verify that SQLite always gets the same answer
3062 ** with and without the column cache.
3063 */
3064 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
3065
3066 /* First replace any existing entry.
3067 **
3068 ** Actually, the way the column cache is currently used, we are guaranteed
3069 ** that the object will never already be in cache. Verify this guarantee.
3070 */
3071 #ifndef NDEBUG
3072 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3073 assert( p->iTable!=iTab || p->iColumn!=iCol );
3074 }
3075 #endif
3076
3077 /* If the cache is already full, delete the least recently used entry */
3078 if( pParse->nColCache>=SQLITE_N_COLCACHE ){
3079 minLru = 0x7fffffff;
3080 idxLru = -1;
3081 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3082 if( p->lru<minLru ){
3083 idxLru = i;
3084 minLru = p->lru;
3085 }
3086 }
3087 p = &pParse->aColCache[idxLru];
3088 }else{
3089 p = &pParse->aColCache[pParse->nColCache++];
3090 }
3091
3092 /* Add the new entry to the end of the cache */
3093 p->iLevel = pParse->iCacheLevel;
3094 p->iTable = iTab;
3095 p->iColumn = iCol;
3096 p->iReg = iReg;
3097 p->tempReg = 0;
3098 p->lru = pParse->iCacheCnt++;
3099 }
3100
3101 /*
3102 ** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3103 ** Purge the range of registers from the column cache.
3104 */
3105 void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
3106 int i = 0;
3107 while( i<pParse->nColCache ){
3108 struct yColCache *p = &pParse->aColCache[i];
3109 if( p->iReg >= iReg && p->iReg < iReg+nReg ){
3110 cacheEntryClear(pParse, i);
3111 }else{
3112 i++;
3113 }
3114 }
3115 }
3116
3117 /*
3118 ** Remember the current column cache context. Any new entries added
3119 ** added to the column cache after this call are removed when the
3120 ** corresponding pop occurs.
3121 */
3122 void sqlite3ExprCachePush(Parse *pParse){
3123 pParse->iCacheLevel++;
3124 #ifdef SQLITE_DEBUG
3125 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3126 printf("PUSH to %d\n", pParse->iCacheLevel);
3127 }
3128 #endif
3129 }
3130
3131 /*
3132 ** Remove from the column cache any entries that were added since the
3133 ** the previous sqlite3ExprCachePush operation. In other words, restore
3134 ** the cache to the state it was in prior the most recent Push.
3135 */
3136 void sqlite3ExprCachePop(Parse *pParse){
3137 int i = 0;
3138 assert( pParse->iCacheLevel>=1 );
3139 pParse->iCacheLevel--;
3140 #ifdef SQLITE_DEBUG
3141 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3142 printf("POP to %d\n", pParse->iCacheLevel);
3143 }
3144 #endif
3145 while( i<pParse->nColCache ){
3146 if( pParse->aColCache[i].iLevel>pParse->iCacheLevel ){
3147 cacheEntryClear(pParse, i);
3148 }else{
3149 i++;
3150 }
3151 }
3152 }
3153
3154 /*
3155 ** When a cached column is reused, make sure that its register is
3156 ** no longer available as a temp register. ticket #3879: that same
3157 ** register might be in the cache in multiple places, so be sure to
3158 ** get them all.
3159 */
3160 static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3161 int i;
3162 struct yColCache *p;
3163 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3164 if( p->iReg==iReg ){
3165 p->tempReg = 0;
3166 }
3167 }
3168 }
3169
3170 /* Generate code that will load into register regOut a value that is
3171 ** appropriate for the iIdxCol-th column of index pIdx.
3172 */
3173 void sqlite3ExprCodeLoadIndexColumn(
3174 Parse *pParse, /* The parsing context */
3175 Index *pIdx, /* The index whose column is to be loaded */
3176 int iTabCur, /* Cursor pointing to a table row */
3177 int iIdxCol, /* The column of the index to be loaded */
3178 int regOut /* Store the index column value in this register */
3179 ){
3180 i16 iTabCol = pIdx->aiColumn[iIdxCol];
3181 if( iTabCol==XN_EXPR ){
3182 assert( pIdx->aColExpr );
3183 assert( pIdx->aColExpr->nExpr>iIdxCol );
3184 pParse->iSelfTab = iTabCur;
3185 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
3186 }else{
3187 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3188 iTabCol, regOut);
3189 }
3190 }
3191
3192 /*
3193 ** Generate code to extract the value of the iCol-th column of a table.
3194 */
3195 void sqlite3ExprCodeGetColumnOfTable(
3196 Vdbe *v, /* The VDBE under construction */
3197 Table *pTab, /* The table containing the value */
3198 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
3199 int iCol, /* Index of the column to extract */
3200 int regOut /* Extract the value into this register */
3201 ){
3202 if( iCol<0 || iCol==pTab->iPKey ){
3203 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3204 }else{
3205 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
3206 int x = iCol;
3207 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
3208 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3209 }
3210 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
3211 }
3212 if( iCol>=0 ){
3213 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3214 }
3215 }
3216
3217 /*
3218 ** Generate code that will extract the iColumn-th column from
3219 ** table pTab and store the column value in a register.
3220 **
3221 ** An effort is made to store the column value in register iReg. This
3222 ** is not garanteeed for GetColumn() - the result can be stored in
3223 ** any register. But the result is guaranteed to land in register iReg
3224 ** for GetColumnToReg().
3225 **
3226 ** There must be an open cursor to pTab in iTable when this routine
3227 ** is called. If iColumn<0 then code is generated that extracts the rowid.
3228 */
3229 int sqlite3ExprCodeGetColumn(
3230 Parse *pParse, /* Parsing and code generating context */
3231 Table *pTab, /* Description of the table we are reading from */
3232 int iColumn, /* Index of the table column */
3233 int iTable, /* The cursor pointing to the table */
3234 int iReg, /* Store results here */
3235 u8 p5 /* P5 value for OP_Column + FLAGS */
3236 ){
3237 Vdbe *v = pParse->pVdbe;
3238 int i;
3239 struct yColCache *p;
3240
3241 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3242 if( p->iTable==iTable && p->iColumn==iColumn ){
3243 p->lru = pParse->iCacheCnt++;
3244 sqlite3ExprCachePinRegister(pParse, p->iReg);
3245 return p->iReg;
3246 }
3247 }
3248 assert( v!=0 );
3249 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
3250 if( p5 ){
3251 sqlite3VdbeChangeP5(v, p5);
3252 }else{
3253 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3254 }
3255 return iReg;
3256 }
3257 void sqlite3ExprCodeGetColumnToReg(
3258 Parse *pParse, /* Parsing and code generating context */
3259 Table *pTab, /* Description of the table we are reading from */
3260 int iColumn, /* Index of the table column */
3261 int iTable, /* The cursor pointing to the table */
3262 int iReg /* Store results here */
3263 ){
3264 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3265 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3266 }
3267
3268
3269 /*
3270 ** Clear all column cache entries.
3271 */
3272 void sqlite3ExprCacheClear(Parse *pParse){
3273 int i;
3274
3275 #if SQLITE_DEBUG
3276 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3277 printf("CLEAR\n");
3278 }
3279 #endif
3280 for(i=0; i<pParse->nColCache; i++){
3281 if( pParse->aColCache[i].tempReg
3282 && pParse->nTempReg<ArraySize(pParse->aTempReg)
3283 ){
3284 pParse->aTempReg[pParse->nTempReg++] = pParse->aColCache[i].iReg;
3285 }
3286 }
3287 pParse->nColCache = 0;
3288 }
3289
3290 /*
3291 ** Record the fact that an affinity change has occurred on iCount
3292 ** registers starting with iStart.
3293 */
3294 void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
3295 sqlite3ExprCacheRemove(pParse, iStart, iCount);
3296 }
3297
3298 /*
3299 ** Generate code to move content from registers iFrom...iFrom+nReg-1
3300 ** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
3301 */
3302 void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
3303 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
3304 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
3305 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
3306 }
3307
3308 #if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
3309 /*
3310 ** Return true if any register in the range iFrom..iTo (inclusive)
3311 ** is used as part of the column cache.
3312 **
3313 ** This routine is used within assert() and testcase() macros only
3314 ** and does not appear in a normal build.
3315 */
3316 static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3317 int i;
3318 struct yColCache *p;
3319 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
3320 int r = p->iReg;
3321 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
3322 }
3323 return 0;
3324 }
3325 #endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
3326
3327
3328 /*
3329 ** Convert a scalar expression node to a TK_REGISTER referencing
3330 ** register iReg. The caller must ensure that iReg already contains
3331 ** the correct value for the expression.
3332 */
3333 static void exprToRegister(Expr *p, int iReg){
3334 p->op2 = p->op;
3335 p->op = TK_REGISTER;
3336 p->iTable = iReg;
3337 ExprClearProperty(p, EP_Skip);
3338 }
3339
3340 /*
3341 ** Evaluate an expression (either a vector or a scalar expression) and store
3342 ** the result in continguous temporary registers. Return the index of
3343 ** the first register used to store the result.
3344 **
3345 ** If the returned result register is a temporary scalar, then also write
3346 ** that register number into *piFreeable. If the returned result register
3347 ** is not a temporary or if the expression is a vector set *piFreeable
3348 ** to 0.
3349 */
3350 static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3351 int iResult;
3352 int nResult = sqlite3ExprVectorSize(p);
3353 if( nResult==1 ){
3354 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3355 }else{
3356 *piFreeable = 0;
3357 if( p->op==TK_SELECT ){
3358 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3359 }else{
3360 int i;
3361 iResult = pParse->nMem+1;
3362 pParse->nMem += nResult;
3363 for(i=0; i<nResult; i++){
3364 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
3365 }
3366 }
3367 }
3368 return iResult;
3369 }
3370
3371
3372 /*
3373 ** Generate code into the current Vdbe to evaluate the given
3374 ** expression. Attempt to store the results in register "target".
3375 ** Return the register where results are stored.
3376 **
3377 ** With this routine, there is no guarantee that results will
3378 ** be stored in target. The result might be stored in some other
3379 ** register if it is convenient to do so. The calling function
3380 ** must check the return code and move the results to the desired
3381 ** register.
3382 */
3383 int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
3384 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3385 int op; /* The opcode being coded */
3386 int inReg = target; /* Results stored in register inReg */
3387 int regFree1 = 0; /* If non-zero free this temporary register */
3388 int regFree2 = 0; /* If non-zero free this temporary register */
3389 int r1, r2; /* Various register numbers */
3390 Expr tempX; /* Temporary expression node */
3391 int p5 = 0;
3392
3393 assert( target>0 && target<=pParse->nMem );
3394 if( v==0 ){
3395 assert( pParse->db->mallocFailed );
3396 return 0;
3397 }
3398
3399 if( pExpr==0 ){
3400 op = TK_NULL;
3401 }else{
3402 op = pExpr->op;
3403 }
3404 switch( op ){
3405 case TK_AGG_COLUMN: {
3406 AggInfo *pAggInfo = pExpr->pAggInfo;
3407 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3408 if( !pAggInfo->directMode ){
3409 assert( pCol->iMem>0 );
3410 return pCol->iMem;
3411 }else if( pAggInfo->useSortingIdx ){
3412 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
3413 pCol->iSorterColumn, target);
3414 return target;
3415 }
3416 /* Otherwise, fall thru into the TK_COLUMN case */
3417 }
3418 case TK_COLUMN: {
3419 int iTab = pExpr->iTable;
3420 if( iTab<0 ){
3421 if( pParse->ckBase>0 ){
3422 /* Generating CHECK constraints or inserting into partial index */
3423 return pExpr->iColumn + pParse->ckBase;
3424 }else{
3425 /* Coding an expression that is part of an index where column names
3426 ** in the index refer to the table to which the index belongs */
3427 iTab = pParse->iSelfTab;
3428 }
3429 }
3430 return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3431 pExpr->iColumn, iTab, target,
3432 pExpr->op2);
3433 }
3434 case TK_INTEGER: {
3435 codeInteger(pParse, pExpr, 0, target);
3436 return target;
3437 }
3438 #ifndef SQLITE_OMIT_FLOATING_POINT
3439 case TK_FLOAT: {
3440 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3441 codeReal(v, pExpr->u.zToken, 0, target);
3442 return target;
3443 }
3444 #endif
3445 case TK_STRING: {
3446 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3447 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
3448 return target;
3449 }
3450 case TK_NULL: {
3451 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3452 return target;
3453 }
3454 #ifndef SQLITE_OMIT_BLOB_LITERAL
3455 case TK_BLOB: {
3456 int n;
3457 const char *z;
3458 char *zBlob;
3459 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3460 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3461 assert( pExpr->u.zToken[1]=='\'' );
3462 z = &pExpr->u.zToken[2];
3463 n = sqlite3Strlen30(z) - 1;
3464 assert( z[n]=='\'' );
3465 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3466 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
3467 return target;
3468 }
3469 #endif
3470 case TK_VARIABLE: {
3471 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3472 assert( pExpr->u.zToken!=0 );
3473 assert( pExpr->u.zToken[0]!=0 );
3474 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3475 if( pExpr->u.zToken[1]!=0 ){
3476 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
3477 assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
3478 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
3479 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
3480 }
3481 return target;
3482 }
3483 case TK_REGISTER: {
3484 return pExpr->iTable;
3485 }
3486 #ifndef SQLITE_OMIT_CAST
3487 case TK_CAST: {
3488 /* Expressions of the form: CAST(pLeft AS token) */
3489 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3490 if( inReg!=target ){
3491 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3492 inReg = target;
3493 }
3494 sqlite3VdbeAddOp2(v, OP_Cast, target,
3495 sqlite3AffinityType(pExpr->u.zToken, 0));
3496 testcase( usedAsColumnCache(pParse, inReg, inReg) );
3497 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
3498 return inReg;
3499 }
3500 #endif /* SQLITE_OMIT_CAST */
3501 case TK_IS:
3502 case TK_ISNOT:
3503 op = (op==TK_IS) ? TK_EQ : TK_NE;
3504 p5 = SQLITE_NULLEQ;
3505 /* fall-through */
3506 case TK_LT:
3507 case TK_LE:
3508 case TK_GT:
3509 case TK_GE:
3510 case TK_NE:
3511 case TK_EQ: {
3512 Expr *pLeft = pExpr->pLeft;
3513 if( sqlite3ExprIsVector(pLeft) ){
3514 codeVectorCompare(pParse, pExpr, target, op, p5);
3515 }else{
3516 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3517 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3518 codeCompare(pParse, pLeft, pExpr->pRight, op,
3519 r1, r2, inReg, SQLITE_STOREP2 | p5);
3520 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3521 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3522 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3523 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3524 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3525 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3526 testcase( regFree1==0 );
3527 testcase( regFree2==0 );
3528 }
3529 break;
3530 }
3531 case TK_AND:
3532 case TK_OR:
3533 case TK_PLUS:
3534 case TK_STAR:
3535 case TK_MINUS:
3536 case TK_REM:
3537 case TK_BITAND:
3538 case TK_BITOR:
3539 case TK_SLASH:
3540 case TK_LSHIFT:
3541 case TK_RSHIFT:
3542 case TK_CONCAT: {
3543 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3544 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3545 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3546 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3547 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3548 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3549 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3550 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3551 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3552 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3553 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
3554 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3555 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3556 sqlite3VdbeAddOp3(v, op, r2, r1, target);
3557 testcase( regFree1==0 );
3558 testcase( regFree2==0 );
3559 break;
3560 }
3561 case TK_UMINUS: {
3562 Expr *pLeft = pExpr->pLeft;
3563 assert( pLeft );
3564 if( pLeft->op==TK_INTEGER ){
3565 codeInteger(pParse, pLeft, 1, target);
3566 return target;
3567 #ifndef SQLITE_OMIT_FLOATING_POINT
3568 }else if( pLeft->op==TK_FLOAT ){
3569 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3570 codeReal(v, pLeft->u.zToken, 1, target);
3571 return target;
3572 #endif
3573 }else{
3574 tempX.op = TK_INTEGER;
3575 tempX.flags = EP_IntValue|EP_TokenOnly;
3576 tempX.u.iValue = 0;
3577 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
3578 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
3579 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
3580 testcase( regFree2==0 );
3581 }
3582 break;
3583 }
3584 case TK_BITNOT:
3585 case TK_NOT: {
3586 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3587 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
3588 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3589 testcase( regFree1==0 );
3590 sqlite3VdbeAddOp2(v, op, r1, inReg);
3591 break;
3592 }
3593 case TK_ISNULL:
3594 case TK_NOTNULL: {
3595 int addr;
3596 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3597 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
3598 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3599 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3600 testcase( regFree1==0 );
3601 addr = sqlite3VdbeAddOp1(v, op, r1);
3602 VdbeCoverageIf(v, op==TK_ISNULL);
3603 VdbeCoverageIf(v, op==TK_NOTNULL);
3604 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
3605 sqlite3VdbeJumpHere(v, addr);
3606 break;
3607 }
3608 case TK_AGG_FUNCTION: {
3609 AggInfo *pInfo = pExpr->pAggInfo;
3610 if( pInfo==0 ){
3611 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3612 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
3613 }else{
3614 return pInfo->aFunc[pExpr->iAgg].iMem;
3615 }
3616 break;
3617 }
3618 case TK_FUNCTION: {
3619 ExprList *pFarg; /* List of function arguments */
3620 int nFarg; /* Number of function arguments */
3621 FuncDef *pDef; /* The function definition object */
3622 const char *zId; /* The function name */
3623 u32 constMask = 0; /* Mask of function arguments that are constant */
3624 int i; /* Loop counter */
3625 sqlite3 *db = pParse->db; /* The database connection */
3626 u8 enc = ENC(db); /* The text encoding used by this database */
3627 CollSeq *pColl = 0; /* A collating sequence */
3628
3629 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
3630 /* SQL functions can be expensive. So try to move constant functions
3631 ** out of the inner loop, even if that means an extra OP_Copy. */
3632 return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
3633 }
3634 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3635 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
3636 pFarg = 0;
3637 }else{
3638 pFarg = pExpr->x.pList;
3639 }
3640 nFarg = pFarg ? pFarg->nExpr : 0;
3641 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3642 zId = pExpr->u.zToken;
3643 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
3644 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3645 if( pDef==0 && pParse->explain ){
3646 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3647 }
3648 #endif
3649 if( pDef==0 || pDef->xFinalize!=0 ){
3650 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
3651 break;
3652 }
3653
3654 /* Attempt a direct implementation of the built-in COALESCE() and
3655 ** IFNULL() functions. This avoids unnecessary evaluation of
3656 ** arguments past the first non-NULL argument.
3657 */
3658 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
3659 int endCoalesce = sqlite3VdbeMakeLabel(v);
3660 assert( nFarg>=2 );
3661 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3662 for(i=1; i<nFarg; i++){
3663 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
3664 VdbeCoverage(v);
3665 sqlite3ExprCacheRemove(pParse, target, 1);
3666 sqlite3ExprCachePush(pParse);
3667 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
3668 sqlite3ExprCachePop(pParse);
3669 }
3670 sqlite3VdbeResolveLabel(v, endCoalesce);
3671 break;
3672 }
3673
3674 /* The UNLIKELY() function is a no-op. The result is the value
3675 ** of the first argument.
3676 */
3677 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3678 assert( nFarg>=1 );
3679 return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
3680 }
3681
3682 #ifdef SQLITE_DEBUG
3683 /* The AFFINITY() function evaluates to a string that describes
3684 ** the type affinity of the argument. This is used for testing of
3685 ** the SQLite type logic.
3686 */
3687 if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
3688 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3689 char aff;
3690 assert( nFarg==1 );
3691 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3692 sqlite3VdbeLoadString(v, target,
3693 aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
3694 return target;
3695 }
3696 #endif
3697
3698 for(i=0; i<nFarg; i++){
3699 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
3700 testcase( i==31 );
3701 constMask |= MASKBIT32(i);
3702 }
3703 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3704 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3705 }
3706 }
3707 if( pFarg ){
3708 if( constMask ){
3709 r1 = pParse->nMem+1;
3710 pParse->nMem += nFarg;
3711 }else{
3712 r1 = sqlite3GetTempRange(pParse, nFarg);
3713 }
3714
3715 /* For length() and typeof() functions with a column argument,
3716 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3717 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3718 ** loading.
3719 */
3720 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
3721 u8 exprOp;
3722 assert( nFarg==1 );
3723 assert( pFarg->a[0].pExpr!=0 );
3724 exprOp = pFarg->a[0].pExpr->op;
3725 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
3726 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3727 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
3728 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3729 pFarg->a[0].pExpr->op2 =
3730 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
3731 }
3732 }
3733
3734 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
3735 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
3736 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
3737 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
3738 }else{
3739 r1 = 0;
3740 }
3741 #ifndef SQLITE_OMIT_VIRTUALTABLE
3742 /* Possibly overload the function if the first argument is
3743 ** a virtual table column.
3744 **
3745 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3746 ** second argument, not the first, as the argument to test to
3747 ** see if it is a column in a virtual table. This is done because
3748 ** the left operand of infix functions (the operand we want to
3749 ** control overloading) ends up as the second argument to the
3750 ** function. The expression "A glob B" is equivalent to
3751 ** "glob(B,A). We want to use the A in "A glob B" to test
3752 ** for function overloading. But we use the B term in "glob(B,A)".
3753 */
3754 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3755 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3756 }else if( nFarg>0 ){
3757 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
3758 }
3759 #endif
3760 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
3761 if( !pColl ) pColl = db->pDfltColl;
3762 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
3763 }
3764 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
3765 (char*)pDef, P4_FUNCDEF);
3766 sqlite3VdbeChangeP5(v, (u8)nFarg);
3767 if( nFarg && constMask==0 ){
3768 sqlite3ReleaseTempRange(pParse, r1, nFarg);
3769 }
3770 return target;
3771 }
3772 #ifndef SQLITE_OMIT_SUBQUERY
3773 case TK_EXISTS:
3774 case TK_SELECT: {
3775 int nCol;
3776 testcase( op==TK_EXISTS );
3777 testcase( op==TK_SELECT );
3778 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3779 sqlite3SubselectError(pParse, nCol, 1);
3780 }else{
3781 return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3782 }
3783 break;
3784 }
3785 case TK_SELECT_COLUMN: {
3786 int n;
3787 if( pExpr->pLeft->iTable==0 ){
3788 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3789 }
3790 assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
3791 if( pExpr->iTable
3792 && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
3793 ){
3794 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
3795 pExpr->iTable, n);
3796 }
3797 return pExpr->pLeft->iTable + pExpr->iColumn;
3798 }
3799 case TK_IN: {
3800 int destIfFalse = sqlite3VdbeMakeLabel(v);
3801 int destIfNull = sqlite3VdbeMakeLabel(v);
3802 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3803 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3804 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3805 sqlite3VdbeResolveLabel(v, destIfFalse);
3806 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3807 sqlite3VdbeResolveLabel(v, destIfNull);
3808 return target;
3809 }
3810 #endif /* SQLITE_OMIT_SUBQUERY */
3811
3812
3813 /*
3814 ** x BETWEEN y AND z
3815 **
3816 ** This is equivalent to
3817 **
3818 ** x>=y AND x<=z
3819 **
3820 ** X is stored in pExpr->pLeft.
3821 ** Y is stored in pExpr->pList->a[0].pExpr.
3822 ** Z is stored in pExpr->pList->a[1].pExpr.
3823 */
3824 case TK_BETWEEN: {
3825 exprCodeBetween(pParse, pExpr, target, 0, 0);
3826 return target;
3827 }
3828 case TK_SPAN:
3829 case TK_COLLATE:
3830 case TK_UPLUS: {
3831 return sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
3832 }
3833
3834 case TK_TRIGGER: {
3835 /* If the opcode is TK_TRIGGER, then the expression is a reference
3836 ** to a column in the new.* or old.* pseudo-tables available to
3837 ** trigger programs. In this case Expr.iTable is set to 1 for the
3838 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3839 ** is set to the column of the pseudo-table to read, or to -1 to
3840 ** read the rowid field.
3841 **
3842 ** The expression is implemented using an OP_Param opcode. The p1
3843 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3844 ** to reference another column of the old.* pseudo-table, where
3845 ** i is the index of the column. For a new.rowid reference, p1 is
3846 ** set to (n+1), where n is the number of columns in each pseudo-table.
3847 ** For a reference to any other column in the new.* pseudo-table, p1
3848 ** is set to (n+2+i), where n and i are as defined previously. For
3849 ** example, if the table on which triggers are being fired is
3850 ** declared as:
3851 **
3852 ** CREATE TABLE t1(a, b);
3853 **
3854 ** Then p1 is interpreted as follows:
3855 **
3856 ** p1==0 -> old.rowid p1==3 -> new.rowid
3857 ** p1==1 -> old.a p1==4 -> new.a
3858 ** p1==2 -> old.b p1==5 -> new.b
3859 */
3860 Table *pTab = pExpr->pTab;
3861 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3862
3863 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3864 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3865 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3866 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3867
3868 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
3869 VdbeComment((v, "%s.%s -> $%d",
3870 (pExpr->iTable ? "new" : "old"),
3871 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
3872 target
3873 ));
3874
3875 #ifndef SQLITE_OMIT_FLOATING_POINT
3876 /* If the column has REAL affinity, it may currently be stored as an
3877 ** integer. Use OP_RealAffinity to make sure it is really real.
3878 **
3879 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3880 ** floating point when extracting it from the record. */
3881 if( pExpr->iColumn>=0
3882 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3883 ){
3884 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3885 }
3886 #endif
3887 break;
3888 }
3889
3890 case TK_VECTOR: {
3891 sqlite3ErrorMsg(pParse, "row value misused");
3892 break;
3893 }
3894
3895 /*
3896 ** Form A:
3897 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3898 **
3899 ** Form B:
3900 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3901 **
3902 ** Form A is can be transformed into the equivalent form B as follows:
3903 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3904 ** WHEN x=eN THEN rN ELSE y END
3905 **
3906 ** X (if it exists) is in pExpr->pLeft.
3907 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3908 ** odd. The Y is also optional. If the number of elements in x.pList
3909 ** is even, then Y is omitted and the "otherwise" result is NULL.
3910 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3911 **
3912 ** The result of the expression is the Ri for the first matching Ei,
3913 ** or if there is no matching Ei, the ELSE term Y, or if there is
3914 ** no ELSE term, NULL.
3915 */
3916 default: assert( op==TK_CASE ); {
3917 int endLabel; /* GOTO label for end of CASE stmt */
3918 int nextCase; /* GOTO label for next WHEN clause */
3919 int nExpr; /* 2x number of WHEN terms */
3920 int i; /* Loop counter */
3921 ExprList *pEList; /* List of WHEN terms */
3922 struct ExprList_item *aListelem; /* Array of WHEN terms */
3923 Expr opCompare; /* The X==Ei expression */
3924 Expr *pX; /* The X expression */
3925 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
3926 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
3927
3928 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
3929 assert(pExpr->x.pList->nExpr > 0);
3930 pEList = pExpr->x.pList;
3931 aListelem = pEList->a;
3932 nExpr = pEList->nExpr;
3933 endLabel = sqlite3VdbeMakeLabel(v);
3934 if( (pX = pExpr->pLeft)!=0 ){
3935 tempX = *pX;
3936 testcase( pX->op==TK_COLUMN );
3937 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
3938 testcase( regFree1==0 );
3939 memset(&opCompare, 0, sizeof(opCompare));
3940 opCompare.op = TK_EQ;
3941 opCompare.pLeft = &tempX;
3942 pTest = &opCompare;
3943 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3944 ** The value in regFree1 might get SCopy-ed into the file result.
3945 ** So make sure that the regFree1 register is not reused for other
3946 ** purposes and possibly overwritten. */
3947 regFree1 = 0;
3948 }
3949 for(i=0; i<nExpr-1; i=i+2){
3950 sqlite3ExprCachePush(pParse);
3951 if( pX ){
3952 assert( pTest!=0 );
3953 opCompare.pRight = aListelem[i].pExpr;
3954 }else{
3955 pTest = aListelem[i].pExpr;
3956 }
3957 nextCase = sqlite3VdbeMakeLabel(v);
3958 testcase( pTest->op==TK_COLUMN );
3959 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
3960 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
3961 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
3962 sqlite3VdbeGoto(v, endLabel);
3963 sqlite3ExprCachePop(pParse);
3964 sqlite3VdbeResolveLabel(v, nextCase);
3965 }
3966 if( (nExpr&1)!=0 ){
3967 sqlite3ExprCachePush(pParse);
3968 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
3969 sqlite3ExprCachePop(pParse);
3970 }else{
3971 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3972 }
3973 assert( pParse->db->mallocFailed || pParse->nErr>0
3974 || pParse->iCacheLevel==iCacheLevel );
3975 sqlite3VdbeResolveLabel(v, endLabel);
3976 break;
3977 }
3978 #ifndef SQLITE_OMIT_TRIGGER
3979 case TK_RAISE: {
3980 assert( pExpr->affinity==OE_Rollback
3981 || pExpr->affinity==OE_Abort
3982 || pExpr->affinity==OE_Fail
3983 || pExpr->affinity==OE_Ignore
3984 );
3985 if( !pParse->pTriggerTab ){
3986 sqlite3ErrorMsg(pParse,
3987 "RAISE() may only be used within a trigger-program");
3988 return 0;
3989 }
3990 if( pExpr->affinity==OE_Abort ){
3991 sqlite3MayAbort(pParse);
3992 }
3993 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3994 if( pExpr->affinity==OE_Ignore ){
3995 sqlite3VdbeAddOp4(
3996 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
3997 VdbeCoverage(v);
3998 }else{
3999 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
4000 pExpr->affinity, pExpr->u.zToken, 0, 0);
4001 }
4002
4003 break;
4004 }
4005 #endif
4006 }
4007 sqlite3ReleaseTempReg(pParse, regFree1);
4008 sqlite3ReleaseTempReg(pParse, regFree2);
4009 return inReg;
4010 }
4011
4012 /*
4013 ** Factor out the code of the given expression to initialization time.
4014 **
4015 ** If regDest>=0 then the result is always stored in that register and the
4016 ** result is not reusable. If regDest<0 then this routine is free to
4017 ** store the value whereever it wants. The register where the expression
4018 ** is stored is returned. When regDest<0, two identical expressions will
4019 ** code to the same register.
4020 */
4021 int sqlite3ExprCodeAtInit(
4022 Parse *pParse, /* Parsing context */
4023 Expr *pExpr, /* The expression to code when the VDBE initializes */
4024 int regDest /* Store the value in this register */
4025 ){
4026 ExprList *p;
4027 assert( ConstFactorOk(pParse) );
4028 p = pParse->pConstExpr;
4029 if( regDest<0 && p ){
4030 struct ExprList_item *pItem;
4031 int i;
4032 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
4033 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
4034 return pItem->u.iConstExprReg;
4035 }
4036 }
4037 }
4038 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4039 p = sqlite3ExprListAppend(pParse, p, pExpr);
4040 if( p ){
4041 struct ExprList_item *pItem = &p->a[p->nExpr-1];
4042 pItem->reusable = regDest<0;
4043 if( regDest<0 ) regDest = ++pParse->nMem;
4044 pItem->u.iConstExprReg = regDest;
4045 }
4046 pParse->pConstExpr = p;
4047 return regDest;
4048 }
4049
4050 /*
4051 ** Generate code to evaluate an expression and store the results
4052 ** into a register. Return the register number where the results
4053 ** are stored.
4054 **
4055 ** If the register is a temporary register that can be deallocated,
4056 ** then write its number into *pReg. If the result register is not
4057 ** a temporary, then set *pReg to zero.
4058 **
4059 ** If pExpr is a constant, then this routine might generate this
4060 ** code to fill the register in the initialization section of the
4061 ** VDBE program, in order to factor it out of the evaluation loop.
4062 */
4063 int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
4064 int r2;
4065 pExpr = sqlite3ExprSkipCollate(pExpr);
4066 if( ConstFactorOk(pParse)
4067 && pExpr->op!=TK_REGISTER
4068 && sqlite3ExprIsConstantNotJoin(pExpr)
4069 ){
4070 *pReg = 0;
4071 r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
4072 }else{
4073 int r1 = sqlite3GetTempReg(pParse);
4074 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4075 if( r2==r1 ){
4076 *pReg = r1;
4077 }else{
4078 sqlite3ReleaseTempReg(pParse, r1);
4079 *pReg = 0;
4080 }
4081 }
4082 return r2;
4083 }
4084
4085 /*
4086 ** Generate code that will evaluate expression pExpr and store the
4087 ** results in register target. The results are guaranteed to appear
4088 ** in register target.
4089 */
4090 void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
4091 int inReg;
4092
4093 assert( target>0 && target<=pParse->nMem );
4094 if( pExpr && pExpr->op==TK_REGISTER ){
4095 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
4096 }else{
4097 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
4098 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
4099 if( inReg!=target && pParse->pVdbe ){
4100 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
4101 }
4102 }
4103 }
4104
4105 /*
4106 ** Make a transient copy of expression pExpr and then code it using
4107 ** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
4108 ** except that the input expression is guaranteed to be unchanged.
4109 */
4110 void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4111 sqlite3 *db = pParse->db;
4112 pExpr = sqlite3ExprDup(db, pExpr, 0);
4113 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4114 sqlite3ExprDelete(db, pExpr);
4115 }
4116
4117 /*
4118 ** Generate code that will evaluate expression pExpr and store the
4119 ** results in register target. The results are guaranteed to appear
4120 ** in register target. If the expression is constant, then this routine
4121 ** might choose to code the expression at initialization time.
4122 */
4123 void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4124 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4125 sqlite3ExprCodeAtInit(pParse, pExpr, target);
4126 }else{
4127 sqlite3ExprCode(pParse, pExpr, target);
4128 }
4129 }
4130
4131 /*
4132 ** Generate code that evaluates the given expression and puts the result
4133 ** in register target.
4134 **
4135 ** Also make a copy of the expression results into another "cache" register
4136 ** and modify the expression so that the next time it is evaluated,
4137 ** the result is a copy of the cache register.
4138 **
4139 ** This routine is used for expressions that are used multiple
4140 ** times. They are evaluated once and the results of the expression
4141 ** are reused.
4142 */
4143 void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
4144 Vdbe *v = pParse->pVdbe;
4145 int iMem;
4146
4147 assert( target>0 );
4148 assert( pExpr->op!=TK_REGISTER );
4149 sqlite3ExprCode(pParse, pExpr, target);
4150 iMem = ++pParse->nMem;
4151 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4152 exprToRegister(pExpr, iMem);
4153 }
4154
4155 /*
4156 ** Generate code that pushes the value of every element of the given
4157 ** expression list into a sequence of registers beginning at target.
4158 **
4159 ** Return the number of elements evaluated.
4160 **
4161 ** The SQLITE_ECEL_DUP flag prevents the arguments from being
4162 ** filled using OP_SCopy. OP_Copy must be used instead.
4163 **
4164 ** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4165 ** factored out into initialization code.
4166 **
4167 ** The SQLITE_ECEL_REF flag means that expressions in the list with
4168 ** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4169 ** in registers at srcReg, and so the value can be copied from there.
4170 */
4171 int sqlite3ExprCodeExprList(
4172 Parse *pParse, /* Parsing context */
4173 ExprList *pList, /* The expression list to be coded */
4174 int target, /* Where to write results */
4175 int srcReg, /* Source registers if SQLITE_ECEL_REF */
4176 u8 flags /* SQLITE_ECEL_* flags */
4177 ){
4178 struct ExprList_item *pItem;
4179 int i, j, n;
4180 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
4181 Vdbe *v = pParse->pVdbe;
4182 assert( pList!=0 );
4183 assert( target>0 );
4184 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
4185 n = pList->nExpr;
4186 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
4187 for(pItem=pList->a, i=0; i<n; i++, pItem++){
4188 Expr *pExpr = pItem->pExpr;
4189 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4190 if( flags & SQLITE_ECEL_OMITREF ){
4191 i--;
4192 n--;
4193 }else{
4194 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4195 }
4196 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
4197 sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
4198 }else{
4199 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4200 if( inReg!=target+i ){
4201 VdbeOp *pOp;
4202 if( copyOp==OP_Copy
4203 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4204 && pOp->p1+pOp->p3+1==inReg
4205 && pOp->p2+pOp->p3+1==target+i
4206 ){
4207 pOp->p3++;
4208 }else{
4209 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4210 }
4211 }
4212 }
4213 }
4214 return n;
4215 }
4216
4217 /*
4218 ** Generate code for a BETWEEN operator.
4219 **
4220 ** x BETWEEN y AND z
4221 **
4222 ** The above is equivalent to
4223 **
4224 ** x>=y AND x<=z
4225 **
4226 ** Code it as such, taking care to do the common subexpression
4227 ** elimination of x.
4228 **
4229 ** The xJumpIf parameter determines details:
4230 **
4231 ** NULL: Store the boolean result in reg[dest]
4232 ** sqlite3ExprIfTrue: Jump to dest if true
4233 ** sqlite3ExprIfFalse: Jump to dest if false
4234 **
4235 ** The jumpIfNull parameter is ignored if xJumpIf is NULL.
4236 */
4237 static void exprCodeBetween(
4238 Parse *pParse, /* Parsing and code generating context */
4239 Expr *pExpr, /* The BETWEEN expression */
4240 int dest, /* Jump destination or storage location */
4241 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
4242 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4243 ){
4244 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
4245 Expr compLeft; /* The x>=y term */
4246 Expr compRight; /* The x<=z term */
4247 Expr exprX; /* The x subexpression */
4248 int regFree1 = 0; /* Temporary use register */
4249
4250
4251 memset(&compLeft, 0, sizeof(Expr));
4252 memset(&compRight, 0, sizeof(Expr));
4253 memset(&exprAnd, 0, sizeof(Expr));
4254
4255 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4256 exprX = *pExpr->pLeft;
4257 exprAnd.op = TK_AND;
4258 exprAnd.pLeft = &compLeft;
4259 exprAnd.pRight = &compRight;
4260 compLeft.op = TK_GE;
4261 compLeft.pLeft = &exprX;
4262 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4263 compRight.op = TK_LE;
4264 compRight.pLeft = &exprX;
4265 compRight.pRight = pExpr->x.pList->a[1].pExpr;
4266 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
4267 if( xJump ){
4268 xJump(pParse, &exprAnd, dest, jumpIfNull);
4269 }else{
4270 /* Mark the expression is being from the ON or USING clause of a join
4271 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4272 ** it into the Parse.pConstExpr list. We should use a new bit for this,
4273 ** for clarity, but we are out of bits in the Expr.flags field so we
4274 ** have to reuse the EP_FromJoin bit. Bummer. */
4275 exprX.flags |= EP_FromJoin;
4276 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
4277 }
4278 sqlite3ReleaseTempReg(pParse, regFree1);
4279
4280 /* Ensure adequate test coverage */
4281 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4282 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4283 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4284 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4285 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4286 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4287 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4288 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
4289 testcase( xJump==0 );
4290 }
4291
4292 /*
4293 ** Generate code for a boolean expression such that a jump is made
4294 ** to the label "dest" if the expression is true but execution
4295 ** continues straight thru if the expression is false.
4296 **
4297 ** If the expression evaluates to NULL (neither true nor false), then
4298 ** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
4299 **
4300 ** This code depends on the fact that certain token values (ex: TK_EQ)
4301 ** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4302 ** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4303 ** the make process cause these values to align. Assert()s in the code
4304 ** below verify that the numbers are aligned correctly.
4305 */
4306 void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4307 Vdbe *v = pParse->pVdbe;
4308 int op = 0;
4309 int regFree1 = 0;
4310 int regFree2 = 0;
4311 int r1, r2;
4312
4313 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4314 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
4315 if( NEVER(pExpr==0) ) return; /* No way this can happen */
4316 op = pExpr->op;
4317 switch( op ){
4318 case TK_AND: {
4319 int d2 = sqlite3VdbeMakeLabel(v);
4320 testcase( jumpIfNull==0 );
4321 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
4322 sqlite3ExprCachePush(pParse);
4323 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4324 sqlite3VdbeResolveLabel(v, d2);
4325 sqlite3ExprCachePop(pParse);
4326 break;
4327 }
4328 case TK_OR: {
4329 testcase( jumpIfNull==0 );
4330 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4331 sqlite3ExprCachePush(pParse);
4332 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4333 sqlite3ExprCachePop(pParse);
4334 break;
4335 }
4336 case TK_NOT: {
4337 testcase( jumpIfNull==0 );
4338 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4339 break;
4340 }
4341 case TK_IS:
4342 case TK_ISNOT:
4343 testcase( op==TK_IS );
4344 testcase( op==TK_ISNOT );
4345 op = (op==TK_IS) ? TK_EQ : TK_NE;
4346 jumpIfNull = SQLITE_NULLEQ;
4347 /* Fall thru */
4348 case TK_LT:
4349 case TK_LE:
4350 case TK_GT:
4351 case TK_GE:
4352 case TK_NE:
4353 case TK_EQ: {
4354 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4355 testcase( jumpIfNull==0 );
4356 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4357 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4358 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
4359 r1, r2, dest, jumpIfNull);
4360 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4361 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4362 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4363 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4364 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4365 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4366 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4367 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4368 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4369 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4370 testcase( regFree1==0 );
4371 testcase( regFree2==0 );
4372 break;
4373 }
4374 case TK_ISNULL:
4375 case TK_NOTNULL: {
4376 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4377 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
4378 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4379 sqlite3VdbeAddOp2(v, op, r1, dest);
4380 VdbeCoverageIf(v, op==TK_ISNULL);
4381 VdbeCoverageIf(v, op==TK_NOTNULL);
4382 testcase( regFree1==0 );
4383 break;
4384 }
4385 case TK_BETWEEN: {
4386 testcase( jumpIfNull==0 );
4387 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
4388 break;
4389 }
4390 #ifndef SQLITE_OMIT_SUBQUERY
4391 case TK_IN: {
4392 int destIfFalse = sqlite3VdbeMakeLabel(v);
4393 int destIfNull = jumpIfNull ? dest : destIfFalse;
4394 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
4395 sqlite3VdbeGoto(v, dest);
4396 sqlite3VdbeResolveLabel(v, destIfFalse);
4397 break;
4398 }
4399 #endif
4400 default: {
4401 default_expr:
4402 if( exprAlwaysTrue(pExpr) ){
4403 sqlite3VdbeGoto(v, dest);
4404 }else if( exprAlwaysFalse(pExpr) ){
4405 /* No-op */
4406 }else{
4407 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4408 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
4409 VdbeCoverage(v);
4410 testcase( regFree1==0 );
4411 testcase( jumpIfNull==0 );
4412 }
4413 break;
4414 }
4415 }
4416 sqlite3ReleaseTempReg(pParse, regFree1);
4417 sqlite3ReleaseTempReg(pParse, regFree2);
4418 }
4419
4420 /*
4421 ** Generate code for a boolean expression such that a jump is made
4422 ** to the label "dest" if the expression is false but execution
4423 ** continues straight thru if the expression is true.
4424 **
4425 ** If the expression evaluates to NULL (neither true nor false) then
4426 ** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4427 ** is 0.
4428 */
4429 void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
4430 Vdbe *v = pParse->pVdbe;
4431 int op = 0;
4432 int regFree1 = 0;
4433 int regFree2 = 0;
4434 int r1, r2;
4435
4436 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
4437 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
4438 if( pExpr==0 ) return;
4439
4440 /* The value of pExpr->op and op are related as follows:
4441 **
4442 ** pExpr->op op
4443 ** --------- ----------
4444 ** TK_ISNULL OP_NotNull
4445 ** TK_NOTNULL OP_IsNull
4446 ** TK_NE OP_Eq
4447 ** TK_EQ OP_Ne
4448 ** TK_GT OP_Le
4449 ** TK_LE OP_Gt
4450 ** TK_GE OP_Lt
4451 ** TK_LT OP_Ge
4452 **
4453 ** For other values of pExpr->op, op is undefined and unused.
4454 ** The value of TK_ and OP_ constants are arranged such that we
4455 ** can compute the mapping above using the following expression.
4456 ** Assert()s verify that the computation is correct.
4457 */
4458 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4459
4460 /* Verify correct alignment of TK_ and OP_ constants
4461 */
4462 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4463 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4464 assert( pExpr->op!=TK_NE || op==OP_Eq );
4465 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4466 assert( pExpr->op!=TK_LT || op==OP_Ge );
4467 assert( pExpr->op!=TK_LE || op==OP_Gt );
4468 assert( pExpr->op!=TK_GT || op==OP_Le );
4469 assert( pExpr->op!=TK_GE || op==OP_Lt );
4470
4471 switch( pExpr->op ){
4472 case TK_AND: {
4473 testcase( jumpIfNull==0 );
4474 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
4475 sqlite3ExprCachePush(pParse);
4476 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4477 sqlite3ExprCachePop(pParse);
4478 break;
4479 }
4480 case TK_OR: {
4481 int d2 = sqlite3VdbeMakeLabel(v);
4482 testcase( jumpIfNull==0 );
4483 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
4484 sqlite3ExprCachePush(pParse);
4485 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4486 sqlite3VdbeResolveLabel(v, d2);
4487 sqlite3ExprCachePop(pParse);
4488 break;
4489 }
4490 case TK_NOT: {
4491 testcase( jumpIfNull==0 );
4492 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
4493 break;
4494 }
4495 case TK_IS:
4496 case TK_ISNOT:
4497 testcase( pExpr->op==TK_IS );
4498 testcase( pExpr->op==TK_ISNOT );
4499 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4500 jumpIfNull = SQLITE_NULLEQ;
4501 /* Fall thru */
4502 case TK_LT:
4503 case TK_LE:
4504 case TK_GT:
4505 case TK_GE:
4506 case TK_NE:
4507 case TK_EQ: {
4508 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
4509 testcase( jumpIfNull==0 );
4510 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4511 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
4512 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
4513 r1, r2, dest, jumpIfNull);
4514 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4515 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4516 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4517 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
4518 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4519 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4520 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4521 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4522 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4523 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4524 testcase( regFree1==0 );
4525 testcase( regFree2==0 );
4526 break;
4527 }
4528 case TK_ISNULL:
4529 case TK_NOTNULL: {
4530 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4531 sqlite3VdbeAddOp2(v, op, r1, dest);
4532 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4533 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
4534 testcase( regFree1==0 );
4535 break;
4536 }
4537 case TK_BETWEEN: {
4538 testcase( jumpIfNull==0 );
4539 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
4540 break;
4541 }
4542 #ifndef SQLITE_OMIT_SUBQUERY
4543 case TK_IN: {
4544 if( jumpIfNull ){
4545 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4546 }else{
4547 int destIfNull = sqlite3VdbeMakeLabel(v);
4548 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4549 sqlite3VdbeResolveLabel(v, destIfNull);
4550 }
4551 break;
4552 }
4553 #endif
4554 default: {
4555 default_expr:
4556 if( exprAlwaysFalse(pExpr) ){
4557 sqlite3VdbeGoto(v, dest);
4558 }else if( exprAlwaysTrue(pExpr) ){
4559 /* no-op */
4560 }else{
4561 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4562 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
4563 VdbeCoverage(v);
4564 testcase( regFree1==0 );
4565 testcase( jumpIfNull==0 );
4566 }
4567 break;
4568 }
4569 }
4570 sqlite3ReleaseTempReg(pParse, regFree1);
4571 sqlite3ReleaseTempReg(pParse, regFree2);
4572 }
4573
4574 /*
4575 ** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4576 ** code generation, and that copy is deleted after code generation. This
4577 ** ensures that the original pExpr is unchanged.
4578 */
4579 void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4580 sqlite3 *db = pParse->db;
4581 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4582 if( db->mallocFailed==0 ){
4583 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4584 }
4585 sqlite3ExprDelete(db, pCopy);
4586 }
4587
4588
4589 /*
4590 ** Do a deep comparison of two expression trees. Return 0 if the two
4591 ** expressions are completely identical. Return 1 if they differ only
4592 ** by a COLLATE operator at the top level. Return 2 if there are differences
4593 ** other than the top-level COLLATE operator.
4594 **
4595 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4596 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4597 **
4598 ** The pA side might be using TK_REGISTER. If that is the case and pB is
4599 ** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4600 **
4601 ** Sometimes this routine will return 2 even if the two expressions
4602 ** really are equivalent. If we cannot prove that the expressions are
4603 ** identical, we return 2 just to be safe. So if this routine
4604 ** returns 2, then you do not really know for certain if the two
4605 ** expressions are the same. But if you get a 0 or 1 return, then you
4606 ** can be sure the expressions are the same. In the places where
4607 ** this routine is used, it does not hurt to get an extra 2 - that
4608 ** just might result in some slightly slower code. But returning
4609 ** an incorrect 0 or 1 could lead to a malfunction.
4610 */
4611 int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
4612 u32 combinedFlags;
4613 if( pA==0 || pB==0 ){
4614 return pB==pA ? 0 : 2;
4615 }
4616 combinedFlags = pA->flags | pB->flags;
4617 if( combinedFlags & EP_IntValue ){
4618 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4619 return 0;
4620 }
4621 return 2;
4622 }
4623 if( pA->op!=pB->op ){
4624 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
4625 return 1;
4626 }
4627 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
4628 return 1;
4629 }
4630 return 2;
4631 }
4632 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
4633 if( pA->op==TK_FUNCTION ){
4634 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4635 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
4636 return pA->op==TK_COLLATE ? 1 : 2;
4637 }
4638 }
4639 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
4640 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
4641 if( combinedFlags & EP_xIsSelect ) return 2;
4642 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4643 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4644 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
4645 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
4646 if( pA->iColumn!=pB->iColumn ) return 2;
4647 if( pA->iTable!=pB->iTable
4648 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
4649 }
4650 }
4651 return 0;
4652 }
4653
4654 /*
4655 ** Compare two ExprList objects. Return 0 if they are identical and
4656 ** non-zero if they differ in any way.
4657 **
4658 ** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4659 ** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4660 **
4661 ** This routine might return non-zero for equivalent ExprLists. The
4662 ** only consequence will be disabled optimizations. But this routine
4663 ** must never return 0 if the two ExprList objects are different, or
4664 ** a malfunction will result.
4665 **
4666 ** Two NULL pointers are considered to be the same. But a NULL pointer
4667 ** always differs from a non-NULL pointer.
4668 */
4669 int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
4670 int i;
4671 if( pA==0 && pB==0 ) return 0;
4672 if( pA==0 || pB==0 ) return 1;
4673 if( pA->nExpr!=pB->nExpr ) return 1;
4674 for(i=0; i<pA->nExpr; i++){
4675 Expr *pExprA = pA->a[i].pExpr;
4676 Expr *pExprB = pB->a[i].pExpr;
4677 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
4678 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
4679 }
4680 return 0;
4681 }
4682
4683 /*
4684 ** Return true if we can prove the pE2 will always be true if pE1 is
4685 ** true. Return false if we cannot complete the proof or if pE2 might
4686 ** be false. Examples:
4687 **
4688 ** pE1: x==5 pE2: x==5 Result: true
4689 ** pE1: x>0 pE2: x==5 Result: false
4690 ** pE1: x=21 pE2: x=21 OR y=43 Result: true
4691 ** pE1: x!=123 pE2: x IS NOT NULL Result: true
4692 ** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4693 ** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4694 ** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
4695 **
4696 ** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4697 ** Expr.iTable<0 then assume a table number given by iTab.
4698 **
4699 ** When in doubt, return false. Returning true might give a performance
4700 ** improvement. Returning false might cause a performance reduction, but
4701 ** it will always give the correct answer and is hence always safe.
4702 */
4703 int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
4704 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4705 return 1;
4706 }
4707 if( pE2->op==TK_OR
4708 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4709 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4710 ){
4711 return 1;
4712 }
4713 if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
4714 Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
4715 testcase( pX!=pE1->pLeft );
4716 if( sqlite3ExprCompare(pX, pE2->pLeft, iTab)==0 ) return 1;
4717 }
4718 return 0;
4719 }
4720
4721 /*
4722 ** An instance of the following structure is used by the tree walker
4723 ** to determine if an expression can be evaluated by reference to the
4724 ** index only, without having to do a search for the corresponding
4725 ** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4726 ** is the cursor for the table.
4727 */
4728 struct IdxCover {
4729 Index *pIdx; /* The index to be tested for coverage */
4730 int iCur; /* Cursor number for the table corresponding to the index */
4731 };
4732
4733 /*
4734 ** Check to see if there are references to columns in table
4735 ** pWalker->u.pIdxCover->iCur can be satisfied using the index
4736 ** pWalker->u.pIdxCover->pIdx.
4737 */
4738 static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4739 if( pExpr->op==TK_COLUMN
4740 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4741 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4742 ){
4743 pWalker->eCode = 1;
4744 return WRC_Abort;
4745 }
4746 return WRC_Continue;
4747 }
4748
4749 /*
4750 ** Determine if an index pIdx on table with cursor iCur contains will
4751 ** the expression pExpr. Return true if the index does cover the
4752 ** expression and false if the pExpr expression references table columns
4753 ** that are not found in the index pIdx.
4754 **
4755 ** An index covering an expression means that the expression can be
4756 ** evaluated using only the index and without having to lookup the
4757 ** corresponding table entry.
4758 */
4759 int sqlite3ExprCoveredByIndex(
4760 Expr *pExpr, /* The index to be tested */
4761 int iCur, /* The cursor number for the corresponding table */
4762 Index *pIdx /* The index that might be used for coverage */
4763 ){
4764 Walker w;
4765 struct IdxCover xcov;
4766 memset(&w, 0, sizeof(w));
4767 xcov.iCur = iCur;
4768 xcov.pIdx = pIdx;
4769 w.xExprCallback = exprIdxCover;
4770 w.u.pIdxCover = &xcov;
4771 sqlite3WalkExpr(&w, pExpr);
4772 return !w.eCode;
4773 }
4774
4775
4776 /*
4777 ** An instance of the following structure is used by the tree walker
4778 ** to count references to table columns in the arguments of an
4779 ** aggregate function, in order to implement the
4780 ** sqlite3FunctionThisSrc() routine.
4781 */
4782 struct SrcCount {
4783 SrcList *pSrc; /* One particular FROM clause in a nested query */
4784 int nThis; /* Number of references to columns in pSrcList */
4785 int nOther; /* Number of references to columns in other FROM clauses */
4786 };
4787
4788 /*
4789 ** Count the number of references to columns.
4790 */
4791 static int exprSrcCount(Walker *pWalker, Expr *pExpr){
4792 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4793 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4794 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4795 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4796 ** NEVER() will need to be removed. */
4797 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
4798 int i;
4799 struct SrcCount *p = pWalker->u.pSrcCount;
4800 SrcList *pSrc = p->pSrc;
4801 int nSrc = pSrc ? pSrc->nSrc : 0;
4802 for(i=0; i<nSrc; i++){
4803 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
4804 }
4805 if( i<nSrc ){
4806 p->nThis++;
4807 }else{
4808 p->nOther++;
4809 }
4810 }
4811 return WRC_Continue;
4812 }
4813
4814 /*
4815 ** Determine if any of the arguments to the pExpr Function reference
4816 ** pSrcList. Return true if they do. Also return true if the function
4817 ** has no arguments or has only constant arguments. Return false if pExpr
4818 ** references columns but not columns of tables found in pSrcList.
4819 */
4820 int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
4821 Walker w;
4822 struct SrcCount cnt;
4823 assert( pExpr->op==TK_AGG_FUNCTION );
4824 memset(&w, 0, sizeof(w));
4825 w.xExprCallback = exprSrcCount;
4826 w.u.pSrcCount = &cnt;
4827 cnt.pSrc = pSrcList;
4828 cnt.nThis = 0;
4829 cnt.nOther = 0;
4830 sqlite3WalkExprList(&w, pExpr->x.pList);
4831 return cnt.nThis>0 || cnt.nOther==0;
4832 }
4833
4834 /*
4835 ** Add a new element to the pAggInfo->aCol[] array. Return the index of
4836 ** the new element. Return a negative number if malloc fails.
4837 */
4838 static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
4839 int i;
4840 pInfo->aCol = sqlite3ArrayAllocate(
4841 db,
4842 pInfo->aCol,
4843 sizeof(pInfo->aCol[0]),
4844 &pInfo->nColumn,
4845 &i
4846 );
4847 return i;
4848 }
4849
4850 /*
4851 ** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4852 ** the new element. Return a negative number if malloc fails.
4853 */
4854 static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
4855 int i;
4856 pInfo->aFunc = sqlite3ArrayAllocate(
4857 db,
4858 pInfo->aFunc,
4859 sizeof(pInfo->aFunc[0]),
4860 &pInfo->nFunc,
4861 &i
4862 );
4863 return i;
4864 }
4865
4866 /*
4867 ** This is the xExprCallback for a tree walker. It is used to
4868 ** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
4869 ** for additional information.
4870 */
4871 static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
4872 int i;
4873 NameContext *pNC = pWalker->u.pNC;
4874 Parse *pParse = pNC->pParse;
4875 SrcList *pSrcList = pNC->pSrcList;
4876 AggInfo *pAggInfo = pNC->pAggInfo;
4877
4878 switch( pExpr->op ){
4879 case TK_AGG_COLUMN:
4880 case TK_COLUMN: {
4881 testcase( pExpr->op==TK_AGG_COLUMN );
4882 testcase( pExpr->op==TK_COLUMN );
4883 /* Check to see if the column is in one of the tables in the FROM
4884 ** clause of the aggregate query */
4885 if( ALWAYS(pSrcList!=0) ){
4886 struct SrcList_item *pItem = pSrcList->a;
4887 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4888 struct AggInfo_col *pCol;
4889 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4890 if( pExpr->iTable==pItem->iCursor ){
4891 /* If we reach this point, it means that pExpr refers to a table
4892 ** that is in the FROM clause of the aggregate query.
4893 **
4894 ** Make an entry for the column in pAggInfo->aCol[] if there
4895 ** is not an entry there already.
4896 */
4897 int k;
4898 pCol = pAggInfo->aCol;
4899 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
4900 if( pCol->iTable==pExpr->iTable &&
4901 pCol->iColumn==pExpr->iColumn ){
4902 break;
4903 }
4904 }
4905 if( (k>=pAggInfo->nColumn)
4906 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4907 ){
4908 pCol = &pAggInfo->aCol[k];
4909 pCol->pTab = pExpr->pTab;
4910 pCol->iTable = pExpr->iTable;
4911 pCol->iColumn = pExpr->iColumn;
4912 pCol->iMem = ++pParse->nMem;
4913 pCol->iSorterColumn = -1;
4914 pCol->pExpr = pExpr;
4915 if( pAggInfo->pGroupBy ){
4916 int j, n;
4917 ExprList *pGB = pAggInfo->pGroupBy;
4918 struct ExprList_item *pTerm = pGB->a;
4919 n = pGB->nExpr;
4920 for(j=0; j<n; j++, pTerm++){
4921 Expr *pE = pTerm->pExpr;
4922 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4923 pE->iColumn==pExpr->iColumn ){
4924 pCol->iSorterColumn = j;
4925 break;
4926 }
4927 }
4928 }
4929 if( pCol->iSorterColumn<0 ){
4930 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4931 }
4932 }
4933 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4934 ** because it was there before or because we just created it).
4935 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4936 ** pAggInfo->aCol[] entry.
4937 */
4938 ExprSetVVAProperty(pExpr, EP_NoReduce);
4939 pExpr->pAggInfo = pAggInfo;
4940 pExpr->op = TK_AGG_COLUMN;
4941 pExpr->iAgg = (i16)k;
4942 break;
4943 } /* endif pExpr->iTable==pItem->iCursor */
4944 } /* end loop over pSrcList */
4945 }
4946 return WRC_Prune;
4947 }
4948 case TK_AGG_FUNCTION: {
4949 if( (pNC->ncFlags & NC_InAggFunc)==0
4950 && pWalker->walkerDepth==pExpr->op2
4951 ){
4952 /* Check to see if pExpr is a duplicate of another aggregate
4953 ** function that is already in the pAggInfo structure
4954 */
4955 struct AggInfo_func *pItem = pAggInfo->aFunc;
4956 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
4957 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
4958 break;
4959 }
4960 }
4961 if( i>=pAggInfo->nFunc ){
4962 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4963 */
4964 u8 enc = ENC(pParse->db);
4965 i = addAggInfoFunc(pParse->db, pAggInfo);
4966 if( i>=0 ){
4967 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4968 pItem = &pAggInfo->aFunc[i];
4969 pItem->pExpr = pExpr;
4970 pItem->iMem = ++pParse->nMem;
4971 assert( !ExprHasProperty(pExpr, EP_IntValue) );
4972 pItem->pFunc = sqlite3FindFunction(pParse->db,
4973 pExpr->u.zToken,
4974 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
4975 if( pExpr->flags & EP_Distinct ){
4976 pItem->iDistinct = pParse->nTab++;
4977 }else{
4978 pItem->iDistinct = -1;
4979 }
4980 }
4981 }
4982 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4983 */
4984 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
4985 ExprSetVVAProperty(pExpr, EP_NoReduce);
4986 pExpr->iAgg = (i16)i;
4987 pExpr->pAggInfo = pAggInfo;
4988 return WRC_Prune;
4989 }else{
4990 return WRC_Continue;
4991 }
4992 }
4993 }
4994 return WRC_Continue;
4995 }
4996 static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
4997 UNUSED_PARAMETER(pWalker);
4998 UNUSED_PARAMETER(pSelect);
4999 return WRC_Continue;
5000 }
5001
5002 /*
5003 ** Analyze the pExpr expression looking for aggregate functions and
5004 ** for variables that need to be added to AggInfo object that pNC->pAggInfo
5005 ** points to. Additional entries are made on the AggInfo object as
5006 ** necessary.
5007 **
5008 ** This routine should only be called after the expression has been
5009 ** analyzed by sqlite3ResolveExprNames().
5010 */
5011 void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
5012 Walker w;
5013 memset(&w, 0, sizeof(w));
5014 w.xExprCallback = analyzeAggregate;
5015 w.xSelectCallback = analyzeAggregatesInSelect;
5016 w.u.pNC = pNC;
5017 assert( pNC->pSrcList!=0 );
5018 sqlite3WalkExpr(&w, pExpr);
5019 }
5020
5021 /*
5022 ** Call sqlite3ExprAnalyzeAggregates() for every expression in an
5023 ** expression list. Return the number of errors.
5024 **
5025 ** If an error is found, the analysis is cut short.
5026 */
5027 void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
5028 struct ExprList_item *pItem;
5029 int i;
5030 if( pList ){
5031 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5032 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
5033 }
5034 }
5035 }
5036
5037 /*
5038 ** Allocate a single new register for use to hold some intermediate result.
5039 */
5040 int sqlite3GetTempReg(Parse *pParse){
5041 if( pParse->nTempReg==0 ){
5042 return ++pParse->nMem;
5043 }
5044 return pParse->aTempReg[--pParse->nTempReg];
5045 }
5046
5047 /*
5048 ** Deallocate a register, making available for reuse for some other
5049 ** purpose.
5050 **
5051 ** If a register is currently being used by the column cache, then
5052 ** the deallocation is deferred until the column cache line that uses
5053 ** the register becomes stale.
5054 */
5055 void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
5056 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
5057 int i;
5058 struct yColCache *p;
5059 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
5060 if( p->iReg==iReg ){
5061 p->tempReg = 1;
5062 return;
5063 }
5064 }
5065 pParse->aTempReg[pParse->nTempReg++] = iReg;
5066 }
5067 }
5068
5069 /*
5070 ** Allocate or deallocate a block of nReg consecutive registers.
5071 */
5072 int sqlite3GetTempRange(Parse *pParse, int nReg){
5073 int i, n;
5074 if( nReg==1 ) return sqlite3GetTempReg(pParse);
5075 i = pParse->iRangeReg;
5076 n = pParse->nRangeReg;
5077 if( nReg<=n ){
5078 assert( !usedAsColumnCache(pParse, i, i+n-1) );
5079 pParse->iRangeReg += nReg;
5080 pParse->nRangeReg -= nReg;
5081 }else{
5082 i = pParse->nMem+1;
5083 pParse->nMem += nReg;
5084 }
5085 return i;
5086 }
5087 void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
5088 if( nReg==1 ){
5089 sqlite3ReleaseTempReg(pParse, iReg);
5090 return;
5091 }
5092 sqlite3ExprCacheRemove(pParse, iReg, nReg);
5093 if( nReg>pParse->nRangeReg ){
5094 pParse->nRangeReg = nReg;
5095 pParse->iRangeReg = iReg;
5096 }
5097 }
5098
5099 /*
5100 ** Mark all temporary registers as being unavailable for reuse.
5101 */
5102 void sqlite3ClearTempRegCache(Parse *pParse){
5103 pParse->nTempReg = 0;
5104 pParse->nRangeReg = 0;
5105 }
5106
5107 /*
5108 ** Validate that no temporary register falls within the range of
5109 ** iFirst..iLast, inclusive. This routine is only call from within assert()
5110 ** statements.
5111 */
5112 #ifdef SQLITE_DEBUG
5113 int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5114 int i;
5115 if( pParse->nRangeReg>0
5116 && pParse->iRangeReg+pParse->nRangeReg<iLast
5117 && pParse->iRangeReg>=iFirst
5118 ){
5119 return 0;
5120 }
5121 for(i=0; i<pParse->nTempReg; i++){
5122 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5123 return 0;
5124 }
5125 }
5126 return 1;
5127 }
5128 #endif /* SQLITE_DEBUG */
OLDNEW
« no previous file with comments | « third_party/sqlite/sqlite-src-3170000/src/delete.c ('k') | third_party/sqlite/sqlite-src-3170000/src/fault.c » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698