4
** The author disclaims copyright to this source code. In place of
5
** a legal notice, here is a blessing:
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.
11
*************************************************************************
12
** This file contains routines used for analyzing expressions and
13
** for generating VDBE code that evaluates expressions in SQLite.
15
#include "sqliteInt.h"
18
** Return the 'affinity' of the expression pExpr if any.
20
** If pExpr is a column, a reference to a column via an 'AS' alias,
21
** or a sub-select with a column as the return value, then the
22
** affinity of that column is returned. Otherwise, 0x00 is returned,
23
** indicating no affinity for the expression.
25
** i.e. the WHERE clause expresssions in the following statements all
28
** CREATE TABLE t1(a);
29
** SELECT * FROM t1 WHERE a;
30
** SELECT a AS b FROM t1 WHERE b;
31
** SELECT * FROM t1 WHERE (select a from t1);
33
char sqlite3ExprAffinity(Expr *pExpr){
36
assert( pExpr->flags&EP_xIsSelect );
37
return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
39
#ifndef SQLITE_OMIT_CAST
41
assert( !ExprHasProperty(pExpr, EP_IntValue) );
42
return sqlite3AffinityType(pExpr->u.zToken);
45
if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
48
/* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
49
** a TK_COLUMN but was previously evaluated and cached in a register */
50
int j = pExpr->iColumn;
51
if( j<0 ) return SQLITE_AFF_INTEGER;
52
assert( pExpr->pTab && j<pExpr->pTab->nCol );
53
return pExpr->pTab->aCol[j].affinity;
55
return pExpr->affinity;
59
** Set the collating sequence for expression pExpr to be the collating
60
** sequence named by pToken. Return a pointer to the revised expression.
61
** The collating sequence is marked as "explicit" using the EP_ExpCollate
62
** flag. An explicit collating sequence will override implicit
63
** collating sequences.
65
Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pCollName){
66
char *zColl = 0; /* Dequoted name of collation sequence */
68
sqlite3 *db = pParse->db;
69
zColl = sqlite3NameFromToken(db, pCollName);
71
pColl = sqlite3LocateCollSeq(pParse, zColl);
74
pExpr->flags |= EP_ExpCollate;
77
sqlite3DbFree(db, zColl);
82
** Return the default collation sequence for the expression pExpr. If
83
** there is no default collation type, return 0.
85
CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
94
op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER || op==TK_TRIGGER
96
/* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
97
** a TK_COLUMN but was previously evaluated and cached in a register */
101
sqlite3 *db = pParse->db;
102
zColl = p->pTab->aCol[j].zColl;
103
pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
104
pExpr->pColl = pColl;
108
if( op!=TK_CAST && op!=TK_UPLUS ){
113
if( sqlite3CheckCollSeq(pParse, pColl) ){
120
** pExpr is an operand of a comparison operator. aff2 is the
121
** type affinity of the other operand. This routine returns the
122
** type affinity that should be used for the comparison operator.
124
char sqlite3CompareAffinity(Expr *pExpr, char aff2){
125
char aff1 = sqlite3ExprAffinity(pExpr);
127
/* Both sides of the comparison are columns. If one has numeric
128
** affinity, use that. Otherwise use no affinity.
130
if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
131
return SQLITE_AFF_NUMERIC;
133
return SQLITE_AFF_NONE;
135
}else if( !aff1 && !aff2 ){
136
/* Neither side of the comparison is a column. Compare the
139
return SQLITE_AFF_NONE;
141
/* One side is a column, the other is not. Use the columns affinity. */
142
assert( aff1==0 || aff2==0 );
143
return (aff1 + aff2);
148
** pExpr is a comparison operator. Return the type affinity that should
149
** be applied to both operands prior to doing the comparison.
151
static char comparisonAffinity(Expr *pExpr){
153
assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
154
pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
155
pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
156
assert( pExpr->pLeft );
157
aff = sqlite3ExprAffinity(pExpr->pLeft);
159
aff = sqlite3CompareAffinity(pExpr->pRight, aff);
160
}else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
161
aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
163
aff = SQLITE_AFF_NONE;
169
** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
170
** idx_affinity is the affinity of an indexed column. Return true
171
** if the index with affinity idx_affinity may be used to implement
172
** the comparison in pExpr.
174
int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
175
char aff = comparisonAffinity(pExpr);
177
case SQLITE_AFF_NONE:
179
case SQLITE_AFF_TEXT:
180
return idx_affinity==SQLITE_AFF_TEXT;
182
return sqlite3IsNumericAffinity(idx_affinity);
187
** Return the P5 value that should be used for a binary comparison
188
** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
190
static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
191
u8 aff = (char)sqlite3ExprAffinity(pExpr2);
192
aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
197
** Return a pointer to the collation sequence that should be used by
198
** a binary comparison operator comparing pLeft and pRight.
200
** If the left hand expression has a collating sequence type, then it is
201
** used. Otherwise the collation sequence for the right hand expression
202
** is used, or the default (BINARY) if neither expression has a collating
205
** Argument pRight (but not pLeft) may be a null pointer. In this case,
206
** it is not considered.
208
CollSeq *sqlite3BinaryCompareCollSeq(
215
if( pLeft->flags & EP_ExpCollate ){
216
assert( pLeft->pColl );
217
pColl = pLeft->pColl;
218
}else if( pRight && pRight->flags & EP_ExpCollate ){
219
assert( pRight->pColl );
220
pColl = pRight->pColl;
222
pColl = sqlite3ExprCollSeq(pParse, pLeft);
224
pColl = sqlite3ExprCollSeq(pParse, pRight);
231
** Generate code for a comparison operator.
233
static int codeCompare(
234
Parse *pParse, /* The parsing (and code generating) context */
235
Expr *pLeft, /* The left operand */
236
Expr *pRight, /* The right operand */
237
int opcode, /* The comparison opcode */
238
int in1, int in2, /* Register holding operands */
239
int dest, /* Jump here if true. */
240
int jumpIfNull /* If true, jump if either operand is NULL */
246
p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
247
p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
248
addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
249
(void*)p4, P4_COLLSEQ);
250
sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
254
#if SQLITE_MAX_EXPR_DEPTH>0
256
** Check that argument nHeight is less than or equal to the maximum
257
** expression depth allowed. If it is not, leave an error message in
260
int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
262
int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
263
if( nHeight>mxHeight ){
264
sqlite3ErrorMsg(pParse,
265
"Expression tree is too large (maximum depth %d)", mxHeight
272
/* The following three functions, heightOfExpr(), heightOfExprList()
273
** and heightOfSelect(), are used to determine the maximum height
274
** of any expression tree referenced by the structure passed as the
277
** If this maximum height is greater than the current value pointed
278
** to by pnHeight, the second parameter, then set *pnHeight to that
281
static void heightOfExpr(Expr *p, int *pnHeight){
283
if( p->nHeight>*pnHeight ){
284
*pnHeight = p->nHeight;
288
static void heightOfExprList(ExprList *p, int *pnHeight){
291
for(i=0; i<p->nExpr; i++){
292
heightOfExpr(p->a[i].pExpr, pnHeight);
296
static void heightOfSelect(Select *p, int *pnHeight){
298
heightOfExpr(p->pWhere, pnHeight);
299
heightOfExpr(p->pHaving, pnHeight);
300
heightOfExpr(p->pLimit, pnHeight);
301
heightOfExpr(p->pOffset, pnHeight);
302
heightOfExprList(p->pEList, pnHeight);
303
heightOfExprList(p->pGroupBy, pnHeight);
304
heightOfExprList(p->pOrderBy, pnHeight);
305
heightOfSelect(p->pPrior, pnHeight);
310
** Set the Expr.nHeight variable in the structure passed as an
311
** argument. An expression with no children, Expr.pList or
312
** Expr.pSelect member has a height of 1. Any other expression
313
** has a height equal to the maximum height of any other
314
** referenced Expr plus one.
316
static void exprSetHeight(Expr *p){
318
heightOfExpr(p->pLeft, &nHeight);
319
heightOfExpr(p->pRight, &nHeight);
320
if( ExprHasProperty(p, EP_xIsSelect) ){
321
heightOfSelect(p->x.pSelect, &nHeight);
323
heightOfExprList(p->x.pList, &nHeight);
325
p->nHeight = nHeight + 1;
329
** Set the Expr.nHeight variable using the exprSetHeight() function. If
330
** the height is greater than the maximum allowed expression depth,
331
** leave an error in pParse.
333
void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
335
sqlite3ExprCheckHeight(pParse, p->nHeight);
339
** Return the maximum height of any expression tree referenced
340
** by the select statement passed as an argument.
342
int sqlite3SelectExprHeight(Select *p){
344
heightOfSelect(p, &nHeight);
348
#define exprSetHeight(y)
349
#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
352
** This routine is the core allocator for Expr nodes.
354
** Construct a new expression node and return a pointer to it. Memory
355
** for this node and for the pToken argument is a single allocation
356
** obtained from sqlite3DbMalloc(). The calling function
357
** is responsible for making sure the node eventually gets freed.
359
** If dequote is true, then the token (if it exists) is dequoted.
360
** If dequote is false, no dequoting is performance. The deQuote
361
** parameter is ignored if pToken is NULL or if the token does not
362
** appear to be quoted. If the quotes were of the form "..." (double-quotes)
363
** then the EP_DblQuoted flag is set on the expression node.
365
** Special case: If op==TK_INTEGER and pToken points to a string that
366
** can be translated into a 32-bit integer, then the token is not
367
** stored in u.zToken. Instead, the integer values is written
368
** into u.iValue and the EP_IntValue flag is set. No extra storage
369
** is allocated to hold the integer text and the dequote flag is ignored.
371
Expr *sqlite3ExprAlloc(
372
sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
373
int op, /* Expression opcode */
374
const Token *pToken, /* Token argument. Might be NULL */
375
int dequote /* True to dequote */
382
if( op!=TK_INTEGER || pToken->z==0
383
|| sqlite3GetInt32(pToken->z, &iValue)==0 ){
384
nExtra = pToken->n+1;
387
pNew = sqlite3DbMallocZero(db, sizeof(Expr)+nExtra);
393
pNew->flags |= EP_IntValue;
394
pNew->u.iValue = iValue;
397
pNew->u.zToken = (char*)&pNew[1];
398
memcpy(pNew->u.zToken, pToken->z, pToken->n);
399
pNew->u.zToken[pToken->n] = 0;
400
if( dequote && nExtra>=3
401
&& ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
402
sqlite3Dequote(pNew->u.zToken);
403
if( c=='"' ) pNew->flags |= EP_DblQuoted;
407
#if SQLITE_MAX_EXPR_DEPTH>0
415
** Allocate a new expression node from a zero-terminated token that has
416
** already been dequoted.
419
sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
420
int op, /* Expression opcode */
421
const char *zToken /* Token argument. Might be NULL */
425
x.n = zToken ? sqlite3Strlen30(zToken) : 0;
426
return sqlite3ExprAlloc(db, op, &x, 0);
430
** Attach subtrees pLeft and pRight to the Expr node pRoot.
432
** If pRoot==NULL that means that a memory allocation error has occurred.
433
** In that case, delete the subtrees pLeft and pRight.
435
void sqlite3ExprAttachSubtrees(
442
assert( db->mallocFailed );
443
sqlite3ExprDelete(db, pLeft);
444
sqlite3ExprDelete(db, pRight);
447
pRoot->pRight = pRight;
448
if( pRight->flags & EP_ExpCollate ){
449
pRoot->flags |= EP_ExpCollate;
450
pRoot->pColl = pRight->pColl;
454
pRoot->pLeft = pLeft;
455
if( pLeft->flags & EP_ExpCollate ){
456
pRoot->flags |= EP_ExpCollate;
457
pRoot->pColl = pLeft->pColl;
460
exprSetHeight(pRoot);
465
** Allocate a Expr node which joins as many as two subtrees.
467
** One or both of the subtrees can be NULL. Return a pointer to the new
468
** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
469
** free the subtrees and return NULL.
472
Parse *pParse, /* Parsing context */
473
int op, /* Expression opcode */
474
Expr *pLeft, /* Left operand */
475
Expr *pRight, /* Right operand */
476
const Token *pToken /* Argument token */
478
Expr *p = sqlite3ExprAlloc(pParse->db, op, pToken, 1);
479
sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
484
** Join two expressions using an AND operator. If either expression is
485
** NULL, then just return the other expression.
487
Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
490
}else if( pRight==0 ){
493
Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
494
sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
500
** Construct a new expression node for a function with multiple
503
Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
505
sqlite3 *db = pParse->db;
507
pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
509
sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
512
pNew->x.pList = pList;
513
assert( !ExprHasProperty(pNew, EP_xIsSelect) );
514
sqlite3ExprSetHeight(pParse, pNew);
519
** Assign a variable number to an expression that encodes a wildcard
520
** in the original SQL statement.
522
** Wildcards consisting of a single "?" are assigned the next sequential
525
** Wildcards of the form "?nnn" are assigned the number "nnn". We make
526
** sure "nnn" is not too be to avoid a denial of service attack when
527
** the SQL statement comes from an external source.
529
** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
530
** as the previous instance of the same wildcard. Or if this is the first
531
** instance of the wildcard, the next sequenial variable number is
534
void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
535
sqlite3 *db = pParse->db;
538
if( pExpr==0 ) return;
539
assert( !ExprHasAnyProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
544
/* Wildcard of the form "?". Assign the next variable number */
546
pExpr->iColumn = (ynVar)(++pParse->nVar);
547
}else if( z[0]=='?' ){
548
/* Wildcard of the form "?nnn". Convert "nnn" to an integer and
549
** use it as the variable number */
550
int i = atoi((char*)&z[1]);
551
pExpr->iColumn = (ynVar)i;
554
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
555
testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
556
if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
557
sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
558
db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
560
if( i>pParse->nVar ){
564
/* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
565
** number as the prior appearance of the same name, or if the name
566
** has never appeared before, reuse the same variable number
570
n = sqlite3Strlen30(z);
571
for(i=0; i<pParse->nVarExpr; i++){
572
Expr *pE = pParse->apVarExpr[i];
574
if( memcmp(pE->u.zToken, z, n)==0 && pE->u.zToken[n]==0 ){
575
pExpr->iColumn = pE->iColumn;
579
if( i>=pParse->nVarExpr ){
580
pExpr->iColumn = (ynVar)(++pParse->nVar);
581
if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
582
pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
584
sqlite3DbReallocOrFree(
587
pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
590
if( !db->mallocFailed ){
591
assert( pParse->apVarExpr!=0 );
592
pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
596
if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
597
sqlite3ErrorMsg(pParse, "too many SQL variables");
602
** Recursively delete an expression tree.
604
void sqlite3ExprDelete(sqlite3 *db, Expr *p){
606
if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
607
sqlite3ExprDelete(db, p->pLeft);
608
sqlite3ExprDelete(db, p->pRight);
609
if( !ExprHasProperty(p, EP_Reduced) && (p->flags2 & EP2_MallocedToken)!=0 ){
610
sqlite3DbFree(db, p->u.zToken);
612
if( ExprHasProperty(p, EP_xIsSelect) ){
613
sqlite3SelectDelete(db, p->x.pSelect);
615
sqlite3ExprListDelete(db, p->x.pList);
618
if( !ExprHasProperty(p, EP_Static) ){
619
sqlite3DbFree(db, p);
624
** Return the number of bytes allocated for the expression structure
625
** passed as the first argument. This is always one of EXPR_FULLSIZE,
626
** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
628
static int exprStructSize(Expr *p){
629
if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
630
if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
631
return EXPR_FULLSIZE;
635
** The dupedExpr*Size() routines each return the number of bytes required
636
** to store a copy of an expression or expression tree. They differ in
637
** how much of the tree is measured.
639
** dupedExprStructSize() Size of only the Expr structure
640
** dupedExprNodeSize() Size of Expr + space for token
641
** dupedExprSize() Expr + token + subtree components
643
***************************************************************************
645
** The dupedExprStructSize() function returns two values OR-ed together:
646
** (1) the space required for a copy of the Expr structure only and
647
** (2) the EP_xxx flags that indicate what the structure size should be.
648
** The return values is always one of:
651
** EXPR_REDUCEDSIZE | EP_Reduced
652
** EXPR_TOKENONLYSIZE | EP_TokenOnly
654
** The size of the structure can be found by masking the return value
655
** of this routine with 0xfff. The flags can be found by masking the
656
** return value with EP_Reduced|EP_TokenOnly.
658
** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
659
** (unreduced) Expr objects as they or originally constructed by the parser.
660
** During expression analysis, extra information is computed and moved into
661
** later parts of teh Expr object and that extra information might get chopped
662
** off if the expression is reduced. Note also that it does not work to
663
** make a EXPRDUP_REDUCE copy of a reduced expression. It is only legal
664
** to reduce a pristine expression tree from the parser. The implementation
665
** of dupedExprStructSize() contain multiple assert() statements that attempt
666
** to enforce this constraint.
668
static int dupedExprStructSize(Expr *p, int flags){
670
assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
671
if( 0==(flags&EXPRDUP_REDUCE) ){
672
nSize = EXPR_FULLSIZE;
674
assert( !ExprHasAnyProperty(p, EP_TokenOnly|EP_Reduced) );
675
assert( !ExprHasProperty(p, EP_FromJoin) );
676
assert( (p->flags2 & EP2_MallocedToken)==0 );
677
assert( (p->flags2 & EP2_Irreducible)==0 );
678
if( p->pLeft || p->pRight || p->pColl || p->x.pList ){
679
nSize = EXPR_REDUCEDSIZE | EP_Reduced;
681
nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
688
** This function returns the space in bytes required to store the copy
689
** of the Expr structure and a copy of the Expr.u.zToken string (if that
690
** string is defined.)
692
static int dupedExprNodeSize(Expr *p, int flags){
693
int nByte = dupedExprStructSize(p, flags) & 0xfff;
694
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
695
nByte += sqlite3Strlen30(p->u.zToken)+1;
697
return ROUND8(nByte);
701
** Return the number of bytes required to create a duplicate of the
702
** expression passed as the first argument. The second argument is a
703
** mask containing EXPRDUP_XXX flags.
705
** The value returned includes space to create a copy of the Expr struct
706
** itself and the buffer referred to by Expr.u.zToken, if any.
708
** If the EXPRDUP_REDUCE flag is set, then the return value includes
709
** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
710
** and Expr.pRight variables (but not for any structures pointed to or
711
** descended from the Expr.x.pList or Expr.x.pSelect variables).
713
static int dupedExprSize(Expr *p, int flags){
716
nByte = dupedExprNodeSize(p, flags);
717
if( flags&EXPRDUP_REDUCE ){
718
nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
725
** This function is similar to sqlite3ExprDup(), except that if pzBuffer
726
** is not NULL then *pzBuffer is assumed to point to a buffer large enough
727
** to store the copy of expression p, the copies of p->u.zToken
728
** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
729
** if any. Before returning, *pzBuffer is set to the first byte passed the
730
** portion of the buffer copied into by this function.
732
static Expr *exprDup(sqlite3 *db, Expr *p, int flags, u8 **pzBuffer){
733
Expr *pNew = 0; /* Value to return */
735
const int isReduced = (flags&EXPRDUP_REDUCE);
739
assert( pzBuffer==0 || isReduced );
741
/* Figure out where to write the new Expr structure. */
744
staticFlag = EP_Static;
746
zAlloc = sqlite3DbMallocRaw(db, dupedExprSize(p, flags));
748
pNew = (Expr *)zAlloc;
751
/* Set nNewSize to the size allocated for the structure pointed to
752
** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
753
** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
754
** by the copy of the p->u.zToken string (if any).
756
const unsigned nStructSize = dupedExprStructSize(p, flags);
757
const int nNewSize = nStructSize & 0xfff;
759
if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
760
nToken = sqlite3Strlen30(p->u.zToken) + 1;
765
assert( ExprHasProperty(p, EP_Reduced)==0 );
766
memcpy(zAlloc, p, nNewSize);
768
int nSize = exprStructSize(p);
769
memcpy(zAlloc, p, nSize);
770
memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
773
/* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
774
pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static);
775
pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
776
pNew->flags |= staticFlag;
778
/* Copy the p->u.zToken string, if any. */
780
char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
781
memcpy(zToken, p->u.zToken, nToken);
784
if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
785
/* Fill in the pNew->x.pSelect or pNew->x.pList member. */
786
if( ExprHasProperty(p, EP_xIsSelect) ){
787
pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, isReduced);
789
pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, isReduced);
793
/* Fill in pNew->pLeft and pNew->pRight. */
794
if( ExprHasAnyProperty(pNew, EP_Reduced|EP_TokenOnly) ){
795
zAlloc += dupedExprNodeSize(p, flags);
796
if( ExprHasProperty(pNew, EP_Reduced) ){
797
pNew->pLeft = exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc);
798
pNew->pRight = exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc);
805
if( !ExprHasAnyProperty(p, EP_TokenOnly) ){
806
pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
807
pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
817
** The following group of routines make deep copies of expressions,
818
** expression lists, ID lists, and select statements. The copies can
819
** be deleted (by being passed to their respective ...Delete() routines)
820
** without effecting the originals.
822
** The expression list, ID, and source lists return by sqlite3ExprListDup(),
823
** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
824
** by subsequent calls to sqlite*ListAppend() routines.
826
** Any tables that the SrcList might point to are not duplicated.
828
** The flags parameter contains a combination of the EXPRDUP_XXX flags.
829
** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
830
** truncated version of the usual Expr structure that will be stored as
831
** part of the in-memory representation of the database schema.
833
Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
834
return exprDup(db, p, flags, 0);
836
ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
838
struct ExprList_item *pItem, *pOldItem;
841
pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
842
if( pNew==0 ) return 0;
844
pNew->nExpr = pNew->nAlloc = p->nExpr;
845
pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
847
sqlite3DbFree(db, pNew);
851
for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
852
Expr *pOldExpr = pOldItem->pExpr;
853
pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
854
pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
855
pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
856
pItem->sortOrder = pOldItem->sortOrder;
858
pItem->iCol = pOldItem->iCol;
859
pItem->iAlias = pOldItem->iAlias;
865
** If cursors, triggers, views and subqueries are all omitted from
866
** the build, then none of the following routines, except for
867
** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
868
** called with a NULL argument.
870
#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
871
|| !defined(SQLITE_OMIT_SUBQUERY)
872
SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
877
nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
878
pNew = sqlite3DbMallocRaw(db, nByte );
879
if( pNew==0 ) return 0;
880
pNew->nSrc = pNew->nAlloc = p->nSrc;
881
for(i=0; i<p->nSrc; i++){
882
struct SrcList_item *pNewItem = &pNew->a[i];
883
struct SrcList_item *pOldItem = &p->a[i];
885
pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
886
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
887
pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
888
pNewItem->jointype = pOldItem->jointype;
889
pNewItem->iCursor = pOldItem->iCursor;
890
pNewItem->isPopulated = pOldItem->isPopulated;
891
pNewItem->zIndex = sqlite3DbStrDup(db, pOldItem->zIndex);
892
pNewItem->notIndexed = pOldItem->notIndexed;
893
pNewItem->pIndex = pOldItem->pIndex;
894
pTab = pNewItem->pTab = pOldItem->pTab;
898
pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
899
pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
900
pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
901
pNewItem->colUsed = pOldItem->colUsed;
905
IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
909
pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
910
if( pNew==0 ) return 0;
911
pNew->nId = pNew->nAlloc = p->nId;
912
pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
914
sqlite3DbFree(db, pNew);
917
for(i=0; i<p->nId; i++){
918
struct IdList_item *pNewItem = &pNew->a[i];
919
struct IdList_item *pOldItem = &p->a[i];
920
pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
921
pNewItem->idx = pOldItem->idx;
925
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
928
pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
929
if( pNew==0 ) return 0;
930
pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
931
pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
932
pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
933
pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
934
pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
935
pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
937
pNew->pPrior = sqlite3SelectDup(db, p->pPrior, flags);
938
pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
939
pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
942
pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
943
pNew->pRightmost = 0;
944
pNew->addrOpenEphm[0] = -1;
945
pNew->addrOpenEphm[1] = -1;
946
pNew->addrOpenEphm[2] = -1;
950
Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
958
** Add a new element to the end of an expression list. If pList is
959
** initially NULL, then create a new expression list.
961
** If a memory allocation error occurs, the entire list is freed and
962
** NULL is returned. If non-NULL is returned, then it is guaranteed
963
** that the new entry was successfully appended.
965
ExprList *sqlite3ExprListAppend(
966
Parse *pParse, /* Parsing context */
967
ExprList *pList, /* List to which to append. Might be NULL */
968
Expr *pExpr /* Expression to be appended. Might be NULL */
970
sqlite3 *db = pParse->db;
972
pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
976
assert( pList->nAlloc==0 );
978
if( pList->nAlloc<=pList->nExpr ){
979
struct ExprList_item *a;
980
int n = pList->nAlloc*2 + 4;
981
a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
986
pList->nAlloc = sqlite3DbMallocSize(db, a)/sizeof(a[0]);
988
assert( pList->a!=0 );
990
struct ExprList_item *pItem = &pList->a[pList->nExpr++];
991
memset(pItem, 0, sizeof(*pItem));
992
pItem->pExpr = pExpr;
997
/* Avoid leaking memory if malloc has failed. */
998
sqlite3ExprDelete(db, pExpr);
999
sqlite3ExprListDelete(db, pList);
1004
** Set the ExprList.a[].zName element of the most recently added item
1005
** on the expression list.
1007
** pList might be NULL following an OOM error. But pName should never be
1008
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1011
void sqlite3ExprListSetName(
1012
Parse *pParse, /* Parsing context */
1013
ExprList *pList, /* List to which to add the span. */
1014
Token *pName, /* Name to be added */
1015
int dequote /* True to cause the name to be dequoted */
1017
assert( pList!=0 || pParse->db->mallocFailed!=0 );
1019
struct ExprList_item *pItem;
1020
assert( pList->nExpr>0 );
1021
pItem = &pList->a[pList->nExpr-1];
1022
assert( pItem->zName==0 );
1023
pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1024
if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1029
** Set the ExprList.a[].zSpan element of the most recently added item
1030
** on the expression list.
1032
** pList might be NULL following an OOM error. But pSpan should never be
1033
** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1036
void sqlite3ExprListSetSpan(
1037
Parse *pParse, /* Parsing context */
1038
ExprList *pList, /* List to which to add the span. */
1039
ExprSpan *pSpan /* The span to be added */
1041
sqlite3 *db = pParse->db;
1042
assert( pList!=0 || db->mallocFailed!=0 );
1044
struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1045
assert( pList->nExpr>0 );
1046
assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1047
sqlite3DbFree(db, pItem->zSpan);
1048
pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
1049
(int)(pSpan->zEnd - pSpan->zStart));
1054
** If the expression list pEList contains more than iLimit elements,
1055
** leave an error message in pParse.
1057
void sqlite3ExprListCheckLength(
1062
int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
1063
testcase( pEList && pEList->nExpr==mx );
1064
testcase( pEList && pEList->nExpr==mx+1 );
1065
if( pEList && pEList->nExpr>mx ){
1066
sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1071
** Delete an entire expression list.
1073
void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1075
struct ExprList_item *pItem;
1076
if( pList==0 ) return;
1077
assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
1078
assert( pList->nExpr<=pList->nAlloc );
1079
for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
1080
sqlite3ExprDelete(db, pItem->pExpr);
1081
sqlite3DbFree(db, pItem->zName);
1082
sqlite3DbFree(db, pItem->zSpan);
1084
sqlite3DbFree(db, pList->a);
1085
sqlite3DbFree(db, pList);
1089
** These routines are Walker callbacks. Walker.u.pi is a pointer
1090
** to an integer. These routines are checking an expression to see
1091
** if it is a constant. Set *Walker.u.pi to 0 if the expression is
1094
** These callback routines are used to implement the following:
1096
** sqlite3ExprIsConstant()
1097
** sqlite3ExprIsConstantNotJoin()
1098
** sqlite3ExprIsConstantOrFunction()
1101
static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
1103
/* If pWalker->u.i is 3 then any term of the expression that comes from
1104
** the ON or USING clauses of a join disqualifies the expression
1105
** from being considered constant. */
1106
if( pWalker->u.i==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
1111
switch( pExpr->op ){
1112
/* Consider functions to be constant if all their arguments are constant
1113
** and pWalker->u.i==2 */
1115
if( pWalker->u.i==2 ) return 0;
1119
case TK_AGG_FUNCTION:
1121
testcase( pExpr->op==TK_ID );
1122
testcase( pExpr->op==TK_COLUMN );
1123
testcase( pExpr->op==TK_AGG_FUNCTION );
1124
testcase( pExpr->op==TK_AGG_COLUMN );
1128
testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1129
testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
1130
return WRC_Continue;
1133
static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1134
UNUSED_PARAMETER(NotUsed);
1138
static int exprIsConst(Expr *p, int initFlag){
1141
w.xExprCallback = exprNodeIsConstant;
1142
w.xSelectCallback = selectNodeIsConstant;
1143
sqlite3WalkExpr(&w, p);
1148
** Walk an expression tree. Return 1 if the expression is constant
1149
** and 0 if it involves variables or function calls.
1151
** For the purposes of this function, a double-quoted string (ex: "abc")
1152
** is considered a variable but a single-quoted string (ex: 'abc') is
1155
int sqlite3ExprIsConstant(Expr *p){
1156
return exprIsConst(p, 1);
1160
** Walk an expression tree. Return 1 if the expression is constant
1161
** that does no originate from the ON or USING clauses of a join.
1162
** Return 0 if it involves variables or function calls or terms from
1163
** an ON or USING clause.
1165
int sqlite3ExprIsConstantNotJoin(Expr *p){
1166
return exprIsConst(p, 3);
1170
** Walk an expression tree. Return 1 if the expression is constant
1171
** or a function call with constant arguments. Return and 0 if there
1172
** are any variables.
1174
** For the purposes of this function, a double-quoted string (ex: "abc")
1175
** is considered a variable but a single-quoted string (ex: 'abc') is
1178
int sqlite3ExprIsConstantOrFunction(Expr *p){
1179
return exprIsConst(p, 2);
1183
** If the expression p codes a constant integer that is small enough
1184
** to fit in a 32-bit integer, return 1 and put the value of the integer
1185
** in *pValue. If the expression is not an integer or if it is too big
1186
** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
1188
int sqlite3ExprIsInteger(Expr *p, int *pValue){
1190
if( p->flags & EP_IntValue ){
1191
*pValue = p->u.iValue;
1196
rc = sqlite3GetInt32(p->u.zToken, pValue);
1201
rc = sqlite3ExprIsInteger(p->pLeft, pValue);
1206
if( sqlite3ExprIsInteger(p->pLeft, &v) ){
1215
assert( ExprHasAnyProperty(p, EP_Reduced|EP_TokenOnly)
1216
|| (p->flags2 & EP2_MallocedToken)==0 );
1218
p->flags |= EP_IntValue;
1219
p->u.iValue = *pValue;
1225
** Return FALSE if there is no chance that the expression can be NULL.
1227
** If the expression might be NULL or if the expression is too complex
1228
** to tell return TRUE.
1230
** This routine is used as an optimization, to skip OP_IsNull opcodes
1231
** when we know that a value cannot be NULL. Hence, a false positive
1232
** (returning TRUE when in fact the expression can never be NULL) might
1233
** be a small performance hit but is otherwise harmless. On the other
1234
** hand, a false negative (returning FALSE when the result could be NULL)
1235
** will likely result in an incorrect answer. So when in doubt, return
1238
int sqlite3ExprCanBeNull(const Expr *p){
1240
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1242
if( op==TK_REGISTER ) op = p->op2;
1255
** Generate an OP_IsNull instruction that tests register iReg and jumps
1256
** to location iDest if the value in iReg is NULL. The value in iReg
1257
** was computed by pExpr. If we can look at pExpr at compile-time and
1258
** determine that it can never generate a NULL, then the OP_IsNull operation
1261
void sqlite3ExprCodeIsNullJump(
1262
Vdbe *v, /* The VDBE under construction */
1263
const Expr *pExpr, /* Only generate OP_IsNull if this expr can be NULL */
1264
int iReg, /* Test the value in this register for NULL */
1265
int iDest /* Jump here if the value is null */
1267
if( sqlite3ExprCanBeNull(pExpr) ){
1268
sqlite3VdbeAddOp2(v, OP_IsNull, iReg, iDest);
1273
** Return TRUE if the given expression is a constant which would be
1274
** unchanged by OP_Affinity with the affinity given in the second
1277
** This routine is used to determine if the OP_Affinity operation
1278
** can be omitted. When in doubt return FALSE. A false negative
1279
** is harmless. A false positive, however, can result in the wrong
1282
int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1284
if( aff==SQLITE_AFF_NONE ) return 1;
1285
while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
1287
if( op==TK_REGISTER ) op = p->op2;
1290
return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1293
return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1296
return aff==SQLITE_AFF_TEXT;
1302
assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1304
&& (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
1313
** Return TRUE if the given string is a row-id column name.
1315
int sqlite3IsRowid(const char *z){
1316
if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1317
if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1318
if( sqlite3StrICmp(z, "OID")==0 ) return 1;
1323
** Return true if we are able to the IN operator optimization on a
1324
** query of the form
1326
** x IN (SELECT ...)
1328
** Where the SELECT... clause is as specified by the parameter to this
1331
** The Select object passed in has already been preprocessed and no
1332
** errors have been found.
1334
#ifndef SQLITE_OMIT_SUBQUERY
1335
static int isCandidateForInOpt(Select *p){
1339
if( p==0 ) return 0; /* right-hand side of IN is SELECT */
1340
if( p->pPrior ) return 0; /* Not a compound SELECT */
1341
if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
1342
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1343
testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1344
return 0; /* No DISTINCT keyword and no aggregate functions */
1346
assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
1347
if( p->pLimit ) return 0; /* Has no LIMIT clause */
1348
assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
1349
if( p->pWhere ) return 0; /* Has no WHERE clause */
1352
if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
1353
if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
1354
pTab = pSrc->a[0].pTab;
1355
if( NEVER(pTab==0) ) return 0;
1356
assert( pTab->pSelect==0 ); /* FROM clause is not a view */
1357
if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1359
if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
1360
if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1363
#endif /* SQLITE_OMIT_SUBQUERY */
1366
** This function is used by the implementation of the IN (...) operator.
1367
** It's job is to find or create a b-tree structure that may be used
1368
** either to test for membership of the (...) set or to iterate through
1369
** its members, skipping duplicates.
1371
** The index of the cursor opened on the b-tree (database table, database index
1372
** or ephermal table) is stored in pX->iTable before this function returns.
1373
** The returned value of this function indicates the b-tree type, as follows:
1375
** IN_INDEX_ROWID - The cursor was opened on a database table.
1376
** IN_INDEX_INDEX - The cursor was opened on a database index.
1377
** IN_INDEX_EPH - The cursor was opened on a specially created and
1378
** populated epheremal table.
1380
** An existing b-tree may only be used if the SELECT is of the simple
1383
** SELECT <column> FROM <table>
1385
** If the prNotFound parameter is 0, then the b-tree will be used to iterate
1386
** through the set members, skipping any duplicates. In this case an
1387
** epheremal table must be used unless the selected <column> is guaranteed
1388
** to be unique - either because it is an INTEGER PRIMARY KEY or it
1389
** has a UNIQUE constraint or UNIQUE index.
1391
** If the prNotFound parameter is not 0, then the b-tree will be used
1392
** for fast set membership tests. In this case an epheremal table must
1393
** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1394
** be found with <column> as its left-most column.
1396
** When the b-tree is being used for membership tests, the calling function
1397
** needs to know whether or not the structure contains an SQL NULL
1398
** value in order to correctly evaluate expressions like "X IN (Y, Z)".
1399
** If there is any chance that the (...) might contain a NULL value at
1400
** runtime, then a register is allocated and the register number written
1401
** to *prNotFound. If there is no chance that the (...) contains a
1402
** NULL value, then *prNotFound is left unchanged.
1404
** If a register is allocated and its location stored in *prNotFound, then
1405
** its initial value is NULL. If the (...) does not remain constant
1406
** for the duration of the query (i.e. the SELECT within the (...)
1407
** is a correlated subquery) then the value of the allocated register is
1408
** reset to NULL each time the subquery is rerun. This allows the
1409
** caller to use vdbe code equivalent to the following:
1411
** if( register==NULL ){
1412
** has_null = <test if data structure contains null>
1416
** in order to avoid running the <test if data structure contains null>
1417
** test more often than is necessary.
1419
#ifndef SQLITE_OMIT_SUBQUERY
1420
int sqlite3FindInIndex(Parse *pParse, Expr *pX, int *prNotFound){
1421
Select *p; /* SELECT to the right of IN operator */
1422
int eType = 0; /* Type of RHS table. IN_INDEX_* */
1423
int iTab = pParse->nTab++; /* Cursor of the RHS table */
1424
int mustBeUnique = (prNotFound==0); /* True if RHS must be unique */
1426
assert( pX->op==TK_IN );
1428
/* Check to see if an existing table or index can be used to
1429
** satisfy the query. This is preferable to generating a new
1432
p = (ExprHasProperty(pX, EP_xIsSelect) ? pX->x.pSelect : 0);
1433
if( ALWAYS(pParse->nErr==0) && isCandidateForInOpt(p) ){
1434
sqlite3 *db = pParse->db; /* Database connection */
1435
Expr *pExpr = p->pEList->a[0].pExpr; /* Expression <column> */
1436
int iCol = pExpr->iColumn; /* Index of column <column> */
1437
Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1438
Table *pTab = p->pSrc->a[0].pTab; /* Table <table>. */
1439
int iDb; /* Database idx for pTab */
1441
/* Code an OP_VerifyCookie and OP_TableLock for <table>. */
1442
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1443
sqlite3CodeVerifySchema(pParse, iDb);
1444
sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
1446
/* This function is only called from two places. In both cases the vdbe
1447
** has already been allocated. So assume sqlite3GetVdbe() is always
1452
int iMem = ++pParse->nMem;
1455
iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1456
sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1458
sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1459
eType = IN_INDEX_ROWID;
1461
sqlite3VdbeJumpHere(v, iAddr);
1463
Index *pIdx; /* Iterator variable */
1465
/* The collation sequence used by the comparison. If an index is to
1466
** be used in place of a temp-table, it must be ordered according
1467
** to this collation sequence. */
1468
CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1470
/* Check that the affinity that will be used to perform the
1471
** comparison is the same as the affinity of the column. If
1472
** it is not, it is not possible to use any index.
1474
char aff = comparisonAffinity(pX);
1475
int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
1477
for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1478
if( (pIdx->aiColumn[0]==iCol)
1479
&& sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
1480
&& (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
1482
int iMem = ++pParse->nMem;
1486
pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
1487
iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
1488
sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
1490
sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
1491
pKey,P4_KEYINFO_HANDOFF);
1492
VdbeComment((v, "%s", pIdx->zName));
1493
eType = IN_INDEX_INDEX;
1495
sqlite3VdbeJumpHere(v, iAddr);
1496
if( prNotFound && !pTab->aCol[iCol].notNull ){
1497
*prNotFound = ++pParse->nMem;
1505
/* Could not found an existing table or index to use as the RHS b-tree.
1506
** We will have to generate an ephemeral table to do the job.
1508
int rMayHaveNull = 0;
1509
eType = IN_INDEX_EPH;
1511
*prNotFound = rMayHaveNull = ++pParse->nMem;
1512
}else if( pX->pLeft->iColumn<0 && !ExprHasAnyProperty(pX, EP_xIsSelect) ){
1513
eType = IN_INDEX_ROWID;
1515
sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
1524
** Generate code for scalar subqueries used as an expression
1525
** and IN operators. Examples:
1527
** (SELECT a FROM b) -- subquery
1528
** EXISTS (SELECT a FROM b) -- EXISTS subquery
1529
** x IN (4,5,11) -- IN operator with list on right-hand side
1530
** x IN (SELECT a FROM b) -- IN operator with subquery on the right
1532
** The pExpr parameter describes the expression that contains the IN
1533
** operator or subquery.
1535
** If parameter isRowid is non-zero, then expression pExpr is guaranteed
1536
** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
1537
** to some integer key column of a table B-Tree. In this case, use an
1538
** intkey B-Tree to store the set of IN(...) values instead of the usual
1539
** (slower) variable length keys B-Tree.
1541
** If rMayHaveNull is non-zero, that means that the operation is an IN
1542
** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
1543
** Furthermore, the IN is in a WHERE clause and that we really want
1544
** to iterate over the RHS of the IN operator in order to quickly locate
1545
** all corresponding LHS elements. All this routine does is initialize
1546
** the register given by rMayHaveNull to NULL. Calling routines will take
1547
** care of changing this register value to non-NULL if the RHS is NULL-free.
1549
** If rMayHaveNull is zero, that means that the subquery is being used
1550
** for membership testing only. There is no need to initialize any
1551
** registers to indicate the presense or absence of NULLs on the RHS.
1553
** For a SELECT or EXISTS operator, return the register that holds the
1554
** result. For IN operators or if an error occurs, the return value is 0.
1556
#ifndef SQLITE_OMIT_SUBQUERY
1557
int sqlite3CodeSubselect(
1558
Parse *pParse, /* Parsing context */
1559
Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
1560
int rMayHaveNull, /* Register that records whether NULLs exist in RHS */
1561
int isRowid /* If true, LHS of IN operator is a rowid */
1563
int testAddr = 0; /* One-time test address */
1564
int rReg = 0; /* Register storing resulting */
1565
Vdbe *v = sqlite3GetVdbe(pParse);
1566
if( NEVER(v==0) ) return 0;
1567
sqlite3ExprCachePush(pParse);
1569
/* This code must be run in its entirety every time it is encountered
1570
** if any of the following is true:
1572
** * The right-hand side is a correlated subquery
1573
** * The right-hand side is an expression list containing variables
1574
** * We are inside a trigger
1576
** If all of the above are false, then we can run this code just once
1577
** save the results, and reuse the same result on subsequent invocations.
1579
if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->pTriggerTab ){
1580
int mem = ++pParse->nMem;
1581
sqlite3VdbeAddOp1(v, OP_If, mem);
1582
testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
1583
assert( testAddr>0 || pParse->db->mallocFailed );
1586
switch( pExpr->op ){
1590
int addr; /* Address of OP_OpenEphemeral instruction */
1591
Expr *pLeft = pExpr->pLeft;
1594
sqlite3VdbeAddOp2(v, OP_Null, 0, rMayHaveNull);
1597
affinity = sqlite3ExprAffinity(pLeft);
1599
/* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1600
** expression it is handled the same way. An ephemeral table is
1601
** filled with single-field index keys representing the results
1602
** from the SELECT or the <exprlist>.
1604
** If the 'x' expression is a column value, or the SELECT...
1605
** statement returns a column value, then the affinity of that
1606
** column is used to build the index keys. If both 'x' and the
1607
** SELECT... statement are columns, then numeric affinity is used
1608
** if either column has NUMERIC or INTEGER affinity. If neither
1609
** 'x' nor the SELECT... statement are columns, then numeric affinity
1612
pExpr->iTable = pParse->nTab++;
1613
addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
1614
memset(&keyInfo, 0, sizeof(keyInfo));
1617
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
1618
/* Case 1: expr IN (SELECT ...)
1620
** Generate code to write the results of the select into the temporary
1621
** table allocated and opened above.
1627
sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
1628
dest.affinity = (u8)affinity;
1629
assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1630
if( sqlite3Select(pParse, pExpr->x.pSelect, &dest) ){
1633
pEList = pExpr->x.pSelect->pEList;
1634
if( ALWAYS(pEList!=0 && pEList->nExpr>0) ){
1635
keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1636
pEList->a[0].pExpr);
1638
}else if( pExpr->x.pList!=0 ){
1639
/* Case 2: expr IN (exprlist)
1641
** For each expression, build an index key from the evaluation and
1642
** store it in the temporary table. If <expr> is a column, then use
1643
** that columns affinity when building index keys. If <expr> is not
1644
** a column, use numeric affinity.
1647
ExprList *pList = pExpr->x.pList;
1648
struct ExprList_item *pItem;
1652
affinity = SQLITE_AFF_NONE;
1654
keyInfo.aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
1656
/* Loop through each expression in <exprlist>. */
1657
r1 = sqlite3GetTempReg(pParse);
1658
r2 = sqlite3GetTempReg(pParse);
1659
sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
1660
for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1661
Expr *pE2 = pItem->pExpr;
1664
/* If the expression is not constant then we will need to
1665
** disable the test that was generated above that makes sure
1666
** this code only executes once. Because for a non-constant
1667
** expression we need to rerun this code each time.
1669
if( testAddr && !sqlite3ExprIsConstant(pE2) ){
1670
sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
1674
/* Evaluate the expression and insert it into the temp table */
1675
if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
1676
sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
1678
r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
1680
sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
1681
sqlite3VdbeCurrentAddr(v)+2);
1682
sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
1684
sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
1685
sqlite3ExprCacheAffinityChange(pParse, r3, 1);
1686
sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
1690
sqlite3ReleaseTempReg(pParse, r1);
1691
sqlite3ReleaseTempReg(pParse, r2);
1694
sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
1702
/* If this has to be a scalar SELECT. Generate code to put the
1703
** value of this select in a memory cell and record the number
1704
** of the memory cell in iColumn. If this is an EXISTS, write
1705
** an integer 0 (not exists) or 1 (exists) into a memory cell
1706
** and record that memory cell in iColumn.
1708
static const Token one = { "1", 1 }; /* Token for literal value 1 */
1709
Select *pSel; /* SELECT statement to encode */
1710
SelectDest dest; /* How to deal with SELECt result */
1712
testcase( pExpr->op==TK_EXISTS );
1713
testcase( pExpr->op==TK_SELECT );
1714
assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
1716
assert( ExprHasProperty(pExpr, EP_xIsSelect) );
1717
pSel = pExpr->x.pSelect;
1718
sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
1719
if( pExpr->op==TK_SELECT ){
1720
dest.eDest = SRT_Mem;
1721
sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
1722
VdbeComment((v, "Init subquery result"));
1724
dest.eDest = SRT_Exists;
1725
sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
1726
VdbeComment((v, "Init EXISTS result"));
1728
sqlite3ExprDelete(pParse->db, pSel->pLimit);
1729
pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
1730
if( sqlite3Select(pParse, pSel, &dest) ){
1734
ExprSetIrreducible(pExpr);
1740
sqlite3VdbeJumpHere(v, testAddr-1);
1742
sqlite3ExprCachePop(pParse, 1);
1746
#endif /* SQLITE_OMIT_SUBQUERY */
1748
#ifndef SQLITE_OMIT_SUBQUERY
1750
** Generate code for an IN expression.
1752
** x IN (SELECT ...)
1753
** x IN (value, value, ...)
1755
** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
1756
** is an array of zero or more values. The expression is true if the LHS is
1757
** contained within the RHS. The value of the expression is unknown (NULL)
1758
** if the LHS is NULL or if the LHS is not contained within the RHS and the
1759
** RHS contains one or more NULL values.
1761
** This routine generates code will jump to destIfFalse if the LHS is not
1762
** contained within the RHS. If due to NULLs we cannot determine if the LHS
1763
** is contained in the RHS then jump to destIfNull. If the LHS is contained
1764
** within the RHS then fall through.
1766
static void sqlite3ExprCodeIN(
1767
Parse *pParse, /* Parsing and code generating context */
1768
Expr *pExpr, /* The IN expression */
1769
int destIfFalse, /* Jump here if LHS is not contained in the RHS */
1770
int destIfNull /* Jump here if the results are unknown due to NULLs */
1772
int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
1773
char affinity; /* Comparison affinity to use */
1774
int eType; /* Type of the RHS */
1775
int r1; /* Temporary use register */
1776
Vdbe *v; /* Statement under construction */
1778
/* Compute the RHS. After this step, the table with cursor
1779
** pExpr->iTable will contains the values that make up the RHS.
1782
assert( v!=0 ); /* OOM detected prior to this routine */
1783
VdbeNoopComment((v, "begin IN expr"));
1784
eType = sqlite3FindInIndex(pParse, pExpr, &rRhsHasNull);
1786
/* Figure out the affinity to use to create a key from the results
1787
** of the expression. affinityStr stores a static string suitable for
1788
** P4 of OP_MakeRecord.
1790
affinity = comparisonAffinity(pExpr);
1792
/* Code the LHS, the <expr> from "<expr> IN (...)".
1794
sqlite3ExprCachePush(pParse);
1795
r1 = sqlite3GetTempReg(pParse);
1796
sqlite3ExprCode(pParse, pExpr->pLeft, r1);
1797
sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull);
1800
if( eType==IN_INDEX_ROWID ){
1801
/* In this case, the RHS is the ROWID of table b-tree
1803
sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse);
1804
sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
1806
/* In this case, the RHS is an index b-tree.
1808
sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
1810
/* If the set membership test fails, then the result of the
1811
** "x IN (...)" expression must be either 0 or NULL. If the set
1812
** contains no NULL values, then the result is 0. If the set
1813
** contains one or more NULL values, then the result of the
1814
** expression is also NULL.
1816
if( rRhsHasNull==0 || destIfFalse==destIfNull ){
1817
/* This branch runs if it is known at compile time that the RHS
1818
** cannot contain NULL values. This happens as the result
1819
** of a "NOT NULL" constraint in the database schema.
1821
** Also run this branch if NULL is equivalent to FALSE
1822
** for this particular IN operator.
1824
sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
1827
/* In this branch, the RHS of the IN might contain a NULL and
1828
** the presence of a NULL on the RHS makes a difference in the
1833
/* First check to see if the LHS is contained in the RHS. If so,
1834
** then the presence of NULLs in the RHS does not matter, so jump
1835
** over all of the code that follows.
1837
j1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
1839
/* Here we begin generating code that runs if the LHS is not
1840
** contained within the RHS. Generate additional code that
1841
** tests the RHS for NULLs. If the RHS contains a NULL then
1842
** jump to destIfNull. If there are no NULLs in the RHS then
1843
** jump to destIfFalse.
1845
j2 = sqlite3VdbeAddOp1(v, OP_NotNull, rRhsHasNull);
1846
j3 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, rRhsHasNull, 1);
1847
sqlite3VdbeAddOp2(v, OP_Integer, -1, rRhsHasNull);
1848
sqlite3VdbeJumpHere(v, j3);
1849
sqlite3VdbeAddOp2(v, OP_AddImm, rRhsHasNull, 1);
1850
sqlite3VdbeJumpHere(v, j2);
1852
/* Jump to the appropriate target depending on whether or not
1853
** the RHS contains a NULL
1855
sqlite3VdbeAddOp2(v, OP_If, rRhsHasNull, destIfNull);
1856
sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
1858
/* The OP_Found at the top of this branch jumps here when true,
1859
** causing the overall IN expression evaluation to fall through.
1861
sqlite3VdbeJumpHere(v, j1);
1864
sqlite3ReleaseTempReg(pParse, r1);
1865
sqlite3ExprCachePop(pParse, 1);
1866
VdbeComment((v, "end IN expr"));
1868
#endif /* SQLITE_OMIT_SUBQUERY */
1871
** Duplicate an 8-byte value
1873
static char *dup8bytes(Vdbe *v, const char *in){
1874
char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1881
#ifndef SQLITE_OMIT_FLOATING_POINT
1883
** Generate an instruction that will put the floating point
1884
** value described by z[0..n-1] into register iMem.
1886
** The z[] string will probably not be zero-terminated. But the
1887
** z[n] character is guaranteed to be something that does not look
1888
** like the continuation of the number.
1890
static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
1894
sqlite3AtoF(z, &value);
1895
assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
1896
if( negateFlag ) value = -value;
1897
zV = dup8bytes(v, (char*)&value);
1898
sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
1905
** Generate an instruction that will put the integer describe by
1906
** text z[0..n-1] into register iMem.
1908
** The z[] string will probably not be zero-terminated. But the
1909
** z[n] character is guaranteed to be something that does not look
1910
** like the continuation of the number.
1912
static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
1913
Vdbe *v = pParse->pVdbe;
1914
if( pExpr->flags & EP_IntValue ){
1915
int i = pExpr->u.iValue;
1916
if( negFlag ) i = -i;
1917
sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1919
const char *z = pExpr->u.zToken;
1921
if( sqlite3FitsIn64Bits(z, negFlag) ){
1924
sqlite3Atoi64(z, &value);
1925
if( negFlag ) value = -value;
1926
zV = dup8bytes(v, (char*)&value);
1927
sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
1929
#ifdef SQLITE_OMIT_FLOATING_POINT
1930
sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
1932
codeReal(v, z, negFlag, iMem);
1939
** Clear a cache entry.
1941
static void cacheEntryClear(Parse *pParse, struct yColCache *p){
1943
if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
1944
pParse->aTempReg[pParse->nTempReg++] = p->iReg;
1952
** Record in the column cache that a particular column from a
1953
** particular table is stored in a particular register.
1955
void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
1959
struct yColCache *p;
1961
assert( iReg>0 ); /* Register numbers are always positive */
1962
assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
1964
/* The SQLITE_ColumnCache flag disables the column cache. This is used
1965
** for testing only - to verify that SQLite always gets the same answer
1966
** with and without the column cache.
1968
if( pParse->db->flags & SQLITE_ColumnCache ) return;
1970
/* First replace any existing entry.
1972
** Actually, the way the column cache is currently used, we are guaranteed
1973
** that the object will never already be in cache. Verify this guarantee.
1976
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1977
#if 0 /* This code wold remove the entry from the cache if it existed */
1978
if( p->iReg && p->iTable==iTab && p->iColumn==iCol ){
1979
cacheEntryClear(pParse, p);
1980
p->iLevel = pParse->iCacheLevel;
1982
p->lru = pParse->iCacheCnt++;
1986
assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
1990
/* Find an empty slot and replace it */
1991
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
1993
p->iLevel = pParse->iCacheLevel;
1998
p->lru = pParse->iCacheCnt++;
2003
/* Replace the last recently used */
2004
minLru = 0x7fffffff;
2006
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2007
if( p->lru<minLru ){
2012
if( ALWAYS(idxLru>=0) ){
2013
p = &pParse->aColCache[idxLru];
2014
p->iLevel = pParse->iCacheLevel;
2019
p->lru = pParse->iCacheCnt++;
2025
** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2026
** Purge the range of registers from the column cache.
2028
void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
2030
int iLast = iReg + nReg - 1;
2031
struct yColCache *p;
2032
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2034
if( r>=iReg && r<=iLast ){
2035
cacheEntryClear(pParse, p);
2042
** Remember the current column cache context. Any new entries added
2043
** added to the column cache after this call are removed when the
2044
** corresponding pop occurs.
2046
void sqlite3ExprCachePush(Parse *pParse){
2047
pParse->iCacheLevel++;
2051
** Remove from the column cache any entries that were added since the
2052
** the previous N Push operations. In other words, restore the cache
2053
** to the state it was in N Pushes ago.
2055
void sqlite3ExprCachePop(Parse *pParse, int N){
2057
struct yColCache *p;
2059
assert( pParse->iCacheLevel>=N );
2060
pParse->iCacheLevel -= N;
2061
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2062
if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2063
cacheEntryClear(pParse, p);
2070
** When a cached column is reused, make sure that its register is
2071
** no longer available as a temp register. ticket #3879: that same
2072
** register might be in the cache in multiple places, so be sure to
2075
static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
2077
struct yColCache *p;
2078
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2079
if( p->iReg==iReg ){
2086
** Generate code that will extract the iColumn-th column from
2087
** table pTab and store the column value in a register. An effort
2088
** is made to store the column value in register iReg, but this is
2089
** not guaranteed. The location of the column value is returned.
2091
** There must be an open cursor to pTab in iTable when this routine
2092
** is called. If iColumn<0 then code is generated that extracts the rowid.
2094
int sqlite3ExprCodeGetColumn(
2095
Parse *pParse, /* Parsing and code generating context */
2096
Table *pTab, /* Description of the table we are reading from */
2097
int iColumn, /* Index of the table column */
2098
int iTable, /* The cursor pointing to the table */
2099
int iReg /* Store results here */
2101
Vdbe *v = pParse->pVdbe;
2103
struct yColCache *p;
2105
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2106
if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
2107
p->lru = pParse->iCacheCnt++;
2108
sqlite3ExprCachePinRegister(pParse, p->iReg);
2114
sqlite3VdbeAddOp2(v, OP_Rowid, iTable, iReg);
2115
}else if( ALWAYS(pTab!=0) ){
2116
int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
2117
sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
2118
sqlite3ColumnDefault(v, pTab, iColumn, iReg);
2120
sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2125
** Clear all column cache entries.
2127
void sqlite3ExprCacheClear(Parse *pParse){
2129
struct yColCache *p;
2131
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2133
cacheEntryClear(pParse, p);
2140
** Record the fact that an affinity change has occurred on iCount
2141
** registers starting with iStart.
2143
void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2144
sqlite3ExprCacheRemove(pParse, iStart, iCount);
2148
** Generate code to move content from registers iFrom...iFrom+nReg-1
2149
** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
2151
void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
2153
struct yColCache *p;
2154
if( NEVER(iFrom==iTo) ) return;
2155
sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
2156
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2158
if( x>=iFrom && x<iFrom+nReg ){
2159
p->iReg += iTo-iFrom;
2165
** Generate code to copy content from registers iFrom...iFrom+nReg-1
2166
** over to iTo..iTo+nReg-1.
2168
void sqlite3ExprCodeCopy(Parse *pParse, int iFrom, int iTo, int nReg){
2170
if( NEVER(iFrom==iTo) ) return;
2171
for(i=0; i<nReg; i++){
2172
sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, iFrom+i, iTo+i);
2176
#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
2178
** Return true if any register in the range iFrom..iTo (inclusive)
2179
** is used as part of the column cache.
2181
** This routine is used within assert() and testcase() macros only
2182
** and does not appear in a normal build.
2184
static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2186
struct yColCache *p;
2187
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2189
if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
2193
#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
2196
** If the last instruction coded is an ephemeral copy of any of
2197
** the registers in the nReg registers beginning with iReg, then
2198
** convert the last instruction from OP_SCopy to OP_Copy.
2200
void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
2204
assert( pParse->db->mallocFailed==0 );
2207
pOp = sqlite3VdbeGetOp(v, -1);
2209
if( pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
2210
pOp->opcode = OP_Copy;
2215
** Generate code to store the value of the iAlias-th alias in register
2216
** target. The first time this is called, pExpr is evaluated to compute
2217
** the value of the alias. The value is stored in an auxiliary register
2218
** and the number of that register is returned. On subsequent calls,
2219
** the register number is returned without generating any code.
2221
** Note that in order for this to work, code must be generated in the
2222
** same order that it is executed.
2224
** Aliases are numbered starting with 1. So iAlias is in the range
2225
** of 1 to pParse->nAlias inclusive.
2227
** pParse->aAlias[iAlias-1] records the register number where the value
2228
** of the iAlias-th alias is stored. If zero, that means that the
2229
** alias has not yet been computed.
2231
static int codeAlias(Parse *pParse, int iAlias, Expr *pExpr, int target){
2233
sqlite3 *db = pParse->db;
2235
if( pParse->nAliasAlloc<pParse->nAlias ){
2236
pParse->aAlias = sqlite3DbReallocOrFree(db, pParse->aAlias,
2237
sizeof(pParse->aAlias[0])*pParse->nAlias );
2238
testcase( db->mallocFailed && pParse->nAliasAlloc>0 );
2239
if( db->mallocFailed ) return 0;
2240
memset(&pParse->aAlias[pParse->nAliasAlloc], 0,
2241
(pParse->nAlias-pParse->nAliasAlloc)*sizeof(pParse->aAlias[0]));
2242
pParse->nAliasAlloc = pParse->nAlias;
2244
assert( iAlias>0 && iAlias<=pParse->nAlias );
2245
iReg = pParse->aAlias[iAlias-1];
2247
if( pParse->iCacheLevel>0 ){
2248
iReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2250
iReg = ++pParse->nMem;
2251
sqlite3ExprCode(pParse, pExpr, iReg);
2252
pParse->aAlias[iAlias-1] = iReg;
2257
UNUSED_PARAMETER(iAlias);
2258
return sqlite3ExprCodeTarget(pParse, pExpr, target);
2263
** Generate code into the current Vdbe to evaluate the given
2264
** expression. Attempt to store the results in register "target".
2265
** Return the register where results are stored.
2267
** With this routine, there is no guarantee that results will
2268
** be stored in target. The result might be stored in some other
2269
** register if it is convenient to do so. The calling function
2270
** must check the return code and move the results to the desired
2273
int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
2274
Vdbe *v = pParse->pVdbe; /* The VM under construction */
2275
int op; /* The opcode being coded */
2276
int inReg = target; /* Results stored in register inReg */
2277
int regFree1 = 0; /* If non-zero free this temporary register */
2278
int regFree2 = 0; /* If non-zero free this temporary register */
2279
int r1, r2, r3, r4; /* Various register numbers */
2280
sqlite3 *db = pParse->db; /* The database connection */
2282
assert( target>0 && target<=pParse->nMem );
2284
assert( pParse->db->mallocFailed );
2294
case TK_AGG_COLUMN: {
2295
AggInfo *pAggInfo = pExpr->pAggInfo;
2296
struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
2297
if( !pAggInfo->directMode ){
2298
assert( pCol->iMem>0 );
2301
}else if( pAggInfo->useSortingIdx ){
2302
sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
2303
pCol->iSorterColumn, target);
2306
/* Otherwise, fall thru into the TK_COLUMN case */
2309
if( pExpr->iTable<0 ){
2310
/* This only happens when coding check constraints */
2311
assert( pParse->ckBase>0 );
2312
inReg = pExpr->iColumn + pParse->ckBase;
2314
inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2315
pExpr->iColumn, pExpr->iTable, target);
2320
codeInteger(pParse, pExpr, 0, target);
2323
#ifndef SQLITE_OMIT_FLOATING_POINT
2325
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2326
codeReal(v, pExpr->u.zToken, 0, target);
2331
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2332
sqlite3VdbeAddOp4(v, OP_String8, 0, target, 0, pExpr->u.zToken, 0);
2336
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2339
#ifndef SQLITE_OMIT_BLOB_LITERAL
2344
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2345
assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
2346
assert( pExpr->u.zToken[1]=='\'' );
2347
z = &pExpr->u.zToken[2];
2348
n = sqlite3Strlen30(z) - 1;
2349
assert( z[n]=='\'' );
2350
zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2351
sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
2357
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2358
assert( pExpr->u.zToken!=0 );
2359
assert( pExpr->u.zToken[0]!=0 );
2360
if( pExpr->u.zToken[1]==0
2361
&& (pOp = sqlite3VdbeGetOp(v, -1))->opcode==OP_Variable
2362
&& pOp->p1+pOp->p3==pExpr->iColumn
2363
&& pOp->p2+pOp->p3==target
2366
/* If the previous instruction was a copy of the previous unnamed
2367
** parameter into the previous register, then simply increment the
2368
** repeat count on the prior instruction rather than making a new
2373
sqlite3VdbeAddOp3(v, OP_Variable, pExpr->iColumn, target, 1);
2374
if( pExpr->u.zToken[1]!=0 ){
2375
sqlite3VdbeChangeP4(v, -1, pExpr->u.zToken, 0);
2381
inReg = pExpr->iTable;
2385
inReg = codeAlias(pParse, pExpr->iTable, pExpr->pLeft, target);
2388
#ifndef SQLITE_OMIT_CAST
2390
/* Expressions of the form: CAST(pLeft AS token) */
2392
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2393
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2394
aff = sqlite3AffinityType(pExpr->u.zToken);
2395
to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2396
assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
2397
assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
2398
assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2399
assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
2400
assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
2401
testcase( to_op==OP_ToText );
2402
testcase( to_op==OP_ToBlob );
2403
testcase( to_op==OP_ToNumeric );
2404
testcase( to_op==OP_ToInt );
2405
testcase( to_op==OP_ToReal );
2406
if( inReg!=target ){
2407
sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
2410
sqlite3VdbeAddOp1(v, to_op, inReg);
2411
testcase( usedAsColumnCache(pParse, inReg, inReg) );
2412
sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
2415
#endif /* SQLITE_OMIT_CAST */
2422
assert( TK_LT==OP_Lt );
2423
assert( TK_LE==OP_Le );
2424
assert( TK_GT==OP_Gt );
2425
assert( TK_GE==OP_Ge );
2426
assert( TK_EQ==OP_Eq );
2427
assert( TK_NE==OP_Ne );
2428
testcase( op==TK_LT );
2429
testcase( op==TK_LE );
2430
testcase( op==TK_GT );
2431
testcase( op==TK_GE );
2432
testcase( op==TK_EQ );
2433
testcase( op==TK_NE );
2434
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
2435
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
2436
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2437
r1, r2, inReg, SQLITE_STOREP2);
2438
testcase( regFree1==0 );
2439
testcase( regFree2==0 );
2444
testcase( op==TK_IS );
2445
testcase( op==TK_ISNOT );
2446
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
2447
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
2448
op = (op==TK_IS) ? TK_EQ : TK_NE;
2449
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2450
r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
2451
testcase( regFree1==0 );
2452
testcase( regFree2==0 );
2467
assert( TK_AND==OP_And );
2468
assert( TK_OR==OP_Or );
2469
assert( TK_PLUS==OP_Add );
2470
assert( TK_MINUS==OP_Subtract );
2471
assert( TK_REM==OP_Remainder );
2472
assert( TK_BITAND==OP_BitAnd );
2473
assert( TK_BITOR==OP_BitOr );
2474
assert( TK_SLASH==OP_Divide );
2475
assert( TK_LSHIFT==OP_ShiftLeft );
2476
assert( TK_RSHIFT==OP_ShiftRight );
2477
assert( TK_CONCAT==OP_Concat );
2478
testcase( op==TK_AND );
2479
testcase( op==TK_OR );
2480
testcase( op==TK_PLUS );
2481
testcase( op==TK_MINUS );
2482
testcase( op==TK_REM );
2483
testcase( op==TK_BITAND );
2484
testcase( op==TK_BITOR );
2485
testcase( op==TK_SLASH );
2486
testcase( op==TK_LSHIFT );
2487
testcase( op==TK_RSHIFT );
2488
testcase( op==TK_CONCAT );
2489
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
2490
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
2491
sqlite3VdbeAddOp3(v, op, r2, r1, target);
2492
testcase( regFree1==0 );
2493
testcase( regFree2==0 );
2497
Expr *pLeft = pExpr->pLeft;
2499
if( pLeft->op==TK_INTEGER ){
2500
codeInteger(pParse, pLeft, 1, target);
2501
#ifndef SQLITE_OMIT_FLOATING_POINT
2502
}else if( pLeft->op==TK_FLOAT ){
2503
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2504
codeReal(v, pLeft->u.zToken, 1, target);
2507
regFree1 = r1 = sqlite3GetTempReg(pParse);
2508
sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
2509
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free2);
2510
sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
2511
testcase( regFree2==0 );
2518
assert( TK_BITNOT==OP_BitNot );
2519
assert( TK_NOT==OP_Not );
2520
testcase( op==TK_BITNOT );
2521
testcase( op==TK_NOT );
2522
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
2523
testcase( regFree1==0 );
2525
sqlite3VdbeAddOp2(v, op, r1, inReg);
2531
assert( TK_ISNULL==OP_IsNull );
2532
assert( TK_NOTNULL==OP_NotNull );
2533
testcase( op==TK_ISNULL );
2534
testcase( op==TK_NOTNULL );
2535
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2536
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
2537
testcase( regFree1==0 );
2538
addr = sqlite3VdbeAddOp1(v, op, r1);
2539
sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
2540
sqlite3VdbeJumpHere(v, addr);
2543
case TK_AGG_FUNCTION: {
2544
AggInfo *pInfo = pExpr->pAggInfo;
2546
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2547
sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
2549
inReg = pInfo->aFunc[pExpr->iAgg].iMem;
2555
ExprList *pFarg; /* List of function arguments */
2556
int nFarg; /* Number of function arguments */
2557
FuncDef *pDef; /* The function definition object */
2558
int nId; /* Length of the function name in bytes */
2559
const char *zId; /* The function name */
2560
int constMask = 0; /* Mask of function arguments that are constant */
2561
int i; /* Loop counter */
2562
u8 enc = ENC(db); /* The text encoding used by this database */
2563
CollSeq *pColl = 0; /* A collating sequence */
2565
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
2566
testcase( op==TK_CONST_FUNC );
2567
testcase( op==TK_FUNCTION );
2568
if( ExprHasAnyProperty(pExpr, EP_TokenOnly) ){
2571
pFarg = pExpr->x.pList;
2573
nFarg = pFarg ? pFarg->nExpr : 0;
2574
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2575
zId = pExpr->u.zToken;
2576
nId = sqlite3Strlen30(zId);
2577
pDef = sqlite3FindFunction(db, zId, nId, nFarg, enc, 0);
2579
sqlite3ErrorMsg(pParse, "unknown function: %.*s()", nId, zId);
2583
/* Attempt a direct implementation of the built-in COALESCE() and
2584
** IFNULL() functions. This avoids unnecessary evalation of
2585
** arguments past the first non-NULL argument.
2587
if( pDef->flags & SQLITE_FUNC_COALESCE ){
2588
int endCoalesce = sqlite3VdbeMakeLabel(v);
2590
sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2591
for(i=1; i<nFarg; i++){
2592
sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
2593
sqlite3ExprCacheRemove(pParse, target, 1);
2594
sqlite3ExprCachePush(pParse);
2595
sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
2596
sqlite3ExprCachePop(pParse, 1);
2598
sqlite3VdbeResolveLabel(v, endCoalesce);
2604
r1 = sqlite3GetTempRange(pParse, nFarg);
2605
sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
2606
sqlite3ExprCodeExprList(pParse, pFarg, r1, 1);
2607
sqlite3ExprCachePop(pParse, 1); /* Ticket 2ea2425d34be */
2611
#ifndef SQLITE_OMIT_VIRTUALTABLE
2612
/* Possibly overload the function if the first argument is
2613
** a virtual table column.
2615
** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2616
** second argument, not the first, as the argument to test to
2617
** see if it is a column in a virtual table. This is done because
2618
** the left operand of infix functions (the operand we want to
2619
** control overloading) ends up as the second argument to the
2620
** function. The expression "A glob B" is equivalent to
2621
** "glob(B,A). We want to use the A in "A glob B" to test
2622
** for function overloading. But we use the B term in "glob(B,A)".
2624
if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
2625
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
2626
}else if( nFarg>0 ){
2627
pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
2630
for(i=0; i<nFarg; i++){
2631
if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
2632
constMask |= (1<<i);
2634
if( (pDef->flags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2635
pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2638
if( pDef->flags & SQLITE_FUNC_NEEDCOLL ){
2639
if( !pColl ) pColl = db->pDfltColl;
2640
sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
2642
sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
2643
(char*)pDef, P4_FUNCDEF);
2644
sqlite3VdbeChangeP5(v, (u8)nFarg);
2646
sqlite3ReleaseTempRange(pParse, r1, nFarg);
2650
#ifndef SQLITE_OMIT_SUBQUERY
2653
testcase( op==TK_EXISTS );
2654
testcase( op==TK_SELECT );
2655
inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
2659
int destIfFalse = sqlite3VdbeMakeLabel(v);
2660
int destIfNull = sqlite3VdbeMakeLabel(v);
2661
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2662
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
2663
sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
2664
sqlite3VdbeResolveLabel(v, destIfFalse);
2665
sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
2666
sqlite3VdbeResolveLabel(v, destIfNull);
2669
#endif /* SQLITE_OMIT_SUBQUERY */
2673
** x BETWEEN y AND z
2675
** This is equivalent to
2679
** X is stored in pExpr->pLeft.
2680
** Y is stored in pExpr->pList->a[0].pExpr.
2681
** Z is stored in pExpr->pList->a[1].pExpr.
2684
Expr *pLeft = pExpr->pLeft;
2685
struct ExprList_item *pLItem = pExpr->x.pList->a;
2686
Expr *pRight = pLItem->pExpr;
2688
r1 = sqlite3ExprCodeTemp(pParse, pLeft, ®Free1);
2689
r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2);
2690
testcase( regFree1==0 );
2691
testcase( regFree2==0 );
2692
r3 = sqlite3GetTempReg(pParse);
2693
r4 = sqlite3GetTempReg(pParse);
2694
codeCompare(pParse, pLeft, pRight, OP_Ge,
2695
r1, r2, r3, SQLITE_STOREP2);
2697
pRight = pLItem->pExpr;
2698
sqlite3ReleaseTempReg(pParse, regFree2);
2699
r2 = sqlite3ExprCodeTemp(pParse, pRight, ®Free2);
2700
testcase( regFree2==0 );
2701
codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2702
sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
2703
sqlite3ReleaseTempReg(pParse, r3);
2704
sqlite3ReleaseTempReg(pParse, r4);
2708
inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
2713
/* If the opcode is TK_TRIGGER, then the expression is a reference
2714
** to a column in the new.* or old.* pseudo-tables available to
2715
** trigger programs. In this case Expr.iTable is set to 1 for the
2716
** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
2717
** is set to the column of the pseudo-table to read, or to -1 to
2718
** read the rowid field.
2720
** The expression is implemented using an OP_Param opcode. The p1
2721
** parameter is set to 0 for an old.rowid reference, or to (i+1)
2722
** to reference another column of the old.* pseudo-table, where
2723
** i is the index of the column. For a new.rowid reference, p1 is
2724
** set to (n+1), where n is the number of columns in each pseudo-table.
2725
** For a reference to any other column in the new.* pseudo-table, p1
2726
** is set to (n+2+i), where n and i are as defined previously. For
2727
** example, if the table on which triggers are being fired is
2730
** CREATE TABLE t1(a, b);
2732
** Then p1 is interpreted as follows:
2734
** p1==0 -> old.rowid p1==3 -> new.rowid
2735
** p1==1 -> old.a p1==4 -> new.a
2736
** p1==2 -> old.b p1==5 -> new.b
2738
Table *pTab = pExpr->pTab;
2739
int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
2741
assert( pExpr->iTable==0 || pExpr->iTable==1 );
2742
assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
2743
assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
2744
assert( p1>=0 && p1<(pTab->nCol*2+2) );
2746
sqlite3VdbeAddOp2(v, OP_Param, p1, target);
2747
VdbeComment((v, "%s.%s -> $%d",
2748
(pExpr->iTable ? "new" : "old"),
2749
(pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
2753
#ifndef SQLITE_OMIT_FLOATING_POINT
2754
/* If the column has REAL affinity, it may currently be stored as an
2755
** integer. Use OP_RealAffinity to make sure it is really real. */
2756
if( pExpr->iColumn>=0
2757
&& pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
2759
sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
2768
** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2771
** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2773
** Form A is can be transformed into the equivalent form B as follows:
2774
** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
2775
** WHEN x=eN THEN rN ELSE y END
2777
** X (if it exists) is in pExpr->pLeft.
2778
** Y is in pExpr->pRight. The Y is also optional. If there is no
2779
** ELSE clause and no other term matches, then the result of the
2780
** exprssion is NULL.
2781
** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
2783
** The result of the expression is the Ri for the first matching Ei,
2784
** or if there is no matching Ei, the ELSE term Y, or if there is
2785
** no ELSE term, NULL.
2787
default: assert( op==TK_CASE ); {
2788
int endLabel; /* GOTO label for end of CASE stmt */
2789
int nextCase; /* GOTO label for next WHEN clause */
2790
int nExpr; /* 2x number of WHEN terms */
2791
int i; /* Loop counter */
2792
ExprList *pEList; /* List of WHEN terms */
2793
struct ExprList_item *aListelem; /* Array of WHEN terms */
2794
Expr opCompare; /* The X==Ei expression */
2795
Expr cacheX; /* Cached expression X */
2796
Expr *pX; /* The X expression */
2797
Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
2798
VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
2800
assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
2801
assert((pExpr->x.pList->nExpr % 2) == 0);
2802
assert(pExpr->x.pList->nExpr > 0);
2803
pEList = pExpr->x.pList;
2804
aListelem = pEList->a;
2805
nExpr = pEList->nExpr;
2806
endLabel = sqlite3VdbeMakeLabel(v);
2807
if( (pX = pExpr->pLeft)!=0 ){
2809
testcase( pX->op==TK_COLUMN );
2810
testcase( pX->op==TK_REGISTER );
2811
cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, ®Free1);
2812
testcase( regFree1==0 );
2813
cacheX.op = TK_REGISTER;
2814
opCompare.op = TK_EQ;
2815
opCompare.pLeft = &cacheX;
2818
for(i=0; i<nExpr; i=i+2){
2819
sqlite3ExprCachePush(pParse);
2822
opCompare.pRight = aListelem[i].pExpr;
2824
pTest = aListelem[i].pExpr;
2826
nextCase = sqlite3VdbeMakeLabel(v);
2827
testcase( pTest->op==TK_COLUMN );
2828
sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
2829
testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2830
testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
2831
sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
2832
sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
2833
sqlite3ExprCachePop(pParse, 1);
2834
sqlite3VdbeResolveLabel(v, nextCase);
2836
if( pExpr->pRight ){
2837
sqlite3ExprCachePush(pParse);
2838
sqlite3ExprCode(pParse, pExpr->pRight, target);
2839
sqlite3ExprCachePop(pParse, 1);
2841
sqlite3VdbeAddOp2(v, OP_Null, 0, target);
2843
assert( db->mallocFailed || pParse->nErr>0
2844
|| pParse->iCacheLevel==iCacheLevel );
2845
sqlite3VdbeResolveLabel(v, endLabel);
2848
#ifndef SQLITE_OMIT_TRIGGER
2850
assert( pExpr->affinity==OE_Rollback
2851
|| pExpr->affinity==OE_Abort
2852
|| pExpr->affinity==OE_Fail
2853
|| pExpr->affinity==OE_Ignore
2855
if( !pParse->pTriggerTab ){
2856
sqlite3ErrorMsg(pParse,
2857
"RAISE() may only be used within a trigger-program");
2860
if( pExpr->affinity==OE_Abort ){
2861
sqlite3MayAbort(pParse);
2863
assert( !ExprHasProperty(pExpr, EP_IntValue) );
2864
if( pExpr->affinity==OE_Ignore ){
2866
v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
2868
sqlite3HaltConstraint(pParse, pExpr->affinity, pExpr->u.zToken, 0);
2875
sqlite3ReleaseTempReg(pParse, regFree1);
2876
sqlite3ReleaseTempReg(pParse, regFree2);
2881
** Generate code to evaluate an expression and store the results
2882
** into a register. Return the register number where the results
2885
** If the register is a temporary register that can be deallocated,
2886
** then write its number into *pReg. If the result register is not
2887
** a temporary, then set *pReg to zero.
2889
int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
2890
int r1 = sqlite3GetTempReg(pParse);
2891
int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2895
sqlite3ReleaseTempReg(pParse, r1);
2902
** Generate code that will evaluate expression pExpr and store the
2903
** results in register target. The results are guaranteed to appear
2904
** in register target.
2906
int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
2909
assert( target>0 && target<=pParse->nMem );
2910
inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
2911
assert( pParse->pVdbe || pParse->db->mallocFailed );
2912
if( inReg!=target && pParse->pVdbe ){
2913
sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
2919
** Generate code that evalutes the given expression and puts the result
2920
** in register target.
2922
** Also make a copy of the expression results into another "cache" register
2923
** and modify the expression so that the next time it is evaluated,
2924
** the result is a copy of the cache register.
2926
** This routine is used for expressions that are used multiple
2927
** times. They are evaluated once and the results of the expression
2930
int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
2931
Vdbe *v = pParse->pVdbe;
2933
inReg = sqlite3ExprCode(pParse, pExpr, target);
2935
/* This routine is called for terms to INSERT or UPDATE. And the only
2936
** other place where expressions can be converted into TK_REGISTER is
2937
** in WHERE clause processing. So as currently implemented, there is
2938
** no way for a TK_REGISTER to exist here. But it seems prudent to
2939
** keep the ALWAYS() in case the conditions above change with future
2940
** modifications or enhancements. */
2941
if( ALWAYS(pExpr->op!=TK_REGISTER) ){
2943
iMem = ++pParse->nMem;
2944
sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
2945
pExpr->iTable = iMem;
2946
pExpr->op2 = pExpr->op;
2947
pExpr->op = TK_REGISTER;
2953
** Return TRUE if pExpr is an constant expression that is appropriate
2954
** for factoring out of a loop. Appropriate expressions are:
2956
** * Any expression that evaluates to two or more opcodes.
2958
** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
2959
** or OP_Variable that does not need to be placed in a
2960
** specific register.
2962
** There is no point in factoring out single-instruction constant
2963
** expressions that need to be placed in a particular register.
2964
** We could factor them out, but then we would end up adding an
2965
** OP_SCopy instruction to move the value into the correct register
2966
** later. We might as well just use the original instruction and
2967
** avoid the OP_SCopy.
2969
static int isAppropriateForFactoring(Expr *p){
2970
if( !sqlite3ExprIsConstantNotJoin(p) ){
2971
return 0; /* Only constant expressions are appropriate for factoring */
2973
if( (p->flags & EP_FixedDest)==0 ){
2974
return 1; /* Any constant without a fixed destination is appropriate */
2976
while( p->op==TK_UPLUS ) p = p->pLeft;
2978
#ifndef SQLITE_OMIT_BLOB_LITERAL
2986
testcase( p->op==TK_BLOB );
2987
testcase( p->op==TK_VARIABLE );
2988
testcase( p->op==TK_INTEGER );
2989
testcase( p->op==TK_FLOAT );
2990
testcase( p->op==TK_NULL );
2991
testcase( p->op==TK_STRING );
2992
/* Single-instruction constants with a fixed destination are
2993
** better done in-line. If we factor them, they will just end
2994
** up generating an OP_SCopy to move the value to the destination
2999
if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
3012
** If pExpr is a constant expression that is appropriate for
3013
** factoring out of a loop, then evaluate the expression
3014
** into a register and convert the expression into a TK_REGISTER
3017
static int evalConstExpr(Walker *pWalker, Expr *pExpr){
3018
Parse *pParse = pWalker->pParse;
3019
switch( pExpr->op ){
3025
case TK_AGG_FUNCTION:
3026
case TK_CONST_FUNC: {
3027
/* The arguments to a function have a fixed destination.
3028
** Mark them this way to avoid generated unneeded OP_SCopy
3031
ExprList *pList = pExpr->x.pList;
3032
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3034
int i = pList->nExpr;
3035
struct ExprList_item *pItem = pList->a;
3036
for(; i>0; i--, pItem++){
3037
if( ALWAYS(pItem->pExpr) ) pItem->pExpr->flags |= EP_FixedDest;
3043
if( isAppropriateForFactoring(pExpr) ){
3044
int r1 = ++pParse->nMem;
3046
r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3047
if( NEVER(r1!=r2) ) sqlite3ReleaseTempReg(pParse, r1);
3048
pExpr->op2 = pExpr->op;
3049
pExpr->op = TK_REGISTER;
3053
return WRC_Continue;
3057
** Preevaluate constant subexpressions within pExpr and store the
3058
** results in registers. Modify pExpr so that the constant subexpresions
3059
** are TK_REGISTER opcodes that refer to the precomputed values.
3061
void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
3063
w.xExprCallback = evalConstExpr;
3064
w.xSelectCallback = 0;
3066
sqlite3WalkExpr(&w, pExpr);
3071
** Generate code that pushes the value of every element of the given
3072
** expression list into a sequence of registers beginning at target.
3074
** Return the number of elements evaluated.
3076
int sqlite3ExprCodeExprList(
3077
Parse *pParse, /* Parsing context */
3078
ExprList *pList, /* The expression list to be coded */
3079
int target, /* Where to write results */
3080
int doHardCopy /* Make a hard copy of every element */
3082
struct ExprList_item *pItem;
3087
for(pItem=pList->a, i=0; i<n; i++, pItem++){
3088
if( pItem->iAlias ){
3089
int iReg = codeAlias(pParse, pItem->iAlias, pItem->pExpr, target+i);
3090
Vdbe *v = sqlite3GetVdbe(pParse);
3091
if( iReg!=target+i ){
3092
sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target+i);
3095
sqlite3ExprCode(pParse, pItem->pExpr, target+i);
3097
if( doHardCopy && !pParse->db->mallocFailed ){
3098
sqlite3ExprHardCopy(pParse, target, n);
3105
** Generate code for a BETWEEN operator.
3107
** x BETWEEN y AND z
3109
** The above is equivalent to
3113
** Code it as such, taking care to do the common subexpression
3114
** elementation of x.
3116
static void exprCodeBetween(
3117
Parse *pParse, /* Parsing and code generating context */
3118
Expr *pExpr, /* The BETWEEN expression */
3119
int dest, /* Jump here if the jump is taken */
3120
int jumpIfTrue, /* Take the jump if the BETWEEN is true */
3121
int jumpIfNull /* Take the jump if the BETWEEN is NULL */
3123
Expr exprAnd; /* The AND operator in x>=y AND x<=z */
3124
Expr compLeft; /* The x>=y term */
3125
Expr compRight; /* The x<=z term */
3126
Expr exprX; /* The x subexpression */
3127
int regFree1 = 0; /* Temporary use register */
3129
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3130
exprX = *pExpr->pLeft;
3131
exprAnd.op = TK_AND;
3132
exprAnd.pLeft = &compLeft;
3133
exprAnd.pRight = &compRight;
3134
compLeft.op = TK_GE;
3135
compLeft.pLeft = &exprX;
3136
compLeft.pRight = pExpr->x.pList->a[0].pExpr;
3137
compRight.op = TK_LE;
3138
compRight.pLeft = &exprX;
3139
compRight.pRight = pExpr->x.pList->a[1].pExpr;
3140
exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, ®Free1);
3141
exprX.op = TK_REGISTER;
3143
sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
3145
sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
3147
sqlite3ReleaseTempReg(pParse, regFree1);
3149
/* Ensure adequate test coverage */
3150
testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
3151
testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
3152
testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
3153
testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
3154
testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
3155
testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
3156
testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
3157
testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
3161
** Generate code for a boolean expression such that a jump is made
3162
** to the label "dest" if the expression is true but execution
3163
** continues straight thru if the expression is false.
3165
** If the expression evaluates to NULL (neither true nor false), then
3166
** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
3168
** This code depends on the fact that certain token values (ex: TK_EQ)
3169
** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3170
** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
3171
** the make process cause these values to align. Assert()s in the code
3172
** below verify that the numbers are aligned correctly.
3174
void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3175
Vdbe *v = pParse->pVdbe;
3181
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3182
if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
3183
if( NEVER(pExpr==0) ) return; /* No way this can happen */
3187
int d2 = sqlite3VdbeMakeLabel(v);
3188
testcase( jumpIfNull==0 );
3189
sqlite3ExprCachePush(pParse);
3190
sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
3191
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3192
sqlite3VdbeResolveLabel(v, d2);
3193
sqlite3ExprCachePop(pParse, 1);
3197
testcase( jumpIfNull==0 );
3198
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3199
sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3203
testcase( jumpIfNull==0 );
3204
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3213
assert( TK_LT==OP_Lt );
3214
assert( TK_LE==OP_Le );
3215
assert( TK_GT==OP_Gt );
3216
assert( TK_GE==OP_Ge );
3217
assert( TK_EQ==OP_Eq );
3218
assert( TK_NE==OP_Ne );
3219
testcase( op==TK_LT );
3220
testcase( op==TK_LE );
3221
testcase( op==TK_GT );
3222
testcase( op==TK_GE );
3223
testcase( op==TK_EQ );
3224
testcase( op==TK_NE );
3225
testcase( jumpIfNull==0 );
3226
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
3227
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
3228
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3229
r1, r2, dest, jumpIfNull);
3230
testcase( regFree1==0 );
3231
testcase( regFree2==0 );
3236
testcase( op==TK_IS );
3237
testcase( op==TK_ISNOT );
3238
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
3239
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
3240
op = (op==TK_IS) ? TK_EQ : TK_NE;
3241
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3242
r1, r2, dest, SQLITE_NULLEQ);
3243
testcase( regFree1==0 );
3244
testcase( regFree2==0 );
3249
assert( TK_ISNULL==OP_IsNull );
3250
assert( TK_NOTNULL==OP_NotNull );
3251
testcase( op==TK_ISNULL );
3252
testcase( op==TK_NOTNULL );
3253
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
3254
sqlite3VdbeAddOp2(v, op, r1, dest);
3255
testcase( regFree1==0 );
3259
testcase( jumpIfNull==0 );
3260
exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
3264
int destIfFalse = sqlite3VdbeMakeLabel(v);
3265
int destIfNull = jumpIfNull ? dest : destIfFalse;
3266
sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3267
sqlite3VdbeAddOp2(v, OP_Goto, 0, dest);
3268
sqlite3VdbeResolveLabel(v, destIfFalse);
3272
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
3273
sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
3274
testcase( regFree1==0 );
3275
testcase( jumpIfNull==0 );
3279
sqlite3ReleaseTempReg(pParse, regFree1);
3280
sqlite3ReleaseTempReg(pParse, regFree2);
3284
** Generate code for a boolean expression such that a jump is made
3285
** to the label "dest" if the expression is false but execution
3286
** continues straight thru if the expression is true.
3288
** If the expression evaluates to NULL (neither true nor false) then
3289
** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
3292
void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
3293
Vdbe *v = pParse->pVdbe;
3299
assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
3300
if( NEVER(v==0) ) return; /* Existance of VDBE checked by caller */
3301
if( pExpr==0 ) return;
3303
/* The value of pExpr->op and op are related as follows:
3306
** --------- ----------
3307
** TK_ISNULL OP_NotNull
3308
** TK_NOTNULL OP_IsNull
3316
** For other values of pExpr->op, op is undefined and unused.
3317
** The value of TK_ and OP_ constants are arranged such that we
3318
** can compute the mapping above using the following expression.
3319
** Assert()s verify that the computation is correct.
3321
op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3323
/* Verify correct alignment of TK_ and OP_ constants
3325
assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3326
assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3327
assert( pExpr->op!=TK_NE || op==OP_Eq );
3328
assert( pExpr->op!=TK_EQ || op==OP_Ne );
3329
assert( pExpr->op!=TK_LT || op==OP_Ge );
3330
assert( pExpr->op!=TK_LE || op==OP_Gt );
3331
assert( pExpr->op!=TK_GT || op==OP_Le );
3332
assert( pExpr->op!=TK_GE || op==OP_Lt );
3334
switch( pExpr->op ){
3336
testcase( jumpIfNull==0 );
3337
sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
3338
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3342
int d2 = sqlite3VdbeMakeLabel(v);
3343
testcase( jumpIfNull==0 );
3344
sqlite3ExprCachePush(pParse);
3345
sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
3346
sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3347
sqlite3VdbeResolveLabel(v, d2);
3348
sqlite3ExprCachePop(pParse, 1);
3352
testcase( jumpIfNull==0 );
3353
sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
3362
testcase( op==TK_LT );
3363
testcase( op==TK_LE );
3364
testcase( op==TK_GT );
3365
testcase( op==TK_GE );
3366
testcase( op==TK_EQ );
3367
testcase( op==TK_NE );
3368
testcase( jumpIfNull==0 );
3369
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
3370
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
3371
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3372
r1, r2, dest, jumpIfNull);
3373
testcase( regFree1==0 );
3374
testcase( regFree2==0 );
3379
testcase( pExpr->op==TK_IS );
3380
testcase( pExpr->op==TK_ISNOT );
3381
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
3382
r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, ®Free2);
3383
op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
3384
codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
3385
r1, r2, dest, SQLITE_NULLEQ);
3386
testcase( regFree1==0 );
3387
testcase( regFree2==0 );
3392
testcase( op==TK_ISNULL );
3393
testcase( op==TK_NOTNULL );
3394
r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, ®Free1);
3395
sqlite3VdbeAddOp2(v, op, r1, dest);
3396
testcase( regFree1==0 );
3400
testcase( jumpIfNull==0 );
3401
exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
3406
sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3408
int destIfNull = sqlite3VdbeMakeLabel(v);
3409
sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3410
sqlite3VdbeResolveLabel(v, destIfNull);
3415
r1 = sqlite3ExprCodeTemp(pParse, pExpr, ®Free1);
3416
sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
3417
testcase( regFree1==0 );
3418
testcase( jumpIfNull==0 );
3422
sqlite3ReleaseTempReg(pParse, regFree1);
3423
sqlite3ReleaseTempReg(pParse, regFree2);
3427
** Do a deep comparison of two expression trees. Return 0 if the two
3428
** expressions are completely identical. Return 1 if they differ only
3429
** by a COLLATE operator at the top level. Return 2 if there are differences
3430
** other than the top-level COLLATE operator.
3432
** Sometimes this routine will return 2 even if the two expressions
3433
** really are equivalent. If we cannot prove that the expressions are
3434
** identical, we return 2 just to be safe. So if this routine
3435
** returns 2, then you do not really know for certain if the two
3436
** expressions are the same. But if you get a 0 or 1 return, then you
3437
** can be sure the expressions are the same. In the places where
3438
** this routine is used, it does not hurt to get an extra 2 - that
3439
** just might result in some slightly slower code. But returning
3440
** an incorrect 0 or 1 could lead to a malfunction.
3442
int sqlite3ExprCompare(Expr *pA, Expr *pB){
3445
return pB==pA ? 0 : 2;
3447
assert( !ExprHasAnyProperty(pA, EP_TokenOnly|EP_Reduced) );
3448
assert( !ExprHasAnyProperty(pB, EP_TokenOnly|EP_Reduced) );
3449
if( ExprHasProperty(pA, EP_xIsSelect) || ExprHasProperty(pB, EP_xIsSelect) ){
3452
if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
3453
if( pA->op!=pB->op ) return 2;
3454
if( sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 2;
3455
if( sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 2;
3457
if( pA->x.pList && pB->x.pList ){
3458
if( pA->x.pList->nExpr!=pB->x.pList->nExpr ) return 2;
3459
for(i=0; i<pA->x.pList->nExpr; i++){
3460
Expr *pExprA = pA->x.pList->a[i].pExpr;
3461
Expr *pExprB = pB->x.pList->a[i].pExpr;
3462
if( sqlite3ExprCompare(pExprA, pExprB) ) return 2;
3464
}else if( pA->x.pList || pB->x.pList ){
3468
if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 2;
3469
if( ExprHasProperty(pA, EP_IntValue) ){
3470
if( !ExprHasProperty(pB, EP_IntValue) || pA->u.iValue!=pB->u.iValue ){
3473
}else if( pA->op!=TK_COLUMN && pA->u.zToken ){
3474
if( ExprHasProperty(pB, EP_IntValue) || NEVER(pB->u.zToken==0) ) return 2;
3475
if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ){
3479
if( (pA->flags & EP_ExpCollate)!=(pB->flags & EP_ExpCollate) ) return 1;
3480
if( (pA->flags & EP_ExpCollate)!=0 && pA->pColl!=pB->pColl ) return 2;
3486
** Add a new element to the pAggInfo->aCol[] array. Return the index of
3487
** the new element. Return a negative number if malloc fails.
3489
static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
3491
pInfo->aCol = sqlite3ArrayAllocate(
3494
sizeof(pInfo->aCol[0]),
3497
&pInfo->nColumnAlloc,
3504
** Add a new element to the pAggInfo->aFunc[] array. Return the index of
3505
** the new element. Return a negative number if malloc fails.
3507
static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
3509
pInfo->aFunc = sqlite3ArrayAllocate(
3512
sizeof(pInfo->aFunc[0]),
3522
** This is the xExprCallback for a tree walker. It is used to
3523
** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
3524
** for additional information.
3526
static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
3528
NameContext *pNC = pWalker->u.pNC;
3529
Parse *pParse = pNC->pParse;
3530
SrcList *pSrcList = pNC->pSrcList;
3531
AggInfo *pAggInfo = pNC->pAggInfo;
3533
switch( pExpr->op ){
3536
testcase( pExpr->op==TK_AGG_COLUMN );
3537
testcase( pExpr->op==TK_COLUMN );
3538
/* Check to see if the column is in one of the tables in the FROM
3539
** clause of the aggregate query */
3540
if( ALWAYS(pSrcList!=0) ){
3541
struct SrcList_item *pItem = pSrcList->a;
3542
for(i=0; i<pSrcList->nSrc; i++, pItem++){
3543
struct AggInfo_col *pCol;
3544
assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3545
if( pExpr->iTable==pItem->iCursor ){
3546
/* If we reach this point, it means that pExpr refers to a table
3547
** that is in the FROM clause of the aggregate query.
3549
** Make an entry for the column in pAggInfo->aCol[] if there
3550
** is not an entry there already.
3553
pCol = pAggInfo->aCol;
3554
for(k=0; k<pAggInfo->nColumn; k++, pCol++){
3555
if( pCol->iTable==pExpr->iTable &&
3556
pCol->iColumn==pExpr->iColumn ){
3560
if( (k>=pAggInfo->nColumn)
3561
&& (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
3563
pCol = &pAggInfo->aCol[k];
3564
pCol->pTab = pExpr->pTab;
3565
pCol->iTable = pExpr->iTable;
3566
pCol->iColumn = pExpr->iColumn;
3567
pCol->iMem = ++pParse->nMem;
3568
pCol->iSorterColumn = -1;
3569
pCol->pExpr = pExpr;
3570
if( pAggInfo->pGroupBy ){
3572
ExprList *pGB = pAggInfo->pGroupBy;
3573
struct ExprList_item *pTerm = pGB->a;
3575
for(j=0; j<n; j++, pTerm++){
3576
Expr *pE = pTerm->pExpr;
3577
if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
3578
pE->iColumn==pExpr->iColumn ){
3579
pCol->iSorterColumn = j;
3584
if( pCol->iSorterColumn<0 ){
3585
pCol->iSorterColumn = pAggInfo->nSortingColumn++;
3588
/* There is now an entry for pExpr in pAggInfo->aCol[] (either
3589
** because it was there before or because we just created it).
3590
** Convert the pExpr to be a TK_AGG_COLUMN referring to that
3591
** pAggInfo->aCol[] entry.
3593
ExprSetIrreducible(pExpr);
3594
pExpr->pAggInfo = pAggInfo;
3595
pExpr->op = TK_AGG_COLUMN;
3596
pExpr->iAgg = (i16)k;
3598
} /* endif pExpr->iTable==pItem->iCursor */
3599
} /* end loop over pSrcList */
3603
case TK_AGG_FUNCTION: {
3604
/* The pNC->nDepth==0 test causes aggregate functions in subqueries
3606
if( pNC->nDepth==0 ){
3607
/* Check to see if pExpr is a duplicate of another aggregate
3608
** function that is already in the pAggInfo structure
3610
struct AggInfo_func *pItem = pAggInfo->aFunc;
3611
for(i=0; i<pAggInfo->nFunc; i++, pItem++){
3612
if( sqlite3ExprCompare(pItem->pExpr, pExpr)==0 ){
3616
if( i>=pAggInfo->nFunc ){
3617
/* pExpr is original. Make a new entry in pAggInfo->aFunc[]
3619
u8 enc = ENC(pParse->db);
3620
i = addAggInfoFunc(pParse->db, pAggInfo);
3622
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3623
pItem = &pAggInfo->aFunc[i];
3624
pItem->pExpr = pExpr;
3625
pItem->iMem = ++pParse->nMem;
3626
assert( !ExprHasProperty(pExpr, EP_IntValue) );
3627
pItem->pFunc = sqlite3FindFunction(pParse->db,
3628
pExpr->u.zToken, sqlite3Strlen30(pExpr->u.zToken),
3629
pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
3630
if( pExpr->flags & EP_Distinct ){
3631
pItem->iDistinct = pParse->nTab++;
3633
pItem->iDistinct = -1;
3637
/* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
3639
assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
3640
ExprSetIrreducible(pExpr);
3641
pExpr->iAgg = (i16)i;
3642
pExpr->pAggInfo = pAggInfo;
3647
return WRC_Continue;
3649
static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
3650
NameContext *pNC = pWalker->u.pNC;
3651
if( pNC->nDepth==0 ){
3653
sqlite3WalkSelect(pWalker, pSelect);
3657
return WRC_Continue;
3662
** Analyze the given expression looking for aggregate functions and
3663
** for variables that need to be added to the pParse->aAgg[] array.
3664
** Make additional entries to the pParse->aAgg[] array as necessary.
3666
** This routine should only be called after the expression has been
3667
** analyzed by sqlite3ResolveExprNames().
3669
void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
3671
w.xExprCallback = analyzeAggregate;
3672
w.xSelectCallback = analyzeAggregatesInSelect;
3674
assert( pNC->pSrcList!=0 );
3675
sqlite3WalkExpr(&w, pExpr);
3679
** Call sqlite3ExprAnalyzeAggregates() for every expression in an
3680
** expression list. Return the number of errors.
3682
** If an error is found, the analysis is cut short.
3684
void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
3685
struct ExprList_item *pItem;
3688
for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
3689
sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
3695
** Allocate a single new register for use to hold some intermediate result.
3697
int sqlite3GetTempReg(Parse *pParse){
3698
if( pParse->nTempReg==0 ){
3699
return ++pParse->nMem;
3701
return pParse->aTempReg[--pParse->nTempReg];
3705
** Deallocate a register, making available for reuse for some other
3708
** If a register is currently being used by the column cache, then
3709
** the dallocation is deferred until the column cache line that uses
3710
** the register becomes stale.
3712
void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
3713
if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
3715
struct yColCache *p;
3716
for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3717
if( p->iReg==iReg ){
3722
pParse->aTempReg[pParse->nTempReg++] = iReg;
3727
** Allocate or deallocate a block of nReg consecutive registers
3729
int sqlite3GetTempRange(Parse *pParse, int nReg){
3731
i = pParse->iRangeReg;
3732
n = pParse->nRangeReg;
3734
assert( !usedAsColumnCache(pParse, i, i+n-1) );
3735
pParse->iRangeReg += nReg;
3736
pParse->nRangeReg -= nReg;
3739
pParse->nMem += nReg;
3743
void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
3744
sqlite3ExprCacheRemove(pParse, iReg, nReg);
3745
if( nReg>pParse->nRangeReg ){
3746
pParse->nRangeReg = nReg;
3747
pParse->iRangeReg = iReg;