blob: 264f27dbfd660c78ef80edb2915a296d49378eab [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
danielk1977e014a832004-05-17 10:48:57 +000017/*
18** Return the 'affinity' of the expression pExpr if any.
19**
20** If pExpr is a column, a reference to a column via an 'AS' alias,
21** or a sub-select with a column as the return value, then the
22** affinity of that column is returned. Otherwise, 0x00 is returned,
23** indicating no affinity for the expression.
24**
peter.d.reid60ec9142014-09-06 16:39:46 +000025** i.e. the WHERE clause expressions in the following statements all
danielk1977e014a832004-05-17 10:48:57 +000026** have an affinity:
27**
28** CREATE TABLE t1(a);
29** SELECT * FROM t1 WHERE a;
30** SELECT a AS b FROM t1 WHERE b;
31** SELECT * FROM t1 WHERE (select a from t1);
32*/
danielk1977bf3b7212004-05-18 10:06:24 +000033char sqlite3ExprAffinity(Expr *pExpr){
drh580c8c12012-12-08 03:34:04 +000034 int op;
35 pExpr = sqlite3ExprSkipCollate(pExpr);
mistachkin9bec6fb2014-06-26 21:28:21 +000036 if( pExpr->flags & EP_Generic ) return 0;
drh580c8c12012-12-08 03:34:04 +000037 op = pExpr->op;
drh487e2622005-06-25 18:42:14 +000038 if( op==TK_SELECT ){
danielk19776ab3a2e2009-02-19 14:39:25 +000039 assert( pExpr->flags&EP_xIsSelect );
40 return sqlite3ExprAffinity(pExpr->x.pSelect->pEList->a[0].pExpr);
danielk1977a37cdde2004-05-16 11:15:36 +000041 }
drh487e2622005-06-25 18:42:14 +000042#ifndef SQLITE_OMIT_CAST
43 if( op==TK_CAST ){
drh33e619f2009-05-28 01:00:55 +000044 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drhfdaac672013-10-04 15:30:21 +000045 return sqlite3AffinityType(pExpr->u.zToken, 0);
drh487e2622005-06-25 18:42:14 +000046 }
47#endif
danielk1977259a4552008-11-12 08:07:12 +000048 if( (op==TK_AGG_COLUMN || op==TK_COLUMN || op==TK_REGISTER)
49 && pExpr->pTab!=0
50 ){
drh7d10d5a2008-08-20 16:35:10 +000051 /* op==TK_REGISTER && pExpr->pTab!=0 happens when pExpr was originally
52 ** a TK_COLUMN but was previously evaluated and cached in a register */
53 int j = pExpr->iColumn;
54 if( j<0 ) return SQLITE_AFF_INTEGER;
55 assert( pExpr->pTab && j<pExpr->pTab->nCol );
56 return pExpr->pTab->aCol[j].affinity;
57 }
danielk1977a37cdde2004-05-16 11:15:36 +000058 return pExpr->affinity;
59}
60
drh53db1452004-05-20 13:54:53 +000061/*
drh8b4c40d2007-02-01 23:02:45 +000062** Set the collating sequence for expression pExpr to be the collating
drhae80dde2012-12-06 21:16:43 +000063** sequence named by pToken. Return a pointer to a new Expr node that
64** implements the COLLATE operator.
drh0a8a4062012-12-07 18:38:16 +000065**
66** If a memory allocation error occurs, that fact is recorded in pParse->db
67** and the pExpr parameter is returned unchanged.
drh8b4c40d2007-02-01 23:02:45 +000068*/
drh4ef7efa2014-03-20 15:14:08 +000069Expr *sqlite3ExprAddCollateToken(
70 Parse *pParse, /* Parsing context */
71 Expr *pExpr, /* Add the "COLLATE" clause to this expression */
dan80103fc2015-03-20 08:43:59 +000072 const Token *pCollName, /* Name of collating sequence */
73 int dequote /* True to dequote pCollName */
drh4ef7efa2014-03-20 15:14:08 +000074){
drh0a8a4062012-12-07 18:38:16 +000075 if( pCollName->n>0 ){
dan80103fc2015-03-20 08:43:59 +000076 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLLATE, pCollName, dequote);
drh0a8a4062012-12-07 18:38:16 +000077 if( pNew ){
78 pNew->pLeft = pExpr;
drha4c3c872013-09-12 17:29:25 +000079 pNew->flags |= EP_Collate|EP_Skip;
drh0a8a4062012-12-07 18:38:16 +000080 pExpr = pNew;
81 }
drhae80dde2012-12-06 21:16:43 +000082 }
drh0a8a4062012-12-07 18:38:16 +000083 return pExpr;
84}
85Expr *sqlite3ExprAddCollateString(Parse *pParse, Expr *pExpr, const char *zC){
drh261d8a52012-12-08 21:36:26 +000086 Token s;
87 assert( zC!=0 );
drh40aced52016-01-22 17:48:09 +000088 sqlite3TokenInit(&s, (char*)zC);
dan80103fc2015-03-20 08:43:59 +000089 return sqlite3ExprAddCollateToken(pParse, pExpr, &s, 0);
drh0a8a4062012-12-07 18:38:16 +000090}
91
92/*
drh0b8d2552015-09-05 22:36:07 +000093** Skip over any TK_COLLATE operators and any unlikely()
drha4c3c872013-09-12 17:29:25 +000094** or likelihood() function at the root of an expression.
drh0a8a4062012-12-07 18:38:16 +000095*/
96Expr *sqlite3ExprSkipCollate(Expr *pExpr){
drha4c3c872013-09-12 17:29:25 +000097 while( pExpr && ExprHasProperty(pExpr, EP_Skip) ){
98 if( ExprHasProperty(pExpr, EP_Unlikely) ){
drhcca9f3d2013-09-06 15:23:29 +000099 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
100 assert( pExpr->x.pList->nExpr>0 );
drha4c3c872013-09-12 17:29:25 +0000101 assert( pExpr->op==TK_FUNCTION );
drhcca9f3d2013-09-06 15:23:29 +0000102 pExpr = pExpr->x.pList->a[0].pExpr;
103 }else{
drh0b8d2552015-09-05 22:36:07 +0000104 assert( pExpr->op==TK_COLLATE );
drha4c3c872013-09-12 17:29:25 +0000105 pExpr = pExpr->pLeft;
drhcca9f3d2013-09-06 15:23:29 +0000106 }
drha4c3c872013-09-12 17:29:25 +0000107 }
drh0a8a4062012-12-07 18:38:16 +0000108 return pExpr;
drh8b4c40d2007-02-01 23:02:45 +0000109}
110
111/*
drhae80dde2012-12-06 21:16:43 +0000112** Return the collation sequence for the expression pExpr. If
113** there is no defined collating sequence, return NULL.
114**
115** The collating sequence might be determined by a COLLATE operator
116** or by the presence of a column with a defined collating sequence.
117** COLLATE operators take first precedence. Left operands take
118** precedence over right operands.
danielk19770202b292004-06-09 09:55:16 +0000119*/
danielk19777cedc8d2004-06-10 10:50:08 +0000120CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
drhae80dde2012-12-06 21:16:43 +0000121 sqlite3 *db = pParse->db;
danielk19777cedc8d2004-06-10 10:50:08 +0000122 CollSeq *pColl = 0;
drh7d10d5a2008-08-20 16:35:10 +0000123 Expr *p = pExpr;
drh261d8a52012-12-08 21:36:26 +0000124 while( p ){
drhae80dde2012-12-06 21:16:43 +0000125 int op = p->op;
drhfbb24d12014-03-20 17:03:30 +0000126 if( p->flags & EP_Generic ) break;
drhae80dde2012-12-06 21:16:43 +0000127 if( op==TK_CAST || op==TK_UPLUS ){
128 p = p->pLeft;
129 continue;
130 }
dan36e78302013-08-21 12:04:32 +0000131 if( op==TK_COLLATE || (op==TK_REGISTER && p->op2==TK_COLLATE) ){
drh6fdd3d82013-05-15 17:47:12 +0000132 pColl = sqlite3GetCollSeq(pParse, ENC(db), 0, p->u.zToken);
drhae80dde2012-12-06 21:16:43 +0000133 break;
134 }
drha58d4a92015-01-27 13:17:05 +0000135 if( (op==TK_AGG_COLUMN || op==TK_COLUMN
drhae80dde2012-12-06 21:16:43 +0000136 || op==TK_REGISTER || op==TK_TRIGGER)
drha58d4a92015-01-27 13:17:05 +0000137 && p->pTab!=0
drhae80dde2012-12-06 21:16:43 +0000138 ){
drh7d10d5a2008-08-20 16:35:10 +0000139 /* op==TK_REGISTER && p->pTab!=0 happens when pExpr was originally
140 ** a TK_COLUMN but was previously evaluated and cached in a register */
drh7d10d5a2008-08-20 16:35:10 +0000141 int j = p->iColumn;
142 if( j>=0 ){
drhae80dde2012-12-06 21:16:43 +0000143 const char *zColl = p->pTab->aCol[j].zColl;
drhc4a64fa2009-05-11 20:53:28 +0000144 pColl = sqlite3FindCollSeq(db, ENC(db), zColl, 0);
drh7d10d5a2008-08-20 16:35:10 +0000145 }
146 break;
danielk19770202b292004-06-09 09:55:16 +0000147 }
drhae80dde2012-12-06 21:16:43 +0000148 if( p->flags & EP_Collate ){
drh2308ed32015-02-09 16:09:34 +0000149 if( p->pLeft && (p->pLeft->flags & EP_Collate)!=0 ){
drhae80dde2012-12-06 21:16:43 +0000150 p = p->pLeft;
151 }else{
drh2308ed32015-02-09 16:09:34 +0000152 Expr *pNext = p->pRight;
drh6728cd92015-02-09 18:28:03 +0000153 /* The Expr.x union is never used at the same time as Expr.pRight */
154 assert( p->x.pList==0 || p->pRight==0 );
155 /* p->flags holds EP_Collate and p->pLeft->flags does not. And
156 ** p->x.pSelect cannot. So if p->x.pLeft exists, it must hold at
157 ** least one EP_Collate. Thus the following two ALWAYS. */
158 if( p->x.pList!=0 && ALWAYS(!ExprHasProperty(p, EP_xIsSelect)) ){
drh2308ed32015-02-09 16:09:34 +0000159 int i;
drh6728cd92015-02-09 18:28:03 +0000160 for(i=0; ALWAYS(i<p->x.pList->nExpr); i++){
drh2308ed32015-02-09 16:09:34 +0000161 if( ExprHasProperty(p->x.pList->a[i].pExpr, EP_Collate) ){
162 pNext = p->x.pList->a[i].pExpr;
163 break;
164 }
165 }
166 }
167 p = pNext;
drhae80dde2012-12-06 21:16:43 +0000168 }
169 }else{
drh7d10d5a2008-08-20 16:35:10 +0000170 break;
171 }
danielk19770202b292004-06-09 09:55:16 +0000172 }
danielk19777cedc8d2004-06-10 10:50:08 +0000173 if( sqlite3CheckCollSeq(pParse, pColl) ){
174 pColl = 0;
175 }
176 return pColl;
danielk19770202b292004-06-09 09:55:16 +0000177}
178
179/*
drh626a8792005-01-17 22:08:19 +0000180** pExpr is an operand of a comparison operator. aff2 is the
181** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +0000182** type affinity that should be used for the comparison operator.
183*/
danielk1977e014a832004-05-17 10:48:57 +0000184char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +0000185 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +0000186 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +0000187 /* Both sides of the comparison are columns. If one has numeric
188 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +0000189 */
drh8a512562005-11-14 22:29:05 +0000190 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +0000191 return SQLITE_AFF_NUMERIC;
192 }else{
drh05883a32015-06-02 15:32:08 +0000193 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000194 }
195 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +0000196 /* Neither side of the comparison is a column. Compare the
197 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +0000198 */
drh05883a32015-06-02 15:32:08 +0000199 return SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000200 }else{
201 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +0000202 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +0000203 return (aff1 + aff2);
204 }
205}
206
drh53db1452004-05-20 13:54:53 +0000207/*
208** pExpr is a comparison operator. Return the type affinity that should
209** be applied to both operands prior to doing the comparison.
210*/
danielk1977e014a832004-05-17 10:48:57 +0000211static char comparisonAffinity(Expr *pExpr){
212 char aff;
213 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
214 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
drh6a2fe092009-09-23 02:29:36 +0000215 pExpr->op==TK_NE || pExpr->op==TK_IS || pExpr->op==TK_ISNOT );
danielk1977e014a832004-05-17 10:48:57 +0000216 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000217 aff = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +0000218 if( pExpr->pRight ){
219 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
danielk19776ab3a2e2009-02-19 14:39:25 +0000220 }else if( ExprHasProperty(pExpr, EP_xIsSelect) ){
221 aff = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[0].pExpr, aff);
222 }else if( !aff ){
drh05883a32015-06-02 15:32:08 +0000223 aff = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +0000224 }
225 return aff;
226}
227
228/*
229** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
230** idx_affinity is the affinity of an indexed column. Return true
231** if the index with affinity idx_affinity may be used to implement
232** the comparison in pExpr.
233*/
234int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
235 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000236 switch( aff ){
drh05883a32015-06-02 15:32:08 +0000237 case SQLITE_AFF_BLOB:
drh8a512562005-11-14 22:29:05 +0000238 return 1;
239 case SQLITE_AFF_TEXT:
240 return idx_affinity==SQLITE_AFF_TEXT;
241 default:
242 return sqlite3IsNumericAffinity(idx_affinity);
243 }
danielk1977e014a832004-05-17 10:48:57 +0000244}
245
danielk1977a37cdde2004-05-16 11:15:36 +0000246/*
drh35573352008-01-08 23:54:25 +0000247** Return the P5 value that should be used for a binary comparison
danielk1977a37cdde2004-05-16 11:15:36 +0000248** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
danielk1977a37cdde2004-05-16 11:15:36 +0000249*/
drh35573352008-01-08 23:54:25 +0000250static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
251 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
drh1bd10f82008-12-10 21:19:56 +0000252 aff = (u8)sqlite3CompareAffinity(pExpr1, aff) | (u8)jumpIfNull;
drh35573352008-01-08 23:54:25 +0000253 return aff;
danielk1977a37cdde2004-05-16 11:15:36 +0000254}
255
drha2e00042002-01-22 03:13:42 +0000256/*
danielk19770202b292004-06-09 09:55:16 +0000257** Return a pointer to the collation sequence that should be used by
258** a binary comparison operator comparing pLeft and pRight.
259**
260** If the left hand expression has a collating sequence type, then it is
261** used. Otherwise the collation sequence for the right hand expression
262** is used, or the default (BINARY) if neither expression has a collating
263** type.
danielk1977bcbb04e2007-05-29 12:11:29 +0000264**
265** Argument pRight (but not pLeft) may be a null pointer. In this case,
266** it is not considered.
danielk19770202b292004-06-09 09:55:16 +0000267*/
drh0a0e1312007-08-07 17:04:59 +0000268CollSeq *sqlite3BinaryCompareCollSeq(
danielk1977bcbb04e2007-05-29 12:11:29 +0000269 Parse *pParse,
270 Expr *pLeft,
271 Expr *pRight
272){
drhec41dda2007-02-07 13:09:45 +0000273 CollSeq *pColl;
274 assert( pLeft );
drhae80dde2012-12-06 21:16:43 +0000275 if( pLeft->flags & EP_Collate ){
276 pColl = sqlite3ExprCollSeq(pParse, pLeft);
277 }else if( pRight && (pRight->flags & EP_Collate)!=0 ){
278 pColl = sqlite3ExprCollSeq(pParse, pRight);
drhec41dda2007-02-07 13:09:45 +0000279 }else{
280 pColl = sqlite3ExprCollSeq(pParse, pLeft);
281 if( !pColl ){
282 pColl = sqlite3ExprCollSeq(pParse, pRight);
283 }
danielk19770202b292004-06-09 09:55:16 +0000284 }
285 return pColl;
286}
287
288/*
drhbe5c89a2004-07-26 00:31:09 +0000289** Generate code for a comparison operator.
290*/
291static int codeCompare(
292 Parse *pParse, /* The parsing (and code generating) context */
293 Expr *pLeft, /* The left operand */
294 Expr *pRight, /* The right operand */
295 int opcode, /* The comparison opcode */
drh35573352008-01-08 23:54:25 +0000296 int in1, int in2, /* Register holding operands */
drhbe5c89a2004-07-26 00:31:09 +0000297 int dest, /* Jump here if true. */
298 int jumpIfNull /* If true, jump if either operand is NULL */
299){
drh35573352008-01-08 23:54:25 +0000300 int p5;
301 int addr;
302 CollSeq *p4;
303
304 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
305 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
306 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
307 (void*)p4, P4_COLLSEQ);
drh1bd10f82008-12-10 21:19:56 +0000308 sqlite3VdbeChangeP5(pParse->pVdbe, (u8)p5);
drh35573352008-01-08 23:54:25 +0000309 return addr;
drhbe5c89a2004-07-26 00:31:09 +0000310}
311
dancfbb5e82016-07-13 19:48:13 +0000312/*
313** If the expression passed as the only argument is of type TK_VECTOR
314** return the number of expressions in the vector. Or, if the expression
315** is a sub-select, return the number of columns in the sub-select. For
316** any other type of expression, return 1.
317*/
dan71c57db2016-07-09 20:23:55 +0000318int sqlite3ExprVectorSize(Expr *pExpr){
319 if( (pExpr->flags & EP_Vector)==0 ) return 1;
320 if( pExpr->flags & EP_xIsSelect ){
321 return pExpr->x.pSelect->pEList->nExpr;
322 }
323 return pExpr->x.pList->nExpr;
324}
325
danba00e302016-07-23 20:24:06 +0000326/*
327** If the expression passed as the first argument is a TK_VECTOR, return
328** a pointer to the i'th field of the vector. Or, if the first argument
329** points to a sub-select, return a pointer to the i'th returned column
330** value. Otherwise, return a copy of the first argument.
331*/
dan71c57db2016-07-09 20:23:55 +0000332static Expr *exprVectorField(Expr *pVector, int i){
dancfbb5e82016-07-13 19:48:13 +0000333 if( (pVector->flags & EP_Vector)==0 ){
334 assert( i==0 );
335 return pVector;
336 }else if( pVector->flags & EP_xIsSelect ){
dan71c57db2016-07-09 20:23:55 +0000337 return pVector->x.pSelect->pEList->a[i].pExpr;
338 }
339 return pVector->x.pList->a[i].pExpr;
340}
341
dan8da209b2016-07-26 18:06:08 +0000342static int exprVectorSubselect(Parse *pParse, Expr *pExpr){
343 int reg = 0;
344 if( pExpr->flags & EP_xIsSelect ){
345 assert( pExpr->op==TK_REGISTER || pExpr->op==TK_SELECT );
346 if( pExpr->op==TK_REGISTER ){
347 reg = pExpr->iTable;
348 }else{
349 reg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
350 }
351 }
352 return reg;
353}
354
dan71c57db2016-07-09 20:23:55 +0000355static void codeVectorCompare(Parse *pParse, Expr *pExpr, int dest){
356 Vdbe *v = pParse->pVdbe;
357 Expr *pLeft = pExpr->pLeft;
358 Expr *pRight = pExpr->pRight;
359 int nLeft = sqlite3ExprVectorSize(pLeft);
360 int nRight = sqlite3ExprVectorSize(pRight);
361 int addr = sqlite3VdbeMakeLabel(v);
362
363 /* Check that both sides of the comparison are vectors, and that
364 ** both are the same length. */
365 if( nLeft!=nRight ){
366 sqlite3ErrorMsg(pParse, "invalid use of row value");
367 }else{
368 int p5 = (pExpr->op==TK_IS || pExpr->op==TK_ISNOT) ? SQLITE_NULLEQ : 0;
369 int opCmp;
370 int opTest;
371 int i;
372 int p3 = 1;
373 int regLeft = 0;
374 int regRight = 0;
375
376 assert( pExpr->op==TK_EQ || pExpr->op==TK_NE
377 || pExpr->op==TK_IS || pExpr->op==TK_ISNOT
378 || pExpr->op==TK_LT || pExpr->op==TK_GT
379 || pExpr->op==TK_LE || pExpr->op==TK_GE
380 );
381
382 switch( pExpr->op ){
383 case TK_EQ:
384 case TK_IS:
385 opTest = OP_IfNot;
386 opCmp = OP_Eq;
387 break;
388
389 case TK_NE:
390 case TK_ISNOT:
391 opTest = OP_If;
392 opCmp = OP_Ne;
393 break;
394
395 case TK_LT:
396 case TK_LE:
397 case TK_GT:
398 case TK_GE:
399 opCmp = OP_Cmp;
400 opTest = OP_CmpTest;
401 p3 = pExpr->op;
402 break;
403 }
404
dan8da209b2016-07-26 18:06:08 +0000405 regLeft = exprVectorSubselect(pParse, pLeft);
406 regRight = exprVectorSubselect(pParse, pRight);
dan71c57db2016-07-09 20:23:55 +0000407 if( pParse->nErr ) return;
408
409 for(i=0; i<nLeft; i++){
410 int regFree1 = 0, regFree2 = 0;
411 Expr *pL, *pR;
412 int r1, r2;
413
dan19ff12d2016-07-29 20:58:19 +0000414 if( i ) sqlite3ExprCachePush(pParse);
dan71c57db2016-07-09 20:23:55 +0000415 if( regLeft ){
416 pL = pLeft->x.pSelect->pEList->a[i].pExpr;
417 r1 = regLeft+i;
418 }else{
419 pL = pLeft->x.pList->a[i].pExpr;
420 r1 = sqlite3ExprCodeTemp(pParse, pL, &regFree1);
421 }
422
423 if( regRight ){
424 pR = pRight->x.pSelect->pEList->a[i].pExpr;
425 r2 = regRight+i;
426 }else{
427 pR = pRight->x.pList->a[i].pExpr;
428 r2 = sqlite3ExprCodeTemp(pParse, pR, &regFree1);
429 }
430
431 codeCompare(pParse, pL, pR, opCmp, r1, r2, dest, SQLITE_STOREP2 | p5);
432 sqlite3VdbeAddOp3(v, opTest, dest, addr, p3);
433 sqlite3ReleaseTempReg(pParse, regFree1);
434 sqlite3ReleaseTempReg(pParse, regFree2);
dan19ff12d2016-07-29 20:58:19 +0000435 if( i ) sqlite3ExprCachePop(pParse);
dan71c57db2016-07-09 20:23:55 +0000436 }
437 }
438
439 sqlite3VdbeResolveLabel(v, addr);
440}
441
danielk19774b5255a2008-06-05 16:47:39 +0000442#if SQLITE_MAX_EXPR_DEPTH>0
443/*
444** Check that argument nHeight is less than or equal to the maximum
445** expression depth allowed. If it is not, leave an error message in
446** pParse.
447*/
drh7d10d5a2008-08-20 16:35:10 +0000448int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000449 int rc = SQLITE_OK;
450 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
451 if( nHeight>mxHeight ){
452 sqlite3ErrorMsg(pParse,
453 "Expression tree is too large (maximum depth %d)", mxHeight
454 );
455 rc = SQLITE_ERROR;
456 }
457 return rc;
458}
459
460/* The following three functions, heightOfExpr(), heightOfExprList()
461** and heightOfSelect(), are used to determine the maximum height
462** of any expression tree referenced by the structure passed as the
463** first argument.
464**
465** If this maximum height is greater than the current value pointed
466** to by pnHeight, the second parameter, then set *pnHeight to that
467** value.
468*/
469static void heightOfExpr(Expr *p, int *pnHeight){
470 if( p ){
471 if( p->nHeight>*pnHeight ){
472 *pnHeight = p->nHeight;
473 }
474 }
475}
476static void heightOfExprList(ExprList *p, int *pnHeight){
477 if( p ){
478 int i;
479 for(i=0; i<p->nExpr; i++){
480 heightOfExpr(p->a[i].pExpr, pnHeight);
481 }
482 }
483}
484static void heightOfSelect(Select *p, int *pnHeight){
485 if( p ){
486 heightOfExpr(p->pWhere, pnHeight);
487 heightOfExpr(p->pHaving, pnHeight);
488 heightOfExpr(p->pLimit, pnHeight);
489 heightOfExpr(p->pOffset, pnHeight);
490 heightOfExprList(p->pEList, pnHeight);
491 heightOfExprList(p->pGroupBy, pnHeight);
492 heightOfExprList(p->pOrderBy, pnHeight);
493 heightOfSelect(p->pPrior, pnHeight);
494 }
495}
496
497/*
498** Set the Expr.nHeight variable in the structure passed as an
499** argument. An expression with no children, Expr.pList or
500** Expr.pSelect member has a height of 1. Any other expression
501** has a height equal to the maximum height of any other
502** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000503**
504** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
505** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000506*/
507static void exprSetHeight(Expr *p){
508 int nHeight = 0;
509 heightOfExpr(p->pLeft, &nHeight);
510 heightOfExpr(p->pRight, &nHeight);
danielk19776ab3a2e2009-02-19 14:39:25 +0000511 if( ExprHasProperty(p, EP_xIsSelect) ){
512 heightOfSelect(p->x.pSelect, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000513 }else if( p->x.pList ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000514 heightOfExprList(p->x.pList, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000515 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
danielk19776ab3a2e2009-02-19 14:39:25 +0000516 }
danielk19774b5255a2008-06-05 16:47:39 +0000517 p->nHeight = nHeight + 1;
518}
519
520/*
521** Set the Expr.nHeight variable using the exprSetHeight() function. If
522** the height is greater than the maximum allowed expression depth,
523** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000524**
525** Also propagate all EP_Propagate flags from the Expr.x.pList into
526** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000527*/
drh2308ed32015-02-09 16:09:34 +0000528void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh74893a42015-03-22 10:23:17 +0000529 if( pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000530 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000531 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000532}
533
534/*
535** Return the maximum height of any expression tree referenced
536** by the select statement passed as an argument.
537*/
538int sqlite3SelectExprHeight(Select *p){
539 int nHeight = 0;
540 heightOfSelect(p, &nHeight);
541 return nHeight;
542}
drh2308ed32015-02-09 16:09:34 +0000543#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
544/*
545** Propagate all EP_Propagate flags from the Expr.x.pList into
546** Expr.flags.
547*/
548void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
549 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
550 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
551 }
552}
553#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000554#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
555
drhbe5c89a2004-07-26 00:31:09 +0000556/*
drhb7916a72009-05-27 10:31:29 +0000557** This routine is the core allocator for Expr nodes.
558**
drha76b5df2002-02-23 02:32:10 +0000559** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000560** for this node and for the pToken argument is a single allocation
561** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000562** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000563**
564** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000565** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000566** parameter is ignored if pToken is NULL or if the token does not
567** appear to be quoted. If the quotes were of the form "..." (double-quotes)
568** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000569**
570** Special case: If op==TK_INTEGER and pToken points to a string that
571** can be translated into a 32-bit integer, then the token is not
572** stored in u.zToken. Instead, the integer values is written
573** into u.iValue and the EP_IntValue flag is set. No extra storage
574** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000575*/
drhb7916a72009-05-27 10:31:29 +0000576Expr *sqlite3ExprAlloc(
danielk1977a1644fd2007-08-29 12:31:25 +0000577 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
drh17435752007-08-16 04:30:38 +0000578 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000579 const Token *pToken, /* Token argument. Might be NULL */
580 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000581){
drha76b5df2002-02-23 02:32:10 +0000582 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000583 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000584 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000585
drh575fad62016-02-05 13:38:36 +0000586 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000587 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000588 if( op!=TK_INTEGER || pToken->z==0
589 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
590 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000591 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000592 }
drhb7916a72009-05-27 10:31:29 +0000593 }
drh575fad62016-02-05 13:38:36 +0000594 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000595 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000596 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000597 pNew->op = (u8)op;
598 pNew->iAgg = -1;
599 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000600 if( nExtra==0 ){
601 pNew->flags |= EP_IntValue;
602 pNew->u.iValue = iValue;
603 }else{
drh33e619f2009-05-28 01:00:55 +0000604 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000605 assert( pToken->z!=0 || pToken->n==0 );
606 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000607 pNew->u.zToken[pToken->n] = 0;
drh244b9d62016-04-11 19:01:08 +0000608 if( dequote && sqlite3Isquote(pNew->u.zToken[0]) ){
609 if( pNew->u.zToken[0]=='"' ) pNew->flags |= EP_DblQuoted;
drh33e619f2009-05-28 01:00:55 +0000610 sqlite3Dequote(pNew->u.zToken);
drh33e619f2009-05-28 01:00:55 +0000611 }
drhb7916a72009-05-27 10:31:29 +0000612 }
613 }
614#if SQLITE_MAX_EXPR_DEPTH>0
615 pNew->nHeight = 1;
616#endif
617 }
drha76b5df2002-02-23 02:32:10 +0000618 return pNew;
619}
620
621/*
drhb7916a72009-05-27 10:31:29 +0000622** Allocate a new expression node from a zero-terminated token that has
623** already been dequoted.
624*/
625Expr *sqlite3Expr(
626 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
627 int op, /* Expression opcode */
628 const char *zToken /* Token argument. Might be NULL */
629){
630 Token x;
631 x.z = zToken;
632 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
633 return sqlite3ExprAlloc(db, op, &x, 0);
634}
635
636/*
637** Attach subtrees pLeft and pRight to the Expr node pRoot.
638**
639** If pRoot==NULL that means that a memory allocation error has occurred.
640** In that case, delete the subtrees pLeft and pRight.
641*/
642void sqlite3ExprAttachSubtrees(
643 sqlite3 *db,
644 Expr *pRoot,
645 Expr *pLeft,
646 Expr *pRight
647){
648 if( pRoot==0 ){
649 assert( db->mallocFailed );
650 sqlite3ExprDelete(db, pLeft);
651 sqlite3ExprDelete(db, pRight);
652 }else{
653 if( pRight ){
654 pRoot->pRight = pRight;
drh885a5b02015-02-09 15:21:36 +0000655 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000656 }
657 if( pLeft ){
658 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000659 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000660 }
661 exprSetHeight(pRoot);
662 }
663}
664
665/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000666** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000667**
drhbf664462009-06-19 18:32:54 +0000668** One or both of the subtrees can be NULL. Return a pointer to the new
669** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
670** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000671*/
drh17435752007-08-16 04:30:38 +0000672Expr *sqlite3PExpr(
673 Parse *pParse, /* Parsing context */
674 int op, /* Expression opcode */
675 Expr *pLeft, /* Left operand */
676 Expr *pRight, /* Right operand */
677 const Token *pToken /* Argument token */
678){
drh5fb52ca2012-03-31 02:34:35 +0000679 Expr *p;
drh1167d322015-10-28 20:01:45 +0000680 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000681 /* Take advantage of short-circuit false optimization for AND */
682 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
683 }else{
drh1167d322015-10-28 20:01:45 +0000684 p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
drh5fb52ca2012-03-31 02:34:35 +0000685 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
686 }
dan2b359bd2010-10-28 11:31:23 +0000687 if( p ) {
688 sqlite3ExprCheckHeight(pParse, p->nHeight);
689 }
drh4e0cff62004-11-05 05:10:28 +0000690 return p;
691}
692
693/*
drh08de4f72016-04-11 01:06:47 +0000694** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
695** do a memory allocation failure) then delete the pSelect object.
696*/
697void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
698 if( pExpr ){
699 pExpr->x.pSelect = pSelect;
700 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
701 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
702 }else{
703 assert( pParse->db->mallocFailed );
704 sqlite3SelectDelete(pParse->db, pSelect);
705 }
706}
707
708
709/*
drh991a1982014-01-02 17:57:16 +0000710** If the expression is always either TRUE or FALSE (respectively),
711** then return 1. If one cannot determine the truth value of the
712** expression at compile-time return 0.
713**
714** This is an optimization. If is OK to return 0 here even if
715** the expression really is always false or false (a false negative).
716** But it is a bug to return 1 if the expression might have different
717** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000718**
719** Note that if the expression is part of conditional for a
720** LEFT JOIN, then we cannot determine at compile-time whether or not
721** is it true or false, so always return 0.
722*/
drh991a1982014-01-02 17:57:16 +0000723static int exprAlwaysTrue(Expr *p){
724 int v = 0;
725 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
726 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
727 return v!=0;
728}
drh5fb52ca2012-03-31 02:34:35 +0000729static int exprAlwaysFalse(Expr *p){
730 int v = 0;
731 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
732 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
733 return v==0;
734}
735
736/*
drh91bb0ee2004-09-01 03:06:34 +0000737** Join two expressions using an AND operator. If either expression is
738** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000739**
740** If one side or the other of the AND is known to be false, then instead
741** of returning an AND expression, just return a constant expression with
742** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000743*/
danielk19771e536952007-08-16 10:09:01 +0000744Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000745 if( pLeft==0 ){
746 return pRight;
747 }else if( pRight==0 ){
748 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000749 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
750 sqlite3ExprDelete(db, pLeft);
751 sqlite3ExprDelete(db, pRight);
752 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000753 }else{
drhb7916a72009-05-27 10:31:29 +0000754 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
755 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
756 return pNew;
drha76b5df2002-02-23 02:32:10 +0000757 }
758}
759
760/*
761** Construct a new expression node for a function with multiple
762** arguments.
763*/
drh17435752007-08-16 04:30:38 +0000764Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000765 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000766 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000767 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000768 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000769 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000770 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000771 return 0;
772 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000773 pNew->x.pList = pList;
774 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
drh2308ed32015-02-09 16:09:34 +0000775 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drha76b5df2002-02-23 02:32:10 +0000776 return pNew;
777}
778
779/*
drhfa6bc002004-09-07 16:19:52 +0000780** Assign a variable number to an expression that encodes a wildcard
781** in the original SQL statement.
782**
783** Wildcards consisting of a single "?" are assigned the next sequential
784** variable number.
785**
786** Wildcards of the form "?nnn" are assigned the number "nnn". We make
787** sure "nnn" is not too be to avoid a denial of service attack when
788** the SQL statement comes from an external source.
789**
drh51f49f12009-05-21 20:41:32 +0000790** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +0000791** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +0000792** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +0000793** assigned.
794*/
795void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
drh17435752007-08-16 04:30:38 +0000796 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +0000797 const char *z;
drh17435752007-08-16 04:30:38 +0000798
drhfa6bc002004-09-07 16:19:52 +0000799 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +0000800 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +0000801 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000802 assert( z!=0 );
803 assert( z[0]!=0 );
804 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +0000805 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +0000806 assert( z[0]=='?' );
drh8677d302009-11-04 13:17:14 +0000807 pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000808 }else{
drh124c0b42011-06-01 18:15:55 +0000809 ynVar x = 0;
810 u32 n = sqlite3Strlen30(z);
811 if( z[0]=='?' ){
812 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
813 ** use it as the variable number */
814 i64 i;
815 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
816 pExpr->iColumn = x = (ynVar)i;
817 testcase( i==0 );
818 testcase( i==1 );
819 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
820 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
821 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
822 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
823 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
824 x = 0;
drhfa6bc002004-09-07 16:19:52 +0000825 }
drh124c0b42011-06-01 18:15:55 +0000826 if( i>pParse->nVar ){
827 pParse->nVar = (int)i;
828 }
829 }else{
830 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
831 ** number as the prior appearance of the same name, or if the name
832 ** has never appeared before, reuse the same variable number
833 */
834 ynVar i;
835 for(i=0; i<pParse->nzVar; i++){
drh503a6862013-03-01 01:07:17 +0000836 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
drh124c0b42011-06-01 18:15:55 +0000837 pExpr->iColumn = x = (ynVar)i+1;
838 break;
839 }
840 }
841 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000842 }
drh124c0b42011-06-01 18:15:55 +0000843 if( x>0 ){
844 if( x>pParse->nzVar ){
845 char **a;
846 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
drh4a642b62016-02-05 01:55:27 +0000847 if( a==0 ){
848 assert( db->mallocFailed ); /* Error reported through mallocFailed */
849 return;
850 }
drh124c0b42011-06-01 18:15:55 +0000851 pParse->azVar = a;
852 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
853 pParse->nzVar = x;
drhfa6bc002004-09-07 16:19:52 +0000854 }
drh124c0b42011-06-01 18:15:55 +0000855 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
856 sqlite3DbFree(db, pParse->azVar[x-1]);
857 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
drhfa6bc002004-09-07 16:19:52 +0000858 }
859 }
860 }
drhbb4957f2008-03-20 14:03:29 +0000861 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +0000862 sqlite3ErrorMsg(pParse, "too many SQL variables");
863 }
drhfa6bc002004-09-07 16:19:52 +0000864}
865
866/*
danf6963f92009-11-23 14:39:14 +0000867** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +0000868*/
drh4f0010b2016-04-11 14:49:39 +0000869static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
870 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +0000871 /* Sanity check: Assert that the IntValue is non-negative if it exists */
872 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drhc5cd1242013-09-12 16:50:49 +0000873 if( !ExprHasProperty(p, EP_TokenOnly) ){
874 /* The Expr.x union is never used at the same time as Expr.pRight */
875 assert( p->x.pList==0 || p->pRight==0 );
dan71c57db2016-07-09 20:23:55 +0000876 if( p->op!=TK_SELECT_COLUMN ) sqlite3ExprDelete(db, p->pLeft);
drh33e619f2009-05-28 01:00:55 +0000877 sqlite3ExprDelete(db, p->pRight);
drhc5cd1242013-09-12 16:50:49 +0000878 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
danielk19776ab3a2e2009-02-19 14:39:25 +0000879 if( ExprHasProperty(p, EP_xIsSelect) ){
880 sqlite3SelectDelete(db, p->x.pSelect);
881 }else{
882 sqlite3ExprListDelete(db, p->x.pList);
883 }
884 }
drh33e619f2009-05-28 01:00:55 +0000885 if( !ExprHasProperty(p, EP_Static) ){
886 sqlite3DbFree(db, p);
887 }
drha2e00042002-01-22 03:13:42 +0000888}
drh4f0010b2016-04-11 14:49:39 +0000889void sqlite3ExprDelete(sqlite3 *db, Expr *p){
890 if( p ) sqlite3ExprDeleteNN(db, p);
891}
drha2e00042002-01-22 03:13:42 +0000892
drhd2687b72005-08-12 22:56:09 +0000893/*
danielk19776ab3a2e2009-02-19 14:39:25 +0000894** Return the number of bytes allocated for the expression structure
895** passed as the first argument. This is always one of EXPR_FULLSIZE,
896** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
897*/
898static int exprStructSize(Expr *p){
899 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +0000900 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
901 return EXPR_FULLSIZE;
902}
903
904/*
drh33e619f2009-05-28 01:00:55 +0000905** The dupedExpr*Size() routines each return the number of bytes required
906** to store a copy of an expression or expression tree. They differ in
907** how much of the tree is measured.
908**
909** dupedExprStructSize() Size of only the Expr structure
910** dupedExprNodeSize() Size of Expr + space for token
911** dupedExprSize() Expr + token + subtree components
912**
913***************************************************************************
914**
915** The dupedExprStructSize() function returns two values OR-ed together:
916** (1) the space required for a copy of the Expr structure only and
917** (2) the EP_xxx flags that indicate what the structure size should be.
918** The return values is always one of:
919**
920** EXPR_FULLSIZE
921** EXPR_REDUCEDSIZE | EP_Reduced
922** EXPR_TOKENONLYSIZE | EP_TokenOnly
923**
924** The size of the structure can be found by masking the return value
925** of this routine with 0xfff. The flags can be found by masking the
926** return value with EP_Reduced|EP_TokenOnly.
927**
928** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
929** (unreduced) Expr objects as they or originally constructed by the parser.
930** During expression analysis, extra information is computed and moved into
931** later parts of teh Expr object and that extra information might get chopped
932** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +0000933** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +0000934** to reduce a pristine expression tree from the parser. The implementation
935** of dupedExprStructSize() contain multiple assert() statements that attempt
936** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +0000937*/
938static int dupedExprStructSize(Expr *p, int flags){
939 int nSize;
drh33e619f2009-05-28 01:00:55 +0000940 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +0000941 assert( EXPR_FULLSIZE<=0xfff );
942 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
drh3c194692016-04-11 16:43:43 +0000943 if( 0==flags ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000944 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +0000945 }else{
drhc5cd1242013-09-12 16:50:49 +0000946 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +0000947 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +0000948 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +0000949 assert( !ExprHasProperty(p, EP_NoReduce) );
drhaecd8022013-09-13 18:15:15 +0000950 if( p->pLeft || p->x.pList ){
drh33e619f2009-05-28 01:00:55 +0000951 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
952 }else{
drhaecd8022013-09-13 18:15:15 +0000953 assert( p->pRight==0 );
drh33e619f2009-05-28 01:00:55 +0000954 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
955 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000956 }
957 return nSize;
958}
959
960/*
drh33e619f2009-05-28 01:00:55 +0000961** This function returns the space in bytes required to store the copy
962** of the Expr structure and a copy of the Expr.u.zToken string (if that
963** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +0000964*/
965static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +0000966 int nByte = dupedExprStructSize(p, flags) & 0xfff;
967 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
968 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +0000969 }
danielk1977bc739712009-03-23 04:33:32 +0000970 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +0000971}
972
973/*
974** Return the number of bytes required to create a duplicate of the
975** expression passed as the first argument. The second argument is a
976** mask containing EXPRDUP_XXX flags.
977**
978** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +0000979** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +0000980**
981** If the EXPRDUP_REDUCE flag is set, then the return value includes
982** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
983** and Expr.pRight variables (but not for any structures pointed to or
984** descended from the Expr.x.pList or Expr.x.pSelect variables).
985*/
986static int dupedExprSize(Expr *p, int flags){
987 int nByte = 0;
988 if( p ){
989 nByte = dupedExprNodeSize(p, flags);
990 if( flags&EXPRDUP_REDUCE ){
drhb7916a72009-05-27 10:31:29 +0000991 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +0000992 }
993 }
994 return nByte;
995}
996
997/*
998** This function is similar to sqlite3ExprDup(), except that if pzBuffer
999** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +00001000** to store the copy of expression p, the copies of p->u.zToken
danielk19776ab3a2e2009-02-19 14:39:25 +00001001** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +00001002** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +00001003** portion of the buffer copied into by this function.
1004*/
drh3c194692016-04-11 16:43:43 +00001005static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
1006 Expr *pNew; /* Value to return */
1007 u8 *zAlloc; /* Memory space from which to build Expr object */
1008 u32 staticFlag; /* EP_Static if space not obtained from malloc */
1009
drh575fad62016-02-05 13:38:36 +00001010 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +00001011 assert( p );
1012 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
1013 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +00001014
drh3c194692016-04-11 16:43:43 +00001015 /* Figure out where to write the new Expr structure. */
1016 if( pzBuffer ){
1017 zAlloc = *pzBuffer;
1018 staticFlag = EP_Static;
1019 }else{
1020 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
1021 staticFlag = 0;
1022 }
1023 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001024
drh3c194692016-04-11 16:43:43 +00001025 if( pNew ){
1026 /* Set nNewSize to the size allocated for the structure pointed to
1027 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
1028 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
1029 ** by the copy of the p->u.zToken string (if any).
1030 */
1031 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
1032 const int nNewSize = nStructSize & 0xfff;
1033 int nToken;
1034 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
1035 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +00001036 }else{
drh3c194692016-04-11 16:43:43 +00001037 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001038 }
drh3c194692016-04-11 16:43:43 +00001039 if( dupFlags ){
1040 assert( ExprHasProperty(p, EP_Reduced)==0 );
1041 memcpy(zAlloc, p, nNewSize);
1042 }else{
1043 u32 nSize = (u32)exprStructSize(p);
1044 memcpy(zAlloc, p, nSize);
1045 if( nSize<EXPR_FULLSIZE ){
1046 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
1047 }
1048 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001049
drh3c194692016-04-11 16:43:43 +00001050 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
1051 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
1052 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
1053 pNew->flags |= staticFlag;
1054
1055 /* Copy the p->u.zToken string, if any. */
1056 if( nToken ){
1057 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
1058 memcpy(zToken, p->u.zToken, nToken);
1059 }
1060
1061 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
1062 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
1063 if( ExprHasProperty(p, EP_xIsSelect) ){
1064 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001065 }else{
drh3c194692016-04-11 16:43:43 +00001066 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
drh33e619f2009-05-28 01:00:55 +00001067 }
drh3c194692016-04-11 16:43:43 +00001068 }
1069
1070 /* Fill in pNew->pLeft and pNew->pRight. */
1071 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
1072 zAlloc += dupedExprNodeSize(p, dupFlags);
1073 if( ExprHasProperty(pNew, EP_Reduced) ){
1074 pNew->pLeft = p->pLeft ?
1075 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
1076 pNew->pRight = p->pRight ?
1077 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001078 }
drh3c194692016-04-11 16:43:43 +00001079 if( pzBuffer ){
1080 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +00001081 }
drh3c194692016-04-11 16:43:43 +00001082 }else{
1083 if( !ExprHasProperty(p, EP_TokenOnly) ){
1084 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
1085 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
danielk19776ab3a2e2009-02-19 14:39:25 +00001086 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001087 }
1088 }
1089 return pNew;
1090}
1091
1092/*
danbfe31e72014-01-15 14:17:31 +00001093** Create and return a deep copy of the object passed as the second
1094** argument. If an OOM condition is encountered, NULL is returned
1095** and the db->mallocFailed flag set.
1096*/
daneede6a52014-01-15 19:42:23 +00001097#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +00001098static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +00001099 With *pRet = 0;
1100 if( p ){
1101 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
1102 pRet = sqlite3DbMallocZero(db, nByte);
1103 if( pRet ){
1104 int i;
1105 pRet->nCte = p->nCte;
1106 for(i=0; i<p->nCte; i++){
1107 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
1108 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
1109 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
1110 }
1111 }
1112 }
1113 return pRet;
1114}
daneede6a52014-01-15 19:42:23 +00001115#else
1116# define withDup(x,y) 0
1117#endif
dan4e9119d2014-01-13 15:12:23 +00001118
drha76b5df2002-02-23 02:32:10 +00001119/*
drhff78bd22002-02-27 01:47:11 +00001120** The following group of routines make deep copies of expressions,
1121** expression lists, ID lists, and select statements. The copies can
1122** be deleted (by being passed to their respective ...Delete() routines)
1123** without effecting the originals.
1124**
danielk19774adee202004-05-08 08:23:19 +00001125** The expression list, ID, and source lists return by sqlite3ExprListDup(),
1126** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +00001127** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001128**
drhad3cab52002-05-24 02:04:32 +00001129** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001130**
drhb7916a72009-05-27 10:31:29 +00001131** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001132** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1133** truncated version of the usual Expr structure that will be stored as
1134** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001135*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001136Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001137 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001138 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001139}
danielk19776ab3a2e2009-02-19 14:39:25 +00001140ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001141 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001142 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001143 int i;
drh575fad62016-02-05 13:38:36 +00001144 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001145 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001146 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001147 if( pNew==0 ) return 0;
drhd872bb12012-02-02 01:58:08 +00001148 pNew->nExpr = i = p->nExpr;
1149 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
drh575fad62016-02-05 13:38:36 +00001150 pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +00001151 if( pItem==0 ){
drh633e6d52008-07-28 19:34:53 +00001152 sqlite3DbFree(db, pNew);
danielk1977e0048402004-06-15 16:51:01 +00001153 return 0;
1154 }
drh145716b2004-09-24 12:24:06 +00001155 pOldItem = p->a;
1156 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001157 Expr *pOldExpr = pOldItem->pExpr;
drhb5526ea2009-07-16 12:41:05 +00001158 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh17435752007-08-16 04:30:38 +00001159 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001160 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001161 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001162 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001163 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
drhc2acc4e2013-11-15 18:15:19 +00001164 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001165 }
1166 return pNew;
1167}
danielk197793758c82005-01-21 08:13:14 +00001168
1169/*
1170** If cursors, triggers, views and subqueries are all omitted from
1171** the build, then none of the following routines, except for
1172** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1173** called with a NULL argument.
1174*/
danielk19776a67fe82005-02-04 04:07:16 +00001175#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1176 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001177SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001178 SrcList *pNew;
1179 int i;
drh113088e2003-03-20 01:16:58 +00001180 int nByte;
drh575fad62016-02-05 13:38:36 +00001181 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001182 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001183 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001184 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001185 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001186 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001187 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001188 struct SrcList_item *pNewItem = &pNew->a[i];
1189 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001190 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001191 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001192 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1193 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1194 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001195 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001196 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001197 pNewItem->addrFillSub = pOldItem->addrFillSub;
1198 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001199 if( pNewItem->fg.isIndexedBy ){
1200 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1201 }
1202 pNewItem->pIBIndex = pOldItem->pIBIndex;
1203 if( pNewItem->fg.isTabFunc ){
1204 pNewItem->u1.pFuncArg =
1205 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1206 }
drhed8a3bb2005-06-06 21:19:56 +00001207 pTab = pNewItem->pTab = pOldItem->pTab;
1208 if( pTab ){
1209 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001210 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001211 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1212 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001213 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001214 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001215 }
1216 return pNew;
1217}
drh17435752007-08-16 04:30:38 +00001218IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001219 IdList *pNew;
1220 int i;
drh575fad62016-02-05 13:38:36 +00001221 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001222 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001223 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001224 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001225 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001226 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001227 if( pNew->a==0 ){
drh633e6d52008-07-28 19:34:53 +00001228 sqlite3DbFree(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001229 return 0;
1230 }
drh6c535152012-02-02 03:38:30 +00001231 /* Note that because the size of the allocation for p->a[] is not
1232 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1233 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001234 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001235 struct IdList_item *pNewItem = &pNew->a[i];
1236 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001237 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001238 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001239 }
1240 return pNew;
1241}
danielk19776ab3a2e2009-02-19 14:39:25 +00001242Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
drh23b1b372011-12-07 01:55:51 +00001243 Select *pNew, *pPrior;
drh575fad62016-02-05 13:38:36 +00001244 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001245 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001246 pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +00001247 if( pNew==0 ) return 0;
drhb7916a72009-05-27 10:31:29 +00001248 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001249 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1250 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1251 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1252 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1253 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
drhff78bd22002-02-27 01:47:11 +00001254 pNew->op = p->op;
drh23b1b372011-12-07 01:55:51 +00001255 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
1256 if( pPrior ) pPrior->pNext = pNew;
1257 pNew->pNext = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001258 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1259 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
drh92b01d52008-06-24 00:32:35 +00001260 pNew->iLimit = 0;
1261 pNew->iOffset = 0;
drh7d10d5a2008-08-20 16:35:10 +00001262 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
drhb9bb7c12006-06-11 23:41:55 +00001263 pNew->addrOpenEphm[0] = -1;
1264 pNew->addrOpenEphm[1] = -1;
drhec2da852014-01-29 01:46:12 +00001265 pNew->nSelectRow = p->nSelectRow;
dan4e9119d2014-01-13 15:12:23 +00001266 pNew->pWith = withDup(db, p->pWith);
drheb9b8842014-09-21 00:27:26 +00001267 sqlite3SelectSetName(pNew, p->zSelName);
drhff78bd22002-02-27 01:47:11 +00001268 return pNew;
1269}
danielk197793758c82005-01-21 08:13:14 +00001270#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001271Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001272 assert( p==0 );
1273 return 0;
1274}
1275#endif
drhff78bd22002-02-27 01:47:11 +00001276
1277
1278/*
drha76b5df2002-02-23 02:32:10 +00001279** Add a new element to the end of an expression list. If pList is
1280** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001281**
1282** If a memory allocation error occurs, the entire list is freed and
1283** NULL is returned. If non-NULL is returned, then it is guaranteed
1284** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001285*/
drh17435752007-08-16 04:30:38 +00001286ExprList *sqlite3ExprListAppend(
1287 Parse *pParse, /* Parsing context */
1288 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001289 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001290){
1291 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001292 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001293 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001294 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001295 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001296 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001297 }
drhc263f7c2016-01-18 13:18:54 +00001298 pList->nExpr = 0;
drh575fad62016-02-05 13:38:36 +00001299 pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
drhd872bb12012-02-02 01:58:08 +00001300 if( pList->a==0 ) goto no_mem;
1301 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001302 struct ExprList_item *a;
drhd872bb12012-02-02 01:58:08 +00001303 assert( pList->nExpr>0 );
1304 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001305 if( a==0 ){
1306 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001307 }
danielk1977d5d56522005-03-16 12:15:20 +00001308 pList->a = a;
drha76b5df2002-02-23 02:32:10 +00001309 }
drh4efc4752004-01-16 15:55:37 +00001310 assert( pList->a!=0 );
drhb7916a72009-05-27 10:31:29 +00001311 if( 1 ){
drh4efc4752004-01-16 15:55:37 +00001312 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1313 memset(pItem, 0, sizeof(*pItem));
danielk1977e94ddc92005-03-21 03:53:38 +00001314 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001315 }
1316 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001317
1318no_mem:
1319 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001320 sqlite3ExprDelete(db, pExpr);
1321 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001322 return 0;
drha76b5df2002-02-23 02:32:10 +00001323}
1324
1325/*
drhbc622bc2015-08-24 15:39:42 +00001326** Set the sort order for the last element on the given ExprList.
1327*/
1328void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1329 if( p==0 ) return;
1330 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1331 assert( p->nExpr>0 );
1332 if( iSortOrder<0 ){
1333 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1334 return;
1335 }
1336 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001337}
1338
1339/*
drhb7916a72009-05-27 10:31:29 +00001340** Set the ExprList.a[].zName element of the most recently added item
1341** on the expression list.
1342**
1343** pList might be NULL following an OOM error. But pName should never be
1344** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1345** is set.
1346*/
1347void sqlite3ExprListSetName(
1348 Parse *pParse, /* Parsing context */
1349 ExprList *pList, /* List to which to add the span. */
1350 Token *pName, /* Name to be added */
1351 int dequote /* True to cause the name to be dequoted */
1352){
1353 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1354 if( pList ){
1355 struct ExprList_item *pItem;
1356 assert( pList->nExpr>0 );
1357 pItem = &pList->a[pList->nExpr-1];
1358 assert( pItem->zName==0 );
1359 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
drh244b9d62016-04-11 19:01:08 +00001360 if( dequote ) sqlite3Dequote(pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001361 }
1362}
1363
1364/*
1365** Set the ExprList.a[].zSpan element of the most recently added item
1366** on the expression list.
1367**
1368** pList might be NULL following an OOM error. But pSpan should never be
1369** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1370** is set.
1371*/
1372void sqlite3ExprListSetSpan(
1373 Parse *pParse, /* Parsing context */
1374 ExprList *pList, /* List to which to add the span. */
1375 ExprSpan *pSpan /* The span to be added */
1376){
1377 sqlite3 *db = pParse->db;
1378 assert( pList!=0 || db->mallocFailed!=0 );
1379 if( pList ){
1380 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1381 assert( pList->nExpr>0 );
1382 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1383 sqlite3DbFree(db, pItem->zSpan);
1384 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001385 (int)(pSpan->zEnd - pSpan->zStart));
drhb7916a72009-05-27 10:31:29 +00001386 }
1387}
1388
1389/*
danielk19777a15a4b2007-05-08 17:54:43 +00001390** If the expression list pEList contains more than iLimit elements,
1391** leave an error message in pParse.
1392*/
1393void sqlite3ExprListCheckLength(
1394 Parse *pParse,
1395 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001396 const char *zObject
1397){
drhb1a6c3c2008-03-20 16:30:17 +00001398 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001399 testcase( pEList && pEList->nExpr==mx );
1400 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001401 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001402 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1403 }
1404}
1405
1406/*
drha76b5df2002-02-23 02:32:10 +00001407** Delete an entire expression list.
1408*/
drhaffa8552016-04-11 18:25:05 +00001409static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drha76b5df2002-02-23 02:32:10 +00001410 int i;
drhbe5c89a2004-07-26 00:31:09 +00001411 struct ExprList_item *pItem;
drhd872bb12012-02-02 01:58:08 +00001412 assert( pList->a!=0 || pList->nExpr==0 );
drhbe5c89a2004-07-26 00:31:09 +00001413 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00001414 sqlite3ExprDelete(db, pItem->pExpr);
1415 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001416 sqlite3DbFree(db, pItem->zSpan);
drha76b5df2002-02-23 02:32:10 +00001417 }
drh633e6d52008-07-28 19:34:53 +00001418 sqlite3DbFree(db, pList->a);
1419 sqlite3DbFree(db, pList);
drha76b5df2002-02-23 02:32:10 +00001420}
drhaffa8552016-04-11 18:25:05 +00001421void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1422 if( pList ) exprListDeleteNN(db, pList);
1423}
drha76b5df2002-02-23 02:32:10 +00001424
1425/*
drh2308ed32015-02-09 16:09:34 +00001426** Return the bitwise-OR of all Expr.flags fields in the given
1427** ExprList.
drh885a5b02015-02-09 15:21:36 +00001428*/
drh2308ed32015-02-09 16:09:34 +00001429u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001430 int i;
drh2308ed32015-02-09 16:09:34 +00001431 u32 m = 0;
1432 if( pList ){
1433 for(i=0; i<pList->nExpr; i++){
drhd0c73052015-04-19 19:21:19 +00001434 Expr *pExpr = pList->a[i].pExpr;
drhde845c22016-03-17 19:07:52 +00001435 assert( pExpr!=0 );
1436 m |= pExpr->flags;
drh2308ed32015-02-09 16:09:34 +00001437 }
drh885a5b02015-02-09 15:21:36 +00001438 }
drh2308ed32015-02-09 16:09:34 +00001439 return m;
drh885a5b02015-02-09 15:21:36 +00001440}
1441
1442/*
drh059b2d52014-10-24 19:28:09 +00001443** These routines are Walker callbacks used to check expressions to
1444** see if they are "constant" for some definition of constant. The
1445** Walker.eCode value determines the type of "constant" we are looking
1446** for.
drh73b211a2005-01-18 04:00:42 +00001447**
drh7d10d5a2008-08-20 16:35:10 +00001448** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001449**
drh059b2d52014-10-24 19:28:09 +00001450** sqlite3ExprIsConstant() pWalker->eCode==1
1451** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001452** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001453** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001454**
drh059b2d52014-10-24 19:28:09 +00001455** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1456** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001457**
drhfeada2d2014-09-24 13:20:22 +00001458** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001459** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1460** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001461** parameter raises an error for new statements, but is silently converted
1462** to NULL for existing schemas. This allows sqlite_master tables that
1463** contain a bound parameter because they were generated by older versions
1464** of SQLite to be parsed by newer versions of SQLite without raising a
1465** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001466*/
drh7d10d5a2008-08-20 16:35:10 +00001467static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001468
drh059b2d52014-10-24 19:28:09 +00001469 /* If pWalker->eCode is 2 then any term of the expression that comes from
1470 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001471 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001472 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1473 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001474 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001475 }
1476
drh626a8792005-01-17 22:08:19 +00001477 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001478 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001479 ** and either pWalker->eCode==4 or 5 or the function has the
1480 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001481 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001482 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001483 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001484 }else{
1485 pWalker->eCode = 0;
1486 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001487 }
drh626a8792005-01-17 22:08:19 +00001488 case TK_ID:
1489 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001490 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001491 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001492 testcase( pExpr->op==TK_ID );
1493 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001494 testcase( pExpr->op==TK_AGG_FUNCTION );
1495 testcase( pExpr->op==TK_AGG_COLUMN );
drh059b2d52014-10-24 19:28:09 +00001496 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1497 return WRC_Continue;
1498 }else{
1499 pWalker->eCode = 0;
1500 return WRC_Abort;
1501 }
drhfeada2d2014-09-24 13:20:22 +00001502 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001503 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001504 /* Silently convert bound parameters that appear inside of CREATE
1505 ** statements into a NULL when parsing the CREATE statement text out
1506 ** of the sqlite_master table */
1507 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001508 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001509 /* A bound parameter in a CREATE statement that originates from
1510 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001511 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001512 return WRC_Abort;
1513 }
1514 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001515 default:
drhb74b1012009-05-28 21:04:37 +00001516 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1517 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
drh7d10d5a2008-08-20 16:35:10 +00001518 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001519 }
1520}
danielk197762c14b32008-11-19 09:05:26 +00001521static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1522 UNUSED_PARAMETER(NotUsed);
drh059b2d52014-10-24 19:28:09 +00001523 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001524 return WRC_Abort;
1525}
drh059b2d52014-10-24 19:28:09 +00001526static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001527 Walker w;
drhaa87f9a2013-04-25 00:57:10 +00001528 memset(&w, 0, sizeof(w));
drh059b2d52014-10-24 19:28:09 +00001529 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001530 w.xExprCallback = exprNodeIsConstant;
1531 w.xSelectCallback = selectNodeIsConstant;
drh059b2d52014-10-24 19:28:09 +00001532 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001533 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001534 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001535}
drh626a8792005-01-17 22:08:19 +00001536
1537/*
drh059b2d52014-10-24 19:28:09 +00001538** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001539** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001540**
1541** For the purposes of this function, a double-quoted string (ex: "abc")
1542** is considered a variable but a single-quoted string (ex: 'abc') is
1543** a constant.
drhfef52082000-06-06 01:50:43 +00001544*/
danielk19774adee202004-05-08 08:23:19 +00001545int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001546 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001547}
1548
1549/*
drh059b2d52014-10-24 19:28:09 +00001550** Walk an expression tree. Return non-zero if the expression is constant
drh0a168372007-06-08 00:20:47 +00001551** that does no originate from the ON or USING clauses of a join.
1552** Return 0 if it involves variables or function calls or terms from
1553** an ON or USING clause.
1554*/
1555int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001556 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001557}
1558
1559/*
drhfcb9f4f2015-06-01 18:13:16 +00001560** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00001561** for any single row of the table with cursor iCur. In other words, the
1562** expression must not refer to any non-deterministic function nor any
1563** table other than iCur.
1564*/
1565int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1566 return exprIsConst(p, 3, iCur);
1567}
1568
1569/*
1570** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001571** or a function call with constant arguments. Return and 0 if there
1572** are any variables.
1573**
1574** For the purposes of this function, a double-quoted string (ex: "abc")
1575** is considered a variable but a single-quoted string (ex: 'abc') is
1576** a constant.
1577*/
drhfeada2d2014-09-24 13:20:22 +00001578int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1579 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00001580 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00001581}
1582
drh5b88bc42013-12-07 23:35:21 +00001583#ifdef SQLITE_ENABLE_CURSOR_HINTS
1584/*
1585** Walk an expression tree. Return 1 if the expression contains a
1586** subquery of some kind. Return 0 if there are no subqueries.
1587*/
1588int sqlite3ExprContainsSubquery(Expr *p){
1589 Walker w;
1590 memset(&w, 0, sizeof(w));
drhbec24762015-08-13 20:07:13 +00001591 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00001592 w.xExprCallback = sqlite3ExprWalkNoop;
1593 w.xSelectCallback = selectNodeIsConstant;
1594 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00001595 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00001596}
1597#endif
1598
drheb55bd22005-06-30 17:04:21 +00001599/*
drh73b211a2005-01-18 04:00:42 +00001600** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001601** to fit in a 32-bit integer, return 1 and put the value of the integer
1602** in *pValue. If the expression is not an integer or if it is too big
1603** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001604*/
danielk19774adee202004-05-08 08:23:19 +00001605int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00001606 int rc = 0;
drhcd92e842011-02-17 15:58:20 +00001607
1608 /* If an expression is an integer literal that fits in a signed 32-bit
1609 ** integer, then the EP_IntValue flag will have already been set */
1610 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1611 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1612
drh92b01d52008-06-24 00:32:35 +00001613 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00001614 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00001615 return 1;
1616 }
drhe4de1fe2002-06-02 16:09:01 +00001617 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00001618 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00001619 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00001620 break;
drh4b59ab52002-08-24 18:24:51 +00001621 }
drhe4de1fe2002-06-02 16:09:01 +00001622 case TK_UMINUS: {
1623 int v;
danielk19774adee202004-05-08 08:23:19 +00001624 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00001625 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00001626 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00001627 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00001628 }
1629 break;
1630 }
1631 default: break;
1632 }
drh92b01d52008-06-24 00:32:35 +00001633 return rc;
drhe4de1fe2002-06-02 16:09:01 +00001634}
1635
1636/*
drh039fc322009-11-17 18:31:47 +00001637** Return FALSE if there is no chance that the expression can be NULL.
1638**
1639** If the expression might be NULL or if the expression is too complex
1640** to tell return TRUE.
1641**
1642** This routine is used as an optimization, to skip OP_IsNull opcodes
1643** when we know that a value cannot be NULL. Hence, a false positive
1644** (returning TRUE when in fact the expression can never be NULL) might
1645** be a small performance hit but is otherwise harmless. On the other
1646** hand, a false negative (returning FALSE when the result could be NULL)
1647** will likely result in an incorrect answer. So when in doubt, return
1648** TRUE.
1649*/
1650int sqlite3ExprCanBeNull(const Expr *p){
1651 u8 op;
drhcd7f4572009-11-19 14:48:40 +00001652 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001653 op = p->op;
1654 if( op==TK_REGISTER ) op = p->op2;
1655 switch( op ){
1656 case TK_INTEGER:
1657 case TK_STRING:
1658 case TK_FLOAT:
1659 case TK_BLOB:
1660 return 0;
drh7248a8b2014-08-04 18:50:54 +00001661 case TK_COLUMN:
1662 assert( p->pTab!=0 );
drh72673a22014-12-04 16:27:17 +00001663 return ExprHasProperty(p, EP_CanBeNull) ||
1664 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00001665 default:
1666 return 1;
1667 }
1668}
1669
1670/*
1671** Return TRUE if the given expression is a constant which would be
1672** unchanged by OP_Affinity with the affinity given in the second
1673** argument.
1674**
1675** This routine is used to determine if the OP_Affinity operation
1676** can be omitted. When in doubt return FALSE. A false negative
1677** is harmless. A false positive, however, can result in the wrong
1678** answer.
1679*/
1680int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1681 u8 op;
drh05883a32015-06-02 15:32:08 +00001682 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00001683 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001684 op = p->op;
1685 if( op==TK_REGISTER ) op = p->op2;
1686 switch( op ){
1687 case TK_INTEGER: {
1688 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1689 }
1690 case TK_FLOAT: {
1691 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1692 }
1693 case TK_STRING: {
1694 return aff==SQLITE_AFF_TEXT;
1695 }
1696 case TK_BLOB: {
1697 return 1;
1698 }
drh2f2855b2009-11-18 01:25:26 +00001699 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00001700 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1701 return p->iColumn<0
1702 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00001703 }
drh039fc322009-11-17 18:31:47 +00001704 default: {
1705 return 0;
1706 }
1707 }
1708}
1709
1710/*
drhc4a3c772001-04-04 11:48:57 +00001711** Return TRUE if the given string is a row-id column name.
1712*/
danielk19774adee202004-05-08 08:23:19 +00001713int sqlite3IsRowid(const char *z){
1714 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1715 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1716 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001717 return 0;
1718}
1719
danielk19779a96b662007-11-29 17:05:18 +00001720/*
drh69c355b2016-03-09 15:34:51 +00001721** pX is the RHS of an IN operator. If pX is a SELECT statement
1722** that can be simplified to a direct table access, then return
1723** a pointer to the SELECT statement. If pX is not a SELECT statement,
1724** or if the SELECT statement needs to be manifested into a transient
1725** table, then return NULL.
danba00e302016-07-23 20:24:06 +00001726**
1727** If parameter bNullSensitive is 0, then this operation will be
1728** used in a context in which there is no difference between a result
1729** of 0 and one of NULL. For example:
1730**
1731** ... WHERE (?,?) IN (SELECT ...)
1732**
drhb287f4b2008-04-25 00:08:38 +00001733*/
1734#ifndef SQLITE_OMIT_SUBQUERY
dan7b35a772016-07-28 19:47:15 +00001735static Select *isCandidateForInOpt(Expr *pX){
drh69c355b2016-03-09 15:34:51 +00001736 Select *p;
drhb287f4b2008-04-25 00:08:38 +00001737 SrcList *pSrc;
1738 ExprList *pEList;
1739 Table *pTab;
dancfbb5e82016-07-13 19:48:13 +00001740 int i;
drh69c355b2016-03-09 15:34:51 +00001741 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1742 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1743 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00001744 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00001745 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00001746 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1747 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1748 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00001749 }
drhb74b1012009-05-28 21:04:37 +00001750 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00001751 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb74b1012009-05-28 21:04:37 +00001752 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
drhb287f4b2008-04-25 00:08:38 +00001753 if( p->pWhere ) return 0; /* Has no WHERE clause */
1754 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00001755 assert( pSrc!=0 );
1756 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00001757 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00001758 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00001759 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00001760 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00001761 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1762 pEList = p->pEList;
dancfbb5e82016-07-13 19:48:13 +00001763
dan7b35a772016-07-28 19:47:15 +00001764 /* All SELECT results must be columns. */
dancfbb5e82016-07-13 19:48:13 +00001765 for(i=0; i<pEList->nExpr; i++){
1766 Expr *pRes = pEList->a[i].pExpr;
1767 if( pRes->op!=TK_COLUMN ) return 0;
1768 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
dancfbb5e82016-07-13 19:48:13 +00001769 }
drh69c355b2016-03-09 15:34:51 +00001770 return p;
drhb287f4b2008-04-25 00:08:38 +00001771}
1772#endif /* SQLITE_OMIT_SUBQUERY */
1773
1774/*
dan1d8cb212011-12-09 13:24:16 +00001775** Code an OP_Once instruction and allocate space for its flag. Return the
1776** address of the new instruction.
1777*/
1778int sqlite3CodeOnce(Parse *pParse){
1779 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1780 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1781}
1782
1783/*
drh4c259e92014-08-01 21:12:35 +00001784** Generate code that checks the left-most column of index table iCur to see if
1785** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00001786** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1787** to be set to NULL if iCur contains one or more NULL values.
1788*/
1789static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00001790 int addr1;
drh6be515e2014-08-01 21:00:53 +00001791 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00001792 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00001793 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
1794 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00001795 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00001796 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00001797}
1798
drhbb53ecb2014-08-02 21:03:33 +00001799
1800#ifndef SQLITE_OMIT_SUBQUERY
1801/*
1802** The argument is an IN operator with a list (not a subquery) on the
1803** right-hand side. Return TRUE if that list is constant.
1804*/
1805static int sqlite3InRhsIsConstant(Expr *pIn){
1806 Expr *pLHS;
1807 int res;
1808 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
1809 pLHS = pIn->pLeft;
1810 pIn->pLeft = 0;
1811 res = sqlite3ExprIsConstant(pIn);
1812 pIn->pLeft = pLHS;
1813 return res;
1814}
1815#endif
1816
drh6be515e2014-08-01 21:00:53 +00001817/*
danielk19779a96b662007-11-29 17:05:18 +00001818** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00001819** The pX parameter is the expression on the RHS of the IN operator, which
1820** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00001821**
drhd4305ca2012-09-18 17:08:33 +00001822** The job of this routine is to find or create a b-tree object that can
1823** be used either to test for membership in the RHS set or to iterate through
1824** all members of the RHS set, skipping duplicates.
1825**
drh3a856252014-08-01 14:46:57 +00001826** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00001827** and pX->iTable is set to the index of that cursor.
1828**
drhb74b1012009-05-28 21:04:37 +00001829** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00001830**
drh1ccce442013-03-12 20:38:51 +00001831** IN_INDEX_ROWID - The cursor was opened on a database table.
1832** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
1833** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
1834** IN_INDEX_EPH - The cursor was opened on a specially created and
1835** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00001836** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
1837** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00001838**
drhd4305ca2012-09-18 17:08:33 +00001839** An existing b-tree might be used if the RHS expression pX is a simple
1840** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00001841**
1842** SELECT <column> FROM <table>
1843**
drhd4305ca2012-09-18 17:08:33 +00001844** If the RHS of the IN operator is a list or a more complex subquery, then
1845** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00001846** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00001847** existing table.
drhd4305ca2012-09-18 17:08:33 +00001848**
drh3a856252014-08-01 14:46:57 +00001849** The inFlags parameter must contain exactly one of the bits
1850** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
1851** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
1852** fast membership test. When the IN_INDEX_LOOP bit is set, the
1853** IN index will be used to loop over all values of the RHS of the
1854** IN operator.
1855**
1856** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
1857** through the set members) then the b-tree must not contain duplicates.
1858** An epheremal table must be used unless the selected <column> is guaranteed
danielk19779a96b662007-11-29 17:05:18 +00001859** to be unique - either because it is an INTEGER PRIMARY KEY or it
drhb74b1012009-05-28 21:04:37 +00001860** has a UNIQUE constraint or UNIQUE index.
danielk19770cdc0222008-06-26 18:04:03 +00001861**
drh3a856252014-08-01 14:46:57 +00001862** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
1863** for fast set membership tests) then an epheremal table must
danielk19770cdc0222008-06-26 18:04:03 +00001864** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1865** be found with <column> as its left-most column.
1866**
drhbb53ecb2014-08-02 21:03:33 +00001867** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
1868** if the RHS of the IN operator is a list (not a subquery) then this
1869** routine might decide that creating an ephemeral b-tree for membership
1870** testing is too expensive and return IN_INDEX_NOOP. In that case, the
1871** calling routine should implement the IN operator using a sequence
1872** of Eq or Ne comparison operations.
1873**
drhb74b1012009-05-28 21:04:37 +00001874** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00001875** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00001876** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00001877** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00001878** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00001879** to *prRhsHasNull. If there is no chance that the (...) contains a
1880** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00001881**
drhe21a6e12014-08-01 18:00:24 +00001882** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00001883** the value in that register will be NULL if the b-tree contains one or more
1884** NULL values, and it will be some non-NULL value if the b-tree contains no
1885** NULL values.
danielk19779a96b662007-11-29 17:05:18 +00001886*/
danielk1977284f4ac2007-12-10 05:03:46 +00001887#ifndef SQLITE_OMIT_SUBQUERY
danba00e302016-07-23 20:24:06 +00001888int sqlite3FindInIndex(
1889 Parse *pParse,
1890 Expr *pX,
1891 u32 inFlags,
1892 int *prRhsHasNull,
1893 int *aiMap
1894){
drhb74b1012009-05-28 21:04:37 +00001895 Select *p; /* SELECT to the right of IN operator */
1896 int eType = 0; /* Type of RHS table. IN_INDEX_* */
1897 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00001898 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00001899 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00001900
drh1450bc62009-10-30 13:25:56 +00001901 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00001902 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00001903
dan7b35a772016-07-28 19:47:15 +00001904 /* If the RHS of this IN(...) operator is a SELECT, and if it matters
1905 ** whether or not the SELECT result contains NULL values, check whether
1906 ** or not NULL is actuall possible (it may not be, for example, due
1907 ** to NOT NULL constraints in the schema). If no NULL values are possible,
1908 ** set prRhsHasNull to 0 before continuing.
1909 */
1910 if( prRhsHasNull && (pX->flags & EP_xIsSelect) ){
1911 int i;
1912 ExprList *pEList = pX->x.pSelect->pEList;
1913 for(i=0; i<pEList->nExpr; i++){
1914 if( sqlite3ExprCanBeNull(pEList->a[i].pExpr) ) break;
1915 }
1916 if( i==pEList->nExpr ){
1917 prRhsHasNull = 0;
1918 }
1919 }
1920
drhb74b1012009-05-28 21:04:37 +00001921 /* Check to see if an existing table or index can be used to
1922 ** satisfy the query. This is preferable to generating a new
dan7b35a772016-07-28 19:47:15 +00001923 ** ephemeral table. */
1924 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00001925 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00001926 Table *pTab; /* Table <table>. */
danba00e302016-07-23 20:24:06 +00001927 i16 iDb; /* Database idx for pTab */
dancfbb5e82016-07-13 19:48:13 +00001928 ExprList *pEList = p->pEList;
1929 int nExpr = pEList->nExpr;
drhb07028f2011-10-14 21:49:18 +00001930
drhb07028f2011-10-14 21:49:18 +00001931 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
1932 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1933 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
1934 pTab = p->pSrc->a[0].pTab;
dancfbb5e82016-07-13 19:48:13 +00001935
drhb22f7c82014-02-06 23:56:27 +00001936 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00001937 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1938 sqlite3CodeVerifySchema(pParse, iDb);
1939 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00001940
1941 /* This function is only called from two places. In both cases the vdbe
1942 ** has already been allocated. So assume sqlite3GetVdbe() is always
1943 ** successful here.
1944 */
1945 assert(v);
dancfbb5e82016-07-13 19:48:13 +00001946 if( nExpr==1 && pEList->a[0].pExpr->iColumn<0 ){
drh7d176102014-02-18 03:07:12 +00001947 int iAddr = sqlite3CodeOnce(pParse);
1948 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00001949
1950 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1951 eType = IN_INDEX_ROWID;
1952
1953 sqlite3VdbeJumpHere(v, iAddr);
1954 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00001955 Index *pIdx; /* Iterator variable */
dancfbb5e82016-07-13 19:48:13 +00001956 int affinity_ok = 1;
1957 int i;
1958
1959 /* Check that the affinity that will be used to perform each
1960 ** comparison is the same as the affinity of each column. If
1961 ** it not, it is not possible to use any index. */
1962 for(i=0; i<nExpr && affinity_ok; i++){
1963 Expr *pLhs = exprVectorField(pX->pLeft, i);
1964 int iCol = pEList->a[i].pExpr->iColumn;
1965 char idxaff = pTab->aCol[iCol].affinity;
1966 char cmpaff = sqlite3CompareAffinity(pLhs, idxaff);
1967 switch( cmpaff ){
1968 case SQLITE_AFF_BLOB:
1969 break;
1970 case SQLITE_AFF_TEXT:
1971 affinity_ok = (idxaff==SQLITE_AFF_TEXT);
1972 break;
1973 default:
1974 affinity_ok = sqlite3IsNumericAffinity(idxaff);
1975 }
1976 }
danielk1977e1fb65a2009-04-02 17:23:32 +00001977
drhb74b1012009-05-28 21:04:37 +00001978 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00001979 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00001980 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00001981
1982 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
dancfbb5e82016-07-13 19:48:13 +00001983 if( pIdx->nKeyCol<nExpr ) continue;
1984 if( mustBeUnique && (pIdx->nKeyCol!=nExpr || !IsUniqueIndex(pIdx)) ){
1985 continue;
1986 }
1987
1988 for(i=0; i<nExpr; i++){
1989 Expr *pLhs = exprVectorField(pX->pLeft, i);
1990 Expr *pRhs = pEList->a[i].pExpr;
1991 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pLhs, pRhs);
1992 int j;
1993
1994 for(j=0; j<nExpr; j++){
1995 if( pIdx->aiColumn[j]!=pRhs->iColumn ) continue;
1996 assert( pIdx->azColl[j] );
1997 if( sqlite3StrICmp(pReq->zName, pIdx->azColl[j])!=0 ) continue;
1998 break;
1999 }
2000 if( j==nExpr ) break;
danba00e302016-07-23 20:24:06 +00002001 if( aiMap ) aiMap[i] = j;
dancfbb5e82016-07-13 19:48:13 +00002002 }
2003
2004 if( i==nExpr ){
drh7d176102014-02-18 03:07:12 +00002005 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00002006 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
2007 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00002008 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00002009 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
2010 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00002011
dan7b35a772016-07-28 19:47:15 +00002012 if( prRhsHasNull ){
2013 *prRhsHasNull = ++pParse->nMem;
dan3480bfd2016-06-16 17:14:02 +00002014#ifdef SQLITE_ENABLE_COLUMN_USED_MASK
dancfbb5e82016-07-13 19:48:13 +00002015 i64 mask = (1<<nExpr)-1;
dan3480bfd2016-06-16 17:14:02 +00002016 sqlite3VdbeAddOp4Dup8(v, OP_ColumnsUsed,
dancfbb5e82016-07-13 19:48:13 +00002017 iTab, 0, 0, (u8*)&mask, P4_INT64);
dan3480bfd2016-06-16 17:14:02 +00002018#endif
dan7b35a772016-07-28 19:47:15 +00002019 if( nExpr==1 ){
2020 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
2021 }
danielk19770cdc0222008-06-26 18:04:03 +00002022 }
drh552fd452014-02-18 01:07:38 +00002023 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00002024 }
2025 }
2026 }
2027 }
2028
drhbb53ecb2014-08-02 21:03:33 +00002029 /* If no preexisting index is available for the IN clause
2030 ** and IN_INDEX_NOOP is an allowed reply
2031 ** and the RHS of the IN operator is a list, not a subquery
dan71c57db2016-07-09 20:23:55 +00002032 ** and the RHS is not constant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00002033 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00002034 ** the IN operator so return IN_INDEX_NOOP.
2035 */
2036 if( eType==0
2037 && (inFlags & IN_INDEX_NOOP_OK)
2038 && !ExprHasProperty(pX, EP_xIsSelect)
2039 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
2040 ){
2041 eType = IN_INDEX_NOOP;
2042 }
drhbb53ecb2014-08-02 21:03:33 +00002043
danielk19779a96b662007-11-29 17:05:18 +00002044 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00002045 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00002046 ** We will have to generate an ephemeral table to do the job.
2047 */
drh8e23daf2013-06-11 13:30:04 +00002048 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00002049 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00002050 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00002051 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00002052 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00002053 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00002054 eType = IN_INDEX_ROWID;
2055 }
drhe21a6e12014-08-01 18:00:24 +00002056 }else if( prRhsHasNull ){
2057 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00002058 }
danielk197741a05b72008-10-02 13:50:55 +00002059 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00002060 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00002061 }else{
2062 pX->iTable = iTab;
2063 }
danba00e302016-07-23 20:24:06 +00002064
2065 if( aiMap && eType!=IN_INDEX_INDEX_ASC && eType!=IN_INDEX_INDEX_DESC ){
2066 int i, n;
2067 n = sqlite3ExprVectorSize(pX->pLeft);
2068 for(i=0; i<n; i++) aiMap[i] = i;
2069 }
danielk19779a96b662007-11-29 17:05:18 +00002070 return eType;
2071}
danielk1977284f4ac2007-12-10 05:03:46 +00002072#endif
drh626a8792005-01-17 22:08:19 +00002073
dan71c57db2016-07-09 20:23:55 +00002074static char *exprINAffinity(Parse *pParse, Expr *pExpr){
2075 Expr *pLeft = pExpr->pLeft;
2076 int nVal = sqlite3ExprVectorSize(pLeft);
2077 char *zRet;
2078
2079 zRet = sqlite3DbMallocZero(pParse->db, nVal+1);
2080 if( zRet ){
2081 int i;
2082 for(i=0; i<nVal; i++){
2083 Expr *pA;
2084 char a;
dan8da209b2016-07-26 18:06:08 +00002085 if( nVal==1 && 0 ){
dan71c57db2016-07-09 20:23:55 +00002086 pA = pLeft;
2087 }else{
2088 pA = exprVectorField(pLeft, i);
2089 }
2090 a = sqlite3ExprAffinity(pA);
2091 zRet[i] = sqlite3CompareAffinity(pExpr->x.pSelect->pEList->a[i].pExpr, a);
2092 }
2093 zRet[nVal] = '\0';
2094 }
2095 return zRet;
2096}
2097
dan8da209b2016-07-26 18:06:08 +00002098#ifndef SQLITE_OMIT_SUBQUERY
2099/*
2100** Load the Parse object passed as the first argument with an error
2101** message of the form:
2102**
2103** "sub-select returns N columns - expected M"
2104*/
2105void sqlite3SubselectError(Parse *pParse, int nActual, int nExpect){
2106 const char *zFmt = "sub-select returns %d columns - expected %d";
2107 sqlite3ErrorMsg(pParse, zFmt, nActual, nExpect);
2108}
2109#endif
2110
drh626a8792005-01-17 22:08:19 +00002111/*
drhd4187c72010-08-30 22:15:45 +00002112** Generate code for scalar subqueries used as a subquery expression, EXISTS,
2113** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00002114**
drh9cbe6352005-11-29 03:13:21 +00002115** (SELECT a FROM b) -- subquery
2116** EXISTS (SELECT a FROM b) -- EXISTS subquery
2117** x IN (4,5,11) -- IN operator with list on right-hand side
2118** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00002119**
drh9cbe6352005-11-29 03:13:21 +00002120** The pExpr parameter describes the expression that contains the IN
2121** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00002122**
2123** If parameter isRowid is non-zero, then expression pExpr is guaranteed
2124** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
2125** to some integer key column of a table B-Tree. In this case, use an
2126** intkey B-Tree to store the set of IN(...) values instead of the usual
2127** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00002128**
2129** If rMayHaveNull is non-zero, that means that the operation is an IN
2130** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00002131** All this routine does is initialize the register given by rMayHaveNull
2132** to NULL. Calling routines will take care of changing this register
2133** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00002134**
2135** For a SELECT or EXISTS operator, return the register that holds the
2136** result. For IN operators or if an error occurs, the return value is 0.
drhcce7d172000-05-31 15:34:51 +00002137*/
drh51522cd2005-01-20 13:36:19 +00002138#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00002139int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00002140 Parse *pParse, /* Parsing context */
2141 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00002142 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00002143 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00002144){
drh6be515e2014-08-01 21:00:53 +00002145 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00002146 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00002147 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00002148 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00002149 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002150
drh57dbd7b2005-07-08 18:25:26 +00002151 /* This code must be run in its entirety every time it is encountered
2152 ** if any of the following is true:
2153 **
2154 ** * The right-hand side is a correlated subquery
2155 ** * The right-hand side is an expression list containing variables
2156 ** * We are inside a trigger
2157 **
2158 ** If all of the above are false, then we can run this code just once
2159 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00002160 */
drhc5cd1242013-09-12 16:50:49 +00002161 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00002162 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00002163 }
2164
dan4a07e3d2010-11-09 14:48:59 +00002165#ifndef SQLITE_OMIT_EXPLAIN
2166 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00002167 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
2168 jmpIfDynamic>=0?"":"CORRELATED ",
2169 pExpr->op==TK_IN?"LIST":"SCALAR",
2170 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00002171 );
2172 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
2173 }
2174#endif
2175
drhcce7d172000-05-31 15:34:51 +00002176 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00002177 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00002178 int addr; /* Address of OP_OpenEphemeral instruction */
2179 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00002180 KeyInfo *pKeyInfo = 0; /* Key information */
dan71c57db2016-07-09 20:23:55 +00002181 int nVal; /* Size of vector pLeft */
2182
2183 nVal = sqlite3ExprVectorSize(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002184
2185 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00002186 ** expression it is handled the same way. An ephemeral table is
danielk1977e014a832004-05-17 10:48:57 +00002187 ** filled with single-field index keys representing the results
2188 ** from the SELECT or the <exprlist>.
2189 **
2190 ** If the 'x' expression is a column value, or the SELECT...
2191 ** statement returns a column value, then the affinity of that
2192 ** column is used to build the index keys. If both 'x' and the
2193 ** SELECT... statement are columns, then numeric affinity is used
2194 ** if either column has NUMERIC or INTEGER affinity. If neither
2195 ** 'x' nor the SELECT... statement are columns, then numeric affinity
2196 ** is used.
2197 */
2198 pExpr->iTable = pParse->nTab++;
dan71c57db2016-07-09 20:23:55 +00002199 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral,
2200 pExpr->iTable, (isRowid?0:nVal));
2201 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, nVal, 1);
danielk1977e014a832004-05-17 10:48:57 +00002202
danielk19776ab3a2e2009-02-19 14:39:25 +00002203 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00002204 /* Case 1: expr IN (SELECT ...)
2205 **
danielk1977e014a832004-05-17 10:48:57 +00002206 ** Generate code to write the results of the select into the temporary
2207 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00002208 */
drh43870062014-07-31 15:44:44 +00002209 Select *pSelect = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002210 ExprList *pEList = pSelect->pEList;
drh1013c932008-01-06 00:25:21 +00002211
danielk197741a05b72008-10-02 13:50:55 +00002212 assert( !isRowid );
dan71c57db2016-07-09 20:23:55 +00002213 if( pEList->nExpr!=nVal ){
dan8da209b2016-07-26 18:06:08 +00002214 sqlite3SubselectError(pParse, pEList->nExpr, nVal);
dan71c57db2016-07-09 20:23:55 +00002215 }else{
2216 SelectDest dest;
2217 int i;
2218 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
2219 dest.zAffSdst = exprINAffinity(pParse, pExpr);
2220 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
2221 pSelect->iLimit = 0;
2222 testcase( pSelect->selFlags & SF_Distinct );
2223 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
2224 if( sqlite3Select(pParse, pSelect, &dest) ){
2225 sqlite3DbFree(pParse->db, dest.zAffSdst);
2226 sqlite3KeyInfoUnref(pKeyInfo);
2227 return 0;
2228 }
2229 sqlite3DbFree(pParse->db, dest.zAffSdst);
2230 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
2231 assert( pEList!=0 );
2232 assert( pEList->nExpr>0 );
2233 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
2234 for(i=0; i<nVal; i++){
2235 Expr *p = (nVal>1) ? exprVectorField(pLeft, i) : pLeft;
2236 pKeyInfo->aColl[i] = sqlite3BinaryCompareCollSeq(
2237 pParse, p, pEList->a[i].pExpr
2238 );
2239 }
drh94ccde52007-04-13 16:06:32 +00002240 }
drha7d2db12010-07-14 20:23:52 +00002241 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00002242 /* Case 2: expr IN (exprlist)
2243 **
drhfd131da2007-08-07 17:13:03 +00002244 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00002245 ** store it in the temporary table. If <expr> is a column, then use
2246 ** that columns affinity when building index keys. If <expr> is not
2247 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00002248 */
dan71c57db2016-07-09 20:23:55 +00002249 char affinity; /* Affinity of the LHS of the IN */
danielk1977e014a832004-05-17 10:48:57 +00002250 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002251 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002252 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002253 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002254
dan71c57db2016-07-09 20:23:55 +00002255 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00002256 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002257 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002258 }
drh323df792013-08-05 19:11:29 +00002259 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002260 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002261 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2262 }
danielk1977e014a832004-05-17 10:48:57 +00002263
2264 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002265 r1 = sqlite3GetTempReg(pParse);
2266 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002267 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002268 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2269 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002270 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002271
drh57dbd7b2005-07-08 18:25:26 +00002272 /* If the expression is not constant then we will need to
2273 ** disable the test that was generated above that makes sure
2274 ** this code only executes once. Because for a non-constant
2275 ** expression we need to rerun this code each time.
2276 */
drh6be515e2014-08-01 21:00:53 +00002277 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2278 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2279 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002280 }
danielk1977e014a832004-05-17 10:48:57 +00002281
2282 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002283 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2284 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002285 }else{
drhe05c9292009-10-29 13:48:10 +00002286 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2287 if( isRowid ){
2288 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2289 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002290 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002291 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2292 }else{
2293 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2294 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2295 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2296 }
danielk197741a05b72008-10-02 13:50:55 +00002297 }
drhfef52082000-06-06 01:50:43 +00002298 }
drh2d401ab2008-01-10 23:50:11 +00002299 sqlite3ReleaseTempReg(pParse, r1);
2300 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002301 }
drh323df792013-08-05 19:11:29 +00002302 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002303 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002304 }
danielk1977b3bce662005-01-29 08:32:43 +00002305 break;
drhfef52082000-06-06 01:50:43 +00002306 }
2307
drh51522cd2005-01-20 13:36:19 +00002308 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002309 case TK_SELECT:
2310 default: {
drhfd773cf2009-05-29 14:39:07 +00002311 /* If this has to be a scalar SELECT. Generate code to put the
drhfef52082000-06-06 01:50:43 +00002312 ** value of this select in a memory cell and record the number
drhfd773cf2009-05-29 14:39:07 +00002313 ** of the memory cell in iColumn. If this is an EXISTS, write
2314 ** an integer 0 (not exists) or 1 (exists) into a memory cell
2315 ** and record that memory cell in iColumn.
drhfef52082000-06-06 01:50:43 +00002316 */
drhfd773cf2009-05-29 14:39:07 +00002317 Select *pSel; /* SELECT statement to encode */
2318 SelectDest dest; /* How to deal with SELECt result */
dan71c57db2016-07-09 20:23:55 +00002319 int nReg; /* Registers to allocate */
drh1398ad32005-01-19 23:24:50 +00002320
shanecf697392009-06-01 16:53:09 +00002321 testcase( pExpr->op==TK_EXISTS );
2322 testcase( pExpr->op==TK_SELECT );
2323 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
danielk19776ab3a2e2009-02-19 14:39:25 +00002324 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
dan71c57db2016-07-09 20:23:55 +00002325
danielk19776ab3a2e2009-02-19 14:39:25 +00002326 pSel = pExpr->x.pSelect;
dan71c57db2016-07-09 20:23:55 +00002327 nReg = pExpr->op==TK_SELECT ? pSel->pEList->nExpr : 1;
2328 sqlite3SelectDestInit(&dest, 0, pParse->nMem+1);
2329 pParse->nMem += nReg;
drh51522cd2005-01-20 13:36:19 +00002330 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002331 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002332 dest.iSdst = dest.iSDParm;
dan71c57db2016-07-09 20:23:55 +00002333 dest.nSdst = nReg;
2334 sqlite3VdbeAddOp3(v, OP_Null, 0, dest.iSDParm, dest.iSDParm+nReg-1);
drhd4e70eb2008-01-02 00:34:36 +00002335 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002336 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002337 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002338 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002339 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002340 }
drh633e6d52008-07-28 19:34:53 +00002341 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002342 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2343 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002344 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002345 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002346 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002347 return 0;
drh94ccde52007-04-13 16:06:32 +00002348 }
drh2b596da2012-07-23 21:43:19 +00002349 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002350 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002351 break;
drhcce7d172000-05-31 15:34:51 +00002352 }
2353 }
danielk1977b3bce662005-01-29 08:32:43 +00002354
drh6be515e2014-08-01 21:00:53 +00002355 if( rHasNullFlag ){
2356 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002357 }
drh6be515e2014-08-01 21:00:53 +00002358
2359 if( jmpIfDynamic>=0 ){
2360 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002361 }
drhd2490902014-04-13 19:28:15 +00002362 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002363
drh1450bc62009-10-30 13:25:56 +00002364 return rReg;
drhcce7d172000-05-31 15:34:51 +00002365}
drh51522cd2005-01-20 13:36:19 +00002366#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002367
drhe3365e62009-11-12 17:52:24 +00002368#ifndef SQLITE_OMIT_SUBQUERY
2369/*
dan7b35a772016-07-28 19:47:15 +00002370** Expr pIn is an IN(...) expression. This function checks that the
2371** sub-select on the RHS of the IN() operator has the same number of
2372** columns as the vector on the LHS. Or, if the RHS of the IN() is not
2373** a sub-query, that the LHS is a vector of size 1.
2374*/
2375int sqlite3ExprCheckIN(Parse *pParse, Expr *pIn){
2376 int nVector = sqlite3ExprVectorSize(pIn->pLeft);
2377 if( (pIn->flags & EP_xIsSelect) ){
2378 if( nVector!=pIn->x.pSelect->pEList->nExpr ){
2379 sqlite3SubselectError(pParse, pIn->x.pSelect->pEList->nExpr, nVector);
2380 return 1;
2381 }
2382 }else if( nVector!=1 ){
2383 if( (pIn->pLeft->flags & EP_xIsSelect) ){
2384 sqlite3SubselectError(pParse, nVector, 1);
2385 }else{
2386 sqlite3ErrorMsg(pParse, "invalid use of row value");
2387 }
2388 return 1;
2389 }
2390 return 0;
2391}
2392#endif
2393
2394#ifndef SQLITE_OMIT_SUBQUERY
2395/*
drhe3365e62009-11-12 17:52:24 +00002396** Generate code for an IN expression.
2397**
2398** x IN (SELECT ...)
2399** x IN (value, value, ...)
2400**
2401** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
2402** is an array of zero or more values. The expression is true if the LHS is
2403** contained within the RHS. The value of the expression is unknown (NULL)
2404** if the LHS is NULL or if the LHS is not contained within the RHS and the
2405** RHS contains one or more NULL values.
2406**
drh6be515e2014-08-01 21:00:53 +00002407** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002408** contained within the RHS. If due to NULLs we cannot determine if the LHS
2409** is contained in the RHS then jump to destIfNull. If the LHS is contained
2410** within the RHS then fall through.
2411*/
2412static void sqlite3ExprCodeIN(
2413 Parse *pParse, /* Parsing and code generating context */
2414 Expr *pExpr, /* The IN expression */
2415 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2416 int destIfNull /* Jump here if the results are unknown due to NULLs */
2417){
2418 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
drhe3365e62009-11-12 17:52:24 +00002419 int eType; /* Type of the RHS */
2420 int r1; /* Temporary use register */
2421 Vdbe *v; /* Statement under construction */
danba00e302016-07-23 20:24:06 +00002422 int *aiMap = 0; /* Map from vector field to index column */
2423 char *zAff = 0; /* Affinity string for comparisons */
2424 int nVector; /* Size of vectors for this IN(...) op */
2425 int regSelect = 0;
2426 Expr *pLeft = pExpr->pLeft;
2427 int i;
drhe3365e62009-11-12 17:52:24 +00002428
dan7b35a772016-07-28 19:47:15 +00002429 if( sqlite3ExprCheckIN(pParse, pExpr) ) return;
danba00e302016-07-23 20:24:06 +00002430 nVector = sqlite3ExprVectorSize(pExpr->pLeft);
2431 aiMap = (int*)sqlite3DbMallocZero(
2432 pParse->db, nVector*(sizeof(int) + sizeof(char)) + 1
2433 );
2434 if( !aiMap ) return;
2435 zAff = (char*)&aiMap[nVector];
dan71c57db2016-07-09 20:23:55 +00002436
dan7b35a772016-07-28 19:47:15 +00002437
danba00e302016-07-23 20:24:06 +00002438 /* Attempt to compute the RHS. After this step, if anything other than
2439 ** IN_INDEX_NOOP is returned, the table opened ith cursor pExpr->iTable
2440 ** contains the values that make up the RHS. If IN_INDEX_NOOP is returned,
2441 ** the RHS has not yet been coded. */
drhe3365e62009-11-12 17:52:24 +00002442 v = pParse->pVdbe;
2443 assert( v!=0 ); /* OOM detected prior to this routine */
2444 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002445 eType = sqlite3FindInIndex(pParse, pExpr,
2446 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
danba00e302016-07-23 20:24:06 +00002447 destIfFalse==destIfNull ? 0 : &rRhsHasNull, aiMap);
drhe3365e62009-11-12 17:52:24 +00002448
danba00e302016-07-23 20:24:06 +00002449 assert( pParse->nErr || nVector==1 || eType==IN_INDEX_EPH
2450 || eType==IN_INDEX_INDEX_ASC || eType==IN_INDEX_INDEX_DESC
2451 );
drhe3365e62009-11-12 17:52:24 +00002452
danba00e302016-07-23 20:24:06 +00002453 /* Code the LHS, the <expr> from "<expr> IN (...)". If the LHS is a
2454 ** vector, then it is stored in an array of nVector registers starting
2455 ** at r1.
drhe3365e62009-11-12 17:52:24 +00002456 */
danba00e302016-07-23 20:24:06 +00002457 r1 = sqlite3GetTempRange(pParse, nVector);
drhe3365e62009-11-12 17:52:24 +00002458 sqlite3ExprCachePush(pParse);
danba00e302016-07-23 20:24:06 +00002459 if( nVector>1 && (pLeft->flags & EP_xIsSelect) ){
2460 regSelect = sqlite3CodeSubselect(pParse, pLeft, 0, 0);
2461 }
2462 for(i=0; i<nVector; i++){
2463 int iCol = aiMap[i];
2464 Expr *pLhs = exprVectorField(pLeft, i);
2465
2466 if( regSelect ){
2467 sqlite3VdbeAddOp3(v, OP_Copy, regSelect+i, r1+iCol, 0);
2468 }else{
2469 sqlite3ExprCode(pParse, pLhs, r1+iCol);
2470 }
2471
2472 zAff[iCol] = sqlite3ExprAffinity(pLhs);
2473 if( pExpr->flags & EP_xIsSelect ){
2474 zAff[iCol] = sqlite3CompareAffinity(
2475 pExpr->x.pSelect->pEList->a[iCol].pExpr, zAff[iCol]
2476 );
2477 }
2478 }
drhe3365e62009-11-12 17:52:24 +00002479
drhbb53ecb2014-08-02 21:03:33 +00002480 /* If sqlite3FindInIndex() did not find or create an index that is
2481 ** suitable for evaluating the IN operator, then evaluate using a
2482 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002483 */
drhbb53ecb2014-08-02 21:03:33 +00002484 if( eType==IN_INDEX_NOOP ){
2485 ExprList *pList = pExpr->x.pList;
2486 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2487 int labelOk = sqlite3VdbeMakeLabel(v);
2488 int r2, regToFree;
2489 int regCkNull = 0;
2490 int ii;
2491 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002492 if( destIfNull!=destIfFalse ){
2493 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002494 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002495 }
2496 for(ii=0; ii<pList->nExpr; ii++){
2497 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002498 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002499 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2500 }
2501 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2502 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002503 (void*)pColl, P4_COLLSEQ);
2504 VdbeCoverageIf(v, ii<pList->nExpr-1);
2505 VdbeCoverageIf(v, ii==pList->nExpr-1);
danba00e302016-07-23 20:24:06 +00002506 sqlite3VdbeChangeP5(v, zAff[0]);
drhbb53ecb2014-08-02 21:03:33 +00002507 }else{
2508 assert( destIfNull==destIfFalse );
2509 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2510 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
danba00e302016-07-23 20:24:06 +00002511 sqlite3VdbeChangeP5(v, zAff[0] | SQLITE_JUMPIFNULL);
drhbb53ecb2014-08-02 21:03:33 +00002512 }
2513 sqlite3ReleaseTempReg(pParse, regToFree);
2514 }
2515 if( regCkNull ){
2516 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002517 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002518 }
2519 sqlite3VdbeResolveLabel(v, labelOk);
2520 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002521 }else{
drhbb53ecb2014-08-02 21:03:33 +00002522
dan7b35a772016-07-28 19:47:15 +00002523 /* If any value on the LHS is NULL, the result of the IN(...) operator
2524 ** must be either false or NULL. If these two are handled identically,
2525 ** test the LHS for NULLs and jump directly to destIfNull if any are
2526 ** found.
2527 **
2528 ** Otherwise, if NULL and false are handled differently, and the
2529 ** IN(...) operation is not a vector operation, and the LHS of the
2530 ** operator is NULL, then the result is false if the index is
2531 ** completely empty, or NULL otherwise. */
dand49fd4e2016-07-27 19:33:04 +00002532 if( destIfNull==destIfFalse ){
2533 for(i=0; i<nVector; i++){
2534 Expr *p = exprVectorField(pExpr->pLeft, i);
2535 if( sqlite3ExprCanBeNull(p) ){
2536 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
2537 }
drh7248a8b2014-08-04 18:50:54 +00002538 }
dand49fd4e2016-07-27 19:33:04 +00002539 }else if( nVector==1 && sqlite3ExprCanBeNull(pExpr->pLeft) ){
2540 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2541 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2542 VdbeCoverage(v);
2543 sqlite3VdbeGoto(v, destIfNull);
2544 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002545 }
2546
2547 if( eType==IN_INDEX_ROWID ){
dan7b35a772016-07-28 19:47:15 +00002548 /* In this case, the RHS is the ROWID of table b-tree */
drheeb95652016-05-26 20:56:38 +00002549 sqlite3VdbeAddOp3(v, OP_SeekRowid, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002550 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002551 }else{
dan7b35a772016-07-28 19:47:15 +00002552 /* In this case, the RHS is an index b-tree. Apply the comparison
2553 ** affinities to each value on the LHS of the operator. */
danba00e302016-07-23 20:24:06 +00002554 sqlite3VdbeAddOp4(v, OP_Affinity, r1, nVector, 0, zAff, nVector);
dan7b35a772016-07-28 19:47:15 +00002555
2556 if( nVector>1 && destIfNull!=destIfFalse ){
2557 int iIdx = pExpr->iTable;
2558 int addr;
2559 int addrNext;
2560
2561 /* Search the index for the key. */
2562 addr = sqlite3VdbeAddOp4Int(v, OP_Found, iIdx, 0, r1, nVector);
2563
2564 /* At this point the specified key is not present in the index,
2565 ** so the result of the IN(..) operator must be either NULL or
2566 ** 0. The vdbe code generated below figures out which. */
2567 addrNext = 1+sqlite3VdbeAddOp2(v, OP_Rewind, iIdx, destIfFalse);
2568
2569 for(i=0; i<nVector; i++){
2570 Expr *p;
2571 CollSeq *pColl;
2572 int r2 = sqlite3GetTempReg(pParse);
2573 p = exprVectorField(pLeft, i);
2574 pColl = sqlite3ExprCollSeq(pParse, p);
2575
2576 sqlite3VdbeAddOp3(v, OP_Column, iIdx, i, r2);
2577 sqlite3VdbeAddOp4(v, OP_Eq, r1+i, 0, r2, (void*)pColl,P4_COLLSEQ);
2578 sqlite3VdbeChangeP5(v, SQLITE_JUMPIFNULL);
2579 sqlite3VdbeAddOp2(v, OP_Next, iIdx, addrNext);
2580 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfFalse);
2581 sqlite3VdbeJumpHere(v, sqlite3VdbeCurrentAddr(v)-3);
2582 sqlite3ReleaseTempReg(pParse, r2);
2583 }
2584 sqlite3VdbeAddOp2(v, OP_Goto, 0, destIfNull);
2585
2586 /* The key was found in the index. If it contains any NULL values,
2587 ** then the result of the IN(...) operator is NULL. Otherwise, the
2588 ** result is 1. */
2589 sqlite3VdbeJumpHere(v, addr);
2590 for(i=0; i<nVector; i++){
2591 Expr *p = exprVectorField(pExpr->pLeft, i);
2592 if( sqlite3ExprCanBeNull(p) ){
2593 sqlite3VdbeAddOp2(v, OP_IsNull, r1+aiMap[i], destIfNull);
2594 }
2595 }
2596
2597 }else if( rRhsHasNull==0 ){
drhbb53ecb2014-08-02 21:03:33 +00002598 /* This branch runs if it is known at compile time that the RHS
dan7b35a772016-07-28 19:47:15 +00002599 ** cannot contain NULL values. This happens as a result
2600 ** of "NOT NULL" constraints in the database schema.
drhbb53ecb2014-08-02 21:03:33 +00002601 **
2602 ** Also run this branch if NULL is equivalent to FALSE
dan7b35a772016-07-28 19:47:15 +00002603 ** for this particular IN operator. */
danba00e302016-07-23 20:24:06 +00002604 sqlite3VdbeAddOp4Int(
2605 v, OP_NotFound, pExpr->iTable, destIfFalse, r1, nVector
2606 );
drhbb53ecb2014-08-02 21:03:33 +00002607 VdbeCoverage(v);
2608 }else{
2609 /* In this branch, the RHS of the IN might contain a NULL and
2610 ** the presence of a NULL on the RHS makes a difference in the
2611 ** outcome.
2612 */
drh728e0f92015-10-10 14:41:28 +00002613 int addr1;
dan7b35a772016-07-28 19:47:15 +00002614
drhbb53ecb2014-08-02 21:03:33 +00002615 /* First check to see if the LHS is contained in the RHS. If so,
2616 ** then the answer is TRUE the presence of NULLs in the RHS does
2617 ** not matter. If the LHS is not contained in the RHS, then the
2618 ** answer is NULL if the RHS contains NULLs and the answer is
2619 ** FALSE if the RHS is NULL-free.
2620 */
drh728e0f92015-10-10 14:41:28 +00002621 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002622 VdbeCoverage(v);
2623 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2624 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002625 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002626 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002627 }
drhe3365e62009-11-12 17:52:24 +00002628 }
drhe3365e62009-11-12 17:52:24 +00002629 }
2630 sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002631 sqlite3ExprCachePop(pParse);
danba00e302016-07-23 20:24:06 +00002632 sqlite3DbFree(pParse->db, aiMap);
drhe3365e62009-11-12 17:52:24 +00002633 VdbeComment((v, "end IN expr"));
2634}
2635#endif /* SQLITE_OMIT_SUBQUERY */
2636
drh13573c72010-01-12 17:04:07 +00002637#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002638/*
2639** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002640** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002641**
2642** The z[] string will probably not be zero-terminated. But the
2643** z[n] character is guaranteed to be something that does not look
2644** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002645*/
drhb7916a72009-05-27 10:31:29 +00002646static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002647 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002648 double value;
drh9339da12010-09-30 00:50:49 +00002649 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002650 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2651 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002652 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002653 }
2654}
drh13573c72010-01-12 17:04:07 +00002655#endif
drh598f1342007-10-23 15:39:45 +00002656
2657
2658/*
drhfec19aa2004-05-19 20:41:03 +00002659** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002660** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002661**
shaneh5f1d6b62010-09-30 16:51:25 +00002662** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002663*/
drh13573c72010-01-12 17:04:07 +00002664static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2665 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002666 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002667 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002668 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002669 if( negFlag ) i = -i;
2670 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002671 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002672 int c;
2673 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002674 const char *z = pExpr->u.zToken;
2675 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002676 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002677 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002678 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002679 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002680 }else{
drh13573c72010-01-12 17:04:07 +00002681#ifdef SQLITE_OMIT_FLOATING_POINT
2682 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2683#else
drh1b7ddc52014-07-23 14:52:05 +00002684#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002685 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2686 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002687 }else
2688#endif
2689 {
drh9296c182014-07-23 13:40:49 +00002690 codeReal(v, z, negFlag, iMem);
2691 }
drh13573c72010-01-12 17:04:07 +00002692#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002693 }
drhfec19aa2004-05-19 20:41:03 +00002694 }
2695}
2696
drhbea119c2016-04-11 18:15:37 +00002697#if defined(SQLITE_DEBUG)
2698/*
2699** Verify the consistency of the column cache
2700*/
2701static int cacheIsValid(Parse *pParse){
2702 int i, n;
2703 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2704 if( pParse->aColCache[i].iReg>0 ) n++;
2705 }
2706 return n==pParse->nColCache;
2707}
2708#endif
2709
drhceea3322009-04-23 13:22:42 +00002710/*
2711** Clear a cache entry.
2712*/
2713static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2714 if( p->tempReg ){
2715 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2716 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2717 }
2718 p->tempReg = 0;
2719 }
drhbea119c2016-04-11 18:15:37 +00002720 p->iReg = 0;
2721 pParse->nColCache--;
danee65eea2016-04-16 15:03:20 +00002722 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002723}
2724
2725
2726/*
2727** Record in the column cache that a particular column from a
2728** particular table is stored in a particular register.
2729*/
2730void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2731 int i;
2732 int minLru;
2733 int idxLru;
2734 struct yColCache *p;
2735
dance8f53d2015-01-21 17:00:57 +00002736 /* Unless an error has occurred, register numbers are always positive. */
2737 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002738 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2739
drhb6da74e2009-12-24 16:00:28 +00002740 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2741 ** for testing only - to verify that SQLite always gets the same answer
2742 ** with and without the column cache.
2743 */
drh7e5418e2012-09-27 15:05:54 +00002744 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002745
drh27ee4062009-12-30 01:13:11 +00002746 /* First replace any existing entry.
2747 **
2748 ** Actually, the way the column cache is currently used, we are guaranteed
2749 ** that the object will never already be in cache. Verify this guarantee.
2750 */
2751#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00002752 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00002753 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00002754 }
drh27ee4062009-12-30 01:13:11 +00002755#endif
drhceea3322009-04-23 13:22:42 +00002756
2757 /* Find an empty slot and replace it */
2758 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2759 if( p->iReg==0 ){
2760 p->iLevel = pParse->iCacheLevel;
2761 p->iTable = iTab;
2762 p->iColumn = iCol;
2763 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002764 p->tempReg = 0;
2765 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002766 pParse->nColCache++;
danee65eea2016-04-16 15:03:20 +00002767 assert( pParse->db->mallocFailed || cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002768 return;
2769 }
2770 }
2771
2772 /* Replace the last recently used */
2773 minLru = 0x7fffffff;
2774 idxLru = -1;
2775 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2776 if( p->lru<minLru ){
2777 idxLru = i;
2778 minLru = p->lru;
2779 }
2780 }
drh20411ea2009-05-29 19:00:12 +00002781 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00002782 p = &pParse->aColCache[idxLru];
2783 p->iLevel = pParse->iCacheLevel;
2784 p->iTable = iTab;
2785 p->iColumn = iCol;
2786 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002787 p->tempReg = 0;
2788 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002789 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002790 return;
2791 }
2792}
2793
2794/*
drhf49f3522009-12-30 14:12:38 +00002795** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2796** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00002797*/
drhf49f3522009-12-30 14:12:38 +00002798void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00002799 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00002800 if( iReg<=0 || pParse->nColCache==0 ) return;
2801 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
2802 while(1){
2803 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
2804 if( p==pParse->aColCache ) break;
2805 p--;
drhceea3322009-04-23 13:22:42 +00002806 }
2807}
2808
2809/*
2810** Remember the current column cache context. Any new entries added
2811** added to the column cache after this call are removed when the
2812** corresponding pop occurs.
2813*/
2814void sqlite3ExprCachePush(Parse *pParse){
2815 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00002816#ifdef SQLITE_DEBUG
2817 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
2818 printf("PUSH to %d\n", pParse->iCacheLevel);
2819 }
2820#endif
drhceea3322009-04-23 13:22:42 +00002821}
2822
2823/*
2824** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00002825** the previous sqlite3ExprCachePush operation. In other words, restore
2826** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00002827*/
drhd2490902014-04-13 19:28:15 +00002828void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00002829 int i;
2830 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00002831 assert( pParse->iCacheLevel>=1 );
2832 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00002833#ifdef SQLITE_DEBUG
2834 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
2835 printf("POP to %d\n", pParse->iCacheLevel);
2836 }
2837#endif
drhceea3322009-04-23 13:22:42 +00002838 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2839 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2840 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00002841 }
2842 }
2843}
drh945498f2007-02-24 11:52:52 +00002844
2845/*
drh5cd79232009-05-25 11:46:29 +00002846** When a cached column is reused, make sure that its register is
2847** no longer available as a temp register. ticket #3879: that same
2848** register might be in the cache in multiple places, so be sure to
2849** get them all.
2850*/
2851static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
2852 int i;
2853 struct yColCache *p;
2854 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2855 if( p->iReg==iReg ){
2856 p->tempReg = 0;
2857 }
2858 }
2859}
2860
drh1f9ca2c2015-08-25 16:57:52 +00002861/* Generate code that will load into register regOut a value that is
2862** appropriate for the iIdxCol-th column of index pIdx.
2863*/
2864void sqlite3ExprCodeLoadIndexColumn(
2865 Parse *pParse, /* The parsing context */
2866 Index *pIdx, /* The index whose column is to be loaded */
2867 int iTabCur, /* Cursor pointing to a table row */
2868 int iIdxCol, /* The column of the index to be loaded */
2869 int regOut /* Store the index column value in this register */
2870){
2871 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00002872 if( iTabCol==XN_EXPR ){
2873 assert( pIdx->aColExpr );
2874 assert( pIdx->aColExpr->nExpr>iIdxCol );
2875 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00002876 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00002877 }else{
drh1f9ca2c2015-08-25 16:57:52 +00002878 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
2879 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00002880 }
drh1f9ca2c2015-08-25 16:57:52 +00002881}
2882
drh5cd79232009-05-25 11:46:29 +00002883/*
drh5c092e82010-05-14 19:24:02 +00002884** Generate code to extract the value of the iCol-th column of a table.
2885*/
2886void sqlite3ExprCodeGetColumnOfTable(
2887 Vdbe *v, /* The VDBE under construction */
2888 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00002889 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00002890 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00002891 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00002892){
2893 if( iCol<0 || iCol==pTab->iPKey ){
2894 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
2895 }else{
2896 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00002897 int x = iCol;
drh35db31b2016-06-02 23:13:21 +00002898 if( !HasRowid(pTab) && !IsVirtual(pTab) ){
drhee0ec8e2013-10-31 17:38:01 +00002899 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
2900 }
2901 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00002902 }
2903 if( iCol>=0 ){
2904 sqlite3ColumnDefault(v, pTab, iCol, regOut);
2905 }
2906}
2907
2908/*
drh945498f2007-02-24 11:52:52 +00002909** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00002910** table pTab and store the column value in a register.
2911**
2912** An effort is made to store the column value in register iReg. This
2913** is not garanteeed for GetColumn() - the result can be stored in
2914** any register. But the result is guaranteed to land in register iReg
2915** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00002916**
2917** There must be an open cursor to pTab in iTable when this routine
2918** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00002919*/
drhe55cbd72008-03-31 23:48:03 +00002920int sqlite3ExprCodeGetColumn(
2921 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00002922 Table *pTab, /* Description of the table we are reading from */
2923 int iColumn, /* Index of the table column */
2924 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00002925 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00002926 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00002927){
drhe55cbd72008-03-31 23:48:03 +00002928 Vdbe *v = pParse->pVdbe;
2929 int i;
drhda250ea2008-04-01 05:07:14 +00002930 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00002931
drhceea3322009-04-23 13:22:42 +00002932 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00002933 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00002934 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00002935 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00002936 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00002937 }
2938 }
2939 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00002940 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00002941 if( p5 ){
2942 sqlite3VdbeChangeP5(v, p5);
2943 }else{
2944 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2945 }
drhe55cbd72008-03-31 23:48:03 +00002946 return iReg;
2947}
drhce78bc62015-10-15 19:21:51 +00002948void sqlite3ExprCodeGetColumnToReg(
2949 Parse *pParse, /* Parsing and code generating context */
2950 Table *pTab, /* Description of the table we are reading from */
2951 int iColumn, /* Index of the table column */
2952 int iTable, /* The cursor pointing to the table */
2953 int iReg /* Store results here */
2954){
2955 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
2956 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
2957}
2958
drhe55cbd72008-03-31 23:48:03 +00002959
2960/*
drhceea3322009-04-23 13:22:42 +00002961** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00002962*/
drhceea3322009-04-23 13:22:42 +00002963void sqlite3ExprCacheClear(Parse *pParse){
2964 int i;
2965 struct yColCache *p;
2966
drh9ac79622013-12-18 15:11:47 +00002967#if SQLITE_DEBUG
2968 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
2969 printf("CLEAR\n");
2970 }
2971#endif
drhceea3322009-04-23 13:22:42 +00002972 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2973 if( p->iReg ){
2974 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00002975 }
drhe55cbd72008-03-31 23:48:03 +00002976 }
2977}
2978
2979/*
drhda250ea2008-04-01 05:07:14 +00002980** Record the fact that an affinity change has occurred on iCount
2981** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00002982*/
drhda250ea2008-04-01 05:07:14 +00002983void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00002984 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00002985}
2986
2987/*
drhb21e7c72008-06-22 12:37:57 +00002988** Generate code to move content from registers iFrom...iFrom+nReg-1
2989** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00002990*/
drhb21e7c72008-06-22 12:37:57 +00002991void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00002992 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00002993 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00002994 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00002995}
2996
drhf49f3522009-12-30 14:12:38 +00002997#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00002998/*
drh652fbf52008-04-01 01:42:41 +00002999** Return true if any register in the range iFrom..iTo (inclusive)
3000** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00003001**
3002** This routine is used within assert() and testcase() macros only
3003** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00003004*/
3005static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
3006 int i;
drhceea3322009-04-23 13:22:42 +00003007 struct yColCache *p;
3008 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
3009 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00003010 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00003011 }
3012 return 0;
3013}
drhf49f3522009-12-30 14:12:38 +00003014#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00003015
drhbea119c2016-04-11 18:15:37 +00003016
drh652fbf52008-04-01 01:42:41 +00003017/*
drha4c3c872013-09-12 17:29:25 +00003018** Convert an expression node to a TK_REGISTER
3019*/
3020static void exprToRegister(Expr *p, int iReg){
3021 p->op2 = p->op;
3022 p->op = TK_REGISTER;
3023 p->iTable = iReg;
3024 ExprClearProperty(p, EP_Skip);
3025}
3026
dan71c57db2016-07-09 20:23:55 +00003027static void exprCodeBetween(Parse*,Expr*,int,void(*)(Parse*,Expr*,int,int),int);
3028
drha4c3c872013-09-12 17:29:25 +00003029/*
drhcce7d172000-05-31 15:34:51 +00003030** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00003031** expression. Attempt to store the results in register "target".
3032** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00003033**
drh8b213892008-08-29 02:14:02 +00003034** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00003035** be stored in target. The result might be stored in some other
3036** register if it is convenient to do so. The calling function
3037** must check the return code and move the results to the desired
3038** register.
drhcce7d172000-05-31 15:34:51 +00003039*/
drh678ccce2008-03-31 18:19:54 +00003040int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00003041 Vdbe *v = pParse->pVdbe; /* The VM under construction */
3042 int op; /* The opcode being coded */
3043 int inReg = target; /* Results stored in register inReg */
3044 int regFree1 = 0; /* If non-zero free this temporary register */
3045 int regFree2 = 0; /* If non-zero free this temporary register */
dan7b35a772016-07-28 19:47:15 +00003046 int r1, r2; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00003047 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00003048 Expr tempX; /* Temporary expression node */
dan71c57db2016-07-09 20:23:55 +00003049 int p5 = 0;
drhffe07b22005-11-03 00:41:17 +00003050
drh9cbf3422008-01-17 16:22:13 +00003051 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00003052 if( v==0 ){
3053 assert( pParse->db->mallocFailed );
3054 return 0;
3055 }
drh389a1ad2008-01-03 23:44:53 +00003056
3057 if( pExpr==0 ){
3058 op = TK_NULL;
3059 }else{
3060 op = pExpr->op;
3061 }
drhf2bc0132004-10-04 13:19:23 +00003062 switch( op ){
drh13449892005-09-07 21:22:45 +00003063 case TK_AGG_COLUMN: {
3064 AggInfo *pAggInfo = pExpr->pAggInfo;
3065 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
3066 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00003067 assert( pCol->iMem>0 );
3068 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00003069 break;
3070 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00003071 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00003072 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00003073 break;
3074 }
3075 /* Otherwise, fall thru into the TK_COLUMN case */
3076 }
drh967e8b72000-06-21 13:59:10 +00003077 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00003078 int iTab = pExpr->iTable;
3079 if( iTab<0 ){
3080 if( pParse->ckBase>0 ){
3081 /* Generating CHECK constraints or inserting into partial index */
3082 inReg = pExpr->iColumn + pParse->ckBase;
3083 break;
3084 }else{
drh1f9ca2c2015-08-25 16:57:52 +00003085 /* Coding an expression that is part of an index where column names
3086 ** in the index refer to the table to which the index belongs */
3087 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00003088 }
drh22827922000-06-06 17:27:05 +00003089 }
drhb2b9d3d2013-08-01 01:14:43 +00003090 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
3091 pExpr->iColumn, iTab, target,
3092 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00003093 break;
3094 }
3095 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00003096 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00003097 break;
3098 }
drh13573c72010-01-12 17:04:07 +00003099#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00003100 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00003101 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3102 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00003103 break;
3104 }
drh13573c72010-01-12 17:04:07 +00003105#endif
drhfec19aa2004-05-19 20:41:03 +00003106 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00003107 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00003108 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00003109 break;
3110 }
drhf0863fe2005-06-12 21:35:51 +00003111 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00003112 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00003113 break;
3114 }
danielk19775338a5f2005-01-20 13:03:10 +00003115#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00003116 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00003117 int n;
3118 const char *z;
drhca48c902008-01-18 14:08:24 +00003119 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00003120 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3121 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
3122 assert( pExpr->u.zToken[1]=='\'' );
3123 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00003124 n = sqlite3Strlen30(z) - 1;
3125 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00003126 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
3127 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00003128 break;
3129 }
danielk19775338a5f2005-01-20 13:03:10 +00003130#endif
drh50457892003-09-06 01:10:47 +00003131 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00003132 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3133 assert( pExpr->u.zToken!=0 );
3134 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00003135 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
3136 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00003137 assert( pExpr->u.zToken[0]=='?'
3138 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
3139 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00003140 }
drh50457892003-09-06 01:10:47 +00003141 break;
3142 }
drh4e0cff62004-11-05 05:10:28 +00003143 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00003144 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00003145 break;
3146 }
drh487e2622005-06-25 18:42:14 +00003147#ifndef SQLITE_OMIT_CAST
3148 case TK_CAST: {
3149 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00003150 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00003151 if( inReg!=target ){
3152 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
3153 inReg = target;
3154 }
drh4169e432014-08-25 20:11:52 +00003155 sqlite3VdbeAddOp2(v, OP_Cast, target,
3156 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00003157 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00003158 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00003159 break;
3160 }
3161#endif /* SQLITE_OMIT_CAST */
dan71c57db2016-07-09 20:23:55 +00003162 case TK_IS:
3163 case TK_ISNOT:
3164 op = (op==TK_IS) ? TK_EQ : TK_NE;
3165 p5 = SQLITE_NULLEQ;
3166 /* fall-through */
drhc9b84a12002-06-20 11:36:48 +00003167 case TK_LT:
3168 case TK_LE:
3169 case TK_GT:
3170 case TK_GE:
3171 case TK_NE:
3172 case TK_EQ: {
dan71c57db2016-07-09 20:23:55 +00003173 Expr *pLeft = pExpr->pLeft;
3174 if( (pLeft->flags & EP_Vector) ){
3175 codeVectorCompare(pParse, pExpr, target);
3176 }else{
3177 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3178 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
3179 codeCompare(pParse, pLeft, pExpr->pRight, op,
3180 r1, r2, inReg, SQLITE_STOREP2 | p5);
3181 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3182 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3183 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3184 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
3185 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
3186 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
3187 testcase( regFree1==0 );
3188 testcase( regFree2==0 );
3189 }
drh6a2fe092009-09-23 02:29:36 +00003190 break;
3191 }
drhcce7d172000-05-31 15:34:51 +00003192 case TK_AND:
3193 case TK_OR:
3194 case TK_PLUS:
3195 case TK_STAR:
3196 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00003197 case TK_REM:
3198 case TK_BITAND:
3199 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00003200 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00003201 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00003202 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00003203 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00003204 assert( TK_AND==OP_And ); testcase( op==TK_AND );
3205 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
3206 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
3207 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
3208 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
3209 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
3210 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
3211 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
3212 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
3213 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
3214 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00003215 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3216 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00003217 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003218 testcase( regFree1==0 );
3219 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00003220 break;
3221 }
drhcce7d172000-05-31 15:34:51 +00003222 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00003223 Expr *pLeft = pExpr->pLeft;
3224 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00003225 if( pLeft->op==TK_INTEGER ){
3226 codeInteger(pParse, pLeft, 1, target);
3227#ifndef SQLITE_OMIT_FLOATING_POINT
3228 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00003229 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3230 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00003231#endif
drh3c84ddf2008-01-09 02:15:38 +00003232 }else{
drh10d1edf2013-11-15 15:52:39 +00003233 tempX.op = TK_INTEGER;
3234 tempX.flags = EP_IntValue|EP_TokenOnly;
3235 tempX.u.iValue = 0;
3236 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00003237 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00003238 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00003239 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00003240 }
drh3c84ddf2008-01-09 02:15:38 +00003241 inReg = target;
3242 break;
drh6e142f52000-06-08 13:36:40 +00003243 }
drhbf4133c2001-10-13 02:59:08 +00003244 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00003245 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00003246 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
3247 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00003248 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3249 testcase( regFree1==0 );
3250 inReg = target;
3251 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00003252 break;
3253 }
3254 case TK_ISNULL:
3255 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00003256 int addr;
drh7d176102014-02-18 03:07:12 +00003257 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3258 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00003259 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00003260 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003261 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003262 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00003263 VdbeCoverageIf(v, op==TK_ISNULL);
3264 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00003265 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00003266 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00003267 break;
drhcce7d172000-05-31 15:34:51 +00003268 }
drh22827922000-06-06 17:27:05 +00003269 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003270 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00003271 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00003272 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3273 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00003274 }else{
drh9de221d2008-01-05 06:51:30 +00003275 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00003276 }
drh22827922000-06-06 17:27:05 +00003277 break;
3278 }
drhcce7d172000-05-31 15:34:51 +00003279 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00003280 ExprList *pFarg; /* List of function arguments */
3281 int nFarg; /* Number of function arguments */
3282 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00003283 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00003284 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00003285 int i; /* Loop counter */
3286 u8 enc = ENC(db); /* The text encoding used by this database */
3287 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00003288
danielk19776ab3a2e2009-02-19 14:39:25 +00003289 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00003290 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00003291 pFarg = 0;
3292 }else{
3293 pFarg = pExpr->x.pList;
3294 }
3295 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00003296 assert( !ExprHasProperty(pExpr, EP_IntValue) );
3297 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00003298 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drh2d801512016-01-14 22:19:58 +00003299 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00003300 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00003301 break;
3302 }
drhae6bb952009-11-11 00:24:31 +00003303
3304 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00003305 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00003306 ** arguments past the first non-NULL argument.
3307 */
drhd36e1042013-09-06 13:10:12 +00003308 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00003309 int endCoalesce = sqlite3VdbeMakeLabel(v);
3310 assert( nFarg>=2 );
3311 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
3312 for(i=1; i<nFarg; i++){
3313 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00003314 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00003315 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00003316 sqlite3ExprCachePush(pParse);
3317 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003318 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00003319 }
3320 sqlite3VdbeResolveLabel(v, endCoalesce);
3321 break;
3322 }
3323
drhcca9f3d2013-09-06 15:23:29 +00003324 /* The UNLIKELY() function is a no-op. The result is the value
3325 ** of the first argument.
3326 */
3327 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
3328 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00003329 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00003330 break;
3331 }
drhae6bb952009-11-11 00:24:31 +00003332
drhd1a01ed2013-11-21 16:08:52 +00003333 for(i=0; i<nFarg; i++){
3334 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00003335 testcase( i==31 );
3336 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00003337 }
3338 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
3339 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
3340 }
3341 }
drh12ffee82009-04-08 13:51:51 +00003342 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00003343 if( constMask ){
3344 r1 = pParse->nMem+1;
3345 pParse->nMem += nFarg;
3346 }else{
3347 r1 = sqlite3GetTempRange(pParse, nFarg);
3348 }
drha748fdc2012-03-28 01:34:47 +00003349
3350 /* For length() and typeof() functions with a column argument,
3351 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
3352 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
3353 ** loading.
3354 */
drhd36e1042013-09-06 13:10:12 +00003355 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003356 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003357 assert( nFarg==1 );
3358 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003359 exprOp = pFarg->a[0].pExpr->op;
3360 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003361 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3362 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003363 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3364 pFarg->a[0].pExpr->op2 =
3365 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003366 }
3367 }
3368
drhd7d385d2009-09-03 01:18:00 +00003369 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003370 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003371 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003372 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003373 }else{
drh12ffee82009-04-08 13:51:51 +00003374 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003375 }
drhb7f6f682006-07-08 17:06:43 +00003376#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003377 /* Possibly overload the function if the first argument is
3378 ** a virtual table column.
3379 **
3380 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3381 ** second argument, not the first, as the argument to test to
3382 ** see if it is a column in a virtual table. This is done because
3383 ** the left operand of infix functions (the operand we want to
3384 ** control overloading) ends up as the second argument to the
3385 ** function. The expression "A glob B" is equivalent to
3386 ** "glob(B,A). We want to use the A in "A glob B" to test
3387 ** for function overloading. But we use the B term in "glob(B,A)".
3388 */
drh12ffee82009-04-08 13:51:51 +00003389 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3390 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3391 }else if( nFarg>0 ){
3392 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003393 }
3394#endif
drhd36e1042013-09-06 13:10:12 +00003395 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003396 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003397 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003398 }
drh9c7c9132015-06-26 18:16:52 +00003399 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003400 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003401 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003402 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003403 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003404 }
drhcce7d172000-05-31 15:34:51 +00003405 break;
3406 }
drhfe2093d2005-01-20 22:48:47 +00003407#ifndef SQLITE_OMIT_SUBQUERY
3408 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003409 case TK_SELECT: {
dan8da209b2016-07-26 18:06:08 +00003410 int nCol;
drhc5499be2008-04-01 15:06:33 +00003411 testcase( op==TK_EXISTS );
3412 testcase( op==TK_SELECT );
dan8da209b2016-07-26 18:06:08 +00003413 if( op==TK_SELECT && (nCol = pExpr->x.pSelect->pEList->nExpr)!=1 ){
3414 sqlite3SubselectError(pParse, nCol, 1);
3415 }else{
3416 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
3417 }
drh19a775c2000-06-05 18:54:46 +00003418 break;
3419 }
drhfef52082000-06-06 01:50:43 +00003420 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003421 int destIfFalse = sqlite3VdbeMakeLabel(v);
3422 int destIfNull = sqlite3VdbeMakeLabel(v);
3423 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3424 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3425 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3426 sqlite3VdbeResolveLabel(v, destIfFalse);
3427 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3428 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003429 break;
3430 }
drhe3365e62009-11-12 17:52:24 +00003431#endif /* SQLITE_OMIT_SUBQUERY */
3432
3433
drh2dcef112008-01-12 19:03:48 +00003434 /*
3435 ** x BETWEEN y AND z
3436 **
3437 ** This is equivalent to
3438 **
3439 ** x>=y AND x<=z
3440 **
3441 ** X is stored in pExpr->pLeft.
3442 ** Y is stored in pExpr->pList->a[0].pExpr.
3443 ** Z is stored in pExpr->pList->a[1].pExpr.
3444 */
drhfef52082000-06-06 01:50:43 +00003445 case TK_BETWEEN: {
dan71c57db2016-07-09 20:23:55 +00003446 exprCodeBetween(pParse, pExpr, target, 0, 0);
drhfef52082000-06-06 01:50:43 +00003447 break;
3448 }
drh94fa9c42016-02-27 21:16:04 +00003449 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003450 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003451 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003452 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003453 break;
3454 }
drh2dcef112008-01-12 19:03:48 +00003455
dan165921a2009-08-28 18:53:45 +00003456 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003457 /* If the opcode is TK_TRIGGER, then the expression is a reference
3458 ** to a column in the new.* or old.* pseudo-tables available to
3459 ** trigger programs. In this case Expr.iTable is set to 1 for the
3460 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3461 ** is set to the column of the pseudo-table to read, or to -1 to
3462 ** read the rowid field.
3463 **
3464 ** The expression is implemented using an OP_Param opcode. The p1
3465 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3466 ** to reference another column of the old.* pseudo-table, where
3467 ** i is the index of the column. For a new.rowid reference, p1 is
3468 ** set to (n+1), where n is the number of columns in each pseudo-table.
3469 ** For a reference to any other column in the new.* pseudo-table, p1
3470 ** is set to (n+2+i), where n and i are as defined previously. For
3471 ** example, if the table on which triggers are being fired is
3472 ** declared as:
3473 **
3474 ** CREATE TABLE t1(a, b);
3475 **
3476 ** Then p1 is interpreted as follows:
3477 **
3478 ** p1==0 -> old.rowid p1==3 -> new.rowid
3479 ** p1==1 -> old.a p1==4 -> new.a
3480 ** p1==2 -> old.b p1==5 -> new.b
3481 */
dan2832ad42009-08-31 15:27:27 +00003482 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003483 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3484
3485 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3486 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3487 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3488 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3489
3490 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003491 VdbeComment((v, "%s.%s -> $%d",
3492 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003493 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003494 target
dan165921a2009-08-28 18:53:45 +00003495 ));
dan65a7cd12009-09-01 12:16:01 +00003496
drh44dbca82010-01-13 04:22:20 +00003497#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003498 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003499 ** integer. Use OP_RealAffinity to make sure it is really real.
3500 **
3501 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3502 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003503 if( pExpr->iColumn>=0
3504 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3505 ){
3506 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3507 }
drh44dbca82010-01-13 04:22:20 +00003508#endif
dan165921a2009-08-28 18:53:45 +00003509 break;
3510 }
3511
dan71c57db2016-07-09 20:23:55 +00003512 case TK_VECTOR: {
dand49fd4e2016-07-27 19:33:04 +00003513 sqlite3ErrorMsg(pParse, "invalid use of row value");
dan71c57db2016-07-09 20:23:55 +00003514 break;
3515 }
3516
drh2dcef112008-01-12 19:03:48 +00003517 /*
3518 ** Form A:
3519 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3520 **
3521 ** Form B:
3522 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3523 **
3524 ** Form A is can be transformed into the equivalent form B as follows:
3525 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3526 ** WHEN x=eN THEN rN ELSE y END
3527 **
3528 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003529 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3530 ** odd. The Y is also optional. If the number of elements in x.pList
3531 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003532 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3533 **
3534 ** The result of the expression is the Ri for the first matching Ei,
3535 ** or if there is no matching Ei, the ELSE term Y, or if there is
3536 ** no ELSE term, NULL.
3537 */
drh33cd4902009-05-30 20:49:20 +00003538 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003539 int endLabel; /* GOTO label for end of CASE stmt */
3540 int nextCase; /* GOTO label for next WHEN clause */
3541 int nExpr; /* 2x number of WHEN terms */
3542 int i; /* Loop counter */
3543 ExprList *pEList; /* List of WHEN terms */
3544 struct ExprList_item *aListelem; /* Array of WHEN terms */
3545 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003546 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003547 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003548 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003549
danielk19776ab3a2e2009-02-19 14:39:25 +00003550 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003551 assert(pExpr->x.pList->nExpr > 0);
3552 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003553 aListelem = pEList->a;
3554 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003555 endLabel = sqlite3VdbeMakeLabel(v);
3556 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003557 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003558 testcase( pX->op==TK_COLUMN );
drh10d1edf2013-11-15 15:52:39 +00003559 exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003560 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003561 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003562 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003563 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003564 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3565 ** The value in regFree1 might get SCopy-ed into the file result.
3566 ** So make sure that the regFree1 register is not reused for other
3567 ** purposes and possibly overwritten. */
3568 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003569 }
drhc5cd1242013-09-12 16:50:49 +00003570 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003571 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003572 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003573 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003574 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003575 }else{
drh2dcef112008-01-12 19:03:48 +00003576 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003577 }
drh2dcef112008-01-12 19:03:48 +00003578 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003579 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003580 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003581 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003582 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003583 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003584 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003585 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003586 }
drhc5cd1242013-09-12 16:50:49 +00003587 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003588 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003589 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003590 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003591 }else{
drh9de221d2008-01-05 06:51:30 +00003592 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003593 }
danielk1977c1f4a192009-04-28 12:08:15 +00003594 assert( db->mallocFailed || pParse->nErr>0
3595 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003596 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003597 break;
3598 }
danielk19775338a5f2005-01-20 13:03:10 +00003599#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003600 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003601 assert( pExpr->affinity==OE_Rollback
3602 || pExpr->affinity==OE_Abort
3603 || pExpr->affinity==OE_Fail
3604 || pExpr->affinity==OE_Ignore
3605 );
dane0af83a2009-09-08 19:15:01 +00003606 if( !pParse->pTriggerTab ){
3607 sqlite3ErrorMsg(pParse,
3608 "RAISE() may only be used within a trigger-program");
3609 return 0;
3610 }
3611 if( pExpr->affinity==OE_Abort ){
3612 sqlite3MayAbort(pParse);
3613 }
dan165921a2009-08-28 18:53:45 +00003614 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003615 if( pExpr->affinity==OE_Ignore ){
3616 sqlite3VdbeAddOp4(
3617 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003618 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003619 }else{
drh433dccf2013-02-09 15:37:11 +00003620 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003621 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003622 }
3623
drhffe07b22005-11-03 00:41:17 +00003624 break;
drh17a7f8d2002-03-24 13:13:27 +00003625 }
danielk19775338a5f2005-01-20 13:03:10 +00003626#endif
drhffe07b22005-11-03 00:41:17 +00003627 }
drh2dcef112008-01-12 19:03:48 +00003628 sqlite3ReleaseTempReg(pParse, regFree1);
3629 sqlite3ReleaseTempReg(pParse, regFree2);
3630 return inReg;
3631}
3632
3633/*
drhd1a01ed2013-11-21 16:08:52 +00003634** Factor out the code of the given expression to initialization time.
3635*/
drhd673cdd2013-11-21 21:23:31 +00003636void sqlite3ExprCodeAtInit(
3637 Parse *pParse, /* Parsing context */
3638 Expr *pExpr, /* The expression to code when the VDBE initializes */
3639 int regDest, /* Store the value in this register */
3640 u8 reusable /* True if this expression is reusable */
3641){
drhd1a01ed2013-11-21 16:08:52 +00003642 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003643 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003644 p = pParse->pConstExpr;
3645 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3646 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003647 if( p ){
3648 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3649 pItem->u.iConstExprReg = regDest;
3650 pItem->reusable = reusable;
3651 }
drhd1a01ed2013-11-21 16:08:52 +00003652 pParse->pConstExpr = p;
3653}
3654
3655/*
drh2dcef112008-01-12 19:03:48 +00003656** Generate code to evaluate an expression and store the results
3657** into a register. Return the register number where the results
3658** are stored.
3659**
3660** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003661** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003662** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003663**
3664** If pExpr is a constant, then this routine might generate this
3665** code to fill the register in the initialization section of the
3666** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003667*/
3668int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003669 int r2;
3670 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003671 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003672 && pExpr->op!=TK_REGISTER
3673 && sqlite3ExprIsConstantNotJoin(pExpr)
3674 ){
3675 ExprList *p = pParse->pConstExpr;
3676 int i;
3677 *pReg = 0;
3678 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003679 struct ExprList_item *pItem;
3680 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3681 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3682 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003683 }
3684 }
3685 }
drhf30a9692013-11-15 01:10:18 +00003686 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003687 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003688 }else{
drhf30a9692013-11-15 01:10:18 +00003689 int r1 = sqlite3GetTempReg(pParse);
3690 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3691 if( r2==r1 ){
3692 *pReg = r1;
3693 }else{
3694 sqlite3ReleaseTempReg(pParse, r1);
3695 *pReg = 0;
3696 }
drh2dcef112008-01-12 19:03:48 +00003697 }
3698 return r2;
3699}
3700
3701/*
3702** Generate code that will evaluate expression pExpr and store the
3703** results in register target. The results are guaranteed to appear
3704** in register target.
3705*/
drh05a86c52014-02-16 01:55:49 +00003706void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00003707 int inReg;
3708
3709 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00003710 if( pExpr && pExpr->op==TK_REGISTER ){
3711 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3712 }else{
3713 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00003714 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00003715 if( inReg!=target && pParse->pVdbe ){
3716 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
3717 }
drhcce7d172000-05-31 15:34:51 +00003718 }
drhcce7d172000-05-31 15:34:51 +00003719}
3720
3721/*
drh1c75c9d2015-12-21 15:22:13 +00003722** Make a transient copy of expression pExpr and then code it using
3723** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
3724** except that the input expression is guaranteed to be unchanged.
3725*/
3726void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
3727 sqlite3 *db = pParse->db;
3728 pExpr = sqlite3ExprDup(db, pExpr, 0);
3729 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
3730 sqlite3ExprDelete(db, pExpr);
3731}
3732
3733/*
drh05a86c52014-02-16 01:55:49 +00003734** Generate code that will evaluate expression pExpr and store the
3735** results in register target. The results are guaranteed to appear
3736** in register target. If the expression is constant, then this routine
3737** might choose to code the expression at initialization time.
3738*/
3739void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
3740 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
3741 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
3742 }else{
3743 sqlite3ExprCode(pParse, pExpr, target);
3744 }
drhcce7d172000-05-31 15:34:51 +00003745}
3746
3747/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003748** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00003749** in register target.
drh25303782004-12-07 15:41:48 +00003750**
drh2dcef112008-01-12 19:03:48 +00003751** Also make a copy of the expression results into another "cache" register
3752** and modify the expression so that the next time it is evaluated,
3753** the result is a copy of the cache register.
3754**
3755** This routine is used for expressions that are used multiple
3756** times. They are evaluated once and the results of the expression
3757** are reused.
drh25303782004-12-07 15:41:48 +00003758*/
drh05a86c52014-02-16 01:55:49 +00003759void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00003760 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00003761 int iMem;
3762
drhde4fcfd2008-01-19 23:50:26 +00003763 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00003764 assert( pExpr->op!=TK_REGISTER );
3765 sqlite3ExprCode(pParse, pExpr, target);
3766 iMem = ++pParse->nMem;
3767 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
3768 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00003769}
drh2dcef112008-01-12 19:03:48 +00003770
drh678ccce2008-03-31 18:19:54 +00003771/*
drh268380c2004-02-25 13:47:31 +00003772** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00003773** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00003774**
drh892d3172008-01-10 03:46:36 +00003775** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00003776**
3777** The SQLITE_ECEL_DUP flag prevents the arguments from being
3778** filled using OP_SCopy. OP_Copy must be used instead.
3779**
3780** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
3781** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00003782**
3783** The SQLITE_ECEL_REF flag means that expressions in the list with
3784** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
3785** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00003786*/
danielk19774adee202004-05-08 08:23:19 +00003787int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00003788 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00003789 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00003790 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00003791 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00003792 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00003793){
3794 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00003795 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00003796 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00003797 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00003798 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00003799 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00003800 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00003801 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00003802 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00003803 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00003804 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00003805 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
3806 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
3807 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00003808 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00003809 }else{
3810 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3811 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00003812 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00003813 if( copyOp==OP_Copy
3814 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
3815 && pOp->p1+pOp->p3+1==inReg
3816 && pOp->p2+pOp->p3+1==target+i
3817 ){
3818 pOp->p3++;
3819 }else{
3820 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
3821 }
drhd1a01ed2013-11-21 16:08:52 +00003822 }
drhd1766112008-09-17 00:13:12 +00003823 }
drh268380c2004-02-25 13:47:31 +00003824 }
drhf9b596e2004-05-26 16:54:42 +00003825 return n;
drh268380c2004-02-25 13:47:31 +00003826}
3827
3828/*
drh36c563a2009-11-12 13:32:22 +00003829** Generate code for a BETWEEN operator.
3830**
3831** x BETWEEN y AND z
3832**
3833** The above is equivalent to
3834**
3835** x>=y AND x<=z
3836**
3837** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00003838** elimination of x.
drh36c563a2009-11-12 13:32:22 +00003839*/
3840static void exprCodeBetween(
3841 Parse *pParse, /* Parsing and code generating context */
3842 Expr *pExpr, /* The BETWEEN expression */
3843 int dest, /* Jump here if the jump is taken */
dan71c57db2016-07-09 20:23:55 +00003844 void (*xJumpIf)(Parse*,Expr*,int,int),
drh36c563a2009-11-12 13:32:22 +00003845 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
3846){
3847 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
3848 Expr compLeft; /* The x>=y term */
3849 Expr compRight; /* The x<=z term */
3850 Expr exprX; /* The x subexpression */
3851 int regFree1 = 0; /* Temporary use register */
3852
dan71c57db2016-07-09 20:23:55 +00003853 memset(&compLeft, 0, sizeof(Expr));
3854 memset(&compRight, 0, sizeof(Expr));
3855 memset(&exprAnd, 0, sizeof(Expr));
3856
drh36c563a2009-11-12 13:32:22 +00003857 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3858 exprX = *pExpr->pLeft;
3859 exprAnd.op = TK_AND;
3860 exprAnd.pLeft = &compLeft;
3861 exprAnd.pRight = &compRight;
3862 compLeft.op = TK_GE;
3863 compLeft.pLeft = &exprX;
3864 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
3865 compRight.op = TK_LE;
3866 compRight.pLeft = &exprX;
3867 compRight.pRight = pExpr->x.pList->a[1].pExpr;
dan71c57db2016-07-09 20:23:55 +00003868 if( (exprX.flags & EP_Vector)==0 ){
3869 exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
3870 }
3871 if( xJumpIf ){
3872 xJumpIf(pParse, &exprAnd, dest, jumpIfNull);
drh36c563a2009-11-12 13:32:22 +00003873 }else{
dan71c57db2016-07-09 20:23:55 +00003874 exprX.flags |= EP_FromJoin;
3875 sqlite3ExprCodeTarget(pParse, &exprAnd, dest);
drh36c563a2009-11-12 13:32:22 +00003876 }
3877 sqlite3ReleaseTempReg(pParse, regFree1);
3878
3879 /* Ensure adequate test coverage */
3880 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
3881 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
3882 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
3883 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
3884 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
3885 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
3886 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
3887 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
3888}
3889
3890/*
drhcce7d172000-05-31 15:34:51 +00003891** Generate code for a boolean expression such that a jump is made
3892** to the label "dest" if the expression is true but execution
3893** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00003894**
3895** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00003896** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00003897**
3898** This code depends on the fact that certain token values (ex: TK_EQ)
3899** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3900** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
3901** the make process cause these values to align. Assert()s in the code
3902** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00003903*/
danielk19774adee202004-05-08 08:23:19 +00003904void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00003905 Vdbe *v = pParse->pVdbe;
3906 int op = 0;
drh2dcef112008-01-12 19:03:48 +00003907 int regFree1 = 0;
3908 int regFree2 = 0;
3909 int r1, r2;
3910
drh35573352008-01-08 23:54:25 +00003911 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00003912 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00003913 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00003914 op = pExpr->op;
dan7b35a772016-07-28 19:47:15 +00003915 switch( op ){
drhcce7d172000-05-31 15:34:51 +00003916 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00003917 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00003918 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00003919 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00003920 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00003921 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3922 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00003923 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00003924 break;
3925 }
3926 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00003927 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00003928 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00003929 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00003930 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00003931 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00003932 break;
3933 }
3934 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00003935 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00003936 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00003937 break;
3938 }
drhde845c22016-03-17 19:07:52 +00003939 case TK_IS:
3940 case TK_ISNOT:
3941 testcase( op==TK_IS );
3942 testcase( op==TK_ISNOT );
3943 op = (op==TK_IS) ? TK_EQ : TK_NE;
3944 jumpIfNull = SQLITE_NULLEQ;
3945 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00003946 case TK_LT:
3947 case TK_LE:
3948 case TK_GT:
3949 case TK_GE:
3950 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00003951 case TK_EQ: {
dan7b35a772016-07-28 19:47:15 +00003952 if( pExpr->pLeft->flags & EP_Vector ) goto default_expr;
drhc5499be2008-04-01 15:06:33 +00003953 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00003954 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3955 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00003956 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00003957 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00003958 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3959 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3960 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3961 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00003962 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
3963 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
3964 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
3965 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
3966 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
3967 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00003968 testcase( regFree1==0 );
3969 testcase( regFree2==0 );
3970 break;
3971 }
drhcce7d172000-05-31 15:34:51 +00003972 case TK_ISNULL:
3973 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00003974 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3975 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00003976 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3977 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00003978 VdbeCoverageIf(v, op==TK_ISNULL);
3979 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00003980 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00003981 break;
3982 }
drhfef52082000-06-06 01:50:43 +00003983 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00003984 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00003985 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfTrue, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00003986 break;
3987 }
drh84e30ca2011-02-10 17:46:14 +00003988#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00003989 case TK_IN: {
3990 int destIfFalse = sqlite3VdbeMakeLabel(v);
3991 int destIfNull = jumpIfNull ? dest : destIfFalse;
3992 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00003993 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00003994 sqlite3VdbeResolveLabel(v, destIfFalse);
3995 break;
3996 }
shanehbb201342011-02-09 19:55:20 +00003997#endif
drhcce7d172000-05-31 15:34:51 +00003998 default: {
dan7b35a772016-07-28 19:47:15 +00003999 default_expr:
drh991a1982014-01-02 17:57:16 +00004000 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004001 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004002 }else if( exprAlwaysFalse(pExpr) ){
4003 /* No-op */
4004 }else{
4005 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4006 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004007 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004008 testcase( regFree1==0 );
4009 testcase( jumpIfNull==0 );
4010 }
drhcce7d172000-05-31 15:34:51 +00004011 break;
4012 }
4013 }
drh2dcef112008-01-12 19:03:48 +00004014 sqlite3ReleaseTempReg(pParse, regFree1);
4015 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004016}
4017
4018/*
drh66b89c82000-11-28 20:47:17 +00004019** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00004020** to the label "dest" if the expression is false but execution
4021** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00004022**
4023** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00004024** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
4025** is 0.
drhcce7d172000-05-31 15:34:51 +00004026*/
danielk19774adee202004-05-08 08:23:19 +00004027void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00004028 Vdbe *v = pParse->pVdbe;
4029 int op = 0;
drh2dcef112008-01-12 19:03:48 +00004030 int regFree1 = 0;
4031 int regFree2 = 0;
4032 int r1, r2;
4033
drh35573352008-01-08 23:54:25 +00004034 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00004035 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00004036 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00004037
4038 /* The value of pExpr->op and op are related as follows:
4039 **
4040 ** pExpr->op op
4041 ** --------- ----------
4042 ** TK_ISNULL OP_NotNull
4043 ** TK_NOTNULL OP_IsNull
4044 ** TK_NE OP_Eq
4045 ** TK_EQ OP_Ne
4046 ** TK_GT OP_Le
4047 ** TK_LE OP_Gt
4048 ** TK_GE OP_Lt
4049 ** TK_LT OP_Ge
4050 **
4051 ** For other values of pExpr->op, op is undefined and unused.
4052 ** The value of TK_ and OP_ constants are arranged such that we
4053 ** can compute the mapping above using the following expression.
4054 ** Assert()s verify that the computation is correct.
4055 */
4056 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
4057
4058 /* Verify correct alignment of TK_ and OP_ constants
4059 */
4060 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
4061 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
4062 assert( pExpr->op!=TK_NE || op==OP_Eq );
4063 assert( pExpr->op!=TK_EQ || op==OP_Ne );
4064 assert( pExpr->op!=TK_LT || op==OP_Ge );
4065 assert( pExpr->op!=TK_LE || op==OP_Gt );
4066 assert( pExpr->op!=TK_GT || op==OP_Le );
4067 assert( pExpr->op!=TK_GE || op==OP_Lt );
4068
danba00e302016-07-23 20:24:06 +00004069 switch( pExpr->op ){
drhcce7d172000-05-31 15:34:51 +00004070 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00004071 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004072 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00004073 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004074 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00004075 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004076 break;
4077 }
4078 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00004079 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00004080 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00004081 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00004082 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00004083 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
4084 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00004085 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00004086 break;
4087 }
4088 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00004089 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00004090 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00004091 break;
4092 }
drhde845c22016-03-17 19:07:52 +00004093 case TK_IS:
4094 case TK_ISNOT:
4095 testcase( pExpr->op==TK_IS );
4096 testcase( pExpr->op==TK_ISNOT );
4097 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
4098 jumpIfNull = SQLITE_NULLEQ;
4099 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00004100 case TK_LT:
4101 case TK_LE:
4102 case TK_GT:
4103 case TK_GE:
4104 case TK_NE:
4105 case TK_EQ: {
danba00e302016-07-23 20:24:06 +00004106 if( pExpr->pLeft->flags & EP_Vector ) goto default_expr;
4107
drhc5499be2008-04-01 15:06:33 +00004108 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00004109 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4110 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00004111 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00004112 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00004113 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
4114 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
4115 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
4116 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00004117 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
4118 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
4119 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
4120 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
4121 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
4122 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00004123 testcase( regFree1==0 );
4124 testcase( regFree2==0 );
4125 break;
4126 }
drhcce7d172000-05-31 15:34:51 +00004127 case TK_ISNULL:
4128 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00004129 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
4130 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00004131 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
4132 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00004133 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00004134 break;
4135 }
drhfef52082000-06-06 01:50:43 +00004136 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00004137 testcase( jumpIfNull==0 );
dan71c57db2016-07-09 20:23:55 +00004138 exprCodeBetween(pParse, pExpr, dest, sqlite3ExprIfFalse, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00004139 break;
4140 }
drh84e30ca2011-02-10 17:46:14 +00004141#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00004142 case TK_IN: {
4143 if( jumpIfNull ){
4144 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
4145 }else{
4146 int destIfNull = sqlite3VdbeMakeLabel(v);
4147 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
4148 sqlite3VdbeResolveLabel(v, destIfNull);
4149 }
4150 break;
4151 }
shanehbb201342011-02-09 19:55:20 +00004152#endif
drhcce7d172000-05-31 15:34:51 +00004153 default: {
danba00e302016-07-23 20:24:06 +00004154 default_expr:
drh991a1982014-01-02 17:57:16 +00004155 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00004156 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00004157 }else if( exprAlwaysTrue(pExpr) ){
4158 /* no-op */
4159 }else{
4160 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
4161 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00004162 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00004163 testcase( regFree1==0 );
4164 testcase( jumpIfNull==0 );
4165 }
drhcce7d172000-05-31 15:34:51 +00004166 break;
4167 }
4168 }
drh2dcef112008-01-12 19:03:48 +00004169 sqlite3ReleaseTempReg(pParse, regFree1);
4170 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00004171}
drh22827922000-06-06 17:27:05 +00004172
4173/*
drh72bc8202015-06-11 13:58:35 +00004174** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
4175** code generation, and that copy is deleted after code generation. This
4176** ensures that the original pExpr is unchanged.
4177*/
4178void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
4179 sqlite3 *db = pParse->db;
4180 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
4181 if( db->mallocFailed==0 ){
4182 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
4183 }
4184 sqlite3ExprDelete(db, pCopy);
4185}
4186
4187
4188/*
drh1d9da702010-01-07 15:17:02 +00004189** Do a deep comparison of two expression trees. Return 0 if the two
4190** expressions are completely identical. Return 1 if they differ only
4191** by a COLLATE operator at the top level. Return 2 if there are differences
4192** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00004193**
drh619a1302013-08-01 13:04:46 +00004194** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4195** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4196**
drh66518ca2013-08-01 15:09:57 +00004197** The pA side might be using TK_REGISTER. If that is the case and pB is
4198** not using TK_REGISTER but is otherwise equivalent, then still return 0.
4199**
drh1d9da702010-01-07 15:17:02 +00004200** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00004201** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00004202** identical, we return 2 just to be safe. So if this routine
4203** returns 2, then you do not really know for certain if the two
4204** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00004205** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00004206** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00004207** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00004208** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00004209*/
drh619a1302013-08-01 13:04:46 +00004210int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00004211 u32 combinedFlags;
4212 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00004213 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00004214 }
drh10d1edf2013-11-15 15:52:39 +00004215 combinedFlags = pA->flags | pB->flags;
4216 if( combinedFlags & EP_IntValue ){
4217 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
4218 return 0;
4219 }
drh1d9da702010-01-07 15:17:02 +00004220 return 2;
drh22827922000-06-06 17:27:05 +00004221 }
drhc2acc4e2013-11-15 18:15:19 +00004222 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00004223 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004224 return 1;
4225 }
drh619a1302013-08-01 13:04:46 +00004226 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00004227 return 1;
4228 }
4229 return 2;
4230 }
drh2edc5fd2015-11-24 02:10:52 +00004231 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00004232 if( pA->op==TK_FUNCTION ){
4233 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
4234 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00004235 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00004236 }
drh22827922000-06-06 17:27:05 +00004237 }
drh10d1edf2013-11-15 15:52:39 +00004238 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00004239 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00004240 if( combinedFlags & EP_xIsSelect ) return 2;
4241 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
4242 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
4243 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00004244 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00004245 if( pA->iColumn!=pB->iColumn ) return 2;
4246 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00004247 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00004248 }
4249 }
drh1d9da702010-01-07 15:17:02 +00004250 return 0;
drh22827922000-06-06 17:27:05 +00004251}
4252
drh8c6f6662010-04-26 19:17:26 +00004253/*
4254** Compare two ExprList objects. Return 0 if they are identical and
4255** non-zero if they differ in any way.
4256**
drh619a1302013-08-01 13:04:46 +00004257** If any subelement of pB has Expr.iTable==(-1) then it is allowed
4258** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
4259**
drh8c6f6662010-04-26 19:17:26 +00004260** This routine might return non-zero for equivalent ExprLists. The
4261** only consequence will be disabled optimizations. But this routine
4262** must never return 0 if the two ExprList objects are different, or
4263** a malfunction will result.
4264**
4265** Two NULL pointers are considered to be the same. But a NULL pointer
4266** always differs from a non-NULL pointer.
4267*/
drh619a1302013-08-01 13:04:46 +00004268int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00004269 int i;
4270 if( pA==0 && pB==0 ) return 0;
4271 if( pA==0 || pB==0 ) return 1;
4272 if( pA->nExpr!=pB->nExpr ) return 1;
4273 for(i=0; i<pA->nExpr; i++){
4274 Expr *pExprA = pA->a[i].pExpr;
4275 Expr *pExprB = pB->a[i].pExpr;
4276 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00004277 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00004278 }
4279 return 0;
4280}
drh13449892005-09-07 21:22:45 +00004281
drh22827922000-06-06 17:27:05 +00004282/*
drh4bd5f732013-07-31 23:22:39 +00004283** Return true if we can prove the pE2 will always be true if pE1 is
4284** true. Return false if we cannot complete the proof or if pE2 might
4285** be false. Examples:
4286**
drh619a1302013-08-01 13:04:46 +00004287** pE1: x==5 pE2: x==5 Result: true
4288** pE1: x>0 pE2: x==5 Result: false
4289** pE1: x=21 pE2: x=21 OR y=43 Result: true
4290** pE1: x!=123 pE2: x IS NOT NULL Result: true
4291** pE1: x!=?1 pE2: x IS NOT NULL Result: true
4292** pE1: x IS NULL pE2: x IS NOT NULL Result: false
4293** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00004294**
4295** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
4296** Expr.iTable<0 then assume a table number given by iTab.
4297**
4298** When in doubt, return false. Returning true might give a performance
4299** improvement. Returning false might cause a performance reduction, but
4300** it will always give the correct answer and is hence always safe.
4301*/
4302int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00004303 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
4304 return 1;
4305 }
4306 if( pE2->op==TK_OR
4307 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
4308 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
4309 ){
4310 return 1;
4311 }
4312 if( pE2->op==TK_NOTNULL
4313 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
4314 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
4315 ){
4316 return 1;
4317 }
4318 return 0;
drh4bd5f732013-07-31 23:22:39 +00004319}
4320
4321/*
drh030796d2012-08-23 16:18:10 +00004322** An instance of the following structure is used by the tree walker
drh2409f8a2016-07-27 18:27:02 +00004323** to determine if an expression can be evaluated by reference to the
4324** index only, without having to do a search for the corresponding
4325** table entry. The IdxCover.pIdx field is the index. IdxCover.iCur
4326** is the cursor for the table.
4327*/
4328struct IdxCover {
4329 Index *pIdx; /* The index to be tested for coverage */
4330 int iCur; /* Cursor number for the table corresponding to the index */
4331};
4332
4333/*
4334** Check to see if there are references to columns in table
4335** pWalker->u.pIdxCover->iCur can be satisfied using the index
4336** pWalker->u.pIdxCover->pIdx.
4337*/
4338static int exprIdxCover(Walker *pWalker, Expr *pExpr){
4339 if( pExpr->op==TK_COLUMN
4340 && pExpr->iTable==pWalker->u.pIdxCover->iCur
4341 && sqlite3ColumnOfIndex(pWalker->u.pIdxCover->pIdx, pExpr->iColumn)<0
4342 ){
4343 pWalker->eCode = 1;
4344 return WRC_Abort;
4345 }
4346 return WRC_Continue;
4347}
4348
4349/*
drhe604ec02016-07-27 19:20:58 +00004350** Determine if an index pIdx on table with cursor iCur contains will
4351** the expression pExpr. Return true if the index does cover the
4352** expression and false if the pExpr expression references table columns
4353** that are not found in the index pIdx.
drh2409f8a2016-07-27 18:27:02 +00004354**
4355** An index covering an expression means that the expression can be
4356** evaluated using only the index and without having to lookup the
4357** corresponding table entry.
4358*/
4359int sqlite3ExprCoveredByIndex(
4360 Expr *pExpr, /* The index to be tested */
4361 int iCur, /* The cursor number for the corresponding table */
4362 Index *pIdx /* The index that might be used for coverage */
4363){
4364 Walker w;
4365 struct IdxCover xcov;
4366 memset(&w, 0, sizeof(w));
4367 xcov.iCur = iCur;
4368 xcov.pIdx = pIdx;
4369 w.xExprCallback = exprIdxCover;
4370 w.u.pIdxCover = &xcov;
4371 sqlite3WalkExpr(&w, pExpr);
4372 return !w.eCode;
4373}
4374
4375
4376/*
4377** An instance of the following structure is used by the tree walker
drh030796d2012-08-23 16:18:10 +00004378** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00004379** aggregate function, in order to implement the
4380** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00004381*/
drh030796d2012-08-23 16:18:10 +00004382struct SrcCount {
4383 SrcList *pSrc; /* One particular FROM clause in a nested query */
4384 int nThis; /* Number of references to columns in pSrcList */
4385 int nOther; /* Number of references to columns in other FROM clauses */
4386};
4387
4388/*
4389** Count the number of references to columns.
4390*/
4391static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00004392 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
4393 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
4394 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
4395 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
4396 ** NEVER() will need to be removed. */
4397 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00004398 int i;
drh030796d2012-08-23 16:18:10 +00004399 struct SrcCount *p = pWalker->u.pSrcCount;
4400 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00004401 int nSrc = pSrc ? pSrc->nSrc : 0;
4402 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00004403 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00004404 }
drh655814d2015-01-09 01:27:29 +00004405 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00004406 p->nThis++;
4407 }else{
4408 p->nOther++;
4409 }
drh374fdce2012-04-17 16:38:53 +00004410 }
drh030796d2012-08-23 16:18:10 +00004411 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004412}
4413
4414/*
drh030796d2012-08-23 16:18:10 +00004415** Determine if any of the arguments to the pExpr Function reference
4416** pSrcList. Return true if they do. Also return true if the function
4417** has no arguments or has only constant arguments. Return false if pExpr
4418** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004419*/
drh030796d2012-08-23 16:18:10 +00004420int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004421 Walker w;
drh030796d2012-08-23 16:18:10 +00004422 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004423 assert( pExpr->op==TK_AGG_FUNCTION );
4424 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004425 w.xExprCallback = exprSrcCount;
4426 w.u.pSrcCount = &cnt;
4427 cnt.pSrc = pSrcList;
4428 cnt.nThis = 0;
4429 cnt.nOther = 0;
4430 sqlite3WalkExprList(&w, pExpr->x.pList);
4431 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004432}
4433
4434/*
drh13449892005-09-07 21:22:45 +00004435** Add a new element to the pAggInfo->aCol[] array. Return the index of
4436** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004437*/
drh17435752007-08-16 04:30:38 +00004438static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004439 int i;
drhcf643722007-03-27 13:36:37 +00004440 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004441 db,
drhcf643722007-03-27 13:36:37 +00004442 pInfo->aCol,
4443 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004444 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004445 &i
4446 );
drh13449892005-09-07 21:22:45 +00004447 return i;
4448}
4449
4450/*
4451** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4452** the new element. Return a negative number if malloc fails.
4453*/
drh17435752007-08-16 04:30:38 +00004454static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004455 int i;
drhcf643722007-03-27 13:36:37 +00004456 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004457 db,
drhcf643722007-03-27 13:36:37 +00004458 pInfo->aFunc,
4459 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004460 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004461 &i
4462 );
drh13449892005-09-07 21:22:45 +00004463 return i;
4464}
drh22827922000-06-06 17:27:05 +00004465
4466/*
drh7d10d5a2008-08-20 16:35:10 +00004467** This is the xExprCallback for a tree walker. It is used to
4468** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004469** for additional information.
drh22827922000-06-06 17:27:05 +00004470*/
drh7d10d5a2008-08-20 16:35:10 +00004471static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004472 int i;
drh7d10d5a2008-08-20 16:35:10 +00004473 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004474 Parse *pParse = pNC->pParse;
4475 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004476 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004477
drh22827922000-06-06 17:27:05 +00004478 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004479 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004480 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004481 testcase( pExpr->op==TK_AGG_COLUMN );
4482 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004483 /* Check to see if the column is in one of the tables in the FROM
4484 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004485 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004486 struct SrcList_item *pItem = pSrcList->a;
4487 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4488 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004489 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004490 if( pExpr->iTable==pItem->iCursor ){
4491 /* If we reach this point, it means that pExpr refers to a table
4492 ** that is in the FROM clause of the aggregate query.
4493 **
4494 ** Make an entry for the column in pAggInfo->aCol[] if there
4495 ** is not an entry there already.
4496 */
drh7f906d62007-03-12 23:48:52 +00004497 int k;
drh13449892005-09-07 21:22:45 +00004498 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004499 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004500 if( pCol->iTable==pExpr->iTable &&
4501 pCol->iColumn==pExpr->iColumn ){
4502 break;
4503 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004504 }
danielk19771e536952007-08-16 10:09:01 +00004505 if( (k>=pAggInfo->nColumn)
4506 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4507 ){
drh7f906d62007-03-12 23:48:52 +00004508 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004509 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004510 pCol->iTable = pExpr->iTable;
4511 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004512 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004513 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004514 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004515 if( pAggInfo->pGroupBy ){
4516 int j, n;
4517 ExprList *pGB = pAggInfo->pGroupBy;
4518 struct ExprList_item *pTerm = pGB->a;
4519 n = pGB->nExpr;
4520 for(j=0; j<n; j++, pTerm++){
4521 Expr *pE = pTerm->pExpr;
4522 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4523 pE->iColumn==pExpr->iColumn ){
4524 pCol->iSorterColumn = j;
4525 break;
4526 }
4527 }
4528 }
4529 if( pCol->iSorterColumn<0 ){
4530 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4531 }
4532 }
4533 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4534 ** because it was there before or because we just created it).
4535 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4536 ** pAggInfo->aCol[] entry.
4537 */
drhebb6a652013-09-12 23:42:22 +00004538 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004539 pExpr->pAggInfo = pAggInfo;
4540 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004541 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004542 break;
4543 } /* endif pExpr->iTable==pItem->iCursor */
4544 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004545 }
drh7d10d5a2008-08-20 16:35:10 +00004546 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004547 }
4548 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004549 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004550 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004551 ){
drh13449892005-09-07 21:22:45 +00004552 /* Check to see if pExpr is a duplicate of another aggregate
4553 ** function that is already in the pAggInfo structure
4554 */
4555 struct AggInfo_func *pItem = pAggInfo->aFunc;
4556 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004557 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004558 break;
4559 }
drh22827922000-06-06 17:27:05 +00004560 }
drh13449892005-09-07 21:22:45 +00004561 if( i>=pAggInfo->nFunc ){
4562 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4563 */
danielk197714db2662006-01-09 16:12:04 +00004564 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004565 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004566 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004567 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004568 pItem = &pAggInfo->aFunc[i];
4569 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004570 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004571 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004572 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004573 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004574 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004575 if( pExpr->flags & EP_Distinct ){
4576 pItem->iDistinct = pParse->nTab++;
4577 }else{
4578 pItem->iDistinct = -1;
4579 }
drh13449892005-09-07 21:22:45 +00004580 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004581 }
drh13449892005-09-07 21:22:45 +00004582 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4583 */
drhc5cd1242013-09-12 16:50:49 +00004584 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004585 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004586 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004587 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004588 return WRC_Prune;
4589 }else{
4590 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004591 }
drh22827922000-06-06 17:27:05 +00004592 }
4593 }
drh7d10d5a2008-08-20 16:35:10 +00004594 return WRC_Continue;
4595}
4596static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004597 UNUSED_PARAMETER(pWalker);
4598 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004599 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004600}
4601
4602/*
drhe8abb4c2012-11-02 18:24:57 +00004603** Analyze the pExpr expression looking for aggregate functions and
4604** for variables that need to be added to AggInfo object that pNC->pAggInfo
4605** points to. Additional entries are made on the AggInfo object as
4606** necessary.
drh626a8792005-01-17 22:08:19 +00004607**
4608** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004609** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004610*/
drhd2b3e232008-01-23 14:51:49 +00004611void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004612 Walker w;
drh374fdce2012-04-17 16:38:53 +00004613 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004614 w.xExprCallback = analyzeAggregate;
4615 w.xSelectCallback = analyzeAggregatesInSelect;
4616 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004617 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004618 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004619}
drh5d9a4af2005-08-30 00:54:01 +00004620
4621/*
4622** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4623** expression list. Return the number of errors.
4624**
4625** If an error is found, the analysis is cut short.
4626*/
drhd2b3e232008-01-23 14:51:49 +00004627void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004628 struct ExprList_item *pItem;
4629 int i;
drh5d9a4af2005-08-30 00:54:01 +00004630 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004631 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4632 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004633 }
4634 }
drh5d9a4af2005-08-30 00:54:01 +00004635}
drh892d3172008-01-10 03:46:36 +00004636
4637/*
drhceea3322009-04-23 13:22:42 +00004638** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004639*/
4640int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004641 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004642 return ++pParse->nMem;
4643 }
danielk19772f425f62008-07-04 09:41:39 +00004644 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004645}
drhceea3322009-04-23 13:22:42 +00004646
4647/*
4648** Deallocate a register, making available for reuse for some other
4649** purpose.
4650**
4651** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004652** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004653** the register becomes stale.
4654*/
drh892d3172008-01-10 03:46:36 +00004655void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004656 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004657 int i;
4658 struct yColCache *p;
4659 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4660 if( p->iReg==iReg ){
4661 p->tempReg = 1;
4662 return;
4663 }
4664 }
drh892d3172008-01-10 03:46:36 +00004665 pParse->aTempReg[pParse->nTempReg++] = iReg;
4666 }
4667}
4668
4669/*
4670** Allocate or deallocate a block of nReg consecutive registers
4671*/
4672int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004673 int i, n;
4674 i = pParse->iRangeReg;
4675 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004676 if( nReg<=n ){
4677 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004678 pParse->iRangeReg += nReg;
4679 pParse->nRangeReg -= nReg;
4680 }else{
4681 i = pParse->nMem+1;
4682 pParse->nMem += nReg;
4683 }
4684 return i;
4685}
4686void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004687 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004688 if( nReg>pParse->nRangeReg ){
4689 pParse->nRangeReg = nReg;
4690 pParse->iRangeReg = iReg;
4691 }
4692}
drhcdc69552011-12-06 13:24:59 +00004693
4694/*
4695** Mark all temporary registers as being unavailable for reuse.
4696*/
4697void sqlite3ClearTempRegCache(Parse *pParse){
4698 pParse->nTempReg = 0;
4699 pParse->nRangeReg = 0;
4700}
drhbb9b5f22016-03-19 00:35:02 +00004701
4702/*
4703** Validate that no temporary register falls within the range of
4704** iFirst..iLast, inclusive. This routine is only call from within assert()
4705** statements.
4706*/
4707#ifdef SQLITE_DEBUG
4708int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4709 int i;
4710 if( pParse->nRangeReg>0
4711 && pParse->iRangeReg+pParse->nRangeReg<iLast
4712 && pParse->iRangeReg>=iFirst
4713 ){
4714 return 0;
4715 }
4716 for(i=0; i<pParse->nTempReg; i++){
4717 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4718 return 0;
4719 }
4720 }
4721 return 1;
4722}
4723#endif /* SQLITE_DEBUG */