blob: 2e09d07982ba2c93c7828fb3d6b1741c59516391 [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;
drh66860af2016-08-23 18:30:10 +00001492 int iFirst = pList ? pList->nExpr : 0;
drha1251bc2016-08-20 00:51:37 +00001493 if( pColumns==0 ) goto vector_append_error;
1494 if( pExpr==0 ) goto vector_append_error;
1495 n = sqlite3ExprVectorSize(pExpr);
1496 if( pColumns->nId!=n ){
1497 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1498 pColumns->nId, n);
1499 goto vector_append_error;
1500 }
1501 for(i=0; i<n; i++){
1502 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1503 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1504 if( pList ){
drh66860af2016-08-23 18:30:10 +00001505 assert( pList->nExpr==iFirst+i+1 );
drha1251bc2016-08-20 00:51:37 +00001506 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1507 pColumns->a[i].zName = 0;
1508 }
1509 }
1510 if( pExpr->op==TK_SELECT ){
drh66860af2016-08-23 18:30:10 +00001511 if( pList && pList->a[iFirst].pExpr ){
1512 assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN );
1513 pList->a[iFirst].pExpr->pRight = pExpr;
drha1251bc2016-08-20 00:51:37 +00001514 pExpr = 0;
1515 }
1516 }
1517
1518vector_append_error:
1519 sqlite3ExprDelete(db, pExpr);
1520 sqlite3IdListDelete(db, pColumns);
1521 return pList;
1522}
1523
1524/*
drhbc622bc2015-08-24 15:39:42 +00001525** Set the sort order for the last element on the given ExprList.
1526*/
1527void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1528 if( p==0 ) return;
1529 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1530 assert( p->nExpr>0 );
1531 if( iSortOrder<0 ){
1532 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1533 return;
1534 }
1535 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001536}
1537
1538/*
drhb7916a72009-05-27 10:31:29 +00001539** Set the ExprList.a[].zName element of the most recently added item
1540** on the expression list.
1541**
1542** pList might be NULL following an OOM error. But pName should never be
1543** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1544** is set.
1545*/
1546void sqlite3ExprListSetName(
1547 Parse *pParse, /* Parsing context */
1548 ExprList *pList, /* List to which to add the span. */
1549 Token *pName, /* Name to be added */
1550 int dequote /* True to cause the name to be dequoted */
1551){
1552 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1553 if( pList ){
1554 struct ExprList_item *pItem;
1555 assert( pList->nExpr>0 );
1556 pItem = &pList->a[pList->nExpr-1];
1557 assert( pItem->zName==0 );
1558 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001559 if( dequote ) sqlite3Dequote(pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001560 }
1561}
1562
1563/*
1564** Set the ExprList.a[].zSpan element of the most recently added item
1565** on the expression list.
1566**
1567** pList might be NULL following an OOM error. But pSpan should never be
1568** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1569** is set.
1570*/
1571void sqlite3ExprListSetSpan(
1572 Parse *pParse, /* Parsing context */
1573 ExprList *pList, /* List to which to add the span. */
1574 ExprSpan *pSpan /* The span to be added */
1575){
1576 sqlite3 *db = pParse->db;
1577 assert( pList!=0 || db->mallocFailed!=0 );
1578 if( pList ){
1579 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1580 assert( pList->nExpr>0 );
1581 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1582 sqlite3DbFree(db, pItem->zSpan);
1583 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001584 (int)(pSpan->zEnd - pSpan->zStart));
drhb7916a72009-05-27 10:31:29 +00001585 }
1586}
1587
1588/*
danielk19777a15a4b2007-05-08 17:54:43 +00001589** If the expression list pEList contains more than iLimit elements,
1590** leave an error message in pParse.
1591*/
1592void sqlite3ExprListCheckLength(
1593 Parse *pParse,
1594 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001595 const char *zObject
1596){
drhb1a6c3c2008-03-20 16:30:17 +00001597 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001598 testcase( pEList && pEList->nExpr==mx );
1599 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001600 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001601 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1602 }
1603}
1604
1605/*
drha76b5df2002-02-23 02:32:10 +00001606** Delete an entire expression list.
1607*/
drhaffa8552016-04-11 18:25:05 +00001608static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drha76b5df2002-02-23 02:32:10 +00001609 int i;
drhbe5c89a2004-07-26 00:31:09 +00001610 struct ExprList_item *pItem;
drhd872bb12012-02-02 01:58:08 +00001611 assert( pList->a!=0 || pList->nExpr==0 );
drhbe5c89a2004-07-26 00:31:09 +00001612 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00001613 sqlite3ExprDelete(db, pItem->pExpr);
1614 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001615 sqlite3DbFree(db, pItem->zSpan);
drha76b5df2002-02-23 02:32:10 +00001616 }
drh633e6d52008-07-28 19:34:53 +00001617 sqlite3DbFree(db, pList->a);
1618 sqlite3DbFree(db, pList);
drha76b5df2002-02-23 02:32:10 +00001619}
drhaffa8552016-04-11 18:25:05 +00001620void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1621 if( pList ) exprListDeleteNN(db, pList);
1622}
drha76b5df2002-02-23 02:32:10 +00001623
1624/*
drh2308ed32015-02-09 16:09:34 +00001625** Return the bitwise-OR of all Expr.flags fields in the given
1626** ExprList.
drh885a5b02015-02-09 15:21:36 +00001627*/
drh2308ed32015-02-09 16:09:34 +00001628u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001629 int i;
drh2308ed32015-02-09 16:09:34 +00001630 u32 m = 0;
1631 if( pList ){
1632 for(i=0; i<pList->nExpr; i++){
drhd0c73052015-04-19 19:21:19 +00001633 Expr *pExpr = pList->a[i].pExpr;
drhde845c22016-03-17 19:07:52 +00001634 assert( pExpr!=0 );
1635 m |= pExpr->flags;
drh2308ed32015-02-09 16:09:34 +00001636 }
drh885a5b02015-02-09 15:21:36 +00001637 }
drh2308ed32015-02-09 16:09:34 +00001638 return m;
drh885a5b02015-02-09 15:21:36 +00001639}
1640
1641/*
drh059b2d52014-10-24 19:28:09 +00001642** These routines are Walker callbacks used to check expressions to
1643** see if they are "constant" for some definition of constant. The
1644** Walker.eCode value determines the type of "constant" we are looking
1645** for.
drh73b211a2005-01-18 04:00:42 +00001646**
drh7d10d5a2008-08-20 16:35:10 +00001647** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001648**
drh059b2d52014-10-24 19:28:09 +00001649** sqlite3ExprIsConstant() pWalker->eCode==1
1650** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001651** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001652** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001653**
drh059b2d52014-10-24 19:28:09 +00001654** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1655** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001656**
drhfeada2d2014-09-24 13:20:22 +00001657** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001658** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1659** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001660** parameter raises an error for new statements, but is silently converted
1661** to NULL for existing schemas. This allows sqlite_master tables that
1662** contain a bound parameter because they were generated by older versions
1663** of SQLite to be parsed by newer versions of SQLite without raising a
1664** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001665*/
drh7d10d5a2008-08-20 16:35:10 +00001666static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001667
drh059b2d52014-10-24 19:28:09 +00001668 /* If pWalker->eCode is 2 then any term of the expression that comes from
1669 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001670 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001671 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1672 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001673 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001674 }
1675
drh626a8792005-01-17 22:08:19 +00001676 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001677 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001678 ** and either pWalker->eCode==4 or 5 or the function has the
1679 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001680 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001681 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001682 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001683 }else{
1684 pWalker->eCode = 0;
1685 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001686 }
drh626a8792005-01-17 22:08:19 +00001687 case TK_ID:
1688 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001689 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001690 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001691 testcase( pExpr->op==TK_ID );
1692 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001693 testcase( pExpr->op==TK_AGG_FUNCTION );
1694 testcase( pExpr->op==TK_AGG_COLUMN );
drh059b2d52014-10-24 19:28:09 +00001695 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1696 return WRC_Continue;
1697 }else{
1698 pWalker->eCode = 0;
1699 return WRC_Abort;
1700 }
drhfeada2d2014-09-24 13:20:22 +00001701 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001702 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001703 /* Silently convert bound parameters that appear inside of CREATE
1704 ** statements into a NULL when parsing the CREATE statement text out
1705 ** of the sqlite_master table */
1706 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001707 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001708 /* A bound parameter in a CREATE statement that originates from
1709 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001710 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001711 return WRC_Abort;
1712 }
1713 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001714 default:
drhb74b1012009-05-28 21:04:37 +00001715 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1716 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
drh7d10d5a2008-08-20 16:35:10 +00001717 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001718 }
1719}
danielk197762c14b32008-11-19 09:05:26 +00001720static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1721 UNUSED_PARAMETER(NotUsed);
drh059b2d52014-10-24 19:28:09 +00001722 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001723 return WRC_Abort;
1724}
drh059b2d52014-10-24 19:28:09 +00001725static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001726 Walker w;
drhaa87f9a2013-04-25 00:57:10 +00001727 memset(&w, 0, sizeof(w));
drh059b2d52014-10-24 19:28:09 +00001728 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001729 w.xExprCallback = exprNodeIsConstant;
1730 w.xSelectCallback = selectNodeIsConstant;
drh059b2d52014-10-24 19:28:09 +00001731 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001732 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001733 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001734}
drh626a8792005-01-17 22:08:19 +00001735
1736/*
drh059b2d52014-10-24 19:28:09 +00001737** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001738** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001739**
1740** For the purposes of this function, a double-quoted string (ex: "abc")
1741** is considered a variable but a single-quoted string (ex: 'abc') is
1742** a constant.
drhfef52082000-06-06 01:50:43 +00001743*/
danielk19774adee202004-05-08 08:23:19 +00001744int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001745 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001746}
1747
1748/*
drh059b2d52014-10-24 19:28:09 +00001749** Walk an expression tree. Return non-zero if the expression is constant
drh0a168372007-06-08 00:20:47 +00001750** that does no originate from the ON or USING clauses of a join.
1751** Return 0 if it involves variables or function calls or terms from
1752** an ON or USING clause.
1753*/
1754int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001755 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001756}
1757
1758/*
drhfcb9f4f2015-06-01 18:13:16 +00001759** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00001760** for any single row of the table with cursor iCur. In other words, the
1761** expression must not refer to any non-deterministic function nor any
1762** table other than iCur.
1763*/
1764int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1765 return exprIsConst(p, 3, iCur);
1766}
1767
1768/*
1769** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001770** or a function call with constant arguments. Return and 0 if there
1771** are any variables.
1772**
1773** For the purposes of this function, a double-quoted string (ex: "abc")
1774** is considered a variable but a single-quoted string (ex: 'abc') is
1775** a constant.
1776*/
drhfeada2d2014-09-24 13:20:22 +00001777int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1778 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00001779 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00001780}
1781
drh5b88bc42013-12-07 23:35:21 +00001782#ifdef SQLITE_ENABLE_CURSOR_HINTS
1783/*
1784** Walk an expression tree. Return 1 if the expression contains a
1785** subquery of some kind. Return 0 if there are no subqueries.
1786*/
1787int sqlite3ExprContainsSubquery(Expr *p){
1788 Walker w;
1789 memset(&w, 0, sizeof(w));
drhbec24762015-08-13 20:07:13 +00001790 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00001791 w.xExprCallback = sqlite3ExprWalkNoop;
1792 w.xSelectCallback = selectNodeIsConstant;
1793 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00001794 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00001795}
1796#endif
1797
drheb55bd22005-06-30 17:04:21 +00001798/*
drh73b211a2005-01-18 04:00:42 +00001799** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001800** to fit in a 32-bit integer, return 1 and put the value of the integer
1801** in *pValue. If the expression is not an integer or if it is too big
1802** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001803*/
danielk19774adee202004-05-08 08:23:19 +00001804int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00001805 int rc = 0;
drhcd92e842011-02-17 15:58:20 +00001806
1807 /* If an expression is an integer literal that fits in a signed 32-bit
1808 ** integer, then the EP_IntValue flag will have already been set */
1809 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1810 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1811
drh92b01d52008-06-24 00:32:35 +00001812 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00001813 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00001814 return 1;
1815 }
drhe4de1fe2002-06-02 16:09:01 +00001816 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00001817 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00001818 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00001819 break;
drh4b59ab52002-08-24 18:24:51 +00001820 }
drhe4de1fe2002-06-02 16:09:01 +00001821 case TK_UMINUS: {
1822 int v;
danielk19774adee202004-05-08 08:23:19 +00001823 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00001824 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00001825 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00001826 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00001827 }
1828 break;
1829 }
1830 default: break;
1831 }
drh92b01d52008-06-24 00:32:35 +00001832 return rc;
drhe4de1fe2002-06-02 16:09:01 +00001833}
1834
1835/*
drh039fc322009-11-17 18:31:47 +00001836** Return FALSE if there is no chance that the expression can be NULL.
1837**
1838** If the expression might be NULL or if the expression is too complex
1839** to tell return TRUE.
1840**
1841** This routine is used as an optimization, to skip OP_IsNull opcodes
1842** when we know that a value cannot be NULL. Hence, a false positive
1843** (returning TRUE when in fact the expression can never be NULL) might
1844** be a small performance hit but is otherwise harmless. On the other
1845** hand, a false negative (returning FALSE when the result could be NULL)
1846** will likely result in an incorrect answer. So when in doubt, return
1847** TRUE.
1848*/
1849int sqlite3ExprCanBeNull(const Expr *p){
1850 u8 op;
drhcd7f4572009-11-19 14:48:40 +00001851 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001852 op = p->op;
1853 if( op==TK_REGISTER ) op = p->op2;
1854 switch( op ){
1855 case TK_INTEGER:
1856 case TK_STRING:
1857 case TK_FLOAT:
1858 case TK_BLOB:
1859 return 0;
drh7248a8b2014-08-04 18:50:54 +00001860 case TK_COLUMN:
1861 assert( p->pTab!=0 );
drh72673a22014-12-04 16:27:17 +00001862 return ExprHasProperty(p, EP_CanBeNull) ||
1863 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00001864 default:
1865 return 1;
1866 }
1867}
1868
1869/*
1870** Return TRUE if the given expression is a constant which would be
1871** unchanged by OP_Affinity with the affinity given in the second
1872** argument.
1873**
1874** This routine is used to determine if the OP_Affinity operation
1875** can be omitted. When in doubt return FALSE. A false negative
1876** is harmless. A false positive, however, can result in the wrong
1877** answer.
1878*/
1879int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1880 u8 op;
drh05883a32015-06-02 15:32:08 +00001881 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00001882 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001883 op = p->op;
1884 if( op==TK_REGISTER ) op = p->op2;
1885 switch( op ){
1886 case TK_INTEGER: {
1887 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1888 }
1889 case TK_FLOAT: {
1890 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1891 }
1892 case TK_STRING: {
1893 return aff==SQLITE_AFF_TEXT;
1894 }
1895 case TK_BLOB: {
1896 return 1;
1897 }
drh2f2855b2009-11-18 01:25:26 +00001898 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00001899 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1900 return p->iColumn<0
1901 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00001902 }
drh039fc322009-11-17 18:31:47 +00001903 default: {
1904 return 0;
1905 }
1906 }
1907}
1908
1909/*
drhc4a3c772001-04-04 11:48:57 +00001910** Return TRUE if the given string is a row-id column name.
1911*/
danielk19774adee202004-05-08 08:23:19 +00001912int sqlite3IsRowid(const char *z){
1913 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1914 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1915 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001916 return 0;
1917}
1918
danielk19779a96b662007-11-29 17:05:18 +00001919/*
drh69c355b2016-03-09 15:34:51 +00001920** pX is the RHS of an IN operator. If pX is a SELECT statement
1921** that can be simplified to a direct table access, then return
1922** a pointer to the SELECT statement. If pX is not a SELECT statement,
1923** or if the SELECT statement needs to be manifested into a transient
1924** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00001925*/
1926#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00001927static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00001928 Select *p;
drhb287f4b2008-04-25 00:08:38 +00001929 SrcList *pSrc;
1930 ExprList *pEList;
1931 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00001932 int i;
drh69c355b2016-03-09 15:34:51 +00001933 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1934 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1935 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00001936 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00001937 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00001938 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1939 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1940 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00001941 }
drhb74b1012009-05-28 21:04:37 +00001942 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00001943 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb74b1012009-05-28 21:04:37 +00001944 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
drhb287f4b2008-04-25 00:08:38 +00001945 if( p->pWhere ) return 0; /* Has no WHERE clause */
1946 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00001947 assert( pSrc!=0 );
1948 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00001949 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00001950 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00001951 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00001952 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00001953 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1954 pEList = p->pEList;
dancfbb5e82016-07-13 19:48:13 +00001955
dan7b35a772016-07-28 19:47:15 +00001956 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00001957 for(i=0; i<pEList->nExpr; i++){
1958 Expr *pRes = pEList->a[i].pExpr;
1959 if( pRes->op!=TK_COLUMN ) return 0;
1960 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00001961 }
drh69c355b2016-03-09 15:34:51 +00001962 return p;
drhb287f4b2008-04-25 00:08:38 +00001963}
1964#endif /* SQLITE_OMIT_SUBQUERY */
1965
1966/*
dan1d8cb212011-12-09 13:24:16 +00001967** Code an OP_Once instruction and allocate space for its flag. Return the
1968** address of the new instruction.
1969*/
1970int sqlite3CodeOnce(Parse *pParse){
1971 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1972 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1973}
1974
danf9b2e052016-08-02 17:45:00 +00001975#ifndef SQLITE_OMIT_SUBQUERY
dan1d8cb212011-12-09 13:24:16 +00001976/*
drh4c259e92014-08-01 21:12:35 +00001977** Generate code that checks the left-most column of index table iCur to see if
1978** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00001979** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1980** to be set to NULL if iCur contains one or more NULL values.
1981*/
1982static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00001983 int addr1;
drh6be515e2014-08-01 21:00:53 +00001984 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00001985 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00001986 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
1987 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00001988 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00001989 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00001990}
danf9b2e052016-08-02 17:45:00 +00001991#endif
drh6be515e2014-08-01 21:00:53 +00001992
drhbb53ecb2014-08-02 21:03:33 +00001993
1994#ifndef SQLITE_OMIT_SUBQUERY
1995/*
1996** The argument is an IN operator with a list (not a subquery) on the
1997** right-hand side. Return TRUE if that list is constant.
1998*/
1999static int sqlite3InRhsIsConstant(Expr *pIn){
2000 Expr *pLHS;
2001 int res;
2002 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2003 pLHS = pIn->pLeft;
2004 pIn->pLeft = 0;
2005 res = sqlite3ExprIsConstant(pIn);
2006 pIn->pLeft = pLHS;
2007 return res;
2008}
2009#endif
2010
drh6be515e2014-08-01 21:00:53 +00002011/*
danielk19779a96b662007-11-29 17:05:18 +00002012** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00002013** The pX parameter is the expression on the RHS of the IN operator, which
2014** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00002015**
drhd4305ca2012-09-18 17:08:33 +00002016** The job of this routine is to find or create a b-tree object that can
2017** be used either to test for membership in the RHS set or to iterate through
2018** all members of the RHS set, skipping duplicates.
2019**
drh3a856252014-08-01 14:46:57 +00002020** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00002021** and pX->iTable is set to the index of that cursor.
2022**
drhb74b1012009-05-28 21:04:37 +00002023** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00002024**
drh1ccce442013-03-12 20:38:51 +00002025** IN_INDEX_ROWID - The cursor was opened on a database table.
2026** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2027** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2028** IN_INDEX_EPH - The cursor was opened on a specially created and
2029** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00002030** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2031** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00002032**
drhd4305ca2012-09-18 17:08:33 +00002033** An existing b-tree might be used if the RHS expression pX is a simple
2034** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00002035**
dan553168c2016-08-01 20:14:31 +00002036** SELECT <column1>, <column2>... FROM <table>
danielk19779a96b662007-11-29 17:05:18 +00002037**
drhd4305ca2012-09-18 17:08:33 +00002038** If the RHS of the IN operator is a list or a more complex subquery, then
2039** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00002040** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00002041** existing table.
drhd4305ca2012-09-18 17:08:33 +00002042**
drh3a856252014-08-01 14:46:57 +00002043** The inFlags parameter must contain exactly one of the bits
2044** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
2045** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
2046** fast membership test. When the IN_INDEX_LOOP bit is set, the
2047** IN index will be used to loop over all values of the RHS of the
2048** IN operator.
2049**
2050** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2051** through the set members) then the b-tree must not contain duplicates.
dan553168c2016-08-01 20:14:31 +00002052** An epheremal table must be used unless the selected columns are guaranteed
2053** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2054** a UNIQUE constraint or index.
danielk19770cdc0222008-06-26 18:04:03 +00002055**
drh3a856252014-08-01 14:46:57 +00002056** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2057** for fast set membership tests) then an epheremal table must
dan553168c2016-08-01 20:14:31 +00002058** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2059** index can be found with the specified <columns> as its left-most.
danielk19770cdc0222008-06-26 18:04:03 +00002060**
drhbb53ecb2014-08-02 21:03:33 +00002061** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2062** if the RHS of the IN operator is a list (not a subquery) then this
2063** routine might decide that creating an ephemeral b-tree for membership
2064** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2065** calling routine should implement the IN operator using a sequence
2066** of Eq or Ne comparison operations.
2067**
drhb74b1012009-05-28 21:04:37 +00002068** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00002069** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00002070** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00002071** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00002072** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00002073** to *prRhsHasNull. If there is no chance that the (...) contains a
2074** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00002075**
drhe21a6e12014-08-01 18:00:24 +00002076** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00002077** the value in that register will be NULL if the b-tree contains one or more
2078** NULL values, and it will be some non-NULL value if the b-tree contains no
2079** NULL values.
dan553168c2016-08-01 20:14:31 +00002080**
2081** If the aiMap parameter is not NULL, it must point to an array containing
2082** one element for each column returned by the SELECT statement on the RHS
2083** of the IN(...) operator. The i'th entry of the array is populated with the
2084** offset of the index column that matches the i'th column returned by the
2085** SELECT. For example, if the expression and selected index are:
2086**
2087** (?,?,?) IN (SELECT a, b, c FROM t1)
2088** CREATE INDEX i1 ON t1(b, c, a);
2089**
2090** then aiMap[] is populated with {2, 0, 1}.
danielk19779a96b662007-11-29 17:05:18 +00002091*/
danielk1977284f4ac2007-12-10 05:03:46 +00002092#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00002093int sqlite3FindInIndex(
2094 Parse *pParse,
2095 Expr *pX,
2096 u32 inFlags,
2097 int *prRhsHasNull,
2098 int *aiMap
2099){
drhb74b1012009-05-28 21:04:37 +00002100 Select *p; /* SELECT to the right of IN operator */
2101 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2102 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00002103 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00002104 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00002105
drh1450bc62009-10-30 13:25:56 +00002106 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00002107 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00002108
dan7b35a772016-07-28 19:47:15 +00002109 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2110 ** whether or not the SELECT result contains NULL values, check whether
dan870a0702016-08-01 16:37:43 +00002111 ** or not NULL is actually possible (it may not be, for example, due
dan7b35a772016-07-28 19:47:15 +00002112 ** to NOT NULL constraints in the schema). If no NULL values are possible,
dan870a0702016-08-01 16:37:43 +00002113 ** set prRhsHasNull to 0 before continuing. */
dan7b35a772016-07-28 19:47:15 +00002114 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2115 int i;
2116 ExprList *pEList = pX->x.pSelect->pEList;
2117 for(i=0; i<pEList->nExpr; i++){
2118 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2119 }
2120 if( i==pEList->nExpr ){
2121 prRhsHasNull = 0;
2122 }
2123 }
2124
drhb74b1012009-05-28 21:04:37 +00002125 /* Check to see if an existing table or index can be used to
2126 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00002127 ** ephemeral table. */
2128 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00002129 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00002130 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00002131 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00002132 ExprList *pEList = p->pEList;
2133 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00002134
drhb07028f2011-10-14 21:49:18 +00002135 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2136 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2137 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2138 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00002139
drhb22f7c82014-02-06 23:56:27 +00002140 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00002141 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2142 sqlite3CodeVerifySchema(pParse, iDb);
2143 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00002144
2145 /* This function is only called from two places. In both cases the vdbe
2146 ** has already been allocated. So assume sqlite3GetVdbe() is always
2147 ** successful here.
2148 */
2149 assert(v);
dancfbb5e82016-07-13 19:48:13 +00002150 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh7d176102014-02-18 03:07:12 +00002151 int iAddr = sqlite3CodeOnce(pParse);
2152 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002153
2154 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2155 eType = IN_INDEX_ROWID;
2156
2157 sqlite3VdbeJumpHere(v, iAddr);
2158 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002159 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002160 int affinity_ok = 1;
2161 int i;
2162
2163 /* Check that the affinity that will be used to perform each
2164 ** comparison is the same as the affinity of each column. If
2165 ** it not, it is not possible to use any index. */
2166 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002167 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002168 int iCol = pEList->a[i].pExpr->iColumn;
2169 char idxaff = pTab->aCol[iCol].affinity;
2170 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2171 switch( cmpaff ){
2172 case SQLITE_AFF_BLOB:
2173 break;
2174 case SQLITE_AFF_TEXT:
2175 affinity_ok = (idxaff==SQLITE_AFF_TEXT);
2176 break;
2177 default:
2178 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2179 }
2180 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002181
drhb74b1012009-05-28 21:04:37 +00002182 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00002183 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00002184 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00002185
2186 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
dancfbb5e82016-07-13 19:48:13 +00002187 if( pIdx->nKeyCol<nExpr ) continue;
2188 if( mustBeUnique && (pIdx->nKeyCol!=nExpr || !IsUniqueIndex(pIdx)) ){
2189 continue;
2190 }
2191
2192 for(i=0; i<nExpr; i++){
drhfc7f27b2016-08-20 00:07:01 +00002193 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002194 Expr *pRhs = pEList->a[i].pExpr;
2195 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2196 int j;
2197
dan17994e32016-08-11 12:01:52 +00002198 assert( pReq || pParse->nErr );
2199 if( pReq==0 ) break;
2200
dancfbb5e82016-07-13 19:48:13 +00002201 for(j=0; j<nExpr; j++){
2202 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2203 assert( pIdx->azColl[j] );
2204 if( sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ) continue;
2205 break;
2206 }
2207 if( j==nExpr ) break;
danba00e302016-07-23 20:24:06 +00002208 if( aiMap ) aiMap[i] = j;
dancfbb5e82016-07-13 19:48:13 +00002209 }
2210
2211 if( i==nExpr ){
drh7d176102014-02-18 03:07:12 +00002212 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00002213 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2214 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00002215 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00002216 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2217 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00002218
dan7b35a772016-07-28 19:47:15 +00002219 if( prRhsHasNull ){
2220 *prRhsHasNull = ++pParse->nMem;
dan3480bfd2016-06-16 17:14:02 +00002221#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
dancfbb5e82016-07-13 19:48:13 +00002222 i64 mask = (1<<nExpr)-1;
dan3480bfd2016-06-16 17:14:02 +00002223 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
dancfbb5e82016-07-13 19:48:13 +00002224 iTab, 0, 0, (u8*)&mask, P4_INT64);
dan3480bfd2016-06-16 17:14:02 +00002225#endif
dan7b35a772016-07-28 19:47:15 +00002226 if( nExpr==1 ){
2227 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2228 }
danielk19770cdc0222008-06-26 18:04:03 +00002229 }
drh552fd452014-02-18 01:07:38 +00002230 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00002231 }
2232 }
2233 }
2234 }
2235
drhbb53ecb2014-08-02 21:03:33 +00002236 /* If no preexisting index is available for the IN clause
2237 ** and IN_INDEX_NOOP is an allowed reply
2238 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002239 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002240 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002241 ** the IN operator so return IN_INDEX_NOOP.
2242 */
2243 if( eType==0
2244 && (inFlags & IN_INDEX_NOOP_OK)
2245 && !ExprHasProperty(pX, EP_xIsSelect)
2246 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2247 ){
2248 eType = IN_INDEX_NOOP;
2249 }
drhbb53ecb2014-08-02 21:03:33 +00002250
danielk19779a96b662007-11-29 17:05:18 +00002251 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002252 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002253 ** We will have to generate an ephemeral table to do the job.
2254 */
drh8e23daf2013-06-11 13:30:04 +00002255 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002256 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002257 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002258 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002259 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00002260 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00002261 eType = IN_INDEX_ROWID;
2262 }
drhe21a6e12014-08-01 18:00:24 +00002263 }else if( prRhsHasNull ){
2264 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002265 }
danielk197741a05b72008-10-02 13:50:55 +00002266 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002267 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002268 }else{
2269 pX->iTable = iTab;
2270 }
danba00e302016-07-23 20:24:06 +00002271
2272 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2273 int i, n;
2274 n = sqlite3ExprVectorSize(pX->pLeft);
2275 for(i=0; i<n; i++) aiMap[i] = i;
2276 }
danielk19779a96b662007-11-29 17:05:18 +00002277 return eType;
2278}
danielk1977284f4ac2007-12-10 05:03:46 +00002279#endif
drh626a8792005-01-17 22:08:19 +00002280
danf9b2e052016-08-02 17:45:00 +00002281#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002282/*
2283** Argument pExpr is an (?, ?...) IN(...) expression. This
2284** function allocates and returns a nul-terminated string containing
2285** the affinities to be used for each column of the comparison.
2286**
2287** It is the responsibility of the caller to ensure that the returned
2288** string is eventually freed using sqlite3DbFree().
2289*/
dan71c57db2016-07-09 20:23:55 +00002290static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2291 Expr *pLeft = pExpr->pLeft;
2292 int nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002293 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002294 char *zRet;
2295
dan553168c2016-08-01 20:14:31 +00002296 assert( pExpr->op==TK_IN );
dan71c57db2016-07-09 20:23:55 +00002297 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2298 if( zRet ){
2299 int i;
2300 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002301 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002302 char a = sqlite3ExprAffinity(pA);
2303 if( pSelect ){
2304 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2305 }else{
2306 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002307 }
dan71c57db2016-07-09 20:23:55 +00002308 }
2309 zRet[nVal] = '\0';
2310 }
2311 return zRet;
2312}
danf9b2e052016-08-02 17:45:00 +00002313#endif
dan71c57db2016-07-09 20:23:55 +00002314
dan8da209b2016-07-26 18:06:08 +00002315#ifndef SQLITE_OMIT_SUBQUERY
2316/*
2317** Load the Parse object passed as the first argument with an error
2318** message of the form:
2319**
2320** "sub-select returns N columns - expected M"
2321*/
2322void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2323 const char *zFmt = "sub-select returns %d columns - expected %d";
2324 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2325}
2326#endif
2327
drh626a8792005-01-17 22:08:19 +00002328/*
drhd4187c72010-08-30 22:15:45 +00002329** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2330** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002331**
drh9cbe6352005-11-29 03:13:21 +00002332** (SELECT a FROM b) -- subquery
2333** EXISTS (SELECT a FROM b) -- EXISTS subquery
2334** x IN (4,5,11) -- IN operator with list on right-hand side
2335** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002336**
drh9cbe6352005-11-29 03:13:21 +00002337** The pExpr parameter describes the expression that contains the IN
2338** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002339**
2340** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2341** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2342** to some integer key column of a table B-Tree. In this case, use an
2343** intkey B-Tree to store the set of IN(...) values instead of the usual
2344** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002345**
2346** If rMayHaveNull is non-zero, that means that the operation is an IN
2347** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002348** All this routine does is initialize the register given by rMayHaveNull
2349** to NULL. Calling routines will take care of changing this register
2350** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002351**
2352** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002353** result. For a multi-column SELECT, the result is stored in a contiguous
2354** array of registers and the return value is the register of the left-most
2355** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002356*/
drh51522cd2005-01-20 13:36:19 +00002357#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002358int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002359 Parse *pParse, /* Parsing context */
2360 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002361 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002362 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002363){
drh6be515e2014-08-01 21:00:53 +00002364 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002365 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002366 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002367 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00002368 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002369
drh39a11812016-08-19 19:12:58 +00002370 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2371 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002372 **
2373 ** * The right-hand side is a correlated subquery
2374 ** * The right-hand side is an expression list containing variables
2375 ** * We are inside a trigger
2376 **
2377 ** If all of the above are false, then we can run this code just once
2378 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002379 */
drhc5cd1242013-09-12 16:50:49 +00002380 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00002381 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002382 }
2383
dan4a07e3d2010-11-09 14:48:59 +00002384#ifndef SQLITE_OMIT_EXPLAIN
2385 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00002386 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2387 jmpIfDynamic>=0?"":"CORRELATED ",
2388 pExpr->op==TK_IN?"LIST":"SCALAR",
2389 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00002390 );
2391 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2392 }
2393#endif
2394
drhcce7d172000-05-31 15:34:51 +00002395 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002396 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002397 int addr; /* Address of OP_OpenEphemeral instruction */
2398 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002399 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002400 int nVal; /* Size of vector pLeft */
2401
2402 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002403 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002404
2405 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002406 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002407 ** filled with index keys representing the results from the
2408 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002409 **
2410 ** If the 'x' expression is a column value, or the SELECT...
2411 ** statement returns a column value, then the affinity of that
2412 ** column is used to build the index keys. If both 'x' and the
2413 ** SELECT... statement are columns, then numeric affinity is used
2414 ** if either column has NUMERIC or INTEGER affinity. If neither
2415 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2416 ** is used.
2417 */
2418 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002419 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2420 pExpr->iTable, (isRowid?0:nVal));
2421 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002422
danielk19776ab3a2e2009-02-19 14:39:25 +00002423 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00002424 /* Case 1: expr IN (SELECT ...)
2425 **
danielk1977e014a832004-05-17 10:48:57 +00002426 ** Generate code to write the results of the select into the temporary
2427 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002428 */
drh43870062014-07-31 15:44:44 +00002429 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002430 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002431
danielk197741a05b72008-10-02 13:50:55 +00002432 assert( !isRowid );
dan71c57db2016-07-09 20:23:55 +00002433 if( pEList->nExpr!=nVal ){
dan8da209b2016-07-26 18:06:08 +00002434 sqlite3SubselectError(pParse, pEList->nExpr, nVal);
dan71c57db2016-07-09 20:23:55 +00002435 }else{
2436 SelectDest dest;
2437 int i;
2438 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2439 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2440 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2441 pSelect->iLimit = 0;
2442 testcase( pSelect->selFlags & SF_Distinct );
2443 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2444 if( sqlite3Select(pParse, pSelect, &dest) ){
2445 sqlite3DbFree(pParse->db, dest.zAffSdst);
2446 sqlite3KeyInfoUnref(pKeyInfo);
2447 return 0;
2448 }
2449 sqlite3DbFree(pParse->db, dest.zAffSdst);
2450 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2451 assert( pEList!=0 );
2452 assert( pEList->nExpr>0 );
2453 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2454 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002455 Expr *p = (nVal>1) ? sqlite3VectorFieldSubexpr(pLeft, i) : pLeft;
dan71c57db2016-07-09 20:23:55 +00002456 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2457 pParse, p, pEList->a[i].pExpr
2458 );
2459 }
drh94ccde52007-04-13 16:06:32 +00002460 }
drha7d2db12010-07-14 20:23:52 +00002461 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002462 /* Case 2: expr IN (exprlist)
2463 **
drhfd131da2007-08-07 17:13:03 +00002464 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002465 ** store it in the temporary table. If <expr> is a column, then use
2466 ** that columns affinity when building index keys. If <expr> is not
2467 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002468 */
dan71c57db2016-07-09 20:23:55 +00002469 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002470 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002471 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002472 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002473 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002474
dan71c57db2016-07-09 20:23:55 +00002475 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002476 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002477 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002478 }
drh323df792013-08-05 19:11:29 +00002479 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002480 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002481 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2482 }
danielk1977e014a832004-05-17 10:48:57 +00002483
2484 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002485 r1 = sqlite3GetTempReg(pParse);
2486 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002487 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002488 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2489 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002490 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002491
drh57dbd7b2005-07-08 18:25:26 +00002492 /* If the expression is not constant then we will need to
2493 ** disable the test that was generated above that makes sure
2494 ** this code only executes once. Because for a non-constant
2495 ** expression we need to rerun this code each time.
2496 */
drh6be515e2014-08-01 21:00:53 +00002497 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2498 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2499 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002500 }
danielk1977e014a832004-05-17 10:48:57 +00002501
2502 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002503 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2504 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002505 }else{
drhe05c9292009-10-29 13:48:10 +00002506 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2507 if( isRowid ){
2508 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2509 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002510 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002511 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2512 }else{
2513 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2514 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2515 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2516 }
danielk197741a05b72008-10-02 13:50:55 +00002517 }
drhfef52082000-06-06 01:50:43 +00002518 }
drh2d401ab2008-01-10 23:50:11 +00002519 sqlite3ReleaseTempReg(pParse, r1);
2520 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002521 }
drh323df792013-08-05 19:11:29 +00002522 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002523 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002524 }
danielk1977b3bce662005-01-29 08:32:43 +00002525 break;
drhfef52082000-06-06 01:50:43 +00002526 }
2527
drh51522cd2005-01-20 13:36:19 +00002528 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002529 case TK_SELECT:
2530 default: {
drh39a11812016-08-19 19:12:58 +00002531 /* Case 3: (SELECT ... FROM ...)
2532 ** or: EXISTS(SELECT ... FROM ...)
2533 **
2534 ** For a SELECT, generate code to put the values for all columns of
2535 ** the first row into an array of registers and return the index of
2536 ** the first register.
2537 **
2538 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2539 ** into a register and return that register number.
2540 **
2541 ** In both cases, the query is augmented with "LIMIT 1". Any
2542 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002543 */
drhfd773cf2009-05-29 14:39:07 +00002544 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002545 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002546 int nReg; /* Registers to allocate */
drh1398ad32005-01-19 23:24:50 +00002547
shanecf697392009-06-01 16:53:09 +00002548 testcase( pExpr->op==TK_EXISTS );
2549 testcase( pExpr->op==TK_SELECT );
2550 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
danielk19776ab3a2e2009-02-19 14:39:25 +00002551 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
dan71c57db2016-07-09 20:23:55 +00002552
danielk19776ab3a2e2009-02-19 14:39:25 +00002553 pSel = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002554 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2555 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2556 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002557 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002558 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002559 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002560 dest.nSdst = nReg;
2561 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002562 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002563 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002564 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002565 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002566 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002567 }
drh633e6d52008-07-28 19:34:53 +00002568 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002569 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2570 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002571 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002572 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002573 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002574 return 0;
drh94ccde52007-04-13 16:06:32 +00002575 }
drh2b596da2012-07-23 21:43:19 +00002576 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002577 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002578 break;
drhcce7d172000-05-31 15:34:51 +00002579 }
2580 }
danielk1977b3bce662005-01-29 08:32:43 +00002581
drh6be515e2014-08-01 21:00:53 +00002582 if( rHasNullFlag ){
2583 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002584 }
drh6be515e2014-08-01 21:00:53 +00002585
2586 if( jmpIfDynamic>=0 ){
2587 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002588 }
drhd2490902014-04-13 19:28:15 +00002589 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002590
drh1450bc62009-10-30 13:25:56 +00002591 return rReg;
drhcce7d172000-05-31 15:34:51 +00002592}
drh51522cd2005-01-20 13:36:19 +00002593#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002594
drhe3365e62009-11-12 17:52:24 +00002595#ifndef SQLITE_OMIT_SUBQUERY
2596/*
dan7b35a772016-07-28 19:47:15 +00002597** Expr pIn is an IN(...) expression. This function checks that the
2598** sub-select on the RHS of the IN() operator has the same number of
2599** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2600** a sub-query, that the LHS is a vector of size 1.
2601*/
2602int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2603 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2604 if( (pIn->flags & EP_xIsSelect) ){
2605 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2606 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2607 return 1;
2608 }
2609 }else if( nVector!=1 ){
2610 if( (pIn->pLeft->flags & EP_xIsSelect) ){
2611 sqlite3SubselectError(pParse, nVector, 1);
2612 }else{
2613 sqlite3ErrorMsg(pParse, "invalid use of row value");
2614 }
2615 return 1;
2616 }
2617 return 0;
2618}
2619#endif
2620
2621#ifndef SQLITE_OMIT_SUBQUERY
2622/*
drhe3365e62009-11-12 17:52:24 +00002623** Generate code for an IN expression.
2624**
2625** x IN (SELECT ...)
2626** x IN (value, value, ...)
2627**
2628** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
2629** is an array of zero or more values. The expression is true if the LHS is
2630** contained within the RHS. The value of the expression is unknown (NULL)
2631** if the LHS is NULL or if the LHS is not contained within the RHS and the
2632** RHS contains one or more NULL values.
2633**
drh6be515e2014-08-01 21:00:53 +00002634** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002635** contained within the RHS. If due to NULLs we cannot determine if the LHS
2636** is contained in the RHS then jump to destIfNull. If the LHS is contained
2637** within the RHS then fall through.
2638*/
2639static void sqlite3ExprCodeIN(
2640 Parse *pParse, /* Parsing and code generating context */
2641 Expr *pExpr, /* The IN expression */
2642 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2643 int destIfNull /* Jump here if the results are unknown due to NULLs */
2644){
2645 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002646 int eType; /* Type of the RHS */
drh12abf402016-08-22 14:30:05 +00002647 int r1, r2; /* Temporary use registers */
drhe3365e62009-11-12 17:52:24 +00002648 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002649 int *aiMap = 0; /* Map from vector field to index column */
2650 char *zAff = 0; /* Affinity string for comparisons */
2651 int nVector; /* Size of vectors for this IN(...) op */
drh12abf402016-08-22 14:30:05 +00002652 int iDummy; /* Dummy parameter to exprCodeVector() */
danba00e302016-07-23 20:24:06 +00002653 Expr *pLeft = pExpr->pLeft;
2654 int i;
drhe3365e62009-11-12 17:52:24 +00002655
dan7b35a772016-07-28 19:47:15 +00002656 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00002657 zAff = exprINAffinity(pParse, pExpr);
drha48d7e72016-08-12 11:01:20 +00002658 if( zAff==0 ) return;
danba00e302016-07-23 20:24:06 +00002659 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2660 aiMap = (int*)sqlite3DbMallocZero(
2661 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2662 );
drha48d7e72016-08-12 11:01:20 +00002663 if( aiMap==0 ){
2664 sqlite3DbFree(pParse->db, zAff);
dan553168c2016-08-01 20:14:31 +00002665 return;
2666 }
dan7b35a772016-07-28 19:47:15 +00002667
danba00e302016-07-23 20:24:06 +00002668 /* Attempt to compute the RHS. After this step, if anything other than
2669 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2670 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2671 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00002672 v = pParse->pVdbe;
2673 assert( v!=0 ); /* OOM detected prior to this routine */
2674 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002675 eType = sqlite3FindInIndex(pParse, pExpr,
2676 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00002677 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00002678
danba00e302016-07-23 20:24:06 +00002679 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2680 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2681 );
drhe3365e62009-11-12 17:52:24 +00002682
danba00e302016-07-23 20:24:06 +00002683 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2684 ** vector, then it is stored in an array of nVector registers starting
2685 ** at r1.
drhe3365e62009-11-12 17:52:24 +00002686 */
danba00e302016-07-23 20:24:06 +00002687 r1 = sqlite3GetTempRange(pParse, nVector);
drhe3365e62009-11-12 17:52:24 +00002688 sqlite3ExprCachePush(pParse);
drh12abf402016-08-22 14:30:05 +00002689 r2 = exprCodeVector(pParse, pLeft, &iDummy);
2690 for(i=0; i<nVector; i++){
2691 sqlite3VdbeAddOp3(v, OP_Copy, r2+i, r1+aiMap[i], 0);
danba00e302016-07-23 20:24:06 +00002692 }
drhe3365e62009-11-12 17:52:24 +00002693
drhbb53ecb2014-08-02 21:03:33 +00002694 /* If sqlite3FindInIndex() did not find or create an index that is
2695 ** suitable for evaluating the IN operator, then evaluate using a
2696 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002697 */
drhbb53ecb2014-08-02 21:03:33 +00002698 if( eType==IN_INDEX_NOOP ){
2699 ExprList *pList = pExpr->x.pList;
2700 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2701 int labelOk = sqlite3VdbeMakeLabel(v);
2702 int r2, regToFree;
2703 int regCkNull = 0;
2704 int ii;
2705 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002706 if( destIfNull!=destIfFalse ){
2707 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002708 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002709 }
2710 for(ii=0; ii<pList->nExpr; ii++){
2711 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002712 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002713 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2714 }
2715 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2716 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002717 (void*)pColl, P4_COLLSEQ);
2718 VdbeCoverageIf(v, ii<pList->nExpr-1);
2719 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00002720 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00002721 }else{
2722 assert( destIfNull==destIfFalse );
2723 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2724 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00002725 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00002726 }
2727 sqlite3ReleaseTempReg(pParse, regToFree);
2728 }
2729 if( regCkNull ){
2730 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002731 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002732 }
2733 sqlite3VdbeResolveLabel(v, labelOk);
2734 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002735 }else{
drhbb53ecb2014-08-02 21:03:33 +00002736
dan7b35a772016-07-28 19:47:15 +00002737 /* If any value on the LHS is NULL, the result of the IN(...) operator
2738 ** must be either false or NULL. If these two are handled identically,
2739 ** test the LHS for NULLs and jump directly to destIfNull if any are
2740 ** found.
2741 **
2742 ** Otherwise, if NULL and false are handled differently, and the
2743 ** IN(...) operation is not a vector operation, and the LHS of the
2744 ** operator is NULL, then the result is false if the index is
2745 ** completely empty, or NULL otherwise. */
dand49fd4e2016-07-27 19:33:04 +00002746 if( destIfNull==destIfFalse ){
2747 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002748 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dand49fd4e2016-07-27 19:33:04 +00002749 if( sqlite3ExprCanBeNull(p) ){
2750 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002751 VdbeCoverage(v);
dand49fd4e2016-07-27 19:33:04 +00002752 }
drh7248a8b2014-08-04 18:50:54 +00002753 }
dand49fd4e2016-07-27 19:33:04 +00002754 }else if( nVector==1 && sqlite3ExprCanBeNull(pExpr->pLeft) ){
2755 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2756 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2757 VdbeCoverage(v);
2758 sqlite3VdbeGoto(v, destIfNull);
2759 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002760 }
2761
2762 if( eType==IN_INDEX_ROWID ){
dan7b35a772016-07-28 19:47:15 +00002763 /* In this case, the RHS is the ROWID of table b-tree */
drheeb95652016-05-26 20:56:38 +00002764 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002765 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002766 }else{
dan7b35a772016-07-28 19:47:15 +00002767 /* In this case, the RHS is an index b-tree. Apply the comparison
2768 ** affinities to each value on the LHS of the operator. */
danba00e302016-07-23 20:24:06 +00002769 sqlite3VdbeAddOp4(v, OP_Affinity, r1, nVector, 0, zAff, nVector);
dan7b35a772016-07-28 19:47:15 +00002770
2771 if( nVector>1 && destIfNull!=destIfFalse ){
2772 int iIdx = pExpr->iTable;
2773 int addr;
2774 int addrNext;
2775
2776 /* Search the index for the key. */
2777 addr = sqlite3VdbeAddOp4Int(v, OP_Found, iIdx, 0, r1, nVector);
drh471b4b92016-08-12 11:25:49 +00002778 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002779
2780 /* At this point the specified key is not present in the index,
2781 ** so the result of the IN(..) operator must be either NULL or
2782 ** 0. The vdbe code generated below figures out which. */
2783 addrNext = 1+sqlite3VdbeAddOp2(v, OP_Rewind, iIdx, destIfFalse);
drh471b4b92016-08-12 11:25:49 +00002784 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002785
2786 for(i=0; i<nVector; i++){
2787 Expr *p;
2788 CollSeq *pColl;
2789 int r2 = sqlite3GetTempReg(pParse);
drhfc7f27b2016-08-20 00:07:01 +00002790 p = sqlite3VectorFieldSubexpr(pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002791 pColl = sqlite3ExprCollSeq(pParse, p);
2792
2793 sqlite3VdbeAddOp3(v, OP_Column, iIdx, i, r2);
2794 sqlite3VdbeAddOp4(v, OP_Eq, r1+i, 0, r2, (void*)pColl,P4_COLLSEQ);
2795 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh471b4b92016-08-12 11:25:49 +00002796 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002797 sqlite3VdbeAddOp2(v, OP_Next, iIdx, addrNext);
drh471b4b92016-08-12 11:25:49 +00002798 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002799 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2800 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-3);
2801 sqlite3ReleaseTempReg(pParse, r2);
2802 }
2803 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
2804
2805 /* The key was found in the index. If it contains any NULL values,
2806 ** then the result of the IN(...) operator is NULL. Otherwise, the
2807 ** result is 1. */
2808 sqlite3VdbeJumpHere(v, addr);
2809 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002810 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002811 if( sqlite3ExprCanBeNull(p) ){
2812 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002813 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002814 }
2815 }
2816
2817 }else if( rRhsHasNull==0 ){
drhbb53ecb2014-08-02 21:03:33 +00002818 /* This branch runs if it is known at compile time that the RHS
dan7b35a772016-07-28 19:47:15 +00002819 ** cannot contain NULL values. This happens as a result
2820 ** of "NOT NULL" constraints in the database schema.
drhbb53ecb2014-08-02 21:03:33 +00002821 **
2822 ** Also run this branch if NULL is equivalent to FALSE
dan7b35a772016-07-28 19:47:15 +00002823 ** for this particular IN operator. */
danba00e302016-07-23 20:24:06 +00002824 sqlite3VdbeAddOp4Int(
2825 v, OP_NotFound, pExpr->iTable, destIfFalse, r1, nVector
2826 );
drhbb53ecb2014-08-02 21:03:33 +00002827 VdbeCoverage(v);
2828 }else{
2829 /* In this branch, the RHS of the IN might contain a NULL and
2830 ** the presence of a NULL on the RHS makes a difference in the
2831 ** outcome.
2832 */
drh728e0f92015-10-10 14:41:28 +00002833 int addr1;
dan7b35a772016-07-28 19:47:15 +00002834
drhbb53ecb2014-08-02 21:03:33 +00002835 /* First check to see if the LHS is contained in the RHS. If so,
2836 ** then the answer is TRUE the presence of NULLs in the RHS does
2837 ** not matter. If the LHS is not contained in the RHS, then the
2838 ** answer is NULL if the RHS contains NULLs and the answer is
2839 ** FALSE if the RHS is NULL-free.
2840 */
drh728e0f92015-10-10 14:41:28 +00002841 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002842 VdbeCoverage(v);
2843 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2844 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002845 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002846 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002847 }
drhe3365e62009-11-12 17:52:24 +00002848 }
drhe3365e62009-11-12 17:52:24 +00002849 }
2850 sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002851 sqlite3ExprCachePop(pParse);
danba00e302016-07-23 20:24:06 +00002852 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00002853 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00002854 VdbeComment((v, "end IN expr"));
2855}
2856#endif /* SQLITE_OMIT_SUBQUERY */
2857
drh13573c72010-01-12 17:04:07 +00002858#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002859/*
2860** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002861** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002862**
2863** The z[] string will probably not be zero-terminated. But the
2864** z[n] character is guaranteed to be something that does not look
2865** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002866*/
drhb7916a72009-05-27 10:31:29 +00002867static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002868 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002869 double value;
drh9339da12010-09-30 00:50:49 +00002870 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002871 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2872 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002873 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002874 }
2875}
drh13573c72010-01-12 17:04:07 +00002876#endif
drh598f1342007-10-23 15:39:45 +00002877
2878
2879/*
drhfec19aa2004-05-19 20:41:03 +00002880** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002881** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002882**
shaneh5f1d6b62010-09-30 16:51:25 +00002883** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002884*/
drh13573c72010-01-12 17:04:07 +00002885static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2886 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002887 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002888 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002889 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002890 if( negFlag ) i = -i;
2891 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002892 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002893 int c;
2894 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002895 const char *z = pExpr->u.zToken;
2896 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002897 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002898 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002899 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002900 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002901 }else{
drh13573c72010-01-12 17:04:07 +00002902#ifdef SQLITE_OMIT_FLOATING_POINT
2903 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2904#else
drh1b7ddc52014-07-23 14:52:05 +00002905#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002906 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2907 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002908 }else
2909#endif
2910 {
drh9296c182014-07-23 13:40:49 +00002911 codeReal(v, z, negFlag, iMem);
2912 }
drh13573c72010-01-12 17:04:07 +00002913#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002914 }
drhfec19aa2004-05-19 20:41:03 +00002915 }
2916}
2917
drhbea119c2016-04-11 18:15:37 +00002918#if defined(SQLITE_DEBUG)
2919/*
2920** Verify the consistency of the column cache
2921*/
2922static int cacheIsValid(Parse *pParse){
2923 int i, n;
2924 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2925 if( pParse->aColCache[i].iReg>0 ) n++;
2926 }
2927 return n==pParse->nColCache;
2928}
2929#endif
2930
drhceea3322009-04-23 13:22:42 +00002931/*
2932** Clear a cache entry.
2933*/
2934static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2935 if( p->tempReg ){
2936 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2937 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2938 }
2939 p->tempReg = 0;
2940 }
drhbea119c2016-04-11 18:15:37 +00002941 p->iReg = 0;
2942 pParse->nColCache--;
danee65eea2016-04-16 15:03:20 +00002943 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002944}
2945
2946
2947/*
2948** Record in the column cache that a particular column from a
2949** particular table is stored in a particular register.
2950*/
2951void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2952 int i;
2953 int minLru;
2954 int idxLru;
2955 struct yColCache *p;
2956
dance8f53d2015-01-21 17:00:57 +00002957 /* Unless an error has occurred, register numbers are always positive. */
2958 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002959 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2960
drhb6da74e2009-12-24 16:00:28 +00002961 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2962 ** for testing only - to verify that SQLite always gets the same answer
2963 ** with and without the column cache.
2964 */
drh7e5418e2012-09-27 15:05:54 +00002965 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002966
drh27ee4062009-12-30 01:13:11 +00002967 /* First replace any existing entry.
2968 **
2969 ** Actually, the way the column cache is currently used, we are guaranteed
2970 ** that the object will never already be in cache. Verify this guarantee.
2971 */
2972#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00002973 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00002974 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00002975 }
drh27ee4062009-12-30 01:13:11 +00002976#endif
drhceea3322009-04-23 13:22:42 +00002977
2978 /* Find an empty slot and replace it */
2979 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2980 if( p->iReg==0 ){
2981 p->iLevel = pParse->iCacheLevel;
2982 p->iTable = iTab;
2983 p->iColumn = iCol;
2984 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002985 p->tempReg = 0;
2986 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002987 pParse->nColCache++;
danee65eea2016-04-16 15:03:20 +00002988 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002989 return;
2990 }
2991 }
2992
2993 /* Replace the last recently used */
2994 minLru = 0x7fffffff;
2995 idxLru = -1;
2996 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2997 if( p->lru<minLru ){
2998 idxLru = i;
2999 minLru = p->lru;
3000 }
3001 }
drh20411ea2009-05-29 19:00:12 +00003002 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00003003 p = &pParse->aColCache[idxLru];
3004 p->iLevel = pParse->iCacheLevel;
3005 p->iTable = iTab;
3006 p->iColumn = iCol;
3007 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00003008 p->tempReg = 0;
3009 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00003010 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00003011 return;
3012 }
3013}
3014
3015/*
drhf49f3522009-12-30 14:12:38 +00003016** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3017** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00003018*/
drhf49f3522009-12-30 14:12:38 +00003019void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00003020 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00003021 if( iReg<=0 || pParse->nColCache==0 ) return;
3022 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
3023 while(1){
3024 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
3025 if( p==pParse->aColCache ) break;
3026 p--;
drhceea3322009-04-23 13:22:42 +00003027 }
3028}
3029
3030/*
3031** Remember the current column cache context. Any new entries added
3032** added to the column cache after this call are removed when the
3033** corresponding pop occurs.
3034*/
3035void sqlite3ExprCachePush(Parse *pParse){
3036 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00003037#ifdef SQLITE_DEBUG
3038 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3039 printf("PUSH to %d\n", pParse->iCacheLevel);
3040 }
3041#endif
drhceea3322009-04-23 13:22:42 +00003042}
3043
3044/*
3045** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00003046** the previous sqlite3ExprCachePush operation. In other words, restore
3047** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00003048*/
drhd2490902014-04-13 19:28:15 +00003049void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00003050 int i;
3051 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00003052 assert( pParse->iCacheLevel>=1 );
3053 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00003054#ifdef SQLITE_DEBUG
3055 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3056 printf("POP to %d\n", pParse->iCacheLevel);
3057 }
3058#endif
drhceea3322009-04-23 13:22:42 +00003059 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3060 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
3061 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00003062 }
3063 }
3064}
drh945498f2007-02-24 11:52:52 +00003065
3066/*
drh5cd79232009-05-25 11:46:29 +00003067** When a cached column is reused, make sure that its register is
3068** no longer available as a temp register. ticket #3879: that same
3069** register might be in the cache in multiple places, so be sure to
3070** get them all.
3071*/
3072static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3073 int i;
3074 struct yColCache *p;
3075 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3076 if( p->iReg==iReg ){
3077 p->tempReg = 0;
3078 }
3079 }
3080}
3081
drh1f9ca2c2015-08-25 16:57:52 +00003082/* Generate code that will load into register regOut a value that is
3083** appropriate for the iIdxCol-th column of index pIdx.
3084*/
3085void sqlite3ExprCodeLoadIndexColumn(
3086 Parse *pParse, /* The parsing context */
3087 Index *pIdx, /* The index whose column is to be loaded */
3088 int iTabCur, /* Cursor pointing to a table row */
3089 int iIdxCol, /* The column of the index to be loaded */
3090 int regOut /* Store the index column value in this register */
3091){
3092 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003093 if( iTabCol==XN_EXPR ){
3094 assert( pIdx->aColExpr );
3095 assert( pIdx->aColExpr->nExpr>iIdxCol );
3096 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00003097 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00003098 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003099 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3100 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003101 }
drh1f9ca2c2015-08-25 16:57:52 +00003102}
3103
drh5cd79232009-05-25 11:46:29 +00003104/*
drh5c092e82010-05-14 19:24:02 +00003105** Generate code to extract the value of the iCol-th column of a table.
3106*/
3107void sqlite3ExprCodeGetColumnOfTable(
3108 Vdbe *v, /* The VDBE under construction */
3109 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003110 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003111 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003112 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003113){
3114 if( iCol<0 || iCol==pTab->iPKey ){
3115 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3116 }else{
3117 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003118 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003119 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003120 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3121 }
3122 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003123 }
3124 if( iCol>=0 ){
3125 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3126 }
3127}
3128
3129/*
drh945498f2007-02-24 11:52:52 +00003130** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00003131** table pTab and store the column value in a register.
3132**
3133** An effort is made to store the column value in register iReg. This
3134** is not garanteeed for GetColumn() - the result can be stored in
3135** any register. But the result is guaranteed to land in register iReg
3136** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00003137**
3138** There must be an open cursor to pTab in iTable when this routine
3139** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003140*/
drhe55cbd72008-03-31 23:48:03 +00003141int sqlite3ExprCodeGetColumn(
3142 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003143 Table *pTab, /* Description of the table we are reading from */
3144 int iColumn, /* Index of the table column */
3145 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003146 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003147 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003148){
drhe55cbd72008-03-31 23:48:03 +00003149 Vdbe *v = pParse->pVdbe;
3150 int i;
drhda250ea2008-04-01 05:07:14 +00003151 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00003152
drhceea3322009-04-23 13:22:42 +00003153 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00003154 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00003155 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00003156 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00003157 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00003158 }
3159 }
3160 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003161 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003162 if( p5 ){
3163 sqlite3VdbeChangeP5(v, p5);
3164 }else{
3165 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3166 }
drhe55cbd72008-03-31 23:48:03 +00003167 return iReg;
3168}
drhce78bc62015-10-15 19:21:51 +00003169void sqlite3ExprCodeGetColumnToReg(
3170 Parse *pParse, /* Parsing and code generating context */
3171 Table *pTab, /* Description of the table we are reading from */
3172 int iColumn, /* Index of the table column */
3173 int iTable, /* The cursor pointing to the table */
3174 int iReg /* Store results here */
3175){
3176 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3177 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3178}
3179
drhe55cbd72008-03-31 23:48:03 +00003180
3181/*
drhceea3322009-04-23 13:22:42 +00003182** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00003183*/
drhceea3322009-04-23 13:22:42 +00003184void sqlite3ExprCacheClear(Parse *pParse){
3185 int i;
3186 struct yColCache *p;
3187
drh9ac79622013-12-18 15:11:47 +00003188#if SQLITE_DEBUG
3189 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3190 printf("CLEAR\n");
3191 }
3192#endif
drhceea3322009-04-23 13:22:42 +00003193 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3194 if( p->iReg ){
3195 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00003196 }
drhe55cbd72008-03-31 23:48:03 +00003197 }
3198}
3199
3200/*
drhda250ea2008-04-01 05:07:14 +00003201** Record the fact that an affinity change has occurred on iCount
3202** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00003203*/
drhda250ea2008-04-01 05:07:14 +00003204void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00003205 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00003206}
3207
3208/*
drhb21e7c72008-06-22 12:37:57 +00003209** Generate code to move content from registers iFrom...iFrom+nReg-1
3210** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00003211*/
drhb21e7c72008-06-22 12:37:57 +00003212void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003213 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003214 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00003215 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00003216}
3217
drhf49f3522009-12-30 14:12:38 +00003218#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00003219/*
drh652fbf52008-04-01 01:42:41 +00003220** Return true if any register in the range iFrom..iTo (inclusive)
3221** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00003222**
3223** This routine is used within assert() and testcase() macros only
3224** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00003225*/
3226static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3227 int i;
drhceea3322009-04-23 13:22:42 +00003228 struct yColCache *p;
3229 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3230 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00003231 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00003232 }
3233 return 0;
3234}
drhf49f3522009-12-30 14:12:38 +00003235#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00003236
drhbea119c2016-04-11 18:15:37 +00003237
drh652fbf52008-04-01 01:42:41 +00003238/*
drh12abf402016-08-22 14:30:05 +00003239** Convert a scalar expression node to a TK_REGISTER referencing
3240** register iReg. The caller must ensure that iReg already contains
3241** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003242*/
3243static void exprToRegister(Expr *p, int iReg){
3244 p->op2 = p->op;
3245 p->op = TK_REGISTER;
3246 p->iTable = iReg;
3247 ExprClearProperty(p, EP_Skip);
3248}
3249
drh12abf402016-08-22 14:30:05 +00003250/*
3251** Evaluate an expression (either a vector or a scalar expression) and store
3252** the result in continguous temporary registers. Return the index of
3253** the first register used to store the result.
3254**
3255** If the returned result register is a temporary scalar, then also write
3256** that register number into *piFreeable. If the returned result register
3257** is not a temporary or if the expression is a vector set *piFreeable
3258** to 0.
3259*/
3260static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3261 int iResult;
3262 int nResult = sqlite3ExprVectorSize(p);
3263 if( nResult==1 ){
3264 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3265 }else{
3266 *piFreeable = 0;
3267 if( p->op==TK_SELECT ){
3268 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3269 }else{
3270 int i;
3271 iResult = pParse->nMem+1;
3272 pParse->nMem += nResult;
3273 for(i=0; i<nResult; i++){
3274 sqlite3ExprCode(pParse, p->x.pList->a[i].pExpr, i+iResult);
3275 }
3276 }
3277 }
3278 return iResult;
3279}
3280
dan71c57db2016-07-09 20:23:55 +00003281
drha4c3c872013-09-12 17:29:25 +00003282/*
drhcce7d172000-05-31 15:34:51 +00003283** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003284** expression. Attempt to store the results in register "target".
3285** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003286**
drh8b213892008-08-29 02:14:02 +00003287** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003288** be stored in target. The result might be stored in some other
3289** register if it is convenient to do so. The calling function
3290** must check the return code and move the results to the desired
3291** register.
drhcce7d172000-05-31 15:34:51 +00003292*/
drh678ccce2008-03-31 18:19:54 +00003293int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003294 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3295 int op; /* The opcode being coded */
3296 int inReg = target; /* Results stored in register inReg */
3297 int regFree1 = 0; /* If non-zero free this temporary register */
3298 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003299 int r1, r2; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00003300 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00003301 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003302 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003303
drh9cbf3422008-01-17 16:22:13 +00003304 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003305 if( v==0 ){
3306 assert( pParse->db->mallocFailed );
3307 return 0;
3308 }
drh389a1ad2008-01-03 23:44:53 +00003309
3310 if( pExpr==0 ){
3311 op = TK_NULL;
3312 }else{
3313 op = pExpr->op;
3314 }
drhf2bc0132004-10-04 13:19:23 +00003315 switch( op ){
drh13449892005-09-07 21:22:45 +00003316 case TK_AGG_COLUMN: {
3317 AggInfo *pAggInfo = pExpr->pAggInfo;
3318 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3319 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003320 assert( pCol->iMem>0 );
3321 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00003322 break;
3323 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003324 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003325 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00003326 break;
3327 }
3328 /* Otherwise, fall thru into the TK_COLUMN case */
3329 }
drh967e8b72000-06-21 13:59:10 +00003330 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003331 int iTab = pExpr->iTable;
3332 if( iTab<0 ){
3333 if( pParse->ckBase>0 ){
3334 /* Generating CHECK constraints or inserting into partial index */
3335 inReg = pExpr->iColumn + pParse->ckBase;
3336 break;
3337 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003338 /* Coding an expression that is part of an index where column names
3339 ** in the index refer to the table to which the index belongs */
3340 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003341 }
drh22827922000-06-06 17:27:05 +00003342 }
drhb2b9d3d2013-08-01 01:14:43 +00003343 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3344 pExpr->iColumn, iTab, target,
3345 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003346 break;
3347 }
3348 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003349 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00003350 break;
3351 }
drh13573c72010-01-12 17:04:07 +00003352#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003353 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003354 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3355 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00003356 break;
3357 }
drh13573c72010-01-12 17:04:07 +00003358#endif
drhfec19aa2004-05-19 20:41:03 +00003359 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003360 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003361 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00003362 break;
3363 }
drhf0863fe2005-06-12 21:35:51 +00003364 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003365 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00003366 break;
3367 }
danielk19775338a5f2005-01-20 13:03:10 +00003368#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003369 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003370 int n;
3371 const char *z;
drhca48c902008-01-18 14:08:24 +00003372 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003373 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3374 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3375 assert( pExpr->u.zToken[1]=='\'' );
3376 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003377 n = sqlite3Strlen30(z) - 1;
3378 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003379 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3380 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00003381 break;
3382 }
danielk19775338a5f2005-01-20 13:03:10 +00003383#endif
drh50457892003-09-06 01:10:47 +00003384 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003385 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3386 assert( pExpr->u.zToken!=0 );
3387 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003388 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3389 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00003390 assert( pExpr->u.zToken[0]=='?'
3391 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
3392 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003393 }
drh50457892003-09-06 01:10:47 +00003394 break;
3395 }
drh4e0cff62004-11-05 05:10:28 +00003396 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00003397 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003398 break;
3399 }
drh487e2622005-06-25 18:42:14 +00003400#ifndef SQLITE_OMIT_CAST
3401 case TK_CAST: {
3402 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003403 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003404 if( inReg!=target ){
3405 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3406 inReg = target;
3407 }
drh4169e432014-08-25 20:11:52 +00003408 sqlite3VdbeAddOp2(v, OP_Cast, target,
3409 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00003410 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00003411 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00003412 break;
3413 }
3414#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003415 case TK_IS:
3416 case TK_ISNOT:
3417 op = (op==TK_IS) ? TK_EQ : TK_NE;
3418 p5 = SQLITE_NULLEQ;
3419 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003420 case TK_LT:
3421 case TK_LE:
3422 case TK_GT:
3423 case TK_GE:
3424 case TK_NE:
3425 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003426 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003427 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003428 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003429 }else{
3430 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3431 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3432 codeCompare(pParse, pLeft, pExpr->pRight, op,
3433 r1, r2, inReg, SQLITE_STOREP2 | p5);
3434 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3435 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3436 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3437 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3438 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3439 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3440 testcase( regFree1==0 );
3441 testcase( regFree2==0 );
3442 }
drh6a2fe092009-09-23 02:29:36 +00003443 break;
3444 }
drhcce7d172000-05-31 15:34:51 +00003445 case TK_AND:
3446 case TK_OR:
3447 case TK_PLUS:
3448 case TK_STAR:
3449 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003450 case TK_REM:
3451 case TK_BITAND:
3452 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003453 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003454 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003455 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003456 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003457 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3458 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3459 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3460 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3461 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3462 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3463 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3464 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3465 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3466 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3467 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003468 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3469 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003470 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003471 testcase( regFree1==0 );
3472 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003473 break;
3474 }
drhcce7d172000-05-31 15:34:51 +00003475 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003476 Expr *pLeft = pExpr->pLeft;
3477 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003478 if( pLeft->op==TK_INTEGER ){
3479 codeInteger(pParse, pLeft, 1, target);
3480#ifndef SQLITE_OMIT_FLOATING_POINT
3481 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003482 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3483 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00003484#endif
drh3c84ddf2008-01-09 02:15:38 +00003485 }else{
drh10d1edf2013-11-15 15:52:39 +00003486 tempX.op = TK_INTEGER;
3487 tempX.flags = EP_IntValue|EP_TokenOnly;
3488 tempX.u.iValue = 0;
3489 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003490 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003491 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003492 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003493 }
drh3c84ddf2008-01-09 02:15:38 +00003494 inReg = target;
3495 break;
drh6e142f52000-06-08 13:36:40 +00003496 }
drhbf4133c2001-10-13 02:59:08 +00003497 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003498 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003499 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3500 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003501 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3502 testcase( regFree1==0 );
3503 inReg = target;
3504 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003505 break;
3506 }
3507 case TK_ISNULL:
3508 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003509 int addr;
drh7d176102014-02-18 03:07:12 +00003510 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3511 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003512 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003513 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003514 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003515 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003516 VdbeCoverageIf(v, op==TK_ISNULL);
3517 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003518 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003519 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003520 break;
drhcce7d172000-05-31 15:34:51 +00003521 }
drh22827922000-06-06 17:27:05 +00003522 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003523 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003524 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003525 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3526 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003527 }else{
drh9de221d2008-01-05 06:51:30 +00003528 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003529 }
drh22827922000-06-06 17:27:05 +00003530 break;
3531 }
drhcce7d172000-05-31 15:34:51 +00003532 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003533 ExprList *pFarg; /* List of function arguments */
3534 int nFarg; /* Number of function arguments */
3535 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003536 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003537 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003538 int i; /* Loop counter */
3539 u8 enc = ENC(db); /* The text encoding used by this database */
3540 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003541
danielk19776ab3a2e2009-02-19 14:39:25 +00003542 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00003543 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003544 pFarg = 0;
3545 }else{
3546 pFarg = pExpr->x.pList;
3547 }
3548 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003549 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3550 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003551 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003552#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3553 if( pDef==0 && pParse->explain ){
3554 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3555 }
3556#endif
drh2d801512016-01-14 22:19:58 +00003557 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003558 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003559 break;
3560 }
drhae6bb952009-11-11 00:24:31 +00003561
3562 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003563 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003564 ** arguments past the first non-NULL argument.
3565 */
drhd36e1042013-09-06 13:10:12 +00003566 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003567 int endCoalesce = sqlite3VdbeMakeLabel(v);
3568 assert( nFarg>=2 );
3569 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3570 for(i=1; i<nFarg; i++){
3571 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003572 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00003573 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00003574 sqlite3ExprCachePush(pParse);
3575 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003576 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00003577 }
3578 sqlite3VdbeResolveLabel(v, endCoalesce);
3579 break;
3580 }
3581
drhcca9f3d2013-09-06 15:23:29 +00003582 /* The UNLIKELY() function is a no-op. The result is the value
3583 ** of the first argument.
3584 */
3585 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3586 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00003587 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003588 break;
3589 }
drhae6bb952009-11-11 00:24:31 +00003590
drhd1a01ed2013-11-21 16:08:52 +00003591 for(i=0; i<nFarg; i++){
3592 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003593 testcase( i==31 );
3594 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003595 }
3596 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3597 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3598 }
3599 }
drh12ffee82009-04-08 13:51:51 +00003600 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003601 if( constMask ){
3602 r1 = pParse->nMem+1;
3603 pParse->nMem += nFarg;
3604 }else{
3605 r1 = sqlite3GetTempRange(pParse, nFarg);
3606 }
drha748fdc2012-03-28 01:34:47 +00003607
3608 /* For length() and typeof() functions with a column argument,
3609 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3610 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3611 ** loading.
3612 */
drhd36e1042013-09-06 13:10:12 +00003613 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003614 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003615 assert( nFarg==1 );
3616 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003617 exprOp = pFarg->a[0].pExpr->op;
3618 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003619 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3620 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003621 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3622 pFarg->a[0].pExpr->op2 =
3623 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003624 }
3625 }
3626
drhd7d385d2009-09-03 01:18:00 +00003627 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003628 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003629 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003630 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003631 }else{
drh12ffee82009-04-08 13:51:51 +00003632 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003633 }
drhb7f6f682006-07-08 17:06:43 +00003634#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003635 /* Possibly overload the function if the first argument is
3636 ** a virtual table column.
3637 **
3638 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3639 ** second argument, not the first, as the argument to test to
3640 ** see if it is a column in a virtual table. This is done because
3641 ** the left operand of infix functions (the operand we want to
3642 ** control overloading) ends up as the second argument to the
3643 ** function. The expression "A glob B" is equivalent to
3644 ** "glob(B,A). We want to use the A in "A glob B" to test
3645 ** for function overloading. But we use the B term in "glob(B,A)".
3646 */
drh12ffee82009-04-08 13:51:51 +00003647 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3648 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3649 }else if( nFarg>0 ){
3650 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003651 }
3652#endif
drhd36e1042013-09-06 13:10:12 +00003653 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003654 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003655 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003656 }
drh9c7c9132015-06-26 18:16:52 +00003657 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003658 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003659 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003660 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003661 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003662 }
drhcce7d172000-05-31 15:34:51 +00003663 break;
3664 }
drhfe2093d2005-01-20 22:48:47 +00003665#ifndef SQLITE_OMIT_SUBQUERY
3666 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003667 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003668 int nCol;
drhc5499be2008-04-01 15:06:33 +00003669 testcase( op==TK_EXISTS );
3670 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003671 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3672 sqlite3SubselectError(pParse, nCol, 1);
3673 }else{
3674 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3675 }
drh19a775c2000-06-05 18:54:46 +00003676 break;
3677 }
drhfc7f27b2016-08-20 00:07:01 +00003678 case TK_SELECT_COLUMN: {
3679 if( pExpr->pLeft->iTable==0 ){
3680 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3681 }
3682 inReg = pExpr->pLeft->iTable + pExpr->iColumn;
3683 break;
3684 }
drhfef52082000-06-06 01:50:43 +00003685 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003686 int destIfFalse = sqlite3VdbeMakeLabel(v);
3687 int destIfNull = sqlite3VdbeMakeLabel(v);
3688 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3689 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3690 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3691 sqlite3VdbeResolveLabel(v, destIfFalse);
3692 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3693 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003694 break;
3695 }
drhe3365e62009-11-12 17:52:24 +00003696#endif /* SQLITE_OMIT_SUBQUERY */
3697
3698
drh2dcef112008-01-12 19:03:48 +00003699 /*
3700 ** x BETWEEN y AND z
3701 **
3702 ** This is equivalent to
3703 **
3704 ** x>=y AND x<=z
3705 **
3706 ** X is stored in pExpr->pLeft.
3707 ** Y is stored in pExpr->pList->a[0].pExpr.
3708 ** Z is stored in pExpr->pList->a[1].pExpr.
3709 */
drhfef52082000-06-06 01:50:43 +00003710 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003711 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhfef52082000-06-06 01:50:43 +00003712 break;
3713 }
drh94fa9c42016-02-27 21:16:04 +00003714 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003715 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003716 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003717 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003718 break;
3719 }
drh2dcef112008-01-12 19:03:48 +00003720
dan165921a2009-08-28 18:53:45 +00003721 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003722 /* If the opcode is TK_TRIGGER, then the expression is a reference
3723 ** to a column in the new.* or old.* pseudo-tables available to
3724 ** trigger programs. In this case Expr.iTable is set to 1 for the
3725 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3726 ** is set to the column of the pseudo-table to read, or to -1 to
3727 ** read the rowid field.
3728 **
3729 ** The expression is implemented using an OP_Param opcode. The p1
3730 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3731 ** to reference another column of the old.* pseudo-table, where
3732 ** i is the index of the column. For a new.rowid reference, p1 is
3733 ** set to (n+1), where n is the number of columns in each pseudo-table.
3734 ** For a reference to any other column in the new.* pseudo-table, p1
3735 ** is set to (n+2+i), where n and i are as defined previously. For
3736 ** example, if the table on which triggers are being fired is
3737 ** declared as:
3738 **
3739 ** CREATE TABLE t1(a, b);
3740 **
3741 ** Then p1 is interpreted as follows:
3742 **
3743 ** p1==0 -> old.rowid p1==3 -> new.rowid
3744 ** p1==1 -> old.a p1==4 -> new.a
3745 ** p1==2 -> old.b p1==5 -> new.b
3746 */
dan2832ad42009-08-31 15:27:27 +00003747 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003748 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3749
3750 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3751 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3752 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3753 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3754
3755 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003756 VdbeComment((v, "%s.%s -> $%d",
3757 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003758 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003759 target
dan165921a2009-08-28 18:53:45 +00003760 ));
dan65a7cd12009-09-01 12:16:01 +00003761
drh44dbca82010-01-13 04:22:20 +00003762#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003763 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003764 ** integer. Use OP_RealAffinity to make sure it is really real.
3765 **
3766 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3767 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003768 if( pExpr->iColumn>=0
3769 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3770 ){
3771 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3772 }
drh44dbca82010-01-13 04:22:20 +00003773#endif
dan165921a2009-08-28 18:53:45 +00003774 break;
3775 }
3776
dan71c57db2016-07-09 20:23:55 +00003777 case TK_VECTOR: {
dand49fd4e2016-07-27 19:33:04 +00003778 sqlite3ErrorMsg(pParse, "invalid use of row value");
dan71c57db2016-07-09 20:23:55 +00003779 break;
3780 }
3781
drh2dcef112008-01-12 19:03:48 +00003782 /*
3783 ** Form A:
3784 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3785 **
3786 ** Form B:
3787 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3788 **
3789 ** Form A is can be transformed into the equivalent form B as follows:
3790 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3791 ** WHEN x=eN THEN rN ELSE y END
3792 **
3793 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003794 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3795 ** odd. The Y is also optional. If the number of elements in x.pList
3796 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003797 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3798 **
3799 ** The result of the expression is the Ri for the first matching Ei,
3800 ** or if there is no matching Ei, the ELSE term Y, or if there is
3801 ** no ELSE term, NULL.
3802 */
drh33cd4902009-05-30 20:49:20 +00003803 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003804 int endLabel; /* GOTO label for end of CASE stmt */
3805 int nextCase; /* GOTO label for next WHEN clause */
3806 int nExpr; /* 2x number of WHEN terms */
3807 int i; /* Loop counter */
3808 ExprList *pEList; /* List of WHEN terms */
3809 struct ExprList_item *aListelem; /* Array of WHEN terms */
3810 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003811 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003812 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003813 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003814
danielk19776ab3a2e2009-02-19 14:39:25 +00003815 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003816 assert(pExpr->x.pList->nExpr > 0);
3817 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003818 aListelem = pEList->a;
3819 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003820 endLabel = sqlite3VdbeMakeLabel(v);
3821 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003822 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003823 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00003824 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003825 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00003826 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00003827 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003828 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003829 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003830 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3831 ** The value in regFree1 might get SCopy-ed into the file result.
3832 ** So make sure that the regFree1 register is not reused for other
3833 ** purposes and possibly overwritten. */
3834 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003835 }
drhc5cd1242013-09-12 16:50:49 +00003836 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003837 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003838 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003839 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003840 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003841 }else{
drh2dcef112008-01-12 19:03:48 +00003842 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003843 }
drh2dcef112008-01-12 19:03:48 +00003844 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003845 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003846 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003847 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003848 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003849 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003850 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003851 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003852 }
drhc5cd1242013-09-12 16:50:49 +00003853 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003854 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003855 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003856 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003857 }else{
drh9de221d2008-01-05 06:51:30 +00003858 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003859 }
danielk1977c1f4a192009-04-28 12:08:15 +00003860 assert( db->mallocFailed || pParse->nErr>0
3861 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003862 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003863 break;
3864 }
danielk19775338a5f2005-01-20 13:03:10 +00003865#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003866 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003867 assert( pExpr->affinity==OE_Rollback
3868 || pExpr->affinity==OE_Abort
3869 || pExpr->affinity==OE_Fail
3870 || pExpr->affinity==OE_Ignore
3871 );
dane0af83a2009-09-08 19:15:01 +00003872 if( !pParse->pTriggerTab ){
3873 sqlite3ErrorMsg(pParse,
3874 "RAISE() may only be used within a trigger-program");
3875 return 0;
3876 }
3877 if( pExpr->affinity==OE_Abort ){
3878 sqlite3MayAbort(pParse);
3879 }
dan165921a2009-08-28 18:53:45 +00003880 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003881 if( pExpr->affinity==OE_Ignore ){
3882 sqlite3VdbeAddOp4(
3883 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003884 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003885 }else{
drh433dccf2013-02-09 15:37:11 +00003886 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003887 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003888 }
3889
drhffe07b22005-11-03 00:41:17 +00003890 break;
drh17a7f8d2002-03-24 13:13:27 +00003891 }
danielk19775338a5f2005-01-20 13:03:10 +00003892#endif
drhffe07b22005-11-03 00:41:17 +00003893 }
drh2dcef112008-01-12 19:03:48 +00003894 sqlite3ReleaseTempReg(pParse, regFree1);
3895 sqlite3ReleaseTempReg(pParse, regFree2);
3896 return inReg;
3897}
3898
3899/*
drhd1a01ed2013-11-21 16:08:52 +00003900** Factor out the code of the given expression to initialization time.
3901*/
drhd673cdd2013-11-21 21:23:31 +00003902void sqlite3ExprCodeAtInit(
3903 Parse *pParse, /* Parsing context */
3904 Expr *pExpr, /* The expression to code when the VDBE initializes */
3905 int regDest, /* Store the value in this register */
3906 u8 reusable /* True if this expression is reusable */
3907){
drhd1a01ed2013-11-21 16:08:52 +00003908 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003909 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003910 p = pParse->pConstExpr;
3911 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3912 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003913 if( p ){
3914 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3915 pItem->u.iConstExprReg = regDest;
3916 pItem->reusable = reusable;
3917 }
drhd1a01ed2013-11-21 16:08:52 +00003918 pParse->pConstExpr = p;
3919}
3920
3921/*
drh2dcef112008-01-12 19:03:48 +00003922** Generate code to evaluate an expression and store the results
3923** into a register. Return the register number where the results
3924** are stored.
3925**
3926** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003927** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003928** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003929**
3930** If pExpr is a constant, then this routine might generate this
3931** code to fill the register in the initialization section of the
3932** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003933*/
3934int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003935 int r2;
3936 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003937 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003938 && pExpr->op!=TK_REGISTER
3939 && sqlite3ExprIsConstantNotJoin(pExpr)
3940 ){
3941 ExprList *p = pParse->pConstExpr;
3942 int i;
3943 *pReg = 0;
3944 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003945 struct ExprList_item *pItem;
3946 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3947 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3948 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003949 }
3950 }
3951 }
drhf30a9692013-11-15 01:10:18 +00003952 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003953 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003954 }else{
drhf30a9692013-11-15 01:10:18 +00003955 int r1 = sqlite3GetTempReg(pParse);
3956 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3957 if( r2==r1 ){
3958 *pReg = r1;
3959 }else{
3960 sqlite3ReleaseTempReg(pParse, r1);
3961 *pReg = 0;
3962 }
drh2dcef112008-01-12 19:03:48 +00003963 }
3964 return r2;
3965}
3966
3967/*
3968** Generate code that will evaluate expression pExpr and store the
3969** results in register target. The results are guaranteed to appear
3970** in register target.
3971*/
drh05a86c52014-02-16 01:55:49 +00003972void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00003973 int inReg;
3974
3975 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00003976 if( pExpr && pExpr->op==TK_REGISTER ){
3977 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3978 }else{
3979 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00003980 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00003981 if( inReg!=target && pParse->pVdbe ){
3982 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
3983 }
drhcce7d172000-05-31 15:34:51 +00003984 }
drhcce7d172000-05-31 15:34:51 +00003985}
3986
3987/*
drh1c75c9d2015-12-21 15:22:13 +00003988** Make a transient copy of expression pExpr and then code it using
3989** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
3990** except that the input expression is guaranteed to be unchanged.
3991*/
3992void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
3993 sqlite3 *db = pParse->db;
3994 pExpr = sqlite3ExprDup(db, pExpr, 0);
3995 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
3996 sqlite3ExprDelete(db, pExpr);
3997}
3998
3999/*
drh05a86c52014-02-16 01:55:49 +00004000** Generate code that will evaluate expression pExpr and store the
4001** results in register target. The results are guaranteed to appear
4002** in register target. If the expression is constant, then this routine
4003** might choose to code the expression at initialization time.
4004*/
4005void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4006 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4007 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
4008 }else{
4009 sqlite3ExprCode(pParse, pExpr, target);
4010 }
drhcce7d172000-05-31 15:34:51 +00004011}
4012
4013/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004014** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004015** in register target.
drh25303782004-12-07 15:41:48 +00004016**
drh2dcef112008-01-12 19:03:48 +00004017** Also make a copy of the expression results into another "cache" register
4018** and modify the expression so that the next time it is evaluated,
4019** the result is a copy of the cache register.
4020**
4021** This routine is used for expressions that are used multiple
4022** times. They are evaluated once and the results of the expression
4023** are reused.
drh25303782004-12-07 15:41:48 +00004024*/
drh05a86c52014-02-16 01:55:49 +00004025void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004026 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004027 int iMem;
4028
drhde4fcfd2008-01-19 23:50:26 +00004029 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004030 assert( pExpr->op!=TK_REGISTER );
4031 sqlite3ExprCode(pParse, pExpr, target);
4032 iMem = ++pParse->nMem;
4033 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4034 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004035}
drh2dcef112008-01-12 19:03:48 +00004036
drh678ccce2008-03-31 18:19:54 +00004037/*
drh268380c2004-02-25 13:47:31 +00004038** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004039** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004040**
drh892d3172008-01-10 03:46:36 +00004041** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00004042**
4043** The SQLITE_ECEL_DUP flag prevents the arguments from being
4044** filled using OP_SCopy. OP_Copy must be used instead.
4045**
4046** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4047** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004048**
4049** The SQLITE_ECEL_REF flag means that expressions in the list with
4050** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4051** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00004052*/
danielk19774adee202004-05-08 08:23:19 +00004053int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004054 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004055 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004056 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004057 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004058 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004059){
4060 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004061 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004062 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004063 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004064 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004065 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004066 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004067 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004068 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004069 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004070 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00004071 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
4072 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4073 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00004074 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00004075 }else{
4076 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4077 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004078 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004079 if( copyOp==OP_Copy
4080 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4081 && pOp->p1+pOp->p3+1==inReg
4082 && pOp->p2+pOp->p3+1==target+i
4083 ){
4084 pOp->p3++;
4085 }else{
4086 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4087 }
drhd1a01ed2013-11-21 16:08:52 +00004088 }
drhd1766112008-09-17 00:13:12 +00004089 }
drh268380c2004-02-25 13:47:31 +00004090 }
drhf9b596e2004-05-26 16:54:42 +00004091 return n;
drh268380c2004-02-25 13:47:31 +00004092}
4093
4094/*
drh36c563a2009-11-12 13:32:22 +00004095** Generate code for a BETWEEN operator.
4096**
4097** x BETWEEN y AND z
4098**
4099** The above is equivalent to
4100**
4101** x>=y AND x<=z
4102**
4103** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004104** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004105**
4106** The xJumpIf parameter determines details:
4107**
4108** NULL: Store the boolean result in reg[dest]
4109** sqlite3ExprIfTrue: Jump to dest if true
4110** sqlite3ExprIfFalse: Jump to dest if false
4111**
4112** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004113*/
4114static void exprCodeBetween(
4115 Parse *pParse, /* Parsing and code generating context */
4116 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004117 int dest, /* Jump destination or storage location */
4118 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004119 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4120){
drhdb45bd52016-08-22 00:48:58 +00004121 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004122 Expr compLeft; /* The x>=y term */
4123 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004124 Expr exprX; /* The x subexpression */
4125 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004126
drh36c563a2009-11-12 13:32:22 +00004127
dan71c57db2016-07-09 20:23:55 +00004128 memset(&compLeft, 0, sizeof(Expr));
4129 memset(&compRight, 0, sizeof(Expr));
4130 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004131
4132 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4133 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004134 exprAnd.op = TK_AND;
4135 exprAnd.pLeft = &compLeft;
4136 exprAnd.pRight = &compRight;
4137 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004138 compLeft.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004139 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4140 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004141 compRight.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004142 compRight.pRight = pExpr->x.pList->a[1].pExpr;
drh12abf402016-08-22 14:30:05 +00004143 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004144 if( xJump ){
4145 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004146 }else{
drhdb45bd52016-08-22 00:48:58 +00004147 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004148 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004149 }
drhdb45bd52016-08-22 00:48:58 +00004150 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004151
4152 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004153 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4154 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4155 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4156 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4157 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4158 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4159 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4160 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004161 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004162}
4163
4164/*
drhcce7d172000-05-31 15:34:51 +00004165** Generate code for a boolean expression such that a jump is made
4166** to the label "dest" if the expression is true but execution
4167** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004168**
4169** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004170** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004171**
4172** This code depends on the fact that certain token values (ex: TK_EQ)
4173** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4174** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4175** the make process cause these values to align. Assert()s in the code
4176** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004177*/
danielk19774adee202004-05-08 08:23:19 +00004178void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004179 Vdbe *v = pParse->pVdbe;
4180 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004181 int regFree1 = 0;
4182 int regFree2 = 0;
4183 int r1, r2;
4184
drh35573352008-01-08 23:54:25 +00004185 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004186 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004187 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004188 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004189 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004190 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004191 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004192 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004193 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004194 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004195 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4196 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004197 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004198 break;
4199 }
4200 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004201 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004202 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004203 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004204 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004205 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004206 break;
4207 }
4208 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004209 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004210 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004211 break;
4212 }
drhde845c22016-03-17 19:07:52 +00004213 case TK_IS:
4214 case TK_ISNOT:
4215 testcase( op==TK_IS );
4216 testcase( op==TK_ISNOT );
4217 op = (op==TK_IS) ? TK_EQ : TK_NE;
4218 jumpIfNull = SQLITE_NULLEQ;
4219 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004220 case TK_LT:
4221 case TK_LE:
4222 case TK_GT:
4223 case TK_GE:
4224 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004225 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004226 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004227 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004228 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4229 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004230 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004231 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004232 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4233 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4234 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4235 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004236 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4237 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4238 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4239 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4240 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4241 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004242 testcase( regFree1==0 );
4243 testcase( regFree2==0 );
4244 break;
4245 }
drhcce7d172000-05-31 15:34:51 +00004246 case TK_ISNULL:
4247 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004248 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4249 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004250 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4251 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004252 VdbeCoverageIf(v, op==TK_ISNULL);
4253 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004254 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004255 break;
4256 }
drhfef52082000-06-06 01:50:43 +00004257 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004258 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004259 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004260 break;
4261 }
drh84e30ca2011-02-10 17:46:14 +00004262#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004263 case TK_IN: {
4264 int destIfFalse = sqlite3VdbeMakeLabel(v);
4265 int destIfNull = jumpIfNull ? dest : destIfFalse;
4266 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004267 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004268 sqlite3VdbeResolveLabel(v, destIfFalse);
4269 break;
4270 }
shanehbb201342011-02-09 19:55:20 +00004271#endif
drhcce7d172000-05-31 15:34:51 +00004272 default: {
dan7b35a772016-07-28 19:47:15 +00004273 default_expr:
drh991a1982014-01-02 17:57:16 +00004274 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004275 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004276 }else if( exprAlwaysFalse(pExpr) ){
4277 /* No-op */
4278 }else{
4279 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4280 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004281 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004282 testcase( regFree1==0 );
4283 testcase( jumpIfNull==0 );
4284 }
drhcce7d172000-05-31 15:34:51 +00004285 break;
4286 }
4287 }
drh2dcef112008-01-12 19:03:48 +00004288 sqlite3ReleaseTempReg(pParse, regFree1);
4289 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004290}
4291
4292/*
drh66b89c82000-11-28 20:47:17 +00004293** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004294** to the label "dest" if the expression is false but execution
4295** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004296**
4297** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004298** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4299** is 0.
drhcce7d172000-05-31 15:34:51 +00004300*/
danielk19774adee202004-05-08 08:23:19 +00004301void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004302 Vdbe *v = pParse->pVdbe;
4303 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004304 int regFree1 = 0;
4305 int regFree2 = 0;
4306 int r1, r2;
4307
drh35573352008-01-08 23:54:25 +00004308 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004309 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004310 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004311
4312 /* The value of pExpr->op and op are related as follows:
4313 **
4314 ** pExpr->op op
4315 ** --------- ----------
4316 ** TK_ISNULL OP_NotNull
4317 ** TK_NOTNULL OP_IsNull
4318 ** TK_NE OP_Eq
4319 ** TK_EQ OP_Ne
4320 ** TK_GT OP_Le
4321 ** TK_LE OP_Gt
4322 ** TK_GE OP_Lt
4323 ** TK_LT OP_Ge
4324 **
4325 ** For other values of pExpr->op, op is undefined and unused.
4326 ** The value of TK_ and OP_ constants are arranged such that we
4327 ** can compute the mapping above using the following expression.
4328 ** Assert()s verify that the computation is correct.
4329 */
4330 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4331
4332 /* Verify correct alignment of TK_ and OP_ constants
4333 */
4334 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4335 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4336 assert( pExpr->op!=TK_NE || op==OP_Eq );
4337 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4338 assert( pExpr->op!=TK_LT || op==OP_Ge );
4339 assert( pExpr->op!=TK_LE || op==OP_Gt );
4340 assert( pExpr->op!=TK_GT || op==OP_Le );
4341 assert( pExpr->op!=TK_GE || op==OP_Lt );
4342
danba00e302016-07-23 20:24:06 +00004343 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004344 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004345 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004346 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004347 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004348 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004349 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004350 break;
4351 }
4352 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004353 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004354 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004355 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004356 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004357 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4358 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004359 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004360 break;
4361 }
4362 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004363 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004364 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004365 break;
4366 }
drhde845c22016-03-17 19:07:52 +00004367 case TK_IS:
4368 case TK_ISNOT:
4369 testcase( pExpr->op==TK_IS );
4370 testcase( pExpr->op==TK_ISNOT );
4371 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4372 jumpIfNull = SQLITE_NULLEQ;
4373 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004374 case TK_LT:
4375 case TK_LE:
4376 case TK_GT:
4377 case TK_GE:
4378 case TK_NE:
4379 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004380 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004381 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004382 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4383 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004384 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004385 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004386 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4387 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4388 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4389 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004390 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4391 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4392 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4393 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4394 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4395 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004396 testcase( regFree1==0 );
4397 testcase( regFree2==0 );
4398 break;
4399 }
drhcce7d172000-05-31 15:34:51 +00004400 case TK_ISNULL:
4401 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004402 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4403 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004404 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4405 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004406 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004407 break;
4408 }
drhfef52082000-06-06 01:50:43 +00004409 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004410 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004411 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004412 break;
4413 }
drh84e30ca2011-02-10 17:46:14 +00004414#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004415 case TK_IN: {
4416 if( jumpIfNull ){
4417 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4418 }else{
4419 int destIfNull = sqlite3VdbeMakeLabel(v);
4420 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4421 sqlite3VdbeResolveLabel(v, destIfNull);
4422 }
4423 break;
4424 }
shanehbb201342011-02-09 19:55:20 +00004425#endif
drhcce7d172000-05-31 15:34:51 +00004426 default: {
danba00e302016-07-23 20:24:06 +00004427 default_expr:
drh991a1982014-01-02 17:57:16 +00004428 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004429 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004430 }else if( exprAlwaysTrue(pExpr) ){
4431 /* no-op */
4432 }else{
4433 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4434 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004435 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004436 testcase( regFree1==0 );
4437 testcase( jumpIfNull==0 );
4438 }
drhcce7d172000-05-31 15:34:51 +00004439 break;
4440 }
4441 }
drh2dcef112008-01-12 19:03:48 +00004442 sqlite3ReleaseTempReg(pParse, regFree1);
4443 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004444}
drh22827922000-06-06 17:27:05 +00004445
4446/*
drh72bc8202015-06-11 13:58:35 +00004447** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4448** code generation, and that copy is deleted after code generation. This
4449** ensures that the original pExpr is unchanged.
4450*/
4451void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4452 sqlite3 *db = pParse->db;
4453 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4454 if( db->mallocFailed==0 ){
4455 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4456 }
4457 sqlite3ExprDelete(db, pCopy);
4458}
4459
4460
4461/*
drh1d9da702010-01-07 15:17:02 +00004462** Do a deep comparison of two expression trees. Return 0 if the two
4463** expressions are completely identical. Return 1 if they differ only
4464** by a COLLATE operator at the top level. Return 2 if there are differences
4465** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004466**
drh619a1302013-08-01 13:04:46 +00004467** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4468** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4469**
drh66518ca2013-08-01 15:09:57 +00004470** The pA side might be using TK_REGISTER. If that is the case and pB is
4471** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4472**
drh1d9da702010-01-07 15:17:02 +00004473** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004474** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004475** identical, we return 2 just to be safe. So if this routine
4476** returns 2, then you do not really know for certain if the two
4477** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004478** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004479** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004480** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004481** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00004482*/
drh619a1302013-08-01 13:04:46 +00004483int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004484 u32 combinedFlags;
4485 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004486 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004487 }
drh10d1edf2013-11-15 15:52:39 +00004488 combinedFlags = pA->flags | pB->flags;
4489 if( combinedFlags & EP_IntValue ){
4490 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4491 return 0;
4492 }
drh1d9da702010-01-07 15:17:02 +00004493 return 2;
drh22827922000-06-06 17:27:05 +00004494 }
drhc2acc4e2013-11-15 18:15:19 +00004495 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00004496 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004497 return 1;
4498 }
drh619a1302013-08-01 13:04:46 +00004499 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004500 return 1;
4501 }
4502 return 2;
4503 }
drh2edc5fd2015-11-24 02:10:52 +00004504 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004505 if( pA->op==TK_FUNCTION ){
4506 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4507 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00004508 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00004509 }
drh22827922000-06-06 17:27:05 +00004510 }
drh10d1edf2013-11-15 15:52:39 +00004511 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004512 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00004513 if( combinedFlags & EP_xIsSelect ) return 2;
4514 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4515 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4516 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00004517 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00004518 if( pA->iColumn!=pB->iColumn ) return 2;
4519 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004520 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004521 }
4522 }
drh1d9da702010-01-07 15:17:02 +00004523 return 0;
drh22827922000-06-06 17:27:05 +00004524}
4525
drh8c6f6662010-04-26 19:17:26 +00004526/*
4527** Compare two ExprList objects. Return 0 if they are identical and
4528** non-zero if they differ in any way.
4529**
drh619a1302013-08-01 13:04:46 +00004530** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4531** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4532**
drh8c6f6662010-04-26 19:17:26 +00004533** This routine might return non-zero for equivalent ExprLists. The
4534** only consequence will be disabled optimizations. But this routine
4535** must never return 0 if the two ExprList objects are different, or
4536** a malfunction will result.
4537**
4538** Two NULL pointers are considered to be the same. But a NULL pointer
4539** always differs from a non-NULL pointer.
4540*/
drh619a1302013-08-01 13:04:46 +00004541int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004542 int i;
4543 if( pA==0 && pB==0 ) return 0;
4544 if( pA==0 || pB==0 ) return 1;
4545 if( pA->nExpr!=pB->nExpr ) return 1;
4546 for(i=0; i<pA->nExpr; i++){
4547 Expr *pExprA = pA->a[i].pExpr;
4548 Expr *pExprB = pB->a[i].pExpr;
4549 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00004550 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004551 }
4552 return 0;
4553}
drh13449892005-09-07 21:22:45 +00004554
drh22827922000-06-06 17:27:05 +00004555/*
drh4bd5f732013-07-31 23:22:39 +00004556** Return true if we can prove the pE2 will always be true if pE1 is
4557** true. Return false if we cannot complete the proof or if pE2 might
4558** be false. Examples:
4559**
drh619a1302013-08-01 13:04:46 +00004560** pE1: x==5 pE2: x==5 Result: true
4561** pE1: x>0 pE2: x==5 Result: false
4562** pE1: x=21 pE2: x=21 OR y=43 Result: true
4563** pE1: x!=123 pE2: x IS NOT NULL Result: true
4564** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4565** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4566** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004567**
4568** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4569** Expr.iTable<0 then assume a table number given by iTab.
4570**
4571** When in doubt, return false. Returning true might give a performance
4572** improvement. Returning false might cause a performance reduction, but
4573** it will always give the correct answer and is hence always safe.
4574*/
4575int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00004576 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4577 return 1;
4578 }
4579 if( pE2->op==TK_OR
4580 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4581 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4582 ){
4583 return 1;
4584 }
4585 if( pE2->op==TK_NOTNULL
4586 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4587 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4588 ){
4589 return 1;
4590 }
4591 return 0;
drh4bd5f732013-07-31 23:22:39 +00004592}
4593
4594/*
drh030796d2012-08-23 16:18:10 +00004595** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00004596** to determine if an expression can be evaluated by reference to the
4597** index only, without having to do a search for the corresponding
4598** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4599** is the cursor for the table.
4600*/
4601struct IdxCover {
4602 Index *pIdx; /* The index to be tested for coverage */
4603 int iCur; /* Cursor number for the table corresponding to the index */
4604};
4605
4606/*
4607** Check to see if there are references to columns in table
4608** pWalker->u.pIdxCover->iCur can be satisfied using the index
4609** pWalker->u.pIdxCover->pIdx.
4610*/
4611static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4612 if( pExpr->op==TK_COLUMN
4613 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4614 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4615 ){
4616 pWalker->eCode = 1;
4617 return WRC_Abort;
4618 }
4619 return WRC_Continue;
4620}
4621
4622/*
drhe604ec02016-07-27 19:20:58 +00004623** Determine if an index pIdx on table with cursor iCur contains will
4624** the expression pExpr. Return true if the index does cover the
4625** expression and false if the pExpr expression references table columns
4626** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00004627**
4628** An index covering an expression means that the expression can be
4629** evaluated using only the index and without having to lookup the
4630** corresponding table entry.
4631*/
4632int sqlite3ExprCoveredByIndex(
4633 Expr *pExpr, /* The index to be tested */
4634 int iCur, /* The cursor number for the corresponding table */
4635 Index *pIdx /* The index that might be used for coverage */
4636){
4637 Walker w;
4638 struct IdxCover xcov;
4639 memset(&w, 0, sizeof(w));
4640 xcov.iCur = iCur;
4641 xcov.pIdx = pIdx;
4642 w.xExprCallback = exprIdxCover;
4643 w.u.pIdxCover = &xcov;
4644 sqlite3WalkExpr(&w, pExpr);
4645 return !w.eCode;
4646}
4647
4648
4649/*
4650** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00004651** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00004652** aggregate function, in order to implement the
4653** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00004654*/
drh030796d2012-08-23 16:18:10 +00004655struct SrcCount {
4656 SrcList *pSrc; /* One particular FROM clause in a nested query */
4657 int nThis; /* Number of references to columns in pSrcList */
4658 int nOther; /* Number of references to columns in other FROM clauses */
4659};
4660
4661/*
4662** Count the number of references to columns.
4663*/
4664static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00004665 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4666 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4667 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4668 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4669 ** NEVER() will need to be removed. */
4670 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00004671 int i;
drh030796d2012-08-23 16:18:10 +00004672 struct SrcCount *p = pWalker->u.pSrcCount;
4673 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00004674 int nSrc = pSrc ? pSrc->nSrc : 0;
4675 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00004676 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00004677 }
drh655814d2015-01-09 01:27:29 +00004678 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00004679 p->nThis++;
4680 }else{
4681 p->nOther++;
4682 }
drh374fdce2012-04-17 16:38:53 +00004683 }
drh030796d2012-08-23 16:18:10 +00004684 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004685}
4686
4687/*
drh030796d2012-08-23 16:18:10 +00004688** Determine if any of the arguments to the pExpr Function reference
4689** pSrcList. Return true if they do. Also return true if the function
4690** has no arguments or has only constant arguments. Return false if pExpr
4691** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004692*/
drh030796d2012-08-23 16:18:10 +00004693int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004694 Walker w;
drh030796d2012-08-23 16:18:10 +00004695 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004696 assert( pExpr->op==TK_AGG_FUNCTION );
4697 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004698 w.xExprCallback = exprSrcCount;
4699 w.u.pSrcCount = &cnt;
4700 cnt.pSrc = pSrcList;
4701 cnt.nThis = 0;
4702 cnt.nOther = 0;
4703 sqlite3WalkExprList(&w, pExpr->x.pList);
4704 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004705}
4706
4707/*
drh13449892005-09-07 21:22:45 +00004708** Add a new element to the pAggInfo->aCol[] array. Return the index of
4709** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004710*/
drh17435752007-08-16 04:30:38 +00004711static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004712 int i;
drhcf643722007-03-27 13:36:37 +00004713 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004714 db,
drhcf643722007-03-27 13:36:37 +00004715 pInfo->aCol,
4716 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004717 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004718 &i
4719 );
drh13449892005-09-07 21:22:45 +00004720 return i;
4721}
4722
4723/*
4724** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4725** the new element. Return a negative number if malloc fails.
4726*/
drh17435752007-08-16 04:30:38 +00004727static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004728 int i;
drhcf643722007-03-27 13:36:37 +00004729 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004730 db,
drhcf643722007-03-27 13:36:37 +00004731 pInfo->aFunc,
4732 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004733 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004734 &i
4735 );
drh13449892005-09-07 21:22:45 +00004736 return i;
4737}
drh22827922000-06-06 17:27:05 +00004738
4739/*
drh7d10d5a2008-08-20 16:35:10 +00004740** This is the xExprCallback for a tree walker. It is used to
4741** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004742** for additional information.
drh22827922000-06-06 17:27:05 +00004743*/
drh7d10d5a2008-08-20 16:35:10 +00004744static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004745 int i;
drh7d10d5a2008-08-20 16:35:10 +00004746 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004747 Parse *pParse = pNC->pParse;
4748 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004749 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004750
drh22827922000-06-06 17:27:05 +00004751 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004752 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004753 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004754 testcase( pExpr->op==TK_AGG_COLUMN );
4755 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004756 /* Check to see if the column is in one of the tables in the FROM
4757 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004758 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004759 struct SrcList_item *pItem = pSrcList->a;
4760 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4761 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004762 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004763 if( pExpr->iTable==pItem->iCursor ){
4764 /* If we reach this point, it means that pExpr refers to a table
4765 ** that is in the FROM clause of the aggregate query.
4766 **
4767 ** Make an entry for the column in pAggInfo->aCol[] if there
4768 ** is not an entry there already.
4769 */
drh7f906d62007-03-12 23:48:52 +00004770 int k;
drh13449892005-09-07 21:22:45 +00004771 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004772 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004773 if( pCol->iTable==pExpr->iTable &&
4774 pCol->iColumn==pExpr->iColumn ){
4775 break;
4776 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004777 }
danielk19771e536952007-08-16 10:09:01 +00004778 if( (k>=pAggInfo->nColumn)
4779 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4780 ){
drh7f906d62007-03-12 23:48:52 +00004781 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004782 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004783 pCol->iTable = pExpr->iTable;
4784 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004785 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004786 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004787 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004788 if( pAggInfo->pGroupBy ){
4789 int j, n;
4790 ExprList *pGB = pAggInfo->pGroupBy;
4791 struct ExprList_item *pTerm = pGB->a;
4792 n = pGB->nExpr;
4793 for(j=0; j<n; j++, pTerm++){
4794 Expr *pE = pTerm->pExpr;
4795 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4796 pE->iColumn==pExpr->iColumn ){
4797 pCol->iSorterColumn = j;
4798 break;
4799 }
4800 }
4801 }
4802 if( pCol->iSorterColumn<0 ){
4803 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4804 }
4805 }
4806 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4807 ** because it was there before or because we just created it).
4808 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4809 ** pAggInfo->aCol[] entry.
4810 */
drhebb6a652013-09-12 23:42:22 +00004811 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004812 pExpr->pAggInfo = pAggInfo;
4813 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004814 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004815 break;
4816 } /* endif pExpr->iTable==pItem->iCursor */
4817 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004818 }
drh7d10d5a2008-08-20 16:35:10 +00004819 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004820 }
4821 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004822 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004823 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004824 ){
drh13449892005-09-07 21:22:45 +00004825 /* Check to see if pExpr is a duplicate of another aggregate
4826 ** function that is already in the pAggInfo structure
4827 */
4828 struct AggInfo_func *pItem = pAggInfo->aFunc;
4829 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004830 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004831 break;
4832 }
drh22827922000-06-06 17:27:05 +00004833 }
drh13449892005-09-07 21:22:45 +00004834 if( i>=pAggInfo->nFunc ){
4835 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4836 */
danielk197714db2662006-01-09 16:12:04 +00004837 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004838 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004839 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004840 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004841 pItem = &pAggInfo->aFunc[i];
4842 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004843 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004844 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004845 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004846 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004847 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004848 if( pExpr->flags & EP_Distinct ){
4849 pItem->iDistinct = pParse->nTab++;
4850 }else{
4851 pItem->iDistinct = -1;
4852 }
drh13449892005-09-07 21:22:45 +00004853 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004854 }
drh13449892005-09-07 21:22:45 +00004855 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4856 */
drhc5cd1242013-09-12 16:50:49 +00004857 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004858 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004859 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004860 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004861 return WRC_Prune;
4862 }else{
4863 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004864 }
drh22827922000-06-06 17:27:05 +00004865 }
4866 }
drh7d10d5a2008-08-20 16:35:10 +00004867 return WRC_Continue;
4868}
4869static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004870 UNUSED_PARAMETER(pWalker);
4871 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004872 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004873}
4874
4875/*
drhe8abb4c2012-11-02 18:24:57 +00004876** Analyze the pExpr expression looking for aggregate functions and
4877** for variables that need to be added to AggInfo object that pNC->pAggInfo
4878** points to. Additional entries are made on the AggInfo object as
4879** necessary.
drh626a8792005-01-17 22:08:19 +00004880**
4881** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004882** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004883*/
drhd2b3e232008-01-23 14:51:49 +00004884void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004885 Walker w;
drh374fdce2012-04-17 16:38:53 +00004886 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004887 w.xExprCallback = analyzeAggregate;
4888 w.xSelectCallback = analyzeAggregatesInSelect;
4889 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004890 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004891 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004892}
drh5d9a4af2005-08-30 00:54:01 +00004893
4894/*
4895** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4896** expression list. Return the number of errors.
4897**
4898** If an error is found, the analysis is cut short.
4899*/
drhd2b3e232008-01-23 14:51:49 +00004900void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004901 struct ExprList_item *pItem;
4902 int i;
drh5d9a4af2005-08-30 00:54:01 +00004903 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004904 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4905 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004906 }
4907 }
drh5d9a4af2005-08-30 00:54:01 +00004908}
drh892d3172008-01-10 03:46:36 +00004909
4910/*
drhceea3322009-04-23 13:22:42 +00004911** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004912*/
4913int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004914 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004915 return ++pParse->nMem;
4916 }
danielk19772f425f62008-07-04 09:41:39 +00004917 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004918}
drhceea3322009-04-23 13:22:42 +00004919
4920/*
4921** Deallocate a register, making available for reuse for some other
4922** purpose.
4923**
4924** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004925** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004926** the register becomes stale.
4927*/
drh892d3172008-01-10 03:46:36 +00004928void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004929 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004930 int i;
4931 struct yColCache *p;
4932 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4933 if( p->iReg==iReg ){
4934 p->tempReg = 1;
4935 return;
4936 }
4937 }
drh892d3172008-01-10 03:46:36 +00004938 pParse->aTempReg[pParse->nTempReg++] = iReg;
4939 }
4940}
4941
4942/*
4943** Allocate or deallocate a block of nReg consecutive registers
4944*/
4945int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004946 int i, n;
4947 i = pParse->iRangeReg;
4948 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004949 if( nReg<=n ){
4950 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004951 pParse->iRangeReg += nReg;
4952 pParse->nRangeReg -= nReg;
4953 }else{
4954 i = pParse->nMem+1;
4955 pParse->nMem += nReg;
4956 }
4957 return i;
4958}
4959void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004960 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004961 if( nReg>pParse->nRangeReg ){
4962 pParse->nRangeReg = nReg;
4963 pParse->iRangeReg = iReg;
4964 }
4965}
drhcdc69552011-12-06 13:24:59 +00004966
4967/*
4968** Mark all temporary registers as being unavailable for reuse.
4969*/
4970void sqlite3ClearTempRegCache(Parse *pParse){
4971 pParse->nTempReg = 0;
4972 pParse->nRangeReg = 0;
4973}
drhbb9b5f22016-03-19 00:35:02 +00004974
4975/*
4976** Validate that no temporary register falls within the range of
4977** iFirst..iLast, inclusive. This routine is only call from within assert()
4978** statements.
4979*/
4980#ifdef SQLITE_DEBUG
4981int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4982 int i;
4983 if( pParse->nRangeReg>0
4984 && pParse->iRangeReg+pParse->nRangeReg<iLast
4985 && pParse->iRangeReg>=iFirst
4986 ){
4987 return 0;
4988 }
4989 for(i=0; i<pParse->nTempReg; i++){
4990 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4991 return 0;
4992 }
4993 }
4994 return 1;
4995}
4996#endif /* SQLITE_DEBUG */