blob: 385e80891790c32b957c3cc839071507e8f039d8 [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);
drhd0b67a82016-08-24 15:37:31 +0000224 }else if( NEVER(aff==0) ){
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 ){
drhe835bc12016-08-23 19:02:55 +0000520 sqlite3ErrorMsg(pParse, "row value misused");
dan71c57db2016-07-09 20:23:55 +0000521 }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
drh321e8282016-08-24 17:49:07 +0000545 for(i=0; 1 /*Loop exits by "break"*/; i++){
dan71c57db2016-07-09 20:23:55 +0000546 int regFree1 = 0, regFree2 = 0;
547 Expr *pL, *pR;
548 int r1, r2;
drh321e8282016-08-24 17:49:07 +0000549 assert( i>=0 && i<nLeft );
drh79752b62016-08-13 10:02:17 +0000550 if( i>0 ) sqlite3ExprCachePush(pParse);
dan5c288b92016-07-30 21:02:33 +0000551 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
552 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
drh79752b62016-08-13 10:02:17 +0000553 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
554 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
555 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
556 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
557 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
558 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
559 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
dan71c57db2016-07-09 20:23:55 +0000560 sqlite3ReleaseTempReg(pParse, regFree1);
561 sqlite3ReleaseTempReg(pParse, regFree2);
drh79752b62016-08-13 10:02:17 +0000562 if( i>0 ) sqlite3ExprCachePop(pParse);
563 if( i==nLeft-1 ){
564 break;
565 }
566 if( opx==TK_EQ ){
567 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
568 p5 |= SQLITE_KEEPNULL;
569 }else if( opx==TK_NE ){
570 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
571 p5 |= SQLITE_KEEPNULL;
drha2f62922016-08-13 12:37:47 +0000572 }else{
573 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
574 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
drh79752b62016-08-13 10:02:17 +0000575 VdbeCoverageIf(v, op==TK_LT);
576 VdbeCoverageIf(v, op==TK_GT);
drh79752b62016-08-13 10:02:17 +0000577 VdbeCoverageIf(v, op==TK_LE);
578 VdbeCoverageIf(v, op==TK_GE);
579 if( i==nLeft-2 ) opx = op;
580 }
dan71c57db2016-07-09 20:23:55 +0000581 }
drh79752b62016-08-13 10:02:17 +0000582 sqlite3VdbeResolveLabel(v, addrDone);
dan71c57db2016-07-09 20:23:55 +0000583 }
dan71c57db2016-07-09 20:23:55 +0000584}
585
danielk19774b5255a2008-06-05 16:47:39 +0000586#if SQLITE_MAX_EXPR_DEPTH>0
587/*
588** Check that argument nHeight is less than or equal to the maximum
589** expression depth allowed. If it is not, leave an error message in
590** pParse.
591*/
drh7d10d5a2008-08-20 16:35:10 +0000592int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000593 int rc = SQLITE_OK;
594 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
595 if( nHeight>mxHeight ){
596 sqlite3ErrorMsg(pParse,
597 "Expression tree is too large (maximum depth %d)", mxHeight
598 );
599 rc = SQLITE_ERROR;
600 }
601 return rc;
602}
603
604/* The following three functions, heightOfExpr(), heightOfExprList()
605** and heightOfSelect(), are used to determine the maximum height
606** of any expression tree referenced by the structure passed as the
607** first argument.
608**
609** If this maximum height is greater than the current value pointed
610** to by pnHeight, the second parameter, then set *pnHeight to that
611** value.
612*/
613static void heightOfExpr(Expr *p, int *pnHeight){
614 if( p ){
615 if( p->nHeight>*pnHeight ){
616 *pnHeight = p->nHeight;
617 }
618 }
619}
620static void heightOfExprList(ExprList *p, int *pnHeight){
621 if( p ){
622 int i;
623 for(i=0; i<p->nExpr; i++){
624 heightOfExpr(p->a[i].pExpr, pnHeight);
625 }
626 }
627}
628static void heightOfSelect(Select *p, int *pnHeight){
629 if( p ){
630 heightOfExpr(p->pWhere, pnHeight);
631 heightOfExpr(p->pHaving, pnHeight);
632 heightOfExpr(p->pLimit, pnHeight);
633 heightOfExpr(p->pOffset, pnHeight);
634 heightOfExprList(p->pEList, pnHeight);
635 heightOfExprList(p->pGroupBy, pnHeight);
636 heightOfExprList(p->pOrderBy, pnHeight);
637 heightOfSelect(p->pPrior, pnHeight);
638 }
639}
640
641/*
642** Set the Expr.nHeight variable in the structure passed as an
643** argument. An expression with no children, Expr.pList or
644** Expr.pSelect member has a height of 1. Any other expression
645** has a height equal to the maximum height of any other
646** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000647**
648** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
649** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000650*/
651static void exprSetHeight(Expr *p){
652 int nHeight = 0;
653 heightOfExpr(p->pLeft, &nHeight);
654 heightOfExpr(p->pRight, &nHeight);
danielk19776ab3a2e2009-02-19 14:39:25 +0000655 if( ExprHasProperty(p, EP_xIsSelect) ){
656 heightOfSelect(p->x.pSelect, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000657 }else if( p->x.pList ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000658 heightOfExprList(p->x.pList, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000659 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
danielk19776ab3a2e2009-02-19 14:39:25 +0000660 }
danielk19774b5255a2008-06-05 16:47:39 +0000661 p->nHeight = nHeight + 1;
662}
663
664/*
665** Set the Expr.nHeight variable using the exprSetHeight() function. If
666** the height is greater than the maximum allowed expression depth,
667** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000668**
669** Also propagate all EP_Propagate flags from the Expr.x.pList into
670** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000671*/
drh2308ed32015-02-09 16:09:34 +0000672void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh74893a42015-03-22 10:23:17 +0000673 if( pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000674 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000675 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000676}
677
678/*
679** Return the maximum height of any expression tree referenced
680** by the select statement passed as an argument.
681*/
682int sqlite3SelectExprHeight(Select *p){
683 int nHeight = 0;
684 heightOfSelect(p, &nHeight);
685 return nHeight;
686}
drh2308ed32015-02-09 16:09:34 +0000687#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
688/*
689** Propagate all EP_Propagate flags from the Expr.x.pList into
690** Expr.flags.
691*/
692void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
693 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
694 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
695 }
696}
697#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000698#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
699
drhbe5c89a2004-07-26 00:31:09 +0000700/*
drhb7916a72009-05-27 10:31:29 +0000701** This routine is the core allocator for Expr nodes.
702**
drha76b5df2002-02-23 02:32:10 +0000703** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000704** for this node and for the pToken argument is a single allocation
705** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000706** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000707**
708** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000709** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000710** parameter is ignored if pToken is NULL or if the token does not
711** appear to be quoted. If the quotes were of the form "..." (double-quotes)
712** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000713**
714** Special case: If op==TK_INTEGER and pToken points to a string that
715** can be translated into a 32-bit integer, then the token is not
716** stored in u.zToken. Instead, the integer values is written
717** into u.iValue and the EP_IntValue flag is set. No extra storage
718** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000719*/
drhb7916a72009-05-27 10:31:29 +0000720Expr *sqlite3ExprAlloc(
danielk1977a1644fd2007-08-29 12:31:25 +0000721 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
drh17435752007-08-16 04:30:38 +0000722 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000723 const Token *pToken, /* Token argument. Might be NULL */
724 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000725){
drha76b5df2002-02-23 02:32:10 +0000726 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000727 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000728 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000729
drh575fad62016-02-05 13:38:36 +0000730 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000731 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000732 if( op!=TK_INTEGER || pToken->z==0
733 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
734 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000735 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000736 }
drhb7916a72009-05-27 10:31:29 +0000737 }
drh575fad62016-02-05 13:38:36 +0000738 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000739 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000740 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000741 pNew->op = (u8)op;
742 pNew->iAgg = -1;
743 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000744 if( nExtra==0 ){
745 pNew->flags |= EP_IntValue;
746 pNew->u.iValue = iValue;
747 }else{
drh33e619f2009-05-28 01:00:55 +0000748 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000749 assert( pToken->z!=0 || pToken->n==0 );
750 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000751 pNew->u.zToken[pToken->n] = 0;
drh244b9d62016-04-11 19:01:08 +0000752 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
753 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
drh33e619f2009-05-28 01:00:55 +0000754 sqlite3Dequote(pNew->u.zToken);
drh33e619f2009-05-28 01:00:55 +0000755 }
drhb7916a72009-05-27 10:31:29 +0000756 }
757 }
758#if SQLITE_MAX_EXPR_DEPTH>0
759 pNew->nHeight = 1;
760#endif
761 }
drha76b5df2002-02-23 02:32:10 +0000762 return pNew;
763}
764
765/*
drhb7916a72009-05-27 10:31:29 +0000766** Allocate a new expression node from a zero-terminated token that has
767** already been dequoted.
768*/
769Expr *sqlite3Expr(
770 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
771 int op, /* Expression opcode */
772 const char *zToken /* Token argument. Might be NULL */
773){
774 Token x;
775 x.z = zToken;
776 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
777 return sqlite3ExprAlloc(db, op, &x, 0);
778}
779
780/*
781** Attach subtrees pLeft and pRight to the Expr node pRoot.
782**
783** If pRoot==NULL that means that a memory allocation error has occurred.
784** In that case, delete the subtrees pLeft and pRight.
785*/
786void sqlite3ExprAttachSubtrees(
787 sqlite3 *db,
788 Expr *pRoot,
789 Expr *pLeft,
790 Expr *pRight
791){
792 if( pRoot==0 ){
793 assert( db->mallocFailed );
794 sqlite3ExprDelete(db, pLeft);
795 sqlite3ExprDelete(db, pRight);
796 }else{
797 if( pRight ){
798 pRoot->pRight = pRight;
drh885a5b02015-02-09 15:21:36 +0000799 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000800 }
801 if( pLeft ){
802 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000803 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000804 }
805 exprSetHeight(pRoot);
806 }
807}
808
809/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000810** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000811**
drhbf664462009-06-19 18:32:54 +0000812** One or both of the subtrees can be NULL. Return a pointer to the new
813** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
814** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000815*/
drh17435752007-08-16 04:30:38 +0000816Expr *sqlite3PExpr(
817 Parse *pParse, /* Parsing context */
818 int op, /* Expression opcode */
819 Expr *pLeft, /* Left operand */
820 Expr *pRight, /* Right operand */
821 const Token *pToken /* Argument token */
822){
drh5fb52ca2012-03-31 02:34:35 +0000823 Expr *p;
drh1167d322015-10-28 20:01:45 +0000824 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000825 /* Take advantage of short-circuit false optimization for AND */
826 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
827 }else{
drh1167d322015-10-28 20:01:45 +0000828 p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
drh5fb52ca2012-03-31 02:34:35 +0000829 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
830 }
dan2b359bd2010-10-28 11:31:23 +0000831 if( p ) {
832 sqlite3ExprCheckHeight(pParse, p->nHeight);
833 }
drh4e0cff62004-11-05 05:10:28 +0000834 return p;
835}
836
837/*
drh08de4f72016-04-11 01:06:47 +0000838** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
839** do a memory allocation failure) then delete the pSelect object.
840*/
841void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
842 if( pExpr ){
843 pExpr->x.pSelect = pSelect;
844 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
845 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
846 }else{
847 assert( pParse->db->mallocFailed );
848 sqlite3SelectDelete(pParse->db, pSelect);
849 }
850}
851
852
853/*
drh991a1982014-01-02 17:57:16 +0000854** If the expression is always either TRUE or FALSE (respectively),
855** then return 1. If one cannot determine the truth value of the
856** expression at compile-time return 0.
857**
858** This is an optimization. If is OK to return 0 here even if
859** the expression really is always false or false (a false negative).
860** But it is a bug to return 1 if the expression might have different
861** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000862**
863** Note that if the expression is part of conditional for a
864** LEFT JOIN, then we cannot determine at compile-time whether or not
865** is it true or false, so always return 0.
866*/
drh991a1982014-01-02 17:57:16 +0000867static int exprAlwaysTrue(Expr *p){
868 int v = 0;
869 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
870 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
871 return v!=0;
872}
drh5fb52ca2012-03-31 02:34:35 +0000873static int exprAlwaysFalse(Expr *p){
874 int v = 0;
875 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
876 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
877 return v==0;
878}
879
880/*
drh91bb0ee2004-09-01 03:06:34 +0000881** Join two expressions using an AND operator. If either expression is
882** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000883**
884** If one side or the other of the AND is known to be false, then instead
885** of returning an AND expression, just return a constant expression with
886** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000887*/
danielk19771e536952007-08-16 10:09:01 +0000888Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000889 if( pLeft==0 ){
890 return pRight;
891 }else if( pRight==0 ){
892 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000893 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
894 sqlite3ExprDelete(db, pLeft);
895 sqlite3ExprDelete(db, pRight);
896 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000897 }else{
drhb7916a72009-05-27 10:31:29 +0000898 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
899 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
900 return pNew;
drha76b5df2002-02-23 02:32:10 +0000901 }
902}
903
904/*
905** Construct a new expression node for a function with multiple
906** arguments.
907*/
drh17435752007-08-16 04:30:38 +0000908Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000909 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000910 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000911 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000912 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000913 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000914 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000915 return 0;
916 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000917 pNew->x.pList = pList;
918 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
drh2308ed32015-02-09 16:09:34 +0000919 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drha76b5df2002-02-23 02:32:10 +0000920 return pNew;
921}
922
923/*
drhfa6bc002004-09-07 16:19:52 +0000924** Assign a variable number to an expression that encodes a wildcard
925** in the original SQL statement.
926**
927** Wildcards consisting of a single "?" are assigned the next sequential
928** variable number.
929**
930** Wildcards of the form "?nnn" are assigned the number "nnn". We make
931** sure "nnn" is not too be to avoid a denial of service attack when
932** the SQL statement comes from an external source.
933**
drh51f49f12009-05-21 20:41:32 +0000934** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +0000935** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +0000936** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +0000937** assigned.
938*/
939void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
drh17435752007-08-16 04:30:38 +0000940 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +0000941 const char *z;
drh17435752007-08-16 04:30:38 +0000942
drhfa6bc002004-09-07 16:19:52 +0000943 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +0000944 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +0000945 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000946 assert( z!=0 );
947 assert( z[0]!=0 );
948 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +0000949 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +0000950 assert( z[0]=='?' );
drh8677d302009-11-04 13:17:14 +0000951 pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000952 }else{
drh124c0b42011-06-01 18:15:55 +0000953 ynVar x = 0;
954 u32 n = sqlite3Strlen30(z);
955 if( z[0]=='?' ){
956 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
957 ** use it as the variable number */
958 i64 i;
959 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
960 pExpr->iColumn = x = (ynVar)i;
961 testcase( i==0 );
962 testcase( i==1 );
963 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
964 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
965 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
966 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
967 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
968 x = 0;
drhfa6bc002004-09-07 16:19:52 +0000969 }
drh124c0b42011-06-01 18:15:55 +0000970 if( i>pParse->nVar ){
971 pParse->nVar = (int)i;
972 }
973 }else{
974 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
975 ** number as the prior appearance of the same name, or if the name
976 ** has never appeared before, reuse the same variable number
977 */
978 ynVar i;
979 for(i=0; i<pParse->nzVar; i++){
drh503a6862013-03-01 01:07:17 +0000980 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
drh124c0b42011-06-01 18:15:55 +0000981 pExpr->iColumn = x = (ynVar)i+1;
982 break;
983 }
984 }
985 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000986 }
drh124c0b42011-06-01 18:15:55 +0000987 if( x>0 ){
988 if( x>pParse->nzVar ){
989 char **a;
990 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
drh4a642b62016-02-05 01:55:27 +0000991 if( a==0 ){
992 assert( db->mallocFailed ); /* Error reported through mallocFailed */
993 return;
994 }
drh124c0b42011-06-01 18:15:55 +0000995 pParse->azVar = a;
996 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
997 pParse->nzVar = x;
drhfa6bc002004-09-07 16:19:52 +0000998 }
drh124c0b42011-06-01 18:15:55 +0000999 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
1000 sqlite3DbFree(db, pParse->azVar[x-1]);
1001 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
drhfa6bc002004-09-07 16:19:52 +00001002 }
1003 }
1004 }
drhbb4957f2008-03-20 14:03:29 +00001005 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +00001006 sqlite3ErrorMsg(pParse, "too many SQL variables");
1007 }
drhfa6bc002004-09-07 16:19:52 +00001008}
1009
1010/*
danf6963f92009-11-23 14:39:14 +00001011** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +00001012*/
drh4f0010b2016-04-11 14:49:39 +00001013static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1014 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +00001015 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1016 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drhc5cd1242013-09-12 16:50:49 +00001017 if( !ExprHasProperty(p, EP_TokenOnly) ){
1018 /* The Expr.x union is never used at the same time as Expr.pRight */
1019 assert( p->x.pList==0 || p->pRight==0 );
dan71c57db2016-07-09 20:23:55 +00001020 if( p->op!=TK_SELECT_COLUMN ) sqlite3ExprDelete(db, p->pLeft);
drh33e619f2009-05-28 01:00:55 +00001021 sqlite3ExprDelete(db, p->pRight);
drhc5cd1242013-09-12 16:50:49 +00001022 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
danielk19776ab3a2e2009-02-19 14:39:25 +00001023 if( ExprHasProperty(p, EP_xIsSelect) ){
1024 sqlite3SelectDelete(db, p->x.pSelect);
1025 }else{
1026 sqlite3ExprListDelete(db, p->x.pList);
1027 }
1028 }
drh33e619f2009-05-28 01:00:55 +00001029 if( !ExprHasProperty(p, EP_Static) ){
1030 sqlite3DbFree(db, p);
1031 }
drha2e00042002-01-22 03:13:42 +00001032}
drh4f0010b2016-04-11 14:49:39 +00001033void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1034 if( p ) sqlite3ExprDeleteNN(db, p);
1035}
drha2e00042002-01-22 03:13:42 +00001036
drhd2687b72005-08-12 22:56:09 +00001037/*
danielk19776ab3a2e2009-02-19 14:39:25 +00001038** Return the number of bytes allocated for the expression structure
1039** passed as the first argument. This is always one of EXPR_FULLSIZE,
1040** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1041*/
1042static int exprStructSize(Expr *p){
1043 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001044 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1045 return EXPR_FULLSIZE;
1046}
1047
1048/*
drh33e619f2009-05-28 01:00:55 +00001049** The dupedExpr*Size() routines each return the number of bytes required
1050** to store a copy of an expression or expression tree. They differ in
1051** how much of the tree is measured.
1052**
1053** dupedExprStructSize() Size of only the Expr structure
1054** dupedExprNodeSize() Size of Expr + space for token
1055** dupedExprSize() Expr + token + subtree components
1056**
1057***************************************************************************
1058**
1059** The dupedExprStructSize() function returns two values OR-ed together:
1060** (1) the space required for a copy of the Expr structure only and
1061** (2) the EP_xxx flags that indicate what the structure size should be.
1062** The return values is always one of:
1063**
1064** EXPR_FULLSIZE
1065** EXPR_REDUCEDSIZE | EP_Reduced
1066** EXPR_TOKENONLYSIZE | EP_TokenOnly
1067**
1068** The size of the structure can be found by masking the return value
1069** of this routine with 0xfff. The flags can be found by masking the
1070** return value with EP_Reduced|EP_TokenOnly.
1071**
1072** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1073** (unreduced) Expr objects as they or originally constructed by the parser.
1074** During expression analysis, extra information is computed and moved into
1075** later parts of teh Expr object and that extra information might get chopped
1076** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +00001077** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +00001078** to reduce a pristine expression tree from the parser. The implementation
1079** of dupedExprStructSize() contain multiple assert() statements that attempt
1080** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +00001081*/
1082static int dupedExprStructSize(Expr *p, int flags){
1083 int nSize;
drh33e619f2009-05-28 01:00:55 +00001084 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +00001085 assert( EXPR_FULLSIZE<=0xfff );
1086 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
drh3c194692016-04-11 16:43:43 +00001087 if( 0==flags ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001088 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001089 }else{
drhc5cd1242013-09-12 16:50:49 +00001090 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +00001091 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +00001092 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +00001093 assert( !ExprHasProperty(p, EP_NoReduce) );
drhaecd8022013-09-13 18:15:15 +00001094 if( p->pLeft || p->x.pList ){
drh33e619f2009-05-28 01:00:55 +00001095 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1096 }else{
drhaecd8022013-09-13 18:15:15 +00001097 assert( p->pRight==0 );
drh33e619f2009-05-28 01:00:55 +00001098 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1099 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001100 }
1101 return nSize;
1102}
1103
1104/*
drh33e619f2009-05-28 01:00:55 +00001105** This function returns the space in bytes required to store the copy
1106** of the Expr structure and a copy of the Expr.u.zToken string (if that
1107** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +00001108*/
1109static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +00001110 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1111 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1112 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001113 }
danielk1977bc739712009-03-23 04:33:32 +00001114 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +00001115}
1116
1117/*
1118** Return the number of bytes required to create a duplicate of the
1119** expression passed as the first argument. The second argument is a
1120** mask containing EXPRDUP_XXX flags.
1121**
1122** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +00001123** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +00001124**
1125** If the EXPRDUP_REDUCE flag is set, then the return value includes
1126** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1127** and Expr.pRight variables (but not for any structures pointed to or
1128** descended from the Expr.x.pList or Expr.x.pSelect variables).
1129*/
1130static int dupedExprSize(Expr *p, int flags){
1131 int nByte = 0;
1132 if( p ){
1133 nByte = dupedExprNodeSize(p, flags);
1134 if( flags&EXPRDUP_REDUCE ){
drhb7916a72009-05-27 10:31:29 +00001135 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001136 }
1137 }
1138 return nByte;
1139}
1140
1141/*
1142** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1143** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +00001144** to store the copy of expression p, the copies of p->u.zToken
danielk19776ab3a2e2009-02-19 14:39:25 +00001145** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +00001146** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +00001147** portion of the buffer copied into by this function.
1148*/
drh3c194692016-04-11 16:43:43 +00001149static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1150 Expr *pNew; /* Value to return */
1151 u8 *zAlloc; /* Memory space from which to build Expr object */
1152 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1153
drh575fad62016-02-05 13:38:36 +00001154 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +00001155 assert( p );
1156 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1157 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +00001158
drh3c194692016-04-11 16:43:43 +00001159 /* Figure out where to write the new Expr structure. */
1160 if( pzBuffer ){
1161 zAlloc = *pzBuffer;
1162 staticFlag = EP_Static;
1163 }else{
1164 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1165 staticFlag = 0;
1166 }
1167 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001168
drh3c194692016-04-11 16:43:43 +00001169 if( pNew ){
1170 /* Set nNewSize to the size allocated for the structure pointed to
1171 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1172 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1173 ** by the copy of the p->u.zToken string (if any).
1174 */
1175 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1176 const int nNewSize = nStructSize & 0xfff;
1177 int nToken;
1178 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1179 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001180 }else{
drh3c194692016-04-11 16:43:43 +00001181 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001182 }
drh3c194692016-04-11 16:43:43 +00001183 if( dupFlags ){
1184 assert( ExprHasProperty(p, EP_Reduced)==0 );
1185 memcpy(zAlloc, p, nNewSize);
1186 }else{
1187 u32 nSize = (u32)exprStructSize(p);
1188 memcpy(zAlloc, p, nSize);
1189 if( nSize<EXPR_FULLSIZE ){
1190 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1191 }
1192 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001193
drh3c194692016-04-11 16:43:43 +00001194 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1195 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1196 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1197 pNew->flags |= staticFlag;
1198
1199 /* Copy the p->u.zToken string, if any. */
1200 if( nToken ){
1201 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1202 memcpy(zToken, p->u.zToken, nToken);
1203 }
1204
1205 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
1206 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1207 if( ExprHasProperty(p, EP_xIsSelect) ){
1208 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001209 }else{
drh3c194692016-04-11 16:43:43 +00001210 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001211 }
drh3c194692016-04-11 16:43:43 +00001212 }
1213
1214 /* Fill in pNew->pLeft and pNew->pRight. */
1215 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1216 zAlloc += dupedExprNodeSize(p, dupFlags);
1217 if( ExprHasProperty(pNew, EP_Reduced) ){
1218 pNew->pLeft = p->pLeft ?
1219 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1220 pNew->pRight = p->pRight ?
1221 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001222 }
drh3c194692016-04-11 16:43:43 +00001223 if( pzBuffer ){
1224 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001225 }
drh3c194692016-04-11 16:43:43 +00001226 }else{
1227 if( !ExprHasProperty(p, EP_TokenOnly) ){
drh98542602016-08-20 17:00:16 +00001228 if( pNew->op==TK_SELECT_COLUMN ){
1229 pNew->pLeft = p->pLeft;
1230 }else{
1231 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1232 }
drh3c194692016-04-11 16:43:43 +00001233 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
danielk19776ab3a2e2009-02-19 14:39:25 +00001234 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001235 }
1236 }
1237 return pNew;
1238}
1239
1240/*
danbfe31e72014-01-15 14:17:31 +00001241** Create and return a deep copy of the object passed as the second
1242** argument. If an OOM condition is encountered, NULL is returned
1243** and the db->mallocFailed flag set.
1244*/
daneede6a52014-01-15 19:42:23 +00001245#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +00001246static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +00001247 With *pRet = 0;
1248 if( p ){
1249 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1250 pRet = sqlite3DbMallocZero(db, nByte);
1251 if( pRet ){
1252 int i;
1253 pRet->nCte = p->nCte;
1254 for(i=0; i<p->nCte; i++){
1255 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1256 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1257 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1258 }
1259 }
1260 }
1261 return pRet;
1262}
daneede6a52014-01-15 19:42:23 +00001263#else
1264# define withDup(x,y) 0
1265#endif
dan4e9119d2014-01-13 15:12:23 +00001266
drha76b5df2002-02-23 02:32:10 +00001267/*
drhff78bd22002-02-27 01:47:11 +00001268** The following group of routines make deep copies of expressions,
1269** expression lists, ID lists, and select statements. The copies can
1270** be deleted (by being passed to their respective ...Delete() routines)
1271** without effecting the originals.
1272**
danielk19774adee202004-05-08 08:23:19 +00001273** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1274** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +00001275** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001276**
drhad3cab52002-05-24 02:04:32 +00001277** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001278**
drhb7916a72009-05-27 10:31:29 +00001279** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001280** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1281** truncated version of the usual Expr structure that will be stored as
1282** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001283*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001284Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001285 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001286 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001287}
danielk19776ab3a2e2009-02-19 14:39:25 +00001288ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001289 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001290 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001291 int i;
drh575fad62016-02-05 13:38:36 +00001292 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001293 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001294 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001295 if( pNew==0 ) return 0;
drhd872bb12012-02-02 01:58:08 +00001296 pNew->nExpr = i = p->nExpr;
1297 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
drh575fad62016-02-05 13:38:36 +00001298 pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +00001299 if( pItem==0 ){
drh633e6d52008-07-28 19:34:53 +00001300 sqlite3DbFree(db, pNew);
danielk1977e0048402004-06-15 16:51:01 +00001301 return 0;
1302 }
drh145716b2004-09-24 12:24:06 +00001303 pOldItem = p->a;
1304 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001305 Expr *pOldExpr = pOldItem->pExpr;
drhb5526ea2009-07-16 12:41:05 +00001306 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh17435752007-08-16 04:30:38 +00001307 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001308 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001309 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001310 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001311 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
drhc2acc4e2013-11-15 18:15:19 +00001312 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001313 }
1314 return pNew;
1315}
danielk197793758c82005-01-21 08:13:14 +00001316
1317/*
1318** If cursors, triggers, views and subqueries are all omitted from
1319** the build, then none of the following routines, except for
1320** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1321** called with a NULL argument.
1322*/
danielk19776a67fe82005-02-04 04:07:16 +00001323#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1324 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001325SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001326 SrcList *pNew;
1327 int i;
drh113088e2003-03-20 01:16:58 +00001328 int nByte;
drh575fad62016-02-05 13:38:36 +00001329 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001330 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001331 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001332 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001333 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001334 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001335 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001336 struct SrcList_item *pNewItem = &pNew->a[i];
1337 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001338 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001339 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001340 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1341 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1342 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001343 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001344 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001345 pNewItem->addrFillSub = pOldItem->addrFillSub;
1346 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001347 if( pNewItem->fg.isIndexedBy ){
1348 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1349 }
1350 pNewItem->pIBIndex = pOldItem->pIBIndex;
1351 if( pNewItem->fg.isTabFunc ){
1352 pNewItem->u1.pFuncArg =
1353 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1354 }
drhed8a3bb2005-06-06 21:19:56 +00001355 pTab = pNewItem->pTab = pOldItem->pTab;
1356 if( pTab ){
1357 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001358 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001359 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1360 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001361 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001362 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001363 }
1364 return pNew;
1365}
drh17435752007-08-16 04:30:38 +00001366IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001367 IdList *pNew;
1368 int i;
drh575fad62016-02-05 13:38:36 +00001369 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001370 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001371 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001372 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001373 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001374 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001375 if( pNew->a==0 ){
drh633e6d52008-07-28 19:34:53 +00001376 sqlite3DbFree(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001377 return 0;
1378 }
drh6c535152012-02-02 03:38:30 +00001379 /* Note that because the size of the allocation for p->a[] is not
1380 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1381 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001382 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001383 struct IdList_item *pNewItem = &pNew->a[i];
1384 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001385 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001386 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001387 }
1388 return pNew;
1389}
danielk19776ab3a2e2009-02-19 14:39:25 +00001390Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
drh23b1b372011-12-07 01:55:51 +00001391 Select *pNew, *pPrior;
drh575fad62016-02-05 13:38:36 +00001392 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001393 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001394 pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +00001395 if( pNew==0 ) return 0;
drhb7916a72009-05-27 10:31:29 +00001396 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001397 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1398 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1399 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1400 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1401 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
drhff78bd22002-02-27 01:47:11 +00001402 pNew->op = p->op;
drh23b1b372011-12-07 01:55:51 +00001403 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
1404 if( pPrior ) pPrior->pNext = pNew;
1405 pNew->pNext = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001406 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1407 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
drh92b01d52008-06-24 00:32:35 +00001408 pNew->iLimit = 0;
1409 pNew->iOffset = 0;
drh7d10d5a2008-08-20 16:35:10 +00001410 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
drhb9bb7c12006-06-11 23:41:55 +00001411 pNew->addrOpenEphm[0] = -1;
1412 pNew->addrOpenEphm[1] = -1;
drhec2da852014-01-29 01:46:12 +00001413 pNew->nSelectRow = p->nSelectRow;
dan4e9119d2014-01-13 15:12:23 +00001414 pNew->pWith = withDup(db, p->pWith);
drheb9b8842014-09-21 00:27:26 +00001415 sqlite3SelectSetName(pNew, p->zSelName);
drhff78bd22002-02-27 01:47:11 +00001416 return pNew;
1417}
danielk197793758c82005-01-21 08:13:14 +00001418#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001419Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001420 assert( p==0 );
1421 return 0;
1422}
1423#endif
drhff78bd22002-02-27 01:47:11 +00001424
1425
1426/*
drha76b5df2002-02-23 02:32:10 +00001427** Add a new element to the end of an expression list. If pList is
1428** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001429**
1430** If a memory allocation error occurs, the entire list is freed and
1431** NULL is returned. If non-NULL is returned, then it is guaranteed
1432** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001433*/
drh17435752007-08-16 04:30:38 +00001434ExprList *sqlite3ExprListAppend(
1435 Parse *pParse, /* Parsing context */
1436 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001437 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001438){
1439 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001440 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001441 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001442 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001443 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001444 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001445 }
drhc263f7c2016-01-18 13:18:54 +00001446 pList->nExpr = 0;
drh575fad62016-02-05 13:38:36 +00001447 pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
drhd872bb12012-02-02 01:58:08 +00001448 if( pList->a==0 ) goto no_mem;
1449 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001450 struct ExprList_item *a;
drhd872bb12012-02-02 01:58:08 +00001451 assert( pList->nExpr>0 );
1452 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001453 if( a==0 ){
1454 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001455 }
danielk1977d5d56522005-03-16 12:15:20 +00001456 pList->a = a;
drha76b5df2002-02-23 02:32:10 +00001457 }
drh4efc4752004-01-16 15:55:37 +00001458 assert( pList->a!=0 );
drhb7916a72009-05-27 10:31:29 +00001459 if( 1 ){
drh4efc4752004-01-16 15:55:37 +00001460 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1461 memset(pItem, 0, sizeof(*pItem));
danielk1977e94ddc92005-03-21 03:53:38 +00001462 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001463 }
1464 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001465
1466no_mem:
1467 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001468 sqlite3ExprDelete(db, pExpr);
1469 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001470 return 0;
drha76b5df2002-02-23 02:32:10 +00001471}
1472
1473/*
drh8762ec12016-08-20 01:06:22 +00001474** pColumns and pExpr form a vector assignment which is part of the SET
1475** clause of an UPDATE statement. Like this:
drha1251bc2016-08-20 00:51:37 +00001476**
1477** (a,b,c) = (expr1,expr2,expr3)
1478** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1479**
1480** For each term of the vector assignment, append new entries to the
drh8762ec12016-08-20 01:06:22 +00001481** expression list pList. In the case of a subquery on the LHS, append
drha1251bc2016-08-20 00:51:37 +00001482** TK_SELECT_COLUMN expressions.
1483*/
1484ExprList *sqlite3ExprListAppendVector(
1485 Parse *pParse, /* Parsing context */
1486 ExprList *pList, /* List to which to append. Might be NULL */
1487 IdList *pColumns, /* List of names of LHS of the assignment */
1488 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1489){
1490 sqlite3 *db = pParse->db;
1491 int n;
1492 int i;
drh66860af2016-08-23 18:30:10 +00001493 int iFirst = pList ? pList->nExpr : 0;
drh321e8282016-08-24 17:49:07 +00001494 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1495 ** exit prior to this routine being invoked */
1496 if( NEVER(pColumns==0) ) goto vector_append_error;
drha1251bc2016-08-20 00:51:37 +00001497 if( pExpr==0 ) goto vector_append_error;
1498 n = sqlite3ExprVectorSize(pExpr);
1499 if( pColumns->nId!=n ){
1500 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1501 pColumns->nId, n);
1502 goto vector_append_error;
1503 }
1504 for(i=0; i<n; i++){
1505 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1506 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1507 if( pList ){
drh66860af2016-08-23 18:30:10 +00001508 assert( pList->nExpr==iFirst+i+1 );
drha1251bc2016-08-20 00:51:37 +00001509 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1510 pColumns->a[i].zName = 0;
1511 }
1512 }
1513 if( pExpr->op==TK_SELECT ){
drh66860af2016-08-23 18:30:10 +00001514 if( pList && pList->a[iFirst].pExpr ){
1515 assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN );
1516 pList->a[iFirst].pExpr->pRight = pExpr;
drha1251bc2016-08-20 00:51:37 +00001517 pExpr = 0;
1518 }
1519 }
1520
1521vector_append_error:
1522 sqlite3ExprDelete(db, pExpr);
1523 sqlite3IdListDelete(db, pColumns);
1524 return pList;
1525}
1526
1527/*
drhbc622bc2015-08-24 15:39:42 +00001528** Set the sort order for the last element on the given ExprList.
1529*/
1530void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1531 if( p==0 ) return;
1532 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1533 assert( p->nExpr>0 );
1534 if( iSortOrder<0 ){
1535 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1536 return;
1537 }
1538 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001539}
1540
1541/*
drhb7916a72009-05-27 10:31:29 +00001542** Set the ExprList.a[].zName element of the most recently added item
1543** on the expression list.
1544**
1545** pList might be NULL following an OOM error. But pName should never be
1546** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1547** is set.
1548*/
1549void sqlite3ExprListSetName(
1550 Parse *pParse, /* Parsing context */
1551 ExprList *pList, /* List to which to add the span. */
1552 Token *pName, /* Name to be added */
1553 int dequote /* True to cause the name to be dequoted */
1554){
1555 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1556 if( pList ){
1557 struct ExprList_item *pItem;
1558 assert( pList->nExpr>0 );
1559 pItem = &pList->a[pList->nExpr-1];
1560 assert( pItem->zName==0 );
1561 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001562 if( dequote ) sqlite3Dequote(pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001563 }
1564}
1565
1566/*
1567** Set the ExprList.a[].zSpan element of the most recently added item
1568** on the expression list.
1569**
1570** pList might be NULL following an OOM error. But pSpan should never be
1571** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1572** is set.
1573*/
1574void sqlite3ExprListSetSpan(
1575 Parse *pParse, /* Parsing context */
1576 ExprList *pList, /* List to which to add the span. */
1577 ExprSpan *pSpan /* The span to be added */
1578){
1579 sqlite3 *db = pParse->db;
1580 assert( pList!=0 || db->mallocFailed!=0 );
1581 if( pList ){
1582 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1583 assert( pList->nExpr>0 );
1584 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1585 sqlite3DbFree(db, pItem->zSpan);
1586 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001587 (int)(pSpan->zEnd - pSpan->zStart));
drhb7916a72009-05-27 10:31:29 +00001588 }
1589}
1590
1591/*
danielk19777a15a4b2007-05-08 17:54:43 +00001592** If the expression list pEList contains more than iLimit elements,
1593** leave an error message in pParse.
1594*/
1595void sqlite3ExprListCheckLength(
1596 Parse *pParse,
1597 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001598 const char *zObject
1599){
drhb1a6c3c2008-03-20 16:30:17 +00001600 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001601 testcase( pEList && pEList->nExpr==mx );
1602 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001603 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001604 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1605 }
1606}
1607
1608/*
drha76b5df2002-02-23 02:32:10 +00001609** Delete an entire expression list.
1610*/
drhaffa8552016-04-11 18:25:05 +00001611static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drha76b5df2002-02-23 02:32:10 +00001612 int i;
drhbe5c89a2004-07-26 00:31:09 +00001613 struct ExprList_item *pItem;
drhd872bb12012-02-02 01:58:08 +00001614 assert( pList->a!=0 || pList->nExpr==0 );
drhbe5c89a2004-07-26 00:31:09 +00001615 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00001616 sqlite3ExprDelete(db, pItem->pExpr);
1617 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001618 sqlite3DbFree(db, pItem->zSpan);
drha76b5df2002-02-23 02:32:10 +00001619 }
drh633e6d52008-07-28 19:34:53 +00001620 sqlite3DbFree(db, pList->a);
1621 sqlite3DbFree(db, pList);
drha76b5df2002-02-23 02:32:10 +00001622}
drhaffa8552016-04-11 18:25:05 +00001623void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1624 if( pList ) exprListDeleteNN(db, pList);
1625}
drha76b5df2002-02-23 02:32:10 +00001626
1627/*
drh2308ed32015-02-09 16:09:34 +00001628** Return the bitwise-OR of all Expr.flags fields in the given
1629** ExprList.
drh885a5b02015-02-09 15:21:36 +00001630*/
drh2308ed32015-02-09 16:09:34 +00001631u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001632 int i;
drh2308ed32015-02-09 16:09:34 +00001633 u32 m = 0;
1634 if( pList ){
1635 for(i=0; i<pList->nExpr; i++){
drhd0c73052015-04-19 19:21:19 +00001636 Expr *pExpr = pList->a[i].pExpr;
drhde845c22016-03-17 19:07:52 +00001637 assert( pExpr!=0 );
1638 m |= pExpr->flags;
drh2308ed32015-02-09 16:09:34 +00001639 }
drh885a5b02015-02-09 15:21:36 +00001640 }
drh2308ed32015-02-09 16:09:34 +00001641 return m;
drh885a5b02015-02-09 15:21:36 +00001642}
1643
1644/*
drh059b2d52014-10-24 19:28:09 +00001645** These routines are Walker callbacks used to check expressions to
1646** see if they are "constant" for some definition of constant. The
1647** Walker.eCode value determines the type of "constant" we are looking
1648** for.
drh73b211a2005-01-18 04:00:42 +00001649**
drh7d10d5a2008-08-20 16:35:10 +00001650** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001651**
drh059b2d52014-10-24 19:28:09 +00001652** sqlite3ExprIsConstant() pWalker->eCode==1
1653** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001654** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001655** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001656**
drh059b2d52014-10-24 19:28:09 +00001657** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1658** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001659**
drhfeada2d2014-09-24 13:20:22 +00001660** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001661** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1662** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001663** parameter raises an error for new statements, but is silently converted
1664** to NULL for existing schemas. This allows sqlite_master tables that
1665** contain a bound parameter because they were generated by older versions
1666** of SQLite to be parsed by newer versions of SQLite without raising a
1667** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001668*/
drh7d10d5a2008-08-20 16:35:10 +00001669static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001670
drh059b2d52014-10-24 19:28:09 +00001671 /* If pWalker->eCode is 2 then any term of the expression that comes from
1672 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001673 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001674 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1675 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001676 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001677 }
1678
drh626a8792005-01-17 22:08:19 +00001679 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001680 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001681 ** and either pWalker->eCode==4 or 5 or the function has the
1682 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001683 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001684 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001685 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001686 }else{
1687 pWalker->eCode = 0;
1688 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001689 }
drh626a8792005-01-17 22:08:19 +00001690 case TK_ID:
1691 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001692 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001693 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001694 testcase( pExpr->op==TK_ID );
1695 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001696 testcase( pExpr->op==TK_AGG_FUNCTION );
1697 testcase( pExpr->op==TK_AGG_COLUMN );
drh059b2d52014-10-24 19:28:09 +00001698 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1699 return WRC_Continue;
1700 }else{
1701 pWalker->eCode = 0;
1702 return WRC_Abort;
1703 }
drhfeada2d2014-09-24 13:20:22 +00001704 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001705 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001706 /* Silently convert bound parameters that appear inside of CREATE
1707 ** statements into a NULL when parsing the CREATE statement text out
1708 ** of the sqlite_master table */
1709 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001710 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001711 /* A bound parameter in a CREATE statement that originates from
1712 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001713 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001714 return WRC_Abort;
1715 }
1716 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001717 default:
drhb74b1012009-05-28 21:04:37 +00001718 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1719 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
drh7d10d5a2008-08-20 16:35:10 +00001720 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001721 }
1722}
danielk197762c14b32008-11-19 09:05:26 +00001723static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1724 UNUSED_PARAMETER(NotUsed);
drh059b2d52014-10-24 19:28:09 +00001725 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001726 return WRC_Abort;
1727}
drh059b2d52014-10-24 19:28:09 +00001728static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001729 Walker w;
drhaa87f9a2013-04-25 00:57:10 +00001730 memset(&w, 0, sizeof(w));
drh059b2d52014-10-24 19:28:09 +00001731 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001732 w.xExprCallback = exprNodeIsConstant;
1733 w.xSelectCallback = selectNodeIsConstant;
drh059b2d52014-10-24 19:28:09 +00001734 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001735 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001736 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001737}
drh626a8792005-01-17 22:08:19 +00001738
1739/*
drh059b2d52014-10-24 19:28:09 +00001740** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001741** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001742**
1743** For the purposes of this function, a double-quoted string (ex: "abc")
1744** is considered a variable but a single-quoted string (ex: 'abc') is
1745** a constant.
drhfef52082000-06-06 01:50:43 +00001746*/
danielk19774adee202004-05-08 08:23:19 +00001747int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001748 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001749}
1750
1751/*
drh059b2d52014-10-24 19:28:09 +00001752** Walk an expression tree. Return non-zero if the expression is constant
drh0a168372007-06-08 00:20:47 +00001753** that does no originate from the ON or USING clauses of a join.
1754** Return 0 if it involves variables or function calls or terms from
1755** an ON or USING clause.
1756*/
1757int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001758 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001759}
1760
1761/*
drhfcb9f4f2015-06-01 18:13:16 +00001762** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00001763** for any single row of the table with cursor iCur. In other words, the
1764** expression must not refer to any non-deterministic function nor any
1765** table other than iCur.
1766*/
1767int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1768 return exprIsConst(p, 3, iCur);
1769}
1770
1771/*
1772** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001773** or a function call with constant arguments. Return and 0 if there
1774** are any variables.
1775**
1776** For the purposes of this function, a double-quoted string (ex: "abc")
1777** is considered a variable but a single-quoted string (ex: 'abc') is
1778** a constant.
1779*/
drhfeada2d2014-09-24 13:20:22 +00001780int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1781 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00001782 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00001783}
1784
drh5b88bc42013-12-07 23:35:21 +00001785#ifdef SQLITE_ENABLE_CURSOR_HINTS
1786/*
1787** Walk an expression tree. Return 1 if the expression contains a
1788** subquery of some kind. Return 0 if there are no subqueries.
1789*/
1790int sqlite3ExprContainsSubquery(Expr *p){
1791 Walker w;
1792 memset(&w, 0, sizeof(w));
drhbec24762015-08-13 20:07:13 +00001793 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00001794 w.xExprCallback = sqlite3ExprWalkNoop;
1795 w.xSelectCallback = selectNodeIsConstant;
1796 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00001797 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00001798}
1799#endif
1800
drheb55bd22005-06-30 17:04:21 +00001801/*
drh73b211a2005-01-18 04:00:42 +00001802** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001803** to fit in a 32-bit integer, return 1 and put the value of the integer
1804** in *pValue. If the expression is not an integer or if it is too big
1805** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001806*/
danielk19774adee202004-05-08 08:23:19 +00001807int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00001808 int rc = 0;
drhcd92e842011-02-17 15:58:20 +00001809
1810 /* If an expression is an integer literal that fits in a signed 32-bit
1811 ** integer, then the EP_IntValue flag will have already been set */
1812 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1813 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1814
drh92b01d52008-06-24 00:32:35 +00001815 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00001816 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00001817 return 1;
1818 }
drhe4de1fe2002-06-02 16:09:01 +00001819 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00001820 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00001821 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00001822 break;
drh4b59ab52002-08-24 18:24:51 +00001823 }
drhe4de1fe2002-06-02 16:09:01 +00001824 case TK_UMINUS: {
1825 int v;
danielk19774adee202004-05-08 08:23:19 +00001826 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00001827 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00001828 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00001829 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00001830 }
1831 break;
1832 }
1833 default: break;
1834 }
drh92b01d52008-06-24 00:32:35 +00001835 return rc;
drhe4de1fe2002-06-02 16:09:01 +00001836}
1837
1838/*
drh039fc322009-11-17 18:31:47 +00001839** Return FALSE if there is no chance that the expression can be NULL.
1840**
1841** If the expression might be NULL or if the expression is too complex
1842** to tell return TRUE.
1843**
1844** This routine is used as an optimization, to skip OP_IsNull opcodes
1845** when we know that a value cannot be NULL. Hence, a false positive
1846** (returning TRUE when in fact the expression can never be NULL) might
1847** be a small performance hit but is otherwise harmless. On the other
1848** hand, a false negative (returning FALSE when the result could be NULL)
1849** will likely result in an incorrect answer. So when in doubt, return
1850** TRUE.
1851*/
1852int sqlite3ExprCanBeNull(const Expr *p){
1853 u8 op;
drhcd7f4572009-11-19 14:48:40 +00001854 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001855 op = p->op;
1856 if( op==TK_REGISTER ) op = p->op2;
1857 switch( op ){
1858 case TK_INTEGER:
1859 case TK_STRING:
1860 case TK_FLOAT:
1861 case TK_BLOB:
1862 return 0;
drh7248a8b2014-08-04 18:50:54 +00001863 case TK_COLUMN:
1864 assert( p->pTab!=0 );
drh72673a22014-12-04 16:27:17 +00001865 return ExprHasProperty(p, EP_CanBeNull) ||
1866 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00001867 default:
1868 return 1;
1869 }
1870}
1871
1872/*
1873** Return TRUE if the given expression is a constant which would be
1874** unchanged by OP_Affinity with the affinity given in the second
1875** argument.
1876**
1877** This routine is used to determine if the OP_Affinity operation
1878** can be omitted. When in doubt return FALSE. A false negative
1879** is harmless. A false positive, however, can result in the wrong
1880** answer.
1881*/
1882int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1883 u8 op;
drh05883a32015-06-02 15:32:08 +00001884 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00001885 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001886 op = p->op;
1887 if( op==TK_REGISTER ) op = p->op2;
1888 switch( op ){
1889 case TK_INTEGER: {
1890 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1891 }
1892 case TK_FLOAT: {
1893 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1894 }
1895 case TK_STRING: {
1896 return aff==SQLITE_AFF_TEXT;
1897 }
1898 case TK_BLOB: {
1899 return 1;
1900 }
drh2f2855b2009-11-18 01:25:26 +00001901 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00001902 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1903 return p->iColumn<0
1904 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00001905 }
drh039fc322009-11-17 18:31:47 +00001906 default: {
1907 return 0;
1908 }
1909 }
1910}
1911
1912/*
drhc4a3c772001-04-04 11:48:57 +00001913** Return TRUE if the given string is a row-id column name.
1914*/
danielk19774adee202004-05-08 08:23:19 +00001915int sqlite3IsRowid(const char *z){
1916 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1917 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1918 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001919 return 0;
1920}
1921
danielk19779a96b662007-11-29 17:05:18 +00001922/*
drh69c355b2016-03-09 15:34:51 +00001923** pX is the RHS of an IN operator. If pX is a SELECT statement
1924** that can be simplified to a direct table access, then return
1925** a pointer to the SELECT statement. If pX is not a SELECT statement,
1926** or if the SELECT statement needs to be manifested into a transient
1927** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00001928*/
1929#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00001930static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00001931 Select *p;
drhb287f4b2008-04-25 00:08:38 +00001932 SrcList *pSrc;
1933 ExprList *pEList;
1934 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00001935 int i;
drh69c355b2016-03-09 15:34:51 +00001936 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1937 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1938 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00001939 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00001940 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00001941 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1942 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1943 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00001944 }
drhb74b1012009-05-28 21:04:37 +00001945 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00001946 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb74b1012009-05-28 21:04:37 +00001947 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
drhb287f4b2008-04-25 00:08:38 +00001948 if( p->pWhere ) return 0; /* Has no WHERE clause */
1949 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00001950 assert( pSrc!=0 );
1951 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00001952 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00001953 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00001954 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00001955 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00001956 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1957 pEList = p->pEList;
drhac6b47d2016-08-24 00:51:48 +00001958 assert( pEList!=0 );
dancfbb5e82016-07-13 19:48:13 +00001959
dan7b35a772016-07-28 19:47:15 +00001960 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00001961 for(i=0; i<pEList->nExpr; i++){
1962 Expr *pRes = pEList->a[i].pExpr;
1963 if( pRes->op!=TK_COLUMN ) return 0;
1964 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00001965 }
drh69c355b2016-03-09 15:34:51 +00001966 return p;
drhb287f4b2008-04-25 00:08:38 +00001967}
1968#endif /* SQLITE_OMIT_SUBQUERY */
1969
1970/*
dan1d8cb212011-12-09 13:24:16 +00001971** Code an OP_Once instruction and allocate space for its flag. Return the
1972** address of the new instruction.
1973*/
1974int sqlite3CodeOnce(Parse *pParse){
1975 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1976 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1977}
1978
danf9b2e052016-08-02 17:45:00 +00001979#ifndef SQLITE_OMIT_SUBQUERY
dan1d8cb212011-12-09 13:24:16 +00001980/*
drh4c259e92014-08-01 21:12:35 +00001981** Generate code that checks the left-most column of index table iCur to see if
1982** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00001983** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1984** to be set to NULL if iCur contains one or more NULL values.
1985*/
1986static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00001987 int addr1;
drh6be515e2014-08-01 21:00:53 +00001988 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00001989 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00001990 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
1991 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00001992 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00001993 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00001994}
danf9b2e052016-08-02 17:45:00 +00001995#endif
drh6be515e2014-08-01 21:00:53 +00001996
drhbb53ecb2014-08-02 21:03:33 +00001997
1998#ifndef SQLITE_OMIT_SUBQUERY
1999/*
2000** The argument is an IN operator with a list (not a subquery) on the
2001** right-hand side. Return TRUE if that list is constant.
2002*/
2003static int sqlite3InRhsIsConstant(Expr *pIn){
2004 Expr *pLHS;
2005 int res;
2006 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2007 pLHS = pIn->pLeft;
2008 pIn->pLeft = 0;
2009 res = sqlite3ExprIsConstant(pIn);
2010 pIn->pLeft = pLHS;
2011 return res;
2012}
2013#endif
2014
drh6be515e2014-08-01 21:00:53 +00002015/*
danielk19779a96b662007-11-29 17:05:18 +00002016** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00002017** The pX parameter is the expression on the RHS of the IN operator, which
2018** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00002019**
drhd4305ca2012-09-18 17:08:33 +00002020** The job of this routine is to find or create a b-tree object that can
2021** be used either to test for membership in the RHS set or to iterate through
2022** all members of the RHS set, skipping duplicates.
2023**
drh3a856252014-08-01 14:46:57 +00002024** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00002025** and pX->iTable is set to the index of that cursor.
2026**
drhb74b1012009-05-28 21:04:37 +00002027** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00002028**
drh1ccce442013-03-12 20:38:51 +00002029** IN_INDEX_ROWID - The cursor was opened on a database table.
2030** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2031** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2032** IN_INDEX_EPH - The cursor was opened on a specially created and
2033** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00002034** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2035** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00002036**
drhd4305ca2012-09-18 17:08:33 +00002037** An existing b-tree might be used if the RHS expression pX is a simple
2038** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00002039**
dan553168c2016-08-01 20:14:31 +00002040** SELECT <column1>, <column2>... FROM <table>
danielk19779a96b662007-11-29 17:05:18 +00002041**
drhd4305ca2012-09-18 17:08:33 +00002042** If the RHS of the IN operator is a list or a more complex subquery, then
2043** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00002044** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00002045** existing table.
drhd4305ca2012-09-18 17:08:33 +00002046**
drh3a856252014-08-01 14:46:57 +00002047** The inFlags parameter must contain exactly one of the bits
2048** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
2049** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
2050** fast membership test. When the IN_INDEX_LOOP bit is set, the
2051** IN index will be used to loop over all values of the RHS of the
2052** IN operator.
2053**
2054** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2055** through the set members) then the b-tree must not contain duplicates.
dan553168c2016-08-01 20:14:31 +00002056** An epheremal table must be used unless the selected columns are guaranteed
2057** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2058** a UNIQUE constraint or index.
danielk19770cdc0222008-06-26 18:04:03 +00002059**
drh3a856252014-08-01 14:46:57 +00002060** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2061** for fast set membership tests) then an epheremal table must
dan553168c2016-08-01 20:14:31 +00002062** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2063** index can be found with the specified <columns> as its left-most.
danielk19770cdc0222008-06-26 18:04:03 +00002064**
drhbb53ecb2014-08-02 21:03:33 +00002065** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2066** if the RHS of the IN operator is a list (not a subquery) then this
2067** routine might decide that creating an ephemeral b-tree for membership
2068** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2069** calling routine should implement the IN operator using a sequence
2070** of Eq or Ne comparison operations.
2071**
drhb74b1012009-05-28 21:04:37 +00002072** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00002073** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00002074** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00002075** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00002076** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00002077** to *prRhsHasNull. If there is no chance that the (...) contains a
2078** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00002079**
drhe21a6e12014-08-01 18:00:24 +00002080** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00002081** the value in that register will be NULL if the b-tree contains one or more
2082** NULL values, and it will be some non-NULL value if the b-tree contains no
2083** NULL values.
dan553168c2016-08-01 20:14:31 +00002084**
2085** If the aiMap parameter is not NULL, it must point to an array containing
2086** one element for each column returned by the SELECT statement on the RHS
2087** of the IN(...) operator. The i'th entry of the array is populated with the
2088** offset of the index column that matches the i'th column returned by the
2089** SELECT. For example, if the expression and selected index are:
2090**
2091** (?,?,?) IN (SELECT a, b, c FROM t1)
2092** CREATE INDEX i1 ON t1(b, c, a);
2093**
2094** then aiMap[] is populated with {2, 0, 1}.
danielk19779a96b662007-11-29 17:05:18 +00002095*/
danielk1977284f4ac2007-12-10 05:03:46 +00002096#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00002097int sqlite3FindInIndex(
2098 Parse *pParse,
2099 Expr *pX,
2100 u32 inFlags,
2101 int *prRhsHasNull,
2102 int *aiMap
2103){
drhb74b1012009-05-28 21:04:37 +00002104 Select *p; /* SELECT to the right of IN operator */
2105 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2106 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00002107 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00002108 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00002109
drh1450bc62009-10-30 13:25:56 +00002110 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00002111 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00002112
dan7b35a772016-07-28 19:47:15 +00002113 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2114 ** whether or not the SELECT result contains NULL values, check whether
dan870a0702016-08-01 16:37:43 +00002115 ** or not NULL is actually possible (it may not be, for example, due
dan7b35a772016-07-28 19:47:15 +00002116 ** to NOT NULL constraints in the schema). If no NULL values are possible,
dan870a0702016-08-01 16:37:43 +00002117 ** set prRhsHasNull to 0 before continuing. */
dan7b35a772016-07-28 19:47:15 +00002118 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2119 int i;
2120 ExprList *pEList = pX->x.pSelect->pEList;
2121 for(i=0; i<pEList->nExpr; i++){
2122 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2123 }
2124 if( i==pEList->nExpr ){
2125 prRhsHasNull = 0;
2126 }
2127 }
2128
drhb74b1012009-05-28 21:04:37 +00002129 /* Check to see if an existing table or index can be used to
2130 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00002131 ** ephemeral table. */
2132 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00002133 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00002134 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00002135 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00002136 ExprList *pEList = p->pEList;
2137 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00002138
drhb07028f2011-10-14 21:49:18 +00002139 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2140 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2141 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2142 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00002143
drhb22f7c82014-02-06 23:56:27 +00002144 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00002145 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2146 sqlite3CodeVerifySchema(pParse, iDb);
2147 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00002148
2149 /* This function is only called from two places. In both cases the vdbe
2150 ** has already been allocated. So assume sqlite3GetVdbe() is always
2151 ** successful here.
2152 */
2153 assert(v);
dancfbb5e82016-07-13 19:48:13 +00002154 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh62659b22016-08-24 18:51:23 +00002155 /* The "x IN (SELECT rowid FROM table)" case */
drh7d176102014-02-18 03:07:12 +00002156 int iAddr = sqlite3CodeOnce(pParse);
2157 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002158
2159 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2160 eType = IN_INDEX_ROWID;
2161
2162 sqlite3VdbeJumpHere(v, iAddr);
2163 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002164 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002165 int affinity_ok = 1;
2166 int i;
2167
2168 /* Check that the affinity that will be used to perform each
drh62659b22016-08-24 18:51:23 +00002169 ** comparison is the same as the affinity of each column in table
2170 ** on the RHS of the IN operator. If it not, it is not possible to
2171 ** use any index of the RHS table. */
dancfbb5e82016-07-13 19:48:13 +00002172 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002173 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002174 int iCol = pEList->a[i].pExpr->iColumn;
drh62659b22016-08-24 18:51:23 +00002175 char idxaff = pTab->aCol[iCol].affinity; /* RHS table affinity */
dancfbb5e82016-07-13 19:48:13 +00002176 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
drh62659b22016-08-24 18:51:23 +00002177 testcase( cmpaff==SQLITE_AFF_BLOB );
2178 testcase( cmpaff==SQLITE_AFF_TEXT );
dancfbb5e82016-07-13 19:48:13 +00002179 switch( cmpaff ){
2180 case SQLITE_AFF_BLOB:
2181 break;
2182 case SQLITE_AFF_TEXT:
drh62659b22016-08-24 18:51:23 +00002183 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2184 ** other has no affinity and the other side is TEXT. Hence,
2185 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2186 ** and for the term on the LHS of the IN to have no affinity. */
2187 assert( idxaff==SQLITE_AFF_TEXT );
dancfbb5e82016-07-13 19:48:13 +00002188 break;
2189 default:
2190 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2191 }
2192 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002193
drhb74b1012009-05-28 21:04:37 +00002194 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00002195 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00002196 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00002197
2198 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
dancfbb5e82016-07-13 19:48:13 +00002199 if( pIdx->nKeyCol<nExpr ) continue;
2200 if( mustBeUnique && (pIdx->nKeyCol!=nExpr || !IsUniqueIndex(pIdx)) ){
2201 continue;
2202 }
2203
2204 for(i=0; i<nExpr; i++){
drhfc7f27b2016-08-20 00:07:01 +00002205 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002206 Expr *pRhs = pEList->a[i].pExpr;
2207 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2208 int j;
2209
dan17994e32016-08-11 12:01:52 +00002210 assert( pReq || pParse->nErr );
2211 if( pReq==0 ) break;
2212
dancfbb5e82016-07-13 19:48:13 +00002213 for(j=0; j<nExpr; j++){
2214 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2215 assert( pIdx->azColl[j] );
2216 if( sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ) continue;
2217 break;
2218 }
2219 if( j==nExpr ) break;
danba00e302016-07-23 20:24:06 +00002220 if( aiMap ) aiMap[i] = j;
dancfbb5e82016-07-13 19:48:13 +00002221 }
2222
2223 if( i==nExpr ){
drh7d176102014-02-18 03:07:12 +00002224 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00002225 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2226 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00002227 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00002228 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2229 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00002230
dan7b35a772016-07-28 19:47:15 +00002231 if( prRhsHasNull ){
2232 *prRhsHasNull = ++pParse->nMem;
dan3480bfd2016-06-16 17:14:02 +00002233#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
dancfbb5e82016-07-13 19:48:13 +00002234 i64 mask = (1<<nExpr)-1;
dan3480bfd2016-06-16 17:14:02 +00002235 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
dancfbb5e82016-07-13 19:48:13 +00002236 iTab, 0, 0, (u8*)&mask, P4_INT64);
dan3480bfd2016-06-16 17:14:02 +00002237#endif
dan7b35a772016-07-28 19:47:15 +00002238 if( nExpr==1 ){
2239 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2240 }
danielk19770cdc0222008-06-26 18:04:03 +00002241 }
drh552fd452014-02-18 01:07:38 +00002242 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00002243 }
2244 }
2245 }
2246 }
2247
drhbb53ecb2014-08-02 21:03:33 +00002248 /* If no preexisting index is available for the IN clause
2249 ** and IN_INDEX_NOOP is an allowed reply
2250 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002251 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002252 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002253 ** the IN operator so return IN_INDEX_NOOP.
2254 */
2255 if( eType==0
2256 && (inFlags & IN_INDEX_NOOP_OK)
2257 && !ExprHasProperty(pX, EP_xIsSelect)
2258 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2259 ){
2260 eType = IN_INDEX_NOOP;
2261 }
drhbb53ecb2014-08-02 21:03:33 +00002262
danielk19779a96b662007-11-29 17:05:18 +00002263 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002264 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002265 ** We will have to generate an ephemeral table to do the job.
2266 */
drh8e23daf2013-06-11 13:30:04 +00002267 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002268 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002269 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002270 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002271 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00002272 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00002273 eType = IN_INDEX_ROWID;
2274 }
drhe21a6e12014-08-01 18:00:24 +00002275 }else if( prRhsHasNull ){
2276 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002277 }
danielk197741a05b72008-10-02 13:50:55 +00002278 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002279 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002280 }else{
2281 pX->iTable = iTab;
2282 }
danba00e302016-07-23 20:24:06 +00002283
2284 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2285 int i, n;
2286 n = sqlite3ExprVectorSize(pX->pLeft);
2287 for(i=0; i<n; i++) aiMap[i] = i;
2288 }
danielk19779a96b662007-11-29 17:05:18 +00002289 return eType;
2290}
danielk1977284f4ac2007-12-10 05:03:46 +00002291#endif
drh626a8792005-01-17 22:08:19 +00002292
danf9b2e052016-08-02 17:45:00 +00002293#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002294/*
2295** Argument pExpr is an (?, ?...) IN(...) expression. This
2296** function allocates and returns a nul-terminated string containing
2297** the affinities to be used for each column of the comparison.
2298**
2299** It is the responsibility of the caller to ensure that the returned
2300** string is eventually freed using sqlite3DbFree().
2301*/
dan71c57db2016-07-09 20:23:55 +00002302static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2303 Expr *pLeft = pExpr->pLeft;
2304 int nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002305 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002306 char *zRet;
2307
dan553168c2016-08-01 20:14:31 +00002308 assert( pExpr->op==TK_IN );
dan71c57db2016-07-09 20:23:55 +00002309 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2310 if( zRet ){
2311 int i;
2312 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002313 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002314 char a = sqlite3ExprAffinity(pA);
2315 if( pSelect ){
2316 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2317 }else{
2318 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002319 }
dan71c57db2016-07-09 20:23:55 +00002320 }
2321 zRet[nVal] = '\0';
2322 }
2323 return zRet;
2324}
danf9b2e052016-08-02 17:45:00 +00002325#endif
dan71c57db2016-07-09 20:23:55 +00002326
dan8da209b2016-07-26 18:06:08 +00002327#ifndef SQLITE_OMIT_SUBQUERY
2328/*
2329** Load the Parse object passed as the first argument with an error
2330** message of the form:
2331**
2332** "sub-select returns N columns - expected M"
2333*/
2334void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2335 const char *zFmt = "sub-select returns %d columns - expected %d";
2336 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2337}
2338#endif
2339
drh626a8792005-01-17 22:08:19 +00002340/*
drhd4187c72010-08-30 22:15:45 +00002341** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2342** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002343**
drh9cbe6352005-11-29 03:13:21 +00002344** (SELECT a FROM b) -- subquery
2345** EXISTS (SELECT a FROM b) -- EXISTS subquery
2346** x IN (4,5,11) -- IN operator with list on right-hand side
2347** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002348**
drh9cbe6352005-11-29 03:13:21 +00002349** The pExpr parameter describes the expression that contains the IN
2350** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002351**
2352** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2353** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2354** to some integer key column of a table B-Tree. In this case, use an
2355** intkey B-Tree to store the set of IN(...) values instead of the usual
2356** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002357**
2358** If rMayHaveNull is non-zero, that means that the operation is an IN
2359** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002360** All this routine does is initialize the register given by rMayHaveNull
2361** to NULL. Calling routines will take care of changing this register
2362** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002363**
2364** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002365** result. For a multi-column SELECT, the result is stored in a contiguous
2366** array of registers and the return value is the register of the left-most
2367** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002368*/
drh51522cd2005-01-20 13:36:19 +00002369#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002370int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002371 Parse *pParse, /* Parsing context */
2372 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002373 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002374 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002375){
drh6be515e2014-08-01 21:00:53 +00002376 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002377 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002378 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002379 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00002380 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002381
drh39a11812016-08-19 19:12:58 +00002382 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2383 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002384 **
2385 ** * The right-hand side is a correlated subquery
2386 ** * The right-hand side is an expression list containing variables
2387 ** * We are inside a trigger
2388 **
2389 ** If all of the above are false, then we can run this code just once
2390 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002391 */
drhc5cd1242013-09-12 16:50:49 +00002392 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00002393 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002394 }
2395
dan4a07e3d2010-11-09 14:48:59 +00002396#ifndef SQLITE_OMIT_EXPLAIN
2397 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00002398 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2399 jmpIfDynamic>=0?"":"CORRELATED ",
2400 pExpr->op==TK_IN?"LIST":"SCALAR",
2401 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00002402 );
2403 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2404 }
2405#endif
2406
drhcce7d172000-05-31 15:34:51 +00002407 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002408 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002409 int addr; /* Address of OP_OpenEphemeral instruction */
2410 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002411 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002412 int nVal; /* Size of vector pLeft */
2413
2414 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002415 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002416
2417 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002418 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002419 ** filled with index keys representing the results from the
2420 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002421 **
2422 ** If the 'x' expression is a column value, or the SELECT...
2423 ** statement returns a column value, then the affinity of that
2424 ** column is used to build the index keys. If both 'x' and the
2425 ** SELECT... statement are columns, then numeric affinity is used
2426 ** if either column has NUMERIC or INTEGER affinity. If neither
2427 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2428 ** is used.
2429 */
2430 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002431 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2432 pExpr->iTable, (isRowid?0:nVal));
2433 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002434
danielk19776ab3a2e2009-02-19 14:39:25 +00002435 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00002436 /* Case 1: expr IN (SELECT ...)
2437 **
danielk1977e014a832004-05-17 10:48:57 +00002438 ** Generate code to write the results of the select into the temporary
2439 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002440 */
drh43870062014-07-31 15:44:44 +00002441 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002442 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002443
danielk197741a05b72008-10-02 13:50:55 +00002444 assert( !isRowid );
dan71c57db2016-07-09 20:23:55 +00002445 if( pEList->nExpr!=nVal ){
dan8da209b2016-07-26 18:06:08 +00002446 sqlite3SubselectError(pParse, pEList->nExpr, nVal);
dan71c57db2016-07-09 20:23:55 +00002447 }else{
2448 SelectDest dest;
2449 int i;
2450 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2451 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2452 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2453 pSelect->iLimit = 0;
2454 testcase( pSelect->selFlags & SF_Distinct );
2455 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2456 if( sqlite3Select(pParse, pSelect, &dest) ){
2457 sqlite3DbFree(pParse->db, dest.zAffSdst);
2458 sqlite3KeyInfoUnref(pKeyInfo);
2459 return 0;
2460 }
2461 sqlite3DbFree(pParse->db, dest.zAffSdst);
2462 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2463 assert( pEList!=0 );
2464 assert( pEList->nExpr>0 );
2465 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2466 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002467 Expr *p = (nVal>1) ? sqlite3VectorFieldSubexpr(pLeft, i) : pLeft;
dan71c57db2016-07-09 20:23:55 +00002468 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2469 pParse, p, pEList->a[i].pExpr
2470 );
2471 }
drh94ccde52007-04-13 16:06:32 +00002472 }
drha7d2db12010-07-14 20:23:52 +00002473 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002474 /* Case 2: expr IN (exprlist)
2475 **
drhfd131da2007-08-07 17:13:03 +00002476 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002477 ** store it in the temporary table. If <expr> is a column, then use
2478 ** that columns affinity when building index keys. If <expr> is not
2479 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002480 */
dan71c57db2016-07-09 20:23:55 +00002481 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002482 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002483 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002484 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002485 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002486
dan71c57db2016-07-09 20:23:55 +00002487 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002488 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002489 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002490 }
drh323df792013-08-05 19:11:29 +00002491 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002492 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002493 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2494 }
danielk1977e014a832004-05-17 10:48:57 +00002495
2496 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002497 r1 = sqlite3GetTempReg(pParse);
2498 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002499 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002500 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2501 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002502 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002503
drh57dbd7b2005-07-08 18:25:26 +00002504 /* If the expression is not constant then we will need to
2505 ** disable the test that was generated above that makes sure
2506 ** this code only executes once. Because for a non-constant
2507 ** expression we need to rerun this code each time.
2508 */
drh6be515e2014-08-01 21:00:53 +00002509 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2510 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2511 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002512 }
danielk1977e014a832004-05-17 10:48:57 +00002513
2514 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002515 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2516 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002517 }else{
drhe05c9292009-10-29 13:48:10 +00002518 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2519 if( isRowid ){
2520 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2521 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002522 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002523 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2524 }else{
2525 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2526 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2527 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2528 }
danielk197741a05b72008-10-02 13:50:55 +00002529 }
drhfef52082000-06-06 01:50:43 +00002530 }
drh2d401ab2008-01-10 23:50:11 +00002531 sqlite3ReleaseTempReg(pParse, r1);
2532 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002533 }
drh323df792013-08-05 19:11:29 +00002534 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002535 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002536 }
danielk1977b3bce662005-01-29 08:32:43 +00002537 break;
drhfef52082000-06-06 01:50:43 +00002538 }
2539
drh51522cd2005-01-20 13:36:19 +00002540 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002541 case TK_SELECT:
2542 default: {
drh39a11812016-08-19 19:12:58 +00002543 /* Case 3: (SELECT ... FROM ...)
2544 ** or: EXISTS(SELECT ... FROM ...)
2545 **
2546 ** For a SELECT, generate code to put the values for all columns of
2547 ** the first row into an array of registers and return the index of
2548 ** the first register.
2549 **
2550 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2551 ** into a register and return that register number.
2552 **
2553 ** In both cases, the query is augmented with "LIMIT 1". Any
2554 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002555 */
drhfd773cf2009-05-29 14:39:07 +00002556 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002557 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002558 int nReg; /* Registers to allocate */
drh1398ad32005-01-19 23:24:50 +00002559
shanecf697392009-06-01 16:53:09 +00002560 testcase( pExpr->op==TK_EXISTS );
2561 testcase( pExpr->op==TK_SELECT );
2562 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
danielk19776ab3a2e2009-02-19 14:39:25 +00002563 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
dan71c57db2016-07-09 20:23:55 +00002564
danielk19776ab3a2e2009-02-19 14:39:25 +00002565 pSel = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002566 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2567 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2568 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002569 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002570 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002571 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002572 dest.nSdst = nReg;
2573 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002574 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002575 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002576 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002577 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002578 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002579 }
drh633e6d52008-07-28 19:34:53 +00002580 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002581 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2582 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002583 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002584 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002585 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002586 return 0;
drh94ccde52007-04-13 16:06:32 +00002587 }
drh2b596da2012-07-23 21:43:19 +00002588 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002589 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002590 break;
drhcce7d172000-05-31 15:34:51 +00002591 }
2592 }
danielk1977b3bce662005-01-29 08:32:43 +00002593
drh6be515e2014-08-01 21:00:53 +00002594 if( rHasNullFlag ){
2595 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002596 }
drh6be515e2014-08-01 21:00:53 +00002597
2598 if( jmpIfDynamic>=0 ){
2599 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002600 }
drhd2490902014-04-13 19:28:15 +00002601 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002602
drh1450bc62009-10-30 13:25:56 +00002603 return rReg;
drhcce7d172000-05-31 15:34:51 +00002604}
drh51522cd2005-01-20 13:36:19 +00002605#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002606
drhe3365e62009-11-12 17:52:24 +00002607#ifndef SQLITE_OMIT_SUBQUERY
2608/*
dan7b35a772016-07-28 19:47:15 +00002609** Expr pIn is an IN(...) expression. This function checks that the
2610** sub-select on the RHS of the IN() operator has the same number of
2611** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2612** a sub-query, that the LHS is a vector of size 1.
2613*/
2614int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2615 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2616 if( (pIn->flags & EP_xIsSelect) ){
2617 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2618 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2619 return 1;
2620 }
2621 }else if( nVector!=1 ){
2622 if( (pIn->pLeft->flags & EP_xIsSelect) ){
2623 sqlite3SubselectError(pParse, nVector, 1);
2624 }else{
drhe835bc12016-08-23 19:02:55 +00002625 sqlite3ErrorMsg(pParse, "row value misused");
dan7b35a772016-07-28 19:47:15 +00002626 }
2627 return 1;
2628 }
2629 return 0;
2630}
2631#endif
2632
2633#ifndef SQLITE_OMIT_SUBQUERY
2634/*
drhe3365e62009-11-12 17:52:24 +00002635** Generate code for an IN expression.
2636**
2637** x IN (SELECT ...)
2638** x IN (value, value, ...)
2639**
drhecb87ac2016-08-25 15:46:25 +00002640** The left-hand side (LHS) is a scalar or vector expression. The
2641** right-hand side (RHS) is an array of zero or more values. The IN operator
2642** is true if the LHS is contained within the RHS. The result is false
2643** if the LHS is definitely not in the RHS. The result is NULL if the presence
2644** of the LHS in the RHS cannot be determined due to NULLs.
drhe3365e62009-11-12 17:52:24 +00002645**
drh6be515e2014-08-01 21:00:53 +00002646** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002647** contained within the RHS. If due to NULLs we cannot determine if the LHS
2648** is contained in the RHS then jump to destIfNull. If the LHS is contained
2649** within the RHS then fall through.
drhecb87ac2016-08-25 15:46:25 +00002650**
2651** See the separate in-operator.md documentation file in the canonical
2652** SQLite source tree for additional information.
drhe3365e62009-11-12 17:52:24 +00002653*/
2654static void sqlite3ExprCodeIN(
2655 Parse *pParse, /* Parsing and code generating context */
2656 Expr *pExpr, /* The IN expression */
2657 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2658 int destIfNull /* Jump here if the results are unknown due to NULLs */
2659){
2660 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002661 int eType; /* Type of the RHS */
drh12abf402016-08-22 14:30:05 +00002662 int r1, r2; /* Temporary use registers */
drhe3365e62009-11-12 17:52:24 +00002663 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002664 int *aiMap = 0; /* Map from vector field to index column */
2665 char *zAff = 0; /* Affinity string for comparisons */
drhecb87ac2016-08-25 15:46:25 +00002666 int nVector; /* Size of vectors for this IN operator */
2667 int iDummy; /* Dummy parameter to exprCodeVector() */
2668 Expr *pLeft = pExpr->pLeft; /* The LHS of the IN operator */
2669 int i; /* loop counter */
drhe3365e62009-11-12 17:52:24 +00002670
dan7b35a772016-07-28 19:47:15 +00002671 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00002672 zAff = exprINAffinity(pParse, pExpr);
danba00e302016-07-23 20:24:06 +00002673 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2674 aiMap = (int*)sqlite3DbMallocZero(
2675 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2676 );
drhecb87ac2016-08-25 15:46:25 +00002677 if( pParse->db->mallocFailed ) goto end_code_IN_op;
dan7b35a772016-07-28 19:47:15 +00002678
danba00e302016-07-23 20:24:06 +00002679 /* Attempt to compute the RHS. After this step, if anything other than
2680 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2681 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2682 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00002683 v = pParse->pVdbe;
2684 assert( v!=0 ); /* OOM detected prior to this routine */
2685 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002686 eType = sqlite3FindInIndex(pParse, pExpr,
2687 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00002688 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00002689
danba00e302016-07-23 20:24:06 +00002690 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2691 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2692 );
drhecb87ac2016-08-25 15:46:25 +00002693#ifdef SQLITE_DEBUG
2694 /* Confirm that aiMap[] contains nVector integer values between 0 and
2695 ** nVector-1. */
2696 for(i=0; i<nVector; i++){
2697 int j, cnt;
2698 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
2699 assert( cnt==1 );
2700 }
2701#endif
drhe3365e62009-11-12 17:52:24 +00002702
danba00e302016-07-23 20:24:06 +00002703 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2704 ** vector, then it is stored in an array of nVector registers starting
2705 ** at r1.
drhe3365e62009-11-12 17:52:24 +00002706 */
2707 sqlite3ExprCachePush(pParse);
drh12abf402016-08-22 14:30:05 +00002708 r2 = exprCodeVector(pParse, pLeft, &iDummy);
drhecb87ac2016-08-25 15:46:25 +00002709 for(i=0; i<nVector && aiMap[i]==i; i++){}
2710 if( i==nVector ){
2711 /* LHS fields are already in the correct order */
2712 r1 = r2;
2713 }else{
2714 /* Need to reorder the LHS fields according to aiMap */
2715 r1 = sqlite3GetTempRange(pParse, nVector);
2716 for(i=0; i<nVector; i++){
2717 sqlite3VdbeAddOp3(v, OP_Copy, r2+i, r1+aiMap[i], 0);
2718 }
danba00e302016-07-23 20:24:06 +00002719 }
drhe3365e62009-11-12 17:52:24 +00002720
drhbb53ecb2014-08-02 21:03:33 +00002721 /* If sqlite3FindInIndex() did not find or create an index that is
2722 ** suitable for evaluating the IN operator, then evaluate using a
2723 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002724 */
drhbb53ecb2014-08-02 21:03:33 +00002725 if( eType==IN_INDEX_NOOP ){
2726 ExprList *pList = pExpr->x.pList;
2727 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2728 int labelOk = sqlite3VdbeMakeLabel(v);
2729 int r2, regToFree;
2730 int regCkNull = 0;
2731 int ii;
2732 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002733 if( destIfNull!=destIfFalse ){
2734 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002735 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002736 }
2737 for(ii=0; ii<pList->nExpr; ii++){
2738 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002739 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002740 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2741 }
2742 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2743 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002744 (void*)pColl, P4_COLLSEQ);
2745 VdbeCoverageIf(v, ii<pList->nExpr-1);
2746 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00002747 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00002748 }else{
2749 assert( destIfNull==destIfFalse );
2750 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2751 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00002752 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00002753 }
2754 sqlite3ReleaseTempReg(pParse, regToFree);
2755 }
2756 if( regCkNull ){
2757 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002758 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002759 }
2760 sqlite3VdbeResolveLabel(v, labelOk);
2761 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002762 }else{
drhbb53ecb2014-08-02 21:03:33 +00002763
dan7b35a772016-07-28 19:47:15 +00002764 /* If any value on the LHS is NULL, the result of the IN(...) operator
2765 ** must be either false or NULL. If these two are handled identically,
2766 ** test the LHS for NULLs and jump directly to destIfNull if any are
2767 ** found.
2768 **
2769 ** Otherwise, if NULL and false are handled differently, and the
2770 ** IN(...) operation is not a vector operation, and the LHS of the
2771 ** operator is NULL, then the result is false if the index is
2772 ** completely empty, or NULL otherwise. */
dand49fd4e2016-07-27 19:33:04 +00002773 if( destIfNull==destIfFalse ){
2774 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002775 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dand49fd4e2016-07-27 19:33:04 +00002776 if( sqlite3ExprCanBeNull(p) ){
2777 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002778 VdbeCoverage(v);
dand49fd4e2016-07-27 19:33:04 +00002779 }
drh7248a8b2014-08-04 18:50:54 +00002780 }
dand49fd4e2016-07-27 19:33:04 +00002781 }else if( nVector==1 && sqlite3ExprCanBeNull(pExpr->pLeft) ){
2782 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2783 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2784 VdbeCoverage(v);
2785 sqlite3VdbeGoto(v, destIfNull);
2786 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002787 }
2788
2789 if( eType==IN_INDEX_ROWID ){
dan7b35a772016-07-28 19:47:15 +00002790 /* In this case, the RHS is the ROWID of table b-tree */
drheeb95652016-05-26 20:56:38 +00002791 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002792 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002793 }else{
dan7b35a772016-07-28 19:47:15 +00002794 /* In this case, the RHS is an index b-tree. Apply the comparison
2795 ** affinities to each value on the LHS of the operator. */
danba00e302016-07-23 20:24:06 +00002796 sqlite3VdbeAddOp4(v, OP_Affinity, r1, nVector, 0, zAff, nVector);
dan7b35a772016-07-28 19:47:15 +00002797
2798 if( nVector>1 && destIfNull!=destIfFalse ){
2799 int iIdx = pExpr->iTable;
drh18016ad2016-08-24 21:54:47 +00002800 int addrTop;
dan7b35a772016-07-28 19:47:15 +00002801 int addrNext;
drh18016ad2016-08-24 21:54:47 +00002802 int addrFound;
dan7b35a772016-07-28 19:47:15 +00002803
2804 /* Search the index for the key. */
drh18016ad2016-08-24 21:54:47 +00002805 addrFound = sqlite3VdbeAddOp4Int(v, OP_Found, iIdx, 0, r1, nVector);
drh471b4b92016-08-12 11:25:49 +00002806 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002807
2808 /* At this point the specified key is not present in the index,
2809 ** so the result of the IN(..) operator must be either NULL or
2810 ** 0. The vdbe code generated below figures out which. */
drh18016ad2016-08-24 21:54:47 +00002811 addrTop = 1+sqlite3VdbeAddOp2(v, OP_Rewind, iIdx, destIfFalse);
drh471b4b92016-08-12 11:25:49 +00002812 VdbeCoverage(v);
drh18016ad2016-08-24 21:54:47 +00002813 addrNext = sqlite3VdbeMakeLabel(v);
dan7b35a772016-07-28 19:47:15 +00002814
2815 for(i=0; i<nVector; i++){
2816 Expr *p;
2817 CollSeq *pColl;
2818 int r2 = sqlite3GetTempReg(pParse);
drhfc7f27b2016-08-20 00:07:01 +00002819 p = sqlite3VectorFieldSubexpr(pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002820 pColl = sqlite3ExprCollSeq(pParse, p);
2821
2822 sqlite3VdbeAddOp3(v, OP_Column, iIdx, i, r2);
drh18016ad2016-08-24 21:54:47 +00002823 sqlite3VdbeAddOp4(v, OP_Ne, r1+i, addrNext, r2,
2824 (void*)pColl, P4_COLLSEQ);
drh471b4b92016-08-12 11:25:49 +00002825 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002826 sqlite3ReleaseTempReg(pParse, r2);
2827 }
2828 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
drh18016ad2016-08-24 21:54:47 +00002829 sqlite3VdbeResolveLabel(v, addrNext);
2830 sqlite3VdbeAddOp2(v, OP_Next, iIdx, addrTop);
2831 VdbeCoverage(v);
2832 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
dan7b35a772016-07-28 19:47:15 +00002833
2834 /* The key was found in the index. If it contains any NULL values,
2835 ** then the result of the IN(...) operator is NULL. Otherwise, the
2836 ** result is 1. */
drh18016ad2016-08-24 21:54:47 +00002837 sqlite3VdbeJumpHere(v, addrFound);
dan7b35a772016-07-28 19:47:15 +00002838 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002839 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002840 if( sqlite3ExprCanBeNull(p) ){
2841 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002842 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002843 }
2844 }
2845
2846 }else if( rRhsHasNull==0 ){
drhbb53ecb2014-08-02 21:03:33 +00002847 /* This branch runs if it is known at compile time that the RHS
dan7b35a772016-07-28 19:47:15 +00002848 ** cannot contain NULL values. This happens as a result
2849 ** of "NOT NULL" constraints in the database schema.
drhbb53ecb2014-08-02 21:03:33 +00002850 **
2851 ** Also run this branch if NULL is equivalent to FALSE
dan7b35a772016-07-28 19:47:15 +00002852 ** for this particular IN operator. */
danba00e302016-07-23 20:24:06 +00002853 sqlite3VdbeAddOp4Int(
2854 v, OP_NotFound, pExpr->iTable, destIfFalse, r1, nVector
2855 );
drhbb53ecb2014-08-02 21:03:33 +00002856 VdbeCoverage(v);
2857 }else{
2858 /* In this branch, the RHS of the IN might contain a NULL and
2859 ** the presence of a NULL on the RHS makes a difference in the
2860 ** outcome.
2861 */
drh728e0f92015-10-10 14:41:28 +00002862 int addr1;
dan7b35a772016-07-28 19:47:15 +00002863
drhbb53ecb2014-08-02 21:03:33 +00002864 /* First check to see if the LHS is contained in the RHS. If so,
2865 ** then the answer is TRUE the presence of NULLs in the RHS does
2866 ** not matter. If the LHS is not contained in the RHS, then the
2867 ** answer is NULL if the RHS contains NULLs and the answer is
2868 ** FALSE if the RHS is NULL-free.
2869 */
drh728e0f92015-10-10 14:41:28 +00002870 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002871 VdbeCoverage(v);
2872 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2873 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002874 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002875 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002876 }
drhe3365e62009-11-12 17:52:24 +00002877 }
drhe3365e62009-11-12 17:52:24 +00002878 }
drhecb87ac2016-08-25 15:46:25 +00002879 if( r2!=r1 ) sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002880 sqlite3ExprCachePop(pParse);
drhecb87ac2016-08-25 15:46:25 +00002881 VdbeComment((v, "end IN expr"));
2882end_code_IN_op:
danba00e302016-07-23 20:24:06 +00002883 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00002884 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00002885}
2886#endif /* SQLITE_OMIT_SUBQUERY */
2887
drh13573c72010-01-12 17:04:07 +00002888#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002889/*
2890** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002891** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002892**
2893** The z[] string will probably not be zero-terminated. But the
2894** z[n] character is guaranteed to be something that does not look
2895** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002896*/
drhb7916a72009-05-27 10:31:29 +00002897static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002898 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002899 double value;
drh9339da12010-09-30 00:50:49 +00002900 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002901 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2902 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002903 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002904 }
2905}
drh13573c72010-01-12 17:04:07 +00002906#endif
drh598f1342007-10-23 15:39:45 +00002907
2908
2909/*
drhfec19aa2004-05-19 20:41:03 +00002910** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002911** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002912**
shaneh5f1d6b62010-09-30 16:51:25 +00002913** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002914*/
drh13573c72010-01-12 17:04:07 +00002915static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2916 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002917 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002918 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002919 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002920 if( negFlag ) i = -i;
2921 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002922 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002923 int c;
2924 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002925 const char *z = pExpr->u.zToken;
2926 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002927 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002928 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002929 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002930 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002931 }else{
drh13573c72010-01-12 17:04:07 +00002932#ifdef SQLITE_OMIT_FLOATING_POINT
2933 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2934#else
drh1b7ddc52014-07-23 14:52:05 +00002935#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002936 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2937 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002938 }else
2939#endif
2940 {
drh9296c182014-07-23 13:40:49 +00002941 codeReal(v, z, negFlag, iMem);
2942 }
drh13573c72010-01-12 17:04:07 +00002943#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002944 }
drhfec19aa2004-05-19 20:41:03 +00002945 }
2946}
2947
drhbea119c2016-04-11 18:15:37 +00002948#if defined(SQLITE_DEBUG)
2949/*
2950** Verify the consistency of the column cache
2951*/
2952static int cacheIsValid(Parse *pParse){
2953 int i, n;
2954 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2955 if( pParse->aColCache[i].iReg>0 ) n++;
2956 }
2957 return n==pParse->nColCache;
2958}
2959#endif
2960
drhceea3322009-04-23 13:22:42 +00002961/*
2962** Clear a cache entry.
2963*/
2964static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2965 if( p->tempReg ){
2966 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2967 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2968 }
2969 p->tempReg = 0;
2970 }
drhbea119c2016-04-11 18:15:37 +00002971 p->iReg = 0;
2972 pParse->nColCache--;
danee65eea2016-04-16 15:03:20 +00002973 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002974}
2975
2976
2977/*
2978** Record in the column cache that a particular column from a
2979** particular table is stored in a particular register.
2980*/
2981void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2982 int i;
2983 int minLru;
2984 int idxLru;
2985 struct yColCache *p;
2986
dance8f53d2015-01-21 17:00:57 +00002987 /* Unless an error has occurred, register numbers are always positive. */
2988 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002989 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2990
drhb6da74e2009-12-24 16:00:28 +00002991 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2992 ** for testing only - to verify that SQLite always gets the same answer
2993 ** with and without the column cache.
2994 */
drh7e5418e2012-09-27 15:05:54 +00002995 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002996
drh27ee4062009-12-30 01:13:11 +00002997 /* First replace any existing entry.
2998 **
2999 ** Actually, the way the column cache is currently used, we are guaranteed
3000 ** that the object will never already be in cache. Verify this guarantee.
3001 */
3002#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00003003 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00003004 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00003005 }
drh27ee4062009-12-30 01:13:11 +00003006#endif
drhceea3322009-04-23 13:22:42 +00003007
3008 /* Find an empty slot and replace it */
3009 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3010 if( p->iReg==0 ){
3011 p->iLevel = pParse->iCacheLevel;
3012 p->iTable = iTab;
3013 p->iColumn = iCol;
3014 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00003015 p->tempReg = 0;
3016 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00003017 pParse->nColCache++;
danee65eea2016-04-16 15:03:20 +00003018 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00003019 return;
3020 }
3021 }
3022
3023 /* Replace the last recently used */
3024 minLru = 0x7fffffff;
3025 idxLru = -1;
3026 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3027 if( p->lru<minLru ){
3028 idxLru = i;
3029 minLru = p->lru;
3030 }
3031 }
drh20411ea2009-05-29 19:00:12 +00003032 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00003033 p = &pParse->aColCache[idxLru];
3034 p->iLevel = pParse->iCacheLevel;
3035 p->iTable = iTab;
3036 p->iColumn = iCol;
3037 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00003038 p->tempReg = 0;
3039 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00003040 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00003041 return;
3042 }
3043}
3044
3045/*
drhf49f3522009-12-30 14:12:38 +00003046** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3047** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00003048*/
drhf49f3522009-12-30 14:12:38 +00003049void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00003050 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00003051 if( iReg<=0 || pParse->nColCache==0 ) return;
3052 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
3053 while(1){
3054 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
3055 if( p==pParse->aColCache ) break;
3056 p--;
drhceea3322009-04-23 13:22:42 +00003057 }
3058}
3059
3060/*
3061** Remember the current column cache context. Any new entries added
3062** added to the column cache after this call are removed when the
3063** corresponding pop occurs.
3064*/
3065void sqlite3ExprCachePush(Parse *pParse){
3066 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00003067#ifdef SQLITE_DEBUG
3068 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3069 printf("PUSH to %d\n", pParse->iCacheLevel);
3070 }
3071#endif
drhceea3322009-04-23 13:22:42 +00003072}
3073
3074/*
3075** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00003076** the previous sqlite3ExprCachePush operation. In other words, restore
3077** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00003078*/
drhd2490902014-04-13 19:28:15 +00003079void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00003080 int i;
3081 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00003082 assert( pParse->iCacheLevel>=1 );
3083 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00003084#ifdef SQLITE_DEBUG
3085 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3086 printf("POP to %d\n", pParse->iCacheLevel);
3087 }
3088#endif
drhceea3322009-04-23 13:22:42 +00003089 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3090 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
3091 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00003092 }
3093 }
3094}
drh945498f2007-02-24 11:52:52 +00003095
3096/*
drh5cd79232009-05-25 11:46:29 +00003097** When a cached column is reused, make sure that its register is
3098** no longer available as a temp register. ticket #3879: that same
3099** register might be in the cache in multiple places, so be sure to
3100** get them all.
3101*/
3102static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3103 int i;
3104 struct yColCache *p;
3105 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3106 if( p->iReg==iReg ){
3107 p->tempReg = 0;
3108 }
3109 }
3110}
3111
drh1f9ca2c2015-08-25 16:57:52 +00003112/* Generate code that will load into register regOut a value that is
3113** appropriate for the iIdxCol-th column of index pIdx.
3114*/
3115void sqlite3ExprCodeLoadIndexColumn(
3116 Parse *pParse, /* The parsing context */
3117 Index *pIdx, /* The index whose column is to be loaded */
3118 int iTabCur, /* Cursor pointing to a table row */
3119 int iIdxCol, /* The column of the index to be loaded */
3120 int regOut /* Store the index column value in this register */
3121){
3122 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003123 if( iTabCol==XN_EXPR ){
3124 assert( pIdx->aColExpr );
3125 assert( pIdx->aColExpr->nExpr>iIdxCol );
3126 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00003127 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00003128 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003129 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3130 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003131 }
drh1f9ca2c2015-08-25 16:57:52 +00003132}
3133
drh5cd79232009-05-25 11:46:29 +00003134/*
drh5c092e82010-05-14 19:24:02 +00003135** Generate code to extract the value of the iCol-th column of a table.
3136*/
3137void sqlite3ExprCodeGetColumnOfTable(
3138 Vdbe *v, /* The VDBE under construction */
3139 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003140 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003141 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003142 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003143){
3144 if( iCol<0 || iCol==pTab->iPKey ){
3145 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3146 }else{
3147 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003148 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003149 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003150 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3151 }
3152 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003153 }
3154 if( iCol>=0 ){
3155 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3156 }
3157}
3158
3159/*
drh945498f2007-02-24 11:52:52 +00003160** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00003161** table pTab and store the column value in a register.
3162**
3163** An effort is made to store the column value in register iReg. This
3164** is not garanteeed for GetColumn() - the result can be stored in
3165** any register. But the result is guaranteed to land in register iReg
3166** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00003167**
3168** There must be an open cursor to pTab in iTable when this routine
3169** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003170*/
drhe55cbd72008-03-31 23:48:03 +00003171int sqlite3ExprCodeGetColumn(
3172 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003173 Table *pTab, /* Description of the table we are reading from */
3174 int iColumn, /* Index of the table column */
3175 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003176 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003177 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003178){
drhe55cbd72008-03-31 23:48:03 +00003179 Vdbe *v = pParse->pVdbe;
3180 int i;
drhda250ea2008-04-01 05:07:14 +00003181 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00003182
drhceea3322009-04-23 13:22:42 +00003183 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00003184 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00003185 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00003186 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00003187 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00003188 }
3189 }
3190 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003191 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003192 if( p5 ){
3193 sqlite3VdbeChangeP5(v, p5);
3194 }else{
3195 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3196 }
drhe55cbd72008-03-31 23:48:03 +00003197 return iReg;
3198}
drhce78bc62015-10-15 19:21:51 +00003199void sqlite3ExprCodeGetColumnToReg(
3200 Parse *pParse, /* Parsing and code generating context */
3201 Table *pTab, /* Description of the table we are reading from */
3202 int iColumn, /* Index of the table column */
3203 int iTable, /* The cursor pointing to the table */
3204 int iReg /* Store results here */
3205){
3206 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3207 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3208}
3209
drhe55cbd72008-03-31 23:48:03 +00003210
3211/*
drhceea3322009-04-23 13:22:42 +00003212** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00003213*/
drhceea3322009-04-23 13:22:42 +00003214void sqlite3ExprCacheClear(Parse *pParse){
3215 int i;
3216 struct yColCache *p;
3217
drh9ac79622013-12-18 15:11:47 +00003218#if SQLITE_DEBUG
3219 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3220 printf("CLEAR\n");
3221 }
3222#endif
drhceea3322009-04-23 13:22:42 +00003223 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3224 if( p->iReg ){
3225 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00003226 }
drhe55cbd72008-03-31 23:48:03 +00003227 }
3228}
3229
3230/*
drhda250ea2008-04-01 05:07:14 +00003231** Record the fact that an affinity change has occurred on iCount
3232** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00003233*/
drhda250ea2008-04-01 05:07:14 +00003234void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00003235 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00003236}
3237
3238/*
drhb21e7c72008-06-22 12:37:57 +00003239** Generate code to move content from registers iFrom...iFrom+nReg-1
3240** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00003241*/
drhb21e7c72008-06-22 12:37:57 +00003242void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003243 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003244 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00003245 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00003246}
3247
drhf49f3522009-12-30 14:12:38 +00003248#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00003249/*
drh652fbf52008-04-01 01:42:41 +00003250** Return true if any register in the range iFrom..iTo (inclusive)
3251** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00003252**
3253** This routine is used within assert() and testcase() macros only
3254** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00003255*/
3256static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3257 int i;
drhceea3322009-04-23 13:22:42 +00003258 struct yColCache *p;
3259 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3260 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00003261 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00003262 }
3263 return 0;
3264}
drhf49f3522009-12-30 14:12:38 +00003265#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00003266
drhbea119c2016-04-11 18:15:37 +00003267
drh652fbf52008-04-01 01:42:41 +00003268/*
drh12abf402016-08-22 14:30:05 +00003269** Convert a scalar expression node to a TK_REGISTER referencing
3270** register iReg. The caller must ensure that iReg already contains
3271** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003272*/
3273static void exprToRegister(Expr *p, int iReg){
3274 p->op2 = p->op;
3275 p->op = TK_REGISTER;
3276 p->iTable = iReg;
3277 ExprClearProperty(p, EP_Skip);
3278}
3279
drh12abf402016-08-22 14:30:05 +00003280/*
3281** Evaluate an expression (either a vector or a scalar expression) and store
3282** the result in continguous temporary registers. Return the index of
3283** the first register used to store the result.
3284**
3285** If the returned result register is a temporary scalar, then also write
3286** that register number into *piFreeable. If the returned result register
3287** is not a temporary or if the expression is a vector set *piFreeable
3288** to 0.
3289*/
3290static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3291 int iResult;
3292 int nResult = sqlite3ExprVectorSize(p);
3293 if( nResult==1 ){
3294 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3295 }else{
3296 *piFreeable = 0;
3297 if( p->op==TK_SELECT ){
3298 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3299 }else{
3300 int i;
3301 iResult = pParse->nMem+1;
3302 pParse->nMem += nResult;
3303 for(i=0; i<nResult; i++){
3304 sqlite3ExprCode(pParse, p->x.pList->a[i].pExpr, i+iResult);
3305 }
3306 }
3307 }
3308 return iResult;
3309}
3310
dan71c57db2016-07-09 20:23:55 +00003311
drha4c3c872013-09-12 17:29:25 +00003312/*
drhcce7d172000-05-31 15:34:51 +00003313** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003314** expression. Attempt to store the results in register "target".
3315** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003316**
drh8b213892008-08-29 02:14:02 +00003317** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003318** be stored in target. The result might be stored in some other
3319** register if it is convenient to do so. The calling function
3320** must check the return code and move the results to the desired
3321** register.
drhcce7d172000-05-31 15:34:51 +00003322*/
drh678ccce2008-03-31 18:19:54 +00003323int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003324 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3325 int op; /* The opcode being coded */
3326 int inReg = target; /* Results stored in register inReg */
3327 int regFree1 = 0; /* If non-zero free this temporary register */
3328 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003329 int r1, r2; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00003330 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00003331 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003332 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003333
drh9cbf3422008-01-17 16:22:13 +00003334 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003335 if( v==0 ){
3336 assert( pParse->db->mallocFailed );
3337 return 0;
3338 }
drh389a1ad2008-01-03 23:44:53 +00003339
3340 if( pExpr==0 ){
3341 op = TK_NULL;
3342 }else{
3343 op = pExpr->op;
3344 }
drhf2bc0132004-10-04 13:19:23 +00003345 switch( op ){
drh13449892005-09-07 21:22:45 +00003346 case TK_AGG_COLUMN: {
3347 AggInfo *pAggInfo = pExpr->pAggInfo;
3348 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3349 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003350 assert( pCol->iMem>0 );
3351 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00003352 break;
3353 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003354 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003355 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00003356 break;
3357 }
3358 /* Otherwise, fall thru into the TK_COLUMN case */
3359 }
drh967e8b72000-06-21 13:59:10 +00003360 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003361 int iTab = pExpr->iTable;
3362 if( iTab<0 ){
3363 if( pParse->ckBase>0 ){
3364 /* Generating CHECK constraints or inserting into partial index */
3365 inReg = pExpr->iColumn + pParse->ckBase;
3366 break;
3367 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003368 /* Coding an expression that is part of an index where column names
3369 ** in the index refer to the table to which the index belongs */
3370 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003371 }
drh22827922000-06-06 17:27:05 +00003372 }
drhb2b9d3d2013-08-01 01:14:43 +00003373 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3374 pExpr->iColumn, iTab, target,
3375 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003376 break;
3377 }
3378 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003379 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00003380 break;
3381 }
drh13573c72010-01-12 17:04:07 +00003382#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003383 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003384 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3385 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00003386 break;
3387 }
drh13573c72010-01-12 17:04:07 +00003388#endif
drhfec19aa2004-05-19 20:41:03 +00003389 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003390 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003391 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00003392 break;
3393 }
drhf0863fe2005-06-12 21:35:51 +00003394 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003395 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00003396 break;
3397 }
danielk19775338a5f2005-01-20 13:03:10 +00003398#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003399 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003400 int n;
3401 const char *z;
drhca48c902008-01-18 14:08:24 +00003402 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003403 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3404 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3405 assert( pExpr->u.zToken[1]=='\'' );
3406 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003407 n = sqlite3Strlen30(z) - 1;
3408 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003409 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3410 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00003411 break;
3412 }
danielk19775338a5f2005-01-20 13:03:10 +00003413#endif
drh50457892003-09-06 01:10:47 +00003414 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003415 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3416 assert( pExpr->u.zToken!=0 );
3417 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003418 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3419 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00003420 assert( pExpr->u.zToken[0]=='?'
3421 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
3422 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003423 }
drh50457892003-09-06 01:10:47 +00003424 break;
3425 }
drh4e0cff62004-11-05 05:10:28 +00003426 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00003427 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003428 break;
3429 }
drh487e2622005-06-25 18:42:14 +00003430#ifndef SQLITE_OMIT_CAST
3431 case TK_CAST: {
3432 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003433 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003434 if( inReg!=target ){
3435 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3436 inReg = target;
3437 }
drh4169e432014-08-25 20:11:52 +00003438 sqlite3VdbeAddOp2(v, OP_Cast, target,
3439 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00003440 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00003441 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00003442 break;
3443 }
3444#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003445 case TK_IS:
3446 case TK_ISNOT:
3447 op = (op==TK_IS) ? TK_EQ : TK_NE;
3448 p5 = SQLITE_NULLEQ;
3449 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003450 case TK_LT:
3451 case TK_LE:
3452 case TK_GT:
3453 case TK_GE:
3454 case TK_NE:
3455 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003456 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003457 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003458 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003459 }else{
3460 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3461 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3462 codeCompare(pParse, pLeft, pExpr->pRight, op,
3463 r1, r2, inReg, SQLITE_STOREP2 | p5);
3464 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3465 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3466 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3467 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3468 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3469 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3470 testcase( regFree1==0 );
3471 testcase( regFree2==0 );
3472 }
drh6a2fe092009-09-23 02:29:36 +00003473 break;
3474 }
drhcce7d172000-05-31 15:34:51 +00003475 case TK_AND:
3476 case TK_OR:
3477 case TK_PLUS:
3478 case TK_STAR:
3479 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003480 case TK_REM:
3481 case TK_BITAND:
3482 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003483 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003484 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003485 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003486 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003487 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3488 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3489 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3490 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3491 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3492 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3493 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3494 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3495 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3496 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3497 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003498 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3499 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003500 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003501 testcase( regFree1==0 );
3502 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003503 break;
3504 }
drhcce7d172000-05-31 15:34:51 +00003505 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003506 Expr *pLeft = pExpr->pLeft;
3507 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003508 if( pLeft->op==TK_INTEGER ){
3509 codeInteger(pParse, pLeft, 1, target);
3510#ifndef SQLITE_OMIT_FLOATING_POINT
3511 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003512 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3513 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00003514#endif
drh3c84ddf2008-01-09 02:15:38 +00003515 }else{
drh10d1edf2013-11-15 15:52:39 +00003516 tempX.op = TK_INTEGER;
3517 tempX.flags = EP_IntValue|EP_TokenOnly;
3518 tempX.u.iValue = 0;
3519 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003520 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003521 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003522 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003523 }
drh3c84ddf2008-01-09 02:15:38 +00003524 inReg = target;
3525 break;
drh6e142f52000-06-08 13:36:40 +00003526 }
drhbf4133c2001-10-13 02:59:08 +00003527 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003528 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003529 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3530 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003531 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3532 testcase( regFree1==0 );
3533 inReg = target;
3534 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003535 break;
3536 }
3537 case TK_ISNULL:
3538 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003539 int addr;
drh7d176102014-02-18 03:07:12 +00003540 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3541 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003542 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003543 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003544 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003545 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003546 VdbeCoverageIf(v, op==TK_ISNULL);
3547 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003548 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003549 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003550 break;
drhcce7d172000-05-31 15:34:51 +00003551 }
drh22827922000-06-06 17:27:05 +00003552 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003553 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003554 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003555 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3556 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003557 }else{
drh9de221d2008-01-05 06:51:30 +00003558 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003559 }
drh22827922000-06-06 17:27:05 +00003560 break;
3561 }
drhcce7d172000-05-31 15:34:51 +00003562 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003563 ExprList *pFarg; /* List of function arguments */
3564 int nFarg; /* Number of function arguments */
3565 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003566 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003567 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003568 int i; /* Loop counter */
3569 u8 enc = ENC(db); /* The text encoding used by this database */
3570 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003571
danielk19776ab3a2e2009-02-19 14:39:25 +00003572 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00003573 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003574 pFarg = 0;
3575 }else{
3576 pFarg = pExpr->x.pList;
3577 }
3578 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003579 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3580 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003581 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003582#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3583 if( pDef==0 && pParse->explain ){
3584 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3585 }
3586#endif
drh2d801512016-01-14 22:19:58 +00003587 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003588 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003589 break;
3590 }
drhae6bb952009-11-11 00:24:31 +00003591
3592 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003593 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003594 ** arguments past the first non-NULL argument.
3595 */
drhd36e1042013-09-06 13:10:12 +00003596 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003597 int endCoalesce = sqlite3VdbeMakeLabel(v);
3598 assert( nFarg>=2 );
3599 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3600 for(i=1; i<nFarg; i++){
3601 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003602 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00003603 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00003604 sqlite3ExprCachePush(pParse);
3605 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003606 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00003607 }
3608 sqlite3VdbeResolveLabel(v, endCoalesce);
3609 break;
3610 }
3611
drhcca9f3d2013-09-06 15:23:29 +00003612 /* The UNLIKELY() function is a no-op. The result is the value
3613 ** of the first argument.
3614 */
3615 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3616 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00003617 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003618 break;
3619 }
drhae6bb952009-11-11 00:24:31 +00003620
drhd1a01ed2013-11-21 16:08:52 +00003621 for(i=0; i<nFarg; i++){
3622 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003623 testcase( i==31 );
3624 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003625 }
3626 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3627 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3628 }
3629 }
drh12ffee82009-04-08 13:51:51 +00003630 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003631 if( constMask ){
3632 r1 = pParse->nMem+1;
3633 pParse->nMem += nFarg;
3634 }else{
3635 r1 = sqlite3GetTempRange(pParse, nFarg);
3636 }
drha748fdc2012-03-28 01:34:47 +00003637
3638 /* For length() and typeof() functions with a column argument,
3639 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3640 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3641 ** loading.
3642 */
drhd36e1042013-09-06 13:10:12 +00003643 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003644 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003645 assert( nFarg==1 );
3646 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003647 exprOp = pFarg->a[0].pExpr->op;
3648 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003649 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3650 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003651 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3652 pFarg->a[0].pExpr->op2 =
3653 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003654 }
3655 }
3656
drhd7d385d2009-09-03 01:18:00 +00003657 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003658 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003659 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003660 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003661 }else{
drh12ffee82009-04-08 13:51:51 +00003662 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003663 }
drhb7f6f682006-07-08 17:06:43 +00003664#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003665 /* Possibly overload the function if the first argument is
3666 ** a virtual table column.
3667 **
3668 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3669 ** second argument, not the first, as the argument to test to
3670 ** see if it is a column in a virtual table. This is done because
3671 ** the left operand of infix functions (the operand we want to
3672 ** control overloading) ends up as the second argument to the
3673 ** function. The expression "A glob B" is equivalent to
3674 ** "glob(B,A). We want to use the A in "A glob B" to test
3675 ** for function overloading. But we use the B term in "glob(B,A)".
3676 */
drh12ffee82009-04-08 13:51:51 +00003677 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3678 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3679 }else if( nFarg>0 ){
3680 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003681 }
3682#endif
drhd36e1042013-09-06 13:10:12 +00003683 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003684 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003685 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003686 }
drh9c7c9132015-06-26 18:16:52 +00003687 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003688 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003689 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003690 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003691 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003692 }
drhcce7d172000-05-31 15:34:51 +00003693 break;
3694 }
drhfe2093d2005-01-20 22:48:47 +00003695#ifndef SQLITE_OMIT_SUBQUERY
3696 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003697 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003698 int nCol;
drhc5499be2008-04-01 15:06:33 +00003699 testcase( op==TK_EXISTS );
3700 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003701 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3702 sqlite3SubselectError(pParse, nCol, 1);
3703 }else{
3704 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3705 }
drh19a775c2000-06-05 18:54:46 +00003706 break;
3707 }
drhfc7f27b2016-08-20 00:07:01 +00003708 case TK_SELECT_COLUMN: {
3709 if( pExpr->pLeft->iTable==0 ){
3710 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3711 }
3712 inReg = pExpr->pLeft->iTable + pExpr->iColumn;
3713 break;
3714 }
drhfef52082000-06-06 01:50:43 +00003715 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003716 int destIfFalse = sqlite3VdbeMakeLabel(v);
3717 int destIfNull = sqlite3VdbeMakeLabel(v);
3718 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3719 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3720 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3721 sqlite3VdbeResolveLabel(v, destIfFalse);
3722 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3723 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003724 break;
3725 }
drhe3365e62009-11-12 17:52:24 +00003726#endif /* SQLITE_OMIT_SUBQUERY */
3727
3728
drh2dcef112008-01-12 19:03:48 +00003729 /*
3730 ** x BETWEEN y AND z
3731 **
3732 ** This is equivalent to
3733 **
3734 ** x>=y AND x<=z
3735 **
3736 ** X is stored in pExpr->pLeft.
3737 ** Y is stored in pExpr->pList->a[0].pExpr.
3738 ** Z is stored in pExpr->pList->a[1].pExpr.
3739 */
drhfef52082000-06-06 01:50:43 +00003740 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003741 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhfef52082000-06-06 01:50:43 +00003742 break;
3743 }
drh94fa9c42016-02-27 21:16:04 +00003744 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003745 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003746 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003747 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003748 break;
3749 }
drh2dcef112008-01-12 19:03:48 +00003750
dan165921a2009-08-28 18:53:45 +00003751 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003752 /* If the opcode is TK_TRIGGER, then the expression is a reference
3753 ** to a column in the new.* or old.* pseudo-tables available to
3754 ** trigger programs. In this case Expr.iTable is set to 1 for the
3755 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3756 ** is set to the column of the pseudo-table to read, or to -1 to
3757 ** read the rowid field.
3758 **
3759 ** The expression is implemented using an OP_Param opcode. The p1
3760 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3761 ** to reference another column of the old.* pseudo-table, where
3762 ** i is the index of the column. For a new.rowid reference, p1 is
3763 ** set to (n+1), where n is the number of columns in each pseudo-table.
3764 ** For a reference to any other column in the new.* pseudo-table, p1
3765 ** is set to (n+2+i), where n and i are as defined previously. For
3766 ** example, if the table on which triggers are being fired is
3767 ** declared as:
3768 **
3769 ** CREATE TABLE t1(a, b);
3770 **
3771 ** Then p1 is interpreted as follows:
3772 **
3773 ** p1==0 -> old.rowid p1==3 -> new.rowid
3774 ** p1==1 -> old.a p1==4 -> new.a
3775 ** p1==2 -> old.b p1==5 -> new.b
3776 */
dan2832ad42009-08-31 15:27:27 +00003777 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003778 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3779
3780 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3781 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3782 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3783 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3784
3785 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003786 VdbeComment((v, "%s.%s -> $%d",
3787 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003788 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003789 target
dan165921a2009-08-28 18:53:45 +00003790 ));
dan65a7cd12009-09-01 12:16:01 +00003791
drh44dbca82010-01-13 04:22:20 +00003792#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003793 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003794 ** integer. Use OP_RealAffinity to make sure it is really real.
3795 **
3796 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3797 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003798 if( pExpr->iColumn>=0
3799 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3800 ){
3801 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3802 }
drh44dbca82010-01-13 04:22:20 +00003803#endif
dan165921a2009-08-28 18:53:45 +00003804 break;
3805 }
3806
dan71c57db2016-07-09 20:23:55 +00003807 case TK_VECTOR: {
drhe835bc12016-08-23 19:02:55 +00003808 sqlite3ErrorMsg(pParse, "row value misused");
dan71c57db2016-07-09 20:23:55 +00003809 break;
3810 }
3811
drh2dcef112008-01-12 19:03:48 +00003812 /*
3813 ** Form A:
3814 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3815 **
3816 ** Form B:
3817 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3818 **
3819 ** Form A is can be transformed into the equivalent form B as follows:
3820 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3821 ** WHEN x=eN THEN rN ELSE y END
3822 **
3823 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003824 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3825 ** odd. The Y is also optional. If the number of elements in x.pList
3826 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003827 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3828 **
3829 ** The result of the expression is the Ri for the first matching Ei,
3830 ** or if there is no matching Ei, the ELSE term Y, or if there is
3831 ** no ELSE term, NULL.
3832 */
drh33cd4902009-05-30 20:49:20 +00003833 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003834 int endLabel; /* GOTO label for end of CASE stmt */
3835 int nextCase; /* GOTO label for next WHEN clause */
3836 int nExpr; /* 2x number of WHEN terms */
3837 int i; /* Loop counter */
3838 ExprList *pEList; /* List of WHEN terms */
3839 struct ExprList_item *aListelem; /* Array of WHEN terms */
3840 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003841 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003842 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003843 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003844
danielk19776ab3a2e2009-02-19 14:39:25 +00003845 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003846 assert(pExpr->x.pList->nExpr > 0);
3847 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003848 aListelem = pEList->a;
3849 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003850 endLabel = sqlite3VdbeMakeLabel(v);
3851 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003852 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003853 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00003854 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003855 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00003856 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00003857 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003858 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003859 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003860 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3861 ** The value in regFree1 might get SCopy-ed into the file result.
3862 ** So make sure that the regFree1 register is not reused for other
3863 ** purposes and possibly overwritten. */
3864 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003865 }
drhc5cd1242013-09-12 16:50:49 +00003866 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003867 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003868 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003869 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003870 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003871 }else{
drh2dcef112008-01-12 19:03:48 +00003872 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003873 }
drh2dcef112008-01-12 19:03:48 +00003874 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003875 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003876 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003877 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003878 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003879 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003880 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003881 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003882 }
drhc5cd1242013-09-12 16:50:49 +00003883 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003884 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003885 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003886 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003887 }else{
drh9de221d2008-01-05 06:51:30 +00003888 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003889 }
danielk1977c1f4a192009-04-28 12:08:15 +00003890 assert( db->mallocFailed || pParse->nErr>0
3891 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003892 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003893 break;
3894 }
danielk19775338a5f2005-01-20 13:03:10 +00003895#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003896 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003897 assert( pExpr->affinity==OE_Rollback
3898 || pExpr->affinity==OE_Abort
3899 || pExpr->affinity==OE_Fail
3900 || pExpr->affinity==OE_Ignore
3901 );
dane0af83a2009-09-08 19:15:01 +00003902 if( !pParse->pTriggerTab ){
3903 sqlite3ErrorMsg(pParse,
3904 "RAISE() may only be used within a trigger-program");
3905 return 0;
3906 }
3907 if( pExpr->affinity==OE_Abort ){
3908 sqlite3MayAbort(pParse);
3909 }
dan165921a2009-08-28 18:53:45 +00003910 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003911 if( pExpr->affinity==OE_Ignore ){
3912 sqlite3VdbeAddOp4(
3913 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003914 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003915 }else{
drh433dccf2013-02-09 15:37:11 +00003916 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003917 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003918 }
3919
drhffe07b22005-11-03 00:41:17 +00003920 break;
drh17a7f8d2002-03-24 13:13:27 +00003921 }
danielk19775338a5f2005-01-20 13:03:10 +00003922#endif
drhffe07b22005-11-03 00:41:17 +00003923 }
drh2dcef112008-01-12 19:03:48 +00003924 sqlite3ReleaseTempReg(pParse, regFree1);
3925 sqlite3ReleaseTempReg(pParse, regFree2);
3926 return inReg;
3927}
3928
3929/*
drhd1a01ed2013-11-21 16:08:52 +00003930** Factor out the code of the given expression to initialization time.
3931*/
drhd673cdd2013-11-21 21:23:31 +00003932void sqlite3ExprCodeAtInit(
3933 Parse *pParse, /* Parsing context */
3934 Expr *pExpr, /* The expression to code when the VDBE initializes */
3935 int regDest, /* Store the value in this register */
3936 u8 reusable /* True if this expression is reusable */
3937){
drhd1a01ed2013-11-21 16:08:52 +00003938 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003939 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003940 p = pParse->pConstExpr;
3941 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3942 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003943 if( p ){
3944 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3945 pItem->u.iConstExprReg = regDest;
3946 pItem->reusable = reusable;
3947 }
drhd1a01ed2013-11-21 16:08:52 +00003948 pParse->pConstExpr = p;
3949}
3950
3951/*
drh2dcef112008-01-12 19:03:48 +00003952** Generate code to evaluate an expression and store the results
3953** into a register. Return the register number where the results
3954** are stored.
3955**
3956** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003957** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003958** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003959**
3960** If pExpr is a constant, then this routine might generate this
3961** code to fill the register in the initialization section of the
3962** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003963*/
3964int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003965 int r2;
3966 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003967 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003968 && pExpr->op!=TK_REGISTER
3969 && sqlite3ExprIsConstantNotJoin(pExpr)
3970 ){
3971 ExprList *p = pParse->pConstExpr;
3972 int i;
3973 *pReg = 0;
3974 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003975 struct ExprList_item *pItem;
3976 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3977 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3978 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003979 }
3980 }
3981 }
drhf30a9692013-11-15 01:10:18 +00003982 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003983 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003984 }else{
drhf30a9692013-11-15 01:10:18 +00003985 int r1 = sqlite3GetTempReg(pParse);
3986 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3987 if( r2==r1 ){
3988 *pReg = r1;
3989 }else{
3990 sqlite3ReleaseTempReg(pParse, r1);
3991 *pReg = 0;
3992 }
drh2dcef112008-01-12 19:03:48 +00003993 }
3994 return r2;
3995}
3996
3997/*
3998** Generate code that will evaluate expression pExpr and store the
3999** results in register target. The results are guaranteed to appear
4000** in register target.
4001*/
drh05a86c52014-02-16 01:55:49 +00004002void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00004003 int inReg;
4004
4005 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00004006 if( pExpr && pExpr->op==TK_REGISTER ){
4007 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
4008 }else{
4009 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00004010 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00004011 if( inReg!=target && pParse->pVdbe ){
4012 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
4013 }
drhcce7d172000-05-31 15:34:51 +00004014 }
drhcce7d172000-05-31 15:34:51 +00004015}
4016
4017/*
drh1c75c9d2015-12-21 15:22:13 +00004018** Make a transient copy of expression pExpr and then code it using
4019** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
4020** except that the input expression is guaranteed to be unchanged.
4021*/
4022void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4023 sqlite3 *db = pParse->db;
4024 pExpr = sqlite3ExprDup(db, pExpr, 0);
4025 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4026 sqlite3ExprDelete(db, pExpr);
4027}
4028
4029/*
drh05a86c52014-02-16 01:55:49 +00004030** Generate code that will evaluate expression pExpr and store the
4031** results in register target. The results are guaranteed to appear
4032** in register target. If the expression is constant, then this routine
4033** might choose to code the expression at initialization time.
4034*/
4035void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4036 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4037 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
4038 }else{
4039 sqlite3ExprCode(pParse, pExpr, target);
4040 }
drhcce7d172000-05-31 15:34:51 +00004041}
4042
4043/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004044** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004045** in register target.
drh25303782004-12-07 15:41:48 +00004046**
drh2dcef112008-01-12 19:03:48 +00004047** Also make a copy of the expression results into another "cache" register
4048** and modify the expression so that the next time it is evaluated,
4049** the result is a copy of the cache register.
4050**
4051** This routine is used for expressions that are used multiple
4052** times. They are evaluated once and the results of the expression
4053** are reused.
drh25303782004-12-07 15:41:48 +00004054*/
drh05a86c52014-02-16 01:55:49 +00004055void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004056 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004057 int iMem;
4058
drhde4fcfd2008-01-19 23:50:26 +00004059 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004060 assert( pExpr->op!=TK_REGISTER );
4061 sqlite3ExprCode(pParse, pExpr, target);
4062 iMem = ++pParse->nMem;
4063 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4064 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004065}
drh2dcef112008-01-12 19:03:48 +00004066
drh678ccce2008-03-31 18:19:54 +00004067/*
drh268380c2004-02-25 13:47:31 +00004068** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004069** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004070**
drh892d3172008-01-10 03:46:36 +00004071** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00004072**
4073** The SQLITE_ECEL_DUP flag prevents the arguments from being
4074** filled using OP_SCopy. OP_Copy must be used instead.
4075**
4076** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4077** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004078**
4079** The SQLITE_ECEL_REF flag means that expressions in the list with
4080** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4081** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00004082*/
danielk19774adee202004-05-08 08:23:19 +00004083int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004084 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004085 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004086 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004087 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004088 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004089){
4090 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004091 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004092 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004093 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004094 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004095 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004096 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004097 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004098 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004099 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004100 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00004101 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
4102 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4103 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00004104 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00004105 }else{
4106 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4107 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004108 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004109 if( copyOp==OP_Copy
4110 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4111 && pOp->p1+pOp->p3+1==inReg
4112 && pOp->p2+pOp->p3+1==target+i
4113 ){
4114 pOp->p3++;
4115 }else{
4116 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4117 }
drhd1a01ed2013-11-21 16:08:52 +00004118 }
drhd1766112008-09-17 00:13:12 +00004119 }
drh268380c2004-02-25 13:47:31 +00004120 }
drhf9b596e2004-05-26 16:54:42 +00004121 return n;
drh268380c2004-02-25 13:47:31 +00004122}
4123
4124/*
drh36c563a2009-11-12 13:32:22 +00004125** Generate code for a BETWEEN operator.
4126**
4127** x BETWEEN y AND z
4128**
4129** The above is equivalent to
4130**
4131** x>=y AND x<=z
4132**
4133** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004134** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004135**
4136** The xJumpIf parameter determines details:
4137**
4138** NULL: Store the boolean result in reg[dest]
4139** sqlite3ExprIfTrue: Jump to dest if true
4140** sqlite3ExprIfFalse: Jump to dest if false
4141**
4142** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004143*/
4144static void exprCodeBetween(
4145 Parse *pParse, /* Parsing and code generating context */
4146 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004147 int dest, /* Jump destination or storage location */
4148 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004149 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4150){
drhdb45bd52016-08-22 00:48:58 +00004151 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004152 Expr compLeft; /* The x>=y term */
4153 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004154 Expr exprX; /* The x subexpression */
4155 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004156
drh36c563a2009-11-12 13:32:22 +00004157
dan71c57db2016-07-09 20:23:55 +00004158 memset(&compLeft, 0, sizeof(Expr));
4159 memset(&compRight, 0, sizeof(Expr));
4160 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004161
4162 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4163 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004164 exprAnd.op = TK_AND;
4165 exprAnd.pLeft = &compLeft;
4166 exprAnd.pRight = &compRight;
4167 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004168 compLeft.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004169 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4170 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004171 compRight.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004172 compRight.pRight = pExpr->x.pList->a[1].pExpr;
drh12abf402016-08-22 14:30:05 +00004173 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004174 if( xJump ){
4175 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004176 }else{
drhdb45bd52016-08-22 00:48:58 +00004177 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004178 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004179 }
drhdb45bd52016-08-22 00:48:58 +00004180 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004181
4182 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004183 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4184 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4185 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4186 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4187 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4188 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4189 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4190 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004191 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004192}
4193
4194/*
drhcce7d172000-05-31 15:34:51 +00004195** Generate code for a boolean expression such that a jump is made
4196** to the label "dest" if the expression is true but execution
4197** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004198**
4199** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004200** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004201**
4202** This code depends on the fact that certain token values (ex: TK_EQ)
4203** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4204** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4205** the make process cause these values to align. Assert()s in the code
4206** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004207*/
danielk19774adee202004-05-08 08:23:19 +00004208void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004209 Vdbe *v = pParse->pVdbe;
4210 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004211 int regFree1 = 0;
4212 int regFree2 = 0;
4213 int r1, r2;
4214
drh35573352008-01-08 23:54:25 +00004215 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004216 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004217 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004218 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004219 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004220 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004221 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004222 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004223 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004224 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004225 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4226 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004227 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004228 break;
4229 }
4230 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004231 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004232 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004233 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004234 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004235 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004236 break;
4237 }
4238 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004239 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004240 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004241 break;
4242 }
drhde845c22016-03-17 19:07:52 +00004243 case TK_IS:
4244 case TK_ISNOT:
4245 testcase( op==TK_IS );
4246 testcase( op==TK_ISNOT );
4247 op = (op==TK_IS) ? TK_EQ : TK_NE;
4248 jumpIfNull = SQLITE_NULLEQ;
4249 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004250 case TK_LT:
4251 case TK_LE:
4252 case TK_GT:
4253 case TK_GE:
4254 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004255 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004256 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004257 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004258 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4259 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004260 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004261 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004262 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4263 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4264 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4265 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004266 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4267 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4268 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4269 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4270 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4271 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004272 testcase( regFree1==0 );
4273 testcase( regFree2==0 );
4274 break;
4275 }
drhcce7d172000-05-31 15:34:51 +00004276 case TK_ISNULL:
4277 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004278 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4279 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004280 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4281 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004282 VdbeCoverageIf(v, op==TK_ISNULL);
4283 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004284 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004285 break;
4286 }
drhfef52082000-06-06 01:50:43 +00004287 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004288 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004289 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004290 break;
4291 }
drh84e30ca2011-02-10 17:46:14 +00004292#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004293 case TK_IN: {
4294 int destIfFalse = sqlite3VdbeMakeLabel(v);
4295 int destIfNull = jumpIfNull ? dest : destIfFalse;
4296 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004297 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004298 sqlite3VdbeResolveLabel(v, destIfFalse);
4299 break;
4300 }
shanehbb201342011-02-09 19:55:20 +00004301#endif
drhcce7d172000-05-31 15:34:51 +00004302 default: {
dan7b35a772016-07-28 19:47:15 +00004303 default_expr:
drh991a1982014-01-02 17:57:16 +00004304 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004305 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004306 }else if( exprAlwaysFalse(pExpr) ){
4307 /* No-op */
4308 }else{
4309 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4310 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004311 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004312 testcase( regFree1==0 );
4313 testcase( jumpIfNull==0 );
4314 }
drhcce7d172000-05-31 15:34:51 +00004315 break;
4316 }
4317 }
drh2dcef112008-01-12 19:03:48 +00004318 sqlite3ReleaseTempReg(pParse, regFree1);
4319 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004320}
4321
4322/*
drh66b89c82000-11-28 20:47:17 +00004323** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004324** to the label "dest" if the expression is false but execution
4325** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004326**
4327** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004328** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4329** is 0.
drhcce7d172000-05-31 15:34:51 +00004330*/
danielk19774adee202004-05-08 08:23:19 +00004331void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004332 Vdbe *v = pParse->pVdbe;
4333 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004334 int regFree1 = 0;
4335 int regFree2 = 0;
4336 int r1, r2;
4337
drh35573352008-01-08 23:54:25 +00004338 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004339 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004340 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004341
4342 /* The value of pExpr->op and op are related as follows:
4343 **
4344 ** pExpr->op op
4345 ** --------- ----------
4346 ** TK_ISNULL OP_NotNull
4347 ** TK_NOTNULL OP_IsNull
4348 ** TK_NE OP_Eq
4349 ** TK_EQ OP_Ne
4350 ** TK_GT OP_Le
4351 ** TK_LE OP_Gt
4352 ** TK_GE OP_Lt
4353 ** TK_LT OP_Ge
4354 **
4355 ** For other values of pExpr->op, op is undefined and unused.
4356 ** The value of TK_ and OP_ constants are arranged such that we
4357 ** can compute the mapping above using the following expression.
4358 ** Assert()s verify that the computation is correct.
4359 */
4360 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4361
4362 /* Verify correct alignment of TK_ and OP_ constants
4363 */
4364 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4365 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4366 assert( pExpr->op!=TK_NE || op==OP_Eq );
4367 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4368 assert( pExpr->op!=TK_LT || op==OP_Ge );
4369 assert( pExpr->op!=TK_LE || op==OP_Gt );
4370 assert( pExpr->op!=TK_GT || op==OP_Le );
4371 assert( pExpr->op!=TK_GE || op==OP_Lt );
4372
danba00e302016-07-23 20:24:06 +00004373 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004374 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004375 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004376 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004377 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004378 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004379 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004380 break;
4381 }
4382 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004383 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004384 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004385 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004386 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004387 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4388 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004389 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004390 break;
4391 }
4392 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004393 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004394 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004395 break;
4396 }
drhde845c22016-03-17 19:07:52 +00004397 case TK_IS:
4398 case TK_ISNOT:
4399 testcase( pExpr->op==TK_IS );
4400 testcase( pExpr->op==TK_ISNOT );
4401 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4402 jumpIfNull = SQLITE_NULLEQ;
4403 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004404 case TK_LT:
4405 case TK_LE:
4406 case TK_GT:
4407 case TK_GE:
4408 case TK_NE:
4409 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004410 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004411 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004412 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4413 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004414 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004415 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004416 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4417 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4418 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4419 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004420 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4421 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4422 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4423 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4424 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4425 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004426 testcase( regFree1==0 );
4427 testcase( regFree2==0 );
4428 break;
4429 }
drhcce7d172000-05-31 15:34:51 +00004430 case TK_ISNULL:
4431 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004432 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4433 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004434 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4435 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004436 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004437 break;
4438 }
drhfef52082000-06-06 01:50:43 +00004439 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004440 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004441 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004442 break;
4443 }
drh84e30ca2011-02-10 17:46:14 +00004444#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004445 case TK_IN: {
4446 if( jumpIfNull ){
4447 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4448 }else{
4449 int destIfNull = sqlite3VdbeMakeLabel(v);
4450 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4451 sqlite3VdbeResolveLabel(v, destIfNull);
4452 }
4453 break;
4454 }
shanehbb201342011-02-09 19:55:20 +00004455#endif
drhcce7d172000-05-31 15:34:51 +00004456 default: {
danba00e302016-07-23 20:24:06 +00004457 default_expr:
drh991a1982014-01-02 17:57:16 +00004458 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004459 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004460 }else if( exprAlwaysTrue(pExpr) ){
4461 /* no-op */
4462 }else{
4463 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4464 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004465 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004466 testcase( regFree1==0 );
4467 testcase( jumpIfNull==0 );
4468 }
drhcce7d172000-05-31 15:34:51 +00004469 break;
4470 }
4471 }
drh2dcef112008-01-12 19:03:48 +00004472 sqlite3ReleaseTempReg(pParse, regFree1);
4473 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004474}
drh22827922000-06-06 17:27:05 +00004475
4476/*
drh72bc8202015-06-11 13:58:35 +00004477** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4478** code generation, and that copy is deleted after code generation. This
4479** ensures that the original pExpr is unchanged.
4480*/
4481void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4482 sqlite3 *db = pParse->db;
4483 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4484 if( db->mallocFailed==0 ){
4485 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4486 }
4487 sqlite3ExprDelete(db, pCopy);
4488}
4489
4490
4491/*
drh1d9da702010-01-07 15:17:02 +00004492** Do a deep comparison of two expression trees. Return 0 if the two
4493** expressions are completely identical. Return 1 if they differ only
4494** by a COLLATE operator at the top level. Return 2 if there are differences
4495** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004496**
drh619a1302013-08-01 13:04:46 +00004497** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4498** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4499**
drh66518ca2013-08-01 15:09:57 +00004500** The pA side might be using TK_REGISTER. If that is the case and pB is
4501** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4502**
drh1d9da702010-01-07 15:17:02 +00004503** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004504** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004505** identical, we return 2 just to be safe. So if this routine
4506** returns 2, then you do not really know for certain if the two
4507** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004508** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004509** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004510** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004511** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00004512*/
drh619a1302013-08-01 13:04:46 +00004513int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004514 u32 combinedFlags;
4515 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004516 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004517 }
drh10d1edf2013-11-15 15:52:39 +00004518 combinedFlags = pA->flags | pB->flags;
4519 if( combinedFlags & EP_IntValue ){
4520 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4521 return 0;
4522 }
drh1d9da702010-01-07 15:17:02 +00004523 return 2;
drh22827922000-06-06 17:27:05 +00004524 }
drhc2acc4e2013-11-15 18:15:19 +00004525 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00004526 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004527 return 1;
4528 }
drh619a1302013-08-01 13:04:46 +00004529 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004530 return 1;
4531 }
4532 return 2;
4533 }
drh2edc5fd2015-11-24 02:10:52 +00004534 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004535 if( pA->op==TK_FUNCTION ){
4536 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4537 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00004538 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00004539 }
drh22827922000-06-06 17:27:05 +00004540 }
drh10d1edf2013-11-15 15:52:39 +00004541 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004542 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00004543 if( combinedFlags & EP_xIsSelect ) return 2;
4544 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4545 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4546 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00004547 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00004548 if( pA->iColumn!=pB->iColumn ) return 2;
4549 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004550 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004551 }
4552 }
drh1d9da702010-01-07 15:17:02 +00004553 return 0;
drh22827922000-06-06 17:27:05 +00004554}
4555
drh8c6f6662010-04-26 19:17:26 +00004556/*
4557** Compare two ExprList objects. Return 0 if they are identical and
4558** non-zero if they differ in any way.
4559**
drh619a1302013-08-01 13:04:46 +00004560** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4561** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4562**
drh8c6f6662010-04-26 19:17:26 +00004563** This routine might return non-zero for equivalent ExprLists. The
4564** only consequence will be disabled optimizations. But this routine
4565** must never return 0 if the two ExprList objects are different, or
4566** a malfunction will result.
4567**
4568** Two NULL pointers are considered to be the same. But a NULL pointer
4569** always differs from a non-NULL pointer.
4570*/
drh619a1302013-08-01 13:04:46 +00004571int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004572 int i;
4573 if( pA==0 && pB==0 ) return 0;
4574 if( pA==0 || pB==0 ) return 1;
4575 if( pA->nExpr!=pB->nExpr ) return 1;
4576 for(i=0; i<pA->nExpr; i++){
4577 Expr *pExprA = pA->a[i].pExpr;
4578 Expr *pExprB = pB->a[i].pExpr;
4579 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00004580 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004581 }
4582 return 0;
4583}
drh13449892005-09-07 21:22:45 +00004584
drh22827922000-06-06 17:27:05 +00004585/*
drh4bd5f732013-07-31 23:22:39 +00004586** Return true if we can prove the pE2 will always be true if pE1 is
4587** true. Return false if we cannot complete the proof or if pE2 might
4588** be false. Examples:
4589**
drh619a1302013-08-01 13:04:46 +00004590** pE1: x==5 pE2: x==5 Result: true
4591** pE1: x>0 pE2: x==5 Result: false
4592** pE1: x=21 pE2: x=21 OR y=43 Result: true
4593** pE1: x!=123 pE2: x IS NOT NULL Result: true
4594** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4595** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4596** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004597**
4598** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4599** Expr.iTable<0 then assume a table number given by iTab.
4600**
4601** When in doubt, return false. Returning true might give a performance
4602** improvement. Returning false might cause a performance reduction, but
4603** it will always give the correct answer and is hence always safe.
4604*/
4605int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00004606 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4607 return 1;
4608 }
4609 if( pE2->op==TK_OR
4610 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4611 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4612 ){
4613 return 1;
4614 }
4615 if( pE2->op==TK_NOTNULL
4616 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4617 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4618 ){
4619 return 1;
4620 }
4621 return 0;
drh4bd5f732013-07-31 23:22:39 +00004622}
4623
4624/*
drh030796d2012-08-23 16:18:10 +00004625** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00004626** to determine if an expression can be evaluated by reference to the
4627** index only, without having to do a search for the corresponding
4628** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4629** is the cursor for the table.
4630*/
4631struct IdxCover {
4632 Index *pIdx; /* The index to be tested for coverage */
4633 int iCur; /* Cursor number for the table corresponding to the index */
4634};
4635
4636/*
4637** Check to see if there are references to columns in table
4638** pWalker->u.pIdxCover->iCur can be satisfied using the index
4639** pWalker->u.pIdxCover->pIdx.
4640*/
4641static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4642 if( pExpr->op==TK_COLUMN
4643 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4644 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4645 ){
4646 pWalker->eCode = 1;
4647 return WRC_Abort;
4648 }
4649 return WRC_Continue;
4650}
4651
4652/*
drhe604ec02016-07-27 19:20:58 +00004653** Determine if an index pIdx on table with cursor iCur contains will
4654** the expression pExpr. Return true if the index does cover the
4655** expression and false if the pExpr expression references table columns
4656** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00004657**
4658** An index covering an expression means that the expression can be
4659** evaluated using only the index and without having to lookup the
4660** corresponding table entry.
4661*/
4662int sqlite3ExprCoveredByIndex(
4663 Expr *pExpr, /* The index to be tested */
4664 int iCur, /* The cursor number for the corresponding table */
4665 Index *pIdx /* The index that might be used for coverage */
4666){
4667 Walker w;
4668 struct IdxCover xcov;
4669 memset(&w, 0, sizeof(w));
4670 xcov.iCur = iCur;
4671 xcov.pIdx = pIdx;
4672 w.xExprCallback = exprIdxCover;
4673 w.u.pIdxCover = &xcov;
4674 sqlite3WalkExpr(&w, pExpr);
4675 return !w.eCode;
4676}
4677
4678
4679/*
4680** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00004681** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00004682** aggregate function, in order to implement the
4683** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00004684*/
drh030796d2012-08-23 16:18:10 +00004685struct SrcCount {
4686 SrcList *pSrc; /* One particular FROM clause in a nested query */
4687 int nThis; /* Number of references to columns in pSrcList */
4688 int nOther; /* Number of references to columns in other FROM clauses */
4689};
4690
4691/*
4692** Count the number of references to columns.
4693*/
4694static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00004695 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4696 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4697 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4698 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4699 ** NEVER() will need to be removed. */
4700 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00004701 int i;
drh030796d2012-08-23 16:18:10 +00004702 struct SrcCount *p = pWalker->u.pSrcCount;
4703 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00004704 int nSrc = pSrc ? pSrc->nSrc : 0;
4705 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00004706 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00004707 }
drh655814d2015-01-09 01:27:29 +00004708 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00004709 p->nThis++;
4710 }else{
4711 p->nOther++;
4712 }
drh374fdce2012-04-17 16:38:53 +00004713 }
drh030796d2012-08-23 16:18:10 +00004714 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004715}
4716
4717/*
drh030796d2012-08-23 16:18:10 +00004718** Determine if any of the arguments to the pExpr Function reference
4719** pSrcList. Return true if they do. Also return true if the function
4720** has no arguments or has only constant arguments. Return false if pExpr
4721** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004722*/
drh030796d2012-08-23 16:18:10 +00004723int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004724 Walker w;
drh030796d2012-08-23 16:18:10 +00004725 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004726 assert( pExpr->op==TK_AGG_FUNCTION );
4727 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004728 w.xExprCallback = exprSrcCount;
4729 w.u.pSrcCount = &cnt;
4730 cnt.pSrc = pSrcList;
4731 cnt.nThis = 0;
4732 cnt.nOther = 0;
4733 sqlite3WalkExprList(&w, pExpr->x.pList);
4734 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004735}
4736
4737/*
drh13449892005-09-07 21:22:45 +00004738** Add a new element to the pAggInfo->aCol[] array. Return the index of
4739** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004740*/
drh17435752007-08-16 04:30:38 +00004741static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004742 int i;
drhcf643722007-03-27 13:36:37 +00004743 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004744 db,
drhcf643722007-03-27 13:36:37 +00004745 pInfo->aCol,
4746 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004747 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004748 &i
4749 );
drh13449892005-09-07 21:22:45 +00004750 return i;
4751}
4752
4753/*
4754** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4755** the new element. Return a negative number if malloc fails.
4756*/
drh17435752007-08-16 04:30:38 +00004757static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004758 int i;
drhcf643722007-03-27 13:36:37 +00004759 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004760 db,
drhcf643722007-03-27 13:36:37 +00004761 pInfo->aFunc,
4762 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004763 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004764 &i
4765 );
drh13449892005-09-07 21:22:45 +00004766 return i;
4767}
drh22827922000-06-06 17:27:05 +00004768
4769/*
drh7d10d5a2008-08-20 16:35:10 +00004770** This is the xExprCallback for a tree walker. It is used to
4771** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004772** for additional information.
drh22827922000-06-06 17:27:05 +00004773*/
drh7d10d5a2008-08-20 16:35:10 +00004774static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004775 int i;
drh7d10d5a2008-08-20 16:35:10 +00004776 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004777 Parse *pParse = pNC->pParse;
4778 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004779 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004780
drh22827922000-06-06 17:27:05 +00004781 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004782 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004783 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004784 testcase( pExpr->op==TK_AGG_COLUMN );
4785 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004786 /* Check to see if the column is in one of the tables in the FROM
4787 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004788 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004789 struct SrcList_item *pItem = pSrcList->a;
4790 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4791 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004792 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004793 if( pExpr->iTable==pItem->iCursor ){
4794 /* If we reach this point, it means that pExpr refers to a table
4795 ** that is in the FROM clause of the aggregate query.
4796 **
4797 ** Make an entry for the column in pAggInfo->aCol[] if there
4798 ** is not an entry there already.
4799 */
drh7f906d62007-03-12 23:48:52 +00004800 int k;
drh13449892005-09-07 21:22:45 +00004801 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004802 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004803 if( pCol->iTable==pExpr->iTable &&
4804 pCol->iColumn==pExpr->iColumn ){
4805 break;
4806 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004807 }
danielk19771e536952007-08-16 10:09:01 +00004808 if( (k>=pAggInfo->nColumn)
4809 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4810 ){
drh7f906d62007-03-12 23:48:52 +00004811 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004812 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004813 pCol->iTable = pExpr->iTable;
4814 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004815 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004816 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004817 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004818 if( pAggInfo->pGroupBy ){
4819 int j, n;
4820 ExprList *pGB = pAggInfo->pGroupBy;
4821 struct ExprList_item *pTerm = pGB->a;
4822 n = pGB->nExpr;
4823 for(j=0; j<n; j++, pTerm++){
4824 Expr *pE = pTerm->pExpr;
4825 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4826 pE->iColumn==pExpr->iColumn ){
4827 pCol->iSorterColumn = j;
4828 break;
4829 }
4830 }
4831 }
4832 if( pCol->iSorterColumn<0 ){
4833 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4834 }
4835 }
4836 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4837 ** because it was there before or because we just created it).
4838 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4839 ** pAggInfo->aCol[] entry.
4840 */
drhebb6a652013-09-12 23:42:22 +00004841 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004842 pExpr->pAggInfo = pAggInfo;
4843 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004844 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004845 break;
4846 } /* endif pExpr->iTable==pItem->iCursor */
4847 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004848 }
drh7d10d5a2008-08-20 16:35:10 +00004849 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004850 }
4851 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004852 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004853 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004854 ){
drh13449892005-09-07 21:22:45 +00004855 /* Check to see if pExpr is a duplicate of another aggregate
4856 ** function that is already in the pAggInfo structure
4857 */
4858 struct AggInfo_func *pItem = pAggInfo->aFunc;
4859 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004860 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004861 break;
4862 }
drh22827922000-06-06 17:27:05 +00004863 }
drh13449892005-09-07 21:22:45 +00004864 if( i>=pAggInfo->nFunc ){
4865 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4866 */
danielk197714db2662006-01-09 16:12:04 +00004867 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004868 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004869 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004870 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004871 pItem = &pAggInfo->aFunc[i];
4872 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004873 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004874 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004875 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004876 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004877 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004878 if( pExpr->flags & EP_Distinct ){
4879 pItem->iDistinct = pParse->nTab++;
4880 }else{
4881 pItem->iDistinct = -1;
4882 }
drh13449892005-09-07 21:22:45 +00004883 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004884 }
drh13449892005-09-07 21:22:45 +00004885 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4886 */
drhc5cd1242013-09-12 16:50:49 +00004887 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004888 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004889 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004890 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004891 return WRC_Prune;
4892 }else{
4893 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004894 }
drh22827922000-06-06 17:27:05 +00004895 }
4896 }
drh7d10d5a2008-08-20 16:35:10 +00004897 return WRC_Continue;
4898}
4899static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004900 UNUSED_PARAMETER(pWalker);
4901 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004902 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004903}
4904
4905/*
drhe8abb4c2012-11-02 18:24:57 +00004906** Analyze the pExpr expression looking for aggregate functions and
4907** for variables that need to be added to AggInfo object that pNC->pAggInfo
4908** points to. Additional entries are made on the AggInfo object as
4909** necessary.
drh626a8792005-01-17 22:08:19 +00004910**
4911** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004912** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004913*/
drhd2b3e232008-01-23 14:51:49 +00004914void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004915 Walker w;
drh374fdce2012-04-17 16:38:53 +00004916 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004917 w.xExprCallback = analyzeAggregate;
4918 w.xSelectCallback = analyzeAggregatesInSelect;
4919 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004920 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004921 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004922}
drh5d9a4af2005-08-30 00:54:01 +00004923
4924/*
4925** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4926** expression list. Return the number of errors.
4927**
4928** If an error is found, the analysis is cut short.
4929*/
drhd2b3e232008-01-23 14:51:49 +00004930void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004931 struct ExprList_item *pItem;
4932 int i;
drh5d9a4af2005-08-30 00:54:01 +00004933 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004934 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4935 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004936 }
4937 }
drh5d9a4af2005-08-30 00:54:01 +00004938}
drh892d3172008-01-10 03:46:36 +00004939
4940/*
drhceea3322009-04-23 13:22:42 +00004941** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004942*/
4943int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004944 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004945 return ++pParse->nMem;
4946 }
danielk19772f425f62008-07-04 09:41:39 +00004947 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004948}
drhceea3322009-04-23 13:22:42 +00004949
4950/*
4951** Deallocate a register, making available for reuse for some other
4952** purpose.
4953**
4954** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004955** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004956** the register becomes stale.
4957*/
drh892d3172008-01-10 03:46:36 +00004958void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004959 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004960 int i;
4961 struct yColCache *p;
4962 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4963 if( p->iReg==iReg ){
4964 p->tempReg = 1;
4965 return;
4966 }
4967 }
drh892d3172008-01-10 03:46:36 +00004968 pParse->aTempReg[pParse->nTempReg++] = iReg;
4969 }
4970}
4971
4972/*
4973** Allocate or deallocate a block of nReg consecutive registers
4974*/
4975int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004976 int i, n;
4977 i = pParse->iRangeReg;
4978 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004979 if( nReg<=n ){
4980 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004981 pParse->iRangeReg += nReg;
4982 pParse->nRangeReg -= nReg;
4983 }else{
4984 i = pParse->nMem+1;
4985 pParse->nMem += nReg;
4986 }
4987 return i;
4988}
4989void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004990 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004991 if( nReg>pParse->nRangeReg ){
4992 pParse->nRangeReg = nReg;
4993 pParse->iRangeReg = iReg;
4994 }
4995}
drhcdc69552011-12-06 13:24:59 +00004996
4997/*
4998** Mark all temporary registers as being unavailable for reuse.
4999*/
5000void sqlite3ClearTempRegCache(Parse *pParse){
5001 pParse->nTempReg = 0;
5002 pParse->nRangeReg = 0;
5003}
drhbb9b5f22016-03-19 00:35:02 +00005004
5005/*
5006** Validate that no temporary register falls within the range of
5007** iFirst..iLast, inclusive. This routine is only call from within assert()
5008** statements.
5009*/
5010#ifdef SQLITE_DEBUG
5011int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5012 int i;
5013 if( pParse->nRangeReg>0
5014 && pParse->iRangeReg+pParse->nRangeReg<iLast
5015 && pParse->iRangeReg>=iFirst
5016 ){
5017 return 0;
5018 }
5019 for(i=0; i<pParse->nTempReg; i++){
5020 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5021 return 0;
5022 }
5023 }
5024 return 1;
5025}
5026#endif /* SQLITE_DEBUG */