blob: 0de6378c0a5f8d05ae6716cb1fba6ecbcb613cf1 [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
danielk19774b5255a2008-06-05 16:47:39 +0000312#if SQLITE_MAX_EXPR_DEPTH>0
313/*
314** Check that argument nHeight is less than or equal to the maximum
315** expression depth allowed. If it is not, leave an error message in
316** pParse.
317*/
drh7d10d5a2008-08-20 16:35:10 +0000318int sqlite3ExprCheckHeight(Parse *pParse, int nHeight){
danielk19774b5255a2008-06-05 16:47:39 +0000319 int rc = SQLITE_OK;
320 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
321 if( nHeight>mxHeight ){
322 sqlite3ErrorMsg(pParse,
323 "Expression tree is too large (maximum depth %d)", mxHeight
324 );
325 rc = SQLITE_ERROR;
326 }
327 return rc;
328}
329
330/* The following three functions, heightOfExpr(), heightOfExprList()
331** and heightOfSelect(), are used to determine the maximum height
332** of any expression tree referenced by the structure passed as the
333** first argument.
334**
335** If this maximum height is greater than the current value pointed
336** to by pnHeight, the second parameter, then set *pnHeight to that
337** value.
338*/
339static void heightOfExpr(Expr *p, int *pnHeight){
340 if( p ){
341 if( p->nHeight>*pnHeight ){
342 *pnHeight = p->nHeight;
343 }
344 }
345}
346static void heightOfExprList(ExprList *p, int *pnHeight){
347 if( p ){
348 int i;
349 for(i=0; i<p->nExpr; i++){
350 heightOfExpr(p->a[i].pExpr, pnHeight);
351 }
352 }
353}
354static void heightOfSelect(Select *p, int *pnHeight){
355 if( p ){
356 heightOfExpr(p->pWhere, pnHeight);
357 heightOfExpr(p->pHaving, pnHeight);
358 heightOfExpr(p->pLimit, pnHeight);
359 heightOfExpr(p->pOffset, pnHeight);
360 heightOfExprList(p->pEList, pnHeight);
361 heightOfExprList(p->pGroupBy, pnHeight);
362 heightOfExprList(p->pOrderBy, pnHeight);
363 heightOfSelect(p->pPrior, pnHeight);
364 }
365}
366
367/*
368** Set the Expr.nHeight variable in the structure passed as an
369** argument. An expression with no children, Expr.pList or
370** Expr.pSelect member has a height of 1. Any other expression
371** has a height equal to the maximum height of any other
372** referenced Expr plus one.
drh2308ed32015-02-09 16:09:34 +0000373**
374** Also propagate EP_Propagate flags up from Expr.x.pList to Expr.flags,
375** if appropriate.
danielk19774b5255a2008-06-05 16:47:39 +0000376*/
377static void exprSetHeight(Expr *p){
378 int nHeight = 0;
379 heightOfExpr(p->pLeft, &nHeight);
380 heightOfExpr(p->pRight, &nHeight);
danielk19776ab3a2e2009-02-19 14:39:25 +0000381 if( ExprHasProperty(p, EP_xIsSelect) ){
382 heightOfSelect(p->x.pSelect, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000383 }else if( p->x.pList ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000384 heightOfExprList(p->x.pList, &nHeight);
drh2308ed32015-02-09 16:09:34 +0000385 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
danielk19776ab3a2e2009-02-19 14:39:25 +0000386 }
danielk19774b5255a2008-06-05 16:47:39 +0000387 p->nHeight = nHeight + 1;
388}
389
390/*
391** Set the Expr.nHeight variable using the exprSetHeight() function. If
392** the height is greater than the maximum allowed expression depth,
393** leave an error in pParse.
drh2308ed32015-02-09 16:09:34 +0000394**
395** Also propagate all EP_Propagate flags from the Expr.x.pList into
396** Expr.flags.
danielk19774b5255a2008-06-05 16:47:39 +0000397*/
drh2308ed32015-02-09 16:09:34 +0000398void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
drh74893a42015-03-22 10:23:17 +0000399 if( pParse->nErr ) return;
danielk19774b5255a2008-06-05 16:47:39 +0000400 exprSetHeight(p);
drh7d10d5a2008-08-20 16:35:10 +0000401 sqlite3ExprCheckHeight(pParse, p->nHeight);
danielk19774b5255a2008-06-05 16:47:39 +0000402}
403
404/*
405** Return the maximum height of any expression tree referenced
406** by the select statement passed as an argument.
407*/
408int sqlite3SelectExprHeight(Select *p){
409 int nHeight = 0;
410 heightOfSelect(p, &nHeight);
411 return nHeight;
412}
drh2308ed32015-02-09 16:09:34 +0000413#else /* ABOVE: Height enforcement enabled. BELOW: Height enforcement off */
414/*
415** Propagate all EP_Propagate flags from the Expr.x.pList into
416** Expr.flags.
417*/
418void sqlite3ExprSetHeightAndFlags(Parse *pParse, Expr *p){
419 if( p && p->x.pList && !ExprHasProperty(p, EP_xIsSelect) ){
420 p->flags |= EP_Propagate & sqlite3ExprListFlags(p->x.pList);
421 }
422}
423#define exprSetHeight(y)
danielk19774b5255a2008-06-05 16:47:39 +0000424#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
425
drhbe5c89a2004-07-26 00:31:09 +0000426/*
drhb7916a72009-05-27 10:31:29 +0000427** This routine is the core allocator for Expr nodes.
428**
drha76b5df2002-02-23 02:32:10 +0000429** Construct a new expression node and return a pointer to it. Memory
drhb7916a72009-05-27 10:31:29 +0000430** for this node and for the pToken argument is a single allocation
431** obtained from sqlite3DbMalloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000432** is responsible for making sure the node eventually gets freed.
drhb7916a72009-05-27 10:31:29 +0000433**
434** If dequote is true, then the token (if it exists) is dequoted.
drhe792b5b2015-08-23 20:48:29 +0000435** If dequote is false, no dequoting is performed. The deQuote
drhb7916a72009-05-27 10:31:29 +0000436** parameter is ignored if pToken is NULL or if the token does not
437** appear to be quoted. If the quotes were of the form "..." (double-quotes)
438** then the EP_DblQuoted flag is set on the expression node.
drh33e619f2009-05-28 01:00:55 +0000439**
440** Special case: If op==TK_INTEGER and pToken points to a string that
441** can be translated into a 32-bit integer, then the token is not
442** stored in u.zToken. Instead, the integer values is written
443** into u.iValue and the EP_IntValue flag is set. No extra storage
444** is allocated to hold the integer text and the dequote flag is ignored.
drha76b5df2002-02-23 02:32:10 +0000445*/
drhb7916a72009-05-27 10:31:29 +0000446Expr *sqlite3ExprAlloc(
danielk1977a1644fd2007-08-29 12:31:25 +0000447 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
drh17435752007-08-16 04:30:38 +0000448 int op, /* Expression opcode */
drhb7916a72009-05-27 10:31:29 +0000449 const Token *pToken, /* Token argument. Might be NULL */
450 int dequote /* True to dequote */
drh17435752007-08-16 04:30:38 +0000451){
drha76b5df2002-02-23 02:32:10 +0000452 Expr *pNew;
drh33e619f2009-05-28 01:00:55 +0000453 int nExtra = 0;
shanecf697392009-06-01 16:53:09 +0000454 int iValue = 0;
danielk1977fc976062007-05-10 10:46:56 +0000455
drh575fad62016-02-05 13:38:36 +0000456 assert( db!=0 );
drhb7916a72009-05-27 10:31:29 +0000457 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000458 if( op!=TK_INTEGER || pToken->z==0
459 || sqlite3GetInt32(pToken->z, &iValue)==0 ){
460 nExtra = pToken->n+1;
drhd50ffc42011-03-08 02:38:28 +0000461 assert( iValue>=0 );
drh33e619f2009-05-28 01:00:55 +0000462 }
drhb7916a72009-05-27 10:31:29 +0000463 }
drh575fad62016-02-05 13:38:36 +0000464 pNew = sqlite3DbMallocRawNN(db, sizeof(Expr)+nExtra);
drhb7916a72009-05-27 10:31:29 +0000465 if( pNew ){
drhca3862d2016-01-08 12:46:39 +0000466 memset(pNew, 0, sizeof(Expr));
drhb7916a72009-05-27 10:31:29 +0000467 pNew->op = (u8)op;
468 pNew->iAgg = -1;
469 if( pToken ){
drh33e619f2009-05-28 01:00:55 +0000470 if( nExtra==0 ){
471 pNew->flags |= EP_IntValue;
472 pNew->u.iValue = iValue;
473 }else{
474 int c;
475 pNew->u.zToken = (char*)&pNew[1];
drhb07028f2011-10-14 21:49:18 +0000476 assert( pToken->z!=0 || pToken->n==0 );
477 if( pToken->n ) memcpy(pNew->u.zToken, pToken->z, pToken->n);
drh33e619f2009-05-28 01:00:55 +0000478 pNew->u.zToken[pToken->n] = 0;
479 if( dequote && nExtra>=3
480 && ((c = pToken->z[0])=='\'' || c=='"' || c=='[' || c=='`') ){
481 sqlite3Dequote(pNew->u.zToken);
482 if( c=='"' ) pNew->flags |= EP_DblQuoted;
483 }
drhb7916a72009-05-27 10:31:29 +0000484 }
485 }
486#if SQLITE_MAX_EXPR_DEPTH>0
487 pNew->nHeight = 1;
488#endif
489 }
drha76b5df2002-02-23 02:32:10 +0000490 return pNew;
491}
492
493/*
drhb7916a72009-05-27 10:31:29 +0000494** Allocate a new expression node from a zero-terminated token that has
495** already been dequoted.
496*/
497Expr *sqlite3Expr(
498 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
499 int op, /* Expression opcode */
500 const char *zToken /* Token argument. Might be NULL */
501){
502 Token x;
503 x.z = zToken;
504 x.n = zToken ? sqlite3Strlen30(zToken) : 0;
505 return sqlite3ExprAlloc(db, op, &x, 0);
506}
507
508/*
509** Attach subtrees pLeft and pRight to the Expr node pRoot.
510**
511** If pRoot==NULL that means that a memory allocation error has occurred.
512** In that case, delete the subtrees pLeft and pRight.
513*/
514void sqlite3ExprAttachSubtrees(
515 sqlite3 *db,
516 Expr *pRoot,
517 Expr *pLeft,
518 Expr *pRight
519){
520 if( pRoot==0 ){
521 assert( db->mallocFailed );
522 sqlite3ExprDelete(db, pLeft);
523 sqlite3ExprDelete(db, pRight);
524 }else{
525 if( pRight ){
526 pRoot->pRight = pRight;
drh885a5b02015-02-09 15:21:36 +0000527 pRoot->flags |= EP_Propagate & pRight->flags;
drhb7916a72009-05-27 10:31:29 +0000528 }
529 if( pLeft ){
530 pRoot->pLeft = pLeft;
drh885a5b02015-02-09 15:21:36 +0000531 pRoot->flags |= EP_Propagate & pLeft->flags;
drhb7916a72009-05-27 10:31:29 +0000532 }
533 exprSetHeight(pRoot);
534 }
535}
536
537/*
peter.d.reid60ec9142014-09-06 16:39:46 +0000538** Allocate an Expr node which joins as many as two subtrees.
drhb7916a72009-05-27 10:31:29 +0000539**
drhbf664462009-06-19 18:32:54 +0000540** One or both of the subtrees can be NULL. Return a pointer to the new
541** Expr node. Or, if an OOM error occurs, set pParse->db->mallocFailed,
542** free the subtrees and return NULL.
drh206f3d92006-07-11 13:15:08 +0000543*/
drh17435752007-08-16 04:30:38 +0000544Expr *sqlite3PExpr(
545 Parse *pParse, /* Parsing context */
546 int op, /* Expression opcode */
547 Expr *pLeft, /* Left operand */
548 Expr *pRight, /* Right operand */
549 const Token *pToken /* Argument token */
550){
drh5fb52ca2012-03-31 02:34:35 +0000551 Expr *p;
drh1167d322015-10-28 20:01:45 +0000552 if( op==TK_AND && pParse->nErr==0 ){
drh5fb52ca2012-03-31 02:34:35 +0000553 /* Take advantage of short-circuit false optimization for AND */
554 p = sqlite3ExprAnd(pParse->db, pLeft, pRight);
555 }else{
drh1167d322015-10-28 20:01:45 +0000556 p = sqlite3ExprAlloc(pParse->db, op & TKFLG_MASK, pToken, 1);
drh5fb52ca2012-03-31 02:34:35 +0000557 sqlite3ExprAttachSubtrees(pParse->db, p, pLeft, pRight);
558 }
dan2b359bd2010-10-28 11:31:23 +0000559 if( p ) {
560 sqlite3ExprCheckHeight(pParse, p->nHeight);
561 }
drh4e0cff62004-11-05 05:10:28 +0000562 return p;
563}
564
565/*
drh08de4f72016-04-11 01:06:47 +0000566** Add pSelect to the Expr.x.pSelect field. Or, if pExpr is NULL (due
567** do a memory allocation failure) then delete the pSelect object.
568*/
569void sqlite3PExprAddSelect(Parse *pParse, Expr *pExpr, Select *pSelect){
570 if( pExpr ){
571 pExpr->x.pSelect = pSelect;
572 ExprSetProperty(pExpr, EP_xIsSelect|EP_Subquery);
573 sqlite3ExprSetHeightAndFlags(pParse, pExpr);
574 }else{
575 assert( pParse->db->mallocFailed );
576 sqlite3SelectDelete(pParse->db, pSelect);
577 }
578}
579
580
581/*
drh991a1982014-01-02 17:57:16 +0000582** If the expression is always either TRUE or FALSE (respectively),
583** then return 1. If one cannot determine the truth value of the
584** expression at compile-time return 0.
585**
586** This is an optimization. If is OK to return 0 here even if
587** the expression really is always false or false (a false negative).
588** But it is a bug to return 1 if the expression might have different
589** boolean values in different circumstances (a false positive.)
drh5fb52ca2012-03-31 02:34:35 +0000590**
591** Note that if the expression is part of conditional for a
592** LEFT JOIN, then we cannot determine at compile-time whether or not
593** is it true or false, so always return 0.
594*/
drh991a1982014-01-02 17:57:16 +0000595static int exprAlwaysTrue(Expr *p){
596 int v = 0;
597 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
598 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
599 return v!=0;
600}
drh5fb52ca2012-03-31 02:34:35 +0000601static int exprAlwaysFalse(Expr *p){
602 int v = 0;
603 if( ExprHasProperty(p, EP_FromJoin) ) return 0;
604 if( !sqlite3ExprIsInteger(p, &v) ) return 0;
605 return v==0;
606}
607
608/*
drh91bb0ee2004-09-01 03:06:34 +0000609** Join two expressions using an AND operator. If either expression is
610** NULL, then just return the other expression.
drh5fb52ca2012-03-31 02:34:35 +0000611**
612** If one side or the other of the AND is known to be false, then instead
613** of returning an AND expression, just return a constant expression with
614** a value of false.
drh91bb0ee2004-09-01 03:06:34 +0000615*/
danielk19771e536952007-08-16 10:09:01 +0000616Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000617 if( pLeft==0 ){
618 return pRight;
619 }else if( pRight==0 ){
620 return pLeft;
drh5fb52ca2012-03-31 02:34:35 +0000621 }else if( exprAlwaysFalse(pLeft) || exprAlwaysFalse(pRight) ){
622 sqlite3ExprDelete(db, pLeft);
623 sqlite3ExprDelete(db, pRight);
624 return sqlite3ExprAlloc(db, TK_INTEGER, &sqlite3IntTokens[0], 0);
drh91bb0ee2004-09-01 03:06:34 +0000625 }else{
drhb7916a72009-05-27 10:31:29 +0000626 Expr *pNew = sqlite3ExprAlloc(db, TK_AND, 0, 0);
627 sqlite3ExprAttachSubtrees(db, pNew, pLeft, pRight);
628 return pNew;
drha76b5df2002-02-23 02:32:10 +0000629 }
630}
631
632/*
633** Construct a new expression node for a function with multiple
634** arguments.
635*/
drh17435752007-08-16 04:30:38 +0000636Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000637 Expr *pNew;
drh633e6d52008-07-28 19:34:53 +0000638 sqlite3 *db = pParse->db;
danielk19774b202ae2006-01-23 05:50:58 +0000639 assert( pToken );
drhb7916a72009-05-27 10:31:29 +0000640 pNew = sqlite3ExprAlloc(db, TK_FUNCTION, pToken, 1);
drha76b5df2002-02-23 02:32:10 +0000641 if( pNew==0 ){
drhd9da78a2009-03-24 15:08:09 +0000642 sqlite3ExprListDelete(db, pList); /* Avoid memory leak when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000643 return 0;
644 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000645 pNew->x.pList = pList;
646 assert( !ExprHasProperty(pNew, EP_xIsSelect) );
drh2308ed32015-02-09 16:09:34 +0000647 sqlite3ExprSetHeightAndFlags(pParse, pNew);
drha76b5df2002-02-23 02:32:10 +0000648 return pNew;
649}
650
651/*
drhfa6bc002004-09-07 16:19:52 +0000652** Assign a variable number to an expression that encodes a wildcard
653** in the original SQL statement.
654**
655** Wildcards consisting of a single "?" are assigned the next sequential
656** variable number.
657**
658** Wildcards of the form "?nnn" are assigned the number "nnn". We make
659** sure "nnn" is not too be to avoid a denial of service attack when
660** the SQL statement comes from an external source.
661**
drh51f49f12009-05-21 20:41:32 +0000662** Wildcards of the form ":aaa", "@aaa", or "$aaa" are assigned the same number
drhfa6bc002004-09-07 16:19:52 +0000663** as the previous instance of the same wildcard. Or if this is the first
peter.d.reid60ec9142014-09-06 16:39:46 +0000664** instance of the wildcard, the next sequential variable number is
drhfa6bc002004-09-07 16:19:52 +0000665** assigned.
666*/
667void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
drh17435752007-08-16 04:30:38 +0000668 sqlite3 *db = pParse->db;
drhb7916a72009-05-27 10:31:29 +0000669 const char *z;
drh17435752007-08-16 04:30:38 +0000670
drhfa6bc002004-09-07 16:19:52 +0000671 if( pExpr==0 ) return;
drhc5cd1242013-09-12 16:50:49 +0000672 assert( !ExprHasProperty(pExpr, EP_IntValue|EP_Reduced|EP_TokenOnly) );
drh33e619f2009-05-28 01:00:55 +0000673 z = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000674 assert( z!=0 );
675 assert( z[0]!=0 );
676 if( z[1]==0 ){
drhfa6bc002004-09-07 16:19:52 +0000677 /* Wildcard of the form "?". Assign the next variable number */
drhb7916a72009-05-27 10:31:29 +0000678 assert( z[0]=='?' );
drh8677d302009-11-04 13:17:14 +0000679 pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000680 }else{
drh124c0b42011-06-01 18:15:55 +0000681 ynVar x = 0;
682 u32 n = sqlite3Strlen30(z);
683 if( z[0]=='?' ){
684 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
685 ** use it as the variable number */
686 i64 i;
687 int bOk = 0==sqlite3Atoi64(&z[1], &i, n-1, SQLITE_UTF8);
688 pExpr->iColumn = x = (ynVar)i;
689 testcase( i==0 );
690 testcase( i==1 );
691 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
692 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
693 if( bOk==0 || i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
694 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
695 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
696 x = 0;
drhfa6bc002004-09-07 16:19:52 +0000697 }
drh124c0b42011-06-01 18:15:55 +0000698 if( i>pParse->nVar ){
699 pParse->nVar = (int)i;
700 }
701 }else{
702 /* Wildcards like ":aaa", "$aaa" or "@aaa". Reuse the same variable
703 ** number as the prior appearance of the same name, or if the name
704 ** has never appeared before, reuse the same variable number
705 */
706 ynVar i;
707 for(i=0; i<pParse->nzVar; i++){
drh503a6862013-03-01 01:07:17 +0000708 if( pParse->azVar[i] && strcmp(pParse->azVar[i],z)==0 ){
drh124c0b42011-06-01 18:15:55 +0000709 pExpr->iColumn = x = (ynVar)i+1;
710 break;
711 }
712 }
713 if( x==0 ) x = pExpr->iColumn = (ynVar)(++pParse->nVar);
drhfa6bc002004-09-07 16:19:52 +0000714 }
drh124c0b42011-06-01 18:15:55 +0000715 if( x>0 ){
716 if( x>pParse->nzVar ){
717 char **a;
718 a = sqlite3DbRealloc(db, pParse->azVar, x*sizeof(a[0]));
drh4a642b62016-02-05 01:55:27 +0000719 if( a==0 ){
720 assert( db->mallocFailed ); /* Error reported through mallocFailed */
721 return;
722 }
drh124c0b42011-06-01 18:15:55 +0000723 pParse->azVar = a;
724 memset(&a[pParse->nzVar], 0, (x-pParse->nzVar)*sizeof(a[0]));
725 pParse->nzVar = x;
drhfa6bc002004-09-07 16:19:52 +0000726 }
drh124c0b42011-06-01 18:15:55 +0000727 if( z[0]!='?' || pParse->azVar[x-1]==0 ){
728 sqlite3DbFree(db, pParse->azVar[x-1]);
729 pParse->azVar[x-1] = sqlite3DbStrNDup(db, z, n);
drhfa6bc002004-09-07 16:19:52 +0000730 }
731 }
732 }
drhbb4957f2008-03-20 14:03:29 +0000733 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +0000734 sqlite3ErrorMsg(pParse, "too many SQL variables");
735 }
drhfa6bc002004-09-07 16:19:52 +0000736}
737
738/*
danf6963f92009-11-23 14:39:14 +0000739** Recursively delete an expression tree.
drha2e00042002-01-22 03:13:42 +0000740*/
drh4f0010b2016-04-11 14:49:39 +0000741static SQLITE_NOINLINE void sqlite3ExprDeleteNN(sqlite3 *db, Expr *p){
742 assert( p!=0 );
drhd50ffc42011-03-08 02:38:28 +0000743 /* Sanity check: Assert that the IntValue is non-negative if it exists */
744 assert( !ExprHasProperty(p, EP_IntValue) || p->u.iValue>=0 );
drhc5cd1242013-09-12 16:50:49 +0000745 if( !ExprHasProperty(p, EP_TokenOnly) ){
746 /* The Expr.x union is never used at the same time as Expr.pRight */
747 assert( p->x.pList==0 || p->pRight==0 );
drh33e619f2009-05-28 01:00:55 +0000748 sqlite3ExprDelete(db, p->pLeft);
749 sqlite3ExprDelete(db, p->pRight);
drhc5cd1242013-09-12 16:50:49 +0000750 if( ExprHasProperty(p, EP_MemToken) ) sqlite3DbFree(db, p->u.zToken);
danielk19776ab3a2e2009-02-19 14:39:25 +0000751 if( ExprHasProperty(p, EP_xIsSelect) ){
752 sqlite3SelectDelete(db, p->x.pSelect);
753 }else{
754 sqlite3ExprListDelete(db, p->x.pList);
755 }
756 }
drh33e619f2009-05-28 01:00:55 +0000757 if( !ExprHasProperty(p, EP_Static) ){
758 sqlite3DbFree(db, p);
759 }
drha2e00042002-01-22 03:13:42 +0000760}
drh4f0010b2016-04-11 14:49:39 +0000761void sqlite3ExprDelete(sqlite3 *db, Expr *p){
762 if( p ) sqlite3ExprDeleteNN(db, p);
763}
drha2e00042002-01-22 03:13:42 +0000764
drhd2687b72005-08-12 22:56:09 +0000765/*
danielk19776ab3a2e2009-02-19 14:39:25 +0000766** Return the number of bytes allocated for the expression structure
767** passed as the first argument. This is always one of EXPR_FULLSIZE,
768** EXPR_REDUCEDSIZE or EXPR_TOKENONLYSIZE.
769*/
770static int exprStructSize(Expr *p){
771 if( ExprHasProperty(p, EP_TokenOnly) ) return EXPR_TOKENONLYSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +0000772 if( ExprHasProperty(p, EP_Reduced) ) return EXPR_REDUCEDSIZE;
773 return EXPR_FULLSIZE;
774}
775
776/*
drh33e619f2009-05-28 01:00:55 +0000777** The dupedExpr*Size() routines each return the number of bytes required
778** to store a copy of an expression or expression tree. They differ in
779** how much of the tree is measured.
780**
781** dupedExprStructSize() Size of only the Expr structure
782** dupedExprNodeSize() Size of Expr + space for token
783** dupedExprSize() Expr + token + subtree components
784**
785***************************************************************************
786**
787** The dupedExprStructSize() function returns two values OR-ed together:
788** (1) the space required for a copy of the Expr structure only and
789** (2) the EP_xxx flags that indicate what the structure size should be.
790** The return values is always one of:
791**
792** EXPR_FULLSIZE
793** EXPR_REDUCEDSIZE | EP_Reduced
794** EXPR_TOKENONLYSIZE | EP_TokenOnly
795**
796** The size of the structure can be found by masking the return value
797** of this routine with 0xfff. The flags can be found by masking the
798** return value with EP_Reduced|EP_TokenOnly.
799**
800** Note that with flags==EXPRDUP_REDUCE, this routines works on full-size
801** (unreduced) Expr objects as they or originally constructed by the parser.
802** During expression analysis, extra information is computed and moved into
803** later parts of teh Expr object and that extra information might get chopped
804** off if the expression is reduced. Note also that it does not work to
peter.d.reid60ec9142014-09-06 16:39:46 +0000805** make an EXPRDUP_REDUCE copy of a reduced expression. It is only legal
drh33e619f2009-05-28 01:00:55 +0000806** to reduce a pristine expression tree from the parser. The implementation
807** of dupedExprStructSize() contain multiple assert() statements that attempt
808** to enforce this constraint.
danielk19776ab3a2e2009-02-19 14:39:25 +0000809*/
810static int dupedExprStructSize(Expr *p, int flags){
811 int nSize;
drh33e619f2009-05-28 01:00:55 +0000812 assert( flags==EXPRDUP_REDUCE || flags==0 ); /* Only one flag value allowed */
drhaecd8022013-09-13 18:15:15 +0000813 assert( EXPR_FULLSIZE<=0xfff );
814 assert( (0xfff & (EP_Reduced|EP_TokenOnly))==0 );
drh3c194692016-04-11 16:43:43 +0000815 if( 0==flags ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000816 nSize = EXPR_FULLSIZE;
danielk19776ab3a2e2009-02-19 14:39:25 +0000817 }else{
drhc5cd1242013-09-12 16:50:49 +0000818 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
drh33e619f2009-05-28 01:00:55 +0000819 assert( !ExprHasProperty(p, EP_FromJoin) );
drhc5cd1242013-09-12 16:50:49 +0000820 assert( !ExprHasProperty(p, EP_MemToken) );
drhebb6a652013-09-12 23:42:22 +0000821 assert( !ExprHasProperty(p, EP_NoReduce) );
drhaecd8022013-09-13 18:15:15 +0000822 if( p->pLeft || p->x.pList ){
drh33e619f2009-05-28 01:00:55 +0000823 nSize = EXPR_REDUCEDSIZE | EP_Reduced;
824 }else{
drhaecd8022013-09-13 18:15:15 +0000825 assert( p->pRight==0 );
drh33e619f2009-05-28 01:00:55 +0000826 nSize = EXPR_TOKENONLYSIZE | EP_TokenOnly;
827 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000828 }
829 return nSize;
830}
831
832/*
drh33e619f2009-05-28 01:00:55 +0000833** This function returns the space in bytes required to store the copy
834** of the Expr structure and a copy of the Expr.u.zToken string (if that
835** string is defined.)
danielk19776ab3a2e2009-02-19 14:39:25 +0000836*/
837static int dupedExprNodeSize(Expr *p, int flags){
drh33e619f2009-05-28 01:00:55 +0000838 int nByte = dupedExprStructSize(p, flags) & 0xfff;
839 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
840 nByte += sqlite3Strlen30(p->u.zToken)+1;
danielk19776ab3a2e2009-02-19 14:39:25 +0000841 }
danielk1977bc739712009-03-23 04:33:32 +0000842 return ROUND8(nByte);
danielk19776ab3a2e2009-02-19 14:39:25 +0000843}
844
845/*
846** Return the number of bytes required to create a duplicate of the
847** expression passed as the first argument. The second argument is a
848** mask containing EXPRDUP_XXX flags.
849**
850** The value returned includes space to create a copy of the Expr struct
drh33e619f2009-05-28 01:00:55 +0000851** itself and the buffer referred to by Expr.u.zToken, if any.
danielk19776ab3a2e2009-02-19 14:39:25 +0000852**
853** If the EXPRDUP_REDUCE flag is set, then the return value includes
854** space to duplicate all Expr nodes in the tree formed by Expr.pLeft
855** and Expr.pRight variables (but not for any structures pointed to or
856** descended from the Expr.x.pList or Expr.x.pSelect variables).
857*/
858static int dupedExprSize(Expr *p, int flags){
859 int nByte = 0;
860 if( p ){
861 nByte = dupedExprNodeSize(p, flags);
862 if( flags&EXPRDUP_REDUCE ){
drhb7916a72009-05-27 10:31:29 +0000863 nByte += dupedExprSize(p->pLeft, flags) + dupedExprSize(p->pRight, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +0000864 }
865 }
866 return nByte;
867}
868
869/*
870** This function is similar to sqlite3ExprDup(), except that if pzBuffer
871** is not NULL then *pzBuffer is assumed to point to a buffer large enough
drh33e619f2009-05-28 01:00:55 +0000872** to store the copy of expression p, the copies of p->u.zToken
danielk19776ab3a2e2009-02-19 14:39:25 +0000873** (if applicable), and the copies of the p->pLeft and p->pRight expressions,
peter.d.reid60ec9142014-09-06 16:39:46 +0000874** if any. Before returning, *pzBuffer is set to the first byte past the
danielk19776ab3a2e2009-02-19 14:39:25 +0000875** portion of the buffer copied into by this function.
876*/
drh3c194692016-04-11 16:43:43 +0000877static Expr *exprDup(sqlite3 *db, Expr *p, int dupFlags, u8 **pzBuffer){
878 Expr *pNew; /* Value to return */
879 u8 *zAlloc; /* Memory space from which to build Expr object */
880 u32 staticFlag; /* EP_Static if space not obtained from malloc */
881
drh575fad62016-02-05 13:38:36 +0000882 assert( db!=0 );
drh3c194692016-04-11 16:43:43 +0000883 assert( p );
884 assert( dupFlags==0 || dupFlags==EXPRDUP_REDUCE );
885 assert( pzBuffer==0 || dupFlags==EXPRDUP_REDUCE );
danielk19776ab3a2e2009-02-19 14:39:25 +0000886
drh3c194692016-04-11 16:43:43 +0000887 /* Figure out where to write the new Expr structure. */
888 if( pzBuffer ){
889 zAlloc = *pzBuffer;
890 staticFlag = EP_Static;
891 }else{
892 zAlloc = sqlite3DbMallocRawNN(db, dupedExprSize(p, dupFlags));
893 staticFlag = 0;
894 }
895 pNew = (Expr *)zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +0000896
drh3c194692016-04-11 16:43:43 +0000897 if( pNew ){
898 /* Set nNewSize to the size allocated for the structure pointed to
899 ** by pNew. This is either EXPR_FULLSIZE, EXPR_REDUCEDSIZE or
900 ** EXPR_TOKENONLYSIZE. nToken is set to the number of bytes consumed
901 ** by the copy of the p->u.zToken string (if any).
902 */
903 const unsigned nStructSize = dupedExprStructSize(p, dupFlags);
904 const int nNewSize = nStructSize & 0xfff;
905 int nToken;
906 if( !ExprHasProperty(p, EP_IntValue) && p->u.zToken ){
907 nToken = sqlite3Strlen30(p->u.zToken) + 1;
danielk19776ab3a2e2009-02-19 14:39:25 +0000908 }else{
drh3c194692016-04-11 16:43:43 +0000909 nToken = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +0000910 }
drh3c194692016-04-11 16:43:43 +0000911 if( dupFlags ){
912 assert( ExprHasProperty(p, EP_Reduced)==0 );
913 memcpy(zAlloc, p, nNewSize);
914 }else{
915 u32 nSize = (u32)exprStructSize(p);
916 memcpy(zAlloc, p, nSize);
917 if( nSize<EXPR_FULLSIZE ){
918 memset(&zAlloc[nSize], 0, EXPR_FULLSIZE-nSize);
919 }
920 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000921
drh3c194692016-04-11 16:43:43 +0000922 /* Set the EP_Reduced, EP_TokenOnly, and EP_Static flags appropriately. */
923 pNew->flags &= ~(EP_Reduced|EP_TokenOnly|EP_Static|EP_MemToken);
924 pNew->flags |= nStructSize & (EP_Reduced|EP_TokenOnly);
925 pNew->flags |= staticFlag;
926
927 /* Copy the p->u.zToken string, if any. */
928 if( nToken ){
929 char *zToken = pNew->u.zToken = (char*)&zAlloc[nNewSize];
930 memcpy(zToken, p->u.zToken, nToken);
931 }
932
933 if( 0==((p->flags|pNew->flags) & EP_TokenOnly) ){
934 /* Fill in the pNew->x.pSelect or pNew->x.pList member. */
935 if( ExprHasProperty(p, EP_xIsSelect) ){
936 pNew->x.pSelect = sqlite3SelectDup(db, p->x.pSelect, dupFlags);
drh33e619f2009-05-28 01:00:55 +0000937 }else{
drh3c194692016-04-11 16:43:43 +0000938 pNew->x.pList = sqlite3ExprListDup(db, p->x.pList, dupFlags);
drh33e619f2009-05-28 01:00:55 +0000939 }
drh3c194692016-04-11 16:43:43 +0000940 }
941
942 /* Fill in pNew->pLeft and pNew->pRight. */
943 if( ExprHasProperty(pNew, EP_Reduced|EP_TokenOnly) ){
944 zAlloc += dupedExprNodeSize(p, dupFlags);
945 if( ExprHasProperty(pNew, EP_Reduced) ){
946 pNew->pLeft = p->pLeft ?
947 exprDup(db, p->pLeft, EXPRDUP_REDUCE, &zAlloc) : 0;
948 pNew->pRight = p->pRight ?
949 exprDup(db, p->pRight, EXPRDUP_REDUCE, &zAlloc) : 0;
danielk19776ab3a2e2009-02-19 14:39:25 +0000950 }
drh3c194692016-04-11 16:43:43 +0000951 if( pzBuffer ){
952 *pzBuffer = zAlloc;
danielk19776ab3a2e2009-02-19 14:39:25 +0000953 }
drh3c194692016-04-11 16:43:43 +0000954 }else{
955 if( !ExprHasProperty(p, EP_TokenOnly) ){
956 pNew->pLeft = sqlite3ExprDup(db, p->pLeft, 0);
957 pNew->pRight = sqlite3ExprDup(db, p->pRight, 0);
danielk19776ab3a2e2009-02-19 14:39:25 +0000958 }
danielk19776ab3a2e2009-02-19 14:39:25 +0000959 }
960 }
961 return pNew;
962}
963
964/*
danbfe31e72014-01-15 14:17:31 +0000965** Create and return a deep copy of the object passed as the second
966** argument. If an OOM condition is encountered, NULL is returned
967** and the db->mallocFailed flag set.
968*/
daneede6a52014-01-15 19:42:23 +0000969#ifndef SQLITE_OMIT_CTE
danbfe31e72014-01-15 14:17:31 +0000970static With *withDup(sqlite3 *db, With *p){
dan4e9119d2014-01-13 15:12:23 +0000971 With *pRet = 0;
972 if( p ){
973 int nByte = sizeof(*p) + sizeof(p->a[0]) * (p->nCte-1);
974 pRet = sqlite3DbMallocZero(db, nByte);
975 if( pRet ){
976 int i;
977 pRet->nCte = p->nCte;
978 for(i=0; i<p->nCte; i++){
979 pRet->a[i].pSelect = sqlite3SelectDup(db, p->a[i].pSelect, 0);
980 pRet->a[i].pCols = sqlite3ExprListDup(db, p->a[i].pCols, 0);
981 pRet->a[i].zName = sqlite3DbStrDup(db, p->a[i].zName);
982 }
983 }
984 }
985 return pRet;
986}
daneede6a52014-01-15 19:42:23 +0000987#else
988# define withDup(x,y) 0
989#endif
dan4e9119d2014-01-13 15:12:23 +0000990
drha76b5df2002-02-23 02:32:10 +0000991/*
drhff78bd22002-02-27 01:47:11 +0000992** The following group of routines make deep copies of expressions,
993** expression lists, ID lists, and select statements. The copies can
994** be deleted (by being passed to their respective ...Delete() routines)
995** without effecting the originals.
996**
danielk19774adee202004-05-08 08:23:19 +0000997** The expression list, ID, and source lists return by sqlite3ExprListDup(),
998** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +0000999** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +00001000**
drhad3cab52002-05-24 02:04:32 +00001001** Any tables that the SrcList might point to are not duplicated.
danielk19776ab3a2e2009-02-19 14:39:25 +00001002**
drhb7916a72009-05-27 10:31:29 +00001003** The flags parameter contains a combination of the EXPRDUP_XXX flags.
danielk19776ab3a2e2009-02-19 14:39:25 +00001004** If the EXPRDUP_REDUCE flag is set, then the structure returned is a
1005** truncated version of the usual Expr structure that will be stored as
1006** part of the in-memory representation of the database schema.
drhff78bd22002-02-27 01:47:11 +00001007*/
danielk19776ab3a2e2009-02-19 14:39:25 +00001008Expr *sqlite3ExprDup(sqlite3 *db, Expr *p, int flags){
drh72ea29d2015-12-08 16:58:45 +00001009 assert( flags==0 || flags==EXPRDUP_REDUCE );
drh3c194692016-04-11 16:43:43 +00001010 return p ? exprDup(db, p, flags, 0) : 0;
drhff78bd22002-02-27 01:47:11 +00001011}
danielk19776ab3a2e2009-02-19 14:39:25 +00001012ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p, int flags){
drhff78bd22002-02-27 01:47:11 +00001013 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +00001014 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +00001015 int i;
drh575fad62016-02-05 13:38:36 +00001016 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001017 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001018 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001019 if( pNew==0 ) return 0;
drhd872bb12012-02-02 01:58:08 +00001020 pNew->nExpr = i = p->nExpr;
1021 if( (flags & EXPRDUP_REDUCE)==0 ) for(i=1; i<p->nExpr; i+=i){}
drh575fad62016-02-05 13:38:36 +00001022 pNew->a = pItem = sqlite3DbMallocRawNN(db, i*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +00001023 if( pItem==0 ){
drh633e6d52008-07-28 19:34:53 +00001024 sqlite3DbFree(db, pNew);
danielk1977e0048402004-06-15 16:51:01 +00001025 return 0;
1026 }
drh145716b2004-09-24 12:24:06 +00001027 pOldItem = p->a;
1028 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
danielk19776ab3a2e2009-02-19 14:39:25 +00001029 Expr *pOldExpr = pOldItem->pExpr;
drhb5526ea2009-07-16 12:41:05 +00001030 pItem->pExpr = sqlite3ExprDup(db, pOldExpr, flags);
drh17435752007-08-16 04:30:38 +00001031 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drhb7916a72009-05-27 10:31:29 +00001032 pItem->zSpan = sqlite3DbStrDup(db, pOldItem->zSpan);
drh145716b2004-09-24 12:24:06 +00001033 pItem->sortOrder = pOldItem->sortOrder;
drh3e7bc9c2004-02-21 19:17:17 +00001034 pItem->done = 0;
drh2c036cf2013-06-26 00:34:13 +00001035 pItem->bSpanIsTab = pOldItem->bSpanIsTab;
drhc2acc4e2013-11-15 18:15:19 +00001036 pItem->u = pOldItem->u;
drhff78bd22002-02-27 01:47:11 +00001037 }
1038 return pNew;
1039}
danielk197793758c82005-01-21 08:13:14 +00001040
1041/*
1042** If cursors, triggers, views and subqueries are all omitted from
1043** the build, then none of the following routines, except for
1044** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
1045** called with a NULL argument.
1046*/
danielk19776a67fe82005-02-04 04:07:16 +00001047#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
1048 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19776ab3a2e2009-02-19 14:39:25 +00001049SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p, int flags){
drhad3cab52002-05-24 02:04:32 +00001050 SrcList *pNew;
1051 int i;
drh113088e2003-03-20 01:16:58 +00001052 int nByte;
drh575fad62016-02-05 13:38:36 +00001053 assert( db!=0 );
drhad3cab52002-05-24 02:04:32 +00001054 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +00001055 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh575fad62016-02-05 13:38:36 +00001056 pNew = sqlite3DbMallocRawNN(db, nByte );
drhad3cab52002-05-24 02:04:32 +00001057 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +00001058 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +00001059 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +00001060 struct SrcList_item *pNewItem = &pNew->a[i];
1061 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +00001062 Table *pTab;
dan41fb5cd2012-10-04 19:33:00 +00001063 pNewItem->pSchema = pOldItem->pSchema;
drh17435752007-08-16 04:30:38 +00001064 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
1065 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
1066 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh8a48b9c2015-08-19 15:20:00 +00001067 pNewItem->fg = pOldItem->fg;
drh4efc4752004-01-16 15:55:37 +00001068 pNewItem->iCursor = pOldItem->iCursor;
drh5b6a9ed2011-09-15 23:58:14 +00001069 pNewItem->addrFillSub = pOldItem->addrFillSub;
1070 pNewItem->regReturn = pOldItem->regReturn;
drh8a48b9c2015-08-19 15:20:00 +00001071 if( pNewItem->fg.isIndexedBy ){
1072 pNewItem->u1.zIndexedBy = sqlite3DbStrDup(db, pOldItem->u1.zIndexedBy);
1073 }
1074 pNewItem->pIBIndex = pOldItem->pIBIndex;
1075 if( pNewItem->fg.isTabFunc ){
1076 pNewItem->u1.pFuncArg =
1077 sqlite3ExprListDup(db, pOldItem->u1.pFuncArg, flags);
1078 }
drhed8a3bb2005-06-06 21:19:56 +00001079 pTab = pNewItem->pTab = pOldItem->pTab;
1080 if( pTab ){
1081 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +00001082 }
danielk19776ab3a2e2009-02-19 14:39:25 +00001083 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect, flags);
1084 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn, flags);
drh17435752007-08-16 04:30:38 +00001085 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +00001086 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +00001087 }
1088 return pNew;
1089}
drh17435752007-08-16 04:30:38 +00001090IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +00001091 IdList *pNew;
1092 int i;
drh575fad62016-02-05 13:38:36 +00001093 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001094 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001095 pNew = sqlite3DbMallocRawNN(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +00001096 if( pNew==0 ) return 0;
drh6c535152012-02-02 03:38:30 +00001097 pNew->nId = p->nId;
drh575fad62016-02-05 13:38:36 +00001098 pNew->a = sqlite3DbMallocRawNN(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +00001099 if( pNew->a==0 ){
drh633e6d52008-07-28 19:34:53 +00001100 sqlite3DbFree(db, pNew);
danielk1977d5d56522005-03-16 12:15:20 +00001101 return 0;
1102 }
drh6c535152012-02-02 03:38:30 +00001103 /* Note that because the size of the allocation for p->a[] is not
1104 ** necessarily a power of two, sqlite3IdListAppend() may not be called
1105 ** on the duplicate created by this function. */
drhff78bd22002-02-27 01:47:11 +00001106 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +00001107 struct IdList_item *pNewItem = &pNew->a[i];
1108 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +00001109 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +00001110 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +00001111 }
1112 return pNew;
1113}
danielk19776ab3a2e2009-02-19 14:39:25 +00001114Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
drh23b1b372011-12-07 01:55:51 +00001115 Select *pNew, *pPrior;
drh575fad62016-02-05 13:38:36 +00001116 assert( db!=0 );
drhff78bd22002-02-27 01:47:11 +00001117 if( p==0 ) return 0;
drh575fad62016-02-05 13:38:36 +00001118 pNew = sqlite3DbMallocRawNN(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +00001119 if( pNew==0 ) return 0;
drhb7916a72009-05-27 10:31:29 +00001120 pNew->pEList = sqlite3ExprListDup(db, p->pEList, flags);
danielk19776ab3a2e2009-02-19 14:39:25 +00001121 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc, flags);
1122 pNew->pWhere = sqlite3ExprDup(db, p->pWhere, flags);
1123 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy, flags);
1124 pNew->pHaving = sqlite3ExprDup(db, p->pHaving, flags);
1125 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy, flags);
drhff78bd22002-02-27 01:47:11 +00001126 pNew->op = p->op;
drh23b1b372011-12-07 01:55:51 +00001127 pNew->pPrior = pPrior = sqlite3SelectDup(db, p->pPrior, flags);
1128 if( pPrior ) pPrior->pNext = pNew;
1129 pNew->pNext = 0;
danielk19776ab3a2e2009-02-19 14:39:25 +00001130 pNew->pLimit = sqlite3ExprDup(db, p->pLimit, flags);
1131 pNew->pOffset = sqlite3ExprDup(db, p->pOffset, flags);
drh92b01d52008-06-24 00:32:35 +00001132 pNew->iLimit = 0;
1133 pNew->iOffset = 0;
drh7d10d5a2008-08-20 16:35:10 +00001134 pNew->selFlags = p->selFlags & ~SF_UsesEphemeral;
drhb9bb7c12006-06-11 23:41:55 +00001135 pNew->addrOpenEphm[0] = -1;
1136 pNew->addrOpenEphm[1] = -1;
drhec2da852014-01-29 01:46:12 +00001137 pNew->nSelectRow = p->nSelectRow;
dan4e9119d2014-01-13 15:12:23 +00001138 pNew->pWith = withDup(db, p->pWith);
drheb9b8842014-09-21 00:27:26 +00001139 sqlite3SelectSetName(pNew, p->zSelName);
drhff78bd22002-02-27 01:47:11 +00001140 return pNew;
1141}
danielk197793758c82005-01-21 08:13:14 +00001142#else
danielk19776ab3a2e2009-02-19 14:39:25 +00001143Select *sqlite3SelectDup(sqlite3 *db, Select *p, int flags){
danielk197793758c82005-01-21 08:13:14 +00001144 assert( p==0 );
1145 return 0;
1146}
1147#endif
drhff78bd22002-02-27 01:47:11 +00001148
1149
1150/*
drha76b5df2002-02-23 02:32:10 +00001151** Add a new element to the end of an expression list. If pList is
1152** initially NULL, then create a new expression list.
drhb7916a72009-05-27 10:31:29 +00001153**
1154** If a memory allocation error occurs, the entire list is freed and
1155** NULL is returned. If non-NULL is returned, then it is guaranteed
1156** that the new entry was successfully appended.
drha76b5df2002-02-23 02:32:10 +00001157*/
drh17435752007-08-16 04:30:38 +00001158ExprList *sqlite3ExprListAppend(
1159 Parse *pParse, /* Parsing context */
1160 ExprList *pList, /* List to which to append. Might be NULL */
drhb7916a72009-05-27 10:31:29 +00001161 Expr *pExpr /* Expression to be appended. Might be NULL */
drh17435752007-08-16 04:30:38 +00001162){
1163 sqlite3 *db = pParse->db;
drh575fad62016-02-05 13:38:36 +00001164 assert( db!=0 );
drha76b5df2002-02-23 02:32:10 +00001165 if( pList==0 ){
drh575fad62016-02-05 13:38:36 +00001166 pList = sqlite3DbMallocRawNN(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +00001167 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001168 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001169 }
drhc263f7c2016-01-18 13:18:54 +00001170 pList->nExpr = 0;
drh575fad62016-02-05 13:38:36 +00001171 pList->a = sqlite3DbMallocRawNN(db, sizeof(pList->a[0]));
drhd872bb12012-02-02 01:58:08 +00001172 if( pList->a==0 ) goto no_mem;
1173 }else if( (pList->nExpr & (pList->nExpr-1))==0 ){
danielk1977d5d56522005-03-16 12:15:20 +00001174 struct ExprList_item *a;
drhd872bb12012-02-02 01:58:08 +00001175 assert( pList->nExpr>0 );
1176 a = sqlite3DbRealloc(db, pList->a, pList->nExpr*2*sizeof(pList->a[0]));
danielk1977d5d56522005-03-16 12:15:20 +00001177 if( a==0 ){
1178 goto no_mem;
drha76b5df2002-02-23 02:32:10 +00001179 }
danielk1977d5d56522005-03-16 12:15:20 +00001180 pList->a = a;
drha76b5df2002-02-23 02:32:10 +00001181 }
drh4efc4752004-01-16 15:55:37 +00001182 assert( pList->a!=0 );
drhb7916a72009-05-27 10:31:29 +00001183 if( 1 ){
drh4efc4752004-01-16 15:55:37 +00001184 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
1185 memset(pItem, 0, sizeof(*pItem));
danielk1977e94ddc92005-03-21 03:53:38 +00001186 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +00001187 }
1188 return pList;
danielk1977d5d56522005-03-16 12:15:20 +00001189
1190no_mem:
1191 /* Avoid leaking memory if malloc has failed. */
drh633e6d52008-07-28 19:34:53 +00001192 sqlite3ExprDelete(db, pExpr);
1193 sqlite3ExprListDelete(db, pList);
danielk1977d5d56522005-03-16 12:15:20 +00001194 return 0;
drha76b5df2002-02-23 02:32:10 +00001195}
1196
1197/*
drhbc622bc2015-08-24 15:39:42 +00001198** Set the sort order for the last element on the given ExprList.
1199*/
1200void sqlite3ExprListSetSortOrder(ExprList *p, int iSortOrder){
1201 if( p==0 ) return;
1202 assert( SQLITE_SO_UNDEFINED<0 && SQLITE_SO_ASC>=0 && SQLITE_SO_DESC>0 );
1203 assert( p->nExpr>0 );
1204 if( iSortOrder<0 ){
1205 assert( p->a[p->nExpr-1].sortOrder==SQLITE_SO_ASC );
1206 return;
1207 }
1208 p->a[p->nExpr-1].sortOrder = (u8)iSortOrder;
drhbc622bc2015-08-24 15:39:42 +00001209}
1210
1211/*
drhb7916a72009-05-27 10:31:29 +00001212** Set the ExprList.a[].zName element of the most recently added item
1213** on the expression list.
1214**
1215** pList might be NULL following an OOM error. But pName should never be
1216** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1217** is set.
1218*/
1219void sqlite3ExprListSetName(
1220 Parse *pParse, /* Parsing context */
1221 ExprList *pList, /* List to which to add the span. */
1222 Token *pName, /* Name to be added */
1223 int dequote /* True to cause the name to be dequoted */
1224){
1225 assert( pList!=0 || pParse->db->mallocFailed!=0 );
1226 if( pList ){
1227 struct ExprList_item *pItem;
1228 assert( pList->nExpr>0 );
1229 pItem = &pList->a[pList->nExpr-1];
1230 assert( pItem->zName==0 );
1231 pItem->zName = sqlite3DbStrNDup(pParse->db, pName->z, pName->n);
1232 if( dequote && pItem->zName ) sqlite3Dequote(pItem->zName);
1233 }
1234}
1235
1236/*
1237** Set the ExprList.a[].zSpan element of the most recently added item
1238** on the expression list.
1239**
1240** pList might be NULL following an OOM error. But pSpan should never be
1241** NULL. If a memory allocation fails, the pParse->db->mallocFailed flag
1242** is set.
1243*/
1244void sqlite3ExprListSetSpan(
1245 Parse *pParse, /* Parsing context */
1246 ExprList *pList, /* List to which to add the span. */
1247 ExprSpan *pSpan /* The span to be added */
1248){
1249 sqlite3 *db = pParse->db;
1250 assert( pList!=0 || db->mallocFailed!=0 );
1251 if( pList ){
1252 struct ExprList_item *pItem = &pList->a[pList->nExpr-1];
1253 assert( pList->nExpr>0 );
1254 assert( db->mallocFailed || pItem->pExpr==pSpan->pExpr );
1255 sqlite3DbFree(db, pItem->zSpan);
1256 pItem->zSpan = sqlite3DbStrNDup(db, (char*)pSpan->zStart,
shanecf697392009-06-01 16:53:09 +00001257 (int)(pSpan->zEnd - pSpan->zStart));
drhb7916a72009-05-27 10:31:29 +00001258 }
1259}
1260
1261/*
danielk19777a15a4b2007-05-08 17:54:43 +00001262** If the expression list pEList contains more than iLimit elements,
1263** leave an error message in pParse.
1264*/
1265void sqlite3ExprListCheckLength(
1266 Parse *pParse,
1267 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +00001268 const char *zObject
1269){
drhb1a6c3c2008-03-20 16:30:17 +00001270 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +00001271 testcase( pEList && pEList->nExpr==mx );
1272 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +00001273 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +00001274 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
1275 }
1276}
1277
1278/*
drha76b5df2002-02-23 02:32:10 +00001279** Delete an entire expression list.
1280*/
drhaffa8552016-04-11 18:25:05 +00001281static SQLITE_NOINLINE void exprListDeleteNN(sqlite3 *db, ExprList *pList){
drha76b5df2002-02-23 02:32:10 +00001282 int i;
drhbe5c89a2004-07-26 00:31:09 +00001283 struct ExprList_item *pItem;
drhd872bb12012-02-02 01:58:08 +00001284 assert( pList->a!=0 || pList->nExpr==0 );
drhbe5c89a2004-07-26 00:31:09 +00001285 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
drh633e6d52008-07-28 19:34:53 +00001286 sqlite3ExprDelete(db, pItem->pExpr);
1287 sqlite3DbFree(db, pItem->zName);
drhb7916a72009-05-27 10:31:29 +00001288 sqlite3DbFree(db, pItem->zSpan);
drha76b5df2002-02-23 02:32:10 +00001289 }
drh633e6d52008-07-28 19:34:53 +00001290 sqlite3DbFree(db, pList->a);
1291 sqlite3DbFree(db, pList);
drha76b5df2002-02-23 02:32:10 +00001292}
drhaffa8552016-04-11 18:25:05 +00001293void sqlite3ExprListDelete(sqlite3 *db, ExprList *pList){
1294 if( pList ) exprListDeleteNN(db, pList);
1295}
drha76b5df2002-02-23 02:32:10 +00001296
1297/*
drh2308ed32015-02-09 16:09:34 +00001298** Return the bitwise-OR of all Expr.flags fields in the given
1299** ExprList.
drh885a5b02015-02-09 15:21:36 +00001300*/
drh2308ed32015-02-09 16:09:34 +00001301u32 sqlite3ExprListFlags(const ExprList *pList){
drh885a5b02015-02-09 15:21:36 +00001302 int i;
drh2308ed32015-02-09 16:09:34 +00001303 u32 m = 0;
1304 if( pList ){
1305 for(i=0; i<pList->nExpr; i++){
drhd0c73052015-04-19 19:21:19 +00001306 Expr *pExpr = pList->a[i].pExpr;
drhde845c22016-03-17 19:07:52 +00001307 assert( pExpr!=0 );
1308 m |= pExpr->flags;
drh2308ed32015-02-09 16:09:34 +00001309 }
drh885a5b02015-02-09 15:21:36 +00001310 }
drh2308ed32015-02-09 16:09:34 +00001311 return m;
drh885a5b02015-02-09 15:21:36 +00001312}
1313
1314/*
drh059b2d52014-10-24 19:28:09 +00001315** These routines are Walker callbacks used to check expressions to
1316** see if they are "constant" for some definition of constant. The
1317** Walker.eCode value determines the type of "constant" we are looking
1318** for.
drh73b211a2005-01-18 04:00:42 +00001319**
drh7d10d5a2008-08-20 16:35:10 +00001320** These callback routines are used to implement the following:
drh626a8792005-01-17 22:08:19 +00001321**
drh059b2d52014-10-24 19:28:09 +00001322** sqlite3ExprIsConstant() pWalker->eCode==1
1323** sqlite3ExprIsConstantNotJoin() pWalker->eCode==2
drhfcb9f4f2015-06-01 18:13:16 +00001324** sqlite3ExprIsTableConstant() pWalker->eCode==3
drh059b2d52014-10-24 19:28:09 +00001325** sqlite3ExprIsConstantOrFunction() pWalker->eCode==4 or 5
drh87abf5c2005-08-25 12:45:04 +00001326**
drh059b2d52014-10-24 19:28:09 +00001327** In all cases, the callbacks set Walker.eCode=0 and abort if the expression
1328** is found to not be a constant.
drh87abf5c2005-08-25 12:45:04 +00001329**
drhfeada2d2014-09-24 13:20:22 +00001330** The sqlite3ExprIsConstantOrFunction() is used for evaluating expressions
drh059b2d52014-10-24 19:28:09 +00001331** in a CREATE TABLE statement. The Walker.eCode value is 5 when parsing
1332** an existing schema and 4 when processing a new statement. A bound
drhfeada2d2014-09-24 13:20:22 +00001333** parameter raises an error for new statements, but is silently converted
1334** to NULL for existing schemas. This allows sqlite_master tables that
1335** contain a bound parameter because they were generated by older versions
1336** of SQLite to be parsed by newer versions of SQLite without raising a
1337** malformed schema error.
drh626a8792005-01-17 22:08:19 +00001338*/
drh7d10d5a2008-08-20 16:35:10 +00001339static int exprNodeIsConstant(Walker *pWalker, Expr *pExpr){
drh626a8792005-01-17 22:08:19 +00001340
drh059b2d52014-10-24 19:28:09 +00001341 /* If pWalker->eCode is 2 then any term of the expression that comes from
1342 ** the ON or USING clauses of a left join disqualifies the expression
drh0a168372007-06-08 00:20:47 +00001343 ** from being considered constant. */
drh059b2d52014-10-24 19:28:09 +00001344 if( pWalker->eCode==2 && ExprHasProperty(pExpr, EP_FromJoin) ){
1345 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001346 return WRC_Abort;
drh0a168372007-06-08 00:20:47 +00001347 }
1348
drh626a8792005-01-17 22:08:19 +00001349 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +00001350 /* Consider functions to be constant if all their arguments are constant
drh059b2d52014-10-24 19:28:09 +00001351 ** and either pWalker->eCode==4 or 5 or the function has the
1352 ** SQLITE_FUNC_CONST flag. */
drheb55bd22005-06-30 17:04:21 +00001353 case TK_FUNCTION:
drh63f84572015-02-09 14:07:07 +00001354 if( pWalker->eCode>=4 || ExprHasProperty(pExpr,EP_ConstFunc) ){
drhb1fba282013-11-21 14:33:48 +00001355 return WRC_Continue;
drh059b2d52014-10-24 19:28:09 +00001356 }else{
1357 pWalker->eCode = 0;
1358 return WRC_Abort;
drhb1fba282013-11-21 14:33:48 +00001359 }
drh626a8792005-01-17 22:08:19 +00001360 case TK_ID:
1361 case TK_COLUMN:
drh626a8792005-01-17 22:08:19 +00001362 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +00001363 case TK_AGG_COLUMN:
drhc5499be2008-04-01 15:06:33 +00001364 testcase( pExpr->op==TK_ID );
1365 testcase( pExpr->op==TK_COLUMN );
drhc5499be2008-04-01 15:06:33 +00001366 testcase( pExpr->op==TK_AGG_FUNCTION );
1367 testcase( pExpr->op==TK_AGG_COLUMN );
drh059b2d52014-10-24 19:28:09 +00001368 if( pWalker->eCode==3 && pExpr->iTable==pWalker->u.iCur ){
1369 return WRC_Continue;
1370 }else{
1371 pWalker->eCode = 0;
1372 return WRC_Abort;
1373 }
drhfeada2d2014-09-24 13:20:22 +00001374 case TK_VARIABLE:
drh059b2d52014-10-24 19:28:09 +00001375 if( pWalker->eCode==5 ){
drhfeada2d2014-09-24 13:20:22 +00001376 /* Silently convert bound parameters that appear inside of CREATE
1377 ** statements into a NULL when parsing the CREATE statement text out
1378 ** of the sqlite_master table */
1379 pExpr->op = TK_NULL;
drh059b2d52014-10-24 19:28:09 +00001380 }else if( pWalker->eCode==4 ){
drhfeada2d2014-09-24 13:20:22 +00001381 /* A bound parameter in a CREATE statement that originates from
1382 ** sqlite3_prepare() causes an error */
drh059b2d52014-10-24 19:28:09 +00001383 pWalker->eCode = 0;
drhfeada2d2014-09-24 13:20:22 +00001384 return WRC_Abort;
1385 }
1386 /* Fall through */
drh626a8792005-01-17 22:08:19 +00001387 default:
drhb74b1012009-05-28 21:04:37 +00001388 testcase( pExpr->op==TK_SELECT ); /* selectNodeIsConstant will disallow */
1389 testcase( pExpr->op==TK_EXISTS ); /* selectNodeIsConstant will disallow */
drh7d10d5a2008-08-20 16:35:10 +00001390 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00001391 }
1392}
danielk197762c14b32008-11-19 09:05:26 +00001393static int selectNodeIsConstant(Walker *pWalker, Select *NotUsed){
1394 UNUSED_PARAMETER(NotUsed);
drh059b2d52014-10-24 19:28:09 +00001395 pWalker->eCode = 0;
drh7d10d5a2008-08-20 16:35:10 +00001396 return WRC_Abort;
1397}
drh059b2d52014-10-24 19:28:09 +00001398static int exprIsConst(Expr *p, int initFlag, int iCur){
drh7d10d5a2008-08-20 16:35:10 +00001399 Walker w;
drhaa87f9a2013-04-25 00:57:10 +00001400 memset(&w, 0, sizeof(w));
drh059b2d52014-10-24 19:28:09 +00001401 w.eCode = initFlag;
drh7d10d5a2008-08-20 16:35:10 +00001402 w.xExprCallback = exprNodeIsConstant;
1403 w.xSelectCallback = selectNodeIsConstant;
drh059b2d52014-10-24 19:28:09 +00001404 w.u.iCur = iCur;
drh7d10d5a2008-08-20 16:35:10 +00001405 sqlite3WalkExpr(&w, p);
drh059b2d52014-10-24 19:28:09 +00001406 return w.eCode;
drh7d10d5a2008-08-20 16:35:10 +00001407}
drh626a8792005-01-17 22:08:19 +00001408
1409/*
drh059b2d52014-10-24 19:28:09 +00001410** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001411** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +00001412**
1413** For the purposes of this function, a double-quoted string (ex: "abc")
1414** is considered a variable but a single-quoted string (ex: 'abc') is
1415** a constant.
drhfef52082000-06-06 01:50:43 +00001416*/
danielk19774adee202004-05-08 08:23:19 +00001417int sqlite3ExprIsConstant(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001418 return exprIsConst(p, 1, 0);
drhfef52082000-06-06 01:50:43 +00001419}
1420
1421/*
drh059b2d52014-10-24 19:28:09 +00001422** Walk an expression tree. Return non-zero if the expression is constant
drh0a168372007-06-08 00:20:47 +00001423** that does no originate from the ON or USING clauses of a join.
1424** Return 0 if it involves variables or function calls or terms from
1425** an ON or USING clause.
1426*/
1427int sqlite3ExprIsConstantNotJoin(Expr *p){
drh059b2d52014-10-24 19:28:09 +00001428 return exprIsConst(p, 2, 0);
drh0a168372007-06-08 00:20:47 +00001429}
1430
1431/*
drhfcb9f4f2015-06-01 18:13:16 +00001432** Walk an expression tree. Return non-zero if the expression is constant
drh059b2d52014-10-24 19:28:09 +00001433** for any single row of the table with cursor iCur. In other words, the
1434** expression must not refer to any non-deterministic function nor any
1435** table other than iCur.
1436*/
1437int sqlite3ExprIsTableConstant(Expr *p, int iCur){
1438 return exprIsConst(p, 3, iCur);
1439}
1440
1441/*
1442** Walk an expression tree. Return non-zero if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001443** or a function call with constant arguments. Return and 0 if there
1444** are any variables.
1445**
1446** For the purposes of this function, a double-quoted string (ex: "abc")
1447** is considered a variable but a single-quoted string (ex: 'abc') is
1448** a constant.
1449*/
drhfeada2d2014-09-24 13:20:22 +00001450int sqlite3ExprIsConstantOrFunction(Expr *p, u8 isInit){
1451 assert( isInit==0 || isInit==1 );
drh059b2d52014-10-24 19:28:09 +00001452 return exprIsConst(p, 4+isInit, 0);
drheb55bd22005-06-30 17:04:21 +00001453}
1454
drh5b88bc42013-12-07 23:35:21 +00001455#ifdef SQLITE_ENABLE_CURSOR_HINTS
1456/*
1457** Walk an expression tree. Return 1 if the expression contains a
1458** subquery of some kind. Return 0 if there are no subqueries.
1459*/
1460int sqlite3ExprContainsSubquery(Expr *p){
1461 Walker w;
1462 memset(&w, 0, sizeof(w));
drhbec24762015-08-13 20:07:13 +00001463 w.eCode = 1;
drh5b88bc42013-12-07 23:35:21 +00001464 w.xExprCallback = sqlite3ExprWalkNoop;
1465 w.xSelectCallback = selectNodeIsConstant;
1466 sqlite3WalkExpr(&w, p);
drh07194bf2015-08-13 20:34:41 +00001467 return w.eCode==0;
drh5b88bc42013-12-07 23:35:21 +00001468}
1469#endif
1470
drheb55bd22005-06-30 17:04:21 +00001471/*
drh73b211a2005-01-18 04:00:42 +00001472** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001473** to fit in a 32-bit integer, return 1 and put the value of the integer
1474** in *pValue. If the expression is not an integer or if it is too big
1475** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001476*/
danielk19774adee202004-05-08 08:23:19 +00001477int sqlite3ExprIsInteger(Expr *p, int *pValue){
drh92b01d52008-06-24 00:32:35 +00001478 int rc = 0;
drhcd92e842011-02-17 15:58:20 +00001479
1480 /* If an expression is an integer literal that fits in a signed 32-bit
1481 ** integer, then the EP_IntValue flag will have already been set */
1482 assert( p->op!=TK_INTEGER || (p->flags & EP_IntValue)!=0
1483 || sqlite3GetInt32(p->u.zToken, &rc)==0 );
1484
drh92b01d52008-06-24 00:32:35 +00001485 if( p->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00001486 *pValue = p->u.iValue;
drh92b01d52008-06-24 00:32:35 +00001487 return 1;
1488 }
drhe4de1fe2002-06-02 16:09:01 +00001489 switch( p->op ){
drh4b59ab52002-08-24 18:24:51 +00001490 case TK_UPLUS: {
drh92b01d52008-06-24 00:32:35 +00001491 rc = sqlite3ExprIsInteger(p->pLeft, pValue);
drhf6e369a2008-06-24 12:46:30 +00001492 break;
drh4b59ab52002-08-24 18:24:51 +00001493 }
drhe4de1fe2002-06-02 16:09:01 +00001494 case TK_UMINUS: {
1495 int v;
danielk19774adee202004-05-08 08:23:19 +00001496 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
mistachkinf6418892013-08-28 01:54:12 +00001497 assert( v!=(-2147483647-1) );
drhe4de1fe2002-06-02 16:09:01 +00001498 *pValue = -v;
drh92b01d52008-06-24 00:32:35 +00001499 rc = 1;
drhe4de1fe2002-06-02 16:09:01 +00001500 }
1501 break;
1502 }
1503 default: break;
1504 }
drh92b01d52008-06-24 00:32:35 +00001505 return rc;
drhe4de1fe2002-06-02 16:09:01 +00001506}
1507
1508/*
drh039fc322009-11-17 18:31:47 +00001509** Return FALSE if there is no chance that the expression can be NULL.
1510**
1511** If the expression might be NULL or if the expression is too complex
1512** to tell return TRUE.
1513**
1514** This routine is used as an optimization, to skip OP_IsNull opcodes
1515** when we know that a value cannot be NULL. Hence, a false positive
1516** (returning TRUE when in fact the expression can never be NULL) might
1517** be a small performance hit but is otherwise harmless. On the other
1518** hand, a false negative (returning FALSE when the result could be NULL)
1519** will likely result in an incorrect answer. So when in doubt, return
1520** TRUE.
1521*/
1522int sqlite3ExprCanBeNull(const Expr *p){
1523 u8 op;
drhcd7f4572009-11-19 14:48:40 +00001524 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001525 op = p->op;
1526 if( op==TK_REGISTER ) op = p->op2;
1527 switch( op ){
1528 case TK_INTEGER:
1529 case TK_STRING:
1530 case TK_FLOAT:
1531 case TK_BLOB:
1532 return 0;
drh7248a8b2014-08-04 18:50:54 +00001533 case TK_COLUMN:
1534 assert( p->pTab!=0 );
drh72673a22014-12-04 16:27:17 +00001535 return ExprHasProperty(p, EP_CanBeNull) ||
1536 (p->iColumn>=0 && p->pTab->aCol[p->iColumn].notNull==0);
drh039fc322009-11-17 18:31:47 +00001537 default:
1538 return 1;
1539 }
1540}
1541
1542/*
1543** Return TRUE if the given expression is a constant which would be
1544** unchanged by OP_Affinity with the affinity given in the second
1545** argument.
1546**
1547** This routine is used to determine if the OP_Affinity operation
1548** can be omitted. When in doubt return FALSE. A false negative
1549** is harmless. A false positive, however, can result in the wrong
1550** answer.
1551*/
1552int sqlite3ExprNeedsNoAffinityChange(const Expr *p, char aff){
1553 u8 op;
drh05883a32015-06-02 15:32:08 +00001554 if( aff==SQLITE_AFF_BLOB ) return 1;
drhcd7f4572009-11-19 14:48:40 +00001555 while( p->op==TK_UPLUS || p->op==TK_UMINUS ){ p = p->pLeft; }
drh039fc322009-11-17 18:31:47 +00001556 op = p->op;
1557 if( op==TK_REGISTER ) op = p->op2;
1558 switch( op ){
1559 case TK_INTEGER: {
1560 return aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC;
1561 }
1562 case TK_FLOAT: {
1563 return aff==SQLITE_AFF_REAL || aff==SQLITE_AFF_NUMERIC;
1564 }
1565 case TK_STRING: {
1566 return aff==SQLITE_AFF_TEXT;
1567 }
1568 case TK_BLOB: {
1569 return 1;
1570 }
drh2f2855b2009-11-18 01:25:26 +00001571 case TK_COLUMN: {
drh88376ca2009-11-19 15:44:53 +00001572 assert( p->iTable>=0 ); /* p cannot be part of a CHECK constraint */
1573 return p->iColumn<0
1574 && (aff==SQLITE_AFF_INTEGER || aff==SQLITE_AFF_NUMERIC);
drh2f2855b2009-11-18 01:25:26 +00001575 }
drh039fc322009-11-17 18:31:47 +00001576 default: {
1577 return 0;
1578 }
1579 }
1580}
1581
1582/*
drhc4a3c772001-04-04 11:48:57 +00001583** Return TRUE if the given string is a row-id column name.
1584*/
danielk19774adee202004-05-08 08:23:19 +00001585int sqlite3IsRowid(const char *z){
1586 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1587 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1588 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001589 return 0;
1590}
1591
danielk19779a96b662007-11-29 17:05:18 +00001592/*
drh69c355b2016-03-09 15:34:51 +00001593** pX is the RHS of an IN operator. If pX is a SELECT statement
1594** that can be simplified to a direct table access, then return
1595** a pointer to the SELECT statement. If pX is not a SELECT statement,
1596** or if the SELECT statement needs to be manifested into a transient
1597** table, then return NULL.
drhb287f4b2008-04-25 00:08:38 +00001598*/
1599#ifndef SQLITE_OMIT_SUBQUERY
drh69c355b2016-03-09 15:34:51 +00001600static Select *isCandidateForInOpt(Expr *pX){
1601 Select *p;
drhb287f4b2008-04-25 00:08:38 +00001602 SrcList *pSrc;
1603 ExprList *pEList;
drh69c355b2016-03-09 15:34:51 +00001604 Expr *pRes;
drhb287f4b2008-04-25 00:08:38 +00001605 Table *pTab;
drh69c355b2016-03-09 15:34:51 +00001606 if( !ExprHasProperty(pX, EP_xIsSelect) ) return 0; /* Not a subquery */
1607 if( ExprHasProperty(pX, EP_VarSelect) ) return 0; /* Correlated subq */
1608 p = pX->x.pSelect;
drhb287f4b2008-04-25 00:08:38 +00001609 if( p->pPrior ) return 0; /* Not a compound SELECT */
drh7d10d5a2008-08-20 16:35:10 +00001610 if( p->selFlags & (SF_Distinct|SF_Aggregate) ){
drhb74b1012009-05-28 21:04:37 +00001611 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
1612 testcase( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
1613 return 0; /* No DISTINCT keyword and no aggregate functions */
drh7d10d5a2008-08-20 16:35:10 +00001614 }
drhb74b1012009-05-28 21:04:37 +00001615 assert( p->pGroupBy==0 ); /* Has no GROUP BY clause */
drhb287f4b2008-04-25 00:08:38 +00001616 if( p->pLimit ) return 0; /* Has no LIMIT clause */
drhb74b1012009-05-28 21:04:37 +00001617 assert( p->pOffset==0 ); /* No LIMIT means no OFFSET */
drhb287f4b2008-04-25 00:08:38 +00001618 if( p->pWhere ) return 0; /* Has no WHERE clause */
1619 pSrc = p->pSrc;
drhd1fa7bc2009-01-10 13:24:50 +00001620 assert( pSrc!=0 );
1621 if( pSrc->nSrc!=1 ) return 0; /* Single term in FROM clause */
drhb74b1012009-05-28 21:04:37 +00001622 if( pSrc->a[0].pSelect ) return 0; /* FROM is not a subquery or view */
drhb287f4b2008-04-25 00:08:38 +00001623 pTab = pSrc->a[0].pTab;
drh69c355b2016-03-09 15:34:51 +00001624 assert( pTab!=0 );
drhb74b1012009-05-28 21:04:37 +00001625 assert( pTab->pSelect==0 ); /* FROM clause is not a view */
drhb287f4b2008-04-25 00:08:38 +00001626 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1627 pEList = p->pEList;
1628 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
drh90730c92016-03-09 15:09:22 +00001629 pRes = pEList->a[0].pExpr;
1630 if( pRes->op!=TK_COLUMN ) return 0; /* Result is a column */
drh69c355b2016-03-09 15:34:51 +00001631 assert( pRes->iTable==pSrc->a[0].iCursor ); /* Not a correlated subquery */
1632 return p;
drhb287f4b2008-04-25 00:08:38 +00001633}
1634#endif /* SQLITE_OMIT_SUBQUERY */
1635
1636/*
dan1d8cb212011-12-09 13:24:16 +00001637** Code an OP_Once instruction and allocate space for its flag. Return the
1638** address of the new instruction.
1639*/
1640int sqlite3CodeOnce(Parse *pParse){
1641 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
1642 return sqlite3VdbeAddOp1(v, OP_Once, pParse->nOnce++);
1643}
1644
1645/*
drh4c259e92014-08-01 21:12:35 +00001646** Generate code that checks the left-most column of index table iCur to see if
1647** it contains any NULL entries. Cause the register at regHasNull to be set
drh6be515e2014-08-01 21:00:53 +00001648** to a non-NULL value if iCur contains no NULLs. Cause register regHasNull
1649** to be set to NULL if iCur contains one or more NULL values.
1650*/
1651static void sqlite3SetHasNullFlag(Vdbe *v, int iCur, int regHasNull){
drh728e0f92015-10-10 14:41:28 +00001652 int addr1;
drh6be515e2014-08-01 21:00:53 +00001653 sqlite3VdbeAddOp2(v, OP_Integer, 0, regHasNull);
drh728e0f92015-10-10 14:41:28 +00001654 addr1 = sqlite3VdbeAddOp1(v, OP_Rewind, iCur); VdbeCoverage(v);
drh6be515e2014-08-01 21:00:53 +00001655 sqlite3VdbeAddOp3(v, OP_Column, iCur, 0, regHasNull);
1656 sqlite3VdbeChangeP5(v, OPFLAG_TYPEOFARG);
drh4c259e92014-08-01 21:12:35 +00001657 VdbeComment((v, "first_entry_in(%d)", iCur));
drh728e0f92015-10-10 14:41:28 +00001658 sqlite3VdbeJumpHere(v, addr1);
drh6be515e2014-08-01 21:00:53 +00001659}
1660
drhbb53ecb2014-08-02 21:03:33 +00001661
1662#ifndef SQLITE_OMIT_SUBQUERY
1663/*
1664** The argument is an IN operator with a list (not a subquery) on the
1665** right-hand side. Return TRUE if that list is constant.
1666*/
1667static int sqlite3InRhsIsConstant(Expr *pIn){
1668 Expr *pLHS;
1669 int res;
1670 assert( !ExprHasProperty(pIn, EP_xIsSelect) );
1671 pLHS = pIn->pLeft;
1672 pIn->pLeft = 0;
1673 res = sqlite3ExprIsConstant(pIn);
1674 pIn->pLeft = pLHS;
1675 return res;
1676}
1677#endif
1678
drh6be515e2014-08-01 21:00:53 +00001679/*
danielk19779a96b662007-11-29 17:05:18 +00001680** This function is used by the implementation of the IN (...) operator.
drhd4305ca2012-09-18 17:08:33 +00001681** The pX parameter is the expression on the RHS of the IN operator, which
1682** might be either a list of expressions or a subquery.
danielk19779a96b662007-11-29 17:05:18 +00001683**
drhd4305ca2012-09-18 17:08:33 +00001684** The job of this routine is to find or create a b-tree object that can
1685** be used either to test for membership in the RHS set or to iterate through
1686** all members of the RHS set, skipping duplicates.
1687**
drh3a856252014-08-01 14:46:57 +00001688** A cursor is opened on the b-tree object that is the RHS of the IN operator
drhd4305ca2012-09-18 17:08:33 +00001689** and pX->iTable is set to the index of that cursor.
1690**
drhb74b1012009-05-28 21:04:37 +00001691** The returned value of this function indicates the b-tree type, as follows:
danielk19779a96b662007-11-29 17:05:18 +00001692**
drh1ccce442013-03-12 20:38:51 +00001693** IN_INDEX_ROWID - The cursor was opened on a database table.
1694** IN_INDEX_INDEX_ASC - The cursor was opened on an ascending index.
1695** IN_INDEX_INDEX_DESC - The cursor was opened on a descending index.
1696** IN_INDEX_EPH - The cursor was opened on a specially created and
1697** populated epheremal table.
drhbb53ecb2014-08-02 21:03:33 +00001698** IN_INDEX_NOOP - No cursor was allocated. The IN operator must be
1699** implemented as a sequence of comparisons.
danielk19779a96b662007-11-29 17:05:18 +00001700**
drhd4305ca2012-09-18 17:08:33 +00001701** An existing b-tree might be used if the RHS expression pX is a simple
1702** subquery such as:
danielk19779a96b662007-11-29 17:05:18 +00001703**
1704** SELECT <column> FROM <table>
1705**
drhd4305ca2012-09-18 17:08:33 +00001706** If the RHS of the IN operator is a list or a more complex subquery, then
1707** an ephemeral table might need to be generated from the RHS and then
peter.d.reid60ec9142014-09-06 16:39:46 +00001708** pX->iTable made to point to the ephemeral table instead of an
drh3a856252014-08-01 14:46:57 +00001709** existing table.
drhd4305ca2012-09-18 17:08:33 +00001710**
drh3a856252014-08-01 14:46:57 +00001711** The inFlags parameter must contain exactly one of the bits
1712** IN_INDEX_MEMBERSHIP or IN_INDEX_LOOP. If inFlags contains
1713** IN_INDEX_MEMBERSHIP, then the generated table will be used for a
1714** fast membership test. When the IN_INDEX_LOOP bit is set, the
1715** IN index will be used to loop over all values of the RHS of the
1716** IN operator.
1717**
1718** When IN_INDEX_LOOP is used (and the b-tree will be used to iterate
1719** through the set members) then the b-tree must not contain duplicates.
1720** An epheremal table must be used unless the selected <column> is guaranteed
danielk19779a96b662007-11-29 17:05:18 +00001721** to be unique - either because it is an INTEGER PRIMARY KEY or it
drhb74b1012009-05-28 21:04:37 +00001722** has a UNIQUE constraint or UNIQUE index.
danielk19770cdc0222008-06-26 18:04:03 +00001723**
drh3a856252014-08-01 14:46:57 +00001724** When IN_INDEX_MEMBERSHIP is used (and the b-tree will be used
1725** for fast set membership tests) then an epheremal table must
danielk19770cdc0222008-06-26 18:04:03 +00001726** be used unless <column> is an INTEGER PRIMARY KEY or an index can
1727** be found with <column> as its left-most column.
1728**
drhbb53ecb2014-08-02 21:03:33 +00001729** If the IN_INDEX_NOOP_OK and IN_INDEX_MEMBERSHIP are both set and
1730** if the RHS of the IN operator is a list (not a subquery) then this
1731** routine might decide that creating an ephemeral b-tree for membership
1732** testing is too expensive and return IN_INDEX_NOOP. In that case, the
1733** calling routine should implement the IN operator using a sequence
1734** of Eq or Ne comparison operations.
1735**
drhb74b1012009-05-28 21:04:37 +00001736** When the b-tree is being used for membership tests, the calling function
drh3a856252014-08-01 14:46:57 +00001737** might need to know whether or not the RHS side of the IN operator
drhe21a6e12014-08-01 18:00:24 +00001738** contains a NULL. If prRhsHasNull is not a NULL pointer and
drh3a856252014-08-01 14:46:57 +00001739** if there is any chance that the (...) might contain a NULL value at
danielk19770cdc0222008-06-26 18:04:03 +00001740** runtime, then a register is allocated and the register number written
drhe21a6e12014-08-01 18:00:24 +00001741** to *prRhsHasNull. If there is no chance that the (...) contains a
1742** NULL value, then *prRhsHasNull is left unchanged.
danielk19770cdc0222008-06-26 18:04:03 +00001743**
drhe21a6e12014-08-01 18:00:24 +00001744** If a register is allocated and its location stored in *prRhsHasNull, then
drh6be515e2014-08-01 21:00:53 +00001745** the value in that register will be NULL if the b-tree contains one or more
1746** NULL values, and it will be some non-NULL value if the b-tree contains no
1747** NULL values.
danielk19779a96b662007-11-29 17:05:18 +00001748*/
danielk1977284f4ac2007-12-10 05:03:46 +00001749#ifndef SQLITE_OMIT_SUBQUERY
drhe21a6e12014-08-01 18:00:24 +00001750int sqlite3FindInIndex(Parse *pParse, Expr *pX, u32 inFlags, int *prRhsHasNull){
drhb74b1012009-05-28 21:04:37 +00001751 Select *p; /* SELECT to the right of IN operator */
1752 int eType = 0; /* Type of RHS table. IN_INDEX_* */
1753 int iTab = pParse->nTab++; /* Cursor of the RHS table */
drh3a856252014-08-01 14:46:57 +00001754 int mustBeUnique; /* True if RHS must be unique */
drhb8475df2011-12-09 16:21:19 +00001755 Vdbe *v = sqlite3GetVdbe(pParse); /* Virtual machine being coded */
danielk19779a96b662007-11-29 17:05:18 +00001756
drh1450bc62009-10-30 13:25:56 +00001757 assert( pX->op==TK_IN );
drh3a856252014-08-01 14:46:57 +00001758 mustBeUnique = (inFlags & IN_INDEX_LOOP)!=0;
drh1450bc62009-10-30 13:25:56 +00001759
drhb74b1012009-05-28 21:04:37 +00001760 /* Check to see if an existing table or index can be used to
1761 ** satisfy the query. This is preferable to generating a new
1762 ** ephemeral table.
danielk19779a96b662007-11-29 17:05:18 +00001763 */
drh69c355b2016-03-09 15:34:51 +00001764 if( pParse->nErr==0 && (p = isCandidateForInOpt(pX))!=0 ){
danielk1977e1fb65a2009-04-02 17:23:32 +00001765 sqlite3 *db = pParse->db; /* Database connection */
drhb07028f2011-10-14 21:49:18 +00001766 Table *pTab; /* Table <table>. */
1767 Expr *pExpr; /* Expression <column> */
drhbbbdc832013-10-22 18:01:40 +00001768 i16 iCol; /* Index of column <column> */
1769 i16 iDb; /* Database idx for pTab */
drhb07028f2011-10-14 21:49:18 +00001770
drhb07028f2011-10-14 21:49:18 +00001771 assert( p->pEList!=0 ); /* Because of isCandidateForInOpt(p) */
1772 assert( p->pEList->a[0].pExpr!=0 ); /* Because of isCandidateForInOpt(p) */
1773 assert( p->pSrc!=0 ); /* Because of isCandidateForInOpt(p) */
1774 pTab = p->pSrc->a[0].pTab;
1775 pExpr = p->pEList->a[0].pExpr;
drhbbbdc832013-10-22 18:01:40 +00001776 iCol = (i16)pExpr->iColumn;
danielk1977e1fb65a2009-04-02 17:23:32 +00001777
drhb22f7c82014-02-06 23:56:27 +00001778 /* Code an OP_Transaction and OP_TableLock for <table>. */
danielk1977e1fb65a2009-04-02 17:23:32 +00001779 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1780 sqlite3CodeVerifySchema(pParse, iDb);
1781 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
danielk19779a96b662007-11-29 17:05:18 +00001782
1783 /* This function is only called from two places. In both cases the vdbe
1784 ** has already been allocated. So assume sqlite3GetVdbe() is always
1785 ** successful here.
1786 */
1787 assert(v);
1788 if( iCol<0 ){
drh7d176102014-02-18 03:07:12 +00001789 int iAddr = sqlite3CodeOnce(pParse);
1790 VdbeCoverage(v);
danielk19779a96b662007-11-29 17:05:18 +00001791
1792 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1793 eType = IN_INDEX_ROWID;
1794
1795 sqlite3VdbeJumpHere(v, iAddr);
1796 }else{
danielk1977e1fb65a2009-04-02 17:23:32 +00001797 Index *pIdx; /* Iterator variable */
1798
drhb74b1012009-05-28 21:04:37 +00001799 /* The collation sequence used by the comparison. If an index is to
danielk19779a96b662007-11-29 17:05:18 +00001800 ** be used in place of a temp-table, it must be ordered according
danielk1977e1fb65a2009-04-02 17:23:32 +00001801 ** to this collation sequence. */
danielk19779a96b662007-11-29 17:05:18 +00001802 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1803
1804 /* Check that the affinity that will be used to perform the
1805 ** comparison is the same as the affinity of the column. If
1806 ** it is not, it is not possible to use any index.
1807 */
drhdbaee5e2012-09-18 19:29:06 +00001808 int affinity_ok = sqlite3IndexAffinityOk(pX, pTab->aCol[iCol].affinity);
danielk19779a96b662007-11-29 17:05:18 +00001809
1810 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1811 if( (pIdx->aiColumn[0]==iCol)
drhb74b1012009-05-28 21:04:37 +00001812 && sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], 0)==pReq
drh5f1d1d92014-07-31 22:59:04 +00001813 && (!mustBeUnique || (pIdx->nKeyCol==1 && IsUniqueIndex(pIdx)))
danielk19779a96b662007-11-29 17:05:18 +00001814 ){
drh7d176102014-02-18 03:07:12 +00001815 int iAddr = sqlite3CodeOnce(pParse); VdbeCoverage(v);
drh2ec2fb22013-11-06 19:59:23 +00001816 sqlite3VdbeAddOp3(v, OP_OpenRead, iTab, pIdx->tnum, iDb);
1817 sqlite3VdbeSetP4KeyInfo(pParse, pIdx);
danielk1977207872a2008-01-03 07:54:23 +00001818 VdbeComment((v, "%s", pIdx->zName));
drh1ccce442013-03-12 20:38:51 +00001819 assert( IN_INDEX_INDEX_DESC == IN_INDEX_INDEX_ASC+1 );
1820 eType = IN_INDEX_INDEX_ASC + pIdx->aSortOrder[0];
danielk19779a96b662007-11-29 17:05:18 +00001821
drhe21a6e12014-08-01 18:00:24 +00001822 if( prRhsHasNull && !pTab->aCol[iCol].notNull ){
1823 *prRhsHasNull = ++pParse->nMem;
drh6be515e2014-08-01 21:00:53 +00001824 sqlite3SetHasNullFlag(v, iTab, *prRhsHasNull);
danielk19770cdc0222008-06-26 18:04:03 +00001825 }
drh552fd452014-02-18 01:07:38 +00001826 sqlite3VdbeJumpHere(v, iAddr);
danielk19779a96b662007-11-29 17:05:18 +00001827 }
1828 }
1829 }
1830 }
1831
drhbb53ecb2014-08-02 21:03:33 +00001832 /* If no preexisting index is available for the IN clause
1833 ** and IN_INDEX_NOOP is an allowed reply
1834 ** and the RHS of the IN operator is a list, not a subquery
1835 ** and the RHS is not contant or has two or fewer terms,
peter.d.reid60ec9142014-09-06 16:39:46 +00001836 ** then it is not worth creating an ephemeral table to evaluate
drhbb53ecb2014-08-02 21:03:33 +00001837 ** the IN operator so return IN_INDEX_NOOP.
1838 */
1839 if( eType==0
1840 && (inFlags & IN_INDEX_NOOP_OK)
1841 && !ExprHasProperty(pX, EP_xIsSelect)
1842 && (!sqlite3InRhsIsConstant(pX) || pX->x.pList->nExpr<=2)
1843 ){
1844 eType = IN_INDEX_NOOP;
1845 }
1846
1847
danielk19779a96b662007-11-29 17:05:18 +00001848 if( eType==0 ){
drh43870062014-07-31 15:44:44 +00001849 /* Could not find an existing table or index to use as the RHS b-tree.
drhb74b1012009-05-28 21:04:37 +00001850 ** We will have to generate an ephemeral table to do the job.
1851 */
drh8e23daf2013-06-11 13:30:04 +00001852 u32 savedNQueryLoop = pParse->nQueryLoop;
danielk19770cdc0222008-06-26 18:04:03 +00001853 int rMayHaveNull = 0;
danielk197741a05b72008-10-02 13:50:55 +00001854 eType = IN_INDEX_EPH;
drh3a856252014-08-01 14:46:57 +00001855 if( inFlags & IN_INDEX_LOOP ){
drh4a5acf82013-06-18 20:06:23 +00001856 pParse->nQueryLoop = 0;
drhc5cd1242013-09-12 16:50:49 +00001857 if( pX->pLeft->iColumn<0 && !ExprHasProperty(pX, EP_xIsSelect) ){
drhcf4d38a2010-07-28 02:53:36 +00001858 eType = IN_INDEX_ROWID;
1859 }
drhe21a6e12014-08-01 18:00:24 +00001860 }else if( prRhsHasNull ){
1861 *prRhsHasNull = rMayHaveNull = ++pParse->nMem;
danielk19770cdc0222008-06-26 18:04:03 +00001862 }
danielk197741a05b72008-10-02 13:50:55 +00001863 sqlite3CodeSubselect(pParse, pX, rMayHaveNull, eType==IN_INDEX_ROWID);
drhcf4d38a2010-07-28 02:53:36 +00001864 pParse->nQueryLoop = savedNQueryLoop;
danielk19779a96b662007-11-29 17:05:18 +00001865 }else{
1866 pX->iTable = iTab;
1867 }
1868 return eType;
1869}
danielk1977284f4ac2007-12-10 05:03:46 +00001870#endif
drh626a8792005-01-17 22:08:19 +00001871
1872/*
drhd4187c72010-08-30 22:15:45 +00001873** Generate code for scalar subqueries used as a subquery expression, EXISTS,
1874** or IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00001875**
drh9cbe6352005-11-29 03:13:21 +00001876** (SELECT a FROM b) -- subquery
1877** EXISTS (SELECT a FROM b) -- EXISTS subquery
1878** x IN (4,5,11) -- IN operator with list on right-hand side
1879** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00001880**
drh9cbe6352005-11-29 03:13:21 +00001881** The pExpr parameter describes the expression that contains the IN
1882** operator or subquery.
danielk197741a05b72008-10-02 13:50:55 +00001883**
1884** If parameter isRowid is non-zero, then expression pExpr is guaranteed
1885** to be of the form "<rowid> IN (?, ?, ?)", where <rowid> is a reference
1886** to some integer key column of a table B-Tree. In this case, use an
1887** intkey B-Tree to store the set of IN(...) values instead of the usual
1888** (slower) variable length keys B-Tree.
drhfd773cf2009-05-29 14:39:07 +00001889**
1890** If rMayHaveNull is non-zero, that means that the operation is an IN
1891** (not a SELECT or EXISTS) and that the RHS might contains NULLs.
drh3a856252014-08-01 14:46:57 +00001892** All this routine does is initialize the register given by rMayHaveNull
1893** to NULL. Calling routines will take care of changing this register
1894** value to non-NULL if the RHS is NULL-free.
drh1450bc62009-10-30 13:25:56 +00001895**
1896** For a SELECT or EXISTS operator, return the register that holds the
1897** result. For IN operators or if an error occurs, the return value is 0.
drhcce7d172000-05-31 15:34:51 +00001898*/
drh51522cd2005-01-20 13:36:19 +00001899#ifndef SQLITE_OMIT_SUBQUERY
drh1450bc62009-10-30 13:25:56 +00001900int sqlite3CodeSubselect(
drhfd773cf2009-05-29 14:39:07 +00001901 Parse *pParse, /* Parsing context */
1902 Expr *pExpr, /* The IN, SELECT, or EXISTS operator */
drh6be515e2014-08-01 21:00:53 +00001903 int rHasNullFlag, /* Register that records whether NULLs exist in RHS */
drhfd773cf2009-05-29 14:39:07 +00001904 int isRowid /* If true, LHS of IN operator is a rowid */
danielk197741a05b72008-10-02 13:50:55 +00001905){
drh6be515e2014-08-01 21:00:53 +00001906 int jmpIfDynamic = -1; /* One-time test address */
drh1450bc62009-10-30 13:25:56 +00001907 int rReg = 0; /* Register storing resulting */
danielk1977b3bce662005-01-29 08:32:43 +00001908 Vdbe *v = sqlite3GetVdbe(pParse);
drh1450bc62009-10-30 13:25:56 +00001909 if( NEVER(v==0) ) return 0;
drhceea3322009-04-23 13:22:42 +00001910 sqlite3ExprCachePush(pParse);
danielk1977fc976062007-05-10 10:46:56 +00001911
drh57dbd7b2005-07-08 18:25:26 +00001912 /* This code must be run in its entirety every time it is encountered
1913 ** if any of the following is true:
1914 **
1915 ** * The right-hand side is a correlated subquery
1916 ** * The right-hand side is an expression list containing variables
1917 ** * We are inside a trigger
1918 **
1919 ** If all of the above are false, then we can run this code just once
1920 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00001921 */
drhc5cd1242013-09-12 16:50:49 +00001922 if( !ExprHasProperty(pExpr, EP_VarSelect) ){
drh6be515e2014-08-01 21:00:53 +00001923 jmpIfDynamic = sqlite3CodeOnce(pParse); VdbeCoverage(v);
danielk1977b3bce662005-01-29 08:32:43 +00001924 }
1925
dan4a07e3d2010-11-09 14:48:59 +00001926#ifndef SQLITE_OMIT_EXPLAIN
1927 if( pParse->explain==2 ){
drh62aaa6c2015-11-21 17:27:42 +00001928 char *zMsg = sqlite3MPrintf(pParse->db, "EXECUTE %s%s SUBQUERY %d",
1929 jmpIfDynamic>=0?"":"CORRELATED ",
1930 pExpr->op==TK_IN?"LIST":"SCALAR",
1931 pParse->iNextSelectId
dan4a07e3d2010-11-09 14:48:59 +00001932 );
1933 sqlite3VdbeAddOp4(v, OP_Explain, pParse->iSelectId, 0, 0, zMsg, P4_DYNAMIC);
1934 }
1935#endif
1936
drhcce7d172000-05-31 15:34:51 +00001937 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00001938 case TK_IN: {
drhd4187c72010-08-30 22:15:45 +00001939 char affinity; /* Affinity of the LHS of the IN */
drhd4187c72010-08-30 22:15:45 +00001940 int addr; /* Address of OP_OpenEphemeral instruction */
1941 Expr *pLeft = pExpr->pLeft; /* the LHS of the IN operator */
drh323df792013-08-05 19:11:29 +00001942 KeyInfo *pKeyInfo = 0; /* Key information */
drhd3d39e92004-05-20 22:16:29 +00001943
danielk197741a05b72008-10-02 13:50:55 +00001944 affinity = sqlite3ExprAffinity(pLeft);
danielk1977e014a832004-05-17 10:48:57 +00001945
1946 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh8cff69d2009-11-12 19:59:44 +00001947 ** expression it is handled the same way. An ephemeral table is
danielk1977e014a832004-05-17 10:48:57 +00001948 ** filled with single-field index keys representing the results
1949 ** from the SELECT or the <exprlist>.
1950 **
1951 ** If the 'x' expression is a column value, or the SELECT...
1952 ** statement returns a column value, then the affinity of that
1953 ** column is used to build the index keys. If both 'x' and the
1954 ** SELECT... statement are columns, then numeric affinity is used
1955 ** if either column has NUMERIC or INTEGER affinity. If neither
1956 ** 'x' nor the SELECT... statement are columns, then numeric affinity
1957 ** is used.
1958 */
1959 pExpr->iTable = pParse->nTab++;
danielk197741a05b72008-10-02 13:50:55 +00001960 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, !isRowid);
drhad124322013-10-23 13:30:58 +00001961 pKeyInfo = isRowid ? 0 : sqlite3KeyInfoAlloc(pParse->db, 1, 1);
danielk1977e014a832004-05-17 10:48:57 +00001962
danielk19776ab3a2e2009-02-19 14:39:25 +00001963 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drhfef52082000-06-06 01:50:43 +00001964 /* Case 1: expr IN (SELECT ...)
1965 **
danielk1977e014a832004-05-17 10:48:57 +00001966 ** Generate code to write the results of the select into the temporary
1967 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00001968 */
drh43870062014-07-31 15:44:44 +00001969 Select *pSelect = pExpr->x.pSelect;
drh1013c932008-01-06 00:25:21 +00001970 SelectDest dest;
drhbe5c89a2004-07-26 00:31:09 +00001971 ExprList *pEList;
drh1013c932008-01-06 00:25:21 +00001972
danielk197741a05b72008-10-02 13:50:55 +00001973 assert( !isRowid );
drh1013c932008-01-06 00:25:21 +00001974 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
drh2b596da2012-07-23 21:43:19 +00001975 dest.affSdst = (u8)affinity;
danielk1977e014a832004-05-17 10:48:57 +00001976 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
drh43870062014-07-31 15:44:44 +00001977 pSelect->iLimit = 0;
1978 testcase( pSelect->selFlags & SF_Distinct );
drh812ea832013-08-06 17:24:23 +00001979 testcase( pKeyInfo==0 ); /* Caused by OOM in sqlite3KeyInfoAlloc() */
drh43870062014-07-31 15:44:44 +00001980 if( sqlite3Select(pParse, pSelect, &dest) ){
drh2ec2fb22013-11-06 19:59:23 +00001981 sqlite3KeyInfoUnref(pKeyInfo);
drh1450bc62009-10-30 13:25:56 +00001982 return 0;
drh94ccde52007-04-13 16:06:32 +00001983 }
drh43870062014-07-31 15:44:44 +00001984 pEList = pSelect->pEList;
drh812ea832013-08-06 17:24:23 +00001985 assert( pKeyInfo!=0 ); /* OOM will cause exit after sqlite3Select() */
drh3535ec32013-08-06 16:56:44 +00001986 assert( pEList!=0 );
1987 assert( pEList->nExpr>0 );
drh2ec2fb22013-11-06 19:59:23 +00001988 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh3535ec32013-08-06 16:56:44 +00001989 pKeyInfo->aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1990 pEList->a[0].pExpr);
drha7d2db12010-07-14 20:23:52 +00001991 }else if( ALWAYS(pExpr->x.pList!=0) ){
drhfef52082000-06-06 01:50:43 +00001992 /* Case 2: expr IN (exprlist)
1993 **
drhfd131da2007-08-07 17:13:03 +00001994 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00001995 ** store it in the temporary table. If <expr> is a column, then use
1996 ** that columns affinity when building index keys. If <expr> is not
1997 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00001998 */
danielk1977e014a832004-05-17 10:48:57 +00001999 int i;
danielk19776ab3a2e2009-02-19 14:39:25 +00002000 ExprList *pList = pExpr->x.pList;
drh57dbd7b2005-07-08 18:25:26 +00002001 struct ExprList_item *pItem;
drhecc31802008-06-26 20:06:06 +00002002 int r1, r2, r3;
drh57dbd7b2005-07-08 18:25:26 +00002003
danielk1977e014a832004-05-17 10:48:57 +00002004 if( !affinity ){
drh05883a32015-06-02 15:32:08 +00002005 affinity = SQLITE_AFF_BLOB;
danielk1977e014a832004-05-17 10:48:57 +00002006 }
drh323df792013-08-05 19:11:29 +00002007 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002008 assert( sqlite3KeyInfoIsWriteable(pKeyInfo) );
drh323df792013-08-05 19:11:29 +00002009 pKeyInfo->aColl[0] = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2010 }
danielk1977e014a832004-05-17 10:48:57 +00002011
2012 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00002013 r1 = sqlite3GetTempReg(pParse);
2014 r2 = sqlite3GetTempReg(pParse);
drh37e08082014-07-31 20:16:08 +00002015 if( isRowid ) sqlite3VdbeAddOp2(v, OP_Null, 0, r2);
drh57dbd7b2005-07-08 18:25:26 +00002016 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
2017 Expr *pE2 = pItem->pExpr;
drhe05c9292009-10-29 13:48:10 +00002018 int iValToIns;
danielk1977e014a832004-05-17 10:48:57 +00002019
drh57dbd7b2005-07-08 18:25:26 +00002020 /* If the expression is not constant then we will need to
2021 ** disable the test that was generated above that makes sure
2022 ** this code only executes once. Because for a non-constant
2023 ** expression we need to rerun this code each time.
2024 */
drh6be515e2014-08-01 21:00:53 +00002025 if( jmpIfDynamic>=0 && !sqlite3ExprIsConstant(pE2) ){
2026 sqlite3VdbeChangeToNoop(v, jmpIfDynamic);
2027 jmpIfDynamic = -1;
drh4794b982000-06-06 13:54:14 +00002028 }
danielk1977e014a832004-05-17 10:48:57 +00002029
2030 /* Evaluate the expression and insert it into the temp table */
drhe05c9292009-10-29 13:48:10 +00002031 if( isRowid && sqlite3ExprIsInteger(pE2, &iValToIns) ){
2032 sqlite3VdbeAddOp3(v, OP_InsertInt, pExpr->iTable, r2, iValToIns);
danielk197741a05b72008-10-02 13:50:55 +00002033 }else{
drhe05c9292009-10-29 13:48:10 +00002034 r3 = sqlite3ExprCodeTarget(pParse, pE2, r1);
2035 if( isRowid ){
2036 sqlite3VdbeAddOp2(v, OP_MustBeInt, r3,
2037 sqlite3VdbeCurrentAddr(v)+2);
drh688852a2014-02-17 22:40:43 +00002038 VdbeCoverage(v);
drhe05c9292009-10-29 13:48:10 +00002039 sqlite3VdbeAddOp3(v, OP_Insert, pExpr->iTable, r2, r3);
2040 }else{
2041 sqlite3VdbeAddOp4(v, OP_MakeRecord, r3, 1, r2, &affinity, 1);
2042 sqlite3ExprCacheAffinityChange(pParse, r3, 1);
2043 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
2044 }
danielk197741a05b72008-10-02 13:50:55 +00002045 }
drhfef52082000-06-06 01:50:43 +00002046 }
drh2d401ab2008-01-10 23:50:11 +00002047 sqlite3ReleaseTempReg(pParse, r1);
2048 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00002049 }
drh323df792013-08-05 19:11:29 +00002050 if( pKeyInfo ){
drh2ec2fb22013-11-06 19:59:23 +00002051 sqlite3VdbeChangeP4(v, addr, (void *)pKeyInfo, P4_KEYINFO);
danielk197741a05b72008-10-02 13:50:55 +00002052 }
danielk1977b3bce662005-01-29 08:32:43 +00002053 break;
drhfef52082000-06-06 01:50:43 +00002054 }
2055
drh51522cd2005-01-20 13:36:19 +00002056 case TK_EXISTS:
drhfd773cf2009-05-29 14:39:07 +00002057 case TK_SELECT:
2058 default: {
drhfd773cf2009-05-29 14:39:07 +00002059 /* If this has to be a scalar SELECT. Generate code to put the
drhfef52082000-06-06 01:50:43 +00002060 ** value of this select in a memory cell and record the number
drhfd773cf2009-05-29 14:39:07 +00002061 ** of the memory cell in iColumn. If this is an EXISTS, write
2062 ** an integer 0 (not exists) or 1 (exists) into a memory cell
2063 ** and record that memory cell in iColumn.
drhfef52082000-06-06 01:50:43 +00002064 */
drhfd773cf2009-05-29 14:39:07 +00002065 Select *pSel; /* SELECT statement to encode */
2066 SelectDest dest; /* How to deal with SELECt result */
drh1398ad32005-01-19 23:24:50 +00002067
shanecf697392009-06-01 16:53:09 +00002068 testcase( pExpr->op==TK_EXISTS );
2069 testcase( pExpr->op==TK_SELECT );
2070 assert( pExpr->op==TK_EXISTS || pExpr->op==TK_SELECT );
2071
danielk19776ab3a2e2009-02-19 14:39:25 +00002072 assert( ExprHasProperty(pExpr, EP_xIsSelect) );
2073 pSel = pExpr->x.pSelect;
drh1013c932008-01-06 00:25:21 +00002074 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
drh51522cd2005-01-20 13:36:19 +00002075 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00002076 dest.eDest = SRT_Mem;
drh53932ce2014-08-29 12:29:39 +00002077 dest.iSdst = dest.iSDParm;
drh2b596da2012-07-23 21:43:19 +00002078 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002079 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00002080 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00002081 dest.eDest = SRT_Exists;
drh2b596da2012-07-23 21:43:19 +00002082 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iSDParm);
drhd4e70eb2008-01-02 00:34:36 +00002083 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00002084 }
drh633e6d52008-07-28 19:34:53 +00002085 sqlite3ExprDelete(pParse->db, pSel->pLimit);
drh094430e2010-07-14 18:24:06 +00002086 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0,
2087 &sqlite3IntTokens[1]);
drh48b5b042010-12-06 18:50:32 +00002088 pSel->iLimit = 0;
drh772460f2015-04-16 14:13:12 +00002089 pSel->selFlags &= ~SF_MultiValue;
drh7d10d5a2008-08-20 16:35:10 +00002090 if( sqlite3Select(pParse, pSel, &dest) ){
drh1450bc62009-10-30 13:25:56 +00002091 return 0;
drh94ccde52007-04-13 16:06:32 +00002092 }
drh2b596da2012-07-23 21:43:19 +00002093 rReg = dest.iSDParm;
drhebb6a652013-09-12 23:42:22 +00002094 ExprSetVVAProperty(pExpr, EP_NoReduce);
danielk1977b3bce662005-01-29 08:32:43 +00002095 break;
drhcce7d172000-05-31 15:34:51 +00002096 }
2097 }
danielk1977b3bce662005-01-29 08:32:43 +00002098
drh6be515e2014-08-01 21:00:53 +00002099 if( rHasNullFlag ){
2100 sqlite3SetHasNullFlag(v, pExpr->iTable, rHasNullFlag);
danielk1977b3bce662005-01-29 08:32:43 +00002101 }
drh6be515e2014-08-01 21:00:53 +00002102
2103 if( jmpIfDynamic>=0 ){
2104 sqlite3VdbeJumpHere(v, jmpIfDynamic);
danielk1977b3bce662005-01-29 08:32:43 +00002105 }
drhd2490902014-04-13 19:28:15 +00002106 sqlite3ExprCachePop(pParse);
danielk1977fc976062007-05-10 10:46:56 +00002107
drh1450bc62009-10-30 13:25:56 +00002108 return rReg;
drhcce7d172000-05-31 15:34:51 +00002109}
drh51522cd2005-01-20 13:36:19 +00002110#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00002111
drhe3365e62009-11-12 17:52:24 +00002112#ifndef SQLITE_OMIT_SUBQUERY
2113/*
2114** Generate code for an IN expression.
2115**
2116** x IN (SELECT ...)
2117** x IN (value, value, ...)
2118**
2119** The left-hand side (LHS) is a scalar expression. The right-hand side (RHS)
2120** is an array of zero or more values. The expression is true if the LHS is
2121** contained within the RHS. The value of the expression is unknown (NULL)
2122** if the LHS is NULL or if the LHS is not contained within the RHS and the
2123** RHS contains one or more NULL values.
2124**
drh6be515e2014-08-01 21:00:53 +00002125** This routine generates code that jumps to destIfFalse if the LHS is not
drhe3365e62009-11-12 17:52:24 +00002126** contained within the RHS. If due to NULLs we cannot determine if the LHS
2127** is contained in the RHS then jump to destIfNull. If the LHS is contained
2128** within the RHS then fall through.
2129*/
2130static void sqlite3ExprCodeIN(
2131 Parse *pParse, /* Parsing and code generating context */
2132 Expr *pExpr, /* The IN expression */
2133 int destIfFalse, /* Jump here if LHS is not contained in the RHS */
2134 int destIfNull /* Jump here if the results are unknown due to NULLs */
2135){
2136 int rRhsHasNull = 0; /* Register that is true if RHS contains NULL values */
2137 char affinity; /* Comparison affinity to use */
2138 int eType; /* Type of the RHS */
2139 int r1; /* Temporary use register */
2140 Vdbe *v; /* Statement under construction */
2141
2142 /* Compute the RHS. After this step, the table with cursor
2143 ** pExpr->iTable will contains the values that make up the RHS.
2144 */
2145 v = pParse->pVdbe;
2146 assert( v!=0 ); /* OOM detected prior to this routine */
2147 VdbeNoopComment((v, "begin IN expr"));
drhbb53ecb2014-08-02 21:03:33 +00002148 eType = sqlite3FindInIndex(pParse, pExpr,
2149 IN_INDEX_MEMBERSHIP | IN_INDEX_NOOP_OK,
drh3a856252014-08-01 14:46:57 +00002150 destIfFalse==destIfNull ? 0 : &rRhsHasNull);
drhe3365e62009-11-12 17:52:24 +00002151
2152 /* Figure out the affinity to use to create a key from the results
2153 ** of the expression. affinityStr stores a static string suitable for
2154 ** P4 of OP_MakeRecord.
2155 */
2156 affinity = comparisonAffinity(pExpr);
2157
2158 /* Code the LHS, the <expr> from "<expr> IN (...)".
2159 */
2160 sqlite3ExprCachePush(pParse);
2161 r1 = sqlite3GetTempReg(pParse);
2162 sqlite3ExprCode(pParse, pExpr->pLeft, r1);
drhe3365e62009-11-12 17:52:24 +00002163
drhbb53ecb2014-08-02 21:03:33 +00002164 /* If sqlite3FindInIndex() did not find or create an index that is
2165 ** suitable for evaluating the IN operator, then evaluate using a
2166 ** sequence of comparisons.
drh094430e2010-07-14 18:24:06 +00002167 */
drhbb53ecb2014-08-02 21:03:33 +00002168 if( eType==IN_INDEX_NOOP ){
2169 ExprList *pList = pExpr->x.pList;
2170 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pExpr->pLeft);
2171 int labelOk = sqlite3VdbeMakeLabel(v);
2172 int r2, regToFree;
2173 int regCkNull = 0;
2174 int ii;
2175 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhbb53ecb2014-08-02 21:03:33 +00002176 if( destIfNull!=destIfFalse ){
2177 regCkNull = sqlite3GetTempReg(pParse);
drha9769792014-08-04 16:39:39 +00002178 sqlite3VdbeAddOp3(v, OP_BitAnd, r1, r1, regCkNull);
drhbb53ecb2014-08-02 21:03:33 +00002179 }
2180 for(ii=0; ii<pList->nExpr; ii++){
2181 r2 = sqlite3ExprCodeTemp(pParse, pList->a[ii].pExpr, &regToFree);
drha9769792014-08-04 16:39:39 +00002182 if( regCkNull && sqlite3ExprCanBeNull(pList->a[ii].pExpr) ){
drhbb53ecb2014-08-02 21:03:33 +00002183 sqlite3VdbeAddOp3(v, OP_BitAnd, regCkNull, r2, regCkNull);
2184 }
2185 if( ii<pList->nExpr-1 || destIfNull!=destIfFalse ){
2186 sqlite3VdbeAddOp4(v, OP_Eq, r1, labelOk, r2,
drh4336b0e2014-08-05 00:53:51 +00002187 (void*)pColl, P4_COLLSEQ);
2188 VdbeCoverageIf(v, ii<pList->nExpr-1);
2189 VdbeCoverageIf(v, ii==pList->nExpr-1);
drhbb53ecb2014-08-02 21:03:33 +00002190 sqlite3VdbeChangeP5(v, affinity);
2191 }else{
2192 assert( destIfNull==destIfFalse );
2193 sqlite3VdbeAddOp4(v, OP_Ne, r1, destIfFalse, r2,
2194 (void*)pColl, P4_COLLSEQ); VdbeCoverage(v);
2195 sqlite3VdbeChangeP5(v, affinity | SQLITE_JUMPIFNULL);
2196 }
2197 sqlite3ReleaseTempReg(pParse, regToFree);
2198 }
2199 if( regCkNull ){
2200 sqlite3VdbeAddOp2(v, OP_IsNull, regCkNull, destIfNull); VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002201 sqlite3VdbeGoto(v, destIfFalse);
drhbb53ecb2014-08-02 21:03:33 +00002202 }
2203 sqlite3VdbeResolveLabel(v, labelOk);
2204 sqlite3ReleaseTempReg(pParse, regCkNull);
drh094430e2010-07-14 18:24:06 +00002205 }else{
drhbb53ecb2014-08-02 21:03:33 +00002206
2207 /* If the LHS is NULL, then the result is either false or NULL depending
2208 ** on whether the RHS is empty or not, respectively.
drhe3365e62009-11-12 17:52:24 +00002209 */
drh7248a8b2014-08-04 18:50:54 +00002210 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
2211 if( destIfNull==destIfFalse ){
2212 /* Shortcut for the common case where the false and NULL outcomes are
2213 ** the same. */
2214 sqlite3VdbeAddOp2(v, OP_IsNull, r1, destIfNull); VdbeCoverage(v);
2215 }else{
2216 int addr1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1); VdbeCoverage(v);
2217 sqlite3VdbeAddOp2(v, OP_Rewind, pExpr->iTable, destIfFalse);
2218 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002219 sqlite3VdbeGoto(v, destIfNull);
drh7248a8b2014-08-04 18:50:54 +00002220 sqlite3VdbeJumpHere(v, addr1);
2221 }
drhbb53ecb2014-08-02 21:03:33 +00002222 }
2223
2224 if( eType==IN_INDEX_ROWID ){
2225 /* In this case, the RHS is the ROWID of table b-tree
drhe3365e62009-11-12 17:52:24 +00002226 */
drhbb53ecb2014-08-02 21:03:33 +00002227 sqlite3VdbeAddOp2(v, OP_MustBeInt, r1, destIfFalse); VdbeCoverage(v);
2228 sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, destIfFalse, r1);
drh688852a2014-02-17 22:40:43 +00002229 VdbeCoverage(v);
drhe3365e62009-11-12 17:52:24 +00002230 }else{
drhbb53ecb2014-08-02 21:03:33 +00002231 /* In this case, the RHS is an index b-tree.
drhe3365e62009-11-12 17:52:24 +00002232 */
drhbb53ecb2014-08-02 21:03:33 +00002233 sqlite3VdbeAddOp4(v, OP_Affinity, r1, 1, 0, &affinity, 1);
2234
2235 /* If the set membership test fails, then the result of the
2236 ** "x IN (...)" expression must be either 0 or NULL. If the set
2237 ** contains no NULL values, then the result is 0. If the set
2238 ** contains one or more NULL values, then the result of the
2239 ** expression is also NULL.
drhe3365e62009-11-12 17:52:24 +00002240 */
drhbb53ecb2014-08-02 21:03:33 +00002241 assert( destIfFalse!=destIfNull || rRhsHasNull==0 );
2242 if( rRhsHasNull==0 ){
2243 /* This branch runs if it is known at compile time that the RHS
2244 ** cannot contain NULL values. This happens as the result
2245 ** of a "NOT NULL" constraint in the database schema.
2246 **
2247 ** Also run this branch if NULL is equivalent to FALSE
2248 ** for this particular IN operator.
2249 */
2250 sqlite3VdbeAddOp4Int(v, OP_NotFound, pExpr->iTable, destIfFalse, r1, 1);
2251 VdbeCoverage(v);
2252 }else{
2253 /* In this branch, the RHS of the IN might contain a NULL and
2254 ** the presence of a NULL on the RHS makes a difference in the
2255 ** outcome.
2256 */
drh728e0f92015-10-10 14:41:28 +00002257 int addr1;
drhbb53ecb2014-08-02 21:03:33 +00002258
2259 /* First check to see if the LHS is contained in the RHS. If so,
2260 ** then the answer is TRUE the presence of NULLs in the RHS does
2261 ** not matter. If the LHS is not contained in the RHS, then the
2262 ** answer is NULL if the RHS contains NULLs and the answer is
2263 ** FALSE if the RHS is NULL-free.
2264 */
drh728e0f92015-10-10 14:41:28 +00002265 addr1 = sqlite3VdbeAddOp4Int(v, OP_Found, pExpr->iTable, 0, r1, 1);
drhbb53ecb2014-08-02 21:03:33 +00002266 VdbeCoverage(v);
2267 sqlite3VdbeAddOp2(v, OP_IsNull, rRhsHasNull, destIfNull);
2268 VdbeCoverage(v);
drh076e85f2015-09-03 13:46:12 +00002269 sqlite3VdbeGoto(v, destIfFalse);
drh728e0f92015-10-10 14:41:28 +00002270 sqlite3VdbeJumpHere(v, addr1);
drhbb53ecb2014-08-02 21:03:33 +00002271 }
drhe3365e62009-11-12 17:52:24 +00002272 }
drhe3365e62009-11-12 17:52:24 +00002273 }
2274 sqlite3ReleaseTempReg(pParse, r1);
drhd2490902014-04-13 19:28:15 +00002275 sqlite3ExprCachePop(pParse);
drhe3365e62009-11-12 17:52:24 +00002276 VdbeComment((v, "end IN expr"));
2277}
2278#endif /* SQLITE_OMIT_SUBQUERY */
2279
drh13573c72010-01-12 17:04:07 +00002280#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002281/*
2282** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00002283** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002284**
2285** The z[] string will probably not be zero-terminated. But the
2286** z[n] character is guaranteed to be something that does not look
2287** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00002288*/
drhb7916a72009-05-27 10:31:29 +00002289static void codeReal(Vdbe *v, const char *z, int negateFlag, int iMem){
drhfd773cf2009-05-29 14:39:07 +00002290 if( ALWAYS(z!=0) ){
drh598f1342007-10-23 15:39:45 +00002291 double value;
drh9339da12010-09-30 00:50:49 +00002292 sqlite3AtoF(z, &value, sqlite3Strlen30(z), SQLITE_UTF8);
drhd0015162009-08-21 13:22:25 +00002293 assert( !sqlite3IsNaN(value) ); /* The new AtoF never returns NaN */
2294 if( negateFlag ) value = -value;
drh97bae792015-06-05 15:59:57 +00002295 sqlite3VdbeAddOp4Dup8(v, OP_Real, 0, iMem, 0, (u8*)&value, P4_REAL);
drh598f1342007-10-23 15:39:45 +00002296 }
2297}
drh13573c72010-01-12 17:04:07 +00002298#endif
drh598f1342007-10-23 15:39:45 +00002299
2300
2301/*
drhfec19aa2004-05-19 20:41:03 +00002302** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00002303** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00002304**
shaneh5f1d6b62010-09-30 16:51:25 +00002305** Expr.u.zToken is always UTF8 and zero-terminated.
drhfec19aa2004-05-19 20:41:03 +00002306*/
drh13573c72010-01-12 17:04:07 +00002307static void codeInteger(Parse *pParse, Expr *pExpr, int negFlag, int iMem){
2308 Vdbe *v = pParse->pVdbe;
drh92b01d52008-06-24 00:32:35 +00002309 if( pExpr->flags & EP_IntValue ){
drh33e619f2009-05-28 01:00:55 +00002310 int i = pExpr->u.iValue;
drhd50ffc42011-03-08 02:38:28 +00002311 assert( i>=0 );
drh92b01d52008-06-24 00:32:35 +00002312 if( negFlag ) i = -i;
2313 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
drhfd773cf2009-05-29 14:39:07 +00002314 }else{
shaneh5f1d6b62010-09-30 16:51:25 +00002315 int c;
2316 i64 value;
drhfd773cf2009-05-29 14:39:07 +00002317 const char *z = pExpr->u.zToken;
2318 assert( z!=0 );
drh9296c182014-07-23 13:40:49 +00002319 c = sqlite3DecOrHexToI64(z, &value);
shaneh5f1d6b62010-09-30 16:51:25 +00002320 if( c==0 || (c==2 && negFlag) ){
drh158b9cb2011-03-05 20:59:46 +00002321 if( negFlag ){ value = c==2 ? SMALLEST_INT64 : -value; }
drh97bae792015-06-05 15:59:57 +00002322 sqlite3VdbeAddOp4Dup8(v, OP_Int64, 0, iMem, 0, (u8*)&value, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002323 }else{
drh13573c72010-01-12 17:04:07 +00002324#ifdef SQLITE_OMIT_FLOATING_POINT
2325 sqlite3ErrorMsg(pParse, "oversized integer: %s%s", negFlag ? "-" : "", z);
2326#else
drh1b7ddc52014-07-23 14:52:05 +00002327#ifndef SQLITE_OMIT_HEX_INTEGER
drh9296c182014-07-23 13:40:49 +00002328 if( sqlite3_strnicmp(z,"0x",2)==0 ){
2329 sqlite3ErrorMsg(pParse, "hex literal too big: %s", z);
drh1b7ddc52014-07-23 14:52:05 +00002330 }else
2331#endif
2332 {
drh9296c182014-07-23 13:40:49 +00002333 codeReal(v, z, negFlag, iMem);
2334 }
drh13573c72010-01-12 17:04:07 +00002335#endif
danielk1977c9cf9012007-05-30 10:36:47 +00002336 }
drhfec19aa2004-05-19 20:41:03 +00002337 }
2338}
2339
drhbea119c2016-04-11 18:15:37 +00002340#if defined(SQLITE_DEBUG)
2341/*
2342** Verify the consistency of the column cache
2343*/
2344static int cacheIsValid(Parse *pParse){
2345 int i, n;
2346 for(i=n=0; i<SQLITE_N_COLCACHE; i++){
2347 if( pParse->aColCache[i].iReg>0 ) n++;
2348 }
2349 return n==pParse->nColCache;
2350}
2351#endif
2352
drhceea3322009-04-23 13:22:42 +00002353/*
2354** Clear a cache entry.
2355*/
2356static void cacheEntryClear(Parse *pParse, struct yColCache *p){
2357 if( p->tempReg ){
2358 if( pParse->nTempReg<ArraySize(pParse->aTempReg) ){
2359 pParse->aTempReg[pParse->nTempReg++] = p->iReg;
2360 }
2361 p->tempReg = 0;
2362 }
drhbea119c2016-04-11 18:15:37 +00002363 p->iReg = 0;
2364 pParse->nColCache--;
2365 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002366}
2367
2368
2369/*
2370** Record in the column cache that a particular column from a
2371** particular table is stored in a particular register.
2372*/
2373void sqlite3ExprCacheStore(Parse *pParse, int iTab, int iCol, int iReg){
2374 int i;
2375 int minLru;
2376 int idxLru;
2377 struct yColCache *p;
2378
dance8f53d2015-01-21 17:00:57 +00002379 /* Unless an error has occurred, register numbers are always positive. */
2380 assert( iReg>0 || pParse->nErr || pParse->db->mallocFailed );
drh20411ea2009-05-29 19:00:12 +00002381 assert( iCol>=-1 && iCol<32768 ); /* Finite column numbers */
2382
drhb6da74e2009-12-24 16:00:28 +00002383 /* The SQLITE_ColumnCache flag disables the column cache. This is used
2384 ** for testing only - to verify that SQLite always gets the same answer
2385 ** with and without the column cache.
2386 */
drh7e5418e2012-09-27 15:05:54 +00002387 if( OptimizationDisabled(pParse->db, SQLITE_ColumnCache) ) return;
drhb6da74e2009-12-24 16:00:28 +00002388
drh27ee4062009-12-30 01:13:11 +00002389 /* First replace any existing entry.
2390 **
2391 ** Actually, the way the column cache is currently used, we are guaranteed
2392 ** that the object will never already be in cache. Verify this guarantee.
2393 */
2394#ifndef NDEBUG
drhceea3322009-04-23 13:22:42 +00002395 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drh27ee4062009-12-30 01:13:11 +00002396 assert( p->iReg==0 || p->iTable!=iTab || p->iColumn!=iCol );
drhceea3322009-04-23 13:22:42 +00002397 }
drh27ee4062009-12-30 01:13:11 +00002398#endif
drhceea3322009-04-23 13:22:42 +00002399
2400 /* Find an empty slot and replace it */
2401 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2402 if( p->iReg==0 ){
2403 p->iLevel = pParse->iCacheLevel;
2404 p->iTable = iTab;
2405 p->iColumn = iCol;
2406 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002407 p->tempReg = 0;
2408 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002409 pParse->nColCache++;
2410 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002411 return;
2412 }
2413 }
2414
2415 /* Replace the last recently used */
2416 minLru = 0x7fffffff;
2417 idxLru = -1;
2418 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2419 if( p->lru<minLru ){
2420 idxLru = i;
2421 minLru = p->lru;
2422 }
2423 }
drh20411ea2009-05-29 19:00:12 +00002424 if( ALWAYS(idxLru>=0) ){
drhceea3322009-04-23 13:22:42 +00002425 p = &pParse->aColCache[idxLru];
2426 p->iLevel = pParse->iCacheLevel;
2427 p->iTable = iTab;
2428 p->iColumn = iCol;
2429 p->iReg = iReg;
drhceea3322009-04-23 13:22:42 +00002430 p->tempReg = 0;
2431 p->lru = pParse->iCacheCnt++;
drhbea119c2016-04-11 18:15:37 +00002432 assert( cacheIsValid(pParse) );
drhceea3322009-04-23 13:22:42 +00002433 return;
2434 }
2435}
2436
2437/*
drhf49f3522009-12-30 14:12:38 +00002438** Indicate that registers between iReg..iReg+nReg-1 are being overwritten.
2439** Purge the range of registers from the column cache.
drhceea3322009-04-23 13:22:42 +00002440*/
drhf49f3522009-12-30 14:12:38 +00002441void sqlite3ExprCacheRemove(Parse *pParse, int iReg, int nReg){
drhceea3322009-04-23 13:22:42 +00002442 struct yColCache *p;
drhbea119c2016-04-11 18:15:37 +00002443 if( iReg<=0 || pParse->nColCache==0 ) return;
2444 p = &pParse->aColCache[SQLITE_N_COLCACHE-1];
2445 while(1){
2446 if( p->iReg >= iReg && p->iReg < iReg+nReg ) cacheEntryClear(pParse, p);
2447 if( p==pParse->aColCache ) break;
2448 p--;
drhceea3322009-04-23 13:22:42 +00002449 }
2450}
2451
2452/*
2453** Remember the current column cache context. Any new entries added
2454** added to the column cache after this call are removed when the
2455** corresponding pop occurs.
2456*/
2457void sqlite3ExprCachePush(Parse *pParse){
2458 pParse->iCacheLevel++;
drh9ac79622013-12-18 15:11:47 +00002459#ifdef SQLITE_DEBUG
2460 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
2461 printf("PUSH to %d\n", pParse->iCacheLevel);
2462 }
2463#endif
drhceea3322009-04-23 13:22:42 +00002464}
2465
2466/*
2467** Remove from the column cache any entries that were added since the
drhd2490902014-04-13 19:28:15 +00002468** the previous sqlite3ExprCachePush operation. In other words, restore
2469** the cache to the state it was in prior the most recent Push.
drhceea3322009-04-23 13:22:42 +00002470*/
drhd2490902014-04-13 19:28:15 +00002471void sqlite3ExprCachePop(Parse *pParse){
drhceea3322009-04-23 13:22:42 +00002472 int i;
2473 struct yColCache *p;
drhd2490902014-04-13 19:28:15 +00002474 assert( pParse->iCacheLevel>=1 );
2475 pParse->iCacheLevel--;
drh9ac79622013-12-18 15:11:47 +00002476#ifdef SQLITE_DEBUG
2477 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
2478 printf("POP to %d\n", pParse->iCacheLevel);
2479 }
2480#endif
drhceea3322009-04-23 13:22:42 +00002481 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2482 if( p->iReg && p->iLevel>pParse->iCacheLevel ){
2483 cacheEntryClear(pParse, p);
drhceea3322009-04-23 13:22:42 +00002484 }
2485 }
2486}
drh945498f2007-02-24 11:52:52 +00002487
2488/*
drh5cd79232009-05-25 11:46:29 +00002489** When a cached column is reused, make sure that its register is
2490** no longer available as a temp register. ticket #3879: that same
2491** register might be in the cache in multiple places, so be sure to
2492** get them all.
2493*/
2494static void sqlite3ExprCachePinRegister(Parse *pParse, int iReg){
2495 int i;
2496 struct yColCache *p;
2497 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2498 if( p->iReg==iReg ){
2499 p->tempReg = 0;
2500 }
2501 }
2502}
2503
drh1f9ca2c2015-08-25 16:57:52 +00002504/* Generate code that will load into register regOut a value that is
2505** appropriate for the iIdxCol-th column of index pIdx.
2506*/
2507void sqlite3ExprCodeLoadIndexColumn(
2508 Parse *pParse, /* The parsing context */
2509 Index *pIdx, /* The index whose column is to be loaded */
2510 int iTabCur, /* Cursor pointing to a table row */
2511 int iIdxCol, /* The column of the index to be loaded */
2512 int regOut /* Store the index column value in this register */
2513){
2514 i16 iTabCol = pIdx->aiColumn[iIdxCol];
drh4b92f982015-09-29 17:20:14 +00002515 if( iTabCol==XN_EXPR ){
2516 assert( pIdx->aColExpr );
2517 assert( pIdx->aColExpr->nExpr>iIdxCol );
2518 pParse->iSelfTab = iTabCur;
drh1c75c9d2015-12-21 15:22:13 +00002519 sqlite3ExprCodeCopy(pParse, pIdx->aColExpr->a[iIdxCol].pExpr, regOut);
drh4b92f982015-09-29 17:20:14 +00002520 }else{
drh1f9ca2c2015-08-25 16:57:52 +00002521 sqlite3ExprCodeGetColumnOfTable(pParse->pVdbe, pIdx->pTable, iTabCur,
2522 iTabCol, regOut);
drh1f9ca2c2015-08-25 16:57:52 +00002523 }
drh1f9ca2c2015-08-25 16:57:52 +00002524}
2525
drh5cd79232009-05-25 11:46:29 +00002526/*
drh5c092e82010-05-14 19:24:02 +00002527** Generate code to extract the value of the iCol-th column of a table.
2528*/
2529void sqlite3ExprCodeGetColumnOfTable(
2530 Vdbe *v, /* The VDBE under construction */
2531 Table *pTab, /* The table containing the value */
drh313619f2013-10-31 20:34:06 +00002532 int iTabCur, /* The table cursor. Or the PK cursor for WITHOUT ROWID */
drh5c092e82010-05-14 19:24:02 +00002533 int iCol, /* Index of the column to extract */
drh313619f2013-10-31 20:34:06 +00002534 int regOut /* Extract the value into this register */
drh5c092e82010-05-14 19:24:02 +00002535){
2536 if( iCol<0 || iCol==pTab->iPKey ){
2537 sqlite3VdbeAddOp2(v, OP_Rowid, iTabCur, regOut);
2538 }else{
2539 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drhee0ec8e2013-10-31 17:38:01 +00002540 int x = iCol;
2541 if( !HasRowid(pTab) ){
2542 x = sqlite3ColumnOfIndex(sqlite3PrimaryKeyIndex(pTab), iCol);
2543 }
2544 sqlite3VdbeAddOp3(v, op, iTabCur, x, regOut);
drh5c092e82010-05-14 19:24:02 +00002545 }
2546 if( iCol>=0 ){
2547 sqlite3ColumnDefault(v, pTab, iCol, regOut);
2548 }
2549}
2550
2551/*
drh945498f2007-02-24 11:52:52 +00002552** Generate code that will extract the iColumn-th column from
drhce78bc62015-10-15 19:21:51 +00002553** table pTab and store the column value in a register.
2554**
2555** An effort is made to store the column value in register iReg. This
2556** is not garanteeed for GetColumn() - the result can be stored in
2557** any register. But the result is guaranteed to land in register iReg
2558** for GetColumnToReg().
drhe55cbd72008-03-31 23:48:03 +00002559**
2560** There must be an open cursor to pTab in iTable when this routine
2561** is called. If iColumn<0 then code is generated that extracts the rowid.
drh945498f2007-02-24 11:52:52 +00002562*/
drhe55cbd72008-03-31 23:48:03 +00002563int sqlite3ExprCodeGetColumn(
2564 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00002565 Table *pTab, /* Description of the table we are reading from */
2566 int iColumn, /* Index of the table column */
2567 int iTable, /* The cursor pointing to the table */
drha748fdc2012-03-28 01:34:47 +00002568 int iReg, /* Store results here */
drhce78bc62015-10-15 19:21:51 +00002569 u8 p5 /* P5 value for OP_Column + FLAGS */
drh2133d822008-01-03 18:44:59 +00002570){
drhe55cbd72008-03-31 23:48:03 +00002571 Vdbe *v = pParse->pVdbe;
2572 int i;
drhda250ea2008-04-01 05:07:14 +00002573 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00002574
drhceea3322009-04-23 13:22:42 +00002575 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
drhb6da74e2009-12-24 16:00:28 +00002576 if( p->iReg>0 && p->iTable==iTable && p->iColumn==iColumn ){
drhceea3322009-04-23 13:22:42 +00002577 p->lru = pParse->iCacheCnt++;
drh5cd79232009-05-25 11:46:29 +00002578 sqlite3ExprCachePinRegister(pParse, p->iReg);
drhda250ea2008-04-01 05:07:14 +00002579 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00002580 }
2581 }
2582 assert( v!=0 );
drh5c092e82010-05-14 19:24:02 +00002583 sqlite3ExprCodeGetColumnOfTable(v, pTab, iTable, iColumn, iReg);
drha748fdc2012-03-28 01:34:47 +00002584 if( p5 ){
2585 sqlite3VdbeChangeP5(v, p5);
2586 }else{
2587 sqlite3ExprCacheStore(pParse, iTable, iColumn, iReg);
2588 }
drhe55cbd72008-03-31 23:48:03 +00002589 return iReg;
2590}
drhce78bc62015-10-15 19:21:51 +00002591void sqlite3ExprCodeGetColumnToReg(
2592 Parse *pParse, /* Parsing and code generating context */
2593 Table *pTab, /* Description of the table we are reading from */
2594 int iColumn, /* Index of the table column */
2595 int iTable, /* The cursor pointing to the table */
2596 int iReg /* Store results here */
2597){
2598 int r1 = sqlite3ExprCodeGetColumn(pParse, pTab, iColumn, iTable, iReg, 0);
2599 if( r1!=iReg ) sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, r1, iReg);
2600}
2601
drhe55cbd72008-03-31 23:48:03 +00002602
2603/*
drhceea3322009-04-23 13:22:42 +00002604** Clear all column cache entries.
drhe55cbd72008-03-31 23:48:03 +00002605*/
drhceea3322009-04-23 13:22:42 +00002606void sqlite3ExprCacheClear(Parse *pParse){
2607 int i;
2608 struct yColCache *p;
2609
drh9ac79622013-12-18 15:11:47 +00002610#if SQLITE_DEBUG
2611 if( pParse->db->flags & SQLITE_VdbeAddopTrace ){
2612 printf("CLEAR\n");
2613 }
2614#endif
drhceea3322009-04-23 13:22:42 +00002615 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2616 if( p->iReg ){
2617 cacheEntryClear(pParse, p);
drhe55cbd72008-03-31 23:48:03 +00002618 }
drhe55cbd72008-03-31 23:48:03 +00002619 }
2620}
2621
2622/*
drhda250ea2008-04-01 05:07:14 +00002623** Record the fact that an affinity change has occurred on iCount
2624** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00002625*/
drhda250ea2008-04-01 05:07:14 +00002626void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
drhf49f3522009-12-30 14:12:38 +00002627 sqlite3ExprCacheRemove(pParse, iStart, iCount);
drhe55cbd72008-03-31 23:48:03 +00002628}
2629
2630/*
drhb21e7c72008-06-22 12:37:57 +00002631** Generate code to move content from registers iFrom...iFrom+nReg-1
2632** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00002633*/
drhb21e7c72008-06-22 12:37:57 +00002634void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe8e4af72012-09-21 00:04:28 +00002635 assert( iFrom>=iTo+nReg || iFrom+nReg<=iTo );
drh079a3072014-03-19 14:10:55 +00002636 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drh236241a2014-09-12 17:41:30 +00002637 sqlite3ExprCacheRemove(pParse, iFrom, nReg);
drh945498f2007-02-24 11:52:52 +00002638}
2639
drhf49f3522009-12-30 14:12:38 +00002640#if defined(SQLITE_DEBUG) || defined(SQLITE_COVERAGE_TEST)
drh92b01d52008-06-24 00:32:35 +00002641/*
drh652fbf52008-04-01 01:42:41 +00002642** Return true if any register in the range iFrom..iTo (inclusive)
2643** is used as part of the column cache.
drhf49f3522009-12-30 14:12:38 +00002644**
2645** This routine is used within assert() and testcase() macros only
2646** and does not appear in a normal build.
drh652fbf52008-04-01 01:42:41 +00002647*/
2648static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2649 int i;
drhceea3322009-04-23 13:22:42 +00002650 struct yColCache *p;
2651 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
2652 int r = p->iReg;
drhf49f3522009-12-30 14:12:38 +00002653 if( r>=iFrom && r<=iTo ) return 1; /*NO_TEST*/
drh652fbf52008-04-01 01:42:41 +00002654 }
2655 return 0;
2656}
drhf49f3522009-12-30 14:12:38 +00002657#endif /* SQLITE_DEBUG || SQLITE_COVERAGE_TEST */
drh652fbf52008-04-01 01:42:41 +00002658
drhbea119c2016-04-11 18:15:37 +00002659
drh652fbf52008-04-01 01:42:41 +00002660/*
drha4c3c872013-09-12 17:29:25 +00002661** Convert an expression node to a TK_REGISTER
2662*/
2663static void exprToRegister(Expr *p, int iReg){
2664 p->op2 = p->op;
2665 p->op = TK_REGISTER;
2666 p->iTable = iReg;
2667 ExprClearProperty(p, EP_Skip);
2668}
2669
2670/*
drhcce7d172000-05-31 15:34:51 +00002671** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00002672** expression. Attempt to store the results in register "target".
2673** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00002674**
drh8b213892008-08-29 02:14:02 +00002675** With this routine, there is no guarantee that results will
drh2dcef112008-01-12 19:03:48 +00002676** be stored in target. The result might be stored in some other
2677** register if it is convenient to do so. The calling function
2678** must check the return code and move the results to the desired
2679** register.
drhcce7d172000-05-31 15:34:51 +00002680*/
drh678ccce2008-03-31 18:19:54 +00002681int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00002682 Vdbe *v = pParse->pVdbe; /* The VM under construction */
2683 int op; /* The opcode being coded */
2684 int inReg = target; /* Results stored in register inReg */
2685 int regFree1 = 0; /* If non-zero free this temporary register */
2686 int regFree2 = 0; /* If non-zero free this temporary register */
drh678ccce2008-03-31 18:19:54 +00002687 int r1, r2, r3, r4; /* Various register numbers */
drh20411ea2009-05-29 19:00:12 +00002688 sqlite3 *db = pParse->db; /* The database connection */
drh10d1edf2013-11-15 15:52:39 +00002689 Expr tempX; /* Temporary expression node */
drhffe07b22005-11-03 00:41:17 +00002690
drh9cbf3422008-01-17 16:22:13 +00002691 assert( target>0 && target<=pParse->nMem );
drh20411ea2009-05-29 19:00:12 +00002692 if( v==0 ){
2693 assert( pParse->db->mallocFailed );
2694 return 0;
2695 }
drh389a1ad2008-01-03 23:44:53 +00002696
2697 if( pExpr==0 ){
2698 op = TK_NULL;
2699 }else{
2700 op = pExpr->op;
2701 }
drhf2bc0132004-10-04 13:19:23 +00002702 switch( op ){
drh13449892005-09-07 21:22:45 +00002703 case TK_AGG_COLUMN: {
2704 AggInfo *pAggInfo = pExpr->pAggInfo;
2705 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
2706 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00002707 assert( pCol->iMem>0 );
2708 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00002709 break;
2710 }else if( pAggInfo->useSortingIdx ){
dan5134d132011-09-02 10:31:11 +00002711 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdxPTab,
drh389a1ad2008-01-03 23:44:53 +00002712 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00002713 break;
2714 }
2715 /* Otherwise, fall thru into the TK_COLUMN case */
2716 }
drh967e8b72000-06-21 13:59:10 +00002717 case TK_COLUMN: {
drhb2b9d3d2013-08-01 01:14:43 +00002718 int iTab = pExpr->iTable;
2719 if( iTab<0 ){
2720 if( pParse->ckBase>0 ){
2721 /* Generating CHECK constraints or inserting into partial index */
2722 inReg = pExpr->iColumn + pParse->ckBase;
2723 break;
2724 }else{
drh1f9ca2c2015-08-25 16:57:52 +00002725 /* Coding an expression that is part of an index where column names
2726 ** in the index refer to the table to which the index belongs */
2727 iTab = pParse->iSelfTab;
drhb2b9d3d2013-08-01 01:14:43 +00002728 }
drh22827922000-06-06 17:27:05 +00002729 }
drhb2b9d3d2013-08-01 01:14:43 +00002730 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
2731 pExpr->iColumn, iTab, target,
2732 pExpr->op2);
drhcce7d172000-05-31 15:34:51 +00002733 break;
2734 }
2735 case TK_INTEGER: {
drh13573c72010-01-12 17:04:07 +00002736 codeInteger(pParse, pExpr, 0, target);
drhfec19aa2004-05-19 20:41:03 +00002737 break;
2738 }
drh13573c72010-01-12 17:04:07 +00002739#ifndef SQLITE_OMIT_FLOATING_POINT
drh598f1342007-10-23 15:39:45 +00002740 case TK_FLOAT: {
drh33e619f2009-05-28 01:00:55 +00002741 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2742 codeReal(v, pExpr->u.zToken, 0, target);
drh598f1342007-10-23 15:39:45 +00002743 break;
2744 }
drh13573c72010-01-12 17:04:07 +00002745#endif
drhfec19aa2004-05-19 20:41:03 +00002746 case TK_STRING: {
drh33e619f2009-05-28 01:00:55 +00002747 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh076e85f2015-09-03 13:46:12 +00002748 sqlite3VdbeLoadString(v, target, pExpr->u.zToken);
drhcce7d172000-05-31 15:34:51 +00002749 break;
2750 }
drhf0863fe2005-06-12 21:35:51 +00002751 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00002752 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00002753 break;
2754 }
danielk19775338a5f2005-01-20 13:03:10 +00002755#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00002756 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00002757 int n;
2758 const char *z;
drhca48c902008-01-18 14:08:24 +00002759 char *zBlob;
drh33e619f2009-05-28 01:00:55 +00002760 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2761 assert( pExpr->u.zToken[0]=='x' || pExpr->u.zToken[0]=='X' );
2762 assert( pExpr->u.zToken[1]=='\'' );
2763 z = &pExpr->u.zToken[2];
drhb7916a72009-05-27 10:31:29 +00002764 n = sqlite3Strlen30(z) - 1;
2765 assert( z[n]=='\'' );
drhca48c902008-01-18 14:08:24 +00002766 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2767 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00002768 break;
2769 }
danielk19775338a5f2005-01-20 13:03:10 +00002770#endif
drh50457892003-09-06 01:10:47 +00002771 case TK_VARIABLE: {
drh33e619f2009-05-28 01:00:55 +00002772 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2773 assert( pExpr->u.zToken!=0 );
2774 assert( pExpr->u.zToken[0]!=0 );
drheaf52d82010-05-12 13:50:23 +00002775 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iColumn, target);
2776 if( pExpr->u.zToken[1]!=0 ){
drh04e9eea2011-06-01 19:16:06 +00002777 assert( pExpr->u.zToken[0]=='?'
2778 || strcmp(pExpr->u.zToken, pParse->azVar[pExpr->iColumn-1])==0 );
2779 sqlite3VdbeChangeP4(v, -1, pParse->azVar[pExpr->iColumn-1], P4_STATIC);
drh895d7472004-08-20 16:02:39 +00002780 }
drh50457892003-09-06 01:10:47 +00002781 break;
2782 }
drh4e0cff62004-11-05 05:10:28 +00002783 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00002784 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00002785 break;
2786 }
drh487e2622005-06-25 18:42:14 +00002787#ifndef SQLITE_OMIT_CAST
2788 case TK_CAST: {
2789 /* Expressions of the form: CAST(pLeft AS token) */
drh2dcef112008-01-12 19:03:48 +00002790 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh1735fa82008-11-06 15:33:03 +00002791 if( inReg!=target ){
2792 sqlite3VdbeAddOp2(v, OP_SCopy, inReg, target);
2793 inReg = target;
2794 }
drh4169e432014-08-25 20:11:52 +00002795 sqlite3VdbeAddOp2(v, OP_Cast, target,
2796 sqlite3AffinityType(pExpr->u.zToken, 0));
drhc5499be2008-04-01 15:06:33 +00002797 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00002798 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00002799 break;
2800 }
2801#endif /* SQLITE_OMIT_CAST */
drhc9b84a12002-06-20 11:36:48 +00002802 case TK_LT:
2803 case TK_LE:
2804 case TK_GT:
2805 case TK_GE:
2806 case TK_NE:
2807 case TK_EQ: {
drhb6da74e2009-12-24 16:00:28 +00002808 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2809 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00002810 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2811 r1, r2, inReg, SQLITE_STOREP2);
drh7d176102014-02-18 03:07:12 +00002812 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
2813 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
2814 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
2815 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
2816 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq); VdbeCoverageIf(v,op==OP_Eq);
2817 assert(TK_NE==OP_Ne); testcase(op==OP_Ne); VdbeCoverageIf(v,op==OP_Ne);
drhc5499be2008-04-01 15:06:33 +00002818 testcase( regFree1==0 );
2819 testcase( regFree2==0 );
danielk1977a37cdde2004-05-16 11:15:36 +00002820 break;
drhc9b84a12002-06-20 11:36:48 +00002821 }
drh6a2fe092009-09-23 02:29:36 +00002822 case TK_IS:
2823 case TK_ISNOT: {
2824 testcase( op==TK_IS );
2825 testcase( op==TK_ISNOT );
drhb6da74e2009-12-24 16:00:28 +00002826 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2827 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh6a2fe092009-09-23 02:29:36 +00002828 op = (op==TK_IS) ? TK_EQ : TK_NE;
2829 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2830 r1, r2, inReg, SQLITE_STOREP2 | SQLITE_NULLEQ);
drh7d176102014-02-18 03:07:12 +00002831 VdbeCoverageIf(v, op==TK_EQ);
2832 VdbeCoverageIf(v, op==TK_NE);
drh6a2fe092009-09-23 02:29:36 +00002833 testcase( regFree1==0 );
2834 testcase( regFree2==0 );
2835 break;
2836 }
drhcce7d172000-05-31 15:34:51 +00002837 case TK_AND:
2838 case TK_OR:
2839 case TK_PLUS:
2840 case TK_STAR:
2841 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00002842 case TK_REM:
2843 case TK_BITAND:
2844 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00002845 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00002846 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00002847 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00002848 case TK_CONCAT: {
drh7d176102014-02-18 03:07:12 +00002849 assert( TK_AND==OP_And ); testcase( op==TK_AND );
2850 assert( TK_OR==OP_Or ); testcase( op==TK_OR );
2851 assert( TK_PLUS==OP_Add ); testcase( op==TK_PLUS );
2852 assert( TK_MINUS==OP_Subtract ); testcase( op==TK_MINUS );
2853 assert( TK_REM==OP_Remainder ); testcase( op==TK_REM );
2854 assert( TK_BITAND==OP_BitAnd ); testcase( op==TK_BITAND );
2855 assert( TK_BITOR==OP_BitOr ); testcase( op==TK_BITOR );
2856 assert( TK_SLASH==OP_Divide ); testcase( op==TK_SLASH );
2857 assert( TK_LSHIFT==OP_ShiftLeft ); testcase( op==TK_LSHIFT );
2858 assert( TK_RSHIFT==OP_ShiftRight ); testcase( op==TK_RSHIFT );
2859 assert( TK_CONCAT==OP_Concat ); testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00002860 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2861 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00002862 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00002863 testcase( regFree1==0 );
2864 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00002865 break;
2866 }
drhcce7d172000-05-31 15:34:51 +00002867 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00002868 Expr *pLeft = pExpr->pLeft;
2869 assert( pLeft );
drh13573c72010-01-12 17:04:07 +00002870 if( pLeft->op==TK_INTEGER ){
2871 codeInteger(pParse, pLeft, 1, target);
2872#ifndef SQLITE_OMIT_FLOATING_POINT
2873 }else if( pLeft->op==TK_FLOAT ){
drh33e619f2009-05-28 01:00:55 +00002874 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2875 codeReal(v, pLeft->u.zToken, 1, target);
drh13573c72010-01-12 17:04:07 +00002876#endif
drh3c84ddf2008-01-09 02:15:38 +00002877 }else{
drh10d1edf2013-11-15 15:52:39 +00002878 tempX.op = TK_INTEGER;
2879 tempX.flags = EP_IntValue|EP_TokenOnly;
2880 tempX.u.iValue = 0;
2881 r1 = sqlite3ExprCodeTemp(pParse, &tempX, &regFree1);
drhe55cbd72008-03-31 23:48:03 +00002882 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00002883 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00002884 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00002885 }
drh3c84ddf2008-01-09 02:15:38 +00002886 inReg = target;
2887 break;
drh6e142f52000-06-08 13:36:40 +00002888 }
drhbf4133c2001-10-13 02:59:08 +00002889 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00002890 case TK_NOT: {
drh7d176102014-02-18 03:07:12 +00002891 assert( TK_BITNOT==OP_BitNot ); testcase( op==TK_BITNOT );
2892 assert( TK_NOT==OP_Not ); testcase( op==TK_NOT );
drhe99fa2a2008-12-15 15:27:51 +00002893 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2894 testcase( regFree1==0 );
2895 inReg = target;
2896 sqlite3VdbeAddOp2(v, op, r1, inReg);
drhcce7d172000-05-31 15:34:51 +00002897 break;
2898 }
2899 case TK_ISNULL:
2900 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00002901 int addr;
drh7d176102014-02-18 03:07:12 +00002902 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
2903 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00002904 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00002905 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00002906 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00002907 addr = sqlite3VdbeAddOp1(v, op, r1);
drh7d176102014-02-18 03:07:12 +00002908 VdbeCoverageIf(v, op==TK_ISNULL);
2909 VdbeCoverageIf(v, op==TK_NOTNULL);
drha9769792014-08-04 16:39:39 +00002910 sqlite3VdbeAddOp2(v, OP_Integer, 0, target);
drh6a288a32008-01-07 19:20:24 +00002911 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00002912 break;
drhcce7d172000-05-31 15:34:51 +00002913 }
drh22827922000-06-06 17:27:05 +00002914 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00002915 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00002916 if( pInfo==0 ){
drh33e619f2009-05-28 01:00:55 +00002917 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2918 sqlite3ErrorMsg(pParse, "misuse of aggregate: %s()", pExpr->u.zToken);
drh7e56e712005-11-16 12:53:15 +00002919 }else{
drh9de221d2008-01-05 06:51:30 +00002920 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00002921 }
drh22827922000-06-06 17:27:05 +00002922 break;
2923 }
drhcce7d172000-05-31 15:34:51 +00002924 case TK_FUNCTION: {
drh12ffee82009-04-08 13:51:51 +00002925 ExprList *pFarg; /* List of function arguments */
2926 int nFarg; /* Number of function arguments */
2927 FuncDef *pDef; /* The function definition object */
drh12ffee82009-04-08 13:51:51 +00002928 const char *zId; /* The function name */
drh693e6712014-01-24 22:58:00 +00002929 u32 constMask = 0; /* Mask of function arguments that are constant */
drh12ffee82009-04-08 13:51:51 +00002930 int i; /* Loop counter */
2931 u8 enc = ENC(db); /* The text encoding used by this database */
2932 CollSeq *pColl = 0; /* A collating sequence */
drh17435752007-08-16 04:30:38 +00002933
danielk19776ab3a2e2009-02-19 14:39:25 +00002934 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drhc5cd1242013-09-12 16:50:49 +00002935 if( ExprHasProperty(pExpr, EP_TokenOnly) ){
drh12ffee82009-04-08 13:51:51 +00002936 pFarg = 0;
2937 }else{
2938 pFarg = pExpr->x.pList;
2939 }
2940 nFarg = pFarg ? pFarg->nExpr : 0;
drh33e619f2009-05-28 01:00:55 +00002941 assert( !ExprHasProperty(pExpr, EP_IntValue) );
2942 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:16 +00002943 pDef = sqlite3FindFunction(db, zId, nFarg, enc, 0);
drh2d801512016-01-14 22:19:58 +00002944 if( pDef==0 || pDef->xFinalize!=0 ){
drh80738d92016-02-15 00:34:16 +00002945 sqlite3ErrorMsg(pParse, "unknown function: %s()", zId);
drhfeb306f2009-08-18 16:05:46 +00002946 break;
2947 }
drhae6bb952009-11-11 00:24:31 +00002948
2949 /* Attempt a direct implementation of the built-in COALESCE() and
peter.d.reid60ec9142014-09-06 16:39:46 +00002950 ** IFNULL() functions. This avoids unnecessary evaluation of
drhae6bb952009-11-11 00:24:31 +00002951 ** arguments past the first non-NULL argument.
2952 */
drhd36e1042013-09-06 13:10:12 +00002953 if( pDef->funcFlags & SQLITE_FUNC_COALESCE ){
drhae6bb952009-11-11 00:24:31 +00002954 int endCoalesce = sqlite3VdbeMakeLabel(v);
2955 assert( nFarg>=2 );
2956 sqlite3ExprCode(pParse, pFarg->a[0].pExpr, target);
2957 for(i=1; i<nFarg; i++){
2958 sqlite3VdbeAddOp2(v, OP_NotNull, target, endCoalesce);
drh688852a2014-02-17 22:40:43 +00002959 VdbeCoverage(v);
drhf49f3522009-12-30 14:12:38 +00002960 sqlite3ExprCacheRemove(pParse, target, 1);
drhae6bb952009-11-11 00:24:31 +00002961 sqlite3ExprCachePush(pParse);
2962 sqlite3ExprCode(pParse, pFarg->a[i].pExpr, target);
drhd2490902014-04-13 19:28:15 +00002963 sqlite3ExprCachePop(pParse);
drhae6bb952009-11-11 00:24:31 +00002964 }
2965 sqlite3VdbeResolveLabel(v, endCoalesce);
2966 break;
2967 }
2968
drhcca9f3d2013-09-06 15:23:29 +00002969 /* The UNLIKELY() function is a no-op. The result is the value
2970 ** of the first argument.
2971 */
2972 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
2973 assert( nFarg>=1 );
drh5f02ab02015-06-20 13:18:34 +00002974 inReg = sqlite3ExprCodeTarget(pParse, pFarg->a[0].pExpr, target);
drhcca9f3d2013-09-06 15:23:29 +00002975 break;
2976 }
drhae6bb952009-11-11 00:24:31 +00002977
drhd1a01ed2013-11-21 16:08:52 +00002978 for(i=0; i<nFarg; i++){
2979 if( i<32 && sqlite3ExprIsConstant(pFarg->a[i].pExpr) ){
drh693e6712014-01-24 22:58:00 +00002980 testcase( i==31 );
2981 constMask |= MASKBIT32(i);
drhd1a01ed2013-11-21 16:08:52 +00002982 }
2983 if( (pDef->funcFlags & SQLITE_FUNC_NEEDCOLL)!=0 && !pColl ){
2984 pColl = sqlite3ExprCollSeq(pParse, pFarg->a[i].pExpr);
2985 }
2986 }
drh12ffee82009-04-08 13:51:51 +00002987 if( pFarg ){
drhd1a01ed2013-11-21 16:08:52 +00002988 if( constMask ){
2989 r1 = pParse->nMem+1;
2990 pParse->nMem += nFarg;
2991 }else{
2992 r1 = sqlite3GetTempRange(pParse, nFarg);
2993 }
drha748fdc2012-03-28 01:34:47 +00002994
2995 /* For length() and typeof() functions with a column argument,
2996 ** set the P5 parameter to the OP_Column opcode to OPFLAG_LENGTHARG
2997 ** or OPFLAG_TYPEOFARG respectively, to avoid unnecessary data
2998 ** loading.
2999 */
drhd36e1042013-09-06 13:10:12 +00003000 if( (pDef->funcFlags & (SQLITE_FUNC_LENGTH|SQLITE_FUNC_TYPEOF))!=0 ){
drh4e245a42012-03-30 00:00:36 +00003001 u8 exprOp;
drha748fdc2012-03-28 01:34:47 +00003002 assert( nFarg==1 );
3003 assert( pFarg->a[0].pExpr!=0 );
drh4e245a42012-03-30 00:00:36 +00003004 exprOp = pFarg->a[0].pExpr->op;
3005 if( exprOp==TK_COLUMN || exprOp==TK_AGG_COLUMN ){
drha748fdc2012-03-28 01:34:47 +00003006 assert( SQLITE_FUNC_LENGTH==OPFLAG_LENGTHARG );
3007 assert( SQLITE_FUNC_TYPEOF==OPFLAG_TYPEOFARG );
drhb1fba282013-11-21 14:33:48 +00003008 testcase( pDef->funcFlags & OPFLAG_LENGTHARG );
3009 pFarg->a[0].pExpr->op2 =
3010 pDef->funcFlags & (OPFLAG_LENGTHARG|OPFLAG_TYPEOFARG);
drha748fdc2012-03-28 01:34:47 +00003011 }
3012 }
3013
drhd7d385d2009-09-03 01:18:00 +00003014 sqlite3ExprCachePush(pParse); /* Ticket 2ea2425d34be */
drh5579d592015-08-26 14:01:41 +00003015 sqlite3ExprCodeExprList(pParse, pFarg, r1, 0,
drhd1a01ed2013-11-21 16:08:52 +00003016 SQLITE_ECEL_DUP|SQLITE_ECEL_FACTOR);
drhd2490902014-04-13 19:28:15 +00003017 sqlite3ExprCachePop(pParse); /* Ticket 2ea2425d34be */
drh892d3172008-01-10 03:46:36 +00003018 }else{
drh12ffee82009-04-08 13:51:51 +00003019 r1 = 0;
drh892d3172008-01-10 03:46:36 +00003020 }
drhb7f6f682006-07-08 17:06:43 +00003021#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00003022 /* Possibly overload the function if the first argument is
3023 ** a virtual table column.
3024 **
3025 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
3026 ** second argument, not the first, as the argument to test to
3027 ** see if it is a column in a virtual table. This is done because
3028 ** the left operand of infix functions (the operand we want to
3029 ** control overloading) ends up as the second argument to the
3030 ** function. The expression "A glob B" is equivalent to
3031 ** "glob(B,A). We want to use the A in "A glob B" to test
3032 ** for function overloading. But we use the B term in "glob(B,A)".
3033 */
drh12ffee82009-04-08 13:51:51 +00003034 if( nFarg>=2 && (pExpr->flags & EP_InfixFunc) ){
3035 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[1].pExpr);
3036 }else if( nFarg>0 ){
3037 pDef = sqlite3VtabOverloadFunction(db, pDef, nFarg, pFarg->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00003038 }
3039#endif
drhd36e1042013-09-06 13:10:12 +00003040 if( pDef->funcFlags & SQLITE_FUNC_NEEDCOLL ){
drh8b213892008-08-29 02:14:02 +00003041 if( !pColl ) pColl = db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00003042 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00003043 }
drh9c7c9132015-06-26 18:16:52 +00003044 sqlite3VdbeAddOp4(v, OP_Function0, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00003045 (char*)pDef, P4_FUNCDEF);
drh12ffee82009-04-08 13:51:51 +00003046 sqlite3VdbeChangeP5(v, (u8)nFarg);
drhd1a01ed2013-11-21 16:08:52 +00003047 if( nFarg && constMask==0 ){
drh12ffee82009-04-08 13:51:51 +00003048 sqlite3ReleaseTempRange(pParse, r1, nFarg);
drh2dcef112008-01-12 19:03:48 +00003049 }
drhcce7d172000-05-31 15:34:51 +00003050 break;
3051 }
drhfe2093d2005-01-20 22:48:47 +00003052#ifndef SQLITE_OMIT_SUBQUERY
3053 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00003054 case TK_SELECT: {
drhc5499be2008-04-01 15:06:33 +00003055 testcase( op==TK_EXISTS );
3056 testcase( op==TK_SELECT );
drh1450bc62009-10-30 13:25:56 +00003057 inReg = sqlite3CodeSubselect(pParse, pExpr, 0, 0);
drh19a775c2000-06-05 18:54:46 +00003058 break;
3059 }
drhfef52082000-06-06 01:50:43 +00003060 case TK_IN: {
drhe3365e62009-11-12 17:52:24 +00003061 int destIfFalse = sqlite3VdbeMakeLabel(v);
3062 int destIfNull = sqlite3VdbeMakeLabel(v);
3063 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
3064 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
3065 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
3066 sqlite3VdbeResolveLabel(v, destIfFalse);
3067 sqlite3VdbeAddOp2(v, OP_AddImm, target, 0);
3068 sqlite3VdbeResolveLabel(v, destIfNull);
drhfef52082000-06-06 01:50:43 +00003069 break;
3070 }
drhe3365e62009-11-12 17:52:24 +00003071#endif /* SQLITE_OMIT_SUBQUERY */
3072
3073
drh2dcef112008-01-12 19:03:48 +00003074 /*
3075 ** x BETWEEN y AND z
3076 **
3077 ** This is equivalent to
3078 **
3079 ** x>=y AND x<=z
3080 **
3081 ** X is stored in pExpr->pLeft.
3082 ** Y is stored in pExpr->pList->a[0].pExpr.
3083 ** Z is stored in pExpr->pList->a[1].pExpr.
3084 */
drhfef52082000-06-06 01:50:43 +00003085 case TK_BETWEEN: {
drhbe5c89a2004-07-26 00:31:09 +00003086 Expr *pLeft = pExpr->pLeft;
danielk19776ab3a2e2009-02-19 14:39:25 +00003087 struct ExprList_item *pLItem = pExpr->x.pList->a;
drhbe5c89a2004-07-26 00:31:09 +00003088 Expr *pRight = pLItem->pExpr;
drh35573352008-01-08 23:54:25 +00003089
drhb6da74e2009-12-24 16:00:28 +00003090 r1 = sqlite3ExprCodeTemp(pParse, pLeft, &regFree1);
3091 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
drhc5499be2008-04-01 15:06:33 +00003092 testcase( regFree1==0 );
3093 testcase( regFree2==0 );
drh2dcef112008-01-12 19:03:48 +00003094 r3 = sqlite3GetTempReg(pParse);
drh678ccce2008-03-31 18:19:54 +00003095 r4 = sqlite3GetTempReg(pParse);
drh35573352008-01-08 23:54:25 +00003096 codeCompare(pParse, pLeft, pRight, OP_Ge,
drh7d176102014-02-18 03:07:12 +00003097 r1, r2, r3, SQLITE_STOREP2); VdbeCoverage(v);
drhbe5c89a2004-07-26 00:31:09 +00003098 pLItem++;
3099 pRight = pLItem->pExpr;
drh2dcef112008-01-12 19:03:48 +00003100 sqlite3ReleaseTempReg(pParse, regFree2);
3101 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
drhc5499be2008-04-01 15:06:33 +00003102 testcase( regFree2==0 );
drh678ccce2008-03-31 18:19:54 +00003103 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
drh688852a2014-02-17 22:40:43 +00003104 VdbeCoverage(v);
drh678ccce2008-03-31 18:19:54 +00003105 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
drh2dcef112008-01-12 19:03:48 +00003106 sqlite3ReleaseTempReg(pParse, r3);
drh678ccce2008-03-31 18:19:54 +00003107 sqlite3ReleaseTempReg(pParse, r4);
drhfef52082000-06-06 01:50:43 +00003108 break;
3109 }
drh94fa9c42016-02-27 21:16:04 +00003110 case TK_SPAN:
drhae80dde2012-12-06 21:16:43 +00003111 case TK_COLLATE:
drh4f07e5f2007-05-14 11:34:46 +00003112 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00003113 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00003114 break;
3115 }
drh2dcef112008-01-12 19:03:48 +00003116
dan165921a2009-08-28 18:53:45 +00003117 case TK_TRIGGER: {
dan65a7cd12009-09-01 12:16:01 +00003118 /* If the opcode is TK_TRIGGER, then the expression is a reference
3119 ** to a column in the new.* or old.* pseudo-tables available to
3120 ** trigger programs. In this case Expr.iTable is set to 1 for the
3121 ** new.* pseudo-table, or 0 for the old.* pseudo-table. Expr.iColumn
3122 ** is set to the column of the pseudo-table to read, or to -1 to
3123 ** read the rowid field.
3124 **
3125 ** The expression is implemented using an OP_Param opcode. The p1
3126 ** parameter is set to 0 for an old.rowid reference, or to (i+1)
3127 ** to reference another column of the old.* pseudo-table, where
3128 ** i is the index of the column. For a new.rowid reference, p1 is
3129 ** set to (n+1), where n is the number of columns in each pseudo-table.
3130 ** For a reference to any other column in the new.* pseudo-table, p1
3131 ** is set to (n+2+i), where n and i are as defined previously. For
3132 ** example, if the table on which triggers are being fired is
3133 ** declared as:
3134 **
3135 ** CREATE TABLE t1(a, b);
3136 **
3137 ** Then p1 is interpreted as follows:
3138 **
3139 ** p1==0 -> old.rowid p1==3 -> new.rowid
3140 ** p1==1 -> old.a p1==4 -> new.a
3141 ** p1==2 -> old.b p1==5 -> new.b
3142 */
dan2832ad42009-08-31 15:27:27 +00003143 Table *pTab = pExpr->pTab;
dan65a7cd12009-09-01 12:16:01 +00003144 int p1 = pExpr->iTable * (pTab->nCol+1) + 1 + pExpr->iColumn;
3145
3146 assert( pExpr->iTable==0 || pExpr->iTable==1 );
3147 assert( pExpr->iColumn>=-1 && pExpr->iColumn<pTab->nCol );
3148 assert( pTab->iPKey<0 || pExpr->iColumn!=pTab->iPKey );
3149 assert( p1>=0 && p1<(pTab->nCol*2+2) );
3150
3151 sqlite3VdbeAddOp2(v, OP_Param, p1, target);
dan2bd93512009-08-31 08:22:46 +00003152 VdbeComment((v, "%s.%s -> $%d",
3153 (pExpr->iTable ? "new" : "old"),
dan76d462e2009-08-30 11:42:51 +00003154 (pExpr->iColumn<0 ? "rowid" : pExpr->pTab->aCol[pExpr->iColumn].zName),
dan2bd93512009-08-31 08:22:46 +00003155 target
dan165921a2009-08-28 18:53:45 +00003156 ));
dan65a7cd12009-09-01 12:16:01 +00003157
drh44dbca82010-01-13 04:22:20 +00003158#ifndef SQLITE_OMIT_FLOATING_POINT
dan65a7cd12009-09-01 12:16:01 +00003159 /* If the column has REAL affinity, it may currently be stored as an
drh113762a2014-11-19 16:36:25 +00003160 ** integer. Use OP_RealAffinity to make sure it is really real.
3161 **
3162 ** EVIDENCE-OF: R-60985-57662 SQLite will convert the value back to
3163 ** floating point when extracting it from the record. */
dan2832ad42009-08-31 15:27:27 +00003164 if( pExpr->iColumn>=0
3165 && pTab->aCol[pExpr->iColumn].affinity==SQLITE_AFF_REAL
3166 ){
3167 sqlite3VdbeAddOp1(v, OP_RealAffinity, target);
3168 }
drh44dbca82010-01-13 04:22:20 +00003169#endif
dan165921a2009-08-28 18:53:45 +00003170 break;
3171 }
3172
3173
drh2dcef112008-01-12 19:03:48 +00003174 /*
3175 ** Form A:
3176 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3177 **
3178 ** Form B:
3179 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
3180 **
3181 ** Form A is can be transformed into the equivalent form B as follows:
3182 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
3183 ** WHEN x=eN THEN rN ELSE y END
3184 **
3185 ** X (if it exists) is in pExpr->pLeft.
drhc5cd1242013-09-12 16:50:49 +00003186 ** Y is in the last element of pExpr->x.pList if pExpr->x.pList->nExpr is
3187 ** odd. The Y is also optional. If the number of elements in x.pList
3188 ** is even, then Y is omitted and the "otherwise" result is NULL.
drh2dcef112008-01-12 19:03:48 +00003189 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
3190 **
3191 ** The result of the expression is the Ri for the first matching Ei,
3192 ** or if there is no matching Ei, the ELSE term Y, or if there is
3193 ** no ELSE term, NULL.
3194 */
drh33cd4902009-05-30 20:49:20 +00003195 default: assert( op==TK_CASE ); {
drh2dcef112008-01-12 19:03:48 +00003196 int endLabel; /* GOTO label for end of CASE stmt */
3197 int nextCase; /* GOTO label for next WHEN clause */
3198 int nExpr; /* 2x number of WHEN terms */
3199 int i; /* Loop counter */
3200 ExprList *pEList; /* List of WHEN terms */
3201 struct ExprList_item *aListelem; /* Array of WHEN terms */
3202 Expr opCompare; /* The X==Ei expression */
drh2dcef112008-01-12 19:03:48 +00003203 Expr *pX; /* The X expression */
drh1bd10f82008-12-10 21:19:56 +00003204 Expr *pTest = 0; /* X==Ei (form A) or just Ei (form B) */
drhceea3322009-04-23 13:22:42 +00003205 VVA_ONLY( int iCacheLevel = pParse->iCacheLevel; )
drh17a7f8d2002-03-24 13:13:27 +00003206
danielk19776ab3a2e2009-02-19 14:39:25 +00003207 assert( !ExprHasProperty(pExpr, EP_xIsSelect) && pExpr->x.pList );
danielk19776ab3a2e2009-02-19 14:39:25 +00003208 assert(pExpr->x.pList->nExpr > 0);
3209 pEList = pExpr->x.pList;
drhbe5c89a2004-07-26 00:31:09 +00003210 aListelem = pEList->a;
3211 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00003212 endLabel = sqlite3VdbeMakeLabel(v);
3213 if( (pX = pExpr->pLeft)!=0 ){
drh10d1edf2013-11-15 15:52:39 +00003214 tempX = *pX;
drh33cd4902009-05-30 20:49:20 +00003215 testcase( pX->op==TK_COLUMN );
drh10d1edf2013-11-15 15:52:39 +00003216 exprToRegister(&tempX, sqlite3ExprCodeTemp(pParse, pX, &regFree1));
drhc5499be2008-04-01 15:06:33 +00003217 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003218 opCompare.op = TK_EQ;
drh10d1edf2013-11-15 15:52:39 +00003219 opCompare.pLeft = &tempX;
drh2dcef112008-01-12 19:03:48 +00003220 pTest = &opCompare;
drh8b1db072010-09-28 04:14:03 +00003221 /* Ticket b351d95f9cd5ef17e9d9dbae18f5ca8611190001:
3222 ** The value in regFree1 might get SCopy-ed into the file result.
3223 ** So make sure that the regFree1 register is not reused for other
3224 ** purposes and possibly overwritten. */
3225 regFree1 = 0;
drh17a7f8d2002-03-24 13:13:27 +00003226 }
drhc5cd1242013-09-12 16:50:49 +00003227 for(i=0; i<nExpr-1; i=i+2){
drhceea3322009-04-23 13:22:42 +00003228 sqlite3ExprCachePush(pParse);
drh2dcef112008-01-12 19:03:48 +00003229 if( pX ){
drh1bd10f82008-12-10 21:19:56 +00003230 assert( pTest!=0 );
drh2dcef112008-01-12 19:03:48 +00003231 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003232 }else{
drh2dcef112008-01-12 19:03:48 +00003233 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00003234 }
drh2dcef112008-01-12 19:03:48 +00003235 nextCase = sqlite3VdbeMakeLabel(v);
drh33cd4902009-05-30 20:49:20 +00003236 testcase( pTest->op==TK_COLUMN );
drh2dcef112008-01-12 19:03:48 +00003237 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00003238 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
drh9de221d2008-01-05 06:51:30 +00003239 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh076e85f2015-09-03 13:46:12 +00003240 sqlite3VdbeGoto(v, endLabel);
drhd2490902014-04-13 19:28:15 +00003241 sqlite3ExprCachePop(pParse);
drh2dcef112008-01-12 19:03:48 +00003242 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00003243 }
drhc5cd1242013-09-12 16:50:49 +00003244 if( (nExpr&1)!=0 ){
drhceea3322009-04-23 13:22:42 +00003245 sqlite3ExprCachePush(pParse);
drhc5cd1242013-09-12 16:50:49 +00003246 sqlite3ExprCode(pParse, pEList->a[nExpr-1].pExpr, target);
drhd2490902014-04-13 19:28:15 +00003247 sqlite3ExprCachePop(pParse);
drh17a7f8d2002-03-24 13:13:27 +00003248 }else{
drh9de221d2008-01-05 06:51:30 +00003249 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00003250 }
danielk1977c1f4a192009-04-28 12:08:15 +00003251 assert( db->mallocFailed || pParse->nErr>0
3252 || pParse->iCacheLevel==iCacheLevel );
drh2dcef112008-01-12 19:03:48 +00003253 sqlite3VdbeResolveLabel(v, endLabel);
danielk19776f349032002-06-11 02:25:40 +00003254 break;
3255 }
danielk19775338a5f2005-01-20 13:03:10 +00003256#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00003257 case TK_RAISE: {
dan165921a2009-08-28 18:53:45 +00003258 assert( pExpr->affinity==OE_Rollback
3259 || pExpr->affinity==OE_Abort
3260 || pExpr->affinity==OE_Fail
3261 || pExpr->affinity==OE_Ignore
3262 );
dane0af83a2009-09-08 19:15:01 +00003263 if( !pParse->pTriggerTab ){
3264 sqlite3ErrorMsg(pParse,
3265 "RAISE() may only be used within a trigger-program");
3266 return 0;
3267 }
3268 if( pExpr->affinity==OE_Abort ){
3269 sqlite3MayAbort(pParse);
3270 }
dan165921a2009-08-28 18:53:45 +00003271 assert( !ExprHasProperty(pExpr, EP_IntValue) );
dane0af83a2009-09-08 19:15:01 +00003272 if( pExpr->affinity==OE_Ignore ){
3273 sqlite3VdbeAddOp4(
3274 v, OP_Halt, SQLITE_OK, OE_Ignore, 0, pExpr->u.zToken,0);
drh688852a2014-02-17 22:40:43 +00003275 VdbeCoverage(v);
dane0af83a2009-09-08 19:15:01 +00003276 }else{
drh433dccf2013-02-09 15:37:11 +00003277 sqlite3HaltConstraint(pParse, SQLITE_CONSTRAINT_TRIGGER,
drhf9c8ce32013-11-05 13:33:55 +00003278 pExpr->affinity, pExpr->u.zToken, 0, 0);
dane0af83a2009-09-08 19:15:01 +00003279 }
3280
drhffe07b22005-11-03 00:41:17 +00003281 break;
drh17a7f8d2002-03-24 13:13:27 +00003282 }
danielk19775338a5f2005-01-20 13:03:10 +00003283#endif
drhffe07b22005-11-03 00:41:17 +00003284 }
drh2dcef112008-01-12 19:03:48 +00003285 sqlite3ReleaseTempReg(pParse, regFree1);
3286 sqlite3ReleaseTempReg(pParse, regFree2);
3287 return inReg;
3288}
3289
3290/*
drhd1a01ed2013-11-21 16:08:52 +00003291** Factor out the code of the given expression to initialization time.
3292*/
drhd673cdd2013-11-21 21:23:31 +00003293void sqlite3ExprCodeAtInit(
3294 Parse *pParse, /* Parsing context */
3295 Expr *pExpr, /* The expression to code when the VDBE initializes */
3296 int regDest, /* Store the value in this register */
3297 u8 reusable /* True if this expression is reusable */
3298){
drhd1a01ed2013-11-21 16:08:52 +00003299 ExprList *p;
drhd9f158e2013-11-21 20:48:42 +00003300 assert( ConstFactorOk(pParse) );
drhd1a01ed2013-11-21 16:08:52 +00003301 p = pParse->pConstExpr;
3302 pExpr = sqlite3ExprDup(pParse->db, pExpr, 0);
3303 p = sqlite3ExprListAppend(pParse, p, pExpr);
drhd673cdd2013-11-21 21:23:31 +00003304 if( p ){
3305 struct ExprList_item *pItem = &p->a[p->nExpr-1];
3306 pItem->u.iConstExprReg = regDest;
3307 pItem->reusable = reusable;
3308 }
drhd1a01ed2013-11-21 16:08:52 +00003309 pParse->pConstExpr = p;
3310}
3311
3312/*
drh2dcef112008-01-12 19:03:48 +00003313** Generate code to evaluate an expression and store the results
3314** into a register. Return the register number where the results
3315** are stored.
3316**
3317** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00003318** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00003319** a temporary, then set *pReg to zero.
drhf30a9692013-11-15 01:10:18 +00003320**
3321** If pExpr is a constant, then this routine might generate this
3322** code to fill the register in the initialization section of the
3323** VDBE program, in order to factor it out of the evaluation loop.
drh2dcef112008-01-12 19:03:48 +00003324*/
3325int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
drhf30a9692013-11-15 01:10:18 +00003326 int r2;
3327 pExpr = sqlite3ExprSkipCollate(pExpr);
drhd9f158e2013-11-21 20:48:42 +00003328 if( ConstFactorOk(pParse)
drhf30a9692013-11-15 01:10:18 +00003329 && pExpr->op!=TK_REGISTER
3330 && sqlite3ExprIsConstantNotJoin(pExpr)
3331 ){
3332 ExprList *p = pParse->pConstExpr;
3333 int i;
3334 *pReg = 0;
3335 if( p ){
drhd673cdd2013-11-21 21:23:31 +00003336 struct ExprList_item *pItem;
3337 for(pItem=p->a, i=p->nExpr; i>0; pItem++, i--){
3338 if( pItem->reusable && sqlite3ExprCompare(pItem->pExpr,pExpr,-1)==0 ){
3339 return pItem->u.iConstExprReg;
drhf30a9692013-11-15 01:10:18 +00003340 }
3341 }
3342 }
drhf30a9692013-11-15 01:10:18 +00003343 r2 = ++pParse->nMem;
drhd673cdd2013-11-21 21:23:31 +00003344 sqlite3ExprCodeAtInit(pParse, pExpr, r2, 1);
drh2dcef112008-01-12 19:03:48 +00003345 }else{
drhf30a9692013-11-15 01:10:18 +00003346 int r1 = sqlite3GetTempReg(pParse);
3347 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
3348 if( r2==r1 ){
3349 *pReg = r1;
3350 }else{
3351 sqlite3ReleaseTempReg(pParse, r1);
3352 *pReg = 0;
3353 }
drh2dcef112008-01-12 19:03:48 +00003354 }
3355 return r2;
3356}
3357
3358/*
3359** Generate code that will evaluate expression pExpr and store the
3360** results in register target. The results are guaranteed to appear
3361** in register target.
3362*/
drh05a86c52014-02-16 01:55:49 +00003363void sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00003364 int inReg;
3365
3366 assert( target>0 && target<=pParse->nMem );
drhebc16712010-09-28 00:25:58 +00003367 if( pExpr && pExpr->op==TK_REGISTER ){
3368 sqlite3VdbeAddOp2(pParse->pVdbe, OP_Copy, pExpr->iTable, target);
3369 }else{
3370 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh1c75c9d2015-12-21 15:22:13 +00003371 assert( pParse->pVdbe!=0 || pParse->db->mallocFailed );
drhebc16712010-09-28 00:25:58 +00003372 if( inReg!=target && pParse->pVdbe ){
3373 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
3374 }
drhcce7d172000-05-31 15:34:51 +00003375 }
drhcce7d172000-05-31 15:34:51 +00003376}
3377
3378/*
drh1c75c9d2015-12-21 15:22:13 +00003379** Make a transient copy of expression pExpr and then code it using
3380** sqlite3ExprCode(). This routine works just like sqlite3ExprCode()
3381** except that the input expression is guaranteed to be unchanged.
3382*/
3383void sqlite3ExprCodeCopy(Parse *pParse, Expr *pExpr, int target){
3384 sqlite3 *db = pParse->db;
3385 pExpr = sqlite3ExprDup(db, pExpr, 0);
3386 if( !db->mallocFailed ) sqlite3ExprCode(pParse, pExpr, target);
3387 sqlite3ExprDelete(db, pExpr);
3388}
3389
3390/*
drh05a86c52014-02-16 01:55:49 +00003391** Generate code that will evaluate expression pExpr and store the
3392** results in register target. The results are guaranteed to appear
3393** in register target. If the expression is constant, then this routine
3394** might choose to code the expression at initialization time.
3395*/
3396void sqlite3ExprCodeFactorable(Parse *pParse, Expr *pExpr, int target){
3397 if( pParse->okConstFactor && sqlite3ExprIsConstant(pExpr) ){
3398 sqlite3ExprCodeAtInit(pParse, pExpr, target, 0);
3399 }else{
3400 sqlite3ExprCode(pParse, pExpr, target);
3401 }
drhcce7d172000-05-31 15:34:51 +00003402}
3403
3404/*
peter.d.reid60ec9142014-09-06 16:39:46 +00003405** Generate code that evaluates the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00003406** in register target.
drh25303782004-12-07 15:41:48 +00003407**
drh2dcef112008-01-12 19:03:48 +00003408** Also make a copy of the expression results into another "cache" register
3409** and modify the expression so that the next time it is evaluated,
3410** the result is a copy of the cache register.
3411**
3412** This routine is used for expressions that are used multiple
3413** times. They are evaluated once and the results of the expression
3414** are reused.
drh25303782004-12-07 15:41:48 +00003415*/
drh05a86c52014-02-16 01:55:49 +00003416void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00003417 Vdbe *v = pParse->pVdbe;
drh05a86c52014-02-16 01:55:49 +00003418 int iMem;
3419
drhde4fcfd2008-01-19 23:50:26 +00003420 assert( target>0 );
drh05a86c52014-02-16 01:55:49 +00003421 assert( pExpr->op!=TK_REGISTER );
3422 sqlite3ExprCode(pParse, pExpr, target);
3423 iMem = ++pParse->nMem;
3424 sqlite3VdbeAddOp2(v, OP_Copy, target, iMem);
3425 exprToRegister(pExpr, iMem);
drh25303782004-12-07 15:41:48 +00003426}
drh2dcef112008-01-12 19:03:48 +00003427
drh678ccce2008-03-31 18:19:54 +00003428/*
drh268380c2004-02-25 13:47:31 +00003429** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00003430** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00003431**
drh892d3172008-01-10 03:46:36 +00003432** Return the number of elements evaluated.
drhd1a01ed2013-11-21 16:08:52 +00003433**
3434** The SQLITE_ECEL_DUP flag prevents the arguments from being
3435** filled using OP_SCopy. OP_Copy must be used instead.
3436**
3437** The SQLITE_ECEL_FACTOR argument allows constant arguments to be
3438** factored out into initialization code.
drhb0df9632015-10-16 23:55:08 +00003439**
3440** The SQLITE_ECEL_REF flag means that expressions in the list with
3441** ExprList.a[].u.x.iOrderByCol>0 have already been evaluated and stored
3442** in registers at srcReg, and so the value can be copied from there.
drh268380c2004-02-25 13:47:31 +00003443*/
danielk19774adee202004-05-08 08:23:19 +00003444int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00003445 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00003446 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00003447 int target, /* Where to write results */
drh5579d592015-08-26 14:01:41 +00003448 int srcReg, /* Source registers if SQLITE_ECEL_REF */
drhd1a01ed2013-11-21 16:08:52 +00003449 u8 flags /* SQLITE_ECEL_* flags */
drh268380c2004-02-25 13:47:31 +00003450){
3451 struct ExprList_item *pItem;
drh5579d592015-08-26 14:01:41 +00003452 int i, j, n;
drhd1a01ed2013-11-21 16:08:52 +00003453 u8 copyOp = (flags & SQLITE_ECEL_DUP) ? OP_Copy : OP_SCopy;
drh5579d592015-08-26 14:01:41 +00003454 Vdbe *v = pParse->pVdbe;
drh9d8b3072008-08-22 16:29:51 +00003455 assert( pList!=0 );
drh9cbf3422008-01-17 16:22:13 +00003456 assert( target>0 );
drhd81a1422010-09-28 07:11:24 +00003457 assert( pParse->pVdbe!=0 ); /* Never gets this far otherwise */
drh268380c2004-02-25 13:47:31 +00003458 n = pList->nExpr;
drhd9f158e2013-11-21 20:48:42 +00003459 if( !ConstFactorOk(pParse) ) flags &= ~SQLITE_ECEL_FACTOR;
drh191b54c2008-04-15 12:14:21 +00003460 for(pItem=pList->a, i=0; i<n; i++, pItem++){
drh7445ffe2010-09-27 18:14:12 +00003461 Expr *pExpr = pItem->pExpr;
drh5579d592015-08-26 14:01:41 +00003462 if( (flags & SQLITE_ECEL_REF)!=0 && (j = pList->a[i].u.x.iOrderByCol)>0 ){
3463 sqlite3VdbeAddOp2(v, copyOp, j+srcReg-1, target+i);
3464 }else if( (flags & SQLITE_ECEL_FACTOR)!=0 && sqlite3ExprIsConstant(pExpr) ){
drhd673cdd2013-11-21 21:23:31 +00003465 sqlite3ExprCodeAtInit(pParse, pExpr, target+i, 0);
drhd1a01ed2013-11-21 16:08:52 +00003466 }else{
3467 int inReg = sqlite3ExprCodeTarget(pParse, pExpr, target+i);
3468 if( inReg!=target+i ){
drh4eded602013-12-20 15:59:20 +00003469 VdbeOp *pOp;
drh4eded602013-12-20 15:59:20 +00003470 if( copyOp==OP_Copy
3471 && (pOp=sqlite3VdbeGetOp(v, -1))->opcode==OP_Copy
3472 && pOp->p1+pOp->p3+1==inReg
3473 && pOp->p2+pOp->p3+1==target+i
3474 ){
3475 pOp->p3++;
3476 }else{
3477 sqlite3VdbeAddOp2(v, copyOp, inReg, target+i);
3478 }
drhd1a01ed2013-11-21 16:08:52 +00003479 }
drhd1766112008-09-17 00:13:12 +00003480 }
drh268380c2004-02-25 13:47:31 +00003481 }
drhf9b596e2004-05-26 16:54:42 +00003482 return n;
drh268380c2004-02-25 13:47:31 +00003483}
3484
3485/*
drh36c563a2009-11-12 13:32:22 +00003486** Generate code for a BETWEEN operator.
3487**
3488** x BETWEEN y AND z
3489**
3490** The above is equivalent to
3491**
3492** x>=y AND x<=z
3493**
3494** Code it as such, taking care to do the common subexpression
peter.d.reid60ec9142014-09-06 16:39:46 +00003495** elimination of x.
drh36c563a2009-11-12 13:32:22 +00003496*/
3497static void exprCodeBetween(
3498 Parse *pParse, /* Parsing and code generating context */
3499 Expr *pExpr, /* The BETWEEN expression */
3500 int dest, /* Jump here if the jump is taken */
3501 int jumpIfTrue, /* Take the jump if the BETWEEN is true */
3502 int jumpIfNull /* Take the jump if the BETWEEN is NULL */
3503){
3504 Expr exprAnd; /* The AND operator in x>=y AND x<=z */
3505 Expr compLeft; /* The x>=y term */
3506 Expr compRight; /* The x<=z term */
3507 Expr exprX; /* The x subexpression */
3508 int regFree1 = 0; /* Temporary use register */
3509
3510 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
3511 exprX = *pExpr->pLeft;
3512 exprAnd.op = TK_AND;
3513 exprAnd.pLeft = &compLeft;
3514 exprAnd.pRight = &compRight;
3515 compLeft.op = TK_GE;
3516 compLeft.pLeft = &exprX;
3517 compLeft.pRight = pExpr->x.pList->a[0].pExpr;
3518 compRight.op = TK_LE;
3519 compRight.pLeft = &exprX;
3520 compRight.pRight = pExpr->x.pList->a[1].pExpr;
drha4c3c872013-09-12 17:29:25 +00003521 exprToRegister(&exprX, sqlite3ExprCodeTemp(pParse, &exprX, &regFree1));
drh36c563a2009-11-12 13:32:22 +00003522 if( jumpIfTrue ){
3523 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
3524 }else{
3525 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
3526 }
3527 sqlite3ReleaseTempReg(pParse, regFree1);
3528
3529 /* Ensure adequate test coverage */
3530 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1==0 );
3531 testcase( jumpIfTrue==0 && jumpIfNull==0 && regFree1!=0 );
3532 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1==0 );
3533 testcase( jumpIfTrue==0 && jumpIfNull!=0 && regFree1!=0 );
3534 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1==0 );
3535 testcase( jumpIfTrue!=0 && jumpIfNull==0 && regFree1!=0 );
3536 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1==0 );
3537 testcase( jumpIfTrue!=0 && jumpIfNull!=0 && regFree1!=0 );
3538}
3539
3540/*
drhcce7d172000-05-31 15:34:51 +00003541** Generate code for a boolean expression such that a jump is made
3542** to the label "dest" if the expression is true but execution
3543** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00003544**
3545** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00003546** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00003547**
3548** This code depends on the fact that certain token values (ex: TK_EQ)
3549** are the same as opcode values (ex: OP_Eq) that implement the corresponding
3550** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
3551** the make process cause these values to align. Assert()s in the code
3552** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00003553*/
danielk19774adee202004-05-08 08:23:19 +00003554void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00003555 Vdbe *v = pParse->pVdbe;
3556 int op = 0;
drh2dcef112008-01-12 19:03:48 +00003557 int regFree1 = 0;
3558 int regFree2 = 0;
3559 int r1, r2;
3560
drh35573352008-01-08 23:54:25 +00003561 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00003562 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00003563 if( NEVER(pExpr==0) ) return; /* No way this can happen */
drhf2bc0132004-10-04 13:19:23 +00003564 op = pExpr->op;
3565 switch( op ){
drhcce7d172000-05-31 15:34:51 +00003566 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00003567 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00003568 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00003569 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00003570 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00003571 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
3572 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00003573 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00003574 break;
3575 }
3576 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00003577 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00003578 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00003579 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00003580 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00003581 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00003582 break;
3583 }
3584 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00003585 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00003586 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00003587 break;
3588 }
drhde845c22016-03-17 19:07:52 +00003589 case TK_IS:
3590 case TK_ISNOT:
3591 testcase( op==TK_IS );
3592 testcase( op==TK_ISNOT );
3593 op = (op==TK_IS) ? TK_EQ : TK_NE;
3594 jumpIfNull = SQLITE_NULLEQ;
3595 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00003596 case TK_LT:
3597 case TK_LE:
3598 case TK_GT:
3599 case TK_GE:
3600 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00003601 case TK_EQ: {
drhc5499be2008-04-01 15:06:33 +00003602 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00003603 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3604 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00003605 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00003606 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00003607 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3608 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3609 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3610 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00003611 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
3612 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
3613 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
3614 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
3615 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
3616 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00003617 testcase( regFree1==0 );
3618 testcase( regFree2==0 );
3619 break;
3620 }
drhcce7d172000-05-31 15:34:51 +00003621 case TK_ISNULL:
3622 case TK_NOTNULL: {
drh7d176102014-02-18 03:07:12 +00003623 assert( TK_ISNULL==OP_IsNull ); testcase( op==TK_ISNULL );
3624 assert( TK_NOTNULL==OP_NotNull ); testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00003625 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3626 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00003627 VdbeCoverageIf(v, op==TK_ISNULL);
3628 VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00003629 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00003630 break;
3631 }
drhfef52082000-06-06 01:50:43 +00003632 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00003633 testcase( jumpIfNull==0 );
drh36c563a2009-11-12 13:32:22 +00003634 exprCodeBetween(pParse, pExpr, dest, 1, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00003635 break;
3636 }
drh84e30ca2011-02-10 17:46:14 +00003637#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00003638 case TK_IN: {
3639 int destIfFalse = sqlite3VdbeMakeLabel(v);
3640 int destIfNull = jumpIfNull ? dest : destIfFalse;
3641 sqlite3ExprCodeIN(pParse, pExpr, destIfFalse, destIfNull);
drh076e85f2015-09-03 13:46:12 +00003642 sqlite3VdbeGoto(v, dest);
drhe3365e62009-11-12 17:52:24 +00003643 sqlite3VdbeResolveLabel(v, destIfFalse);
3644 break;
3645 }
shanehbb201342011-02-09 19:55:20 +00003646#endif
drhcce7d172000-05-31 15:34:51 +00003647 default: {
drh991a1982014-01-02 17:57:16 +00003648 if( exprAlwaysTrue(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00003649 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00003650 }else if( exprAlwaysFalse(pExpr) ){
3651 /* No-op */
3652 }else{
3653 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3654 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00003655 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00003656 testcase( regFree1==0 );
3657 testcase( jumpIfNull==0 );
3658 }
drhcce7d172000-05-31 15:34:51 +00003659 break;
3660 }
3661 }
drh2dcef112008-01-12 19:03:48 +00003662 sqlite3ReleaseTempReg(pParse, regFree1);
3663 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00003664}
3665
3666/*
drh66b89c82000-11-28 20:47:17 +00003667** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00003668** to the label "dest" if the expression is false but execution
3669** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00003670**
3671** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00003672** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
3673** is 0.
drhcce7d172000-05-31 15:34:51 +00003674*/
danielk19774adee202004-05-08 08:23:19 +00003675void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00003676 Vdbe *v = pParse->pVdbe;
3677 int op = 0;
drh2dcef112008-01-12 19:03:48 +00003678 int regFree1 = 0;
3679 int regFree2 = 0;
3680 int r1, r2;
3681
drh35573352008-01-08 23:54:25 +00003682 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
mistachkin48864df2013-03-21 21:20:32 +00003683 if( NEVER(v==0) ) return; /* Existence of VDBE checked by caller */
drh33cd4902009-05-30 20:49:20 +00003684 if( pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00003685
3686 /* The value of pExpr->op and op are related as follows:
3687 **
3688 ** pExpr->op op
3689 ** --------- ----------
3690 ** TK_ISNULL OP_NotNull
3691 ** TK_NOTNULL OP_IsNull
3692 ** TK_NE OP_Eq
3693 ** TK_EQ OP_Ne
3694 ** TK_GT OP_Le
3695 ** TK_LE OP_Gt
3696 ** TK_GE OP_Lt
3697 ** TK_LT OP_Ge
3698 **
3699 ** For other values of pExpr->op, op is undefined and unused.
3700 ** The value of TK_ and OP_ constants are arranged such that we
3701 ** can compute the mapping above using the following expression.
3702 ** Assert()s verify that the computation is correct.
3703 */
3704 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3705
3706 /* Verify correct alignment of TK_ and OP_ constants
3707 */
3708 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3709 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3710 assert( pExpr->op!=TK_NE || op==OP_Eq );
3711 assert( pExpr->op!=TK_EQ || op==OP_Ne );
3712 assert( pExpr->op!=TK_LT || op==OP_Ge );
3713 assert( pExpr->op!=TK_LE || op==OP_Gt );
3714 assert( pExpr->op!=TK_GT || op==OP_Le );
3715 assert( pExpr->op!=TK_GE || op==OP_Lt );
3716
drhcce7d172000-05-31 15:34:51 +00003717 switch( pExpr->op ){
3718 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00003719 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00003720 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drh54e2adb2014-01-04 15:17:04 +00003721 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00003722 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhd2490902014-04-13 19:28:15 +00003723 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00003724 break;
3725 }
3726 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00003727 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00003728 testcase( jumpIfNull==0 );
drh35573352008-01-08 23:54:25 +00003729 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drh54e2adb2014-01-04 15:17:04 +00003730 sqlite3ExprCachePush(pParse);
danielk19774adee202004-05-08 08:23:19 +00003731 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
3732 sqlite3VdbeResolveLabel(v, d2);
drhd2490902014-04-13 19:28:15 +00003733 sqlite3ExprCachePop(pParse);
drhcce7d172000-05-31 15:34:51 +00003734 break;
3735 }
3736 case TK_NOT: {
drh5c03f302009-11-13 15:03:59 +00003737 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00003738 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00003739 break;
3740 }
drhde845c22016-03-17 19:07:52 +00003741 case TK_IS:
3742 case TK_ISNOT:
3743 testcase( pExpr->op==TK_IS );
3744 testcase( pExpr->op==TK_ISNOT );
3745 op = (pExpr->op==TK_IS) ? TK_NE : TK_EQ;
3746 jumpIfNull = SQLITE_NULLEQ;
3747 /* Fall thru */
drhcce7d172000-05-31 15:34:51 +00003748 case TK_LT:
3749 case TK_LE:
3750 case TK_GT:
3751 case TK_GE:
3752 case TK_NE:
3753 case TK_EQ: {
drhc5499be2008-04-01 15:06:33 +00003754 testcase( jumpIfNull==0 );
drhb6da74e2009-12-24 16:00:28 +00003755 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3756 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh35573352008-01-08 23:54:25 +00003757 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00003758 r1, r2, dest, jumpIfNull);
drh7d176102014-02-18 03:07:12 +00003759 assert(TK_LT==OP_Lt); testcase(op==OP_Lt); VdbeCoverageIf(v,op==OP_Lt);
3760 assert(TK_LE==OP_Le); testcase(op==OP_Le); VdbeCoverageIf(v,op==OP_Le);
3761 assert(TK_GT==OP_Gt); testcase(op==OP_Gt); VdbeCoverageIf(v,op==OP_Gt);
3762 assert(TK_GE==OP_Ge); testcase(op==OP_Ge); VdbeCoverageIf(v,op==OP_Ge);
drhde845c22016-03-17 19:07:52 +00003763 assert(TK_EQ==OP_Eq); testcase(op==OP_Eq);
3764 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull!=SQLITE_NULLEQ);
3765 VdbeCoverageIf(v, op==OP_Eq && jumpIfNull==SQLITE_NULLEQ);
3766 assert(TK_NE==OP_Ne); testcase(op==OP_Ne);
3767 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull!=SQLITE_NULLEQ);
3768 VdbeCoverageIf(v, op==OP_Ne && jumpIfNull==SQLITE_NULLEQ);
drh6a2fe092009-09-23 02:29:36 +00003769 testcase( regFree1==0 );
3770 testcase( regFree2==0 );
3771 break;
3772 }
drhcce7d172000-05-31 15:34:51 +00003773 case TK_ISNULL:
3774 case TK_NOTNULL: {
drh2dcef112008-01-12 19:03:48 +00003775 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3776 sqlite3VdbeAddOp2(v, op, r1, dest);
drh7d176102014-02-18 03:07:12 +00003777 testcase( op==TK_ISNULL ); VdbeCoverageIf(v, op==TK_ISNULL);
3778 testcase( op==TK_NOTNULL ); VdbeCoverageIf(v, op==TK_NOTNULL);
drhc5499be2008-04-01 15:06:33 +00003779 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00003780 break;
3781 }
drhfef52082000-06-06 01:50:43 +00003782 case TK_BETWEEN: {
drh5c03f302009-11-13 15:03:59 +00003783 testcase( jumpIfNull==0 );
drh36c563a2009-11-12 13:32:22 +00003784 exprCodeBetween(pParse, pExpr, dest, 0, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00003785 break;
3786 }
drh84e30ca2011-02-10 17:46:14 +00003787#ifndef SQLITE_OMIT_SUBQUERY
drhe3365e62009-11-12 17:52:24 +00003788 case TK_IN: {
3789 if( jumpIfNull ){
3790 sqlite3ExprCodeIN(pParse, pExpr, dest, dest);
3791 }else{
3792 int destIfNull = sqlite3VdbeMakeLabel(v);
3793 sqlite3ExprCodeIN(pParse, pExpr, dest, destIfNull);
3794 sqlite3VdbeResolveLabel(v, destIfNull);
3795 }
3796 break;
3797 }
shanehbb201342011-02-09 19:55:20 +00003798#endif
drhcce7d172000-05-31 15:34:51 +00003799 default: {
drh991a1982014-01-02 17:57:16 +00003800 if( exprAlwaysFalse(pExpr) ){
drh076e85f2015-09-03 13:46:12 +00003801 sqlite3VdbeGoto(v, dest);
drh991a1982014-01-02 17:57:16 +00003802 }else if( exprAlwaysTrue(pExpr) ){
3803 /* no-op */
3804 }else{
3805 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3806 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drh688852a2014-02-17 22:40:43 +00003807 VdbeCoverage(v);
drh991a1982014-01-02 17:57:16 +00003808 testcase( regFree1==0 );
3809 testcase( jumpIfNull==0 );
3810 }
drhcce7d172000-05-31 15:34:51 +00003811 break;
3812 }
3813 }
drh2dcef112008-01-12 19:03:48 +00003814 sqlite3ReleaseTempReg(pParse, regFree1);
3815 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00003816}
drh22827922000-06-06 17:27:05 +00003817
3818/*
drh72bc8202015-06-11 13:58:35 +00003819** Like sqlite3ExprIfFalse() except that a copy is made of pExpr before
3820** code generation, and that copy is deleted after code generation. This
3821** ensures that the original pExpr is unchanged.
3822*/
3823void sqlite3ExprIfFalseDup(Parse *pParse, Expr *pExpr, int dest,int jumpIfNull){
3824 sqlite3 *db = pParse->db;
3825 Expr *pCopy = sqlite3ExprDup(db, pExpr, 0);
3826 if( db->mallocFailed==0 ){
3827 sqlite3ExprIfFalse(pParse, pCopy, dest, jumpIfNull);
3828 }
3829 sqlite3ExprDelete(db, pCopy);
3830}
3831
3832
3833/*
drh1d9da702010-01-07 15:17:02 +00003834** Do a deep comparison of two expression trees. Return 0 if the two
3835** expressions are completely identical. Return 1 if they differ only
3836** by a COLLATE operator at the top level. Return 2 if there are differences
3837** other than the top-level COLLATE operator.
drhd40aab02007-02-24 15:29:03 +00003838**
drh619a1302013-08-01 13:04:46 +00003839** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3840** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3841**
drh66518ca2013-08-01 15:09:57 +00003842** The pA side might be using TK_REGISTER. If that is the case and pB is
3843** not using TK_REGISTER but is otherwise equivalent, then still return 0.
3844**
drh1d9da702010-01-07 15:17:02 +00003845** Sometimes this routine will return 2 even if the two expressions
drhd40aab02007-02-24 15:29:03 +00003846** really are equivalent. If we cannot prove that the expressions are
drh1d9da702010-01-07 15:17:02 +00003847** identical, we return 2 just to be safe. So if this routine
3848** returns 2, then you do not really know for certain if the two
3849** expressions are the same. But if you get a 0 or 1 return, then you
drhd40aab02007-02-24 15:29:03 +00003850** can be sure the expressions are the same. In the places where
drh1d9da702010-01-07 15:17:02 +00003851** this routine is used, it does not hurt to get an extra 2 - that
drhd40aab02007-02-24 15:29:03 +00003852** just might result in some slightly slower code. But returning
drh1d9da702010-01-07 15:17:02 +00003853** an incorrect 0 or 1 could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00003854*/
drh619a1302013-08-01 13:04:46 +00003855int sqlite3ExprCompare(Expr *pA, Expr *pB, int iTab){
drh10d1edf2013-11-15 15:52:39 +00003856 u32 combinedFlags;
3857 if( pA==0 || pB==0 ){
drh1d9da702010-01-07 15:17:02 +00003858 return pB==pA ? 0 : 2;
drh22827922000-06-06 17:27:05 +00003859 }
drh10d1edf2013-11-15 15:52:39 +00003860 combinedFlags = pA->flags | pB->flags;
3861 if( combinedFlags & EP_IntValue ){
3862 if( (pA->flags&pB->flags&EP_IntValue)!=0 && pA->u.iValue==pB->u.iValue ){
3863 return 0;
3864 }
drh1d9da702010-01-07 15:17:02 +00003865 return 2;
drh22827922000-06-06 17:27:05 +00003866 }
drhc2acc4e2013-11-15 18:15:19 +00003867 if( pA->op!=pB->op ){
drh619a1302013-08-01 13:04:46 +00003868 if( pA->op==TK_COLLATE && sqlite3ExprCompare(pA->pLeft, pB, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00003869 return 1;
3870 }
drh619a1302013-08-01 13:04:46 +00003871 if( pB->op==TK_COLLATE && sqlite3ExprCompare(pA, pB->pLeft, iTab)<2 ){
drhae80dde2012-12-06 21:16:43 +00003872 return 1;
3873 }
3874 return 2;
3875 }
drh2edc5fd2015-11-24 02:10:52 +00003876 if( pA->op!=TK_COLUMN && pA->op!=TK_AGG_COLUMN && pA->u.zToken ){
drh390b88a2015-08-31 18:13:01 +00003877 if( pA->op==TK_FUNCTION ){
3878 if( sqlite3StrICmp(pA->u.zToken,pB->u.zToken)!=0 ) return 2;
3879 }else if( strcmp(pA->u.zToken,pB->u.zToken)!=0 ){
drhae80dde2012-12-06 21:16:43 +00003880 return pA->op==TK_COLLATE ? 1 : 2;
drh2646da72005-12-09 20:02:05 +00003881 }
drh22827922000-06-06 17:27:05 +00003882 }
drh10d1edf2013-11-15 15:52:39 +00003883 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 2;
drh85f8aa72013-11-15 20:06:26 +00003884 if( ALWAYS((combinedFlags & EP_TokenOnly)==0) ){
drh10d1edf2013-11-15 15:52:39 +00003885 if( combinedFlags & EP_xIsSelect ) return 2;
3886 if( sqlite3ExprCompare(pA->pLeft, pB->pLeft, iTab) ) return 2;
3887 if( sqlite3ExprCompare(pA->pRight, pB->pRight, iTab) ) return 2;
3888 if( sqlite3ExprListCompare(pA->x.pList, pB->x.pList, iTab) ) return 2;
drh7693c422015-04-17 19:41:37 +00003889 if( ALWAYS((combinedFlags & EP_Reduced)==0) && pA->op!=TK_STRING ){
drh10d1edf2013-11-15 15:52:39 +00003890 if( pA->iColumn!=pB->iColumn ) return 2;
3891 if( pA->iTable!=pB->iTable
drh85f8aa72013-11-15 20:06:26 +00003892 && (pA->iTable!=iTab || NEVER(pB->iTable>=0)) ) return 2;
drh10d1edf2013-11-15 15:52:39 +00003893 }
3894 }
drh1d9da702010-01-07 15:17:02 +00003895 return 0;
drh22827922000-06-06 17:27:05 +00003896}
3897
drh8c6f6662010-04-26 19:17:26 +00003898/*
3899** Compare two ExprList objects. Return 0 if they are identical and
3900** non-zero if they differ in any way.
3901**
drh619a1302013-08-01 13:04:46 +00003902** If any subelement of pB has Expr.iTable==(-1) then it is allowed
3903** to compare equal to an equivalent element in pA with Expr.iTable==iTab.
3904**
drh8c6f6662010-04-26 19:17:26 +00003905** This routine might return non-zero for equivalent ExprLists. The
3906** only consequence will be disabled optimizations. But this routine
3907** must never return 0 if the two ExprList objects are different, or
3908** a malfunction will result.
3909**
3910** Two NULL pointers are considered to be the same. But a NULL pointer
3911** always differs from a non-NULL pointer.
3912*/
drh619a1302013-08-01 13:04:46 +00003913int sqlite3ExprListCompare(ExprList *pA, ExprList *pB, int iTab){
drh8c6f6662010-04-26 19:17:26 +00003914 int i;
3915 if( pA==0 && pB==0 ) return 0;
3916 if( pA==0 || pB==0 ) return 1;
3917 if( pA->nExpr!=pB->nExpr ) return 1;
3918 for(i=0; i<pA->nExpr; i++){
3919 Expr *pExprA = pA->a[i].pExpr;
3920 Expr *pExprB = pB->a[i].pExpr;
3921 if( pA->a[i].sortOrder!=pB->a[i].sortOrder ) return 1;
drh619a1302013-08-01 13:04:46 +00003922 if( sqlite3ExprCompare(pExprA, pExprB, iTab) ) return 1;
drh8c6f6662010-04-26 19:17:26 +00003923 }
3924 return 0;
3925}
drh13449892005-09-07 21:22:45 +00003926
drh22827922000-06-06 17:27:05 +00003927/*
drh4bd5f732013-07-31 23:22:39 +00003928** Return true if we can prove the pE2 will always be true if pE1 is
3929** true. Return false if we cannot complete the proof or if pE2 might
3930** be false. Examples:
3931**
drh619a1302013-08-01 13:04:46 +00003932** pE1: x==5 pE2: x==5 Result: true
3933** pE1: x>0 pE2: x==5 Result: false
3934** pE1: x=21 pE2: x=21 OR y=43 Result: true
3935** pE1: x!=123 pE2: x IS NOT NULL Result: true
3936** pE1: x!=?1 pE2: x IS NOT NULL Result: true
3937** pE1: x IS NULL pE2: x IS NOT NULL Result: false
3938** pE1: x IS ?2 pE2: x IS NOT NULL Reuslt: false
drh4bd5f732013-07-31 23:22:39 +00003939**
3940** When comparing TK_COLUMN nodes between pE1 and pE2, if pE2 has
3941** Expr.iTable<0 then assume a table number given by iTab.
3942**
3943** When in doubt, return false. Returning true might give a performance
3944** improvement. Returning false might cause a performance reduction, but
3945** it will always give the correct answer and is hence always safe.
3946*/
3947int sqlite3ExprImpliesExpr(Expr *pE1, Expr *pE2, int iTab){
drh619a1302013-08-01 13:04:46 +00003948 if( sqlite3ExprCompare(pE1, pE2, iTab)==0 ){
3949 return 1;
3950 }
3951 if( pE2->op==TK_OR
3952 && (sqlite3ExprImpliesExpr(pE1, pE2->pLeft, iTab)
3953 || sqlite3ExprImpliesExpr(pE1, pE2->pRight, iTab) )
3954 ){
3955 return 1;
3956 }
3957 if( pE2->op==TK_NOTNULL
3958 && sqlite3ExprCompare(pE1->pLeft, pE2->pLeft, iTab)==0
3959 && (pE1->op!=TK_ISNULL && pE1->op!=TK_IS)
3960 ){
3961 return 1;
3962 }
3963 return 0;
drh4bd5f732013-07-31 23:22:39 +00003964}
3965
3966/*
drh030796d2012-08-23 16:18:10 +00003967** An instance of the following structure is used by the tree walker
3968** to count references to table columns in the arguments of an
drhed551b92012-08-23 19:46:11 +00003969** aggregate function, in order to implement the
3970** sqlite3FunctionThisSrc() routine.
drh374fdce2012-04-17 16:38:53 +00003971*/
drh030796d2012-08-23 16:18:10 +00003972struct SrcCount {
3973 SrcList *pSrc; /* One particular FROM clause in a nested query */
3974 int nThis; /* Number of references to columns in pSrcList */
3975 int nOther; /* Number of references to columns in other FROM clauses */
3976};
3977
3978/*
3979** Count the number of references to columns.
3980*/
3981static int exprSrcCount(Walker *pWalker, Expr *pExpr){
drhfb0a6082012-08-24 01:07:52 +00003982 /* The NEVER() on the second term is because sqlite3FunctionUsesThisSrc()
3983 ** is always called before sqlite3ExprAnalyzeAggregates() and so the
3984 ** TK_COLUMNs have not yet been converted into TK_AGG_COLUMN. If
3985 ** sqlite3FunctionUsesThisSrc() is used differently in the future, the
3986 ** NEVER() will need to be removed. */
3987 if( pExpr->op==TK_COLUMN || NEVER(pExpr->op==TK_AGG_COLUMN) ){
drh374fdce2012-04-17 16:38:53 +00003988 int i;
drh030796d2012-08-23 16:18:10 +00003989 struct SrcCount *p = pWalker->u.pSrcCount;
3990 SrcList *pSrc = p->pSrc;
drh655814d2015-01-09 01:27:29 +00003991 int nSrc = pSrc ? pSrc->nSrc : 0;
3992 for(i=0; i<nSrc; i++){
drh030796d2012-08-23 16:18:10 +00003993 if( pExpr->iTable==pSrc->a[i].iCursor ) break;
drh374fdce2012-04-17 16:38:53 +00003994 }
drh655814d2015-01-09 01:27:29 +00003995 if( i<nSrc ){
drh030796d2012-08-23 16:18:10 +00003996 p->nThis++;
3997 }else{
3998 p->nOther++;
3999 }
drh374fdce2012-04-17 16:38:53 +00004000 }
drh030796d2012-08-23 16:18:10 +00004001 return WRC_Continue;
drh374fdce2012-04-17 16:38:53 +00004002}
4003
4004/*
drh030796d2012-08-23 16:18:10 +00004005** Determine if any of the arguments to the pExpr Function reference
4006** pSrcList. Return true if they do. Also return true if the function
4007** has no arguments or has only constant arguments. Return false if pExpr
4008** references columns but not columns of tables found in pSrcList.
drh374fdce2012-04-17 16:38:53 +00004009*/
drh030796d2012-08-23 16:18:10 +00004010int sqlite3FunctionUsesThisSrc(Expr *pExpr, SrcList *pSrcList){
drh374fdce2012-04-17 16:38:53 +00004011 Walker w;
drh030796d2012-08-23 16:18:10 +00004012 struct SrcCount cnt;
drh374fdce2012-04-17 16:38:53 +00004013 assert( pExpr->op==TK_AGG_FUNCTION );
4014 memset(&w, 0, sizeof(w));
drh030796d2012-08-23 16:18:10 +00004015 w.xExprCallback = exprSrcCount;
4016 w.u.pSrcCount = &cnt;
4017 cnt.pSrc = pSrcList;
4018 cnt.nThis = 0;
4019 cnt.nOther = 0;
4020 sqlite3WalkExprList(&w, pExpr->x.pList);
4021 return cnt.nThis>0 || cnt.nOther==0;
drh374fdce2012-04-17 16:38:53 +00004022}
4023
4024/*
drh13449892005-09-07 21:22:45 +00004025** Add a new element to the pAggInfo->aCol[] array. Return the index of
4026** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00004027*/
drh17435752007-08-16 04:30:38 +00004028static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004029 int i;
drhcf643722007-03-27 13:36:37 +00004030 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004031 db,
drhcf643722007-03-27 13:36:37 +00004032 pInfo->aCol,
4033 sizeof(pInfo->aCol[0]),
drhcf643722007-03-27 13:36:37 +00004034 &pInfo->nColumn,
drhcf643722007-03-27 13:36:37 +00004035 &i
4036 );
drh13449892005-09-07 21:22:45 +00004037 return i;
4038}
4039
4040/*
4041** Add a new element to the pAggInfo->aFunc[] array. Return the index of
4042** the new element. Return a negative number if malloc fails.
4043*/
drh17435752007-08-16 04:30:38 +00004044static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00004045 int i;
drhcf643722007-03-27 13:36:37 +00004046 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00004047 db,
drhcf643722007-03-27 13:36:37 +00004048 pInfo->aFunc,
4049 sizeof(pInfo->aFunc[0]),
drhcf643722007-03-27 13:36:37 +00004050 &pInfo->nFunc,
drhcf643722007-03-27 13:36:37 +00004051 &i
4052 );
drh13449892005-09-07 21:22:45 +00004053 return i;
4054}
drh22827922000-06-06 17:27:05 +00004055
4056/*
drh7d10d5a2008-08-20 16:35:10 +00004057** This is the xExprCallback for a tree walker. It is used to
4058** implement sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
drh626a8792005-01-17 22:08:19 +00004059** for additional information.
drh22827922000-06-06 17:27:05 +00004060*/
drh7d10d5a2008-08-20 16:35:10 +00004061static int analyzeAggregate(Walker *pWalker, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00004062 int i;
drh7d10d5a2008-08-20 16:35:10 +00004063 NameContext *pNC = pWalker->u.pNC;
danielk1977a58fdfb2005-02-08 07:50:40 +00004064 Parse *pParse = pNC->pParse;
4065 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00004066 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00004067
drh22827922000-06-06 17:27:05 +00004068 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00004069 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00004070 case TK_COLUMN: {
drh8b213892008-08-29 02:14:02 +00004071 testcase( pExpr->op==TK_AGG_COLUMN );
4072 testcase( pExpr->op==TK_COLUMN );
drh13449892005-09-07 21:22:45 +00004073 /* Check to see if the column is in one of the tables in the FROM
4074 ** clause of the aggregate query */
drh20bc3932009-05-30 23:35:43 +00004075 if( ALWAYS(pSrcList!=0) ){
drh13449892005-09-07 21:22:45 +00004076 struct SrcList_item *pItem = pSrcList->a;
4077 for(i=0; i<pSrcList->nSrc; i++, pItem++){
4078 struct AggInfo_col *pCol;
drhc5cd1242013-09-12 16:50:49 +00004079 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh13449892005-09-07 21:22:45 +00004080 if( pExpr->iTable==pItem->iCursor ){
4081 /* If we reach this point, it means that pExpr refers to a table
4082 ** that is in the FROM clause of the aggregate query.
4083 **
4084 ** Make an entry for the column in pAggInfo->aCol[] if there
4085 ** is not an entry there already.
4086 */
drh7f906d62007-03-12 23:48:52 +00004087 int k;
drh13449892005-09-07 21:22:45 +00004088 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00004089 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00004090 if( pCol->iTable==pExpr->iTable &&
4091 pCol->iColumn==pExpr->iColumn ){
4092 break;
4093 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004094 }
danielk19771e536952007-08-16 10:09:01 +00004095 if( (k>=pAggInfo->nColumn)
4096 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
4097 ){
drh7f906d62007-03-12 23:48:52 +00004098 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00004099 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00004100 pCol->iTable = pExpr->iTable;
4101 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00004102 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00004103 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00004104 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00004105 if( pAggInfo->pGroupBy ){
4106 int j, n;
4107 ExprList *pGB = pAggInfo->pGroupBy;
4108 struct ExprList_item *pTerm = pGB->a;
4109 n = pGB->nExpr;
4110 for(j=0; j<n; j++, pTerm++){
4111 Expr *pE = pTerm->pExpr;
4112 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
4113 pE->iColumn==pExpr->iColumn ){
4114 pCol->iSorterColumn = j;
4115 break;
4116 }
4117 }
4118 }
4119 if( pCol->iSorterColumn<0 ){
4120 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
4121 }
4122 }
4123 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
4124 ** because it was there before or because we just created it).
4125 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
4126 ** pAggInfo->aCol[] entry.
4127 */
drhebb6a652013-09-12 23:42:22 +00004128 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh13449892005-09-07 21:22:45 +00004129 pExpr->pAggInfo = pAggInfo;
4130 pExpr->op = TK_AGG_COLUMN;
shanecf697392009-06-01 16:53:09 +00004131 pExpr->iAgg = (i16)k;
drh13449892005-09-07 21:22:45 +00004132 break;
4133 } /* endif pExpr->iTable==pItem->iCursor */
4134 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00004135 }
drh7d10d5a2008-08-20 16:35:10 +00004136 return WRC_Prune;
drh22827922000-06-06 17:27:05 +00004137 }
4138 case TK_AGG_FUNCTION: {
drh3a8c4be2012-05-21 20:13:39 +00004139 if( (pNC->ncFlags & NC_InAggFunc)==0
drhed551b92012-08-23 19:46:11 +00004140 && pWalker->walkerDepth==pExpr->op2
drh3a8c4be2012-05-21 20:13:39 +00004141 ){
drh13449892005-09-07 21:22:45 +00004142 /* Check to see if pExpr is a duplicate of another aggregate
4143 ** function that is already in the pAggInfo structure
4144 */
4145 struct AggInfo_func *pItem = pAggInfo->aFunc;
4146 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
drh619a1302013-08-01 13:04:46 +00004147 if( sqlite3ExprCompare(pItem->pExpr, pExpr, -1)==0 ){
danielk1977a58fdfb2005-02-08 07:50:40 +00004148 break;
4149 }
drh22827922000-06-06 17:27:05 +00004150 }
drh13449892005-09-07 21:22:45 +00004151 if( i>=pAggInfo->nFunc ){
4152 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
4153 */
danielk197714db2662006-01-09 16:12:04 +00004154 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00004155 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00004156 if( i>=0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +00004157 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh13449892005-09-07 21:22:45 +00004158 pItem = &pAggInfo->aFunc[i];
4159 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00004160 pItem->iMem = ++pParse->nMem;
drh33e619f2009-05-28 01:00:55 +00004161 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh13449892005-09-07 21:22:45 +00004162 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh80738d92016-02-15 00:34:16 +00004163 pExpr->u.zToken,
danielk19776ab3a2e2009-02-19 14:39:25 +00004164 pExpr->x.pList ? pExpr->x.pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00004165 if( pExpr->flags & EP_Distinct ){
4166 pItem->iDistinct = pParse->nTab++;
4167 }else{
4168 pItem->iDistinct = -1;
4169 }
drh13449892005-09-07 21:22:45 +00004170 }
danielk1977a58fdfb2005-02-08 07:50:40 +00004171 }
drh13449892005-09-07 21:22:45 +00004172 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
4173 */
drhc5cd1242013-09-12 16:50:49 +00004174 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drhebb6a652013-09-12 23:42:22 +00004175 ExprSetVVAProperty(pExpr, EP_NoReduce);
shanecf697392009-06-01 16:53:09 +00004176 pExpr->iAgg = (i16)i;
drh13449892005-09-07 21:22:45 +00004177 pExpr->pAggInfo = pAggInfo;
drh6e83a572012-11-02 18:48:49 +00004178 return WRC_Prune;
4179 }else{
4180 return WRC_Continue;
drh22827922000-06-06 17:27:05 +00004181 }
drh22827922000-06-06 17:27:05 +00004182 }
4183 }
drh7d10d5a2008-08-20 16:35:10 +00004184 return WRC_Continue;
4185}
4186static int analyzeAggregatesInSelect(Walker *pWalker, Select *pSelect){
drhd5a336e2012-04-19 15:49:19 +00004187 UNUSED_PARAMETER(pWalker);
4188 UNUSED_PARAMETER(pSelect);
drh374fdce2012-04-17 16:38:53 +00004189 return WRC_Continue;
drh626a8792005-01-17 22:08:19 +00004190}
4191
4192/*
drhe8abb4c2012-11-02 18:24:57 +00004193** Analyze the pExpr expression looking for aggregate functions and
4194** for variables that need to be added to AggInfo object that pNC->pAggInfo
4195** points to. Additional entries are made on the AggInfo object as
4196** necessary.
drh626a8792005-01-17 22:08:19 +00004197**
4198** This routine should only be called after the expression has been
drh7d10d5a2008-08-20 16:35:10 +00004199** analyzed by sqlite3ResolveExprNames().
drh626a8792005-01-17 22:08:19 +00004200*/
drhd2b3e232008-01-23 14:51:49 +00004201void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
drh7d10d5a2008-08-20 16:35:10 +00004202 Walker w;
drh374fdce2012-04-17 16:38:53 +00004203 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00004204 w.xExprCallback = analyzeAggregate;
4205 w.xSelectCallback = analyzeAggregatesInSelect;
4206 w.u.pNC = pNC;
drh20bc3932009-05-30 23:35:43 +00004207 assert( pNC->pSrcList!=0 );
drh7d10d5a2008-08-20 16:35:10 +00004208 sqlite3WalkExpr(&w, pExpr);
drh22827922000-06-06 17:27:05 +00004209}
drh5d9a4af2005-08-30 00:54:01 +00004210
4211/*
4212** Call sqlite3ExprAnalyzeAggregates() for every expression in an
4213** expression list. Return the number of errors.
4214**
4215** If an error is found, the analysis is cut short.
4216*/
drhd2b3e232008-01-23 14:51:49 +00004217void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00004218 struct ExprList_item *pItem;
4219 int i;
drh5d9a4af2005-08-30 00:54:01 +00004220 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00004221 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
4222 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00004223 }
4224 }
drh5d9a4af2005-08-30 00:54:01 +00004225}
drh892d3172008-01-10 03:46:36 +00004226
4227/*
drhceea3322009-04-23 13:22:42 +00004228** Allocate a single new register for use to hold some intermediate result.
drh892d3172008-01-10 03:46:36 +00004229*/
4230int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00004231 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00004232 return ++pParse->nMem;
4233 }
danielk19772f425f62008-07-04 09:41:39 +00004234 return pParse->aTempReg[--pParse->nTempReg];
drh892d3172008-01-10 03:46:36 +00004235}
drhceea3322009-04-23 13:22:42 +00004236
4237/*
4238** Deallocate a register, making available for reuse for some other
4239** purpose.
4240**
4241** If a register is currently being used by the column cache, then
peter.d.reid60ec9142014-09-06 16:39:46 +00004242** the deallocation is deferred until the column cache line that uses
drhceea3322009-04-23 13:22:42 +00004243** the register becomes stale.
4244*/
drh892d3172008-01-10 03:46:36 +00004245void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00004246 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drhceea3322009-04-23 13:22:42 +00004247 int i;
4248 struct yColCache *p;
4249 for(i=0, p=pParse->aColCache; i<SQLITE_N_COLCACHE; i++, p++){
4250 if( p->iReg==iReg ){
4251 p->tempReg = 1;
4252 return;
4253 }
4254 }
drh892d3172008-01-10 03:46:36 +00004255 pParse->aTempReg[pParse->nTempReg++] = iReg;
4256 }
4257}
4258
4259/*
4260** Allocate or deallocate a block of nReg consecutive registers
4261*/
4262int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00004263 int i, n;
4264 i = pParse->iRangeReg;
4265 n = pParse->nRangeReg;
drhf49f3522009-12-30 14:12:38 +00004266 if( nReg<=n ){
4267 assert( !usedAsColumnCache(pParse, i, i+n-1) );
drh892d3172008-01-10 03:46:36 +00004268 pParse->iRangeReg += nReg;
4269 pParse->nRangeReg -= nReg;
4270 }else{
4271 i = pParse->nMem+1;
4272 pParse->nMem += nReg;
4273 }
4274 return i;
4275}
4276void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
drhf49f3522009-12-30 14:12:38 +00004277 sqlite3ExprCacheRemove(pParse, iReg, nReg);
drh892d3172008-01-10 03:46:36 +00004278 if( nReg>pParse->nRangeReg ){
4279 pParse->nRangeReg = nReg;
4280 pParse->iRangeReg = iReg;
4281 }
4282}
drhcdc69552011-12-06 13:24:59 +00004283
4284/*
4285** Mark all temporary registers as being unavailable for reuse.
4286*/
4287void sqlite3ClearTempRegCache(Parse *pParse){
4288 pParse->nTempReg = 0;
4289 pParse->nRangeReg = 0;
4290}
drhbb9b5f22016-03-19 00:35:02 +00004291
4292/*
4293** Validate that no temporary register falls within the range of
4294** iFirst..iLast, inclusive. This routine is only call from within assert()
4295** statements.
4296*/
4297#ifdef SQLITE_DEBUG
4298int sqlite3NoTempsInRange(Parse *pParse, int iFirst, int iLast){
4299 int i;
4300 if( pParse->nRangeReg>0
4301 && pParse->iRangeReg+pParse->nRangeReg<iLast
4302 && pParse->iRangeReg>=iFirst
4303 ){
4304 return 0;
4305 }
4306 for(i=0; i<pParse->nTempReg; i++){
4307 if( pParse->aTempReg[i]>=iFirst && pParse->aTempReg[i]<=iLast ){
4308 return 0;
4309 }
4310 }
4311 return 1;
4312}
4313#endif /* SQLITE_DEBUG */