blob: 572edaa541566de3ee2e6f36031537a3a797c847 [file] [log] [blame]
drhcce7d172000-05-31 15:34:51 +00001/*
drhb19a2bc2001-09-16 00:13:26 +00002** 2001 September 15
drhcce7d172000-05-31 15:34:51 +00003**
drhb19a2bc2001-09-16 00:13:26 +00004** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
drhcce7d172000-05-31 15:34:51 +00006**
drhb19a2bc2001-09-16 00:13:26 +00007** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
drhcce7d172000-05-31 15:34:51 +000010**
11*************************************************************************
drh1ccde152000-06-17 13:12:39 +000012** This file contains routines used for analyzing expressions and
drhb19a2bc2001-09-16 00:13:26 +000013** for generating VDBE code that evaluates expressions in SQLite.
drhcce7d172000-05-31 15:34:51 +000014*/
15#include "sqliteInt.h"
drha2e00042002-01-22 03:13:42 +000016
drh12abf402016-08-22 14:30:05 +000017/* Forward declarations */
18static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
19static int exprCodeVector(Parse *pParse, Expr *p, int *piToFree);
20
21
danielk1977e014a832004-05-17 10:48:57 +000022/*
23** Return the 'affinity' of the expression pExpr if any.
24**
25** If pExpr is a column, a reference to a column via an 'AS' alias,
26** or a sub-select with a column as the return value, then the
27** affinity of that column is returned. Otherwise, 0x00 is returned,
28** indicating no affinity for the expression.
29**
peter.d.reid60ec9142014-09-06 16:39:46 +000030** i.e. the WHERE clause expressions in the following statements all
danielk1977e014a832004-05-17 10:48:57 +000031** have an affinity:
32**
33** CREATE TABLE t1(a);
34** SELECT * FROM t1 WHERE a;
35** SELECT a AS b FROM t1 WHERE b;
36** SELECT * FROM t1 WHERE (select a from t1);
37*/
danielk1977bf3b7212004-05-18 10:06:24 +000038char sqlite3ExprAffinity(Expr *pExpr){
drh580c8c12012-12-08 03:34:04 +000039 int op;
40 pExpr = sqlite3ExprSkipCollate(pExpr);
mistachkin9bec6fb2014-06-26 21:28:21 +000041 if( pExpr->flags & EP_Generic ) return 0;
drh580c8c12012-12-08 03:34:04 +000042 op = pExpr->op;
drh487e2622005-06-25 18:42:14 +000043 if( op==TK_SELECT ){
danielk19776ab3a2e2009-02-19 14:39:25 +000044 assert( pExpr->flags&EP_xIsSelect );
45 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
danielk1977a37cdde2004-05-16 11:15:36 +000046 }
drhdb45bd52016-08-22 00:48:58 +000047 if( op==TK_REGISTER ) op = pExpr->op2;
drh487e2622005-06-25 18:42:14 +000048#ifndef SQLITE_OMIT_CAST
49 if( op==TK_CAST ){
drh33e619f2009-05-28 01:00:55 +000050 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drhfdaac672013-10-04 15:30:21 +000051 return sqlite3AffinityType(pExpr->u.zToken, 0);
drh487e2622005-06-25 18:42:14 +000052 }
53#endif
drhdb45bd52016-08-22 00:48:58 +000054 if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab!=0 ){
drh7d10d5a2008-08-20 16:35:10 +000055 int j = pExpr->iColumn;
56 if( j<0 ) return SQLITE_AFF_INTEGER;
57 assert( pExpr->pTab && j<pExpr->pTab->nCol );
58 return pExpr->pTab->aCol[j].affinity;
59 }
danielk1977a37cdde2004-05-16 11:15:36 +000060 return pExpr->affinity;
61}
62
drh53db1452004-05-20 13:54:53 +000063/*
drh8b4c40d2007-02-01 23:02:45 +000064** Set the collating sequence for expression pExpr to be the collating
drhae80dde2012-12-06 21:16:43 +000065** sequence named by pToken. Return a pointer to a new Expr node that
66** implements the COLLATE operator.
drh0a8a4062012-12-07 18:38:16 +000067**
68** If a memory allocation error occurs, that fact is recorded in pParse->db
69** and the pExpr parameter is returned unchanged.
drh8b4c40d2007-02-01 23:02:45 +000070*/
drh4ef7efa2014-03-20 15:14:08 +000071Expr *sqlite3ExprAddCollateToken(
72 Parse *pParse, /* Parsing context */
73 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
dan80103fc2015-03-20 08:43:59 +000074 const Token *pCollName, /* Name of collating sequence */
75 int dequote /* True to dequote pCollName */
drh4ef7efa2014-03-20 15:14:08 +000076){
drh0a8a4062012-12-07 18:38:16 +000077 if( pCollName->n>0 ){
dan80103fc2015-03-20 08:43:59 +000078 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
drh0a8a4062012-12-07 18:38:16 +000079 if( pNew ){
80 pNew->pLeft = pExpr;
drha4c3c872013-09-12 17:29:25 +000081 pNew->flags |= EP_Collate|EP_Skip;
drh0a8a4062012-12-07 18:38:16 +000082 pExpr = pNew;
83 }
drhae80dde2012-12-06 21:16:43 +000084 }
drh0a8a4062012-12-07 18:38:16 +000085 return pExpr;
86}
87Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
drh261d8a52012-12-08 21:36:26 +000088 Token s;
89 assert( zC!=0 );
drh40aced52016-01-22 17:48:09 +000090 sqlite3TokenInit(&s, (char*)zC);
dan80103fc2015-03-20 08:43:59 +000091 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
drh0a8a4062012-12-07 18:38:16 +000092}
93
94/*
drh0b8d2552015-09-05 22:36:07 +000095** Skip over any TK_COLLATE operators and any unlikely()
drha4c3c872013-09-12 17:29:25 +000096** or likelihood() function at the root of an expression.
drh0a8a4062012-12-07 18:38:16 +000097*/
98Expr *sqlite3ExprSkipCollate(Expr *pExpr){
drha4c3c872013-09-12 17:29:25 +000099 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
100 if( ExprHasProperty(pExpr, EP_Unlikely) ){
drhcca9f3d2013-09-06 15:23:29 +0000101 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
102 assert( pExpr->x.pList->nExpr>0 );
drha4c3c872013-09-12 17:29:25 +0000103 assert( pExpr->op==TK_FUNCTION );
drhcca9f3d2013-09-06 15:23:29 +0000104 pExpr = pExpr->x.pList->a[0].pExpr;
105 }else{
drh0b8d2552015-09-05 22:36:07 +0000106 assert( pExpr->op==TK_COLLATE );
drha4c3c872013-09-12 17:29:25 +0000107 pExpr = pExpr->pLeft;
drhcca9f3d2013-09-06 15:23:29 +0000108 }
drha4c3c872013-09-12 17:29:25 +0000109 }
drh0a8a4062012-12-07 18:38:16 +0000110 return pExpr;
drh8b4c40d2007-02-01 23:02:45 +0000111}
112
113/*
drhae80dde2012-12-06 21:16:43 +0000114** Return the collation sequence for the expression pExpr. If
115** there is no defined collating sequence, return NULL.
116**
117** The collating sequence might be determined by a COLLATE operator
118** or by the presence of a column with a defined collating sequence.
119** COLLATE operators take first precedence. Left operands take
120** precedence over right operands.
danielk19770202b292004-06-09 09:55:16 +0000121*/
danielk19777cedc8d2004-06-10 10:50:08 +0000122CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000123 sqlite3 *db = pParse->db;
danielk19777cedc8d2004-06-10 10:50:08 +0000124 CollSeq *pColl = 0;
drh7d10d5a2008-08-20 16:35:10 +0000125 Expr *p = pExpr;
drh261d8a52012-12-08 21:36:26 +0000126 while( p ){
drhae80dde2012-12-06 21:16:43 +0000127 int op = p->op;
drhfbb24d12014-03-20 17:03:30 +0000128 if( p->flags & EP_Generic ) break;
drhae80dde2012-12-06 21:16:43 +0000129 if( op==TK_CAST || op==TK_UPLUS ){
130 p = p->pLeft;
131 continue;
132 }
dan36e78302013-08-21 12:04:32 +0000133 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
drh6fdd3d82013-05-15 17:47:12 +0000134 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
drhae80dde2012-12-06 21:16:43 +0000135 break;
136 }
drha58d4a92015-01-27 13:17:05 +0000137 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
drhae80dde2012-12-06 21:16:43 +0000138 || op==TK_REGISTER || op==TK_TRIGGER)
drha58d4a92015-01-27 13:17:05 +0000139 && p->pTab!=0
drhae80dde2012-12-06 21:16:43 +0000140 ){
drh7d10d5a2008-08-20 16:35:10 +0000141 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
142 ** a TK_COLUMN but was previously evaluated and cached in a register */
drh7d10d5a2008-08-20 16:35:10 +0000143 int j = p->iColumn;
144 if( j>=0 ){
drhae80dde2012-12-06 21:16:43 +0000145 const char *zColl = p->pTab->aCol[j].zColl;
drhc4a64fa2009-05-11 20:53:28 +0000146 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh7d10d5a2008-08-20 16:35:10 +0000147 }
148 break;
danielk19770202b292004-06-09 09:55:16 +0000149 }
drhae80dde2012-12-06 21:16:43 +0000150 if( p->flags & EP_Collate ){
drh2308ed32015-02-09 16:09:34 +0000151 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
drhae80dde2012-12-06 21:16:43 +0000152 p = p->pLeft;
153 }else{
drh2308ed32015-02-09 16:09:34 +0000154 Expr *pNext = p->pRight;
drh6728cd92015-02-09 18:28:03 +0000155 /* The Expr.x union is never used at the same time as Expr.pRight */
156 assert( p->x.pList==0 || p->pRight==0 );
157 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
158 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
159 ** least one EP_Collate. Thus the following two ALWAYS. */
160 if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
drh2308ed32015-02-09 16:09:34 +0000161 int i;
drh6728cd92015-02-09 18:28:03 +0000162 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
drh2308ed32015-02-09 16:09:34 +0000163 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
164 pNext = p->x.pList->a[i].pExpr;
165 break;
166 }
167 }
168 }
169 p = pNext;
drhae80dde2012-12-06 21:16:43 +0000170 }
171 }else{
drh7d10d5a2008-08-20 16:35:10 +0000172 break;
173 }
danielk19770202b292004-06-09 09:55:16 +0000174 }
danielk19777cedc8d2004-06-10 10:50:08 +0000175 if( sqlite3CheckCollSeq(pParse, pColl) ){
176 pColl = 0;
177 }
178 return pColl;
danielk19770202b292004-06-09 09:55:16 +0000179}
180
181/*
drh626a8792005-01-17 22:08:19 +0000182** pExpr is an operand of a comparison operator. aff2 is the
183** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +0000184** type affinity that should be used for the comparison operator.
185*/
danielk1977e014a832004-05-17 10:48:57 +0000186char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +0000187 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +0000188 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +0000189 /* Both sides of the comparison are columns. If one has numeric
190 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +0000191 */
drh8a512562005-11-14 22:29:05 +0000192 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +0000193 return SQLITE_AFF_NUMERIC;
194 }else{
drh05883a32015-06-02 15:32:08 +0000195 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000196 }
197 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +0000198 /* Neither side of the comparison is a column. Compare the
199 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +0000200 */
drh05883a32015-06-02 15:32:08 +0000201 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000202 }else{
203 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +0000204 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +0000205 return (aff1 + aff2);
206 }
207}
208
drh53db1452004-05-20 13:54:53 +0000209/*
210** pExpr is a comparison operator. Return the type affinity that should
211** be applied to both operands prior to doing the comparison.
212*/
danielk1977e014a832004-05-17 10:48:57 +0000213static char comparisonAffinity(Expr *pExpr){
214 char aff;
215 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
216 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
drh6a2fe092009-09-23 02:29:36 +0000217 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
danielk1977e014a832004-05-17 10:48:57 +0000218 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000219 aff = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +0000220 if( pExpr->pRight ){
221 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
danielk19776ab3a2e2009-02-19 14:39:25 +0000222 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
223 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
224 }else if( !aff ){
drh05883a32015-06-02 15:32:08 +0000225 aff = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000226 }
227 return aff;
228}
229
230/*
231** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
232** idx_affinity is the affinity of an indexed column. Return true
233** if the index with affinity idx_affinity may be used to implement
234** the comparison in pExpr.
235*/
236int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
237 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000238 switch( aff ){
drh05883a32015-06-02 15:32:08 +0000239 case SQLITE_AFF_BLOB:
drh8a512562005-11-14 22:29:05 +0000240 return 1;
241 case SQLITE_AFF_TEXT:
242 return idx_affinity==SQLITE_AFF_TEXT;
243 default:
244 return sqlite3IsNumericAffinity(idx_affinity);
245 }
danielk1977e014a832004-05-17 10:48:57 +0000246}
247
danielk1977a37cdde2004-05-16 11:15:36 +0000248/*
drh35573352008-01-08 23:54:25 +0000249** Return the P5 value that should be used for a binary comparison
danielk1977a37cdde2004-05-16 11:15:36 +0000250** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
danielk1977a37cdde2004-05-16 11:15:36 +0000251*/
drh35573352008-01-08 23:54:25 +0000252static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
253 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
drh1bd10f82008-12-10 21:19:56 +0000254 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
drh35573352008-01-08 23:54:25 +0000255 return aff;
danielk1977a37cdde2004-05-16 11:15:36 +0000256}
257
drha2e00042002-01-22 03:13:42 +0000258/*
danielk19770202b292004-06-09 09:55:16 +0000259** Return a pointer to the collation sequence that should be used by
260** a binary comparison operator comparing pLeft and pRight.
261**
262** If the left hand expression has a collating sequence type, then it is
263** used. Otherwise the collation sequence for the right hand expression
264** is used, or the default (BINARY) if neither expression has a collating
265** type.
danielk1977bcbb04e2007-05-29 12:11:29 +0000266**
267** Argument pRight (but not pLeft) may be a null pointer. In this case,
268** it is not considered.
danielk19770202b292004-06-09 09:55:16 +0000269*/
drh0a0e1312007-08-07 17:04:59 +0000270CollSeq *sqlite3BinaryCompareCollSeq(
danielk1977bcbb04e2007-05-29 12:11:29 +0000271 Parse *pParse,
272 Expr *pLeft,
273 Expr *pRight
274){
drhec41dda2007-02-07 13:09:45 +0000275 CollSeq *pColl;
276 assert( pLeft );
drhae80dde2012-12-06 21:16:43 +0000277 if( pLeft->flags & EP_Collate ){
278 pColl = sqlite3ExprCollSeq(pParse, pLeft);
279 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
280 pColl = sqlite3ExprCollSeq(pParse, pRight);
drhec41dda2007-02-07 13:09:45 +0000281 }else{
282 pColl = sqlite3ExprCollSeq(pParse, pLeft);
283 if( !pColl ){
284 pColl = sqlite3ExprCollSeq(pParse, pRight);
285 }
danielk19770202b292004-06-09 09:55:16 +0000286 }
287 return pColl;
288}
289
290/*
drhbe5c89a2004-07-26 00:31:09 +0000291** Generate code for a comparison operator.
292*/
293static int codeCompare(
294 Parse *pParse, /* The parsing (and code generating) context */
295 Expr *pLeft, /* The left operand */
296 Expr *pRight, /* The right operand */
297 int opcode, /* The comparison opcode */
drh35573352008-01-08 23:54:25 +0000298 int in1, int in2, /* Register holding operands */
drhbe5c89a2004-07-26 00:31:09 +0000299 int dest, /* Jump here if true. */
300 int jumpIfNull /* If true, jump if either operand is NULL */
301){
drh35573352008-01-08 23:54:25 +0000302 int p5;
303 int addr;
304 CollSeq *p4;
305
306 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
307 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
308 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
309 (void*)p4, P4_COLLSEQ);
drh1bd10f82008-12-10 21:19:56 +0000310 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
drh35573352008-01-08 23:54:25 +0000311 return addr;
drhbe5c89a2004-07-26 00:31:09 +0000312}
313
dancfbb5e82016-07-13 19:48:13 +0000314/*
dan870a0702016-08-01 16:37:43 +0000315** Return true if expression pExpr is a vector, or false otherwise.
drhd832da72016-08-20 21:11:25 +0000316**
317** A vector is defined as any expression that results in two or more
318** columns of result. Every TK_VECTOR node is an vector because the
319** parser will not generate a TK_VECTOR with fewer than two entries.
320** But a TK_SELECT might be either a vector or a scalar. It is only
321** considered a vector if it has two or more result columns.
dan870a0702016-08-01 16:37:43 +0000322*/
323int sqlite3ExprIsVector(Expr *pExpr){
drh76dbe7a2016-08-20 21:02:38 +0000324 return sqlite3ExprVectorSize(pExpr)>1;
dan870a0702016-08-01 16:37:43 +0000325}
326
327/*
dancfbb5e82016-07-13 19:48:13 +0000328** If the expression passed as the only argument is of type TK_VECTOR
329** return the number of expressions in the vector. Or, if the expression
330** is a sub-select, return the number of columns in the sub-select. For
331** any other type of expression, return 1.
332*/
dan71c57db2016-07-09 20:23:55 +0000333int sqlite3ExprVectorSize(Expr *pExpr){
drh12abf402016-08-22 14:30:05 +0000334 u8 op = pExpr->op;
335 if( op==TK_REGISTER ) op = pExpr->op2;
336 if( op==TK_VECTOR ){
drh76dbe7a2016-08-20 21:02:38 +0000337 return pExpr->x.pList->nExpr;
drh12abf402016-08-22 14:30:05 +0000338 }else if( op==TK_SELECT ){
dan71c57db2016-07-09 20:23:55 +0000339 return pExpr->x.pSelect->pEList->nExpr;
drh76dbe7a2016-08-20 21:02:38 +0000340 }else{
341 return 1;
dan71c57db2016-07-09 20:23:55 +0000342 }
dan71c57db2016-07-09 20:23:55 +0000343}
344
danf9b2e052016-08-02 17:45:00 +0000345#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +0000346/*
drhfc7f27b2016-08-20 00:07:01 +0000347** Return a pointer to a subexpression of pVector that is the i-th
348** column of the vector (numbered starting with 0). The caller must
349** ensure that i is within range.
350**
drh76dbe7a2016-08-20 21:02:38 +0000351** If pVector is really a scalar (and "scalar" here includes subqueries
352** that return a single column!) then return pVector unmodified.
353**
drhfc7f27b2016-08-20 00:07:01 +0000354** pVector retains ownership of the returned subexpression.
355**
356** If the vector is a (SELECT ...) then the expression returned is
drh76dbe7a2016-08-20 21:02:38 +0000357** just the expression for the i-th term of the result set, and may
358** not be ready for evaluation because the table cursor has not yet
359** been positioned.
danba00e302016-07-23 20:24:06 +0000360*/
drhfc7f27b2016-08-20 00:07:01 +0000361Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
dan870a0702016-08-01 16:37:43 +0000362 assert( i<sqlite3ExprVectorSize(pVector) );
363 if( sqlite3ExprIsVector(pVector) ){
drh12abf402016-08-22 14:30:05 +0000364 if( pVector->op==TK_SELECT
365 || (pVector->op==TK_REGISTER && pVector->op2==TK_SELECT)
366 ){
dan870a0702016-08-01 16:37:43 +0000367 return pVector->x.pSelect->pEList->a[i].pExpr;
368 }else{
369 return pVector->x.pList->a[i].pExpr;
370 }
dan71c57db2016-07-09 20:23:55 +0000371 }
dan870a0702016-08-01 16:37:43 +0000372 return pVector;
dan71c57db2016-07-09 20:23:55 +0000373}
drhfc7f27b2016-08-20 00:07:01 +0000374#endif /* !defined(SQLITE_OMIT_SUBQUERY) */
375
376#ifndef SQLITE_OMIT_SUBQUERY
377/*
378** Compute and return a new Expr object which when passed to
379** sqlite3ExprCode() will generate all necessary code to compute
380** the iField-th column of the vector expression pVector.
381**
drh8762ec12016-08-20 01:06:22 +0000382** It is ok for pVector to be a scalar (as long as iField==0).
383** In that case, this routine works like sqlite3ExprDup().
384**
drhfc7f27b2016-08-20 00:07:01 +0000385** The caller owns the returned Expr object and is responsible for
386** ensuring that the returned value eventually gets freed.
387**
drh8762ec12016-08-20 01:06:22 +0000388** The caller retains ownership of pVector. If pVector is a TK_SELECT,
drh76dbe7a2016-08-20 21:02:38 +0000389** then the returne object will reference pVector and so pVector must remain
drh8762ec12016-08-20 01:06:22 +0000390** valid for the life of the returned object. If pVector is a TK_VECTOR
391** or a scalar expression, then it can be deleted as soon as this routine
drh76dbe7a2016-08-20 21:02:38 +0000392** returns.
drh8762ec12016-08-20 01:06:22 +0000393**
394** A trick to cause a TK_SELECT pVector to be deleted together with
395** the returned Expr object is to attach the pVector to the pRight field
396** of the returned TK_SELECT_COLUMN Expr object.
drhfc7f27b2016-08-20 00:07:01 +0000397*/
398Expr *sqlite3ExprForVectorField(
399 Parse *pParse, /* Parsing context */
400 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
drha1251bc2016-08-20 00:51:37 +0000401 int iField /* Which column of the vector to return */
drhfc7f27b2016-08-20 00:07:01 +0000402){
403 Expr *pRet;
drha1251bc2016-08-20 00:51:37 +0000404 if( pVector->op==TK_SELECT ){
405 assert( pVector->flags & EP_xIsSelect );
drhfc7f27b2016-08-20 00:07:01 +0000406 /* The TK_SELECT_COLUMN Expr node:
407 **
408 ** pLeft: pVector containing TK_SELECT
drh8762ec12016-08-20 01:06:22 +0000409 ** pRight: not used. But recursively deleted.
drhfc7f27b2016-08-20 00:07:01 +0000410 ** iColumn: Index of a column in pVector
411 ** pLeft->iTable: First in an array of register holding result, or 0
412 ** if the result is not yet computed.
413 **
414 ** sqlite3ExprDelete() specifically skips the recursive delete of
415 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
drh8762ec12016-08-20 01:06:22 +0000416 ** can be attached to pRight to cause this node to take ownership of
417 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
418 ** with the same pLeft pointer to the pVector, but only one of them
419 ** will own the pVector.
drhfc7f27b2016-08-20 00:07:01 +0000420 */
drh8bd0d582016-08-20 18:06:14 +0000421 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0, 0);
422 if( pRet ){
423 pRet->iColumn = iField;
424 pRet->pLeft = pVector;
425 }
drhfc7f27b2016-08-20 00:07:01 +0000426 assert( pRet==0 || pRet->iTable==0 );
427 }else{
drha1251bc2016-08-20 00:51:37 +0000428 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
429 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
drhfc7f27b2016-08-20 00:07:01 +0000430 }
431 return pRet;
432}
433#endif /* !define(SQLITE_OMIT_SUBQUERY) */
dan71c57db2016-07-09 20:23:55 +0000434
dan5c288b92016-07-30 21:02:33 +0000435/*
436** If expression pExpr is of type TK_SELECT, generate code to evaluate
437** it. Return the register in which the result is stored (or, if the
438** sub-select returns more than one column, the first in an array
439** of registers in which the result is stored).
440**
441** If pExpr is not a TK_SELECT expression, return 0.
442*/
443static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
dan8da209b2016-07-26 18:06:08 +0000444 int reg = 0;
danf9b2e052016-08-02 17:45:00 +0000445#ifndef SQLITE_OMIT_SUBQUERY
dan5c288b92016-07-30 21:02:33 +0000446 if( pExpr->op==TK_SELECT ){
447 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
dan8da209b2016-07-26 18:06:08 +0000448 }
danf9b2e052016-08-02 17:45:00 +0000449#endif
dan8da209b2016-07-26 18:06:08 +0000450 return reg;
451}
452
dan5c288b92016-07-30 21:02:33 +0000453/*
454** Argument pVector points to a vector expression - either a TK_VECTOR
dan870a0702016-08-01 16:37:43 +0000455** or TK_SELECT that returns more than one column. This function returns
456** the register number of a register that contains the value of
457** element iField of the vector.
458**
459** If pVector is a TK_SELECT expression, then code for it must have
460** already been generated using the exprCodeSubselect() routine. In this
461** case parameter regSelect should be the first in an array of registers
462** containing the results of the sub-select.
463**
464** If pVector is of type TK_VECTOR, then code for the requested field
465** is generated. In this case (*pRegFree) may be set to the number of
466** a temporary register to be freed by the caller before returning.
dan5c288b92016-07-30 21:02:33 +0000467**
468** Before returning, output parameter (*ppExpr) is set to point to the
469** Expr object corresponding to element iElem of the vector.
dan5c288b92016-07-30 21:02:33 +0000470*/
471static int exprVectorRegister(
472 Parse *pParse, /* Parse context */
473 Expr *pVector, /* Vector to extract element from */
dan870a0702016-08-01 16:37:43 +0000474 int iField, /* Field to extract from pVector */
dan5c288b92016-07-30 21:02:33 +0000475 int regSelect, /* First in array of registers */
476 Expr **ppExpr, /* OUT: Expression element */
477 int *pRegFree /* OUT: Temp register to free */
478){
drh12abf402016-08-22 14:30:05 +0000479 u8 op = pVector->op;
480 assert( op==TK_VECTOR || op==TK_SELECT || op==TK_REGISTER );
481 if( op==TK_REGISTER ){
482 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
483 return pVector->iTable+iField;
484 }
485 if( op==TK_SELECT ){
dan870a0702016-08-01 16:37:43 +0000486 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
487 return regSelect+iField;
dan5c288b92016-07-30 21:02:33 +0000488 }
dan870a0702016-08-01 16:37:43 +0000489 *ppExpr = pVector->x.pList->a[iField].pExpr;
dan5c288b92016-07-30 21:02:33 +0000490 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
491}
492
493/*
494** Expression pExpr is a comparison between two vector values. Compute
drh79752b62016-08-13 10:02:17 +0000495** the result of the comparison (1, 0, or NULL) and write that
496** result into register dest.
497**
498** The caller must satisfy the following preconditions:
499**
500** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
501** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
502** otherwise: op==pExpr->op and p5==0
dan5c288b92016-07-30 21:02:33 +0000503*/
drh79752b62016-08-13 10:02:17 +0000504static void codeVectorCompare(
505 Parse *pParse, /* Code generator context */
506 Expr *pExpr, /* The comparison operation */
507 int dest, /* Write results into this register */
508 u8 op, /* Comparison operator */
509 u8 p5 /* SQLITE_NULLEQ or zero */
510){
dan71c57db2016-07-09 20:23:55 +0000511 Vdbe *v = pParse->pVdbe;
512 Expr *pLeft = pExpr->pLeft;
513 Expr *pRight = pExpr->pRight;
514 int nLeft = sqlite3ExprVectorSize(pLeft);
515 int nRight = sqlite3ExprVectorSize(pRight);
dan71c57db2016-07-09 20:23:55 +0000516
517 /* Check that both sides of the comparison are vectors, and that
518 ** both are the same length. */
519 if( nLeft!=nRight ){
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
545 for(i=0; i<nLeft; i++){
546 int regFree1 = 0, regFree2 = 0;
547 Expr *pL, *pR;
548 int r1, r2;
drh79752b62016-08-13 10:02:17 +0000549 if( i>0 ) sqlite3ExprCachePush(pParse);
dan5c288b92016-07-30 21:02:33 +0000550 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
551 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
drh79752b62016-08-13 10:02:17 +0000552 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
553 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
554 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
555 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
556 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
557 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
558 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
dan71c57db2016-07-09 20:23:55 +0000559 sqlite3ReleaseTempReg(pParse, regFree1);
560 sqlite3ReleaseTempReg(pParse, regFree2);
drh79752b62016-08-13 10:02:17 +0000561 if( i>0 ) sqlite3ExprCachePop(pParse);
562 if( i==nLeft-1 ){
563 break;
564 }
565 if( opx==TK_EQ ){
566 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
567 p5 |= SQLITE_KEEPNULL;
568 }else if( opx==TK_NE ){
569 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
570 p5 |= SQLITE_KEEPNULL;
drha2f62922016-08-13 12:37:47 +0000571 }else{
572 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
573 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
drh79752b62016-08-13 10:02:17 +0000574 VdbeCoverageIf(v, op==TK_LT);
575 VdbeCoverageIf(v, op==TK_GT);
drh79752b62016-08-13 10:02:17 +0000576 VdbeCoverageIf(v, op==TK_LE);
577 VdbeCoverageIf(v, op==TK_GE);
578 if( i==nLeft-2 ) opx = op;
579 }
dan71c57db2016-07-09 20:23:55 +0000580 }
drh79752b62016-08-13 10:02:17 +0000581 sqlite3VdbeResolveLabel(v, addrDone);
dan71c57db2016-07-09 20:23:55 +0000582 }
dan71c57db2016-07-09 20:23:55 +0000583}
584
danielk19774b5255a2008-06-05 16:47:39 +0000585#if SQLITE_MAX_EXPR_DEPTH>0
586/*
587** Check that argument nHeight is less than or equal to the maximum
588** expression depth allowed. If it is not, leave an error message in
589** pParse.
590*/
drh7d10d5a2008-08-20 16:35:10 +0000591int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000592 int rc = SQLITE_OK;
593 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
594 if( nHeight>mxHeight ){
595 sqlite3ErrorMsg(pParse,
596 "Expression tree is too large (maximum depth %d)", mxHeight
597 );
598 rc = SQLITE_ERROR;
599 }
600 return rc;
601}
602
603/* The following three functions, heightOfExpr(), heightOfExprList()
604** and heightOfSelect(), are used to determine the maximum height
605** of any expression tree referenced by the structure passed as the
606** first argument.
607**
608** If this maximum height is greater than the current value pointed
609** to by pnHeight, the second parameter, then set *pnHeight to that
610** value.
611*/
612static void heightOfExpr(Expr *p, int *pnHeight){
613 if( p ){
614 if( p->nHeight>*pnHeight ){
615 *pnHeight = p->nHeight;
616 }
617 }
618}
619static void heightOfExprList(ExprList *p, int *pnHeight){
620 if( p ){
621 int i;
622 for(i=0; i<p->nExpr; i++){
623 heightOfExpr(p->a[i].pExpr, pnHeight);
624 }
625 }
626}
627static void heightOfSelect(Select *p, int *pnHeight){
628 if( p ){
629 heightOfExpr(p->pWhere, pnHeight);
630 heightOfExpr(p->pHaving, pnHeight);
631 heightOfExpr(p->pLimit, pnHeight);
632 heightOfExpr(p->pOffset, pnHeight);
633 heightOfExprList(p->pEList, pnHeight);
634 heightOfExprList(p->pGroupBy, pnHeight);
635 heightOfExprList(p->pOrderBy, pnHeight);
636 heightOfSelect(p->pPrior, pnHeight);
637 }
638}
639
640/*
641** Set the Expr.nHeight variable in the structure passed as an
642** argument. An expression with no children, Expr.pList or
643** Expr.pSelect member has a height of 1. Any other expression
644** has a height equal to the maximum height of any other
645** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000646**
647** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
648** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000649*/
650static void exprSetHeight(Expr *p){
651 int nHeight = 0;
652 heightOfExpr(p->pLeft, &nHeight);
653 heightOfExpr(p->pRight, &nHeight);
danielk19776ab3a2e2009-02-19 14:39:25 +0000654 if( ExprHasProperty(p, EP_xIsSelect) ){
655 heightOfSelect(p->x.pSelect, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000656 }else if( p->x.pList ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000657 heightOfExprList(p->x.pList, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000658 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
danielk19776ab3a2e2009-02-19 14:39:25 +0000659 }
danielk19774b5255a2008-06-05 16:47:39 +0000660 p->nHeight = nHeight + 1;
661}
662
663/*
664** Set the Expr.nHeight variable using the exprSetHeight() function. If
665** the height is greater than the maximum allowed expression depth,
666** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000667**
668** Also propagate all EP_Propagate flags from the Expr.x.pList into
669** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000670*/
drh2308ed32015-02-09 16:09:34 +0000671void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh74893a42015-03-22 10:23:17 +0000672 if( pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000673 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000674 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000675}
676
677/*
678** Return the maximum height of any expression tree referenced
679** by the select statement passed as an argument.
680*/
681int sqlite3SelectExprHeight(Select *p){
682 int nHeight = 0;
683 heightOfSelect(p, &nHeight);
684 return nHeight;
685}
drh2308ed32015-02-09 16:09:34 +0000686#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
687/*
688** Propagate all EP_Propagate flags from the Expr.x.pList into
689** Expr.flags.
690*/
691void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
692 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
693 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
694 }
695}
696#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000697#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
698
drhbe5c89a2004-07-26 00:31:09 +0000699/*
drhb7916a72009-05-27 10:31:29 +0000700** This routine is the core allocator for Expr nodes.
701**
drha76b5df2002-02-23 02:32:10 +0000702** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000703** for this node and for the pToken argument is a single allocation
704** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000705** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000706**
707** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000708** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000709** parameter is ignored if pToken is NULL or if the token does not
710** appear to be quoted. If the quotes were of the form "..." (double-quotes)
711** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000712**
713** Special case: If op==TK_INTEGER and pToken points to a string that
714** can be translated into a 32-bit integer, then the token is not
715** stored in u.zToken. Instead, the integer values is written
716** into u.iValue and the EP_IntValue flag is set. No extra storage
717** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000718*/
drhb7916a72009-05-27 10:31:29 +0000719Expr *sqlite3ExprAlloc(
danielk1977a1644fd2007-08-29 12:31:25 +0000720 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
drh17435752007-08-16 04:30:38 +0000721 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000722 const Token *pToken, /* Token argument. Might be NULL */
723 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000724){
drha76b5df2002-02-23 02:32:10 +0000725 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000726 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000727 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000728
drh575fad62016-02-05 13:38:36 +0000729 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000730 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000731 if( op!=TK_INTEGER || pToken->z==0
732 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
733 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000734 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000735 }
drhb7916a72009-05-27 10:31:29 +0000736 }
drh575fad62016-02-05 13:38:36 +0000737 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000738 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000739 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000740 pNew->op = (u8)op;
741 pNew->iAgg = -1;
742 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000743 if( nExtra==0 ){
744 pNew->flags |= EP_IntValue;
745 pNew->u.iValue = iValue;
746 }else{
drh33e619f2009-05-28 01:00:55 +0000747 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000748 assert( pToken->z!=0 || pToken->n==0 );
749 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000750 pNew->u.zToken[pToken->n] = 0;
drh244b9d62016-04-11 19:01:08 +0000751 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
752 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
drh33e619f2009-05-28 01:00:55 +0000753 sqlite3Dequote(pNew->u.zToken);
drh33e619f2009-05-28 01:00:55 +0000754 }
drhb7916a72009-05-27 10:31:29 +0000755 }
756 }
757#if SQLITE_MAX_EXPR_DEPTH>0
758 pNew->nHeight = 1;
759#endif
760 }
drha76b5df2002-02-23 02:32:10 +0000761 return pNew;
762}
763
764/*
drhb7916a72009-05-27 10:31:29 +0000765** Allocate a new expression node from a zero-terminated token that has
766** already been dequoted.
767*/
768Expr *sqlite3Expr(
769 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
770 int op, /* Expression opcode */
771 const char *zToken /* Token argument. Might be NULL */
772){
773 Token x;
774 x.z = zToken;
775 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
776 return sqlite3ExprAlloc(db, op, &x, 0);
777}
778
779/*
780** Attach subtrees pLeft and pRight to the Expr node pRoot.
781**
782** If pRoot==NULL that means that a memory allocation error has occurred.
783** In that case, delete the subtrees pLeft and pRight.
784*/
785void sqlite3ExprAttachSubtrees(
786 sqlite3 *db,
787 Expr *pRoot,
788 Expr *pLeft,
789 Expr *pRight
790){
791 if( pRoot==0 ){
792 assert( db->mallocFailed );
793 sqlite3ExprDelete(db, pLeft);
794 sqlite3ExprDelete(db, pRight);
795 }else{
796 if( pRight ){
797 pRoot->pRight = pRight;
drh885a5b02015-02-09 15:21:36 +0000798 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000799 }
800 if( pLeft ){
801 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000802 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000803 }
804 exprSetHeight(pRoot);
805 }
806}
807
808/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000809** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000810**
drhbf664462009-06-19 18:32:54 +0000811** One or both of the subtrees can be NULL. Return a pointer to the new
812** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
813** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000814*/
drh17435752007-08-16 04:30:38 +0000815Expr *sqlite3PExpr(
816 Parse *pParse, /* Parsing context */
817 int op, /* Expression opcode */
818 Expr *pLeft, /* Left operand */
819 Expr *pRight, /* Right operand */
820 const Token *pToken /* Argument token */
821){
drh5fb52ca2012-03-31 02:34:35 +0000822 Expr *p;
drh1167d322015-10-28 20:01:45 +0000823 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000824 /* Take advantage of short-circuit false optimization for AND */
825 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
826 }else{
drh1167d322015-10-28 20:01:45 +0000827 p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
drh5fb52ca2012-03-31 02:34:35 +0000828 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
829 }
dan2b359bd2010-10-28 11:31:23 +0000830 if( p ) {
831 sqlite3ExprCheckHeight(pParse, p->nHeight);
832 }
drh4e0cff62004-11-05 05:10:28 +0000833 return p;
834}
835
836/*
drh08de4f72016-04-11 01:06:47 +0000837** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
838** do a memory allocation failure) then delete the pSelect object.
839*/
840void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
841 if( pExpr ){
842 pExpr->x.pSelect = pSelect;
843 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
844 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
845 }else{
846 assert( pParse->db->mallocFailed );
847 sqlite3SelectDelete(pParse->db, pSelect);
848 }
849}
850
851
852/*
drh991a1982014-01-02 17:57:16 +0000853** If the expression is always either TRUE or FALSE (respectively),
854** then return 1. If one cannot determine the truth value of the
855** expression at compile-time return 0.
856**
857** This is an optimization. If is OK to return 0 here even if
858** the expression really is always false or false (a false negative).
859** But it is a bug to return 1 if the expression might have different
860** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000861**
862** Note that if the expression is part of conditional for a
863** LEFT JOIN, then we cannot determine at compile-time whether or not
864** is it true or false, so always return 0.
865*/
drh991a1982014-01-02 17:57:16 +0000866static int exprAlwaysTrue(Expr *p){
867 int v = 0;
868 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
869 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
870 return v!=0;
871}
drh5fb52ca2012-03-31 02:34:35 +0000872static int exprAlwaysFalse(Expr *p){
873 int v = 0;
874 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
875 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
876 return v==0;
877}
878
879/*
drh91bb0ee2004-09-01 03:06:34 +0000880** Join two expressions using an AND operator. If either expression is
881** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000882**
883** If one side or the other of the AND is known to be false, then instead
884** of returning an AND expression, just return a constant expression with
885** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000886*/
danielk19771e536952007-08-16 10:09:01 +0000887Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000888 if( pLeft==0 ){
889 return pRight;
890 }else if( pRight==0 ){
891 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000892 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
893 sqlite3ExprDelete(db, pLeft);
894 sqlite3ExprDelete(db, pRight);
895 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000896 }else{
drhb7916a72009-05-27 10:31:29 +0000897 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
898 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
899 return pNew;
drha76b5df2002-02-23 02:32:10 +0000900 }
901}
902
903/*
904** Construct a new expression node for a function with multiple
905** arguments.
906*/
drh17435752007-08-16 04:30:38 +0000907Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000908 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000909 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000910 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000911 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000912 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000913 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000914 return 0;
915 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000916 pNew->x.pList = pList;
917 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
drh2308ed32015-02-09 16:09:34 +0000918 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drha76b5df2002-02-23 02:32:10 +0000919 return pNew;
920}
921
922/*
drhfa6bc002004-09-07 16:19:52 +0000923** Assign a variable number to an expression that encodes a wildcard
924** in the original SQL statement.
925**
926** Wildcards consisting of a single "?" are assigned the next sequential
927** variable number.
928**
929** Wildcards of the form "?nnn" are assigned the number "nnn". We make
930** sure "nnn" is not too be to avoid a denial of service attack when
931** the SQL statement comes from an external source.
932**
drh51f49f12009-05-21 20:41:32 +0000933** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +0000934** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +0000935** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +0000936** assigned.
937*/
938void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
drh17435752007-08-16 04:30:38 +0000939 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +0000940 const char *z;
drh17435752007-08-16 04:30:38 +0000941
drhfa6bc002004-09-07 16:19:52 +0000942 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +0000943 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +0000944 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000945 assert( z!=0 );
946 assert( z[0]!=0 );
947 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +0000948 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +0000949 assert( z[0]=='?' );
drh8677d302009-11-04 13:17:14 +0000950 pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000951 }else{
drh124c0b42011-06-01 18:15:55 +0000952 ynVar x = 0;
953 u32 n = sqlite3Strlen30(z);
954 if( z[0]=='?' ){
955 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
956 ** use it as the variable number */
957 i64 i;
958 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
959 pExpr->iColumn = x = (ynVar)i;
960 testcase( i==0 );
961 testcase( i==1 );
962 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
963 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
964 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
965 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
966 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
967 x = 0;
drhfa6bc002004-09-07 16:19:52 +0000968 }
drh124c0b42011-06-01 18:15:55 +0000969 if( i>pParse->nVar ){
970 pParse->nVar = (int)i;
971 }
972 }else{
973 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
974 ** number as the prior appearance of the same name, or if the name
975 ** has never appeared before, reuse the same variable number
976 */
977 ynVar i;
978 for(i=0; i<pParse->nzVar; i++){
drh503a6862013-03-01 01:07:17 +0000979 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
drh124c0b42011-06-01 18:15:55 +0000980 pExpr->iColumn = x = (ynVar)i+1;
981 break;
982 }
983 }
984 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000985 }
drh124c0b42011-06-01 18:15:55 +0000986 if( x>0 ){
987 if( x>pParse->nzVar ){
988 char **a;
989 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
drh4a642b62016-02-05 01:55:27 +0000990 if( a==0 ){
991 assert( db->mallocFailed ); /* Error reported through mallocFailed */
992 return;
993 }
drh124c0b42011-06-01 18:15:55 +0000994 pParse->azVar = a;
995 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
996 pParse->nzVar = x;
drhfa6bc002004-09-07 16:19:52 +0000997 }
drh124c0b42011-06-01 18:15:55 +0000998 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
999 sqlite3DbFree(db, pParse->azVar[x-1]);
1000 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
drhfa6bc002004-09-07 16:19:52 +00001001 }
1002 }
1003 }
drhbb4957f2008-03-20 14:03:29 +00001004 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +00001005 sqlite3ErrorMsg(pParse, "too many SQL variables");
1006 }
drhfa6bc002004-09-07 16:19:52 +00001007}
1008
1009/*
danf6963f92009-11-23 14:39:14 +00001010** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +00001011*/
drh4f0010b2016-04-11 14:49:39 +00001012static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1013 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +00001014 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1015 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drhc5cd1242013-09-12 16:50:49 +00001016 if( !ExprHasProperty(p, EP_TokenOnly) ){
1017 /* The Expr.x union is never used at the same time as Expr.pRight */
1018 assert( p->x.pList==0 || p->pRight==0 );
dan71c57db2016-07-09 20:23:55 +00001019 if( p->op!=TK_SELECT_COLUMN ) sqlite3ExprDelete(db, p->pLeft);
drh33e619f2009-05-28 01:00:55 +00001020 sqlite3ExprDelete(db, p->pRight);
drhc5cd1242013-09-12 16:50:49 +00001021 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
danielk19776ab3a2e2009-02-19 14:39:25 +00001022 if( ExprHasProperty(p, EP_xIsSelect) ){
1023 sqlite3SelectDelete(db, p->x.pSelect);
1024 }else{
1025 sqlite3ExprListDelete(db, p->x.pList);
1026 }
1027 }
drh33e619f2009-05-28 01:00:55 +00001028 if( !ExprHasProperty(p, EP_Static) ){
1029 sqlite3DbFree(db, p);
1030 }
drha2e00042002-01-22 03:13:42 +00001031}
drh4f0010b2016-04-11 14:49:39 +00001032void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1033 if( p ) sqlite3ExprDeleteNN(db, p);
1034}
drha2e00042002-01-22 03:13:42 +00001035
drhd2687b72005-08-12 22:56:09 +00001036/*
danielk19776ab3a2e2009-02-19 14:39:25 +00001037** Return the number of bytes allocated for the expression structure
1038** passed as the first argument. This is always one of EXPR_FULLSIZE,
1039** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1040*/
1041static int exprStructSize(Expr *p){
1042 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001043 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1044 return EXPR_FULLSIZE;
1045}
1046
1047/*
drh33e619f2009-05-28 01:00:55 +00001048** The dupedExpr*Size() routines each return the number of bytes required
1049** to store a copy of an expression or expression tree. They differ in
1050** how much of the tree is measured.
1051**
1052** dupedExprStructSize() Size of only the Expr structure
1053** dupedExprNodeSize() Size of Expr + space for token
1054** dupedExprSize() Expr + token + subtree components
1055**
1056***************************************************************************
1057**
1058** The dupedExprStructSize() function returns two values OR-ed together:
1059** (1) the space required for a copy of the Expr structure only and
1060** (2) the EP_xxx flags that indicate what the structure size should be.
1061** The return values is always one of:
1062**
1063** EXPR_FULLSIZE
1064** EXPR_REDUCEDSIZE | EP_Reduced
1065** EXPR_TOKENONLYSIZE | EP_TokenOnly
1066**
1067** The size of the structure can be found by masking the return value
1068** of this routine with 0xfff. The flags can be found by masking the
1069** return value with EP_Reduced|EP_TokenOnly.
1070**
1071** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1072** (unreduced) Expr objects as they or originally constructed by the parser.
1073** During expression analysis, extra information is computed and moved into
1074** later parts of teh Expr object and that extra information might get chopped
1075** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +00001076** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +00001077** to reduce a pristine expression tree from the parser. The implementation
1078** of dupedExprStructSize() contain multiple assert() statements that attempt
1079** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +00001080*/
1081static int dupedExprStructSize(Expr *p, int flags){
1082 int nSize;
drh33e619f2009-05-28 01:00:55 +00001083 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +00001084 assert( EXPR_FULLSIZE<=0xfff );
1085 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
drh3c194692016-04-11 16:43:43 +00001086 if( 0==flags ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001087 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001088 }else{
drhc5cd1242013-09-12 16:50:49 +00001089 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +00001090 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +00001091 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +00001092 assert( !ExprHasProperty(p, EP_NoReduce) );
drhaecd8022013-09-13 18:15:15 +00001093 if( p->pLeft || p->x.pList ){
drh33e619f2009-05-28 01:00:55 +00001094 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1095 }else{
drhaecd8022013-09-13 18:15:15 +00001096 assert( p->pRight==0 );
drh33e619f2009-05-28 01:00:55 +00001097 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1098 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001099 }
1100 return nSize;
1101}
1102
1103/*
drh33e619f2009-05-28 01:00:55 +00001104** This function returns the space in bytes required to store the copy
1105** of the Expr structure and a copy of the Expr.u.zToken string (if that
1106** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +00001107*/
1108static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +00001109 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1110 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1111 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001112 }
danielk1977bc739712009-03-23 04:33:32 +00001113 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +00001114}
1115
1116/*
1117** Return the number of bytes required to create a duplicate of the
1118** expression passed as the first argument. The second argument is a
1119** mask containing EXPRDUP_XXX flags.
1120**
1121** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +00001122** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +00001123**
1124** If the EXPRDUP_REDUCE flag is set, then the return value includes
1125** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1126** and Expr.pRight variables (but not for any structures pointed to or
1127** descended from the Expr.x.pList or Expr.x.pSelect variables).
1128*/
1129static int dupedExprSize(Expr *p, int flags){
1130 int nByte = 0;
1131 if( p ){
1132 nByte = dupedExprNodeSize(p, flags);
1133 if( flags&EXPRDUP_REDUCE ){
drhb7916a72009-05-27 10:31:29 +00001134 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001135 }
1136 }
1137 return nByte;
1138}
1139
1140/*
1141** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1142** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +00001143** to store the copy of expression p, the copies of p->u.zToken
danielk19776ab3a2e2009-02-19 14:39:25 +00001144** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +00001145** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +00001146** portion of the buffer copied into by this function.
1147*/
drh3c194692016-04-11 16:43:43 +00001148static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1149 Expr *pNew; /* Value to return */
1150 u8 *zAlloc; /* Memory space from which to build Expr object */
1151 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1152
drh575fad62016-02-05 13:38:36 +00001153 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +00001154 assert( p );
1155 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1156 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +00001157
drh3c194692016-04-11 16:43:43 +00001158 /* Figure out where to write the new Expr structure. */
1159 if( pzBuffer ){
1160 zAlloc = *pzBuffer;
1161 staticFlag = EP_Static;
1162 }else{
1163 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1164 staticFlag = 0;
1165 }
1166 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001167
drh3c194692016-04-11 16:43:43 +00001168 if( pNew ){
1169 /* Set nNewSize to the size allocated for the structure pointed to
1170 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1171 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1172 ** by the copy of the p->u.zToken string (if any).
1173 */
1174 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1175 const int nNewSize = nStructSize & 0xfff;
1176 int nToken;
1177 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1178 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001179 }else{
drh3c194692016-04-11 16:43:43 +00001180 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001181 }
drh3c194692016-04-11 16:43:43 +00001182 if( dupFlags ){
1183 assert( ExprHasProperty(p, EP_Reduced)==0 );
1184 memcpy(zAlloc, p, nNewSize);
1185 }else{
1186 u32 nSize = (u32)exprStructSize(p);
1187 memcpy(zAlloc, p, nSize);
1188 if( nSize<EXPR_FULLSIZE ){
1189 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1190 }
1191 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001192
drh3c194692016-04-11 16:43:43 +00001193 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1194 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1195 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1196 pNew->flags |= staticFlag;
1197
1198 /* Copy the p->u.zToken string, if any. */
1199 if( nToken ){
1200 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1201 memcpy(zToken, p->u.zToken, nToken);
1202 }
1203
1204 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
1205 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1206 if( ExprHasProperty(p, EP_xIsSelect) ){
1207 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001208 }else{
drh3c194692016-04-11 16:43:43 +00001209 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001210 }
drh3c194692016-04-11 16:43:43 +00001211 }
1212
1213 /* Fill in pNew->pLeft and pNew->pRight. */
1214 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1215 zAlloc += dupedExprNodeSize(p, dupFlags);
1216 if( ExprHasProperty(pNew, EP_Reduced) ){
1217 pNew->pLeft = p->pLeft ?
1218 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1219 pNew->pRight = p->pRight ?
1220 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001221 }
drh3c194692016-04-11 16:43:43 +00001222 if( pzBuffer ){
1223 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001224 }
drh3c194692016-04-11 16:43:43 +00001225 }else{
1226 if( !ExprHasProperty(p, EP_TokenOnly) ){
drh98542602016-08-20 17:00:16 +00001227 if( pNew->op==TK_SELECT_COLUMN ){
1228 pNew->pLeft = p->pLeft;
1229 }else{
1230 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1231 }
drh3c194692016-04-11 16:43:43 +00001232 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
danielk19776ab3a2e2009-02-19 14:39:25 +00001233 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001234 }
1235 }
1236 return pNew;
1237}
1238
1239/*
danbfe31e72014-01-15 14:17:31 +00001240** Create and return a deep copy of the object passed as the second
1241** argument. If an OOM condition is encountered, NULL is returned
1242** and the db->mallocFailed flag set.
1243*/
daneede6a52014-01-15 19:42:23 +00001244#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +00001245static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +00001246 With *pRet = 0;
1247 if( p ){
1248 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1249 pRet = sqlite3DbMallocZero(db, nByte);
1250 if( pRet ){
1251 int i;
1252 pRet->nCte = p->nCte;
1253 for(i=0; i<p->nCte; i++){
1254 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1255 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1256 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1257 }
1258 }
1259 }
1260 return pRet;
1261}
daneede6a52014-01-15 19:42:23 +00001262#else
1263# define withDup(x,y) 0
1264#endif
dan4e9119d2014-01-13 15:12:23 +00001265
drha76b5df2002-02-23 02:32:10 +00001266/*
drhff78bd22002-02-27 01:47:11 +00001267** The following group of routines make deep copies of expressions,
1268** expression lists, ID lists, and select statements. The copies can
1269** be deleted (by being passed to their respective ...Delete() routines)
1270** without effecting the originals.
1271**
danielk19774adee202004-05-08 08:23:19 +00001272** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1273** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +00001274** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001275**
drhad3cab52002-05-24 02:04:32 +00001276** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001277**
drhb7916a72009-05-27 10:31:29 +00001278** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001279** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1280** truncated version of the usual Expr structure that will be stored as
1281** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001282*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001283Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001284 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001285 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001286}
danielk19776ab3a2e2009-02-19 14:39:25 +00001287ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001288 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001289 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001290 int i;
drh575fad62016-02-05 13:38:36 +00001291 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001292 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001293 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001294 if( pNew==0 ) return 0;
drhd872bb12012-02-02 01:58:08 +00001295 pNew->nExpr = i = p->nExpr;
1296 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
drh575fad62016-02-05 13:38:36 +00001297 pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +00001298 if( pItem==0 ){
drh633e6d52008-07-28 19:34:53 +00001299 sqlite3DbFree(db, pNew);
danielk1977e0048402004-06-15 16:51:01 +00001300 return 0;
1301 }
drh145716b2004-09-24 12:24:06 +00001302 pOldItem = p->a;
1303 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001304 Expr *pOldExpr = pOldItem->pExpr;
drhb5526ea2009-07-16 12:41:05 +00001305 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh17435752007-08-16 04:30:38 +00001306 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001307 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001308 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001309 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001310 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
drhc2acc4e2013-11-15 18:15:19 +00001311 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001312 }
1313 return pNew;
1314}
danielk197793758c82005-01-21 08:13:14 +00001315
1316/*
1317** If cursors, triggers, views and subqueries are all omitted from
1318** the build, then none of the following routines, except for
1319** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1320** called with a NULL argument.
1321*/
danielk19776a67fe82005-02-04 04:07:16 +00001322#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1323 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001324SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001325 SrcList *pNew;
1326 int i;
drh113088e2003-03-20 01:16:58 +00001327 int nByte;
drh575fad62016-02-05 13:38:36 +00001328 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001329 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001330 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001331 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001332 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001333 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001334 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001335 struct SrcList_item *pNewItem = &pNew->a[i];
1336 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001337 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001338 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001339 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1340 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1341 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001342 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001343 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001344 pNewItem->addrFillSub = pOldItem->addrFillSub;
1345 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001346 if( pNewItem->fg.isIndexedBy ){
1347 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1348 }
1349 pNewItem->pIBIndex = pOldItem->pIBIndex;
1350 if( pNewItem->fg.isTabFunc ){
1351 pNewItem->u1.pFuncArg =
1352 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1353 }
drhed8a3bb2005-06-06 21:19:56 +00001354 pTab = pNewItem->pTab = pOldItem->pTab;
1355 if( pTab ){
1356 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001357 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001358 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1359 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001360 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001361 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001362 }
1363 return pNew;
1364}
drh17435752007-08-16 04:30:38 +00001365IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001366 IdList *pNew;
1367 int i;
drh575fad62016-02-05 13:38:36 +00001368 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001369 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001370 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001371 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001372 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001373 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001374 if( pNew->a==0 ){
drh633e6d52008-07-28 19:34:53 +00001375 sqlite3DbFree(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001376 return 0;
1377 }
drh6c535152012-02-02 03:38:30 +00001378 /* Note that because the size of the allocation for p->a[] is not
1379 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1380 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001381 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001382 struct IdList_item *pNewItem = &pNew->a[i];
1383 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001384 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001385 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001386 }
1387 return pNew;
1388}
danielk19776ab3a2e2009-02-19 14:39:25 +00001389Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
drh23b1b372011-12-07 01:55:51 +00001390 Select *pNew, *pPrior;
drh575fad62016-02-05 13:38:36 +00001391 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001392 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001393 pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +00001394 if( pNew==0 ) return 0;
drhb7916a72009-05-27 10:31:29 +00001395 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001396 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1397 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1398 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1399 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1400 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
drhff78bd22002-02-27 01:47:11 +00001401 pNew->op = p->op;
drh23b1b372011-12-07 01:55:51 +00001402 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
1403 if( pPrior ) pPrior->pNext = pNew;
1404 pNew->pNext = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001405 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1406 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
drh92b01d52008-06-24 00:32:35 +00001407 pNew->iLimit = 0;
1408 pNew->iOffset = 0;
drh7d10d5a2008-08-20 16:35:10 +00001409 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
drhb9bb7c12006-06-11 23:41:55 +00001410 pNew->addrOpenEphm[0] = -1;
1411 pNew->addrOpenEphm[1] = -1;
drhec2da852014-01-29 01:46:12 +00001412 pNew->nSelectRow = p->nSelectRow;
dan4e9119d2014-01-13 15:12:23 +00001413 pNew->pWith = withDup(db, p->pWith);
drheb9b8842014-09-21 00:27:26 +00001414 sqlite3SelectSetName(pNew, p->zSelName);
drhff78bd22002-02-27 01:47:11 +00001415 return pNew;
1416}
danielk197793758c82005-01-21 08:13:14 +00001417#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001418Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001419 assert( p==0 );
1420 return 0;
1421}
1422#endif
drhff78bd22002-02-27 01:47:11 +00001423
1424
1425/*
drha76b5df2002-02-23 02:32:10 +00001426** Add a new element to the end of an expression list. If pList is
1427** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001428**
1429** If a memory allocation error occurs, the entire list is freed and
1430** NULL is returned. If non-NULL is returned, then it is guaranteed
1431** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001432*/
drh17435752007-08-16 04:30:38 +00001433ExprList *sqlite3ExprListAppend(
1434 Parse *pParse, /* Parsing context */
1435 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001436 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001437){
1438 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001439 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001440 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001441 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001442 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001443 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001444 }
drhc263f7c2016-01-18 13:18:54 +00001445 pList->nExpr = 0;
drh575fad62016-02-05 13:38:36 +00001446 pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
drhd872bb12012-02-02 01:58:08 +00001447 if( pList->a==0 ) goto no_mem;
1448 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001449 struct ExprList_item *a;
drhd872bb12012-02-02 01:58:08 +00001450 assert( pList->nExpr>0 );
1451 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001452 if( a==0 ){
1453 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001454 }
danielk1977d5d56522005-03-16 12:15:20 +00001455 pList->a = a;
drha76b5df2002-02-23 02:32:10 +00001456 }
drh4efc4752004-01-16 15:55:37 +00001457 assert( pList->a!=0 );
drhb7916a72009-05-27 10:31:29 +00001458 if( 1 ){
drh4efc4752004-01-16 15:55:37 +00001459 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1460 memset(pItem, 0, sizeof(*pItem));
danielk1977e94ddc92005-03-21 03:53:38 +00001461 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001462 }
1463 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001464
1465no_mem:
1466 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001467 sqlite3ExprDelete(db, pExpr);
1468 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001469 return 0;
drha76b5df2002-02-23 02:32:10 +00001470}
1471
1472/*
drh8762ec12016-08-20 01:06:22 +00001473** pColumns and pExpr form a vector assignment which is part of the SET
1474** clause of an UPDATE statement. Like this:
drha1251bc2016-08-20 00:51:37 +00001475**
1476** (a,b,c) = (expr1,expr2,expr3)
1477** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1478**
1479** For each term of the vector assignment, append new entries to the
drh8762ec12016-08-20 01:06:22 +00001480** expression list pList. In the case of a subquery on the LHS, append
drha1251bc2016-08-20 00:51:37 +00001481** TK_SELECT_COLUMN expressions.
1482*/
1483ExprList *sqlite3ExprListAppendVector(
1484 Parse *pParse, /* Parsing context */
1485 ExprList *pList, /* List to which to append. Might be NULL */
1486 IdList *pColumns, /* List of names of LHS of the assignment */
1487 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1488){
1489 sqlite3 *db = pParse->db;
1490 int n;
1491 int i;
drh66860af2016-08-23 18:30:10 +00001492 int iFirst = pList ? pList->nExpr : 0;
drha1251bc2016-08-20 00:51:37 +00001493 if( pColumns==0 ) goto vector_append_error;
1494 if( pExpr==0 ) goto vector_append_error;
1495 n = sqlite3ExprVectorSize(pExpr);
1496 if( pColumns->nId!=n ){
1497 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1498 pColumns->nId, n);
1499 goto vector_append_error;
1500 }
1501 for(i=0; i<n; i++){
1502 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1503 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1504 if( pList ){
drh66860af2016-08-23 18:30:10 +00001505 assert( pList->nExpr==iFirst+i+1 );
drha1251bc2016-08-20 00:51:37 +00001506 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1507 pColumns->a[i].zName = 0;
1508 }
1509 }
1510 if( pExpr->op==TK_SELECT ){
drh66860af2016-08-23 18:30:10 +00001511 if( pList && pList->a[iFirst].pExpr ){
1512 assert( pList->a[iFirst].pExpr->op==TK_SELECT_COLUMN );
1513 pList->a[iFirst].pExpr->pRight = pExpr;
drha1251bc2016-08-20 00:51:37 +00001514 pExpr = 0;
1515 }
1516 }
1517
1518vector_append_error:
1519 sqlite3ExprDelete(db, pExpr);
1520 sqlite3IdListDelete(db, pColumns);
1521 return pList;
1522}
1523
1524/*
drhbc622bc2015-08-24 15:39:42 +00001525** Set the sort order for the last element on the given ExprList.
1526*/
1527void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1528 if( p==0 ) return;
1529 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1530 assert( p->nExpr>0 );
1531 if( iSortOrder<0 ){
1532 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1533 return;
1534 }
1535 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001536}
1537
1538/*
drhb7916a72009-05-27 10:31:29 +00001539** Set the ExprList.a[].zName element of the most recently added item
1540** on the expression list.
1541**
1542** pList might be NULL following an OOM error. But pName should never be
1543** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1544** is set.
1545*/
1546void sqlite3ExprListSetName(
1547 Parse *pParse, /* Parsing context */
1548 ExprList *pList, /* List to which to add the span. */
1549 Token *pName, /* Name to be added */
1550 int dequote /* True to cause the name to be dequoted */
1551){
1552 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1553 if( pList ){
1554 struct ExprList_item *pItem;
1555 assert( pList->nExpr>0 );
1556 pItem = &pList->a[pList->nExpr-1];
1557 assert( pItem->zName==0 );
1558 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001559 if( dequote ) sqlite3Dequote(pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001560 }
1561}
1562
1563/*
1564** Set the ExprList.a[].zSpan element of the most recently added item
1565** on the expression list.
1566**
1567** pList might be NULL following an OOM error. But pSpan should never be
1568** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1569** is set.
1570*/
1571void sqlite3ExprListSetSpan(
1572 Parse *pParse, /* Parsing context */
1573 ExprList *pList, /* List to which to add the span. */
1574 ExprSpan *pSpan /* The span to be added */
1575){
1576 sqlite3 *db = pParse->db;
1577 assert( pList!=0 || db->mallocFailed!=0 );
1578 if( pList ){
1579 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1580 assert( pList->nExpr>0 );
1581 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1582 sqlite3DbFree(db, pItem->zSpan);
1583 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001584 (int)(pSpan->zEnd - pSpan->zStart));
drhb7916a72009-05-27 10:31:29 +00001585 }
1586}
1587
1588/*
danielk19777a15a4b2007-05-08 17:54:43 +00001589** If the expression list pEList contains more than iLimit elements,
1590** leave an error message in pParse.
1591*/
1592void sqlite3ExprListCheckLength(
1593 Parse *pParse,
1594 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001595 const char *zObject
1596){
drhb1a6c3c2008-03-20 16:30:17 +00001597 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001598 testcase( pEList && pEList->nExpr==mx );
1599 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001600 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001601 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1602 }
1603}
1604
1605/*
drha76b5df2002-02-23 02:32:10 +00001606** Delete an entire expression list.
1607*/
drhaffa8552016-04-11 18:25:05 +00001608static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drha76b5df2002-02-23 02:32:10 +00001609 int i;
drhbe5c89a2004-07-26 00:31:09 +00001610 struct ExprList_item *pItem;
drhd872bb12012-02-02 01:58:08 +00001611 assert( pList->a!=0 || pList->nExpr==0 );
drhbe5c89a2004-07-26 00:31:09 +00001612 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00001613 sqlite3ExprDelete(db, pItem->pExpr);
1614 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001615 sqlite3DbFree(db, pItem->zSpan);
drha76b5df2002-02-23 02:32:10 +00001616 }
drh633e6d52008-07-28 19:34:53 +00001617 sqlite3DbFree(db, pList->a);
1618 sqlite3DbFree(db, pList);
drha76b5df2002-02-23 02:32:10 +00001619}
drhaffa8552016-04-11 18:25:05 +00001620void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1621 if( pList ) exprListDeleteNN(db, pList);
1622}
drha76b5df2002-02-23 02:32:10 +00001623
1624/*
drh2308ed32015-02-09 16:09:34 +00001625** Return the bitwise-OR of all Expr.flags fields in the given
1626** ExprList.
drh885a5b02015-02-09 15:21:36 +00001627*/
drh2308ed32015-02-09 16:09:34 +00001628u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001629 int i;
drh2308ed32015-02-09 16:09:34 +00001630 u32 m = 0;
1631 if( pList ){
1632 for(i=0; i<pList->nExpr; i++){
drhd0c73052015-04-19 19:21:19 +00001633 Expr *pExpr = pList->a[i].pExpr;
drhde845c22016-03-17 19:07:52 +00001634 assert( pExpr!=0 );
1635 m |= pExpr->flags;
drh2308ed32015-02-09 16:09:34 +00001636 }
drh885a5b02015-02-09 15:21:36 +00001637 }
drh2308ed32015-02-09 16:09:34 +00001638 return m;
drh885a5b02015-02-09 15:21:36 +00001639}
1640
1641/*
drh059b2d52014-10-24 19:28:09 +00001642** These routines are Walker callbacks used to check expressions to
1643** see if they are "constant" for some definition of constant. The
1644** Walker.eCode value determines the type of "constant" we are looking
1645** for.
drh73b211a2005-01-18 04:00:42 +00001646**
drh7d10d5a2008-08-20 16:35:10 +00001647** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001648**
drh059b2d52014-10-24 19:28:09 +00001649** sqlite3ExprIsConstant() pWalker->eCode==1
1650** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001651** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001652** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001653**
drh059b2d52014-10-24 19:28:09 +00001654** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1655** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001656**
drhfeada2d2014-09-24 13:20:22 +00001657** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001658** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1659** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001660** parameter raises an error for new statements, but is silently converted
1661** to NULL for existing schemas. This allows sqlite_master tables that
1662** contain a bound parameter because they were generated by older versions
1663** of SQLite to be parsed by newer versions of SQLite without raising a
1664** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001665*/
drh7d10d5a2008-08-20 16:35:10 +00001666static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001667
drh059b2d52014-10-24 19:28:09 +00001668 /* If pWalker->eCode is 2 then any term of the expression that comes from
1669 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001670 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001671 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1672 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001673 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001674 }
1675
drh626a8792005-01-17 22:08:19 +00001676 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001677 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001678 ** and either pWalker->eCode==4 or 5 or the function has the
1679 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001680 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001681 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001682 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001683 }else{
1684 pWalker->eCode = 0;
1685 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001686 }
drh626a8792005-01-17 22:08:19 +00001687 case TK_ID:
1688 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001689 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001690 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001691 testcase( pExpr->op==TK_ID );
1692 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001693 testcase( pExpr->op==TK_AGG_FUNCTION );
1694 testcase( pExpr->op==TK_AGG_COLUMN );
drh059b2d52014-10-24 19:28:09 +00001695 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1696 return WRC_Continue;
1697 }else{
1698 pWalker->eCode = 0;
1699 return WRC_Abort;
1700 }
drhfeada2d2014-09-24 13:20:22 +00001701 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001702 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001703 /* Silently convert bound parameters that appear inside of CREATE
1704 ** statements into a NULL when parsing the CREATE statement text out
1705 ** of the sqlite_master table */
1706 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001707 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001708 /* A bound parameter in a CREATE statement that originates from
1709 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001710 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001711 return WRC_Abort;
1712 }
1713 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001714 default:
drhb74b1012009-05-28 21:04:37 +00001715 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1716 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
drh7d10d5a2008-08-20 16:35:10 +00001717 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001718 }
1719}
danielk197762c14b32008-11-19 09:05:26 +00001720static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1721 UNUSED_PARAMETER(NotUsed);
drh059b2d52014-10-24 19:28:09 +00001722 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001723 return WRC_Abort;
1724}
drh059b2d52014-10-24 19:28:09 +00001725static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001726 Walker w;
drhaa87f9a2013-04-25 00:57:10 +00001727 memset(&w, 0, sizeof(w));
drh059b2d52014-10-24 19:28:09 +00001728 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001729 w.xExprCallback = exprNodeIsConstant;
1730 w.xSelectCallback = selectNodeIsConstant;
drh059b2d52014-10-24 19:28:09 +00001731 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001732 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001733 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001734}
drh626a8792005-01-17 22:08:19 +00001735
1736/*
drh059b2d52014-10-24 19:28:09 +00001737** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001738** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001739**
1740** For the purposes of this function, a double-quoted string (ex: "abc")
1741** is considered a variable but a single-quoted string (ex: 'abc') is
1742** a constant.
drhfef52082000-06-06 01:50:43 +00001743*/
danielk19774adee202004-05-08 08:23:19 +00001744int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001745 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001746}
1747
1748/*
drh059b2d52014-10-24 19:28:09 +00001749** Walk an expression tree. Return non-zero if the expression is constant
drh0a168372007-06-08 00:20:47 +00001750** that does no originate from the ON or USING clauses of a join.
1751** Return 0 if it involves variables or function calls or terms from
1752** an ON or USING clause.
1753*/
1754int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001755 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001756}
1757
1758/*
drhfcb9f4f2015-06-01 18:13:16 +00001759** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00001760** for any single row of the table with cursor iCur. In other words, the
1761** expression must not refer to any non-deterministic function nor any
1762** table other than iCur.
1763*/
1764int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1765 return exprIsConst(p, 3, iCur);
1766}
1767
1768/*
1769** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001770** or a function call with constant arguments. Return and 0 if there
1771** are any variables.
1772**
1773** For the purposes of this function, a double-quoted string (ex: "abc")
1774** is considered a variable but a single-quoted string (ex: 'abc') is
1775** a constant.
1776*/
drhfeada2d2014-09-24 13:20:22 +00001777int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1778 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00001779 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00001780}
1781
drh5b88bc42013-12-07 23:35:21 +00001782#ifdef SQLITE_ENABLE_CURSOR_HINTS
1783/*
1784** Walk an expression tree. Return 1 if the expression contains a
1785** subquery of some kind. Return 0 if there are no subqueries.
1786*/
1787int sqlite3ExprContainsSubquery(Expr *p){
1788 Walker w;
1789 memset(&w, 0, sizeof(w));
drhbec24762015-08-13 20:07:13 +00001790 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00001791 w.xExprCallback = sqlite3ExprWalkNoop;
1792 w.xSelectCallback = selectNodeIsConstant;
1793 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00001794 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00001795}
1796#endif
1797
drheb55bd22005-06-30 17:04:21 +00001798/*
drh73b211a2005-01-18 04:00:42 +00001799** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001800** to fit in a 32-bit integer, return 1 and put the value of the integer
1801** in *pValue. If the expression is not an integer or if it is too big
1802** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001803*/
danielk19774adee202004-05-08 08:23:19 +00001804int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00001805 int rc = 0;
drhcd92e842011-02-17 15:58:20 +00001806
1807 /* If an expression is an integer literal that fits in a signed 32-bit
1808 ** integer, then the EP_IntValue flag will have already been set */
1809 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1810 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1811
drh92b01d52008-06-24 00:32:35 +00001812 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00001813 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00001814 return 1;
1815 }
drhe4de1fe2002-06-02 16:09:01 +00001816 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00001817 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00001818 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00001819 break;
drh4b59ab52002-08-24 18:24:51 +00001820 }
drhe4de1fe2002-06-02 16:09:01 +00001821 case TK_UMINUS: {
1822 int v;
danielk19774adee202004-05-08 08:23:19 +00001823 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00001824 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00001825 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00001826 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00001827 }
1828 break;
1829 }
1830 default: break;
1831 }
drh92b01d52008-06-24 00:32:35 +00001832 return rc;
drhe4de1fe2002-06-02 16:09:01 +00001833}
1834
1835/*
drh039fc322009-11-17 18:31:47 +00001836** Return FALSE if there is no chance that the expression can be NULL.
1837**
1838** If the expression might be NULL or if the expression is too complex
1839** to tell return TRUE.
1840**
1841** This routine is used as an optimization, to skip OP_IsNull opcodes
1842** when we know that a value cannot be NULL. Hence, a false positive
1843** (returning TRUE when in fact the expression can never be NULL) might
1844** be a small performance hit but is otherwise harmless. On the other
1845** hand, a false negative (returning FALSE when the result could be NULL)
1846** will likely result in an incorrect answer. So when in doubt, return
1847** TRUE.
1848*/
1849int sqlite3ExprCanBeNull(const Expr *p){
1850 u8 op;
drhcd7f4572009-11-19 14:48:40 +00001851 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001852 op = p->op;
1853 if( op==TK_REGISTER ) op = p->op2;
1854 switch( op ){
1855 case TK_INTEGER:
1856 case TK_STRING:
1857 case TK_FLOAT:
1858 case TK_BLOB:
1859 return 0;
drh7248a8b2014-08-04 18:50:54 +00001860 case TK_COLUMN:
1861 assert( p->pTab!=0 );
drh72673a22014-12-04 16:27:17 +00001862 return ExprHasProperty(p, EP_CanBeNull) ||
1863 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00001864 default:
1865 return 1;
1866 }
1867}
1868
1869/*
1870** Return TRUE if the given expression is a constant which would be
1871** unchanged by OP_Affinity with the affinity given in the second
1872** argument.
1873**
1874** This routine is used to determine if the OP_Affinity operation
1875** can be omitted. When in doubt return FALSE. A false negative
1876** is harmless. A false positive, however, can result in the wrong
1877** answer.
1878*/
1879int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1880 u8 op;
drh05883a32015-06-02 15:32:08 +00001881 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00001882 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001883 op = p->op;
1884 if( op==TK_REGISTER ) op = p->op2;
1885 switch( op ){
1886 case TK_INTEGER: {
1887 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1888 }
1889 case TK_FLOAT: {
1890 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1891 }
1892 case TK_STRING: {
1893 return aff==SQLITE_AFF_TEXT;
1894 }
1895 case TK_BLOB: {
1896 return 1;
1897 }
drh2f2855b2009-11-18 01:25:26 +00001898 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00001899 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1900 return p->iColumn<0
1901 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00001902 }
drh039fc322009-11-17 18:31:47 +00001903 default: {
1904 return 0;
1905 }
1906 }
1907}
1908
1909/*
drhc4a3c772001-04-04 11:48:57 +00001910** Return TRUE if the given string is a row-id column name.
1911*/
danielk19774adee202004-05-08 08:23:19 +00001912int sqlite3IsRowid(const char *z){
1913 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1914 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1915 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001916 return 0;
1917}
1918
danielk19779a96b662007-11-29 17:05:18 +00001919/*
drh69c355b2016-03-09 15:34:51 +00001920** pX is the RHS of an IN operator. If pX is a SELECT statement
1921** that can be simplified to a direct table access, then return
1922** a pointer to the SELECT statement. If pX is not a SELECT statement,
1923** or if the SELECT statement needs to be manifested into a transient
1924** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00001925*/
1926#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00001927static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00001928 Select *p;
drhb287f4b2008-04-25 00:08:38 +00001929 SrcList *pSrc;
1930 ExprList *pEList;
1931 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00001932 int i;
drh69c355b2016-03-09 15:34:51 +00001933 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1934 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1935 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00001936 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00001937 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00001938 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1939 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1940 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00001941 }
drhb74b1012009-05-28 21:04:37 +00001942 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00001943 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb74b1012009-05-28 21:04:37 +00001944 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
drhb287f4b2008-04-25 00:08:38 +00001945 if( p->pWhere ) return 0; /* Has no WHERE clause */
1946 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00001947 assert( pSrc!=0 );
1948 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00001949 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00001950 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00001951 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00001952 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00001953 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1954 pEList = p->pEList;
drhac6b47d2016-08-24 00:51:48 +00001955 assert( pEList!=0 );
dancfbb5e82016-07-13 19:48:13 +00001956
dan7b35a772016-07-28 19:47:15 +00001957 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00001958 for(i=0; i<pEList->nExpr; i++){
1959 Expr *pRes = pEList->a[i].pExpr;
1960 if( pRes->op!=TK_COLUMN ) return 0;
1961 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00001962 }
drh69c355b2016-03-09 15:34:51 +00001963 return p;
drhb287f4b2008-04-25 00:08:38 +00001964}
1965#endif /* SQLITE_OMIT_SUBQUERY */
1966
1967/*
dan1d8cb212011-12-09 13:24:16 +00001968** Code an OP_Once instruction and allocate space for its flag. Return the
1969** address of the new instruction.
1970*/
1971int sqlite3CodeOnce(Parse *pParse){
1972 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1973 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1974}
1975
danf9b2e052016-08-02 17:45:00 +00001976#ifndef SQLITE_OMIT_SUBQUERY
dan1d8cb212011-12-09 13:24:16 +00001977/*
drh4c259e92014-08-01 21:12:35 +00001978** Generate code that checks the left-most column of index table iCur to see if
1979** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00001980** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1981** to be set to NULL if iCur contains one or more NULL values.
1982*/
1983static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00001984 int addr1;
drh6be515e2014-08-01 21:00:53 +00001985 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00001986 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00001987 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
1988 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00001989 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00001990 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00001991}
danf9b2e052016-08-02 17:45:00 +00001992#endif
drh6be515e2014-08-01 21:00:53 +00001993
drhbb53ecb2014-08-02 21:03:33 +00001994
1995#ifndef SQLITE_OMIT_SUBQUERY
1996/*
1997** The argument is an IN operator with a list (not a subquery) on the
1998** right-hand side. Return TRUE if that list is constant.
1999*/
2000static int sqlite3InRhsIsConstant(Expr *pIn){
2001 Expr *pLHS;
2002 int res;
2003 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
2004 pLHS = pIn->pLeft;
2005 pIn->pLeft = 0;
2006 res = sqlite3ExprIsConstant(pIn);
2007 pIn->pLeft = pLHS;
2008 return res;
2009}
2010#endif
2011
drh6be515e2014-08-01 21:00:53 +00002012/*
danielk19779a96b662007-11-29 17:05:18 +00002013** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00002014** The pX parameter is the expression on the RHS of the IN operator, which
2015** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00002016**
drhd4305ca2012-09-18 17:08:33 +00002017** The job of this routine is to find or create a b-tree object that can
2018** be used either to test for membership in the RHS set or to iterate through
2019** all members of the RHS set, skipping duplicates.
2020**
drh3a856252014-08-01 14:46:57 +00002021** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00002022** and pX->iTable is set to the index of that cursor.
2023**
drhb74b1012009-05-28 21:04:37 +00002024** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00002025**
drh1ccce442013-03-12 20:38:51 +00002026** IN_INDEX_ROWID - The cursor was opened on a database table.
2027** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2028** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2029** IN_INDEX_EPH - The cursor was opened on a specially created and
2030** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00002031** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2032** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00002033**
drhd4305ca2012-09-18 17:08:33 +00002034** An existing b-tree might be used if the RHS expression pX is a simple
2035** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00002036**
dan553168c2016-08-01 20:14:31 +00002037** SELECT <column1>, <column2>... FROM <table>
danielk19779a96b662007-11-29 17:05:18 +00002038**
drhd4305ca2012-09-18 17:08:33 +00002039** If the RHS of the IN operator is a list or a more complex subquery, then
2040** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00002041** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00002042** existing table.
drhd4305ca2012-09-18 17:08:33 +00002043**
drh3a856252014-08-01 14:46:57 +00002044** The inFlags parameter must contain exactly one of the bits
2045** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
2046** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
2047** fast membership test. When the IN_INDEX_LOOP bit is set, the
2048** IN index will be used to loop over all values of the RHS of the
2049** IN operator.
2050**
2051** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2052** through the set members) then the b-tree must not contain duplicates.
dan553168c2016-08-01 20:14:31 +00002053** An epheremal table must be used unless the selected columns are guaranteed
2054** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2055** a UNIQUE constraint or index.
danielk19770cdc0222008-06-26 18:04:03 +00002056**
drh3a856252014-08-01 14:46:57 +00002057** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2058** for fast set membership tests) then an epheremal table must
dan553168c2016-08-01 20:14:31 +00002059** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2060** index can be found with the specified <columns> as its left-most.
danielk19770cdc0222008-06-26 18:04:03 +00002061**
drhbb53ecb2014-08-02 21:03:33 +00002062** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2063** if the RHS of the IN operator is a list (not a subquery) then this
2064** routine might decide that creating an ephemeral b-tree for membership
2065** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2066** calling routine should implement the IN operator using a sequence
2067** of Eq or Ne comparison operations.
2068**
drhb74b1012009-05-28 21:04:37 +00002069** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00002070** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00002071** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00002072** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00002073** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00002074** to *prRhsHasNull. If there is no chance that the (...) contains a
2075** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00002076**
drhe21a6e12014-08-01 18:00:24 +00002077** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00002078** the value in that register will be NULL if the b-tree contains one or more
2079** NULL values, and it will be some non-NULL value if the b-tree contains no
2080** NULL values.
dan553168c2016-08-01 20:14:31 +00002081**
2082** If the aiMap parameter is not NULL, it must point to an array containing
2083** one element for each column returned by the SELECT statement on the RHS
2084** of the IN(...) operator. The i'th entry of the array is populated with the
2085** offset of the index column that matches the i'th column returned by the
2086** SELECT. For example, if the expression and selected index are:
2087**
2088** (?,?,?) IN (SELECT a, b, c FROM t1)
2089** CREATE INDEX i1 ON t1(b, c, a);
2090**
2091** then aiMap[] is populated with {2, 0, 1}.
danielk19779a96b662007-11-29 17:05:18 +00002092*/
danielk1977284f4ac2007-12-10 05:03:46 +00002093#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00002094int sqlite3FindInIndex(
2095 Parse *pParse,
2096 Expr *pX,
2097 u32 inFlags,
2098 int *prRhsHasNull,
2099 int *aiMap
2100){
drhb74b1012009-05-28 21:04:37 +00002101 Select *p; /* SELECT to the right of IN operator */
2102 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2103 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00002104 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00002105 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00002106
drh1450bc62009-10-30 13:25:56 +00002107 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00002108 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00002109
dan7b35a772016-07-28 19:47:15 +00002110 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2111 ** whether or not the SELECT result contains NULL values, check whether
dan870a0702016-08-01 16:37:43 +00002112 ** or not NULL is actually possible (it may not be, for example, due
dan7b35a772016-07-28 19:47:15 +00002113 ** to NOT NULL constraints in the schema). If no NULL values are possible,
dan870a0702016-08-01 16:37:43 +00002114 ** set prRhsHasNull to 0 before continuing. */
dan7b35a772016-07-28 19:47:15 +00002115 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
2116 int i;
2117 ExprList *pEList = pX->x.pSelect->pEList;
2118 for(i=0; i<pEList->nExpr; i++){
2119 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2120 }
2121 if( i==pEList->nExpr ){
2122 prRhsHasNull = 0;
2123 }
2124 }
2125
drhb74b1012009-05-28 21:04:37 +00002126 /* Check to see if an existing table or index can be used to
2127 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00002128 ** ephemeral table. */
2129 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00002130 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00002131 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00002132 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00002133 ExprList *pEList = p->pEList;
2134 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00002135
drhb07028f2011-10-14 21:49:18 +00002136 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2137 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2138 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2139 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00002140
drhb22f7c82014-02-06 23:56:27 +00002141 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00002142 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2143 sqlite3CodeVerifySchema(pParse, iDb);
2144 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00002145
2146 /* This function is only called from two places. In both cases the vdbe
2147 ** has already been allocated. So assume sqlite3GetVdbe() is always
2148 ** successful here.
2149 */
2150 assert(v);
dancfbb5e82016-07-13 19:48:13 +00002151 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh7d176102014-02-18 03:07:12 +00002152 int iAddr = sqlite3CodeOnce(pParse);
2153 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002154
2155 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2156 eType = IN_INDEX_ROWID;
2157
2158 sqlite3VdbeJumpHere(v, iAddr);
2159 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002160 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002161 int affinity_ok = 1;
2162 int i;
2163
2164 /* Check that the affinity that will be used to perform each
2165 ** comparison is the same as the affinity of each column. If
2166 ** it not, it is not possible to use any index. */
2167 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002168 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002169 int iCol = pEList->a[i].pExpr->iColumn;
2170 char idxaff = pTab->aCol[iCol].affinity;
2171 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
2172 switch( cmpaff ){
2173 case SQLITE_AFF_BLOB:
2174 break;
2175 case SQLITE_AFF_TEXT:
2176 affinity_ok = (idxaff==SQLITE_AFF_TEXT);
2177 break;
2178 default:
2179 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2180 }
2181 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002182
drhb74b1012009-05-28 21:04:37 +00002183 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00002184 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00002185 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00002186
2187 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
dancfbb5e82016-07-13 19:48:13 +00002188 if( pIdx->nKeyCol<nExpr ) continue;
2189 if( mustBeUnique && (pIdx->nKeyCol!=nExpr || !IsUniqueIndex(pIdx)) ){
2190 continue;
2191 }
2192
2193 for(i=0; i<nExpr; i++){
drhfc7f27b2016-08-20 00:07:01 +00002194 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002195 Expr *pRhs = pEList->a[i].pExpr;
2196 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
2197 int j;
2198
dan17994e32016-08-11 12:01:52 +00002199 assert( pReq || pParse->nErr );
2200 if( pReq==0 ) break;
2201
dancfbb5e82016-07-13 19:48:13 +00002202 for(j=0; j<nExpr; j++){
2203 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2204 assert( pIdx->azColl[j] );
2205 if( sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ) continue;
2206 break;
2207 }
2208 if( j==nExpr ) break;
danba00e302016-07-23 20:24:06 +00002209 if( aiMap ) aiMap[i] = j;
dancfbb5e82016-07-13 19:48:13 +00002210 }
2211
2212 if( i==nExpr ){
drh7d176102014-02-18 03:07:12 +00002213 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00002214 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2215 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00002216 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00002217 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2218 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00002219
dan7b35a772016-07-28 19:47:15 +00002220 if( prRhsHasNull ){
2221 *prRhsHasNull = ++pParse->nMem;
dan3480bfd2016-06-16 17:14:02 +00002222#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
dancfbb5e82016-07-13 19:48:13 +00002223 i64 mask = (1<<nExpr)-1;
dan3480bfd2016-06-16 17:14:02 +00002224 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
dancfbb5e82016-07-13 19:48:13 +00002225 iTab, 0, 0, (u8*)&mask, P4_INT64);
dan3480bfd2016-06-16 17:14:02 +00002226#endif
dan7b35a772016-07-28 19:47:15 +00002227 if( nExpr==1 ){
2228 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2229 }
danielk19770cdc0222008-06-26 18:04:03 +00002230 }
drh552fd452014-02-18 01:07:38 +00002231 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00002232 }
2233 }
2234 }
2235 }
2236
drhbb53ecb2014-08-02 21:03:33 +00002237 /* If no preexisting index is available for the IN clause
2238 ** and IN_INDEX_NOOP is an allowed reply
2239 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002240 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002241 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002242 ** the IN operator so return IN_INDEX_NOOP.
2243 */
2244 if( eType==0
2245 && (inFlags & IN_INDEX_NOOP_OK)
2246 && !ExprHasProperty(pX, EP_xIsSelect)
2247 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2248 ){
2249 eType = IN_INDEX_NOOP;
2250 }
drhbb53ecb2014-08-02 21:03:33 +00002251
danielk19779a96b662007-11-29 17:05:18 +00002252 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002253 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002254 ** We will have to generate an ephemeral table to do the job.
2255 */
drh8e23daf2013-06-11 13:30:04 +00002256 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002257 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002258 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002259 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002260 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00002261 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00002262 eType = IN_INDEX_ROWID;
2263 }
drhe21a6e12014-08-01 18:00:24 +00002264 }else if( prRhsHasNull ){
2265 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002266 }
danielk197741a05b72008-10-02 13:50:55 +00002267 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002268 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002269 }else{
2270 pX->iTable = iTab;
2271 }
danba00e302016-07-23 20:24:06 +00002272
2273 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2274 int i, n;
2275 n = sqlite3ExprVectorSize(pX->pLeft);
2276 for(i=0; i<n; i++) aiMap[i] = i;
2277 }
danielk19779a96b662007-11-29 17:05:18 +00002278 return eType;
2279}
danielk1977284f4ac2007-12-10 05:03:46 +00002280#endif
drh626a8792005-01-17 22:08:19 +00002281
danf9b2e052016-08-02 17:45:00 +00002282#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002283/*
2284** Argument pExpr is an (?, ?...) IN(...) expression. This
2285** function allocates and returns a nul-terminated string containing
2286** the affinities to be used for each column of the comparison.
2287**
2288** It is the responsibility of the caller to ensure that the returned
2289** string is eventually freed using sqlite3DbFree().
2290*/
dan71c57db2016-07-09 20:23:55 +00002291static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2292 Expr *pLeft = pExpr->pLeft;
2293 int nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002294 Select *pSelect = (pExpr->flags & EP_xIsSelect) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002295 char *zRet;
2296
dan553168c2016-08-01 20:14:31 +00002297 assert( pExpr->op==TK_IN );
dan71c57db2016-07-09 20:23:55 +00002298 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2299 if( zRet ){
2300 int i;
2301 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002302 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002303 char a = sqlite3ExprAffinity(pA);
2304 if( pSelect ){
2305 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2306 }else{
2307 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002308 }
dan71c57db2016-07-09 20:23:55 +00002309 }
2310 zRet[nVal] = '\0';
2311 }
2312 return zRet;
2313}
danf9b2e052016-08-02 17:45:00 +00002314#endif
dan71c57db2016-07-09 20:23:55 +00002315
dan8da209b2016-07-26 18:06:08 +00002316#ifndef SQLITE_OMIT_SUBQUERY
2317/*
2318** Load the Parse object passed as the first argument with an error
2319** message of the form:
2320**
2321** "sub-select returns N columns - expected M"
2322*/
2323void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2324 const char *zFmt = "sub-select returns %d columns - expected %d";
2325 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2326}
2327#endif
2328
drh626a8792005-01-17 22:08:19 +00002329/*
drhd4187c72010-08-30 22:15:45 +00002330** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2331** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002332**
drh9cbe6352005-11-29 03:13:21 +00002333** (SELECT a FROM b) -- subquery
2334** EXISTS (SELECT a FROM b) -- EXISTS subquery
2335** x IN (4,5,11) -- IN operator with list on right-hand side
2336** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002337**
drh9cbe6352005-11-29 03:13:21 +00002338** The pExpr parameter describes the expression that contains the IN
2339** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002340**
2341** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2342** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2343** to some integer key column of a table B-Tree. In this case, use an
2344** intkey B-Tree to store the set of IN(...) values instead of the usual
2345** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002346**
2347** If rMayHaveNull is non-zero, that means that the operation is an IN
2348** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002349** All this routine does is initialize the register given by rMayHaveNull
2350** to NULL. Calling routines will take care of changing this register
2351** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002352**
2353** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002354** result. For a multi-column SELECT, the result is stored in a contiguous
2355** array of registers and the return value is the register of the left-most
2356** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002357*/
drh51522cd2005-01-20 13:36:19 +00002358#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002359int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002360 Parse *pParse, /* Parsing context */
2361 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002362 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002363 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002364){
drh6be515e2014-08-01 21:00:53 +00002365 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002366 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002367 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002368 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00002369 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002370
drh39a11812016-08-19 19:12:58 +00002371 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2372 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002373 **
2374 ** * The right-hand side is a correlated subquery
2375 ** * The right-hand side is an expression list containing variables
2376 ** * We are inside a trigger
2377 **
2378 ** If all of the above are false, then we can run this code just once
2379 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002380 */
drhc5cd1242013-09-12 16:50:49 +00002381 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00002382 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002383 }
2384
dan4a07e3d2010-11-09 14:48:59 +00002385#ifndef SQLITE_OMIT_EXPLAIN
2386 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00002387 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2388 jmpIfDynamic>=0?"":"CORRELATED ",
2389 pExpr->op==TK_IN?"LIST":"SCALAR",
2390 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00002391 );
2392 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2393 }
2394#endif
2395
drhcce7d172000-05-31 15:34:51 +00002396 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002397 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002398 int addr; /* Address of OP_OpenEphemeral instruction */
2399 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002400 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002401 int nVal; /* Size of vector pLeft */
2402
2403 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002404 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002405
2406 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002407 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002408 ** filled with index keys representing the results from the
2409 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002410 **
2411 ** If the 'x' expression is a column value, or the SELECT...
2412 ** statement returns a column value, then the affinity of that
2413 ** column is used to build the index keys. If both 'x' and the
2414 ** SELECT... statement are columns, then numeric affinity is used
2415 ** if either column has NUMERIC or INTEGER affinity. If neither
2416 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2417 ** is used.
2418 */
2419 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002420 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2421 pExpr->iTable, (isRowid?0:nVal));
2422 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002423
danielk19776ab3a2e2009-02-19 14:39:25 +00002424 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00002425 /* Case 1: expr IN (SELECT ...)
2426 **
danielk1977e014a832004-05-17 10:48:57 +00002427 ** Generate code to write the results of the select into the temporary
2428 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002429 */
drh43870062014-07-31 15:44:44 +00002430 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002431 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002432
danielk197741a05b72008-10-02 13:50:55 +00002433 assert( !isRowid );
dan71c57db2016-07-09 20:23:55 +00002434 if( pEList->nExpr!=nVal ){
dan8da209b2016-07-26 18:06:08 +00002435 sqlite3SubselectError(pParse, pEList->nExpr, nVal);
dan71c57db2016-07-09 20:23:55 +00002436 }else{
2437 SelectDest dest;
2438 int i;
2439 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2440 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2441 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2442 pSelect->iLimit = 0;
2443 testcase( pSelect->selFlags & SF_Distinct );
2444 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2445 if( sqlite3Select(pParse, pSelect, &dest) ){
2446 sqlite3DbFree(pParse->db, dest.zAffSdst);
2447 sqlite3KeyInfoUnref(pKeyInfo);
2448 return 0;
2449 }
2450 sqlite3DbFree(pParse->db, dest.zAffSdst);
2451 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2452 assert( pEList!=0 );
2453 assert( pEList->nExpr>0 );
2454 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2455 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002456 Expr *p = (nVal>1) ? sqlite3VectorFieldSubexpr(pLeft, i) : pLeft;
dan71c57db2016-07-09 20:23:55 +00002457 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2458 pParse, p, pEList->a[i].pExpr
2459 );
2460 }
drh94ccde52007-04-13 16:06:32 +00002461 }
drha7d2db12010-07-14 20:23:52 +00002462 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002463 /* Case 2: expr IN (exprlist)
2464 **
drhfd131da2007-08-07 17:13:03 +00002465 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002466 ** store it in the temporary table. If <expr> is a column, then use
2467 ** that columns affinity when building index keys. If <expr> is not
2468 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002469 */
dan71c57db2016-07-09 20:23:55 +00002470 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002471 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002472 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002473 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002474 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002475
dan71c57db2016-07-09 20:23:55 +00002476 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002477 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002478 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002479 }
drh323df792013-08-05 19:11:29 +00002480 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002481 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002482 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2483 }
danielk1977e014a832004-05-17 10:48:57 +00002484
2485 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002486 r1 = sqlite3GetTempReg(pParse);
2487 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002488 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002489 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2490 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002491 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002492
drh57dbd7b2005-07-08 18:25:26 +00002493 /* If the expression is not constant then we will need to
2494 ** disable the test that was generated above that makes sure
2495 ** this code only executes once. Because for a non-constant
2496 ** expression we need to rerun this code each time.
2497 */
drh6be515e2014-08-01 21:00:53 +00002498 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2499 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2500 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002501 }
danielk1977e014a832004-05-17 10:48:57 +00002502
2503 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002504 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2505 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002506 }else{
drhe05c9292009-10-29 13:48:10 +00002507 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2508 if( isRowid ){
2509 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2510 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002511 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002512 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2513 }else{
2514 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2515 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2516 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2517 }
danielk197741a05b72008-10-02 13:50:55 +00002518 }
drhfef52082000-06-06 01:50:43 +00002519 }
drh2d401ab2008-01-10 23:50:11 +00002520 sqlite3ReleaseTempReg(pParse, r1);
2521 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002522 }
drh323df792013-08-05 19:11:29 +00002523 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002524 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002525 }
danielk1977b3bce662005-01-29 08:32:43 +00002526 break;
drhfef52082000-06-06 01:50:43 +00002527 }
2528
drh51522cd2005-01-20 13:36:19 +00002529 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002530 case TK_SELECT:
2531 default: {
drh39a11812016-08-19 19:12:58 +00002532 /* Case 3: (SELECT ... FROM ...)
2533 ** or: EXISTS(SELECT ... FROM ...)
2534 **
2535 ** For a SELECT, generate code to put the values for all columns of
2536 ** the first row into an array of registers and return the index of
2537 ** the first register.
2538 **
2539 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2540 ** into a register and return that register number.
2541 **
2542 ** In both cases, the query is augmented with "LIMIT 1". Any
2543 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002544 */
drhfd773cf2009-05-29 14:39:07 +00002545 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002546 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002547 int nReg; /* Registers to allocate */
drh1398ad32005-01-19 23:24:50 +00002548
shanecf697392009-06-01 16:53:09 +00002549 testcase( pExpr->op==TK_EXISTS );
2550 testcase( pExpr->op==TK_SELECT );
2551 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
danielk19776ab3a2e2009-02-19 14:39:25 +00002552 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
dan71c57db2016-07-09 20:23:55 +00002553
danielk19776ab3a2e2009-02-19 14:39:25 +00002554 pSel = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002555 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2556 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2557 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002558 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002559 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002560 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002561 dest.nSdst = nReg;
2562 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002563 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002564 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002565 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002566 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002567 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002568 }
drh633e6d52008-07-28 19:34:53 +00002569 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002570 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2571 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002572 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002573 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002574 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002575 return 0;
drh94ccde52007-04-13 16:06:32 +00002576 }
drh2b596da2012-07-23 21:43:19 +00002577 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002578 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002579 break;
drhcce7d172000-05-31 15:34:51 +00002580 }
2581 }
danielk1977b3bce662005-01-29 08:32:43 +00002582
drh6be515e2014-08-01 21:00:53 +00002583 if( rHasNullFlag ){
2584 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002585 }
drh6be515e2014-08-01 21:00:53 +00002586
2587 if( jmpIfDynamic>=0 ){
2588 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002589 }
drhd2490902014-04-13 19:28:15 +00002590 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002591
drh1450bc62009-10-30 13:25:56 +00002592 return rReg;
drhcce7d172000-05-31 15:34:51 +00002593}
drh51522cd2005-01-20 13:36:19 +00002594#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002595
drhe3365e62009-11-12 17:52:24 +00002596#ifndef SQLITE_OMIT_SUBQUERY
2597/*
dan7b35a772016-07-28 19:47:15 +00002598** Expr pIn is an IN(...) expression. This function checks that the
2599** sub-select on the RHS of the IN() operator has the same number of
2600** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2601** a sub-query, that the LHS is a vector of size 1.
2602*/
2603int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2604 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2605 if( (pIn->flags & EP_xIsSelect) ){
2606 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2607 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2608 return 1;
2609 }
2610 }else if( nVector!=1 ){
2611 if( (pIn->pLeft->flags & EP_xIsSelect) ){
2612 sqlite3SubselectError(pParse, nVector, 1);
2613 }else{
drhe835bc12016-08-23 19:02:55 +00002614 sqlite3ErrorMsg(pParse, "row value misused");
dan7b35a772016-07-28 19:47:15 +00002615 }
2616 return 1;
2617 }
2618 return 0;
2619}
2620#endif
2621
2622#ifndef SQLITE_OMIT_SUBQUERY
2623/*
drhe3365e62009-11-12 17:52:24 +00002624** Generate code for an IN expression.
2625**
2626** x IN (SELECT ...)
2627** x IN (value, value, ...)
2628**
2629** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
2630** is an array of zero or more values. The expression is true if the LHS is
2631** contained within the RHS. The value of the expression is unknown (NULL)
2632** if the LHS is NULL or if the LHS is not contained within the RHS and the
2633** RHS contains one or more NULL values.
2634**
drh6be515e2014-08-01 21:00:53 +00002635** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002636** contained within the RHS. If due to NULLs we cannot determine if the LHS
2637** is contained in the RHS then jump to destIfNull. If the LHS is contained
2638** within the RHS then fall through.
2639*/
2640static void sqlite3ExprCodeIN(
2641 Parse *pParse, /* Parsing and code generating context */
2642 Expr *pExpr, /* The IN expression */
2643 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2644 int destIfNull /* Jump here if the results are unknown due to NULLs */
2645){
2646 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002647 int eType; /* Type of the RHS */
drh12abf402016-08-22 14:30:05 +00002648 int r1, r2; /* Temporary use registers */
drhe3365e62009-11-12 17:52:24 +00002649 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002650 int *aiMap = 0; /* Map from vector field to index column */
2651 char *zAff = 0; /* Affinity string for comparisons */
2652 int nVector; /* Size of vectors for this IN(...) op */
drh12abf402016-08-22 14:30:05 +00002653 int iDummy; /* Dummy parameter to exprCodeVector() */
danba00e302016-07-23 20:24:06 +00002654 Expr *pLeft = pExpr->pLeft;
2655 int i;
drhe3365e62009-11-12 17:52:24 +00002656
dan7b35a772016-07-28 19:47:15 +00002657 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00002658 zAff = exprINAffinity(pParse, pExpr);
drha48d7e72016-08-12 11:01:20 +00002659 if( zAff==0 ) return;
danba00e302016-07-23 20:24:06 +00002660 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2661 aiMap = (int*)sqlite3DbMallocZero(
2662 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2663 );
drha48d7e72016-08-12 11:01:20 +00002664 if( aiMap==0 ){
2665 sqlite3DbFree(pParse->db, zAff);
dan553168c2016-08-01 20:14:31 +00002666 return;
2667 }
dan7b35a772016-07-28 19:47:15 +00002668
danba00e302016-07-23 20:24:06 +00002669 /* Attempt to compute the RHS. After this step, if anything other than
2670 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2671 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2672 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00002673 v = pParse->pVdbe;
2674 assert( v!=0 ); /* OOM detected prior to this routine */
2675 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002676 eType = sqlite3FindInIndex(pParse, pExpr,
2677 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00002678 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00002679
danba00e302016-07-23 20:24:06 +00002680 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2681 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2682 );
drhe3365e62009-11-12 17:52:24 +00002683
danba00e302016-07-23 20:24:06 +00002684 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2685 ** vector, then it is stored in an array of nVector registers starting
2686 ** at r1.
drhe3365e62009-11-12 17:52:24 +00002687 */
danba00e302016-07-23 20:24:06 +00002688 r1 = sqlite3GetTempRange(pParse, nVector);
drhe3365e62009-11-12 17:52:24 +00002689 sqlite3ExprCachePush(pParse);
drh12abf402016-08-22 14:30:05 +00002690 r2 = exprCodeVector(pParse, pLeft, &iDummy);
2691 for(i=0; i<nVector; i++){
2692 sqlite3VdbeAddOp3(v, OP_Copy, r2+i, r1+aiMap[i], 0);
danba00e302016-07-23 20:24:06 +00002693 }
drhe3365e62009-11-12 17:52:24 +00002694
drhbb53ecb2014-08-02 21:03:33 +00002695 /* If sqlite3FindInIndex() did not find or create an index that is
2696 ** suitable for evaluating the IN operator, then evaluate using a
2697 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002698 */
drhbb53ecb2014-08-02 21:03:33 +00002699 if( eType==IN_INDEX_NOOP ){
2700 ExprList *pList = pExpr->x.pList;
2701 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2702 int labelOk = sqlite3VdbeMakeLabel(v);
2703 int r2, regToFree;
2704 int regCkNull = 0;
2705 int ii;
2706 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002707 if( destIfNull!=destIfFalse ){
2708 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002709 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002710 }
2711 for(ii=0; ii<pList->nExpr; ii++){
2712 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002713 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002714 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2715 }
2716 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2717 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002718 (void*)pColl, P4_COLLSEQ);
2719 VdbeCoverageIf(v, ii<pList->nExpr-1);
2720 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00002721 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00002722 }else{
2723 assert( destIfNull==destIfFalse );
2724 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2725 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00002726 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00002727 }
2728 sqlite3ReleaseTempReg(pParse, regToFree);
2729 }
2730 if( regCkNull ){
2731 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002732 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002733 }
2734 sqlite3VdbeResolveLabel(v, labelOk);
2735 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002736 }else{
drhbb53ecb2014-08-02 21:03:33 +00002737
dan7b35a772016-07-28 19:47:15 +00002738 /* If any value on the LHS is NULL, the result of the IN(...) operator
2739 ** must be either false or NULL. If these two are handled identically,
2740 ** test the LHS for NULLs and jump directly to destIfNull if any are
2741 ** found.
2742 **
2743 ** Otherwise, if NULL and false are handled differently, and the
2744 ** IN(...) operation is not a vector operation, and the LHS of the
2745 ** operator is NULL, then the result is false if the index is
2746 ** completely empty, or NULL otherwise. */
dand49fd4e2016-07-27 19:33:04 +00002747 if( destIfNull==destIfFalse ){
2748 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002749 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dand49fd4e2016-07-27 19:33:04 +00002750 if( sqlite3ExprCanBeNull(p) ){
2751 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002752 VdbeCoverage(v);
dand49fd4e2016-07-27 19:33:04 +00002753 }
drh7248a8b2014-08-04 18:50:54 +00002754 }
dand49fd4e2016-07-27 19:33:04 +00002755 }else if( nVector==1 && sqlite3ExprCanBeNull(pExpr->pLeft) ){
2756 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2757 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2758 VdbeCoverage(v);
2759 sqlite3VdbeGoto(v, destIfNull);
2760 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002761 }
2762
2763 if( eType==IN_INDEX_ROWID ){
dan7b35a772016-07-28 19:47:15 +00002764 /* In this case, the RHS is the ROWID of table b-tree */
drheeb95652016-05-26 20:56:38 +00002765 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002766 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002767 }else{
dan7b35a772016-07-28 19:47:15 +00002768 /* In this case, the RHS is an index b-tree. Apply the comparison
2769 ** affinities to each value on the LHS of the operator. */
danba00e302016-07-23 20:24:06 +00002770 sqlite3VdbeAddOp4(v, OP_Affinity, r1, nVector, 0, zAff, nVector);
dan7b35a772016-07-28 19:47:15 +00002771
2772 if( nVector>1 && destIfNull!=destIfFalse ){
2773 int iIdx = pExpr->iTable;
2774 int addr;
2775 int addrNext;
2776
2777 /* Search the index for the key. */
2778 addr = sqlite3VdbeAddOp4Int(v, OP_Found, iIdx, 0, r1, nVector);
drh471b4b92016-08-12 11:25:49 +00002779 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002780
2781 /* At this point the specified key is not present in the index,
2782 ** so the result of the IN(..) operator must be either NULL or
2783 ** 0. The vdbe code generated below figures out which. */
2784 addrNext = 1+sqlite3VdbeAddOp2(v, OP_Rewind, iIdx, destIfFalse);
drh471b4b92016-08-12 11:25:49 +00002785 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002786
2787 for(i=0; i<nVector; i++){
2788 Expr *p;
2789 CollSeq *pColl;
2790 int r2 = sqlite3GetTempReg(pParse);
drhfc7f27b2016-08-20 00:07:01 +00002791 p = sqlite3VectorFieldSubexpr(pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002792 pColl = sqlite3ExprCollSeq(pParse, p);
2793
2794 sqlite3VdbeAddOp3(v, OP_Column, iIdx, i, r2);
2795 sqlite3VdbeAddOp4(v, OP_Eq, r1+i, 0, r2, (void*)pColl,P4_COLLSEQ);
2796 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
drh471b4b92016-08-12 11:25:49 +00002797 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002798 sqlite3VdbeAddOp2(v, OP_Next, iIdx, addrNext);
drh471b4b92016-08-12 11:25:49 +00002799 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002800 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2801 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-3);
2802 sqlite3ReleaseTempReg(pParse, r2);
2803 }
2804 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
2805
2806 /* The key was found in the index. If it contains any NULL values,
2807 ** then the result of the IN(...) operator is NULL. Otherwise, the
2808 ** result is 1. */
2809 sqlite3VdbeJumpHere(v, addr);
2810 for(i=0; i<nVector; i++){
drhfc7f27b2016-08-20 00:07:01 +00002811 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
dan7b35a772016-07-28 19:47:15 +00002812 if( sqlite3ExprCanBeNull(p) ){
2813 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
drh471b4b92016-08-12 11:25:49 +00002814 VdbeCoverage(v);
dan7b35a772016-07-28 19:47:15 +00002815 }
2816 }
2817
2818 }else if( rRhsHasNull==0 ){
drhbb53ecb2014-08-02 21:03:33 +00002819 /* This branch runs if it is known at compile time that the RHS
dan7b35a772016-07-28 19:47:15 +00002820 ** cannot contain NULL values. This happens as a result
2821 ** of "NOT NULL" constraints in the database schema.
drhbb53ecb2014-08-02 21:03:33 +00002822 **
2823 ** Also run this branch if NULL is equivalent to FALSE
dan7b35a772016-07-28 19:47:15 +00002824 ** for this particular IN operator. */
danba00e302016-07-23 20:24:06 +00002825 sqlite3VdbeAddOp4Int(
2826 v, OP_NotFound, pExpr->iTable, destIfFalse, r1, nVector
2827 );
drhbb53ecb2014-08-02 21:03:33 +00002828 VdbeCoverage(v);
2829 }else{
2830 /* In this branch, the RHS of the IN might contain a NULL and
2831 ** the presence of a NULL on the RHS makes a difference in the
2832 ** outcome.
2833 */
drh728e0f92015-10-10 14:41:28 +00002834 int addr1;
dan7b35a772016-07-28 19:47:15 +00002835
drhbb53ecb2014-08-02 21:03:33 +00002836 /* First check to see if the LHS is contained in the RHS. If so,
2837 ** then the answer is TRUE the presence of NULLs in the RHS does
2838 ** not matter. If the LHS is not contained in the RHS, then the
2839 ** answer is NULL if the RHS contains NULLs and the answer is
2840 ** FALSE if the RHS is NULL-free.
2841 */
drh728e0f92015-10-10 14:41:28 +00002842 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002843 VdbeCoverage(v);
2844 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2845 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002846 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002847 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002848 }
drhe3365e62009-11-12 17:52:24 +00002849 }
drhe3365e62009-11-12 17:52:24 +00002850 }
2851 sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002852 sqlite3ExprCachePop(pParse);
danba00e302016-07-23 20:24:06 +00002853 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00002854 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00002855 VdbeComment((v, "end IN expr"));
2856}
2857#endif /* SQLITE_OMIT_SUBQUERY */
2858
drh13573c72010-01-12 17:04:07 +00002859#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002860/*
2861** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002862** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002863**
2864** The z[] string will probably not be zero-terminated. But the
2865** z[n] character is guaranteed to be something that does not look
2866** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002867*/
drhb7916a72009-05-27 10:31:29 +00002868static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002869 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002870 double value;
drh9339da12010-09-30 00:50:49 +00002871 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002872 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2873 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002874 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002875 }
2876}
drh13573c72010-01-12 17:04:07 +00002877#endif
drh598f1342007-10-23 15:39:45 +00002878
2879
2880/*
drhfec19aa2004-05-19 20:41:03 +00002881** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002882** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002883**
shaneh5f1d6b62010-09-30 16:51:25 +00002884** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002885*/
drh13573c72010-01-12 17:04:07 +00002886static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2887 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002888 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002889 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002890 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002891 if( negFlag ) i = -i;
2892 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002893 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002894 int c;
2895 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002896 const char *z = pExpr->u.zToken;
2897 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002898 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002899 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002900 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002901 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002902 }else{
drh13573c72010-01-12 17:04:07 +00002903#ifdef SQLITE_OMIT_FLOATING_POINT
2904 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2905#else
drh1b7ddc52014-07-23 14:52:05 +00002906#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002907 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2908 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002909 }else
2910#endif
2911 {
drh9296c182014-07-23 13:40:49 +00002912 codeReal(v, z, negFlag, iMem);
2913 }
drh13573c72010-01-12 17:04:07 +00002914#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002915 }
drhfec19aa2004-05-19 20:41:03 +00002916 }
2917}
2918
drhbea119c2016-04-11 18:15:37 +00002919#if defined(SQLITE_DEBUG)
2920/*
2921** Verify the consistency of the column cache
2922*/
2923static int cacheIsValid(Parse *pParse){
2924 int i, n;
2925 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2926 if( pParse->aColCache[i].iReg>0 ) n++;
2927 }
2928 return n==pParse->nColCache;
2929}
2930#endif
2931
drhceea3322009-04-23 13:22:42 +00002932/*
2933** Clear a cache entry.
2934*/
2935static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2936 if( p->tempReg ){
2937 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2938 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2939 }
2940 p->tempReg = 0;
2941 }
drhbea119c2016-04-11 18:15:37 +00002942 p->iReg = 0;
2943 pParse->nColCache--;
danee65eea2016-04-16 15:03:20 +00002944 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002945}
2946
2947
2948/*
2949** Record in the column cache that a particular column from a
2950** particular table is stored in a particular register.
2951*/
2952void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2953 int i;
2954 int minLru;
2955 int idxLru;
2956 struct yColCache *p;
2957
dance8f53d2015-01-21 17:00:57 +00002958 /* Unless an error has occurred, register numbers are always positive. */
2959 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002960 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2961
drhb6da74e2009-12-24 16:00:28 +00002962 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2963 ** for testing only - to verify that SQLite always gets the same answer
2964 ** with and without the column cache.
2965 */
drh7e5418e2012-09-27 15:05:54 +00002966 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002967
drh27ee4062009-12-30 01:13:11 +00002968 /* First replace any existing entry.
2969 **
2970 ** Actually, the way the column cache is currently used, we are guaranteed
2971 ** that the object will never already be in cache. Verify this guarantee.
2972 */
2973#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00002974 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00002975 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00002976 }
drh27ee4062009-12-30 01:13:11 +00002977#endif
drhceea3322009-04-23 13:22:42 +00002978
2979 /* Find an empty slot and replace it */
2980 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2981 if( p->iReg==0 ){
2982 p->iLevel = pParse->iCacheLevel;
2983 p->iTable = iTab;
2984 p->iColumn = iCol;
2985 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002986 p->tempReg = 0;
2987 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002988 pParse->nColCache++;
danee65eea2016-04-16 15:03:20 +00002989 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002990 return;
2991 }
2992 }
2993
2994 /* Replace the last recently used */
2995 minLru = 0x7fffffff;
2996 idxLru = -1;
2997 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2998 if( p->lru<minLru ){
2999 idxLru = i;
3000 minLru = p->lru;
3001 }
3002 }
drh20411ea2009-05-29 19:00:12 +00003003 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00003004 p = &pParse->aColCache[idxLru];
3005 p->iLevel = pParse->iCacheLevel;
3006 p->iTable = iTab;
3007 p->iColumn = iCol;
3008 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00003009 p->tempReg = 0;
3010 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00003011 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00003012 return;
3013 }
3014}
3015
3016/*
drhf49f3522009-12-30 14:12:38 +00003017** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
3018** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00003019*/
drhf49f3522009-12-30 14:12:38 +00003020void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00003021 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00003022 if( iReg<=0 || pParse->nColCache==0 ) return;
3023 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
3024 while(1){
3025 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
3026 if( p==pParse->aColCache ) break;
3027 p--;
drhceea3322009-04-23 13:22:42 +00003028 }
3029}
3030
3031/*
3032** Remember the current column cache context. Any new entries added
3033** added to the column cache after this call are removed when the
3034** corresponding pop occurs.
3035*/
3036void sqlite3ExprCachePush(Parse *pParse){
3037 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00003038#ifdef SQLITE_DEBUG
3039 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3040 printf("PUSH to %d\n", pParse->iCacheLevel);
3041 }
3042#endif
drhceea3322009-04-23 13:22:42 +00003043}
3044
3045/*
3046** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00003047** the previous sqlite3ExprCachePush operation. In other words, restore
3048** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00003049*/
drhd2490902014-04-13 19:28:15 +00003050void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00003051 int i;
3052 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00003053 assert( pParse->iCacheLevel>=1 );
3054 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00003055#ifdef SQLITE_DEBUG
3056 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3057 printf("POP to %d\n", pParse->iCacheLevel);
3058 }
3059#endif
drhceea3322009-04-23 13:22:42 +00003060 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3061 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
3062 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00003063 }
3064 }
3065}
drh945498f2007-02-24 11:52:52 +00003066
3067/*
drh5cd79232009-05-25 11:46:29 +00003068** When a cached column is reused, make sure that its register is
3069** no longer available as a temp register. ticket #3879: that same
3070** register might be in the cache in multiple places, so be sure to
3071** get them all.
3072*/
3073static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
3074 int i;
3075 struct yColCache *p;
3076 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3077 if( p->iReg==iReg ){
3078 p->tempReg = 0;
3079 }
3080 }
3081}
3082
drh1f9ca2c2015-08-25 16:57:52 +00003083/* Generate code that will load into register regOut a value that is
3084** appropriate for the iIdxCol-th column of index pIdx.
3085*/
3086void sqlite3ExprCodeLoadIndexColumn(
3087 Parse *pParse, /* The parsing context */
3088 Index *pIdx, /* The index whose column is to be loaded */
3089 int iTabCur, /* Cursor pointing to a table row */
3090 int iIdxCol, /* The column of the index to be loaded */
3091 int regOut /* Store the index column value in this register */
3092){
3093 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003094 if( iTabCol==XN_EXPR ){
3095 assert( pIdx->aColExpr );
3096 assert( pIdx->aColExpr->nExpr>iIdxCol );
3097 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00003098 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00003099 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003100 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3101 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003102 }
drh1f9ca2c2015-08-25 16:57:52 +00003103}
3104
drh5cd79232009-05-25 11:46:29 +00003105/*
drh5c092e82010-05-14 19:24:02 +00003106** Generate code to extract the value of the iCol-th column of a table.
3107*/
3108void sqlite3ExprCodeGetColumnOfTable(
3109 Vdbe *v, /* The VDBE under construction */
3110 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003111 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003112 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003113 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003114){
3115 if( iCol<0 || iCol==pTab->iPKey ){
3116 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3117 }else{
3118 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003119 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003120 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003121 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3122 }
3123 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003124 }
3125 if( iCol>=0 ){
3126 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3127 }
3128}
3129
3130/*
drh945498f2007-02-24 11:52:52 +00003131** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00003132** table pTab and store the column value in a register.
3133**
3134** An effort is made to store the column value in register iReg. This
3135** is not garanteeed for GetColumn() - the result can be stored in
3136** any register. But the result is guaranteed to land in register iReg
3137** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00003138**
3139** There must be an open cursor to pTab in iTable when this routine
3140** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003141*/
drhe55cbd72008-03-31 23:48:03 +00003142int sqlite3ExprCodeGetColumn(
3143 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003144 Table *pTab, /* Description of the table we are reading from */
3145 int iColumn, /* Index of the table column */
3146 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003147 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003148 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003149){
drhe55cbd72008-03-31 23:48:03 +00003150 Vdbe *v = pParse->pVdbe;
3151 int i;
drhda250ea2008-04-01 05:07:14 +00003152 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00003153
drhceea3322009-04-23 13:22:42 +00003154 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00003155 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00003156 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00003157 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00003158 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00003159 }
3160 }
3161 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003162 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003163 if( p5 ){
3164 sqlite3VdbeChangeP5(v, p5);
3165 }else{
3166 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
3167 }
drhe55cbd72008-03-31 23:48:03 +00003168 return iReg;
3169}
drhce78bc62015-10-15 19:21:51 +00003170void sqlite3ExprCodeGetColumnToReg(
3171 Parse *pParse, /* Parsing and code generating context */
3172 Table *pTab, /* Description of the table we are reading from */
3173 int iColumn, /* Index of the table column */
3174 int iTable, /* The cursor pointing to the table */
3175 int iReg /* Store results here */
3176){
3177 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
3178 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
3179}
3180
drhe55cbd72008-03-31 23:48:03 +00003181
3182/*
drhceea3322009-04-23 13:22:42 +00003183** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00003184*/
drhceea3322009-04-23 13:22:42 +00003185void sqlite3ExprCacheClear(Parse *pParse){
3186 int i;
3187 struct yColCache *p;
3188
drh9ac79622013-12-18 15:11:47 +00003189#if SQLITE_DEBUG
3190 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
3191 printf("CLEAR\n");
3192 }
3193#endif
drhceea3322009-04-23 13:22:42 +00003194 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3195 if( p->iReg ){
3196 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00003197 }
drhe55cbd72008-03-31 23:48:03 +00003198 }
3199}
3200
3201/*
drhda250ea2008-04-01 05:07:14 +00003202** Record the fact that an affinity change has occurred on iCount
3203** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00003204*/
drhda250ea2008-04-01 05:07:14 +00003205void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00003206 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00003207}
3208
3209/*
drhb21e7c72008-06-22 12:37:57 +00003210** Generate code to move content from registers iFrom...iFrom+nReg-1
3211** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00003212*/
drhb21e7c72008-06-22 12:37:57 +00003213void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003214 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003215 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00003216 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00003217}
3218
drhf49f3522009-12-30 14:12:38 +00003219#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00003220/*
drh652fbf52008-04-01 01:42:41 +00003221** Return true if any register in the range iFrom..iTo (inclusive)
3222** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00003223**
3224** This routine is used within assert() and testcase() macros only
3225** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00003226*/
3227static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3228 int i;
drhceea3322009-04-23 13:22:42 +00003229 struct yColCache *p;
3230 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3231 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00003232 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00003233 }
3234 return 0;
3235}
drhf49f3522009-12-30 14:12:38 +00003236#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00003237
drhbea119c2016-04-11 18:15:37 +00003238
drh652fbf52008-04-01 01:42:41 +00003239/*
drh12abf402016-08-22 14:30:05 +00003240** Convert a scalar expression node to a TK_REGISTER referencing
3241** register iReg. The caller must ensure that iReg already contains
3242** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003243*/
3244static void exprToRegister(Expr *p, int iReg){
3245 p->op2 = p->op;
3246 p->op = TK_REGISTER;
3247 p->iTable = iReg;
3248 ExprClearProperty(p, EP_Skip);
3249}
3250
drh12abf402016-08-22 14:30:05 +00003251/*
3252** Evaluate an expression (either a vector or a scalar expression) and store
3253** the result in continguous temporary registers. Return the index of
3254** the first register used to store the result.
3255**
3256** If the returned result register is a temporary scalar, then also write
3257** that register number into *piFreeable. If the returned result register
3258** is not a temporary or if the expression is a vector set *piFreeable
3259** to 0.
3260*/
3261static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3262 int iResult;
3263 int nResult = sqlite3ExprVectorSize(p);
3264 if( nResult==1 ){
3265 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3266 }else{
3267 *piFreeable = 0;
3268 if( p->op==TK_SELECT ){
3269 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
3270 }else{
3271 int i;
3272 iResult = pParse->nMem+1;
3273 pParse->nMem += nResult;
3274 for(i=0; i<nResult; i++){
3275 sqlite3ExprCode(pParse, p->x.pList->a[i].pExpr, i+iResult);
3276 }
3277 }
3278 }
3279 return iResult;
3280}
3281
dan71c57db2016-07-09 20:23:55 +00003282
drha4c3c872013-09-12 17:29:25 +00003283/*
drhcce7d172000-05-31 15:34:51 +00003284** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003285** expression. Attempt to store the results in register "target".
3286** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003287**
drh8b213892008-08-29 02:14:02 +00003288** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003289** be stored in target. The result might be stored in some other
3290** register if it is convenient to do so. The calling function
3291** must check the return code and move the results to the desired
3292** register.
drhcce7d172000-05-31 15:34:51 +00003293*/
drh678ccce2008-03-31 18:19:54 +00003294int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003295 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3296 int op; /* The opcode being coded */
3297 int inReg = target; /* Results stored in register inReg */
3298 int regFree1 = 0; /* If non-zero free this temporary register */
3299 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003300 int r1, r2; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00003301 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00003302 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003303 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003304
drh9cbf3422008-01-17 16:22:13 +00003305 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003306 if( v==0 ){
3307 assert( pParse->db->mallocFailed );
3308 return 0;
3309 }
drh389a1ad2008-01-03 23:44:53 +00003310
3311 if( pExpr==0 ){
3312 op = TK_NULL;
3313 }else{
3314 op = pExpr->op;
3315 }
drhf2bc0132004-10-04 13:19:23 +00003316 switch( op ){
drh13449892005-09-07 21:22:45 +00003317 case TK_AGG_COLUMN: {
3318 AggInfo *pAggInfo = pExpr->pAggInfo;
3319 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3320 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003321 assert( pCol->iMem>0 );
3322 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00003323 break;
3324 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003325 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003326 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00003327 break;
3328 }
3329 /* Otherwise, fall thru into the TK_COLUMN case */
3330 }
drh967e8b72000-06-21 13:59:10 +00003331 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003332 int iTab = pExpr->iTable;
3333 if( iTab<0 ){
3334 if( pParse->ckBase>0 ){
3335 /* Generating CHECK constraints or inserting into partial index */
3336 inReg = pExpr->iColumn + pParse->ckBase;
3337 break;
3338 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003339 /* Coding an expression that is part of an index where column names
3340 ** in the index refer to the table to which the index belongs */
3341 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003342 }
drh22827922000-06-06 17:27:05 +00003343 }
drhb2b9d3d2013-08-01 01:14:43 +00003344 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3345 pExpr->iColumn, iTab, target,
3346 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003347 break;
3348 }
3349 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003350 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00003351 break;
3352 }
drh13573c72010-01-12 17:04:07 +00003353#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003354 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003355 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3356 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00003357 break;
3358 }
drh13573c72010-01-12 17:04:07 +00003359#endif
drhfec19aa2004-05-19 20:41:03 +00003360 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003361 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003362 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00003363 break;
3364 }
drhf0863fe2005-06-12 21:35:51 +00003365 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003366 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00003367 break;
3368 }
danielk19775338a5f2005-01-20 13:03:10 +00003369#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003370 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003371 int n;
3372 const char *z;
drhca48c902008-01-18 14:08:24 +00003373 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003374 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3375 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3376 assert( pExpr->u.zToken[1]=='\'' );
3377 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003378 n = sqlite3Strlen30(z) - 1;
3379 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003380 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3381 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00003382 break;
3383 }
danielk19775338a5f2005-01-20 13:03:10 +00003384#endif
drh50457892003-09-06 01:10:47 +00003385 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003386 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3387 assert( pExpr->u.zToken!=0 );
3388 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003389 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3390 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00003391 assert( pExpr->u.zToken[0]=='?'
3392 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
3393 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003394 }
drh50457892003-09-06 01:10:47 +00003395 break;
3396 }
drh4e0cff62004-11-05 05:10:28 +00003397 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00003398 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003399 break;
3400 }
drh487e2622005-06-25 18:42:14 +00003401#ifndef SQLITE_OMIT_CAST
3402 case TK_CAST: {
3403 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003404 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003405 if( inReg!=target ){
3406 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3407 inReg = target;
3408 }
drh4169e432014-08-25 20:11:52 +00003409 sqlite3VdbeAddOp2(v, OP_Cast, target,
3410 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00003411 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00003412 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00003413 break;
3414 }
3415#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003416 case TK_IS:
3417 case TK_ISNOT:
3418 op = (op==TK_IS) ? TK_EQ : TK_NE;
3419 p5 = SQLITE_NULLEQ;
3420 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003421 case TK_LT:
3422 case TK_LE:
3423 case TK_GT:
3424 case TK_GE:
3425 case TK_NE:
3426 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003427 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003428 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003429 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003430 }else{
3431 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3432 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3433 codeCompare(pParse, pLeft, pExpr->pRight, op,
3434 r1, r2, inReg, SQLITE_STOREP2 | p5);
3435 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3436 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3437 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3438 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3439 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3440 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3441 testcase( regFree1==0 );
3442 testcase( regFree2==0 );
3443 }
drh6a2fe092009-09-23 02:29:36 +00003444 break;
3445 }
drhcce7d172000-05-31 15:34:51 +00003446 case TK_AND:
3447 case TK_OR:
3448 case TK_PLUS:
3449 case TK_STAR:
3450 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003451 case TK_REM:
3452 case TK_BITAND:
3453 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003454 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003455 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003456 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003457 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003458 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3459 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3460 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3461 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3462 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3463 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3464 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3465 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3466 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3467 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3468 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003469 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3470 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003471 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003472 testcase( regFree1==0 );
3473 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003474 break;
3475 }
drhcce7d172000-05-31 15:34:51 +00003476 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003477 Expr *pLeft = pExpr->pLeft;
3478 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003479 if( pLeft->op==TK_INTEGER ){
3480 codeInteger(pParse, pLeft, 1, target);
3481#ifndef SQLITE_OMIT_FLOATING_POINT
3482 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003483 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3484 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00003485#endif
drh3c84ddf2008-01-09 02:15:38 +00003486 }else{
drh10d1edf2013-11-15 15:52:39 +00003487 tempX.op = TK_INTEGER;
3488 tempX.flags = EP_IntValue|EP_TokenOnly;
3489 tempX.u.iValue = 0;
3490 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003491 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003492 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003493 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003494 }
drh3c84ddf2008-01-09 02:15:38 +00003495 inReg = target;
3496 break;
drh6e142f52000-06-08 13:36:40 +00003497 }
drhbf4133c2001-10-13 02:59:08 +00003498 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003499 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003500 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3501 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003502 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3503 testcase( regFree1==0 );
3504 inReg = target;
3505 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003506 break;
3507 }
3508 case TK_ISNULL:
3509 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003510 int addr;
drh7d176102014-02-18 03:07:12 +00003511 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3512 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003513 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003514 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003515 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003516 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003517 VdbeCoverageIf(v, op==TK_ISNULL);
3518 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003519 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003520 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003521 break;
drhcce7d172000-05-31 15:34:51 +00003522 }
drh22827922000-06-06 17:27:05 +00003523 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003524 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003525 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003526 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3527 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003528 }else{
drh9de221d2008-01-05 06:51:30 +00003529 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003530 }
drh22827922000-06-06 17:27:05 +00003531 break;
3532 }
drhcce7d172000-05-31 15:34:51 +00003533 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003534 ExprList *pFarg; /* List of function arguments */
3535 int nFarg; /* Number of function arguments */
3536 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003537 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003538 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003539 int i; /* Loop counter */
3540 u8 enc = ENC(db); /* The text encoding used by this database */
3541 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003542
danielk19776ab3a2e2009-02-19 14:39:25 +00003543 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00003544 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003545 pFarg = 0;
3546 }else{
3547 pFarg = pExpr->x.pList;
3548 }
3549 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003550 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3551 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003552 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003553#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3554 if( pDef==0 && pParse->explain ){
3555 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3556 }
3557#endif
drh2d801512016-01-14 22:19:58 +00003558 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003559 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003560 break;
3561 }
drhae6bb952009-11-11 00:24:31 +00003562
3563 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003564 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003565 ** arguments past the first non-NULL argument.
3566 */
drhd36e1042013-09-06 13:10:12 +00003567 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003568 int endCoalesce = sqlite3VdbeMakeLabel(v);
3569 assert( nFarg>=2 );
3570 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3571 for(i=1; i<nFarg; i++){
3572 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003573 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00003574 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00003575 sqlite3ExprCachePush(pParse);
3576 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003577 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00003578 }
3579 sqlite3VdbeResolveLabel(v, endCoalesce);
3580 break;
3581 }
3582
drhcca9f3d2013-09-06 15:23:29 +00003583 /* The UNLIKELY() function is a no-op. The result is the value
3584 ** of the first argument.
3585 */
3586 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3587 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00003588 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003589 break;
3590 }
drhae6bb952009-11-11 00:24:31 +00003591
drhd1a01ed2013-11-21 16:08:52 +00003592 for(i=0; i<nFarg; i++){
3593 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003594 testcase( i==31 );
3595 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003596 }
3597 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3598 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3599 }
3600 }
drh12ffee82009-04-08 13:51:51 +00003601 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003602 if( constMask ){
3603 r1 = pParse->nMem+1;
3604 pParse->nMem += nFarg;
3605 }else{
3606 r1 = sqlite3GetTempRange(pParse, nFarg);
3607 }
drha748fdc2012-03-28 01:34:47 +00003608
3609 /* For length() and typeof() functions with a column argument,
3610 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3611 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3612 ** loading.
3613 */
drhd36e1042013-09-06 13:10:12 +00003614 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003615 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003616 assert( nFarg==1 );
3617 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003618 exprOp = pFarg->a[0].pExpr->op;
3619 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003620 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3621 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003622 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3623 pFarg->a[0].pExpr->op2 =
3624 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003625 }
3626 }
3627
drhd7d385d2009-09-03 01:18:00 +00003628 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003629 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003630 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003631 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003632 }else{
drh12ffee82009-04-08 13:51:51 +00003633 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003634 }
drhb7f6f682006-07-08 17:06:43 +00003635#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003636 /* Possibly overload the function if the first argument is
3637 ** a virtual table column.
3638 **
3639 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3640 ** second argument, not the first, as the argument to test to
3641 ** see if it is a column in a virtual table. This is done because
3642 ** the left operand of infix functions (the operand we want to
3643 ** control overloading) ends up as the second argument to the
3644 ** function. The expression "A glob B" is equivalent to
3645 ** "glob(B,A). We want to use the A in "A glob B" to test
3646 ** for function overloading. But we use the B term in "glob(B,A)".
3647 */
drh12ffee82009-04-08 13:51:51 +00003648 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3649 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3650 }else if( nFarg>0 ){
3651 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003652 }
3653#endif
drhd36e1042013-09-06 13:10:12 +00003654 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003655 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003656 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003657 }
drh9c7c9132015-06-26 18:16:52 +00003658 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003659 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003660 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003661 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003662 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003663 }
drhcce7d172000-05-31 15:34:51 +00003664 break;
3665 }
drhfe2093d2005-01-20 22:48:47 +00003666#ifndef SQLITE_OMIT_SUBQUERY
3667 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003668 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003669 int nCol;
drhc5499be2008-04-01 15:06:33 +00003670 testcase( op==TK_EXISTS );
3671 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003672 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3673 sqlite3SubselectError(pParse, nCol, 1);
3674 }else{
3675 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3676 }
drh19a775c2000-06-05 18:54:46 +00003677 break;
3678 }
drhfc7f27b2016-08-20 00:07:01 +00003679 case TK_SELECT_COLUMN: {
3680 if( pExpr->pLeft->iTable==0 ){
3681 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3682 }
3683 inReg = pExpr->pLeft->iTable + pExpr->iColumn;
3684 break;
3685 }
drhfef52082000-06-06 01:50:43 +00003686 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003687 int destIfFalse = sqlite3VdbeMakeLabel(v);
3688 int destIfNull = sqlite3VdbeMakeLabel(v);
3689 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3690 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3691 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3692 sqlite3VdbeResolveLabel(v, destIfFalse);
3693 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3694 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003695 break;
3696 }
drhe3365e62009-11-12 17:52:24 +00003697#endif /* SQLITE_OMIT_SUBQUERY */
3698
3699
drh2dcef112008-01-12 19:03:48 +00003700 /*
3701 ** x BETWEEN y AND z
3702 **
3703 ** This is equivalent to
3704 **
3705 ** x>=y AND x<=z
3706 **
3707 ** X is stored in pExpr->pLeft.
3708 ** Y is stored in pExpr->pList->a[0].pExpr.
3709 ** Z is stored in pExpr->pList->a[1].pExpr.
3710 */
drhfef52082000-06-06 01:50:43 +00003711 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003712 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhfef52082000-06-06 01:50:43 +00003713 break;
3714 }
drh94fa9c42016-02-27 21:16:04 +00003715 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003716 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003717 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003718 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003719 break;
3720 }
drh2dcef112008-01-12 19:03:48 +00003721
dan165921a2009-08-28 18:53:45 +00003722 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003723 /* If the opcode is TK_TRIGGER, then the expression is a reference
3724 ** to a column in the new.* or old.* pseudo-tables available to
3725 ** trigger programs. In this case Expr.iTable is set to 1 for the
3726 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3727 ** is set to the column of the pseudo-table to read, or to -1 to
3728 ** read the rowid field.
3729 **
3730 ** The expression is implemented using an OP_Param opcode. The p1
3731 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3732 ** to reference another column of the old.* pseudo-table, where
3733 ** i is the index of the column. For a new.rowid reference, p1 is
3734 ** set to (n+1), where n is the number of columns in each pseudo-table.
3735 ** For a reference to any other column in the new.* pseudo-table, p1
3736 ** is set to (n+2+i), where n and i are as defined previously. For
3737 ** example, if the table on which triggers are being fired is
3738 ** declared as:
3739 **
3740 ** CREATE TABLE t1(a, b);
3741 **
3742 ** Then p1 is interpreted as follows:
3743 **
3744 ** p1==0 -> old.rowid p1==3 -> new.rowid
3745 ** p1==1 -> old.a p1==4 -> new.a
3746 ** p1==2 -> old.b p1==5 -> new.b
3747 */
dan2832ad42009-08-31 15:27:27 +00003748 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003749 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3750
3751 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3752 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3753 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3754 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3755
3756 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003757 VdbeComment((v, "%s.%s -> $%d",
3758 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003759 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003760 target
dan165921a2009-08-28 18:53:45 +00003761 ));
dan65a7cd12009-09-01 12:16:01 +00003762
drh44dbca82010-01-13 04:22:20 +00003763#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003764 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003765 ** integer. Use OP_RealAffinity to make sure it is really real.
3766 **
3767 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3768 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003769 if( pExpr->iColumn>=0
3770 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3771 ){
3772 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3773 }
drh44dbca82010-01-13 04:22:20 +00003774#endif
dan165921a2009-08-28 18:53:45 +00003775 break;
3776 }
3777
dan71c57db2016-07-09 20:23:55 +00003778 case TK_VECTOR: {
drhe835bc12016-08-23 19:02:55 +00003779 sqlite3ErrorMsg(pParse, "row value misused");
dan71c57db2016-07-09 20:23:55 +00003780 break;
3781 }
3782
drh2dcef112008-01-12 19:03:48 +00003783 /*
3784 ** Form A:
3785 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3786 **
3787 ** Form B:
3788 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3789 **
3790 ** Form A is can be transformed into the equivalent form B as follows:
3791 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3792 ** WHEN x=eN THEN rN ELSE y END
3793 **
3794 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003795 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3796 ** odd. The Y is also optional. If the number of elements in x.pList
3797 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003798 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3799 **
3800 ** The result of the expression is the Ri for the first matching Ei,
3801 ** or if there is no matching Ei, the ELSE term Y, or if there is
3802 ** no ELSE term, NULL.
3803 */
drh33cd4902009-05-30 20:49:20 +00003804 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003805 int endLabel; /* GOTO label for end of CASE stmt */
3806 int nextCase; /* GOTO label for next WHEN clause */
3807 int nExpr; /* 2x number of WHEN terms */
3808 int i; /* Loop counter */
3809 ExprList *pEList; /* List of WHEN terms */
3810 struct ExprList_item *aListelem; /* Array of WHEN terms */
3811 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003812 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003813 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003814 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003815
danielk19776ab3a2e2009-02-19 14:39:25 +00003816 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003817 assert(pExpr->x.pList->nExpr > 0);
3818 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003819 aListelem = pEList->a;
3820 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003821 endLabel = sqlite3VdbeMakeLabel(v);
3822 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003823 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003824 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00003825 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003826 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00003827 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00003828 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003829 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003830 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003831 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3832 ** The value in regFree1 might get SCopy-ed into the file result.
3833 ** So make sure that the regFree1 register is not reused for other
3834 ** purposes and possibly overwritten. */
3835 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003836 }
drhc5cd1242013-09-12 16:50:49 +00003837 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003838 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003839 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003840 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003841 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003842 }else{
drh2dcef112008-01-12 19:03:48 +00003843 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003844 }
drh2dcef112008-01-12 19:03:48 +00003845 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003846 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003847 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003848 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003849 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003850 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003851 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003852 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003853 }
drhc5cd1242013-09-12 16:50:49 +00003854 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003855 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003856 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003857 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003858 }else{
drh9de221d2008-01-05 06:51:30 +00003859 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003860 }
danielk1977c1f4a192009-04-28 12:08:15 +00003861 assert( db->mallocFailed || pParse->nErr>0
3862 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003863 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003864 break;
3865 }
danielk19775338a5f2005-01-20 13:03:10 +00003866#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003867 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003868 assert( pExpr->affinity==OE_Rollback
3869 || pExpr->affinity==OE_Abort
3870 || pExpr->affinity==OE_Fail
3871 || pExpr->affinity==OE_Ignore
3872 );
dane0af83a2009-09-08 19:15:01 +00003873 if( !pParse->pTriggerTab ){
3874 sqlite3ErrorMsg(pParse,
3875 "RAISE() may only be used within a trigger-program");
3876 return 0;
3877 }
3878 if( pExpr->affinity==OE_Abort ){
3879 sqlite3MayAbort(pParse);
3880 }
dan165921a2009-08-28 18:53:45 +00003881 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003882 if( pExpr->affinity==OE_Ignore ){
3883 sqlite3VdbeAddOp4(
3884 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003885 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003886 }else{
drh433dccf2013-02-09 15:37:11 +00003887 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003888 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003889 }
3890
drhffe07b22005-11-03 00:41:17 +00003891 break;
drh17a7f8d2002-03-24 13:13:27 +00003892 }
danielk19775338a5f2005-01-20 13:03:10 +00003893#endif
drhffe07b22005-11-03 00:41:17 +00003894 }
drh2dcef112008-01-12 19:03:48 +00003895 sqlite3ReleaseTempReg(pParse, regFree1);
3896 sqlite3ReleaseTempReg(pParse, regFree2);
3897 return inReg;
3898}
3899
3900/*
drhd1a01ed2013-11-21 16:08:52 +00003901** Factor out the code of the given expression to initialization time.
3902*/
drhd673cdd2013-11-21 21:23:31 +00003903void sqlite3ExprCodeAtInit(
3904 Parse *pParse, /* Parsing context */
3905 Expr *pExpr, /* The expression to code when the VDBE initializes */
3906 int regDest, /* Store the value in this register */
3907 u8 reusable /* True if this expression is reusable */
3908){
drhd1a01ed2013-11-21 16:08:52 +00003909 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003910 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003911 p = pParse->pConstExpr;
3912 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3913 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003914 if( p ){
3915 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3916 pItem->u.iConstExprReg = regDest;
3917 pItem->reusable = reusable;
3918 }
drhd1a01ed2013-11-21 16:08:52 +00003919 pParse->pConstExpr = p;
3920}
3921
3922/*
drh2dcef112008-01-12 19:03:48 +00003923** Generate code to evaluate an expression and store the results
3924** into a register. Return the register number where the results
3925** are stored.
3926**
3927** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003928** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003929** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003930**
3931** If pExpr is a constant, then this routine might generate this
3932** code to fill the register in the initialization section of the
3933** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003934*/
3935int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003936 int r2;
3937 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003938 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003939 && pExpr->op!=TK_REGISTER
3940 && sqlite3ExprIsConstantNotJoin(pExpr)
3941 ){
3942 ExprList *p = pParse->pConstExpr;
3943 int i;
3944 *pReg = 0;
3945 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003946 struct ExprList_item *pItem;
3947 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3948 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3949 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003950 }
3951 }
3952 }
drhf30a9692013-11-15 01:10:18 +00003953 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003954 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003955 }else{
drhf30a9692013-11-15 01:10:18 +00003956 int r1 = sqlite3GetTempReg(pParse);
3957 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3958 if( r2==r1 ){
3959 *pReg = r1;
3960 }else{
3961 sqlite3ReleaseTempReg(pParse, r1);
3962 *pReg = 0;
3963 }
drh2dcef112008-01-12 19:03:48 +00003964 }
3965 return r2;
3966}
3967
3968/*
3969** Generate code that will evaluate expression pExpr and store the
3970** results in register target. The results are guaranteed to appear
3971** in register target.
3972*/
drh05a86c52014-02-16 01:55:49 +00003973void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00003974 int inReg;
3975
3976 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00003977 if( pExpr && pExpr->op==TK_REGISTER ){
3978 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3979 }else{
3980 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00003981 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00003982 if( inReg!=target && pParse->pVdbe ){
3983 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
3984 }
drhcce7d172000-05-31 15:34:51 +00003985 }
drhcce7d172000-05-31 15:34:51 +00003986}
3987
3988/*
drh1c75c9d2015-12-21 15:22:13 +00003989** Make a transient copy of expression pExpr and then code it using
3990** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
3991** except that the input expression is guaranteed to be unchanged.
3992*/
3993void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
3994 sqlite3 *db = pParse->db;
3995 pExpr = sqlite3ExprDup(db, pExpr, 0);
3996 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
3997 sqlite3ExprDelete(db, pExpr);
3998}
3999
4000/*
drh05a86c52014-02-16 01:55:49 +00004001** Generate code that will evaluate expression pExpr and store the
4002** results in register target. The results are guaranteed to appear
4003** in register target. If the expression is constant, then this routine
4004** might choose to code the expression at initialization time.
4005*/
4006void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
4007 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
4008 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
4009 }else{
4010 sqlite3ExprCode(pParse, pExpr, target);
4011 }
drhcce7d172000-05-31 15:34:51 +00004012}
4013
4014/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004015** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004016** in register target.
drh25303782004-12-07 15:41:48 +00004017**
drh2dcef112008-01-12 19:03:48 +00004018** Also make a copy of the expression results into another "cache" register
4019** and modify the expression so that the next time it is evaluated,
4020** the result is a copy of the cache register.
4021**
4022** This routine is used for expressions that are used multiple
4023** times. They are evaluated once and the results of the expression
4024** are reused.
drh25303782004-12-07 15:41:48 +00004025*/
drh05a86c52014-02-16 01:55:49 +00004026void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004027 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004028 int iMem;
4029
drhde4fcfd2008-01-19 23:50:26 +00004030 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004031 assert( pExpr->op!=TK_REGISTER );
4032 sqlite3ExprCode(pParse, pExpr, target);
4033 iMem = ++pParse->nMem;
4034 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4035 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004036}
drh2dcef112008-01-12 19:03:48 +00004037
drh678ccce2008-03-31 18:19:54 +00004038/*
drh268380c2004-02-25 13:47:31 +00004039** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004040** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004041**
drh892d3172008-01-10 03:46:36 +00004042** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00004043**
4044** The SQLITE_ECEL_DUP flag prevents the arguments from being
4045** filled using OP_SCopy. OP_Copy must be used instead.
4046**
4047** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4048** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004049**
4050** The SQLITE_ECEL_REF flag means that expressions in the list with
4051** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4052** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00004053*/
danielk19774adee202004-05-08 08:23:19 +00004054int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004055 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004056 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004057 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004058 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004059 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004060){
4061 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004062 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004063 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004064 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004065 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004066 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004067 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004068 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004069 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004070 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004071 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00004072 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
4073 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4074 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00004075 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00004076 }else{
4077 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4078 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004079 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004080 if( copyOp==OP_Copy
4081 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4082 && pOp->p1+pOp->p3+1==inReg
4083 && pOp->p2+pOp->p3+1==target+i
4084 ){
4085 pOp->p3++;
4086 }else{
4087 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4088 }
drhd1a01ed2013-11-21 16:08:52 +00004089 }
drhd1766112008-09-17 00:13:12 +00004090 }
drh268380c2004-02-25 13:47:31 +00004091 }
drhf9b596e2004-05-26 16:54:42 +00004092 return n;
drh268380c2004-02-25 13:47:31 +00004093}
4094
4095/*
drh36c563a2009-11-12 13:32:22 +00004096** Generate code for a BETWEEN operator.
4097**
4098** x BETWEEN y AND z
4099**
4100** The above is equivalent to
4101**
4102** x>=y AND x<=z
4103**
4104** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004105** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004106**
4107** The xJumpIf parameter determines details:
4108**
4109** NULL: Store the boolean result in reg[dest]
4110** sqlite3ExprIfTrue: Jump to dest if true
4111** sqlite3ExprIfFalse: Jump to dest if false
4112**
4113** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004114*/
4115static void exprCodeBetween(
4116 Parse *pParse, /* Parsing and code generating context */
4117 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004118 int dest, /* Jump destination or storage location */
4119 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004120 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4121){
drhdb45bd52016-08-22 00:48:58 +00004122 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004123 Expr compLeft; /* The x>=y term */
4124 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004125 Expr exprX; /* The x subexpression */
4126 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004127
drh36c563a2009-11-12 13:32:22 +00004128
dan71c57db2016-07-09 20:23:55 +00004129 memset(&compLeft, 0, sizeof(Expr));
4130 memset(&compRight, 0, sizeof(Expr));
4131 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004132
4133 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
4134 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004135 exprAnd.op = TK_AND;
4136 exprAnd.pLeft = &compLeft;
4137 exprAnd.pRight = &compRight;
4138 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004139 compLeft.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004140 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
4141 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004142 compRight.pLeft = &exprX;
drh36c563a2009-11-12 13:32:22 +00004143 compRight.pRight = pExpr->x.pList->a[1].pExpr;
drh12abf402016-08-22 14:30:05 +00004144 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004145 if( xJump ){
4146 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004147 }else{
drhdb45bd52016-08-22 00:48:58 +00004148 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004149 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004150 }
drhdb45bd52016-08-22 00:48:58 +00004151 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004152
4153 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004154 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4155 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4156 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4157 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4158 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4159 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4160 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4161 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004162 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004163}
4164
4165/*
drhcce7d172000-05-31 15:34:51 +00004166** Generate code for a boolean expression such that a jump is made
4167** to the label "dest" if the expression is true but execution
4168** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004169**
4170** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004171** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004172**
4173** This code depends on the fact that certain token values (ex: TK_EQ)
4174** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4175** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4176** the make process cause these values to align. Assert()s in the code
4177** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004178*/
danielk19774adee202004-05-08 08:23:19 +00004179void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004180 Vdbe *v = pParse->pVdbe;
4181 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004182 int regFree1 = 0;
4183 int regFree2 = 0;
4184 int r1, r2;
4185
drh35573352008-01-08 23:54:25 +00004186 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004187 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004188 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004189 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004190 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004191 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004192 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004193 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004194 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004195 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004196 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
4197 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004198 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004199 break;
4200 }
4201 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004202 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004203 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004204 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004205 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004206 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004207 break;
4208 }
4209 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004210 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004211 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004212 break;
4213 }
drhde845c22016-03-17 19:07:52 +00004214 case TK_IS:
4215 case TK_ISNOT:
4216 testcase( op==TK_IS );
4217 testcase( op==TK_ISNOT );
4218 op = (op==TK_IS) ? TK_EQ : TK_NE;
4219 jumpIfNull = SQLITE_NULLEQ;
4220 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004221 case TK_LT:
4222 case TK_LE:
4223 case TK_GT:
4224 case TK_GE:
4225 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004226 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004227 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004228 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004229 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4230 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004231 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004232 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004233 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4234 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4235 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4236 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004237 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4238 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4239 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4240 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4241 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4242 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004243 testcase( regFree1==0 );
4244 testcase( regFree2==0 );
4245 break;
4246 }
drhcce7d172000-05-31 15:34:51 +00004247 case TK_ISNULL:
4248 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004249 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4250 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004251 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4252 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004253 VdbeCoverageIf(v, op==TK_ISNULL);
4254 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004255 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004256 break;
4257 }
drhfef52082000-06-06 01:50:43 +00004258 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004259 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004260 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004261 break;
4262 }
drh84e30ca2011-02-10 17:46:14 +00004263#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004264 case TK_IN: {
4265 int destIfFalse = sqlite3VdbeMakeLabel(v);
4266 int destIfNull = jumpIfNull ? dest : destIfFalse;
4267 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004268 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004269 sqlite3VdbeResolveLabel(v, destIfFalse);
4270 break;
4271 }
shanehbb201342011-02-09 19:55:20 +00004272#endif
drhcce7d172000-05-31 15:34:51 +00004273 default: {
dan7b35a772016-07-28 19:47:15 +00004274 default_expr:
drh991a1982014-01-02 17:57:16 +00004275 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004276 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004277 }else if( exprAlwaysFalse(pExpr) ){
4278 /* No-op */
4279 }else{
4280 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4281 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004282 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004283 testcase( regFree1==0 );
4284 testcase( jumpIfNull==0 );
4285 }
drhcce7d172000-05-31 15:34:51 +00004286 break;
4287 }
4288 }
drh2dcef112008-01-12 19:03:48 +00004289 sqlite3ReleaseTempReg(pParse, regFree1);
4290 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004291}
4292
4293/*
drh66b89c82000-11-28 20:47:17 +00004294** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004295** to the label "dest" if the expression is false but execution
4296** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004297**
4298** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004299** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4300** is 0.
drhcce7d172000-05-31 15:34:51 +00004301*/
danielk19774adee202004-05-08 08:23:19 +00004302void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004303 Vdbe *v = pParse->pVdbe;
4304 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004305 int regFree1 = 0;
4306 int regFree2 = 0;
4307 int r1, r2;
4308
drh35573352008-01-08 23:54:25 +00004309 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004310 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004311 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004312
4313 /* The value of pExpr->op and op are related as follows:
4314 **
4315 ** pExpr->op op
4316 ** --------- ----------
4317 ** TK_ISNULL OP_NotNull
4318 ** TK_NOTNULL OP_IsNull
4319 ** TK_NE OP_Eq
4320 ** TK_EQ OP_Ne
4321 ** TK_GT OP_Le
4322 ** TK_LE OP_Gt
4323 ** TK_GE OP_Lt
4324 ** TK_LT OP_Ge
4325 **
4326 ** For other values of pExpr->op, op is undefined and unused.
4327 ** The value of TK_ and OP_ constants are arranged such that we
4328 ** can compute the mapping above using the following expression.
4329 ** Assert()s verify that the computation is correct.
4330 */
4331 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4332
4333 /* Verify correct alignment of TK_ and OP_ constants
4334 */
4335 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4336 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4337 assert( pExpr->op!=TK_NE || op==OP_Eq );
4338 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4339 assert( pExpr->op!=TK_LT || op==OP_Ge );
4340 assert( pExpr->op!=TK_LE || op==OP_Gt );
4341 assert( pExpr->op!=TK_GT || op==OP_Le );
4342 assert( pExpr->op!=TK_GE || op==OP_Lt );
4343
danba00e302016-07-23 20:24:06 +00004344 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004345 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004346 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004347 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004348 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004349 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004350 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004351 break;
4352 }
4353 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004354 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004355 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004356 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004357 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004358 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4359 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004360 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004361 break;
4362 }
4363 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004364 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004365 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004366 break;
4367 }
drhde845c22016-03-17 19:07:52 +00004368 case TK_IS:
4369 case TK_ISNOT:
4370 testcase( pExpr->op==TK_IS );
4371 testcase( pExpr->op==TK_ISNOT );
4372 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4373 jumpIfNull = SQLITE_NULLEQ;
4374 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004375 case TK_LT:
4376 case TK_LE:
4377 case TK_GT:
4378 case TK_GE:
4379 case TK_NE:
4380 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004381 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004382 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004383 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4384 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004385 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004386 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004387 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4388 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4389 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4390 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004391 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4392 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4393 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4394 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4395 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4396 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004397 testcase( regFree1==0 );
4398 testcase( regFree2==0 );
4399 break;
4400 }
drhcce7d172000-05-31 15:34:51 +00004401 case TK_ISNULL:
4402 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004403 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4404 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004405 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4406 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004407 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004408 break;
4409 }
drhfef52082000-06-06 01:50:43 +00004410 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004411 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004412 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004413 break;
4414 }
drh84e30ca2011-02-10 17:46:14 +00004415#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004416 case TK_IN: {
4417 if( jumpIfNull ){
4418 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4419 }else{
4420 int destIfNull = sqlite3VdbeMakeLabel(v);
4421 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4422 sqlite3VdbeResolveLabel(v, destIfNull);
4423 }
4424 break;
4425 }
shanehbb201342011-02-09 19:55:20 +00004426#endif
drhcce7d172000-05-31 15:34:51 +00004427 default: {
danba00e302016-07-23 20:24:06 +00004428 default_expr:
drh991a1982014-01-02 17:57:16 +00004429 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004430 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004431 }else if( exprAlwaysTrue(pExpr) ){
4432 /* no-op */
4433 }else{
4434 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4435 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004436 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004437 testcase( regFree1==0 );
4438 testcase( jumpIfNull==0 );
4439 }
drhcce7d172000-05-31 15:34:51 +00004440 break;
4441 }
4442 }
drh2dcef112008-01-12 19:03:48 +00004443 sqlite3ReleaseTempReg(pParse, regFree1);
4444 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004445}
drh22827922000-06-06 17:27:05 +00004446
4447/*
drh72bc8202015-06-11 13:58:35 +00004448** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4449** code generation, and that copy is deleted after code generation. This
4450** ensures that the original pExpr is unchanged.
4451*/
4452void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4453 sqlite3 *db = pParse->db;
4454 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4455 if( db->mallocFailed==0 ){
4456 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4457 }
4458 sqlite3ExprDelete(db, pCopy);
4459}
4460
4461
4462/*
drh1d9da702010-01-07 15:17:02 +00004463** Do a deep comparison of two expression trees. Return 0 if the two
4464** expressions are completely identical. Return 1 if they differ only
4465** by a COLLATE operator at the top level. Return 2 if there are differences
4466** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004467**
drh619a1302013-08-01 13:04:46 +00004468** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4469** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4470**
drh66518ca2013-08-01 15:09:57 +00004471** The pA side might be using TK_REGISTER. If that is the case and pB is
4472** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4473**
drh1d9da702010-01-07 15:17:02 +00004474** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004475** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004476** identical, we return 2 just to be safe. So if this routine
4477** returns 2, then you do not really know for certain if the two
4478** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004479** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004480** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004481** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004482** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00004483*/
drh619a1302013-08-01 13:04:46 +00004484int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004485 u32 combinedFlags;
4486 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004487 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004488 }
drh10d1edf2013-11-15 15:52:39 +00004489 combinedFlags = pA->flags | pB->flags;
4490 if( combinedFlags & EP_IntValue ){
4491 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4492 return 0;
4493 }
drh1d9da702010-01-07 15:17:02 +00004494 return 2;
drh22827922000-06-06 17:27:05 +00004495 }
drhc2acc4e2013-11-15 18:15:19 +00004496 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00004497 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004498 return 1;
4499 }
drh619a1302013-08-01 13:04:46 +00004500 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004501 return 1;
4502 }
4503 return 2;
4504 }
drh2edc5fd2015-11-24 02:10:52 +00004505 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004506 if( pA->op==TK_FUNCTION ){
4507 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4508 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00004509 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00004510 }
drh22827922000-06-06 17:27:05 +00004511 }
drh10d1edf2013-11-15 15:52:39 +00004512 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004513 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00004514 if( combinedFlags & EP_xIsSelect ) return 2;
4515 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4516 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4517 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00004518 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00004519 if( pA->iColumn!=pB->iColumn ) return 2;
4520 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004521 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004522 }
4523 }
drh1d9da702010-01-07 15:17:02 +00004524 return 0;
drh22827922000-06-06 17:27:05 +00004525}
4526
drh8c6f6662010-04-26 19:17:26 +00004527/*
4528** Compare two ExprList objects. Return 0 if they are identical and
4529** non-zero if they differ in any way.
4530**
drh619a1302013-08-01 13:04:46 +00004531** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4532** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4533**
drh8c6f6662010-04-26 19:17:26 +00004534** This routine might return non-zero for equivalent ExprLists. The
4535** only consequence will be disabled optimizations. But this routine
4536** must never return 0 if the two ExprList objects are different, or
4537** a malfunction will result.
4538**
4539** Two NULL pointers are considered to be the same. But a NULL pointer
4540** always differs from a non-NULL pointer.
4541*/
drh619a1302013-08-01 13:04:46 +00004542int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004543 int i;
4544 if( pA==0 && pB==0 ) return 0;
4545 if( pA==0 || pB==0 ) return 1;
4546 if( pA->nExpr!=pB->nExpr ) return 1;
4547 for(i=0; i<pA->nExpr; i++){
4548 Expr *pExprA = pA->a[i].pExpr;
4549 Expr *pExprB = pB->a[i].pExpr;
4550 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00004551 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004552 }
4553 return 0;
4554}
drh13449892005-09-07 21:22:45 +00004555
drh22827922000-06-06 17:27:05 +00004556/*
drh4bd5f732013-07-31 23:22:39 +00004557** Return true if we can prove the pE2 will always be true if pE1 is
4558** true. Return false if we cannot complete the proof or if pE2 might
4559** be false. Examples:
4560**
drh619a1302013-08-01 13:04:46 +00004561** pE1: x==5 pE2: x==5 Result: true
4562** pE1: x>0 pE2: x==5 Result: false
4563** pE1: x=21 pE2: x=21 OR y=43 Result: true
4564** pE1: x!=123 pE2: x IS NOT NULL Result: true
4565** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4566** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4567** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004568**
4569** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4570** Expr.iTable<0 then assume a table number given by iTab.
4571**
4572** When in doubt, return false. Returning true might give a performance
4573** improvement. Returning false might cause a performance reduction, but
4574** it will always give the correct answer and is hence always safe.
4575*/
4576int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00004577 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4578 return 1;
4579 }
4580 if( pE2->op==TK_OR
4581 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4582 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4583 ){
4584 return 1;
4585 }
4586 if( pE2->op==TK_NOTNULL
4587 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4588 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4589 ){
4590 return 1;
4591 }
4592 return 0;
drh4bd5f732013-07-31 23:22:39 +00004593}
4594
4595/*
drh030796d2012-08-23 16:18:10 +00004596** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00004597** to determine if an expression can be evaluated by reference to the
4598** index only, without having to do a search for the corresponding
4599** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4600** is the cursor for the table.
4601*/
4602struct IdxCover {
4603 Index *pIdx; /* The index to be tested for coverage */
4604 int iCur; /* Cursor number for the table corresponding to the index */
4605};
4606
4607/*
4608** Check to see if there are references to columns in table
4609** pWalker->u.pIdxCover->iCur can be satisfied using the index
4610** pWalker->u.pIdxCover->pIdx.
4611*/
4612static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4613 if( pExpr->op==TK_COLUMN
4614 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4615 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4616 ){
4617 pWalker->eCode = 1;
4618 return WRC_Abort;
4619 }
4620 return WRC_Continue;
4621}
4622
4623/*
drhe604ec02016-07-27 19:20:58 +00004624** Determine if an index pIdx on table with cursor iCur contains will
4625** the expression pExpr. Return true if the index does cover the
4626** expression and false if the pExpr expression references table columns
4627** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00004628**
4629** An index covering an expression means that the expression can be
4630** evaluated using only the index and without having to lookup the
4631** corresponding table entry.
4632*/
4633int sqlite3ExprCoveredByIndex(
4634 Expr *pExpr, /* The index to be tested */
4635 int iCur, /* The cursor number for the corresponding table */
4636 Index *pIdx /* The index that might be used for coverage */
4637){
4638 Walker w;
4639 struct IdxCover xcov;
4640 memset(&w, 0, sizeof(w));
4641 xcov.iCur = iCur;
4642 xcov.pIdx = pIdx;
4643 w.xExprCallback = exprIdxCover;
4644 w.u.pIdxCover = &xcov;
4645 sqlite3WalkExpr(&w, pExpr);
4646 return !w.eCode;
4647}
4648
4649
4650/*
4651** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00004652** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00004653** aggregate function, in order to implement the
4654** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00004655*/
drh030796d2012-08-23 16:18:10 +00004656struct SrcCount {
4657 SrcList *pSrc; /* One particular FROM clause in a nested query */
4658 int nThis; /* Number of references to columns in pSrcList */
4659 int nOther; /* Number of references to columns in other FROM clauses */
4660};
4661
4662/*
4663** Count the number of references to columns.
4664*/
4665static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00004666 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4667 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4668 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4669 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4670 ** NEVER() will need to be removed. */
4671 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00004672 int i;
drh030796d2012-08-23 16:18:10 +00004673 struct SrcCount *p = pWalker->u.pSrcCount;
4674 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00004675 int nSrc = pSrc ? pSrc->nSrc : 0;
4676 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00004677 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00004678 }
drh655814d2015-01-09 01:27:29 +00004679 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00004680 p->nThis++;
4681 }else{
4682 p->nOther++;
4683 }
drh374fdce2012-04-17 16:38:53 +00004684 }
drh030796d2012-08-23 16:18:10 +00004685 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004686}
4687
4688/*
drh030796d2012-08-23 16:18:10 +00004689** Determine if any of the arguments to the pExpr Function reference
4690** pSrcList. Return true if they do. Also return true if the function
4691** has no arguments or has only constant arguments. Return false if pExpr
4692** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004693*/
drh030796d2012-08-23 16:18:10 +00004694int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004695 Walker w;
drh030796d2012-08-23 16:18:10 +00004696 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004697 assert( pExpr->op==TK_AGG_FUNCTION );
4698 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004699 w.xExprCallback = exprSrcCount;
4700 w.u.pSrcCount = &cnt;
4701 cnt.pSrc = pSrcList;
4702 cnt.nThis = 0;
4703 cnt.nOther = 0;
4704 sqlite3WalkExprList(&w, pExpr->x.pList);
4705 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004706}
4707
4708/*
drh13449892005-09-07 21:22:45 +00004709** Add a new element to the pAggInfo->aCol[] array. Return the index of
4710** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004711*/
drh17435752007-08-16 04:30:38 +00004712static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004713 int i;
drhcf643722007-03-27 13:36:37 +00004714 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004715 db,
drhcf643722007-03-27 13:36:37 +00004716 pInfo->aCol,
4717 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004718 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004719 &i
4720 );
drh13449892005-09-07 21:22:45 +00004721 return i;
4722}
4723
4724/*
4725** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4726** the new element. Return a negative number if malloc fails.
4727*/
drh17435752007-08-16 04:30:38 +00004728static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004729 int i;
drhcf643722007-03-27 13:36:37 +00004730 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004731 db,
drhcf643722007-03-27 13:36:37 +00004732 pInfo->aFunc,
4733 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004734 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004735 &i
4736 );
drh13449892005-09-07 21:22:45 +00004737 return i;
4738}
drh22827922000-06-06 17:27:05 +00004739
4740/*
drh7d10d5a2008-08-20 16:35:10 +00004741** This is the xExprCallback for a tree walker. It is used to
4742** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004743** for additional information.
drh22827922000-06-06 17:27:05 +00004744*/
drh7d10d5a2008-08-20 16:35:10 +00004745static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004746 int i;
drh7d10d5a2008-08-20 16:35:10 +00004747 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004748 Parse *pParse = pNC->pParse;
4749 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004750 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004751
drh22827922000-06-06 17:27:05 +00004752 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004753 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004754 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004755 testcase( pExpr->op==TK_AGG_COLUMN );
4756 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004757 /* Check to see if the column is in one of the tables in the FROM
4758 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004759 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004760 struct SrcList_item *pItem = pSrcList->a;
4761 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4762 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004763 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004764 if( pExpr->iTable==pItem->iCursor ){
4765 /* If we reach this point, it means that pExpr refers to a table
4766 ** that is in the FROM clause of the aggregate query.
4767 **
4768 ** Make an entry for the column in pAggInfo->aCol[] if there
4769 ** is not an entry there already.
4770 */
drh7f906d62007-03-12 23:48:52 +00004771 int k;
drh13449892005-09-07 21:22:45 +00004772 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004773 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004774 if( pCol->iTable==pExpr->iTable &&
4775 pCol->iColumn==pExpr->iColumn ){
4776 break;
4777 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004778 }
danielk19771e536952007-08-16 10:09:01 +00004779 if( (k>=pAggInfo->nColumn)
4780 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4781 ){
drh7f906d62007-03-12 23:48:52 +00004782 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004783 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004784 pCol->iTable = pExpr->iTable;
4785 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004786 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004787 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004788 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004789 if( pAggInfo->pGroupBy ){
4790 int j, n;
4791 ExprList *pGB = pAggInfo->pGroupBy;
4792 struct ExprList_item *pTerm = pGB->a;
4793 n = pGB->nExpr;
4794 for(j=0; j<n; j++, pTerm++){
4795 Expr *pE = pTerm->pExpr;
4796 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4797 pE->iColumn==pExpr->iColumn ){
4798 pCol->iSorterColumn = j;
4799 break;
4800 }
4801 }
4802 }
4803 if( pCol->iSorterColumn<0 ){
4804 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4805 }
4806 }
4807 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4808 ** because it was there before or because we just created it).
4809 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4810 ** pAggInfo->aCol[] entry.
4811 */
drhebb6a652013-09-12 23:42:22 +00004812 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004813 pExpr->pAggInfo = pAggInfo;
4814 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004815 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004816 break;
4817 } /* endif pExpr->iTable==pItem->iCursor */
4818 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004819 }
drh7d10d5a2008-08-20 16:35:10 +00004820 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004821 }
4822 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004823 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004824 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004825 ){
drh13449892005-09-07 21:22:45 +00004826 /* Check to see if pExpr is a duplicate of another aggregate
4827 ** function that is already in the pAggInfo structure
4828 */
4829 struct AggInfo_func *pItem = pAggInfo->aFunc;
4830 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004831 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004832 break;
4833 }
drh22827922000-06-06 17:27:05 +00004834 }
drh13449892005-09-07 21:22:45 +00004835 if( i>=pAggInfo->nFunc ){
4836 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4837 */
danielk197714db2662006-01-09 16:12:04 +00004838 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004839 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004840 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004841 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004842 pItem = &pAggInfo->aFunc[i];
4843 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004844 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004845 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004846 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004847 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004848 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004849 if( pExpr->flags & EP_Distinct ){
4850 pItem->iDistinct = pParse->nTab++;
4851 }else{
4852 pItem->iDistinct = -1;
4853 }
drh13449892005-09-07 21:22:45 +00004854 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004855 }
drh13449892005-09-07 21:22:45 +00004856 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4857 */
drhc5cd1242013-09-12 16:50:49 +00004858 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004859 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004860 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004861 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004862 return WRC_Prune;
4863 }else{
4864 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004865 }
drh22827922000-06-06 17:27:05 +00004866 }
4867 }
drh7d10d5a2008-08-20 16:35:10 +00004868 return WRC_Continue;
4869}
4870static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004871 UNUSED_PARAMETER(pWalker);
4872 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004873 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004874}
4875
4876/*
drhe8abb4c2012-11-02 18:24:57 +00004877** Analyze the pExpr expression looking for aggregate functions and
4878** for variables that need to be added to AggInfo object that pNC->pAggInfo
4879** points to. Additional entries are made on the AggInfo object as
4880** necessary.
drh626a8792005-01-17 22:08:19 +00004881**
4882** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004883** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004884*/
drhd2b3e232008-01-23 14:51:49 +00004885void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004886 Walker w;
drh374fdce2012-04-17 16:38:53 +00004887 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004888 w.xExprCallback = analyzeAggregate;
4889 w.xSelectCallback = analyzeAggregatesInSelect;
4890 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004891 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004892 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004893}
drh5d9a4af2005-08-30 00:54:01 +00004894
4895/*
4896** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4897** expression list. Return the number of errors.
4898**
4899** If an error is found, the analysis is cut short.
4900*/
drhd2b3e232008-01-23 14:51:49 +00004901void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004902 struct ExprList_item *pItem;
4903 int i;
drh5d9a4af2005-08-30 00:54:01 +00004904 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004905 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4906 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004907 }
4908 }
drh5d9a4af2005-08-30 00:54:01 +00004909}
drh892d3172008-01-10 03:46:36 +00004910
4911/*
drhceea3322009-04-23 13:22:42 +00004912** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004913*/
4914int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004915 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004916 return ++pParse->nMem;
4917 }
danielk19772f425f62008-07-04 09:41:39 +00004918 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004919}
drhceea3322009-04-23 13:22:42 +00004920
4921/*
4922** Deallocate a register, making available for reuse for some other
4923** purpose.
4924**
4925** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004926** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004927** the register becomes stale.
4928*/
drh892d3172008-01-10 03:46:36 +00004929void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004930 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004931 int i;
4932 struct yColCache *p;
4933 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4934 if( p->iReg==iReg ){
4935 p->tempReg = 1;
4936 return;
4937 }
4938 }
drh892d3172008-01-10 03:46:36 +00004939 pParse->aTempReg[pParse->nTempReg++] = iReg;
4940 }
4941}
4942
4943/*
4944** Allocate or deallocate a block of nReg consecutive registers
4945*/
4946int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004947 int i, n;
4948 i = pParse->iRangeReg;
4949 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004950 if( nReg<=n ){
4951 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004952 pParse->iRangeReg += nReg;
4953 pParse->nRangeReg -= nReg;
4954 }else{
4955 i = pParse->nMem+1;
4956 pParse->nMem += nReg;
4957 }
4958 return i;
4959}
4960void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004961 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004962 if( nReg>pParse->nRangeReg ){
4963 pParse->nRangeReg = nReg;
4964 pParse->iRangeReg = iReg;
4965 }
4966}
drhcdc69552011-12-06 13:24:59 +00004967
4968/*
4969** Mark all temporary registers as being unavailable for reuse.
4970*/
4971void sqlite3ClearTempRegCache(Parse *pParse){
4972 pParse->nTempReg = 0;
4973 pParse->nRangeReg = 0;
4974}
drhbb9b5f22016-03-19 00:35:02 +00004975
4976/*
4977** Validate that no temporary register falls within the range of
4978** iFirst..iLast, inclusive. This routine is only call from within assert()
4979** statements.
4980*/
4981#ifdef SQLITE_DEBUG
4982int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4983 int i;
4984 if( pParse->nRangeReg>0
4985 && pParse->iRangeReg+pParse->nRangeReg<iLast
4986 && pParse->iRangeReg>=iFirst
4987 ){
4988 return 0;
4989 }
4990 for(i=0; i<pParse->nTempReg; i++){
4991 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4992 return 0;
4993 }
4994 }
4995 return 1;
4996}
4997#endif /* SQLITE_DEBUG */