blob: 56affdfeaa2a63ef86a61edd60937f2c94adae4b [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 ){
drh7d176102014-02-18 03:07:12 +00002155 int iAddr = sqlite3CodeOnce(pParse);
2156 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002157
2158 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2159 eType = IN_INDEX_ROWID;
2160
2161 sqlite3VdbeJumpHere(v, iAddr);
2162 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002163 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002164 int affinity_ok = 1;
2165 int i;
2166
2167 /* Check that the affinity that will be used to perform each
2168 ** comparison is the same as the affinity of each column. If
2169 ** it not, it is not possible to use any index. */
2170 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002171 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002172 int iCol = pEList->a[i].pExpr->iColumn;
2173 char idxaff = pTab->aCol[iCol].affinity;
2174 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2175 switch( cmpaff ){
2176 case SQLITE_AFF_BLOB:
2177 break;
2178 case SQLITE_AFF_TEXT:
2179 affinity_ok = (idxaff==SQLITE_AFF_TEXT);
2180 break;
2181 default:
2182 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2183 }
2184 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002185
drhb74b1012009-05-28 21:04:37 +00002186 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00002187 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00002188 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00002189
2190 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
dancfbb5e82016-07-13 19:48:13 +00002191 if( pIdx->nKeyCol<nExpr ) continue;
2192 if( mustBeUnique && (pIdx->nKeyCol!=nExpr || !IsUniqueIndex(pIdx)) ){
2193 continue;
2194 }
2195
2196 for(i=0; i<nExpr; i++){
drhfc7f27b2016-08-20 00:07:01 +00002197 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002198 Expr *pRhs = pEList->a[i].pExpr;
2199 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2200 int j;
2201
dan17994e32016-08-11 12:01:52 +00002202 assert( pReq || pParse->nErr );
2203 if( pReq==0 ) break;
2204
dancfbb5e82016-07-13 19:48:13 +00002205 for(j=0; j<nExpr; j++){
2206 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2207 assert( pIdx->azColl[j] );
2208 if( sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ) continue;
2209 break;
2210 }
2211 if( j==nExpr ) break;
danba00e302016-07-23 20:24:06 +00002212 if( aiMap ) aiMap[i] = j;
dancfbb5e82016-07-13 19:48:13 +00002213 }
2214
2215 if( i==nExpr ){
drh7d176102014-02-18 03:07:12 +00002216 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00002217 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2218 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00002219 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00002220 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2221 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00002222
dan7b35a772016-07-28 19:47:15 +00002223 if( prRhsHasNull ){
2224 *prRhsHasNull = ++pParse->nMem;
dan3480bfd2016-06-16 17:14:02 +00002225#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
dancfbb5e82016-07-13 19:48:13 +00002226 i64 mask = (1<<nExpr)-1;
dan3480bfd2016-06-16 17:14:02 +00002227 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
dancfbb5e82016-07-13 19:48:13 +00002228 iTab, 0, 0, (u8*)&mask, P4_INT64);
dan3480bfd2016-06-16 17:14:02 +00002229#endif
dan7b35a772016-07-28 19:47:15 +00002230 if( nExpr==1 ){
2231 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2232 }
danielk19770cdc0222008-06-26 18:04:03 +00002233 }
drh552fd452014-02-18 01:07:38 +00002234 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00002235 }
2236 }
2237 }
2238 }
2239
drhbb53ecb2014-08-02 21:03:33 +00002240 /* If no preexisting index is available for the IN clause
2241 ** and IN_INDEX_NOOP is an allowed reply
2242 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002243 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002244 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002245 ** the IN operator so return IN_INDEX_NOOP.
2246 */
2247 if( eType==0
2248 && (inFlags & IN_INDEX_NOOP_OK)
2249 && !ExprHasProperty(pX, EP_xIsSelect)
2250 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2251 ){
2252 eType = IN_INDEX_NOOP;
2253 }
drhbb53ecb2014-08-02 21:03:33 +00002254
danielk19779a96b662007-11-29 17:05:18 +00002255 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002256 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002257 ** We will have to generate an ephemeral table to do the job.
2258 */
drh8e23daf2013-06-11 13:30:04 +00002259 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002260 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002261 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002262 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002263 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00002264 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00002265 eType = IN_INDEX_ROWID;
2266 }
drhe21a6e12014-08-01 18:00:24 +00002267 }else if( prRhsHasNull ){
2268 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002269 }
danielk197741a05b72008-10-02 13:50:55 +00002270 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002271 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002272 }else{
2273 pX->iTable = iTab;
2274 }
danba00e302016-07-23 20:24:06 +00002275
2276 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2277 int i, n;
2278 n = sqlite3ExprVectorSize(pX->pLeft);
2279 for(i=0; i<n; i++) aiMap[i] = i;
2280 }
danielk19779a96b662007-11-29 17:05:18 +00002281 return eType;
2282}
danielk1977284f4ac2007-12-10 05:03:46 +00002283#endif
drh626a8792005-01-17 22:08:19 +00002284
danf9b2e052016-08-02 17:45:00 +00002285#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002286/*
2287** Argument pExpr is an (?, ?...) IN(...) expression. This
2288** function allocates and returns a nul-terminated string containing
2289** the affinities to be used for each column of the comparison.
2290**
2291** It is the responsibility of the caller to ensure that the returned
2292** string is eventually freed using sqlite3DbFree().
2293*/
dan71c57db2016-07-09 20:23:55 +00002294static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2295 Expr *pLeft = pExpr->pLeft;
2296 int nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002297 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002298 char *zRet;
2299
dan553168c2016-08-01 20:14:31 +00002300 assert( pExpr->op==TK_IN );
dan71c57db2016-07-09 20:23:55 +00002301 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2302 if( zRet ){
2303 int i;
2304 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002305 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002306 char a = sqlite3ExprAffinity(pA);
2307 if( pSelect ){
2308 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2309 }else{
2310 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002311 }
dan71c57db2016-07-09 20:23:55 +00002312 }
2313 zRet[nVal] = '\0';
2314 }
2315 return zRet;
2316}
danf9b2e052016-08-02 17:45:00 +00002317#endif
dan71c57db2016-07-09 20:23:55 +00002318
dan8da209b2016-07-26 18:06:08 +00002319#ifndef SQLITE_OMIT_SUBQUERY
2320/*
2321** Load the Parse object passed as the first argument with an error
2322** message of the form:
2323**
2324** "sub-select returns N columns - expected M"
2325*/
2326void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2327 const char *zFmt = "sub-select returns %d columns - expected %d";
2328 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2329}
2330#endif
2331
drh626a8792005-01-17 22:08:19 +00002332/*
drhd4187c72010-08-30 22:15:45 +00002333** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2334** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002335**
drh9cbe6352005-11-29 03:13:21 +00002336** (SELECT a FROM b) -- subquery
2337** EXISTS (SELECT a FROM b) -- EXISTS subquery
2338** x IN (4,5,11) -- IN operator with list on right-hand side
2339** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002340**
drh9cbe6352005-11-29 03:13:21 +00002341** The pExpr parameter describes the expression that contains the IN
2342** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002343**
2344** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2345** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2346** to some integer key column of a table B-Tree. In this case, use an
2347** intkey B-Tree to store the set of IN(...) values instead of the usual
2348** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002349**
2350** If rMayHaveNull is non-zero, that means that the operation is an IN
2351** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002352** All this routine does is initialize the register given by rMayHaveNull
2353** to NULL. Calling routines will take care of changing this register
2354** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002355**
2356** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002357** result. For a multi-column SELECT, the result is stored in a contiguous
2358** array of registers and the return value is the register of the left-most
2359** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002360*/
drh51522cd2005-01-20 13:36:19 +00002361#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002362int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002363 Parse *pParse, /* Parsing context */
2364 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002365 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002366 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002367){
drh6be515e2014-08-01 21:00:53 +00002368 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002369 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002370 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002371 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00002372 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002373
drh39a11812016-08-19 19:12:58 +00002374 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2375 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002376 **
2377 ** * The right-hand side is a correlated subquery
2378 ** * The right-hand side is an expression list containing variables
2379 ** * We are inside a trigger
2380 **
2381 ** If all of the above are false, then we can run this code just once
2382 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002383 */
drhc5cd1242013-09-12 16:50:49 +00002384 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00002385 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002386 }
2387
dan4a07e3d2010-11-09 14:48:59 +00002388#ifndef SQLITE_OMIT_EXPLAIN
2389 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00002390 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2391 jmpIfDynamic>=0?"":"CORRELATED ",
2392 pExpr->op==TK_IN?"LIST":"SCALAR",
2393 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00002394 );
2395 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2396 }
2397#endif
2398
drhcce7d172000-05-31 15:34:51 +00002399 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002400 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002401 int addr; /* Address of OP_OpenEphemeral instruction */
2402 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002403 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002404 int nVal; /* Size of vector pLeft */
2405
2406 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002407 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002408
2409 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002410 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002411 ** filled with index keys representing the results from the
2412 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002413 **
2414 ** If the 'x' expression is a column value, or the SELECT...
2415 ** statement returns a column value, then the affinity of that
2416 ** column is used to build the index keys. If both 'x' and the
2417 ** SELECT... statement are columns, then numeric affinity is used
2418 ** if either column has NUMERIC or INTEGER affinity. If neither
2419 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2420 ** is used.
2421 */
2422 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002423 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2424 pExpr->iTable, (isRowid?0:nVal));
2425 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002426
danielk19776ab3a2e2009-02-19 14:39:25 +00002427 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00002428 /* Case 1: expr IN (SELECT ...)
2429 **
danielk1977e014a832004-05-17 10:48:57 +00002430 ** Generate code to write the results of the select into the temporary
2431 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002432 */
drh43870062014-07-31 15:44:44 +00002433 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002434 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002435
danielk197741a05b72008-10-02 13:50:55 +00002436 assert( !isRowid );
dan71c57db2016-07-09 20:23:55 +00002437 if( pEList->nExpr!=nVal ){
dan8da209b2016-07-26 18:06:08 +00002438 sqlite3SubselectError(pParse, pEList->nExpr, nVal);
dan71c57db2016-07-09 20:23:55 +00002439 }else{
2440 SelectDest dest;
2441 int i;
2442 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2443 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2444 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2445 pSelect->iLimit = 0;
2446 testcase( pSelect->selFlags & SF_Distinct );
2447 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2448 if( sqlite3Select(pParse, pSelect, &dest) ){
2449 sqlite3DbFree(pParse->db, dest.zAffSdst);
2450 sqlite3KeyInfoUnref(pKeyInfo);
2451 return 0;
2452 }
2453 sqlite3DbFree(pParse->db, dest.zAffSdst);
2454 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2455 assert( pEList!=0 );
2456 assert( pEList->nExpr>0 );
2457 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2458 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002459 Expr *p = (nVal>1) ? sqlite3VectorFieldSubexpr(pLeft, i) : pLeft;
dan71c57db2016-07-09 20:23:55 +00002460 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2461 pParse, p, pEList->a[i].pExpr
2462 );
2463 }
drh94ccde52007-04-13 16:06:32 +00002464 }
drha7d2db12010-07-14 20:23:52 +00002465 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002466 /* Case 2: expr IN (exprlist)
2467 **
drhfd131da2007-08-07 17:13:03 +00002468 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002469 ** store it in the temporary table. If <expr> is a column, then use
2470 ** that columns affinity when building index keys. If <expr> is not
2471 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002472 */
dan71c57db2016-07-09 20:23:55 +00002473 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002474 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002475 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002476 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002477 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002478
dan71c57db2016-07-09 20:23:55 +00002479 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002480 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002481 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002482 }
drh323df792013-08-05 19:11:29 +00002483 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002484 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002485 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2486 }
danielk1977e014a832004-05-17 10:48:57 +00002487
2488 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002489 r1 = sqlite3GetTempReg(pParse);
2490 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002491 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002492 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2493 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002494 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002495
drh57dbd7b2005-07-08 18:25:26 +00002496 /* If the expression is not constant then we will need to
2497 ** disable the test that was generated above that makes sure
2498 ** this code only executes once. Because for a non-constant
2499 ** expression we need to rerun this code each time.
2500 */
drh6be515e2014-08-01 21:00:53 +00002501 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2502 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2503 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002504 }
danielk1977e014a832004-05-17 10:48:57 +00002505
2506 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002507 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2508 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002509 }else{
drhe05c9292009-10-29 13:48:10 +00002510 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2511 if( isRowid ){
2512 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2513 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002514 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002515 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2516 }else{
2517 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2518 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2519 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2520 }
danielk197741a05b72008-10-02 13:50:55 +00002521 }
drhfef52082000-06-06 01:50:43 +00002522 }
drh2d401ab2008-01-10 23:50:11 +00002523 sqlite3ReleaseTempReg(pParse, r1);
2524 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002525 }
drh323df792013-08-05 19:11:29 +00002526 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002527 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002528 }
danielk1977b3bce662005-01-29 08:32:43 +00002529 break;
drhfef52082000-06-06 01:50:43 +00002530 }
2531
drh51522cd2005-01-20 13:36:19 +00002532 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002533 case TK_SELECT:
2534 default: {
drh39a11812016-08-19 19:12:58 +00002535 /* Case 3: (SELECT ... FROM ...)
2536 ** or: EXISTS(SELECT ... FROM ...)
2537 **
2538 ** For a SELECT, generate code to put the values for all columns of
2539 ** the first row into an array of registers and return the index of
2540 ** the first register.
2541 **
2542 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2543 ** into a register and return that register number.
2544 **
2545 ** In both cases, the query is augmented with "LIMIT 1". Any
2546 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002547 */
drhfd773cf2009-05-29 14:39:07 +00002548 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002549 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002550 int nReg; /* Registers to allocate */
drh1398ad32005-01-19 23:24:50 +00002551
shanecf697392009-06-01 16:53:09 +00002552 testcase( pExpr->op==TK_EXISTS );
2553 testcase( pExpr->op==TK_SELECT );
2554 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
danielk19776ab3a2e2009-02-19 14:39:25 +00002555 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
dan71c57db2016-07-09 20:23:55 +00002556
danielk19776ab3a2e2009-02-19 14:39:25 +00002557 pSel = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002558 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2559 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2560 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002561 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002562 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002563 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002564 dest.nSdst = nReg;
2565 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002566 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002567 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002568 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002569 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002570 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002571 }
drh633e6d52008-07-28 19:34:53 +00002572 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002573 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2574 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002575 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002576 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002577 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002578 return 0;
drh94ccde52007-04-13 16:06:32 +00002579 }
drh2b596da2012-07-23 21:43:19 +00002580 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002581 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002582 break;
drhcce7d172000-05-31 15:34:51 +00002583 }
2584 }
danielk1977b3bce662005-01-29 08:32:43 +00002585
drh6be515e2014-08-01 21:00:53 +00002586 if( rHasNullFlag ){
2587 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002588 }
drh6be515e2014-08-01 21:00:53 +00002589
2590 if( jmpIfDynamic>=0 ){
2591 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002592 }
drhd2490902014-04-13 19:28:15 +00002593 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002594
drh1450bc62009-10-30 13:25:56 +00002595 return rReg;
drhcce7d172000-05-31 15:34:51 +00002596}
drh51522cd2005-01-20 13:36:19 +00002597#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002598
drhe3365e62009-11-12 17:52:24 +00002599#ifndef SQLITE_OMIT_SUBQUERY
2600/*
dan7b35a772016-07-28 19:47:15 +00002601** Expr pIn is an IN(...) expression. This function checks that the
2602** sub-select on the RHS of the IN() operator has the same number of
2603** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2604** a sub-query, that the LHS is a vector of size 1.
2605*/
2606int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2607 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2608 if( (pIn->flags & EP_xIsSelect) ){
2609 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2610 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2611 return 1;
2612 }
2613 }else if( nVector!=1 ){
2614 if( (pIn->pLeft->flags & EP_xIsSelect) ){
2615 sqlite3SubselectError(pParse, nVector, 1);
2616 }else{
drhe835bc12016-08-23 19:02:55 +00002617 sqlite3ErrorMsg(pParse, "row value misused");
dan7b35a772016-07-28 19:47:15 +00002618 }
2619 return 1;
2620 }
2621 return 0;
2622}
2623#endif
2624
2625#ifndef SQLITE_OMIT_SUBQUERY
2626/*
drhe3365e62009-11-12 17:52:24 +00002627** Generate code for an IN expression.
2628**
2629** x IN (SELECT ...)
2630** x IN (value, value, ...)
2631**
2632** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
2633** is an array of zero or more values. The expression is true if the LHS is
2634** contained within the RHS. The value of the expression is unknown (NULL)
2635** if the LHS is NULL or if the LHS is not contained within the RHS and the
2636** RHS contains one or more NULL values.
2637**
drh6be515e2014-08-01 21:00:53 +00002638** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002639** contained within the RHS. If due to NULLs we cannot determine if the LHS
2640** is contained in the RHS then jump to destIfNull. If the LHS is contained
2641** within the RHS then fall through.
2642*/
2643static void sqlite3ExprCodeIN(
2644 Parse *pParse, /* Parsing and code generating context */
2645 Expr *pExpr, /* The IN expression */
2646 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2647 int destIfNull /* Jump here if the results are unknown due to NULLs */
2648){
2649 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002650 int eType; /* Type of the RHS */
drh12abf402016-08-22 14:30:05 +00002651 int r1, r2; /* Temporary use registers */
drhe3365e62009-11-12 17:52:24 +00002652 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002653 int *aiMap = 0; /* Map from vector field to index column */
2654 char *zAff = 0; /* Affinity string for comparisons */
2655 int nVector; /* Size of vectors for this IN(...) op */
drh12abf402016-08-22 14:30:05 +00002656 int iDummy; /* Dummy parameter to exprCodeVector() */
danba00e302016-07-23 20:24:06 +00002657 Expr *pLeft = pExpr->pLeft;
2658 int i;
drhe3365e62009-11-12 17:52:24 +00002659
dan7b35a772016-07-28 19:47:15 +00002660 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00002661 zAff = exprINAffinity(pParse, pExpr);
drha48d7e72016-08-12 11:01:20 +00002662 if( zAff==0 ) return;
danba00e302016-07-23 20:24:06 +00002663 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2664 aiMap = (int*)sqlite3DbMallocZero(
2665 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2666 );
drha48d7e72016-08-12 11:01:20 +00002667 if( aiMap==0 ){
2668 sqlite3DbFree(pParse->db, zAff);
dan553168c2016-08-01 20:14:31 +00002669 return;
2670 }
dan7b35a772016-07-28 19:47:15 +00002671
danba00e302016-07-23 20:24:06 +00002672 /* Attempt to compute the RHS. After this step, if anything other than
2673 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2674 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2675 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00002676 v = pParse->pVdbe;
2677 assert( v!=0 ); /* OOM detected prior to this routine */
2678 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002679 eType = sqlite3FindInIndex(pParse, pExpr,
2680 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00002681 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00002682
danba00e302016-07-23 20:24:06 +00002683 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2684 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2685 );
drhe3365e62009-11-12 17:52:24 +00002686
danba00e302016-07-23 20:24:06 +00002687 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2688 ** vector, then it is stored in an array of nVector registers starting
2689 ** at r1.
drhe3365e62009-11-12 17:52:24 +00002690 */
danba00e302016-07-23 20:24:06 +00002691 r1 = sqlite3GetTempRange(pParse, nVector);
drhe3365e62009-11-12 17:52:24 +00002692 sqlite3ExprCachePush(pParse);
drh12abf402016-08-22 14:30:05 +00002693 r2 = exprCodeVector(pParse, pLeft, &iDummy);
2694 for(i=0; i<nVector; i++){
2695 sqlite3VdbeAddOp3(v, OP_Copy, r2+i, r1+aiMap[i], 0);
danba00e302016-07-23 20:24:06 +00002696 }
drhe3365e62009-11-12 17:52:24 +00002697
drhbb53ecb2014-08-02 21:03:33 +00002698 /* If sqlite3FindInIndex() did not find or create an index that is
2699 ** suitable for evaluating the IN operator, then evaluate using a
2700 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002701 */
drhbb53ecb2014-08-02 21:03:33 +00002702 if( eType==IN_INDEX_NOOP ){
2703 ExprList *pList = pExpr->x.pList;
2704 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2705 int labelOk = sqlite3VdbeMakeLabel(v);
2706 int r2, regToFree;
2707 int regCkNull = 0;
2708 int ii;
2709 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002710 if( destIfNull!=destIfFalse ){
2711 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002712 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002713 }
2714 for(ii=0; ii<pList->nExpr; ii++){
2715 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002716 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002717 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2718 }
2719 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2720 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002721 (void*)pColl, P4_COLLSEQ);
2722 VdbeCoverageIf(v, ii<pList->nExpr-1);
2723 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00002724 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00002725 }else{
2726 assert( destIfNull==destIfFalse );
2727 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2728 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00002729 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00002730 }
2731 sqlite3ReleaseTempReg(pParse, regToFree);
2732 }
2733 if( regCkNull ){
2734 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002735 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002736 }
2737 sqlite3VdbeResolveLabel(v, labelOk);
2738 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002739 }else{
drhbb53ecb2014-08-02 21:03:33 +00002740
dan7b35a772016-07-28 19:47:15 +00002741 /* If any value on the LHS is NULL, the result of the IN(...) operator
2742 ** must be either false or NULL. If these two are handled identically,
2743 ** test the LHS for NULLs and jump directly to destIfNull if any are
2744 ** found.
2745 **
2746 ** Otherwise, if NULL and false are handled differently, and the
2747 ** IN(...) operation is not a vector operation, and the LHS of the
2748 ** operator is NULL, then the result is false if the index is
2749 ** completely empty, or NULL otherwise. */
dand49fd4e2016-07-27 19:33:04 +00002750 if( destIfNull==destIfFalse ){
2751 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002752 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dand49fd4e2016-07-27 19:33:04 +00002753 if( sqlite3ExprCanBeNull(p) ){
2754 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002755 VdbeCoverage(v);
dand49fd4e2016-07-27 19:33:04 +00002756 }
drh7248a8b2014-08-04 18:50:54 +00002757 }
dand49fd4e2016-07-27 19:33:04 +00002758 }else if( nVector==1 && sqlite3ExprCanBeNull(pExpr->pLeft) ){
2759 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2760 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2761 VdbeCoverage(v);
2762 sqlite3VdbeGoto(v, destIfNull);
2763 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002764 }
2765
2766 if( eType==IN_INDEX_ROWID ){
dan7b35a772016-07-28 19:47:15 +00002767 /* In this case, the RHS is the ROWID of table b-tree */
drheeb95652016-05-26 20:56:38 +00002768 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002769 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002770 }else{
dan7b35a772016-07-28 19:47:15 +00002771 /* In this case, the RHS is an index b-tree. Apply the comparison
2772 ** affinities to each value on the LHS of the operator. */
danba00e302016-07-23 20:24:06 +00002773 sqlite3VdbeAddOp4(v, OP_Affinity, r1, nVector, 0, zAff, nVector);
dan7b35a772016-07-28 19:47:15 +00002774
2775 if( nVector>1 && destIfNull!=destIfFalse ){
2776 int iIdx = pExpr->iTable;
2777 int addr;
2778 int addrNext;
2779
2780 /* Search the index for the key. */
2781 addr = sqlite3VdbeAddOp4Int(v, OP_Found, iIdx, 0, r1, nVector);
drh471b4b92016-08-12 11:25:49 +00002782 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002783
2784 /* At this point the specified key is not present in the index,
2785 ** so the result of the IN(..) operator must be either NULL or
2786 ** 0. The vdbe code generated below figures out which. */
2787 addrNext = 1+sqlite3VdbeAddOp2(v, OP_Rewind, iIdx, destIfFalse);
drh471b4b92016-08-12 11:25:49 +00002788 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002789
2790 for(i=0; i<nVector; i++){
2791 Expr *p;
2792 CollSeq *pColl;
2793 int r2 = sqlite3GetTempReg(pParse);
drhfc7f27b2016-08-20 00:07:01 +00002794 p = sqlite3VectorFieldSubexpr(pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002795 pColl = sqlite3ExprCollSeq(pParse, p);
2796
2797 sqlite3VdbeAddOp3(v, OP_Column, iIdx, i, r2);
2798 sqlite3VdbeAddOp4(v, OP_Eq, r1+i, 0, r2, (void*)pColl,P4_COLLSEQ);
2799 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh471b4b92016-08-12 11:25:49 +00002800 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002801 sqlite3VdbeAddOp2(v, OP_Next, iIdx, addrNext);
drh471b4b92016-08-12 11:25:49 +00002802 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002803 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2804 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-3);
2805 sqlite3ReleaseTempReg(pParse, r2);
2806 }
2807 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
2808
2809 /* The key was found in the index. If it contains any NULL values,
2810 ** then the result of the IN(...) operator is NULL. Otherwise, the
2811 ** result is 1. */
2812 sqlite3VdbeJumpHere(v, addr);
2813 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002814 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002815 if( sqlite3ExprCanBeNull(p) ){
2816 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002817 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002818 }
2819 }
2820
2821 }else if( rRhsHasNull==0 ){
drhbb53ecb2014-08-02 21:03:33 +00002822 /* This branch runs if it is known at compile time that the RHS
dan7b35a772016-07-28 19:47:15 +00002823 ** cannot contain NULL values. This happens as a result
2824 ** of "NOT NULL" constraints in the database schema.
drhbb53ecb2014-08-02 21:03:33 +00002825 **
2826 ** Also run this branch if NULL is equivalent to FALSE
dan7b35a772016-07-28 19:47:15 +00002827 ** for this particular IN operator. */
danba00e302016-07-23 20:24:06 +00002828 sqlite3VdbeAddOp4Int(
2829 v, OP_NotFound, pExpr->iTable, destIfFalse, r1, nVector
2830 );
drhbb53ecb2014-08-02 21:03:33 +00002831 VdbeCoverage(v);
2832 }else{
2833 /* In this branch, the RHS of the IN might contain a NULL and
2834 ** the presence of a NULL on the RHS makes a difference in the
2835 ** outcome.
2836 */
drh728e0f92015-10-10 14:41:28 +00002837 int addr1;
dan7b35a772016-07-28 19:47:15 +00002838
drhbb53ecb2014-08-02 21:03:33 +00002839 /* First check to see if the LHS is contained in the RHS. If so,
2840 ** then the answer is TRUE the presence of NULLs in the RHS does
2841 ** not matter. If the LHS is not contained in the RHS, then the
2842 ** answer is NULL if the RHS contains NULLs and the answer is
2843 ** FALSE if the RHS is NULL-free.
2844 */
drh728e0f92015-10-10 14:41:28 +00002845 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002846 VdbeCoverage(v);
2847 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2848 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002849 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002850 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002851 }
drhe3365e62009-11-12 17:52:24 +00002852 }
drhe3365e62009-11-12 17:52:24 +00002853 }
2854 sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002855 sqlite3ExprCachePop(pParse);
danba00e302016-07-23 20:24:06 +00002856 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00002857 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00002858 VdbeComment((v, "end IN expr"));
2859}
2860#endif /* SQLITE_OMIT_SUBQUERY */
2861
drh13573c72010-01-12 17:04:07 +00002862#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002863/*
2864** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002865** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002866**
2867** The z[] string will probably not be zero-terminated. But the
2868** z[n] character is guaranteed to be something that does not look
2869** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002870*/
drhb7916a72009-05-27 10:31:29 +00002871static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002872 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002873 double value;
drh9339da12010-09-30 00:50:49 +00002874 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002875 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2876 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002877 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002878 }
2879}
drh13573c72010-01-12 17:04:07 +00002880#endif
drh598f1342007-10-23 15:39:45 +00002881
2882
2883/*
drhfec19aa2004-05-19 20:41:03 +00002884** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002885** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002886**
shaneh5f1d6b62010-09-30 16:51:25 +00002887** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002888*/
drh13573c72010-01-12 17:04:07 +00002889static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2890 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002891 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002892 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002893 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002894 if( negFlag ) i = -i;
2895 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002896 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002897 int c;
2898 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002899 const char *z = pExpr->u.zToken;
2900 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002901 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002902 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002903 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002904 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002905 }else{
drh13573c72010-01-12 17:04:07 +00002906#ifdef SQLITE_OMIT_FLOATING_POINT
2907 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2908#else
drh1b7ddc52014-07-23 14:52:05 +00002909#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002910 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2911 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002912 }else
2913#endif
2914 {
drh9296c182014-07-23 13:40:49 +00002915 codeReal(v, z, negFlag, iMem);
2916 }
drh13573c72010-01-12 17:04:07 +00002917#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002918 }
drhfec19aa2004-05-19 20:41:03 +00002919 }
2920}
2921
drhbea119c2016-04-11 18:15:37 +00002922#if defined(SQLITE_DEBUG)
2923/*
2924** Verify the consistency of the column cache
2925*/
2926static int cacheIsValid(Parse *pParse){
2927 int i, n;
2928 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2929 if( pParse->aColCache[i].iReg>0 ) n++;
2930 }
2931 return n==pParse->nColCache;
2932}
2933#endif
2934
drhceea3322009-04-23 13:22:42 +00002935/*
2936** Clear a cache entry.
2937*/
2938static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2939 if( p->tempReg ){
2940 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2941 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2942 }
2943 p->tempReg = 0;
2944 }
drhbea119c2016-04-11 18:15:37 +00002945 p->iReg = 0;
2946 pParse->nColCache--;
danee65eea2016-04-16 15:03:20 +00002947 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002948}
2949
2950
2951/*
2952** Record in the column cache that a particular column from a
2953** particular table is stored in a particular register.
2954*/
2955void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2956 int i;
2957 int minLru;
2958 int idxLru;
2959 struct yColCache *p;
2960
dance8f53d2015-01-21 17:00:57 +00002961 /* Unless an error has occurred, register numbers are always positive. */
2962 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002963 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2964
drhb6da74e2009-12-24 16:00:28 +00002965 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2966 ** for testing only - to verify that SQLite always gets the same answer
2967 ** with and without the column cache.
2968 */
drh7e5418e2012-09-27 15:05:54 +00002969 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002970
drh27ee4062009-12-30 01:13:11 +00002971 /* First replace any existing entry.
2972 **
2973 ** Actually, the way the column cache is currently used, we are guaranteed
2974 ** that the object will never already be in cache. Verify this guarantee.
2975 */
2976#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00002977 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00002978 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00002979 }
drh27ee4062009-12-30 01:13:11 +00002980#endif
drhceea3322009-04-23 13:22:42 +00002981
2982 /* Find an empty slot and replace it */
2983 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2984 if( p->iReg==0 ){
2985 p->iLevel = pParse->iCacheLevel;
2986 p->iTable = iTab;
2987 p->iColumn = iCol;
2988 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002989 p->tempReg = 0;
2990 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002991 pParse->nColCache++;
danee65eea2016-04-16 15:03:20 +00002992 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002993 return;
2994 }
2995 }
2996
2997 /* Replace the last recently used */
2998 minLru = 0x7fffffff;
2999 idxLru = -1;
3000 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3001 if( p->lru<minLru ){
3002 idxLru = i;
3003 minLru = p->lru;
3004 }
3005 }
drh20411ea2009-05-29 19:00:12 +00003006 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00003007 p = &pParse->aColCache[idxLru];
3008 p->iLevel = pParse->iCacheLevel;
3009 p->iTable = iTab;
3010 p->iColumn = iCol;
3011 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00003012 p->tempReg = 0;
3013 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00003014 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00003015 return;
3016 }
3017}
3018
3019/*
drhf49f3522009-12-30 14:12:38 +00003020** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3021** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00003022*/
drhf49f3522009-12-30 14:12:38 +00003023void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00003024 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00003025 if( iReg<=0 || pParse->nColCache==0 ) return;
3026 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
3027 while(1){
3028 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
3029 if( p==pParse->aColCache ) break;
3030 p--;
drhceea3322009-04-23 13:22:42 +00003031 }
3032}
3033
3034/*
3035** Remember the current column cache context. Any new entries added
3036** added to the column cache after this call are removed when the
3037** corresponding pop occurs.
3038*/
3039void sqlite3ExprCachePush(Parse *pParse){
3040 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00003041#ifdef SQLITE_DEBUG
3042 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3043 printf("PUSH to %d\n", pParse->iCacheLevel);
3044 }
3045#endif
drhceea3322009-04-23 13:22:42 +00003046}
3047
3048/*
3049** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00003050** the previous sqlite3ExprCachePush operation. In other words, restore
3051** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00003052*/
drhd2490902014-04-13 19:28:15 +00003053void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00003054 int i;
3055 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00003056 assert( pParse->iCacheLevel>=1 );
3057 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00003058#ifdef SQLITE_DEBUG
3059 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3060 printf("POP to %d\n", pParse->iCacheLevel);
3061 }
3062#endif
drhceea3322009-04-23 13:22:42 +00003063 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3064 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
3065 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00003066 }
3067 }
3068}
drh945498f2007-02-24 11:52:52 +00003069
3070/*
drh5cd79232009-05-25 11:46:29 +00003071** When a cached column is reused, make sure that its register is
3072** no longer available as a temp register. ticket #3879: that same
3073** register might be in the cache in multiple places, so be sure to
3074** get them all.
3075*/
3076static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3077 int i;
3078 struct yColCache *p;
3079 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3080 if( p->iReg==iReg ){
3081 p->tempReg = 0;
3082 }
3083 }
3084}
3085
drh1f9ca2c2015-08-25 16:57:52 +00003086/* Generate code that will load into register regOut a value that is
3087** appropriate for the iIdxCol-th column of index pIdx.
3088*/
3089void sqlite3ExprCodeLoadIndexColumn(
3090 Parse *pParse, /* The parsing context */
3091 Index *pIdx, /* The index whose column is to be loaded */
3092 int iTabCur, /* Cursor pointing to a table row */
3093 int iIdxCol, /* The column of the index to be loaded */
3094 int regOut /* Store the index column value in this register */
3095){
3096 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003097 if( iTabCol==XN_EXPR ){
3098 assert( pIdx->aColExpr );
3099 assert( pIdx->aColExpr->nExpr>iIdxCol );
3100 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00003101 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00003102 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003103 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3104 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003105 }
drh1f9ca2c2015-08-25 16:57:52 +00003106}
3107
drh5cd79232009-05-25 11:46:29 +00003108/*
drh5c092e82010-05-14 19:24:02 +00003109** Generate code to extract the value of the iCol-th column of a table.
3110*/
3111void sqlite3ExprCodeGetColumnOfTable(
3112 Vdbe *v, /* The VDBE under construction */
3113 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003114 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003115 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003116 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003117){
3118 if( iCol<0 || iCol==pTab->iPKey ){
3119 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3120 }else{
3121 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003122 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003123 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003124 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3125 }
3126 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003127 }
3128 if( iCol>=0 ){
3129 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3130 }
3131}
3132
3133/*
drh945498f2007-02-24 11:52:52 +00003134** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00003135** table pTab and store the column value in a register.
3136**
3137** An effort is made to store the column value in register iReg. This
3138** is not garanteeed for GetColumn() - the result can be stored in
3139** any register. But the result is guaranteed to land in register iReg
3140** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00003141**
3142** There must be an open cursor to pTab in iTable when this routine
3143** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003144*/
drhe55cbd72008-03-31 23:48:03 +00003145int sqlite3ExprCodeGetColumn(
3146 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003147 Table *pTab, /* Description of the table we are reading from */
3148 int iColumn, /* Index of the table column */
3149 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003150 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003151 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003152){
drhe55cbd72008-03-31 23:48:03 +00003153 Vdbe *v = pParse->pVdbe;
3154 int i;
drhda250ea2008-04-01 05:07:14 +00003155 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00003156
drhceea3322009-04-23 13:22:42 +00003157 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00003158 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00003159 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00003160 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00003161 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00003162 }
3163 }
3164 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003165 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003166 if( p5 ){
3167 sqlite3VdbeChangeP5(v, p5);
3168 }else{
3169 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3170 }
drhe55cbd72008-03-31 23:48:03 +00003171 return iReg;
3172}
drhce78bc62015-10-15 19:21:51 +00003173void sqlite3ExprCodeGetColumnToReg(
3174 Parse *pParse, /* Parsing and code generating context */
3175 Table *pTab, /* Description of the table we are reading from */
3176 int iColumn, /* Index of the table column */
3177 int iTable, /* The cursor pointing to the table */
3178 int iReg /* Store results here */
3179){
3180 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3181 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3182}
3183
drhe55cbd72008-03-31 23:48:03 +00003184
3185/*
drhceea3322009-04-23 13:22:42 +00003186** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00003187*/
drhceea3322009-04-23 13:22:42 +00003188void sqlite3ExprCacheClear(Parse *pParse){
3189 int i;
3190 struct yColCache *p;
3191
drh9ac79622013-12-18 15:11:47 +00003192#if SQLITE_DEBUG
3193 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3194 printf("CLEAR\n");
3195 }
3196#endif
drhceea3322009-04-23 13:22:42 +00003197 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3198 if( p->iReg ){
3199 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00003200 }
drhe55cbd72008-03-31 23:48:03 +00003201 }
3202}
3203
3204/*
drhda250ea2008-04-01 05:07:14 +00003205** Record the fact that an affinity change has occurred on iCount
3206** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00003207*/
drhda250ea2008-04-01 05:07:14 +00003208void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00003209 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00003210}
3211
3212/*
drhb21e7c72008-06-22 12:37:57 +00003213** Generate code to move content from registers iFrom...iFrom+nReg-1
3214** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00003215*/
drhb21e7c72008-06-22 12:37:57 +00003216void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003217 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003218 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00003219 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00003220}
3221
drhf49f3522009-12-30 14:12:38 +00003222#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00003223/*
drh652fbf52008-04-01 01:42:41 +00003224** Return true if any register in the range iFrom..iTo (inclusive)
3225** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00003226**
3227** This routine is used within assert() and testcase() macros only
3228** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00003229*/
3230static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3231 int i;
drhceea3322009-04-23 13:22:42 +00003232 struct yColCache *p;
3233 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3234 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00003235 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00003236 }
3237 return 0;
3238}
drhf49f3522009-12-30 14:12:38 +00003239#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00003240
drhbea119c2016-04-11 18:15:37 +00003241
drh652fbf52008-04-01 01:42:41 +00003242/*
drh12abf402016-08-22 14:30:05 +00003243** Convert a scalar expression node to a TK_REGISTER referencing
3244** register iReg. The caller must ensure that iReg already contains
3245** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003246*/
3247static void exprToRegister(Expr *p, int iReg){
3248 p->op2 = p->op;
3249 p->op = TK_REGISTER;
3250 p->iTable = iReg;
3251 ExprClearProperty(p, EP_Skip);
3252}
3253
drh12abf402016-08-22 14:30:05 +00003254/*
3255** Evaluate an expression (either a vector or a scalar expression) and store
3256** the result in continguous temporary registers. Return the index of
3257** the first register used to store the result.
3258**
3259** If the returned result register is a temporary scalar, then also write
3260** that register number into *piFreeable. If the returned result register
3261** is not a temporary or if the expression is a vector set *piFreeable
3262** to 0.
3263*/
3264static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3265 int iResult;
3266 int nResult = sqlite3ExprVectorSize(p);
3267 if( nResult==1 ){
3268 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3269 }else{
3270 *piFreeable = 0;
3271 if( p->op==TK_SELECT ){
3272 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3273 }else{
3274 int i;
3275 iResult = pParse->nMem+1;
3276 pParse->nMem += nResult;
3277 for(i=0; i<nResult; i++){
3278 sqlite3ExprCode(pParse, p->x.pList->a[i].pExpr, i+iResult);
3279 }
3280 }
3281 }
3282 return iResult;
3283}
3284
dan71c57db2016-07-09 20:23:55 +00003285
drha4c3c872013-09-12 17:29:25 +00003286/*
drhcce7d172000-05-31 15:34:51 +00003287** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003288** expression. Attempt to store the results in register "target".
3289** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003290**
drh8b213892008-08-29 02:14:02 +00003291** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003292** be stored in target. The result might be stored in some other
3293** register if it is convenient to do so. The calling function
3294** must check the return code and move the results to the desired
3295** register.
drhcce7d172000-05-31 15:34:51 +00003296*/
drh678ccce2008-03-31 18:19:54 +00003297int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003298 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3299 int op; /* The opcode being coded */
3300 int inReg = target; /* Results stored in register inReg */
3301 int regFree1 = 0; /* If non-zero free this temporary register */
3302 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003303 int r1, r2; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00003304 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00003305 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003306 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003307
drh9cbf3422008-01-17 16:22:13 +00003308 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003309 if( v==0 ){
3310 assert( pParse->db->mallocFailed );
3311 return 0;
3312 }
drh389a1ad2008-01-03 23:44:53 +00003313
3314 if( pExpr==0 ){
3315 op = TK_NULL;
3316 }else{
3317 op = pExpr->op;
3318 }
drhf2bc0132004-10-04 13:19:23 +00003319 switch( op ){
drh13449892005-09-07 21:22:45 +00003320 case TK_AGG_COLUMN: {
3321 AggInfo *pAggInfo = pExpr->pAggInfo;
3322 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3323 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003324 assert( pCol->iMem>0 );
3325 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00003326 break;
3327 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003328 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003329 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00003330 break;
3331 }
3332 /* Otherwise, fall thru into the TK_COLUMN case */
3333 }
drh967e8b72000-06-21 13:59:10 +00003334 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003335 int iTab = pExpr->iTable;
3336 if( iTab<0 ){
3337 if( pParse->ckBase>0 ){
3338 /* Generating CHECK constraints or inserting into partial index */
3339 inReg = pExpr->iColumn + pParse->ckBase;
3340 break;
3341 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003342 /* Coding an expression that is part of an index where column names
3343 ** in the index refer to the table to which the index belongs */
3344 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003345 }
drh22827922000-06-06 17:27:05 +00003346 }
drhb2b9d3d2013-08-01 01:14:43 +00003347 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3348 pExpr->iColumn, iTab, target,
3349 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003350 break;
3351 }
3352 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003353 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00003354 break;
3355 }
drh13573c72010-01-12 17:04:07 +00003356#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003357 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003358 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3359 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00003360 break;
3361 }
drh13573c72010-01-12 17:04:07 +00003362#endif
drhfec19aa2004-05-19 20:41:03 +00003363 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003364 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003365 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00003366 break;
3367 }
drhf0863fe2005-06-12 21:35:51 +00003368 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003369 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00003370 break;
3371 }
danielk19775338a5f2005-01-20 13:03:10 +00003372#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003373 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003374 int n;
3375 const char *z;
drhca48c902008-01-18 14:08:24 +00003376 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003377 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3378 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3379 assert( pExpr->u.zToken[1]=='\'' );
3380 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003381 n = sqlite3Strlen30(z) - 1;
3382 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003383 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3384 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00003385 break;
3386 }
danielk19775338a5f2005-01-20 13:03:10 +00003387#endif
drh50457892003-09-06 01:10:47 +00003388 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003389 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3390 assert( pExpr->u.zToken!=0 );
3391 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003392 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3393 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00003394 assert( pExpr->u.zToken[0]=='?'
3395 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
3396 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003397 }
drh50457892003-09-06 01:10:47 +00003398 break;
3399 }
drh4e0cff62004-11-05 05:10:28 +00003400 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00003401 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003402 break;
3403 }
drh487e2622005-06-25 18:42:14 +00003404#ifndef SQLITE_OMIT_CAST
3405 case TK_CAST: {
3406 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003407 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003408 if( inReg!=target ){
3409 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3410 inReg = target;
3411 }
drh4169e432014-08-25 20:11:52 +00003412 sqlite3VdbeAddOp2(v, OP_Cast, target,
3413 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00003414 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00003415 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00003416 break;
3417 }
3418#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003419 case TK_IS:
3420 case TK_ISNOT:
3421 op = (op==TK_IS) ? TK_EQ : TK_NE;
3422 p5 = SQLITE_NULLEQ;
3423 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003424 case TK_LT:
3425 case TK_LE:
3426 case TK_GT:
3427 case TK_GE:
3428 case TK_NE:
3429 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003430 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003431 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003432 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003433 }else{
3434 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3435 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3436 codeCompare(pParse, pLeft, pExpr->pRight, op,
3437 r1, r2, inReg, SQLITE_STOREP2 | p5);
3438 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3439 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3440 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3441 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3442 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3443 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3444 testcase( regFree1==0 );
3445 testcase( regFree2==0 );
3446 }
drh6a2fe092009-09-23 02:29:36 +00003447 break;
3448 }
drhcce7d172000-05-31 15:34:51 +00003449 case TK_AND:
3450 case TK_OR:
3451 case TK_PLUS:
3452 case TK_STAR:
3453 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003454 case TK_REM:
3455 case TK_BITAND:
3456 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003457 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003458 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003459 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003460 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003461 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3462 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3463 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3464 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3465 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3466 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3467 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3468 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3469 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3470 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3471 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003472 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3473 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003474 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003475 testcase( regFree1==0 );
3476 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003477 break;
3478 }
drhcce7d172000-05-31 15:34:51 +00003479 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003480 Expr *pLeft = pExpr->pLeft;
3481 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003482 if( pLeft->op==TK_INTEGER ){
3483 codeInteger(pParse, pLeft, 1, target);
3484#ifndef SQLITE_OMIT_FLOATING_POINT
3485 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003486 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3487 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00003488#endif
drh3c84ddf2008-01-09 02:15:38 +00003489 }else{
drh10d1edf2013-11-15 15:52:39 +00003490 tempX.op = TK_INTEGER;
3491 tempX.flags = EP_IntValue|EP_TokenOnly;
3492 tempX.u.iValue = 0;
3493 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003494 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003495 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003496 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003497 }
drh3c84ddf2008-01-09 02:15:38 +00003498 inReg = target;
3499 break;
drh6e142f52000-06-08 13:36:40 +00003500 }
drhbf4133c2001-10-13 02:59:08 +00003501 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003502 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003503 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3504 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003505 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3506 testcase( regFree1==0 );
3507 inReg = target;
3508 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003509 break;
3510 }
3511 case TK_ISNULL:
3512 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003513 int addr;
drh7d176102014-02-18 03:07:12 +00003514 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3515 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003516 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003517 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003518 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003519 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003520 VdbeCoverageIf(v, op==TK_ISNULL);
3521 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003522 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003523 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003524 break;
drhcce7d172000-05-31 15:34:51 +00003525 }
drh22827922000-06-06 17:27:05 +00003526 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003527 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003528 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003529 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3530 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003531 }else{
drh9de221d2008-01-05 06:51:30 +00003532 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003533 }
drh22827922000-06-06 17:27:05 +00003534 break;
3535 }
drhcce7d172000-05-31 15:34:51 +00003536 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003537 ExprList *pFarg; /* List of function arguments */
3538 int nFarg; /* Number of function arguments */
3539 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003540 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003541 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003542 int i; /* Loop counter */
3543 u8 enc = ENC(db); /* The text encoding used by this database */
3544 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003545
danielk19776ab3a2e2009-02-19 14:39:25 +00003546 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00003547 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003548 pFarg = 0;
3549 }else{
3550 pFarg = pExpr->x.pList;
3551 }
3552 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003553 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3554 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003555 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003556#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3557 if( pDef==0 && pParse->explain ){
3558 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3559 }
3560#endif
drh2d801512016-01-14 22:19:58 +00003561 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003562 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003563 break;
3564 }
drhae6bb952009-11-11 00:24:31 +00003565
3566 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003567 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003568 ** arguments past the first non-NULL argument.
3569 */
drhd36e1042013-09-06 13:10:12 +00003570 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003571 int endCoalesce = sqlite3VdbeMakeLabel(v);
3572 assert( nFarg>=2 );
3573 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3574 for(i=1; i<nFarg; i++){
3575 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003576 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00003577 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00003578 sqlite3ExprCachePush(pParse);
3579 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003580 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00003581 }
3582 sqlite3VdbeResolveLabel(v, endCoalesce);
3583 break;
3584 }
3585
drhcca9f3d2013-09-06 15:23:29 +00003586 /* The UNLIKELY() function is a no-op. The result is the value
3587 ** of the first argument.
3588 */
3589 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3590 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00003591 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003592 break;
3593 }
drhae6bb952009-11-11 00:24:31 +00003594
drhd1a01ed2013-11-21 16:08:52 +00003595 for(i=0; i<nFarg; i++){
3596 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003597 testcase( i==31 );
3598 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003599 }
3600 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3601 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3602 }
3603 }
drh12ffee82009-04-08 13:51:51 +00003604 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003605 if( constMask ){
3606 r1 = pParse->nMem+1;
3607 pParse->nMem += nFarg;
3608 }else{
3609 r1 = sqlite3GetTempRange(pParse, nFarg);
3610 }
drha748fdc2012-03-28 01:34:47 +00003611
3612 /* For length() and typeof() functions with a column argument,
3613 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3614 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3615 ** loading.
3616 */
drhd36e1042013-09-06 13:10:12 +00003617 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003618 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003619 assert( nFarg==1 );
3620 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003621 exprOp = pFarg->a[0].pExpr->op;
3622 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003623 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3624 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003625 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3626 pFarg->a[0].pExpr->op2 =
3627 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003628 }
3629 }
3630
drhd7d385d2009-09-03 01:18:00 +00003631 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003632 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003633 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003634 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003635 }else{
drh12ffee82009-04-08 13:51:51 +00003636 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003637 }
drhb7f6f682006-07-08 17:06:43 +00003638#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003639 /* Possibly overload the function if the first argument is
3640 ** a virtual table column.
3641 **
3642 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3643 ** second argument, not the first, as the argument to test to
3644 ** see if it is a column in a virtual table. This is done because
3645 ** the left operand of infix functions (the operand we want to
3646 ** control overloading) ends up as the second argument to the
3647 ** function. The expression "A glob B" is equivalent to
3648 ** "glob(B,A). We want to use the A in "A glob B" to test
3649 ** for function overloading. But we use the B term in "glob(B,A)".
3650 */
drh12ffee82009-04-08 13:51:51 +00003651 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3652 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3653 }else if( nFarg>0 ){
3654 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003655 }
3656#endif
drhd36e1042013-09-06 13:10:12 +00003657 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003658 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003659 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003660 }
drh9c7c9132015-06-26 18:16:52 +00003661 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003662 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003663 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003664 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003665 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003666 }
drhcce7d172000-05-31 15:34:51 +00003667 break;
3668 }
drhfe2093d2005-01-20 22:48:47 +00003669#ifndef SQLITE_OMIT_SUBQUERY
3670 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003671 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003672 int nCol;
drhc5499be2008-04-01 15:06:33 +00003673 testcase( op==TK_EXISTS );
3674 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003675 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3676 sqlite3SubselectError(pParse, nCol, 1);
3677 }else{
3678 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3679 }
drh19a775c2000-06-05 18:54:46 +00003680 break;
3681 }
drhfc7f27b2016-08-20 00:07:01 +00003682 case TK_SELECT_COLUMN: {
3683 if( pExpr->pLeft->iTable==0 ){
3684 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3685 }
3686 inReg = pExpr->pLeft->iTable + pExpr->iColumn;
3687 break;
3688 }
drhfef52082000-06-06 01:50:43 +00003689 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003690 int destIfFalse = sqlite3VdbeMakeLabel(v);
3691 int destIfNull = sqlite3VdbeMakeLabel(v);
3692 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3693 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3694 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3695 sqlite3VdbeResolveLabel(v, destIfFalse);
3696 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3697 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003698 break;
3699 }
drhe3365e62009-11-12 17:52:24 +00003700#endif /* SQLITE_OMIT_SUBQUERY */
3701
3702
drh2dcef112008-01-12 19:03:48 +00003703 /*
3704 ** x BETWEEN y AND z
3705 **
3706 ** This is equivalent to
3707 **
3708 ** x>=y AND x<=z
3709 **
3710 ** X is stored in pExpr->pLeft.
3711 ** Y is stored in pExpr->pList->a[0].pExpr.
3712 ** Z is stored in pExpr->pList->a[1].pExpr.
3713 */
drhfef52082000-06-06 01:50:43 +00003714 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003715 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhfef52082000-06-06 01:50:43 +00003716 break;
3717 }
drh94fa9c42016-02-27 21:16:04 +00003718 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003719 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003720 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003721 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003722 break;
3723 }
drh2dcef112008-01-12 19:03:48 +00003724
dan165921a2009-08-28 18:53:45 +00003725 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003726 /* If the opcode is TK_TRIGGER, then the expression is a reference
3727 ** to a column in the new.* or old.* pseudo-tables available to
3728 ** trigger programs. In this case Expr.iTable is set to 1 for the
3729 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3730 ** is set to the column of the pseudo-table to read, or to -1 to
3731 ** read the rowid field.
3732 **
3733 ** The expression is implemented using an OP_Param opcode. The p1
3734 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3735 ** to reference another column of the old.* pseudo-table, where
3736 ** i is the index of the column. For a new.rowid reference, p1 is
3737 ** set to (n+1), where n is the number of columns in each pseudo-table.
3738 ** For a reference to any other column in the new.* pseudo-table, p1
3739 ** is set to (n+2+i), where n and i are as defined previously. For
3740 ** example, if the table on which triggers are being fired is
3741 ** declared as:
3742 **
3743 ** CREATE TABLE t1(a, b);
3744 **
3745 ** Then p1 is interpreted as follows:
3746 **
3747 ** p1==0 -> old.rowid p1==3 -> new.rowid
3748 ** p1==1 -> old.a p1==4 -> new.a
3749 ** p1==2 -> old.b p1==5 -> new.b
3750 */
dan2832ad42009-08-31 15:27:27 +00003751 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003752 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3753
3754 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3755 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3756 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3757 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3758
3759 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003760 VdbeComment((v, "%s.%s -> $%d",
3761 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003762 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003763 target
dan165921a2009-08-28 18:53:45 +00003764 ));
dan65a7cd12009-09-01 12:16:01 +00003765
drh44dbca82010-01-13 04:22:20 +00003766#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003767 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003768 ** integer. Use OP_RealAffinity to make sure it is really real.
3769 **
3770 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3771 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003772 if( pExpr->iColumn>=0
3773 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3774 ){
3775 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3776 }
drh44dbca82010-01-13 04:22:20 +00003777#endif
dan165921a2009-08-28 18:53:45 +00003778 break;
3779 }
3780
dan71c57db2016-07-09 20:23:55 +00003781 case TK_VECTOR: {
drhe835bc12016-08-23 19:02:55 +00003782 sqlite3ErrorMsg(pParse, "row value misused");
dan71c57db2016-07-09 20:23:55 +00003783 break;
3784 }
3785
drh2dcef112008-01-12 19:03:48 +00003786 /*
3787 ** Form A:
3788 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3789 **
3790 ** Form B:
3791 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3792 **
3793 ** Form A is can be transformed into the equivalent form B as follows:
3794 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3795 ** WHEN x=eN THEN rN ELSE y END
3796 **
3797 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003798 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3799 ** odd. The Y is also optional. If the number of elements in x.pList
3800 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003801 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3802 **
3803 ** The result of the expression is the Ri for the first matching Ei,
3804 ** or if there is no matching Ei, the ELSE term Y, or if there is
3805 ** no ELSE term, NULL.
3806 */
drh33cd4902009-05-30 20:49:20 +00003807 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003808 int endLabel; /* GOTO label for end of CASE stmt */
3809 int nextCase; /* GOTO label for next WHEN clause */
3810 int nExpr; /* 2x number of WHEN terms */
3811 int i; /* Loop counter */
3812 ExprList *pEList; /* List of WHEN terms */
3813 struct ExprList_item *aListelem; /* Array of WHEN terms */
3814 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003815 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003816 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003817 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003818
danielk19776ab3a2e2009-02-19 14:39:25 +00003819 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003820 assert(pExpr->x.pList->nExpr > 0);
3821 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003822 aListelem = pEList->a;
3823 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003824 endLabel = sqlite3VdbeMakeLabel(v);
3825 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003826 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003827 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00003828 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003829 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00003830 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00003831 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003832 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003833 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003834 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3835 ** The value in regFree1 might get SCopy-ed into the file result.
3836 ** So make sure that the regFree1 register is not reused for other
3837 ** purposes and possibly overwritten. */
3838 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003839 }
drhc5cd1242013-09-12 16:50:49 +00003840 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003841 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003842 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003843 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003844 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003845 }else{
drh2dcef112008-01-12 19:03:48 +00003846 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003847 }
drh2dcef112008-01-12 19:03:48 +00003848 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003849 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003850 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003851 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003852 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003853 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003854 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003855 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003856 }
drhc5cd1242013-09-12 16:50:49 +00003857 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003858 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003859 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003860 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003861 }else{
drh9de221d2008-01-05 06:51:30 +00003862 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003863 }
danielk1977c1f4a192009-04-28 12:08:15 +00003864 assert( db->mallocFailed || pParse->nErr>0
3865 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003866 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003867 break;
3868 }
danielk19775338a5f2005-01-20 13:03:10 +00003869#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003870 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003871 assert( pExpr->affinity==OE_Rollback
3872 || pExpr->affinity==OE_Abort
3873 || pExpr->affinity==OE_Fail
3874 || pExpr->affinity==OE_Ignore
3875 );
dane0af83a2009-09-08 19:15:01 +00003876 if( !pParse->pTriggerTab ){
3877 sqlite3ErrorMsg(pParse,
3878 "RAISE() may only be used within a trigger-program");
3879 return 0;
3880 }
3881 if( pExpr->affinity==OE_Abort ){
3882 sqlite3MayAbort(pParse);
3883 }
dan165921a2009-08-28 18:53:45 +00003884 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003885 if( pExpr->affinity==OE_Ignore ){
3886 sqlite3VdbeAddOp4(
3887 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003888 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003889 }else{
drh433dccf2013-02-09 15:37:11 +00003890 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003891 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003892 }
3893
drhffe07b22005-11-03 00:41:17 +00003894 break;
drh17a7f8d2002-03-24 13:13:27 +00003895 }
danielk19775338a5f2005-01-20 13:03:10 +00003896#endif
drhffe07b22005-11-03 00:41:17 +00003897 }
drh2dcef112008-01-12 19:03:48 +00003898 sqlite3ReleaseTempReg(pParse, regFree1);
3899 sqlite3ReleaseTempReg(pParse, regFree2);
3900 return inReg;
3901}
3902
3903/*
drhd1a01ed2013-11-21 16:08:52 +00003904** Factor out the code of the given expression to initialization time.
3905*/
drhd673cdd2013-11-21 21:23:31 +00003906void sqlite3ExprCodeAtInit(
3907 Parse *pParse, /* Parsing context */
3908 Expr *pExpr, /* The expression to code when the VDBE initializes */
3909 int regDest, /* Store the value in this register */
3910 u8 reusable /* True if this expression is reusable */
3911){
drhd1a01ed2013-11-21 16:08:52 +00003912 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003913 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003914 p = pParse->pConstExpr;
3915 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3916 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003917 if( p ){
3918 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3919 pItem->u.iConstExprReg = regDest;
3920 pItem->reusable = reusable;
3921 }
drhd1a01ed2013-11-21 16:08:52 +00003922 pParse->pConstExpr = p;
3923}
3924
3925/*
drh2dcef112008-01-12 19:03:48 +00003926** Generate code to evaluate an expression and store the results
3927** into a register. Return the register number where the results
3928** are stored.
3929**
3930** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003931** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003932** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003933**
3934** If pExpr is a constant, then this routine might generate this
3935** code to fill the register in the initialization section of the
3936** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003937*/
3938int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003939 int r2;
3940 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003941 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003942 && pExpr->op!=TK_REGISTER
3943 && sqlite3ExprIsConstantNotJoin(pExpr)
3944 ){
3945 ExprList *p = pParse->pConstExpr;
3946 int i;
3947 *pReg = 0;
3948 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003949 struct ExprList_item *pItem;
3950 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3951 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3952 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003953 }
3954 }
3955 }
drhf30a9692013-11-15 01:10:18 +00003956 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003957 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003958 }else{
drhf30a9692013-11-15 01:10:18 +00003959 int r1 = sqlite3GetTempReg(pParse);
3960 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3961 if( r2==r1 ){
3962 *pReg = r1;
3963 }else{
3964 sqlite3ReleaseTempReg(pParse, r1);
3965 *pReg = 0;
3966 }
drh2dcef112008-01-12 19:03:48 +00003967 }
3968 return r2;
3969}
3970
3971/*
3972** Generate code that will evaluate expression pExpr and store the
3973** results in register target. The results are guaranteed to appear
3974** in register target.
3975*/
drh05a86c52014-02-16 01:55:49 +00003976void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00003977 int inReg;
3978
3979 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00003980 if( pExpr && pExpr->op==TK_REGISTER ){
3981 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3982 }else{
3983 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00003984 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00003985 if( inReg!=target && pParse->pVdbe ){
3986 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
3987 }
drhcce7d172000-05-31 15:34:51 +00003988 }
drhcce7d172000-05-31 15:34:51 +00003989}
3990
3991/*
drh1c75c9d2015-12-21 15:22:13 +00003992** Make a transient copy of expression pExpr and then code it using
3993** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
3994** except that the input expression is guaranteed to be unchanged.
3995*/
3996void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
3997 sqlite3 *db = pParse->db;
3998 pExpr = sqlite3ExprDup(db, pExpr, 0);
3999 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4000 sqlite3ExprDelete(db, pExpr);
4001}
4002
4003/*
drh05a86c52014-02-16 01:55:49 +00004004** Generate code that will evaluate expression pExpr and store the
4005** results in register target. The results are guaranteed to appear
4006** in register target. If the expression is constant, then this routine
4007** might choose to code the expression at initialization time.
4008*/
4009void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4010 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4011 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
4012 }else{
4013 sqlite3ExprCode(pParse, pExpr, target);
4014 }
drhcce7d172000-05-31 15:34:51 +00004015}
4016
4017/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004018** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004019** in register target.
drh25303782004-12-07 15:41:48 +00004020**
drh2dcef112008-01-12 19:03:48 +00004021** Also make a copy of the expression results into another "cache" register
4022** and modify the expression so that the next time it is evaluated,
4023** the result is a copy of the cache register.
4024**
4025** This routine is used for expressions that are used multiple
4026** times. They are evaluated once and the results of the expression
4027** are reused.
drh25303782004-12-07 15:41:48 +00004028*/
drh05a86c52014-02-16 01:55:49 +00004029void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004030 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004031 int iMem;
4032
drhde4fcfd2008-01-19 23:50:26 +00004033 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004034 assert( pExpr->op!=TK_REGISTER );
4035 sqlite3ExprCode(pParse, pExpr, target);
4036 iMem = ++pParse->nMem;
4037 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4038 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004039}
drh2dcef112008-01-12 19:03:48 +00004040
drh678ccce2008-03-31 18:19:54 +00004041/*
drh268380c2004-02-25 13:47:31 +00004042** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004043** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004044**
drh892d3172008-01-10 03:46:36 +00004045** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00004046**
4047** The SQLITE_ECEL_DUP flag prevents the arguments from being
4048** filled using OP_SCopy. OP_Copy must be used instead.
4049**
4050** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4051** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004052**
4053** The SQLITE_ECEL_REF flag means that expressions in the list with
4054** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4055** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00004056*/
danielk19774adee202004-05-08 08:23:19 +00004057int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004058 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004059 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004060 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004061 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004062 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004063){
4064 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004065 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004066 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004067 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004068 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004069 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004070 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004071 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004072 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004073 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004074 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00004075 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
4076 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4077 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00004078 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00004079 }else{
4080 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4081 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004082 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004083 if( copyOp==OP_Copy
4084 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4085 && pOp->p1+pOp->p3+1==inReg
4086 && pOp->p2+pOp->p3+1==target+i
4087 ){
4088 pOp->p3++;
4089 }else{
4090 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4091 }
drhd1a01ed2013-11-21 16:08:52 +00004092 }
drhd1766112008-09-17 00:13:12 +00004093 }
drh268380c2004-02-25 13:47:31 +00004094 }
drhf9b596e2004-05-26 16:54:42 +00004095 return n;
drh268380c2004-02-25 13:47:31 +00004096}
4097
4098/*
drh36c563a2009-11-12 13:32:22 +00004099** Generate code for a BETWEEN operator.
4100**
4101** x BETWEEN y AND z
4102**
4103** The above is equivalent to
4104**
4105** x>=y AND x<=z
4106**
4107** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004108** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004109**
4110** The xJumpIf parameter determines details:
4111**
4112** NULL: Store the boolean result in reg[dest]
4113** sqlite3ExprIfTrue: Jump to dest if true
4114** sqlite3ExprIfFalse: Jump to dest if false
4115**
4116** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004117*/
4118static void exprCodeBetween(
4119 Parse *pParse, /* Parsing and code generating context */
4120 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004121 int dest, /* Jump destination or storage location */
4122 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004123 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4124){
drhdb45bd52016-08-22 00:48:58 +00004125 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004126 Expr compLeft; /* The x>=y term */
4127 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004128 Expr exprX; /* The x subexpression */
4129 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004130
drh36c563a2009-11-12 13:32:22 +00004131
dan71c57db2016-07-09 20:23:55 +00004132 memset(&compLeft, 0, sizeof(Expr));
4133 memset(&compRight, 0, sizeof(Expr));
4134 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004135
4136 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4137 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004138 exprAnd.op = TK_AND;
4139 exprAnd.pLeft = &compLeft;
4140 exprAnd.pRight = &compRight;
4141 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004142 compLeft.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004143 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4144 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004145 compRight.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004146 compRight.pRight = pExpr->x.pList->a[1].pExpr;
drh12abf402016-08-22 14:30:05 +00004147 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004148 if( xJump ){
4149 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004150 }else{
drhdb45bd52016-08-22 00:48:58 +00004151 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004152 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004153 }
drhdb45bd52016-08-22 00:48:58 +00004154 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004155
4156 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004157 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4158 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4159 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4160 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4161 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4162 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4163 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4164 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004165 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004166}
4167
4168/*
drhcce7d172000-05-31 15:34:51 +00004169** Generate code for a boolean expression such that a jump is made
4170** to the label "dest" if the expression is true but execution
4171** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004172**
4173** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004174** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004175**
4176** This code depends on the fact that certain token values (ex: TK_EQ)
4177** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4178** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4179** the make process cause these values to align. Assert()s in the code
4180** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004181*/
danielk19774adee202004-05-08 08:23:19 +00004182void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004183 Vdbe *v = pParse->pVdbe;
4184 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004185 int regFree1 = 0;
4186 int regFree2 = 0;
4187 int r1, r2;
4188
drh35573352008-01-08 23:54:25 +00004189 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004190 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004191 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004192 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004193 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004194 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004195 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004196 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004197 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004198 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004199 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4200 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004201 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004202 break;
4203 }
4204 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004205 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004206 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004207 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004208 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004209 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004210 break;
4211 }
4212 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004213 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004214 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004215 break;
4216 }
drhde845c22016-03-17 19:07:52 +00004217 case TK_IS:
4218 case TK_ISNOT:
4219 testcase( op==TK_IS );
4220 testcase( op==TK_ISNOT );
4221 op = (op==TK_IS) ? TK_EQ : TK_NE;
4222 jumpIfNull = SQLITE_NULLEQ;
4223 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004224 case TK_LT:
4225 case TK_LE:
4226 case TK_GT:
4227 case TK_GE:
4228 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004229 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004230 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004231 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004232 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4233 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004234 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004235 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004236 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4237 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4238 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4239 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004240 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4241 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4242 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4243 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4244 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4245 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004246 testcase( regFree1==0 );
4247 testcase( regFree2==0 );
4248 break;
4249 }
drhcce7d172000-05-31 15:34:51 +00004250 case TK_ISNULL:
4251 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004252 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4253 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004254 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4255 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004256 VdbeCoverageIf(v, op==TK_ISNULL);
4257 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004258 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004259 break;
4260 }
drhfef52082000-06-06 01:50:43 +00004261 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004262 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004263 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004264 break;
4265 }
drh84e30ca2011-02-10 17:46:14 +00004266#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004267 case TK_IN: {
4268 int destIfFalse = sqlite3VdbeMakeLabel(v);
4269 int destIfNull = jumpIfNull ? dest : destIfFalse;
4270 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004271 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004272 sqlite3VdbeResolveLabel(v, destIfFalse);
4273 break;
4274 }
shanehbb201342011-02-09 19:55:20 +00004275#endif
drhcce7d172000-05-31 15:34:51 +00004276 default: {
dan7b35a772016-07-28 19:47:15 +00004277 default_expr:
drh991a1982014-01-02 17:57:16 +00004278 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004279 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004280 }else if( exprAlwaysFalse(pExpr) ){
4281 /* No-op */
4282 }else{
4283 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4284 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004285 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004286 testcase( regFree1==0 );
4287 testcase( jumpIfNull==0 );
4288 }
drhcce7d172000-05-31 15:34:51 +00004289 break;
4290 }
4291 }
drh2dcef112008-01-12 19:03:48 +00004292 sqlite3ReleaseTempReg(pParse, regFree1);
4293 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004294}
4295
4296/*
drh66b89c82000-11-28 20:47:17 +00004297** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004298** to the label "dest" if the expression is false but execution
4299** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004300**
4301** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004302** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4303** is 0.
drhcce7d172000-05-31 15:34:51 +00004304*/
danielk19774adee202004-05-08 08:23:19 +00004305void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004306 Vdbe *v = pParse->pVdbe;
4307 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004308 int regFree1 = 0;
4309 int regFree2 = 0;
4310 int r1, r2;
4311
drh35573352008-01-08 23:54:25 +00004312 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004313 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004314 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004315
4316 /* The value of pExpr->op and op are related as follows:
4317 **
4318 ** pExpr->op op
4319 ** --------- ----------
4320 ** TK_ISNULL OP_NotNull
4321 ** TK_NOTNULL OP_IsNull
4322 ** TK_NE OP_Eq
4323 ** TK_EQ OP_Ne
4324 ** TK_GT OP_Le
4325 ** TK_LE OP_Gt
4326 ** TK_GE OP_Lt
4327 ** TK_LT OP_Ge
4328 **
4329 ** For other values of pExpr->op, op is undefined and unused.
4330 ** The value of TK_ and OP_ constants are arranged such that we
4331 ** can compute the mapping above using the following expression.
4332 ** Assert()s verify that the computation is correct.
4333 */
4334 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4335
4336 /* Verify correct alignment of TK_ and OP_ constants
4337 */
4338 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4339 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4340 assert( pExpr->op!=TK_NE || op==OP_Eq );
4341 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4342 assert( pExpr->op!=TK_LT || op==OP_Ge );
4343 assert( pExpr->op!=TK_LE || op==OP_Gt );
4344 assert( pExpr->op!=TK_GT || op==OP_Le );
4345 assert( pExpr->op!=TK_GE || op==OP_Lt );
4346
danba00e302016-07-23 20:24:06 +00004347 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004348 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004349 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004350 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004351 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004352 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004353 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004354 break;
4355 }
4356 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004357 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004358 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004359 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004360 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004361 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4362 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004363 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004364 break;
4365 }
4366 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004367 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004368 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004369 break;
4370 }
drhde845c22016-03-17 19:07:52 +00004371 case TK_IS:
4372 case TK_ISNOT:
4373 testcase( pExpr->op==TK_IS );
4374 testcase( pExpr->op==TK_ISNOT );
4375 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4376 jumpIfNull = SQLITE_NULLEQ;
4377 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004378 case TK_LT:
4379 case TK_LE:
4380 case TK_GT:
4381 case TK_GE:
4382 case TK_NE:
4383 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004384 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004385 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004386 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4387 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004388 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004389 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004390 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4391 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4392 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4393 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004394 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4395 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4396 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4397 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4398 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4399 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004400 testcase( regFree1==0 );
4401 testcase( regFree2==0 );
4402 break;
4403 }
drhcce7d172000-05-31 15:34:51 +00004404 case TK_ISNULL:
4405 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004406 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4407 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004408 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4409 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004410 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004411 break;
4412 }
drhfef52082000-06-06 01:50:43 +00004413 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004414 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004415 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004416 break;
4417 }
drh84e30ca2011-02-10 17:46:14 +00004418#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004419 case TK_IN: {
4420 if( jumpIfNull ){
4421 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4422 }else{
4423 int destIfNull = sqlite3VdbeMakeLabel(v);
4424 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4425 sqlite3VdbeResolveLabel(v, destIfNull);
4426 }
4427 break;
4428 }
shanehbb201342011-02-09 19:55:20 +00004429#endif
drhcce7d172000-05-31 15:34:51 +00004430 default: {
danba00e302016-07-23 20:24:06 +00004431 default_expr:
drh991a1982014-01-02 17:57:16 +00004432 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004433 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004434 }else if( exprAlwaysTrue(pExpr) ){
4435 /* no-op */
4436 }else{
4437 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4438 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004439 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004440 testcase( regFree1==0 );
4441 testcase( jumpIfNull==0 );
4442 }
drhcce7d172000-05-31 15:34:51 +00004443 break;
4444 }
4445 }
drh2dcef112008-01-12 19:03:48 +00004446 sqlite3ReleaseTempReg(pParse, regFree1);
4447 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004448}
drh22827922000-06-06 17:27:05 +00004449
4450/*
drh72bc8202015-06-11 13:58:35 +00004451** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4452** code generation, and that copy is deleted after code generation. This
4453** ensures that the original pExpr is unchanged.
4454*/
4455void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4456 sqlite3 *db = pParse->db;
4457 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4458 if( db->mallocFailed==0 ){
4459 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4460 }
4461 sqlite3ExprDelete(db, pCopy);
4462}
4463
4464
4465/*
drh1d9da702010-01-07 15:17:02 +00004466** Do a deep comparison of two expression trees. Return 0 if the two
4467** expressions are completely identical. Return 1 if they differ only
4468** by a COLLATE operator at the top level. Return 2 if there are differences
4469** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004470**
drh619a1302013-08-01 13:04:46 +00004471** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4472** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4473**
drh66518ca2013-08-01 15:09:57 +00004474** The pA side might be using TK_REGISTER. If that is the case and pB is
4475** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4476**
drh1d9da702010-01-07 15:17:02 +00004477** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004478** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004479** identical, we return 2 just to be safe. So if this routine
4480** returns 2, then you do not really know for certain if the two
4481** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004482** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004483** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004484** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004485** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00004486*/
drh619a1302013-08-01 13:04:46 +00004487int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004488 u32 combinedFlags;
4489 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004490 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004491 }
drh10d1edf2013-11-15 15:52:39 +00004492 combinedFlags = pA->flags | pB->flags;
4493 if( combinedFlags & EP_IntValue ){
4494 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4495 return 0;
4496 }
drh1d9da702010-01-07 15:17:02 +00004497 return 2;
drh22827922000-06-06 17:27:05 +00004498 }
drhc2acc4e2013-11-15 18:15:19 +00004499 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00004500 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004501 return 1;
4502 }
drh619a1302013-08-01 13:04:46 +00004503 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004504 return 1;
4505 }
4506 return 2;
4507 }
drh2edc5fd2015-11-24 02:10:52 +00004508 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004509 if( pA->op==TK_FUNCTION ){
4510 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4511 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00004512 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00004513 }
drh22827922000-06-06 17:27:05 +00004514 }
drh10d1edf2013-11-15 15:52:39 +00004515 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004516 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00004517 if( combinedFlags & EP_xIsSelect ) return 2;
4518 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4519 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4520 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00004521 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00004522 if( pA->iColumn!=pB->iColumn ) return 2;
4523 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004524 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004525 }
4526 }
drh1d9da702010-01-07 15:17:02 +00004527 return 0;
drh22827922000-06-06 17:27:05 +00004528}
4529
drh8c6f6662010-04-26 19:17:26 +00004530/*
4531** Compare two ExprList objects. Return 0 if they are identical and
4532** non-zero if they differ in any way.
4533**
drh619a1302013-08-01 13:04:46 +00004534** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4535** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4536**
drh8c6f6662010-04-26 19:17:26 +00004537** This routine might return non-zero for equivalent ExprLists. The
4538** only consequence will be disabled optimizations. But this routine
4539** must never return 0 if the two ExprList objects are different, or
4540** a malfunction will result.
4541**
4542** Two NULL pointers are considered to be the same. But a NULL pointer
4543** always differs from a non-NULL pointer.
4544*/
drh619a1302013-08-01 13:04:46 +00004545int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004546 int i;
4547 if( pA==0 && pB==0 ) return 0;
4548 if( pA==0 || pB==0 ) return 1;
4549 if( pA->nExpr!=pB->nExpr ) return 1;
4550 for(i=0; i<pA->nExpr; i++){
4551 Expr *pExprA = pA->a[i].pExpr;
4552 Expr *pExprB = pB->a[i].pExpr;
4553 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00004554 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004555 }
4556 return 0;
4557}
drh13449892005-09-07 21:22:45 +00004558
drh22827922000-06-06 17:27:05 +00004559/*
drh4bd5f732013-07-31 23:22:39 +00004560** Return true if we can prove the pE2 will always be true if pE1 is
4561** true. Return false if we cannot complete the proof or if pE2 might
4562** be false. Examples:
4563**
drh619a1302013-08-01 13:04:46 +00004564** pE1: x==5 pE2: x==5 Result: true
4565** pE1: x>0 pE2: x==5 Result: false
4566** pE1: x=21 pE2: x=21 OR y=43 Result: true
4567** pE1: x!=123 pE2: x IS NOT NULL Result: true
4568** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4569** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4570** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004571**
4572** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4573** Expr.iTable<0 then assume a table number given by iTab.
4574**
4575** When in doubt, return false. Returning true might give a performance
4576** improvement. Returning false might cause a performance reduction, but
4577** it will always give the correct answer and is hence always safe.
4578*/
4579int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00004580 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4581 return 1;
4582 }
4583 if( pE2->op==TK_OR
4584 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4585 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4586 ){
4587 return 1;
4588 }
4589 if( pE2->op==TK_NOTNULL
4590 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4591 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4592 ){
4593 return 1;
4594 }
4595 return 0;
drh4bd5f732013-07-31 23:22:39 +00004596}
4597
4598/*
drh030796d2012-08-23 16:18:10 +00004599** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00004600** to determine if an expression can be evaluated by reference to the
4601** index only, without having to do a search for the corresponding
4602** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4603** is the cursor for the table.
4604*/
4605struct IdxCover {
4606 Index *pIdx; /* The index to be tested for coverage */
4607 int iCur; /* Cursor number for the table corresponding to the index */
4608};
4609
4610/*
4611** Check to see if there are references to columns in table
4612** pWalker->u.pIdxCover->iCur can be satisfied using the index
4613** pWalker->u.pIdxCover->pIdx.
4614*/
4615static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4616 if( pExpr->op==TK_COLUMN
4617 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4618 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4619 ){
4620 pWalker->eCode = 1;
4621 return WRC_Abort;
4622 }
4623 return WRC_Continue;
4624}
4625
4626/*
drhe604ec02016-07-27 19:20:58 +00004627** Determine if an index pIdx on table with cursor iCur contains will
4628** the expression pExpr. Return true if the index does cover the
4629** expression and false if the pExpr expression references table columns
4630** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00004631**
4632** An index covering an expression means that the expression can be
4633** evaluated using only the index and without having to lookup the
4634** corresponding table entry.
4635*/
4636int sqlite3ExprCoveredByIndex(
4637 Expr *pExpr, /* The index to be tested */
4638 int iCur, /* The cursor number for the corresponding table */
4639 Index *pIdx /* The index that might be used for coverage */
4640){
4641 Walker w;
4642 struct IdxCover xcov;
4643 memset(&w, 0, sizeof(w));
4644 xcov.iCur = iCur;
4645 xcov.pIdx = pIdx;
4646 w.xExprCallback = exprIdxCover;
4647 w.u.pIdxCover = &xcov;
4648 sqlite3WalkExpr(&w, pExpr);
4649 return !w.eCode;
4650}
4651
4652
4653/*
4654** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00004655** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00004656** aggregate function, in order to implement the
4657** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00004658*/
drh030796d2012-08-23 16:18:10 +00004659struct SrcCount {
4660 SrcList *pSrc; /* One particular FROM clause in a nested query */
4661 int nThis; /* Number of references to columns in pSrcList */
4662 int nOther; /* Number of references to columns in other FROM clauses */
4663};
4664
4665/*
4666** Count the number of references to columns.
4667*/
4668static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00004669 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4670 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4671 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4672 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4673 ** NEVER() will need to be removed. */
4674 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00004675 int i;
drh030796d2012-08-23 16:18:10 +00004676 struct SrcCount *p = pWalker->u.pSrcCount;
4677 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00004678 int nSrc = pSrc ? pSrc->nSrc : 0;
4679 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00004680 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00004681 }
drh655814d2015-01-09 01:27:29 +00004682 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00004683 p->nThis++;
4684 }else{
4685 p->nOther++;
4686 }
drh374fdce2012-04-17 16:38:53 +00004687 }
drh030796d2012-08-23 16:18:10 +00004688 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004689}
4690
4691/*
drh030796d2012-08-23 16:18:10 +00004692** Determine if any of the arguments to the pExpr Function reference
4693** pSrcList. Return true if they do. Also return true if the function
4694** has no arguments or has only constant arguments. Return false if pExpr
4695** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004696*/
drh030796d2012-08-23 16:18:10 +00004697int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004698 Walker w;
drh030796d2012-08-23 16:18:10 +00004699 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004700 assert( pExpr->op==TK_AGG_FUNCTION );
4701 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004702 w.xExprCallback = exprSrcCount;
4703 w.u.pSrcCount = &cnt;
4704 cnt.pSrc = pSrcList;
4705 cnt.nThis = 0;
4706 cnt.nOther = 0;
4707 sqlite3WalkExprList(&w, pExpr->x.pList);
4708 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004709}
4710
4711/*
drh13449892005-09-07 21:22:45 +00004712** Add a new element to the pAggInfo->aCol[] array. Return the index of
4713** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004714*/
drh17435752007-08-16 04:30:38 +00004715static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004716 int i;
drhcf643722007-03-27 13:36:37 +00004717 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004718 db,
drhcf643722007-03-27 13:36:37 +00004719 pInfo->aCol,
4720 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004721 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004722 &i
4723 );
drh13449892005-09-07 21:22:45 +00004724 return i;
4725}
4726
4727/*
4728** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4729** the new element. Return a negative number if malloc fails.
4730*/
drh17435752007-08-16 04:30:38 +00004731static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004732 int i;
drhcf643722007-03-27 13:36:37 +00004733 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004734 db,
drhcf643722007-03-27 13:36:37 +00004735 pInfo->aFunc,
4736 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004737 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004738 &i
4739 );
drh13449892005-09-07 21:22:45 +00004740 return i;
4741}
drh22827922000-06-06 17:27:05 +00004742
4743/*
drh7d10d5a2008-08-20 16:35:10 +00004744** This is the xExprCallback for a tree walker. It is used to
4745** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004746** for additional information.
drh22827922000-06-06 17:27:05 +00004747*/
drh7d10d5a2008-08-20 16:35:10 +00004748static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004749 int i;
drh7d10d5a2008-08-20 16:35:10 +00004750 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004751 Parse *pParse = pNC->pParse;
4752 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004753 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004754
drh22827922000-06-06 17:27:05 +00004755 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004756 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004757 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004758 testcase( pExpr->op==TK_AGG_COLUMN );
4759 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004760 /* Check to see if the column is in one of the tables in the FROM
4761 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004762 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004763 struct SrcList_item *pItem = pSrcList->a;
4764 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4765 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004766 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004767 if( pExpr->iTable==pItem->iCursor ){
4768 /* If we reach this point, it means that pExpr refers to a table
4769 ** that is in the FROM clause of the aggregate query.
4770 **
4771 ** Make an entry for the column in pAggInfo->aCol[] if there
4772 ** is not an entry there already.
4773 */
drh7f906d62007-03-12 23:48:52 +00004774 int k;
drh13449892005-09-07 21:22:45 +00004775 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004776 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004777 if( pCol->iTable==pExpr->iTable &&
4778 pCol->iColumn==pExpr->iColumn ){
4779 break;
4780 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004781 }
danielk19771e536952007-08-16 10:09:01 +00004782 if( (k>=pAggInfo->nColumn)
4783 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4784 ){
drh7f906d62007-03-12 23:48:52 +00004785 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004786 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004787 pCol->iTable = pExpr->iTable;
4788 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004789 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004790 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004791 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004792 if( pAggInfo->pGroupBy ){
4793 int j, n;
4794 ExprList *pGB = pAggInfo->pGroupBy;
4795 struct ExprList_item *pTerm = pGB->a;
4796 n = pGB->nExpr;
4797 for(j=0; j<n; j++, pTerm++){
4798 Expr *pE = pTerm->pExpr;
4799 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4800 pE->iColumn==pExpr->iColumn ){
4801 pCol->iSorterColumn = j;
4802 break;
4803 }
4804 }
4805 }
4806 if( pCol->iSorterColumn<0 ){
4807 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4808 }
4809 }
4810 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4811 ** because it was there before or because we just created it).
4812 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4813 ** pAggInfo->aCol[] entry.
4814 */
drhebb6a652013-09-12 23:42:22 +00004815 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004816 pExpr->pAggInfo = pAggInfo;
4817 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004818 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004819 break;
4820 } /* endif pExpr->iTable==pItem->iCursor */
4821 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004822 }
drh7d10d5a2008-08-20 16:35:10 +00004823 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004824 }
4825 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004826 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004827 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004828 ){
drh13449892005-09-07 21:22:45 +00004829 /* Check to see if pExpr is a duplicate of another aggregate
4830 ** function that is already in the pAggInfo structure
4831 */
4832 struct AggInfo_func *pItem = pAggInfo->aFunc;
4833 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004834 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004835 break;
4836 }
drh22827922000-06-06 17:27:05 +00004837 }
drh13449892005-09-07 21:22:45 +00004838 if( i>=pAggInfo->nFunc ){
4839 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4840 */
danielk197714db2662006-01-09 16:12:04 +00004841 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004842 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004843 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004844 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004845 pItem = &pAggInfo->aFunc[i];
4846 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004847 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004848 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004849 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004850 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004851 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004852 if( pExpr->flags & EP_Distinct ){
4853 pItem->iDistinct = pParse->nTab++;
4854 }else{
4855 pItem->iDistinct = -1;
4856 }
drh13449892005-09-07 21:22:45 +00004857 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004858 }
drh13449892005-09-07 21:22:45 +00004859 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4860 */
drhc5cd1242013-09-12 16:50:49 +00004861 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004862 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004863 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004864 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004865 return WRC_Prune;
4866 }else{
4867 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004868 }
drh22827922000-06-06 17:27:05 +00004869 }
4870 }
drh7d10d5a2008-08-20 16:35:10 +00004871 return WRC_Continue;
4872}
4873static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004874 UNUSED_PARAMETER(pWalker);
4875 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004876 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004877}
4878
4879/*
drhe8abb4c2012-11-02 18:24:57 +00004880** Analyze the pExpr expression looking for aggregate functions and
4881** for variables that need to be added to AggInfo object that pNC->pAggInfo
4882** points to. Additional entries are made on the AggInfo object as
4883** necessary.
drh626a8792005-01-17 22:08:19 +00004884**
4885** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004886** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004887*/
drhd2b3e232008-01-23 14:51:49 +00004888void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004889 Walker w;
drh374fdce2012-04-17 16:38:53 +00004890 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004891 w.xExprCallback = analyzeAggregate;
4892 w.xSelectCallback = analyzeAggregatesInSelect;
4893 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004894 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004895 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004896}
drh5d9a4af2005-08-30 00:54:01 +00004897
4898/*
4899** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4900** expression list. Return the number of errors.
4901**
4902** If an error is found, the analysis is cut short.
4903*/
drhd2b3e232008-01-23 14:51:49 +00004904void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004905 struct ExprList_item *pItem;
4906 int i;
drh5d9a4af2005-08-30 00:54:01 +00004907 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004908 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4909 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004910 }
4911 }
drh5d9a4af2005-08-30 00:54:01 +00004912}
drh892d3172008-01-10 03:46:36 +00004913
4914/*
drhceea3322009-04-23 13:22:42 +00004915** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004916*/
4917int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004918 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004919 return ++pParse->nMem;
4920 }
danielk19772f425f62008-07-04 09:41:39 +00004921 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004922}
drhceea3322009-04-23 13:22:42 +00004923
4924/*
4925** Deallocate a register, making available for reuse for some other
4926** purpose.
4927**
4928** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004929** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004930** the register becomes stale.
4931*/
drh892d3172008-01-10 03:46:36 +00004932void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004933 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004934 int i;
4935 struct yColCache *p;
4936 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4937 if( p->iReg==iReg ){
4938 p->tempReg = 1;
4939 return;
4940 }
4941 }
drh892d3172008-01-10 03:46:36 +00004942 pParse->aTempReg[pParse->nTempReg++] = iReg;
4943 }
4944}
4945
4946/*
4947** Allocate or deallocate a block of nReg consecutive registers
4948*/
4949int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004950 int i, n;
4951 i = pParse->iRangeReg;
4952 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004953 if( nReg<=n ){
4954 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004955 pParse->iRangeReg += nReg;
4956 pParse->nRangeReg -= nReg;
4957 }else{
4958 i = pParse->nMem+1;
4959 pParse->nMem += nReg;
4960 }
4961 return i;
4962}
4963void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004964 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004965 if( nReg>pParse->nRangeReg ){
4966 pParse->nRangeReg = nReg;
4967 pParse->iRangeReg = iReg;
4968 }
4969}
drhcdc69552011-12-06 13:24:59 +00004970
4971/*
4972** Mark all temporary registers as being unavailable for reuse.
4973*/
4974void sqlite3ClearTempRegCache(Parse *pParse){
4975 pParse->nTempReg = 0;
4976 pParse->nRangeReg = 0;
4977}
drhbb9b5f22016-03-19 00:35:02 +00004978
4979/*
4980** Validate that no temporary register falls within the range of
4981** iFirst..iLast, inclusive. This routine is only call from within assert()
4982** statements.
4983*/
4984#ifdef SQLITE_DEBUG
4985int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4986 int i;
4987 if( pParse->nRangeReg>0
4988 && pParse->iRangeReg+pParse->nRangeReg<iLast
4989 && pParse->iRangeReg>=iFirst
4990 ){
4991 return 0;
4992 }
4993 for(i=0; i<pParse->nTempReg; i++){
4994 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4995 return 0;
4996 }
4997 }
4998 return 1;
4999}
5000#endif /* SQLITE_DEBUG */