blob: 43f116aab8ecb3bbe30a83a898aaaaddb9717cf2 [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
danb8d29c22017-04-11 11:52:25 +000061 if( (op==TK_AGG_COLUMN || op==TK_COLUMN) && pExpr->pTab ){
drh0dfa4f62016-08-26 13:19:49 +000062 return sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
drh7d10d5a2008-08-20 16:35:10 +000063 }
dan80aa5452016-09-03 19:52:12 +000064 if( op==TK_SELECT_COLUMN ){
drh3b3c86a2018-09-18 21:35:31 +000065 assert( pExpr->pLeft->eX==EX_Select );
dan80aa5452016-09-03 19:52:12 +000066 return sqlite3ExprAffinity(
67 pExpr->pLeft->x.pSelect->pEList->a[pExpr->iColumn].pExpr
68 );
69 }
danielk1977a37cdde2004-05-16 11:15:36 +000070 return pExpr->affinity;
71}
72
drh53db1452004-05-20 13:54:53 +000073/*
drh8b4c40d2007-02-01 23:02:45 +000074** Set the collating sequence for expression pExpr to be the collating
drhae80dde2012-12-06 21:16:43 +000075** sequence named by pToken. Return a pointer to a new Expr node that
76** implements the COLLATE operator.
drh0a8a4062012-12-07 18:38:16 +000077**
78** If a memory allocation error occurs, that fact is recorded in pParse->db
79** and the pExpr parameter is returned unchanged.
drh8b4c40d2007-02-01 23:02:45 +000080*/
drh4ef7efa2014-03-20 15:14:08 +000081Expr *sqlite3ExprAddCollateToken(
82 Parse *pParse, /* Parsing context */
83 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
dan80103fc2015-03-20 08:43:59 +000084 const Token *pCollName, /* Name of collating sequence */
85 int dequote /* True to dequote pCollName */
drh4ef7efa2014-03-20 15:14:08 +000086){
drh0a8a4062012-12-07 18:38:16 +000087 if( pCollName->n>0 ){
dan80103fc2015-03-20 08:43:59 +000088 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
drh0a8a4062012-12-07 18:38:16 +000089 if( pNew ){
90 pNew->pLeft = pExpr;
drha4c3c872013-09-12 17:29:25 +000091 pNew->flags |= EP_Collate|EP_Skip;
drh0a8a4062012-12-07 18:38:16 +000092 pExpr = pNew;
93 }
drhae80dde2012-12-06 21:16:43 +000094 }
drh0a8a4062012-12-07 18:38:16 +000095 return pExpr;
96}
97Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
drh261d8a52012-12-08 21:36:26 +000098 Token s;
99 assert( zC!=0 );
drh40aced52016-01-22 17:48:09 +0000100 sqlite3TokenInit(&s, (char*)zC);
dan80103fc2015-03-20 08:43:59 +0000101 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
drh0a8a4062012-12-07 18:38:16 +0000102}
103
104/*
drh0b8d2552015-09-05 22:36:07 +0000105** Skip over any TK_COLLATE operators and any unlikely()
drha4c3c872013-09-12 17:29:25 +0000106** or likelihood() function at the root of an expression.
drh0a8a4062012-12-07 18:38:16 +0000107*/
108Expr *sqlite3ExprSkipCollate(Expr *pExpr){
drha4c3c872013-09-12 17:29:25 +0000109 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
110 if( ExprHasProperty(pExpr, EP_Unlikely) ){
drh3b3c86a2018-09-18 21:35:31 +0000111 assert( pExpr->eX==EX_List );
drhcca9f3d2013-09-06 15:23:29 +0000112 assert( pExpr->x.pList->nExpr>0 );
drha4c3c872013-09-12 17:29:25 +0000113 assert( pExpr->op==TK_FUNCTION );
drhcca9f3d2013-09-06 15:23:29 +0000114 pExpr = pExpr->x.pList->a[0].pExpr;
115 }else{
drh0b8d2552015-09-05 22:36:07 +0000116 assert( pExpr->op==TK_COLLATE );
drha4c3c872013-09-12 17:29:25 +0000117 pExpr = pExpr->pLeft;
drhcca9f3d2013-09-06 15:23:29 +0000118 }
drha4c3c872013-09-12 17:29:25 +0000119 }
drh0a8a4062012-12-07 18:38:16 +0000120 return pExpr;
drh8b4c40d2007-02-01 23:02:45 +0000121}
122
123/*
drhae80dde2012-12-06 21:16:43 +0000124** Return the collation sequence for the expression pExpr. If
125** there is no defined collating sequence, return NULL.
126**
drh70efa842017-09-28 01:58:23 +0000127** See also: sqlite3ExprNNCollSeq()
128**
129** The sqlite3ExprNNCollSeq() works the same exact that it returns the
130** default collation if pExpr has no defined collation.
131**
drhae80dde2012-12-06 21:16:43 +0000132** The collating sequence might be determined by a COLLATE operator
133** or by the presence of a column with a defined collating sequence.
134** COLLATE operators take first precedence. Left operands take
135** precedence over right operands.
danielk19770202b292004-06-09 09:55:16 +0000136*/
danielk19777cedc8d2004-06-10 10:50:08 +0000137CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000138 sqlite3 *db = pParse->db;
danielk19777cedc8d2004-06-10 10:50:08 +0000139 CollSeq *pColl = 0;
drh7d10d5a2008-08-20 16:35:10 +0000140 Expr *p = pExpr;
drh261d8a52012-12-08 21:36:26 +0000141 while( p ){
drhae80dde2012-12-06 21:16:43 +0000142 int op = p->op;
drhfbb24d12014-03-20 17:03:30 +0000143 if( p->flags & EP_Generic ) break;
drha58d4a92015-01-27 13:17:05 +0000144 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
drhae80dde2012-12-06 21:16:43 +0000145 || op==TK_REGISTER || op==TK_TRIGGER)
drha58d4a92015-01-27 13:17:05 +0000146 && p->pTab!=0
drhae80dde2012-12-06 21:16:43 +0000147 ){
drh7d10d5a2008-08-20 16:35:10 +0000148 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
149 ** a TK_COLUMN but was previously evaluated and cached in a register */
drh7d10d5a2008-08-20 16:35:10 +0000150 int j = p->iColumn;
151 if( j>=0 ){
drhae80dde2012-12-06 21:16:43 +0000152 const char *zColl = p->pTab->aCol[j].zColl;
drhc4a64fa2009-05-11 20:53:28 +0000153 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh7d10d5a2008-08-20 16:35:10 +0000154 }
155 break;
danielk19770202b292004-06-09 09:55:16 +0000156 }
drhe081d732018-07-27 18:19:12 +0000157 if( op==TK_CAST || op==TK_UPLUS ){
158 p = p->pLeft;
159 continue;
160 }
161 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
162 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
163 break;
164 }
drhae80dde2012-12-06 21:16:43 +0000165 if( p->flags & EP_Collate ){
drh2308ed32015-02-09 16:09:34 +0000166 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
drhae80dde2012-12-06 21:16:43 +0000167 p = p->pLeft;
168 }else{
drh3d6bedf2018-09-19 14:54:38 +0000169 Expr *pNext = 0;
drh6728cd92015-02-09 18:28:03 +0000170 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
171 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
172 ** least one EP_Collate. Thus the following two ALWAYS. */
drh3b3c86a2018-09-18 21:35:31 +0000173 if( p->eX==EX_List ){
drh2308ed32015-02-09 16:09:34 +0000174 int i;
drh6728cd92015-02-09 18:28:03 +0000175 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
drh2308ed32015-02-09 16:09:34 +0000176 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
177 pNext = p->x.pList->a[i].pExpr;
178 break;
179 }
180 }
drh3d6bedf2018-09-19 14:54:38 +0000181 }else if( p->eX==EX_Right ){
182 pNext = p->x.pRight;
drh2308ed32015-02-09 16:09:34 +0000183 }
184 p = pNext;
drhae80dde2012-12-06 21:16:43 +0000185 }
186 }else{
drh7d10d5a2008-08-20 16:35:10 +0000187 break;
188 }
danielk19770202b292004-06-09 09:55:16 +0000189 }
danielk19777cedc8d2004-06-10 10:50:08 +0000190 if( sqlite3CheckCollSeq(pParse, pColl) ){
191 pColl = 0;
192 }
193 return pColl;
danielk19770202b292004-06-09 09:55:16 +0000194}
195
196/*
drh70efa842017-09-28 01:58:23 +0000197** Return the collation sequence for the expression pExpr. If
198** there is no defined collating sequence, return a pointer to the
199** defautl collation sequence.
200**
201** See also: sqlite3ExprCollSeq()
202**
203** The sqlite3ExprCollSeq() routine works the same except that it
204** returns NULL if there is no defined collation.
205*/
206CollSeq *sqlite3ExprNNCollSeq(Parse *pParse, Expr *pExpr){
207 CollSeq *p = sqlite3ExprCollSeq(pParse, pExpr);
208 if( p==0 ) p = pParse->db->pDfltColl;
209 assert( p!=0 );
210 return p;
211}
212
213/*
214** Return TRUE if the two expressions have equivalent collating sequences.
215*/
216int sqlite3ExprCollSeqMatch(Parse *pParse, Expr *pE1, Expr *pE2){
217 CollSeq *pColl1 = sqlite3ExprNNCollSeq(pParse, pE1);
218 CollSeq *pColl2 = sqlite3ExprNNCollSeq(pParse, pE2);
219 return sqlite3StrICmp(pColl1->zName, pColl2->zName)==0;
220}
221
222/*
drh626a8792005-01-17 22:08:19 +0000223** pExpr is an operand of a comparison operator. aff2 is the
224** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +0000225** type affinity that should be used for the comparison operator.
226*/
danielk1977e014a832004-05-17 10:48:57 +0000227char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +0000228 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +0000229 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +0000230 /* Both sides of the comparison are columns. If one has numeric
231 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +0000232 */
drh8a512562005-11-14 22:29:05 +0000233 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +0000234 return SQLITE_AFF_NUMERIC;
235 }else{
drh05883a32015-06-02 15:32:08 +0000236 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000237 }
238 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +0000239 /* Neither side of the comparison is a column. Compare the
240 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +0000241 */
drh05883a32015-06-02 15:32:08 +0000242 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000243 }else{
244 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +0000245 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +0000246 return (aff1 + aff2);
247 }
248}
249
drh53db1452004-05-20 13:54:53 +0000250/*
251** pExpr is a comparison operator. Return the type affinity that should
252** be applied to both operands prior to doing the comparison.
253*/
danielk1977e014a832004-05-17 10:48:57 +0000254static char comparisonAffinity(Expr *pExpr){
255 char aff;
256 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
257 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
drh6a2fe092009-09-23 02:29:36 +0000258 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
danielk1977e014a832004-05-17 10:48:57 +0000259 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000260 aff = sqlite3ExprAffinity(pExpr->pLeft);
drh3d6bedf2018-09-19 14:54:38 +0000261 if( pExpr->eX==EX_Right ){
262 aff = sqlite3CompareAffinity(pExpr->x.pRight, aff);
drh3b3c86a2018-09-18 21:35:31 +0000263 }else if( pExpr->eX==EX_Select ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000264 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
drh13ac46e2017-02-11 13:51:23 +0000265 }else if( aff==0 ){
drh05883a32015-06-02 15:32:08 +0000266 aff = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000267 }
268 return aff;
269}
270
271/*
272** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
273** idx_affinity is the affinity of an indexed column. Return true
274** if the index with affinity idx_affinity may be used to implement
275** the comparison in pExpr.
276*/
277int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
278 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000279 switch( aff ){
drh05883a32015-06-02 15:32:08 +0000280 case SQLITE_AFF_BLOB:
drh8a512562005-11-14 22:29:05 +0000281 return 1;
282 case SQLITE_AFF_TEXT:
283 return idx_affinity==SQLITE_AFF_TEXT;
284 default:
285 return sqlite3IsNumericAffinity(idx_affinity);
286 }
danielk1977e014a832004-05-17 10:48:57 +0000287}
288
danielk1977a37cdde2004-05-16 11:15:36 +0000289/*
drh35573352008-01-08 23:54:25 +0000290** Return the P5 value that should be used for a binary comparison
danielk1977a37cdde2004-05-16 11:15:36 +0000291** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
danielk1977a37cdde2004-05-16 11:15:36 +0000292*/
drh35573352008-01-08 23:54:25 +0000293static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
294 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
drh1bd10f82008-12-10 21:19:56 +0000295 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
drh35573352008-01-08 23:54:25 +0000296 return aff;
danielk1977a37cdde2004-05-16 11:15:36 +0000297}
298
drha2e00042002-01-22 03:13:42 +0000299/*
danielk19770202b292004-06-09 09:55:16 +0000300** Return a pointer to the collation sequence that should be used by
301** a binary comparison operator comparing pLeft and pRight.
302**
303** If the left hand expression has a collating sequence type, then it is
304** used. Otherwise the collation sequence for the right hand expression
305** is used, or the default (BINARY) if neither expression has a collating
306** type.
danielk1977bcbb04e2007-05-29 12:11:29 +0000307**
308** Argument pRight (but not pLeft) may be a null pointer. In this case,
309** it is not considered.
drh3d6bedf2018-09-19 14:54:38 +0000310**
311** The second form (sqlite3BinaryExprCollSeq()) uses the Expr.pLeft
312** and Expr.x.pRight pointer from the second argument instead of separate
313** pointers.
danielk19770202b292004-06-09 09:55:16 +0000314*/
drh3d6bedf2018-09-19 14:54:38 +0000315CollSeq *sqlite3ComparisonCollSeq(
danielk1977bcbb04e2007-05-29 12:11:29 +0000316 Parse *pParse,
317 Expr *pLeft,
318 Expr *pRight
319){
drhec41dda2007-02-07 13:09:45 +0000320 CollSeq *pColl;
321 assert( pLeft );
drhae80dde2012-12-06 21:16:43 +0000322 if( pLeft->flags & EP_Collate ){
323 pColl = sqlite3ExprCollSeq(pParse, pLeft);
324 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
325 pColl = sqlite3ExprCollSeq(pParse, pRight);
drhec41dda2007-02-07 13:09:45 +0000326 }else{
327 pColl = sqlite3ExprCollSeq(pParse, pLeft);
328 if( !pColl ){
329 pColl = sqlite3ExprCollSeq(pParse, pRight);
330 }
danielk19770202b292004-06-09 09:55:16 +0000331 }
332 return pColl;
333}
drh3d6bedf2018-09-19 14:54:38 +0000334CollSeq *sqlite3ComparisonExprCollSeq(Parse *pParse, Expr *pExpr){
335 if( pExpr->eX==EX_Right ){
336 return sqlite3ComparisonCollSeq(pParse, pExpr->pLeft, pExpr->x.pRight);
337 }else{
338 return sqlite3ComparisonCollSeq(pParse, pExpr->pLeft, 0);
339 }
340}
danielk19770202b292004-06-09 09:55:16 +0000341
342/*
drhbe5c89a2004-07-26 00:31:09 +0000343** Generate code for a comparison operator.
344*/
345static int codeCompare(
346 Parse *pParse, /* The parsing (and code generating) context */
347 Expr *pLeft, /* The left operand */
348 Expr *pRight, /* The right operand */
349 int opcode, /* The comparison opcode */
drh35573352008-01-08 23:54:25 +0000350 int in1, int in2, /* Register holding operands */
drhbe5c89a2004-07-26 00:31:09 +0000351 int dest, /* Jump here if true. */
352 int jumpIfNull /* If true, jump if either operand is NULL */
353){
drh35573352008-01-08 23:54:25 +0000354 int p5;
355 int addr;
356 CollSeq *p4;
357
drh3d6bedf2018-09-19 14:54:38 +0000358 p4 = sqlite3ComparisonCollSeq(pParse, pLeft, pRight);
drh35573352008-01-08 23:54:25 +0000359 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
360 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
361 (void*)p4, P4_COLLSEQ);
drh1bd10f82008-12-10 21:19:56 +0000362 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
drh35573352008-01-08 23:54:25 +0000363 return addr;
drhbe5c89a2004-07-26 00:31:09 +0000364}
365
dancfbb5e82016-07-13 19:48:13 +0000366/*
dan870a0702016-08-01 16:37:43 +0000367** Return true if expression pExpr is a vector, or false otherwise.
drhd832da72016-08-20 21:11:25 +0000368**
369** A vector is defined as any expression that results in two or more
370** columns of result. Every TK_VECTOR node is an vector because the
371** parser will not generate a TK_VECTOR with fewer than two entries.
372** But a TK_SELECT might be either a vector or a scalar. It is only
373** considered a vector if it has two or more result columns.
dan870a0702016-08-01 16:37:43 +0000374*/
375int sqlite3ExprIsVector(Expr *pExpr){
drh76dbe7a2016-08-20 21:02:38 +0000376 return sqlite3ExprVectorSize(pExpr)>1;
dan870a0702016-08-01 16:37:43 +0000377}
378
379/*
dancfbb5e82016-07-13 19:48:13 +0000380** If the expression passed as the only argument is of type TK_VECTOR
381** return the number of expressions in the vector. Or, if the expression
382** is a sub-select, return the number of columns in the sub-select. For
383** any other type of expression, return 1.
384*/
dan71c57db2016-07-09 20:23:55 +0000385int sqlite3ExprVectorSize(Expr *pExpr){
drh12abf402016-08-22 14:30:05 +0000386 u8 op = pExpr->op;
387 if( op==TK_REGISTER ) op = pExpr->op2;
388 if( op==TK_VECTOR ){
drh76dbe7a2016-08-20 21:02:38 +0000389 return pExpr->x.pList->nExpr;
drh12abf402016-08-22 14:30:05 +0000390 }else if( op==TK_SELECT ){
dan71c57db2016-07-09 20:23:55 +0000391 return pExpr->x.pSelect->pEList->nExpr;
drh76dbe7a2016-08-20 21:02:38 +0000392 }else{
393 return 1;
dan71c57db2016-07-09 20:23:55 +0000394 }
dan71c57db2016-07-09 20:23:55 +0000395}
396
danba00e302016-07-23 20:24:06 +0000397/*
drhfc7f27b2016-08-20 00:07:01 +0000398** Return a pointer to a subexpression of pVector that is the i-th
399** column of the vector (numbered starting with 0). The caller must
400** ensure that i is within range.
401**
drh76dbe7a2016-08-20 21:02:38 +0000402** If pVector is really a scalar (and "scalar" here includes subqueries
403** that return a single column!) then return pVector unmodified.
404**
drhfc7f27b2016-08-20 00:07:01 +0000405** pVector retains ownership of the returned subexpression.
406**
407** If the vector is a (SELECT ...) then the expression returned is
drh76dbe7a2016-08-20 21:02:38 +0000408** just the expression for the i-th term of the result set, and may
409** not be ready for evaluation because the table cursor has not yet
410** been positioned.
danba00e302016-07-23 20:24:06 +0000411*/
drhfc7f27b2016-08-20 00:07:01 +0000412Expr *sqlite3VectorFieldSubexpr(Expr *pVector, int i){
dan870a0702016-08-01 16:37:43 +0000413 assert( i<sqlite3ExprVectorSize(pVector) );
414 if( sqlite3ExprIsVector(pVector) ){
drh9f24b532016-09-05 22:50:48 +0000415 assert( pVector->op2==0 || pVector->op==TK_REGISTER );
416 if( pVector->op==TK_SELECT || pVector->op2==TK_SELECT ){
dan870a0702016-08-01 16:37:43 +0000417 return pVector->x.pSelect->pEList->a[i].pExpr;
418 }else{
419 return pVector->x.pList->a[i].pExpr;
420 }
dan71c57db2016-07-09 20:23:55 +0000421 }
dan870a0702016-08-01 16:37:43 +0000422 return pVector;
dan71c57db2016-07-09 20:23:55 +0000423}
drhfc7f27b2016-08-20 00:07:01 +0000424
drhfc7f27b2016-08-20 00:07:01 +0000425/*
426** Compute and return a new Expr object which when passed to
427** sqlite3ExprCode() will generate all necessary code to compute
428** the iField-th column of the vector expression pVector.
429**
drh8762ec12016-08-20 01:06:22 +0000430** It is ok for pVector to be a scalar (as long as iField==0).
431** In that case, this routine works like sqlite3ExprDup().
432**
drhfc7f27b2016-08-20 00:07:01 +0000433** The caller owns the returned Expr object and is responsible for
434** ensuring that the returned value eventually gets freed.
435**
drh8762ec12016-08-20 01:06:22 +0000436** The caller retains ownership of pVector. If pVector is a TK_SELECT,
danfad0e702016-09-06 12:04:50 +0000437** then the returned object will reference pVector and so pVector must remain
drh8762ec12016-08-20 01:06:22 +0000438** valid for the life of the returned object. If pVector is a TK_VECTOR
439** or a scalar expression, then it can be deleted as soon as this routine
drh76dbe7a2016-08-20 21:02:38 +0000440** returns.
drh8762ec12016-08-20 01:06:22 +0000441**
442** A trick to cause a TK_SELECT pVector to be deleted together with
443** the returned Expr object is to attach the pVector to the pRight field
444** of the returned TK_SELECT_COLUMN Expr object.
drhfc7f27b2016-08-20 00:07:01 +0000445*/
446Expr *sqlite3ExprForVectorField(
447 Parse *pParse, /* Parsing context */
448 Expr *pVector, /* The vector. List of expressions or a sub-SELECT */
drha1251bc2016-08-20 00:51:37 +0000449 int iField /* Which column of the vector to return */
drhfc7f27b2016-08-20 00:07:01 +0000450){
451 Expr *pRet;
drha1251bc2016-08-20 00:51:37 +0000452 if( pVector->op==TK_SELECT ){
drh3b3c86a2018-09-18 21:35:31 +0000453 assert( pVector->eX==EX_Select );
drhfc7f27b2016-08-20 00:07:01 +0000454 /* The TK_SELECT_COLUMN Expr node:
455 **
drh966e2912017-01-03 02:58:01 +0000456 ** pLeft: pVector containing TK_SELECT. Not deleted.
drh8762ec12016-08-20 01:06:22 +0000457 ** pRight: not used. But recursively deleted.
drhfc7f27b2016-08-20 00:07:01 +0000458 ** iColumn: Index of a column in pVector
drh966e2912017-01-03 02:58:01 +0000459 ** iTable: 0 or the number of columns on the LHS of an assignment
drhfc7f27b2016-08-20 00:07:01 +0000460 ** pLeft->iTable: First in an array of register holding result, or 0
461 ** if the result is not yet computed.
462 **
463 ** sqlite3ExprDelete() specifically skips the recursive delete of
464 ** pLeft on TK_SELECT_COLUMN nodes. But pRight is followed, so pVector
drh8762ec12016-08-20 01:06:22 +0000465 ** can be attached to pRight to cause this node to take ownership of
466 ** pVector. Typically there will be multiple TK_SELECT_COLUMN nodes
467 ** with the same pLeft pointer to the pVector, but only one of them
468 ** will own the pVector.
drhfc7f27b2016-08-20 00:07:01 +0000469 */
drhabfd35e2016-12-06 22:47:23 +0000470 pRet = sqlite3PExpr(pParse, TK_SELECT_COLUMN, 0, 0);
drh8bd0d582016-08-20 18:06:14 +0000471 if( pRet ){
472 pRet->iColumn = iField;
473 pRet->pLeft = pVector;
474 }
drhfc7f27b2016-08-20 00:07:01 +0000475 assert( pRet==0 || pRet->iTable==0 );
476 }else{
drha1251bc2016-08-20 00:51:37 +0000477 if( pVector->op==TK_VECTOR ) pVector = pVector->x.pList->a[iField].pExpr;
478 pRet = sqlite3ExprDup(pParse->db, pVector, 0);
drhfc7f27b2016-08-20 00:07:01 +0000479 }
480 return pRet;
481}
dan71c57db2016-07-09 20:23:55 +0000482
dan5c288b92016-07-30 21:02:33 +0000483/*
484** If expression pExpr is of type TK_SELECT, generate code to evaluate
485** it. Return the register in which the result is stored (or, if the
486** sub-select returns more than one column, the first in an array
487** of registers in which the result is stored).
488**
489** If pExpr is not a TK_SELECT expression, return 0.
490*/
491static int exprCodeSubselect(Parse *pParse, Expr *pExpr){
dan8da209b2016-07-26 18:06:08 +0000492 int reg = 0;
danf9b2e052016-08-02 17:45:00 +0000493#ifndef SQLITE_OMIT_SUBQUERY
dan5c288b92016-07-30 21:02:33 +0000494 if( pExpr->op==TK_SELECT ){
495 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
dan8da209b2016-07-26 18:06:08 +0000496 }
danf9b2e052016-08-02 17:45:00 +0000497#endif
dan8da209b2016-07-26 18:06:08 +0000498 return reg;
499}
500
dan5c288b92016-07-30 21:02:33 +0000501/*
502** Argument pVector points to a vector expression - either a TK_VECTOR
dan870a0702016-08-01 16:37:43 +0000503** or TK_SELECT that returns more than one column. This function returns
504** the register number of a register that contains the value of
505** element iField of the vector.
506**
507** If pVector is a TK_SELECT expression, then code for it must have
508** already been generated using the exprCodeSubselect() routine. In this
509** case parameter regSelect should be the first in an array of registers
510** containing the results of the sub-select.
511**
512** If pVector is of type TK_VECTOR, then code for the requested field
513** is generated. In this case (*pRegFree) may be set to the number of
514** a temporary register to be freed by the caller before returning.
dan5c288b92016-07-30 21:02:33 +0000515**
516** Before returning, output parameter (*ppExpr) is set to point to the
517** Expr object corresponding to element iElem of the vector.
dan5c288b92016-07-30 21:02:33 +0000518*/
519static int exprVectorRegister(
520 Parse *pParse, /* Parse context */
521 Expr *pVector, /* Vector to extract element from */
dan870a0702016-08-01 16:37:43 +0000522 int iField, /* Field to extract from pVector */
dan5c288b92016-07-30 21:02:33 +0000523 int regSelect, /* First in array of registers */
524 Expr **ppExpr, /* OUT: Expression element */
525 int *pRegFree /* OUT: Temp register to free */
526){
drh12abf402016-08-22 14:30:05 +0000527 u8 op = pVector->op;
drhc1bcd9c2016-09-05 19:57:46 +0000528 assert( op==TK_VECTOR || op==TK_REGISTER || op==TK_SELECT );
drh12abf402016-08-22 14:30:05 +0000529 if( op==TK_REGISTER ){
530 *ppExpr = sqlite3VectorFieldSubexpr(pVector, iField);
531 return pVector->iTable+iField;
532 }
533 if( op==TK_SELECT ){
dan870a0702016-08-01 16:37:43 +0000534 *ppExpr = pVector->x.pSelect->pEList->a[iField].pExpr;
535 return regSelect+iField;
dan5c288b92016-07-30 21:02:33 +0000536 }
dan870a0702016-08-01 16:37:43 +0000537 *ppExpr = pVector->x.pList->a[iField].pExpr;
dan5c288b92016-07-30 21:02:33 +0000538 return sqlite3ExprCodeTemp(pParse, *ppExpr, pRegFree);
539}
540
541/*
542** Expression pExpr is a comparison between two vector values. Compute
drh79752b62016-08-13 10:02:17 +0000543** the result of the comparison (1, 0, or NULL) and write that
544** result into register dest.
545**
546** The caller must satisfy the following preconditions:
547**
548** if pExpr->op==TK_IS: op==TK_EQ and p5==SQLITE_NULLEQ
549** if pExpr->op==TK_ISNOT: op==TK_NE and p5==SQLITE_NULLEQ
550** otherwise: op==pExpr->op and p5==0
dan5c288b92016-07-30 21:02:33 +0000551*/
drh79752b62016-08-13 10:02:17 +0000552static void codeVectorCompare(
553 Parse *pParse, /* Code generator context */
554 Expr *pExpr, /* The comparison operation */
555 int dest, /* Write results into this register */
556 u8 op, /* Comparison operator */
557 u8 p5 /* SQLITE_NULLEQ or zero */
558){
dan71c57db2016-07-09 20:23:55 +0000559 Vdbe *v = pParse->pVdbe;
560 Expr *pLeft = pExpr->pLeft;
drh3d6bedf2018-09-19 14:54:38 +0000561 Expr *pRight = pExpr->x.pRight;
dan71c57db2016-07-09 20:23:55 +0000562 int nLeft = sqlite3ExprVectorSize(pLeft);
drhb29e60c2016-09-05 12:02:34 +0000563 int i;
564 int regLeft = 0;
565 int regRight = 0;
566 u8 opx = op;
567 int addrDone = sqlite3VdbeMakeLabel(v);
dan71c57db2016-07-09 20:23:55 +0000568
drh245ce622017-01-01 12:44:07 +0000569 if( nLeft!=sqlite3ExprVectorSize(pRight) ){
570 sqlite3ErrorMsg(pParse, "row value misused");
571 return;
572 }
drhb29e60c2016-09-05 12:02:34 +0000573 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
574 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
575 || pExpr->op==TK_LT || pExpr->op==TK_GT
576 || pExpr->op==TK_LE || pExpr->op==TK_GE
577 );
578 assert( pExpr->op==op || (pExpr->op==TK_IS && op==TK_EQ)
579 || (pExpr->op==TK_ISNOT && op==TK_NE) );
580 assert( p5==0 || pExpr->op!=op );
581 assert( p5==SQLITE_NULLEQ || pExpr->op==op );
dan71c57db2016-07-09 20:23:55 +0000582
drhb29e60c2016-09-05 12:02:34 +0000583 p5 |= SQLITE_STOREP2;
584 if( opx==TK_LE ) opx = TK_LT;
585 if( opx==TK_GE ) opx = TK_GT;
dan71c57db2016-07-09 20:23:55 +0000586
drhb29e60c2016-09-05 12:02:34 +0000587 regLeft = exprCodeSubselect(pParse, pLeft);
588 regRight = exprCodeSubselect(pParse, pRight);
dan71c57db2016-07-09 20:23:55 +0000589
drhb29e60c2016-09-05 12:02:34 +0000590 for(i=0; 1 /*Loop exits by "break"*/; i++){
591 int regFree1 = 0, regFree2 = 0;
592 Expr *pL, *pR;
593 int r1, r2;
594 assert( i>=0 && i<nLeft );
drhb29e60c2016-09-05 12:02:34 +0000595 r1 = exprVectorRegister(pParse, pLeft, i, regLeft, &pL, &regFree1);
596 r2 = exprVectorRegister(pParse, pRight, i, regRight, &pR, &regFree2);
597 codeCompare(pParse, pL, pR, opx, r1, r2, dest, p5);
598 testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
599 testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
600 testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
601 testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
602 testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
603 testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
604 sqlite3ReleaseTempReg(pParse, regFree1);
605 sqlite3ReleaseTempReg(pParse, regFree2);
drhb29e60c2016-09-05 12:02:34 +0000606 if( i==nLeft-1 ){
607 break;
dan71c57db2016-07-09 20:23:55 +0000608 }
drhb29e60c2016-09-05 12:02:34 +0000609 if( opx==TK_EQ ){
610 sqlite3VdbeAddOp2(v, OP_IfNot, dest, addrDone); VdbeCoverage(v);
611 p5 |= SQLITE_KEEPNULL;
612 }else if( opx==TK_NE ){
613 sqlite3VdbeAddOp2(v, OP_If, dest, addrDone); VdbeCoverage(v);
614 p5 |= SQLITE_KEEPNULL;
615 }else{
616 assert( op==TK_LT || op==TK_GT || op==TK_LE || op==TK_GE );
617 sqlite3VdbeAddOp2(v, OP_ElseNotEq, 0, addrDone);
618 VdbeCoverageIf(v, op==TK_LT);
619 VdbeCoverageIf(v, op==TK_GT);
620 VdbeCoverageIf(v, op==TK_LE);
621 VdbeCoverageIf(v, op==TK_GE);
622 if( i==nLeft-2 ) opx = op;
623 }
dan71c57db2016-07-09 20:23:55 +0000624 }
drhb29e60c2016-09-05 12:02:34 +0000625 sqlite3VdbeResolveLabel(v, addrDone);
dan71c57db2016-07-09 20:23:55 +0000626}
627
danielk19774b5255a2008-06-05 16:47:39 +0000628#if SQLITE_MAX_EXPR_DEPTH>0
629/*
630** Check that argument nHeight is less than or equal to the maximum
631** expression depth allowed. If it is not, leave an error message in
632** pParse.
633*/
drh7d10d5a2008-08-20 16:35:10 +0000634int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000635 int rc = SQLITE_OK;
636 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
637 if( nHeight>mxHeight ){
638 sqlite3ErrorMsg(pParse,
639 "Expression tree is too large (maximum depth %d)", mxHeight
640 );
641 rc = SQLITE_ERROR;
642 }
643 return rc;
644}
645
646/* The following three functions, heightOfExpr(), heightOfExprList()
647** and heightOfSelect(), are used to determine the maximum height
648** of any expression tree referenced by the structure passed as the
649** first argument.
650**
651** If this maximum height is greater than the current value pointed
652** to by pnHeight, the second parameter, then set *pnHeight to that
653** value.
654*/
655static void heightOfExpr(Expr *p, int *pnHeight){
656 if( p ){
657 if( p->nHeight>*pnHeight ){
658 *pnHeight = p->nHeight;
659 }
660 }
661}
662static void heightOfExprList(ExprList *p, int *pnHeight){
663 if( p ){
664 int i;
665 for(i=0; i<p->nExpr; i++){
666 heightOfExpr(p->a[i].pExpr, pnHeight);
667 }
668 }
669}
dan1a3a3082018-01-18 19:00:54 +0000670static void heightOfSelect(Select *pSelect, int *pnHeight){
671 Select *p;
672 for(p=pSelect; p; p=p->pPrior){
danielk19774b5255a2008-06-05 16:47:39 +0000673 heightOfExpr(p->pWhere, pnHeight);
674 heightOfExpr(p->pHaving, pnHeight);
675 heightOfExpr(p->pLimit, pnHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000676 heightOfExprList(p->pEList, pnHeight);
677 heightOfExprList(p->pGroupBy, pnHeight);
678 heightOfExprList(p->pOrderBy, pnHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000679 }
680}
681
682/*
683** Set the Expr.nHeight variable in the structure passed as an
684** argument. An expression with no children, Expr.pList or
685** Expr.pSelect member has a height of 1. Any other expression
686** has a height equal to the maximum height of any other
687** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000688**
689** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
690** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000691*/
692static void exprSetHeight(Expr *p){
693 int nHeight = 0;
694 heightOfExpr(p->pLeft, &nHeight);
drh3d6bedf2018-09-19 14:54:38 +0000695 switch( p->eX ){
696 case EX_Select: {
697 heightOfSelect(p->x.pSelect, &nHeight);
698 break;
699 }
700 case EX_List: {
701 heightOfExprList(p->x.pList, &nHeight);
702 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
703 break;
704 }
705 case EX_Right: {
706 heightOfExpr(p->x.pRight, &nHeight);
707 break;
708 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000709 }
danielk19774b5255a2008-06-05 16:47:39 +0000710 p->nHeight = nHeight + 1;
711}
712
713/*
714** Set the Expr.nHeight variable using the exprSetHeight() function. If
715** the height is greater than the maximum allowed expression depth,
716** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000717**
718** Also propagate all EP_Propagate flags from the Expr.x.pList into
719** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000720*/
drh2308ed32015-02-09 16:09:34 +0000721void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh3b3c86a2018-09-18 21:35:31 +0000722 if( p==0 || pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000723 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000724 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000725}
726
727/*
728** Return the maximum height of any expression tree referenced
729** by the select statement passed as an argument.
730*/
731int sqlite3SelectExprHeight(Select *p){
732 int nHeight = 0;
733 heightOfSelect(p, &nHeight);
734 return nHeight;
735}
drh2308ed32015-02-09 16:09:34 +0000736#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
737/*
738** Propagate all EP_Propagate flags from the Expr.x.pList into
739** Expr.flags.
740*/
741void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh3b3c86a2018-09-18 21:35:31 +0000742 if( p && p->eX==EX_List ){
drh2308ed32015-02-09 16:09:34 +0000743 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
744 }
745}
746#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000747#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
748
drhbe5c89a2004-07-26 00:31:09 +0000749/*
drhb7916a72009-05-27 10:31:29 +0000750** This routine is the core allocator for Expr nodes.
751**
drha76b5df2002-02-23 02:32:10 +0000752** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000753** for this node and for the pToken argument is a single allocation
754** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000755** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000756**
757** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000758** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000759** parameter is ignored if pToken is NULL or if the token does not
760** appear to be quoted. If the quotes were of the form "..." (double-quotes)
761** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000762**
763** Special case: If op==TK_INTEGER and pToken points to a string that
764** can be translated into a 32-bit integer, then the token is not
765** stored in u.zToken. Instead, the integer values is written
766** into u.iValue and the EP_IntValue flag is set. No extra storage
767** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000768*/
drhb7916a72009-05-27 10:31:29 +0000769Expr *sqlite3ExprAlloc(
drhcca8a4a2016-10-03 12:56:48 +0000770 sqlite3 *db, /* Handle for sqlite3DbMallocRawNN() */
drh17435752007-08-16 04:30:38 +0000771 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000772 const Token *pToken, /* Token argument. Might be NULL */
773 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000774){
drha76b5df2002-02-23 02:32:10 +0000775 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000776 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000777 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000778
drh575fad62016-02-05 13:38:36 +0000779 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000780 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000781 if( op!=TK_INTEGER || pToken->z==0
782 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
783 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000784 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000785 }
drhb7916a72009-05-27 10:31:29 +0000786 }
drh575fad62016-02-05 13:38:36 +0000787 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000788 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000789 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000790 pNew->op = (u8)op;
791 pNew->iAgg = -1;
792 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000793 if( nExtra==0 ){
drhb98a2e32017-07-07 12:43:57 +0000794 pNew->flags |= EP_IntValue|EP_Leaf;
drh33e619f2009-05-28 01:00:55 +0000795 pNew->u.iValue = iValue;
796 }else{
drh33e619f2009-05-28 01:00:55 +0000797 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000798 assert( pToken->z!=0 || pToken->n==0 );
799 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000800 pNew->u.zToken[pToken->n] = 0;
drh244b9d62016-04-11 19:01:08 +0000801 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
802 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
drh33e619f2009-05-28 01:00:55 +0000803 sqlite3Dequote(pNew->u.zToken);
drh33e619f2009-05-28 01:00:55 +0000804 }
drhb7916a72009-05-27 10:31:29 +0000805 }
806 }
807#if SQLITE_MAX_EXPR_DEPTH>0
808 pNew->nHeight = 1;
809#endif
810 }
drha76b5df2002-02-23 02:32:10 +0000811 return pNew;
812}
813
814/*
drhb7916a72009-05-27 10:31:29 +0000815** Allocate a new expression node from a zero-terminated token that has
816** already been dequoted.
817*/
818Expr *sqlite3Expr(
819 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
820 int op, /* Expression opcode */
821 const char *zToken /* Token argument. Might be NULL */
822){
823 Token x;
824 x.z = zToken;
drhb40f06c2017-08-21 02:20:57 +0000825 x.n = sqlite3Strlen30(zToken);
drhb7916a72009-05-27 10:31:29 +0000826 return sqlite3ExprAlloc(db, op, &x, 0);
827}
828
829/*
830** Attach subtrees pLeft and pRight to the Expr node pRoot.
831**
832** If pRoot==NULL that means that a memory allocation error has occurred.
833** In that case, delete the subtrees pLeft and pRight.
834*/
835void sqlite3ExprAttachSubtrees(
836 sqlite3 *db,
837 Expr *pRoot,
838 Expr *pLeft,
839 Expr *pRight
840){
841 if( pRoot==0 ){
842 assert( db->mallocFailed );
843 sqlite3ExprDelete(db, pLeft);
844 sqlite3ExprDelete(db, pRight);
845 }else{
846 if( pRight ){
drh3d6bedf2018-09-19 14:54:38 +0000847 assert( pRoot->eX==EX_None );
848 pRoot->x.pRight = pRight;
849 pRoot->eX = EX_Right;
drh885a5b02015-02-09 15:21:36 +0000850 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000851 }
852 if( pLeft ){
853 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000854 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000855 }
856 exprSetHeight(pRoot);
857 }
858}
859
860/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000861** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000862**
drhbf664462009-06-19 18:32:54 +0000863** One or both of the subtrees can be NULL. Return a pointer to the new
864** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
865** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000866*/
drh17435752007-08-16 04:30:38 +0000867Expr *sqlite3PExpr(
868 Parse *pParse, /* Parsing context */
869 int op, /* Expression opcode */
870 Expr *pLeft, /* Left operand */
drhabfd35e2016-12-06 22:47:23 +0000871 Expr *pRight /* Right operand */
drh17435752007-08-16 04:30:38 +0000872){
drh5fb52ca2012-03-31 02:34:35 +0000873 Expr *p;
drh1167d322015-10-28 20:01:45 +0000874 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000875 /* Take advantage of short-circuit false optimization for AND */
876 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
877 }else{
drhabfd35e2016-12-06 22:47:23 +0000878 p = sqlite3DbMallocRawNN(pParse->db, sizeof(Expr));
879 if( p ){
880 memset(p, 0, sizeof(Expr));
881 p->op = op & TKFLG_MASK;
882 p->iAgg = -1;
883 }
drh5fb52ca2012-03-31 02:34:35 +0000884 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
885 }
dan2b359bd2010-10-28 11:31:23 +0000886 if( p ) {
887 sqlite3ExprCheckHeight(pParse, p->nHeight);
888 }
drh4e0cff62004-11-05 05:10:28 +0000889 return p;
890}
891
892/*
drh08de4f72016-04-11 01:06:47 +0000893** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
894** do a memory allocation failure) then delete the pSelect object.
895*/
896void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
drh3b3c86a2018-09-18 21:35:31 +0000897 if( pExpr && pSelect ){
898 assert( pExpr->eX==EX_None );
899 pExpr->eX = EX_Select;
drh08de4f72016-04-11 01:06:47 +0000900 pExpr->x.pSelect = pSelect;
drh3b3c86a2018-09-18 21:35:31 +0000901 ExprSetProperty(pExpr, EP_Subquery);
drh08de4f72016-04-11 01:06:47 +0000902 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
903 }else{
904 assert( pParse->db->mallocFailed );
905 sqlite3SelectDelete(pParse->db, pSelect);
906 }
907}
908
drh3b3c86a2018-09-18 21:35:31 +0000909/*
910** Add ExprList to the Expr.x.pList field. Or, if pExpr is NULL (due
911** do a memory allocation failure) then delete the pSelect object.
912*/
913void sqlite3PExprAddExprList(Parse *pParse, Expr *pExpr, ExprList *pList){
914 if( pExpr && pList ){
915 assert( pExpr->eX==EX_None );
916 pExpr->eX = EX_List;
917 pExpr->x.pList = pList;
918 /* sqlite3ExprSetHeightAndFlags(pParse, pExpr); // done by caller */
919 }else{
920 assert( pParse->db->mallocFailed );
921 sqlite3ExprListDelete(pParse->db, pList);
922 }
923}
924
drh08de4f72016-04-11 01:06:47 +0000925
926/*
drh991a1982014-01-02 17:57:16 +0000927** If the expression is always either TRUE or FALSE (respectively),
928** then return 1. If one cannot determine the truth value of the
929** expression at compile-time return 0.
930**
931** This is an optimization. If is OK to return 0 here even if
932** the expression really is always false or false (a false negative).
933** But it is a bug to return 1 if the expression might have different
934** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000935**
936** Note that if the expression is part of conditional for a
937** LEFT JOIN, then we cannot determine at compile-time whether or not
938** is it true or false, so always return 0.
939*/
drh991a1982014-01-02 17:57:16 +0000940static int exprAlwaysTrue(Expr *p){
941 int v = 0;
942 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
943 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
944 return v!=0;
945}
drh5fb52ca2012-03-31 02:34:35 +0000946static int exprAlwaysFalse(Expr *p){
947 int v = 0;
948 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
949 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
950 return v==0;
951}
952
953/*
drh91bb0ee2004-09-01 03:06:34 +0000954** Join two expressions using an AND operator. If either expression is
955** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000956**
957** If one side or the other of the AND is known to be false, then instead
958** of returning an AND expression, just return a constant expression with
959** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000960*/
danielk19771e536952007-08-16 10:09:01 +0000961Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000962 if( pLeft==0 ){
963 return pRight;
964 }else if( pRight==0 ){
965 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000966 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
967 sqlite3ExprDelete(db, pLeft);
968 sqlite3ExprDelete(db, pRight);
969 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000970 }else{
drhb7916a72009-05-27 10:31:29 +0000971 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
972 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
973 return pNew;
drha76b5df2002-02-23 02:32:10 +0000974 }
975}
976
977/*
978** Construct a new expression node for a function with multiple
979** arguments.
980*/
drh954733b2018-07-27 23:33:16 +0000981Expr *sqlite3ExprFunction(
982 Parse *pParse, /* Parsing context */
983 ExprList *pList, /* Argument list */
984 Token *pToken, /* Name of the function */
985 int eDistinct /* SF_Distinct or SF_ALL or 0 */
986){
drha76b5df2002-02-23 02:32:10 +0000987 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000988 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000989 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000990 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000991 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000992 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000993 return 0;
994 }
drh954733b2018-07-27 23:33:16 +0000995 if( pList && pList->nExpr > pParse->db->aLimit[SQLITE_LIMIT_FUNCTION_ARG] ){
996 sqlite3ErrorMsg(pParse, "too many arguments on function %T", pToken);
997 }
drh3b3c86a2018-09-18 21:35:31 +0000998 assert( pNew->eX==EX_None );
999 if( pList ){
1000 pNew->eX = EX_List;
1001 pNew->x.pList = pList;
1002 }
drhfca23552017-10-28 20:51:54 +00001003 ExprSetProperty(pNew, EP_HasFunc);
drh2308ed32015-02-09 16:09:34 +00001004 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drh954733b2018-07-27 23:33:16 +00001005 if( eDistinct==SF_Distinct ) ExprSetProperty(pNew, EP_Distinct);
drha76b5df2002-02-23 02:32:10 +00001006 return pNew;
1007}
1008
1009/*
drhfa6bc002004-09-07 16:19:52 +00001010** Assign a variable number to an expression that encodes a wildcard
1011** in the original SQL statement.
1012**
1013** Wildcards consisting of a single "?" are assigned the next sequential
1014** variable number.
1015**
1016** Wildcards of the form "?nnn" are assigned the number "nnn". We make
drh9bf755c2016-12-23 03:59:31 +00001017** sure "nnn" is not too big to avoid a denial of service attack when
drhfa6bc002004-09-07 16:19:52 +00001018** the SQL statement comes from an external source.
1019**
drh51f49f12009-05-21 20:41:32 +00001020** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +00001021** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +00001022** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +00001023** assigned.
1024*/
drhde25a882016-10-03 15:28:24 +00001025void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr, u32 n){
drh17435752007-08-16 04:30:38 +00001026 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +00001027 const char *z;
drhf326d662016-12-23 13:30:53 +00001028 ynVar x;
drh17435752007-08-16 04:30:38 +00001029
drhfa6bc002004-09-07 16:19:52 +00001030 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +00001031 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +00001032 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +00001033 assert( z!=0 );
1034 assert( z[0]!=0 );
mistachkinb1ed7172017-04-14 14:50:34 +00001035 assert( n==(u32)sqlite3Strlen30(z) );
drhb7916a72009-05-27 10:31:29 +00001036 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +00001037 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +00001038 assert( z[0]=='?' );
drhf326d662016-12-23 13:30:53 +00001039 x = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +00001040 }else{
drhf326d662016-12-23 13:30:53 +00001041 int doAdd = 0;
drh124c0b42011-06-01 18:15:55 +00001042 if( z[0]=='?' ){
1043 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
1044 ** use it as the variable number */
1045 i64 i;
drh18814df2017-01-31 03:52:34 +00001046 int bOk;
1047 if( n==2 ){ /*OPTIMIZATION-IF-TRUE*/
1048 i = z[1]-'0'; /* The common case of ?N for a single digit N */
1049 bOk = 1;
1050 }else{
1051 bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
1052 }
drh124c0b42011-06-01 18:15:55 +00001053 testcase( i==0 );
1054 testcase( i==1 );
1055 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
1056 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
1057 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
1058 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
1059 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
drhc9b39282016-10-03 16:33:14 +00001060 return;
drhfa6bc002004-09-07 16:19:52 +00001061 }
drh8e74e7b2017-01-31 12:41:48 +00001062 x = (ynVar)i;
drhf326d662016-12-23 13:30:53 +00001063 if( x>pParse->nVar ){
1064 pParse->nVar = (int)x;
1065 doAdd = 1;
1066 }else if( sqlite3VListNumToName(pParse->pVList, x)==0 ){
1067 doAdd = 1;
drh124c0b42011-06-01 18:15:55 +00001068 }
1069 }else{
1070 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
1071 ** number as the prior appearance of the same name, or if the name
1072 ** has never appeared before, reuse the same variable number
1073 */
drh9bf755c2016-12-23 03:59:31 +00001074 x = (ynVar)sqlite3VListNameToNum(pParse->pVList, z, n);
1075 if( x==0 ){
1076 x = (ynVar)(++pParse->nVar);
drhf326d662016-12-23 13:30:53 +00001077 doAdd = 1;
drh124c0b42011-06-01 18:15:55 +00001078 }
drhfa6bc002004-09-07 16:19:52 +00001079 }
drhf326d662016-12-23 13:30:53 +00001080 if( doAdd ){
1081 pParse->pVList = sqlite3VListAdd(db, pParse->pVList, z, n, x);
1082 }
1083 }
1084 pExpr->iColumn = x;
1085 if( x>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +00001086 sqlite3ErrorMsg(pParse, "too many SQL variables");
1087 }
drhfa6bc002004-09-07 16:19:52 +00001088}
1089
1090/*
danf6963f92009-11-23 14:39:14 +00001091** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +00001092*/
drh4f0010b2016-04-11 14:49:39 +00001093static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
1094 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +00001095 /* Sanity check: Assert that the IntValue is non-negative if it exists */
1096 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drh3b3c86a2018-09-18 21:35:31 +00001097 assert( p->eX!=EX_Select || p->x.pSelect!=0 );
1098 assert( p->eX!=EX_List || p->x.pList!=0 );
drh209bc522016-09-23 21:36:24 +00001099#ifdef SQLITE_DEBUG
1100 if( ExprHasProperty(p, EP_Leaf) && !ExprHasProperty(p, EP_TokenOnly) ){
1101 assert( p->pLeft==0 );
drh3b3c86a2018-09-18 21:35:31 +00001102 assert( p->eX==EX_None );
drh209bc522016-09-23 21:36:24 +00001103 }
drh35284b62018-07-28 01:30:43 +00001104 if( !ExprHasProperty(p, EP_TokenOnly) ){
1105 assert( p->op!=TK_FUNCTION || p->pLeft==0 );
drh35284b62018-07-28 01:30:43 +00001106 }
1107 if( !ExprHasProperty(p, (EP_TokenOnly|EP_Reduced)) ){
1108 assert( p->pWin==0 || p->pLeft==0 );
1109 assert( p->pWin==0 || p->pTab==0 );
1110 assert( p->pWin==0 || p->op==TK_FUNCTION );
drh3d6bedf2018-09-19 14:54:38 +00001111 assert( p->pTab==0 || p->eX==EX_None );
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
drhd2687b72005-08-12 22:56:09 +00001143/*
danielk19776ab3a2e2009-02-19 14:39:25 +00001144** Return the number of bytes allocated for the expression structure
1145** passed as the first argument. This is always one of EXPR_FULLSIZE,
1146** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
1147*/
1148static int exprStructSize(Expr *p){
1149 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001150 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
1151 return EXPR_FULLSIZE;
1152}
1153
1154/*
drh33e619f2009-05-28 01:00:55 +00001155** The dupedExpr*Size() routines each return the number of bytes required
1156** to store a copy of an expression or expression tree. They differ in
1157** how much of the tree is measured.
1158**
1159** dupedExprStructSize() Size of only the Expr structure
1160** dupedExprNodeSize() Size of Expr + space for token
1161** dupedExprSize() Expr + token + subtree components
1162**
1163***************************************************************************
1164**
1165** The dupedExprStructSize() function returns two values OR-ed together:
1166** (1) the space required for a copy of the Expr structure only and
1167** (2) the EP_xxx flags that indicate what the structure size should be.
1168** The return values is always one of:
1169**
1170** EXPR_FULLSIZE
1171** EXPR_REDUCEDSIZE | EP_Reduced
1172** EXPR_TOKENONLYSIZE | EP_TokenOnly
1173**
1174** The size of the structure can be found by masking the return value
1175** of this routine with 0xfff. The flags can be found by masking the
1176** return value with EP_Reduced|EP_TokenOnly.
1177**
1178** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
1179** (unreduced) Expr objects as they or originally constructed by the parser.
1180** During expression analysis, extra information is computed and moved into
danc95f38d2018-06-18 20:34:43 +00001181** later parts of the Expr object and that extra information might get chopped
drh33e619f2009-05-28 01:00:55 +00001182** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +00001183** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +00001184** to reduce a pristine expression tree from the parser. The implementation
1185** of dupedExprStructSize() contain multiple assert() statements that attempt
1186** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +00001187*/
1188static int dupedExprStructSize(Expr *p, int flags){
1189 int nSize;
drh33e619f2009-05-28 01:00:55 +00001190 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +00001191 assert( EXPR_FULLSIZE<=0xfff );
1192 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
dan67a9b8e2018-06-22 20:51:35 +00001193 if( 0==flags || p->op==TK_SELECT_COLUMN
1194#ifndef SQLITE_OMIT_WINDOWFUNC
1195 || p->pWin
1196#endif
1197 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00001198 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +00001199 }else{
drhc5cd1242013-09-12 16:50:49 +00001200 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +00001201 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +00001202 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +00001203 assert( !ExprHasProperty(p, EP_NoReduce) );
drh3d6bedf2018-09-19 14:54:38 +00001204 if( p->pLeft || p->eX!=EX_None ){
drh33e619f2009-05-28 01:00:55 +00001205 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
1206 }else{
1207 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
1208 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001209 }
1210 return nSize;
1211}
1212
1213/*
drh33e619f2009-05-28 01:00:55 +00001214** This function returns the space in bytes required to store the copy
1215** of the Expr structure and a copy of the Expr.u.zToken string (if that
1216** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +00001217*/
1218static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +00001219 int nByte = dupedExprStructSize(p, flags) & 0xfff;
1220 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1221 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001222 }
danielk1977bc739712009-03-23 04:33:32 +00001223 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +00001224}
1225
1226/*
1227** Return the number of bytes required to create a duplicate of the
1228** expression passed as the first argument. The second argument is a
1229** mask containing EXPRDUP_XXX flags.
1230**
1231** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +00001232** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +00001233**
1234** If the EXPRDUP_REDUCE flag is set, then the return value includes
1235** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
1236** and Expr.pRight variables (but not for any structures pointed to or
1237** descended from the Expr.x.pList or Expr.x.pSelect variables).
1238*/
1239static int dupedExprSize(Expr *p, int flags){
1240 int nByte = 0;
1241 if( p ){
1242 nByte = dupedExprNodeSize(p, flags);
1243 if( flags&EXPRDUP_REDUCE ){
drh3d6bedf2018-09-19 14:54:38 +00001244 nByte += dupedExprSize(p->pLeft, flags);
1245 if( p->eX==EX_Right ) nByte += dupedExprSize(p->x.pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001246 }
1247 }
1248 return nByte;
1249}
1250
1251/*
1252** This function is similar to sqlite3ExprDup(), except that if pzBuffer
1253** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +00001254** to store the copy of expression p, the copies of p->u.zToken
drh3d6bedf2018-09-19 14:54:38 +00001255** (if applicable), and the copies of the p->pLeft and p->x.pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +00001256** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +00001257** portion of the buffer copied into by this function.
1258*/
drh3c194692016-04-11 16:43:43 +00001259static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1260 Expr *pNew; /* Value to return */
1261 u8 *zAlloc; /* Memory space from which to build Expr object */
1262 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1263
drh575fad62016-02-05 13:38:36 +00001264 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +00001265 assert( p );
1266 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1267 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +00001268
drh3c194692016-04-11 16:43:43 +00001269 /* Figure out where to write the new Expr structure. */
1270 if( pzBuffer ){
1271 zAlloc = *pzBuffer;
1272 staticFlag = EP_Static;
1273 }else{
1274 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1275 staticFlag = 0;
1276 }
1277 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001278
drh3c194692016-04-11 16:43:43 +00001279 if( pNew ){
1280 /* Set nNewSize to the size allocated for the structure pointed to
1281 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1282 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1283 ** by the copy of the p->u.zToken string (if any).
1284 */
1285 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1286 const int nNewSize = nStructSize & 0xfff;
1287 int nToken;
1288 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1289 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001290 }else{
drh3c194692016-04-11 16:43:43 +00001291 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001292 }
drh3c194692016-04-11 16:43:43 +00001293 if( dupFlags ){
1294 assert( ExprHasProperty(p, EP_Reduced)==0 );
1295 memcpy(zAlloc, p, nNewSize);
1296 }else{
1297 u32 nSize = (u32)exprStructSize(p);
1298 memcpy(zAlloc, p, nSize);
1299 if( nSize<EXPR_FULLSIZE ){
1300 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1301 }
1302 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001303
drh3c194692016-04-11 16:43:43 +00001304 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1305 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1306 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1307 pNew->flags |= staticFlag;
drh3b3c86a2018-09-18 21:35:31 +00001308 assert( pNew->eX==p->eX );
1309 assert( pNew->eV==p->eV );
drh3c194692016-04-11 16:43:43 +00001310
1311 /* Copy the p->u.zToken string, if any. */
1312 if( nToken ){
1313 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1314 memcpy(zToken, p->u.zToken, nToken);
1315 }
1316
drh209bc522016-09-23 21:36:24 +00001317 if( 0==((p->flags|pNew->flags) & (EP_TokenOnly|EP_Leaf)) ){
drh3c194692016-04-11 16:43:43 +00001318 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
drh3b3c86a2018-09-18 21:35:31 +00001319 switch( p->eX ){
1320 case EX_Select: {
1321 assert( pNew->eX==EX_Select );
1322 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
1323 if( pNew->x.pSelect==0 ) pNew->eX = EX_None;
1324 break;
1325 }
1326 case EX_List: {
1327 assert( pNew->eX==EX_List );
1328 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
1329 if( pNew->x.pList==0 ) pNew->eX = EX_None;
1330 break;
1331 }
drh33e619f2009-05-28 01:00:55 +00001332 }
drh3c194692016-04-11 16:43:43 +00001333 }
1334
drh3d6bedf2018-09-19 14:54:38 +00001335 /* Fill in pNew->pLeft and pNew->x.pRight. */
drh3c194692016-04-11 16:43:43 +00001336 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1337 zAlloc += dupedExprNodeSize(p, dupFlags);
drh209bc522016-09-23 21:36:24 +00001338 if( !ExprHasProperty(pNew, EP_TokenOnly|EP_Leaf) ){
drh3c194692016-04-11 16:43:43 +00001339 pNew->pLeft = p->pLeft ?
1340 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
drh3d6bedf2018-09-19 14:54:38 +00001341 if( p->eX==EX_Right ){
1342 pNew->x.pRight = exprDup(db, p->x.pRight, EXPRDUP_REDUCE, &zAlloc);
1343 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001344 }
drh3c194692016-04-11 16:43:43 +00001345 if( pzBuffer ){
1346 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001347 }
drh3c194692016-04-11 16:43:43 +00001348 }else{
dan67a9b8e2018-06-22 20:51:35 +00001349#ifndef SQLITE_OMIT_WINDOWFUNC
dane2f781b2018-05-17 19:24:08 +00001350 if( ExprHasProperty(p, EP_Reduced|EP_TokenOnly) ){
1351 pNew->pWin = 0;
1352 }else{
dan2a11bb22018-06-11 20:50:25 +00001353 pNew->pWin = sqlite3WindowDup(db, pNew, p->pWin);
dane2f781b2018-05-17 19:24:08 +00001354 }
dan67a9b8e2018-06-22 20:51:35 +00001355#endif /* SQLITE_OMIT_WINDOWFUNC */
drh209bc522016-09-23 21:36:24 +00001356 if( !ExprHasProperty(p, EP_TokenOnly|EP_Leaf) ){
drh98542602016-08-20 17:00:16 +00001357 if( pNew->op==TK_SELECT_COLUMN ){
1358 pNew->pLeft = p->pLeft;
drh3d6bedf2018-09-19 14:54:38 +00001359 assert( p->iColumn==0 || p->eX!=EX_Right );
1360 /* OLD: assert( p->pRight==0 || p->x.pRight==p->pLeft ); */
drh98542602016-08-20 17:00:16 +00001361 }else{
1362 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1363 }
drh3d6bedf2018-09-19 14:54:38 +00001364 if( p->eX==EX_Right ){
1365 pNew->x.pRight = sqlite3ExprDup(db, p->x.pRight, 0);
1366 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001367 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001368 }
1369 }
1370 return pNew;
1371}
1372
1373/*
danbfe31e72014-01-15 14:17:31 +00001374** Create and return a deep copy of the object passed as the second
1375** argument. If an OOM condition is encountered, NULL is returned
1376** and the db->mallocFailed flag set.
1377*/
daneede6a52014-01-15 19:42:23 +00001378#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +00001379static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +00001380 With *pRet = 0;
1381 if( p ){
1382 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1383 pRet = sqlite3DbMallocZero(db, nByte);
1384 if( pRet ){
1385 int i;
1386 pRet->nCte = p->nCte;
1387 for(i=0; i<p->nCte; i++){
1388 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1389 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1390 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1391 }
1392 }
1393 }
1394 return pRet;
1395}
daneede6a52014-01-15 19:42:23 +00001396#else
1397# define withDup(x,y) 0
1398#endif
dan4e9119d2014-01-13 15:12:23 +00001399
drha76b5df2002-02-23 02:32:10 +00001400/*
drhff78bd22002-02-27 01:47:11 +00001401** The following group of routines make deep copies of expressions,
1402** expression lists, ID lists, and select statements. The copies can
1403** be deleted (by being passed to their respective ...Delete() routines)
1404** without effecting the originals.
1405**
danielk19774adee202004-05-08 08:23:19 +00001406** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1407** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +00001408** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001409**
drhad3cab52002-05-24 02:04:32 +00001410** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001411**
drhb7916a72009-05-27 10:31:29 +00001412** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001413** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1414** truncated version of the usual Expr structure that will be stored as
1415** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001416*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001417Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001418 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001419 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001420}
danielk19776ab3a2e2009-02-19 14:39:25 +00001421ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001422 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001423 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001424 int i;
drhb1637482017-01-03 00:27:16 +00001425 Expr *pPriorSelectCol = 0;
drh575fad62016-02-05 13:38:36 +00001426 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001427 if( p==0 ) return 0;
drh97258192017-09-17 19:45:28 +00001428 pNew = sqlite3DbMallocRawNN(db, sqlite3DbMallocSize(db, p));
drhff78bd22002-02-27 01:47:11 +00001429 if( pNew==0 ) return 0;
drha19543f2017-09-15 15:17:48 +00001430 pNew->nExpr = p->nExpr;
drh43606172017-04-05 11:32:13 +00001431 pItem = pNew->a;
drh145716b2004-09-24 12:24:06 +00001432 pOldItem = p->a;
1433 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001434 Expr *pOldExpr = pOldItem->pExpr;
drh47073f62017-01-02 22:36:32 +00001435 Expr *pNewExpr;
drhb5526ea2009-07-16 12:41:05 +00001436 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh47073f62017-01-02 22:36:32 +00001437 if( pOldExpr
1438 && pOldExpr->op==TK_SELECT_COLUMN
1439 && (pNewExpr = pItem->pExpr)!=0
1440 ){
1441 assert( pNewExpr->iColumn==0 || i>0 );
1442 if( pNewExpr->iColumn==0 ){
drh3d6bedf2018-09-19 14:54:38 +00001443 assert( pOldExpr->pLeft==pOldExpr->x.pRight );
1444 pPriorSelectCol = pNewExpr->pLeft = pNewExpr->x.pRight;
drhb1637482017-01-03 00:27:16 +00001445 }else{
1446 assert( i>0 );
1447 assert( pItem[-1].pExpr!=0 );
1448 assert( pNewExpr->iColumn==pItem[-1].pExpr->iColumn+1 );
1449 assert( pPriorSelectCol==pItem[-1].pExpr->pLeft );
1450 pNewExpr->pLeft = pPriorSelectCol;
drh47073f62017-01-02 22:36:32 +00001451 }
1452 }
drh17435752007-08-16 04:30:38 +00001453 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001454 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001455 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001456 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001457 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
dan24e25d32018-04-14 18:46:20 +00001458 pItem->bSorterRef = pOldItem->bSorterRef;
drhc2acc4e2013-11-15 18:15:19 +00001459 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001460 }
1461 return pNew;
1462}
danielk197793758c82005-01-21 08:13:14 +00001463
1464/*
1465** If cursors, triggers, views and subqueries are all omitted from
1466** the build, then none of the following routines, except for
1467** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1468** called with a NULL argument.
1469*/
danielk19776a67fe82005-02-04 04:07:16 +00001470#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1471 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001472SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001473 SrcList *pNew;
1474 int i;
drh113088e2003-03-20 01:16:58 +00001475 int nByte;
drh575fad62016-02-05 13:38:36 +00001476 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001477 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001478 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001479 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001480 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001481 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001482 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001483 struct SrcList_item *pNewItem = &pNew->a[i];
1484 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001485 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001486 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001487 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1488 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1489 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001490 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001491 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001492 pNewItem->addrFillSub = pOldItem->addrFillSub;
1493 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001494 if( pNewItem->fg.isIndexedBy ){
1495 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1496 }
1497 pNewItem->pIBIndex = pOldItem->pIBIndex;
1498 if( pNewItem->fg.isTabFunc ){
1499 pNewItem->u1.pFuncArg =
1500 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1501 }
drhed8a3bb2005-06-06 21:19:56 +00001502 pTab = pNewItem->pTab = pOldItem->pTab;
1503 if( pTab ){
drh79df7782016-12-14 14:07:35 +00001504 pTab->nTabRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001505 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001506 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1507 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001508 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001509 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001510 }
1511 return pNew;
1512}
drh17435752007-08-16 04:30:38 +00001513IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001514 IdList *pNew;
1515 int i;
drh575fad62016-02-05 13:38:36 +00001516 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001517 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001518 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001519 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001520 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001521 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001522 if( pNew->a==0 ){
drhdbd6a7d2017-04-05 12:39:49 +00001523 sqlite3DbFreeNN(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001524 return 0;
1525 }
drh6c535152012-02-02 03:38:30 +00001526 /* Note that because the size of the allocation for p->a[] is not
1527 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1528 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001529 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001530 struct IdList_item *pNewItem = &pNew->a[i];
1531 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001532 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001533 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001534 }
1535 return pNew;
1536}
dana7466202017-02-03 14:44:52 +00001537Select *sqlite3SelectDup(sqlite3 *db, Select *pDup, int flags){
1538 Select *pRet = 0;
1539 Select *pNext = 0;
1540 Select **pp = &pRet;
1541 Select *p;
1542
drh575fad62016-02-05 13:38:36 +00001543 assert( db!=0 );
dana7466202017-02-03 14:44:52 +00001544 for(p=pDup; p; p=p->pPrior){
1545 Select *pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
1546 if( pNew==0 ) break;
1547 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
1548 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1549 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1550 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1551 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1552 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
1553 pNew->op = p->op;
1554 pNew->pNext = pNext;
1555 pNew->pPrior = 0;
1556 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
dana7466202017-02-03 14:44:52 +00001557 pNew->iLimit = 0;
1558 pNew->iOffset = 0;
1559 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
1560 pNew->addrOpenEphm[0] = -1;
1561 pNew->addrOpenEphm[1] = -1;
1562 pNew->nSelectRow = p->nSelectRow;
1563 pNew->pWith = withDup(db, p->pWith);
dan67a9b8e2018-06-22 20:51:35 +00001564#ifndef SQLITE_OMIT_WINDOWFUNC
dan2e362f92018-05-17 14:26:27 +00001565 pNew->pWin = 0;
danc95f38d2018-06-18 20:34:43 +00001566 pNew->pWinDefn = sqlite3WindowListDup(db, p->pWinDefn);
dan67a9b8e2018-06-22 20:51:35 +00001567#endif
drhfef37762018-07-10 19:48:35 +00001568 pNew->selId = p->selId;
dana7466202017-02-03 14:44:52 +00001569 *pp = pNew;
1570 pp = &pNew->pPrior;
1571 pNext = pNew;
1572 }
1573
1574 return pRet;
drhff78bd22002-02-27 01:47:11 +00001575}
danielk197793758c82005-01-21 08:13:14 +00001576#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001577Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001578 assert( p==0 );
1579 return 0;
1580}
1581#endif
drhff78bd22002-02-27 01:47:11 +00001582
1583
1584/*
drha76b5df2002-02-23 02:32:10 +00001585** Add a new element to the end of an expression list. If pList is
1586** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001587**
drha19543f2017-09-15 15:17:48 +00001588** The pList argument must be either NULL or a pointer to an ExprList
1589** obtained from a prior call to sqlite3ExprListAppend(). This routine
1590** may not be used with an ExprList obtained from sqlite3ExprListDup().
1591** Reason: This routine assumes that the number of slots in pList->a[]
1592** is a power of two. That is true for sqlite3ExprListAppend() returns
1593** but is not necessarily true from the return value of sqlite3ExprListDup().
1594**
drhb7916a72009-05-27 10:31:29 +00001595** If a memory allocation error occurs, the entire list is freed and
1596** NULL is returned. If non-NULL is returned, then it is guaranteed
1597** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001598*/
drh17435752007-08-16 04:30:38 +00001599ExprList *sqlite3ExprListAppend(
1600 Parse *pParse, /* Parsing context */
1601 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001602 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001603){
drh43606172017-04-05 11:32:13 +00001604 struct ExprList_item *pItem;
drh17435752007-08-16 04:30:38 +00001605 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001606 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001607 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001608 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001609 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001610 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001611 }
drhc263f7c2016-01-18 13:18:54 +00001612 pList->nExpr = 0;
drha19543f2017-09-15 15:17:48 +00001613 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
drh43606172017-04-05 11:32:13 +00001614 ExprList *pNew;
1615 pNew = sqlite3DbRealloc(db, pList,
drha19543f2017-09-15 15:17:48 +00001616 sizeof(*pList)+(2*pList->nExpr - 1)*sizeof(pList->a[0]));
drh43606172017-04-05 11:32:13 +00001617 if( pNew==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001618 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001619 }
drh43606172017-04-05 11:32:13 +00001620 pList = pNew;
drha76b5df2002-02-23 02:32:10 +00001621 }
drh43606172017-04-05 11:32:13 +00001622 pItem = &pList->a[pList->nExpr++];
drha8b97932017-05-31 02:58:30 +00001623 assert( offsetof(struct ExprList_item,zName)==sizeof(pItem->pExpr) );
1624 assert( offsetof(struct ExprList_item,pExpr)==0 );
1625 memset(&pItem->zName,0,sizeof(*pItem)-offsetof(struct ExprList_item,zName));
drh43606172017-04-05 11:32:13 +00001626 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001627 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001628
1629no_mem:
1630 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001631 sqlite3ExprDelete(db, pExpr);
1632 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001633 return 0;
drha76b5df2002-02-23 02:32:10 +00001634}
1635
1636/*
drh8762ec12016-08-20 01:06:22 +00001637** pColumns and pExpr form a vector assignment which is part of the SET
1638** clause of an UPDATE statement. Like this:
drha1251bc2016-08-20 00:51:37 +00001639**
1640** (a,b,c) = (expr1,expr2,expr3)
1641** Or: (a,b,c) = (SELECT x,y,z FROM ....)
1642**
1643** For each term of the vector assignment, append new entries to the
drhb67343d2017-01-03 11:59:54 +00001644** expression list pList. In the case of a subquery on the RHS, append
drha1251bc2016-08-20 00:51:37 +00001645** TK_SELECT_COLUMN expressions.
1646*/
1647ExprList *sqlite3ExprListAppendVector(
1648 Parse *pParse, /* Parsing context */
1649 ExprList *pList, /* List to which to append. Might be NULL */
1650 IdList *pColumns, /* List of names of LHS of the assignment */
1651 Expr *pExpr /* Vector expression to be appended. Might be NULL */
1652){
1653 sqlite3 *db = pParse->db;
1654 int n;
1655 int i;
drh66860af2016-08-23 18:30:10 +00001656 int iFirst = pList ? pList->nExpr : 0;
drh321e8282016-08-24 17:49:07 +00001657 /* pColumns can only be NULL due to an OOM but an OOM will cause an
1658 ** exit prior to this routine being invoked */
1659 if( NEVER(pColumns==0) ) goto vector_append_error;
drha1251bc2016-08-20 00:51:37 +00001660 if( pExpr==0 ) goto vector_append_error;
drh966e2912017-01-03 02:58:01 +00001661
1662 /* If the RHS is a vector, then we can immediately check to see that
1663 ** the size of the RHS and LHS match. But if the RHS is a SELECT,
1664 ** wildcards ("*") in the result set of the SELECT must be expanded before
1665 ** we can do the size check, so defer the size check until code generation.
1666 */
1667 if( pExpr->op!=TK_SELECT && pColumns->nId!=(n=sqlite3ExprVectorSize(pExpr)) ){
drha1251bc2016-08-20 00:51:37 +00001668 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
1669 pColumns->nId, n);
1670 goto vector_append_error;
1671 }
drh966e2912017-01-03 02:58:01 +00001672
1673 for(i=0; i<pColumns->nId; i++){
drha1251bc2016-08-20 00:51:37 +00001674 Expr *pSubExpr = sqlite3ExprForVectorField(pParse, pExpr, i);
1675 pList = sqlite3ExprListAppend(pParse, pList, pSubExpr);
1676 if( pList ){
drh66860af2016-08-23 18:30:10 +00001677 assert( pList->nExpr==iFirst+i+1 );
drha1251bc2016-08-20 00:51:37 +00001678 pList->a[pList->nExpr-1].zName = pColumns->a[i].zName;
1679 pColumns->a[i].zName = 0;
1680 }
1681 }
drh966e2912017-01-03 02:58:01 +00001682
drhffe28052017-05-06 18:09:36 +00001683 if( !db->mallocFailed && pExpr->op==TK_SELECT && ALWAYS(pList!=0) ){
drhf4dd26c2017-04-05 11:49:06 +00001684 Expr *pFirst = pList->a[iFirst].pExpr;
1685 assert( pFirst!=0 );
1686 assert( pFirst->op==TK_SELECT_COLUMN );
drh966e2912017-01-03 02:58:01 +00001687
drhf4dd26c2017-04-05 11:49:06 +00001688 /* Store the SELECT statement in pRight so it will be deleted when
1689 ** sqlite3ExprListDelete() is called */
drh3d6bedf2018-09-19 14:54:38 +00001690 assert( pFirst->eX==EX_None );
1691 pFirst->x.pRight = pExpr;
1692 pFirst->eX = EX_Right;
drhf4dd26c2017-04-05 11:49:06 +00001693 pExpr = 0;
drh966e2912017-01-03 02:58:01 +00001694
drhf4dd26c2017-04-05 11:49:06 +00001695 /* Remember the size of the LHS in iTable so that we can check that
1696 ** the RHS and LHS sizes match during code generation. */
1697 pFirst->iTable = pColumns->nId;
drha1251bc2016-08-20 00:51:37 +00001698 }
1699
1700vector_append_error:
1701 sqlite3ExprDelete(db, pExpr);
1702 sqlite3IdListDelete(db, pColumns);
1703 return pList;
1704}
1705
1706/*
drhbc622bc2015-08-24 15:39:42 +00001707** Set the sort order for the last element on the given ExprList.
1708*/
1709void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1710 if( p==0 ) return;
1711 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1712 assert( p->nExpr>0 );
1713 if( iSortOrder<0 ){
1714 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1715 return;
1716 }
1717 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001718}
1719
1720/*
drhb7916a72009-05-27 10:31:29 +00001721** Set the ExprList.a[].zName element of the most recently added item
1722** on the expression list.
1723**
1724** pList might be NULL following an OOM error. But pName should never be
1725** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1726** is set.
1727*/
1728void sqlite3ExprListSetName(
1729 Parse *pParse, /* Parsing context */
1730 ExprList *pList, /* List to which to add the span. */
1731 Token *pName, /* Name to be added */
1732 int dequote /* True to cause the name to be dequoted */
1733){
1734 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1735 if( pList ){
1736 struct ExprList_item *pItem;
1737 assert( pList->nExpr>0 );
1738 pItem = &pList->a[pList->nExpr-1];
1739 assert( pItem->zName==0 );
1740 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001741 if( dequote ) sqlite3Dequote(pItem->zName);
danc9461ec2018-08-29 21:00:16 +00001742 if( IN_RENAME_OBJECT ){
dan07e95232018-08-21 16:32:53 +00001743 sqlite3RenameTokenMap(pParse, (void*)pItem->zName, pName);
dan5be60c52018-08-15 20:28:39 +00001744 }
drhb7916a72009-05-27 10:31:29 +00001745 }
1746}
1747
1748/*
1749** Set the ExprList.a[].zSpan element of the most recently added item
1750** on the expression list.
1751**
1752** pList might be NULL following an OOM error. But pSpan should never be
1753** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1754** is set.
1755*/
1756void sqlite3ExprListSetSpan(
1757 Parse *pParse, /* Parsing context */
1758 ExprList *pList, /* List to which to add the span. */
drh1be266b2017-12-24 00:18:47 +00001759 const char *zStart, /* Start of the span */
1760 const char *zEnd /* End of the span */
drhb7916a72009-05-27 10:31:29 +00001761){
1762 sqlite3 *db = pParse->db;
1763 assert( pList!=0 || db->mallocFailed!=0 );
1764 if( pList ){
1765 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1766 assert( pList->nExpr>0 );
drhb7916a72009-05-27 10:31:29 +00001767 sqlite3DbFree(db, pItem->zSpan);
drh9b2e0432017-12-27 19:43:22 +00001768 pItem->zSpan = sqlite3DbSpanDup(db, zStart, zEnd);
drhb7916a72009-05-27 10:31:29 +00001769 }
1770}
1771
1772/*
danielk19777a15a4b2007-05-08 17:54:43 +00001773** If the expression list pEList contains more than iLimit elements,
1774** leave an error message in pParse.
1775*/
1776void sqlite3ExprListCheckLength(
1777 Parse *pParse,
1778 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001779 const char *zObject
1780){
drhb1a6c3c2008-03-20 16:30:17 +00001781 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001782 testcase( pEList && pEList->nExpr==mx );
1783 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001784 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001785 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1786 }
1787}
1788
1789/*
drha76b5df2002-02-23 02:32:10 +00001790** Delete an entire expression list.
1791*/
drhaffa8552016-04-11 18:25:05 +00001792static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drhac48b752017-04-05 11:57:56 +00001793 int i = pList->nExpr;
1794 struct ExprList_item *pItem = pList->a;
1795 assert( pList->nExpr>0 );
1796 do{
drh633e6d52008-07-28 19:34:53 +00001797 sqlite3ExprDelete(db, pItem->pExpr);
1798 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001799 sqlite3DbFree(db, pItem->zSpan);
drhac48b752017-04-05 11:57:56 +00001800 pItem++;
1801 }while( --i>0 );
drhdbd6a7d2017-04-05 12:39:49 +00001802 sqlite3DbFreeNN(db, pList);
drha76b5df2002-02-23 02:32:10 +00001803}
drhaffa8552016-04-11 18:25:05 +00001804void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1805 if( pList ) exprListDeleteNN(db, pList);
1806}
drha76b5df2002-02-23 02:32:10 +00001807
1808/*
drh2308ed32015-02-09 16:09:34 +00001809** Return the bitwise-OR of all Expr.flags fields in the given
1810** ExprList.
drh885a5b02015-02-09 15:21:36 +00001811*/
drh2308ed32015-02-09 16:09:34 +00001812u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001813 int i;
drh2308ed32015-02-09 16:09:34 +00001814 u32 m = 0;
drh508e2d02017-09-30 01:25:04 +00001815 assert( pList!=0 );
1816 for(i=0; i<pList->nExpr; i++){
1817 Expr *pExpr = pList->a[i].pExpr;
1818 assert( pExpr!=0 );
1819 m |= pExpr->flags;
drh885a5b02015-02-09 15:21:36 +00001820 }
drh2308ed32015-02-09 16:09:34 +00001821 return m;
drh885a5b02015-02-09 15:21:36 +00001822}
1823
1824/*
drh7e6f9802017-09-04 00:33:04 +00001825** This is a SELECT-node callback for the expression walker that
1826** always "fails". By "fail" in this case, we mean set
1827** pWalker->eCode to zero and abort.
1828**
1829** This callback is used by multiple expression walkers.
1830*/
1831int sqlite3SelectWalkFail(Walker *pWalker, Select *NotUsed){
1832 UNUSED_PARAMETER(NotUsed);
1833 pWalker->eCode = 0;
1834 return WRC_Abort;
1835}
1836
1837/*
drh171d16b2018-02-26 20:15:54 +00001838** If the input expression is an ID with the name "true" or "false"
drh96acafb2018-02-27 14:49:25 +00001839** then convert it into an TK_TRUEFALSE term. Return non-zero if
1840** the conversion happened, and zero if the expression is unaltered.
drh171d16b2018-02-26 20:15:54 +00001841*/
1842int sqlite3ExprIdToTrueFalse(Expr *pExpr){
1843 assert( pExpr->op==TK_ID || pExpr->op==TK_STRING );
1844 if( sqlite3StrICmp(pExpr->u.zToken, "true")==0
1845 || sqlite3StrICmp(pExpr->u.zToken, "false")==0
1846 ){
1847 pExpr->op = TK_TRUEFALSE;
drh171d16b2018-02-26 20:15:54 +00001848 return 1;
1849 }
1850 return 0;
1851}
1852
drh43c4ac82018-02-26 21:26:27 +00001853/*
drh96acafb2018-02-27 14:49:25 +00001854** The argument must be a TK_TRUEFALSE Expr node. Return 1 if it is TRUE
drh43c4ac82018-02-26 21:26:27 +00001855** and 0 if it is FALSE.
1856*/
drh96acafb2018-02-27 14:49:25 +00001857int sqlite3ExprTruthValue(const Expr *pExpr){
drh43c4ac82018-02-26 21:26:27 +00001858 assert( pExpr->op==TK_TRUEFALSE );
1859 assert( sqlite3StrICmp(pExpr->u.zToken,"true")==0
1860 || sqlite3StrICmp(pExpr->u.zToken,"false")==0 );
1861 return pExpr->u.zToken[4]==0;
1862}
1863
drh171d16b2018-02-26 20:15:54 +00001864
1865/*
drh059b2d52014-10-24 19:28:09 +00001866** These routines are Walker callbacks used to check expressions to
1867** see if they are "constant" for some definition of constant. The
1868** Walker.eCode value determines the type of "constant" we are looking
1869** for.
drh73b211a2005-01-18 04:00:42 +00001870**
drh7d10d5a2008-08-20 16:35:10 +00001871** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001872**
drh059b2d52014-10-24 19:28:09 +00001873** sqlite3ExprIsConstant() pWalker->eCode==1
1874** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001875** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001876** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001877**
drh059b2d52014-10-24 19:28:09 +00001878** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1879** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001880**
drhfeada2d2014-09-24 13:20:22 +00001881** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001882** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1883** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001884** parameter raises an error for new statements, but is silently converted
1885** to NULL for existing schemas. This allows sqlite_master tables that
1886** contain a bound parameter because they were generated by older versions
1887** of SQLite to be parsed by newer versions of SQLite without raising a
1888** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001889*/
drh7d10d5a2008-08-20 16:35:10 +00001890static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001891
drh059b2d52014-10-24 19:28:09 +00001892 /* If pWalker->eCode is 2 then any term of the expression that comes from
1893 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001894 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001895 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1896 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001897 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001898 }
1899
drh626a8792005-01-17 22:08:19 +00001900 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001901 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001902 ** and either pWalker->eCode==4 or 5 or the function has the
1903 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001904 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001905 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001906 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001907 }else{
1908 pWalker->eCode = 0;
1909 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001910 }
drh626a8792005-01-17 22:08:19 +00001911 case TK_ID:
drh171d16b2018-02-26 20:15:54 +00001912 /* Convert "true" or "false" in a DEFAULT clause into the
1913 ** appropriate TK_TRUEFALSE operator */
drhe39ef312018-02-27 00:58:13 +00001914 if( sqlite3ExprIdToTrueFalse(pExpr) ){
drh171d16b2018-02-26 20:15:54 +00001915 return WRC_Prune;
1916 }
1917 /* Fall thru */
drh626a8792005-01-17 22:08:19 +00001918 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001919 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001920 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001921 testcase( pExpr->op==TK_ID );
1922 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001923 testcase( pExpr->op==TK_AGG_FUNCTION );
1924 testcase( pExpr->op==TK_AGG_COLUMN );
drh07aded62018-07-28 16:24:08 +00001925 if( ExprHasProperty(pExpr, EP_FixedCol) && pWalker->eCode!=2 ){
drhefad2e22018-07-27 16:57:11 +00001926 return WRC_Continue;
1927 }
drh059b2d52014-10-24 19:28:09 +00001928 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1929 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001930 }
drhf43ce0b2017-05-25 00:08:48 +00001931 /* Fall through */
1932 case TK_IF_NULL_ROW:
drh6e341b92018-04-17 18:50:40 +00001933 case TK_REGISTER:
drh99160482018-04-18 01:34:39 +00001934 testcase( pExpr->op==TK_REGISTER );
drhf43ce0b2017-05-25 00:08:48 +00001935 testcase( pExpr->op==TK_IF_NULL_ROW );
1936 pWalker->eCode = 0;
1937 return WRC_Abort;
drhfeada2d2014-09-24 13:20:22 +00001938 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001939 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001940 /* Silently convert bound parameters that appear inside of CREATE
1941 ** statements into a NULL when parsing the CREATE statement text out
1942 ** of the sqlite_master table */
1943 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001944 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001945 /* A bound parameter in a CREATE statement that originates from
1946 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001947 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001948 return WRC_Abort;
1949 }
1950 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001951 default:
drh6e341b92018-04-17 18:50:40 +00001952 testcase( pExpr->op==TK_SELECT ); /* sqlite3SelectWalkFail() disallows */
1953 testcase( pExpr->op==TK_EXISTS ); /* sqlite3SelectWalkFail() disallows */
drh7d10d5a2008-08-20 16:35:10 +00001954 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001955 }
1956}
drh059b2d52014-10-24 19:28:09 +00001957static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001958 Walker w;
drh059b2d52014-10-24 19:28:09 +00001959 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001960 w.xExprCallback = exprNodeIsConstant;
drh7e6f9802017-09-04 00:33:04 +00001961 w.xSelectCallback = sqlite3SelectWalkFail;
drh979dd1b2017-05-29 14:26:07 +00001962#ifdef SQLITE_DEBUG
1963 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
1964#endif
drh059b2d52014-10-24 19:28:09 +00001965 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001966 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001967 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001968}
drh626a8792005-01-17 22:08:19 +00001969
1970/*
drh059b2d52014-10-24 19:28:09 +00001971** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001972** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001973**
1974** For the purposes of this function, a double-quoted string (ex: "abc")
1975** is considered a variable but a single-quoted string (ex: 'abc') is
1976** a constant.
drhfef52082000-06-06 01:50:43 +00001977*/
danielk19774adee202004-05-08 08:23:19 +00001978int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001979 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001980}
1981
1982/*
drh07aded62018-07-28 16:24:08 +00001983** Walk an expression tree. Return non-zero if
1984**
1985** (1) the expression is constant, and
1986** (2) the expression does originate in the ON or USING clause
1987** of a LEFT JOIN, and
1988** (3) the expression does not contain any EP_FixedCol TK_COLUMN
1989** operands created by the constant propagation optimization.
1990**
1991** When this routine returns true, it indicates that the expression
1992** can be added to the pParse->pConstExpr list and evaluated once when
1993** the prepared statement starts up. See sqlite3ExprCodeAtInit().
drh0a168372007-06-08 00:20:47 +00001994*/
1995int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001996 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001997}
1998
1999/*
drhfcb9f4f2015-06-01 18:13:16 +00002000** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00002001** for any single row of the table with cursor iCur. In other words, the
2002** expression must not refer to any non-deterministic function nor any
2003** table other than iCur.
2004*/
2005int sqlite3ExprIsTableConstant(Expr *p, int iCur){
2006 return exprIsConst(p, 3, iCur);
2007}
2008
danab31a842017-04-29 20:53:09 +00002009
2010/*
2011** sqlite3WalkExpr() callback used by sqlite3ExprIsConstantOrGroupBy().
2012*/
2013static int exprNodeIsConstantOrGroupBy(Walker *pWalker, Expr *pExpr){
2014 ExprList *pGroupBy = pWalker->u.pGroupBy;
2015 int i;
2016
2017 /* Check if pExpr is identical to any GROUP BY term. If so, consider
2018 ** it constant. */
2019 for(i=0; i<pGroupBy->nExpr; i++){
2020 Expr *p = pGroupBy->a[i].pExpr;
dan5aa550c2017-06-24 18:10:29 +00002021 if( sqlite3ExprCompare(0, pExpr, p, -1)<2 ){
drh70efa842017-09-28 01:58:23 +00002022 CollSeq *pColl = sqlite3ExprNNCollSeq(pWalker->pParse, p);
drhefad2e22018-07-27 16:57:11 +00002023 if( sqlite3IsBinary(pColl) ){
danab31a842017-04-29 20:53:09 +00002024 return WRC_Prune;
2025 }
2026 }
2027 }
2028
2029 /* Check if pExpr is a sub-select. If so, consider it variable. */
drh3b3c86a2018-09-18 21:35:31 +00002030 if( pExpr->eX==EX_Select ){
danab31a842017-04-29 20:53:09 +00002031 pWalker->eCode = 0;
2032 return WRC_Abort;
2033 }
2034
2035 return exprNodeIsConstant(pWalker, pExpr);
2036}
2037
2038/*
2039** Walk the expression tree passed as the first argument. Return non-zero
2040** if the expression consists entirely of constants or copies of terms
2041** in pGroupBy that sort with the BINARY collation sequence.
drhab314002017-05-02 16:46:41 +00002042**
2043** This routine is used to determine if a term of the HAVING clause can
2044** be promoted into the WHERE clause. In order for such a promotion to work,
2045** the value of the HAVING clause term must be the same for all members of
2046** a "group". The requirement that the GROUP BY term must be BINARY
2047** assumes that no other collating sequence will have a finer-grained
2048** grouping than binary. In other words (A=B COLLATE binary) implies
2049** A=B in every other collating sequence. The requirement that the
2050** GROUP BY be BINARY is stricter than necessary. It would also work
2051** to promote HAVING clauses that use the same alternative collating
2052** sequence as the GROUP BY term, but that is much harder to check,
2053** alternative collating sequences are uncommon, and this is only an
2054** optimization, so we take the easy way out and simply require the
2055** GROUP BY to use the BINARY collating sequence.
danab31a842017-04-29 20:53:09 +00002056*/
2057int sqlite3ExprIsConstantOrGroupBy(Parse *pParse, Expr *p, ExprList *pGroupBy){
2058 Walker w;
danab31a842017-04-29 20:53:09 +00002059 w.eCode = 1;
2060 w.xExprCallback = exprNodeIsConstantOrGroupBy;
drh979dd1b2017-05-29 14:26:07 +00002061 w.xSelectCallback = 0;
danab31a842017-04-29 20:53:09 +00002062 w.u.pGroupBy = pGroupBy;
2063 w.pParse = pParse;
2064 sqlite3WalkExpr(&w, p);
2065 return w.eCode;
2066}
2067
drh059b2d52014-10-24 19:28:09 +00002068/*
2069** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00002070** or a function call with constant arguments. Return and 0 if there
2071** are any variables.
2072**
2073** For the purposes of this function, a double-quoted string (ex: "abc")
2074** is considered a variable but a single-quoted string (ex: 'abc') is
2075** a constant.
2076*/
drhfeada2d2014-09-24 13:20:22 +00002077int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
2078 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00002079 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00002080}
2081
drh5b88bc42013-12-07 23:35:21 +00002082#ifdef SQLITE_ENABLE_CURSOR_HINTS
2083/*
2084** Walk an expression tree. Return 1 if the expression contains a
2085** subquery of some kind. Return 0 if there are no subqueries.
2086*/
2087int sqlite3ExprContainsSubquery(Expr *p){
2088 Walker w;
drhbec24762015-08-13 20:07:13 +00002089 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00002090 w.xExprCallback = sqlite3ExprWalkNoop;
drh7e6f9802017-09-04 00:33:04 +00002091 w.xSelectCallback = sqlite3SelectWalkFail;
drh979dd1b2017-05-29 14:26:07 +00002092#ifdef SQLITE_DEBUG
2093 w.xSelectCallback2 = sqlite3SelectWalkAssert2;
2094#endif
drh5b88bc42013-12-07 23:35:21 +00002095 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00002096 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00002097}
2098#endif
2099
drheb55bd22005-06-30 17:04:21 +00002100/*
drh73b211a2005-01-18 04:00:42 +00002101** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00002102** to fit in a 32-bit integer, return 1 and put the value of the integer
2103** in *pValue. If the expression is not an integer or if it is too big
2104** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00002105*/
danielk19774adee202004-05-08 08:23:19 +00002106int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00002107 int rc = 0;
drhba28b5a2017-03-12 20:28:44 +00002108 if( p==0 ) return 0; /* Can only happen following on OOM */
drhcd92e842011-02-17 15:58:20 +00002109
2110 /* If an expression is an integer literal that fits in a signed 32-bit
2111 ** integer, then the EP_IntValue flag will have already been set */
2112 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
2113 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
2114
drh92b01d52008-06-24 00:32:35 +00002115 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002116 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00002117 return 1;
2118 }
drhe4de1fe2002-06-02 16:09:01 +00002119 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00002120 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00002121 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00002122 break;
drh4b59ab52002-08-24 18:24:51 +00002123 }
drhe4de1fe2002-06-02 16:09:01 +00002124 case TK_UMINUS: {
2125 int v;
danielk19774adee202004-05-08 08:23:19 +00002126 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00002127 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00002128 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00002129 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00002130 }
2131 break;
2132 }
2133 default: break;
2134 }
drh92b01d52008-06-24 00:32:35 +00002135 return rc;
drhe4de1fe2002-06-02 16:09:01 +00002136}
2137
2138/*
drh039fc322009-11-17 18:31:47 +00002139** Return FALSE if there is no chance that the expression can be NULL.
2140**
2141** If the expression might be NULL or if the expression is too complex
2142** to tell return TRUE.
2143**
2144** This routine is used as an optimization, to skip OP_IsNull opcodes
2145** when we know that a value cannot be NULL. Hence, a false positive
2146** (returning TRUE when in fact the expression can never be NULL) might
2147** be a small performance hit but is otherwise harmless. On the other
2148** hand, a false negative (returning FALSE when the result could be NULL)
2149** will likely result in an incorrect answer. So when in doubt, return
2150** TRUE.
2151*/
2152int sqlite3ExprCanBeNull(const Expr *p){
2153 u8 op;
drhcd7f4572009-11-19 14:48:40 +00002154 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00002155 op = p->op;
2156 if( op==TK_REGISTER ) op = p->op2;
2157 switch( op ){
2158 case TK_INTEGER:
2159 case TK_STRING:
2160 case TK_FLOAT:
2161 case TK_BLOB:
2162 return 0;
drh7248a8b2014-08-04 18:50:54 +00002163 case TK_COLUMN:
drh72673a22014-12-04 16:27:17 +00002164 return ExprHasProperty(p, EP_CanBeNull) ||
drh4dd89d52017-08-14 14:53:24 +00002165 p->pTab==0 || /* Reference to column of index on expression */
drh72673a22014-12-04 16:27:17 +00002166 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00002167 default:
2168 return 1;
2169 }
2170}
2171
2172/*
2173** Return TRUE if the given expression is a constant which would be
2174** unchanged by OP_Affinity with the affinity given in the second
2175** argument.
2176**
2177** This routine is used to determine if the OP_Affinity operation
2178** can be omitted. When in doubt return FALSE. A false negative
2179** is harmless. A false positive, however, can result in the wrong
2180** answer.
2181*/
2182int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
2183 u8 op;
drh05883a32015-06-02 15:32:08 +00002184 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00002185 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00002186 op = p->op;
2187 if( op==TK_REGISTER ) op = p->op2;
2188 switch( op ){
2189 case TK_INTEGER: {
2190 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
2191 }
2192 case TK_FLOAT: {
2193 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
2194 }
2195 case TK_STRING: {
2196 return aff==SQLITE_AFF_TEXT;
2197 }
2198 case TK_BLOB: {
2199 return 1;
2200 }
drh2f2855b2009-11-18 01:25:26 +00002201 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00002202 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
2203 return p->iColumn<0
2204 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00002205 }
drh039fc322009-11-17 18:31:47 +00002206 default: {
2207 return 0;
2208 }
2209 }
2210}
2211
2212/*
drhc4a3c772001-04-04 11:48:57 +00002213** Return TRUE if the given string is a row-id column name.
2214*/
danielk19774adee202004-05-08 08:23:19 +00002215int sqlite3IsRowid(const char *z){
2216 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
2217 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
2218 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00002219 return 0;
2220}
2221
danielk19779a96b662007-11-29 17:05:18 +00002222/*
drh69c355b2016-03-09 15:34:51 +00002223** pX is the RHS of an IN operator. If pX is a SELECT statement
2224** that can be simplified to a direct table access, then return
2225** a pointer to the SELECT statement. If pX is not a SELECT statement,
2226** or if the SELECT statement needs to be manifested into a transient
2227** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00002228*/
2229#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00002230static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00002231 Select *p;
drhb287f4b2008-04-25 00:08:38 +00002232 SrcList *pSrc;
2233 ExprList *pEList;
2234 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00002235 int i;
drh3b3c86a2018-09-18 21:35:31 +00002236 if( pX->eX!=EX_Select ) return 0; /* Not a subquery */
2237 if( ExprHasProperty(pX, EP_VarSelect) ){
2238 return 0; /* Correlated subq */
2239 }
drh69c355b2016-03-09 15:34:51 +00002240 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00002241 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00002242 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00002243 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
2244 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
2245 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00002246 }
drhb74b1012009-05-28 21:04:37 +00002247 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00002248 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb287f4b2008-04-25 00:08:38 +00002249 if( p->pWhere ) return 0; /* Has no WHERE clause */
2250 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00002251 assert( pSrc!=0 );
2252 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00002253 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00002254 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00002255 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00002256 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00002257 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
2258 pEList = p->pEList;
drhac6b47d2016-08-24 00:51:48 +00002259 assert( pEList!=0 );
dan7b35a772016-07-28 19:47:15 +00002260 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00002261 for(i=0; i<pEList->nExpr; i++){
2262 Expr *pRes = pEList->a[i].pExpr;
2263 if( pRes->op!=TK_COLUMN ) return 0;
2264 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00002265 }
drh69c355b2016-03-09 15:34:51 +00002266 return p;
drhb287f4b2008-04-25 00:08:38 +00002267}
2268#endif /* SQLITE_OMIT_SUBQUERY */
2269
danf9b2e052016-08-02 17:45:00 +00002270#ifndef SQLITE_OMIT_SUBQUERY
dan1d8cb212011-12-09 13:24:16 +00002271/*
drh4c259e92014-08-01 21:12:35 +00002272** Generate code that checks the left-most column of index table iCur to see if
2273** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00002274** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
2275** to be set to NULL if iCur contains one or more NULL values.
2276*/
2277static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00002278 int addr1;
drh6be515e2014-08-01 21:00:53 +00002279 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00002280 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00002281 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
2282 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00002283 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00002284 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00002285}
danf9b2e052016-08-02 17:45:00 +00002286#endif
drh6be515e2014-08-01 21:00:53 +00002287
drhbb53ecb2014-08-02 21:03:33 +00002288
2289#ifndef SQLITE_OMIT_SUBQUERY
2290/*
2291** The argument is an IN operator with a list (not a subquery) on the
2292** right-hand side. Return TRUE if that list is constant.
2293*/
2294static int sqlite3InRhsIsConstant(Expr *pIn){
2295 Expr *pLHS;
2296 int res;
drh3b3c86a2018-09-18 21:35:31 +00002297 assert( pIn->eX!=EX_Select );
drhbb53ecb2014-08-02 21:03:33 +00002298 pLHS = pIn->pLeft;
2299 pIn->pLeft = 0;
2300 res = sqlite3ExprIsConstant(pIn);
2301 pIn->pLeft = pLHS;
2302 return res;
2303}
2304#endif
2305
drh6be515e2014-08-01 21:00:53 +00002306/*
danielk19779a96b662007-11-29 17:05:18 +00002307** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00002308** The pX parameter is the expression on the RHS of the IN operator, which
2309** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00002310**
drhd4305ca2012-09-18 17:08:33 +00002311** The job of this routine is to find or create a b-tree object that can
2312** be used either to test for membership in the RHS set or to iterate through
2313** all members of the RHS set, skipping duplicates.
2314**
drh3a856252014-08-01 14:46:57 +00002315** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00002316** and pX->iTable is set to the index of that cursor.
2317**
drhb74b1012009-05-28 21:04:37 +00002318** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00002319**
drh1ccce442013-03-12 20:38:51 +00002320** IN_INDEX_ROWID - The cursor was opened on a database table.
2321** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
2322** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
2323** IN_INDEX_EPH - The cursor was opened on a specially created and
2324** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00002325** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
2326** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00002327**
drhd4305ca2012-09-18 17:08:33 +00002328** An existing b-tree might be used if the RHS expression pX is a simple
2329** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00002330**
dan553168c2016-08-01 20:14:31 +00002331** SELECT <column1>, <column2>... FROM <table>
danielk19779a96b662007-11-29 17:05:18 +00002332**
drhd4305ca2012-09-18 17:08:33 +00002333** If the RHS of the IN operator is a list or a more complex subquery, then
2334** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00002335** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00002336** existing table.
drhd4305ca2012-09-18 17:08:33 +00002337**
drh7fc0ba02017-11-17 15:02:00 +00002338** The inFlags parameter must contain, at a minimum, one of the bits
2339** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP but not both. If inFlags contains
2340** IN_INDEX_MEMBERSHIP, then the generated table will be used for a fast
2341** membership test. When the IN_INDEX_LOOP bit is set, the IN index will
2342** be used to loop over all values of the RHS of the IN operator.
drh3a856252014-08-01 14:46:57 +00002343**
2344** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
2345** through the set members) then the b-tree must not contain duplicates.
drh7fc0ba02017-11-17 15:02:00 +00002346** An epheremal table will be created unless the selected columns are guaranteed
dan553168c2016-08-01 20:14:31 +00002347** to be unique - either because it is an INTEGER PRIMARY KEY or due to
2348** a UNIQUE constraint or index.
danielk19770cdc0222008-06-26 18:04:03 +00002349**
drh3a856252014-08-01 14:46:57 +00002350** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
2351** for fast set membership tests) then an epheremal table must
dan553168c2016-08-01 20:14:31 +00002352** be used unless <columns> is a single INTEGER PRIMARY KEY column or an
2353** index can be found with the specified <columns> as its left-most.
danielk19770cdc0222008-06-26 18:04:03 +00002354**
drhbb53ecb2014-08-02 21:03:33 +00002355** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
2356** if the RHS of the IN operator is a list (not a subquery) then this
2357** routine might decide that creating an ephemeral b-tree for membership
2358** testing is too expensive and return IN_INDEX_NOOP. In that case, the
2359** calling routine should implement the IN operator using a sequence
2360** of Eq or Ne comparison operations.
2361**
drhb74b1012009-05-28 21:04:37 +00002362** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00002363** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00002364** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00002365** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00002366** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00002367** to *prRhsHasNull. If there is no chance that the (...) contains a
2368** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00002369**
drhe21a6e12014-08-01 18:00:24 +00002370** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00002371** the value in that register will be NULL if the b-tree contains one or more
2372** NULL values, and it will be some non-NULL value if the b-tree contains no
2373** NULL values.
dan553168c2016-08-01 20:14:31 +00002374**
2375** If the aiMap parameter is not NULL, it must point to an array containing
2376** one element for each column returned by the SELECT statement on the RHS
2377** of the IN(...) operator. The i'th entry of the array is populated with the
2378** offset of the index column that matches the i'th column returned by the
2379** SELECT. For example, if the expression and selected index are:
2380**
2381** (?,?,?) IN (SELECT a, b, c FROM t1)
2382** CREATE INDEX i1 ON t1(b, c, a);
2383**
2384** then aiMap[] is populated with {2, 0, 1}.
danielk19779a96b662007-11-29 17:05:18 +00002385*/
danielk1977284f4ac2007-12-10 05:03:46 +00002386#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00002387int sqlite3FindInIndex(
drh6fc8f362016-08-26 19:31:29 +00002388 Parse *pParse, /* Parsing context */
2389 Expr *pX, /* The right-hand side (RHS) of the IN operator */
2390 u32 inFlags, /* IN_INDEX_LOOP, _MEMBERSHIP, and/or _NOOP_OK */
2391 int *prRhsHasNull, /* Register holding NULL status. See notes */
2392 int *aiMap /* Mapping from Index fields to RHS fields */
danba00e302016-07-23 20:24:06 +00002393){
drhb74b1012009-05-28 21:04:37 +00002394 Select *p; /* SELECT to the right of IN operator */
2395 int eType = 0; /* Type of RHS table. IN_INDEX_* */
2396 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00002397 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00002398 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00002399
drh1450bc62009-10-30 13:25:56 +00002400 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00002401 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00002402
dan7b35a772016-07-28 19:47:15 +00002403 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
2404 ** whether or not the SELECT result contains NULL values, check whether
dan870a0702016-08-01 16:37:43 +00002405 ** or not NULL is actually possible (it may not be, for example, due
dan7b35a772016-07-28 19:47:15 +00002406 ** to NOT NULL constraints in the schema). If no NULL values are possible,
dan870a0702016-08-01 16:37:43 +00002407 ** set prRhsHasNull to 0 before continuing. */
drh3b3c86a2018-09-18 21:35:31 +00002408 if( prRhsHasNull && pX->eX==EX_Select ){
dan7b35a772016-07-28 19:47:15 +00002409 int i;
2410 ExprList *pEList = pX->x.pSelect->pEList;
2411 for(i=0; i<pEList->nExpr; i++){
2412 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
2413 }
2414 if( i==pEList->nExpr ){
2415 prRhsHasNull = 0;
2416 }
2417 }
2418
drhb74b1012009-05-28 21:04:37 +00002419 /* Check to see if an existing table or index can be used to
2420 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00002421 ** ephemeral table. */
2422 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00002423 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00002424 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00002425 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00002426 ExprList *pEList = p->pEList;
2427 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00002428
drhb07028f2011-10-14 21:49:18 +00002429 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
2430 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
2431 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
2432 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00002433
drhb22f7c82014-02-06 23:56:27 +00002434 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00002435 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
2436 sqlite3CodeVerifySchema(pParse, iDb);
2437 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00002438
drha84a2832016-08-26 21:15:35 +00002439 assert(v); /* sqlite3GetVdbe() has always been previously called */
dancfbb5e82016-07-13 19:48:13 +00002440 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh62659b22016-08-24 18:51:23 +00002441 /* The "x IN (SELECT rowid FROM table)" case */
drh511f9e82016-09-22 18:53:13 +00002442 int iAddr = sqlite3VdbeAddOp0(v, OP_Once);
drh7d176102014-02-18 03:07:12 +00002443 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00002444
2445 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
2446 eType = IN_INDEX_ROWID;
drhd8852092018-08-16 15:29:40 +00002447 ExplainQueryPlan((pParse, 0,
2448 "USING ROWID SEARCH ON TABLE %s FOR IN-OPERATOR",pTab->zName));
danielk19779a96b662007-11-29 17:05:18 +00002449 sqlite3VdbeJumpHere(v, iAddr);
2450 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00002451 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00002452 int affinity_ok = 1;
2453 int i;
2454
2455 /* Check that the affinity that will be used to perform each
drh62659b22016-08-24 18:51:23 +00002456 ** comparison is the same as the affinity of each column in table
2457 ** on the RHS of the IN operator. If it not, it is not possible to
2458 ** use any index of the RHS table. */
dancfbb5e82016-07-13 19:48:13 +00002459 for(i=0; i<nExpr && affinity_ok; i++){
drhfc7f27b2016-08-20 00:07:01 +00002460 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
dancfbb5e82016-07-13 19:48:13 +00002461 int iCol = pEList->a[i].pExpr->iColumn;
drh0dfa4f62016-08-26 13:19:49 +00002462 char idxaff = sqlite3TableColumnAffinity(pTab,iCol); /* RHS table */
dancfbb5e82016-07-13 19:48:13 +00002463 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
drh62659b22016-08-24 18:51:23 +00002464 testcase( cmpaff==SQLITE_AFF_BLOB );
2465 testcase( cmpaff==SQLITE_AFF_TEXT );
dancfbb5e82016-07-13 19:48:13 +00002466 switch( cmpaff ){
2467 case SQLITE_AFF_BLOB:
2468 break;
2469 case SQLITE_AFF_TEXT:
drh62659b22016-08-24 18:51:23 +00002470 /* sqlite3CompareAffinity() only returns TEXT if one side or the
2471 ** other has no affinity and the other side is TEXT. Hence,
2472 ** the only way for cmpaff to be TEXT is for idxaff to be TEXT
2473 ** and for the term on the LHS of the IN to have no affinity. */
2474 assert( idxaff==SQLITE_AFF_TEXT );
dancfbb5e82016-07-13 19:48:13 +00002475 break;
2476 default:
2477 affinity_ok = sqlite3IsNumericAffinity(idxaff);
2478 }
2479 }
danielk1977e1fb65a2009-04-02 17:23:32 +00002480
drha84a2832016-08-26 21:15:35 +00002481 if( affinity_ok ){
2482 /* Search for an existing index that will work for this IN operator */
2483 for(pIdx=pTab->pIndex; pIdx && eType==0; pIdx=pIdx->pNext){
2484 Bitmask colUsed; /* Columns of the index used */
2485 Bitmask mCol; /* Mask for the current column */
2486 if( pIdx->nColumn<nExpr ) continue;
2487 /* Maximum nColumn is BMS-2, not BMS-1, so that we can compute
2488 ** BITMASK(nExpr) without overflowing */
2489 testcase( pIdx->nColumn==BMS-2 );
2490 testcase( pIdx->nColumn==BMS-1 );
2491 if( pIdx->nColumn>=BMS-1 ) continue;
2492 if( mustBeUnique ){
2493 if( pIdx->nKeyCol>nExpr
2494 ||(pIdx->nColumn>nExpr && !IsUniqueIndex(pIdx))
2495 ){
2496 continue; /* This index is not unique over the IN RHS columns */
dan7b35a772016-07-28 19:47:15 +00002497 }
danielk19770cdc0222008-06-26 18:04:03 +00002498 }
drha84a2832016-08-26 21:15:35 +00002499
2500 colUsed = 0; /* Columns of index used so far */
2501 for(i=0; i<nExpr; i++){
2502 Expr *pLhs = sqlite3VectorFieldSubexpr(pX->pLeft, i);
2503 Expr *pRhs = pEList->a[i].pExpr;
drh3d6bedf2018-09-19 14:54:38 +00002504 CollSeq *pReq = sqlite3ComparisonCollSeq(pParse, pLhs, pRhs);
drha84a2832016-08-26 21:15:35 +00002505 int j;
2506
2507 assert( pReq!=0 || pRhs->iColumn==XN_ROWID || pParse->nErr );
2508 for(j=0; j<nExpr; j++){
2509 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
2510 assert( pIdx->azColl[j] );
drh106526e2016-08-26 22:09:01 +00002511 if( pReq!=0 && sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ){
2512 continue;
2513 }
drha84a2832016-08-26 21:15:35 +00002514 break;
2515 }
2516 if( j==nExpr ) break;
2517 mCol = MASKBIT(j);
2518 if( mCol & colUsed ) break; /* Each column used only once */
2519 colUsed |= mCol;
2520 if( aiMap ) aiMap[i] = j;
2521 }
2522
2523 assert( i==nExpr || colUsed!=(MASKBIT(nExpr)-1) );
2524 if( colUsed==(MASKBIT(nExpr)-1) ){
2525 /* If we reach this point, that means the index pIdx is usable */
drh511f9e82016-09-22 18:53:13 +00002526 int iAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
drhe2ca99c2018-05-02 00:33:43 +00002527 ExplainQueryPlan((pParse, 0,
2528 "USING INDEX %s FOR IN-OPERATOR",pIdx->zName));
drha84a2832016-08-26 21:15:35 +00002529 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2530 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
2531 VdbeComment((v, "%s", pIdx->zName));
2532 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2533 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
2534
2535 if( prRhsHasNull ){
drhb80dbdc2016-09-09 15:12:41 +00002536#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
drha84a2832016-08-26 21:15:35 +00002537 i64 mask = (1<<nExpr)-1;
2538 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
2539 iTab, 0, 0, (u8*)&mask, P4_INT64);
drhb80dbdc2016-09-09 15:12:41 +00002540#endif
2541 *prRhsHasNull = ++pParse->nMem;
drha84a2832016-08-26 21:15:35 +00002542 if( nExpr==1 ){
2543 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2544 }
2545 }
2546 sqlite3VdbeJumpHere(v, iAddr);
2547 }
2548 } /* End loop over indexes */
2549 } /* End if( affinity_ok ) */
2550 } /* End if not an rowid index */
2551 } /* End attempt to optimize using an index */
danielk19779a96b662007-11-29 17:05:18 +00002552
drhbb53ecb2014-08-02 21:03:33 +00002553 /* If no preexisting index is available for the IN clause
2554 ** and IN_INDEX_NOOP is an allowed reply
2555 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002556 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002557 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002558 ** the IN operator so return IN_INDEX_NOOP.
2559 */
2560 if( eType==0
drh3b3c86a2018-09-18 21:35:31 +00002561 && (inFlags & IN_INDEX_NOOP_OK)!=0
2562 && pX->eX==EX_List
drhbb53ecb2014-08-02 21:03:33 +00002563 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2564 ){
2565 eType = IN_INDEX_NOOP;
2566 }
drhbb53ecb2014-08-02 21:03:33 +00002567
danielk19779a96b662007-11-29 17:05:18 +00002568 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002569 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002570 ** We will have to generate an ephemeral table to do the job.
2571 */
drh8e23daf2013-06-11 13:30:04 +00002572 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002573 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002574 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002575 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002576 pParse->nQueryLoop = 0;
drh3b3c86a2018-09-18 21:35:31 +00002577 if( pX->pLeft->iColumn<0 && pX->eX==EX_List ){
drhcf4d38a2010-07-28 02:53:36 +00002578 eType = IN_INDEX_ROWID;
2579 }
drhe21a6e12014-08-01 18:00:24 +00002580 }else if( prRhsHasNull ){
2581 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002582 }
danielk197741a05b72008-10-02 13:50:55 +00002583 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002584 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002585 }else{
2586 pX->iTable = iTab;
2587 }
danba00e302016-07-23 20:24:06 +00002588
2589 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2590 int i, n;
2591 n = sqlite3ExprVectorSize(pX->pLeft);
2592 for(i=0; i<n; i++) aiMap[i] = i;
2593 }
danielk19779a96b662007-11-29 17:05:18 +00002594 return eType;
2595}
danielk1977284f4ac2007-12-10 05:03:46 +00002596#endif
drh626a8792005-01-17 22:08:19 +00002597
danf9b2e052016-08-02 17:45:00 +00002598#ifndef SQLITE_OMIT_SUBQUERY
dan553168c2016-08-01 20:14:31 +00002599/*
2600** Argument pExpr is an (?, ?...) IN(...) expression. This
2601** function allocates and returns a nul-terminated string containing
2602** the affinities to be used for each column of the comparison.
2603**
2604** It is the responsibility of the caller to ensure that the returned
2605** string is eventually freed using sqlite3DbFree().
2606*/
dan71c57db2016-07-09 20:23:55 +00002607static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2608 Expr *pLeft = pExpr->pLeft;
2609 int nVal = sqlite3ExprVectorSize(pLeft);
drh3b3c86a2018-09-18 21:35:31 +00002610 Select *pSelect = (pExpr->eX==EX_Select) ? pExpr->x.pSelect : 0;
dan71c57db2016-07-09 20:23:55 +00002611 char *zRet;
2612
dan553168c2016-08-01 20:14:31 +00002613 assert( pExpr->op==TK_IN );
drh5c258dc2017-02-16 17:18:07 +00002614 zRet = sqlite3DbMallocRaw(pParse->db, nVal+1);
dan71c57db2016-07-09 20:23:55 +00002615 if( zRet ){
2616 int i;
2617 for(i=0; i<nVal; i++){
drhfc7f27b2016-08-20 00:07:01 +00002618 Expr *pA = sqlite3VectorFieldSubexpr(pLeft, i);
dan553168c2016-08-01 20:14:31 +00002619 char a = sqlite3ExprAffinity(pA);
2620 if( pSelect ){
2621 zRet[i] = sqlite3CompareAffinity(pSelect->pEList->a[i].pExpr, a);
2622 }else{
2623 zRet[i] = a;
dan71c57db2016-07-09 20:23:55 +00002624 }
dan71c57db2016-07-09 20:23:55 +00002625 }
2626 zRet[nVal] = '\0';
2627 }
2628 return zRet;
2629}
danf9b2e052016-08-02 17:45:00 +00002630#endif
dan71c57db2016-07-09 20:23:55 +00002631
dan8da209b2016-07-26 18:06:08 +00002632#ifndef SQLITE_OMIT_SUBQUERY
2633/*
2634** Load the Parse object passed as the first argument with an error
2635** message of the form:
2636**
2637** "sub-select returns N columns - expected M"
2638*/
2639void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2640 const char *zFmt = "sub-select returns %d columns - expected %d";
2641 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2642}
2643#endif
2644
drh626a8792005-01-17 22:08:19 +00002645/*
dan44c56042016-12-07 15:38:37 +00002646** Expression pExpr is a vector that has been used in a context where
2647** it is not permitted. If pExpr is a sub-select vector, this routine
2648** loads the Parse object with a message of the form:
2649**
2650** "sub-select returns N columns - expected 1"
2651**
2652** Or, if it is a regular scalar vector:
2653**
2654** "row value misused"
2655*/
2656void sqlite3VectorErrorMsg(Parse *pParse, Expr *pExpr){
2657#ifndef SQLITE_OMIT_SUBQUERY
drh3b3c86a2018-09-18 21:35:31 +00002658 if( pExpr->eX==EX_Select ){
dan44c56042016-12-07 15:38:37 +00002659 sqlite3SubselectError(pParse, pExpr->x.pSelect->pEList->nExpr, 1);
2660 }else
2661#endif
2662 {
2663 sqlite3ErrorMsg(pParse, "row value misused");
2664 }
2665}
2666
2667/*
drhd4187c72010-08-30 22:15:45 +00002668** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2669** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002670**
drh9cbe6352005-11-29 03:13:21 +00002671** (SELECT a FROM b) -- subquery
2672** EXISTS (SELECT a FROM b) -- EXISTS subquery
2673** x IN (4,5,11) -- IN operator with list on right-hand side
2674** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002675**
drh9cbe6352005-11-29 03:13:21 +00002676** The pExpr parameter describes the expression that contains the IN
2677** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002678**
2679** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2680** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2681** to some integer key column of a table B-Tree. In this case, use an
2682** intkey B-Tree to store the set of IN(...) values instead of the usual
2683** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002684**
2685** If rMayHaveNull is non-zero, that means that the operation is an IN
2686** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002687** All this routine does is initialize the register given by rMayHaveNull
2688** to NULL. Calling routines will take care of changing this register
2689** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002690**
2691** For a SELECT or EXISTS operator, return the register that holds the
drh39a11812016-08-19 19:12:58 +00002692** result. For a multi-column SELECT, the result is stored in a contiguous
2693** array of registers and the return value is the register of the left-most
2694** result column. Return 0 for IN operators or if an error occurs.
drhcce7d172000-05-31 15:34:51 +00002695*/
drh51522cd2005-01-20 13:36:19 +00002696#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002697int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002698 Parse *pParse, /* Parsing context */
2699 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002700 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002701 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002702){
drh6be515e2014-08-01 21:00:53 +00002703 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002704 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002705 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002706 if( NEVER(v==0) ) return 0;
danielk1977fc976062007-05-10 10:46:56 +00002707
drh39a11812016-08-19 19:12:58 +00002708 /* The evaluation of the IN/EXISTS/SELECT must be repeated every time it
2709 ** is encountered if any of the following is true:
drh57dbd7b2005-07-08 18:25:26 +00002710 **
2711 ** * The right-hand side is a correlated subquery
2712 ** * The right-hand side is an expression list containing variables
2713 ** * We are inside a trigger
2714 **
2715 ** If all of the above are false, then we can run this code just once
2716 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002717 */
drhc5cd1242013-09-12 16:50:49 +00002718 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh511f9e82016-09-22 18:53:13 +00002719 jmpIfDynamic = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002720 }
2721
drhcce7d172000-05-31 15:34:51 +00002722 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002723 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002724 int addr; /* Address of OP_OpenEphemeral instruction */
2725 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002726 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002727 int nVal; /* Size of vector pLeft */
2728
2729 nVal = sqlite3ExprVectorSize(pLeft);
dan553168c2016-08-01 20:14:31 +00002730 assert( !isRowid || nVal==1 );
danielk1977e014a832004-05-17 10:48:57 +00002731
2732 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002733 ** expression it is handled the same way. An ephemeral table is
dan553168c2016-08-01 20:14:31 +00002734 ** filled with index keys representing the results from the
2735 ** SELECT or the <exprlist>.
danielk1977e014a832004-05-17 10:48:57 +00002736 **
2737 ** If the 'x' expression is a column value, or the SELECT...
2738 ** statement returns a column value, then the affinity of that
2739 ** column is used to build the index keys. If both 'x' and the
2740 ** SELECT... statement are columns, then numeric affinity is used
2741 ** if either column has NUMERIC or INTEGER affinity. If neither
2742 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2743 ** is used.
2744 */
2745 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002746 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2747 pExpr->iTable, (isRowid?0:nVal));
2748 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002749
drh3b3c86a2018-09-18 21:35:31 +00002750 assert( pExpr->eX==EX_Select || pExpr->eX==EX_List );
2751 if( pExpr->eX==EX_Select ){
drhfef52082000-06-06 01:50:43 +00002752 /* Case 1: expr IN (SELECT ...)
2753 **
danielk1977e014a832004-05-17 10:48:57 +00002754 ** Generate code to write the results of the select into the temporary
2755 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002756 */
drh43870062014-07-31 15:44:44 +00002757 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002758 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002759
drhe2ca99c2018-05-02 00:33:43 +00002760 ExplainQueryPlan((pParse, 1, "%sLIST SUBQUERY",
2761 jmpIfDynamic>=0?"":"CORRELATED "
2762 ));
danielk197741a05b72008-10-02 13:50:55 +00002763 assert( !isRowid );
drh64bcb8c2016-08-26 03:42:57 +00002764 /* If the LHS and RHS of the IN operator do not match, that
2765 ** error will have been caught long before we reach this point. */
2766 if( ALWAYS(pEList->nExpr==nVal) ){
dan71c57db2016-07-09 20:23:55 +00002767 SelectDest dest;
2768 int i;
2769 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2770 dest.zAffSdst = exprINAffinity(pParse, pExpr);
dan71c57db2016-07-09 20:23:55 +00002771 pSelect->iLimit = 0;
2772 testcase( pSelect->selFlags & SF_Distinct );
2773 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2774 if( sqlite3Select(pParse, pSelect, &dest) ){
2775 sqlite3DbFree(pParse->db, dest.zAffSdst);
2776 sqlite3KeyInfoUnref(pKeyInfo);
2777 return 0;
2778 }
2779 sqlite3DbFree(pParse->db, dest.zAffSdst);
2780 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2781 assert( pEList!=0 );
2782 assert( pEList->nExpr>0 );
2783 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2784 for(i=0; i<nVal; i++){
dan773d3af2016-09-06 17:21:17 +00002785 Expr *p = sqlite3VectorFieldSubexpr(pLeft, i);
drh3d6bedf2018-09-19 14:54:38 +00002786 pKeyInfo->aColl[i] = sqlite3ComparisonCollSeq(
dan71c57db2016-07-09 20:23:55 +00002787 pParse, p, pEList->a[i].pExpr
2788 );
2789 }
drh94ccde52007-04-13 16:06:32 +00002790 }
drha7d2db12010-07-14 20:23:52 +00002791 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002792 /* Case 2: expr IN (exprlist)
2793 **
drhfd131da2007-08-07 17:13:03 +00002794 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002795 ** store it in the temporary table. If <expr> is a column, then use
2796 ** that columns affinity when building index keys. If <expr> is not
2797 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002798 */
dan71c57db2016-07-09 20:23:55 +00002799 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002800 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002801 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002802 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002803 int r1, r2, r3;
dan71c57db2016-07-09 20:23:55 +00002804 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002805 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002806 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002807 }
drh323df792013-08-05 19:11:29 +00002808 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002809 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002810 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2811 }
danielk1977e014a832004-05-17 10:48:57 +00002812
2813 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002814 r1 = sqlite3GetTempReg(pParse);
2815 r2 = sqlite3GetTempReg(pParse);
dan21cd29a2017-10-23 16:03:54 +00002816 if( isRowid ) sqlite3VdbeAddOp4(v, OP_Blob, 0, r2, 0, "", P4_STATIC);
drh57dbd7b2005-07-08 18:25:26 +00002817 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2818 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002819 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002820
drh57dbd7b2005-07-08 18:25:26 +00002821 /* If the expression is not constant then we will need to
2822 ** disable the test that was generated above that makes sure
2823 ** this code only executes once. Because for a non-constant
2824 ** expression we need to rerun this code each time.
2825 */
drh6be515e2014-08-01 21:00:53 +00002826 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2827 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2828 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002829 }
danielk1977e014a832004-05-17 10:48:57 +00002830
2831 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002832 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2833 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002834 }else{
drhe05c9292009-10-29 13:48:10 +00002835 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2836 if( isRowid ){
2837 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2838 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002839 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002840 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2841 }else{
2842 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
drh9b4eaeb2016-11-09 00:10:33 +00002843 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pExpr->iTable, r2, r3, 1);
drhe05c9292009-10-29 13:48:10 +00002844 }
danielk197741a05b72008-10-02 13:50:55 +00002845 }
drhfef52082000-06-06 01:50:43 +00002846 }
drh2d401ab2008-01-10 23:50:11 +00002847 sqlite3ReleaseTempReg(pParse, r1);
2848 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002849 }
drh323df792013-08-05 19:11:29 +00002850 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002851 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002852 }
danielk1977b3bce662005-01-29 08:32:43 +00002853 break;
drhfef52082000-06-06 01:50:43 +00002854 }
2855
drh51522cd2005-01-20 13:36:19 +00002856 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002857 case TK_SELECT:
2858 default: {
drh39a11812016-08-19 19:12:58 +00002859 /* Case 3: (SELECT ... FROM ...)
2860 ** or: EXISTS(SELECT ... FROM ...)
2861 **
2862 ** For a SELECT, generate code to put the values for all columns of
2863 ** the first row into an array of registers and return the index of
2864 ** the first register.
2865 **
2866 ** If this is an EXISTS, write an integer 0 (not exists) or 1 (exists)
2867 ** into a register and return that register number.
2868 **
2869 ** In both cases, the query is augmented with "LIMIT 1". Any
2870 ** preexisting limit is discarded in place of the new LIMIT 1.
drhfef52082000-06-06 01:50:43 +00002871 */
drhfd773cf2009-05-29 14:39:07 +00002872 Select *pSel; /* SELECT statement to encode */
drh39a11812016-08-19 19:12:58 +00002873 SelectDest dest; /* How to deal with SELECT result */
dan71c57db2016-07-09 20:23:55 +00002874 int nReg; /* Registers to allocate */
drh8c0833f2017-11-14 23:48:23 +00002875 Expr *pLimit; /* New limit expression */
drh1398ad32005-01-19 23:24:50 +00002876
shanecf697392009-06-01 16:53:09 +00002877 testcase( pExpr->op==TK_EXISTS );
2878 testcase( pExpr->op==TK_SELECT );
2879 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
drh3b3c86a2018-09-18 21:35:31 +00002880 assert( pExpr->eX==EX_Select );
dan71c57db2016-07-09 20:23:55 +00002881
danielk19776ab3a2e2009-02-19 14:39:25 +00002882 pSel = pExpr->x.pSelect;
drhe2ca99c2018-05-02 00:33:43 +00002883 ExplainQueryPlan((pParse, 1, "%sSCALAR SUBQUERY",
2884 jmpIfDynamic>=0?"":"CORRELATED "));
dan71c57db2016-07-09 20:23:55 +00002885 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2886 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2887 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002888 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002889 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002890 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002891 dest.nSdst = nReg;
2892 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002893 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002894 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002895 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002896 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002897 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002898 }
drh8c0833f2017-11-14 23:48:23 +00002899 pLimit = sqlite3ExprAlloc(pParse->db, TK_INTEGER,&sqlite3IntTokens[1], 0);
2900 if( pSel->pLimit ){
2901 sqlite3ExprDelete(pParse->db, pSel->pLimit->pLeft);
2902 pSel->pLimit->pLeft = pLimit;
2903 }else{
2904 pSel->pLimit = sqlite3PExpr(pParse, TK_LIMIT, pLimit, 0);
2905 }
drh48b5b042010-12-06 18:50:32 +00002906 pSel->iLimit = 0;
drh7d10d5a2008-08-20 16:35:10 +00002907 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002908 return 0;
drh94ccde52007-04-13 16:06:32 +00002909 }
drh2b596da2012-07-23 21:43:19 +00002910 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002911 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002912 break;
drhcce7d172000-05-31 15:34:51 +00002913 }
2914 }
danielk1977b3bce662005-01-29 08:32:43 +00002915
drh6be515e2014-08-01 21:00:53 +00002916 if( rHasNullFlag ){
2917 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002918 }
drh6be515e2014-08-01 21:00:53 +00002919
2920 if( jmpIfDynamic>=0 ){
2921 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002922 }
danielk1977fc976062007-05-10 10:46:56 +00002923
drh1450bc62009-10-30 13:25:56 +00002924 return rReg;
drhcce7d172000-05-31 15:34:51 +00002925}
drh51522cd2005-01-20 13:36:19 +00002926#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002927
drhe3365e62009-11-12 17:52:24 +00002928#ifndef SQLITE_OMIT_SUBQUERY
2929/*
dan7b35a772016-07-28 19:47:15 +00002930** Expr pIn is an IN(...) expression. This function checks that the
2931** sub-select on the RHS of the IN() operator has the same number of
2932** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2933** a sub-query, that the LHS is a vector of size 1.
2934*/
2935int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2936 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
drh3b3c86a2018-09-18 21:35:31 +00002937 if( pIn->eX==EX_Select ){
dan7b35a772016-07-28 19:47:15 +00002938 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2939 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2940 return 1;
2941 }
2942 }else if( nVector!=1 ){
dan44c56042016-12-07 15:38:37 +00002943 sqlite3VectorErrorMsg(pParse, pIn->pLeft);
dan7b35a772016-07-28 19:47:15 +00002944 return 1;
2945 }
2946 return 0;
2947}
2948#endif
2949
2950#ifndef SQLITE_OMIT_SUBQUERY
2951/*
drhe3365e62009-11-12 17:52:24 +00002952** Generate code for an IN expression.
2953**
2954** x IN (SELECT ...)
2955** x IN (value, value, ...)
2956**
drhecb87ac2016-08-25 15:46:25 +00002957** The left-hand side (LHS) is a scalar or vector expression. The
drhe347d3e2016-08-25 21:14:34 +00002958** right-hand side (RHS) is an array of zero or more scalar values, or a
2959** subquery. If the RHS is a subquery, the number of result columns must
2960** match the number of columns in the vector on the LHS. If the RHS is
2961** a list of values, the LHS must be a scalar.
2962**
2963** The IN operator is true if the LHS value is contained within the RHS.
2964** The result is false if the LHS is definitely not in the RHS. The
2965** result is NULL if the presence of the LHS in the RHS cannot be
2966** determined due to NULLs.
drhe3365e62009-11-12 17:52:24 +00002967**
drh6be515e2014-08-01 21:00:53 +00002968** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002969** contained within the RHS. If due to NULLs we cannot determine if the LHS
2970** is contained in the RHS then jump to destIfNull. If the LHS is contained
2971** within the RHS then fall through.
drhecb87ac2016-08-25 15:46:25 +00002972**
2973** See the separate in-operator.md documentation file in the canonical
2974** SQLite source tree for additional information.
drhe3365e62009-11-12 17:52:24 +00002975*/
2976static void sqlite3ExprCodeIN(
2977 Parse *pParse, /* Parsing and code generating context */
2978 Expr *pExpr, /* The IN expression */
2979 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2980 int destIfNull /* Jump here if the results are unknown due to NULLs */
2981){
2982 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002983 int eType; /* Type of the RHS */
drhe347d3e2016-08-25 21:14:34 +00002984 int rLhs; /* Register(s) holding the LHS values */
2985 int rLhsOrig; /* LHS values prior to reordering by aiMap[] */
drhe3365e62009-11-12 17:52:24 +00002986 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002987 int *aiMap = 0; /* Map from vector field to index column */
2988 char *zAff = 0; /* Affinity string for comparisons */
drhe347d3e2016-08-25 21:14:34 +00002989 int nVector; /* Size of vectors for this IN operator */
2990 int iDummy; /* Dummy parameter to exprCodeVector() */
2991 Expr *pLeft; /* The LHS of the IN operator */
2992 int i; /* loop counter */
2993 int destStep2; /* Where to jump when NULLs seen in step 2 */
2994 int destStep6 = 0; /* Start of code for Step 6 */
2995 int addrTruthOp; /* Address of opcode that determines the IN is true */
2996 int destNotNull; /* Jump here if a comparison is not true in step 6 */
2997 int addrTop; /* Top of the step-6 loop */
drhe3365e62009-11-12 17:52:24 +00002998
drhe347d3e2016-08-25 21:14:34 +00002999 pLeft = pExpr->pLeft;
dan7b35a772016-07-28 19:47:15 +00003000 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
dan553168c2016-08-01 20:14:31 +00003001 zAff = exprINAffinity(pParse, pExpr);
danba00e302016-07-23 20:24:06 +00003002 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
3003 aiMap = (int*)sqlite3DbMallocZero(
3004 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
3005 );
drhe347d3e2016-08-25 21:14:34 +00003006 if( pParse->db->mallocFailed ) goto sqlite3ExprCodeIN_oom_error;
dan7b35a772016-07-28 19:47:15 +00003007
danba00e302016-07-23 20:24:06 +00003008 /* Attempt to compute the RHS. After this step, if anything other than
3009 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
3010 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
3011 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00003012 v = pParse->pVdbe;
3013 assert( v!=0 ); /* OOM detected prior to this routine */
3014 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00003015 eType = sqlite3FindInIndex(pParse, pExpr,
3016 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00003017 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00003018
danba00e302016-07-23 20:24:06 +00003019 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
3020 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
3021 );
drhecb87ac2016-08-25 15:46:25 +00003022#ifdef SQLITE_DEBUG
3023 /* Confirm that aiMap[] contains nVector integer values between 0 and
3024 ** nVector-1. */
3025 for(i=0; i<nVector; i++){
3026 int j, cnt;
3027 for(cnt=j=0; j<nVector; j++) if( aiMap[j]==i ) cnt++;
3028 assert( cnt==1 );
3029 }
3030#endif
drhe3365e62009-11-12 17:52:24 +00003031
danba00e302016-07-23 20:24:06 +00003032 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
3033 ** vector, then it is stored in an array of nVector registers starting
3034 ** at r1.
drhe347d3e2016-08-25 21:14:34 +00003035 **
3036 ** sqlite3FindInIndex() might have reordered the fields of the LHS vector
3037 ** so that the fields are in the same order as an existing index. The
3038 ** aiMap[] array contains a mapping from the original LHS field order to
3039 ** the field order that matches the RHS index.
drhe3365e62009-11-12 17:52:24 +00003040 */
drhe347d3e2016-08-25 21:14:34 +00003041 rLhsOrig = exprCodeVector(pParse, pLeft, &iDummy);
3042 for(i=0; i<nVector && aiMap[i]==i; i++){} /* Are LHS fields reordered? */
drhecb87ac2016-08-25 15:46:25 +00003043 if( i==nVector ){
drhe347d3e2016-08-25 21:14:34 +00003044 /* LHS fields are not reordered */
3045 rLhs = rLhsOrig;
drhecb87ac2016-08-25 15:46:25 +00003046 }else{
3047 /* Need to reorder the LHS fields according to aiMap */
drhe347d3e2016-08-25 21:14:34 +00003048 rLhs = sqlite3GetTempRange(pParse, nVector);
drhecb87ac2016-08-25 15:46:25 +00003049 for(i=0; i<nVector; i++){
drhe347d3e2016-08-25 21:14:34 +00003050 sqlite3VdbeAddOp3(v, OP_Copy, rLhsOrig+i, rLhs+aiMap[i], 0);
drhecb87ac2016-08-25 15:46:25 +00003051 }
danba00e302016-07-23 20:24:06 +00003052 }
drhe3365e62009-11-12 17:52:24 +00003053
drhbb53ecb2014-08-02 21:03:33 +00003054 /* If sqlite3FindInIndex() did not find or create an index that is
3055 ** suitable for evaluating the IN operator, then evaluate using a
3056 ** sequence of comparisons.
drhe347d3e2016-08-25 21:14:34 +00003057 **
3058 ** This is step (1) in the in-operator.md optimized algorithm.
drh094430e2010-07-14 18:24:06 +00003059 */
drhbb53ecb2014-08-02 21:03:33 +00003060 if( eType==IN_INDEX_NOOP ){
3061 ExprList *pList = pExpr->x.pList;
3062 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
3063 int labelOk = sqlite3VdbeMakeLabel(v);
3064 int r2, regToFree;
3065 int regCkNull = 0;
3066 int ii;
drh3b3c86a2018-09-18 21:35:31 +00003067 assert( pExpr->eX==EX_List );
drhbb53ecb2014-08-02 21:03:33 +00003068 if( destIfNull!=destIfFalse ){
3069 regCkNull = sqlite3GetTempReg(pParse);
drhe347d3e2016-08-25 21:14:34 +00003070 sqlite3VdbeAddOp3(v, OP_BitAnd, rLhs, rLhs, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00003071 }
3072 for(ii=0; ii<pList->nExpr; ii++){
3073 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00003074 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00003075 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
3076 }
3077 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
drhe347d3e2016-08-25 21:14:34 +00003078 sqlite3VdbeAddOp4(v, OP_Eq, rLhs, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00003079 (void*)pColl, P4_COLLSEQ);
3080 VdbeCoverageIf(v, ii<pList->nExpr-1);
3081 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00003082 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00003083 }else{
3084 assert( destIfNull==destIfFalse );
drhe347d3e2016-08-25 21:14:34 +00003085 sqlite3VdbeAddOp4(v, OP_Ne, rLhs, destIfFalse, r2,
drhbb53ecb2014-08-02 21:03:33 +00003086 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00003087 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00003088 }
3089 sqlite3ReleaseTempReg(pParse, regToFree);
3090 }
3091 if( regCkNull ){
3092 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00003093 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00003094 }
3095 sqlite3VdbeResolveLabel(v, labelOk);
3096 sqlite3ReleaseTempReg(pParse, regCkNull);
drhe347d3e2016-08-25 21:14:34 +00003097 goto sqlite3ExprCodeIN_finished;
3098 }
3099
3100 /* Step 2: Check to see if the LHS contains any NULL columns. If the
3101 ** LHS does contain NULLs then the result must be either FALSE or NULL.
3102 ** We will then skip the binary search of the RHS.
3103 */
3104 if( destIfNull==destIfFalse ){
3105 destStep2 = destIfFalse;
drh094430e2010-07-14 18:24:06 +00003106 }else{
drhe347d3e2016-08-25 21:14:34 +00003107 destStep2 = destStep6 = sqlite3VdbeMakeLabel(v);
3108 }
3109 for(i=0; i<nVector; i++){
3110 Expr *p = sqlite3VectorFieldSubexpr(pExpr->pLeft, i);
3111 if( sqlite3ExprCanBeNull(p) ){
3112 sqlite3VdbeAddOp2(v, OP_IsNull, rLhs+i, destStep2);
dand49fd4e2016-07-27 19:33:04 +00003113 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00003114 }
drhe3365e62009-11-12 17:52:24 +00003115 }
drhe347d3e2016-08-25 21:14:34 +00003116
3117 /* Step 3. The LHS is now known to be non-NULL. Do the binary search
3118 ** of the RHS using the LHS as a probe. If found, the result is
3119 ** true.
3120 */
3121 if( eType==IN_INDEX_ROWID ){
3122 /* In this case, the RHS is the ROWID of table b-tree and so we also
3123 ** know that the RHS is non-NULL. Hence, we combine steps 3 and 4
3124 ** into a single opcode. */
3125 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, rLhs);
3126 VdbeCoverage(v);
3127 addrTruthOp = sqlite3VdbeAddOp0(v, OP_Goto); /* Return True */
3128 }else{
3129 sqlite3VdbeAddOp4(v, OP_Affinity, rLhs, nVector, 0, zAff, nVector);
3130 if( destIfFalse==destIfNull ){
3131 /* Combine Step 3 and Step 5 into a single opcode */
3132 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse,
3133 rLhs, nVector); VdbeCoverage(v);
3134 goto sqlite3ExprCodeIN_finished;
3135 }
3136 /* Ordinary Step 3, for the case where FALSE and NULL are distinct */
3137 addrTruthOp = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0,
3138 rLhs, nVector); VdbeCoverage(v);
3139 }
3140
3141 /* Step 4. If the RHS is known to be non-NULL and we did not find
3142 ** an match on the search above, then the result must be FALSE.
3143 */
3144 if( rRhsHasNull && nVector==1 ){
3145 sqlite3VdbeAddOp2(v, OP_NotNull, rRhsHasNull, destIfFalse);
3146 VdbeCoverage(v);
3147 }
3148
3149 /* Step 5. If we do not care about the difference between NULL and
3150 ** FALSE, then just return false.
3151 */
3152 if( destIfFalse==destIfNull ) sqlite3VdbeGoto(v, destIfFalse);
3153
3154 /* Step 6: Loop through rows of the RHS. Compare each row to the LHS.
3155 ** If any comparison is NULL, then the result is NULL. If all
3156 ** comparisons are FALSE then the final result is FALSE.
3157 **
3158 ** For a scalar LHS, it is sufficient to check just the first row
3159 ** of the RHS.
3160 */
3161 if( destStep6 ) sqlite3VdbeResolveLabel(v, destStep6);
3162 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
3163 VdbeCoverage(v);
3164 if( nVector>1 ){
3165 destNotNull = sqlite3VdbeMakeLabel(v);
3166 }else{
3167 /* For nVector==1, combine steps 6 and 7 by immediately returning
3168 ** FALSE if the first comparison is not NULL */
3169 destNotNull = destIfFalse;
3170 }
3171 for(i=0; i<nVector; i++){
3172 Expr *p;
3173 CollSeq *pColl;
3174 int r3 = sqlite3GetTempReg(pParse);
3175 p = sqlite3VectorFieldSubexpr(pLeft, i);
3176 pColl = sqlite3ExprCollSeq(pParse, p);
3177 sqlite3VdbeAddOp3(v, OP_Column, pExpr->iTable, i, r3);
3178 sqlite3VdbeAddOp4(v, OP_Ne, rLhs+i, destNotNull, r3,
3179 (void*)pColl, P4_COLLSEQ);
3180 VdbeCoverage(v);
3181 sqlite3ReleaseTempReg(pParse, r3);
3182 }
3183 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
3184 if( nVector>1 ){
3185 sqlite3VdbeResolveLabel(v, destNotNull);
3186 sqlite3VdbeAddOp2(v, OP_Next, pExpr->iTable, addrTop+1);
3187 VdbeCoverage(v);
3188
3189 /* Step 7: If we reach this point, we know that the result must
3190 ** be false. */
3191 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
3192 }
3193
3194 /* Jumps here in order to return true. */
3195 sqlite3VdbeJumpHere(v, addrTruthOp);
3196
3197sqlite3ExprCodeIN_finished:
3198 if( rLhs!=rLhsOrig ) sqlite3ReleaseTempReg(pParse, rLhs);
drhecb87ac2016-08-25 15:46:25 +00003199 VdbeComment((v, "end IN expr"));
drhe347d3e2016-08-25 21:14:34 +00003200sqlite3ExprCodeIN_oom_error:
danba00e302016-07-23 20:24:06 +00003201 sqlite3DbFree(pParse->db, aiMap);
dan553168c2016-08-01 20:14:31 +00003202 sqlite3DbFree(pParse->db, zAff);
drhe3365e62009-11-12 17:52:24 +00003203}
3204#endif /* SQLITE_OMIT_SUBQUERY */
3205
drh13573c72010-01-12 17:04:07 +00003206#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003207/*
3208** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00003209** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00003210**
3211** The z[] string will probably not be zero-terminated. But the
3212** z[n] character is guaranteed to be something that does not look
3213** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00003214*/
drhb7916a72009-05-27 10:31:29 +00003215static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00003216 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00003217 double value;
drh9339da12010-09-30 00:50:49 +00003218 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00003219 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
3220 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00003221 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00003222 }
3223}
drh13573c72010-01-12 17:04:07 +00003224#endif
drh598f1342007-10-23 15:39:45 +00003225
3226
3227/*
drhfec19aa2004-05-19 20:41:03 +00003228** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00003229** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00003230**
shaneh5f1d6b62010-09-30 16:51:25 +00003231** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00003232*/
drh13573c72010-01-12 17:04:07 +00003233static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
3234 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00003235 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00003236 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00003237 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00003238 if( negFlag ) i = -i;
3239 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00003240 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00003241 int c;
3242 i64 value;
drhfd773cf2009-05-29 14:39:07 +00003243 const char *z = pExpr->u.zToken;
3244 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00003245 c = sqlite3DecOrHexToI64(z, &value);
drh84d4f1a2017-09-20 10:47:10 +00003246 if( (c==3 && !negFlag) || (c==2) || (negFlag && value==SMALLEST_INT64)){
drh13573c72010-01-12 17:04:07 +00003247#ifdef SQLITE_OMIT_FLOATING_POINT
3248 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
3249#else
drh1b7ddc52014-07-23 14:52:05 +00003250#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00003251 if( sqlite3_strnicmp(z,"0x",2)==0 ){
drh77320ea2016-11-30 14:47:37 +00003252 sqlite3ErrorMsg(pParse, "hex literal too big: %s%s", negFlag?"-":"",z);
drh1b7ddc52014-07-23 14:52:05 +00003253 }else
3254#endif
3255 {
drh9296c182014-07-23 13:40:49 +00003256 codeReal(v, z, negFlag, iMem);
3257 }
drh13573c72010-01-12 17:04:07 +00003258#endif
drh77320ea2016-11-30 14:47:37 +00003259 }else{
drh84d4f1a2017-09-20 10:47:10 +00003260 if( negFlag ){ value = c==3 ? SMALLEST_INT64 : -value; }
drh77320ea2016-11-30 14:47:37 +00003261 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00003262 }
drhfec19aa2004-05-19 20:41:03 +00003263 }
3264}
3265
drh5cd79232009-05-25 11:46:29 +00003266
drh1f9ca2c2015-08-25 16:57:52 +00003267/* Generate code that will load into register regOut a value that is
3268** appropriate for the iIdxCol-th column of index pIdx.
3269*/
3270void sqlite3ExprCodeLoadIndexColumn(
3271 Parse *pParse, /* The parsing context */
3272 Index *pIdx, /* The index whose column is to be loaded */
3273 int iTabCur, /* Cursor pointing to a table row */
3274 int iIdxCol, /* The column of the index to be loaded */
3275 int regOut /* Store the index column value in this register */
3276){
3277 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00003278 if( iTabCol==XN_EXPR ){
3279 assert( pIdx->aColExpr );
3280 assert( pIdx->aColExpr->nExpr>iIdxCol );
drh3e34eab2017-07-19 19:48:40 +00003281 pParse->iSelfTab = iTabCur + 1;
drh1c75c9d2015-12-21 15:22:13 +00003282 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh3e34eab2017-07-19 19:48:40 +00003283 pParse->iSelfTab = 0;
drh4b92f982015-09-29 17:20:14 +00003284 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003285 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
3286 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00003287 }
drh1f9ca2c2015-08-25 16:57:52 +00003288}
3289
drh5cd79232009-05-25 11:46:29 +00003290/*
drh5c092e82010-05-14 19:24:02 +00003291** Generate code to extract the value of the iCol-th column of a table.
3292*/
3293void sqlite3ExprCodeGetColumnOfTable(
3294 Vdbe *v, /* The VDBE under construction */
3295 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00003296 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00003297 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00003298 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00003299){
drhaca19e12017-04-07 19:41:31 +00003300 if( pTab==0 ){
3301 sqlite3VdbeAddOp3(v, OP_Column, iTabCur, iCol, regOut);
3302 return;
3303 }
drh5c092e82010-05-14 19:24:02 +00003304 if( iCol<0 || iCol==pTab->iPKey ){
3305 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
3306 }else{
3307 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00003308 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00003309 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00003310 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
3311 }
3312 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00003313 }
3314 if( iCol>=0 ){
3315 sqlite3ColumnDefault(v, pTab, iCol, regOut);
3316 }
3317}
3318
3319/*
drh945498f2007-02-24 11:52:52 +00003320** Generate code that will extract the iColumn-th column from
drh8c607192018-08-04 15:53:55 +00003321** table pTab and store the column value in register iReg.
drhe55cbd72008-03-31 23:48:03 +00003322**
3323** There must be an open cursor to pTab in iTable when this routine
3324** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00003325*/
drhe55cbd72008-03-31 23:48:03 +00003326int sqlite3ExprCodeGetColumn(
3327 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00003328 Table *pTab, /* Description of the table we are reading from */
3329 int iColumn, /* Index of the table column */
3330 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00003331 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00003332 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00003333){
drhe55cbd72008-03-31 23:48:03 +00003334 Vdbe *v = pParse->pVdbe;
drhe55cbd72008-03-31 23:48:03 +00003335 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00003336 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00003337 if( p5 ){
3338 sqlite3VdbeChangeP5(v, p5);
drha748fdc2012-03-28 01:34:47 +00003339 }
drhe55cbd72008-03-31 23:48:03 +00003340 return iReg;
3341}
drhe55cbd72008-03-31 23:48:03 +00003342
3343/*
drhb21e7c72008-06-22 12:37:57 +00003344** Generate code to move content from registers iFrom...iFrom+nReg-1
drh36a5d882018-08-04 17:15:56 +00003345** over to iTo..iTo+nReg-1.
drhe55cbd72008-03-31 23:48:03 +00003346*/
drhb21e7c72008-06-22 12:37:57 +00003347void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00003348 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00003349 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh945498f2007-02-24 11:52:52 +00003350}
3351
drh652fbf52008-04-01 01:42:41 +00003352/*
drh12abf402016-08-22 14:30:05 +00003353** Convert a scalar expression node to a TK_REGISTER referencing
3354** register iReg. The caller must ensure that iReg already contains
3355** the correct value for the expression.
drha4c3c872013-09-12 17:29:25 +00003356*/
3357static void exprToRegister(Expr *p, int iReg){
3358 p->op2 = p->op;
3359 p->op = TK_REGISTER;
3360 p->iTable = iReg;
3361 ExprClearProperty(p, EP_Skip);
3362}
3363
drh12abf402016-08-22 14:30:05 +00003364/*
3365** Evaluate an expression (either a vector or a scalar expression) and store
3366** the result in continguous temporary registers. Return the index of
3367** the first register used to store the result.
3368**
3369** If the returned result register is a temporary scalar, then also write
3370** that register number into *piFreeable. If the returned result register
3371** is not a temporary or if the expression is a vector set *piFreeable
3372** to 0.
3373*/
3374static int exprCodeVector(Parse *pParse, Expr *p, int *piFreeable){
3375 int iResult;
3376 int nResult = sqlite3ExprVectorSize(p);
3377 if( nResult==1 ){
3378 iResult = sqlite3ExprCodeTemp(pParse, p, piFreeable);
3379 }else{
3380 *piFreeable = 0;
3381 if( p->op==TK_SELECT ){
drhdd1bb432017-05-15 15:12:24 +00003382#if SQLITE_OMIT_SUBQUERY
3383 iResult = 0;
3384#else
drh12abf402016-08-22 14:30:05 +00003385 iResult = sqlite3CodeSubselect(pParse, p, 0, 0);
drhdd1bb432017-05-15 15:12:24 +00003386#endif
drh12abf402016-08-22 14:30:05 +00003387 }else{
3388 int i;
3389 iResult = pParse->nMem+1;
3390 pParse->nMem += nResult;
3391 for(i=0; i<nResult; i++){
dan4b725242016-11-23 19:31:18 +00003392 sqlite3ExprCodeFactorable(pParse, p->x.pList->a[i].pExpr, i+iResult);
drh12abf402016-08-22 14:30:05 +00003393 }
3394 }
3395 }
3396 return iResult;
3397}
3398
dan71c57db2016-07-09 20:23:55 +00003399
drha4c3c872013-09-12 17:29:25 +00003400/*
drhcce7d172000-05-31 15:34:51 +00003401** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003402** expression. Attempt to store the results in register "target".
3403** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003404**
drh8b213892008-08-29 02:14:02 +00003405** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003406** be stored in target. The result might be stored in some other
3407** register if it is convenient to do so. The calling function
3408** must check the return code and move the results to the desired
3409** register.
drhcce7d172000-05-31 15:34:51 +00003410*/
drh678ccce2008-03-31 18:19:54 +00003411int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003412 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3413 int op; /* The opcode being coded */
3414 int inReg = target; /* Results stored in register inReg */
3415 int regFree1 = 0; /* If non-zero free this temporary register */
3416 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003417 int r1, r2; /* Various register numbers */
drh10d1edf2013-11-15 15:52:39 +00003418 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003419 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003420
drh9cbf3422008-01-17 16:22:13 +00003421 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003422 if( v==0 ){
3423 assert( pParse->db->mallocFailed );
3424 return 0;
3425 }
drh389a1ad2008-01-03 23:44:53 +00003426
drh1efa8022018-04-28 04:16:43 +00003427expr_code_doover:
drh389a1ad2008-01-03 23:44:53 +00003428 if( pExpr==0 ){
3429 op = TK_NULL;
3430 }else{
3431 op = pExpr->op;
3432 }
drhf2bc0132004-10-04 13:19:23 +00003433 switch( op ){
drh13449892005-09-07 21:22:45 +00003434 case TK_AGG_COLUMN: {
3435 AggInfo *pAggInfo = pExpr->pAggInfo;
3436 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3437 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003438 assert( pCol->iMem>0 );
drhc332cc32016-09-19 10:24:19 +00003439 return pCol->iMem;
drh13449892005-09-07 21:22:45 +00003440 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003441 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003442 pCol->iSorterColumn, target);
drhc332cc32016-09-19 10:24:19 +00003443 return target;
drh13449892005-09-07 21:22:45 +00003444 }
3445 /* Otherwise, fall thru into the TK_COLUMN case */
3446 }
drh967e8b72000-06-21 13:59:10 +00003447 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003448 int iTab = pExpr->iTable;
drhefad2e22018-07-27 16:57:11 +00003449 if( ExprHasProperty(pExpr, EP_FixedCol) ){
drhd98f5322018-08-09 18:36:54 +00003450 /* This COLUMN expression is really a constant due to WHERE clause
3451 ** constraints, and that constant is coded by the pExpr->pLeft
3452 ** expresssion. However, make sure the constant has the correct
3453 ** datatype by applying the Affinity of the table column to the
3454 ** constant.
3455 */
3456 int iReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft,target);
3457 int aff = sqlite3TableColumnAffinity(pExpr->pTab, pExpr->iColumn);
3458 if( aff!=SQLITE_AFF_BLOB ){
3459 static const char zAff[] = "B\000C\000D\000E";
3460 assert( SQLITE_AFF_BLOB=='A' );
3461 assert( SQLITE_AFF_TEXT=='B' );
3462 if( iReg!=target ){
3463 sqlite3VdbeAddOp2(v, OP_SCopy, iReg, target);
3464 iReg = target;
3465 }
3466 sqlite3VdbeAddOp4(v, OP_Affinity, iReg, 1, 0,
3467 &zAff[(aff-'B')*2], P4_STATIC);
3468 }
3469 return iReg;
drhefad2e22018-07-27 16:57:11 +00003470 }
drhb2b9d3d2013-08-01 01:14:43 +00003471 if( iTab<0 ){
drh6e97f8e2017-07-20 13:17:08 +00003472 if( pParse->iSelfTab<0 ){
drhb2b9d3d2013-08-01 01:14:43 +00003473 /* Generating CHECK constraints or inserting into partial index */
drh6e97f8e2017-07-20 13:17:08 +00003474 return pExpr->iColumn - pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003475 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003476 /* Coding an expression that is part of an index where column names
3477 ** in the index refer to the table to which the index belongs */
drh3e34eab2017-07-19 19:48:40 +00003478 iTab = pParse->iSelfTab - 1;
drhb2b9d3d2013-08-01 01:14:43 +00003479 }
drh22827922000-06-06 17:27:05 +00003480 }
drhc332cc32016-09-19 10:24:19 +00003481 return sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
drhb2b9d3d2013-08-01 01:14:43 +00003482 pExpr->iColumn, iTab, target,
3483 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003484 }
3485 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003486 codeInteger(pParse, pExpr, 0, target);
drhc332cc32016-09-19 10:24:19 +00003487 return target;
drhfec19aa2004-05-19 20:41:03 +00003488 }
drh8abed7b2018-02-26 18:49:05 +00003489 case TK_TRUEFALSE: {
drh96acafb2018-02-27 14:49:25 +00003490 sqlite3VdbeAddOp2(v, OP_Integer, sqlite3ExprTruthValue(pExpr), target);
drh007c8432018-02-26 03:20:18 +00003491 return target;
3492 }
drh13573c72010-01-12 17:04:07 +00003493#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003494 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003495 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3496 codeReal(v, pExpr->u.zToken, 0, target);
drhc332cc32016-09-19 10:24:19 +00003497 return target;
drh598f1342007-10-23 15:39:45 +00003498 }
drh13573c72010-01-12 17:04:07 +00003499#endif
drhfec19aa2004-05-19 20:41:03 +00003500 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003501 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003502 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhc332cc32016-09-19 10:24:19 +00003503 return target;
drhcce7d172000-05-31 15:34:51 +00003504 }
drhf0863fe2005-06-12 21:35:51 +00003505 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003506 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhc332cc32016-09-19 10:24:19 +00003507 return target;
drhf0863fe2005-06-12 21:35:51 +00003508 }
danielk19775338a5f2005-01-20 13:03:10 +00003509#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003510 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003511 int n;
3512 const char *z;
drhca48c902008-01-18 14:08:24 +00003513 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003514 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3515 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3516 assert( pExpr->u.zToken[1]=='\'' );
3517 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003518 n = sqlite3Strlen30(z) - 1;
3519 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003520 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3521 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
drhc332cc32016-09-19 10:24:19 +00003522 return target;
danielk1977c572ef72004-05-27 09:28:41 +00003523 }
danielk19775338a5f2005-01-20 13:03:10 +00003524#endif
drh50457892003-09-06 01:10:47 +00003525 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003526 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3527 assert( pExpr->u.zToken!=0 );
3528 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003529 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3530 if( pExpr->u.zToken[1]!=0 ){
drh9bf755c2016-12-23 03:59:31 +00003531 const char *z = sqlite3VListNumToName(pParse->pVList, pExpr->iColumn);
drhf326d662016-12-23 13:30:53 +00003532 assert( pExpr->u.zToken[0]=='?' || strcmp(pExpr->u.zToken, z)==0 );
drhce1bbe52016-12-23 13:52:45 +00003533 pParse->pVList[0] = 0; /* Indicate VList may no longer be enlarged */
drhf326d662016-12-23 13:30:53 +00003534 sqlite3VdbeAppendP4(v, (char*)z, P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003535 }
drhc332cc32016-09-19 10:24:19 +00003536 return target;
drh50457892003-09-06 01:10:47 +00003537 }
drh4e0cff62004-11-05 05:10:28 +00003538 case TK_REGISTER: {
drhc332cc32016-09-19 10:24:19 +00003539 return pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003540 }
drh487e2622005-06-25 18:42:14 +00003541#ifndef SQLITE_OMIT_CAST
3542 case TK_CAST: {
3543 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003544 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003545 if( inReg!=target ){
3546 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3547 inReg = target;
3548 }
drh4169e432014-08-25 20:11:52 +00003549 sqlite3VdbeAddOp2(v, OP_Cast, target,
3550 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc332cc32016-09-19 10:24:19 +00003551 return inReg;
drh487e2622005-06-25 18:42:14 +00003552 }
3553#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003554 case TK_IS:
3555 case TK_ISNOT:
3556 op = (op==TK_IS) ? TK_EQ : TK_NE;
3557 p5 = SQLITE_NULLEQ;
3558 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003559 case TK_LT:
3560 case TK_LE:
3561 case TK_GT:
3562 case TK_GE:
3563 case TK_NE:
3564 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003565 Expr *pLeft = pExpr->pLeft;
dan625015e2016-07-30 16:39:28 +00003566 if( sqlite3ExprIsVector(pLeft) ){
drh79752b62016-08-13 10:02:17 +00003567 codeVectorCompare(pParse, pExpr, target, op, p5);
dan71c57db2016-07-09 20:23:55 +00003568 }else{
3569 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00003570 assert( pExpr->eX==EX_Right );
3571 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
3572 codeCompare(pParse, pLeft, pExpr->x.pRight, op,
dan71c57db2016-07-09 20:23:55 +00003573 r1, r2, inReg, SQLITE_STOREP2 | p5);
3574 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3575 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3576 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3577 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3578 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3579 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3580 testcase( regFree1==0 );
3581 testcase( regFree2==0 );
3582 }
drh6a2fe092009-09-23 02:29:36 +00003583 break;
3584 }
drhcce7d172000-05-31 15:34:51 +00003585 case TK_AND:
3586 case TK_OR:
3587 case TK_PLUS:
3588 case TK_STAR:
3589 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003590 case TK_REM:
3591 case TK_BITAND:
3592 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003593 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003594 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003595 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003596 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003597 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3598 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3599 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3600 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3601 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3602 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3603 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3604 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3605 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3606 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3607 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003608 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00003609 assert( pExpr->eX==EX_Right );
3610 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003611 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003612 testcase( regFree1==0 );
3613 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003614 break;
3615 }
drhcce7d172000-05-31 15:34:51 +00003616 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003617 Expr *pLeft = pExpr->pLeft;
3618 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003619 if( pLeft->op==TK_INTEGER ){
3620 codeInteger(pParse, pLeft, 1, target);
drhc332cc32016-09-19 10:24:19 +00003621 return target;
drh13573c72010-01-12 17:04:07 +00003622#ifndef SQLITE_OMIT_FLOATING_POINT
3623 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003624 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3625 codeReal(v, pLeft->u.zToken, 1, target);
drhc332cc32016-09-19 10:24:19 +00003626 return target;
drh13573c72010-01-12 17:04:07 +00003627#endif
drh3c84ddf2008-01-09 02:15:38 +00003628 }else{
drh12b0fab2018-09-19 11:59:15 +00003629 memset(&tempX, 0, sizeof(tempX));
drh10d1edf2013-11-15 15:52:39 +00003630 tempX.op = TK_INTEGER;
3631 tempX.flags = EP_IntValue|EP_TokenOnly;
3632 tempX.u.iValue = 0;
3633 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003634 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003635 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003636 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003637 }
drh3c84ddf2008-01-09 02:15:38 +00003638 break;
drh6e142f52000-06-08 13:36:40 +00003639 }
drhbf4133c2001-10-13 02:59:08 +00003640 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003641 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003642 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3643 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003644 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3645 testcase( regFree1==0 );
drhe99fa2a2008-12-15 15:27:51 +00003646 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003647 break;
3648 }
drh8abed7b2018-02-26 18:49:05 +00003649 case TK_TRUTH: {
drh96acafb2018-02-27 14:49:25 +00003650 int isTrue; /* IS TRUE or IS NOT TRUE */
3651 int bNormal; /* IS TRUE or IS FALSE */
drh007c8432018-02-26 03:20:18 +00003652 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3653 testcase( regFree1==0 );
drh3d6bedf2018-09-19 14:54:38 +00003654 assert( pExpr->eX==EX_Right );
3655 isTrue = sqlite3ExprTruthValue(pExpr->x.pRight);
drh96acafb2018-02-27 14:49:25 +00003656 bNormal = pExpr->op2==TK_IS;
3657 testcase( isTrue && bNormal);
3658 testcase( !isTrue && bNormal);
3659 sqlite3VdbeAddOp4Int(v, OP_IsTrue, r1, inReg, !isTrue, isTrue ^ bNormal);
drh007c8432018-02-26 03:20:18 +00003660 break;
3661 }
drhcce7d172000-05-31 15:34:51 +00003662 case TK_ISNULL:
3663 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003664 int addr;
drh7d176102014-02-18 03:07:12 +00003665 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3666 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003667 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003668 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003669 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003670 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003671 VdbeCoverageIf(v, op==TK_ISNULL);
3672 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003673 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003674 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003675 break;
drhcce7d172000-05-31 15:34:51 +00003676 }
drh22827922000-06-06 17:27:05 +00003677 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003678 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003679 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003680 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3681 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003682 }else{
drhc332cc32016-09-19 10:24:19 +00003683 return pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003684 }
drh22827922000-06-06 17:27:05 +00003685 break;
3686 }
drhcce7d172000-05-31 15:34:51 +00003687 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003688 ExprList *pFarg; /* List of function arguments */
3689 int nFarg; /* Number of function arguments */
3690 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003691 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003692 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003693 int i; /* Loop counter */
drhc332cc32016-09-19 10:24:19 +00003694 sqlite3 *db = pParse->db; /* The database connection */
drh12ffee82009-04-08 13:51:51 +00003695 u8 enc = ENC(db); /* The text encoding used by this database */
3696 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003697
dan67a9b8e2018-06-22 20:51:35 +00003698#ifndef SQLITE_OMIT_WINDOWFUNC
dan86fb6e12018-05-16 20:58:07 +00003699 if( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) && pExpr->pWin ){
3700 return pExpr->pWin->regResult;
3701 }
dan67a9b8e2018-06-22 20:51:35 +00003702#endif
dan86fb6e12018-05-16 20:58:07 +00003703
drh1e9b53f2017-01-04 01:07:24 +00003704 if( ConstFactorOk(pParse) && sqlite3ExprIsConstantNotJoin(pExpr) ){
drh49c5ab22017-01-04 04:18:00 +00003705 /* SQL functions can be expensive. So try to move constant functions
drhad879ff2017-01-04 04:10:02 +00003706 ** out of the inner loop, even if that means an extra OP_Copy. */
3707 return sqlite3ExprCodeAtInit(pParse, pExpr, -1);
drh1e9b53f2017-01-04 01:07:24 +00003708 }
drh3b3c86a2018-09-18 21:35:31 +00003709 assert( pExpr->eX==EX_List || pExpr->eX==EX_None );
drhc5cd1242013-09-12 16:50:49 +00003710 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003711 pFarg = 0;
3712 }else{
3713 pFarg = pExpr->x.pList;
3714 }
3715 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003716 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3717 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003718 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drhcc153132016-08-04 12:35:17 +00003719#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
3720 if( pDef==0 && pParse->explain ){
3721 pDef = sqlite3FindFunction(db, "unknown", nFarg, enc, 0);
3722 }
3723#endif
danb6e9f7a2018-05-19 14:15:29 +00003724 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003725 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003726 break;
3727 }
drhae6bb952009-11-11 00:24:31 +00003728
3729 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003730 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003731 ** arguments past the first non-NULL argument.
3732 */
drhd36e1042013-09-06 13:10:12 +00003733 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003734 int endCoalesce = sqlite3VdbeMakeLabel(v);
3735 assert( nFarg>=2 );
3736 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3737 for(i=1; i<nFarg; i++){
3738 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003739 VdbeCoverage(v);
drhae6bb952009-11-11 00:24:31 +00003740 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhae6bb952009-11-11 00:24:31 +00003741 }
3742 sqlite3VdbeResolveLabel(v, endCoalesce);
3743 break;
3744 }
3745
drhcca9f3d2013-09-06 15:23:29 +00003746 /* The UNLIKELY() function is a no-op. The result is the value
3747 ** of the first argument.
3748 */
3749 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3750 assert( nFarg>=1 );
drhc332cc32016-09-19 10:24:19 +00003751 return sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003752 }
drhae6bb952009-11-11 00:24:31 +00003753
drh54240752017-01-03 14:39:30 +00003754#ifdef SQLITE_DEBUG
drha1a523a2016-12-26 00:18:36 +00003755 /* The AFFINITY() function evaluates to a string that describes
3756 ** the type affinity of the argument. This is used for testing of
3757 ** the SQLite type logic.
3758 */
3759 if( pDef->funcFlags & SQLITE_FUNC_AFFINITY ){
3760 const char *azAff[] = { "blob", "text", "numeric", "integer", "real" };
3761 char aff;
3762 assert( nFarg==1 );
3763 aff = sqlite3ExprAffinity(pFarg->a[0].pExpr);
3764 sqlite3VdbeLoadString(v, target,
3765 aff ? azAff[aff-SQLITE_AFF_BLOB] : "none");
3766 return target;
3767 }
drh54240752017-01-03 14:39:30 +00003768#endif
drha1a523a2016-12-26 00:18:36 +00003769
drhd1a01ed2013-11-21 16:08:52 +00003770 for(i=0; i<nFarg; i++){
3771 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003772 testcase( i==31 );
3773 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003774 }
3775 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3776 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3777 }
3778 }
drh12ffee82009-04-08 13:51:51 +00003779 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003780 if( constMask ){
3781 r1 = pParse->nMem+1;
3782 pParse->nMem += nFarg;
3783 }else{
3784 r1 = sqlite3GetTempRange(pParse, nFarg);
3785 }
drha748fdc2012-03-28 01:34:47 +00003786
3787 /* For length() and typeof() functions with a column argument,
3788 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3789 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3790 ** loading.
3791 */
drhd36e1042013-09-06 13:10:12 +00003792 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003793 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003794 assert( nFarg==1 );
3795 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003796 exprOp = pFarg->a[0].pExpr->op;
3797 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003798 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3799 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003800 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3801 pFarg->a[0].pExpr->op2 =
3802 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003803 }
3804 }
3805
drh5579d592015-08-26 14:01:41 +00003806 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003807 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drh892d3172008-01-10 03:46:36 +00003808 }else{
drh12ffee82009-04-08 13:51:51 +00003809 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003810 }
drhb7f6f682006-07-08 17:06:43 +00003811#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003812 /* Possibly overload the function if the first argument is
3813 ** a virtual table column.
3814 **
3815 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3816 ** second argument, not the first, as the argument to test to
3817 ** see if it is a column in a virtual table. This is done because
3818 ** the left operand of infix functions (the operand we want to
3819 ** control overloading) ends up as the second argument to the
3820 ** function. The expression "A glob B" is equivalent to
3821 ** "glob(B,A). We want to use the A in "A glob B" to test
3822 ** for function overloading. But we use the B term in "glob(B,A)".
3823 */
drh59155062018-05-26 18:03:48 +00003824 if( nFarg>=2 && ExprHasProperty(pExpr, EP_InfixFunc) ){
drh12ffee82009-04-08 13:51:51 +00003825 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3826 }else if( nFarg>0 ){
3827 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003828 }
3829#endif
drhd36e1042013-09-06 13:10:12 +00003830 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003831 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003832 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003833 }
drh092457b2017-12-29 15:04:49 +00003834#ifdef SQLITE_ENABLE_OFFSET_SQL_FUNC
3835 if( pDef->funcFlags & SQLITE_FUNC_OFFSET ){
drh2fc865c2017-12-16 20:20:37 +00003836 Expr *pArg = pFarg->a[0].pExpr;
3837 if( pArg->op==TK_COLUMN ){
drh092457b2017-12-29 15:04:49 +00003838 sqlite3VdbeAddOp3(v, OP_Offset, pArg->iTable, pArg->iColumn, target);
drh2fc865c2017-12-16 20:20:37 +00003839 }else{
3840 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3841 }
drh092457b2017-12-29 15:04:49 +00003842 }else
3843#endif
3844 {
drh2fc865c2017-12-16 20:20:37 +00003845 sqlite3VdbeAddOp4(v, pParse->iSelfTab ? OP_PureFunc0 : OP_Function0,
3846 constMask, r1, target, (char*)pDef, P4_FUNCDEF);
3847 sqlite3VdbeChangeP5(v, (u8)nFarg);
3848 }
drhd1a01ed2013-11-21 16:08:52 +00003849 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003850 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003851 }
drhc332cc32016-09-19 10:24:19 +00003852 return target;
drhcce7d172000-05-31 15:34:51 +00003853 }
drhfe2093d2005-01-20 22:48:47 +00003854#ifndef SQLITE_OMIT_SUBQUERY
3855 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003856 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003857 int nCol;
drhc5499be2008-04-01 15:06:33 +00003858 testcase( op==TK_EXISTS );
3859 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003860 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3861 sqlite3SubselectError(pParse, nCol, 1);
3862 }else{
drhc332cc32016-09-19 10:24:19 +00003863 return sqlite3CodeSubselect(pParse, pExpr, 0, 0);
dan8da209b2016-07-26 18:06:08 +00003864 }
drh19a775c2000-06-05 18:54:46 +00003865 break;
3866 }
drhfc7f27b2016-08-20 00:07:01 +00003867 case TK_SELECT_COLUMN: {
drh966e2912017-01-03 02:58:01 +00003868 int n;
drhfc7f27b2016-08-20 00:07:01 +00003869 if( pExpr->pLeft->iTable==0 ){
3870 pExpr->pLeft->iTable = sqlite3CodeSubselect(pParse, pExpr->pLeft, 0, 0);
3871 }
drh966e2912017-01-03 02:58:01 +00003872 assert( pExpr->iTable==0 || pExpr->pLeft->op==TK_SELECT );
3873 if( pExpr->iTable
3874 && pExpr->iTable!=(n = sqlite3ExprVectorSize(pExpr->pLeft))
3875 ){
3876 sqlite3ErrorMsg(pParse, "%d columns assigned %d values",
3877 pExpr->iTable, n);
3878 }
drhc332cc32016-09-19 10:24:19 +00003879 return pExpr->pLeft->iTable + pExpr->iColumn;
drhfc7f27b2016-08-20 00:07:01 +00003880 }
drhfef52082000-06-06 01:50:43 +00003881 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003882 int destIfFalse = sqlite3VdbeMakeLabel(v);
3883 int destIfNull = sqlite3VdbeMakeLabel(v);
3884 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3885 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3886 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3887 sqlite3VdbeResolveLabel(v, destIfFalse);
3888 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3889 sqlite3VdbeResolveLabel(v, destIfNull);
drhc332cc32016-09-19 10:24:19 +00003890 return target;
drhfef52082000-06-06 01:50:43 +00003891 }
drhe3365e62009-11-12 17:52:24 +00003892#endif /* SQLITE_OMIT_SUBQUERY */
3893
3894
drh2dcef112008-01-12 19:03:48 +00003895 /*
3896 ** x BETWEEN y AND z
3897 **
3898 ** This is equivalent to
3899 **
3900 ** x>=y AND x<=z
3901 **
3902 ** X is stored in pExpr->pLeft.
3903 ** Y is stored in pExpr->pList->a[0].pExpr.
3904 ** Z is stored in pExpr->pList->a[1].pExpr.
3905 */
drhfef52082000-06-06 01:50:43 +00003906 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003907 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhc332cc32016-09-19 10:24:19 +00003908 return target;
drhfef52082000-06-06 01:50:43 +00003909 }
drh94fa9c42016-02-27 21:16:04 +00003910 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003911 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003912 case TK_UPLUS: {
drh1efa8022018-04-28 04:16:43 +00003913 pExpr = pExpr->pLeft;
drh59ee43a2018-05-29 15:18:31 +00003914 goto expr_code_doover; /* 2018-04-28: Prevent deep recursion. OSSFuzz. */
drha2e00042002-01-22 03:13:42 +00003915 }
drh2dcef112008-01-12 19:03:48 +00003916
dan165921a2009-08-28 18:53:45 +00003917 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003918 /* If the opcode is TK_TRIGGER, then the expression is a reference
3919 ** to a column in the new.* or old.* pseudo-tables available to
3920 ** trigger programs. In this case Expr.iTable is set to 1 for the
3921 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3922 ** is set to the column of the pseudo-table to read, or to -1 to
3923 ** read the rowid field.
3924 **
3925 ** The expression is implemented using an OP_Param opcode. The p1
3926 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3927 ** to reference another column of the old.* pseudo-table, where
3928 ** i is the index of the column. For a new.rowid reference, p1 is
3929 ** set to (n+1), where n is the number of columns in each pseudo-table.
3930 ** For a reference to any other column in the new.* pseudo-table, p1
3931 ** is set to (n+2+i), where n and i are as defined previously. For
3932 ** example, if the table on which triggers are being fired is
3933 ** declared as:
3934 **
3935 ** CREATE TABLE t1(a, b);
3936 **
3937 ** Then p1 is interpreted as follows:
3938 **
3939 ** p1==0 -> old.rowid p1==3 -> new.rowid
3940 ** p1==1 -> old.a p1==4 -> new.a
3941 ** p1==2 -> old.b p1==5 -> new.b
3942 */
dan2832ad42009-08-31 15:27:27 +00003943 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003944 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3945
3946 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3947 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3948 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3949 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3950
3951 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
drh896494e2018-04-26 12:27:03 +00003952 VdbeComment((v, "r[%d]=%s.%s", target,
dan2bd93512009-08-31 08:22:46 +00003953 (pExpr->iTable ? "new" : "old"),
drh896494e2018-04-26 12:27:03 +00003954 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName)
dan165921a2009-08-28 18:53:45 +00003955 ));
dan65a7cd12009-09-01 12:16:01 +00003956
drh44dbca82010-01-13 04:22:20 +00003957#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003958 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003959 ** integer. Use OP_RealAffinity to make sure it is really real.
3960 **
3961 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3962 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003963 if( pExpr->iColumn>=0
3964 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3965 ){
3966 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3967 }
drh44dbca82010-01-13 04:22:20 +00003968#endif
dan165921a2009-08-28 18:53:45 +00003969 break;
3970 }
3971
dan71c57db2016-07-09 20:23:55 +00003972 case TK_VECTOR: {
drhe835bc12016-08-23 19:02:55 +00003973 sqlite3ErrorMsg(pParse, "row value misused");
dan71c57db2016-07-09 20:23:55 +00003974 break;
3975 }
3976
drh31d6fd52017-04-14 19:03:10 +00003977 case TK_IF_NULL_ROW: {
3978 int addrINR;
3979 addrINR = sqlite3VdbeAddOp1(v, OP_IfNullRow, pExpr->iTable);
drh31d6fd52017-04-14 19:03:10 +00003980 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh31d6fd52017-04-14 19:03:10 +00003981 sqlite3VdbeJumpHere(v, addrINR);
3982 sqlite3VdbeChangeP3(v, addrINR, inReg);
3983 break;
3984 }
3985
drh2dcef112008-01-12 19:03:48 +00003986 /*
3987 ** Form A:
3988 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3989 **
3990 ** Form B:
3991 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3992 **
3993 ** Form A is can be transformed into the equivalent form B as follows:
3994 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3995 ** WHEN x=eN THEN rN ELSE y END
3996 **
3997 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003998 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3999 ** odd. The Y is also optional. If the number of elements in x.pList
4000 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00004001 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
4002 **
4003 ** The result of the expression is the Ri for the first matching Ei,
4004 ** or if there is no matching Ei, the ELSE term Y, or if there is
4005 ** no ELSE term, NULL.
4006 */
drh33cd4902009-05-30 20:49:20 +00004007 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00004008 int endLabel; /* GOTO label for end of CASE stmt */
4009 int nextCase; /* GOTO label for next WHEN clause */
4010 int nExpr; /* 2x number of WHEN terms */
4011 int i; /* Loop counter */
4012 ExprList *pEList; /* List of WHEN terms */
4013 struct ExprList_item *aListelem; /* Array of WHEN terms */
4014 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00004015 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00004016 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drh17a7f8d2002-03-24 13:13:27 +00004017
drh3b3c86a2018-09-18 21:35:31 +00004018 assert( pExpr->eX==EX_List );
4019 assert( pExpr->x.pList->nExpr > 0);
danielk19776ab3a2e2009-02-19 14:39:25 +00004020 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00004021 aListelem = pEList->a;
4022 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00004023 endLabel = sqlite3VdbeMakeLabel(v);
4024 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00004025 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00004026 testcase( pX->op==TK_COLUMN );
drh12abf402016-08-22 14:30:05 +00004027 exprToRegister(&tempX, exprCodeVector(pParse, &tempX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00004028 testcase( regFree1==0 );
drhabb9d5f2016-08-23 17:30:55 +00004029 memset(&opCompare, 0, sizeof(opCompare));
drh2dcef112008-01-12 19:03:48 +00004030 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00004031 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00004032 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00004033 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
4034 ** The value in regFree1 might get SCopy-ed into the file result.
4035 ** So make sure that the regFree1 register is not reused for other
4036 ** purposes and possibly overwritten. */
4037 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00004038 }
drhc5cd1242013-09-12 16:50:49 +00004039 for(i=0; i<nExpr-1; i=i+2){
drh2dcef112008-01-12 19:03:48 +00004040 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00004041 assert( pTest!=0 );
drh3d6bedf2018-09-19 14:54:38 +00004042 opCompare.x.pRight = aListelem[i].pExpr;
4043 opCompare.eX = EX_Right;
drh17a7f8d2002-03-24 13:13:27 +00004044 }else{
drh2dcef112008-01-12 19:03:48 +00004045 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00004046 }
drh2dcef112008-01-12 19:03:48 +00004047 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00004048 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00004049 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00004050 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00004051 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00004052 sqlite3VdbeGoto(v, endLabel);
drh2dcef112008-01-12 19:03:48 +00004053 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00004054 }
drhc5cd1242013-09-12 16:50:49 +00004055 if( (nExpr&1)!=0 ){
drhc5cd1242013-09-12 16:50:49 +00004056 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drh17a7f8d2002-03-24 13:13:27 +00004057 }else{
drh9de221d2008-01-05 06:51:30 +00004058 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00004059 }
drh2dcef112008-01-12 19:03:48 +00004060 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00004061 break;
4062 }
danielk19775338a5f2005-01-20 13:03:10 +00004063#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00004064 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00004065 assert( pExpr->affinity==OE_Rollback
4066 || pExpr->affinity==OE_Abort
4067 || pExpr->affinity==OE_Fail
4068 || pExpr->affinity==OE_Ignore
4069 );
dane0af83a2009-09-08 19:15:01 +00004070 if( !pParse->pTriggerTab ){
4071 sqlite3ErrorMsg(pParse,
4072 "RAISE() may only be used within a trigger-program");
4073 return 0;
4074 }
4075 if( pExpr->affinity==OE_Abort ){
4076 sqlite3MayAbort(pParse);
4077 }
dan165921a2009-08-28 18:53:45 +00004078 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00004079 if( pExpr->affinity==OE_Ignore ){
4080 sqlite3VdbeAddOp4(
4081 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00004082 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00004083 }else{
drh433dccf2013-02-09 15:37:11 +00004084 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00004085 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00004086 }
4087
drhffe07b22005-11-03 00:41:17 +00004088 break;
drh17a7f8d2002-03-24 13:13:27 +00004089 }
danielk19775338a5f2005-01-20 13:03:10 +00004090#endif
drhffe07b22005-11-03 00:41:17 +00004091 }
drh2dcef112008-01-12 19:03:48 +00004092 sqlite3ReleaseTempReg(pParse, regFree1);
4093 sqlite3ReleaseTempReg(pParse, regFree2);
4094 return inReg;
4095}
4096
4097/*
drhd1a01ed2013-11-21 16:08:52 +00004098** Factor out the code of the given expression to initialization time.
drh1e9b53f2017-01-04 01:07:24 +00004099**
drhad879ff2017-01-04 04:10:02 +00004100** If regDest>=0 then the result is always stored in that register and the
4101** result is not reusable. If regDest<0 then this routine is free to
4102** store the value whereever it wants. The register where the expression
4103** is stored is returned. When regDest<0, two identical expressions will
4104** code to the same register.
drhd1a01ed2013-11-21 16:08:52 +00004105*/
drh1e9b53f2017-01-04 01:07:24 +00004106int sqlite3ExprCodeAtInit(
drhd673cdd2013-11-21 21:23:31 +00004107 Parse *pParse, /* Parsing context */
4108 Expr *pExpr, /* The expression to code when the VDBE initializes */
drhad879ff2017-01-04 04:10:02 +00004109 int regDest /* Store the value in this register */
drhd673cdd2013-11-21 21:23:31 +00004110){
drhd1a01ed2013-11-21 16:08:52 +00004111 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00004112 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00004113 p = pParse->pConstExpr;
drhad879ff2017-01-04 04:10:02 +00004114 if( regDest<0 && p ){
4115 struct ExprList_item *pItem;
4116 int i;
4117 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
dan5aa550c2017-06-24 18:10:29 +00004118 if( pItem->reusable && sqlite3ExprCompare(0,pItem->pExpr,pExpr,-1)==0 ){
drhad879ff2017-01-04 04:10:02 +00004119 return pItem->u.iConstExprReg;
drh1e9b53f2017-01-04 01:07:24 +00004120 }
4121 }
drh1e9b53f2017-01-04 01:07:24 +00004122 }
drhd1a01ed2013-11-21 16:08:52 +00004123 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
4124 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00004125 if( p ){
4126 struct ExprList_item *pItem = &p->a[p->nExpr-1];
drhad879ff2017-01-04 04:10:02 +00004127 pItem->reusable = regDest<0;
4128 if( regDest<0 ) regDest = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00004129 pItem->u.iConstExprReg = regDest;
drhd673cdd2013-11-21 21:23:31 +00004130 }
drhd1a01ed2013-11-21 16:08:52 +00004131 pParse->pConstExpr = p;
drh1e9b53f2017-01-04 01:07:24 +00004132 return regDest;
drhd1a01ed2013-11-21 16:08:52 +00004133}
4134
4135/*
drh2dcef112008-01-12 19:03:48 +00004136** Generate code to evaluate an expression and store the results
4137** into a register. Return the register number where the results
4138** are stored.
4139**
4140** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00004141** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00004142** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00004143**
4144** If pExpr is a constant, then this routine might generate this
4145** code to fill the register in the initialization section of the
4146** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00004147*/
4148int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00004149 int r2;
4150 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00004151 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00004152 && pExpr->op!=TK_REGISTER
4153 && sqlite3ExprIsConstantNotJoin(pExpr)
4154 ){
drhf30a9692013-11-15 01:10:18 +00004155 *pReg = 0;
drhad879ff2017-01-04 04:10:02 +00004156 r2 = sqlite3ExprCodeAtInit(pParse, pExpr, -1);
drh2dcef112008-01-12 19:03:48 +00004157 }else{
drhf30a9692013-11-15 01:10:18 +00004158 int r1 = sqlite3GetTempReg(pParse);
4159 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
4160 if( r2==r1 ){
4161 *pReg = r1;
4162 }else{
4163 sqlite3ReleaseTempReg(pParse, r1);
4164 *pReg = 0;
4165 }
drh2dcef112008-01-12 19:03:48 +00004166 }
4167 return r2;
4168}
4169
4170/*
4171** Generate code that will evaluate expression pExpr and store the
4172** results in register target. The results are guaranteed to appear
4173** in register target.
4174*/
drh05a86c52014-02-16 01:55:49 +00004175void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00004176 int inReg;
4177
4178 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00004179 if( pExpr && pExpr->op==TK_REGISTER ){
4180 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
4181 }else{
4182 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00004183 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00004184 if( inReg!=target && pParse->pVdbe ){
4185 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
4186 }
drhcce7d172000-05-31 15:34:51 +00004187 }
drhcce7d172000-05-31 15:34:51 +00004188}
4189
4190/*
drh1c75c9d2015-12-21 15:22:13 +00004191** Make a transient copy of expression pExpr and then code it using
4192** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
4193** except that the input expression is guaranteed to be unchanged.
4194*/
4195void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
4196 sqlite3 *db = pParse->db;
4197 pExpr = sqlite3ExprDup(db, pExpr, 0);
4198 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
4199 sqlite3ExprDelete(db, pExpr);
4200}
4201
4202/*
drh05a86c52014-02-16 01:55:49 +00004203** Generate code that will evaluate expression pExpr and store the
4204** results in register target. The results are guaranteed to appear
4205** in register target. If the expression is constant, then this routine
4206** might choose to code the expression at initialization time.
4207*/
4208void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
drhb8b06692018-08-04 15:16:20 +00004209 if( pParse->okConstFactor && sqlite3ExprIsConstantNotJoin(pExpr) ){
drhad879ff2017-01-04 04:10:02 +00004210 sqlite3ExprCodeAtInit(pParse, pExpr, target);
drh05a86c52014-02-16 01:55:49 +00004211 }else{
4212 sqlite3ExprCode(pParse, pExpr, target);
4213 }
drhcce7d172000-05-31 15:34:51 +00004214}
4215
4216/*
peter.d.reid60ec9142014-09-06 16:39:46 +00004217** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00004218** in register target.
drh25303782004-12-07 15:41:48 +00004219**
drh2dcef112008-01-12 19:03:48 +00004220** Also make a copy of the expression results into another "cache" register
4221** and modify the expression so that the next time it is evaluated,
4222** the result is a copy of the cache register.
4223**
4224** This routine is used for expressions that are used multiple
4225** times. They are evaluated once and the results of the expression
4226** are reused.
drh25303782004-12-07 15:41:48 +00004227*/
drh05a86c52014-02-16 01:55:49 +00004228void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00004229 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00004230 int iMem;
4231
drhde4fcfd2008-01-19 23:50:26 +00004232 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00004233 assert( pExpr->op!=TK_REGISTER );
4234 sqlite3ExprCode(pParse, pExpr, target);
4235 iMem = ++pParse->nMem;
4236 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
4237 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00004238}
drh2dcef112008-01-12 19:03:48 +00004239
drh678ccce2008-03-31 18:19:54 +00004240/*
drh268380c2004-02-25 13:47:31 +00004241** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00004242** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00004243**
drh3df6c3b2017-09-15 15:38:01 +00004244** Return the number of elements evaluated. The number returned will
4245** usually be pList->nExpr but might be reduced if SQLITE_ECEL_OMITREF
4246** is defined.
drhd1a01ed2013-11-21 16:08:52 +00004247**
4248** The SQLITE_ECEL_DUP flag prevents the arguments from being
4249** filled using OP_SCopy. OP_Copy must be used instead.
4250**
4251** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
4252** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00004253**
4254** The SQLITE_ECEL_REF flag means that expressions in the list with
4255** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
4256** in registers at srcReg, and so the value can be copied from there.
drh3df6c3b2017-09-15 15:38:01 +00004257** If SQLITE_ECEL_OMITREF is also set, then the values with u.x.iOrderByCol>0
4258** are simply omitted rather than being copied from srcReg.
drh268380c2004-02-25 13:47:31 +00004259*/
danielk19774adee202004-05-08 08:23:19 +00004260int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00004261 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00004262 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00004263 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00004264 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00004265 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00004266){
4267 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00004268 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00004269 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00004270 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00004271 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00004272 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00004273 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00004274 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00004275 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00004276 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00004277 Expr *pExpr = pItem->pExpr;
dan24e25d32018-04-14 18:46:20 +00004278#ifdef SQLITE_ENABLE_SORTER_REFERENCES
4279 if( pItem->bSorterRef ){
4280 i--;
4281 n--;
4282 }else
4283#endif
dan257c13f2016-11-10 20:14:06 +00004284 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pItem->u.x.iOrderByCol)>0 ){
4285 if( flags & SQLITE_ECEL_OMITREF ){
4286 i--;
4287 n--;
4288 }else{
4289 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
4290 }
drhb8b06692018-08-04 15:16:20 +00004291 }else if( (flags & SQLITE_ECEL_FACTOR)!=0
4292 && sqlite3ExprIsConstantNotJoin(pExpr)
4293 ){
drhad879ff2017-01-04 04:10:02 +00004294 sqlite3ExprCodeAtInit(pParse, pExpr, target+i);
drhd1a01ed2013-11-21 16:08:52 +00004295 }else{
4296 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
4297 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00004298 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00004299 if( copyOp==OP_Copy
4300 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
4301 && pOp->p1+pOp->p3+1==inReg
4302 && pOp->p2+pOp->p3+1==target+i
4303 ){
4304 pOp->p3++;
4305 }else{
4306 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
4307 }
drhd1a01ed2013-11-21 16:08:52 +00004308 }
drhd1766112008-09-17 00:13:12 +00004309 }
drh268380c2004-02-25 13:47:31 +00004310 }
drhf9b596e2004-05-26 16:54:42 +00004311 return n;
drh268380c2004-02-25 13:47:31 +00004312}
4313
4314/*
drh36c563a2009-11-12 13:32:22 +00004315** Generate code for a BETWEEN operator.
4316**
4317** x BETWEEN y AND z
4318**
4319** The above is equivalent to
4320**
4321** x>=y AND x<=z
4322**
4323** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00004324** elimination of x.
drh84b19a32016-08-20 22:49:28 +00004325**
4326** The xJumpIf parameter determines details:
4327**
4328** NULL: Store the boolean result in reg[dest]
4329** sqlite3ExprIfTrue: Jump to dest if true
4330** sqlite3ExprIfFalse: Jump to dest if false
4331**
4332** The jumpIfNull parameter is ignored if xJumpIf is NULL.
drh36c563a2009-11-12 13:32:22 +00004333*/
4334static void exprCodeBetween(
4335 Parse *pParse, /* Parsing and code generating context */
4336 Expr *pExpr, /* The BETWEEN expression */
drh84b19a32016-08-20 22:49:28 +00004337 int dest, /* Jump destination or storage location */
4338 void (*xJump)(Parse*,Expr*,int,int), /* Action to take */
drh36c563a2009-11-12 13:32:22 +00004339 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
4340){
drhdb45bd52016-08-22 00:48:58 +00004341 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
drh36c563a2009-11-12 13:32:22 +00004342 Expr compLeft; /* The x>=y term */
4343 Expr compRight; /* The x<=z term */
drhdb45bd52016-08-22 00:48:58 +00004344 Expr exprX; /* The x subexpression */
4345 int regFree1 = 0; /* Temporary use register */
drh84b19a32016-08-20 22:49:28 +00004346
drh36c563a2009-11-12 13:32:22 +00004347
dan71c57db2016-07-09 20:23:55 +00004348 memset(&compLeft, 0, sizeof(Expr));
4349 memset(&compRight, 0, sizeof(Expr));
4350 memset(&exprAnd, 0, sizeof(Expr));
drhdb45bd52016-08-22 00:48:58 +00004351
drh3b3c86a2018-09-18 21:35:31 +00004352 assert( pExpr->eX==EX_List );
drhdb45bd52016-08-22 00:48:58 +00004353 exprX = *pExpr->pLeft;
drh36c563a2009-11-12 13:32:22 +00004354 exprAnd.op = TK_AND;
4355 exprAnd.pLeft = &compLeft;
drh3d6bedf2018-09-19 14:54:38 +00004356 exprAnd.x.pRight = &compRight;
4357 exprAnd.eX = EX_Right;
drh36c563a2009-11-12 13:32:22 +00004358 compLeft.op = TK_GE;
drhdb45bd52016-08-22 00:48:58 +00004359 compLeft.pLeft = &exprX;
drh3d6bedf2018-09-19 14:54:38 +00004360 compLeft.x.pRight = pExpr->x.pList->a[0].pExpr;
4361 compLeft.eX = EX_Right;
drh36c563a2009-11-12 13:32:22 +00004362 compRight.op = TK_LE;
drhdb45bd52016-08-22 00:48:58 +00004363 compRight.pLeft = &exprX;
drh3d6bedf2018-09-19 14:54:38 +00004364 compRight.x.pRight = pExpr->x.pList->a[1].pExpr;
4365 compRight.eX = EX_Right;
drh12abf402016-08-22 14:30:05 +00004366 exprToRegister(&exprX, exprCodeVector(pParse, &exprX, &regFree1));
drh84b19a32016-08-20 22:49:28 +00004367 if( xJump ){
4368 xJump(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00004369 }else{
drh36fd41e2016-11-25 14:30:42 +00004370 /* Mark the expression is being from the ON or USING clause of a join
4371 ** so that the sqlite3ExprCodeTarget() routine will not attempt to move
4372 ** it into the Parse.pConstExpr list. We should use a new bit for this,
4373 ** for clarity, but we are out of bits in the Expr.flags field so we
4374 ** have to reuse the EP_FromJoin bit. Bummer. */
drhdb45bd52016-08-22 00:48:58 +00004375 exprX.flags |= EP_FromJoin;
dan71c57db2016-07-09 20:23:55 +00004376 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00004377 }
drhdb45bd52016-08-22 00:48:58 +00004378 sqlite3ReleaseTempReg(pParse, regFree1);
drh36c563a2009-11-12 13:32:22 +00004379
4380 /* Ensure adequate test coverage */
drhdb45bd52016-08-22 00:48:58 +00004381 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1==0 );
4382 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull==0 && regFree1!=0 );
4383 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1==0 );
4384 testcase( xJump==sqlite3ExprIfTrue && jumpIfNull!=0 && regFree1!=0 );
4385 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1==0 );
4386 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull==0 && regFree1!=0 );
4387 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1==0 );
4388 testcase( xJump==sqlite3ExprIfFalse && jumpIfNull!=0 && regFree1!=0 );
drh84b19a32016-08-20 22:49:28 +00004389 testcase( xJump==0 );
drh36c563a2009-11-12 13:32:22 +00004390}
4391
4392/*
drhcce7d172000-05-31 15:34:51 +00004393** Generate code for a boolean expression such that a jump is made
4394** to the label "dest" if the expression is true but execution
4395** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00004396**
4397** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00004398** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00004399**
4400** This code depends on the fact that certain token values (ex: TK_EQ)
4401** are the same as opcode values (ex: OP_Eq) that implement the corresponding
4402** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
4403** the make process cause these values to align. Assert()s in the code
4404** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00004405*/
danielk19774adee202004-05-08 08:23:19 +00004406void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004407 Vdbe *v = pParse->pVdbe;
4408 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004409 int regFree1 = 0;
4410 int regFree2 = 0;
4411 int r1, r2;
4412
drh35573352008-01-08 23:54:25 +00004413 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004414 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004415 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00004416 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00004417 switch( op ){
drhcce7d172000-05-31 15:34:51 +00004418 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00004419 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004420 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004421 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh3d6bedf2018-09-19 14:54:38 +00004422 assert( pExpr->eX==EX_Right );
4423 sqlite3ExprIfTrue(pParse, pExpr->x.pRight, dest, jumpIfNull);
danielk19774adee202004-05-08 08:23:19 +00004424 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00004425 break;
4426 }
4427 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00004428 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004429 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh3d6bedf2018-09-19 14:54:38 +00004430 assert( pExpr->eX==EX_Right );
4431 sqlite3ExprIfTrue(pParse, pExpr->x.pRight, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004432 break;
4433 }
4434 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00004435 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004436 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004437 break;
4438 }
drh8abed7b2018-02-26 18:49:05 +00004439 case TK_TRUTH: {
drh96acafb2018-02-27 14:49:25 +00004440 int isNot; /* IS NOT TRUE or IS NOT FALSE */
4441 int isTrue; /* IS TRUE or IS NOT TRUE */
drh007c8432018-02-26 03:20:18 +00004442 testcase( jumpIfNull==0 );
drh8abed7b2018-02-26 18:49:05 +00004443 isNot = pExpr->op2==TK_ISNOT;
drh3d6bedf2018-09-19 14:54:38 +00004444 assert( pExpr->eX==EX_Right );
4445 isTrue = sqlite3ExprTruthValue(pExpr->x.pRight);
drh43c4ac82018-02-26 21:26:27 +00004446 testcase( isTrue && isNot );
drh96acafb2018-02-27 14:49:25 +00004447 testcase( !isTrue && isNot );
drh43c4ac82018-02-26 21:26:27 +00004448 if( isTrue ^ isNot ){
drh8abed7b2018-02-26 18:49:05 +00004449 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
4450 isNot ? SQLITE_JUMPIFNULL : 0);
4451 }else{
4452 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4453 isNot ? SQLITE_JUMPIFNULL : 0);
4454 }
drh007c8432018-02-26 03:20:18 +00004455 break;
4456 }
drhde845c22016-03-17 19:07:52 +00004457 case TK_IS:
4458 case TK_ISNOT:
4459 testcase( op==TK_IS );
4460 testcase( op==TK_ISNOT );
4461 op = (op==TK_IS) ? TK_EQ : TK_NE;
4462 jumpIfNull = SQLITE_NULLEQ;
4463 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004464 case TK_LT:
4465 case TK_LE:
4466 case TK_GT:
4467 case TK_GE:
4468 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00004469 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004470 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004471 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004472 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00004473 assert( pExpr->eX==EX_Right );
4474 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
4475 codeCompare(pParse, pExpr->pLeft, pExpr->x.pRight, op,
drh2dcef112008-01-12 19:03:48 +00004476 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004477 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4478 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4479 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4480 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004481 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4482 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4483 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4484 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4485 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
4486 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004487 testcase( regFree1==0 );
4488 testcase( regFree2==0 );
4489 break;
4490 }
drhcce7d172000-05-31 15:34:51 +00004491 case TK_ISNULL:
4492 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00004493 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
4494 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00004495 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4496 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004497 VdbeCoverageIf(v, op==TK_ISNULL);
4498 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004499 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004500 break;
4501 }
drhfef52082000-06-06 01:50:43 +00004502 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004503 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004504 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004505 break;
4506 }
drh84e30ca2011-02-10 17:46:14 +00004507#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004508 case TK_IN: {
4509 int destIfFalse = sqlite3VdbeMakeLabel(v);
4510 int destIfNull = jumpIfNull ? dest : destIfFalse;
4511 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00004512 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00004513 sqlite3VdbeResolveLabel(v, destIfFalse);
4514 break;
4515 }
shanehbb201342011-02-09 19:55:20 +00004516#endif
drhcce7d172000-05-31 15:34:51 +00004517 default: {
dan7b35a772016-07-28 19:47:15 +00004518 default_expr:
drh991a1982014-01-02 17:57:16 +00004519 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004520 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004521 }else if( exprAlwaysFalse(pExpr) ){
4522 /* No-op */
4523 }else{
4524 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4525 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004526 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004527 testcase( regFree1==0 );
4528 testcase( jumpIfNull==0 );
4529 }
drhcce7d172000-05-31 15:34:51 +00004530 break;
4531 }
4532 }
drh2dcef112008-01-12 19:03:48 +00004533 sqlite3ReleaseTempReg(pParse, regFree1);
4534 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004535}
4536
4537/*
drh66b89c82000-11-28 20:47:17 +00004538** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004539** to the label "dest" if the expression is false but execution
4540** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004541**
4542** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004543** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4544** is 0.
drhcce7d172000-05-31 15:34:51 +00004545*/
danielk19774adee202004-05-08 08:23:19 +00004546void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004547 Vdbe *v = pParse->pVdbe;
4548 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004549 int regFree1 = 0;
4550 int regFree2 = 0;
4551 int r1, r2;
4552
drh35573352008-01-08 23:54:25 +00004553 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004554 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004555 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004556
4557 /* The value of pExpr->op and op are related as follows:
4558 **
4559 ** pExpr->op op
4560 ** --------- ----------
4561 ** TK_ISNULL OP_NotNull
4562 ** TK_NOTNULL OP_IsNull
4563 ** TK_NE OP_Eq
4564 ** TK_EQ OP_Ne
4565 ** TK_GT OP_Le
4566 ** TK_LE OP_Gt
4567 ** TK_GE OP_Lt
4568 ** TK_LT OP_Ge
4569 **
4570 ** For other values of pExpr->op, op is undefined and unused.
4571 ** The value of TK_ and OP_ constants are arranged such that we
4572 ** can compute the mapping above using the following expression.
4573 ** Assert()s verify that the computation is correct.
4574 */
4575 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4576
4577 /* Verify correct alignment of TK_ and OP_ constants
4578 */
4579 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4580 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4581 assert( pExpr->op!=TK_NE || op==OP_Eq );
4582 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4583 assert( pExpr->op!=TK_LT || op==OP_Ge );
4584 assert( pExpr->op!=TK_LE || op==OP_Gt );
4585 assert( pExpr->op!=TK_GT || op==OP_Le );
4586 assert( pExpr->op!=TK_GE || op==OP_Lt );
4587
danba00e302016-07-23 20:24:06 +00004588 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004589 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004590 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004591 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh3d6bedf2018-09-19 14:54:38 +00004592 assert( pExpr->eX==EX_Right );
4593 sqlite3ExprIfFalse(pParse, pExpr->x.pRight, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004594 break;
4595 }
4596 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004597 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004598 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004599 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh3d6bedf2018-09-19 14:54:38 +00004600 assert( pExpr->eX==EX_Right );
4601 sqlite3ExprIfFalse(pParse, pExpr->x.pRight, dest, jumpIfNull);
danielk19774adee202004-05-08 08:23:19 +00004602 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00004603 break;
4604 }
4605 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004606 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004607 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004608 break;
4609 }
drh8abed7b2018-02-26 18:49:05 +00004610 case TK_TRUTH: {
drh96acafb2018-02-27 14:49:25 +00004611 int isNot; /* IS NOT TRUE or IS NOT FALSE */
4612 int isTrue; /* IS TRUE or IS NOT TRUE */
drh8abed7b2018-02-26 18:49:05 +00004613 testcase( jumpIfNull==0 );
drh8abed7b2018-02-26 18:49:05 +00004614 isNot = pExpr->op2==TK_ISNOT;
drh3d6bedf2018-09-19 14:54:38 +00004615 assert( pExpr->eX==EX_Right );
4616 isTrue = sqlite3ExprTruthValue(pExpr->x.pRight);
drh43c4ac82018-02-26 21:26:27 +00004617 testcase( isTrue && isNot );
drh96acafb2018-02-27 14:49:25 +00004618 testcase( !isTrue && isNot );
drh43c4ac82018-02-26 21:26:27 +00004619 if( isTrue ^ isNot ){
drh8abed7b2018-02-26 18:49:05 +00004620 /* IS TRUE and IS NOT FALSE */
4621 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest,
4622 isNot ? 0 : SQLITE_JUMPIFNULL);
4623
4624 }else{
4625 /* IS FALSE and IS NOT TRUE */
4626 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest,
drh96acafb2018-02-27 14:49:25 +00004627 isNot ? 0 : SQLITE_JUMPIFNULL);
drh8abed7b2018-02-26 18:49:05 +00004628 }
drh007c8432018-02-26 03:20:18 +00004629 break;
4630 }
drhde845c22016-03-17 19:07:52 +00004631 case TK_IS:
4632 case TK_ISNOT:
4633 testcase( pExpr->op==TK_IS );
4634 testcase( pExpr->op==TK_ISNOT );
4635 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4636 jumpIfNull = SQLITE_NULLEQ;
4637 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004638 case TK_LT:
4639 case TK_LE:
4640 case TK_GT:
4641 case TK_GE:
4642 case TK_NE:
4643 case TK_EQ: {
dan625015e2016-07-30 16:39:28 +00004644 if( sqlite3ExprIsVector(pExpr->pLeft) ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00004645 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004646 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drh3d6bedf2018-09-19 14:54:38 +00004647 assert( pExpr->eX==EX_Right );
4648 r2 = sqlite3ExprCodeTemp(pParse, pExpr->x.pRight, &regFree2);
4649 codeCompare(pParse, pExpr->pLeft, pExpr->x.pRight, op,
drh2dcef112008-01-12 19:03:48 +00004650 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004651 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4652 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4653 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4654 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004655 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4656 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4657 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4658 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4659 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4660 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004661 testcase( regFree1==0 );
4662 testcase( regFree2==0 );
4663 break;
4664 }
drhcce7d172000-05-31 15:34:51 +00004665 case TK_ISNULL:
4666 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004667 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4668 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004669 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4670 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004671 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004672 break;
4673 }
drhfef52082000-06-06 01:50:43 +00004674 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004675 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004676 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004677 break;
4678 }
drh84e30ca2011-02-10 17:46:14 +00004679#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004680 case TK_IN: {
4681 if( jumpIfNull ){
4682 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4683 }else{
4684 int destIfNull = sqlite3VdbeMakeLabel(v);
4685 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4686 sqlite3VdbeResolveLabel(v, destIfNull);
4687 }
4688 break;
4689 }
shanehbb201342011-02-09 19:55:20 +00004690#endif
drhcce7d172000-05-31 15:34:51 +00004691 default: {
danba00e302016-07-23 20:24:06 +00004692 default_expr:
drh991a1982014-01-02 17:57:16 +00004693 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004694 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004695 }else if( exprAlwaysTrue(pExpr) ){
4696 /* no-op */
4697 }else{
4698 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4699 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004700 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004701 testcase( regFree1==0 );
4702 testcase( jumpIfNull==0 );
4703 }
drhcce7d172000-05-31 15:34:51 +00004704 break;
4705 }
4706 }
drh2dcef112008-01-12 19:03:48 +00004707 sqlite3ReleaseTempReg(pParse, regFree1);
4708 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004709}
drh22827922000-06-06 17:27:05 +00004710
4711/*
drh72bc8202015-06-11 13:58:35 +00004712** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4713** code generation, and that copy is deleted after code generation. This
4714** ensures that the original pExpr is unchanged.
4715*/
4716void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4717 sqlite3 *db = pParse->db;
4718 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4719 if( db->mallocFailed==0 ){
4720 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4721 }
4722 sqlite3ExprDelete(db, pCopy);
4723}
4724
dan5aa550c2017-06-24 18:10:29 +00004725/*
4726** Expression pVar is guaranteed to be an SQL variable. pExpr may be any
4727** type of expression.
4728**
4729** If pExpr is a simple SQL value - an integer, real, string, blob
4730** or NULL value - then the VDBE currently being prepared is configured
4731** to re-prepare each time a new value is bound to variable pVar.
4732**
4733** Additionally, if pExpr is a simple SQL value and the value is the
4734** same as that currently bound to variable pVar, non-zero is returned.
4735** Otherwise, if the values are not the same or if pExpr is not a simple
4736** SQL value, zero is returned.
4737*/
4738static int exprCompareVariable(Parse *pParse, Expr *pVar, Expr *pExpr){
4739 int res = 0;
drhc0804222017-06-28 21:47:16 +00004740 int iVar;
4741 sqlite3_value *pL, *pR = 0;
4742
4743 sqlite3ValueFromExpr(pParse->db, pExpr, SQLITE_UTF8, SQLITE_AFF_BLOB, &pR);
4744 if( pR ){
4745 iVar = pVar->iColumn;
dan5aa550c2017-06-24 18:10:29 +00004746 sqlite3VdbeSetVarmask(pParse->pVdbe, iVar);
dan5aa550c2017-06-24 18:10:29 +00004747 pL = sqlite3VdbeGetBoundValue(pParse->pReprepare, iVar, SQLITE_AFF_BLOB);
drh5aa307e2017-06-29 01:23:12 +00004748 if( pL ){
4749 if( sqlite3_value_type(pL)==SQLITE_TEXT ){
4750 sqlite3_value_text(pL); /* Make sure the encoding is UTF-8 */
4751 }
4752 res = 0==sqlite3MemCompare(pL, pR, 0);
dan5aa550c2017-06-24 18:10:29 +00004753 }
drhc0804222017-06-28 21:47:16 +00004754 sqlite3ValueFree(pR);
4755 sqlite3ValueFree(pL);
dan5aa550c2017-06-24 18:10:29 +00004756 }
4757
4758 return res;
4759}
drh72bc8202015-06-11 13:58:35 +00004760
4761/*
drh1d9da702010-01-07 15:17:02 +00004762** Do a deep comparison of two expression trees. Return 0 if the two
4763** expressions are completely identical. Return 1 if they differ only
4764** by a COLLATE operator at the top level. Return 2 if there are differences
4765** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004766**
drh619a1302013-08-01 13:04:46 +00004767** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4768** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4769**
drh66518ca2013-08-01 15:09:57 +00004770** The pA side might be using TK_REGISTER. If that is the case and pB is
4771** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4772**
drh1d9da702010-01-07 15:17:02 +00004773** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004774** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004775** identical, we return 2 just to be safe. So if this routine
4776** returns 2, then you do not really know for certain if the two
4777** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004778** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004779** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004780** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004781** an incorrect 0 or 1 could lead to a malfunction.
dan5aa550c2017-06-24 18:10:29 +00004782**
drhc0804222017-06-28 21:47:16 +00004783** If pParse is not NULL then TK_VARIABLE terms in pA with bindings in
4784** pParse->pReprepare can be matched against literals in pB. The
4785** pParse->pVdbe->expmask bitmask is updated for each variable referenced.
4786** If pParse is NULL (the normal case) then any TK_VARIABLE term in
4787** Argument pParse should normally be NULL. If it is not NULL and pA or
4788** pB causes a return value of 2.
drh22827922000-06-06 17:27:05 +00004789*/
dan5aa550c2017-06-24 18:10:29 +00004790int sqlite3ExprCompare(Parse *pParse, Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004791 u32 combinedFlags;
4792 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004793 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004794 }
dan5aa550c2017-06-24 18:10:29 +00004795 if( pParse && pA->op==TK_VARIABLE && exprCompareVariable(pParse, pA, pB) ){
4796 return 0;
4797 }
drh10d1edf2013-11-15 15:52:39 +00004798 combinedFlags = pA->flags | pB->flags;
4799 if( combinedFlags & EP_IntValue ){
4800 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4801 return 0;
4802 }
drh1d9da702010-01-07 15:17:02 +00004803 return 2;
drh22827922000-06-06 17:27:05 +00004804 }
drhc2acc4e2013-11-15 18:15:19 +00004805 if( pA->op!=pB->op ){
dan5aa550c2017-06-24 18:10:29 +00004806 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA->pLeft,pB,iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004807 return 1;
4808 }
dan5aa550c2017-06-24 18:10:29 +00004809 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pParse, pA,pB->pLeft,iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004810 return 1;
4811 }
4812 return 2;
4813 }
drh2edc5fd2015-11-24 02:10:52 +00004814 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004815 if( pA->op==TK_FUNCTION ){
4816 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
drhd5af5422018-04-13 14:27:01 +00004817 }else if( pA->op==TK_COLLATE ){
drhe79f6292018-04-18 17:52:28 +00004818 if( sqlite3_stricmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
drhefad2e22018-07-27 16:57:11 +00004819 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhd5af5422018-04-13 14:27:01 +00004820 return 2;
drh2646da72005-12-09 20:02:05 +00004821 }
drh22827922000-06-06 17:27:05 +00004822 }
drh10d1edf2013-11-15 15:52:39 +00004823 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004824 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh3b3c86a2018-09-18 21:35:31 +00004825 if( pA->eX==EX_Select || pA->eX!=pB->eX ) return 2;
drhefad2e22018-07-27 16:57:11 +00004826 if( (combinedFlags & EP_FixedCol)==0
4827 && sqlite3ExprCompare(pParse, pA->pLeft, pB->pLeft, iTab) ) return 2;
drh3d6bedf2018-09-19 14:54:38 +00004828 if( pA->eX==EX_Right ){
4829 if( sqlite3ExprCompare(pParse,pA->x.pRight,pB->x.pRight,iTab) ) return 2;
4830 }
drh3b3c86a2018-09-18 21:35:31 +00004831 if( pA->eX==EX_List ){
4832 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
4833 }
drhf49ff6f2018-04-23 20:38:40 +00004834 assert( (combinedFlags & EP_Reduced)==0 );
4835 if( pA->op!=TK_STRING && pA->op!=TK_TRUEFALSE ){
drh10d1edf2013-11-15 15:52:39 +00004836 if( pA->iColumn!=pB->iColumn ) return 2;
4837 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004838 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004839 }
drh6cbb4c92018-07-10 06:47:07 +00004840#ifndef SQLITE_OMIT_WINDOWFUNC
drh38630ae2018-07-10 07:25:42 +00004841 /* Justification for the assert():
drheee08612018-07-10 07:39:23 +00004842 ** window functions have p->op==TK_FUNCTION but aggregate functions
drh38630ae2018-07-10 07:25:42 +00004843 ** have p->op==TK_AGG_FUNCTION. So any comparison between an aggregate
4844 ** function and a window function should have failed before reaching
4845 ** this point. And, it is not possible to have a window function and
4846 ** a scalar function with the same name and number of arguments. So
4847 ** if we reach this point, either A and B both window functions or
4848 ** neither are a window functions. */
4849 assert( (pA->pWin==0)==(pB->pWin==0) );
4850
drh6cbb4c92018-07-10 06:47:07 +00004851 if( pA->pWin!=0 ){
drh6cbb4c92018-07-10 06:47:07 +00004852 if( sqlite3WindowCompare(pParse,pA->pWin,pB->pWin)!=0 ) return 2;
drh6cbb4c92018-07-10 06:47:07 +00004853 }
4854#endif
drh10d1edf2013-11-15 15:52:39 +00004855 }
drh1d9da702010-01-07 15:17:02 +00004856 return 0;
drh22827922000-06-06 17:27:05 +00004857}
4858
drh8c6f6662010-04-26 19:17:26 +00004859/*
4860** Compare two ExprList objects. Return 0 if they are identical and
4861** non-zero if they differ in any way.
4862**
drh619a1302013-08-01 13:04:46 +00004863** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4864** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4865**
drh8c6f6662010-04-26 19:17:26 +00004866** This routine might return non-zero for equivalent ExprLists. The
4867** only consequence will be disabled optimizations. But this routine
4868** must never return 0 if the two ExprList objects are different, or
4869** a malfunction will result.
4870**
4871** Two NULL pointers are considered to be the same. But a NULL pointer
4872** always differs from a non-NULL pointer.
4873*/
drh619a1302013-08-01 13:04:46 +00004874int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004875 int i;
4876 if( pA==0 && pB==0 ) return 0;
4877 if( pA==0 || pB==0 ) return 1;
4878 if( pA->nExpr!=pB->nExpr ) return 1;
4879 for(i=0; i<pA->nExpr; i++){
4880 Expr *pExprA = pA->a[i].pExpr;
4881 Expr *pExprB = pB->a[i].pExpr;
4882 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
dan5aa550c2017-06-24 18:10:29 +00004883 if( sqlite3ExprCompare(0, pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004884 }
4885 return 0;
4886}
drh13449892005-09-07 21:22:45 +00004887
drh22827922000-06-06 17:27:05 +00004888/*
drhf9463df2017-02-11 14:59:58 +00004889** Like sqlite3ExprCompare() except COLLATE operators at the top-level
4890** are ignored.
4891*/
4892int sqlite3ExprCompareSkip(Expr *pA, Expr *pB, int iTab){
dan5aa550c2017-06-24 18:10:29 +00004893 return sqlite3ExprCompare(0,
drhf9463df2017-02-11 14:59:58 +00004894 sqlite3ExprSkipCollate(pA),
4895 sqlite3ExprSkipCollate(pB),
4896 iTab);
4897}
4898
4899/*
drh4bd5f732013-07-31 23:22:39 +00004900** Return true if we can prove the pE2 will always be true if pE1 is
4901** true. Return false if we cannot complete the proof or if pE2 might
4902** be false. Examples:
4903**
drh619a1302013-08-01 13:04:46 +00004904** pE1: x==5 pE2: x==5 Result: true
4905** pE1: x>0 pE2: x==5 Result: false
4906** pE1: x=21 pE2: x=21 OR y=43 Result: true
4907** pE1: x!=123 pE2: x IS NOT NULL Result: true
4908** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4909** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4910** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004911**
4912** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4913** Expr.iTable<0 then assume a table number given by iTab.
4914**
drhc0804222017-06-28 21:47:16 +00004915** If pParse is not NULL, then the values of bound variables in pE1 are
4916** compared against literal values in pE2 and pParse->pVdbe->expmask is
4917** modified to record which bound variables are referenced. If pParse
4918** is NULL, then false will be returned if pE1 contains any bound variables.
4919**
drh4bd5f732013-07-31 23:22:39 +00004920** When in doubt, return false. Returning true might give a performance
4921** improvement. Returning false might cause a performance reduction, but
4922** it will always give the correct answer and is hence always safe.
4923*/
dan5aa550c2017-06-24 18:10:29 +00004924int sqlite3ExprImpliesExpr(Parse *pParse, Expr *pE1, Expr *pE2, int iTab){
4925 if( sqlite3ExprCompare(pParse, pE1, pE2, iTab)==0 ){
drh619a1302013-08-01 13:04:46 +00004926 return 1;
4927 }
drh3d6bedf2018-09-19 14:54:38 +00004928 assert( pE2->op!=TK_OR || pE2->eX==EX_Right );
drh619a1302013-08-01 13:04:46 +00004929 if( pE2->op==TK_OR
dan5aa550c2017-06-24 18:10:29 +00004930 && (sqlite3ExprImpliesExpr(pParse, pE1, pE2->pLeft, iTab)
drh3d6bedf2018-09-19 14:54:38 +00004931 || sqlite3ExprImpliesExpr(pParse, pE1, pE2->x.pRight, iTab) )
drh619a1302013-08-01 13:04:46 +00004932 ){
4933 return 1;
4934 }
drh1ad93a02016-11-02 02:17:52 +00004935 if( pE2->op==TK_NOTNULL && pE1->op!=TK_ISNULL && pE1->op!=TK_IS ){
4936 Expr *pX = sqlite3ExprSkipCollate(pE1->pLeft);
4937 testcase( pX!=pE1->pLeft );
dan5aa550c2017-06-24 18:10:29 +00004938 if( sqlite3ExprCompare(pParse, pX, pE2->pLeft, iTab)==0 ) return 1;
drh619a1302013-08-01 13:04:46 +00004939 }
4940 return 0;
drh4bd5f732013-07-31 23:22:39 +00004941}
4942
4943/*
drh25897872018-03-20 21:16:15 +00004944** This is the Expr node callback for sqlite3ExprImpliesNotNullRow().
4945** If the expression node requires that the table at pWalker->iCur
4946** have a non-NULL column, then set pWalker->eCode to 1 and abort.
4947*/
4948static int impliesNotNullRow(Walker *pWalker, Expr *pExpr){
drh821b6102018-03-24 18:01:51 +00004949 /* This routine is only called for WHERE clause expressions and so it
4950 ** cannot have any TK_AGG_COLUMN entries because those are only found
4951 ** in HAVING clauses. We can get a TK_AGG_FUNCTION in a WHERE clause,
4952 ** but that is an illegal construct and the query will be rejected at
4953 ** a later stage of processing, so the TK_AGG_FUNCTION case does not
4954 ** need to be considered here. */
4955 assert( pExpr->op!=TK_AGG_COLUMN );
4956 testcase( pExpr->op==TK_AGG_FUNCTION );
4957
drh25897872018-03-20 21:16:15 +00004958 if( ExprHasProperty(pExpr, EP_FromJoin) ) return WRC_Prune;
4959 switch( pExpr->op ){
dan04932222018-04-10 15:31:56 +00004960 case TK_ISNOT:
dana1054dc2018-04-10 12:10:01 +00004961 case TK_NOT:
drh25897872018-03-20 21:16:15 +00004962 case TK_ISNULL:
4963 case TK_IS:
4964 case TK_OR:
drh2c492062018-03-24 13:24:02 +00004965 case TK_CASE:
drhe3eff262018-03-24 15:47:31 +00004966 case TK_IN:
drh25897872018-03-20 21:16:15 +00004967 case TK_FUNCTION:
dan04932222018-04-10 15:31:56 +00004968 testcase( pExpr->op==TK_ISNOT );
4969 testcase( pExpr->op==TK_NOT );
drh821b6102018-03-24 18:01:51 +00004970 testcase( pExpr->op==TK_ISNULL );
4971 testcase( pExpr->op==TK_IS );
4972 testcase( pExpr->op==TK_OR );
4973 testcase( pExpr->op==TK_CASE );
4974 testcase( pExpr->op==TK_IN );
4975 testcase( pExpr->op==TK_FUNCTION );
drh25897872018-03-20 21:16:15 +00004976 return WRC_Prune;
4977 case TK_COLUMN:
drh25897872018-03-20 21:16:15 +00004978 if( pWalker->u.iCur==pExpr->iTable ){
4979 pWalker->eCode = 1;
4980 return WRC_Abort;
4981 }
4982 return WRC_Prune;
drh98811552018-04-03 14:04:48 +00004983
4984 /* Virtual tables are allowed to use constraints like x=NULL. So
4985 ** a term of the form x=y does not prove that y is not null if x
4986 ** is the column of a virtual table */
4987 case TK_EQ:
4988 case TK_NE:
4989 case TK_LT:
4990 case TK_LE:
4991 case TK_GT:
4992 case TK_GE:
4993 testcase( pExpr->op==TK_EQ );
4994 testcase( pExpr->op==TK_NE );
4995 testcase( pExpr->op==TK_LT );
4996 testcase( pExpr->op==TK_LE );
4997 testcase( pExpr->op==TK_GT );
4998 testcase( pExpr->op==TK_GE );
drh3d6bedf2018-09-19 14:54:38 +00004999 assert( pExpr->eX==EX_Right );
drh98811552018-04-03 14:04:48 +00005000 if( (pExpr->pLeft->op==TK_COLUMN && IsVirtual(pExpr->pLeft->pTab))
drh3d6bedf2018-09-19 14:54:38 +00005001 || (pExpr->x.pRight->op==TK_COLUMN && IsVirtual(pExpr->x.pRight->pTab))
drh98811552018-04-03 14:04:48 +00005002 ){
5003 return WRC_Prune;
5004 }
drh25897872018-03-20 21:16:15 +00005005 default:
5006 return WRC_Continue;
5007 }
5008}
5009
5010/*
5011** Return true (non-zero) if expression p can only be true if at least
5012** one column of table iTab is non-null. In other words, return true
5013** if expression p will always be NULL or false if every column of iTab
5014** is NULL.
5015**
drh821b6102018-03-24 18:01:51 +00005016** False negatives are acceptable. In other words, it is ok to return
5017** zero even if expression p will never be true of every column of iTab
5018** is NULL. A false negative is merely a missed optimization opportunity.
5019**
5020** False positives are not allowed, however. A false positive may result
5021** in an incorrect answer.
5022**
drh25897872018-03-20 21:16:15 +00005023** Terms of p that are marked with EP_FromJoin (and hence that come from
5024** the ON or USING clauses of LEFT JOINS) are excluded from the analysis.
5025**
5026** This routine is used to check if a LEFT JOIN can be converted into
5027** an ordinary JOIN. The p argument is the WHERE clause. If the WHERE
5028** clause requires that some column of the right table of the LEFT JOIN
5029** be non-NULL, then the LEFT JOIN can be safely converted into an
5030** ordinary join.
5031*/
5032int sqlite3ExprImpliesNonNullRow(Expr *p, int iTab){
5033 Walker w;
5034 w.xExprCallback = impliesNotNullRow;
5035 w.xSelectCallback = 0;
5036 w.xSelectCallback2 = 0;
5037 w.eCode = 0;
5038 w.u.iCur = iTab;
5039 sqlite3WalkExpr(&w, p);
5040 return w.eCode;
5041}
5042
5043/*
drh030796d2012-08-23 16:18:10 +00005044** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00005045** to determine if an expression can be evaluated by reference to the
5046** index only, without having to do a search for the corresponding
5047** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
5048** is the cursor for the table.
5049*/
5050struct IdxCover {
5051 Index *pIdx; /* The index to be tested for coverage */
5052 int iCur; /* Cursor number for the table corresponding to the index */
5053};
5054
5055/*
5056** Check to see if there are references to columns in table
5057** pWalker->u.pIdxCover->iCur can be satisfied using the index
5058** pWalker->u.pIdxCover->pIdx.
5059*/
5060static int exprIdxCover(Walker *pWalker, Expr *pExpr){
5061 if( pExpr->op==TK_COLUMN
5062 && pExpr->iTable==pWalker->u.pIdxCover->iCur
5063 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
5064 ){
5065 pWalker->eCode = 1;
5066 return WRC_Abort;
5067 }
5068 return WRC_Continue;
5069}
5070
5071/*
drhe604ec02016-07-27 19:20:58 +00005072** Determine if an index pIdx on table with cursor iCur contains will
5073** the expression pExpr. Return true if the index does cover the
5074** expression and false if the pExpr expression references table columns
5075** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00005076**
5077** An index covering an expression means that the expression can be
5078** evaluated using only the index and without having to lookup the
5079** corresponding table entry.
5080*/
5081int sqlite3ExprCoveredByIndex(
5082 Expr *pExpr, /* The index to be tested */
5083 int iCur, /* The cursor number for the corresponding table */
5084 Index *pIdx /* The index that might be used for coverage */
5085){
5086 Walker w;
5087 struct IdxCover xcov;
5088 memset(&w, 0, sizeof(w));
5089 xcov.iCur = iCur;
5090 xcov.pIdx = pIdx;
5091 w.xExprCallback = exprIdxCover;
5092 w.u.pIdxCover = &xcov;
5093 sqlite3WalkExpr(&w, pExpr);
5094 return !w.eCode;
5095}
5096
5097
5098/*
5099** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00005100** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00005101** aggregate function, in order to implement the
5102** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00005103*/
drh030796d2012-08-23 16:18:10 +00005104struct SrcCount {
5105 SrcList *pSrc; /* One particular FROM clause in a nested query */
5106 int nThis; /* Number of references to columns in pSrcList */
5107 int nOther; /* Number of references to columns in other FROM clauses */
5108};
5109
5110/*
5111** Count the number of references to columns.
5112*/
5113static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00005114 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
5115 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
5116 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
5117 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
5118 ** NEVER() will need to be removed. */
5119 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00005120 int i;
drh030796d2012-08-23 16:18:10 +00005121 struct SrcCount *p = pWalker->u.pSrcCount;
5122 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00005123 int nSrc = pSrc ? pSrc->nSrc : 0;
5124 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00005125 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00005126 }
drh655814d2015-01-09 01:27:29 +00005127 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00005128 p->nThis++;
5129 }else{
5130 p->nOther++;
5131 }
drh374fdce2012-04-17 16:38:53 +00005132 }
drh030796d2012-08-23 16:18:10 +00005133 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00005134}
5135
5136/*
drh030796d2012-08-23 16:18:10 +00005137** Determine if any of the arguments to the pExpr Function reference
5138** pSrcList. Return true if they do. Also return true if the function
5139** has no arguments or has only constant arguments. Return false if pExpr
5140** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00005141*/
drh030796d2012-08-23 16:18:10 +00005142int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00005143 Walker w;
drh030796d2012-08-23 16:18:10 +00005144 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00005145 assert( pExpr->op==TK_AGG_FUNCTION );
drh030796d2012-08-23 16:18:10 +00005146 w.xExprCallback = exprSrcCount;
drh979dd1b2017-05-29 14:26:07 +00005147 w.xSelectCallback = 0;
drh030796d2012-08-23 16:18:10 +00005148 w.u.pSrcCount = &cnt;
5149 cnt.pSrc = pSrcList;
5150 cnt.nThis = 0;
5151 cnt.nOther = 0;
5152 sqlite3WalkExprList(&w, pExpr->x.pList);
5153 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00005154}
5155
5156/*
drh13449892005-09-07 21:22:45 +00005157** Add a new element to the pAggInfo->aCol[] array. Return the index of
5158** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00005159*/
drh17435752007-08-16 04:30:38 +00005160static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00005161 int i;
drhcf643722007-03-27 13:36:37 +00005162 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00005163 db,
drhcf643722007-03-27 13:36:37 +00005164 pInfo->aCol,
5165 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00005166 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00005167 &i
5168 );
drh13449892005-09-07 21:22:45 +00005169 return i;
5170}
5171
5172/*
5173** Add a new element to the pAggInfo->aFunc[] array. Return the index of
5174** the new element. Return a negative number if malloc fails.
5175*/
drh17435752007-08-16 04:30:38 +00005176static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00005177 int i;
drhcf643722007-03-27 13:36:37 +00005178 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00005179 db,
drhcf643722007-03-27 13:36:37 +00005180 pInfo->aFunc,
5181 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00005182 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00005183 &i
5184 );
drh13449892005-09-07 21:22:45 +00005185 return i;
5186}
drh22827922000-06-06 17:27:05 +00005187
5188/*
drh7d10d5a2008-08-20 16:35:10 +00005189** This is the xExprCallback for a tree walker. It is used to
5190** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00005191** for additional information.
drh22827922000-06-06 17:27:05 +00005192*/
drh7d10d5a2008-08-20 16:35:10 +00005193static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00005194 int i;
drh7d10d5a2008-08-20 16:35:10 +00005195 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00005196 Parse *pParse = pNC->pParse;
5197 SrcList *pSrcList = pNC->pSrcList;
drh25c3b8c2018-04-16 10:34:13 +00005198 AggInfo *pAggInfo = pNC->uNC.pAggInfo;
drh22827922000-06-06 17:27:05 +00005199
drh25c3b8c2018-04-16 10:34:13 +00005200 assert( pNC->ncFlags & NC_UAggInfo );
drh22827922000-06-06 17:27:05 +00005201 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00005202 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00005203 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00005204 testcase( pExpr->op==TK_AGG_COLUMN );
5205 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00005206 /* Check to see if the column is in one of the tables in the FROM
5207 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00005208 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00005209 struct SrcList_item *pItem = pSrcList->a;
5210 for(i=0; i<pSrcList->nSrc; i++, pItem++){
5211 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00005212 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00005213 if( pExpr->iTable==pItem->iCursor ){
5214 /* If we reach this point, it means that pExpr refers to a table
5215 ** that is in the FROM clause of the aggregate query.
5216 **
5217 ** Make an entry for the column in pAggInfo->aCol[] if there
5218 ** is not an entry there already.
5219 */
drh7f906d62007-03-12 23:48:52 +00005220 int k;
drh13449892005-09-07 21:22:45 +00005221 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00005222 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00005223 if( pCol->iTable==pExpr->iTable &&
5224 pCol->iColumn==pExpr->iColumn ){
5225 break;
5226 }
danielk1977a58fdfb2005-02-08 07:50:40 +00005227 }
danielk19771e536952007-08-16 10:09:01 +00005228 if( (k>=pAggInfo->nColumn)
5229 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
5230 ){
drh7f906d62007-03-12 23:48:52 +00005231 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00005232 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00005233 pCol->iTable = pExpr->iTable;
5234 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00005235 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00005236 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00005237 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00005238 if( pAggInfo->pGroupBy ){
5239 int j, n;
5240 ExprList *pGB = pAggInfo->pGroupBy;
5241 struct ExprList_item *pTerm = pGB->a;
5242 n = pGB->nExpr;
5243 for(j=0; j<n; j++, pTerm++){
5244 Expr *pE = pTerm->pExpr;
5245 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
5246 pE->iColumn==pExpr->iColumn ){
5247 pCol->iSorterColumn = j;
5248 break;
5249 }
5250 }
5251 }
5252 if( pCol->iSorterColumn<0 ){
5253 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
5254 }
5255 }
5256 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
5257 ** because it was there before or because we just created it).
5258 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
5259 ** pAggInfo->aCol[] entry.
5260 */
drhebb6a652013-09-12 23:42:22 +00005261 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00005262 pExpr->pAggInfo = pAggInfo;
5263 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00005264 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00005265 break;
5266 } /* endif pExpr->iTable==pItem->iCursor */
5267 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00005268 }
drh7d10d5a2008-08-20 16:35:10 +00005269 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00005270 }
5271 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00005272 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00005273 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00005274 ){
drh13449892005-09-07 21:22:45 +00005275 /* Check to see if pExpr is a duplicate of another aggregate
5276 ** function that is already in the pAggInfo structure
5277 */
5278 struct AggInfo_func *pItem = pAggInfo->aFunc;
5279 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
dan5aa550c2017-06-24 18:10:29 +00005280 if( sqlite3ExprCompare(0, pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00005281 break;
5282 }
drh22827922000-06-06 17:27:05 +00005283 }
drh13449892005-09-07 21:22:45 +00005284 if( i>=pAggInfo->nFunc ){
5285 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
5286 */
danielk197714db2662006-01-09 16:12:04 +00005287 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00005288 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00005289 if( i>=0 ){
drh3b3c86a2018-09-18 21:35:31 +00005290 assert( pExpr->eX==EX_List || pExpr->eX==EX_None );
drh13449892005-09-07 21:22:45 +00005291 pItem = &pAggInfo->aFunc[i];
5292 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00005293 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00005294 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00005295 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00005296 pExpr->u.zToken,
drh3b3c86a2018-09-18 21:35:31 +00005297 pExpr->eX==EX_List ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00005298 if( pExpr->flags & EP_Distinct ){
5299 pItem->iDistinct = pParse->nTab++;
5300 }else{
5301 pItem->iDistinct = -1;
5302 }
drh13449892005-09-07 21:22:45 +00005303 }
danielk1977a58fdfb2005-02-08 07:50:40 +00005304 }
drh13449892005-09-07 21:22:45 +00005305 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
5306 */
drhc5cd1242013-09-12 16:50:49 +00005307 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00005308 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00005309 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00005310 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00005311 return WRC_Prune;
5312 }else{
5313 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00005314 }
drh22827922000-06-06 17:27:05 +00005315 }
5316 }
drh7d10d5a2008-08-20 16:35:10 +00005317 return WRC_Continue;
5318}
5319static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00005320 UNUSED_PARAMETER(pSelect);
drh979dd1b2017-05-29 14:26:07 +00005321 pWalker->walkerDepth++;
drh374fdce2012-04-17 16:38:53 +00005322 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00005323}
drh979dd1b2017-05-29 14:26:07 +00005324static void analyzeAggregatesInSelectEnd(Walker *pWalker, Select *pSelect){
5325 UNUSED_PARAMETER(pSelect);
5326 pWalker->walkerDepth--;
5327}
drh626a8792005-01-17 22:08:19 +00005328
5329/*
drhe8abb4c2012-11-02 18:24:57 +00005330** Analyze the pExpr expression looking for aggregate functions and
5331** for variables that need to be added to AggInfo object that pNC->pAggInfo
5332** points to. Additional entries are made on the AggInfo object as
5333** necessary.
drh626a8792005-01-17 22:08:19 +00005334**
5335** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00005336** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00005337*/
drhd2b3e232008-01-23 14:51:49 +00005338void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00005339 Walker w;
5340 w.xExprCallback = analyzeAggregate;
5341 w.xSelectCallback = analyzeAggregatesInSelect;
drh979dd1b2017-05-29 14:26:07 +00005342 w.xSelectCallback2 = analyzeAggregatesInSelectEnd;
5343 w.walkerDepth = 0;
drh7d10d5a2008-08-20 16:35:10 +00005344 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00005345 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00005346 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00005347}
drh5d9a4af2005-08-30 00:54:01 +00005348
5349/*
5350** Call sqlite3ExprAnalyzeAggregates() for every expression in an
5351** expression list. Return the number of errors.
5352**
5353** If an error is found, the analysis is cut short.
5354*/
drhd2b3e232008-01-23 14:51:49 +00005355void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00005356 struct ExprList_item *pItem;
5357 int i;
drh5d9a4af2005-08-30 00:54:01 +00005358 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00005359 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
5360 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00005361 }
5362 }
drh5d9a4af2005-08-30 00:54:01 +00005363}
drh892d3172008-01-10 03:46:36 +00005364
5365/*
drhceea3322009-04-23 13:22:42 +00005366** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00005367*/
5368int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00005369 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00005370 return ++pParse->nMem;
5371 }
danielk19772f425f62008-07-04 09:41:39 +00005372 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00005373}
drhceea3322009-04-23 13:22:42 +00005374
5375/*
5376** Deallocate a register, making available for reuse for some other
5377** purpose.
drhceea3322009-04-23 13:22:42 +00005378*/
drh892d3172008-01-10 03:46:36 +00005379void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00005380 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drh892d3172008-01-10 03:46:36 +00005381 pParse->aTempReg[pParse->nTempReg++] = iReg;
5382 }
5383}
5384
5385/*
drhed24da42016-09-06 14:37:05 +00005386** Allocate or deallocate a block of nReg consecutive registers.
drh892d3172008-01-10 03:46:36 +00005387*/
5388int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00005389 int i, n;
drhed24da42016-09-06 14:37:05 +00005390 if( nReg==1 ) return sqlite3GetTempReg(pParse);
drhe55cbd72008-03-31 23:48:03 +00005391 i = pParse->iRangeReg;
5392 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00005393 if( nReg<=n ){
drh892d3172008-01-10 03:46:36 +00005394 pParse->iRangeReg += nReg;
5395 pParse->nRangeReg -= nReg;
5396 }else{
5397 i = pParse->nMem+1;
5398 pParse->nMem += nReg;
5399 }
5400 return i;
5401}
5402void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhed24da42016-09-06 14:37:05 +00005403 if( nReg==1 ){
5404 sqlite3ReleaseTempReg(pParse, iReg);
5405 return;
5406 }
drh892d3172008-01-10 03:46:36 +00005407 if( nReg>pParse->nRangeReg ){
5408 pParse->nRangeReg = nReg;
5409 pParse->iRangeReg = iReg;
5410 }
5411}
drhcdc69552011-12-06 13:24:59 +00005412
5413/*
5414** Mark all temporary registers as being unavailable for reuse.
5415*/
5416void sqlite3ClearTempRegCache(Parse *pParse){
5417 pParse->nTempReg = 0;
5418 pParse->nRangeReg = 0;
5419}
drhbb9b5f22016-03-19 00:35:02 +00005420
5421/*
5422** Validate that no temporary register falls within the range of
5423** iFirst..iLast, inclusive. This routine is only call from within assert()
5424** statements.
5425*/
5426#ifdef SQLITE_DEBUG
5427int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
5428 int i;
5429 if( pParse->nRangeReg>0
drh3963e582017-07-15 20:33:19 +00005430 && pParse->iRangeReg+pParse->nRangeReg > iFirst
5431 && pParse->iRangeReg <= iLast
drhbb9b5f22016-03-19 00:35:02 +00005432 ){
5433 return 0;
5434 }
5435 for(i=0; i<pParse->nTempReg; i++){
5436 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
5437 return 0;
5438 }
5439 }
5440 return 1;
5441}
5442#endif /* SQLITE_DEBUG */