blob: 829afc4cd6cb7313904d21358bcbcf8ae35c9738 [file] [log] [blame]
drhcce7d172000-05-31 15:34:51 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drhcce7d172000-05-31 15:34:51 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drhcce7d172000-05-31 15:34:51 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** 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.
drhcce7d172000-05-31 15:34:51 +000010**
11*************************************************************************
drh1ccde152000-06-17 13:12:39 +000012** This file contains routines used for analyzing expressions and
drhb19a2bc2001-09-16 00:13:26 +000013** for generating VDBE code that evaluates expressions in SQLite.
drhcce7d172000-05-31 15:34:51 +000014*/
15#include "sqliteInt.h"
drha2e00042002-01-22 03:13:42 +000016
drh12abf402016-08-22 14:30:05 +000017/* Forward declarations */
18static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
20
21
danielk1977e014a832004-05-17 10:48:57 +000022/*
23** Return the 'affinity' of the expression pExpr if any.
24**
25** If pExpr is a column, a reference to a column via an 'AS' alias,
26** or a sub-select with a column as the return value, then the
27** affinity of that column is returned. Otherwise, 0x00 is returned,
28** indicating no affinity for the expression.
29**
peter.d.reid60ec9142014-09-06 16:39:46 +000030** i.e. the WHERE clause expressions in the following statements all
danielk1977e014a832004-05-17 10:48:57 +000031** have an affinity:
32**
33** CREATE TABLE t1(a);
34** SELECT * FROM t1 WHERE a;
35** SELECT a AS b FROM t1 WHERE b;
36** SELECT * FROM t1 WHERE (select a from t1);
37*/
danielk1977bf3b7212004-05-18 10:06:24 +000038char sqlite3ExprAffinity(Expr *pExpr){
drh580c8c12012-12-08 03:34:04 +000039 int op;
40 pExpr = sqlite3ExprSkipCollate(pExpr);
mistachkin9bec6fb2014-06-26 21:28:21 +000041 if( pExpr->flags & EP_Generic ) return 0;
drh580c8c12012-12-08 03:34:04 +000042 op = pExpr->op;
drh487e2622005-06-25 18:42:14 +000043 if( op==TK_SELECT ){
danielk19776ab3a2e2009-02-19 14:39:25 +000044 assert( pExpr->flags&EP_xIsSelect );
45 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
danielk1977a37cdde2004-05-16 11:15:36 +000046 }
drhdb45bd52016-08-22 00:48:58 +000047 if( op==TK_REGISTER ) op = pExpr->op2;
drh487e2622005-06-25 18:42:14 +000048#ifndef SQLITE_OMIT_CAST
49 if( op==TK_CAST ){
drh33e619f2009-05-28 01:00:55 +000050 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drhfdaac672013-10-04 15:30:21 +000051 return sqlite3AffinityType(pExpr->u.zToken, 0);
drh487e2622005-06-25 18:42:14 +000052 }
53#endif
drhdb45bd52016-08-22 00:48:58 +000054 if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab!=0 ){
drh7d10d5a2008-08-20 16:35:10 +000055 int j = pExpr->iColumn;
56 if( j<0 ) return SQLITE_AFF_INTEGER;
57 assert( pExpr->pTab && j<pExpr->pTab->nCol );
58 return pExpr->pTab->aCol[j].affinity;
59 }
danielk1977a37cdde2004-05-16 11:15:36 +000060 return pExpr->affinity;
61}
62
drh53db1452004-05-20 13:54:53 +000063/*
drh8b4c40d2007-02-01 23:02:45 +000064** Set the collating sequence for expression pExpr to be the collating
drhae80dde2012-12-06 21:16:43 +000065** sequence named by pToken. Return a pointer to a new Expr node that
66** implements the COLLATE operator.
drh0a8a4062012-12-07 18:38:16 +000067**
68** If a memory allocation error occurs, that fact is recorded in pParse->db
69** and the pExpr parameter is returned unchanged.
drh8b4c40d2007-02-01 23:02:45 +000070*/
drh4ef7efa2014-03-20 15:14:08 +000071Expr *sqlite3ExprAddCollateToken(
72 Parse *pParse, /* Parsing context */
73 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
dan80103fc2015-03-20 08:43:59 +000074 const Token *pCollName, /* Name of collating sequence */
75 int dequote /* True to dequote pCollName */
drh4ef7efa2014-03-20 15:14:08 +000076){
drh0a8a4062012-12-07 18:38:16 +000077 if( pCollName->n>0 ){
dan80103fc2015-03-20 08:43:59 +000078 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
drh0a8a4062012-12-07 18:38:16 +000079 if( pNew ){
80 pNew->pLeft = pExpr;
drha4c3c872013-09-12 17:29:25 +000081 pNew->flags |= EP_Collate|EP_Skip;
drh0a8a4062012-12-07 18:38:16 +000082 pExpr = pNew;
83 }
drhae80dde2012-12-06 21:16:43 +000084 }
drh0a8a4062012-12-07 18:38:16 +000085 return pExpr;
86}
87Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
drh261d8a52012-12-08 21:36:26 +000088 Token s;
89 assert( zC!=0 );
drh40aced52016-01-22 17:48:09 +000090 sqlite3TokenInit(&s, (char*)zC);
dan80103fc2015-03-20 08:43:59 +000091 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
drh0a8a4062012-12-07 18:38:16 +000092}
93
94/*
drh0b8d2552015-09-05 22:36:07 +000095** Skip over any TK_COLLATE operators and any unlikely()
drha4c3c872013-09-12 17:29:25 +000096** or likelihood() function at the root of an expression.
drh0a8a4062012-12-07 18:38:16 +000097*/
98Expr *sqlite3ExprSkipCollate(Expr *pExpr){
drha4c3c872013-09-12 17:29:25 +000099 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
100 if( ExprHasProperty(pExpr, EP_Unlikely) ){
drhcca9f3d2013-09-06 15:23:29 +0000101 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
102 assert( pExpr->x.pList->nExpr>0 );
drha4c3c872013-09-12 17:29:25 +0000103 assert( pExpr->op==TK_FUNCTION );
drhcca9f3d2013-09-06 15:23:29 +0000104 pExpr = pExpr->x.pList->a[0].pExpr;
105 }else{
drh0b8d2552015-09-05 22:36:07 +0000106 assert( pExpr->op==TK_COLLATE );
drha4c3c872013-09-12 17:29:25 +0000107 pExpr = pExpr->pLeft;
drhcca9f3d2013-09-06 15:23:29 +0000108 }
drha4c3c872013-09-12 17:29:25 +0000109 }
drh0a8a4062012-12-07 18:38:16 +0000110 return pExpr;
drh8b4c40d2007-02-01 23:02:45 +0000111}
112
113/*
drhae80dde2012-12-06 21:16:43 +0000114** Return the collation sequence for the expression pExpr. If
115** there is no defined collating sequence, return NULL.
116**
117** The collating sequence might be determined by a COLLATE operator
118** or by the presence of a column with a defined collating sequence.
119** COLLATE operators take first precedence. Left operands take
120** precedence over right operands.
danielk19770202b292004-06-09 09:55:16 +0000121*/
danielk19777cedc8d2004-06-10 10:50:08 +0000122CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000123 sqlite3 *db = pParse->db;
danielk19777cedc8d2004-06-10 10:50:08 +0000124 CollSeq *pColl = 0;
drh7d10d5a2008-08-20 16:35:10 +0000125 Expr *p = pExpr;
drh261d8a52012-12-08 21:36:26 +0000126 while( p ){
drhae80dde2012-12-06 21:16:43 +0000127 int op = p->op;
drhfbb24d12014-03-20 17:03:30 +0000128 if( p->flags & EP_Generic ) break;
drhae80dde2012-12-06 21:16:43 +0000129 if( op==TK_CAST || op==TK_UPLUS ){
130 p = p->pLeft;
131 continue;
132 }
dan36e78302013-08-21 12:04:32 +0000133 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
drh6fdd3d82013-05-15 17:47:12 +0000134 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
drhae80dde2012-12-06 21:16:43 +0000135 break;
136 }
drha58d4a92015-01-27 13:17:05 +0000137 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
drhae80dde2012-12-06 21:16:43 +0000138 || op==TK_REGISTER || op==TK_TRIGGER)
drha58d4a92015-01-27 13:17:05 +0000139 && p->pTab!=0
drhae80dde2012-12-06 21:16:43 +0000140 ){
drh7d10d5a2008-08-20 16:35:10 +0000141 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
142 ** a TK_COLUMN but was previously evaluated and cached in a register */
drh7d10d5a2008-08-20 16:35:10 +0000143 int j = p->iColumn;
144 if( j>=0 ){
drhae80dde2012-12-06 21:16:43 +0000145 const char *zColl = p->pTab->aCol[j].zColl;
drhc4a64fa2009-05-11 20:53:28 +0000146 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh7d10d5a2008-08-20 16:35:10 +0000147 }
148 break;
danielk19770202b292004-06-09 09:55:16 +0000149 }
drhae80dde2012-12-06 21:16:43 +0000150 if( p->flags & EP_Collate ){
drh2308ed32015-02-09 16:09:34 +0000151 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
drhae80dde2012-12-06 21:16:43 +0000152 p = p->pLeft;
153 }else{
drh2308ed32015-02-09 16:09:34 +0000154 Expr *pNext = p->pRight;
drh6728cd92015-02-09 18:28:03 +0000155 /* The Expr.x union is never used at the same time as Expr.pRight */
156 assert( p->x.pList==0 || p->pRight==0 );
157 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
158 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
159 ** least one EP_Collate. Thus the following two ALWAYS. */
160 if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
drh2308ed32015-02-09 16:09:34 +0000161 int i;
drh6728cd92015-02-09 18:28:03 +0000162 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
drh2308ed32015-02-09 16:09:34 +0000163 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
164 pNext = p->x.pList->a[i].pExpr;
165 break;
166 }
167 }
168 }
169 p = pNext;
drhae80dde2012-12-06 21:16:43 +0000170 }
171 }else{
drh7d10d5a2008-08-20 16:35:10 +0000172 break;
173 }
danielk19770202b292004-06-09 09:55:16 +0000174 }
danielk19777cedc8d2004-06-10 10:50:08 +0000175 if( sqlite3CheckCollSeq(pParse, pColl) ){
176 pColl = 0;
177 }
178 return pColl;
danielk19770202b292004-06-09 09:55:16 +0000179}
180
181/*
drh626a8792005-01-17 22:08:19 +0000182** pExpr is an operand of a comparison operator. aff2 is the
183** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +0000184** type affinity that should be used for the comparison operator.
185*/
danielk1977e014a832004-05-17 10:48:57 +0000186char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +0000187 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +0000188 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +0000189 /* Both sides of the comparison are columns. If one has numeric
190 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +0000191 */
drh8a512562005-11-14 22:29:05 +0000192 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +0000193 return SQLITE_AFF_NUMERIC;
194 }else{
drh05883a32015-06-02 15:32:08 +0000195 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000196 }
197 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +0000198 /* Neither side of the comparison is a column. Compare the
199 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +0000200 */
drh05883a32015-06-02 15:32:08 +0000201 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000202 }else{
203 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +0000204 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +0000205 return (aff1 + aff2);
206 }
207}
208
drh53db1452004-05-20 13:54:53 +0000209/*
210** pExpr is a comparison operator. Return the type affinity that should
211** be applied to both operands prior to doing the comparison.
212*/
danielk1977e014a832004-05-17 10:48:57 +0000213static char comparisonAffinity(Expr *pExpr){
214 char aff;
215 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
216 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
drh6a2fe092009-09-23 02:29:36 +0000217 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
danielk1977e014a832004-05-17 10:48:57 +0000218 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000219 aff = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +0000220 if( pExpr->pRight ){
221 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
danielk19776ab3a2e2009-02-19 14:39:25 +0000222 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
223 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
224 }else if( !aff ){
drh05883a32015-06-02 15:32:08 +0000225 aff = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000226 }
227 return aff;
228}
229
230/*
231** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
232** idx_affinity is the affinity of an indexed column. Return true
233** if the index with affinity idx_affinity may be used to implement
234** the comparison in pExpr.
235*/
236int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
237 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000238 switch( aff ){
drh05883a32015-06-02 15:32:08 +0000239 case SQLITE_AFF_BLOB:
drh8a512562005-11-14 22:29:05 +0000240 return 1;
241 case SQLITE_AFF_TEXT:
242 return idx_affinity==SQLITE_AFF_TEXT;
243 default:
244 return sqlite3IsNumericAffinity(idx_affinity);
245 }
danielk1977e014a832004-05-17 10:48:57 +0000246}
247
danielk1977a37cdde2004-05-16 11:15:36 +0000248/*
drh35573352008-01-08 23:54:25 +0000249** Return the P5 value that should be used for a binary comparison
danielk1977a37cdde2004-05-16 11:15:36 +0000250** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
danielk1977a37cdde2004-05-16 11:15:36 +0000251*/
drh35573352008-01-08 23:54:25 +0000252static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
253 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
drh1bd10f82008-12-10 21:19:56 +0000254 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
drh35573352008-01-08 23:54:25 +0000255 return aff;
danielk1977a37cdde2004-05-16 11:15:36 +0000256}
257
drha2e00042002-01-22 03:13:42 +0000258/*
danielk19770202b292004-06-09 09:55:16 +0000259** Return a pointer to the collation sequence that should be used by
260** a binary comparison operator comparing pLeft and pRight.
261**
262** If the left hand expression has a collating sequence type, then it is
263** used. Otherwise the collation sequence for the right hand expression
264** is used, or the default (BINARY) if neither expression has a collating
265** type.
danielk1977bcbb04e2007-05-29 12:11:29 +0000266**
267** Argument pRight (but not pLeft) may be a null pointer. In this case,
268** it is not considered.
danielk19770202b292004-06-09 09:55:16 +0000269*/
drh0a0e1312007-08-07 17:04:59 +0000270CollSeq *sqlite3BinaryCompareCollSeq(
danielk1977bcbb04e2007-05-29 12:11:29 +0000271 Parse *pParse,
272 Expr *pLeft,
273 Expr *pRight
274){
drhec41dda2007-02-07 13:09:45 +0000275 CollSeq *pColl;
276 assert( pLeft );
drhae80dde2012-12-06 21:16:43 +0000277 if( pLeft->flags & EP_Collate ){
278 pColl = sqlite3ExprCollSeq(pParse, pLeft);
279 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
280 pColl = sqlite3ExprCollSeq(pParse, pRight);
drhec41dda2007-02-07 13:09:45 +0000281 }else{
282 pColl = sqlite3ExprCollSeq(pParse, pLeft);
283 if( !pColl ){
284 pColl = sqlite3ExprCollSeq(pParse, pRight);
285 }
danielk19770202b292004-06-09 09:55:16 +0000286 }
287 return pColl;
288}
289
290/*
drhbe5c89a2004-07-26 00:31:09 +0000291** Generate code for a comparison operator.
292*/
293static int codeCompare(
294 Parse *pParse, /* The parsing (and code generating) context */
295 Expr *pLeft, /* The left operand */
296 Expr *pRight, /* The right operand */
297 int opcode, /* The comparison opcode */
drh35573352008-01-08 23:54:25 +0000298 int in1, int in2, /* Register holding operands */
drhbe5c89a2004-07-26 00:31:09 +0000299 int dest, /* Jump here if true. */
300 int jumpIfNull /* If true, jump if either operand is NULL */
301){
drh35573352008-01-08 23:54:25 +0000302 int p5;
303 int addr;
304 CollSeq *p4;
305
306 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
307 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
308 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
309 (void*)p4, P4_COLLSEQ);
drh1bd10f82008-12-10 21:19:56 +0000310 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
drh35573352008-01-08 23:54:25 +0000311 return addr;
drhbe5c89a2004-07-26 00:31:09 +0000312}
313
dancfbb5e82016-07-13 19:48:13 +0000314/*
dan870a0702016-08-01 16:37:43 +0000315** Return true if expression pExpr is a vector, or false otherwise.
drhd832da72016-08-20 21:11:25 +0000316**
317** A vector is defined as any expression that results in two or more
318** columns of result. Every TK_VECTOR node is an vector because the
319** parser will not generate a TK_VECTOR with fewer than two entries.
320** But a TK_SELECT might be either a vector or a scalar. It is only
321** considered a vector if it has two or more result columns.
dan870a0702016-08-01 16:37:43 +0000322*/
323int sqlite3ExprIsVector(Expr *pExpr){
drh76dbe7a2016-08-20 21:02:38 +0000324 return sqlite3ExprVectorSize(pExpr)>1;
dan870a0702016-08-01 16:37:43 +0000325}
326
327/*
dancfbb5e82016-07-13 19:48:13 +0000328** If the expression passed as the only argument is of type TK_VECTOR
329** return the number of expressions in the vector. Or, if the expression
330** is a sub-select, return the number of columns in the sub-select. For
331** any other type of expression, return 1.
332*/
dan71c57db2016-07-09 20:23:55 +0000333int sqlite3ExprVectorSize(Expr *pExpr){
drh12abf402016-08-22 14:30:05 +0000334 u8 op = pExpr->op;
335 if( op==TK_REGISTER ) op = pExpr->op2;
336 if( op==TK_VECTOR ){
drh76dbe7a2016-08-20 21:02:38 +0000337 return pExpr->x.pList->nExpr;
drh12abf402016-08-22 14:30:05 +0000338 }else if( op==TK_SELECT ){
dan71c57db2016-07-09 20:23:55 +0000339 return pExpr->x.pSelect->pEList->nExpr;
drh76dbe7a2016-08-20 21:02:38 +0000340 }else{
341 return 1;
dan71c57db2016-07-09 20:23:55 +0000342 }
dan71c57db2016-07-09 20:23:55 +0000343}
344
danf9b2e052016-08-02 17:45:00 +0000345#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +0000346/*
drhfc7f27b2016-08-20 00:07:01 +0000347** Return a pointer to a subexpression of pVector that is the i-th
348** column of the vector (numbered starting with 0). The caller must
349** ensure that i is within range.
350**
drh76dbe7a2016-08-20 21:02:38 +0000351** If pVector is really a scalar (and "scalar" here includes subqueries
352** that return a single column!) then return pVector unmodified.
353**
drhfc7f27b2016-08-20 00:07:01 +0000354** pVector retains ownership of the returned subexpression.
355**
356** If the vector is a (SELECT ...) then the expression returned is
drh76dbe7a2016-08-20 21:02:38 +0000357** just the expression for the i-th term of the result set, and may
358** not be ready for evaluation because the table cursor has not yet
359** been positioned.
danba00e302016-07-23 20:24:06 +0000360*/
drhfc7f27b2016-08-20 00:07:01 +0000361Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
dan870a0702016-08-01 16:37:43 +0000362 assert( i<sqlite3ExprVectorSize(pVector) );
363 if( sqlite3ExprIsVector(pVector) ){
drh12abf402016-08-22 14:30:05 +0000364 if( pVector->op==TK_SELECT
365 || (pVector->op==TK_REGISTER && pVector->op2==TK_SELECT)
366 ){
dan870a0702016-08-01 16:37:43 +0000367 return pVector->x.pSelect->pEList->a[i].pExpr;
368 }else{
369 return pVector->x.pList->a[i].pExpr;
370 }
dan71c57db2016-07-09 20:23:55 +0000371 }
dan870a0702016-08-01 16:37:43 +0000372 return pVector;
dan71c57db2016-07-09 20:23:55 +0000373}
drhfc7f27b2016-08-20 00:07:01 +0000374#endif /* !defined(SQLITE_OMIT_SUBQUERY) */
375
376#ifndef SQLITE_OMIT_SUBQUERY
377/*
378** Compute and return a new Expr object which when passed to
379** sqlite3ExprCode() will generate all necessary code to compute
380** the iField-th column of the vector expression pVector.
381**
drh8762ec12016-08-20 01:06:22 +0000382** It is ok for pVector to be a scalar (as long as iField==0).
383** In that case, this routine works like sqlite3ExprDup().
384**
drhfc7f27b2016-08-20 00:07:01 +0000385** The caller owns the returned Expr object and is responsible for
386** ensuring that the returned value eventually gets freed.
387**
drh8762ec12016-08-20 01:06:22 +0000388** The caller retains ownership of pVector. If pVector is a TK_SELECT,
drh76dbe7a2016-08-20 21:02:38 +0000389** then the returne object will reference pVector and so pVector must remain
drh8762ec12016-08-20 01:06:22 +0000390** valid for the life of the returned object. If pVector is a TK_VECTOR
391** or a scalar expression, then it can be deleted as soon as this routine
drh76dbe7a2016-08-20 21:02:38 +0000392** returns.
drh8762ec12016-08-20 01:06:22 +0000393**
394** A trick to cause a TK_SELECT pVector to be deleted together with
395** the returned Expr object is to attach the pVector to the pRight field
396** of the returned TK_SELECT_COLUMN Expr object.
drhfc7f27b2016-08-20 00:07:01 +0000397*/
398Expr *sqlite3ExprForVectorField(
399 Parse *pParse, /* Parsing context */
400 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
drha1251bc2016-08-20 00:51:37 +0000401 int iField /* Which column of the vector to return */
drhfc7f27b2016-08-20 00:07:01 +0000402){
403 Expr *pRet;
drha1251bc2016-08-20 00:51:37 +0000404 if( pVector->op==TK_SELECT ){
405 assert( pVector->flags & EP_xIsSelect );
drhfc7f27b2016-08-20 00:07:01 +0000406 /* The TK_SELECT_COLUMN Expr node:
407 **
408 ** pLeft: pVector containing TK_SELECT
drh8762ec12016-08-20 01:06:22 +0000409 ** pRight: not used. But recursively deleted.
drhfc7f27b2016-08-20 00:07:01 +0000410 ** iColumn: Index of a column in pVector
411 ** pLeft->iTable: First in an array of register holding result, or 0
412 ** if the result is not yet computed.
413 **
414 ** sqlite3ExprDelete() specifically skips the recursive delete of
415 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
drh8762ec12016-08-20 01:06:22 +0000416 ** can be attached to pRight to cause this node to take ownership of
417 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
418 ** with the same pLeft pointer to the pVector, but only one of them
419 ** will own the pVector.
drhfc7f27b2016-08-20 00:07:01 +0000420 */
drh8bd0d582016-08-20 18:06:14 +0000421 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0, 0);
422 if( pRet ){
423 pRet->iColumn = iField;
424 pRet->pLeft = pVector;
425 }
drhfc7f27b2016-08-20 00:07:01 +0000426 assert( pRet==0 || pRet->iTable==0 );
427 }else{
drha1251bc2016-08-20 00:51:37 +0000428 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
429 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
drhfc7f27b2016-08-20 00:07:01 +0000430 }
431 return pRet;
432}
433#endif /* !define(SQLITE_OMIT_SUBQUERY) */
dan71c57db2016-07-09 20:23:55 +0000434
dan5c288b92016-07-30 21:02:33 +0000435/*
436** If expression pExpr is of type TK_SELECT, generate code to evaluate
437** it. Return the register in which the result is stored (or, if the
438** sub-select returns more than one column, the first in an array
439** of registers in which the result is stored).
440**
441** If pExpr is not a TK_SELECT expression, return 0.
442*/
443static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
dan8da209b2016-07-26 18:06:08 +0000444 int reg = 0;
danf9b2e052016-08-02 17:45:00 +0000445#ifndef SQLITE_OMIT_SUBQUERY
dan5c288b92016-07-30 21:02:33 +0000446 if( pExpr->op==TK_SELECT ){
447 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
dan8da209b2016-07-26 18:06:08 +0000448 }
danf9b2e052016-08-02 17:45:00 +0000449#endif
dan8da209b2016-07-26 18:06:08 +0000450 return reg;
451}
452
dan5c288b92016-07-30 21:02:33 +0000453/*
454** Argument pVector points to a vector expression - either a TK_VECTOR
dan870a0702016-08-01 16:37:43 +0000455** or TK_SELECT that returns more than one column. This function returns
456** the register number of a register that contains the value of
457** element iField of the vector.
458**
459** If pVector is a TK_SELECT expression, then code for it must have
460** already been generated using the exprCodeSubselect() routine. In this
461** case parameter regSelect should be the first in an array of registers
462** containing the results of the sub-select.
463**
464** If pVector is of type TK_VECTOR, then code for the requested field
465** is generated. In this case (*pRegFree) may be set to the number of
466** a temporary register to be freed by the caller before returning.
dan5c288b92016-07-30 21:02:33 +0000467**
468** Before returning, output parameter (*ppExpr) is set to point to the
469** Expr object corresponding to element iElem of the vector.
dan5c288b92016-07-30 21:02:33 +0000470*/
471static int exprVectorRegister(
472 Parse *pParse, /* Parse context */
473 Expr *pVector, /* Vector to extract element from */
dan870a0702016-08-01 16:37:43 +0000474 int iField, /* Field to extract from pVector */
dan5c288b92016-07-30 21:02:33 +0000475 int regSelect, /* First in array of registers */
476 Expr **ppExpr, /* OUT: Expression element */
477 int *pRegFree /* OUT: Temp register to free */
478){
drh12abf402016-08-22 14:30:05 +0000479 u8 op = pVector->op;
480 assert( op==TK_VECTOR || op==TK_SELECT || op==TK_REGISTER );
481 if( op==TK_REGISTER ){
482 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
483 return pVector->iTable+iField;
484 }
485 if( op==TK_SELECT ){
dan870a0702016-08-01 16:37:43 +0000486 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
487 return regSelect+iField;
dan5c288b92016-07-30 21:02:33 +0000488 }
dan870a0702016-08-01 16:37:43 +0000489 *ppExpr = pVector->x.pList->a[iField].pExpr;
dan5c288b92016-07-30 21:02:33 +0000490 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
491}
492
493/*
494** Expression pExpr is a comparison between two vector values. Compute
drh79752b62016-08-13 10:02:17 +0000495** the result of the comparison (1, 0, or NULL) and write that
496** result into register dest.
497**
498** The caller must satisfy the following preconditions:
499**
500** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
501** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
502** otherwise: op==pExpr->op and p5==0
dan5c288b92016-07-30 21:02:33 +0000503*/
drh79752b62016-08-13 10:02:17 +0000504static void codeVectorCompare(
505 Parse *pParse, /* Code generator context */
506 Expr *pExpr, /* The comparison operation */
507 int dest, /* Write results into this register */
508 u8 op, /* Comparison operator */
509 u8 p5 /* SQLITE_NULLEQ or zero */
510){
dan71c57db2016-07-09 20:23:55 +0000511 Vdbe *v = pParse->pVdbe;
512 Expr *pLeft = pExpr->pLeft;
513 Expr *pRight = pExpr->pRight;
514 int nLeft = sqlite3ExprVectorSize(pLeft);
515 int nRight = sqlite3ExprVectorSize(pRight);
dan71c57db2016-07-09 20:23:55 +0000516
517 /* Check that both sides of the comparison are vectors, and that
518 ** both are the same length. */
519 if( nLeft!=nRight ){
520 sqlite3ErrorMsg(pParse, "invalid use of row value");
521 }else{
dan71c57db2016-07-09 20:23:55 +0000522 int i;
dan71c57db2016-07-09 20:23:55 +0000523 int regLeft = 0;
524 int regRight = 0;
drh79752b62016-08-13 10:02:17 +0000525 u8 opx = op;
526 int addrDone = sqlite3VdbeMakeLabel(v);
dan71c57db2016-07-09 20:23:55 +0000527
528 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
529 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
530 || pExpr->op==TK_LT || pExpr->op==TK_GT
531 || pExpr->op==TK_LE || pExpr->op==TK_GE
532 );
drh79752b62016-08-13 10:02:17 +0000533 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
534 || (pExpr->op==TK_ISNOT && op==TK_NE) );
535 assert( p5==0 || pExpr->op!=op );
536 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
dan71c57db2016-07-09 20:23:55 +0000537
drh79752b62016-08-13 10:02:17 +0000538 p5 |= SQLITE_STOREP2;
539 if( opx==TK_LE ) opx = TK_LT;
540 if( opx==TK_GE ) opx = TK_GT;
dan71c57db2016-07-09 20:23:55 +0000541
dan5c288b92016-07-30 21:02:33 +0000542 regLeft = exprCodeSubselect(pParse, pLeft);
543 regRight = exprCodeSubselect(pParse, pRight);
dan71c57db2016-07-09 20:23:55 +0000544
545 for(i=0; i<nLeft; i++){
546 int regFree1 = 0, regFree2 = 0;
547 Expr *pL, *pR;
548 int r1, r2;
drh79752b62016-08-13 10:02:17 +0000549 if( i>0 ) sqlite3ExprCachePush(pParse);
dan5c288b92016-07-30 21:02:33 +0000550 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
551 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
drh79752b62016-08-13 10:02:17 +0000552 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
553 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
554 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
555 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
556 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
557 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
558 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
dan71c57db2016-07-09 20:23:55 +0000559 sqlite3ReleaseTempReg(pParse, regFree1);
560 sqlite3ReleaseTempReg(pParse, regFree2);
drh79752b62016-08-13 10:02:17 +0000561 if( i>0 ) sqlite3ExprCachePop(pParse);
562 if( i==nLeft-1 ){
563 break;
564 }
565 if( opx==TK_EQ ){
566 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
567 p5 |= SQLITE_KEEPNULL;
568 }else if( opx==TK_NE ){
569 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
570 p5 |= SQLITE_KEEPNULL;
drha2f62922016-08-13 12:37:47 +0000571 }else{
572 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
573 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
drh79752b62016-08-13 10:02:17 +0000574 VdbeCoverageIf(v, op==TK_LT);
575 VdbeCoverageIf(v, op==TK_GT);
drh79752b62016-08-13 10:02:17 +0000576 VdbeCoverageIf(v, op==TK_LE);
577 VdbeCoverageIf(v, op==TK_GE);
578 if( i==nLeft-2 ) opx = op;
579 }
dan71c57db2016-07-09 20:23:55 +0000580 }
drh79752b62016-08-13 10:02:17 +0000581 sqlite3VdbeResolveLabel(v, addrDone);
dan71c57db2016-07-09 20:23:55 +0000582 }
dan71c57db2016-07-09 20:23:55 +0000583}
584
danielk19774b5255a2008-06-05 16:47:39 +0000585#if SQLITE_MAX_EXPR_DEPTH>0
586/*
587** Check that argument nHeight is less than or equal to the maximum
588** expression depth allowed. If it is not, leave an error message in
589** pParse.
590*/
drh7d10d5a2008-08-20 16:35:10 +0000591int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000592 int rc = SQLITE_OK;
593 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
594 if( nHeight>mxHeight ){
595 sqlite3ErrorMsg(pParse,
596 "Expression tree is too large (maximum depth %d)", mxHeight
597 );
598 rc = SQLITE_ERROR;
599 }
600 return rc;
601}
602
603/* The following three functions, heightOfExpr(), heightOfExprList()
604** and heightOfSelect(), are used to determine the maximum height
605** of any expression tree referenced by the structure passed as the
606** first argument.
607**
608** If this maximum height is greater than the current value pointed
609** to by pnHeight, the second parameter, then set *pnHeight to that
610** value.
611*/
612static void heightOfExpr(Expr *p, int *pnHeight){
613 if( p ){
614 if( p->nHeight>*pnHeight ){
615 *pnHeight = p->nHeight;
616 }
617 }
618}
619static void heightOfExprList(ExprList *p, int *pnHeight){
620 if( p ){
621 int i;
622 for(i=0; i<p->nExpr; i++){
623 heightOfExpr(p->a[i].pExpr, pnHeight);
624 }
625 }
626}
627static void heightOfSelect(Select *p, int *pnHeight){
628 if( p ){
629 heightOfExpr(p->pWhere, pnHeight);
630 heightOfExpr(p->pHaving, pnHeight);
631 heightOfExpr(p->pLimit, pnHeight);
632 heightOfExpr(p->pOffset, pnHeight);
633 heightOfExprList(p->pEList, pnHeight);
634 heightOfExprList(p->pGroupBy, pnHeight);
635 heightOfExprList(p->pOrderBy, pnHeight);
636 heightOfSelect(p->pPrior, pnHeight);
637 }
638}
639
640/*
641** Set the Expr.nHeight variable in the structure passed as an
642** argument. An expression with no children, Expr.pList or
643** Expr.pSelect member has a height of 1. Any other expression
644** has a height equal to the maximum height of any other
645** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000646**
647** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
648** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000649*/
650static void exprSetHeight(Expr *p){
651 int nHeight = 0;
652 heightOfExpr(p->pLeft, &nHeight);
653 heightOfExpr(p->pRight, &nHeight);
danielk19776ab3a2e2009-02-19 14:39:25 +0000654 if( ExprHasProperty(p, EP_xIsSelect) ){
655 heightOfSelect(p->x.pSelect, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000656 }else if( p->x.pList ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000657 heightOfExprList(p->x.pList, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000658 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
danielk19776ab3a2e2009-02-19 14:39:25 +0000659 }
danielk19774b5255a2008-06-05 16:47:39 +0000660 p->nHeight = nHeight + 1;
661}
662
663/*
664** Set the Expr.nHeight variable using the exprSetHeight() function. If
665** the height is greater than the maximum allowed expression depth,
666** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000667**
668** Also propagate all EP_Propagate flags from the Expr.x.pList into
669** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000670*/
drh2308ed32015-02-09 16:09:34 +0000671void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh74893a42015-03-22 10:23:17 +0000672 if( pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000673 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000674 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000675}
676
677/*
678** Return the maximum height of any expression tree referenced
679** by the select statement passed as an argument.
680*/
681int sqlite3SelectExprHeight(Select *p){
682 int nHeight = 0;
683 heightOfSelect(p, &nHeight);
684 return nHeight;
685}
drh2308ed32015-02-09 16:09:34 +0000686#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
687/*
688** Propagate all EP_Propagate flags from the Expr.x.pList into
689** Expr.flags.
690*/
691void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
692 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
693 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
694 }
695}
696#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000697#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
698
drhbe5c89a2004-07-26 00:31:09 +0000699/*
drhb7916a72009-05-27 10:31:29 +0000700** This routine is the core allocator for Expr nodes.
701**
drha76b5df2002-02-23 02:32:10 +0000702** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000703** for this node and for the pToken argument is a single allocation
704** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000705** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000706**
707** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000708** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000709** parameter is ignored if pToken is NULL or if the token does not
710** appear to be quoted. If the quotes were of the form "..." (double-quotes)
711** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000712**
713** Special case: If op==TK_INTEGER and pToken points to a string that
714** can be translated into a 32-bit integer, then the token is not
715** stored in u.zToken. Instead, the integer values is written
716** into u.iValue and the EP_IntValue flag is set. No extra storage
717** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000718*/
drhb7916a72009-05-27 10:31:29 +0000719Expr *sqlite3ExprAlloc(
danielk1977a1644fd2007-08-29 12:31:25 +0000720 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
drh17435752007-08-16 04:30:38 +0000721 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000722 const Token *pToken, /* Token argument. Might be NULL */
723 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000724){
drha76b5df2002-02-23 02:32:10 +0000725 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000726 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000727 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000728
drh575fad62016-02-05 13:38:36 +0000729 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000730 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000731 if( op!=TK_INTEGER || pToken->z==0
732 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
733 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000734 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000735 }
drhb7916a72009-05-27 10:31:29 +0000736 }
drh575fad62016-02-05 13:38:36 +0000737 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000738 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000739 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000740 pNew->op = (u8)op;
741 pNew->iAgg = -1;
742 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000743 if( nExtra==0 ){
744 pNew->flags |= EP_IntValue;
745 pNew->u.iValue = iValue;
746 }else{
drh33e619f2009-05-28 01:00:55 +0000747 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000748 assert( pToken->z!=0 || pToken->n==0 );
749 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000750 pNew->u.zToken[pToken->n] = 0;
drh244b9d62016-04-11 19:01:08 +0000751 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
752 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
drh33e619f2009-05-28 01:00:55 +0000753 sqlite3Dequote(pNew->u.zToken);
drh33e619f2009-05-28 01:00:55 +0000754 }
drhb7916a72009-05-27 10:31:29 +0000755 }
756 }
757#if SQLITE_MAX_EXPR_DEPTH>0
758 pNew->nHeight = 1;
759#endif
760 }
drha76b5df2002-02-23 02:32:10 +0000761 return pNew;
762}
763
764/*
drhb7916a72009-05-27 10:31:29 +0000765** Allocate a new expression node from a zero-terminated token that has
766** already been dequoted.
767*/
768Expr *sqlite3Expr(
769 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
770 int op, /* Expression opcode */
771 const char *zToken /* Token argument. Might be NULL */
772){
773 Token x;
774 x.z = zToken;
775 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
776 return sqlite3ExprAlloc(db, op, &x, 0);
777}
778
779/*
780** Attach subtrees pLeft and pRight to the Expr node pRoot.
781**
782** If pRoot==NULL that means that a memory allocation error has occurred.
783** In that case, delete the subtrees pLeft and pRight.
784*/
785void sqlite3ExprAttachSubtrees(
786 sqlite3 *db,
787 Expr *pRoot,
788 Expr *pLeft,
789 Expr *pRight
790){
791 if( pRoot==0 ){
792 assert( db->mallocFailed );
793 sqlite3ExprDelete(db, pLeft);
794 sqlite3ExprDelete(db, pRight);
795 }else{
796 if( pRight ){
797 pRoot->pRight = pRight;
drh885a5b02015-02-09 15:21:36 +0000798 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000799 }
800 if( pLeft ){
801 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000802 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000803 }
804 exprSetHeight(pRoot);
805 }
806}
807
808/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000809** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000810**
drhbf664462009-06-19 18:32:54 +0000811** One or both of the subtrees can be NULL. Return a pointer to the new
812** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
813** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000814*/
drh17435752007-08-16 04:30:38 +0000815Expr *sqlite3PExpr(
816 Parse *pParse, /* Parsing context */
817 int op, /* Expression opcode */
818 Expr *pLeft, /* Left operand */
819 Expr *pRight, /* Right operand */
820 const Token *pToken /* Argument token */
821){
drh5fb52ca2012-03-31 02:34:35 +0000822 Expr *p;
drh1167d322015-10-28 20:01:45 +0000823 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000824 /* Take advantage of short-circuit false optimization for AND */
825 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
826 }else{
drh1167d322015-10-28 20:01:45 +0000827 p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
drh5fb52ca2012-03-31 02:34:35 +0000828 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
829 }
dan2b359bd2010-10-28 11:31:23 +0000830 if( p ) {
831 sqlite3ExprCheckHeight(pParse, p->nHeight);
832 }
drh4e0cff62004-11-05 05:10:28 +0000833 return p;
834}
835
836/*
drh08de4f72016-04-11 01:06:47 +0000837** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
838** do a memory allocation failure) then delete the pSelect object.
839*/
840void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
841 if( pExpr ){
842 pExpr->x.pSelect = pSelect;
843 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
844 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
845 }else{
846 assert( pParse->db->mallocFailed );
847 sqlite3SelectDelete(pParse->db, pSelect);
848 }
849}
850
851
852/*
drh991a1982014-01-02 17:57:16 +0000853** If the expression is always either TRUE or FALSE (respectively),
854** then return 1. If one cannot determine the truth value of the
855** expression at compile-time return 0.
856**
857** This is an optimization. If is OK to return 0 here even if
858** the expression really is always false or false (a false negative).
859** But it is a bug to return 1 if the expression might have different
860** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000861**
862** Note that if the expression is part of conditional for a
863** LEFT JOIN, then we cannot determine at compile-time whether or not
864** is it true or false, so always return 0.
865*/
drh991a1982014-01-02 17:57:16 +0000866static int exprAlwaysTrue(Expr *p){
867 int v = 0;
868 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
869 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
870 return v!=0;
871}
drh5fb52ca2012-03-31 02:34:35 +0000872static int exprAlwaysFalse(Expr *p){
873 int v = 0;
874 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
875 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
876 return v==0;
877}
878
879/*
drh91bb0ee2004-09-01 03:06:34 +0000880** Join two expressions using an AND operator. If either expression is
881** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000882**
883** If one side or the other of the AND is known to be false, then instead
884** of returning an AND expression, just return a constant expression with
885** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000886*/
danielk19771e536952007-08-16 10:09:01 +0000887Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000888 if( pLeft==0 ){
889 return pRight;
890 }else if( pRight==0 ){
891 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000892 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
893 sqlite3ExprDelete(db, pLeft);
894 sqlite3ExprDelete(db, pRight);
895 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000896 }else{
drhb7916a72009-05-27 10:31:29 +0000897 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
898 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
899 return pNew;
drha76b5df2002-02-23 02:32:10 +0000900 }
901}
902
903/*
904** Construct a new expression node for a function with multiple
905** arguments.
906*/
drh17435752007-08-16 04:30:38 +0000907Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000908 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000909 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000910 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000911 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000912 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000913 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000914 return 0;
915 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000916 pNew->x.pList = pList;
917 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
drh2308ed32015-02-09 16:09:34 +0000918 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drha76b5df2002-02-23 02:32:10 +0000919 return pNew;
920}
921
922/*
drhfa6bc002004-09-07 16:19:52 +0000923** Assign a variable number to an expression that encodes a wildcard
924** in the original SQL statement.
925**
926** Wildcards consisting of a single "?" are assigned the next sequential
927** variable number.
928**
929** Wildcards of the form "?nnn" are assigned the number "nnn". We make
930** sure "nnn" is not too be to avoid a denial of service attack when
931** the SQL statement comes from an external source.
932**
drh51f49f12009-05-21 20:41:32 +0000933** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +0000934** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +0000935** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +0000936** assigned.
937*/
938void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
drh17435752007-08-16 04:30:38 +0000939 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +0000940 const char *z;
drh17435752007-08-16 04:30:38 +0000941
drhfa6bc002004-09-07 16:19:52 +0000942 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +0000943 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +0000944 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000945 assert( z!=0 );
946 assert( z[0]!=0 );
947 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +0000948 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +0000949 assert( z[0]=='?' );
drh8677d302009-11-04 13:17:14 +0000950 pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000951 }else{
drh124c0b42011-06-01 18:15:55 +0000952 ynVar x = 0;
953 u32 n = sqlite3Strlen30(z);
954 if( z[0]=='?' ){
955 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
956 ** use it as the variable number */
957 i64 i;
958 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
959 pExpr->iColumn = x = (ynVar)i;
960 testcase( i==0 );
961 testcase( i==1 );
962 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
963 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
964 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
965 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
966 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
967 x = 0;
drhfa6bc002004-09-07 16:19:52 +0000968 }
drh124c0b42011-06-01 18:15:55 +0000969 if( i>pParse->nVar ){
970 pParse->nVar = (int)i;
971 }
972 }else{
973 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
974 ** number as the prior appearance of the same name, or if the name
975 ** has never appeared before, reuse the same variable number
976 */
977 ynVar i;
978 for(i=0; i<pParse->nzVar; i++){
drh503a6862013-03-01 01:07:17 +0000979 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
drh124c0b42011-06-01 18:15:55 +0000980 pExpr->iColumn = x = (ynVar)i+1;
981 break;
982 }
983 }
984 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000985 }
drh124c0b42011-06-01 18:15:55 +0000986 if( x>0 ){
987 if( x>pParse->nzVar ){
988 char **a;
989 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
drh4a642b62016-02-05 01:55:27 +0000990 if( a==0 ){
991 assert( db->mallocFailed ); /* Error reported through mallocFailed */
992 return;
993 }
drh124c0b42011-06-01 18:15:55 +0000994 pParse->azVar = a;
995 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
996 pParse->nzVar = x;
drhfa6bc002004-09-07 16:19:52 +0000997 }
drh124c0b42011-06-01 18:15:55 +0000998 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
999 sqlite3DbFree(db, pParse->azVar[x-1]);
1000 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
drhfa6bc002004-09-07 16:19:52 +00001001 }
1002 }
1003 }
drhbb4957f2008-03-20 14:03:29 +00001004 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +00001005 sqlite3ErrorMsg(pParse, "too many SQL variables");
1006 }
drhfa6bc002004-09-07 16:19:52 +00001007}
1008
1009/*
danf6963f92009-11-23 14:39:14 +00001010** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +00001011*/
drh4f0010b2016-04-11 14:49:39 +00001012static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1013 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +00001014 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1015 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drhc5cd1242013-09-12 16:50:49 +00001016 if( !ExprHasProperty(p, EP_TokenOnly) ){
1017 /* The Expr.x union is never used at the same time as Expr.pRight */
1018 assert( p->x.pList==0 || p->pRight==0 );
dan71c57db2016-07-09 20:23:55 +00001019 if( p->op!=TK_SELECT_COLUMN ) sqlite3ExprDelete(db, p->pLeft);
drh33e619f2009-05-28 01:00:55 +00001020 sqlite3ExprDelete(db, p->pRight);
drhc5cd1242013-09-12 16:50:49 +00001021 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
danielk19776ab3a2e2009-02-19 14:39:25 +00001022 if( ExprHasProperty(p, EP_xIsSelect) ){
1023 sqlite3SelectDelete(db, p->x.pSelect);
1024 }else{
1025 sqlite3ExprListDelete(db, p->x.pList);
1026 }
1027 }
drh33e619f2009-05-28 01:00:55 +00001028 if( !ExprHasProperty(p, EP_Static) ){
1029 sqlite3DbFree(db, p);
1030 }
drha2e00042002-01-22 03:13:42 +00001031}
drh4f0010b2016-04-11 14:49:39 +00001032void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1033 if( p ) sqlite3ExprDeleteNN(db, p);
1034}
drha2e00042002-01-22 03:13:42 +00001035
drhd2687b72005-08-12 22:56:09 +00001036/*
danielk19776ab3a2e2009-02-19 14:39:25 +00001037** Return the number of bytes allocated for the expression structure
1038** passed as the first argument. This is always one of EXPR_FULLSIZE,
1039** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1040*/
1041static int exprStructSize(Expr *p){
1042 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001043 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1044 return EXPR_FULLSIZE;
1045}
1046
1047/*
drh33e619f2009-05-28 01:00:55 +00001048** The dupedExpr*Size() routines each return the number of bytes required
1049** to store a copy of an expression or expression tree. They differ in
1050** how much of the tree is measured.
1051**
1052** dupedExprStructSize() Size of only the Expr structure
1053** dupedExprNodeSize() Size of Expr + space for token
1054** dupedExprSize() Expr + token + subtree components
1055**
1056***************************************************************************
1057**
1058** The dupedExprStructSize() function returns two values OR-ed together:
1059** (1) the space required for a copy of the Expr structure only and
1060** (2) the EP_xxx flags that indicate what the structure size should be.
1061** The return values is always one of:
1062**
1063** EXPR_FULLSIZE
1064** EXPR_REDUCEDSIZE | EP_Reduced
1065** EXPR_TOKENONLYSIZE | EP_TokenOnly
1066**
1067** The size of the structure can be found by masking the return value
1068** of this routine with 0xfff. The flags can be found by masking the
1069** return value with EP_Reduced|EP_TokenOnly.
1070**
1071** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1072** (unreduced) Expr objects as they or originally constructed by the parser.
1073** During expression analysis, extra information is computed and moved into
1074** later parts of teh Expr object and that extra information might get chopped
1075** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +00001076** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +00001077** to reduce a pristine expression tree from the parser. The implementation
1078** of dupedExprStructSize() contain multiple assert() statements that attempt
1079** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +00001080*/
1081static int dupedExprStructSize(Expr *p, int flags){
1082 int nSize;
drh33e619f2009-05-28 01:00:55 +00001083 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +00001084 assert( EXPR_FULLSIZE<=0xfff );
1085 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
drh3c194692016-04-11 16:43:43 +00001086 if( 0==flags ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001087 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001088 }else{
drhc5cd1242013-09-12 16:50:49 +00001089 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +00001090 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +00001091 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +00001092 assert( !ExprHasProperty(p, EP_NoReduce) );
drhaecd8022013-09-13 18:15:15 +00001093 if( p->pLeft || p->x.pList ){
drh33e619f2009-05-28 01:00:55 +00001094 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1095 }else{
drhaecd8022013-09-13 18:15:15 +00001096 assert( p->pRight==0 );
drh33e619f2009-05-28 01:00:55 +00001097 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1098 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001099 }
1100 return nSize;
1101}
1102
1103/*
drh33e619f2009-05-28 01:00:55 +00001104** This function returns the space in bytes required to store the copy
1105** of the Expr structure and a copy of the Expr.u.zToken string (if that
1106** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +00001107*/
1108static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +00001109 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1110 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1111 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001112 }
danielk1977bc739712009-03-23 04:33:32 +00001113 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +00001114}
1115
1116/*
1117** Return the number of bytes required to create a duplicate of the
1118** expression passed as the first argument. The second argument is a
1119** mask containing EXPRDUP_XXX flags.
1120**
1121** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +00001122** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +00001123**
1124** If the EXPRDUP_REDUCE flag is set, then the return value includes
1125** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1126** and Expr.pRight variables (but not for any structures pointed to or
1127** descended from the Expr.x.pList or Expr.x.pSelect variables).
1128*/
1129static int dupedExprSize(Expr *p, int flags){
1130 int nByte = 0;
1131 if( p ){
1132 nByte = dupedExprNodeSize(p, flags);
1133 if( flags&EXPRDUP_REDUCE ){
drhb7916a72009-05-27 10:31:29 +00001134 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001135 }
1136 }
1137 return nByte;
1138}
1139
1140/*
1141** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1142** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +00001143** to store the copy of expression p, the copies of p->u.zToken
danielk19776ab3a2e2009-02-19 14:39:25 +00001144** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +00001145** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +00001146** portion of the buffer copied into by this function.
1147*/
drh3c194692016-04-11 16:43:43 +00001148static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1149 Expr *pNew; /* Value to return */
1150 u8 *zAlloc; /* Memory space from which to build Expr object */
1151 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1152
drh575fad62016-02-05 13:38:36 +00001153 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +00001154 assert( p );
1155 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1156 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +00001157
drh3c194692016-04-11 16:43:43 +00001158 /* Figure out where to write the new Expr structure. */
1159 if( pzBuffer ){
1160 zAlloc = *pzBuffer;
1161 staticFlag = EP_Static;
1162 }else{
1163 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1164 staticFlag = 0;
1165 }
1166 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001167
drh3c194692016-04-11 16:43:43 +00001168 if( pNew ){
1169 /* Set nNewSize to the size allocated for the structure pointed to
1170 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1171 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1172 ** by the copy of the p->u.zToken string (if any).
1173 */
1174 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1175 const int nNewSize = nStructSize & 0xfff;
1176 int nToken;
1177 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1178 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001179 }else{
drh3c194692016-04-11 16:43:43 +00001180 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001181 }
drh3c194692016-04-11 16:43:43 +00001182 if( dupFlags ){
1183 assert( ExprHasProperty(p, EP_Reduced)==0 );
1184 memcpy(zAlloc, p, nNewSize);
1185 }else{
1186 u32 nSize = (u32)exprStructSize(p);
1187 memcpy(zAlloc, p, nSize);
1188 if( nSize<EXPR_FULLSIZE ){
1189 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1190 }
1191 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001192
drh3c194692016-04-11 16:43:43 +00001193 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1194 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1195 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1196 pNew->flags |= staticFlag;
1197
1198 /* Copy the p->u.zToken string, if any. */
1199 if( nToken ){
1200 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1201 memcpy(zToken, p->u.zToken, nToken);
1202 }
1203
1204 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
1205 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1206 if( ExprHasProperty(p, EP_xIsSelect) ){
1207 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001208 }else{
drh3c194692016-04-11 16:43:43 +00001209 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001210 }
drh3c194692016-04-11 16:43:43 +00001211 }
1212
1213 /* Fill in pNew->pLeft and pNew->pRight. */
1214 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1215 zAlloc += dupedExprNodeSize(p, dupFlags);
1216 if( ExprHasProperty(pNew, EP_Reduced) ){
1217 pNew->pLeft = p->pLeft ?
1218 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1219 pNew->pRight = p->pRight ?
1220 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001221 }
drh3c194692016-04-11 16:43:43 +00001222 if( pzBuffer ){
1223 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001224 }
drh3c194692016-04-11 16:43:43 +00001225 }else{
1226 if( !ExprHasProperty(p, EP_TokenOnly) ){
drh98542602016-08-20 17:00:16 +00001227 if( pNew->op==TK_SELECT_COLUMN ){
1228 pNew->pLeft = p->pLeft;
1229 }else{
1230 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1231 }
drh3c194692016-04-11 16:43:43 +00001232 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
danielk19776ab3a2e2009-02-19 14:39:25 +00001233 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001234 }
1235 }
1236 return pNew;
1237}
1238
1239/*
danbfe31e72014-01-15 14:17:31 +00001240** Create and return a deep copy of the object passed as the second
1241** argument. If an OOM condition is encountered, NULL is returned
1242** and the db->mallocFailed flag set.
1243*/
daneede6a52014-01-15 19:42:23 +00001244#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +00001245static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +00001246 With *pRet = 0;
1247 if( p ){
1248 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1249 pRet = sqlite3DbMallocZero(db, nByte);
1250 if( pRet ){
1251 int i;
1252 pRet->nCte = p->nCte;
1253 for(i=0; i<p->nCte; i++){
1254 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1255 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1256 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1257 }
1258 }
1259 }
1260 return pRet;
1261}
daneede6a52014-01-15 19:42:23 +00001262#else
1263# define withDup(x,y) 0
1264#endif
dan4e9119d2014-01-13 15:12:23 +00001265
drha76b5df2002-02-23 02:32:10 +00001266/*
drhff78bd22002-02-27 01:47:11 +00001267** The following group of routines make deep copies of expressions,
1268** expression lists, ID lists, and select statements. The copies can
1269** be deleted (by being passed to their respective ...Delete() routines)
1270** without effecting the originals.
1271**
danielk19774adee202004-05-08 08:23:19 +00001272** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1273** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +00001274** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001275**
drhad3cab52002-05-24 02:04:32 +00001276** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001277**
drhb7916a72009-05-27 10:31:29 +00001278** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001279** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1280** truncated version of the usual Expr structure that will be stored as
1281** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001282*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001283Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001284 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001285 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001286}
danielk19776ab3a2e2009-02-19 14:39:25 +00001287ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001288 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001289 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001290 int i;
drh575fad62016-02-05 13:38:36 +00001291 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001292 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001293 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001294 if( pNew==0 ) return 0;
drhd872bb12012-02-02 01:58:08 +00001295 pNew->nExpr = i = p->nExpr;
1296 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
drh575fad62016-02-05 13:38:36 +00001297 pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +00001298 if( pItem==0 ){
drh633e6d52008-07-28 19:34:53 +00001299 sqlite3DbFree(db, pNew);
danielk1977e0048402004-06-15 16:51:01 +00001300 return 0;
1301 }
drh145716b2004-09-24 12:24:06 +00001302 pOldItem = p->a;
1303 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001304 Expr *pOldExpr = pOldItem->pExpr;
drhb5526ea2009-07-16 12:41:05 +00001305 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh17435752007-08-16 04:30:38 +00001306 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001307 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001308 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001309 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001310 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
drhc2acc4e2013-11-15 18:15:19 +00001311 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001312 }
1313 return pNew;
1314}
danielk197793758c82005-01-21 08:13:14 +00001315
1316/*
1317** If cursors, triggers, views and subqueries are all omitted from
1318** the build, then none of the following routines, except for
1319** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1320** called with a NULL argument.
1321*/
danielk19776a67fe82005-02-04 04:07:16 +00001322#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1323 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001324SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001325 SrcList *pNew;
1326 int i;
drh113088e2003-03-20 01:16:58 +00001327 int nByte;
drh575fad62016-02-05 13:38:36 +00001328 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001329 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001330 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001331 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001332 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001333 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001334 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001335 struct SrcList_item *pNewItem = &pNew->a[i];
1336 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001337 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001338 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001339 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1340 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1341 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001342 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001343 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001344 pNewItem->addrFillSub = pOldItem->addrFillSub;
1345 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001346 if( pNewItem->fg.isIndexedBy ){
1347 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1348 }
1349 pNewItem->pIBIndex = pOldItem->pIBIndex;
1350 if( pNewItem->fg.isTabFunc ){
1351 pNewItem->u1.pFuncArg =
1352 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1353 }
drhed8a3bb2005-06-06 21:19:56 +00001354 pTab = pNewItem->pTab = pOldItem->pTab;
1355 if( pTab ){
1356 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001357 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001358 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1359 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001360 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001361 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001362 }
1363 return pNew;
1364}
drh17435752007-08-16 04:30:38 +00001365IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001366 IdList *pNew;
1367 int i;
drh575fad62016-02-05 13:38:36 +00001368 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001369 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001370 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001371 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001372 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001373 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001374 if( pNew->a==0 ){
drh633e6d52008-07-28 19:34:53 +00001375 sqlite3DbFree(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001376 return 0;
1377 }
drh6c535152012-02-02 03:38:30 +00001378 /* Note that because the size of the allocation for p->a[] is not
1379 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1380 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001381 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001382 struct IdList_item *pNewItem = &pNew->a[i];
1383 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001384 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001385 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001386 }
1387 return pNew;
1388}
danielk19776ab3a2e2009-02-19 14:39:25 +00001389Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
drh23b1b372011-12-07 01:55:51 +00001390 Select *pNew, *pPrior;
drh575fad62016-02-05 13:38:36 +00001391 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001392 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001393 pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +00001394 if( pNew==0 ) return 0;
drhb7916a72009-05-27 10:31:29 +00001395 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001396 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1397 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1398 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1399 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1400 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
drhff78bd22002-02-27 01:47:11 +00001401 pNew->op = p->op;
drh23b1b372011-12-07 01:55:51 +00001402 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
1403 if( pPrior ) pPrior->pNext = pNew;
1404 pNew->pNext = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001405 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1406 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
drh92b01d52008-06-24 00:32:35 +00001407 pNew->iLimit = 0;
1408 pNew->iOffset = 0;
drh7d10d5a2008-08-20 16:35:10 +00001409 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
drhb9bb7c12006-06-11 23:41:55 +00001410 pNew->addrOpenEphm[0] = -1;
1411 pNew->addrOpenEphm[1] = -1;
drhec2da852014-01-29 01:46:12 +00001412 pNew->nSelectRow = p->nSelectRow;
dan4e9119d2014-01-13 15:12:23 +00001413 pNew->pWith = withDup(db, p->pWith);
drheb9b8842014-09-21 00:27:26 +00001414 sqlite3SelectSetName(pNew, p->zSelName);
drhff78bd22002-02-27 01:47:11 +00001415 return pNew;
1416}
danielk197793758c82005-01-21 08:13:14 +00001417#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001418Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001419 assert( p==0 );
1420 return 0;
1421}
1422#endif
drhff78bd22002-02-27 01:47:11 +00001423
1424
1425/*
drha76b5df2002-02-23 02:32:10 +00001426** Add a new element to the end of an expression list. If pList is
1427** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001428**
1429** If a memory allocation error occurs, the entire list is freed and
1430** NULL is returned. If non-NULL is returned, then it is guaranteed
1431** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001432*/
drh17435752007-08-16 04:30:38 +00001433ExprList *sqlite3ExprListAppend(
1434 Parse *pParse, /* Parsing context */
1435 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001436 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001437){
1438 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001439 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001440 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001441 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001442 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001443 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001444 }
drhc263f7c2016-01-18 13:18:54 +00001445 pList->nExpr = 0;
drh575fad62016-02-05 13:38:36 +00001446 pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
drhd872bb12012-02-02 01:58:08 +00001447 if( pList->a==0 ) goto no_mem;
1448 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001449 struct ExprList_item *a;
drhd872bb12012-02-02 01:58:08 +00001450 assert( pList->nExpr>0 );
1451 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001452 if( a==0 ){
1453 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001454 }
danielk1977d5d56522005-03-16 12:15:20 +00001455 pList->a = a;
drha76b5df2002-02-23 02:32:10 +00001456 }
drh4efc4752004-01-16 15:55:37 +00001457 assert( pList->a!=0 );
drhb7916a72009-05-27 10:31:29 +00001458 if( 1 ){
drh4efc4752004-01-16 15:55:37 +00001459 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1460 memset(pItem, 0, sizeof(*pItem));
danielk1977e94ddc92005-03-21 03:53:38 +00001461 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001462 }
1463 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001464
1465no_mem:
1466 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001467 sqlite3ExprDelete(db, pExpr);
1468 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001469 return 0;
drha76b5df2002-02-23 02:32:10 +00001470}
1471
1472/*
drh8762ec12016-08-20 01:06:22 +00001473** pColumns and pExpr form a vector assignment which is part of the SET
1474** clause of an UPDATE statement. Like this:
drha1251bc2016-08-20 00:51:37 +00001475**
1476** (a,b,c) = (expr1,expr2,expr3)
1477** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1478**
1479** For each term of the vector assignment, append new entries to the
drh8762ec12016-08-20 01:06:22 +00001480** expression list pList. In the case of a subquery on the LHS, append
drha1251bc2016-08-20 00:51:37 +00001481** TK_SELECT_COLUMN expressions.
1482*/
1483ExprList *sqlite3ExprListAppendVector(
1484 Parse *pParse, /* Parsing context */
1485 ExprList *pList, /* List to which to append. Might be NULL */
1486 IdList *pColumns, /* List of names of LHS of the assignment */
1487 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1488){
1489 sqlite3 *db = pParse->db;
1490 int n;
1491 int i;
1492 if( pColumns==0 ) goto vector_append_error;
1493 if( pExpr==0 ) goto vector_append_error;
1494 n = sqlite3ExprVectorSize(pExpr);
1495 if( pColumns->nId!=n ){
1496 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1497 pColumns->nId, n);
1498 goto vector_append_error;
1499 }
1500 for(i=0; i<n; i++){
1501 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1502 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1503 if( pList ){
1504 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1505 pColumns->a[i].zName = 0;
1506 }
1507 }
1508 if( pExpr->op==TK_SELECT ){
1509 if( pList && pList->a[0].pExpr ){
1510 assert( pList->a[0].pExpr->op==TK_SELECT_COLUMN );
1511 pList->a[0].pExpr->pRight = pExpr;
1512 pExpr = 0;
1513 }
1514 }
1515
1516vector_append_error:
1517 sqlite3ExprDelete(db, pExpr);
1518 sqlite3IdListDelete(db, pColumns);
1519 return pList;
1520}
1521
1522/*
drhbc622bc2015-08-24 15:39:42 +00001523** Set the sort order for the last element on the given ExprList.
1524*/
1525void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1526 if( p==0 ) return;
1527 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1528 assert( p->nExpr>0 );
1529 if( iSortOrder<0 ){
1530 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1531 return;
1532 }
1533 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001534}
1535
1536/*
drhb7916a72009-05-27 10:31:29 +00001537** Set the ExprList.a[].zName element of the most recently added item
1538** on the expression list.
1539**
1540** pList might be NULL following an OOM error. But pName should never be
1541** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1542** is set.
1543*/
1544void sqlite3ExprListSetName(
1545 Parse *pParse, /* Parsing context */
1546 ExprList *pList, /* List to which to add the span. */
1547 Token *pName, /* Name to be added */
1548 int dequote /* True to cause the name to be dequoted */
1549){
1550 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1551 if( pList ){
1552 struct ExprList_item *pItem;
1553 assert( pList->nExpr>0 );
1554 pItem = &pList->a[pList->nExpr-1];
1555 assert( pItem->zName==0 );
1556 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001557 if( dequote ) sqlite3Dequote(pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001558 }
1559}
1560
1561/*
1562** Set the ExprList.a[].zSpan element of the most recently added item
1563** on the expression list.
1564**
1565** pList might be NULL following an OOM error. But pSpan should never be
1566** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1567** is set.
1568*/
1569void sqlite3ExprListSetSpan(
1570 Parse *pParse, /* Parsing context */
1571 ExprList *pList, /* List to which to add the span. */
1572 ExprSpan *pSpan /* The span to be added */
1573){
1574 sqlite3 *db = pParse->db;
1575 assert( pList!=0 || db->mallocFailed!=0 );
1576 if( pList ){
1577 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1578 assert( pList->nExpr>0 );
1579 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1580 sqlite3DbFree(db, pItem->zSpan);
1581 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001582 (int)(pSpan->zEnd - pSpan->zStart));
drhb7916a72009-05-27 10:31:29 +00001583 }
1584}
1585
1586/*
danielk19777a15a4b2007-05-08 17:54:43 +00001587** If the expression list pEList contains more than iLimit elements,
1588** leave an error message in pParse.
1589*/
1590void sqlite3ExprListCheckLength(
1591 Parse *pParse,
1592 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001593 const char *zObject
1594){
drhb1a6c3c2008-03-20 16:30:17 +00001595 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001596 testcase( pEList && pEList->nExpr==mx );
1597 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001598 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001599 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1600 }
1601}
1602
1603/*
drha76b5df2002-02-23 02:32:10 +00001604** Delete an entire expression list.
1605*/
drhaffa8552016-04-11 18:25:05 +00001606static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drha76b5df2002-02-23 02:32:10 +00001607 int i;
drhbe5c89a2004-07-26 00:31:09 +00001608 struct ExprList_item *pItem;
drhd872bb12012-02-02 01:58:08 +00001609 assert( pList->a!=0 || pList->nExpr==0 );
drhbe5c89a2004-07-26 00:31:09 +00001610 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00001611 sqlite3ExprDelete(db, pItem->pExpr);
1612 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001613 sqlite3DbFree(db, pItem->zSpan);
drha76b5df2002-02-23 02:32:10 +00001614 }
drh633e6d52008-07-28 19:34:53 +00001615 sqlite3DbFree(db, pList->a);
1616 sqlite3DbFree(db, pList);
drha76b5df2002-02-23 02:32:10 +00001617}
drhaffa8552016-04-11 18:25:05 +00001618void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1619 if( pList ) exprListDeleteNN(db, pList);
1620}
drha76b5df2002-02-23 02:32:10 +00001621
1622/*
drh2308ed32015-02-09 16:09:34 +00001623** Return the bitwise-OR of all Expr.flags fields in the given
1624** ExprList.
drh885a5b02015-02-09 15:21:36 +00001625*/
drh2308ed32015-02-09 16:09:34 +00001626u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001627 int i;
drh2308ed32015-02-09 16:09:34 +00001628 u32 m = 0;
1629 if( pList ){
1630 for(i=0; i<pList->nExpr; i++){
drhd0c73052015-04-19 19:21:19 +00001631 Expr *pExpr = pList->a[i].pExpr;
drhde845c22016-03-17 19:07:52 +00001632 assert( pExpr!=0 );
1633 m |= pExpr->flags;
drh2308ed32015-02-09 16:09:34 +00001634 }
drh885a5b02015-02-09 15:21:36 +00001635 }
drh2308ed32015-02-09 16:09:34 +00001636 return m;
drh885a5b02015-02-09 15:21:36 +00001637}
1638
1639/*
drh059b2d52014-10-24 19:28:09 +00001640** These routines are Walker callbacks used to check expressions to
1641** see if they are "constant" for some definition of constant. The
1642** Walker.eCode value determines the type of "constant" we are looking
1643** for.
drh73b211a2005-01-18 04:00:42 +00001644**
drh7d10d5a2008-08-20 16:35:10 +00001645** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001646**
drh059b2d52014-10-24 19:28:09 +00001647** sqlite3ExprIsConstant() pWalker->eCode==1
1648** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001649** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001650** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001651**
drh059b2d52014-10-24 19:28:09 +00001652** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1653** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001654**
drhfeada2d2014-09-24 13:20:22 +00001655** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001656** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1657** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001658** parameter raises an error for new statements, but is silently converted
1659** to NULL for existing schemas. This allows sqlite_master tables that
1660** contain a bound parameter because they were generated by older versions
1661** of SQLite to be parsed by newer versions of SQLite without raising a
1662** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001663*/
drh7d10d5a2008-08-20 16:35:10 +00001664static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001665
drh059b2d52014-10-24 19:28:09 +00001666 /* If pWalker->eCode is 2 then any term of the expression that comes from
1667 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001668 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001669 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1670 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001671 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001672 }
1673
drh626a8792005-01-17 22:08:19 +00001674 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001675 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001676 ** and either pWalker->eCode==4 or 5 or the function has the
1677 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001678 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001679 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001680 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001681 }else{
1682 pWalker->eCode = 0;
1683 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001684 }
drh626a8792005-01-17 22:08:19 +00001685 case TK_ID:
1686 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001687 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001688 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001689 testcase( pExpr->op==TK_ID );
1690 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001691 testcase( pExpr->op==TK_AGG_FUNCTION );
1692 testcase( pExpr->op==TK_AGG_COLUMN );
drh059b2d52014-10-24 19:28:09 +00001693 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1694 return WRC_Continue;
1695 }else{
1696 pWalker->eCode = 0;
1697 return WRC_Abort;
1698 }
drhfeada2d2014-09-24 13:20:22 +00001699 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001700 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001701 /* Silently convert bound parameters that appear inside of CREATE
1702 ** statements into a NULL when parsing the CREATE statement text out
1703 ** of the sqlite_master table */
1704 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001705 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001706 /* A bound parameter in a CREATE statement that originates from
1707 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001708 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001709 return WRC_Abort;
1710 }
1711 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001712 default:
drhb74b1012009-05-28 21:04:37 +00001713 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1714 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
drh7d10d5a2008-08-20 16:35:10 +00001715 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001716 }
1717}
danielk197762c14b32008-11-19 09:05:26 +00001718static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1719 UNUSED_PARAMETER(NotUsed);
drh059b2d52014-10-24 19:28:09 +00001720 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001721 return WRC_Abort;
1722}
drh059b2d52014-10-24 19:28:09 +00001723static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001724 Walker w;
drhaa87f9a2013-04-25 00:57:10 +00001725 memset(&w, 0, sizeof(w));
drh059b2d52014-10-24 19:28:09 +00001726 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001727 w.xExprCallback = exprNodeIsConstant;
1728 w.xSelectCallback = selectNodeIsConstant;
drh059b2d52014-10-24 19:28:09 +00001729 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001730 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001731 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001732}
drh626a8792005-01-17 22:08:19 +00001733
1734/*
drh059b2d52014-10-24 19:28:09 +00001735** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001736** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001737**
1738** For the purposes of this function, a double-quoted string (ex: "abc")
1739** is considered a variable but a single-quoted string (ex: 'abc') is
1740** a constant.
drhfef52082000-06-06 01:50:43 +00001741*/
danielk19774adee202004-05-08 08:23:19 +00001742int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001743 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001744}
1745
1746/*
drh059b2d52014-10-24 19:28:09 +00001747** Walk an expression tree. Return non-zero if the expression is constant
drh0a168372007-06-08 00:20:47 +00001748** that does no originate from the ON or USING clauses of a join.
1749** Return 0 if it involves variables or function calls or terms from
1750** an ON or USING clause.
1751*/
1752int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001753 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001754}
1755
1756/*
drhfcb9f4f2015-06-01 18:13:16 +00001757** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00001758** for any single row of the table with cursor iCur. In other words, the
1759** expression must not refer to any non-deterministic function nor any
1760** table other than iCur.
1761*/
1762int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1763 return exprIsConst(p, 3, iCur);
1764}
1765
1766/*
1767** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001768** or a function call with constant arguments. Return and 0 if there
1769** are any variables.
1770**
1771** For the purposes of this function, a double-quoted string (ex: "abc")
1772** is considered a variable but a single-quoted string (ex: 'abc') is
1773** a constant.
1774*/
drhfeada2d2014-09-24 13:20:22 +00001775int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1776 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00001777 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00001778}
1779
drh5b88bc42013-12-07 23:35:21 +00001780#ifdef SQLITE_ENABLE_CURSOR_HINTS
1781/*
1782** Walk an expression tree. Return 1 if the expression contains a
1783** subquery of some kind. Return 0 if there are no subqueries.
1784*/
1785int sqlite3ExprContainsSubquery(Expr *p){
1786 Walker w;
1787 memset(&w, 0, sizeof(w));
drhbec24762015-08-13 20:07:13 +00001788 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00001789 w.xExprCallback = sqlite3ExprWalkNoop;
1790 w.xSelectCallback = selectNodeIsConstant;
1791 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00001792 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00001793}
1794#endif
1795
drheb55bd22005-06-30 17:04:21 +00001796/*
drh73b211a2005-01-18 04:00:42 +00001797** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001798** to fit in a 32-bit integer, return 1 and put the value of the integer
1799** in *pValue. If the expression is not an integer or if it is too big
1800** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001801*/
danielk19774adee202004-05-08 08:23:19 +00001802int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00001803 int rc = 0;
drhcd92e842011-02-17 15:58:20 +00001804
1805 /* If an expression is an integer literal that fits in a signed 32-bit
1806 ** integer, then the EP_IntValue flag will have already been set */
1807 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1808 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1809
drh92b01d52008-06-24 00:32:35 +00001810 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00001811 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00001812 return 1;
1813 }
drhe4de1fe2002-06-02 16:09:01 +00001814 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00001815 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00001816 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00001817 break;
drh4b59ab52002-08-24 18:24:51 +00001818 }
drhe4de1fe2002-06-02 16:09:01 +00001819 case TK_UMINUS: {
1820 int v;
danielk19774adee202004-05-08 08:23:19 +00001821 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00001822 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00001823 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00001824 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00001825 }
1826 break;
1827 }
1828 default: break;
1829 }
drh92b01d52008-06-24 00:32:35 +00001830 return rc;
drhe4de1fe2002-06-02 16:09:01 +00001831}
1832
1833/*
drh039fc322009-11-17 18:31:47 +00001834** Return FALSE if there is no chance that the expression can be NULL.
1835**
1836** If the expression might be NULL or if the expression is too complex
1837** to tell return TRUE.
1838**
1839** This routine is used as an optimization, to skip OP_IsNull opcodes
1840** when we know that a value cannot be NULL. Hence, a false positive
1841** (returning TRUE when in fact the expression can never be NULL) might
1842** be a small performance hit but is otherwise harmless. On the other
1843** hand, a false negative (returning FALSE when the result could be NULL)
1844** will likely result in an incorrect answer. So when in doubt, return
1845** TRUE.
1846*/
1847int sqlite3ExprCanBeNull(const Expr *p){
1848 u8 op;
drhcd7f4572009-11-19 14:48:40 +00001849 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001850 op = p->op;
1851 if( op==TK_REGISTER ) op = p->op2;
1852 switch( op ){
1853 case TK_INTEGER:
1854 case TK_STRING:
1855 case TK_FLOAT:
1856 case TK_BLOB:
1857 return 0;
drh7248a8b2014-08-04 18:50:54 +00001858 case TK_COLUMN:
1859 assert( p->pTab!=0 );
drh72673a22014-12-04 16:27:17 +00001860 return ExprHasProperty(p, EP_CanBeNull) ||
1861 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00001862 default:
1863 return 1;
1864 }
1865}
1866
1867/*
1868** Return TRUE if the given expression is a constant which would be
1869** unchanged by OP_Affinity with the affinity given in the second
1870** argument.
1871**
1872** This routine is used to determine if the OP_Affinity operation
1873** can be omitted. When in doubt return FALSE. A false negative
1874** is harmless. A false positive, however, can result in the wrong
1875** answer.
1876*/
1877int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1878 u8 op;
drh05883a32015-06-02 15:32:08 +00001879 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00001880 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001881 op = p->op;
1882 if( op==TK_REGISTER ) op = p->op2;
1883 switch( op ){
1884 case TK_INTEGER: {
1885 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1886 }
1887 case TK_FLOAT: {
1888 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1889 }
1890 case TK_STRING: {
1891 return aff==SQLITE_AFF_TEXT;
1892 }
1893 case TK_BLOB: {
1894 return 1;
1895 }
drh2f2855b2009-11-18 01:25:26 +00001896 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00001897 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1898 return p->iColumn<0
1899 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00001900 }
drh039fc322009-11-17 18:31:47 +00001901 default: {
1902 return 0;
1903 }
1904 }
1905}
1906
1907/*
drhc4a3c772001-04-04 11:48:57 +00001908** Return TRUE if the given string is a row-id column name.
1909*/
danielk19774adee202004-05-08 08:23:19 +00001910int sqlite3IsRowid(const char *z){
1911 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1912 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1913 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001914 return 0;
1915}
1916
danielk19779a96b662007-11-29 17:05:18 +00001917/*
drh69c355b2016-03-09 15:34:51 +00001918** pX is the RHS of an IN operator. If pX is a SELECT statement
1919** that can be simplified to a direct table access, then return
1920** a pointer to the SELECT statement. If pX is not a SELECT statement,
1921** or if the SELECT statement needs to be manifested into a transient
1922** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00001923*/
1924#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00001925static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00001926 Select *p;
drhb287f4b2008-04-25 00:08:38 +00001927 SrcList *pSrc;
1928 ExprList *pEList;
1929 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00001930 int i;
drh69c355b2016-03-09 15:34:51 +00001931 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1932 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1933 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00001934 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00001935 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00001936 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1937 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1938 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00001939 }
drhb74b1012009-05-28 21:04:37 +00001940 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00001941 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb74b1012009-05-28 21:04:37 +00001942 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
drhb287f4b2008-04-25 00:08:38 +00001943 if( p->pWhere ) return 0; /* Has no WHERE clause */
1944 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00001945 assert( pSrc!=0 );
1946 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00001947 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00001948 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00001949 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00001950 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00001951 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1952 pEList = p->pEList;
dancfbb5e82016-07-13 19:48:13 +00001953
dan7b35a772016-07-28 19:47:15 +00001954 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00001955 for(i=0; i<pEList->nExpr; i++){
1956 Expr *pRes = pEList->a[i].pExpr;
1957 if( pRes->op!=TK_COLUMN ) return 0;
1958 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00001959 }
drh69c355b2016-03-09 15:34:51 +00001960 return p;
drhb287f4b2008-04-25 00:08:38 +00001961}
1962#endif /* SQLITE_OMIT_SUBQUERY */
1963
1964/*
dan1d8cb212011-12-09 13:24:16 +00001965** Code an OP_Once instruction and allocate space for its flag. Return the
1966** address of the new instruction.
1967*/
1968int sqlite3CodeOnce(Parse *pParse){
1969 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1970 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1971}
1972
danf9b2e052016-08-02 17:45:00 +00001973#ifndef SQLITE_OMIT_SUBQUERY
dan1d8cb212011-12-09 13:24:16 +00001974/*
drh4c259e92014-08-01 21:12:35 +00001975** Generate code that checks the left-most column of index table iCur to see if
1976** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00001977** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1978** to be set to NULL if iCur contains one or more NULL values.
1979*/
1980static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00001981 int addr1;
drh6be515e2014-08-01 21:00:53 +00001982 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00001983 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00001984 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
1985 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00001986 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00001987 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00001988}
danf9b2e052016-08-02 17:45:00 +00001989#endif
drh6be515e2014-08-01 21:00:53 +00001990
drhbb53ecb2014-08-02 21:03:33 +00001991
1992#ifndef SQLITE_OMIT_SUBQUERY
1993/*
1994** The argument is an IN operator with a list (not a subquery) on the
1995** right-hand side. Return TRUE if that list is constant.
1996*/
1997static int sqlite3InRhsIsConstant(Expr *pIn){
1998 Expr *pLHS;
1999 int res;
2000 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2001 pLHS = pIn->pLeft;
2002 pIn->pLeft = 0;
2003 res = sqlite3ExprIsConstant(pIn);
2004 pIn->pLeft = pLHS;
2005 return res;
2006}
2007#endif
2008
drh6be515e2014-08-01 21:00:53 +00002009/*
danielk19779a96b662007-11-29 17:05:18 +00002010** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00002011** The pX parameter is the expression on the RHS of the IN operator, which
2012** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00002013**
drhd4305ca2012-09-18 17:08:33 +00002014** The job of this routine is to find or create a b-tree object that can
2015** be used either to test for membership in the RHS set or to iterate through
2016** all members of the RHS set, skipping duplicates.
2017**
drh3a856252014-08-01 14:46:57 +00002018** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00002019** and pX->iTable is set to the index of that cursor.
2020**
drhb74b1012009-05-28 21:04:37 +00002021** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00002022**
drh1ccce442013-03-12 20:38:51 +00002023** IN_INDEX_ROWID - The cursor was opened on a database table.
2024** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2025** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2026** IN_INDEX_EPH - The cursor was opened on a specially created and
2027** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00002028** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2029** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00002030**
drhd4305ca2012-09-18 17:08:33 +00002031** An existing b-tree might be used if the RHS expression pX is a simple
2032** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00002033**
dan553168c2016-08-01 20:14:31 +00002034** SELECT <column1>, <column2>... FROM <table>
danielk19779a96b662007-11-29 17:05:18 +00002035**
drhd4305ca2012-09-18 17:08:33 +00002036** If the RHS of the IN operator is a list or a more complex subquery, then
2037** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00002038** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00002039** existing table.
drhd4305ca2012-09-18 17:08:33 +00002040**
drh3a856252014-08-01 14:46:57 +00002041** The inFlags parameter must contain exactly one of the bits
2042** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
2043** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
2044** fast membership test. When the IN_INDEX_LOOP bit is set, the
2045** IN index will be used to loop over all values of the RHS of the
2046** IN operator.
2047**
2048** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2049** through the set members) then the b-tree must not contain duplicates.
dan553168c2016-08-01 20:14:31 +00002050** An epheremal table must be used unless the selected columns are guaranteed
2051** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2052** a UNIQUE constraint or index.
danielk19770cdc0222008-06-26 18:04:03 +00002053**
drh3a856252014-08-01 14:46:57 +00002054** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2055** for fast set membership tests) then an epheremal table must
dan553168c2016-08-01 20:14:31 +00002056** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2057** index can be found with the specified <columns> as its left-most.
danielk19770cdc0222008-06-26 18:04:03 +00002058**
drhbb53ecb2014-08-02 21:03:33 +00002059** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2060** if the RHS of the IN operator is a list (not a subquery) then this
2061** routine might decide that creating an ephemeral b-tree for membership
2062** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2063** calling routine should implement the IN operator using a sequence
2064** of Eq or Ne comparison operations.
2065**
drhb74b1012009-05-28 21:04:37 +00002066** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00002067** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00002068** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00002069** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00002070** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00002071** to *prRhsHasNull. If there is no chance that the (...) contains a
2072** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00002073**
drhe21a6e12014-08-01 18:00:24 +00002074** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00002075** the value in that register will be NULL if the b-tree contains one or more
2076** NULL values, and it will be some non-NULL value if the b-tree contains no
2077** NULL values.
dan553168c2016-08-01 20:14:31 +00002078**
2079** If the aiMap parameter is not NULL, it must point to an array containing
2080** one element for each column returned by the SELECT statement on the RHS
2081** of the IN(...) operator. The i'th entry of the array is populated with the
2082** offset of the index column that matches the i'th column returned by the
2083** SELECT. For example, if the expression and selected index are:
2084**
2085** (?,?,?) IN (SELECT a, b, c FROM t1)
2086** CREATE INDEX i1 ON t1(b, c, a);
2087**
2088** then aiMap[] is populated with {2, 0, 1}.
danielk19779a96b662007-11-29 17:05:18 +00002089*/
danielk1977284f4ac2007-12-10 05:03:46 +00002090#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00002091int sqlite3FindInIndex(
2092 Parse *pParse,
2093 Expr *pX,
2094 u32 inFlags,
2095 int *prRhsHasNull,
2096 int *aiMap
2097){
drhb74b1012009-05-28 21:04:37 +00002098 Select *p; /* SELECT to the right of IN operator */
2099 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2100 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00002101 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00002102 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00002103
drh1450bc62009-10-30 13:25:56 +00002104 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00002105 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00002106
dan7b35a772016-07-28 19:47:15 +00002107 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2108 ** whether or not the SELECT result contains NULL values, check whether
dan870a0702016-08-01 16:37:43 +00002109 ** or not NULL is actually possible (it may not be, for example, due
dan7b35a772016-07-28 19:47:15 +00002110 ** to NOT NULL constraints in the schema). If no NULL values are possible,
dan870a0702016-08-01 16:37:43 +00002111 ** set prRhsHasNull to 0 before continuing. */
dan7b35a772016-07-28 19:47:15 +00002112 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2113 int i;
2114 ExprList *pEList = pX->x.pSelect->pEList;
2115 for(i=0; i<pEList->nExpr; i++){
2116 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2117 }
2118 if( i==pEList->nExpr ){
2119 prRhsHasNull = 0;
2120 }
2121 }
2122
drhb74b1012009-05-28 21:04:37 +00002123 /* Check to see if an existing table or index can be used to
2124 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00002125 ** ephemeral table. */
2126 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00002127 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00002128 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00002129 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00002130 ExprList *pEList = p->pEList;
2131 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00002132
drhb07028f2011-10-14 21:49:18 +00002133 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2134 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2135 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2136 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00002137
drhb22f7c82014-02-06 23:56:27 +00002138 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00002139 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2140 sqlite3CodeVerifySchema(pParse, iDb);
2141 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00002142
2143 /* This function is only called from two places. In both cases the vdbe
2144 ** has already been allocated. So assume sqlite3GetVdbe() is always
2145 ** successful here.
2146 */
2147 assert(v);
dancfbb5e82016-07-13 19:48:13 +00002148 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh7d176102014-02-18 03:07:12 +00002149 int iAddr = sqlite3CodeOnce(pParse);
2150 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002151
2152 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2153 eType = IN_INDEX_ROWID;
2154
2155 sqlite3VdbeJumpHere(v, iAddr);
2156 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002157 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002158 int affinity_ok = 1;
2159 int i;
2160
2161 /* Check that the affinity that will be used to perform each
2162 ** comparison is the same as the affinity of each column. If
2163 ** it not, it is not possible to use any index. */
2164 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002165 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002166 int iCol = pEList->a[i].pExpr->iColumn;
2167 char idxaff = pTab->aCol[iCol].affinity;
2168 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2169 switch( cmpaff ){
2170 case SQLITE_AFF_BLOB:
2171 break;
2172 case SQLITE_AFF_TEXT:
2173 affinity_ok = (idxaff==SQLITE_AFF_TEXT);
2174 break;
2175 default:
2176 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2177 }
2178 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002179
drhb74b1012009-05-28 21:04:37 +00002180 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00002181 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00002182 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00002183
2184 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
dancfbb5e82016-07-13 19:48:13 +00002185 if( pIdx->nKeyCol<nExpr ) continue;
2186 if( mustBeUnique && (pIdx->nKeyCol!=nExpr || !IsUniqueIndex(pIdx)) ){
2187 continue;
2188 }
2189
2190 for(i=0; i<nExpr; i++){
drhfc7f27b2016-08-20 00:07:01 +00002191 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002192 Expr *pRhs = pEList->a[i].pExpr;
2193 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2194 int j;
2195
dan17994e32016-08-11 12:01:52 +00002196 assert( pReq || pParse->nErr );
2197 if( pReq==0 ) break;
2198
dancfbb5e82016-07-13 19:48:13 +00002199 for(j=0; j<nExpr; j++){
2200 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2201 assert( pIdx->azColl[j] );
2202 if( sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ) continue;
2203 break;
2204 }
2205 if( j==nExpr ) break;
danba00e302016-07-23 20:24:06 +00002206 if( aiMap ) aiMap[i] = j;
dancfbb5e82016-07-13 19:48:13 +00002207 }
2208
2209 if( i==nExpr ){
drh7d176102014-02-18 03:07:12 +00002210 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00002211 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2212 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00002213 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00002214 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2215 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00002216
dan7b35a772016-07-28 19:47:15 +00002217 if( prRhsHasNull ){
2218 *prRhsHasNull = ++pParse->nMem;
dan3480bfd2016-06-16 17:14:02 +00002219#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
dancfbb5e82016-07-13 19:48:13 +00002220 i64 mask = (1<<nExpr)-1;
dan3480bfd2016-06-16 17:14:02 +00002221 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
dancfbb5e82016-07-13 19:48:13 +00002222 iTab, 0, 0, (u8*)&mask, P4_INT64);
dan3480bfd2016-06-16 17:14:02 +00002223#endif
dan7b35a772016-07-28 19:47:15 +00002224 if( nExpr==1 ){
2225 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2226 }
danielk19770cdc0222008-06-26 18:04:03 +00002227 }
drh552fd452014-02-18 01:07:38 +00002228 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00002229 }
2230 }
2231 }
2232 }
2233
drhbb53ecb2014-08-02 21:03:33 +00002234 /* If no preexisting index is available for the IN clause
2235 ** and IN_INDEX_NOOP is an allowed reply
2236 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002237 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002238 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002239 ** the IN operator so return IN_INDEX_NOOP.
2240 */
2241 if( eType==0
2242 && (inFlags & IN_INDEX_NOOP_OK)
2243 && !ExprHasProperty(pX, EP_xIsSelect)
2244 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2245 ){
2246 eType = IN_INDEX_NOOP;
2247 }
drhbb53ecb2014-08-02 21:03:33 +00002248
danielk19779a96b662007-11-29 17:05:18 +00002249 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002250 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002251 ** We will have to generate an ephemeral table to do the job.
2252 */
drh8e23daf2013-06-11 13:30:04 +00002253 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002254 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002255 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002256 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002257 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00002258 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00002259 eType = IN_INDEX_ROWID;
2260 }
drhe21a6e12014-08-01 18:00:24 +00002261 }else if( prRhsHasNull ){
2262 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002263 }
danielk197741a05b72008-10-02 13:50:55 +00002264 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002265 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002266 }else{
2267 pX->iTable = iTab;
2268 }
danba00e302016-07-23 20:24:06 +00002269
2270 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2271 int i, n;
2272 n = sqlite3ExprVectorSize(pX->pLeft);
2273 for(i=0; i<n; i++) aiMap[i] = i;
2274 }
danielk19779a96b662007-11-29 17:05:18 +00002275 return eType;
2276}
danielk1977284f4ac2007-12-10 05:03:46 +00002277#endif
drh626a8792005-01-17 22:08:19 +00002278
danf9b2e052016-08-02 17:45:00 +00002279#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002280/*
2281** Argument pExpr is an (?, ?...) IN(...) expression. This
2282** function allocates and returns a nul-terminated string containing
2283** the affinities to be used for each column of the comparison.
2284**
2285** It is the responsibility of the caller to ensure that the returned
2286** string is eventually freed using sqlite3DbFree().
2287*/
dan71c57db2016-07-09 20:23:55 +00002288static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2289 Expr *pLeft = pExpr->pLeft;
2290 int nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002291 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002292 char *zRet;
2293
dan553168c2016-08-01 20:14:31 +00002294 assert( pExpr->op==TK_IN );
dan71c57db2016-07-09 20:23:55 +00002295 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2296 if( zRet ){
2297 int i;
2298 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002299 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002300 char a = sqlite3ExprAffinity(pA);
2301 if( pSelect ){
2302 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2303 }else{
2304 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002305 }
dan71c57db2016-07-09 20:23:55 +00002306 }
2307 zRet[nVal] = '\0';
2308 }
2309 return zRet;
2310}
danf9b2e052016-08-02 17:45:00 +00002311#endif
dan71c57db2016-07-09 20:23:55 +00002312
dan8da209b2016-07-26 18:06:08 +00002313#ifndef SQLITE_OMIT_SUBQUERY
2314/*
2315** Load the Parse object passed as the first argument with an error
2316** message of the form:
2317**
2318** "sub-select returns N columns - expected M"
2319*/
2320void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2321 const char *zFmt = "sub-select returns %d columns - expected %d";
2322 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2323}
2324#endif
2325
drh626a8792005-01-17 22:08:19 +00002326/*
drhd4187c72010-08-30 22:15:45 +00002327** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2328** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002329**
drh9cbe6352005-11-29 03:13:21 +00002330** (SELECT a FROM b) -- subquery
2331** EXISTS (SELECT a FROM b) -- EXISTS subquery
2332** x IN (4,5,11) -- IN operator with list on right-hand side
2333** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002334**
drh9cbe6352005-11-29 03:13:21 +00002335** The pExpr parameter describes the expression that contains the IN
2336** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002337**
2338** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2339** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2340** to some integer key column of a table B-Tree. In this case, use an
2341** intkey B-Tree to store the set of IN(...) values instead of the usual
2342** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002343**
2344** If rMayHaveNull is non-zero, that means that the operation is an IN
2345** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002346** All this routine does is initialize the register given by rMayHaveNull
2347** to NULL. Calling routines will take care of changing this register
2348** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002349**
2350** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002351** result. For a multi-column SELECT, the result is stored in a contiguous
2352** array of registers and the return value is the register of the left-most
2353** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002354*/
drh51522cd2005-01-20 13:36:19 +00002355#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002356int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002357 Parse *pParse, /* Parsing context */
2358 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002359 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002360 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002361){
drh6be515e2014-08-01 21:00:53 +00002362 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002363 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002364 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002365 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00002366 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002367
drh39a11812016-08-19 19:12:58 +00002368 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2369 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002370 **
2371 ** * The right-hand side is a correlated subquery
2372 ** * The right-hand side is an expression list containing variables
2373 ** * We are inside a trigger
2374 **
2375 ** If all of the above are false, then we can run this code just once
2376 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002377 */
drhc5cd1242013-09-12 16:50:49 +00002378 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00002379 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002380 }
2381
dan4a07e3d2010-11-09 14:48:59 +00002382#ifndef SQLITE_OMIT_EXPLAIN
2383 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00002384 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2385 jmpIfDynamic>=0?"":"CORRELATED ",
2386 pExpr->op==TK_IN?"LIST":"SCALAR",
2387 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00002388 );
2389 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2390 }
2391#endif
2392
drhcce7d172000-05-31 15:34:51 +00002393 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002394 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002395 int addr; /* Address of OP_OpenEphemeral instruction */
2396 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002397 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002398 int nVal; /* Size of vector pLeft */
2399
2400 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002401 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002402
2403 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002404 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002405 ** filled with index keys representing the results from the
2406 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002407 **
2408 ** If the 'x' expression is a column value, or the SELECT...
2409 ** statement returns a column value, then the affinity of that
2410 ** column is used to build the index keys. If both 'x' and the
2411 ** SELECT... statement are columns, then numeric affinity is used
2412 ** if either column has NUMERIC or INTEGER affinity. If neither
2413 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2414 ** is used.
2415 */
2416 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002417 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2418 pExpr->iTable, (isRowid?0:nVal));
2419 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002420
danielk19776ab3a2e2009-02-19 14:39:25 +00002421 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00002422 /* Case 1: expr IN (SELECT ...)
2423 **
danielk1977e014a832004-05-17 10:48:57 +00002424 ** Generate code to write the results of the select into the temporary
2425 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002426 */
drh43870062014-07-31 15:44:44 +00002427 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002428 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002429
danielk197741a05b72008-10-02 13:50:55 +00002430 assert( !isRowid );
dan71c57db2016-07-09 20:23:55 +00002431 if( pEList->nExpr!=nVal ){
dan8da209b2016-07-26 18:06:08 +00002432 sqlite3SubselectError(pParse, pEList->nExpr, nVal);
dan71c57db2016-07-09 20:23:55 +00002433 }else{
2434 SelectDest dest;
2435 int i;
2436 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2437 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2438 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2439 pSelect->iLimit = 0;
2440 testcase( pSelect->selFlags & SF_Distinct );
2441 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2442 if( sqlite3Select(pParse, pSelect, &dest) ){
2443 sqlite3DbFree(pParse->db, dest.zAffSdst);
2444 sqlite3KeyInfoUnref(pKeyInfo);
2445 return 0;
2446 }
2447 sqlite3DbFree(pParse->db, dest.zAffSdst);
2448 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2449 assert( pEList!=0 );
2450 assert( pEList->nExpr>0 );
2451 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2452 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002453 Expr *p = (nVal>1) ? sqlite3VectorFieldSubexpr(pLeft, i) : pLeft;
dan71c57db2016-07-09 20:23:55 +00002454 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2455 pParse, p, pEList->a[i].pExpr
2456 );
2457 }
drh94ccde52007-04-13 16:06:32 +00002458 }
drha7d2db12010-07-14 20:23:52 +00002459 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002460 /* Case 2: expr IN (exprlist)
2461 **
drhfd131da2007-08-07 17:13:03 +00002462 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002463 ** store it in the temporary table. If <expr> is a column, then use
2464 ** that columns affinity when building index keys. If <expr> is not
2465 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002466 */
dan71c57db2016-07-09 20:23:55 +00002467 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002468 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002469 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002470 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002471 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002472
dan71c57db2016-07-09 20:23:55 +00002473 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002474 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002475 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002476 }
drh323df792013-08-05 19:11:29 +00002477 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002478 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002479 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2480 }
danielk1977e014a832004-05-17 10:48:57 +00002481
2482 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002483 r1 = sqlite3GetTempReg(pParse);
2484 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002485 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002486 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2487 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002488 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002489
drh57dbd7b2005-07-08 18:25:26 +00002490 /* If the expression is not constant then we will need to
2491 ** disable the test that was generated above that makes sure
2492 ** this code only executes once. Because for a non-constant
2493 ** expression we need to rerun this code each time.
2494 */
drh6be515e2014-08-01 21:00:53 +00002495 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2496 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2497 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002498 }
danielk1977e014a832004-05-17 10:48:57 +00002499
2500 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002501 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2502 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002503 }else{
drhe05c9292009-10-29 13:48:10 +00002504 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2505 if( isRowid ){
2506 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2507 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002508 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002509 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2510 }else{
2511 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2512 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2513 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2514 }
danielk197741a05b72008-10-02 13:50:55 +00002515 }
drhfef52082000-06-06 01:50:43 +00002516 }
drh2d401ab2008-01-10 23:50:11 +00002517 sqlite3ReleaseTempReg(pParse, r1);
2518 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002519 }
drh323df792013-08-05 19:11:29 +00002520 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002521 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002522 }
danielk1977b3bce662005-01-29 08:32:43 +00002523 break;
drhfef52082000-06-06 01:50:43 +00002524 }
2525
drh51522cd2005-01-20 13:36:19 +00002526 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002527 case TK_SELECT:
2528 default: {
drh39a11812016-08-19 19:12:58 +00002529 /* Case 3: (SELECT ... FROM ...)
2530 ** or: EXISTS(SELECT ... FROM ...)
2531 **
2532 ** For a SELECT, generate code to put the values for all columns of
2533 ** the first row into an array of registers and return the index of
2534 ** the first register.
2535 **
2536 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2537 ** into a register and return that register number.
2538 **
2539 ** In both cases, the query is augmented with "LIMIT 1". Any
2540 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002541 */
drhfd773cf2009-05-29 14:39:07 +00002542 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002543 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002544 int nReg; /* Registers to allocate */
drh1398ad32005-01-19 23:24:50 +00002545
shanecf697392009-06-01 16:53:09 +00002546 testcase( pExpr->op==TK_EXISTS );
2547 testcase( pExpr->op==TK_SELECT );
2548 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
danielk19776ab3a2e2009-02-19 14:39:25 +00002549 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
dan71c57db2016-07-09 20:23:55 +00002550
danielk19776ab3a2e2009-02-19 14:39:25 +00002551 pSel = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002552 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2553 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2554 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002555 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002556 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002557 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002558 dest.nSdst = nReg;
2559 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002560 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002561 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002562 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002563 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002564 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002565 }
drh633e6d52008-07-28 19:34:53 +00002566 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002567 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2568 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002569 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002570 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002571 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002572 return 0;
drh94ccde52007-04-13 16:06:32 +00002573 }
drh2b596da2012-07-23 21:43:19 +00002574 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002575 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002576 break;
drhcce7d172000-05-31 15:34:51 +00002577 }
2578 }
danielk1977b3bce662005-01-29 08:32:43 +00002579
drh6be515e2014-08-01 21:00:53 +00002580 if( rHasNullFlag ){
2581 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002582 }
drh6be515e2014-08-01 21:00:53 +00002583
2584 if( jmpIfDynamic>=0 ){
2585 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002586 }
drhd2490902014-04-13 19:28:15 +00002587 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002588
drh1450bc62009-10-30 13:25:56 +00002589 return rReg;
drhcce7d172000-05-31 15:34:51 +00002590}
drh51522cd2005-01-20 13:36:19 +00002591#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002592
drhe3365e62009-11-12 17:52:24 +00002593#ifndef SQLITE_OMIT_SUBQUERY
2594/*
dan7b35a772016-07-28 19:47:15 +00002595** Expr pIn is an IN(...) expression. This function checks that the
2596** sub-select on the RHS of the IN() operator has the same number of
2597** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2598** a sub-query, that the LHS is a vector of size 1.
2599*/
2600int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2601 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2602 if( (pIn->flags & EP_xIsSelect) ){
2603 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2604 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2605 return 1;
2606 }
2607 }else if( nVector!=1 ){
2608 if( (pIn->pLeft->flags & EP_xIsSelect) ){
2609 sqlite3SubselectError(pParse, nVector, 1);
2610 }else{
2611 sqlite3ErrorMsg(pParse, "invalid use of row value");
2612 }
2613 return 1;
2614 }
2615 return 0;
2616}
2617#endif
2618
2619#ifndef SQLITE_OMIT_SUBQUERY
2620/*
drhe3365e62009-11-12 17:52:24 +00002621** Generate code for an IN expression.
2622**
2623** x IN (SELECT ...)
2624** x IN (value, value, ...)
2625**
2626** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
2627** is an array of zero or more values. The expression is true if the LHS is
2628** contained within the RHS. The value of the expression is unknown (NULL)
2629** if the LHS is NULL or if the LHS is not contained within the RHS and the
2630** RHS contains one or more NULL values.
2631**
drh6be515e2014-08-01 21:00:53 +00002632** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002633** contained within the RHS. If due to NULLs we cannot determine if the LHS
2634** is contained in the RHS then jump to destIfNull. If the LHS is contained
2635** within the RHS then fall through.
2636*/
2637static void sqlite3ExprCodeIN(
2638 Parse *pParse, /* Parsing and code generating context */
2639 Expr *pExpr, /* The IN expression */
2640 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2641 int destIfNull /* Jump here if the results are unknown due to NULLs */
2642){
2643 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002644 int eType; /* Type of the RHS */
drh12abf402016-08-22 14:30:05 +00002645 int r1, r2; /* Temporary use registers */
drhe3365e62009-11-12 17:52:24 +00002646 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002647 int *aiMap = 0; /* Map from vector field to index column */
2648 char *zAff = 0; /* Affinity string for comparisons */
2649 int nVector; /* Size of vectors for this IN(...) op */
drh12abf402016-08-22 14:30:05 +00002650 int iDummy; /* Dummy parameter to exprCodeVector() */
danba00e302016-07-23 20:24:06 +00002651 Expr *pLeft = pExpr->pLeft;
2652 int i;
drhe3365e62009-11-12 17:52:24 +00002653
dan7b35a772016-07-28 19:47:15 +00002654 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00002655 zAff = exprINAffinity(pParse, pExpr);
drha48d7e72016-08-12 11:01:20 +00002656 if( zAff==0 ) return;
danba00e302016-07-23 20:24:06 +00002657 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2658 aiMap = (int*)sqlite3DbMallocZero(
2659 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2660 );
drha48d7e72016-08-12 11:01:20 +00002661 if( aiMap==0 ){
2662 sqlite3DbFree(pParse->db, zAff);
dan553168c2016-08-01 20:14:31 +00002663 return;
2664 }
dan7b35a772016-07-28 19:47:15 +00002665
danba00e302016-07-23 20:24:06 +00002666 /* Attempt to compute the RHS. After this step, if anything other than
2667 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2668 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2669 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00002670 v = pParse->pVdbe;
2671 assert( v!=0 ); /* OOM detected prior to this routine */
2672 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002673 eType = sqlite3FindInIndex(pParse, pExpr,
2674 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00002675 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00002676
danba00e302016-07-23 20:24:06 +00002677 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2678 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2679 );
drhe3365e62009-11-12 17:52:24 +00002680
danba00e302016-07-23 20:24:06 +00002681 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2682 ** vector, then it is stored in an array of nVector registers starting
2683 ** at r1.
drhe3365e62009-11-12 17:52:24 +00002684 */
danba00e302016-07-23 20:24:06 +00002685 r1 = sqlite3GetTempRange(pParse, nVector);
drhe3365e62009-11-12 17:52:24 +00002686 sqlite3ExprCachePush(pParse);
drh12abf402016-08-22 14:30:05 +00002687 r2 = exprCodeVector(pParse, pLeft, &iDummy);
2688 for(i=0; i<nVector; i++){
2689 sqlite3VdbeAddOp3(v, OP_Copy, r2+i, r1+aiMap[i], 0);
danba00e302016-07-23 20:24:06 +00002690 }
drhe3365e62009-11-12 17:52:24 +00002691
drhbb53ecb2014-08-02 21:03:33 +00002692 /* If sqlite3FindInIndex() did not find or create an index that is
2693 ** suitable for evaluating the IN operator, then evaluate using a
2694 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002695 */
drhbb53ecb2014-08-02 21:03:33 +00002696 if( eType==IN_INDEX_NOOP ){
2697 ExprList *pList = pExpr->x.pList;
2698 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2699 int labelOk = sqlite3VdbeMakeLabel(v);
2700 int r2, regToFree;
2701 int regCkNull = 0;
2702 int ii;
2703 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002704 if( destIfNull!=destIfFalse ){
2705 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002706 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002707 }
2708 for(ii=0; ii<pList->nExpr; ii++){
2709 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002710 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002711 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2712 }
2713 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2714 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002715 (void*)pColl, P4_COLLSEQ);
2716 VdbeCoverageIf(v, ii<pList->nExpr-1);
2717 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00002718 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00002719 }else{
2720 assert( destIfNull==destIfFalse );
2721 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2722 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00002723 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00002724 }
2725 sqlite3ReleaseTempReg(pParse, regToFree);
2726 }
2727 if( regCkNull ){
2728 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002729 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002730 }
2731 sqlite3VdbeResolveLabel(v, labelOk);
2732 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002733 }else{
drhbb53ecb2014-08-02 21:03:33 +00002734
dan7b35a772016-07-28 19:47:15 +00002735 /* If any value on the LHS is NULL, the result of the IN(...) operator
2736 ** must be either false or NULL. If these two are handled identically,
2737 ** test the LHS for NULLs and jump directly to destIfNull if any are
2738 ** found.
2739 **
2740 ** Otherwise, if NULL and false are handled differently, and the
2741 ** IN(...) operation is not a vector operation, and the LHS of the
2742 ** operator is NULL, then the result is false if the index is
2743 ** completely empty, or NULL otherwise. */
dand49fd4e2016-07-27 19:33:04 +00002744 if( destIfNull==destIfFalse ){
2745 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002746 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dand49fd4e2016-07-27 19:33:04 +00002747 if( sqlite3ExprCanBeNull(p) ){
2748 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002749 VdbeCoverage(v);
dand49fd4e2016-07-27 19:33:04 +00002750 }
drh7248a8b2014-08-04 18:50:54 +00002751 }
dand49fd4e2016-07-27 19:33:04 +00002752 }else if( nVector==1 && sqlite3ExprCanBeNull(pExpr->pLeft) ){
2753 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2754 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2755 VdbeCoverage(v);
2756 sqlite3VdbeGoto(v, destIfNull);
2757 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002758 }
2759
2760 if( eType==IN_INDEX_ROWID ){
dan7b35a772016-07-28 19:47:15 +00002761 /* In this case, the RHS is the ROWID of table b-tree */
drheeb95652016-05-26 20:56:38 +00002762 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002763 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002764 }else{
dan7b35a772016-07-28 19:47:15 +00002765 /* In this case, the RHS is an index b-tree. Apply the comparison
2766 ** affinities to each value on the LHS of the operator. */
danba00e302016-07-23 20:24:06 +00002767 sqlite3VdbeAddOp4(v, OP_Affinity, r1, nVector, 0, zAff, nVector);
dan7b35a772016-07-28 19:47:15 +00002768
2769 if( nVector>1 && destIfNull!=destIfFalse ){
2770 int iIdx = pExpr->iTable;
2771 int addr;
2772 int addrNext;
2773
2774 /* Search the index for the key. */
2775 addr = sqlite3VdbeAddOp4Int(v, OP_Found, iIdx, 0, r1, nVector);
drh471b4b92016-08-12 11:25:49 +00002776 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002777
2778 /* At this point the specified key is not present in the index,
2779 ** so the result of the IN(..) operator must be either NULL or
2780 ** 0. The vdbe code generated below figures out which. */
2781 addrNext = 1+sqlite3VdbeAddOp2(v, OP_Rewind, iIdx, destIfFalse);
drh471b4b92016-08-12 11:25:49 +00002782 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002783
2784 for(i=0; i<nVector; i++){
2785 Expr *p;
2786 CollSeq *pColl;
2787 int r2 = sqlite3GetTempReg(pParse);
drhfc7f27b2016-08-20 00:07:01 +00002788 p = sqlite3VectorFieldSubexpr(pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002789 pColl = sqlite3ExprCollSeq(pParse, p);
2790
2791 sqlite3VdbeAddOp3(v, OP_Column, iIdx, i, r2);
2792 sqlite3VdbeAddOp4(v, OP_Eq, r1+i, 0, r2, (void*)pColl,P4_COLLSEQ);
2793 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh471b4b92016-08-12 11:25:49 +00002794 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002795 sqlite3VdbeAddOp2(v, OP_Next, iIdx, addrNext);
drh471b4b92016-08-12 11:25:49 +00002796 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002797 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2798 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-3);
2799 sqlite3ReleaseTempReg(pParse, r2);
2800 }
2801 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
2802
2803 /* The key was found in the index. If it contains any NULL values,
2804 ** then the result of the IN(...) operator is NULL. Otherwise, the
2805 ** result is 1. */
2806 sqlite3VdbeJumpHere(v, addr);
2807 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002808 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002809 if( sqlite3ExprCanBeNull(p) ){
2810 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002811 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002812 }
2813 }
2814
2815 }else if( rRhsHasNull==0 ){
drhbb53ecb2014-08-02 21:03:33 +00002816 /* This branch runs if it is known at compile time that the RHS
dan7b35a772016-07-28 19:47:15 +00002817 ** cannot contain NULL values. This happens as a result
2818 ** of "NOT NULL" constraints in the database schema.
drhbb53ecb2014-08-02 21:03:33 +00002819 **
2820 ** Also run this branch if NULL is equivalent to FALSE
dan7b35a772016-07-28 19:47:15 +00002821 ** for this particular IN operator. */
danba00e302016-07-23 20:24:06 +00002822 sqlite3VdbeAddOp4Int(
2823 v, OP_NotFound, pExpr->iTable, destIfFalse, r1, nVector
2824 );
drhbb53ecb2014-08-02 21:03:33 +00002825 VdbeCoverage(v);
2826 }else{
2827 /* In this branch, the RHS of the IN might contain a NULL and
2828 ** the presence of a NULL on the RHS makes a difference in the
2829 ** outcome.
2830 */
drh728e0f92015-10-10 14:41:28 +00002831 int addr1;
dan7b35a772016-07-28 19:47:15 +00002832
drhbb53ecb2014-08-02 21:03:33 +00002833 /* First check to see if the LHS is contained in the RHS. If so,
2834 ** then the answer is TRUE the presence of NULLs in the RHS does
2835 ** not matter. If the LHS is not contained in the RHS, then the
2836 ** answer is NULL if the RHS contains NULLs and the answer is
2837 ** FALSE if the RHS is NULL-free.
2838 */
drh728e0f92015-10-10 14:41:28 +00002839 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002840 VdbeCoverage(v);
2841 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2842 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002843 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002844 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002845 }
drhe3365e62009-11-12 17:52:24 +00002846 }
drhe3365e62009-11-12 17:52:24 +00002847 }
2848 sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002849 sqlite3ExprCachePop(pParse);
danba00e302016-07-23 20:24:06 +00002850 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00002851 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00002852 VdbeComment((v, "end IN expr"));
2853}
2854#endif /* SQLITE_OMIT_SUBQUERY */
2855
drh13573c72010-01-12 17:04:07 +00002856#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002857/*
2858** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002859** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002860**
2861** The z[] string will probably not be zero-terminated. But the
2862** z[n] character is guaranteed to be something that does not look
2863** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002864*/
drhb7916a72009-05-27 10:31:29 +00002865static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002866 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002867 double value;
drh9339da12010-09-30 00:50:49 +00002868 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002869 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2870 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002871 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002872 }
2873}
drh13573c72010-01-12 17:04:07 +00002874#endif
drh598f1342007-10-23 15:39:45 +00002875
2876
2877/*
drhfec19aa2004-05-19 20:41:03 +00002878** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002879** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002880**
shaneh5f1d6b62010-09-30 16:51:25 +00002881** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002882*/
drh13573c72010-01-12 17:04:07 +00002883static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2884 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002885 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002886 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002887 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002888 if( negFlag ) i = -i;
2889 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002890 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002891 int c;
2892 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002893 const char *z = pExpr->u.zToken;
2894 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002895 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002896 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002897 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002898 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002899 }else{
drh13573c72010-01-12 17:04:07 +00002900#ifdef SQLITE_OMIT_FLOATING_POINT
2901 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2902#else
drh1b7ddc52014-07-23 14:52:05 +00002903#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002904 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2905 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002906 }else
2907#endif
2908 {
drh9296c182014-07-23 13:40:49 +00002909 codeReal(v, z, negFlag, iMem);
2910 }
drh13573c72010-01-12 17:04:07 +00002911#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002912 }
drhfec19aa2004-05-19 20:41:03 +00002913 }
2914}
2915
drhbea119c2016-04-11 18:15:37 +00002916#if defined(SQLITE_DEBUG)
2917/*
2918** Verify the consistency of the column cache
2919*/
2920static int cacheIsValid(Parse *pParse){
2921 int i, n;
2922 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2923 if( pParse->aColCache[i].iReg>0 ) n++;
2924 }
2925 return n==pParse->nColCache;
2926}
2927#endif
2928
drhceea3322009-04-23 13:22:42 +00002929/*
2930** Clear a cache entry.
2931*/
2932static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2933 if( p->tempReg ){
2934 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2935 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2936 }
2937 p->tempReg = 0;
2938 }
drhbea119c2016-04-11 18:15:37 +00002939 p->iReg = 0;
2940 pParse->nColCache--;
danee65eea2016-04-16 15:03:20 +00002941 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002942}
2943
2944
2945/*
2946** Record in the column cache that a particular column from a
2947** particular table is stored in a particular register.
2948*/
2949void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2950 int i;
2951 int minLru;
2952 int idxLru;
2953 struct yColCache *p;
2954
dance8f53d2015-01-21 17:00:57 +00002955 /* Unless an error has occurred, register numbers are always positive. */
2956 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002957 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2958
drhb6da74e2009-12-24 16:00:28 +00002959 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2960 ** for testing only - to verify that SQLite always gets the same answer
2961 ** with and without the column cache.
2962 */
drh7e5418e2012-09-27 15:05:54 +00002963 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002964
drh27ee4062009-12-30 01:13:11 +00002965 /* First replace any existing entry.
2966 **
2967 ** Actually, the way the column cache is currently used, we are guaranteed
2968 ** that the object will never already be in cache. Verify this guarantee.
2969 */
2970#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00002971 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00002972 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00002973 }
drh27ee4062009-12-30 01:13:11 +00002974#endif
drhceea3322009-04-23 13:22:42 +00002975
2976 /* Find an empty slot and replace it */
2977 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2978 if( p->iReg==0 ){
2979 p->iLevel = pParse->iCacheLevel;
2980 p->iTable = iTab;
2981 p->iColumn = iCol;
2982 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002983 p->tempReg = 0;
2984 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002985 pParse->nColCache++;
danee65eea2016-04-16 15:03:20 +00002986 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002987 return;
2988 }
2989 }
2990
2991 /* Replace the last recently used */
2992 minLru = 0x7fffffff;
2993 idxLru = -1;
2994 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2995 if( p->lru<minLru ){
2996 idxLru = i;
2997 minLru = p->lru;
2998 }
2999 }
drh20411ea2009-05-29 19:00:12 +00003000 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00003001 p = &pParse->aColCache[idxLru];
3002 p->iLevel = pParse->iCacheLevel;
3003 p->iTable = iTab;
3004 p->iColumn = iCol;
3005 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00003006 p->tempReg = 0;
3007 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00003008 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00003009 return;
3010 }
3011}
3012
3013/*
drhf49f3522009-12-30 14:12:38 +00003014** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3015** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00003016*/
drhf49f3522009-12-30 14:12:38 +00003017void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00003018 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00003019 if( iReg<=0 || pParse->nColCache==0 ) return;
3020 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
3021 while(1){
3022 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
3023 if( p==pParse->aColCache ) break;
3024 p--;
drhceea3322009-04-23 13:22:42 +00003025 }
3026}
3027
3028/*
3029** Remember the current column cache context. Any new entries added
3030** added to the column cache after this call are removed when the
3031** corresponding pop occurs.
3032*/
3033void sqlite3ExprCachePush(Parse *pParse){
3034 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00003035#ifdef SQLITE_DEBUG
3036 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3037 printf("PUSH to %d\n", pParse->iCacheLevel);
3038 }
3039#endif
drhceea3322009-04-23 13:22:42 +00003040}
3041
3042/*
3043** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00003044** the previous sqlite3ExprCachePush operation. In other words, restore
3045** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00003046*/
drhd2490902014-04-13 19:28:15 +00003047void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00003048 int i;
3049 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00003050 assert( pParse->iCacheLevel>=1 );
3051 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00003052#ifdef SQLITE_DEBUG
3053 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3054 printf("POP to %d\n", pParse->iCacheLevel);
3055 }
3056#endif
drhceea3322009-04-23 13:22:42 +00003057 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3058 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
3059 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00003060 }
3061 }
3062}
drh945498f2007-02-24 11:52:52 +00003063
3064/*
drh5cd79232009-05-25 11:46:29 +00003065** When a cached column is reused, make sure that its register is
3066** no longer available as a temp register. ticket #3879: that same
3067** register might be in the cache in multiple places, so be sure to
3068** get them all.
3069*/
3070static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3071 int i;
3072 struct yColCache *p;
3073 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3074 if( p->iReg==iReg ){
3075 p->tempReg = 0;
3076 }
3077 }
3078}
3079
drh1f9ca2c2015-08-25 16:57:52 +00003080/* Generate code that will load into register regOut a value that is
3081** appropriate for the iIdxCol-th column of index pIdx.
3082*/
3083void sqlite3ExprCodeLoadIndexColumn(
3084 Parse *pParse, /* The parsing context */
3085 Index *pIdx, /* The index whose column is to be loaded */
3086 int iTabCur, /* Cursor pointing to a table row */
3087 int iIdxCol, /* The column of the index to be loaded */
3088 int regOut /* Store the index column value in this register */
3089){
3090 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003091 if( iTabCol==XN_EXPR ){
3092 assert( pIdx->aColExpr );
3093 assert( pIdx->aColExpr->nExpr>iIdxCol );
3094 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00003095 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00003096 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003097 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3098 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003099 }
drh1f9ca2c2015-08-25 16:57:52 +00003100}
3101
drh5cd79232009-05-25 11:46:29 +00003102/*
drh5c092e82010-05-14 19:24:02 +00003103** Generate code to extract the value of the iCol-th column of a table.
3104*/
3105void sqlite3ExprCodeGetColumnOfTable(
3106 Vdbe *v, /* The VDBE under construction */
3107 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003108 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003109 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003110 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003111){
3112 if( iCol<0 || iCol==pTab->iPKey ){
3113 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3114 }else{
3115 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003116 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003117 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003118 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3119 }
3120 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003121 }
3122 if( iCol>=0 ){
3123 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3124 }
3125}
3126
3127/*
drh945498f2007-02-24 11:52:52 +00003128** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00003129** table pTab and store the column value in a register.
3130**
3131** An effort is made to store the column value in register iReg. This
3132** is not garanteeed for GetColumn() - the result can be stored in
3133** any register. But the result is guaranteed to land in register iReg
3134** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00003135**
3136** There must be an open cursor to pTab in iTable when this routine
3137** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003138*/
drhe55cbd72008-03-31 23:48:03 +00003139int sqlite3ExprCodeGetColumn(
3140 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003141 Table *pTab, /* Description of the table we are reading from */
3142 int iColumn, /* Index of the table column */
3143 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003144 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003145 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003146){
drhe55cbd72008-03-31 23:48:03 +00003147 Vdbe *v = pParse->pVdbe;
3148 int i;
drhda250ea2008-04-01 05:07:14 +00003149 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00003150
drhceea3322009-04-23 13:22:42 +00003151 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00003152 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00003153 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00003154 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00003155 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00003156 }
3157 }
3158 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003159 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003160 if( p5 ){
3161 sqlite3VdbeChangeP5(v, p5);
3162 }else{
3163 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3164 }
drhe55cbd72008-03-31 23:48:03 +00003165 return iReg;
3166}
drhce78bc62015-10-15 19:21:51 +00003167void sqlite3ExprCodeGetColumnToReg(
3168 Parse *pParse, /* Parsing and code generating context */
3169 Table *pTab, /* Description of the table we are reading from */
3170 int iColumn, /* Index of the table column */
3171 int iTable, /* The cursor pointing to the table */
3172 int iReg /* Store results here */
3173){
3174 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3175 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3176}
3177
drhe55cbd72008-03-31 23:48:03 +00003178
3179/*
drhceea3322009-04-23 13:22:42 +00003180** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00003181*/
drhceea3322009-04-23 13:22:42 +00003182void sqlite3ExprCacheClear(Parse *pParse){
3183 int i;
3184 struct yColCache *p;
3185
drh9ac79622013-12-18 15:11:47 +00003186#if SQLITE_DEBUG
3187 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3188 printf("CLEAR\n");
3189 }
3190#endif
drhceea3322009-04-23 13:22:42 +00003191 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3192 if( p->iReg ){
3193 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00003194 }
drhe55cbd72008-03-31 23:48:03 +00003195 }
3196}
3197
3198/*
drhda250ea2008-04-01 05:07:14 +00003199** Record the fact that an affinity change has occurred on iCount
3200** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00003201*/
drhda250ea2008-04-01 05:07:14 +00003202void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00003203 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00003204}
3205
3206/*
drhb21e7c72008-06-22 12:37:57 +00003207** Generate code to move content from registers iFrom...iFrom+nReg-1
3208** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00003209*/
drhb21e7c72008-06-22 12:37:57 +00003210void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003211 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003212 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00003213 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00003214}
3215
drhf49f3522009-12-30 14:12:38 +00003216#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00003217/*
drh652fbf52008-04-01 01:42:41 +00003218** Return true if any register in the range iFrom..iTo (inclusive)
3219** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00003220**
3221** This routine is used within assert() and testcase() macros only
3222** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00003223*/
3224static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3225 int i;
drhceea3322009-04-23 13:22:42 +00003226 struct yColCache *p;
3227 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3228 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00003229 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00003230 }
3231 return 0;
3232}
drhf49f3522009-12-30 14:12:38 +00003233#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00003234
drhbea119c2016-04-11 18:15:37 +00003235
drh652fbf52008-04-01 01:42:41 +00003236/*
drh12abf402016-08-22 14:30:05 +00003237** Convert a scalar expression node to a TK_REGISTER referencing
3238** register iReg. The caller must ensure that iReg already contains
3239** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003240*/
3241static void exprToRegister(Expr *p, int iReg){
3242 p->op2 = p->op;
3243 p->op = TK_REGISTER;
3244 p->iTable = iReg;
3245 ExprClearProperty(p, EP_Skip);
3246}
3247
drh12abf402016-08-22 14:30:05 +00003248/*
3249** Evaluate an expression (either a vector or a scalar expression) and store
3250** the result in continguous temporary registers. Return the index of
3251** the first register used to store the result.
3252**
3253** If the returned result register is a temporary scalar, then also write
3254** that register number into *piFreeable. If the returned result register
3255** is not a temporary or if the expression is a vector set *piFreeable
3256** to 0.
3257*/
3258static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3259 int iResult;
3260 int nResult = sqlite3ExprVectorSize(p);
3261 if( nResult==1 ){
3262 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3263 }else{
3264 *piFreeable = 0;
3265 if( p->op==TK_SELECT ){
3266 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3267 }else{
3268 int i;
3269 iResult = pParse->nMem+1;
3270 pParse->nMem += nResult;
3271 for(i=0; i<nResult; i++){
3272 sqlite3ExprCode(pParse, p->x.pList->a[i].pExpr, i+iResult);
3273 }
3274 }
3275 }
3276 return iResult;
3277}
3278
dan71c57db2016-07-09 20:23:55 +00003279
drha4c3c872013-09-12 17:29:25 +00003280/*
drhcce7d172000-05-31 15:34:51 +00003281** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003282** expression. Attempt to store the results in register "target".
3283** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003284**
drh8b213892008-08-29 02:14:02 +00003285** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003286** be stored in target. The result might be stored in some other
3287** register if it is convenient to do so. The calling function
3288** must check the return code and move the results to the desired
3289** register.
drhcce7d172000-05-31 15:34:51 +00003290*/
drh678ccce2008-03-31 18:19:54 +00003291int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003292 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3293 int op; /* The opcode being coded */
3294 int inReg = target; /* Results stored in register inReg */
3295 int regFree1 = 0; /* If non-zero free this temporary register */
3296 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003297 int r1, r2; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00003298 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00003299 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003300 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003301
drh9cbf3422008-01-17 16:22:13 +00003302 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003303 if( v==0 ){
3304 assert( pParse->db->mallocFailed );
3305 return 0;
3306 }
drh389a1ad2008-01-03 23:44:53 +00003307
3308 if( pExpr==0 ){
3309 op = TK_NULL;
3310 }else{
3311 op = pExpr->op;
3312 }
drhf2bc0132004-10-04 13:19:23 +00003313 switch( op ){
drh13449892005-09-07 21:22:45 +00003314 case TK_AGG_COLUMN: {
3315 AggInfo *pAggInfo = pExpr->pAggInfo;
3316 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3317 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003318 assert( pCol->iMem>0 );
3319 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00003320 break;
3321 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003322 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003323 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00003324 break;
3325 }
3326 /* Otherwise, fall thru into the TK_COLUMN case */
3327 }
drh967e8b72000-06-21 13:59:10 +00003328 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003329 int iTab = pExpr->iTable;
3330 if( iTab<0 ){
3331 if( pParse->ckBase>0 ){
3332 /* Generating CHECK constraints or inserting into partial index */
3333 inReg = pExpr->iColumn + pParse->ckBase;
3334 break;
3335 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003336 /* Coding an expression that is part of an index where column names
3337 ** in the index refer to the table to which the index belongs */
3338 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003339 }
drh22827922000-06-06 17:27:05 +00003340 }
drhb2b9d3d2013-08-01 01:14:43 +00003341 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3342 pExpr->iColumn, iTab, target,
3343 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003344 break;
3345 }
3346 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003347 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00003348 break;
3349 }
drh13573c72010-01-12 17:04:07 +00003350#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003351 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003352 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3353 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00003354 break;
3355 }
drh13573c72010-01-12 17:04:07 +00003356#endif
drhfec19aa2004-05-19 20:41:03 +00003357 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003358 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003359 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00003360 break;
3361 }
drhf0863fe2005-06-12 21:35:51 +00003362 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003363 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00003364 break;
3365 }
danielk19775338a5f2005-01-20 13:03:10 +00003366#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003367 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003368 int n;
3369 const char *z;
drhca48c902008-01-18 14:08:24 +00003370 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003371 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3372 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3373 assert( pExpr->u.zToken[1]=='\'' );
3374 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003375 n = sqlite3Strlen30(z) - 1;
3376 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003377 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3378 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00003379 break;
3380 }
danielk19775338a5f2005-01-20 13:03:10 +00003381#endif
drh50457892003-09-06 01:10:47 +00003382 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003383 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3384 assert( pExpr->u.zToken!=0 );
3385 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003386 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3387 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00003388 assert( pExpr->u.zToken[0]=='?'
3389 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
3390 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003391 }
drh50457892003-09-06 01:10:47 +00003392 break;
3393 }
drh4e0cff62004-11-05 05:10:28 +00003394 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00003395 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003396 break;
3397 }
drh487e2622005-06-25 18:42:14 +00003398#ifndef SQLITE_OMIT_CAST
3399 case TK_CAST: {
3400 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003401 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003402 if( inReg!=target ){
3403 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3404 inReg = target;
3405 }
drh4169e432014-08-25 20:11:52 +00003406 sqlite3VdbeAddOp2(v, OP_Cast, target,
3407 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00003408 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00003409 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00003410 break;
3411 }
3412#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003413 case TK_IS:
3414 case TK_ISNOT:
3415 op = (op==TK_IS) ? TK_EQ : TK_NE;
3416 p5 = SQLITE_NULLEQ;
3417 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003418 case TK_LT:
3419 case TK_LE:
3420 case TK_GT:
3421 case TK_GE:
3422 case TK_NE:
3423 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003424 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003425 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003426 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003427 }else{
3428 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3429 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3430 codeCompare(pParse, pLeft, pExpr->pRight, op,
3431 r1, r2, inReg, SQLITE_STOREP2 | p5);
3432 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3433 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3434 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3435 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3436 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3437 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3438 testcase( regFree1==0 );
3439 testcase( regFree2==0 );
3440 }
drh6a2fe092009-09-23 02:29:36 +00003441 break;
3442 }
drhcce7d172000-05-31 15:34:51 +00003443 case TK_AND:
3444 case TK_OR:
3445 case TK_PLUS:
3446 case TK_STAR:
3447 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003448 case TK_REM:
3449 case TK_BITAND:
3450 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003451 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003452 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003453 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003454 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003455 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3456 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3457 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3458 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3459 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3460 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3461 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3462 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3463 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3464 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3465 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003466 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3467 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003468 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003469 testcase( regFree1==0 );
3470 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003471 break;
3472 }
drhcce7d172000-05-31 15:34:51 +00003473 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003474 Expr *pLeft = pExpr->pLeft;
3475 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003476 if( pLeft->op==TK_INTEGER ){
3477 codeInteger(pParse, pLeft, 1, target);
3478#ifndef SQLITE_OMIT_FLOATING_POINT
3479 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003480 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3481 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00003482#endif
drh3c84ddf2008-01-09 02:15:38 +00003483 }else{
drh10d1edf2013-11-15 15:52:39 +00003484 tempX.op = TK_INTEGER;
3485 tempX.flags = EP_IntValue|EP_TokenOnly;
3486 tempX.u.iValue = 0;
3487 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003488 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003489 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003490 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003491 }
drh3c84ddf2008-01-09 02:15:38 +00003492 inReg = target;
3493 break;
drh6e142f52000-06-08 13:36:40 +00003494 }
drhbf4133c2001-10-13 02:59:08 +00003495 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003496 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003497 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3498 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003499 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3500 testcase( regFree1==0 );
3501 inReg = target;
3502 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003503 break;
3504 }
3505 case TK_ISNULL:
3506 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003507 int addr;
drh7d176102014-02-18 03:07:12 +00003508 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3509 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003510 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003511 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003512 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003513 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003514 VdbeCoverageIf(v, op==TK_ISNULL);
3515 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003516 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003517 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003518 break;
drhcce7d172000-05-31 15:34:51 +00003519 }
drh22827922000-06-06 17:27:05 +00003520 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003521 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003522 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003523 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3524 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003525 }else{
drh9de221d2008-01-05 06:51:30 +00003526 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003527 }
drh22827922000-06-06 17:27:05 +00003528 break;
3529 }
drhcce7d172000-05-31 15:34:51 +00003530 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003531 ExprList *pFarg; /* List of function arguments */
3532 int nFarg; /* Number of function arguments */
3533 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003534 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003535 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003536 int i; /* Loop counter */
3537 u8 enc = ENC(db); /* The text encoding used by this database */
3538 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003539
danielk19776ab3a2e2009-02-19 14:39:25 +00003540 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00003541 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003542 pFarg = 0;
3543 }else{
3544 pFarg = pExpr->x.pList;
3545 }
3546 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003547 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3548 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003549 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003550#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3551 if( pDef==0 && pParse->explain ){
3552 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3553 }
3554#endif
drh2d801512016-01-14 22:19:58 +00003555 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003556 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003557 break;
3558 }
drhae6bb952009-11-11 00:24:31 +00003559
3560 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003561 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003562 ** arguments past the first non-NULL argument.
3563 */
drhd36e1042013-09-06 13:10:12 +00003564 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003565 int endCoalesce = sqlite3VdbeMakeLabel(v);
3566 assert( nFarg>=2 );
3567 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3568 for(i=1; i<nFarg; i++){
3569 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003570 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00003571 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00003572 sqlite3ExprCachePush(pParse);
3573 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003574 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00003575 }
3576 sqlite3VdbeResolveLabel(v, endCoalesce);
3577 break;
3578 }
3579
drhcca9f3d2013-09-06 15:23:29 +00003580 /* The UNLIKELY() function is a no-op. The result is the value
3581 ** of the first argument.
3582 */
3583 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3584 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00003585 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003586 break;
3587 }
drhae6bb952009-11-11 00:24:31 +00003588
drhd1a01ed2013-11-21 16:08:52 +00003589 for(i=0; i<nFarg; i++){
3590 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003591 testcase( i==31 );
3592 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003593 }
3594 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3595 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3596 }
3597 }
drh12ffee82009-04-08 13:51:51 +00003598 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003599 if( constMask ){
3600 r1 = pParse->nMem+1;
3601 pParse->nMem += nFarg;
3602 }else{
3603 r1 = sqlite3GetTempRange(pParse, nFarg);
3604 }
drha748fdc2012-03-28 01:34:47 +00003605
3606 /* For length() and typeof() functions with a column argument,
3607 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3608 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3609 ** loading.
3610 */
drhd36e1042013-09-06 13:10:12 +00003611 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003612 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003613 assert( nFarg==1 );
3614 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003615 exprOp = pFarg->a[0].pExpr->op;
3616 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003617 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3618 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003619 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3620 pFarg->a[0].pExpr->op2 =
3621 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003622 }
3623 }
3624
drhd7d385d2009-09-03 01:18:00 +00003625 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003626 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003627 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003628 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003629 }else{
drh12ffee82009-04-08 13:51:51 +00003630 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003631 }
drhb7f6f682006-07-08 17:06:43 +00003632#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003633 /* Possibly overload the function if the first argument is
3634 ** a virtual table column.
3635 **
3636 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3637 ** second argument, not the first, as the argument to test to
3638 ** see if it is a column in a virtual table. This is done because
3639 ** the left operand of infix functions (the operand we want to
3640 ** control overloading) ends up as the second argument to the
3641 ** function. The expression "A glob B" is equivalent to
3642 ** "glob(B,A). We want to use the A in "A glob B" to test
3643 ** for function overloading. But we use the B term in "glob(B,A)".
3644 */
drh12ffee82009-04-08 13:51:51 +00003645 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3646 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3647 }else if( nFarg>0 ){
3648 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003649 }
3650#endif
drhd36e1042013-09-06 13:10:12 +00003651 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003652 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003653 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003654 }
drh9c7c9132015-06-26 18:16:52 +00003655 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003656 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003657 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003658 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003659 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003660 }
drhcce7d172000-05-31 15:34:51 +00003661 break;
3662 }
drhfe2093d2005-01-20 22:48:47 +00003663#ifndef SQLITE_OMIT_SUBQUERY
3664 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003665 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003666 int nCol;
drhc5499be2008-04-01 15:06:33 +00003667 testcase( op==TK_EXISTS );
3668 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003669 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3670 sqlite3SubselectError(pParse, nCol, 1);
3671 }else{
3672 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3673 }
drh19a775c2000-06-05 18:54:46 +00003674 break;
3675 }
drhfc7f27b2016-08-20 00:07:01 +00003676 case TK_SELECT_COLUMN: {
3677 if( pExpr->pLeft->iTable==0 ){
3678 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3679 }
3680 inReg = pExpr->pLeft->iTable + pExpr->iColumn;
3681 break;
3682 }
drhfef52082000-06-06 01:50:43 +00003683 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003684 int destIfFalse = sqlite3VdbeMakeLabel(v);
3685 int destIfNull = sqlite3VdbeMakeLabel(v);
3686 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3687 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3688 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3689 sqlite3VdbeResolveLabel(v, destIfFalse);
3690 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3691 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003692 break;
3693 }
drhe3365e62009-11-12 17:52:24 +00003694#endif /* SQLITE_OMIT_SUBQUERY */
3695
3696
drh2dcef112008-01-12 19:03:48 +00003697 /*
3698 ** x BETWEEN y AND z
3699 **
3700 ** This is equivalent to
3701 **
3702 ** x>=y AND x<=z
3703 **
3704 ** X is stored in pExpr->pLeft.
3705 ** Y is stored in pExpr->pList->a[0].pExpr.
3706 ** Z is stored in pExpr->pList->a[1].pExpr.
3707 */
drhfef52082000-06-06 01:50:43 +00003708 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003709 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhfef52082000-06-06 01:50:43 +00003710 break;
3711 }
drh94fa9c42016-02-27 21:16:04 +00003712 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003713 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003714 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003715 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003716 break;
3717 }
drh2dcef112008-01-12 19:03:48 +00003718
dan165921a2009-08-28 18:53:45 +00003719 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003720 /* If the opcode is TK_TRIGGER, then the expression is a reference
3721 ** to a column in the new.* or old.* pseudo-tables available to
3722 ** trigger programs. In this case Expr.iTable is set to 1 for the
3723 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3724 ** is set to the column of the pseudo-table to read, or to -1 to
3725 ** read the rowid field.
3726 **
3727 ** The expression is implemented using an OP_Param opcode. The p1
3728 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3729 ** to reference another column of the old.* pseudo-table, where
3730 ** i is the index of the column. For a new.rowid reference, p1 is
3731 ** set to (n+1), where n is the number of columns in each pseudo-table.
3732 ** For a reference to any other column in the new.* pseudo-table, p1
3733 ** is set to (n+2+i), where n and i are as defined previously. For
3734 ** example, if the table on which triggers are being fired is
3735 ** declared as:
3736 **
3737 ** CREATE TABLE t1(a, b);
3738 **
3739 ** Then p1 is interpreted as follows:
3740 **
3741 ** p1==0 -> old.rowid p1==3 -> new.rowid
3742 ** p1==1 -> old.a p1==4 -> new.a
3743 ** p1==2 -> old.b p1==5 -> new.b
3744 */
dan2832ad42009-08-31 15:27:27 +00003745 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003746 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3747
3748 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3749 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3750 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3751 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3752
3753 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003754 VdbeComment((v, "%s.%s -> $%d",
3755 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003756 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003757 target
dan165921a2009-08-28 18:53:45 +00003758 ));
dan65a7cd12009-09-01 12:16:01 +00003759
drh44dbca82010-01-13 04:22:20 +00003760#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003761 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003762 ** integer. Use OP_RealAffinity to make sure it is really real.
3763 **
3764 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3765 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003766 if( pExpr->iColumn>=0
3767 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3768 ){
3769 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3770 }
drh44dbca82010-01-13 04:22:20 +00003771#endif
dan165921a2009-08-28 18:53:45 +00003772 break;
3773 }
3774
dan71c57db2016-07-09 20:23:55 +00003775 case TK_VECTOR: {
dand49fd4e2016-07-27 19:33:04 +00003776 sqlite3ErrorMsg(pParse, "invalid use of row value");
dan71c57db2016-07-09 20:23:55 +00003777 break;
3778 }
3779
drh2dcef112008-01-12 19:03:48 +00003780 /*
3781 ** Form A:
3782 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3783 **
3784 ** Form B:
3785 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3786 **
3787 ** Form A is can be transformed into the equivalent form B as follows:
3788 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3789 ** WHEN x=eN THEN rN ELSE y END
3790 **
3791 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003792 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3793 ** odd. The Y is also optional. If the number of elements in x.pList
3794 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003795 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3796 **
3797 ** The result of the expression is the Ri for the first matching Ei,
3798 ** or if there is no matching Ei, the ELSE term Y, or if there is
3799 ** no ELSE term, NULL.
3800 */
drh33cd4902009-05-30 20:49:20 +00003801 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003802 int endLabel; /* GOTO label for end of CASE stmt */
3803 int nextCase; /* GOTO label for next WHEN clause */
3804 int nExpr; /* 2x number of WHEN terms */
3805 int i; /* Loop counter */
3806 ExprList *pEList; /* List of WHEN terms */
3807 struct ExprList_item *aListelem; /* Array of WHEN terms */
3808 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003809 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003810 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003811 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003812
danielk19776ab3a2e2009-02-19 14:39:25 +00003813 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003814 assert(pExpr->x.pList->nExpr > 0);
3815 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003816 aListelem = pEList->a;
3817 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003818 endLabel = sqlite3VdbeMakeLabel(v);
3819 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003820 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003821 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00003822 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003823 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00003824 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00003825 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003826 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003827 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003828 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3829 ** The value in regFree1 might get SCopy-ed into the file result.
3830 ** So make sure that the regFree1 register is not reused for other
3831 ** purposes and possibly overwritten. */
3832 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003833 }
drhc5cd1242013-09-12 16:50:49 +00003834 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003835 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003836 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003837 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003838 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003839 }else{
drh2dcef112008-01-12 19:03:48 +00003840 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003841 }
drh2dcef112008-01-12 19:03:48 +00003842 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003843 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003844 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003845 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003846 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003847 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003848 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003849 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003850 }
drhc5cd1242013-09-12 16:50:49 +00003851 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003852 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003853 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003854 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003855 }else{
drh9de221d2008-01-05 06:51:30 +00003856 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003857 }
danielk1977c1f4a192009-04-28 12:08:15 +00003858 assert( db->mallocFailed || pParse->nErr>0
3859 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003860 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003861 break;
3862 }
danielk19775338a5f2005-01-20 13:03:10 +00003863#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003864 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003865 assert( pExpr->affinity==OE_Rollback
3866 || pExpr->affinity==OE_Abort
3867 || pExpr->affinity==OE_Fail
3868 || pExpr->affinity==OE_Ignore
3869 );
dane0af83a2009-09-08 19:15:01 +00003870 if( !pParse->pTriggerTab ){
3871 sqlite3ErrorMsg(pParse,
3872 "RAISE() may only be used within a trigger-program");
3873 return 0;
3874 }
3875 if( pExpr->affinity==OE_Abort ){
3876 sqlite3MayAbort(pParse);
3877 }
dan165921a2009-08-28 18:53:45 +00003878 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003879 if( pExpr->affinity==OE_Ignore ){
3880 sqlite3VdbeAddOp4(
3881 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003882 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003883 }else{
drh433dccf2013-02-09 15:37:11 +00003884 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003885 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003886 }
3887
drhffe07b22005-11-03 00:41:17 +00003888 break;
drh17a7f8d2002-03-24 13:13:27 +00003889 }
danielk19775338a5f2005-01-20 13:03:10 +00003890#endif
drhffe07b22005-11-03 00:41:17 +00003891 }
drh2dcef112008-01-12 19:03:48 +00003892 sqlite3ReleaseTempReg(pParse, regFree1);
3893 sqlite3ReleaseTempReg(pParse, regFree2);
3894 return inReg;
3895}
3896
3897/*
drhd1a01ed2013-11-21 16:08:52 +00003898** Factor out the code of the given expression to initialization time.
3899*/
drhd673cdd2013-11-21 21:23:31 +00003900void sqlite3ExprCodeAtInit(
3901 Parse *pParse, /* Parsing context */
3902 Expr *pExpr, /* The expression to code when the VDBE initializes */
3903 int regDest, /* Store the value in this register */
3904 u8 reusable /* True if this expression is reusable */
3905){
drhd1a01ed2013-11-21 16:08:52 +00003906 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003907 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003908 p = pParse->pConstExpr;
3909 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3910 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003911 if( p ){
3912 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3913 pItem->u.iConstExprReg = regDest;
3914 pItem->reusable = reusable;
3915 }
drhd1a01ed2013-11-21 16:08:52 +00003916 pParse->pConstExpr = p;
3917}
3918
3919/*
drh2dcef112008-01-12 19:03:48 +00003920** Generate code to evaluate an expression and store the results
3921** into a register. Return the register number where the results
3922** are stored.
3923**
3924** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003925** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003926** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003927**
3928** If pExpr is a constant, then this routine might generate this
3929** code to fill the register in the initialization section of the
3930** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003931*/
3932int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003933 int r2;
3934 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003935 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003936 && pExpr->op!=TK_REGISTER
3937 && sqlite3ExprIsConstantNotJoin(pExpr)
3938 ){
3939 ExprList *p = pParse->pConstExpr;
3940 int i;
3941 *pReg = 0;
3942 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003943 struct ExprList_item *pItem;
3944 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3945 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3946 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003947 }
3948 }
3949 }
drhf30a9692013-11-15 01:10:18 +00003950 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003951 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003952 }else{
drhf30a9692013-11-15 01:10:18 +00003953 int r1 = sqlite3GetTempReg(pParse);
3954 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3955 if( r2==r1 ){
3956 *pReg = r1;
3957 }else{
3958 sqlite3ReleaseTempReg(pParse, r1);
3959 *pReg = 0;
3960 }
drh2dcef112008-01-12 19:03:48 +00003961 }
3962 return r2;
3963}
3964
3965/*
3966** Generate code that will evaluate expression pExpr and store the
3967** results in register target. The results are guaranteed to appear
3968** in register target.
3969*/
drh05a86c52014-02-16 01:55:49 +00003970void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00003971 int inReg;
3972
3973 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00003974 if( pExpr && pExpr->op==TK_REGISTER ){
3975 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3976 }else{
3977 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00003978 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00003979 if( inReg!=target && pParse->pVdbe ){
3980 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
3981 }
drhcce7d172000-05-31 15:34:51 +00003982 }
drhcce7d172000-05-31 15:34:51 +00003983}
3984
3985/*
drh1c75c9d2015-12-21 15:22:13 +00003986** Make a transient copy of expression pExpr and then code it using
3987** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
3988** except that the input expression is guaranteed to be unchanged.
3989*/
3990void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
3991 sqlite3 *db = pParse->db;
3992 pExpr = sqlite3ExprDup(db, pExpr, 0);
3993 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
3994 sqlite3ExprDelete(db, pExpr);
3995}
3996
3997/*
drh05a86c52014-02-16 01:55:49 +00003998** Generate code that will evaluate expression pExpr and store the
3999** results in register target. The results are guaranteed to appear
4000** in register target. If the expression is constant, then this routine
4001** might choose to code the expression at initialization time.
4002*/
4003void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4004 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4005 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
4006 }else{
4007 sqlite3ExprCode(pParse, pExpr, target);
4008 }
drhcce7d172000-05-31 15:34:51 +00004009}
4010
4011/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004012** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004013** in register target.
drh25303782004-12-07 15:41:48 +00004014**
drh2dcef112008-01-12 19:03:48 +00004015** Also make a copy of the expression results into another "cache" register
4016** and modify the expression so that the next time it is evaluated,
4017** the result is a copy of the cache register.
4018**
4019** This routine is used for expressions that are used multiple
4020** times. They are evaluated once and the results of the expression
4021** are reused.
drh25303782004-12-07 15:41:48 +00004022*/
drh05a86c52014-02-16 01:55:49 +00004023void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004024 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004025 int iMem;
4026
drhde4fcfd2008-01-19 23:50:26 +00004027 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004028 assert( pExpr->op!=TK_REGISTER );
4029 sqlite3ExprCode(pParse, pExpr, target);
4030 iMem = ++pParse->nMem;
4031 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4032 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004033}
drh2dcef112008-01-12 19:03:48 +00004034
drh678ccce2008-03-31 18:19:54 +00004035/*
drh268380c2004-02-25 13:47:31 +00004036** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004037** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004038**
drh892d3172008-01-10 03:46:36 +00004039** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00004040**
4041** The SQLITE_ECEL_DUP flag prevents the arguments from being
4042** filled using OP_SCopy. OP_Copy must be used instead.
4043**
4044** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4045** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004046**
4047** The SQLITE_ECEL_REF flag means that expressions in the list with
4048** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4049** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00004050*/
danielk19774adee202004-05-08 08:23:19 +00004051int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004052 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004053 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004054 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004055 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004056 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004057){
4058 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004059 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004060 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004061 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004062 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004063 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004064 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004065 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004066 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004067 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004068 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00004069 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
4070 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4071 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00004072 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00004073 }else{
4074 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4075 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004076 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004077 if( copyOp==OP_Copy
4078 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4079 && pOp->p1+pOp->p3+1==inReg
4080 && pOp->p2+pOp->p3+1==target+i
4081 ){
4082 pOp->p3++;
4083 }else{
4084 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4085 }
drhd1a01ed2013-11-21 16:08:52 +00004086 }
drhd1766112008-09-17 00:13:12 +00004087 }
drh268380c2004-02-25 13:47:31 +00004088 }
drhf9b596e2004-05-26 16:54:42 +00004089 return n;
drh268380c2004-02-25 13:47:31 +00004090}
4091
4092/*
drh36c563a2009-11-12 13:32:22 +00004093** Generate code for a BETWEEN operator.
4094**
4095** x BETWEEN y AND z
4096**
4097** The above is equivalent to
4098**
4099** x>=y AND x<=z
4100**
4101** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004102** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004103**
4104** The xJumpIf parameter determines details:
4105**
4106** NULL: Store the boolean result in reg[dest]
4107** sqlite3ExprIfTrue: Jump to dest if true
4108** sqlite3ExprIfFalse: Jump to dest if false
4109**
4110** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004111*/
4112static void exprCodeBetween(
4113 Parse *pParse, /* Parsing and code generating context */
4114 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004115 int dest, /* Jump destination or storage location */
4116 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004117 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4118){
drhdb45bd52016-08-22 00:48:58 +00004119 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004120 Expr compLeft; /* The x>=y term */
4121 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004122 Expr exprX; /* The x subexpression */
4123 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004124
drh36c563a2009-11-12 13:32:22 +00004125
dan71c57db2016-07-09 20:23:55 +00004126 memset(&compLeft, 0, sizeof(Expr));
4127 memset(&compRight, 0, sizeof(Expr));
4128 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004129
4130 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4131 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004132 exprAnd.op = TK_AND;
4133 exprAnd.pLeft = &compLeft;
4134 exprAnd.pRight = &compRight;
4135 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004136 compLeft.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004137 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4138 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004139 compRight.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004140 compRight.pRight = pExpr->x.pList->a[1].pExpr;
drh12abf402016-08-22 14:30:05 +00004141 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004142 if( xJump ){
4143 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004144 }else{
drhdb45bd52016-08-22 00:48:58 +00004145 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004146 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004147 }
drhdb45bd52016-08-22 00:48:58 +00004148 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004149
4150 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004151 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4152 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4153 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4154 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4155 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4156 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4157 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4158 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004159 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004160}
4161
4162/*
drhcce7d172000-05-31 15:34:51 +00004163** Generate code for a boolean expression such that a jump is made
4164** to the label "dest" if the expression is true but execution
4165** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004166**
4167** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004168** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004169**
4170** This code depends on the fact that certain token values (ex: TK_EQ)
4171** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4172** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4173** the make process cause these values to align. Assert()s in the code
4174** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004175*/
danielk19774adee202004-05-08 08:23:19 +00004176void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004177 Vdbe *v = pParse->pVdbe;
4178 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004179 int regFree1 = 0;
4180 int regFree2 = 0;
4181 int r1, r2;
4182
drh35573352008-01-08 23:54:25 +00004183 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004184 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004185 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004186 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004187 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004188 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004189 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004190 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004191 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004192 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004193 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4194 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004195 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004196 break;
4197 }
4198 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004199 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004200 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004201 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004202 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004203 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004204 break;
4205 }
4206 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004207 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004208 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004209 break;
4210 }
drhde845c22016-03-17 19:07:52 +00004211 case TK_IS:
4212 case TK_ISNOT:
4213 testcase( op==TK_IS );
4214 testcase( op==TK_ISNOT );
4215 op = (op==TK_IS) ? TK_EQ : TK_NE;
4216 jumpIfNull = SQLITE_NULLEQ;
4217 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004218 case TK_LT:
4219 case TK_LE:
4220 case TK_GT:
4221 case TK_GE:
4222 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004223 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004224 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004225 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004226 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4227 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004228 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004229 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004230 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4231 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4232 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4233 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004234 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4235 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4236 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4237 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4238 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4239 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004240 testcase( regFree1==0 );
4241 testcase( regFree2==0 );
4242 break;
4243 }
drhcce7d172000-05-31 15:34:51 +00004244 case TK_ISNULL:
4245 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004246 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4247 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004248 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4249 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004250 VdbeCoverageIf(v, op==TK_ISNULL);
4251 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004252 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004253 break;
4254 }
drhfef52082000-06-06 01:50:43 +00004255 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004256 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004257 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004258 break;
4259 }
drh84e30ca2011-02-10 17:46:14 +00004260#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004261 case TK_IN: {
4262 int destIfFalse = sqlite3VdbeMakeLabel(v);
4263 int destIfNull = jumpIfNull ? dest : destIfFalse;
4264 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004265 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004266 sqlite3VdbeResolveLabel(v, destIfFalse);
4267 break;
4268 }
shanehbb201342011-02-09 19:55:20 +00004269#endif
drhcce7d172000-05-31 15:34:51 +00004270 default: {
dan7b35a772016-07-28 19:47:15 +00004271 default_expr:
drh991a1982014-01-02 17:57:16 +00004272 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004273 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004274 }else if( exprAlwaysFalse(pExpr) ){
4275 /* No-op */
4276 }else{
4277 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4278 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004279 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004280 testcase( regFree1==0 );
4281 testcase( jumpIfNull==0 );
4282 }
drhcce7d172000-05-31 15:34:51 +00004283 break;
4284 }
4285 }
drh2dcef112008-01-12 19:03:48 +00004286 sqlite3ReleaseTempReg(pParse, regFree1);
4287 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004288}
4289
4290/*
drh66b89c82000-11-28 20:47:17 +00004291** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004292** to the label "dest" if the expression is false but execution
4293** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004294**
4295** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004296** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4297** is 0.
drhcce7d172000-05-31 15:34:51 +00004298*/
danielk19774adee202004-05-08 08:23:19 +00004299void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004300 Vdbe *v = pParse->pVdbe;
4301 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004302 int regFree1 = 0;
4303 int regFree2 = 0;
4304 int r1, r2;
4305
drh35573352008-01-08 23:54:25 +00004306 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004307 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004308 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004309
4310 /* The value of pExpr->op and op are related as follows:
4311 **
4312 ** pExpr->op op
4313 ** --------- ----------
4314 ** TK_ISNULL OP_NotNull
4315 ** TK_NOTNULL OP_IsNull
4316 ** TK_NE OP_Eq
4317 ** TK_EQ OP_Ne
4318 ** TK_GT OP_Le
4319 ** TK_LE OP_Gt
4320 ** TK_GE OP_Lt
4321 ** TK_LT OP_Ge
4322 **
4323 ** For other values of pExpr->op, op is undefined and unused.
4324 ** The value of TK_ and OP_ constants are arranged such that we
4325 ** can compute the mapping above using the following expression.
4326 ** Assert()s verify that the computation is correct.
4327 */
4328 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4329
4330 /* Verify correct alignment of TK_ and OP_ constants
4331 */
4332 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4333 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4334 assert( pExpr->op!=TK_NE || op==OP_Eq );
4335 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4336 assert( pExpr->op!=TK_LT || op==OP_Ge );
4337 assert( pExpr->op!=TK_LE || op==OP_Gt );
4338 assert( pExpr->op!=TK_GT || op==OP_Le );
4339 assert( pExpr->op!=TK_GE || op==OP_Lt );
4340
danba00e302016-07-23 20:24:06 +00004341 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004342 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004343 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004344 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004345 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004346 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004347 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004348 break;
4349 }
4350 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004351 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004352 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004353 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004354 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004355 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4356 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004357 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004358 break;
4359 }
4360 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004361 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004362 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004363 break;
4364 }
drhde845c22016-03-17 19:07:52 +00004365 case TK_IS:
4366 case TK_ISNOT:
4367 testcase( pExpr->op==TK_IS );
4368 testcase( pExpr->op==TK_ISNOT );
4369 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4370 jumpIfNull = SQLITE_NULLEQ;
4371 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004372 case TK_LT:
4373 case TK_LE:
4374 case TK_GT:
4375 case TK_GE:
4376 case TK_NE:
4377 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004378 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004379 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004380 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4381 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004382 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004383 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004384 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4385 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4386 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4387 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004388 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4389 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4390 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4391 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4392 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4393 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004394 testcase( regFree1==0 );
4395 testcase( regFree2==0 );
4396 break;
4397 }
drhcce7d172000-05-31 15:34:51 +00004398 case TK_ISNULL:
4399 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004400 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4401 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004402 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4403 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004404 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004405 break;
4406 }
drhfef52082000-06-06 01:50:43 +00004407 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004408 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004409 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004410 break;
4411 }
drh84e30ca2011-02-10 17:46:14 +00004412#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004413 case TK_IN: {
4414 if( jumpIfNull ){
4415 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4416 }else{
4417 int destIfNull = sqlite3VdbeMakeLabel(v);
4418 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4419 sqlite3VdbeResolveLabel(v, destIfNull);
4420 }
4421 break;
4422 }
shanehbb201342011-02-09 19:55:20 +00004423#endif
drhcce7d172000-05-31 15:34:51 +00004424 default: {
danba00e302016-07-23 20:24:06 +00004425 default_expr:
drh991a1982014-01-02 17:57:16 +00004426 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004427 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004428 }else if( exprAlwaysTrue(pExpr) ){
4429 /* no-op */
4430 }else{
4431 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4432 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004433 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004434 testcase( regFree1==0 );
4435 testcase( jumpIfNull==0 );
4436 }
drhcce7d172000-05-31 15:34:51 +00004437 break;
4438 }
4439 }
drh2dcef112008-01-12 19:03:48 +00004440 sqlite3ReleaseTempReg(pParse, regFree1);
4441 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004442}
drh22827922000-06-06 17:27:05 +00004443
4444/*
drh72bc8202015-06-11 13:58:35 +00004445** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4446** code generation, and that copy is deleted after code generation. This
4447** ensures that the original pExpr is unchanged.
4448*/
4449void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4450 sqlite3 *db = pParse->db;
4451 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4452 if( db->mallocFailed==0 ){
4453 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4454 }
4455 sqlite3ExprDelete(db, pCopy);
4456}
4457
4458
4459/*
drh1d9da702010-01-07 15:17:02 +00004460** Do a deep comparison of two expression trees. Return 0 if the two
4461** expressions are completely identical. Return 1 if they differ only
4462** by a COLLATE operator at the top level. Return 2 if there are differences
4463** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004464**
drh619a1302013-08-01 13:04:46 +00004465** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4466** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4467**
drh66518ca2013-08-01 15:09:57 +00004468** The pA side might be using TK_REGISTER. If that is the case and pB is
4469** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4470**
drh1d9da702010-01-07 15:17:02 +00004471** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004472** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004473** identical, we return 2 just to be safe. So if this routine
4474** returns 2, then you do not really know for certain if the two
4475** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004476** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004477** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004478** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004479** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00004480*/
drh619a1302013-08-01 13:04:46 +00004481int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004482 u32 combinedFlags;
4483 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004484 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004485 }
drh10d1edf2013-11-15 15:52:39 +00004486 combinedFlags = pA->flags | pB->flags;
4487 if( combinedFlags & EP_IntValue ){
4488 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4489 return 0;
4490 }
drh1d9da702010-01-07 15:17:02 +00004491 return 2;
drh22827922000-06-06 17:27:05 +00004492 }
drhc2acc4e2013-11-15 18:15:19 +00004493 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00004494 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004495 return 1;
4496 }
drh619a1302013-08-01 13:04:46 +00004497 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004498 return 1;
4499 }
4500 return 2;
4501 }
drh2edc5fd2015-11-24 02:10:52 +00004502 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004503 if( pA->op==TK_FUNCTION ){
4504 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4505 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00004506 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00004507 }
drh22827922000-06-06 17:27:05 +00004508 }
drh10d1edf2013-11-15 15:52:39 +00004509 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004510 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00004511 if( combinedFlags & EP_xIsSelect ) return 2;
4512 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4513 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4514 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00004515 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00004516 if( pA->iColumn!=pB->iColumn ) return 2;
4517 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004518 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004519 }
4520 }
drh1d9da702010-01-07 15:17:02 +00004521 return 0;
drh22827922000-06-06 17:27:05 +00004522}
4523
drh8c6f6662010-04-26 19:17:26 +00004524/*
4525** Compare two ExprList objects. Return 0 if they are identical and
4526** non-zero if they differ in any way.
4527**
drh619a1302013-08-01 13:04:46 +00004528** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4529** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4530**
drh8c6f6662010-04-26 19:17:26 +00004531** This routine might return non-zero for equivalent ExprLists. The
4532** only consequence will be disabled optimizations. But this routine
4533** must never return 0 if the two ExprList objects are different, or
4534** a malfunction will result.
4535**
4536** Two NULL pointers are considered to be the same. But a NULL pointer
4537** always differs from a non-NULL pointer.
4538*/
drh619a1302013-08-01 13:04:46 +00004539int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004540 int i;
4541 if( pA==0 && pB==0 ) return 0;
4542 if( pA==0 || pB==0 ) return 1;
4543 if( pA->nExpr!=pB->nExpr ) return 1;
4544 for(i=0; i<pA->nExpr; i++){
4545 Expr *pExprA = pA->a[i].pExpr;
4546 Expr *pExprB = pB->a[i].pExpr;
4547 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00004548 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004549 }
4550 return 0;
4551}
drh13449892005-09-07 21:22:45 +00004552
drh22827922000-06-06 17:27:05 +00004553/*
drh4bd5f732013-07-31 23:22:39 +00004554** Return true if we can prove the pE2 will always be true if pE1 is
4555** true. Return false if we cannot complete the proof or if pE2 might
4556** be false. Examples:
4557**
drh619a1302013-08-01 13:04:46 +00004558** pE1: x==5 pE2: x==5 Result: true
4559** pE1: x>0 pE2: x==5 Result: false
4560** pE1: x=21 pE2: x=21 OR y=43 Result: true
4561** pE1: x!=123 pE2: x IS NOT NULL Result: true
4562** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4563** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4564** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004565**
4566** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4567** Expr.iTable<0 then assume a table number given by iTab.
4568**
4569** When in doubt, return false. Returning true might give a performance
4570** improvement. Returning false might cause a performance reduction, but
4571** it will always give the correct answer and is hence always safe.
4572*/
4573int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00004574 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4575 return 1;
4576 }
4577 if( pE2->op==TK_OR
4578 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4579 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4580 ){
4581 return 1;
4582 }
4583 if( pE2->op==TK_NOTNULL
4584 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4585 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4586 ){
4587 return 1;
4588 }
4589 return 0;
drh4bd5f732013-07-31 23:22:39 +00004590}
4591
4592/*
drh030796d2012-08-23 16:18:10 +00004593** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00004594** to determine if an expression can be evaluated by reference to the
4595** index only, without having to do a search for the corresponding
4596** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4597** is the cursor for the table.
4598*/
4599struct IdxCover {
4600 Index *pIdx; /* The index to be tested for coverage */
4601 int iCur; /* Cursor number for the table corresponding to the index */
4602};
4603
4604/*
4605** Check to see if there are references to columns in table
4606** pWalker->u.pIdxCover->iCur can be satisfied using the index
4607** pWalker->u.pIdxCover->pIdx.
4608*/
4609static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4610 if( pExpr->op==TK_COLUMN
4611 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4612 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4613 ){
4614 pWalker->eCode = 1;
4615 return WRC_Abort;
4616 }
4617 return WRC_Continue;
4618}
4619
4620/*
drhe604ec02016-07-27 19:20:58 +00004621** Determine if an index pIdx on table with cursor iCur contains will
4622** the expression pExpr. Return true if the index does cover the
4623** expression and false if the pExpr expression references table columns
4624** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00004625**
4626** An index covering an expression means that the expression can be
4627** evaluated using only the index and without having to lookup the
4628** corresponding table entry.
4629*/
4630int sqlite3ExprCoveredByIndex(
4631 Expr *pExpr, /* The index to be tested */
4632 int iCur, /* The cursor number for the corresponding table */
4633 Index *pIdx /* The index that might be used for coverage */
4634){
4635 Walker w;
4636 struct IdxCover xcov;
4637 memset(&w, 0, sizeof(w));
4638 xcov.iCur = iCur;
4639 xcov.pIdx = pIdx;
4640 w.xExprCallback = exprIdxCover;
4641 w.u.pIdxCover = &xcov;
4642 sqlite3WalkExpr(&w, pExpr);
4643 return !w.eCode;
4644}
4645
4646
4647/*
4648** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00004649** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00004650** aggregate function, in order to implement the
4651** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00004652*/
drh030796d2012-08-23 16:18:10 +00004653struct SrcCount {
4654 SrcList *pSrc; /* One particular FROM clause in a nested query */
4655 int nThis; /* Number of references to columns in pSrcList */
4656 int nOther; /* Number of references to columns in other FROM clauses */
4657};
4658
4659/*
4660** Count the number of references to columns.
4661*/
4662static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00004663 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4664 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4665 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4666 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4667 ** NEVER() will need to be removed. */
4668 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00004669 int i;
drh030796d2012-08-23 16:18:10 +00004670 struct SrcCount *p = pWalker->u.pSrcCount;
4671 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00004672 int nSrc = pSrc ? pSrc->nSrc : 0;
4673 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00004674 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00004675 }
drh655814d2015-01-09 01:27:29 +00004676 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00004677 p->nThis++;
4678 }else{
4679 p->nOther++;
4680 }
drh374fdce2012-04-17 16:38:53 +00004681 }
drh030796d2012-08-23 16:18:10 +00004682 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004683}
4684
4685/*
drh030796d2012-08-23 16:18:10 +00004686** Determine if any of the arguments to the pExpr Function reference
4687** pSrcList. Return true if they do. Also return true if the function
4688** has no arguments or has only constant arguments. Return false if pExpr
4689** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004690*/
drh030796d2012-08-23 16:18:10 +00004691int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004692 Walker w;
drh030796d2012-08-23 16:18:10 +00004693 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004694 assert( pExpr->op==TK_AGG_FUNCTION );
4695 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004696 w.xExprCallback = exprSrcCount;
4697 w.u.pSrcCount = &cnt;
4698 cnt.pSrc = pSrcList;
4699 cnt.nThis = 0;
4700 cnt.nOther = 0;
4701 sqlite3WalkExprList(&w, pExpr->x.pList);
4702 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004703}
4704
4705/*
drh13449892005-09-07 21:22:45 +00004706** Add a new element to the pAggInfo->aCol[] array. Return the index of
4707** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004708*/
drh17435752007-08-16 04:30:38 +00004709static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004710 int i;
drhcf643722007-03-27 13:36:37 +00004711 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004712 db,
drhcf643722007-03-27 13:36:37 +00004713 pInfo->aCol,
4714 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004715 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004716 &i
4717 );
drh13449892005-09-07 21:22:45 +00004718 return i;
4719}
4720
4721/*
4722** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4723** the new element. Return a negative number if malloc fails.
4724*/
drh17435752007-08-16 04:30:38 +00004725static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004726 int i;
drhcf643722007-03-27 13:36:37 +00004727 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004728 db,
drhcf643722007-03-27 13:36:37 +00004729 pInfo->aFunc,
4730 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004731 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004732 &i
4733 );
drh13449892005-09-07 21:22:45 +00004734 return i;
4735}
drh22827922000-06-06 17:27:05 +00004736
4737/*
drh7d10d5a2008-08-20 16:35:10 +00004738** This is the xExprCallback for a tree walker. It is used to
4739** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004740** for additional information.
drh22827922000-06-06 17:27:05 +00004741*/
drh7d10d5a2008-08-20 16:35:10 +00004742static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004743 int i;
drh7d10d5a2008-08-20 16:35:10 +00004744 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004745 Parse *pParse = pNC->pParse;
4746 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004747 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004748
drh22827922000-06-06 17:27:05 +00004749 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004750 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004751 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004752 testcase( pExpr->op==TK_AGG_COLUMN );
4753 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004754 /* Check to see if the column is in one of the tables in the FROM
4755 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004756 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004757 struct SrcList_item *pItem = pSrcList->a;
4758 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4759 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004760 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004761 if( pExpr->iTable==pItem->iCursor ){
4762 /* If we reach this point, it means that pExpr refers to a table
4763 ** that is in the FROM clause of the aggregate query.
4764 **
4765 ** Make an entry for the column in pAggInfo->aCol[] if there
4766 ** is not an entry there already.
4767 */
drh7f906d62007-03-12 23:48:52 +00004768 int k;
drh13449892005-09-07 21:22:45 +00004769 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004770 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004771 if( pCol->iTable==pExpr->iTable &&
4772 pCol->iColumn==pExpr->iColumn ){
4773 break;
4774 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004775 }
danielk19771e536952007-08-16 10:09:01 +00004776 if( (k>=pAggInfo->nColumn)
4777 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4778 ){
drh7f906d62007-03-12 23:48:52 +00004779 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004780 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004781 pCol->iTable = pExpr->iTable;
4782 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004783 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004784 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004785 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004786 if( pAggInfo->pGroupBy ){
4787 int j, n;
4788 ExprList *pGB = pAggInfo->pGroupBy;
4789 struct ExprList_item *pTerm = pGB->a;
4790 n = pGB->nExpr;
4791 for(j=0; j<n; j++, pTerm++){
4792 Expr *pE = pTerm->pExpr;
4793 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4794 pE->iColumn==pExpr->iColumn ){
4795 pCol->iSorterColumn = j;
4796 break;
4797 }
4798 }
4799 }
4800 if( pCol->iSorterColumn<0 ){
4801 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4802 }
4803 }
4804 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4805 ** because it was there before or because we just created it).
4806 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4807 ** pAggInfo->aCol[] entry.
4808 */
drhebb6a652013-09-12 23:42:22 +00004809 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004810 pExpr->pAggInfo = pAggInfo;
4811 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004812 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004813 break;
4814 } /* endif pExpr->iTable==pItem->iCursor */
4815 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004816 }
drh7d10d5a2008-08-20 16:35:10 +00004817 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004818 }
4819 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004820 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004821 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004822 ){
drh13449892005-09-07 21:22:45 +00004823 /* Check to see if pExpr is a duplicate of another aggregate
4824 ** function that is already in the pAggInfo structure
4825 */
4826 struct AggInfo_func *pItem = pAggInfo->aFunc;
4827 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004828 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004829 break;
4830 }
drh22827922000-06-06 17:27:05 +00004831 }
drh13449892005-09-07 21:22:45 +00004832 if( i>=pAggInfo->nFunc ){
4833 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4834 */
danielk197714db2662006-01-09 16:12:04 +00004835 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004836 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004837 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004838 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004839 pItem = &pAggInfo->aFunc[i];
4840 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004841 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004842 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004843 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004844 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004845 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004846 if( pExpr->flags & EP_Distinct ){
4847 pItem->iDistinct = pParse->nTab++;
4848 }else{
4849 pItem->iDistinct = -1;
4850 }
drh13449892005-09-07 21:22:45 +00004851 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004852 }
drh13449892005-09-07 21:22:45 +00004853 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4854 */
drhc5cd1242013-09-12 16:50:49 +00004855 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004856 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004857 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004858 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004859 return WRC_Prune;
4860 }else{
4861 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004862 }
drh22827922000-06-06 17:27:05 +00004863 }
4864 }
drh7d10d5a2008-08-20 16:35:10 +00004865 return WRC_Continue;
4866}
4867static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004868 UNUSED_PARAMETER(pWalker);
4869 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004870 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004871}
4872
4873/*
drhe8abb4c2012-11-02 18:24:57 +00004874** Analyze the pExpr expression looking for aggregate functions and
4875** for variables that need to be added to AggInfo object that pNC->pAggInfo
4876** points to. Additional entries are made on the AggInfo object as
4877** necessary.
drh626a8792005-01-17 22:08:19 +00004878**
4879** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004880** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004881*/
drhd2b3e232008-01-23 14:51:49 +00004882void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004883 Walker w;
drh374fdce2012-04-17 16:38:53 +00004884 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004885 w.xExprCallback = analyzeAggregate;
4886 w.xSelectCallback = analyzeAggregatesInSelect;
4887 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004888 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004889 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004890}
drh5d9a4af2005-08-30 00:54:01 +00004891
4892/*
4893** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4894** expression list. Return the number of errors.
4895**
4896** If an error is found, the analysis is cut short.
4897*/
drhd2b3e232008-01-23 14:51:49 +00004898void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004899 struct ExprList_item *pItem;
4900 int i;
drh5d9a4af2005-08-30 00:54:01 +00004901 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004902 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4903 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004904 }
4905 }
drh5d9a4af2005-08-30 00:54:01 +00004906}
drh892d3172008-01-10 03:46:36 +00004907
4908/*
drhceea3322009-04-23 13:22:42 +00004909** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004910*/
4911int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004912 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004913 return ++pParse->nMem;
4914 }
danielk19772f425f62008-07-04 09:41:39 +00004915 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004916}
drhceea3322009-04-23 13:22:42 +00004917
4918/*
4919** Deallocate a register, making available for reuse for some other
4920** purpose.
4921**
4922** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004923** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004924** the register becomes stale.
4925*/
drh892d3172008-01-10 03:46:36 +00004926void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004927 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004928 int i;
4929 struct yColCache *p;
4930 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4931 if( p->iReg==iReg ){
4932 p->tempReg = 1;
4933 return;
4934 }
4935 }
drh892d3172008-01-10 03:46:36 +00004936 pParse->aTempReg[pParse->nTempReg++] = iReg;
4937 }
4938}
4939
4940/*
4941** Allocate or deallocate a block of nReg consecutive registers
4942*/
4943int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004944 int i, n;
4945 i = pParse->iRangeReg;
4946 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004947 if( nReg<=n ){
4948 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004949 pParse->iRangeReg += nReg;
4950 pParse->nRangeReg -= nReg;
4951 }else{
4952 i = pParse->nMem+1;
4953 pParse->nMem += nReg;
4954 }
4955 return i;
4956}
4957void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004958 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004959 if( nReg>pParse->nRangeReg ){
4960 pParse->nRangeReg = nReg;
4961 pParse->iRangeReg = iReg;
4962 }
4963}
drhcdc69552011-12-06 13:24:59 +00004964
4965/*
4966** Mark all temporary registers as being unavailable for reuse.
4967*/
4968void sqlite3ClearTempRegCache(Parse *pParse){
4969 pParse->nTempReg = 0;
4970 pParse->nRangeReg = 0;
4971}
drhbb9b5f22016-03-19 00:35:02 +00004972
4973/*
4974** Validate that no temporary register falls within the range of
4975** iFirst..iLast, inclusive. This routine is only call from within assert()
4976** statements.
4977*/
4978#ifdef SQLITE_DEBUG
4979int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4980 int i;
4981 if( pParse->nRangeReg>0
4982 && pParse->iRangeReg+pParse->nRangeReg<iLast
4983 && pParse->iRangeReg>=iFirst
4984 ){
4985 return 0;
4986 }
4987 for(i=0; i<pParse->nTempReg; i++){
4988 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4989 return 0;
4990 }
4991 }
4992 return 1;
4993}
4994#endif /* SQLITE_DEBUG */