blob: 0b9c236b66eb0dda29bcb98d19eac83ab2cfc94a [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
drh0dfa4f62016-08-26 13:19:49 +000021/*
22** Return the affinity character for a single column of a table.
23*/
24char sqlite3TableColumnAffinity(Table *pTab, int iCol){
25 assert( iCol<pTab->nCol );
26 return iCol>=0 ? pTab->aCol[iCol].affinity : SQLITE_AFF_INTEGER;
27}
drh12abf402016-08-22 14:30:05 +000028
danielk1977e014a832004-05-17 10:48:57 +000029/*
30** Return the 'affinity' of the expression pExpr if any.
31**
32** If pExpr is a column, a reference to a column via an 'AS' alias,
33** or a sub-select with a column as the return value, then the
34** affinity of that column is returned. Otherwise, 0x00 is returned,
35** indicating no affinity for the expression.
36**
peter.d.reid60ec9142014-09-06 16:39:46 +000037** i.e. the WHERE clause expressions in the following statements all
danielk1977e014a832004-05-17 10:48:57 +000038** have an affinity:
39**
40** CREATE TABLE t1(a);
41** SELECT * FROM t1 WHERE a;
42** SELECT a AS b FROM t1 WHERE b;
43** SELECT * FROM t1 WHERE (select a from t1);
44*/
danielk1977bf3b7212004-05-18 10:06:24 +000045char sqlite3ExprAffinity(Expr *pExpr){
drh580c8c12012-12-08 03:34:04 +000046 int op;
47 pExpr = sqlite3ExprSkipCollate(pExpr);
mistachkin9bec6fb2014-06-26 21:28:21 +000048 if( pExpr->flags & EP_Generic ) return 0;
drh580c8c12012-12-08 03:34:04 +000049 op = pExpr->op;
drh487e2622005-06-25 18:42:14 +000050 if( op==TK_SELECT ){
drh3b3c86a2018-09-18 21:35:31 +000051 assert( pExpr->eX==EX_Select );
danielk19776ab3a2e2009-02-19 14:39:25 +000052 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
danielk1977a37cdde2004-05-16 11:15:36 +000053 }
drhdb45bd52016-08-22 00:48:58 +000054 if( op==TK_REGISTER ) op = pExpr->op2;
drh487e2622005-06-25 18:42:14 +000055#ifndef SQLITE_OMIT_CAST
56 if( op==TK_CAST ){
drh33e619f2009-05-28 01:00:55 +000057 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drhfdaac672013-10-04 15:30:21 +000058 return sqlite3AffinityType(pExpr->u.zToken, 0);
drh487e2622005-06-25 18:42:14 +000059 }
60#endif
drh8477f7f2018-09-19 20:14:48 +000061 if( (op==TK_AGG_COLUMN || op==TK_COLUMN)
62 && ALWAYS(pExpr->eX==EX_Tab) && pExpr->x.pTab ){
63 return sqlite3TableColumnAffinity(pExpr->x.pTab, pExpr->iColumn);
drh7d10d5a2008-08-20 16:35:10 +000064 }
dan80aa5452016-09-03 19:52:12 +000065 if( op==TK_SELECT_COLUMN ){
drh3b3c86a2018-09-18 21:35:31 +000066 assert( pExpr->pLeft->eX==EX_Select );
dan80aa5452016-09-03 19:52:12 +000067 return sqlite3ExprAffinity(
68 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
69 );
70 }
danielk1977a37cdde2004-05-16 11:15:36 +000071 return pExpr->affinity;
72}
73
drh53db1452004-05-20 13:54:53 +000074/*
drh8b4c40d2007-02-01 23:02:45 +000075** Set the collating sequence for expression pExpr to be the collating
drhae80dde2012-12-06 21:16:43 +000076** sequence named by pToken. Return a pointer to a new Expr node that
77** implements the COLLATE operator.
drh0a8a4062012-12-07 18:38:16 +000078**
79** If a memory allocation error occurs, that fact is recorded in pParse->db
80** and the pExpr parameter is returned unchanged.
drh8b4c40d2007-02-01 23:02:45 +000081*/
drh4ef7efa2014-03-20 15:14:08 +000082Expr *sqlite3ExprAddCollateToken(
83 Parse *pParse, /* Parsing context */
84 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
dan80103fc2015-03-20 08:43:59 +000085 const Token *pCollName, /* Name of collating sequence */
86 int dequote /* True to dequote pCollName */
drh4ef7efa2014-03-20 15:14:08 +000087){
drh0a8a4062012-12-07 18:38:16 +000088 if( pCollName->n>0 ){
dan80103fc2015-03-20 08:43:59 +000089 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
drh0a8a4062012-12-07 18:38:16 +000090 if( pNew ){
91 pNew->pLeft = pExpr;
drha4c3c872013-09-12 17:29:25 +000092 pNew->flags |= EP_Collate|EP_Skip;
drh0a8a4062012-12-07 18:38:16 +000093 pExpr = pNew;
94 }
drhae80dde2012-12-06 21:16:43 +000095 }
drh0a8a4062012-12-07 18:38:16 +000096 return pExpr;
97}
98Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
drh261d8a52012-12-08 21:36:26 +000099 Token s;
100 assert( zC!=0 );
drh40aced52016-01-22 17:48:09 +0000101 sqlite3TokenInit(&s, (char*)zC);
dan80103fc2015-03-20 08:43:59 +0000102 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
drh0a8a4062012-12-07 18:38:16 +0000103}
104
105/*
drh0b8d2552015-09-05 22:36:07 +0000106** Skip over any TK_COLLATE operators and any unlikely()
drha4c3c872013-09-12 17:29:25 +0000107** or likelihood() function at the root of an expression.
drh0a8a4062012-12-07 18:38:16 +0000108*/
109Expr *sqlite3ExprSkipCollate(Expr *pExpr){
drha4c3c872013-09-12 17:29:25 +0000110 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
111 if( ExprHasProperty(pExpr, EP_Unlikely) ){
drh3b3c86a2018-09-18 21:35:31 +0000112 assert( pExpr->eX==EX_List );
drhcca9f3d2013-09-06 15:23:29 +0000113 assert( pExpr->x.pList->nExpr>0 );
drha4c3c872013-09-12 17:29:25 +0000114 assert( pExpr->op==TK_FUNCTION );
drhcca9f3d2013-09-06 15:23:29 +0000115 pExpr = pExpr->x.pList->a[0].pExpr;
116 }else{
drh0b8d2552015-09-05 22:36:07 +0000117 assert( pExpr->op==TK_COLLATE );
drha4c3c872013-09-12 17:29:25 +0000118 pExpr = pExpr->pLeft;
drhcca9f3d2013-09-06 15:23:29 +0000119 }
drha4c3c872013-09-12 17:29:25 +0000120 }
drh0a8a4062012-12-07 18:38:16 +0000121 return pExpr;
drh8b4c40d2007-02-01 23:02:45 +0000122}
123
124/*
drhae80dde2012-12-06 21:16:43 +0000125** Return the collation sequence for the expression pExpr. If
126** there is no defined collating sequence, return NULL.
127**
drh70efa842017-09-28 01:58:23 +0000128** See also: sqlite3ExprNNCollSeq()
129**
130** The sqlite3ExprNNCollSeq() works the same exact that it returns the
131** default collation if pExpr has no defined collation.
132**
drhae80dde2012-12-06 21:16:43 +0000133** The collating sequence might be determined by a COLLATE operator
134** or by the presence of a column with a defined collating sequence.
135** COLLATE operators take first precedence. Left operands take
136** precedence over right operands.
danielk19770202b292004-06-09 09:55:16 +0000137*/
danielk19777cedc8d2004-06-10 10:50:08 +0000138CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000139 sqlite3 *db = pParse->db;
danielk19777cedc8d2004-06-10 10:50:08 +0000140 CollSeq *pColl = 0;
drh7d10d5a2008-08-20 16:35:10 +0000141 Expr *p = pExpr;
drh261d8a52012-12-08 21:36:26 +0000142 while( p ){
drhae80dde2012-12-06 21:16:43 +0000143 int op = p->op;
drhfbb24d12014-03-20 17:03:30 +0000144 if( p->flags & EP_Generic ) break;
drha58d4a92015-01-27 13:17:05 +0000145 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
drhae80dde2012-12-06 21:16:43 +0000146 || op==TK_REGISTER || op==TK_TRIGGER)
drh8477f7f2018-09-19 20:14:48 +0000147 && p->eX==EX_Tab
148 && p->x.pTab!=0
drhae80dde2012-12-06 21:16:43 +0000149 ){
drh7d10d5a2008-08-20 16:35:10 +0000150 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
151 ** a TK_COLUMN but was previously evaluated and cached in a register */
drh7d10d5a2008-08-20 16:35:10 +0000152 int j = p->iColumn;
153 if( j>=0 ){
drh8477f7f2018-09-19 20:14:48 +0000154 const char *zColl = p->x.pTab->aCol[j].zColl;
drhc4a64fa2009-05-11 20:53:28 +0000155 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh7d10d5a2008-08-20 16:35:10 +0000156 }
157 break;
danielk19770202b292004-06-09 09:55:16 +0000158 }
drhe081d732018-07-27 18:19:12 +0000159 if( op==TK_CAST || op==TK_UPLUS ){
160 p = p->pLeft;
161 continue;
162 }
163 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
164 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
165 break;
166 }
drhae80dde2012-12-06 21:16:43 +0000167 if( p->flags & EP_Collate ){
drh2308ed32015-02-09 16:09:34 +0000168 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
drhae80dde2012-12-06 21:16:43 +0000169 p = p->pLeft;
170 }else{
drh3d6bedf2018-09-19 14:54:38 +0000171 Expr *pNext = 0;
drh6728cd92015-02-09 18:28:03 +0000172 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
173 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
174 ** least one EP_Collate. Thus the following two ALWAYS. */
drh3b3c86a2018-09-18 21:35:31 +0000175 if( p->eX==EX_List ){
drh2308ed32015-02-09 16:09:34 +0000176 int i;
drh6728cd92015-02-09 18:28:03 +0000177 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
drh2308ed32015-02-09 16:09:34 +0000178 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
179 pNext = p->x.pList->a[i].pExpr;
180 break;
181 }
182 }
drh3d6bedf2018-09-19 14:54:38 +0000183 }else if( p->eX==EX_Right ){
184 pNext = p->x.pRight;
drh2308ed32015-02-09 16:09:34 +0000185 }
186 p = pNext;
drhae80dde2012-12-06 21:16:43 +0000187 }
188 }else{
drh7d10d5a2008-08-20 16:35:10 +0000189 break;
190 }
danielk19770202b292004-06-09 09:55:16 +0000191 }
danielk19777cedc8d2004-06-10 10:50:08 +0000192 if( sqlite3CheckCollSeq(pParse, pColl) ){
193 pColl = 0;
194 }
195 return pColl;
danielk19770202b292004-06-09 09:55:16 +0000196}
197
198/*
drh70efa842017-09-28 01:58:23 +0000199** Return the collation sequence for the expression pExpr. If
200** there is no defined collating sequence, return a pointer to the
201** defautl collation sequence.
202**
203** See also: sqlite3ExprCollSeq()
204**
205** The sqlite3ExprCollSeq() routine works the same except that it
206** returns NULL if there is no defined collation.
207*/
208CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
209 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
210 if( p==0 ) p = pParse->db->pDfltColl;
211 assert( p!=0 );
212 return p;
213}
214
215/*
216** Return TRUE if the two expressions have equivalent collating sequences.
217*/
218int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
219 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
220 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
221 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
222}
223
224/*
drh626a8792005-01-17 22:08:19 +0000225** pExpr is an operand of a comparison operator. aff2 is the
226** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +0000227** type affinity that should be used for the comparison operator.
228*/
danielk1977e014a832004-05-17 10:48:57 +0000229char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +0000230 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +0000231 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +0000232 /* Both sides of the comparison are columns. If one has numeric
233 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +0000234 */
drh8a512562005-11-14 22:29:05 +0000235 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +0000236 return SQLITE_AFF_NUMERIC;
237 }else{
drh05883a32015-06-02 15:32:08 +0000238 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000239 }
240 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +0000241 /* Neither side of the comparison is a column. Compare the
242 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +0000243 */
drh05883a32015-06-02 15:32:08 +0000244 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000245 }else{
246 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +0000247 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +0000248 return (aff1 + aff2);
249 }
250}
251
drh53db1452004-05-20 13:54:53 +0000252/*
253** pExpr is a comparison operator. Return the type affinity that should
254** be applied to both operands prior to doing the comparison.
255*/
danielk1977e014a832004-05-17 10:48:57 +0000256static char comparisonAffinity(Expr *pExpr){
257 char aff;
258 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
259 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
drh6a2fe092009-09-23 02:29:36 +0000260 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
danielk1977e014a832004-05-17 10:48:57 +0000261 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000262 aff = sqlite3ExprAffinity(pExpr->pLeft);
drh3d6bedf2018-09-19 14:54:38 +0000263 if( pExpr->eX==EX_Right ){
264 aff = sqlite3CompareAffinity(pExpr->x.pRight, aff);
drh3b3c86a2018-09-18 21:35:31 +0000265 }else if( pExpr->eX==EX_Select ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000266 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
drh13ac46e2017-02-11 13:51:23 +0000267 }else if( aff==0 ){
drh05883a32015-06-02 15:32:08 +0000268 aff = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000269 }
270 return aff;
271}
272
273/*
274** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
275** idx_affinity is the affinity of an indexed column. Return true
276** if the index with affinity idx_affinity may be used to implement
277** the comparison in pExpr.
278*/
279int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
280 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000281 switch( aff ){
drh05883a32015-06-02 15:32:08 +0000282 case SQLITE_AFF_BLOB:
drh8a512562005-11-14 22:29:05 +0000283 return 1;
284 case SQLITE_AFF_TEXT:
285 return idx_affinity==SQLITE_AFF_TEXT;
286 default:
287 return sqlite3IsNumericAffinity(idx_affinity);
288 }
danielk1977e014a832004-05-17 10:48:57 +0000289}
290
danielk1977a37cdde2004-05-16 11:15:36 +0000291/*
drh35573352008-01-08 23:54:25 +0000292** Return the P5 value that should be used for a binary comparison
danielk1977a37cdde2004-05-16 11:15:36 +0000293** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
danielk1977a37cdde2004-05-16 11:15:36 +0000294*/
drh35573352008-01-08 23:54:25 +0000295static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
296 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
drh1bd10f82008-12-10 21:19:56 +0000297 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
drh35573352008-01-08 23:54:25 +0000298 return aff;
danielk1977a37cdde2004-05-16 11:15:36 +0000299}
300
drha2e00042002-01-22 03:13:42 +0000301/*
danielk19770202b292004-06-09 09:55:16 +0000302** Return a pointer to the collation sequence that should be used by
303** a binary comparison operator comparing pLeft and pRight.
304**
305** If the left hand expression has a collating sequence type, then it is
306** used. Otherwise the collation sequence for the right hand expression
307** is used, or the default (BINARY) if neither expression has a collating
308** type.
danielk1977bcbb04e2007-05-29 12:11:29 +0000309**
310** Argument pRight (but not pLeft) may be a null pointer. In this case,
311** it is not considered.
drh3d6bedf2018-09-19 14:54:38 +0000312**
313** The second form (sqlite3BinaryExprCollSeq()) uses the Expr.pLeft
314** and Expr.x.pRight pointer from the second argument instead of separate
315** pointers.
danielk19770202b292004-06-09 09:55:16 +0000316*/
drh3d6bedf2018-09-19 14:54:38 +0000317CollSeq *sqlite3ComparisonCollSeq(
danielk1977bcbb04e2007-05-29 12:11:29 +0000318 Parse *pParse,
319 Expr *pLeft,
320 Expr *pRight
321){
drhec41dda2007-02-07 13:09:45 +0000322 CollSeq *pColl;
323 assert( pLeft );
drhae80dde2012-12-06 21:16:43 +0000324 if( pLeft->flags & EP_Collate ){
325 pColl = sqlite3ExprCollSeq(pParse, pLeft);
326 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
327 pColl = sqlite3ExprCollSeq(pParse, pRight);
drhec41dda2007-02-07 13:09:45 +0000328 }else{
329 pColl = sqlite3ExprCollSeq(pParse, pLeft);
330 if( !pColl ){
331 pColl = sqlite3ExprCollSeq(pParse, pRight);
332 }
danielk19770202b292004-06-09 09:55:16 +0000333 }
334 return pColl;
335}
drh3d6bedf2018-09-19 14:54:38 +0000336CollSeq *sqlite3ComparisonExprCollSeq(Parse *pParse, Expr *pExpr){
337 if( pExpr->eX==EX_Right ){
338 return sqlite3ComparisonCollSeq(pParse, pExpr->pLeft, pExpr->x.pRight);
339 }else{
340 return sqlite3ComparisonCollSeq(pParse, pExpr->pLeft, 0);
341 }
342}
danielk19770202b292004-06-09 09:55:16 +0000343
344/*
drhbe5c89a2004-07-26 00:31:09 +0000345** Generate code for a comparison operator.
346*/
347static int codeCompare(
348 Parse *pParse, /* The parsing (and code generating) context */
349 Expr *pLeft, /* The left operand */
350 Expr *pRight, /* The right operand */
351 int opcode, /* The comparison opcode */
drh35573352008-01-08 23:54:25 +0000352 int in1, int in2, /* Register holding operands */
drhbe5c89a2004-07-26 00:31:09 +0000353 int dest, /* Jump here if true. */
354 int jumpIfNull /* If true, jump if either operand is NULL */
355){
drh35573352008-01-08 23:54:25 +0000356 int p5;
357 int addr;
358 CollSeq *p4;
359
drh3d6bedf2018-09-19 14:54:38 +0000360 p4 = sqlite3ComparisonCollSeq(pParse, pLeft, pRight);
drh35573352008-01-08 23:54:25 +0000361 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
362 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
363 (void*)p4, P4_COLLSEQ);
drh1bd10f82008-12-10 21:19:56 +0000364 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
drh35573352008-01-08 23:54:25 +0000365 return addr;
drhbe5c89a2004-07-26 00:31:09 +0000366}
367
dancfbb5e82016-07-13 19:48:13 +0000368/*
dan870a0702016-08-01 16:37:43 +0000369** Return true if expression pExpr is a vector, or false otherwise.
drhd832da72016-08-20 21:11:25 +0000370**
371** A vector is defined as any expression that results in two or more
372** columns of result. Every TK_VECTOR node is an vector because the
373** parser will not generate a TK_VECTOR with fewer than two entries.
374** But a TK_SELECT might be either a vector or a scalar. It is only
375** considered a vector if it has two or more result columns.
dan870a0702016-08-01 16:37:43 +0000376*/
377int sqlite3ExprIsVector(Expr *pExpr){
drh76dbe7a2016-08-20 21:02:38 +0000378 return sqlite3ExprVectorSize(pExpr)>1;
dan870a0702016-08-01 16:37:43 +0000379}
380
381/*
dancfbb5e82016-07-13 19:48:13 +0000382** If the expression passed as the only argument is of type TK_VECTOR
383** return the number of expressions in the vector. Or, if the expression
384** is a sub-select, return the number of columns in the sub-select. For
385** any other type of expression, return 1.
386*/
dan71c57db2016-07-09 20:23:55 +0000387int sqlite3ExprVectorSize(Expr *pExpr){
drh12abf402016-08-22 14:30:05 +0000388 u8 op = pExpr->op;
389 if( op==TK_REGISTER ) op = pExpr->op2;
390 if( op==TK_VECTOR ){
drh76dbe7a2016-08-20 21:02:38 +0000391 return pExpr->x.pList->nExpr;
drh12abf402016-08-22 14:30:05 +0000392 }else if( op==TK_SELECT ){
dan71c57db2016-07-09 20:23:55 +0000393 return pExpr->x.pSelect->pEList->nExpr;
drh76dbe7a2016-08-20 21:02:38 +0000394 }else{
395 return 1;
dan71c57db2016-07-09 20:23:55 +0000396 }
dan71c57db2016-07-09 20:23:55 +0000397}
398
danba00e302016-07-23 20:24:06 +0000399/*
drhfc7f27b2016-08-20 00:07:01 +0000400** Return a pointer to a subexpression of pVector that is the i-th
401** column of the vector (numbered starting with 0). The caller must
402** ensure that i is within range.
403**
drh76dbe7a2016-08-20 21:02:38 +0000404** If pVector is really a scalar (and "scalar" here includes subqueries
405** that return a single column!) then return pVector unmodified.
406**
drhfc7f27b2016-08-20 00:07:01 +0000407** pVector retains ownership of the returned subexpression.
408**
409** If the vector is a (SELECT ...) then the expression returned is
drh76dbe7a2016-08-20 21:02:38 +0000410** just the expression for the i-th term of the result set, and may
411** not be ready for evaluation because the table cursor has not yet
412** been positioned.
danba00e302016-07-23 20:24:06 +0000413*/
drhfc7f27b2016-08-20 00:07:01 +0000414Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
dan870a0702016-08-01 16:37:43 +0000415 assert( i<sqlite3ExprVectorSize(pVector) );
416 if( sqlite3ExprIsVector(pVector) ){
drh9f24b532016-09-05 22:50:48 +0000417 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
418 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
dan870a0702016-08-01 16:37:43 +0000419 return pVector->x.pSelect->pEList->a[i].pExpr;
420 }else{
421 return pVector->x.pList->a[i].pExpr;
422 }
dan71c57db2016-07-09 20:23:55 +0000423 }
dan870a0702016-08-01 16:37:43 +0000424 return pVector;
dan71c57db2016-07-09 20:23:55 +0000425}
drhfc7f27b2016-08-20 00:07:01 +0000426
drhfc7f27b2016-08-20 00:07:01 +0000427/*
428** Compute and return a new Expr object which when passed to
429** sqlite3ExprCode() will generate all necessary code to compute
430** the iField-th column of the vector expression pVector.
431**
drh8762ec12016-08-20 01:06:22 +0000432** It is ok for pVector to be a scalar (as long as iField==0).
433** In that case, this routine works like sqlite3ExprDup().
434**
drhfc7f27b2016-08-20 00:07:01 +0000435** The caller owns the returned Expr object and is responsible for
436** ensuring that the returned value eventually gets freed.
437**
drh8762ec12016-08-20 01:06:22 +0000438** The caller retains ownership of pVector. If pVector is a TK_SELECT,
danfad0e702016-09-06 12:04:50 +0000439** then the returned object will reference pVector and so pVector must remain
drh8762ec12016-08-20 01:06:22 +0000440** valid for the life of the returned object. If pVector is a TK_VECTOR
441** or a scalar expression, then it can be deleted as soon as this routine
drh76dbe7a2016-08-20 21:02:38 +0000442** returns.
drh8762ec12016-08-20 01:06:22 +0000443**
444** A trick to cause a TK_SELECT pVector to be deleted together with
445** the returned Expr object is to attach the pVector to the pRight field
446** of the returned TK_SELECT_COLUMN Expr object.
drhfc7f27b2016-08-20 00:07:01 +0000447*/
448Expr *sqlite3ExprForVectorField(
449 Parse *pParse, /* Parsing context */
450 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
drha1251bc2016-08-20 00:51:37 +0000451 int iField /* Which column of the vector to return */
drhfc7f27b2016-08-20 00:07:01 +0000452){
453 Expr *pRet;
drha1251bc2016-08-20 00:51:37 +0000454 if( pVector->op==TK_SELECT ){
drh3b3c86a2018-09-18 21:35:31 +0000455 assert( pVector->eX==EX_Select );
drhfc7f27b2016-08-20 00:07:01 +0000456 /* The TK_SELECT_COLUMN Expr node:
457 **
drh966e2912017-01-03 02:58:01 +0000458 ** pLeft: pVector containing TK_SELECT. Not deleted.
drh8762ec12016-08-20 01:06:22 +0000459 ** pRight: not used. But recursively deleted.
drhfc7f27b2016-08-20 00:07:01 +0000460 ** iColumn: Index of a column in pVector
drh966e2912017-01-03 02:58:01 +0000461 ** iTable: 0 or the number of columns on the LHS of an assignment
drhfc7f27b2016-08-20 00:07:01 +0000462 ** pLeft->iTable: First in an array of register holding result, or 0
463 ** if the result is not yet computed.
464 **
465 ** sqlite3ExprDelete() specifically skips the recursive delete of
466 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
drh8762ec12016-08-20 01:06:22 +0000467 ** can be attached to pRight to cause this node to take ownership of
468 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
469 ** with the same pLeft pointer to the pVector, but only one of them
470 ** will own the pVector.
drhfc7f27b2016-08-20 00:07:01 +0000471 */
drhabfd35e2016-12-06 22:47:23 +0000472 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
drh8bd0d582016-08-20 18:06:14 +0000473 if( pRet ){
474 pRet->iColumn = iField;
475 pRet->pLeft = pVector;
476 }
drhfc7f27b2016-08-20 00:07:01 +0000477 assert( pRet==0 || pRet->iTable==0 );
478 }else{
drha1251bc2016-08-20 00:51:37 +0000479 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
480 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
drhfc7f27b2016-08-20 00:07:01 +0000481 }
482 return pRet;
483}
dan71c57db2016-07-09 20:23:55 +0000484
dan5c288b92016-07-30 21:02:33 +0000485/*
486** If expression pExpr is of type TK_SELECT, generate code to evaluate
487** it. Return the register in which the result is stored (or, if the
488** sub-select returns more than one column, the first in an array
489** of registers in which the result is stored).
490**
491** If pExpr is not a TK_SELECT expression, return 0.
492*/
493static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
dan8da209b2016-07-26 18:06:08 +0000494 int reg = 0;
danf9b2e052016-08-02 17:45:00 +0000495#ifndef SQLITE_OMIT_SUBQUERY
dan5c288b92016-07-30 21:02:33 +0000496 if( pExpr->op==TK_SELECT ){
497 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
dan8da209b2016-07-26 18:06:08 +0000498 }
danf9b2e052016-08-02 17:45:00 +0000499#endif
dan8da209b2016-07-26 18:06:08 +0000500 return reg;
501}
502
dan5c288b92016-07-30 21:02:33 +0000503/*
504** Argument pVector points to a vector expression - either a TK_VECTOR
dan870a0702016-08-01 16:37:43 +0000505** or TK_SELECT that returns more than one column. This function returns
506** the register number of a register that contains the value of
507** element iField of the vector.
508**
509** If pVector is a TK_SELECT expression, then code for it must have
510** already been generated using the exprCodeSubselect() routine. In this
511** case parameter regSelect should be the first in an array of registers
512** containing the results of the sub-select.
513**
514** If pVector is of type TK_VECTOR, then code for the requested field
515** is generated. In this case (*pRegFree) may be set to the number of
516** a temporary register to be freed by the caller before returning.
dan5c288b92016-07-30 21:02:33 +0000517**
518** Before returning, output parameter (*ppExpr) is set to point to the
519** Expr object corresponding to element iElem of the vector.
dan5c288b92016-07-30 21:02:33 +0000520*/
521static int exprVectorRegister(
522 Parse *pParse, /* Parse context */
523 Expr *pVector, /* Vector to extract element from */
dan870a0702016-08-01 16:37:43 +0000524 int iField, /* Field to extract from pVector */
dan5c288b92016-07-30 21:02:33 +0000525 int regSelect, /* First in array of registers */
526 Expr **ppExpr, /* OUT: Expression element */
527 int *pRegFree /* OUT: Temp register to free */
528){
drh12abf402016-08-22 14:30:05 +0000529 u8 op = pVector->op;
drhc1bcd9c2016-09-05 19:57:46 +0000530 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
drh12abf402016-08-22 14:30:05 +0000531 if( op==TK_REGISTER ){
532 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
533 return pVector->iTable+iField;
534 }
535 if( op==TK_SELECT ){
dan870a0702016-08-01 16:37:43 +0000536 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
537 return regSelect+iField;
dan5c288b92016-07-30 21:02:33 +0000538 }
dan870a0702016-08-01 16:37:43 +0000539 *ppExpr = pVector->x.pList->a[iField].pExpr;
dan5c288b92016-07-30 21:02:33 +0000540 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
541}
542
543/*
544** Expression pExpr is a comparison between two vector values. Compute
drh79752b62016-08-13 10:02:17 +0000545** the result of the comparison (1, 0, or NULL) and write that
546** result into register dest.
547**
548** The caller must satisfy the following preconditions:
549**
550** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
551** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
552** otherwise: op==pExpr->op and p5==0
dan5c288b92016-07-30 21:02:33 +0000553*/
drh79752b62016-08-13 10:02:17 +0000554static void codeVectorCompare(
555 Parse *pParse, /* Code generator context */
556 Expr *pExpr, /* The comparison operation */
557 int dest, /* Write results into this register */
558 u8 op, /* Comparison operator */
559 u8 p5 /* SQLITE_NULLEQ or zero */
560){
dan71c57db2016-07-09 20:23:55 +0000561 Vdbe *v = pParse->pVdbe;
562 Expr *pLeft = pExpr->pLeft;
drh3d6bedf2018-09-19 14:54:38 +0000563 Expr *pRight = pExpr->x.pRight;
dan71c57db2016-07-09 20:23:55 +0000564 int nLeft = sqlite3ExprVectorSize(pLeft);
drhb29e60c2016-09-05 12:02:34 +0000565 int i;
566 int regLeft = 0;
567 int regRight = 0;
568 u8 opx = op;
569 int addrDone = sqlite3VdbeMakeLabel(v);
dan71c57db2016-07-09 20:23:55 +0000570
drh245ce622017-01-01 12:44:07 +0000571 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
572 sqlite3ErrorMsg(pParse, "row value misused");
573 return;
574 }
drhb29e60c2016-09-05 12:02:34 +0000575 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
576 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
577 || pExpr->op==TK_LT || pExpr->op==TK_GT
578 || pExpr->op==TK_LE || pExpr->op==TK_GE
579 );
580 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
581 || (pExpr->op==TK_ISNOT && op==TK_NE) );
582 assert( p5==0 || pExpr->op!=op );
583 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
dan71c57db2016-07-09 20:23:55 +0000584
drhb29e60c2016-09-05 12:02:34 +0000585 p5 |= SQLITE_STOREP2;
586 if( opx==TK_LE ) opx = TK_LT;
587 if( opx==TK_GE ) opx = TK_GT;
dan71c57db2016-07-09 20:23:55 +0000588
drhb29e60c2016-09-05 12:02:34 +0000589 regLeft = exprCodeSubselect(pParse, pLeft);
590 regRight = exprCodeSubselect(pParse, pRight);
dan71c57db2016-07-09 20:23:55 +0000591
drhb29e60c2016-09-05 12:02:34 +0000592 for(i=0; 1 /*Loop exits by "break"*/; i++){
593 int regFree1 = 0, regFree2 = 0;
594 Expr *pL, *pR;
595 int r1, r2;
596 assert( i>=0 && i<nLeft );
drhb29e60c2016-09-05 12:02:34 +0000597 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
598 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
599 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
600 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
601 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
602 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
603 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
604 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
605 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
606 sqlite3ReleaseTempReg(pParse, regFree1);
607 sqlite3ReleaseTempReg(pParse, regFree2);
drhb29e60c2016-09-05 12:02:34 +0000608 if( i==nLeft-1 ){
609 break;
dan71c57db2016-07-09 20:23:55 +0000610 }
drhb29e60c2016-09-05 12:02:34 +0000611 if( opx==TK_EQ ){
612 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
613 p5 |= SQLITE_KEEPNULL;
614 }else if( opx==TK_NE ){
615 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
616 p5 |= SQLITE_KEEPNULL;
617 }else{
618 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
619 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
620 VdbeCoverageIf(v, op==TK_LT);
621 VdbeCoverageIf(v, op==TK_GT);
622 VdbeCoverageIf(v, op==TK_LE);
623 VdbeCoverageIf(v, op==TK_GE);
624 if( i==nLeft-2 ) opx = op;
625 }
dan71c57db2016-07-09 20:23:55 +0000626 }
drhb29e60c2016-09-05 12:02:34 +0000627 sqlite3VdbeResolveLabel(v, addrDone);
dan71c57db2016-07-09 20:23:55 +0000628}
629
danielk19774b5255a2008-06-05 16:47:39 +0000630#if SQLITE_MAX_EXPR_DEPTH>0
631/*
632** Check that argument nHeight is less than or equal to the maximum
633** expression depth allowed. If it is not, leave an error message in
634** pParse.
635*/
drh7d10d5a2008-08-20 16:35:10 +0000636int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000637 int rc = SQLITE_OK;
638 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
639 if( nHeight>mxHeight ){
640 sqlite3ErrorMsg(pParse,
641 "Expression tree is too large (maximum depth %d)", mxHeight
642 );
643 rc = SQLITE_ERROR;
644 }
645 return rc;
646}
647
648/* The following three functions, heightOfExpr(), heightOfExprList()
649** and heightOfSelect(), are used to determine the maximum height
650** of any expression tree referenced by the structure passed as the
651** first argument.
652**
653** If this maximum height is greater than the current value pointed
654** to by pnHeight, the second parameter, then set *pnHeight to that
655** value.
656*/
657static void heightOfExpr(Expr *p, int *pnHeight){
658 if( p ){
659 if( p->nHeight>*pnHeight ){
660 *pnHeight = p->nHeight;
661 }
662 }
663}
664static void heightOfExprList(ExprList *p, int *pnHeight){
665 if( p ){
666 int i;
667 for(i=0; i<p->nExpr; i++){
668 heightOfExpr(p->a[i].pExpr, pnHeight);
669 }
670 }
671}
dan1a3a3082018-01-18 19:00:54 +0000672static void heightOfSelect(Select *pSelect, int *pnHeight){
673 Select *p;
674 for(p=pSelect; p; p=p->pPrior){
danielk19774b5255a2008-06-05 16:47:39 +0000675 heightOfExpr(p->pWhere, pnHeight);
676 heightOfExpr(p->pHaving, pnHeight);
677 heightOfExpr(p->pLimit, pnHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000678 heightOfExprList(p->pEList, pnHeight);
679 heightOfExprList(p->pGroupBy, pnHeight);
680 heightOfExprList(p->pOrderBy, pnHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000681 }
682}
683
684/*
685** Set the Expr.nHeight variable in the structure passed as an
686** argument. An expression with no children, Expr.pList or
687** Expr.pSelect member has a height of 1. Any other expression
688** has a height equal to the maximum height of any other
689** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000690**
691** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
692** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000693*/
694static void exprSetHeight(Expr *p){
695 int nHeight = 0;
696 heightOfExpr(p->pLeft, &nHeight);
drh3d6bedf2018-09-19 14:54:38 +0000697 switch( p->eX ){
698 case EX_Select: {
699 heightOfSelect(p->x.pSelect, &nHeight);
700 break;
701 }
702 case EX_List: {
703 heightOfExprList(p->x.pList, &nHeight);
704 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
705 break;
706 }
707 case EX_Right: {
708 heightOfExpr(p->x.pRight, &nHeight);
709 break;
710 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000711 }
danielk19774b5255a2008-06-05 16:47:39 +0000712 p->nHeight = nHeight + 1;
713}
714
715/*
716** Set the Expr.nHeight variable using the exprSetHeight() function. If
717** the height is greater than the maximum allowed expression depth,
718** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000719**
720** Also propagate all EP_Propagate flags from the Expr.x.pList into
721** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000722*/
drh2308ed32015-02-09 16:09:34 +0000723void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh3b3c86a2018-09-18 21:35:31 +0000724 if( p==0 || pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000725 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000726 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000727}
728
729/*
730** Return the maximum height of any expression tree referenced
731** by the select statement passed as an argument.
732*/
733int sqlite3SelectExprHeight(Select *p){
734 int nHeight = 0;
735 heightOfSelect(p, &nHeight);
736 return nHeight;
737}
drh2308ed32015-02-09 16:09:34 +0000738#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
739/*
740** Propagate all EP_Propagate flags from the Expr.x.pList into
741** Expr.flags.
742*/
743void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh3b3c86a2018-09-18 21:35:31 +0000744 if( p && p->eX==EX_List ){
drh2308ed32015-02-09 16:09:34 +0000745 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
746 }
747}
748#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000749#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
750
drhbe5c89a2004-07-26 00:31:09 +0000751/*
drhb7916a72009-05-27 10:31:29 +0000752** This routine is the core allocator for Expr nodes.
753**
drha76b5df2002-02-23 02:32:10 +0000754** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000755** for this node and for the pToken argument is a single allocation
756** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000757** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000758**
759** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000760** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000761** parameter is ignored if pToken is NULL or if the token does not
762** appear to be quoted. If the quotes were of the form "..." (double-quotes)
763** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000764**
765** Special case: If op==TK_INTEGER and pToken points to a string that
766** can be translated into a 32-bit integer, then the token is not
767** stored in u.zToken. Instead, the integer values is written
768** into u.iValue and the EP_IntValue flag is set. No extra storage
769** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000770*/
drhb7916a72009-05-27 10:31:29 +0000771Expr *sqlite3ExprAlloc(
drhcca8a4a2016-10-03 12:56:48 +0000772 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
drh17435752007-08-16 04:30:38 +0000773 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000774 const Token *pToken, /* Token argument. Might be NULL */
775 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000776){
drha76b5df2002-02-23 02:32:10 +0000777 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000778 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000779 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000780
drh575fad62016-02-05 13:38:36 +0000781 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000782 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000783 if( op!=TK_INTEGER || pToken->z==0
784 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
785 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000786 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000787 }
drhb7916a72009-05-27 10:31:29 +0000788 }
drh575fad62016-02-05 13:38:36 +0000789 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000790 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000791 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000792 pNew->op = (u8)op;
793 pNew->iAgg = -1;
794 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000795 if( nExtra==0 ){
drhb98a2e32017-07-07 12:43:57 +0000796 pNew->flags |= EP_IntValue|EP_Leaf;
drh33e619f2009-05-28 01:00:55 +0000797 pNew->u.iValue = iValue;
798 }else{
drh33e619f2009-05-28 01:00:55 +0000799 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000800 assert( pToken->z!=0 || pToken->n==0 );
801 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000802 pNew->u.zToken[pToken->n] = 0;
drh244b9d62016-04-11 19:01:08 +0000803 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
804 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
drh33e619f2009-05-28 01:00:55 +0000805 sqlite3Dequote(pNew->u.zToken);
drh33e619f2009-05-28 01:00:55 +0000806 }
drhb7916a72009-05-27 10:31:29 +0000807 }
808 }
809#if SQLITE_MAX_EXPR_DEPTH>0
810 pNew->nHeight = 1;
811#endif
812 }
drha76b5df2002-02-23 02:32:10 +0000813 return pNew;
814}
815
816/*
drhb7916a72009-05-27 10:31:29 +0000817** Allocate a new expression node from a zero-terminated token that has
818** already been dequoted.
819*/
820Expr *sqlite3Expr(
821 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
822 int op, /* Expression opcode */
823 const char *zToken /* Token argument. Might be NULL */
824){
825 Token x;
826 x.z = zToken;
drhb40f06c2017-08-21 02:20:57 +0000827 x.n = sqlite3Strlen30(zToken);
drhb7916a72009-05-27 10:31:29 +0000828 return sqlite3ExprAlloc(db, op, &x, 0);
829}
830
831/*
832** Attach subtrees pLeft and pRight to the Expr node pRoot.
833**
834** If pRoot==NULL that means that a memory allocation error has occurred.
835** In that case, delete the subtrees pLeft and pRight.
836*/
837void sqlite3ExprAttachSubtrees(
838 sqlite3 *db,
839 Expr *pRoot,
840 Expr *pLeft,
841 Expr *pRight
842){
843 if( pRoot==0 ){
844 assert( db->mallocFailed );
845 sqlite3ExprDelete(db, pLeft);
846 sqlite3ExprDelete(db, pRight);
847 }else{
848 if( pRight ){
drh3d6bedf2018-09-19 14:54:38 +0000849 assert( pRoot->eX==EX_None );
850 pRoot->x.pRight = pRight;
851 pRoot->eX = EX_Right;
drh885a5b02015-02-09 15:21:36 +0000852 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000853 }
854 if( pLeft ){
855 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000856 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000857 }
858 exprSetHeight(pRoot);
859 }
860}
861
862/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000863** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000864**
drhbf664462009-06-19 18:32:54 +0000865** One or both of the subtrees can be NULL. Return a pointer to the new
866** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
867** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000868*/
drh17435752007-08-16 04:30:38 +0000869Expr *sqlite3PExpr(
870 Parse *pParse, /* Parsing context */
871 int op, /* Expression opcode */
872 Expr *pLeft, /* Left operand */
drhabfd35e2016-12-06 22:47:23 +0000873 Expr *pRight /* Right operand */
drh17435752007-08-16 04:30:38 +0000874){
drh5fb52ca2012-03-31 02:34:35 +0000875 Expr *p;
drh1167d322015-10-28 20:01:45 +0000876 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000877 /* Take advantage of short-circuit false optimization for AND */
878 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
879 }else{
drhabfd35e2016-12-06 22:47:23 +0000880 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
881 if( p ){
882 memset(p, 0, sizeof(Expr));
883 p->op = op & TKFLG_MASK;
884 p->iAgg = -1;
885 }
drh5fb52ca2012-03-31 02:34:35 +0000886 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
887 }
dan2b359bd2010-10-28 11:31:23 +0000888 if( p ) {
889 sqlite3ExprCheckHeight(pParse, p->nHeight);
890 }
drh4e0cff62004-11-05 05:10:28 +0000891 return p;
892}
893
894/*
drh08de4f72016-04-11 01:06:47 +0000895** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
896** do a memory allocation failure) then delete the pSelect object.
897*/
898void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
drh3b3c86a2018-09-18 21:35:31 +0000899 if( pExpr && pSelect ){
900 assert( pExpr->eX==EX_None );
901 pExpr->eX = EX_Select;
drh08de4f72016-04-11 01:06:47 +0000902 pExpr->x.pSelect = pSelect;
drh3b3c86a2018-09-18 21:35:31 +0000903 ExprSetProperty(pExpr, EP_Subquery);
drh08de4f72016-04-11 01:06:47 +0000904 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
905 }else{
906 assert( pParse->db->mallocFailed );
907 sqlite3SelectDelete(pParse->db, pSelect);
908 }
909}
910
drh3b3c86a2018-09-18 21:35:31 +0000911/*
912** Add ExprList to the Expr.x.pList field. Or, if pExpr is NULL (due
913** do a memory allocation failure) then delete the pSelect object.
914*/
915void sqlite3PExprAddExprList(Parse *pParse, Expr *pExpr, ExprList *pList){
916 if( pExpr && pList ){
917 assert( pExpr->eX==EX_None );
918 pExpr->eX = EX_List;
919 pExpr->x.pList = pList;
920 /* sqlite3ExprSetHeightAndFlags(pParse, pExpr); // done by caller */
921 }else{
922 assert( pParse->db->mallocFailed );
923 sqlite3ExprListDelete(pParse->db, pList);
924 }
925}
926
drh08de4f72016-04-11 01:06:47 +0000927
928/*
drh991a1982014-01-02 17:57:16 +0000929** If the expression is always either TRUE or FALSE (respectively),
930** then return 1. If one cannot determine the truth value of the
931** expression at compile-time return 0.
932**
933** This is an optimization. If is OK to return 0 here even if
934** the expression really is always false or false (a false negative).
935** But it is a bug to return 1 if the expression might have different
936** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000937**
938** Note that if the expression is part of conditional for a
939** LEFT JOIN, then we cannot determine at compile-time whether or not
940** is it true or false, so always return 0.
941*/
drh991a1982014-01-02 17:57:16 +0000942static int exprAlwaysTrue(Expr *p){
943 int v = 0;
944 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
945 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
946 return v!=0;
947}
drh5fb52ca2012-03-31 02:34:35 +0000948static int exprAlwaysFalse(Expr *p){
949 int v = 0;
950 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
951 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
952 return v==0;
953}
954
955/*
drh91bb0ee2004-09-01 03:06:34 +0000956** Join two expressions using an AND operator. If either expression is
957** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000958**
959** If one side or the other of the AND is known to be false, then instead
960** of returning an AND expression, just return a constant expression with
961** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000962*/
danielk19771e536952007-08-16 10:09:01 +0000963Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000964 if( pLeft==0 ){
965 return pRight;
966 }else if( pRight==0 ){
967 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000968 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
969 sqlite3ExprDelete(db, pLeft);
970 sqlite3ExprDelete(db, pRight);
971 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000972 }else{
drhb7916a72009-05-27 10:31:29 +0000973 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
974 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
975 return pNew;
drha76b5df2002-02-23 02:32:10 +0000976 }
977}
978
979/*
980** Construct a new expression node for a function with multiple
981** arguments.
982*/
drh954733b2018-07-27 23:33:16 +0000983Expr *sqlite3ExprFunction(
984 Parse *pParse, /* Parsing context */
985 ExprList *pList, /* Argument list */
986 Token *pToken, /* Name of the function */
987 int eDistinct /* SF_Distinct or SF_ALL or 0 */
988){
drha76b5df2002-02-23 02:32:10 +0000989 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000990 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000991 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000992 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000993 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000994 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000995 return 0;
996 }
drh954733b2018-07-27 23:33:16 +0000997 if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
998 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
999 }
drh3b3c86a2018-09-18 21:35:31 +00001000 assert( pNew->eX==EX_None );
1001 if( pList ){
1002 pNew->eX = EX_List;
1003 pNew->x.pList = pList;
1004 }
drhfca23552017-10-28 20:51:54 +00001005 ExprSetProperty(pNew, EP_HasFunc);
drh2308ed32015-02-09 16:09:34 +00001006 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drh954733b2018-07-27 23:33:16 +00001007 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
drha76b5df2002-02-23 02:32:10 +00001008 return pNew;
1009}
1010
1011/*
drhfa6bc002004-09-07 16:19:52 +00001012** Assign a variable number to an expression that encodes a wildcard
1013** in the original SQL statement.
1014**
1015** Wildcards consisting of a single "?" are assigned the next sequential
1016** variable number.
1017**
1018** Wildcards of the form "?nnn" are assigned the number "nnn". We make
drh9bf755c2016-12-23 03:59:31 +00001019** sure "nnn" is not too big to avoid a denial of service attack when
drhfa6bc002004-09-07 16:19:52 +00001020** the SQL statement comes from an external source.
1021**
drh51f49f12009-05-21 20:41:32 +00001022** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +00001023** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +00001024** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +00001025** assigned.
1026*/
drhde25a882016-10-03 15:28:24 +00001027void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
drh17435752007-08-16 04:30:38 +00001028 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +00001029 const char *z;
drhf326d662016-12-23 13:30:53 +00001030 ynVar x;
drh17435752007-08-16 04:30:38 +00001031
drhfa6bc002004-09-07 16:19:52 +00001032 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +00001033 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +00001034 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +00001035 assert( z!=0 );
1036 assert( z[0]!=0 );
mistachkinb1ed7172017-04-14 14:50:34 +00001037 assert( n==(u32)sqlite3Strlen30(z) );
drhb7916a72009-05-27 10:31:29 +00001038 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +00001039 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +00001040 assert( z[0]=='?' );
drhf326d662016-12-23 13:30:53 +00001041 x = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +00001042 }else{
drhf326d662016-12-23 13:30:53 +00001043 int doAdd = 0;
drh124c0b42011-06-01 18:15:55 +00001044 if( z[0]=='?' ){
1045 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1046 ** use it as the variable number */
1047 i64 i;
drh18814df2017-01-31 03:52:34 +00001048 int bOk;
1049 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1050 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1051 bOk = 1;
1052 }else{
1053 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1054 }
drh124c0b42011-06-01 18:15:55 +00001055 testcase( i==0 );
1056 testcase( i==1 );
1057 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1058 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1059 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1060 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1061 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
drhc9b39282016-10-03 16:33:14 +00001062 return;
drhfa6bc002004-09-07 16:19:52 +00001063 }
drh8e74e7b2017-01-31 12:41:48 +00001064 x = (ynVar)i;
drhf326d662016-12-23 13:30:53 +00001065 if( x>pParse->nVar ){
1066 pParse->nVar = (int)x;
1067 doAdd = 1;
1068 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1069 doAdd = 1;
drh124c0b42011-06-01 18:15:55 +00001070 }
1071 }else{
1072 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1073 ** number as the prior appearance of the same name, or if the name
1074 ** has never appeared before, reuse the same variable number
1075 */
drh9bf755c2016-12-23 03:59:31 +00001076 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1077 if( x==0 ){
1078 x = (ynVar)(++pParse->nVar);
drhf326d662016-12-23 13:30:53 +00001079 doAdd = 1;
drh124c0b42011-06-01 18:15:55 +00001080 }
drhfa6bc002004-09-07 16:19:52 +00001081 }
drhf326d662016-12-23 13:30:53 +00001082 if( doAdd ){
1083 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1084 }
1085 }
1086 pExpr->iColumn = x;
1087 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +00001088 sqlite3ErrorMsg(pParse, "too many SQL variables");
1089 }
drhfa6bc002004-09-07 16:19:52 +00001090}
1091
1092/*
danf6963f92009-11-23 14:39:14 +00001093** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +00001094*/
drh4f0010b2016-04-11 14:49:39 +00001095static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1096 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +00001097 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1098 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drh3b3c86a2018-09-18 21:35:31 +00001099 assert( p->eX!=EX_Select || p->x.pSelect!=0 );
1100 assert( p->eX!=EX_List || p->x.pList!=0 );
drh209bc522016-09-23 21:36:24 +00001101#ifdef SQLITE_DEBUG
1102 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1103 assert( p->pLeft==0 );
drh8477f7f2018-09-19 20:14:48 +00001104 assert( p->eX==EX_None || p->eX==EX_Tab );
drh209bc522016-09-23 21:36:24 +00001105 }
drh35284b62018-07-28 01:30:43 +00001106 if( !ExprHasProperty(p, EP_TokenOnly) ){
1107 assert( p->op!=TK_FUNCTION || p->pLeft==0 );
drh35284b62018-07-28 01:30:43 +00001108 }
1109 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Reduced)) ){
1110 assert( p->pWin==0 || p->pLeft==0 );
drh35284b62018-07-28 01:30:43 +00001111 assert( p->pWin==0 || p->op==TK_FUNCTION );
drh35284b62018-07-28 01:30:43 +00001112 }
drh209bc522016-09-23 21:36:24 +00001113#endif
1114 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Leaf)) ){
drh4910a762016-09-03 01:46:15 +00001115 if( p->pLeft && p->op!=TK_SELECT_COLUMN ) sqlite3ExprDeleteNN(db, p->pLeft);
drh3d6bedf2018-09-19 14:54:38 +00001116 switch( p->eX ){
1117 case EX_Select: {
1118 sqlite3SelectDelete(db, p->x.pSelect);
1119 break;
1120 }
1121 case EX_List: {
1122 sqlite3ExprListDelete(db, p->x.pList);
1123 break;
1124 }
1125 case EX_Right: {
1126 sqlite3ExprDelete(db, p->x.pRight);
1127 break;
drh3b3c86a2018-09-18 21:35:31 +00001128 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001129 }
dan86fb6e12018-05-16 20:58:07 +00001130 if( !ExprHasProperty(p, EP_Reduced) ){
1131 sqlite3WindowDelete(db, p->pWin);
1132 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001133 }
drh209bc522016-09-23 21:36:24 +00001134 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
drh33e619f2009-05-28 01:00:55 +00001135 if( !ExprHasProperty(p, EP_Static) ){
drhdbd6a7d2017-04-05 12:39:49 +00001136 sqlite3DbFreeNN(db, p);
drh33e619f2009-05-28 01:00:55 +00001137 }
drha2e00042002-01-22 03:13:42 +00001138}
drh4f0010b2016-04-11 14:49:39 +00001139void sqlite3ExprDelete(sqlite3 *db, Expr *p){
1140 if( p ) sqlite3ExprDeleteNN(db, p);
1141}
drha2e00042002-01-22 03:13:42 +00001142
drh8477f7f2018-09-19 20:14:48 +00001143void sqlite3ExprClearXUnion(sqlite3 *db, Expr *p){
1144 switch( p->eX ){
1145 case EX_Select: {
1146 sqlite3SelectDelete(db, p->x.pSelect);
1147 break;
1148 }
1149 case EX_List: {
1150 sqlite3ExprListDelete(db, p->x.pList);
1151 break;
1152 }
1153 case EX_Right: {
1154 sqlite3ExprDelete(db, p->x.pRight);
1155 break;
1156 }
1157 }
1158 p->eX = EX_None;
1159}
1160void sqlite3ExprAddTab(sqlite3 *db, Expr *pExpr, Table *pTab){
1161 sqlite3ExprClearXUnion(db, pExpr);
1162 pExpr->eX = EX_Tab;
1163 pExpr->x.pTab = pTab;
1164}
1165
drhd2687b72005-08-12 22:56:09 +00001166/*
danielk19776ab3a2e2009-02-19 14:39:25 +00001167** Return the number of bytes allocated for the expression structure
1168** passed as the first argument. This is always one of EXPR_FULLSIZE,
1169** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1170*/
1171static int exprStructSize(Expr *p){
1172 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001173 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1174 return EXPR_FULLSIZE;
1175}
1176
1177/*
drh33e619f2009-05-28 01:00:55 +00001178** The dupedExpr*Size() routines each return the number of bytes required
1179** to store a copy of an expression or expression tree. They differ in
1180** how much of the tree is measured.
1181**
1182** dupedExprStructSize() Size of only the Expr structure
1183** dupedExprNodeSize() Size of Expr + space for token
1184** dupedExprSize() Expr + token + subtree components
1185**
1186***************************************************************************
1187**
1188** The dupedExprStructSize() function returns two values OR-ed together:
1189** (1) the space required for a copy of the Expr structure only and
1190** (2) the EP_xxx flags that indicate what the structure size should be.
1191** The return values is always one of:
1192**
1193** EXPR_FULLSIZE
1194** EXPR_REDUCEDSIZE | EP_Reduced
1195** EXPR_TOKENONLYSIZE | EP_TokenOnly
1196**
1197** The size of the structure can be found by masking the return value
1198** of this routine with 0xfff. The flags can be found by masking the
1199** return value with EP_Reduced|EP_TokenOnly.
1200**
1201** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1202** (unreduced) Expr objects as they or originally constructed by the parser.
1203** During expression analysis, extra information is computed and moved into
danc95f38d2018-06-18 20:34:43 +00001204** later parts of the Expr object and that extra information might get chopped
drh33e619f2009-05-28 01:00:55 +00001205** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +00001206** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +00001207** to reduce a pristine expression tree from the parser. The implementation
1208** of dupedExprStructSize() contain multiple assert() statements that attempt
1209** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +00001210*/
1211static int dupedExprStructSize(Expr *p, int flags){
1212 int nSize;
drh33e619f2009-05-28 01:00:55 +00001213 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +00001214 assert( EXPR_FULLSIZE<=0xfff );
1215 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
dan67a9b8e2018-06-22 20:51:35 +00001216 if( 0==flags || p->op==TK_SELECT_COLUMN
1217#ifndef SQLITE_OMIT_WINDOWFUNC
1218 || p->pWin
1219#endif
1220 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001221 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001222 }else{
drhc5cd1242013-09-12 16:50:49 +00001223 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +00001224 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +00001225 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +00001226 assert( !ExprHasProperty(p, EP_NoReduce) );
drh3d6bedf2018-09-19 14:54:38 +00001227 if( p->pLeft || p->eX!=EX_None ){
drh33e619f2009-05-28 01:00:55 +00001228 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1229 }else{
1230 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1231 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001232 }
1233 return nSize;
1234}
1235
1236/*
drh33e619f2009-05-28 01:00:55 +00001237** This function returns the space in bytes required to store the copy
1238** of the Expr structure and a copy of the Expr.u.zToken string (if that
1239** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +00001240*/
1241static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +00001242 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1243 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1244 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001245 }
danielk1977bc739712009-03-23 04:33:32 +00001246 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +00001247}
1248
1249/*
1250** Return the number of bytes required to create a duplicate of the
1251** expression passed as the first argument. The second argument is a
1252** mask containing EXPRDUP_XXX flags.
1253**
1254** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +00001255** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +00001256**
1257** If the EXPRDUP_REDUCE flag is set, then the return value includes
1258** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1259** and Expr.pRight variables (but not for any structures pointed to or
1260** descended from the Expr.x.pList or Expr.x.pSelect variables).
1261*/
1262static int dupedExprSize(Expr *p, int flags){
1263 int nByte = 0;
1264 if( p ){
1265 nByte = dupedExprNodeSize(p, flags);
1266 if( flags&EXPRDUP_REDUCE ){
drh3d6bedf2018-09-19 14:54:38 +00001267 nByte += dupedExprSize(p->pLeft, flags);
1268 if( p->eX==EX_Right ) nByte += dupedExprSize(p->x.pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001269 }
1270 }
1271 return nByte;
1272}
1273
1274/*
1275** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1276** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +00001277** to store the copy of expression p, the copies of p->u.zToken
drh3d6bedf2018-09-19 14:54:38 +00001278** (if applicable), and the copies of the p->pLeft and p->x.pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +00001279** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +00001280** portion of the buffer copied into by this function.
1281*/
drh3c194692016-04-11 16:43:43 +00001282static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1283 Expr *pNew; /* Value to return */
1284 u8 *zAlloc; /* Memory space from which to build Expr object */
1285 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1286
drh575fad62016-02-05 13:38:36 +00001287 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +00001288 assert( p );
1289 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1290 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +00001291
drh3c194692016-04-11 16:43:43 +00001292 /* Figure out where to write the new Expr structure. */
1293 if( pzBuffer ){
1294 zAlloc = *pzBuffer;
1295 staticFlag = EP_Static;
1296 }else{
1297 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1298 staticFlag = 0;
1299 }
1300 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001301
drh3c194692016-04-11 16:43:43 +00001302 if( pNew ){
1303 /* Set nNewSize to the size allocated for the structure pointed to
1304 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1305 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1306 ** by the copy of the p->u.zToken string (if any).
1307 */
1308 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1309 const int nNewSize = nStructSize & 0xfff;
1310 int nToken;
1311 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1312 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001313 }else{
drh3c194692016-04-11 16:43:43 +00001314 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001315 }
drh3c194692016-04-11 16:43:43 +00001316 if( dupFlags ){
1317 assert( ExprHasProperty(p, EP_Reduced)==0 );
1318 memcpy(zAlloc, p, nNewSize);
1319 }else{
1320 u32 nSize = (u32)exprStructSize(p);
1321 memcpy(zAlloc, p, nSize);
1322 if( nSize<EXPR_FULLSIZE ){
1323 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1324 }
1325 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001326
drh3c194692016-04-11 16:43:43 +00001327 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1328 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1329 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1330 pNew->flags |= staticFlag;
drh3b3c86a2018-09-18 21:35:31 +00001331 assert( pNew->eX==p->eX );
1332 assert( pNew->eV==p->eV );
drh3c194692016-04-11 16:43:43 +00001333
1334 /* Copy the p->u.zToken string, if any. */
1335 if( nToken ){
1336 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1337 memcpy(zToken, p->u.zToken, nToken);
1338 }
1339
drh209bc522016-09-23 21:36:24 +00001340 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
drh3c194692016-04-11 16:43:43 +00001341 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
drh3b3c86a2018-09-18 21:35:31 +00001342 switch( p->eX ){
1343 case EX_Select: {
1344 assert( pNew->eX==EX_Select );
1345 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1346 if( pNew->x.pSelect==0 ) pNew->eX = EX_None;
1347 break;
1348 }
1349 case EX_List: {
1350 assert( pNew->eX==EX_List );
1351 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1352 if( pNew->x.pList==0 ) pNew->eX = EX_None;
1353 break;
1354 }
drh33e619f2009-05-28 01:00:55 +00001355 }
drh3c194692016-04-11 16:43:43 +00001356 }
1357
drh3d6bedf2018-09-19 14:54:38 +00001358 /* Fill in pNew->pLeft and pNew->x.pRight. */
drh3c194692016-04-11 16:43:43 +00001359 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1360 zAlloc += dupedExprNodeSize(p, dupFlags);
drh209bc522016-09-23 21:36:24 +00001361 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
drh3c194692016-04-11 16:43:43 +00001362 pNew->pLeft = p->pLeft ?
1363 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
drh3d6bedf2018-09-19 14:54:38 +00001364 if( p->eX==EX_Right ){
1365 pNew->x.pRight = exprDup(db, p->x.pRight, EXPRDUP_REDUCE, &zAlloc);
1366 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001367 }
drh3c194692016-04-11 16:43:43 +00001368 if( pzBuffer ){
1369 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001370 }
drh3c194692016-04-11 16:43:43 +00001371 }else{
dan67a9b8e2018-06-22 20:51:35 +00001372#ifndef SQLITE_OMIT_WINDOWFUNC
dane2f781b2018-05-17 19:24:08 +00001373 if( ExprHasProperty(p, EP_Reduced|EP_TokenOnly) ){
1374 pNew->pWin = 0;
1375 }else{
dan2a11bb22018-06-11 20:50:25 +00001376 pNew->pWin = sqlite3WindowDup(db, pNew, p->pWin);
dane2f781b2018-05-17 19:24:08 +00001377 }
dan67a9b8e2018-06-22 20:51:35 +00001378#endif /* SQLITE_OMIT_WINDOWFUNC */
drh209bc522016-09-23 21:36:24 +00001379 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
drh98542602016-08-20 17:00:16 +00001380 if( pNew->op==TK_SELECT_COLUMN ){
1381 pNew->pLeft = p->pLeft;
drh3d6bedf2018-09-19 14:54:38 +00001382 assert( p->iColumn==0 || p->eX!=EX_Right );
1383 /* OLD: assert( p->pRight==0 || p->x.pRight==p->pLeft ); */
drh98542602016-08-20 17:00:16 +00001384 }else{
1385 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1386 }
drh3d6bedf2018-09-19 14:54:38 +00001387 if( p->eX==EX_Right ){
1388 pNew->x.pRight = sqlite3ExprDup(db, p->x.pRight, 0);
drh53872e72018-09-19 16:35:38 +00001389 if( pNew->x.pRight==0 ) pNew->eX = EX_None;
drh3d6bedf2018-09-19 14:54:38 +00001390 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001391 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001392 }
1393 }
1394 return pNew;
1395}
1396
1397/*
danbfe31e72014-01-15 14:17:31 +00001398** Create and return a deep copy of the object passed as the second
1399** argument. If an OOM condition is encountered, NULL is returned
1400** and the db->mallocFailed flag set.
1401*/
daneede6a52014-01-15 19:42:23 +00001402#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +00001403static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +00001404 With *pRet = 0;
1405 if( p ){
1406 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1407 pRet = sqlite3DbMallocZero(db, nByte);
1408 if( pRet ){
1409 int i;
1410 pRet->nCte = p->nCte;
1411 for(i=0; i<p->nCte; i++){
1412 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1413 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1414 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1415 }
1416 }
1417 }
1418 return pRet;
1419}
daneede6a52014-01-15 19:42:23 +00001420#else
1421# define withDup(x,y) 0
1422#endif
dan4e9119d2014-01-13 15:12:23 +00001423
drha76b5df2002-02-23 02:32:10 +00001424/*
drhff78bd22002-02-27 01:47:11 +00001425** The following group of routines make deep copies of expressions,
1426** expression lists, ID lists, and select statements. The copies can
1427** be deleted (by being passed to their respective ...Delete() routines)
1428** without effecting the originals.
1429**
danielk19774adee202004-05-08 08:23:19 +00001430** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1431** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +00001432** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001433**
drhad3cab52002-05-24 02:04:32 +00001434** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001435**
drhb7916a72009-05-27 10:31:29 +00001436** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001437** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1438** truncated version of the usual Expr structure that will be stored as
1439** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001440*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001441Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001442 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001443 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001444}
danielk19776ab3a2e2009-02-19 14:39:25 +00001445ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001446 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001447 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001448 int i;
drhb1637482017-01-03 00:27:16 +00001449 Expr *pPriorSelectCol = 0;
drh575fad62016-02-05 13:38:36 +00001450 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001451 if( p==0 ) return 0;
drh97258192017-09-17 19:45:28 +00001452 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
drhff78bd22002-02-27 01:47:11 +00001453 if( pNew==0 ) return 0;
drha19543f2017-09-15 15:17:48 +00001454 pNew->nExpr = p->nExpr;
drh43606172017-04-05 11:32:13 +00001455 pItem = pNew->a;
drh145716b2004-09-24 12:24:06 +00001456 pOldItem = p->a;
1457 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001458 Expr *pOldExpr = pOldItem->pExpr;
drh47073f62017-01-02 22:36:32 +00001459 Expr *pNewExpr;
drhb5526ea2009-07-16 12:41:05 +00001460 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh47073f62017-01-02 22:36:32 +00001461 if( pOldExpr
1462 && pOldExpr->op==TK_SELECT_COLUMN
1463 && (pNewExpr = pItem->pExpr)!=0
1464 ){
1465 assert( pNewExpr->iColumn==0 || i>0 );
1466 if( pNewExpr->iColumn==0 ){
drh3d6bedf2018-09-19 14:54:38 +00001467 assert( pOldExpr->pLeft==pOldExpr->x.pRight );
1468 pPriorSelectCol = pNewExpr->pLeft = pNewExpr->x.pRight;
drhb1637482017-01-03 00:27:16 +00001469 }else{
1470 assert( i>0 );
1471 assert( pItem[-1].pExpr!=0 );
1472 assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1473 assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1474 pNewExpr->pLeft = pPriorSelectCol;
drh47073f62017-01-02 22:36:32 +00001475 }
1476 }
drh17435752007-08-16 04:30:38 +00001477 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001478 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001479 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001480 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001481 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
dan24e25d32018-04-14 18:46:20 +00001482 pItem->bSorterRef = pOldItem->bSorterRef;
drhc2acc4e2013-11-15 18:15:19 +00001483 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001484 }
1485 return pNew;
1486}
danielk197793758c82005-01-21 08:13:14 +00001487
1488/*
1489** If cursors, triggers, views and subqueries are all omitted from
1490** the build, then none of the following routines, except for
1491** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1492** called with a NULL argument.
1493*/
danielk19776a67fe82005-02-04 04:07:16 +00001494#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1495 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001496SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001497 SrcList *pNew;
1498 int i;
drh113088e2003-03-20 01:16:58 +00001499 int nByte;
drh575fad62016-02-05 13:38:36 +00001500 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001501 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001502 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001503 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001504 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001505 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001506 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001507 struct SrcList_item *pNewItem = &pNew->a[i];
1508 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001509 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001510 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001511 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1512 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1513 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001514 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001515 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001516 pNewItem->addrFillSub = pOldItem->addrFillSub;
1517 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001518 if( pNewItem->fg.isIndexedBy ){
1519 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1520 }
1521 pNewItem->pIBIndex = pOldItem->pIBIndex;
1522 if( pNewItem->fg.isTabFunc ){
1523 pNewItem->u1.pFuncArg =
1524 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1525 }
drhed8a3bb2005-06-06 21:19:56 +00001526 pTab = pNewItem->pTab = pOldItem->pTab;
1527 if( pTab ){
drh79df7782016-12-14 14:07:35 +00001528 pTab->nTabRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001529 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001530 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1531 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001532 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001533 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001534 }
1535 return pNew;
1536}
drh17435752007-08-16 04:30:38 +00001537IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001538 IdList *pNew;
1539 int i;
drh575fad62016-02-05 13:38:36 +00001540 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001541 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001542 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001543 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001544 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001545 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001546 if( pNew->a==0 ){
drhdbd6a7d2017-04-05 12:39:49 +00001547 sqlite3DbFreeNN(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001548 return 0;
1549 }
drh6c535152012-02-02 03:38:30 +00001550 /* Note that because the size of the allocation for p->a[] is not
1551 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1552 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001553 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001554 struct IdList_item *pNewItem = &pNew->a[i];
1555 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001556 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001557 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001558 }
1559 return pNew;
1560}
dana7466202017-02-03 14:44:52 +00001561Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1562 Select *pRet = 0;
1563 Select *pNext = 0;
1564 Select **pp = &pRet;
1565 Select *p;
1566
drh575fad62016-02-05 13:38:36 +00001567 assert( db!=0 );
dana7466202017-02-03 14:44:52 +00001568 for(p=pDup; p; p=p->pPrior){
1569 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1570 if( pNew==0 ) break;
1571 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1572 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1573 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1574 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1575 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1576 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1577 pNew->op = p->op;
1578 pNew->pNext = pNext;
1579 pNew->pPrior = 0;
1580 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
dana7466202017-02-03 14:44:52 +00001581 pNew->iLimit = 0;
1582 pNew->iOffset = 0;
1583 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1584 pNew->addrOpenEphm[0] = -1;
1585 pNew->addrOpenEphm[1] = -1;
1586 pNew->nSelectRow = p->nSelectRow;
1587 pNew->pWith = withDup(db, p->pWith);
dan67a9b8e2018-06-22 20:51:35 +00001588#ifndef SQLITE_OMIT_WINDOWFUNC
dan2e362f92018-05-17 14:26:27 +00001589 pNew->pWin = 0;
danc95f38d2018-06-18 20:34:43 +00001590 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
dan67a9b8e2018-06-22 20:51:35 +00001591#endif
drhfef37762018-07-10 19:48:35 +00001592 pNew->selId = p->selId;
dana7466202017-02-03 14:44:52 +00001593 *pp = pNew;
1594 pp = &pNew->pPrior;
1595 pNext = pNew;
1596 }
1597
1598 return pRet;
drhff78bd22002-02-27 01:47:11 +00001599}
danielk197793758c82005-01-21 08:13:14 +00001600#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001601Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001602 assert( p==0 );
1603 return 0;
1604}
1605#endif
drhff78bd22002-02-27 01:47:11 +00001606
1607
1608/*
drha76b5df2002-02-23 02:32:10 +00001609** Add a new element to the end of an expression list. If pList is
1610** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001611**
drha19543f2017-09-15 15:17:48 +00001612** The pList argument must be either NULL or a pointer to an ExprList
1613** obtained from a prior call to sqlite3ExprListAppend(). This routine
1614** may not be used with an ExprList obtained from sqlite3ExprListDup().
1615** Reason: This routine assumes that the number of slots in pList->a[]
1616** is a power of two. That is true for sqlite3ExprListAppend() returns
1617** but is not necessarily true from the return value of sqlite3ExprListDup().
1618**
drhb7916a72009-05-27 10:31:29 +00001619** If a memory allocation error occurs, the entire list is freed and
1620** NULL is returned. If non-NULL is returned, then it is guaranteed
1621** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001622*/
drh17435752007-08-16 04:30:38 +00001623ExprList *sqlite3ExprListAppend(
1624 Parse *pParse, /* Parsing context */
1625 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001626 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001627){
drh43606172017-04-05 11:32:13 +00001628 struct ExprList_item *pItem;
drh17435752007-08-16 04:30:38 +00001629 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001630 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001631 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001632 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001633 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001634 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001635 }
drhc263f7c2016-01-18 13:18:54 +00001636 pList->nExpr = 0;
drha19543f2017-09-15 15:17:48 +00001637 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
drh43606172017-04-05 11:32:13 +00001638 ExprList *pNew;
1639 pNew = sqlite3DbRealloc(db, pList,
drha19543f2017-09-15 15:17:48 +00001640 sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
drh43606172017-04-05 11:32:13 +00001641 if( pNew==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001642 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001643 }
drh43606172017-04-05 11:32:13 +00001644 pList = pNew;
drha76b5df2002-02-23 02:32:10 +00001645 }
drh43606172017-04-05 11:32:13 +00001646 pItem = &pList->a[pList->nExpr++];
drha8b97932017-05-31 02:58:30 +00001647 assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
1648 assert( offsetof(struct ExprList_item,pExpr)==0 );
1649 memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
drh43606172017-04-05 11:32:13 +00001650 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001651 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001652
1653no_mem:
1654 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001655 sqlite3ExprDelete(db, pExpr);
1656 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001657 return 0;
drha76b5df2002-02-23 02:32:10 +00001658}
1659
1660/*
drh8762ec12016-08-20 01:06:22 +00001661** pColumns and pExpr form a vector assignment which is part of the SET
1662** clause of an UPDATE statement. Like this:
drha1251bc2016-08-20 00:51:37 +00001663**
1664** (a,b,c) = (expr1,expr2,expr3)
1665** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1666**
1667** For each term of the vector assignment, append new entries to the
drhb67343d2017-01-03 11:59:54 +00001668** expression list pList. In the case of a subquery on the RHS, append
drha1251bc2016-08-20 00:51:37 +00001669** TK_SELECT_COLUMN expressions.
1670*/
1671ExprList *sqlite3ExprListAppendVector(
1672 Parse *pParse, /* Parsing context */
1673 ExprList *pList, /* List to which to append. Might be NULL */
1674 IdList *pColumns, /* List of names of LHS of the assignment */
1675 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1676){
1677 sqlite3 *db = pParse->db;
1678 int n;
1679 int i;
drh66860af2016-08-23 18:30:10 +00001680 int iFirst = pList ? pList->nExpr : 0;
drh321e8282016-08-24 17:49:07 +00001681 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1682 ** exit prior to this routine being invoked */
1683 if( NEVER(pColumns==0) ) goto vector_append_error;
drha1251bc2016-08-20 00:51:37 +00001684 if( pExpr==0 ) goto vector_append_error;
drh966e2912017-01-03 02:58:01 +00001685
1686 /* If the RHS is a vector, then we can immediately check to see that
1687 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1688 ** wildcards ("*") in the result set of the SELECT must be expanded before
1689 ** we can do the size check, so defer the size check until code generation.
1690 */
1691 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
drha1251bc2016-08-20 00:51:37 +00001692 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1693 pColumns->nId, n);
1694 goto vector_append_error;
1695 }
drh966e2912017-01-03 02:58:01 +00001696
1697 for(i=0; i<pColumns->nId; i++){
drha1251bc2016-08-20 00:51:37 +00001698 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1699 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1700 if( pList ){
drh66860af2016-08-23 18:30:10 +00001701 assert( pList->nExpr==iFirst+i+1 );
drha1251bc2016-08-20 00:51:37 +00001702 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1703 pColumns->a[i].zName = 0;
1704 }
1705 }
drh966e2912017-01-03 02:58:01 +00001706
drhffe28052017-05-06 18:09:36 +00001707 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
drhf4dd26c2017-04-05 11:49:06 +00001708 Expr *pFirst = pList->a[iFirst].pExpr;
1709 assert( pFirst!=0 );
1710 assert( pFirst->op==TK_SELECT_COLUMN );
drh966e2912017-01-03 02:58:01 +00001711
drhf4dd26c2017-04-05 11:49:06 +00001712 /* Store the SELECT statement in pRight so it will be deleted when
1713 ** sqlite3ExprListDelete() is called */
drh3d6bedf2018-09-19 14:54:38 +00001714 assert( pFirst->eX==EX_None );
1715 pFirst->x.pRight = pExpr;
1716 pFirst->eX = EX_Right;
drhf4dd26c2017-04-05 11:49:06 +00001717 pExpr = 0;
drh966e2912017-01-03 02:58:01 +00001718
drhf4dd26c2017-04-05 11:49:06 +00001719 /* Remember the size of the LHS in iTable so that we can check that
1720 ** the RHS and LHS sizes match during code generation. */
1721 pFirst->iTable = pColumns->nId;
drha1251bc2016-08-20 00:51:37 +00001722 }
1723
1724vector_append_error:
1725 sqlite3ExprDelete(db, pExpr);
1726 sqlite3IdListDelete(db, pColumns);
1727 return pList;
1728}
1729
1730/*
drhbc622bc2015-08-24 15:39:42 +00001731** Set the sort order for the last element on the given ExprList.
1732*/
1733void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1734 if( p==0 ) return;
1735 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1736 assert( p->nExpr>0 );
1737 if( iSortOrder<0 ){
1738 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1739 return;
1740 }
1741 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001742}
1743
1744/*
drhb7916a72009-05-27 10:31:29 +00001745** Set the ExprList.a[].zName element of the most recently added item
1746** on the expression list.
1747**
1748** pList might be NULL following an OOM error. But pName should never be
1749** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1750** is set.
1751*/
1752void sqlite3ExprListSetName(
1753 Parse *pParse, /* Parsing context */
1754 ExprList *pList, /* List to which to add the span. */
1755 Token *pName, /* Name to be added */
1756 int dequote /* True to cause the name to be dequoted */
1757){
1758 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1759 if( pList ){
1760 struct ExprList_item *pItem;
1761 assert( pList->nExpr>0 );
1762 pItem = &pList->a[pList->nExpr-1];
1763 assert( pItem->zName==0 );
1764 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001765 if( dequote ) sqlite3Dequote(pItem->zName);
danc9461ec2018-08-29 21:00:16 +00001766 if( IN_RENAME_OBJECT ){
dan07e95232018-08-21 16:32:53 +00001767 sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
dan5be60c52018-08-15 20:28:39 +00001768 }
drhb7916a72009-05-27 10:31:29 +00001769 }
1770}
1771
1772/*
1773** Set the ExprList.a[].zSpan element of the most recently added item
1774** on the expression list.
1775**
1776** pList might be NULL following an OOM error. But pSpan should never be
1777** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1778** is set.
1779*/
1780void sqlite3ExprListSetSpan(
1781 Parse *pParse, /* Parsing context */
1782 ExprList *pList, /* List to which to add the span. */
drh1be266b2017-12-24 00:18:47 +00001783 const char *zStart, /* Start of the span */
1784 const char *zEnd /* End of the span */
drhb7916a72009-05-27 10:31:29 +00001785){
1786 sqlite3 *db = pParse->db;
1787 assert( pList!=0 || db->mallocFailed!=0 );
1788 if( pList ){
1789 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1790 assert( pList->nExpr>0 );
drhb7916a72009-05-27 10:31:29 +00001791 sqlite3DbFree(db, pItem->zSpan);
drh9b2e0432017-12-27 19:43:22 +00001792 pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
drhb7916a72009-05-27 10:31:29 +00001793 }
1794}
1795
1796/*
danielk19777a15a4b2007-05-08 17:54:43 +00001797** If the expression list pEList contains more than iLimit elements,
1798** leave an error message in pParse.
1799*/
1800void sqlite3ExprListCheckLength(
1801 Parse *pParse,
1802 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001803 const char *zObject
1804){
drhb1a6c3c2008-03-20 16:30:17 +00001805 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001806 testcase( pEList && pEList->nExpr==mx );
1807 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001808 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001809 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1810 }
1811}
1812
1813/*
drha76b5df2002-02-23 02:32:10 +00001814** Delete an entire expression list.
1815*/
drhaffa8552016-04-11 18:25:05 +00001816static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drhac48b752017-04-05 11:57:56 +00001817 int i = pList->nExpr;
1818 struct ExprList_item *pItem = pList->a;
1819 assert( pList->nExpr>0 );
1820 do{
drh633e6d52008-07-28 19:34:53 +00001821 sqlite3ExprDelete(db, pItem->pExpr);
1822 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001823 sqlite3DbFree(db, pItem->zSpan);
drhac48b752017-04-05 11:57:56 +00001824 pItem++;
1825 }while( --i>0 );
drhdbd6a7d2017-04-05 12:39:49 +00001826 sqlite3DbFreeNN(db, pList);
drha76b5df2002-02-23 02:32:10 +00001827}
drhaffa8552016-04-11 18:25:05 +00001828void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1829 if( pList ) exprListDeleteNN(db, pList);
1830}
drha76b5df2002-02-23 02:32:10 +00001831
1832/*
drh2308ed32015-02-09 16:09:34 +00001833** Return the bitwise-OR of all Expr.flags fields in the given
1834** ExprList.
drh885a5b02015-02-09 15:21:36 +00001835*/
drh2308ed32015-02-09 16:09:34 +00001836u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001837 int i;
drh2308ed32015-02-09 16:09:34 +00001838 u32 m = 0;
drh508e2d02017-09-30 01:25:04 +00001839 assert( pList!=0 );
1840 for(i=0; i<pList->nExpr; i++){
1841 Expr *pExpr = pList->a[i].pExpr;
1842 assert( pExpr!=0 );
1843 m |= pExpr->flags;
drh885a5b02015-02-09 15:21:36 +00001844 }
drh2308ed32015-02-09 16:09:34 +00001845 return m;
drh885a5b02015-02-09 15:21:36 +00001846}
1847
1848/*
drh7e6f9802017-09-04 00:33:04 +00001849** This is a SELECT-node callback for the expression walker that
1850** always "fails". By "fail" in this case, we mean set
1851** pWalker->eCode to zero and abort.
1852**
1853** This callback is used by multiple expression walkers.
1854*/
1855int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
1856 UNUSED_PARAMETER(NotUsed);
1857 pWalker->eCode = 0;
1858 return WRC_Abort;
1859}
1860
1861/*
drh171d16b2018-02-26 20:15:54 +00001862** If the input expression is an ID with the name "true" or "false"
drh96acafb2018-02-27 14:49:25 +00001863** then convert it into an TK_TRUEFALSE term. Return non-zero if
1864** the conversion happened, and zero if the expression is unaltered.
drh171d16b2018-02-26 20:15:54 +00001865*/
1866int sqlite3ExprIdToTrueFalse(Expr *pExpr){
1867 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
1868 if( sqlite3StrICmp(pExpr->u.zToken, "true")==0
1869 || sqlite3StrICmp(pExpr->u.zToken, "false")==0
1870 ){
1871 pExpr->op = TK_TRUEFALSE;
drh171d16b2018-02-26 20:15:54 +00001872 return 1;
1873 }
1874 return 0;
1875}
1876
drh43c4ac82018-02-26 21:26:27 +00001877/*
drh96acafb2018-02-27 14:49:25 +00001878** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
drh43c4ac82018-02-26 21:26:27 +00001879** and 0 if it is FALSE.
1880*/
drh96acafb2018-02-27 14:49:25 +00001881int sqlite3ExprTruthValue(const Expr *pExpr){
drh43c4ac82018-02-26 21:26:27 +00001882 assert( pExpr->op==TK_TRUEFALSE );
1883 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
1884 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
1885 return pExpr->u.zToken[4]==0;
1886}
1887
drh171d16b2018-02-26 20:15:54 +00001888
1889/*
drh059b2d52014-10-24 19:28:09 +00001890** These routines are Walker callbacks used to check expressions to
1891** see if they are "constant" for some definition of constant. The
1892** Walker.eCode value determines the type of "constant" we are looking
1893** for.
drh73b211a2005-01-18 04:00:42 +00001894**
drh7d10d5a2008-08-20 16:35:10 +00001895** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001896**
drh059b2d52014-10-24 19:28:09 +00001897** sqlite3ExprIsConstant() pWalker->eCode==1
1898** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001899** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001900** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001901**
drh059b2d52014-10-24 19:28:09 +00001902** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1903** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001904**
drhfeada2d2014-09-24 13:20:22 +00001905** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001906** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1907** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001908** parameter raises an error for new statements, but is silently converted
1909** to NULL for existing schemas. This allows sqlite_master tables that
1910** contain a bound parameter because they were generated by older versions
1911** of SQLite to be parsed by newer versions of SQLite without raising a
1912** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001913*/
drh7d10d5a2008-08-20 16:35:10 +00001914static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001915
drh059b2d52014-10-24 19:28:09 +00001916 /* If pWalker->eCode is 2 then any term of the expression that comes from
1917 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001918 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001919 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1920 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001921 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001922 }
1923
drh626a8792005-01-17 22:08:19 +00001924 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001925 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001926 ** and either pWalker->eCode==4 or 5 or the function has the
1927 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001928 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001929 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001930 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001931 }else{
1932 pWalker->eCode = 0;
1933 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001934 }
drh626a8792005-01-17 22:08:19 +00001935 case TK_ID:
drh171d16b2018-02-26 20:15:54 +00001936 /* Convert "true" or "false" in a DEFAULT clause into the
1937 ** appropriate TK_TRUEFALSE operator */
drhe39ef312018-02-27 00:58:13 +00001938 if( sqlite3ExprIdToTrueFalse(pExpr) ){
drh171d16b2018-02-26 20:15:54 +00001939 return WRC_Prune;
1940 }
1941 /* Fall thru */
drh626a8792005-01-17 22:08:19 +00001942 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001943 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001944 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001945 testcase( pExpr->op==TK_ID );
1946 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001947 testcase( pExpr->op==TK_AGG_FUNCTION );
1948 testcase( pExpr->op==TK_AGG_COLUMN );
drh07aded62018-07-28 16:24:08 +00001949 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
drhefad2e22018-07-27 16:57:11 +00001950 return WRC_Continue;
1951 }
drh059b2d52014-10-24 19:28:09 +00001952 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1953 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001954 }
drhf43ce0b2017-05-25 00:08:48 +00001955 /* Fall through */
1956 case TK_IF_NULL_ROW:
drh6e341b92018-04-17 18:50:40 +00001957 case TK_REGISTER:
drh99160482018-04-18 01:34:39 +00001958 testcase( pExpr->op==TK_REGISTER );
drhf43ce0b2017-05-25 00:08:48 +00001959 testcase( pExpr->op==TK_IF_NULL_ROW );
1960 pWalker->eCode = 0;
1961 return WRC_Abort;
drhfeada2d2014-09-24 13:20:22 +00001962 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001963 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001964 /* Silently convert bound parameters that appear inside of CREATE
1965 ** statements into a NULL when parsing the CREATE statement text out
1966 ** of the sqlite_master table */
1967 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001968 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001969 /* A bound parameter in a CREATE statement that originates from
1970 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001971 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001972 return WRC_Abort;
1973 }
1974 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001975 default:
drh6e341b92018-04-17 18:50:40 +00001976 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
1977 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
drh7d10d5a2008-08-20 16:35:10 +00001978 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001979 }
1980}
drh059b2d52014-10-24 19:28:09 +00001981static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001982 Walker w;
drh059b2d52014-10-24 19:28:09 +00001983 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001984 w.xExprCallback = exprNodeIsConstant;
drh7e6f9802017-09-04 00:33:04 +00001985 w.xSelectCallback = sqlite3SelectWalkFail;
drh979dd1b2017-05-29 14:26:07 +00001986#ifdef SQLITE_DEBUG
1987 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
1988#endif
drh059b2d52014-10-24 19:28:09 +00001989 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001990 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001991 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001992}
drh626a8792005-01-17 22:08:19 +00001993
1994/*
drh059b2d52014-10-24 19:28:09 +00001995** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001996** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001997**
1998** For the purposes of this function, a double-quoted string (ex: "abc")
1999** is considered a variable but a single-quoted string (ex: 'abc') is
2000** a constant.
drhfef52082000-06-06 01:50:43 +00002001*/
danielk19774adee202004-05-08 08:23:19 +00002002int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00002003 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00002004}
2005
2006/*
drh07aded62018-07-28 16:24:08 +00002007** Walk an expression tree. Return non-zero if
2008**
2009** (1) the expression is constant, and
2010** (2) the expression does originate in the ON or USING clause
2011** of a LEFT JOIN, and
2012** (3) the expression does not contain any EP_FixedCol TK_COLUMN
2013** operands created by the constant propagation optimization.
2014**
2015** When this routine returns true, it indicates that the expression
2016** can be added to the pParse->pConstExpr list and evaluated once when
2017** the prepared statement starts up. See sqlite3ExprCodeAtInit().
drh0a168372007-06-08 00:20:47 +00002018*/
2019int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00002020 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00002021}
2022
2023/*
drhfcb9f4f2015-06-01 18:13:16 +00002024** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00002025** for any single row of the table with cursor iCur. In other words, the
2026** expression must not refer to any non-deterministic function nor any
2027** table other than iCur.
2028*/
2029int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2030 return exprIsConst(p, 3, iCur);
2031}
2032
danab31a842017-04-29 20:53:09 +00002033
2034/*
2035** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2036*/
2037static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2038 ExprList *pGroupBy = pWalker->u.pGroupBy;
2039 int i;
2040
2041 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2042 ** it constant. */
2043 for(i=0; i<pGroupBy->nExpr; i++){
2044 Expr *p = pGroupBy->a[i].pExpr;
dan5aa550c2017-06-24 18:10:29 +00002045 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
drh70efa842017-09-28 01:58:23 +00002046 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
drhefad2e22018-07-27 16:57:11 +00002047 if( sqlite3IsBinary(pColl) ){
danab31a842017-04-29 20:53:09 +00002048 return WRC_Prune;
2049 }
2050 }
2051 }
2052
2053 /* Check if pExpr is a sub-select. If so, consider it variable. */
drh3b3c86a2018-09-18 21:35:31 +00002054 if( pExpr->eX==EX_Select ){
danab31a842017-04-29 20:53:09 +00002055 pWalker->eCode = 0;
2056 return WRC_Abort;
2057 }
2058
2059 return exprNodeIsConstant(pWalker, pExpr);
2060}
2061
2062/*
2063** Walk the expression tree passed as the first argument. Return non-zero
2064** if the expression consists entirely of constants or copies of terms
2065** in pGroupBy that sort with the BINARY collation sequence.
drhab314002017-05-02 16:46:41 +00002066**
2067** This routine is used to determine if a term of the HAVING clause can
2068** be promoted into the WHERE clause. In order for such a promotion to work,
2069** the value of the HAVING clause term must be the same for all members of
2070** a "group". The requirement that the GROUP BY term must be BINARY
2071** assumes that no other collating sequence will have a finer-grained
2072** grouping than binary. In other words (A=B COLLATE binary) implies
2073** A=B in every other collating sequence. The requirement that the
2074** GROUP BY be BINARY is stricter than necessary. It would also work
2075** to promote HAVING clauses that use the same alternative collating
2076** sequence as the GROUP BY term, but that is much harder to check,
2077** alternative collating sequences are uncommon, and this is only an
2078** optimization, so we take the easy way out and simply require the
2079** GROUP BY to use the BINARY collating sequence.
danab31a842017-04-29 20:53:09 +00002080*/
2081int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2082 Walker w;
danab31a842017-04-29 20:53:09 +00002083 w.eCode = 1;
2084 w.xExprCallback = exprNodeIsConstantOrGroupBy;
drh979dd1b2017-05-29 14:26:07 +00002085 w.xSelectCallback = 0;
danab31a842017-04-29 20:53:09 +00002086 w.u.pGroupBy = pGroupBy;
2087 w.pParse = pParse;
2088 sqlite3WalkExpr(&w, p);
2089 return w.eCode;
2090}
2091
drh059b2d52014-10-24 19:28:09 +00002092/*
2093** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00002094** or a function call with constant arguments. Return and 0 if there
2095** are any variables.
2096**
2097** For the purposes of this function, a double-quoted string (ex: "abc")
2098** is considered a variable but a single-quoted string (ex: 'abc') is
2099** a constant.
2100*/
drhfeada2d2014-09-24 13:20:22 +00002101int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2102 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00002103 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00002104}
2105
drh5b88bc42013-12-07 23:35:21 +00002106#ifdef SQLITE_ENABLE_CURSOR_HINTS
2107/*
2108** Walk an expression tree. Return 1 if the expression contains a
2109** subquery of some kind. Return 0 if there are no subqueries.
2110*/
2111int sqlite3ExprContainsSubquery(Expr *p){
2112 Walker w;
drhbec24762015-08-13 20:07:13 +00002113 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00002114 w.xExprCallback = sqlite3ExprWalkNoop;
drh7e6f9802017-09-04 00:33:04 +00002115 w.xSelectCallback = sqlite3SelectWalkFail;
drh979dd1b2017-05-29 14:26:07 +00002116#ifdef SQLITE_DEBUG
2117 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2118#endif
drh5b88bc42013-12-07 23:35:21 +00002119 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00002120 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00002121}
2122#endif
2123
drheb55bd22005-06-30 17:04:21 +00002124/*
drh73b211a2005-01-18 04:00:42 +00002125** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00002126** to fit in a 32-bit integer, return 1 and put the value of the integer
2127** in *pValue. If the expression is not an integer or if it is too big
2128** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00002129*/
danielk19774adee202004-05-08 08:23:19 +00002130int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00002131 int rc = 0;
drhba28b5a2017-03-12 20:28:44 +00002132 if( p==0 ) return 0; /* Can only happen following on OOM */
drhcd92e842011-02-17 15:58:20 +00002133
2134 /* If an expression is an integer literal that fits in a signed 32-bit
2135 ** integer, then the EP_IntValue flag will have already been set */
2136 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2137 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2138
drh92b01d52008-06-24 00:32:35 +00002139 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002140 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00002141 return 1;
2142 }
drhe4de1fe2002-06-02 16:09:01 +00002143 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00002144 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00002145 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00002146 break;
drh4b59ab52002-08-24 18:24:51 +00002147 }
drhe4de1fe2002-06-02 16:09:01 +00002148 case TK_UMINUS: {
2149 int v;
danielk19774adee202004-05-08 08:23:19 +00002150 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00002151 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00002152 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00002153 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00002154 }
2155 break;
2156 }
2157 default: break;
2158 }
drh92b01d52008-06-24 00:32:35 +00002159 return rc;
drhe4de1fe2002-06-02 16:09:01 +00002160}
2161
2162/*
drh039fc322009-11-17 18:31:47 +00002163** Return FALSE if there is no chance that the expression can be NULL.
2164**
2165** If the expression might be NULL or if the expression is too complex
2166** to tell return TRUE.
2167**
2168** This routine is used as an optimization, to skip OP_IsNull opcodes
2169** when we know that a value cannot be NULL. Hence, a false positive
2170** (returning TRUE when in fact the expression can never be NULL) might
2171** be a small performance hit but is otherwise harmless. On the other
2172** hand, a false negative (returning FALSE when the result could be NULL)
2173** will likely result in an incorrect answer. So when in doubt, return
2174** TRUE.
2175*/
2176int sqlite3ExprCanBeNull(const Expr *p){
2177 u8 op;
drhcd7f4572009-11-19 14:48:40 +00002178 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00002179 op = p->op;
2180 if( op==TK_REGISTER ) op = p->op2;
2181 switch( op ){
2182 case TK_INTEGER:
2183 case TK_STRING:
2184 case TK_FLOAT:
2185 case TK_BLOB:
2186 return 0;
drh7248a8b2014-08-04 18:50:54 +00002187 case TK_COLUMN:
drh8477f7f2018-09-19 20:14:48 +00002188 assert( p->eX==EX_Tab );
drh72673a22014-12-04 16:27:17 +00002189 return ExprHasProperty(p, EP_CanBeNull) ||
drh8477f7f2018-09-19 20:14:48 +00002190 p->x.pTab==0 || /* Reference to column of index on expression */
2191 (p->iColumn>=0 && p->x.pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00002192 default:
2193 return 1;
2194 }
2195}
2196
2197/*
2198** Return TRUE if the given expression is a constant which would be
2199** unchanged by OP_Affinity with the affinity given in the second
2200** argument.
2201**
2202** This routine is used to determine if the OP_Affinity operation
2203** can be omitted. When in doubt return FALSE. A false negative
2204** is harmless. A false positive, however, can result in the wrong
2205** answer.
2206*/
2207int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2208 u8 op;
drh05883a32015-06-02 15:32:08 +00002209 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00002210 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00002211 op = p->op;
2212 if( op==TK_REGISTER ) op = p->op2;
2213 switch( op ){
2214 case TK_INTEGER: {
2215 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
2216 }
2217 case TK_FLOAT: {
2218 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
2219 }
2220 case TK_STRING: {
2221 return aff==SQLITE_AFF_TEXT;
2222 }
2223 case TK_BLOB: {
2224 return 1;
2225 }
drh2f2855b2009-11-18 01:25:26 +00002226 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00002227 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2228 return p->iColumn<0
2229 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00002230 }
drh039fc322009-11-17 18:31:47 +00002231 default: {
2232 return 0;
2233 }
2234 }
2235}
2236
2237/*
drhc4a3c772001-04-04 11:48:57 +00002238** Return TRUE if the given string is a row-id column name.
2239*/
danielk19774adee202004-05-08 08:23:19 +00002240int sqlite3IsRowid(const char *z){
2241 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2242 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2243 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00002244 return 0;
2245}
2246
danielk19779a96b662007-11-29 17:05:18 +00002247/*
drh69c355b2016-03-09 15:34:51 +00002248** pX is the RHS of an IN operator. If pX is a SELECT statement
2249** that can be simplified to a direct table access, then return
2250** a pointer to the SELECT statement. If pX is not a SELECT statement,
2251** or if the SELECT statement needs to be manifested into a transient
2252** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00002253*/
2254#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00002255static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00002256 Select *p;
drhb287f4b2008-04-25 00:08:38 +00002257 SrcList *pSrc;
2258 ExprList *pEList;
2259 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00002260 int i;
drh3b3c86a2018-09-18 21:35:31 +00002261 if( pX->eX!=EX_Select ) return 0; /* Not a subquery */
2262 if( ExprHasProperty(pX, EP_VarSelect) ){
2263 return 0; /* Correlated subq */
2264 }
drh69c355b2016-03-09 15:34:51 +00002265 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00002266 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00002267 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00002268 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2269 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2270 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00002271 }
drhb74b1012009-05-28 21:04:37 +00002272 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00002273 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb287f4b2008-04-25 00:08:38 +00002274 if( p->pWhere ) return 0; /* Has no WHERE clause */
2275 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00002276 assert( pSrc!=0 );
2277 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00002278 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00002279 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00002280 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00002281 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00002282 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2283 pEList = p->pEList;
drhac6b47d2016-08-24 00:51:48 +00002284 assert( pEList!=0 );
dan7b35a772016-07-28 19:47:15 +00002285 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00002286 for(i=0; i<pEList->nExpr; i++){
2287 Expr *pRes = pEList->a[i].pExpr;
2288 if( pRes->op!=TK_COLUMN ) return 0;
2289 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00002290 }
drh69c355b2016-03-09 15:34:51 +00002291 return p;
drhb287f4b2008-04-25 00:08:38 +00002292}
2293#endif /* SQLITE_OMIT_SUBQUERY */
2294
danf9b2e052016-08-02 17:45:00 +00002295#ifndef SQLITE_OMIT_SUBQUERY
dan1d8cb212011-12-09 13:24:16 +00002296/*
drh4c259e92014-08-01 21:12:35 +00002297** Generate code that checks the left-most column of index table iCur to see if
2298** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00002299** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2300** to be set to NULL if iCur contains one or more NULL values.
2301*/
2302static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00002303 int addr1;
drh6be515e2014-08-01 21:00:53 +00002304 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00002305 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00002306 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2307 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00002308 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00002309 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00002310}
danf9b2e052016-08-02 17:45:00 +00002311#endif
drh6be515e2014-08-01 21:00:53 +00002312
drhbb53ecb2014-08-02 21:03:33 +00002313
2314#ifndef SQLITE_OMIT_SUBQUERY
2315/*
2316** The argument is an IN operator with a list (not a subquery) on the
2317** right-hand side. Return TRUE if that list is constant.
2318*/
2319static int sqlite3InRhsIsConstant(Expr *pIn){
2320 Expr *pLHS;
2321 int res;
drh3b3c86a2018-09-18 21:35:31 +00002322 assert( pIn->eX!=EX_Select );
drhbb53ecb2014-08-02 21:03:33 +00002323 pLHS = pIn->pLeft;
2324 pIn->pLeft = 0;
2325 res = sqlite3ExprIsConstant(pIn);
2326 pIn->pLeft = pLHS;
2327 return res;
2328}
2329#endif
2330
drh6be515e2014-08-01 21:00:53 +00002331/*
danielk19779a96b662007-11-29 17:05:18 +00002332** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00002333** The pX parameter is the expression on the RHS of the IN operator, which
2334** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00002335**
drhd4305ca2012-09-18 17:08:33 +00002336** The job of this routine is to find or create a b-tree object that can
2337** be used either to test for membership in the RHS set or to iterate through
2338** all members of the RHS set, skipping duplicates.
2339**
drh3a856252014-08-01 14:46:57 +00002340** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00002341** and pX->iTable is set to the index of that cursor.
2342**
drhb74b1012009-05-28 21:04:37 +00002343** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00002344**
drh1ccce442013-03-12 20:38:51 +00002345** IN_INDEX_ROWID - The cursor was opened on a database table.
2346** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2347** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2348** IN_INDEX_EPH - The cursor was opened on a specially created and
2349** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00002350** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2351** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00002352**
drhd4305ca2012-09-18 17:08:33 +00002353** An existing b-tree might be used if the RHS expression pX is a simple
2354** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00002355**
dan553168c2016-08-01 20:14:31 +00002356** SELECT <column1>, <column2>... FROM <table>
danielk19779a96b662007-11-29 17:05:18 +00002357**
drhd4305ca2012-09-18 17:08:33 +00002358** If the RHS of the IN operator is a list or a more complex subquery, then
2359** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00002360** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00002361** existing table.
drhd4305ca2012-09-18 17:08:33 +00002362**
drh7fc0ba02017-11-17 15:02:00 +00002363** The inFlags parameter must contain, at a minimum, one of the bits
2364** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2365** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2366** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2367** be used to loop over all values of the RHS of the IN operator.
drh3a856252014-08-01 14:46:57 +00002368**
2369** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2370** through the set members) then the b-tree must not contain duplicates.
drh7fc0ba02017-11-17 15:02:00 +00002371** An epheremal table will be created unless the selected columns are guaranteed
dan553168c2016-08-01 20:14:31 +00002372** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2373** a UNIQUE constraint or index.
danielk19770cdc0222008-06-26 18:04:03 +00002374**
drh3a856252014-08-01 14:46:57 +00002375** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2376** for fast set membership tests) then an epheremal table must
dan553168c2016-08-01 20:14:31 +00002377** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2378** index can be found with the specified <columns> as its left-most.
danielk19770cdc0222008-06-26 18:04:03 +00002379**
drhbb53ecb2014-08-02 21:03:33 +00002380** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2381** if the RHS of the IN operator is a list (not a subquery) then this
2382** routine might decide that creating an ephemeral b-tree for membership
2383** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2384** calling routine should implement the IN operator using a sequence
2385** of Eq or Ne comparison operations.
2386**
drhb74b1012009-05-28 21:04:37 +00002387** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00002388** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00002389** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00002390** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00002391** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00002392** to *prRhsHasNull. If there is no chance that the (...) contains a
2393** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00002394**
drhe21a6e12014-08-01 18:00:24 +00002395** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00002396** the value in that register will be NULL if the b-tree contains one or more
2397** NULL values, and it will be some non-NULL value if the b-tree contains no
2398** NULL values.
dan553168c2016-08-01 20:14:31 +00002399**
2400** If the aiMap parameter is not NULL, it must point to an array containing
2401** one element for each column returned by the SELECT statement on the RHS
2402** of the IN(...) operator. The i'th entry of the array is populated with the
2403** offset of the index column that matches the i'th column returned by the
2404** SELECT. For example, if the expression and selected index are:
2405**
2406** (?,?,?) IN (SELECT a, b, c FROM t1)
2407** CREATE INDEX i1 ON t1(b, c, a);
2408**
2409** then aiMap[] is populated with {2, 0, 1}.
danielk19779a96b662007-11-29 17:05:18 +00002410*/
danielk1977284f4ac2007-12-10 05:03:46 +00002411#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00002412int sqlite3FindInIndex(
drh6fc8f362016-08-26 19:31:29 +00002413 Parse *pParse, /* Parsing context */
2414 Expr *pX, /* The right-hand side (RHS) of the IN operator */
2415 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2416 int *prRhsHasNull, /* Register holding NULL status. See notes */
2417 int *aiMap /* Mapping from Index fields to RHS fields */
danba00e302016-07-23 20:24:06 +00002418){
drhb74b1012009-05-28 21:04:37 +00002419 Select *p; /* SELECT to the right of IN operator */
2420 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2421 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00002422 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00002423 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00002424
drh1450bc62009-10-30 13:25:56 +00002425 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00002426 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00002427
dan7b35a772016-07-28 19:47:15 +00002428 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2429 ** whether or not the SELECT result contains NULL values, check whether
dan870a0702016-08-01 16:37:43 +00002430 ** or not NULL is actually possible (it may not be, for example, due
dan7b35a772016-07-28 19:47:15 +00002431 ** to NOT NULL constraints in the schema). If no NULL values are possible,
dan870a0702016-08-01 16:37:43 +00002432 ** set prRhsHasNull to 0 before continuing. */
drh3b3c86a2018-09-18 21:35:31 +00002433 if( prRhsHasNull && pX->eX==EX_Select ){
dan7b35a772016-07-28 19:47:15 +00002434 int i;
2435 ExprList *pEList = pX->x.pSelect->pEList;
2436 for(i=0; i<pEList->nExpr; i++){
2437 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2438 }
2439 if( i==pEList->nExpr ){
2440 prRhsHasNull = 0;
2441 }
2442 }
2443
drhb74b1012009-05-28 21:04:37 +00002444 /* Check to see if an existing table or index can be used to
2445 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00002446 ** ephemeral table. */
2447 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00002448 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00002449 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00002450 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00002451 ExprList *pEList = p->pEList;
2452 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00002453
drhb07028f2011-10-14 21:49:18 +00002454 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2455 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2456 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2457 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00002458
drhb22f7c82014-02-06 23:56:27 +00002459 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00002460 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2461 sqlite3CodeVerifySchema(pParse, iDb);
2462 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00002463
drha84a2832016-08-26 21:15:35 +00002464 assert(v); /* sqlite3GetVdbe() has always been previously called */
dancfbb5e82016-07-13 19:48:13 +00002465 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh62659b22016-08-24 18:51:23 +00002466 /* The "x IN (SELECT rowid FROM table)" case */
drh511f9e82016-09-22 18:53:13 +00002467 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
drh7d176102014-02-18 03:07:12 +00002468 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002469
2470 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2471 eType = IN_INDEX_ROWID;
drhd8852092018-08-16 15:29:40 +00002472 ExplainQueryPlan((pParse, 0,
2473 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
danielk19779a96b662007-11-29 17:05:18 +00002474 sqlite3VdbeJumpHere(v, iAddr);
2475 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002476 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002477 int affinity_ok = 1;
2478 int i;
2479
2480 /* Check that the affinity that will be used to perform each
drh62659b22016-08-24 18:51:23 +00002481 ** comparison is the same as the affinity of each column in table
2482 ** on the RHS of the IN operator. If it not, it is not possible to
2483 ** use any index of the RHS table. */
dancfbb5e82016-07-13 19:48:13 +00002484 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002485 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002486 int iCol = pEList->a[i].pExpr->iColumn;
drh0dfa4f62016-08-26 13:19:49 +00002487 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
dancfbb5e82016-07-13 19:48:13 +00002488 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
drh62659b22016-08-24 18:51:23 +00002489 testcase( cmpaff==SQLITE_AFF_BLOB );
2490 testcase( cmpaff==SQLITE_AFF_TEXT );
dancfbb5e82016-07-13 19:48:13 +00002491 switch( cmpaff ){
2492 case SQLITE_AFF_BLOB:
2493 break;
2494 case SQLITE_AFF_TEXT:
drh62659b22016-08-24 18:51:23 +00002495 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2496 ** other has no affinity and the other side is TEXT. Hence,
2497 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2498 ** and for the term on the LHS of the IN to have no affinity. */
2499 assert( idxaff==SQLITE_AFF_TEXT );
dancfbb5e82016-07-13 19:48:13 +00002500 break;
2501 default:
2502 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2503 }
2504 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002505
drha84a2832016-08-26 21:15:35 +00002506 if( affinity_ok ){
2507 /* Search for an existing index that will work for this IN operator */
2508 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2509 Bitmask colUsed; /* Columns of the index used */
2510 Bitmask mCol; /* Mask for the current column */
2511 if( pIdx->nColumn<nExpr ) continue;
2512 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2513 ** BITMASK(nExpr) without overflowing */
2514 testcase( pIdx->nColumn==BMS-2 );
2515 testcase( pIdx->nColumn==BMS-1 );
2516 if( pIdx->nColumn>=BMS-1 ) continue;
2517 if( mustBeUnique ){
2518 if( pIdx->nKeyCol>nExpr
2519 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2520 ){
2521 continue; /* This index is not unique over the IN RHS columns */
dan7b35a772016-07-28 19:47:15 +00002522 }
danielk19770cdc0222008-06-26 18:04:03 +00002523 }
drha84a2832016-08-26 21:15:35 +00002524
2525 colUsed = 0; /* Columns of index used so far */
2526 for(i=0; i<nExpr; i++){
2527 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2528 Expr *pRhs = pEList->a[i].pExpr;
drh3d6bedf2018-09-19 14:54:38 +00002529 CollSeq *pReq = sqlite3ComparisonCollSeq(pParse, pLhs, pRhs);
drha84a2832016-08-26 21:15:35 +00002530 int j;
2531
2532 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2533 for(j=0; j<nExpr; j++){
2534 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2535 assert( pIdx->azColl[j] );
drh106526e2016-08-26 22:09:01 +00002536 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2537 continue;
2538 }
drha84a2832016-08-26 21:15:35 +00002539 break;
2540 }
2541 if( j==nExpr ) break;
2542 mCol = MASKBIT(j);
2543 if( mCol & colUsed ) break; /* Each column used only once */
2544 colUsed |= mCol;
2545 if( aiMap ) aiMap[i] = j;
2546 }
2547
2548 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2549 if( colUsed==(MASKBIT(nExpr)-1) ){
2550 /* If we reach this point, that means the index pIdx is usable */
drh511f9e82016-09-22 18:53:13 +00002551 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
drhe2ca99c2018-05-02 00:33:43 +00002552 ExplainQueryPlan((pParse, 0,
2553 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
drha84a2832016-08-26 21:15:35 +00002554 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2555 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2556 VdbeComment((v, "%s", pIdx->zName));
2557 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2558 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2559
2560 if( prRhsHasNull ){
drhb80dbdc2016-09-09 15:12:41 +00002561#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
drha84a2832016-08-26 21:15:35 +00002562 i64 mask = (1<<nExpr)-1;
2563 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2564 iTab, 0, 0, (u8*)&mask, P4_INT64);
drhb80dbdc2016-09-09 15:12:41 +00002565#endif
2566 *prRhsHasNull = ++pParse->nMem;
drha84a2832016-08-26 21:15:35 +00002567 if( nExpr==1 ){
2568 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2569 }
2570 }
2571 sqlite3VdbeJumpHere(v, iAddr);
2572 }
2573 } /* End loop over indexes */
2574 } /* End if( affinity_ok ) */
2575 } /* End if not an rowid index */
2576 } /* End attempt to optimize using an index */
danielk19779a96b662007-11-29 17:05:18 +00002577
drhbb53ecb2014-08-02 21:03:33 +00002578 /* If no preexisting index is available for the IN clause
2579 ** and IN_INDEX_NOOP is an allowed reply
2580 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002581 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002582 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002583 ** the IN operator so return IN_INDEX_NOOP.
2584 */
2585 if( eType==0
drh3b3c86a2018-09-18 21:35:31 +00002586 && (inFlags & IN_INDEX_NOOP_OK)!=0
2587 && pX->eX==EX_List
drhbb53ecb2014-08-02 21:03:33 +00002588 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2589 ){
2590 eType = IN_INDEX_NOOP;
2591 }
drhbb53ecb2014-08-02 21:03:33 +00002592
danielk19779a96b662007-11-29 17:05:18 +00002593 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002594 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002595 ** We will have to generate an ephemeral table to do the job.
2596 */
drh8e23daf2013-06-11 13:30:04 +00002597 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002598 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002599 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002600 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002601 pParse->nQueryLoop = 0;
drh3b3c86a2018-09-18 21:35:31 +00002602 if( pX->pLeft->iColumn<0 && pX->eX==EX_List ){
drhcf4d38a2010-07-28 02:53:36 +00002603 eType = IN_INDEX_ROWID;
2604 }
drhe21a6e12014-08-01 18:00:24 +00002605 }else if( prRhsHasNull ){
2606 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002607 }
danielk197741a05b72008-10-02 13:50:55 +00002608 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002609 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002610 }else{
2611 pX->iTable = iTab;
2612 }
danba00e302016-07-23 20:24:06 +00002613
2614 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2615 int i, n;
2616 n = sqlite3ExprVectorSize(pX->pLeft);
2617 for(i=0; i<n; i++) aiMap[i] = i;
2618 }
danielk19779a96b662007-11-29 17:05:18 +00002619 return eType;
2620}
danielk1977284f4ac2007-12-10 05:03:46 +00002621#endif
drh626a8792005-01-17 22:08:19 +00002622
danf9b2e052016-08-02 17:45:00 +00002623#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002624/*
2625** Argument pExpr is an (?, ?...) IN(...) expression. This
2626** function allocates and returns a nul-terminated string containing
2627** the affinities to be used for each column of the comparison.
2628**
2629** It is the responsibility of the caller to ensure that the returned
2630** string is eventually freed using sqlite3DbFree().
2631*/
dan71c57db2016-07-09 20:23:55 +00002632static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2633 Expr *pLeft = pExpr->pLeft;
2634 int nVal = sqlite3ExprVectorSize(pLeft);
drh3b3c86a2018-09-18 21:35:31 +00002635 Select *pSelect = (pExpr->eX==EX_Select) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002636 char *zRet;
2637
dan553168c2016-08-01 20:14:31 +00002638 assert( pExpr->op==TK_IN );
drh5c258dc2017-02-16 17:18:07 +00002639 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
dan71c57db2016-07-09 20:23:55 +00002640 if( zRet ){
2641 int i;
2642 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002643 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002644 char a = sqlite3ExprAffinity(pA);
2645 if( pSelect ){
2646 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2647 }else{
2648 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002649 }
dan71c57db2016-07-09 20:23:55 +00002650 }
2651 zRet[nVal] = '\0';
2652 }
2653 return zRet;
2654}
danf9b2e052016-08-02 17:45:00 +00002655#endif
dan71c57db2016-07-09 20:23:55 +00002656
dan8da209b2016-07-26 18:06:08 +00002657#ifndef SQLITE_OMIT_SUBQUERY
2658/*
2659** Load the Parse object passed as the first argument with an error
2660** message of the form:
2661**
2662** "sub-select returns N columns - expected M"
2663*/
2664void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2665 const char *zFmt = "sub-select returns %d columns - expected %d";
2666 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2667}
2668#endif
2669
drh626a8792005-01-17 22:08:19 +00002670/*
dan44c56042016-12-07 15:38:37 +00002671** Expression pExpr is a vector that has been used in a context where
2672** it is not permitted. If pExpr is a sub-select vector, this routine
2673** loads the Parse object with a message of the form:
2674**
2675** "sub-select returns N columns - expected 1"
2676**
2677** Or, if it is a regular scalar vector:
2678**
2679** "row value misused"
2680*/
2681void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2682#ifndef SQLITE_OMIT_SUBQUERY
drh3b3c86a2018-09-18 21:35:31 +00002683 if( pExpr->eX==EX_Select ){
dan44c56042016-12-07 15:38:37 +00002684 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2685 }else
2686#endif
2687 {
2688 sqlite3ErrorMsg(pParse, "row value misused");
2689 }
2690}
2691
2692/*
drhd4187c72010-08-30 22:15:45 +00002693** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2694** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002695**
drh9cbe6352005-11-29 03:13:21 +00002696** (SELECT a FROM b) -- subquery
2697** EXISTS (SELECT a FROM b) -- EXISTS subquery
2698** x IN (4,5,11) -- IN operator with list on right-hand side
2699** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002700**
drh9cbe6352005-11-29 03:13:21 +00002701** The pExpr parameter describes the expression that contains the IN
2702** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002703**
2704** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2705** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2706** to some integer key column of a table B-Tree. In this case, use an
2707** intkey B-Tree to store the set of IN(...) values instead of the usual
2708** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002709**
2710** If rMayHaveNull is non-zero, that means that the operation is an IN
2711** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002712** All this routine does is initialize the register given by rMayHaveNull
2713** to NULL. Calling routines will take care of changing this register
2714** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002715**
2716** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002717** result. For a multi-column SELECT, the result is stored in a contiguous
2718** array of registers and the return value is the register of the left-most
2719** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002720*/
drh51522cd2005-01-20 13:36:19 +00002721#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002722int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002723 Parse *pParse, /* Parsing context */
2724 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002725 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002726 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002727){
drh6be515e2014-08-01 21:00:53 +00002728 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002729 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002730 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002731 if( NEVER(v==0) ) return 0;
danielk1977fc976062007-05-10 10:46:56 +00002732
drh39a11812016-08-19 19:12:58 +00002733 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2734 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002735 **
2736 ** * The right-hand side is a correlated subquery
2737 ** * The right-hand side is an expression list containing variables
2738 ** * We are inside a trigger
2739 **
2740 ** If all of the above are false, then we can run this code just once
2741 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002742 */
drhc5cd1242013-09-12 16:50:49 +00002743 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh511f9e82016-09-22 18:53:13 +00002744 jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002745 }
2746
drhcce7d172000-05-31 15:34:51 +00002747 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002748 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002749 int addr; /* Address of OP_OpenEphemeral instruction */
2750 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002751 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002752 int nVal; /* Size of vector pLeft */
2753
2754 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002755 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002756
2757 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002758 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002759 ** filled with index keys representing the results from the
2760 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002761 **
2762 ** If the 'x' expression is a column value, or the SELECT...
2763 ** statement returns a column value, then the affinity of that
2764 ** column is used to build the index keys. If both 'x' and the
2765 ** SELECT... statement are columns, then numeric affinity is used
2766 ** if either column has NUMERIC or INTEGER affinity. If neither
2767 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2768 ** is used.
2769 */
2770 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002771 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2772 pExpr->iTable, (isRowid?0:nVal));
2773 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002774
drh3b3c86a2018-09-18 21:35:31 +00002775 assert( pExpr->eX==EX_Select || pExpr->eX==EX_List );
2776 if( pExpr->eX==EX_Select ){
drhfef52082000-06-06 01:50:43 +00002777 /* Case 1: expr IN (SELECT ...)
2778 **
danielk1977e014a832004-05-17 10:48:57 +00002779 ** Generate code to write the results of the select into the temporary
2780 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002781 */
drh43870062014-07-31 15:44:44 +00002782 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002783 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002784
drhe2ca99c2018-05-02 00:33:43 +00002785 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY",
2786 jmpIfDynamic>=0?"":"CORRELATED "
2787 ));
danielk197741a05b72008-10-02 13:50:55 +00002788 assert( !isRowid );
drh64bcb8c2016-08-26 03:42:57 +00002789 /* If the LHS and RHS of the IN operator do not match, that
2790 ** error will have been caught long before we reach this point. */
2791 if( ALWAYS(pEList->nExpr==nVal) ){
dan71c57db2016-07-09 20:23:55 +00002792 SelectDest dest;
2793 int i;
2794 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2795 dest.zAffSdst = exprINAffinity(pParse, pExpr);
dan71c57db2016-07-09 20:23:55 +00002796 pSelect->iLimit = 0;
2797 testcase( pSelect->selFlags & SF_Distinct );
2798 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2799 if( sqlite3Select(pParse, pSelect, &dest) ){
2800 sqlite3DbFree(pParse->db, dest.zAffSdst);
2801 sqlite3KeyInfoUnref(pKeyInfo);
2802 return 0;
2803 }
2804 sqlite3DbFree(pParse->db, dest.zAffSdst);
2805 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2806 assert( pEList!=0 );
2807 assert( pEList->nExpr>0 );
2808 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2809 for(i=0; i<nVal; i++){
dan773d3af2016-09-06 17:21:17 +00002810 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
drh3d6bedf2018-09-19 14:54:38 +00002811 pKeyInfo->aColl[i] = sqlite3ComparisonCollSeq(
dan71c57db2016-07-09 20:23:55 +00002812 pParse, p, pEList->a[i].pExpr
2813 );
2814 }
drh94ccde52007-04-13 16:06:32 +00002815 }
drha7d2db12010-07-14 20:23:52 +00002816 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002817 /* Case 2: expr IN (exprlist)
2818 **
drhfd131da2007-08-07 17:13:03 +00002819 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002820 ** store it in the temporary table. If <expr> is a column, then use
2821 ** that columns affinity when building index keys. If <expr> is not
2822 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002823 */
dan71c57db2016-07-09 20:23:55 +00002824 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002825 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002826 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002827 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002828 int r1, r2, r3;
dan71c57db2016-07-09 20:23:55 +00002829 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002830 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002831 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002832 }
drh323df792013-08-05 19:11:29 +00002833 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002834 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002835 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2836 }
danielk1977e014a832004-05-17 10:48:57 +00002837
2838 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002839 r1 = sqlite3GetTempReg(pParse);
2840 r2 = sqlite3GetTempReg(pParse);
dan21cd29a2017-10-23 16:03:54 +00002841 if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
drh57dbd7b2005-07-08 18:25:26 +00002842 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2843 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002844 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002845
drh57dbd7b2005-07-08 18:25:26 +00002846 /* If the expression is not constant then we will need to
2847 ** disable the test that was generated above that makes sure
2848 ** this code only executes once. Because for a non-constant
2849 ** expression we need to rerun this code each time.
2850 */
drh6be515e2014-08-01 21:00:53 +00002851 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2852 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2853 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002854 }
danielk1977e014a832004-05-17 10:48:57 +00002855
2856 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002857 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2858 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002859 }else{
drhe05c9292009-10-29 13:48:10 +00002860 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2861 if( isRowid ){
2862 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2863 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002864 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002865 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2866 }else{
2867 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
drh9b4eaeb2016-11-09 00:10:33 +00002868 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
drhe05c9292009-10-29 13:48:10 +00002869 }
danielk197741a05b72008-10-02 13:50:55 +00002870 }
drhfef52082000-06-06 01:50:43 +00002871 }
drh2d401ab2008-01-10 23:50:11 +00002872 sqlite3ReleaseTempReg(pParse, r1);
2873 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002874 }
drh323df792013-08-05 19:11:29 +00002875 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002876 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002877 }
danielk1977b3bce662005-01-29 08:32:43 +00002878 break;
drhfef52082000-06-06 01:50:43 +00002879 }
2880
drh51522cd2005-01-20 13:36:19 +00002881 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002882 case TK_SELECT:
2883 default: {
drh39a11812016-08-19 19:12:58 +00002884 /* Case 3: (SELECT ... FROM ...)
2885 ** or: EXISTS(SELECT ... FROM ...)
2886 **
2887 ** For a SELECT, generate code to put the values for all columns of
2888 ** the first row into an array of registers and return the index of
2889 ** the first register.
2890 **
2891 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2892 ** into a register and return that register number.
2893 **
2894 ** In both cases, the query is augmented with "LIMIT 1". Any
2895 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002896 */
drhfd773cf2009-05-29 14:39:07 +00002897 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002898 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002899 int nReg; /* Registers to allocate */
drh8c0833f2017-11-14 23:48:23 +00002900 Expr *pLimit; /* New limit expression */
drh1398ad32005-01-19 23:24:50 +00002901
shanecf697392009-06-01 16:53:09 +00002902 testcase( pExpr->op==TK_EXISTS );
2903 testcase( pExpr->op==TK_SELECT );
2904 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
drh3b3c86a2018-09-18 21:35:31 +00002905 assert( pExpr->eX==EX_Select );
dan71c57db2016-07-09 20:23:55 +00002906
danielk19776ab3a2e2009-02-19 14:39:25 +00002907 pSel = pExpr->x.pSelect;
drhe2ca99c2018-05-02 00:33:43 +00002908 ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY",
2909 jmpIfDynamic>=0?"":"CORRELATED "));
dan71c57db2016-07-09 20:23:55 +00002910 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2911 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2912 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002913 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002914 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002915 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002916 dest.nSdst = nReg;
2917 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002918 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002919 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002920 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002921 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002922 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002923 }
drh8c0833f2017-11-14 23:48:23 +00002924 pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
2925 if( pSel->pLimit ){
2926 sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
2927 pSel->pLimit->pLeft = pLimit;
2928 }else{
2929 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
2930 }
drh48b5b042010-12-06 18:50:32 +00002931 pSel->iLimit = 0;
drh7d10d5a2008-08-20 16:35:10 +00002932 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002933 return 0;
drh94ccde52007-04-13 16:06:32 +00002934 }
drh2b596da2012-07-23 21:43:19 +00002935 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002936 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002937 break;
drhcce7d172000-05-31 15:34:51 +00002938 }
2939 }
danielk1977b3bce662005-01-29 08:32:43 +00002940
drh6be515e2014-08-01 21:00:53 +00002941 if( rHasNullFlag ){
2942 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002943 }
drh6be515e2014-08-01 21:00:53 +00002944
2945 if( jmpIfDynamic>=0 ){
2946 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002947 }
danielk1977fc976062007-05-10 10:46:56 +00002948
drh1450bc62009-10-30 13:25:56 +00002949 return rReg;
drhcce7d172000-05-31 15:34:51 +00002950}
drh51522cd2005-01-20 13:36:19 +00002951#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002952
drhe3365e62009-11-12 17:52:24 +00002953#ifndef SQLITE_OMIT_SUBQUERY
2954/*
dan7b35a772016-07-28 19:47:15 +00002955** Expr pIn is an IN(...) expression. This function checks that the
2956** sub-select on the RHS of the IN() operator has the same number of
2957** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2958** a sub-query, that the LHS is a vector of size 1.
2959*/
2960int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2961 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
drh3b3c86a2018-09-18 21:35:31 +00002962 if( pIn->eX==EX_Select ){
dan7b35a772016-07-28 19:47:15 +00002963 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2964 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2965 return 1;
2966 }
2967 }else if( nVector!=1 ){
dan44c56042016-12-07 15:38:37 +00002968 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
dan7b35a772016-07-28 19:47:15 +00002969 return 1;
2970 }
2971 return 0;
2972}
2973#endif
2974
2975#ifndef SQLITE_OMIT_SUBQUERY
2976/*
drhe3365e62009-11-12 17:52:24 +00002977** Generate code for an IN expression.
2978**
2979** x IN (SELECT ...)
2980** x IN (value, value, ...)
2981**
drhecb87ac2016-08-25 15:46:25 +00002982** The left-hand side (LHS) is a scalar or vector expression. The
drhe347d3e2016-08-25 21:14:34 +00002983** right-hand side (RHS) is an array of zero or more scalar values, or a
2984** subquery. If the RHS is a subquery, the number of result columns must
2985** match the number of columns in the vector on the LHS. If the RHS is
2986** a list of values, the LHS must be a scalar.
2987**
2988** The IN operator is true if the LHS value is contained within the RHS.
2989** The result is false if the LHS is definitely not in the RHS. The
2990** result is NULL if the presence of the LHS in the RHS cannot be
2991** determined due to NULLs.
drhe3365e62009-11-12 17:52:24 +00002992**
drh6be515e2014-08-01 21:00:53 +00002993** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002994** contained within the RHS. If due to NULLs we cannot determine if the LHS
2995** is contained in the RHS then jump to destIfNull. If the LHS is contained
2996** within the RHS then fall through.
drhecb87ac2016-08-25 15:46:25 +00002997**
2998** See the separate in-operator.md documentation file in the canonical
2999** SQLite source tree for additional information.
drhe3365e62009-11-12 17:52:24 +00003000*/
3001static void sqlite3ExprCodeIN(
3002 Parse *pParse, /* Parsing and code generating context */
3003 Expr *pExpr, /* The IN expression */
3004 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
3005 int destIfNull /* Jump here if the results are unknown due to NULLs */
3006){
3007 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00003008 int eType; /* Type of the RHS */
drhe347d3e2016-08-25 21:14:34 +00003009 int rLhs; /* Register(s) holding the LHS values */
3010 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
drhe3365e62009-11-12 17:52:24 +00003011 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00003012 int *aiMap = 0; /* Map from vector field to index column */
3013 char *zAff = 0; /* Affinity string for comparisons */
drhe347d3e2016-08-25 21:14:34 +00003014 int nVector; /* Size of vectors for this IN operator */
3015 int iDummy; /* Dummy parameter to exprCodeVector() */
3016 Expr *pLeft; /* The LHS of the IN operator */
3017 int i; /* loop counter */
3018 int destStep2; /* Where to jump when NULLs seen in step 2 */
3019 int destStep6 = 0; /* Start of code for Step 6 */
3020 int addrTruthOp; /* Address of opcode that determines the IN is true */
3021 int destNotNull; /* Jump here if a comparison is not true in step 6 */
3022 int addrTop; /* Top of the step-6 loop */
drhe3365e62009-11-12 17:52:24 +00003023
drhe347d3e2016-08-25 21:14:34 +00003024 pLeft = pExpr->pLeft;
dan7b35a772016-07-28 19:47:15 +00003025 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00003026 zAff = exprINAffinity(pParse, pExpr);
danba00e302016-07-23 20:24:06 +00003027 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3028 aiMap = (int*)sqlite3DbMallocZero(
3029 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3030 );
drhe347d3e2016-08-25 21:14:34 +00003031 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
dan7b35a772016-07-28 19:47:15 +00003032
danba00e302016-07-23 20:24:06 +00003033 /* Attempt to compute the RHS. After this step, if anything other than
3034 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
3035 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3036 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00003037 v = pParse->pVdbe;
3038 assert( v!=0 ); /* OOM detected prior to this routine */
3039 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00003040 eType = sqlite3FindInIndex(pParse, pExpr,
3041 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00003042 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00003043
danba00e302016-07-23 20:24:06 +00003044 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3045 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3046 );
drhecb87ac2016-08-25 15:46:25 +00003047#ifdef SQLITE_DEBUG
3048 /* Confirm that aiMap[] contains nVector integer values between 0 and
3049 ** nVector-1. */
3050 for(i=0; i<nVector; i++){
3051 int j, cnt;
3052 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3053 assert( cnt==1 );
3054 }
3055#endif
drhe3365e62009-11-12 17:52:24 +00003056
danba00e302016-07-23 20:24:06 +00003057 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3058 ** vector, then it is stored in an array of nVector registers starting
3059 ** at r1.
drhe347d3e2016-08-25 21:14:34 +00003060 **
3061 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3062 ** so that the fields are in the same order as an existing index. The
3063 ** aiMap[] array contains a mapping from the original LHS field order to
3064 ** the field order that matches the RHS index.
drhe3365e62009-11-12 17:52:24 +00003065 */
drhe347d3e2016-08-25 21:14:34 +00003066 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3067 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
drhecb87ac2016-08-25 15:46:25 +00003068 if( i==nVector ){
drhe347d3e2016-08-25 21:14:34 +00003069 /* LHS fields are not reordered */
3070 rLhs = rLhsOrig;
drhecb87ac2016-08-25 15:46:25 +00003071 }else{
3072 /* Need to reorder the LHS fields according to aiMap */
drhe347d3e2016-08-25 21:14:34 +00003073 rLhs = sqlite3GetTempRange(pParse, nVector);
drhecb87ac2016-08-25 15:46:25 +00003074 for(i=0; i<nVector; i++){
drhe347d3e2016-08-25 21:14:34 +00003075 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
drhecb87ac2016-08-25 15:46:25 +00003076 }
danba00e302016-07-23 20:24:06 +00003077 }
drhe3365e62009-11-12 17:52:24 +00003078
drhbb53ecb2014-08-02 21:03:33 +00003079 /* If sqlite3FindInIndex() did not find or create an index that is
3080 ** suitable for evaluating the IN operator, then evaluate using a
3081 ** sequence of comparisons.
drhe347d3e2016-08-25 21:14:34 +00003082 **
3083 ** This is step (1) in the in-operator.md optimized algorithm.
drh094430e2010-07-14 18:24:06 +00003084 */
drhbb53ecb2014-08-02 21:03:33 +00003085 if( eType==IN_INDEX_NOOP ){
3086 ExprList *pList = pExpr->x.pList;
3087 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3088 int labelOk = sqlite3VdbeMakeLabel(v);
3089 int r2, regToFree;
3090 int regCkNull = 0;
3091 int ii;
drh3b3c86a2018-09-18 21:35:31 +00003092 assert( pExpr->eX==EX_List );
drhbb53ecb2014-08-02 21:03:33 +00003093 if( destIfNull!=destIfFalse ){
3094 regCkNull = sqlite3GetTempReg(pParse);
drhe347d3e2016-08-25 21:14:34 +00003095 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00003096 }
3097 for(ii=0; ii<pList->nExpr; ii++){
3098 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00003099 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00003100 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3101 }
3102 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
drhe347d3e2016-08-25 21:14:34 +00003103 sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00003104 (void*)pColl, P4_COLLSEQ);
3105 VdbeCoverageIf(v, ii<pList->nExpr-1);
3106 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00003107 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00003108 }else{
3109 assert( destIfNull==destIfFalse );
drhe347d3e2016-08-25 21:14:34 +00003110 sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
drhbb53ecb2014-08-02 21:03:33 +00003111 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00003112 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00003113 }
3114 sqlite3ReleaseTempReg(pParse, regToFree);
3115 }
3116 if( regCkNull ){
3117 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00003118 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00003119 }
3120 sqlite3VdbeResolveLabel(v, labelOk);
3121 sqlite3ReleaseTempReg(pParse, regCkNull);
drhe347d3e2016-08-25 21:14:34 +00003122 goto sqlite3ExprCodeIN_finished;
3123 }
3124
3125 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3126 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3127 ** We will then skip the binary search of the RHS.
3128 */
3129 if( destIfNull==destIfFalse ){
3130 destStep2 = destIfFalse;
drh094430e2010-07-14 18:24:06 +00003131 }else{
drhe347d3e2016-08-25 21:14:34 +00003132 destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
3133 }
3134 for(i=0; i<nVector; i++){
3135 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3136 if( sqlite3ExprCanBeNull(p) ){
3137 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
dand49fd4e2016-07-27 19:33:04 +00003138 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00003139 }
drhe3365e62009-11-12 17:52:24 +00003140 }
drhe347d3e2016-08-25 21:14:34 +00003141
3142 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3143 ** of the RHS using the LHS as a probe. If found, the result is
3144 ** true.
3145 */
3146 if( eType==IN_INDEX_ROWID ){
3147 /* In this case, the RHS is the ROWID of table b-tree and so we also
3148 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3149 ** into a single opcode. */
3150 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
3151 VdbeCoverage(v);
3152 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3153 }else{
3154 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3155 if( destIfFalse==destIfNull ){
3156 /* Combine Step 3 and Step 5 into a single opcode */
3157 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
3158 rLhs, nVector); VdbeCoverage(v);
3159 goto sqlite3ExprCodeIN_finished;
3160 }
3161 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3162 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
3163 rLhs, nVector); VdbeCoverage(v);
3164 }
3165
3166 /* Step 4. If the RHS is known to be non-NULL and we did not find
3167 ** an match on the search above, then the result must be FALSE.
3168 */
3169 if( rRhsHasNull && nVector==1 ){
3170 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3171 VdbeCoverage(v);
3172 }
3173
3174 /* Step 5. If we do not care about the difference between NULL and
3175 ** FALSE, then just return false.
3176 */
3177 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3178
3179 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3180 ** If any comparison is NULL, then the result is NULL. If all
3181 ** comparisons are FALSE then the final result is FALSE.
3182 **
3183 ** For a scalar LHS, it is sufficient to check just the first row
3184 ** of the RHS.
3185 */
3186 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3187 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
3188 VdbeCoverage(v);
3189 if( nVector>1 ){
3190 destNotNull = sqlite3VdbeMakeLabel(v);
3191 }else{
3192 /* For nVector==1, combine steps 6 and 7 by immediately returning
3193 ** FALSE if the first comparison is not NULL */
3194 destNotNull = destIfFalse;
3195 }
3196 for(i=0; i<nVector; i++){
3197 Expr *p;
3198 CollSeq *pColl;
3199 int r3 = sqlite3GetTempReg(pParse);
3200 p = sqlite3VectorFieldSubexpr(pLeft, i);
3201 pColl = sqlite3ExprCollSeq(pParse, p);
3202 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
3203 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3204 (void*)pColl, P4_COLLSEQ);
3205 VdbeCoverage(v);
3206 sqlite3ReleaseTempReg(pParse, r3);
3207 }
3208 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3209 if( nVector>1 ){
3210 sqlite3VdbeResolveLabel(v, destNotNull);
3211 sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
3212 VdbeCoverage(v);
3213
3214 /* Step 7: If we reach this point, we know that the result must
3215 ** be false. */
3216 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3217 }
3218
3219 /* Jumps here in order to return true. */
3220 sqlite3VdbeJumpHere(v, addrTruthOp);
3221
3222sqlite3ExprCodeIN_finished:
3223 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
drhecb87ac2016-08-25 15:46:25 +00003224 VdbeComment((v, "end IN expr"));
drhe347d3e2016-08-25 21:14:34 +00003225sqlite3ExprCodeIN_oom_error:
danba00e302016-07-23 20:24:06 +00003226 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00003227 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00003228}
3229#endif /* SQLITE_OMIT_SUBQUERY */
3230
drh13573c72010-01-12 17:04:07 +00003231#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003232/*
3233** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00003234** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00003235**
3236** The z[] string will probably not be zero-terminated. But the
3237** z[n] character is guaranteed to be something that does not look
3238** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00003239*/
drhb7916a72009-05-27 10:31:29 +00003240static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00003241 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00003242 double value;
drh9339da12010-09-30 00:50:49 +00003243 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00003244 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3245 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00003246 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00003247 }
3248}
drh13573c72010-01-12 17:04:07 +00003249#endif
drh598f1342007-10-23 15:39:45 +00003250
3251
3252/*
drhfec19aa2004-05-19 20:41:03 +00003253** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00003254** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00003255**
shaneh5f1d6b62010-09-30 16:51:25 +00003256** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00003257*/
drh13573c72010-01-12 17:04:07 +00003258static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3259 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00003260 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00003261 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00003262 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00003263 if( negFlag ) i = -i;
3264 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00003265 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00003266 int c;
3267 i64 value;
drhfd773cf2009-05-29 14:39:07 +00003268 const char *z = pExpr->u.zToken;
3269 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00003270 c = sqlite3DecOrHexToI64(z, &value);
drh84d4f1a2017-09-20 10:47:10 +00003271 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
drh13573c72010-01-12 17:04:07 +00003272#ifdef SQLITE_OMIT_FLOATING_POINT
3273 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3274#else
drh1b7ddc52014-07-23 14:52:05 +00003275#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00003276 if( sqlite3_strnicmp(z,"0x",2)==0 ){
drh77320ea2016-11-30 14:47:37 +00003277 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
drh1b7ddc52014-07-23 14:52:05 +00003278 }else
3279#endif
3280 {
drh9296c182014-07-23 13:40:49 +00003281 codeReal(v, z, negFlag, iMem);
3282 }
drh13573c72010-01-12 17:04:07 +00003283#endif
drh77320ea2016-11-30 14:47:37 +00003284 }else{
drh84d4f1a2017-09-20 10:47:10 +00003285 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
drh77320ea2016-11-30 14:47:37 +00003286 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00003287 }
drhfec19aa2004-05-19 20:41:03 +00003288 }
3289}
3290
drh5cd79232009-05-25 11:46:29 +00003291
drh1f9ca2c2015-08-25 16:57:52 +00003292/* Generate code that will load into register regOut a value that is
3293** appropriate for the iIdxCol-th column of index pIdx.
3294*/
3295void sqlite3ExprCodeLoadIndexColumn(
3296 Parse *pParse, /* The parsing context */
3297 Index *pIdx, /* The index whose column is to be loaded */
3298 int iTabCur, /* Cursor pointing to a table row */
3299 int iIdxCol, /* The column of the index to be loaded */
3300 int regOut /* Store the index column value in this register */
3301){
3302 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003303 if( iTabCol==XN_EXPR ){
3304 assert( pIdx->aColExpr );
3305 assert( pIdx->aColExpr->nExpr>iIdxCol );
drh3e34eab2017-07-19 19:48:40 +00003306 pParse->iSelfTab = iTabCur + 1;
drh1c75c9d2015-12-21 15:22:13 +00003307 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh3e34eab2017-07-19 19:48:40 +00003308 pParse->iSelfTab = 0;
drh4b92f982015-09-29 17:20:14 +00003309 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003310 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3311 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003312 }
drh1f9ca2c2015-08-25 16:57:52 +00003313}
3314
drh5cd79232009-05-25 11:46:29 +00003315/*
drh5c092e82010-05-14 19:24:02 +00003316** Generate code to extract the value of the iCol-th column of a table.
3317*/
3318void sqlite3ExprCodeGetColumnOfTable(
3319 Vdbe *v, /* The VDBE under construction */
3320 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003321 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003322 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003323 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003324){
drhaca19e12017-04-07 19:41:31 +00003325 if( pTab==0 ){
3326 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3327 return;
3328 }
drh5c092e82010-05-14 19:24:02 +00003329 if( iCol<0 || iCol==pTab->iPKey ){
3330 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3331 }else{
3332 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003333 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003334 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003335 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3336 }
3337 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003338 }
3339 if( iCol>=0 ){
3340 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3341 }
3342}
3343
3344/*
drh945498f2007-02-24 11:52:52 +00003345** Generate code that will extract the iColumn-th column from
drh8c607192018-08-04 15:53:55 +00003346** table pTab and store the column value in register iReg.
drhe55cbd72008-03-31 23:48:03 +00003347**
3348** There must be an open cursor to pTab in iTable when this routine
3349** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003350*/
drhe55cbd72008-03-31 23:48:03 +00003351int sqlite3ExprCodeGetColumn(
3352 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003353 Table *pTab, /* Description of the table we are reading from */
3354 int iColumn, /* Index of the table column */
3355 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003356 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003357 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003358){
drhe55cbd72008-03-31 23:48:03 +00003359 Vdbe *v = pParse->pVdbe;
drhe55cbd72008-03-31 23:48:03 +00003360 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003361 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003362 if( p5 ){
3363 sqlite3VdbeChangeP5(v, p5);
drha748fdc2012-03-28 01:34:47 +00003364 }
drhe55cbd72008-03-31 23:48:03 +00003365 return iReg;
3366}
drhe55cbd72008-03-31 23:48:03 +00003367
3368/*
drhb21e7c72008-06-22 12:37:57 +00003369** Generate code to move content from registers iFrom...iFrom+nReg-1
drh36a5d882018-08-04 17:15:56 +00003370** over to iTo..iTo+nReg-1.
drhe55cbd72008-03-31 23:48:03 +00003371*/
drhb21e7c72008-06-22 12:37:57 +00003372void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003373 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003374 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh945498f2007-02-24 11:52:52 +00003375}
3376
drh652fbf52008-04-01 01:42:41 +00003377/*
drh12abf402016-08-22 14:30:05 +00003378** Convert a scalar expression node to a TK_REGISTER referencing
3379** register iReg. The caller must ensure that iReg already contains
3380** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003381*/
3382static void exprToRegister(Expr *p, int iReg){
3383 p->op2 = p->op;
3384 p->op = TK_REGISTER;
3385 p->iTable = iReg;
3386 ExprClearProperty(p, EP_Skip);
3387}
3388
drh12abf402016-08-22 14:30:05 +00003389/*
3390** Evaluate an expression (either a vector or a scalar expression) and store
3391** the result in continguous temporary registers. Return the index of
3392** the first register used to store the result.
3393**
3394** If the returned result register is a temporary scalar, then also write
3395** that register number into *piFreeable. If the returned result register
3396** is not a temporary or if the expression is a vector set *piFreeable
3397** to 0.
3398*/
3399static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3400 int iResult;
3401 int nResult = sqlite3ExprVectorSize(p);
3402 if( nResult==1 ){
3403 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3404 }else{
3405 *piFreeable = 0;
3406 if( p->op==TK_SELECT ){
drhdd1bb432017-05-15 15:12:24 +00003407#if SQLITE_OMIT_SUBQUERY
3408 iResult = 0;
3409#else
drh12abf402016-08-22 14:30:05 +00003410 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
drhdd1bb432017-05-15 15:12:24 +00003411#endif
drh12abf402016-08-22 14:30:05 +00003412 }else{
3413 int i;
3414 iResult = pParse->nMem+1;
3415 pParse->nMem += nResult;
3416 for(i=0; i<nResult; i++){
dan4b725242016-11-23 19:31:18 +00003417 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
drh12abf402016-08-22 14:30:05 +00003418 }
3419 }
3420 }
3421 return iResult;
3422}
3423
dan71c57db2016-07-09 20:23:55 +00003424
drha4c3c872013-09-12 17:29:25 +00003425/*
drhcce7d172000-05-31 15:34:51 +00003426** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003427** expression. Attempt to store the results in register "target".
3428** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003429**
drh8b213892008-08-29 02:14:02 +00003430** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003431** be stored in target. The result might be stored in some other
3432** register if it is convenient to do so. The calling function
3433** must check the return code and move the results to the desired
3434** register.
drhcce7d172000-05-31 15:34:51 +00003435*/
drh678ccce2008-03-31 18:19:54 +00003436int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003437 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3438 int op; /* The opcode being coded */
3439 int inReg = target; /* Results stored in register inReg */
3440 int regFree1 = 0; /* If non-zero free this temporary register */
3441 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003442 int r1, r2; /* Various register numbers */
drh10d1edf2013-11-15 15:52:39 +00003443 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003444 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003445
drh9cbf3422008-01-17 16:22:13 +00003446 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003447 if( v==0 ){
3448 assert( pParse->db->mallocFailed );
3449 return 0;
3450 }
drh389a1ad2008-01-03 23:44:53 +00003451
drh1efa8022018-04-28 04:16:43 +00003452expr_code_doover:
drh389a1ad2008-01-03 23:44:53 +00003453 if( pExpr==0 ){
3454 op = TK_NULL;
3455 }else{
3456 op = pExpr->op;
3457 }
drhf2bc0132004-10-04 13:19:23 +00003458 switch( op ){
drh13449892005-09-07 21:22:45 +00003459 case TK_AGG_COLUMN: {
3460 AggInfo *pAggInfo = pExpr->pAggInfo;
3461 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3462 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003463 assert( pCol->iMem>0 );
drhc332cc32016-09-19 10:24:19 +00003464 return pCol->iMem;
drh13449892005-09-07 21:22:45 +00003465 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003466 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003467 pCol->iSorterColumn, target);
drhc332cc32016-09-19 10:24:19 +00003468 return target;
drh13449892005-09-07 21:22:45 +00003469 }
3470 /* Otherwise, fall thru into the TK_COLUMN case */
3471 }
drh967e8b72000-06-21 13:59:10 +00003472 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003473 int iTab = pExpr->iTable;
drhefad2e22018-07-27 16:57:11 +00003474 if( ExprHasProperty(pExpr, EP_FixedCol) ){
drhd98f5322018-08-09 18:36:54 +00003475 /* This COLUMN expression is really a constant due to WHERE clause
3476 ** constraints, and that constant is coded by the pExpr->pLeft
3477 ** expresssion. However, make sure the constant has the correct
3478 ** datatype by applying the Affinity of the table column to the
3479 ** constant.
3480 */
drh8477f7f2018-09-19 20:14:48 +00003481 int aff;
drhd98f5322018-08-09 18:36:54 +00003482 int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
drh8477f7f2018-09-19 20:14:48 +00003483 assert( pExpr->eX==EX_Tab );
3484 aff = sqlite3TableColumnAffinity(pExpr->x.pTab, pExpr->iColumn);
drhd98f5322018-08-09 18:36:54 +00003485 if( aff!=SQLITE_AFF_BLOB ){
3486 static const char zAff[] = "B\000C\000D\000E";
3487 assert( SQLITE_AFF_BLOB=='A' );
3488 assert( SQLITE_AFF_TEXT=='B' );
3489 if( iReg!=target ){
3490 sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
3491 iReg = target;
3492 }
3493 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
3494 &zAff[(aff-'B')*2], P4_STATIC);
3495 }
3496 return iReg;
drhefad2e22018-07-27 16:57:11 +00003497 }
drhb2b9d3d2013-08-01 01:14:43 +00003498 if( iTab<0 ){
drh6e97f8e2017-07-20 13:17:08 +00003499 if( pParse->iSelfTab<0 ){
drhb2b9d3d2013-08-01 01:14:43 +00003500 /* Generating CHECK constraints or inserting into partial index */
drh6e97f8e2017-07-20 13:17:08 +00003501 return pExpr->iColumn - pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003502 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003503 /* Coding an expression that is part of an index where column names
3504 ** in the index refer to the table to which the index belongs */
drh3e34eab2017-07-19 19:48:40 +00003505 iTab = pParse->iSelfTab - 1;
drhb2b9d3d2013-08-01 01:14:43 +00003506 }
drh22827922000-06-06 17:27:05 +00003507 }
drh8477f7f2018-09-19 20:14:48 +00003508 assert( pExpr->eX==EX_Tab );
3509 return sqlite3ExprCodeGetColumn(pParse, pExpr->x.pTab,
drhb2b9d3d2013-08-01 01:14:43 +00003510 pExpr->iColumn, iTab, target,
3511 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003512 }
3513 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003514 codeInteger(pParse, pExpr, 0, target);
drhc332cc32016-09-19 10:24:19 +00003515 return target;
drhfec19aa2004-05-19 20:41:03 +00003516 }
drh8abed7b2018-02-26 18:49:05 +00003517 case TK_TRUEFALSE: {
drh96acafb2018-02-27 14:49:25 +00003518 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
drh007c8432018-02-26 03:20:18 +00003519 return target;
3520 }
drh13573c72010-01-12 17:04:07 +00003521#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003522 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003523 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3524 codeReal(v, pExpr->u.zToken, 0, target);
drhc332cc32016-09-19 10:24:19 +00003525 return target;
drh598f1342007-10-23 15:39:45 +00003526 }
drh13573c72010-01-12 17:04:07 +00003527#endif
drhfec19aa2004-05-19 20:41:03 +00003528 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003529 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003530 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhc332cc32016-09-19 10:24:19 +00003531 return target;
drhcce7d172000-05-31 15:34:51 +00003532 }
drhf0863fe2005-06-12 21:35:51 +00003533 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003534 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhc332cc32016-09-19 10:24:19 +00003535 return target;
drhf0863fe2005-06-12 21:35:51 +00003536 }
danielk19775338a5f2005-01-20 13:03:10 +00003537#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003538 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003539 int n;
3540 const char *z;
drhca48c902008-01-18 14:08:24 +00003541 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003542 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3543 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3544 assert( pExpr->u.zToken[1]=='\'' );
3545 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003546 n = sqlite3Strlen30(z) - 1;
3547 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003548 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3549 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
drhc332cc32016-09-19 10:24:19 +00003550 return target;
danielk1977c572ef72004-05-27 09:28:41 +00003551 }
danielk19775338a5f2005-01-20 13:03:10 +00003552#endif
drh50457892003-09-06 01:10:47 +00003553 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003554 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3555 assert( pExpr->u.zToken!=0 );
3556 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003557 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3558 if( pExpr->u.zToken[1]!=0 ){
drh9bf755c2016-12-23 03:59:31 +00003559 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
drhf326d662016-12-23 13:30:53 +00003560 assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
drhce1bbe52016-12-23 13:52:45 +00003561 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
drhf326d662016-12-23 13:30:53 +00003562 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003563 }
drhc332cc32016-09-19 10:24:19 +00003564 return target;
drh50457892003-09-06 01:10:47 +00003565 }
drh4e0cff62004-11-05 05:10:28 +00003566 case TK_REGISTER: {
drhc332cc32016-09-19 10:24:19 +00003567 return pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003568 }
drh487e2622005-06-25 18:42:14 +00003569#ifndef SQLITE_OMIT_CAST
3570 case TK_CAST: {
3571 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003572 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003573 if( inReg!=target ){
3574 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3575 inReg = target;
3576 }
drh4169e432014-08-25 20:11:52 +00003577 sqlite3VdbeAddOp2(v, OP_Cast, target,
3578 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc332cc32016-09-19 10:24:19 +00003579 return inReg;
drh487e2622005-06-25 18:42:14 +00003580 }
3581#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003582 case TK_IS:
3583 case TK_ISNOT:
3584 op = (op==TK_IS) ? TK_EQ : TK_NE;
3585 p5 = SQLITE_NULLEQ;
3586 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003587 case TK_LT:
3588 case TK_LE:
3589 case TK_GT:
3590 case TK_GE:
3591 case TK_NE:
3592 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003593 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003594 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003595 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003596 }else{
3597 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00003598 assert( pExpr->eX==EX_Right );
3599 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
3600 codeCompare(pParse, pLeft, pExpr->x.pRight, op,
dan71c57db2016-07-09 20:23:55 +00003601 r1, r2, inReg, SQLITE_STOREP2 | p5);
3602 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3603 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3604 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3605 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3606 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3607 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3608 testcase( regFree1==0 );
3609 testcase( regFree2==0 );
3610 }
drh6a2fe092009-09-23 02:29:36 +00003611 break;
3612 }
drhcce7d172000-05-31 15:34:51 +00003613 case TK_AND:
3614 case TK_OR:
3615 case TK_PLUS:
3616 case TK_STAR:
3617 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003618 case TK_REM:
3619 case TK_BITAND:
3620 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003621 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003622 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003623 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003624 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003625 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3626 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3627 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3628 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3629 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3630 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3631 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3632 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3633 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3634 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3635 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003636 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00003637 assert( pExpr->eX==EX_Right );
3638 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003639 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003640 testcase( regFree1==0 );
3641 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003642 break;
3643 }
drhcce7d172000-05-31 15:34:51 +00003644 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003645 Expr *pLeft = pExpr->pLeft;
3646 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003647 if( pLeft->op==TK_INTEGER ){
3648 codeInteger(pParse, pLeft, 1, target);
drhc332cc32016-09-19 10:24:19 +00003649 return target;
drh13573c72010-01-12 17:04:07 +00003650#ifndef SQLITE_OMIT_FLOATING_POINT
3651 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003652 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3653 codeReal(v, pLeft->u.zToken, 1, target);
drhc332cc32016-09-19 10:24:19 +00003654 return target;
drh13573c72010-01-12 17:04:07 +00003655#endif
drh3c84ddf2008-01-09 02:15:38 +00003656 }else{
drh12b0fab2018-09-19 11:59:15 +00003657 memset(&tempX, 0, sizeof(tempX));
drh10d1edf2013-11-15 15:52:39 +00003658 tempX.op = TK_INTEGER;
3659 tempX.flags = EP_IntValue|EP_TokenOnly;
3660 tempX.u.iValue = 0;
3661 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003662 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003663 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003664 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003665 }
drh3c84ddf2008-01-09 02:15:38 +00003666 break;
drh6e142f52000-06-08 13:36:40 +00003667 }
drhbf4133c2001-10-13 02:59:08 +00003668 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003669 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003670 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3671 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003672 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3673 testcase( regFree1==0 );
drhe99fa2a2008-12-15 15:27:51 +00003674 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003675 break;
3676 }
drh8abed7b2018-02-26 18:49:05 +00003677 case TK_TRUTH: {
drh96acafb2018-02-27 14:49:25 +00003678 int isTrue; /* IS TRUE or IS NOT TRUE */
3679 int bNormal; /* IS TRUE or IS FALSE */
drh007c8432018-02-26 03:20:18 +00003680 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3681 testcase( regFree1==0 );
drh3d6bedf2018-09-19 14:54:38 +00003682 assert( pExpr->eX==EX_Right );
3683 isTrue = sqlite3ExprTruthValue(pExpr->x.pRight);
drh96acafb2018-02-27 14:49:25 +00003684 bNormal = pExpr->op2==TK_IS;
3685 testcase( isTrue && bNormal);
3686 testcase( !isTrue && bNormal);
3687 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
drh007c8432018-02-26 03:20:18 +00003688 break;
3689 }
drhcce7d172000-05-31 15:34:51 +00003690 case TK_ISNULL:
3691 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003692 int addr;
drh7d176102014-02-18 03:07:12 +00003693 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3694 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003695 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003696 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003697 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003698 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003699 VdbeCoverageIf(v, op==TK_ISNULL);
3700 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003701 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003702 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003703 break;
drhcce7d172000-05-31 15:34:51 +00003704 }
drh22827922000-06-06 17:27:05 +00003705 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003706 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003707 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003708 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3709 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003710 }else{
drhc332cc32016-09-19 10:24:19 +00003711 return pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003712 }
drh22827922000-06-06 17:27:05 +00003713 break;
3714 }
drhcce7d172000-05-31 15:34:51 +00003715 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003716 ExprList *pFarg; /* List of function arguments */
3717 int nFarg; /* Number of function arguments */
3718 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003719 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003720 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003721 int i; /* Loop counter */
drhc332cc32016-09-19 10:24:19 +00003722 sqlite3 *db = pParse->db; /* The database connection */
drh12ffee82009-04-08 13:51:51 +00003723 u8 enc = ENC(db); /* The text encoding used by this database */
3724 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003725
dan67a9b8e2018-06-22 20:51:35 +00003726#ifndef SQLITE_OMIT_WINDOWFUNC
dan86fb6e12018-05-16 20:58:07 +00003727 if( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) && pExpr->pWin ){
3728 return pExpr->pWin->regResult;
3729 }
dan67a9b8e2018-06-22 20:51:35 +00003730#endif
dan86fb6e12018-05-16 20:58:07 +00003731
drh1e9b53f2017-01-04 01:07:24 +00003732 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
drh49c5ab22017-01-04 04:18:00 +00003733 /* SQL functions can be expensive. So try to move constant functions
drhad879ff2017-01-04 04:10:02 +00003734 ** out of the inner loop, even if that means an extra OP_Copy. */
3735 return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
drh1e9b53f2017-01-04 01:07:24 +00003736 }
drh3b3c86a2018-09-18 21:35:31 +00003737 assert( pExpr->eX==EX_List || pExpr->eX==EX_None );
drhc5cd1242013-09-12 16:50:49 +00003738 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003739 pFarg = 0;
3740 }else{
3741 pFarg = pExpr->x.pList;
3742 }
3743 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003744 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3745 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003746 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003747#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3748 if( pDef==0 && pParse->explain ){
3749 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3750 }
3751#endif
danb6e9f7a2018-05-19 14:15:29 +00003752 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003753 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003754 break;
3755 }
drhae6bb952009-11-11 00:24:31 +00003756
3757 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003758 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003759 ** arguments past the first non-NULL argument.
3760 */
drhd36e1042013-09-06 13:10:12 +00003761 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003762 int endCoalesce = sqlite3VdbeMakeLabel(v);
3763 assert( nFarg>=2 );
3764 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3765 for(i=1; i<nFarg; i++){
3766 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003767 VdbeCoverage(v);
drhae6bb952009-11-11 00:24:31 +00003768 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhae6bb952009-11-11 00:24:31 +00003769 }
3770 sqlite3VdbeResolveLabel(v, endCoalesce);
3771 break;
3772 }
3773
drhcca9f3d2013-09-06 15:23:29 +00003774 /* The UNLIKELY() function is a no-op. The result is the value
3775 ** of the first argument.
3776 */
3777 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3778 assert( nFarg>=1 );
drhc332cc32016-09-19 10:24:19 +00003779 return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003780 }
drhae6bb952009-11-11 00:24:31 +00003781
drh54240752017-01-03 14:39:30 +00003782#ifdef SQLITE_DEBUG
drha1a523a2016-12-26 00:18:36 +00003783 /* The AFFINITY() function evaluates to a string that describes
3784 ** the type affinity of the argument. This is used for testing of
3785 ** the SQLite type logic.
3786 */
3787 if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
3788 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3789 char aff;
3790 assert( nFarg==1 );
3791 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3792 sqlite3VdbeLoadString(v, target,
3793 aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
3794 return target;
3795 }
drh54240752017-01-03 14:39:30 +00003796#endif
drha1a523a2016-12-26 00:18:36 +00003797
drhd1a01ed2013-11-21 16:08:52 +00003798 for(i=0; i<nFarg; i++){
3799 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003800 testcase( i==31 );
3801 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003802 }
3803 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3804 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3805 }
3806 }
drh12ffee82009-04-08 13:51:51 +00003807 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003808 if( constMask ){
3809 r1 = pParse->nMem+1;
3810 pParse->nMem += nFarg;
3811 }else{
3812 r1 = sqlite3GetTempRange(pParse, nFarg);
3813 }
drha748fdc2012-03-28 01:34:47 +00003814
3815 /* For length() and typeof() functions with a column argument,
3816 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3817 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3818 ** loading.
3819 */
drhd36e1042013-09-06 13:10:12 +00003820 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003821 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003822 assert( nFarg==1 );
3823 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003824 exprOp = pFarg->a[0].pExpr->op;
3825 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003826 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3827 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003828 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3829 pFarg->a[0].pExpr->op2 =
3830 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003831 }
3832 }
3833
drh5579d592015-08-26 14:01:41 +00003834 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003835 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drh892d3172008-01-10 03:46:36 +00003836 }else{
drh12ffee82009-04-08 13:51:51 +00003837 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003838 }
drhb7f6f682006-07-08 17:06:43 +00003839#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003840 /* Possibly overload the function if the first argument is
3841 ** a virtual table column.
3842 **
3843 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3844 ** second argument, not the first, as the argument to test to
3845 ** see if it is a column in a virtual table. This is done because
3846 ** the left operand of infix functions (the operand we want to
3847 ** control overloading) ends up as the second argument to the
3848 ** function. The expression "A glob B" is equivalent to
3849 ** "glob(B,A). We want to use the A in "A glob B" to test
3850 ** for function overloading. But we use the B term in "glob(B,A)".
3851 */
drh59155062018-05-26 18:03:48 +00003852 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
drh12ffee82009-04-08 13:51:51 +00003853 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3854 }else if( nFarg>0 ){
3855 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003856 }
3857#endif
drhd36e1042013-09-06 13:10:12 +00003858 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003859 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003860 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003861 }
drh092457b2017-12-29 15:04:49 +00003862#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
3863 if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
drh2fc865c2017-12-16 20:20:37 +00003864 Expr *pArg = pFarg->a[0].pExpr;
3865 if( pArg->op==TK_COLUMN ){
drh092457b2017-12-29 15:04:49 +00003866 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
drh2fc865c2017-12-16 20:20:37 +00003867 }else{
3868 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3869 }
drh092457b2017-12-29 15:04:49 +00003870 }else
3871#endif
3872 {
drh2fc865c2017-12-16 20:20:37 +00003873 sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
3874 constMask, r1, target, (char*)pDef, P4_FUNCDEF);
3875 sqlite3VdbeChangeP5(v, (u8)nFarg);
3876 }
drhd1a01ed2013-11-21 16:08:52 +00003877 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003878 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003879 }
drhc332cc32016-09-19 10:24:19 +00003880 return target;
drhcce7d172000-05-31 15:34:51 +00003881 }
drhfe2093d2005-01-20 22:48:47 +00003882#ifndef SQLITE_OMIT_SUBQUERY
3883 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003884 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003885 int nCol;
drhc5499be2008-04-01 15:06:33 +00003886 testcase( op==TK_EXISTS );
3887 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003888 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3889 sqlite3SubselectError(pParse, nCol, 1);
3890 }else{
drhc332cc32016-09-19 10:24:19 +00003891 return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
dan8da209b2016-07-26 18:06:08 +00003892 }
drh19a775c2000-06-05 18:54:46 +00003893 break;
3894 }
drhfc7f27b2016-08-20 00:07:01 +00003895 case TK_SELECT_COLUMN: {
drh966e2912017-01-03 02:58:01 +00003896 int n;
drhfc7f27b2016-08-20 00:07:01 +00003897 if( pExpr->pLeft->iTable==0 ){
3898 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3899 }
drh966e2912017-01-03 02:58:01 +00003900 assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
3901 if( pExpr->iTable
3902 && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
3903 ){
3904 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
3905 pExpr->iTable, n);
3906 }
drhc332cc32016-09-19 10:24:19 +00003907 return pExpr->pLeft->iTable + pExpr->iColumn;
drhfc7f27b2016-08-20 00:07:01 +00003908 }
drhfef52082000-06-06 01:50:43 +00003909 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003910 int destIfFalse = sqlite3VdbeMakeLabel(v);
3911 int destIfNull = sqlite3VdbeMakeLabel(v);
3912 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3913 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3914 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3915 sqlite3VdbeResolveLabel(v, destIfFalse);
3916 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3917 sqlite3VdbeResolveLabel(v, destIfNull);
drhc332cc32016-09-19 10:24:19 +00003918 return target;
drhfef52082000-06-06 01:50:43 +00003919 }
drhe3365e62009-11-12 17:52:24 +00003920#endif /* SQLITE_OMIT_SUBQUERY */
3921
3922
drh2dcef112008-01-12 19:03:48 +00003923 /*
3924 ** x BETWEEN y AND z
3925 **
3926 ** This is equivalent to
3927 **
3928 ** x>=y AND x<=z
3929 **
3930 ** X is stored in pExpr->pLeft.
3931 ** Y is stored in pExpr->pList->a[0].pExpr.
3932 ** Z is stored in pExpr->pList->a[1].pExpr.
3933 */
drhfef52082000-06-06 01:50:43 +00003934 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003935 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhc332cc32016-09-19 10:24:19 +00003936 return target;
drhfef52082000-06-06 01:50:43 +00003937 }
drh94fa9c42016-02-27 21:16:04 +00003938 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003939 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003940 case TK_UPLUS: {
drh1efa8022018-04-28 04:16:43 +00003941 pExpr = pExpr->pLeft;
drh59ee43a2018-05-29 15:18:31 +00003942 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
drha2e00042002-01-22 03:13:42 +00003943 }
drh2dcef112008-01-12 19:03:48 +00003944
dan165921a2009-08-28 18:53:45 +00003945 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003946 /* If the opcode is TK_TRIGGER, then the expression is a reference
3947 ** to a column in the new.* or old.* pseudo-tables available to
3948 ** trigger programs. In this case Expr.iTable is set to 1 for the
3949 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3950 ** is set to the column of the pseudo-table to read, or to -1 to
3951 ** read the rowid field.
3952 **
3953 ** The expression is implemented using an OP_Param opcode. The p1
3954 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3955 ** to reference another column of the old.* pseudo-table, where
3956 ** i is the index of the column. For a new.rowid reference, p1 is
3957 ** set to (n+1), where n is the number of columns in each pseudo-table.
3958 ** For a reference to any other column in the new.* pseudo-table, p1
3959 ** is set to (n+2+i), where n and i are as defined previously. For
3960 ** example, if the table on which triggers are being fired is
3961 ** declared as:
3962 **
3963 ** CREATE TABLE t1(a, b);
3964 **
3965 ** Then p1 is interpreted as follows:
3966 **
3967 ** p1==0 -> old.rowid p1==3 -> new.rowid
3968 ** p1==1 -> old.a p1==4 -> new.a
3969 ** p1==2 -> old.b p1==5 -> new.b
3970 */
drh8477f7f2018-09-19 20:14:48 +00003971 Table *pTab;
3972 assert( pExpr->eX==EX_Tab );
3973 pTab = pExpr->x.pTab;
dan65a7cd12009-09-01 12:16:01 +00003974 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3975
3976 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3977 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3978 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3979 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3980
3981 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
drh8477f7f2018-09-19 20:14:48 +00003982 assert( pExpr->eX==EX_Tab );
drh896494e2018-04-26 12:27:03 +00003983 VdbeComment((v, "r[%d]=%s.%s", target,
dan2bd93512009-08-31 08:22:46 +00003984 (pExpr->iTable ? "new" : "old"),
drh8477f7f2018-09-19 20:14:48 +00003985 (pExpr->iColumn<0 ? "rowid" : pExpr->x.pTab->aCol[pExpr->iColumn].zName)
dan165921a2009-08-28 18:53:45 +00003986 ));
dan65a7cd12009-09-01 12:16:01 +00003987
drh44dbca82010-01-13 04:22:20 +00003988#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003989 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003990 ** integer. Use OP_RealAffinity to make sure it is really real.
3991 **
3992 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3993 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003994 if( pExpr->iColumn>=0
3995 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3996 ){
3997 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3998 }
drh44dbca82010-01-13 04:22:20 +00003999#endif
dan165921a2009-08-28 18:53:45 +00004000 break;
4001 }
4002
dan71c57db2016-07-09 20:23:55 +00004003 case TK_VECTOR: {
drhe835bc12016-08-23 19:02:55 +00004004 sqlite3ErrorMsg(pParse, "row value misused");
dan71c57db2016-07-09 20:23:55 +00004005 break;
4006 }
4007
drh31d6fd52017-04-14 19:03:10 +00004008 case TK_IF_NULL_ROW: {
4009 int addrINR;
4010 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
drh31d6fd52017-04-14 19:03:10 +00004011 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh31d6fd52017-04-14 19:03:10 +00004012 sqlite3VdbeJumpHere(v, addrINR);
4013 sqlite3VdbeChangeP3(v, addrINR, inReg);
4014 break;
4015 }
4016
drh2dcef112008-01-12 19:03:48 +00004017 /*
4018 ** Form A:
4019 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4020 **
4021 ** Form B:
4022 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
4023 **
4024 ** Form A is can be transformed into the equivalent form B as follows:
4025 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
4026 ** WHEN x=eN THEN rN ELSE y END
4027 **
4028 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00004029 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
4030 ** odd. The Y is also optional. If the number of elements in x.pList
4031 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00004032 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4033 **
4034 ** The result of the expression is the Ri for the first matching Ei,
4035 ** or if there is no matching Ei, the ELSE term Y, or if there is
4036 ** no ELSE term, NULL.
4037 */
drh33cd4902009-05-30 20:49:20 +00004038 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00004039 int endLabel; /* GOTO label for end of CASE stmt */
4040 int nextCase; /* GOTO label for next WHEN clause */
4041 int nExpr; /* 2x number of WHEN terms */
4042 int i; /* Loop counter */
4043 ExprList *pEList; /* List of WHEN terms */
4044 struct ExprList_item *aListelem; /* Array of WHEN terms */
4045 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00004046 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00004047 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drh17a7f8d2002-03-24 13:13:27 +00004048
drh3b3c86a2018-09-18 21:35:31 +00004049 assert( pExpr->eX==EX_List );
4050 assert( pExpr->x.pList->nExpr > 0);
danielk19776ab3a2e2009-02-19 14:39:25 +00004051 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00004052 aListelem = pEList->a;
4053 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00004054 endLabel = sqlite3VdbeMakeLabel(v);
4055 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00004056 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00004057 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00004058 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00004059 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00004060 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00004061 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00004062 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00004063 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00004064 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4065 ** The value in regFree1 might get SCopy-ed into the file result.
4066 ** So make sure that the regFree1 register is not reused for other
4067 ** purposes and possibly overwritten. */
4068 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00004069 }
drhc5cd1242013-09-12 16:50:49 +00004070 for(i=0; i<nExpr-1; i=i+2){
drh2dcef112008-01-12 19:03:48 +00004071 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00004072 assert( pTest!=0 );
drh3d6bedf2018-09-19 14:54:38 +00004073 opCompare.x.pRight = aListelem[i].pExpr;
4074 opCompare.eX = EX_Right;
drh17a7f8d2002-03-24 13:13:27 +00004075 }else{
drh2dcef112008-01-12 19:03:48 +00004076 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00004077 }
drh2dcef112008-01-12 19:03:48 +00004078 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00004079 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00004080 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00004081 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00004082 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00004083 sqlite3VdbeGoto(v, endLabel);
drh2dcef112008-01-12 19:03:48 +00004084 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00004085 }
drhc5cd1242013-09-12 16:50:49 +00004086 if( (nExpr&1)!=0 ){
drhc5cd1242013-09-12 16:50:49 +00004087 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drh17a7f8d2002-03-24 13:13:27 +00004088 }else{
drh9de221d2008-01-05 06:51:30 +00004089 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00004090 }
drh2dcef112008-01-12 19:03:48 +00004091 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00004092 break;
4093 }
danielk19775338a5f2005-01-20 13:03:10 +00004094#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00004095 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00004096 assert( pExpr->affinity==OE_Rollback
4097 || pExpr->affinity==OE_Abort
4098 || pExpr->affinity==OE_Fail
4099 || pExpr->affinity==OE_Ignore
4100 );
dane0af83a2009-09-08 19:15:01 +00004101 if( !pParse->pTriggerTab ){
4102 sqlite3ErrorMsg(pParse,
4103 "RAISE() may only be used within a trigger-program");
4104 return 0;
4105 }
4106 if( pExpr->affinity==OE_Abort ){
4107 sqlite3MayAbort(pParse);
4108 }
dan165921a2009-08-28 18:53:45 +00004109 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00004110 if( pExpr->affinity==OE_Ignore ){
4111 sqlite3VdbeAddOp4(
4112 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00004113 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00004114 }else{
drh433dccf2013-02-09 15:37:11 +00004115 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00004116 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00004117 }
4118
drhffe07b22005-11-03 00:41:17 +00004119 break;
drh17a7f8d2002-03-24 13:13:27 +00004120 }
danielk19775338a5f2005-01-20 13:03:10 +00004121#endif
drhffe07b22005-11-03 00:41:17 +00004122 }
drh2dcef112008-01-12 19:03:48 +00004123 sqlite3ReleaseTempReg(pParse, regFree1);
4124 sqlite3ReleaseTempReg(pParse, regFree2);
4125 return inReg;
4126}
4127
4128/*
drhd1a01ed2013-11-21 16:08:52 +00004129** Factor out the code of the given expression to initialization time.
drh1e9b53f2017-01-04 01:07:24 +00004130**
drhad879ff2017-01-04 04:10:02 +00004131** If regDest>=0 then the result is always stored in that register and the
4132** result is not reusable. If regDest<0 then this routine is free to
4133** store the value whereever it wants. The register where the expression
4134** is stored is returned. When regDest<0, two identical expressions will
4135** code to the same register.
drhd1a01ed2013-11-21 16:08:52 +00004136*/
drh1e9b53f2017-01-04 01:07:24 +00004137int sqlite3ExprCodeAtInit(
drhd673cdd2013-11-21 21:23:31 +00004138 Parse *pParse, /* Parsing context */
4139 Expr *pExpr, /* The expression to code when the VDBE initializes */
drhad879ff2017-01-04 04:10:02 +00004140 int regDest /* Store the value in this register */
drhd673cdd2013-11-21 21:23:31 +00004141){
drhd1a01ed2013-11-21 16:08:52 +00004142 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00004143 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00004144 p = pParse->pConstExpr;
drhad879ff2017-01-04 04:10:02 +00004145 if( regDest<0 && p ){
4146 struct ExprList_item *pItem;
4147 int i;
4148 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
dan5aa550c2017-06-24 18:10:29 +00004149 if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
drhad879ff2017-01-04 04:10:02 +00004150 return pItem->u.iConstExprReg;
drh1e9b53f2017-01-04 01:07:24 +00004151 }
4152 }
drh1e9b53f2017-01-04 01:07:24 +00004153 }
drhd1a01ed2013-11-21 16:08:52 +00004154 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4155 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00004156 if( p ){
4157 struct ExprList_item *pItem = &p->a[p->nExpr-1];
drhad879ff2017-01-04 04:10:02 +00004158 pItem->reusable = regDest<0;
4159 if( regDest<0 ) regDest = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00004160 pItem->u.iConstExprReg = regDest;
drhd673cdd2013-11-21 21:23:31 +00004161 }
drhd1a01ed2013-11-21 16:08:52 +00004162 pParse->pConstExpr = p;
drh1e9b53f2017-01-04 01:07:24 +00004163 return regDest;
drhd1a01ed2013-11-21 16:08:52 +00004164}
4165
4166/*
drh2dcef112008-01-12 19:03:48 +00004167** Generate code to evaluate an expression and store the results
4168** into a register. Return the register number where the results
4169** are stored.
4170**
4171** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00004172** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00004173** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00004174**
4175** If pExpr is a constant, then this routine might generate this
4176** code to fill the register in the initialization section of the
4177** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00004178*/
4179int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00004180 int r2;
4181 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00004182 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00004183 && pExpr->op!=TK_REGISTER
4184 && sqlite3ExprIsConstantNotJoin(pExpr)
4185 ){
drhf30a9692013-11-15 01:10:18 +00004186 *pReg = 0;
drhad879ff2017-01-04 04:10:02 +00004187 r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
drh2dcef112008-01-12 19:03:48 +00004188 }else{
drhf30a9692013-11-15 01:10:18 +00004189 int r1 = sqlite3GetTempReg(pParse);
4190 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4191 if( r2==r1 ){
4192 *pReg = r1;
4193 }else{
4194 sqlite3ReleaseTempReg(pParse, r1);
4195 *pReg = 0;
4196 }
drh2dcef112008-01-12 19:03:48 +00004197 }
4198 return r2;
4199}
4200
4201/*
4202** Generate code that will evaluate expression pExpr and store the
4203** results in register target. The results are guaranteed to appear
4204** in register target.
4205*/
drh05a86c52014-02-16 01:55:49 +00004206void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00004207 int inReg;
4208
4209 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00004210 if( pExpr && pExpr->op==TK_REGISTER ){
4211 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
4212 }else{
4213 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00004214 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00004215 if( inReg!=target && pParse->pVdbe ){
4216 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
4217 }
drhcce7d172000-05-31 15:34:51 +00004218 }
drhcce7d172000-05-31 15:34:51 +00004219}
4220
4221/*
drh1c75c9d2015-12-21 15:22:13 +00004222** Make a transient copy of expression pExpr and then code it using
4223** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
4224** except that the input expression is guaranteed to be unchanged.
4225*/
4226void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4227 sqlite3 *db = pParse->db;
4228 pExpr = sqlite3ExprDup(db, pExpr, 0);
4229 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4230 sqlite3ExprDelete(db, pExpr);
4231}
4232
4233/*
drh05a86c52014-02-16 01:55:49 +00004234** Generate code that will evaluate expression pExpr and store the
4235** results in register target. The results are guaranteed to appear
4236** in register target. If the expression is constant, then this routine
4237** might choose to code the expression at initialization time.
4238*/
4239void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
drhb8b06692018-08-04 15:16:20 +00004240 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
drhad879ff2017-01-04 04:10:02 +00004241 sqlite3ExprCodeAtInit(pParse, pExpr, target);
drh05a86c52014-02-16 01:55:49 +00004242 }else{
4243 sqlite3ExprCode(pParse, pExpr, target);
4244 }
drhcce7d172000-05-31 15:34:51 +00004245}
4246
4247/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004248** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004249** in register target.
drh25303782004-12-07 15:41:48 +00004250**
drh2dcef112008-01-12 19:03:48 +00004251** Also make a copy of the expression results into another "cache" register
4252** and modify the expression so that the next time it is evaluated,
4253** the result is a copy of the cache register.
4254**
4255** This routine is used for expressions that are used multiple
4256** times. They are evaluated once and the results of the expression
4257** are reused.
drh25303782004-12-07 15:41:48 +00004258*/
drh05a86c52014-02-16 01:55:49 +00004259void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004260 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004261 int iMem;
4262
drhde4fcfd2008-01-19 23:50:26 +00004263 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004264 assert( pExpr->op!=TK_REGISTER );
4265 sqlite3ExprCode(pParse, pExpr, target);
4266 iMem = ++pParse->nMem;
4267 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4268 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004269}
drh2dcef112008-01-12 19:03:48 +00004270
drh678ccce2008-03-31 18:19:54 +00004271/*
drh268380c2004-02-25 13:47:31 +00004272** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004273** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004274**
drh3df6c3b2017-09-15 15:38:01 +00004275** Return the number of elements evaluated. The number returned will
4276** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
4277** is defined.
drhd1a01ed2013-11-21 16:08:52 +00004278**
4279** The SQLITE_ECEL_DUP flag prevents the arguments from being
4280** filled using OP_SCopy. OP_Copy must be used instead.
4281**
4282** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4283** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004284**
4285** The SQLITE_ECEL_REF flag means that expressions in the list with
4286** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4287** in registers at srcReg, and so the value can be copied from there.
drh3df6c3b2017-09-15 15:38:01 +00004288** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
4289** are simply omitted rather than being copied from srcReg.
drh268380c2004-02-25 13:47:31 +00004290*/
danielk19774adee202004-05-08 08:23:19 +00004291int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004292 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004293 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004294 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004295 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004296 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004297){
4298 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004299 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004300 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004301 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004302 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004303 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004304 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004305 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004306 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004307 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004308 Expr *pExpr = pItem->pExpr;
dan24e25d32018-04-14 18:46:20 +00004309#ifdef SQLITE_ENABLE_SORTER_REFERENCES
4310 if( pItem->bSorterRef ){
4311 i--;
4312 n--;
4313 }else
4314#endif
dan257c13f2016-11-10 20:14:06 +00004315 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4316 if( flags & SQLITE_ECEL_OMITREF ){
4317 i--;
4318 n--;
4319 }else{
4320 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4321 }
drhb8b06692018-08-04 15:16:20 +00004322 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
4323 && sqlite3ExprIsConstantNotJoin(pExpr)
4324 ){
drhad879ff2017-01-04 04:10:02 +00004325 sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
drhd1a01ed2013-11-21 16:08:52 +00004326 }else{
4327 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4328 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004329 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004330 if( copyOp==OP_Copy
4331 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4332 && pOp->p1+pOp->p3+1==inReg
4333 && pOp->p2+pOp->p3+1==target+i
4334 ){
4335 pOp->p3++;
4336 }else{
4337 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4338 }
drhd1a01ed2013-11-21 16:08:52 +00004339 }
drhd1766112008-09-17 00:13:12 +00004340 }
drh268380c2004-02-25 13:47:31 +00004341 }
drhf9b596e2004-05-26 16:54:42 +00004342 return n;
drh268380c2004-02-25 13:47:31 +00004343}
4344
4345/*
drh36c563a2009-11-12 13:32:22 +00004346** Generate code for a BETWEEN operator.
4347**
4348** x BETWEEN y AND z
4349**
4350** The above is equivalent to
4351**
4352** x>=y AND x<=z
4353**
4354** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004355** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004356**
4357** The xJumpIf parameter determines details:
4358**
4359** NULL: Store the boolean result in reg[dest]
4360** sqlite3ExprIfTrue: Jump to dest if true
4361** sqlite3ExprIfFalse: Jump to dest if false
4362**
4363** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004364*/
4365static void exprCodeBetween(
4366 Parse *pParse, /* Parsing and code generating context */
4367 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004368 int dest, /* Jump destination or storage location */
4369 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004370 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4371){
drhdb45bd52016-08-22 00:48:58 +00004372 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004373 Expr compLeft; /* The x>=y term */
4374 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004375 Expr exprX; /* The x subexpression */
4376 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004377
drh36c563a2009-11-12 13:32:22 +00004378
dan71c57db2016-07-09 20:23:55 +00004379 memset(&compLeft, 0, sizeof(Expr));
4380 memset(&compRight, 0, sizeof(Expr));
4381 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004382
drh3b3c86a2018-09-18 21:35:31 +00004383 assert( pExpr->eX==EX_List );
drhdb45bd52016-08-22 00:48:58 +00004384 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004385 exprAnd.op = TK_AND;
4386 exprAnd.pLeft = &compLeft;
drh3d6bedf2018-09-19 14:54:38 +00004387 exprAnd.x.pRight = &compRight;
4388 exprAnd.eX = EX_Right;
drh36c563a2009-11-12 13:32:22 +00004389 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004390 compLeft.pLeft = &exprX;
drh3d6bedf2018-09-19 14:54:38 +00004391 compLeft.x.pRight = pExpr->x.pList->a[0].pExpr;
4392 compLeft.eX = EX_Right;
drh36c563a2009-11-12 13:32:22 +00004393 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004394 compRight.pLeft = &exprX;
drh3d6bedf2018-09-19 14:54:38 +00004395 compRight.x.pRight = pExpr->x.pList->a[1].pExpr;
4396 compRight.eX = EX_Right;
drh12abf402016-08-22 14:30:05 +00004397 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004398 if( xJump ){
4399 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004400 }else{
drh36fd41e2016-11-25 14:30:42 +00004401 /* Mark the expression is being from the ON or USING clause of a join
4402 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4403 ** it into the Parse.pConstExpr list. We should use a new bit for this,
4404 ** for clarity, but we are out of bits in the Expr.flags field so we
4405 ** have to reuse the EP_FromJoin bit. Bummer. */
drhdb45bd52016-08-22 00:48:58 +00004406 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004407 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004408 }
drhdb45bd52016-08-22 00:48:58 +00004409 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004410
4411 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004412 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4413 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4414 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4415 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4416 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4417 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4418 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4419 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004420 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004421}
4422
4423/*
drhcce7d172000-05-31 15:34:51 +00004424** Generate code for a boolean expression such that a jump is made
4425** to the label "dest" if the expression is true but execution
4426** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004427**
4428** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004429** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004430**
4431** This code depends on the fact that certain token values (ex: TK_EQ)
4432** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4433** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4434** the make process cause these values to align. Assert()s in the code
4435** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004436*/
danielk19774adee202004-05-08 08:23:19 +00004437void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004438 Vdbe *v = pParse->pVdbe;
4439 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004440 int regFree1 = 0;
4441 int regFree2 = 0;
4442 int r1, r2;
4443
drh35573352008-01-08 23:54:25 +00004444 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004445 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004446 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004447 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004448 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004449 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004450 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004451 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004452 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh3d6bedf2018-09-19 14:54:38 +00004453 assert( pExpr->eX==EX_Right );
4454 sqlite3ExprIfTrue(pParse, pExpr->x.pRight, dest, jumpIfNull);
danielk19774adee202004-05-08 08:23:19 +00004455 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00004456 break;
4457 }
4458 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004459 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004460 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh3d6bedf2018-09-19 14:54:38 +00004461 assert( pExpr->eX==EX_Right );
4462 sqlite3ExprIfTrue(pParse, pExpr->x.pRight, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004463 break;
4464 }
4465 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004466 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004467 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004468 break;
4469 }
drh8abed7b2018-02-26 18:49:05 +00004470 case TK_TRUTH: {
drh96acafb2018-02-27 14:49:25 +00004471 int isNot; /* IS NOT TRUE or IS NOT FALSE */
4472 int isTrue; /* IS TRUE or IS NOT TRUE */
drh007c8432018-02-26 03:20:18 +00004473 testcase( jumpIfNull==0 );
drh8abed7b2018-02-26 18:49:05 +00004474 isNot = pExpr->op2==TK_ISNOT;
drh3d6bedf2018-09-19 14:54:38 +00004475 assert( pExpr->eX==EX_Right );
4476 isTrue = sqlite3ExprTruthValue(pExpr->x.pRight);
drh43c4ac82018-02-26 21:26:27 +00004477 testcase( isTrue && isNot );
drh96acafb2018-02-27 14:49:25 +00004478 testcase( !isTrue && isNot );
drh43c4ac82018-02-26 21:26:27 +00004479 if( isTrue ^ isNot ){
drh8abed7b2018-02-26 18:49:05 +00004480 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
4481 isNot ? SQLITE_JUMPIFNULL : 0);
4482 }else{
4483 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4484 isNot ? SQLITE_JUMPIFNULL : 0);
4485 }
drh007c8432018-02-26 03:20:18 +00004486 break;
4487 }
drhde845c22016-03-17 19:07:52 +00004488 case TK_IS:
4489 case TK_ISNOT:
4490 testcase( op==TK_IS );
4491 testcase( op==TK_ISNOT );
4492 op = (op==TK_IS) ? TK_EQ : TK_NE;
4493 jumpIfNull = SQLITE_NULLEQ;
4494 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004495 case TK_LT:
4496 case TK_LE:
4497 case TK_GT:
4498 case TK_GE:
4499 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004500 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004501 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004502 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004503 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00004504 assert( pExpr->eX==EX_Right );
4505 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
4506 codeCompare(pParse, pExpr->pLeft, pExpr->x.pRight, op,
drh2dcef112008-01-12 19:03:48 +00004507 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004508 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4509 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4510 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4511 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004512 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4513 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4514 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4515 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4516 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4517 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004518 testcase( regFree1==0 );
4519 testcase( regFree2==0 );
4520 break;
4521 }
drhcce7d172000-05-31 15:34:51 +00004522 case TK_ISNULL:
4523 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004524 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4525 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004526 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4527 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004528 VdbeCoverageIf(v, op==TK_ISNULL);
4529 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004530 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004531 break;
4532 }
drhfef52082000-06-06 01:50:43 +00004533 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004534 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004535 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004536 break;
4537 }
drh84e30ca2011-02-10 17:46:14 +00004538#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004539 case TK_IN: {
4540 int destIfFalse = sqlite3VdbeMakeLabel(v);
4541 int destIfNull = jumpIfNull ? dest : destIfFalse;
4542 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004543 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004544 sqlite3VdbeResolveLabel(v, destIfFalse);
4545 break;
4546 }
shanehbb201342011-02-09 19:55:20 +00004547#endif
drhcce7d172000-05-31 15:34:51 +00004548 default: {
dan7b35a772016-07-28 19:47:15 +00004549 default_expr:
drh991a1982014-01-02 17:57:16 +00004550 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004551 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004552 }else if( exprAlwaysFalse(pExpr) ){
4553 /* No-op */
4554 }else{
4555 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4556 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004557 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004558 testcase( regFree1==0 );
4559 testcase( jumpIfNull==0 );
4560 }
drhcce7d172000-05-31 15:34:51 +00004561 break;
4562 }
4563 }
drh2dcef112008-01-12 19:03:48 +00004564 sqlite3ReleaseTempReg(pParse, regFree1);
4565 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004566}
4567
4568/*
drh66b89c82000-11-28 20:47:17 +00004569** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004570** to the label "dest" if the expression is false but execution
4571** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004572**
4573** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004574** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4575** is 0.
drhcce7d172000-05-31 15:34:51 +00004576*/
danielk19774adee202004-05-08 08:23:19 +00004577void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004578 Vdbe *v = pParse->pVdbe;
4579 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004580 int regFree1 = 0;
4581 int regFree2 = 0;
4582 int r1, r2;
4583
drh35573352008-01-08 23:54:25 +00004584 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004585 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004586 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004587
4588 /* The value of pExpr->op and op are related as follows:
4589 **
4590 ** pExpr->op op
4591 ** --------- ----------
4592 ** TK_ISNULL OP_NotNull
4593 ** TK_NOTNULL OP_IsNull
4594 ** TK_NE OP_Eq
4595 ** TK_EQ OP_Ne
4596 ** TK_GT OP_Le
4597 ** TK_LE OP_Gt
4598 ** TK_GE OP_Lt
4599 ** TK_LT OP_Ge
4600 **
4601 ** For other values of pExpr->op, op is undefined and unused.
4602 ** The value of TK_ and OP_ constants are arranged such that we
4603 ** can compute the mapping above using the following expression.
4604 ** Assert()s verify that the computation is correct.
4605 */
4606 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4607
4608 /* Verify correct alignment of TK_ and OP_ constants
4609 */
4610 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4611 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4612 assert( pExpr->op!=TK_NE || op==OP_Eq );
4613 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4614 assert( pExpr->op!=TK_LT || op==OP_Ge );
4615 assert( pExpr->op!=TK_LE || op==OP_Gt );
4616 assert( pExpr->op!=TK_GT || op==OP_Le );
4617 assert( pExpr->op!=TK_GE || op==OP_Lt );
4618
danba00e302016-07-23 20:24:06 +00004619 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004620 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004621 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004622 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh3d6bedf2018-09-19 14:54:38 +00004623 assert( pExpr->eX==EX_Right );
4624 sqlite3ExprIfFalse(pParse, pExpr->x.pRight, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004625 break;
4626 }
4627 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004628 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004629 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004630 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh3d6bedf2018-09-19 14:54:38 +00004631 assert( pExpr->eX==EX_Right );
4632 sqlite3ExprIfFalse(pParse, pExpr->x.pRight, dest, jumpIfNull);
danielk19774adee202004-05-08 08:23:19 +00004633 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00004634 break;
4635 }
4636 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004637 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004638 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004639 break;
4640 }
drh8abed7b2018-02-26 18:49:05 +00004641 case TK_TRUTH: {
drh96acafb2018-02-27 14:49:25 +00004642 int isNot; /* IS NOT TRUE or IS NOT FALSE */
4643 int isTrue; /* IS TRUE or IS NOT TRUE */
drh8abed7b2018-02-26 18:49:05 +00004644 testcase( jumpIfNull==0 );
drh8abed7b2018-02-26 18:49:05 +00004645 isNot = pExpr->op2==TK_ISNOT;
drh3d6bedf2018-09-19 14:54:38 +00004646 assert( pExpr->eX==EX_Right );
4647 isTrue = sqlite3ExprTruthValue(pExpr->x.pRight);
drh43c4ac82018-02-26 21:26:27 +00004648 testcase( isTrue && isNot );
drh96acafb2018-02-27 14:49:25 +00004649 testcase( !isTrue && isNot );
drh43c4ac82018-02-26 21:26:27 +00004650 if( isTrue ^ isNot ){
drh8abed7b2018-02-26 18:49:05 +00004651 /* IS TRUE and IS NOT FALSE */
4652 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4653 isNot ? 0 : SQLITE_JUMPIFNULL);
4654
4655 }else{
4656 /* IS FALSE and IS NOT TRUE */
4657 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
drh96acafb2018-02-27 14:49:25 +00004658 isNot ? 0 : SQLITE_JUMPIFNULL);
drh8abed7b2018-02-26 18:49:05 +00004659 }
drh007c8432018-02-26 03:20:18 +00004660 break;
4661 }
drhde845c22016-03-17 19:07:52 +00004662 case TK_IS:
4663 case TK_ISNOT:
4664 testcase( pExpr->op==TK_IS );
4665 testcase( pExpr->op==TK_ISNOT );
4666 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4667 jumpIfNull = SQLITE_NULLEQ;
4668 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004669 case TK_LT:
4670 case TK_LE:
4671 case TK_GT:
4672 case TK_GE:
4673 case TK_NE:
4674 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004675 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004676 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004677 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00004678 assert( pExpr->eX==EX_Right );
4679 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
4680 codeCompare(pParse, pExpr->pLeft, pExpr->x.pRight, op,
drh2dcef112008-01-12 19:03:48 +00004681 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004682 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4683 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4684 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4685 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004686 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4687 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4688 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4689 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4690 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4691 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004692 testcase( regFree1==0 );
4693 testcase( regFree2==0 );
4694 break;
4695 }
drhcce7d172000-05-31 15:34:51 +00004696 case TK_ISNULL:
4697 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004698 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4699 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004700 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4701 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004702 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004703 break;
4704 }
drhfef52082000-06-06 01:50:43 +00004705 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004706 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004707 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004708 break;
4709 }
drh84e30ca2011-02-10 17:46:14 +00004710#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004711 case TK_IN: {
4712 if( jumpIfNull ){
4713 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4714 }else{
4715 int destIfNull = sqlite3VdbeMakeLabel(v);
4716 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4717 sqlite3VdbeResolveLabel(v, destIfNull);
4718 }
4719 break;
4720 }
shanehbb201342011-02-09 19:55:20 +00004721#endif
drhcce7d172000-05-31 15:34:51 +00004722 default: {
danba00e302016-07-23 20:24:06 +00004723 default_expr:
drh991a1982014-01-02 17:57:16 +00004724 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004725 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004726 }else if( exprAlwaysTrue(pExpr) ){
4727 /* no-op */
4728 }else{
4729 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4730 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004731 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004732 testcase( regFree1==0 );
4733 testcase( jumpIfNull==0 );
4734 }
drhcce7d172000-05-31 15:34:51 +00004735 break;
4736 }
4737 }
drh2dcef112008-01-12 19:03:48 +00004738 sqlite3ReleaseTempReg(pParse, regFree1);
4739 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004740}
drh22827922000-06-06 17:27:05 +00004741
4742/*
drh72bc8202015-06-11 13:58:35 +00004743** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4744** code generation, and that copy is deleted after code generation. This
4745** ensures that the original pExpr is unchanged.
4746*/
4747void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4748 sqlite3 *db = pParse->db;
4749 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4750 if( db->mallocFailed==0 ){
4751 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4752 }
4753 sqlite3ExprDelete(db, pCopy);
4754}
4755
dan5aa550c2017-06-24 18:10:29 +00004756/*
4757** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
4758** type of expression.
4759**
4760** If pExpr is a simple SQL value - an integer, real, string, blob
4761** or NULL value - then the VDBE currently being prepared is configured
4762** to re-prepare each time a new value is bound to variable pVar.
4763**
4764** Additionally, if pExpr is a simple SQL value and the value is the
4765** same as that currently bound to variable pVar, non-zero is returned.
4766** Otherwise, if the values are not the same or if pExpr is not a simple
4767** SQL value, zero is returned.
4768*/
4769static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
4770 int res = 0;
drhc0804222017-06-28 21:47:16 +00004771 int iVar;
4772 sqlite3_value *pL, *pR = 0;
4773
4774 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
4775 if( pR ){
4776 iVar = pVar->iColumn;
dan5aa550c2017-06-24 18:10:29 +00004777 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
dan5aa550c2017-06-24 18:10:29 +00004778 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
drh5aa307e2017-06-29 01:23:12 +00004779 if( pL ){
4780 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
4781 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
4782 }
4783 res = 0==sqlite3MemCompare(pL, pR, 0);
dan5aa550c2017-06-24 18:10:29 +00004784 }
drhc0804222017-06-28 21:47:16 +00004785 sqlite3ValueFree(pR);
4786 sqlite3ValueFree(pL);
dan5aa550c2017-06-24 18:10:29 +00004787 }
4788
4789 return res;
4790}
drh72bc8202015-06-11 13:58:35 +00004791
4792/*
drh1d9da702010-01-07 15:17:02 +00004793** Do a deep comparison of two expression trees. Return 0 if the two
4794** expressions are completely identical. Return 1 if they differ only
4795** by a COLLATE operator at the top level. Return 2 if there are differences
4796** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004797**
drh619a1302013-08-01 13:04:46 +00004798** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4799** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4800**
drh66518ca2013-08-01 15:09:57 +00004801** The pA side might be using TK_REGISTER. If that is the case and pB is
4802** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4803**
drh1d9da702010-01-07 15:17:02 +00004804** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004805** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004806** identical, we return 2 just to be safe. So if this routine
4807** returns 2, then you do not really know for certain if the two
4808** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004809** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004810** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004811** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004812** an incorrect 0 or 1 could lead to a malfunction.
dan5aa550c2017-06-24 18:10:29 +00004813**
drhc0804222017-06-28 21:47:16 +00004814** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
4815** pParse->pReprepare can be matched against literals in pB. The
4816** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
4817** If pParse is NULL (the normal case) then any TK_VARIABLE term in
4818** Argument pParse should normally be NULL. If it is not NULL and pA or
4819** pB causes a return value of 2.
drh22827922000-06-06 17:27:05 +00004820*/
dan5aa550c2017-06-24 18:10:29 +00004821int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004822 u32 combinedFlags;
4823 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004824 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004825 }
dan5aa550c2017-06-24 18:10:29 +00004826 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
4827 return 0;
4828 }
drh10d1edf2013-11-15 15:52:39 +00004829 combinedFlags = pA->flags | pB->flags;
4830 if( combinedFlags & EP_IntValue ){
4831 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4832 return 0;
4833 }
drh1d9da702010-01-07 15:17:02 +00004834 return 2;
drh22827922000-06-06 17:27:05 +00004835 }
drhc2acc4e2013-11-15 18:15:19 +00004836 if( pA->op!=pB->op ){
dan5aa550c2017-06-24 18:10:29 +00004837 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004838 return 1;
4839 }
dan5aa550c2017-06-24 18:10:29 +00004840 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004841 return 1;
4842 }
4843 return 2;
4844 }
drh2edc5fd2015-11-24 02:10:52 +00004845 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004846 if( pA->op==TK_FUNCTION ){
4847 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
drhd5af5422018-04-13 14:27:01 +00004848 }else if( pA->op==TK_COLLATE ){
drhe79f6292018-04-18 17:52:28 +00004849 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
drhefad2e22018-07-27 16:57:11 +00004850 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhd5af5422018-04-13 14:27:01 +00004851 return 2;
drh2646da72005-12-09 20:02:05 +00004852 }
drh22827922000-06-06 17:27:05 +00004853 }
drh10d1edf2013-11-15 15:52:39 +00004854 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004855 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh3b3c86a2018-09-18 21:35:31 +00004856 if( pA->eX==EX_Select || pA->eX!=pB->eX ) return 2;
drhefad2e22018-07-27 16:57:11 +00004857 if( (combinedFlags & EP_FixedCol)==0
4858 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
drh3d6bedf2018-09-19 14:54:38 +00004859 if( pA->eX==EX_Right ){
4860 if( sqlite3ExprCompare(pParse,pA->x.pRight,pB->x.pRight,iTab) ) return 2;
4861 }
drh3b3c86a2018-09-18 21:35:31 +00004862 if( pA->eX==EX_List ){
4863 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
4864 }
drhf49ff6f2018-04-23 20:38:40 +00004865 assert( (combinedFlags & EP_Reduced)==0 );
4866 if( pA->op!=TK_STRING && pA->op!=TK_TRUEFALSE ){
drh10d1edf2013-11-15 15:52:39 +00004867 if( pA->iColumn!=pB->iColumn ) return 2;
4868 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004869 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004870 }
drh6cbb4c92018-07-10 06:47:07 +00004871#ifndef SQLITE_OMIT_WINDOWFUNC
drh38630ae2018-07-10 07:25:42 +00004872 /* Justification for the assert():
drheee08612018-07-10 07:39:23 +00004873 ** window functions have p->op==TK_FUNCTION but aggregate functions
drh38630ae2018-07-10 07:25:42 +00004874 ** have p->op==TK_AGG_FUNCTION. So any comparison between an aggregate
4875 ** function and a window function should have failed before reaching
4876 ** this point. And, it is not possible to have a window function and
4877 ** a scalar function with the same name and number of arguments. So
4878 ** if we reach this point, either A and B both window functions or
4879 ** neither are a window functions. */
4880 assert( (pA->pWin==0)==(pB->pWin==0) );
4881
drh6cbb4c92018-07-10 06:47:07 +00004882 if( pA->pWin!=0 ){
drh6cbb4c92018-07-10 06:47:07 +00004883 if( sqlite3WindowCompare(pParse,pA->pWin,pB->pWin)!=0 ) return 2;
drh6cbb4c92018-07-10 06:47:07 +00004884 }
4885#endif
drh10d1edf2013-11-15 15:52:39 +00004886 }
drh1d9da702010-01-07 15:17:02 +00004887 return 0;
drh22827922000-06-06 17:27:05 +00004888}
4889
drh8c6f6662010-04-26 19:17:26 +00004890/*
4891** Compare two ExprList objects. Return 0 if they are identical and
4892** non-zero if they differ in any way.
4893**
drh619a1302013-08-01 13:04:46 +00004894** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4895** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4896**
drh8c6f6662010-04-26 19:17:26 +00004897** This routine might return non-zero for equivalent ExprLists. The
4898** only consequence will be disabled optimizations. But this routine
4899** must never return 0 if the two ExprList objects are different, or
4900** a malfunction will result.
4901**
4902** Two NULL pointers are considered to be the same. But a NULL pointer
4903** always differs from a non-NULL pointer.
4904*/
drh619a1302013-08-01 13:04:46 +00004905int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004906 int i;
4907 if( pA==0 && pB==0 ) return 0;
4908 if( pA==0 || pB==0 ) return 1;
4909 if( pA->nExpr!=pB->nExpr ) return 1;
4910 for(i=0; i<pA->nExpr; i++){
4911 Expr *pExprA = pA->a[i].pExpr;
4912 Expr *pExprB = pB->a[i].pExpr;
4913 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
dan5aa550c2017-06-24 18:10:29 +00004914 if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004915 }
4916 return 0;
4917}
drh13449892005-09-07 21:22:45 +00004918
drh22827922000-06-06 17:27:05 +00004919/*
drhf9463df2017-02-11 14:59:58 +00004920** Like sqlite3ExprCompare() except COLLATE operators at the top-level
4921** are ignored.
4922*/
4923int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
dan5aa550c2017-06-24 18:10:29 +00004924 return sqlite3ExprCompare(0,
drhf9463df2017-02-11 14:59:58 +00004925 sqlite3ExprSkipCollate(pA),
4926 sqlite3ExprSkipCollate(pB),
4927 iTab);
4928}
4929
4930/*
drh4bd5f732013-07-31 23:22:39 +00004931** Return true if we can prove the pE2 will always be true if pE1 is
4932** true. Return false if we cannot complete the proof or if pE2 might
4933** be false. Examples:
4934**
drh619a1302013-08-01 13:04:46 +00004935** pE1: x==5 pE2: x==5 Result: true
4936** pE1: x>0 pE2: x==5 Result: false
4937** pE1: x=21 pE2: x=21 OR y=43 Result: true
4938** pE1: x!=123 pE2: x IS NOT NULL Result: true
4939** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4940** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4941** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004942**
4943** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4944** Expr.iTable<0 then assume a table number given by iTab.
4945**
drhc0804222017-06-28 21:47:16 +00004946** If pParse is not NULL, then the values of bound variables in pE1 are
4947** compared against literal values in pE2 and pParse->pVdbe->expmask is
4948** modified to record which bound variables are referenced. If pParse
4949** is NULL, then false will be returned if pE1 contains any bound variables.
4950**
drh4bd5f732013-07-31 23:22:39 +00004951** When in doubt, return false. Returning true might give a performance
4952** improvement. Returning false might cause a performance reduction, but
4953** it will always give the correct answer and is hence always safe.
4954*/
dan5aa550c2017-06-24 18:10:29 +00004955int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
4956 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
drh619a1302013-08-01 13:04:46 +00004957 return 1;
4958 }
drh3d6bedf2018-09-19 14:54:38 +00004959 assert( pE2->op!=TK_OR || pE2->eX==EX_Right );
drh619a1302013-08-01 13:04:46 +00004960 if( pE2->op==TK_OR
dan5aa550c2017-06-24 18:10:29 +00004961 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
drh3d6bedf2018-09-19 14:54:38 +00004962 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->x.pRight, iTab) )
drh619a1302013-08-01 13:04:46 +00004963 ){
4964 return 1;
4965 }
drh1ad93a02016-11-02 02:17:52 +00004966 if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
4967 Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
4968 testcase( pX!=pE1->pLeft );
dan5aa550c2017-06-24 18:10:29 +00004969 if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
drh619a1302013-08-01 13:04:46 +00004970 }
4971 return 0;
drh4bd5f732013-07-31 23:22:39 +00004972}
4973
4974/*
drh25897872018-03-20 21:16:15 +00004975** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
4976** If the expression node requires that the table at pWalker->iCur
4977** have a non-NULL column, then set pWalker->eCode to 1 and abort.
4978*/
4979static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
drh821b6102018-03-24 18:01:51 +00004980 /* This routine is only called for WHERE clause expressions and so it
4981 ** cannot have any TK_AGG_COLUMN entries because those are only found
4982 ** in HAVING clauses. We can get a TK_AGG_FUNCTION in a WHERE clause,
4983 ** but that is an illegal construct and the query will be rejected at
4984 ** a later stage of processing, so the TK_AGG_FUNCTION case does not
4985 ** need to be considered here. */
4986 assert( pExpr->op!=TK_AGG_COLUMN );
4987 testcase( pExpr->op==TK_AGG_FUNCTION );
4988
drh25897872018-03-20 21:16:15 +00004989 if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
4990 switch( pExpr->op ){
dan04932222018-04-10 15:31:56 +00004991 case TK_ISNOT:
dana1054dc2018-04-10 12:10:01 +00004992 case TK_NOT:
drh25897872018-03-20 21:16:15 +00004993 case TK_ISNULL:
4994 case TK_IS:
4995 case TK_OR:
drh2c492062018-03-24 13:24:02 +00004996 case TK_CASE:
drhe3eff262018-03-24 15:47:31 +00004997 case TK_IN:
drh25897872018-03-20 21:16:15 +00004998 case TK_FUNCTION:
dan04932222018-04-10 15:31:56 +00004999 testcase( pExpr->op==TK_ISNOT );
5000 testcase( pExpr->op==TK_NOT );
drh821b6102018-03-24 18:01:51 +00005001 testcase( pExpr->op==TK_ISNULL );
5002 testcase( pExpr->op==TK_IS );
5003 testcase( pExpr->op==TK_OR );
5004 testcase( pExpr->op==TK_CASE );
5005 testcase( pExpr->op==TK_IN );
5006 testcase( pExpr->op==TK_FUNCTION );
drh25897872018-03-20 21:16:15 +00005007 return WRC_Prune;
5008 case TK_COLUMN:
drh25897872018-03-20 21:16:15 +00005009 if( pWalker->u.iCur==pExpr->iTable ){
5010 pWalker->eCode = 1;
5011 return WRC_Abort;
5012 }
5013 return WRC_Prune;
drh98811552018-04-03 14:04:48 +00005014
5015 /* Virtual tables are allowed to use constraints like x=NULL. So
5016 ** a term of the form x=y does not prove that y is not null if x
5017 ** is the column of a virtual table */
5018 case TK_EQ:
5019 case TK_NE:
5020 case TK_LT:
5021 case TK_LE:
5022 case TK_GT:
5023 case TK_GE:
5024 testcase( pExpr->op==TK_EQ );
5025 testcase( pExpr->op==TK_NE );
5026 testcase( pExpr->op==TK_LT );
5027 testcase( pExpr->op==TK_LE );
5028 testcase( pExpr->op==TK_GT );
5029 testcase( pExpr->op==TK_GE );
drh3d6bedf2018-09-19 14:54:38 +00005030 assert( pExpr->eX==EX_Right );
drh8477f7f2018-09-19 20:14:48 +00005031 if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->x.pTab))
5032 || (pExpr->x.pRight->op==TK_COLUMN && IsVirtual(pExpr->x.pRight->x.pTab))
drh98811552018-04-03 14:04:48 +00005033 ){
5034 return WRC_Prune;
5035 }
drh25897872018-03-20 21:16:15 +00005036 default:
5037 return WRC_Continue;
5038 }
5039}
5040
5041/*
5042** Return true (non-zero) if expression p can only be true if at least
5043** one column of table iTab is non-null. In other words, return true
5044** if expression p will always be NULL or false if every column of iTab
5045** is NULL.
5046**
drh821b6102018-03-24 18:01:51 +00005047** False negatives are acceptable. In other words, it is ok to return
5048** zero even if expression p will never be true of every column of iTab
5049** is NULL. A false negative is merely a missed optimization opportunity.
5050**
5051** False positives are not allowed, however. A false positive may result
5052** in an incorrect answer.
5053**
drh25897872018-03-20 21:16:15 +00005054** Terms of p that are marked with EP_FromJoin (and hence that come from
5055** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
5056**
5057** This routine is used to check if a LEFT JOIN can be converted into
5058** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
5059** clause requires that some column of the right table of the LEFT JOIN
5060** be non-NULL, then the LEFT JOIN can be safely converted into an
5061** ordinary join.
5062*/
5063int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
5064 Walker w;
5065 w.xExprCallback = impliesNotNullRow;
5066 w.xSelectCallback = 0;
5067 w.xSelectCallback2 = 0;
5068 w.eCode = 0;
5069 w.u.iCur = iTab;
5070 sqlite3WalkExpr(&w, p);
5071 return w.eCode;
5072}
5073
5074/*
drh030796d2012-08-23 16:18:10 +00005075** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00005076** to determine if an expression can be evaluated by reference to the
5077** index only, without having to do a search for the corresponding
5078** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
5079** is the cursor for the table.
5080*/
5081struct IdxCover {
5082 Index *pIdx; /* The index to be tested for coverage */
5083 int iCur; /* Cursor number for the table corresponding to the index */
5084};
5085
5086/*
5087** Check to see if there are references to columns in table
5088** pWalker->u.pIdxCover->iCur can be satisfied using the index
5089** pWalker->u.pIdxCover->pIdx.
5090*/
5091static int exprIdxCover(Walker *pWalker, Expr *pExpr){
5092 if( pExpr->op==TK_COLUMN
5093 && pExpr->iTable==pWalker->u.pIdxCover->iCur
5094 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
5095 ){
5096 pWalker->eCode = 1;
5097 return WRC_Abort;
5098 }
5099 return WRC_Continue;
5100}
5101
5102/*
drhe604ec02016-07-27 19:20:58 +00005103** Determine if an index pIdx on table with cursor iCur contains will
5104** the expression pExpr. Return true if the index does cover the
5105** expression and false if the pExpr expression references table columns
5106** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00005107**
5108** An index covering an expression means that the expression can be
5109** evaluated using only the index and without having to lookup the
5110** corresponding table entry.
5111*/
5112int sqlite3ExprCoveredByIndex(
5113 Expr *pExpr, /* The index to be tested */
5114 int iCur, /* The cursor number for the corresponding table */
5115 Index *pIdx /* The index that might be used for coverage */
5116){
5117 Walker w;
5118 struct IdxCover xcov;
5119 memset(&w, 0, sizeof(w));
5120 xcov.iCur = iCur;
5121 xcov.pIdx = pIdx;
5122 w.xExprCallback = exprIdxCover;
5123 w.u.pIdxCover = &xcov;
5124 sqlite3WalkExpr(&w, pExpr);
5125 return !w.eCode;
5126}
5127
5128
5129/*
5130** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00005131** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00005132** aggregate function, in order to implement the
5133** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00005134*/
drh030796d2012-08-23 16:18:10 +00005135struct SrcCount {
5136 SrcList *pSrc; /* One particular FROM clause in a nested query */
5137 int nThis; /* Number of references to columns in pSrcList */
5138 int nOther; /* Number of references to columns in other FROM clauses */
5139};
5140
5141/*
5142** Count the number of references to columns.
5143*/
5144static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00005145 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
5146 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
5147 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
5148 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
5149 ** NEVER() will need to be removed. */
5150 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00005151 int i;
drh030796d2012-08-23 16:18:10 +00005152 struct SrcCount *p = pWalker->u.pSrcCount;
5153 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00005154 int nSrc = pSrc ? pSrc->nSrc : 0;
5155 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00005156 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00005157 }
drh655814d2015-01-09 01:27:29 +00005158 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00005159 p->nThis++;
5160 }else{
5161 p->nOther++;
5162 }
drh374fdce2012-04-17 16:38:53 +00005163 }
drh030796d2012-08-23 16:18:10 +00005164 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00005165}
5166
5167/*
drh030796d2012-08-23 16:18:10 +00005168** Determine if any of the arguments to the pExpr Function reference
5169** pSrcList. Return true if they do. Also return true if the function
5170** has no arguments or has only constant arguments. Return false if pExpr
5171** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00005172*/
drh030796d2012-08-23 16:18:10 +00005173int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00005174 Walker w;
drh030796d2012-08-23 16:18:10 +00005175 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00005176 assert( pExpr->op==TK_AGG_FUNCTION );
drh030796d2012-08-23 16:18:10 +00005177 w.xExprCallback = exprSrcCount;
drh979dd1b2017-05-29 14:26:07 +00005178 w.xSelectCallback = 0;
drh030796d2012-08-23 16:18:10 +00005179 w.u.pSrcCount = &cnt;
5180 cnt.pSrc = pSrcList;
5181 cnt.nThis = 0;
5182 cnt.nOther = 0;
5183 sqlite3WalkExprList(&w, pExpr->x.pList);
5184 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00005185}
5186
5187/*
drh13449892005-09-07 21:22:45 +00005188** Add a new element to the pAggInfo->aCol[] array. Return the index of
5189** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00005190*/
drh17435752007-08-16 04:30:38 +00005191static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00005192 int i;
drhcf643722007-03-27 13:36:37 +00005193 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00005194 db,
drhcf643722007-03-27 13:36:37 +00005195 pInfo->aCol,
5196 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00005197 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00005198 &i
5199 );
drh13449892005-09-07 21:22:45 +00005200 return i;
5201}
5202
5203/*
5204** Add a new element to the pAggInfo->aFunc[] array. Return the index of
5205** the new element. Return a negative number if malloc fails.
5206*/
drh17435752007-08-16 04:30:38 +00005207static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00005208 int i;
drhcf643722007-03-27 13:36:37 +00005209 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00005210 db,
drhcf643722007-03-27 13:36:37 +00005211 pInfo->aFunc,
5212 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00005213 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00005214 &i
5215 );
drh13449892005-09-07 21:22:45 +00005216 return i;
5217}
drh22827922000-06-06 17:27:05 +00005218
5219/*
drh7d10d5a2008-08-20 16:35:10 +00005220** This is the xExprCallback for a tree walker. It is used to
5221** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00005222** for additional information.
drh22827922000-06-06 17:27:05 +00005223*/
drh7d10d5a2008-08-20 16:35:10 +00005224static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00005225 int i;
drh7d10d5a2008-08-20 16:35:10 +00005226 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00005227 Parse *pParse = pNC->pParse;
5228 SrcList *pSrcList = pNC->pSrcList;
drh25c3b8c2018-04-16 10:34:13 +00005229 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
drh22827922000-06-06 17:27:05 +00005230
drh25c3b8c2018-04-16 10:34:13 +00005231 assert( pNC->ncFlags & NC_UAggInfo );
drh22827922000-06-06 17:27:05 +00005232 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00005233 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00005234 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00005235 testcase( pExpr->op==TK_AGG_COLUMN );
5236 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00005237 /* Check to see if the column is in one of the tables in the FROM
5238 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00005239 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00005240 struct SrcList_item *pItem = pSrcList->a;
5241 for(i=0; i<pSrcList->nSrc; i++, pItem++){
5242 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00005243 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00005244 if( pExpr->iTable==pItem->iCursor ){
5245 /* If we reach this point, it means that pExpr refers to a table
5246 ** that is in the FROM clause of the aggregate query.
5247 **
5248 ** Make an entry for the column in pAggInfo->aCol[] if there
5249 ** is not an entry there already.
5250 */
drh7f906d62007-03-12 23:48:52 +00005251 int k;
drh13449892005-09-07 21:22:45 +00005252 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00005253 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00005254 if( pCol->iTable==pExpr->iTable &&
5255 pCol->iColumn==pExpr->iColumn ){
5256 break;
5257 }
danielk1977a58fdfb2005-02-08 07:50:40 +00005258 }
danielk19771e536952007-08-16 10:09:01 +00005259 if( (k>=pAggInfo->nColumn)
5260 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
5261 ){
drh7f906d62007-03-12 23:48:52 +00005262 pCol = &pAggInfo->aCol[k];
drh8477f7f2018-09-19 20:14:48 +00005263 assert( pExpr->eX==EX_Tab );
5264 pCol->pTab = pExpr->x.pTab;
drh13449892005-09-07 21:22:45 +00005265 pCol->iTable = pExpr->iTable;
5266 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00005267 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00005268 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00005269 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00005270 if( pAggInfo->pGroupBy ){
5271 int j, n;
5272 ExprList *pGB = pAggInfo->pGroupBy;
5273 struct ExprList_item *pTerm = pGB->a;
5274 n = pGB->nExpr;
5275 for(j=0; j<n; j++, pTerm++){
5276 Expr *pE = pTerm->pExpr;
5277 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
5278 pE->iColumn==pExpr->iColumn ){
5279 pCol->iSorterColumn = j;
5280 break;
5281 }
5282 }
5283 }
5284 if( pCol->iSorterColumn<0 ){
5285 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
5286 }
5287 }
5288 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
5289 ** because it was there before or because we just created it).
5290 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
5291 ** pAggInfo->aCol[] entry.
5292 */
drhebb6a652013-09-12 23:42:22 +00005293 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00005294 pExpr->pAggInfo = pAggInfo;
5295 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00005296 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00005297 break;
5298 } /* endif pExpr->iTable==pItem->iCursor */
5299 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00005300 }
drh7d10d5a2008-08-20 16:35:10 +00005301 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00005302 }
5303 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00005304 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00005305 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00005306 ){
drh13449892005-09-07 21:22:45 +00005307 /* Check to see if pExpr is a duplicate of another aggregate
5308 ** function that is already in the pAggInfo structure
5309 */
5310 struct AggInfo_func *pItem = pAggInfo->aFunc;
5311 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
dan5aa550c2017-06-24 18:10:29 +00005312 if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00005313 break;
5314 }
drh22827922000-06-06 17:27:05 +00005315 }
drh13449892005-09-07 21:22:45 +00005316 if( i>=pAggInfo->nFunc ){
5317 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
5318 */
danielk197714db2662006-01-09 16:12:04 +00005319 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00005320 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00005321 if( i>=0 ){
drh3b3c86a2018-09-18 21:35:31 +00005322 assert( pExpr->eX==EX_List || pExpr->eX==EX_None );
drh13449892005-09-07 21:22:45 +00005323 pItem = &pAggInfo->aFunc[i];
5324 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00005325 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00005326 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00005327 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00005328 pExpr->u.zToken,
drh3b3c86a2018-09-18 21:35:31 +00005329 pExpr->eX==EX_List ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00005330 if( pExpr->flags & EP_Distinct ){
5331 pItem->iDistinct = pParse->nTab++;
5332 }else{
5333 pItem->iDistinct = -1;
5334 }
drh13449892005-09-07 21:22:45 +00005335 }
danielk1977a58fdfb2005-02-08 07:50:40 +00005336 }
drh13449892005-09-07 21:22:45 +00005337 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
5338 */
drhc5cd1242013-09-12 16:50:49 +00005339 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00005340 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00005341 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00005342 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00005343 return WRC_Prune;
5344 }else{
5345 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00005346 }
drh22827922000-06-06 17:27:05 +00005347 }
5348 }
drh7d10d5a2008-08-20 16:35:10 +00005349 return WRC_Continue;
5350}
5351static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00005352 UNUSED_PARAMETER(pSelect);
drh979dd1b2017-05-29 14:26:07 +00005353 pWalker->walkerDepth++;
drh374fdce2012-04-17 16:38:53 +00005354 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00005355}
drh979dd1b2017-05-29 14:26:07 +00005356static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
5357 UNUSED_PARAMETER(pSelect);
5358 pWalker->walkerDepth--;
5359}
drh626a8792005-01-17 22:08:19 +00005360
5361/*
drhe8abb4c2012-11-02 18:24:57 +00005362** Analyze the pExpr expression looking for aggregate functions and
5363** for variables that need to be added to AggInfo object that pNC->pAggInfo
5364** points to. Additional entries are made on the AggInfo object as
5365** necessary.
drh626a8792005-01-17 22:08:19 +00005366**
5367** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00005368** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00005369*/
drhd2b3e232008-01-23 14:51:49 +00005370void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00005371 Walker w;
5372 w.xExprCallback = analyzeAggregate;
5373 w.xSelectCallback = analyzeAggregatesInSelect;
drh979dd1b2017-05-29 14:26:07 +00005374 w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
5375 w.walkerDepth = 0;
drh7d10d5a2008-08-20 16:35:10 +00005376 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00005377 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00005378 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00005379}
drh5d9a4af2005-08-30 00:54:01 +00005380
5381/*
5382** Call sqlite3ExprAnalyzeAggregates() for every expression in an
5383** expression list. Return the number of errors.
5384**
5385** If an error is found, the analysis is cut short.
5386*/
drhd2b3e232008-01-23 14:51:49 +00005387void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00005388 struct ExprList_item *pItem;
5389 int i;
drh5d9a4af2005-08-30 00:54:01 +00005390 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00005391 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5392 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00005393 }
5394 }
drh5d9a4af2005-08-30 00:54:01 +00005395}
drh892d3172008-01-10 03:46:36 +00005396
5397/*
drhceea3322009-04-23 13:22:42 +00005398** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00005399*/
5400int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00005401 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00005402 return ++pParse->nMem;
5403 }
danielk19772f425f62008-07-04 09:41:39 +00005404 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00005405}
drhceea3322009-04-23 13:22:42 +00005406
5407/*
5408** Deallocate a register, making available for reuse for some other
5409** purpose.
drhceea3322009-04-23 13:22:42 +00005410*/
drh892d3172008-01-10 03:46:36 +00005411void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00005412 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drh892d3172008-01-10 03:46:36 +00005413 pParse->aTempReg[pParse->nTempReg++] = iReg;
5414 }
5415}
5416
5417/*
drhed24da42016-09-06 14:37:05 +00005418** Allocate or deallocate a block of nReg consecutive registers.
drh892d3172008-01-10 03:46:36 +00005419*/
5420int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00005421 int i, n;
drhed24da42016-09-06 14:37:05 +00005422 if( nReg==1 ) return sqlite3GetTempReg(pParse);
drhe55cbd72008-03-31 23:48:03 +00005423 i = pParse->iRangeReg;
5424 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00005425 if( nReg<=n ){
drh892d3172008-01-10 03:46:36 +00005426 pParse->iRangeReg += nReg;
5427 pParse->nRangeReg -= nReg;
5428 }else{
5429 i = pParse->nMem+1;
5430 pParse->nMem += nReg;
5431 }
5432 return i;
5433}
5434void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhed24da42016-09-06 14:37:05 +00005435 if( nReg==1 ){
5436 sqlite3ReleaseTempReg(pParse, iReg);
5437 return;
5438 }
drh892d3172008-01-10 03:46:36 +00005439 if( nReg>pParse->nRangeReg ){
5440 pParse->nRangeReg = nReg;
5441 pParse->iRangeReg = iReg;
5442 }
5443}
drhcdc69552011-12-06 13:24:59 +00005444
5445/*
5446** Mark all temporary registers as being unavailable for reuse.
5447*/
5448void sqlite3ClearTempRegCache(Parse *pParse){
5449 pParse->nTempReg = 0;
5450 pParse->nRangeReg = 0;
5451}
drhbb9b5f22016-03-19 00:35:02 +00005452
5453/*
5454** Validate that no temporary register falls within the range of
5455** iFirst..iLast, inclusive. This routine is only call from within assert()
5456** statements.
5457*/
5458#ifdef SQLITE_DEBUG
5459int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5460 int i;
5461 if( pParse->nRangeReg>0
drh3963e582017-07-15 20:33:19 +00005462 && pParse->iRangeReg+pParse->nRangeReg > iFirst
5463 && pParse->iRangeReg <= iLast
drhbb9b5f22016-03-19 00:35:02 +00005464 ){
5465 return 0;
5466 }
5467 for(i=0; i<pParse->nTempReg; i++){
5468 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5469 return 0;
5470 }
5471 }
5472 return 1;
5473}
5474#endif /* SQLITE_DEBUG */