blob: ef88cfecc00c40aa0c84b4cdc81a3fa1d2d0fa91 [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**
drhb21e7c72008-06-22 12:37:57 +000015** $Id: expr.c,v 1.374 2008/06/22 12:37:58 drh Exp $
drhcce7d172000-05-31 15:34:51 +000016*/
17#include "sqliteInt.h"
drh04738cb2002-06-02 18:19:00 +000018#include <ctype.h>
drha2e00042002-01-22 03:13:42 +000019
danielk1977e014a832004-05-17 10:48:57 +000020/*
21** Return the 'affinity' of the expression pExpr if any.
22**
23** If pExpr is a column, a reference to a column via an 'AS' alias,
24** or a sub-select with a column as the return value, then the
25** affinity of that column is returned. Otherwise, 0x00 is returned,
26** indicating no affinity for the expression.
27**
28** i.e. the WHERE clause expresssions in the following statements all
29** have an affinity:
30**
31** CREATE TABLE t1(a);
32** SELECT * FROM t1 WHERE a;
33** SELECT a AS b FROM t1 WHERE b;
34** SELECT * FROM t1 WHERE (select a from t1);
35*/
danielk1977bf3b7212004-05-18 10:06:24 +000036char sqlite3ExprAffinity(Expr *pExpr){
drh487e2622005-06-25 18:42:14 +000037 int op = pExpr->op;
drh487e2622005-06-25 18:42:14 +000038 if( op==TK_SELECT ){
danielk1977bf3b7212004-05-18 10:06:24 +000039 return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
danielk1977a37cdde2004-05-16 11:15:36 +000040 }
drh487e2622005-06-25 18:42:14 +000041#ifndef SQLITE_OMIT_CAST
42 if( op==TK_CAST ){
drh8a512562005-11-14 22:29:05 +000043 return sqlite3AffinityType(&pExpr->token);
drh487e2622005-06-25 18:42:14 +000044 }
45#endif
danielk1977a37cdde2004-05-16 11:15:36 +000046 return pExpr->affinity;
47}
48
drh53db1452004-05-20 13:54:53 +000049/*
drh8b4c40d2007-02-01 23:02:45 +000050** Set the collating sequence for expression pExpr to be the collating
51** sequence named by pToken. Return a pointer to the revised expression.
drha34001c2007-02-02 12:44:37 +000052** The collating sequence is marked as "explicit" using the EP_ExpCollate
53** flag. An explicit collating sequence will override implicit
54** collating sequences.
drh8b4c40d2007-02-01 23:02:45 +000055*/
56Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
danielk197739002502007-11-12 09:50:26 +000057 char *zColl = 0; /* Dequoted name of collation sequence */
drh8b4c40d2007-02-01 23:02:45 +000058 CollSeq *pColl;
danielk197739002502007-11-12 09:50:26 +000059 zColl = sqlite3NameFromToken(pParse->db, pName);
60 if( pExpr && zColl ){
61 pColl = sqlite3LocateCollSeq(pParse, zColl, -1);
62 if( pColl ){
63 pExpr->pColl = pColl;
64 pExpr->flags |= EP_ExpCollate;
65 }
drh8b4c40d2007-02-01 23:02:45 +000066 }
danielk197739002502007-11-12 09:50:26 +000067 sqlite3_free(zColl);
drh8b4c40d2007-02-01 23:02:45 +000068 return pExpr;
69}
70
71/*
danielk19770202b292004-06-09 09:55:16 +000072** Return the default collation sequence for the expression pExpr. If
73** there is no default collation type, return 0.
74*/
danielk19777cedc8d2004-06-10 10:50:08 +000075CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
76 CollSeq *pColl = 0;
danielk19770202b292004-06-09 09:55:16 +000077 if( pExpr ){
drh7e09fe02007-06-20 16:13:23 +000078 int op;
danielk19777cedc8d2004-06-10 10:50:08 +000079 pColl = pExpr->pColl;
drh7e09fe02007-06-20 16:13:23 +000080 op = pExpr->op;
81 if( (op==TK_CAST || op==TK_UPLUS) && !pColl ){
danielk19777cedc8d2004-06-10 10:50:08 +000082 return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
danielk19770202b292004-06-09 09:55:16 +000083 }
84 }
danielk19777cedc8d2004-06-10 10:50:08 +000085 if( sqlite3CheckCollSeq(pParse, pColl) ){
86 pColl = 0;
87 }
88 return pColl;
danielk19770202b292004-06-09 09:55:16 +000089}
90
91/*
drh626a8792005-01-17 22:08:19 +000092** pExpr is an operand of a comparison operator. aff2 is the
93** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +000094** type affinity that should be used for the comparison operator.
95*/
danielk1977e014a832004-05-17 10:48:57 +000096char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +000097 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +000098 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +000099 /* Both sides of the comparison are columns. If one has numeric
100 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +0000101 */
drh8a512562005-11-14 22:29:05 +0000102 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +0000103 return SQLITE_AFF_NUMERIC;
104 }else{
105 return SQLITE_AFF_NONE;
106 }
107 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +0000108 /* Neither side of the comparison is a column. Compare the
109 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +0000110 */
drh5f6a87b2004-07-19 00:39:45 +0000111 return SQLITE_AFF_NONE;
danielk1977e014a832004-05-17 10:48:57 +0000112 }else{
113 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +0000114 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +0000115 return (aff1 + aff2);
116 }
117}
118
drh53db1452004-05-20 13:54:53 +0000119/*
120** pExpr is a comparison operator. Return the type affinity that should
121** be applied to both operands prior to doing the comparison.
122*/
danielk1977e014a832004-05-17 10:48:57 +0000123static char comparisonAffinity(Expr *pExpr){
124 char aff;
125 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
126 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
127 pExpr->op==TK_NE );
128 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000129 aff = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +0000130 if( pExpr->pRight ){
131 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
132 }
133 else if( pExpr->pSelect ){
134 aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
135 }
136 else if( !aff ){
drhde087bd2007-02-23 03:00:44 +0000137 aff = SQLITE_AFF_NONE;
danielk1977e014a832004-05-17 10:48:57 +0000138 }
139 return aff;
140}
141
142/*
143** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
144** idx_affinity is the affinity of an indexed column. Return true
145** if the index with affinity idx_affinity may be used to implement
146** the comparison in pExpr.
147*/
148int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
149 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000150 switch( aff ){
151 case SQLITE_AFF_NONE:
152 return 1;
153 case SQLITE_AFF_TEXT:
154 return idx_affinity==SQLITE_AFF_TEXT;
155 default:
156 return sqlite3IsNumericAffinity(idx_affinity);
157 }
danielk1977e014a832004-05-17 10:48:57 +0000158}
159
danielk1977a37cdde2004-05-16 11:15:36 +0000160/*
drh35573352008-01-08 23:54:25 +0000161** Return the P5 value that should be used for a binary comparison
danielk1977a37cdde2004-05-16 11:15:36 +0000162** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
danielk1977a37cdde2004-05-16 11:15:36 +0000163*/
drh35573352008-01-08 23:54:25 +0000164static u8 binaryCompareP5(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
165 u8 aff = (char)sqlite3ExprAffinity(pExpr2);
166 aff = sqlite3CompareAffinity(pExpr1, aff) | jumpIfNull;
167 return aff;
danielk1977a37cdde2004-05-16 11:15:36 +0000168}
169
drha2e00042002-01-22 03:13:42 +0000170/*
danielk19770202b292004-06-09 09:55:16 +0000171** Return a pointer to the collation sequence that should be used by
172** a binary comparison operator comparing pLeft and pRight.
173**
174** If the left hand expression has a collating sequence type, then it is
175** used. Otherwise the collation sequence for the right hand expression
176** is used, or the default (BINARY) if neither expression has a collating
177** type.
danielk1977bcbb04e2007-05-29 12:11:29 +0000178**
179** Argument pRight (but not pLeft) may be a null pointer. In this case,
180** it is not considered.
danielk19770202b292004-06-09 09:55:16 +0000181*/
drh0a0e1312007-08-07 17:04:59 +0000182CollSeq *sqlite3BinaryCompareCollSeq(
danielk1977bcbb04e2007-05-29 12:11:29 +0000183 Parse *pParse,
184 Expr *pLeft,
185 Expr *pRight
186){
drhec41dda2007-02-07 13:09:45 +0000187 CollSeq *pColl;
188 assert( pLeft );
drhec41dda2007-02-07 13:09:45 +0000189 if( pLeft->flags & EP_ExpCollate ){
190 assert( pLeft->pColl );
191 pColl = pLeft->pColl;
danielk1977bcbb04e2007-05-29 12:11:29 +0000192 }else if( pRight && pRight->flags & EP_ExpCollate ){
drhec41dda2007-02-07 13:09:45 +0000193 assert( pRight->pColl );
194 pColl = pRight->pColl;
195 }else{
196 pColl = sqlite3ExprCollSeq(pParse, pLeft);
197 if( !pColl ){
198 pColl = sqlite3ExprCollSeq(pParse, pRight);
199 }
danielk19770202b292004-06-09 09:55:16 +0000200 }
201 return pColl;
202}
203
204/*
drhda250ea2008-04-01 05:07:14 +0000205** Generate the operands for a comparison operation. Before
206** generating the code for each operand, set the EP_AnyAff
207** flag on the expression so that it will be able to used a
208** cached column value that has previously undergone an
209** affinity change.
210*/
211static void codeCompareOperands(
212 Parse *pParse, /* Parsing and code generating context */
213 Expr *pLeft, /* The left operand */
214 int *pRegLeft, /* Register where left operand is stored */
215 int *pFreeLeft, /* Free this register when done */
216 Expr *pRight, /* The right operand */
217 int *pRegRight, /* Register where right operand is stored */
218 int *pFreeRight /* Write temp register for right operand there */
219){
220 while( pLeft->op==TK_UPLUS ) pLeft = pLeft->pLeft;
221 pLeft->flags |= EP_AnyAff;
222 *pRegLeft = sqlite3ExprCodeTemp(pParse, pLeft, pFreeLeft);
223 while( pRight->op==TK_UPLUS ) pRight = pRight->pLeft;
224 pRight->flags |= EP_AnyAff;
225 *pRegRight = sqlite3ExprCodeTemp(pParse, pRight, pFreeRight);
226}
227
228/*
drhbe5c89a2004-07-26 00:31:09 +0000229** Generate code for a comparison operator.
230*/
231static int codeCompare(
232 Parse *pParse, /* The parsing (and code generating) context */
233 Expr *pLeft, /* The left operand */
234 Expr *pRight, /* The right operand */
235 int opcode, /* The comparison opcode */
drh35573352008-01-08 23:54:25 +0000236 int in1, int in2, /* Register holding operands */
drhbe5c89a2004-07-26 00:31:09 +0000237 int dest, /* Jump here if true. */
238 int jumpIfNull /* If true, jump if either operand is NULL */
239){
drh35573352008-01-08 23:54:25 +0000240 int p5;
241 int addr;
242 CollSeq *p4;
243
244 p4 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
245 p5 = binaryCompareP5(pLeft, pRight, jumpIfNull);
246 addr = sqlite3VdbeAddOp4(pParse->pVdbe, opcode, in2, dest, in1,
247 (void*)p4, P4_COLLSEQ);
248 sqlite3VdbeChangeP5(pParse->pVdbe, p5);
drh2f7794c2008-04-01 03:27:39 +0000249 if( p5 & SQLITE_AFF_MASK ){
drhda250ea2008-04-01 05:07:14 +0000250 sqlite3ExprCacheAffinityChange(pParse, in1, 1);
251 sqlite3ExprCacheAffinityChange(pParse, in2, 1);
drh2f7794c2008-04-01 03:27:39 +0000252 }
drh35573352008-01-08 23:54:25 +0000253 return addr;
drhbe5c89a2004-07-26 00:31:09 +0000254}
255
danielk19774b5255a2008-06-05 16:47:39 +0000256#if SQLITE_MAX_EXPR_DEPTH>0
257/*
258** Check that argument nHeight is less than or equal to the maximum
259** expression depth allowed. If it is not, leave an error message in
260** pParse.
261*/
262static int checkExprHeight(Parse *pParse, int nHeight){
263 int rc = SQLITE_OK;
264 int mxHeight = pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH];
265 if( nHeight>mxHeight ){
266 sqlite3ErrorMsg(pParse,
267 "Expression tree is too large (maximum depth %d)", mxHeight
268 );
269 rc = SQLITE_ERROR;
270 }
271 return rc;
272}
273
274/* The following three functions, heightOfExpr(), heightOfExprList()
275** and heightOfSelect(), are used to determine the maximum height
276** of any expression tree referenced by the structure passed as the
277** first argument.
278**
279** If this maximum height is greater than the current value pointed
280** to by pnHeight, the second parameter, then set *pnHeight to that
281** value.
282*/
283static void heightOfExpr(Expr *p, int *pnHeight){
284 if( p ){
285 if( p->nHeight>*pnHeight ){
286 *pnHeight = p->nHeight;
287 }
288 }
289}
290static void heightOfExprList(ExprList *p, int *pnHeight){
291 if( p ){
292 int i;
293 for(i=0; i<p->nExpr; i++){
294 heightOfExpr(p->a[i].pExpr, pnHeight);
295 }
296 }
297}
298static void heightOfSelect(Select *p, int *pnHeight){
299 if( p ){
300 heightOfExpr(p->pWhere, pnHeight);
301 heightOfExpr(p->pHaving, pnHeight);
302 heightOfExpr(p->pLimit, pnHeight);
303 heightOfExpr(p->pOffset, pnHeight);
304 heightOfExprList(p->pEList, pnHeight);
305 heightOfExprList(p->pGroupBy, pnHeight);
306 heightOfExprList(p->pOrderBy, pnHeight);
307 heightOfSelect(p->pPrior, pnHeight);
308 }
309}
310
311/*
312** Set the Expr.nHeight variable in the structure passed as an
313** argument. An expression with no children, Expr.pList or
314** Expr.pSelect member has a height of 1. Any other expression
315** has a height equal to the maximum height of any other
316** referenced Expr plus one.
317*/
318static void exprSetHeight(Expr *p){
319 int nHeight = 0;
320 heightOfExpr(p->pLeft, &nHeight);
321 heightOfExpr(p->pRight, &nHeight);
322 heightOfExprList(p->pList, &nHeight);
323 heightOfSelect(p->pSelect, &nHeight);
324 p->nHeight = nHeight + 1;
325}
326
327/*
328** Set the Expr.nHeight variable using the exprSetHeight() function. If
329** the height is greater than the maximum allowed expression depth,
330** leave an error in pParse.
331*/
332void sqlite3ExprSetHeight(Parse *pParse, Expr *p){
333 exprSetHeight(p);
334 checkExprHeight(pParse, p->nHeight);
335}
336
337/*
338** Return the maximum height of any expression tree referenced
339** by the select statement passed as an argument.
340*/
341int sqlite3SelectExprHeight(Select *p){
342 int nHeight = 0;
343 heightOfSelect(p, &nHeight);
344 return nHeight;
345}
346#else
347 #define checkExprHeight(x,y)
348 #define exprSetHeight(y)
349#endif /* SQLITE_MAX_EXPR_DEPTH>0 */
350
drhbe5c89a2004-07-26 00:31:09 +0000351/*
drha76b5df2002-02-23 02:32:10 +0000352** Construct a new expression node and return a pointer to it. Memory
drh17435752007-08-16 04:30:38 +0000353** for this node is obtained from sqlite3_malloc(). The calling function
drha76b5df2002-02-23 02:32:10 +0000354** is responsible for making sure the node eventually gets freed.
355*/
drh17435752007-08-16 04:30:38 +0000356Expr *sqlite3Expr(
danielk1977a1644fd2007-08-29 12:31:25 +0000357 sqlite3 *db, /* Handle for sqlite3DbMallocZero() (may be null) */
drh17435752007-08-16 04:30:38 +0000358 int op, /* Expression opcode */
359 Expr *pLeft, /* Left operand */
360 Expr *pRight, /* Right operand */
361 const Token *pToken /* Argument token */
362){
drha76b5df2002-02-23 02:32:10 +0000363 Expr *pNew;
drh26e4a8b2008-05-01 17:16:52 +0000364 pNew = sqlite3DbMallocZero(db, sizeof(Expr));
drha76b5df2002-02-23 02:32:10 +0000365 if( pNew==0 ){
danielk1977d5d56522005-03-16 12:15:20 +0000366 /* When malloc fails, delete pLeft and pRight. Expressions passed to
367 ** this function must always be allocated with sqlite3Expr() for this
368 ** reason.
369 */
370 sqlite3ExprDelete(pLeft);
371 sqlite3ExprDelete(pRight);
drha76b5df2002-02-23 02:32:10 +0000372 return 0;
373 }
374 pNew->op = op;
375 pNew->pLeft = pLeft;
376 pNew->pRight = pRight;
danielk1977a58fdfb2005-02-08 07:50:40 +0000377 pNew->iAgg = -1;
drha76b5df2002-02-23 02:32:10 +0000378 if( pToken ){
drh4b59ab52002-08-24 18:24:51 +0000379 assert( pToken->dyn==0 );
drh145716b2004-09-24 12:24:06 +0000380 pNew->span = pNew->token = *pToken;
drha34001c2007-02-02 12:44:37 +0000381 }else if( pLeft ){
382 if( pRight ){
383 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
drh5ffb3ac2007-04-18 17:07:57 +0000384 if( pRight->flags & EP_ExpCollate ){
drha34001c2007-02-02 12:44:37 +0000385 pNew->flags |= EP_ExpCollate;
386 pNew->pColl = pRight->pColl;
387 }
388 }
drh5ffb3ac2007-04-18 17:07:57 +0000389 if( pLeft->flags & EP_ExpCollate ){
drha34001c2007-02-02 12:44:37 +0000390 pNew->flags |= EP_ExpCollate;
391 pNew->pColl = pLeft->pColl;
392 }
drha76b5df2002-02-23 02:32:10 +0000393 }
danielk1977fc976062007-05-10 10:46:56 +0000394
danielk19774b5255a2008-06-05 16:47:39 +0000395 exprSetHeight(pNew);
drha76b5df2002-02-23 02:32:10 +0000396 return pNew;
397}
398
399/*
drh17435752007-08-16 04:30:38 +0000400** Works like sqlite3Expr() except that it takes an extra Parse*
401** argument and notifies the associated connection object if malloc fails.
drh206f3d92006-07-11 13:15:08 +0000402*/
drh17435752007-08-16 04:30:38 +0000403Expr *sqlite3PExpr(
404 Parse *pParse, /* Parsing context */
405 int op, /* Expression opcode */
406 Expr *pLeft, /* Left operand */
407 Expr *pRight, /* Right operand */
408 const Token *pToken /* Argument token */
409){
danielk19774b5255a2008-06-05 16:47:39 +0000410 Expr *p = sqlite3Expr(pParse->db, op, pLeft, pRight, pToken);
411 if( p ){
412 checkExprHeight(pParse, p->nHeight);
413 }
414 return p;
drh206f3d92006-07-11 13:15:08 +0000415}
416
417/*
drh4e0cff62004-11-05 05:10:28 +0000418** When doing a nested parse, you can include terms in an expression
drhb7654112008-01-12 12:48:07 +0000419** that look like this: #1 #2 ... These terms refer to registers
420** in the virtual machine. #N is the N-th register.
drh4e0cff62004-11-05 05:10:28 +0000421**
422** This routine is called by the parser to deal with on of those terms.
423** It immediately generates code to store the value in a memory location.
424** The returns an expression that will code to extract the value from
425** that memory location as needed.
426*/
427Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
428 Vdbe *v = pParse->pVdbe;
429 Expr *p;
drh4e0cff62004-11-05 05:10:28 +0000430 if( pParse->nested==0 ){
431 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
danielk1977a1644fd2007-08-29 12:31:25 +0000432 return sqlite3PExpr(pParse, TK_NULL, 0, 0, 0);
drh4e0cff62004-11-05 05:10:28 +0000433 }
drhbb7ac002005-08-12 22:58:53 +0000434 if( v==0 ) return 0;
danielk1977a1644fd2007-08-29 12:31:25 +0000435 p = sqlite3PExpr(pParse, TK_REGISTER, 0, 0, pToken);
drh73c42a12004-11-20 18:13:10 +0000436 if( p==0 ){
437 return 0; /* Malloc failed */
438 }
drhb7654112008-01-12 12:48:07 +0000439 p->iTable = atoi((char*)&pToken->z[1]);
drh4e0cff62004-11-05 05:10:28 +0000440 return p;
441}
442
443/*
drh91bb0ee2004-09-01 03:06:34 +0000444** Join two expressions using an AND operator. If either expression is
445** NULL, then just return the other expression.
446*/
danielk19771e536952007-08-16 10:09:01 +0000447Expr *sqlite3ExprAnd(sqlite3 *db, Expr *pLeft, Expr *pRight){
drh91bb0ee2004-09-01 03:06:34 +0000448 if( pLeft==0 ){
449 return pRight;
450 }else if( pRight==0 ){
451 return pLeft;
452 }else{
danielk1977880c15b2007-09-01 18:24:55 +0000453 return sqlite3Expr(db, TK_AND, pLeft, pRight, 0);
drh91bb0ee2004-09-01 03:06:34 +0000454 }
455}
456
457/*
drh6977fea2002-10-22 23:38:04 +0000458** Set the Expr.span field of the given expression to span all
drha76b5df2002-02-23 02:32:10 +0000459** text between the two given tokens.
460*/
danielk19774adee202004-05-08 08:23:19 +0000461void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
drh4efc4752004-01-16 15:55:37 +0000462 assert( pRight!=0 );
463 assert( pLeft!=0 );
drhf3a65f72007-08-22 20:18:21 +0000464 if( pExpr && pRight->z && pLeft->z ){
drhad6d9462004-09-19 02:15:24 +0000465 assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
drh145716b2004-09-24 12:24:06 +0000466 if( pLeft->dyn==0 && pRight->dyn==0 ){
drh6977fea2002-10-22 23:38:04 +0000467 pExpr->span.z = pLeft->z;
drh97903fe2005-05-24 20:19:57 +0000468 pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
drh4b59ab52002-08-24 18:24:51 +0000469 }else{
drh6977fea2002-10-22 23:38:04 +0000470 pExpr->span.z = 0;
drh4b59ab52002-08-24 18:24:51 +0000471 }
drha76b5df2002-02-23 02:32:10 +0000472 }
473}
474
475/*
476** Construct a new expression node for a function with multiple
477** arguments.
478*/
drh17435752007-08-16 04:30:38 +0000479Expr *sqlite3ExprFunction(Parse *pParse, ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000480 Expr *pNew;
danielk19774b202ae2006-01-23 05:50:58 +0000481 assert( pToken );
drh17435752007-08-16 04:30:38 +0000482 pNew = sqlite3DbMallocZero(pParse->db, sizeof(Expr) );
drha76b5df2002-02-23 02:32:10 +0000483 if( pNew==0 ){
danielk1977d5d56522005-03-16 12:15:20 +0000484 sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000485 return 0;
486 }
487 pNew->op = TK_FUNCTION;
488 pNew->pList = pList;
danielk19774b202ae2006-01-23 05:50:58 +0000489 assert( pToken->dyn==0 );
490 pNew->token = *pToken;
drh6977fea2002-10-22 23:38:04 +0000491 pNew->span = pNew->token;
danielk1977fc976062007-05-10 10:46:56 +0000492
danielk19774b5255a2008-06-05 16:47:39 +0000493 sqlite3ExprSetHeight(pParse, pNew);
drha76b5df2002-02-23 02:32:10 +0000494 return pNew;
495}
496
497/*
drhfa6bc002004-09-07 16:19:52 +0000498** Assign a variable number to an expression that encodes a wildcard
499** in the original SQL statement.
500**
501** Wildcards consisting of a single "?" are assigned the next sequential
502** variable number.
503**
504** Wildcards of the form "?nnn" are assigned the number "nnn". We make
505** sure "nnn" is not too be to avoid a denial of service attack when
506** the SQL statement comes from an external source.
507**
508** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
509** as the previous instance of the same wildcard. Or if this is the first
510** instance of the wildcard, the next sequenial variable number is
511** assigned.
512*/
513void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
514 Token *pToken;
drh17435752007-08-16 04:30:38 +0000515 sqlite3 *db = pParse->db;
516
drhfa6bc002004-09-07 16:19:52 +0000517 if( pExpr==0 ) return;
518 pToken = &pExpr->token;
519 assert( pToken->n>=1 );
520 assert( pToken->z!=0 );
521 assert( pToken->z[0]!=0 );
522 if( pToken->n==1 ){
523 /* Wildcard of the form "?". Assign the next variable number */
524 pExpr->iTable = ++pParse->nVar;
525 }else if( pToken->z[0]=='?' ){
526 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
527 ** use it as the variable number */
528 int i;
drh2646da72005-12-09 20:02:05 +0000529 pExpr->iTable = i = atoi((char*)&pToken->z[1]);
drhc5499be2008-04-01 15:06:33 +0000530 testcase( i==0 );
531 testcase( i==1 );
532 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]-1 );
533 testcase( i==db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] );
drhbb4957f2008-03-20 14:03:29 +0000534 if( i<1 || i>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
drhfa6bc002004-09-07 16:19:52 +0000535 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
drhbb4957f2008-03-20 14:03:29 +0000536 db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER]);
drhfa6bc002004-09-07 16:19:52 +0000537 }
538 if( i>pParse->nVar ){
539 pParse->nVar = i;
540 }
541 }else{
542 /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
543 ** number as the prior appearance of the same name, or if the name
544 ** has never appeared before, reuse the same variable number
545 */
546 int i, n;
547 n = pToken->n;
548 for(i=0; i<pParse->nVarExpr; i++){
549 Expr *pE;
550 if( (pE = pParse->apVarExpr[i])!=0
551 && pE->token.n==n
552 && memcmp(pE->token.z, pToken->z, n)==0 ){
553 pExpr->iTable = pE->iTable;
554 break;
555 }
556 }
557 if( i>=pParse->nVarExpr ){
558 pExpr->iTable = ++pParse->nVar;
559 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
560 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
drh17435752007-08-16 04:30:38 +0000561 pParse->apVarExpr =
562 sqlite3DbReallocOrFree(
563 db,
564 pParse->apVarExpr,
565 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0])
566 );
drhfa6bc002004-09-07 16:19:52 +0000567 }
drh17435752007-08-16 04:30:38 +0000568 if( !db->mallocFailed ){
drhfa6bc002004-09-07 16:19:52 +0000569 assert( pParse->apVarExpr!=0 );
570 pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
571 }
572 }
573 }
drhbb4957f2008-03-20 14:03:29 +0000574 if( !pParse->nErr && pParse->nVar>db->aLimit[SQLITE_LIMIT_VARIABLE_NUMBER] ){
danielk1977832b2662007-05-09 11:37:22 +0000575 sqlite3ErrorMsg(pParse, "too many SQL variables");
576 }
drhfa6bc002004-09-07 16:19:52 +0000577}
578
579/*
drha2e00042002-01-22 03:13:42 +0000580** Recursively delete an expression tree.
581*/
danielk19774adee202004-05-08 08:23:19 +0000582void sqlite3ExprDelete(Expr *p){
drha2e00042002-01-22 03:13:42 +0000583 if( p==0 ) return;
drh17435752007-08-16 04:30:38 +0000584 if( p->span.dyn ) sqlite3_free((char*)p->span.z);
585 if( p->token.dyn ) sqlite3_free((char*)p->token.z);
danielk19774adee202004-05-08 08:23:19 +0000586 sqlite3ExprDelete(p->pLeft);
587 sqlite3ExprDelete(p->pRight);
588 sqlite3ExprListDelete(p->pList);
589 sqlite3SelectDelete(p->pSelect);
drh17435752007-08-16 04:30:38 +0000590 sqlite3_free(p);
drha2e00042002-01-22 03:13:42 +0000591}
592
drhd2687b72005-08-12 22:56:09 +0000593/*
594** The Expr.token field might be a string literal that is quoted.
595** If so, remove the quotation marks.
596*/
drh17435752007-08-16 04:30:38 +0000597void sqlite3DequoteExpr(sqlite3 *db, Expr *p){
drhd2687b72005-08-12 22:56:09 +0000598 if( ExprHasAnyProperty(p, EP_Dequoted) ){
599 return;
600 }
601 ExprSetProperty(p, EP_Dequoted);
602 if( p->token.dyn==0 ){
drh17435752007-08-16 04:30:38 +0000603 sqlite3TokenCopy(db, &p->token, &p->token);
drhd2687b72005-08-12 22:56:09 +0000604 }
605 sqlite3Dequote((char*)p->token.z);
606}
607
drha76b5df2002-02-23 02:32:10 +0000608
609/*
drhff78bd22002-02-27 01:47:11 +0000610** The following group of routines make deep copies of expressions,
611** expression lists, ID lists, and select statements. The copies can
612** be deleted (by being passed to their respective ...Delete() routines)
613** without effecting the originals.
614**
danielk19774adee202004-05-08 08:23:19 +0000615** The expression list, ID, and source lists return by sqlite3ExprListDup(),
616** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +0000617** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +0000618**
drhad3cab52002-05-24 02:04:32 +0000619** Any tables that the SrcList might point to are not duplicated.
drhff78bd22002-02-27 01:47:11 +0000620*/
danielk19771e536952007-08-16 10:09:01 +0000621Expr *sqlite3ExprDup(sqlite3 *db, Expr *p){
drhff78bd22002-02-27 01:47:11 +0000622 Expr *pNew;
623 if( p==0 ) return 0;
drh17435752007-08-16 04:30:38 +0000624 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +0000625 if( pNew==0 ) return 0;
drh3b167c72002-06-28 12:18:47 +0000626 memcpy(pNew, p, sizeof(*pNew));
drh6977fea2002-10-22 23:38:04 +0000627 if( p->token.z!=0 ){
drh17435752007-08-16 04:30:38 +0000628 pNew->token.z = (u8*)sqlite3DbStrNDup(db, (char*)p->token.z, p->token.n);
drh4b59ab52002-08-24 18:24:51 +0000629 pNew->token.dyn = 1;
630 }else{
drh4efc4752004-01-16 15:55:37 +0000631 assert( pNew->token.z==0 );
drh4b59ab52002-08-24 18:24:51 +0000632 }
drh6977fea2002-10-22 23:38:04 +0000633 pNew->span.z = 0;
drh17435752007-08-16 04:30:38 +0000634 pNew->pLeft = sqlite3ExprDup(db, p->pLeft);
635 pNew->pRight = sqlite3ExprDup(db, p->pRight);
636 pNew->pList = sqlite3ExprListDup(db, p->pList);
637 pNew->pSelect = sqlite3SelectDup(db, p->pSelect);
drhff78bd22002-02-27 01:47:11 +0000638 return pNew;
639}
drh17435752007-08-16 04:30:38 +0000640void sqlite3TokenCopy(sqlite3 *db, Token *pTo, Token *pFrom){
641 if( pTo->dyn ) sqlite3_free((char*)pTo->z);
drh4b59ab52002-08-24 18:24:51 +0000642 if( pFrom->z ){
643 pTo->n = pFrom->n;
drh17435752007-08-16 04:30:38 +0000644 pTo->z = (u8*)sqlite3DbStrNDup(db, (char*)pFrom->z, pFrom->n);
drh4b59ab52002-08-24 18:24:51 +0000645 pTo->dyn = 1;
646 }else{
drh4b59ab52002-08-24 18:24:51 +0000647 pTo->z = 0;
drh4b59ab52002-08-24 18:24:51 +0000648 }
649}
drh17435752007-08-16 04:30:38 +0000650ExprList *sqlite3ExprListDup(sqlite3 *db, ExprList *p){
drhff78bd22002-02-27 01:47:11 +0000651 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +0000652 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +0000653 int i;
654 if( p==0 ) return 0;
drh17435752007-08-16 04:30:38 +0000655 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +0000656 if( pNew==0 ) return 0;
danielk197731dad9d2007-08-16 11:36:15 +0000657 pNew->iECursor = 0;
drh4305d102003-07-30 12:34:12 +0000658 pNew->nExpr = pNew->nAlloc = p->nExpr;
drh17435752007-08-16 04:30:38 +0000659 pNew->a = pItem = sqlite3DbMallocRaw(db, p->nExpr*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +0000660 if( pItem==0 ){
drh17435752007-08-16 04:30:38 +0000661 sqlite3_free(pNew);
danielk1977e0048402004-06-15 16:51:01 +0000662 return 0;
663 }
drh145716b2004-09-24 12:24:06 +0000664 pOldItem = p->a;
665 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
drh4b59ab52002-08-24 18:24:51 +0000666 Expr *pNewExpr, *pOldExpr;
drh17435752007-08-16 04:30:38 +0000667 pItem->pExpr = pNewExpr = sqlite3ExprDup(db, pOldExpr = pOldItem->pExpr);
drh6977fea2002-10-22 23:38:04 +0000668 if( pOldExpr->span.z!=0 && pNewExpr ){
669 /* Always make a copy of the span for top-level expressions in the
drh4b59ab52002-08-24 18:24:51 +0000670 ** expression list. The logic in SELECT processing that determines
671 ** the names of columns in the result set needs this information */
drh17435752007-08-16 04:30:38 +0000672 sqlite3TokenCopy(db, &pNewExpr->span, &pOldExpr->span);
drh4b59ab52002-08-24 18:24:51 +0000673 }
drh1f3e9052002-10-31 00:09:39 +0000674 assert( pNewExpr==0 || pNewExpr->span.z!=0
drh6f7adc82006-01-11 21:41:20 +0000675 || pOldExpr->span.z==0
drh17435752007-08-16 04:30:38 +0000676 || db->mallocFailed );
677 pItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh145716b2004-09-24 12:24:06 +0000678 pItem->sortOrder = pOldItem->sortOrder;
679 pItem->isAgg = pOldItem->isAgg;
drh3e7bc9c2004-02-21 19:17:17 +0000680 pItem->done = 0;
drhff78bd22002-02-27 01:47:11 +0000681 }
682 return pNew;
683}
danielk197793758c82005-01-21 08:13:14 +0000684
685/*
686** If cursors, triggers, views and subqueries are all omitted from
687** the build, then none of the following routines, except for
688** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
689** called with a NULL argument.
690*/
danielk19776a67fe82005-02-04 04:07:16 +0000691#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
692 || !defined(SQLITE_OMIT_SUBQUERY)
drh17435752007-08-16 04:30:38 +0000693SrcList *sqlite3SrcListDup(sqlite3 *db, SrcList *p){
drhad3cab52002-05-24 02:04:32 +0000694 SrcList *pNew;
695 int i;
drh113088e2003-03-20 01:16:58 +0000696 int nByte;
drhad3cab52002-05-24 02:04:32 +0000697 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +0000698 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh17435752007-08-16 04:30:38 +0000699 pNew = sqlite3DbMallocRaw(db, nByte );
drhad3cab52002-05-24 02:04:32 +0000700 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +0000701 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +0000702 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +0000703 struct SrcList_item *pNewItem = &pNew->a[i];
704 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +0000705 Table *pTab;
drh17435752007-08-16 04:30:38 +0000706 pNewItem->zDatabase = sqlite3DbStrDup(db, pOldItem->zDatabase);
707 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
708 pNewItem->zAlias = sqlite3DbStrDup(db, pOldItem->zAlias);
drh4efc4752004-01-16 15:55:37 +0000709 pNewItem->jointype = pOldItem->jointype;
710 pNewItem->iCursor = pOldItem->iCursor;
danielk19771787cca2006-02-10 07:07:14 +0000711 pNewItem->isPopulated = pOldItem->isPopulated;
drhed8a3bb2005-06-06 21:19:56 +0000712 pTab = pNewItem->pTab = pOldItem->pTab;
713 if( pTab ){
714 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +0000715 }
drh17435752007-08-16 04:30:38 +0000716 pNewItem->pSelect = sqlite3SelectDup(db, pOldItem->pSelect);
717 pNewItem->pOn = sqlite3ExprDup(db, pOldItem->pOn);
718 pNewItem->pUsing = sqlite3IdListDup(db, pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +0000719 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +0000720 }
721 return pNew;
722}
drh17435752007-08-16 04:30:38 +0000723IdList *sqlite3IdListDup(sqlite3 *db, IdList *p){
drhff78bd22002-02-27 01:47:11 +0000724 IdList *pNew;
725 int i;
726 if( p==0 ) return 0;
drh17435752007-08-16 04:30:38 +0000727 pNew = sqlite3DbMallocRaw(db, sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +0000728 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +0000729 pNew->nId = pNew->nAlloc = p->nId;
drh17435752007-08-16 04:30:38 +0000730 pNew->a = sqlite3DbMallocRaw(db, p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +0000731 if( pNew->a==0 ){
drh17435752007-08-16 04:30:38 +0000732 sqlite3_free(pNew);
danielk1977d5d56522005-03-16 12:15:20 +0000733 return 0;
734 }
drhff78bd22002-02-27 01:47:11 +0000735 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +0000736 struct IdList_item *pNewItem = &pNew->a[i];
737 struct IdList_item *pOldItem = &p->a[i];
drh17435752007-08-16 04:30:38 +0000738 pNewItem->zName = sqlite3DbStrDup(db, pOldItem->zName);
drh4efc4752004-01-16 15:55:37 +0000739 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +0000740 }
741 return pNew;
742}
drh17435752007-08-16 04:30:38 +0000743Select *sqlite3SelectDup(sqlite3 *db, Select *p){
drhff78bd22002-02-27 01:47:11 +0000744 Select *pNew;
745 if( p==0 ) return 0;
drh17435752007-08-16 04:30:38 +0000746 pNew = sqlite3DbMallocRaw(db, sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +0000747 if( pNew==0 ) return 0;
748 pNew->isDistinct = p->isDistinct;
drh17435752007-08-16 04:30:38 +0000749 pNew->pEList = sqlite3ExprListDup(db, p->pEList);
750 pNew->pSrc = sqlite3SrcListDup(db, p->pSrc);
751 pNew->pWhere = sqlite3ExprDup(db, p->pWhere);
752 pNew->pGroupBy = sqlite3ExprListDup(db, p->pGroupBy);
753 pNew->pHaving = sqlite3ExprDup(db, p->pHaving);
754 pNew->pOrderBy = sqlite3ExprListDup(db, p->pOrderBy);
drhff78bd22002-02-27 01:47:11 +0000755 pNew->op = p->op;
drh17435752007-08-16 04:30:38 +0000756 pNew->pPrior = sqlite3SelectDup(db, p->pPrior);
757 pNew->pLimit = sqlite3ExprDup(db, p->pLimit);
758 pNew->pOffset = sqlite3ExprDup(db, p->pOffset);
drh7b58dae2003-07-20 01:16:46 +0000759 pNew->iLimit = -1;
760 pNew->iOffset = -1;
danielk1977a1cb1832005-02-12 08:59:55 +0000761 pNew->isResolved = p->isResolved;
762 pNew->isAgg = p->isAgg;
drhb9bb7c12006-06-11 23:41:55 +0000763 pNew->usesEphm = 0;
drh8e647b82005-09-23 21:11:53 +0000764 pNew->disallowOrderBy = 0;
drh0342b1f2005-09-01 03:07:44 +0000765 pNew->pRightmost = 0;
drhb9bb7c12006-06-11 23:41:55 +0000766 pNew->addrOpenEphm[0] = -1;
767 pNew->addrOpenEphm[1] = -1;
768 pNew->addrOpenEphm[2] = -1;
drhff78bd22002-02-27 01:47:11 +0000769 return pNew;
770}
danielk197793758c82005-01-21 08:13:14 +0000771#else
drh17435752007-08-16 04:30:38 +0000772Select *sqlite3SelectDup(sqlite3 *db, Select *p){
danielk197793758c82005-01-21 08:13:14 +0000773 assert( p==0 );
774 return 0;
775}
776#endif
drhff78bd22002-02-27 01:47:11 +0000777
778
779/*
drha76b5df2002-02-23 02:32:10 +0000780** Add a new element to the end of an expression list. If pList is
781** initially NULL, then create a new expression list.
782*/
drh17435752007-08-16 04:30:38 +0000783ExprList *sqlite3ExprListAppend(
784 Parse *pParse, /* Parsing context */
785 ExprList *pList, /* List to which to append. Might be NULL */
786 Expr *pExpr, /* Expression to be appended */
787 Token *pName /* AS keyword for the expression */
788){
789 sqlite3 *db = pParse->db;
drha76b5df2002-02-23 02:32:10 +0000790 if( pList==0 ){
drh17435752007-08-16 04:30:38 +0000791 pList = sqlite3DbMallocZero(db, sizeof(ExprList) );
drha76b5df2002-02-23 02:32:10 +0000792 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +0000793 goto no_mem;
drha76b5df2002-02-23 02:32:10 +0000794 }
drh4efc4752004-01-16 15:55:37 +0000795 assert( pList->nAlloc==0 );
drha76b5df2002-02-23 02:32:10 +0000796 }
drh4305d102003-07-30 12:34:12 +0000797 if( pList->nAlloc<=pList->nExpr ){
danielk1977d5d56522005-03-16 12:15:20 +0000798 struct ExprList_item *a;
799 int n = pList->nAlloc*2 + 4;
danielk197726783a52007-08-29 14:06:22 +0000800 a = sqlite3DbRealloc(db, pList->a, n*sizeof(pList->a[0]));
danielk1977d5d56522005-03-16 12:15:20 +0000801 if( a==0 ){
802 goto no_mem;
drha76b5df2002-02-23 02:32:10 +0000803 }
danielk1977d5d56522005-03-16 12:15:20 +0000804 pList->a = a;
805 pList->nAlloc = n;
drha76b5df2002-02-23 02:32:10 +0000806 }
drh4efc4752004-01-16 15:55:37 +0000807 assert( pList->a!=0 );
808 if( pExpr || pName ){
809 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
810 memset(pItem, 0, sizeof(*pItem));
drh17435752007-08-16 04:30:38 +0000811 pItem->zName = sqlite3NameFromToken(db, pName);
danielk1977e94ddc92005-03-21 03:53:38 +0000812 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +0000813 }
814 return pList;
danielk1977d5d56522005-03-16 12:15:20 +0000815
816no_mem:
817 /* Avoid leaking memory if malloc has failed. */
818 sqlite3ExprDelete(pExpr);
819 sqlite3ExprListDelete(pList);
820 return 0;
drha76b5df2002-02-23 02:32:10 +0000821}
822
823/*
danielk19777a15a4b2007-05-08 17:54:43 +0000824** If the expression list pEList contains more than iLimit elements,
825** leave an error message in pParse.
826*/
827void sqlite3ExprListCheckLength(
828 Parse *pParse,
829 ExprList *pEList,
danielk19777a15a4b2007-05-08 17:54:43 +0000830 const char *zObject
831){
drhb1a6c3c2008-03-20 16:30:17 +0000832 int mx = pParse->db->aLimit[SQLITE_LIMIT_COLUMN];
drhc5499be2008-04-01 15:06:33 +0000833 testcase( pEList && pEList->nExpr==mx );
834 testcase( pEList && pEList->nExpr==mx+1 );
drhb1a6c3c2008-03-20 16:30:17 +0000835 if( pEList && pEList->nExpr>mx ){
danielk19777a15a4b2007-05-08 17:54:43 +0000836 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
837 }
838}
839
840/*
drha76b5df2002-02-23 02:32:10 +0000841** Delete an entire expression list.
842*/
danielk19774adee202004-05-08 08:23:19 +0000843void sqlite3ExprListDelete(ExprList *pList){
drha76b5df2002-02-23 02:32:10 +0000844 int i;
drhbe5c89a2004-07-26 00:31:09 +0000845 struct ExprList_item *pItem;
drha76b5df2002-02-23 02:32:10 +0000846 if( pList==0 ) return;
drh1bdd9b52004-04-23 17:04:44 +0000847 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
848 assert( pList->nExpr<=pList->nAlloc );
drhbe5c89a2004-07-26 00:31:09 +0000849 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
850 sqlite3ExprDelete(pItem->pExpr);
drh17435752007-08-16 04:30:38 +0000851 sqlite3_free(pItem->zName);
drha76b5df2002-02-23 02:32:10 +0000852 }
drh17435752007-08-16 04:30:38 +0000853 sqlite3_free(pList->a);
854 sqlite3_free(pList);
drha76b5df2002-02-23 02:32:10 +0000855}
856
857/*
drh678ccce2008-03-31 18:19:54 +0000858** Walk an expression tree. Call xFunc for each node visited. xFunc
859** is called on the node before xFunc is called on the nodes children.
drh73b211a2005-01-18 04:00:42 +0000860**
drh626a8792005-01-17 22:08:19 +0000861** The return value from xFunc determines whether the tree walk continues.
862** 0 means continue walking the tree. 1 means do not walk children
863** of the current node but continue with siblings. 2 means abandon
864** the tree walk completely.
865**
866** The return value from this routine is 1 to abandon the tree walk
867** and 0 to continue.
drh87abf5c2005-08-25 12:45:04 +0000868**
869** NOTICE: This routine does *not* descend into subqueries.
drh626a8792005-01-17 22:08:19 +0000870*/
danielk1977a58fdfb2005-02-08 07:50:40 +0000871static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
drh626a8792005-01-17 22:08:19 +0000872static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
drh626a8792005-01-17 22:08:19 +0000873 int rc;
874 if( pExpr==0 ) return 0;
875 rc = (*xFunc)(pArg, pExpr);
876 if( rc==0 ){
877 if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
878 if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
danielk1977a58fdfb2005-02-08 07:50:40 +0000879 if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
drh626a8792005-01-17 22:08:19 +0000880 }
881 return rc>1;
882}
883
884/*
danielk1977a58fdfb2005-02-08 07:50:40 +0000885** Call walkExprTree() for every expression in list p.
886*/
887static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
888 int i;
889 struct ExprList_item *pItem;
890 if( !p ) return 0;
891 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
892 if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
893 }
894 return 0;
895}
896
897/*
898** Call walkExprTree() for every expression in Select p, not including
899** expressions that are part of sub-selects in any FROM clause or the LIMIT
900** or OFFSET expressions..
901*/
902static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
903 walkExprList(p->pEList, xFunc, pArg);
904 walkExprTree(p->pWhere, xFunc, pArg);
905 walkExprList(p->pGroupBy, xFunc, pArg);
906 walkExprTree(p->pHaving, xFunc, pArg);
907 walkExprList(p->pOrderBy, xFunc, pArg);
danielk197715d79822007-05-15 07:00:34 +0000908 if( p->pPrior ){
909 walkSelectExpr(p->pPrior, xFunc, pArg);
910 }
danielk1977a58fdfb2005-02-08 07:50:40 +0000911 return 0;
912}
913
914
915/*
drh626a8792005-01-17 22:08:19 +0000916** This routine is designed as an xFunc for walkExprTree().
917**
918** pArg is really a pointer to an integer. If we can tell by looking
drh73b211a2005-01-18 04:00:42 +0000919** at pExpr that the expression that contains pExpr is not a constant
920** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
921** If pExpr does does not disqualify the expression from being a constant
922** then do nothing.
923**
924** After walking the whole tree, if no nodes are found that disqualify
925** the expression as constant, then we assume the whole expression
926** is constant. See sqlite3ExprIsConstant() for additional information.
drh626a8792005-01-17 22:08:19 +0000927*/
928static int exprNodeIsConstant(void *pArg, Expr *pExpr){
drh0a168372007-06-08 00:20:47 +0000929 int *pN = (int*)pArg;
930
931 /* If *pArg is 3 then any term of the expression that comes from
932 ** the ON or USING clauses of a join disqualifies the expression
933 ** from being considered constant. */
934 if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
935 *pN = 0;
936 return 2;
937 }
938
drh626a8792005-01-17 22:08:19 +0000939 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +0000940 /* Consider functions to be constant if all their arguments are constant
941 ** and *pArg==2 */
942 case TK_FUNCTION:
drh0a168372007-06-08 00:20:47 +0000943 if( (*pN)==2 ) return 0;
drheb55bd22005-06-30 17:04:21 +0000944 /* Fall through */
drh626a8792005-01-17 22:08:19 +0000945 case TK_ID:
946 case TK_COLUMN:
947 case TK_DOT:
948 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +0000949 case TK_AGG_COLUMN:
drhfe2093d2005-01-20 22:48:47 +0000950#ifndef SQLITE_OMIT_SUBQUERY
951 case TK_SELECT:
952 case TK_EXISTS:
drhc5499be2008-04-01 15:06:33 +0000953 testcase( pExpr->op==TK_SELECT );
954 testcase( pExpr->op==TK_EXISTS );
drhfe2093d2005-01-20 22:48:47 +0000955#endif
drhc5499be2008-04-01 15:06:33 +0000956 testcase( pExpr->op==TK_ID );
957 testcase( pExpr->op==TK_COLUMN );
958 testcase( pExpr->op==TK_DOT );
959 testcase( pExpr->op==TK_AGG_FUNCTION );
960 testcase( pExpr->op==TK_AGG_COLUMN );
drh0a168372007-06-08 00:20:47 +0000961 *pN = 0;
drh626a8792005-01-17 22:08:19 +0000962 return 2;
drh87abf5c2005-08-25 12:45:04 +0000963 case TK_IN:
964 if( pExpr->pSelect ){
drh0a168372007-06-08 00:20:47 +0000965 *pN = 0;
drh87abf5c2005-08-25 12:45:04 +0000966 return 2;
967 }
drh626a8792005-01-17 22:08:19 +0000968 default:
969 return 0;
970 }
971}
972
973/*
drhfef52082000-06-06 01:50:43 +0000974** Walk an expression tree. Return 1 if the expression is constant
drheb55bd22005-06-30 17:04:21 +0000975** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +0000976**
977** For the purposes of this function, a double-quoted string (ex: "abc")
978** is considered a variable but a single-quoted string (ex: 'abc') is
979** a constant.
drhfef52082000-06-06 01:50:43 +0000980*/
danielk19774adee202004-05-08 08:23:19 +0000981int sqlite3ExprIsConstant(Expr *p){
drh626a8792005-01-17 22:08:19 +0000982 int isConst = 1;
983 walkExprTree(p, exprNodeIsConstant, &isConst);
984 return isConst;
drhfef52082000-06-06 01:50:43 +0000985}
986
987/*
drheb55bd22005-06-30 17:04:21 +0000988** Walk an expression tree. Return 1 if the expression is constant
drh0a168372007-06-08 00:20:47 +0000989** that does no originate from the ON or USING clauses of a join.
990** Return 0 if it involves variables or function calls or terms from
991** an ON or USING clause.
992*/
993int sqlite3ExprIsConstantNotJoin(Expr *p){
994 int isConst = 3;
995 walkExprTree(p, exprNodeIsConstant, &isConst);
996 return isConst!=0;
997}
998
999/*
1000** Walk an expression tree. Return 1 if the expression is constant
drheb55bd22005-06-30 17:04:21 +00001001** or a function call with constant arguments. Return and 0 if there
1002** are any variables.
1003**
1004** For the purposes of this function, a double-quoted string (ex: "abc")
1005** is considered a variable but a single-quoted string (ex: 'abc') is
1006** a constant.
1007*/
1008int sqlite3ExprIsConstantOrFunction(Expr *p){
1009 int isConst = 2;
1010 walkExprTree(p, exprNodeIsConstant, &isConst);
1011 return isConst!=0;
1012}
1013
1014/*
drh73b211a2005-01-18 04:00:42 +00001015** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +00001016** to fit in a 32-bit integer, return 1 and put the value of the integer
1017** in *pValue. If the expression is not an integer or if it is too big
1018** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +00001019*/
danielk19774adee202004-05-08 08:23:19 +00001020int sqlite3ExprIsInteger(Expr *p, int *pValue){
drhe4de1fe2002-06-02 16:09:01 +00001021 switch( p->op ){
1022 case TK_INTEGER: {
drh2646da72005-12-09 20:02:05 +00001023 if( sqlite3GetInt32((char*)p->token.z, pValue) ){
drh202b2df2004-01-06 01:13:46 +00001024 return 1;
1025 }
1026 break;
drhe4de1fe2002-06-02 16:09:01 +00001027 }
drh4b59ab52002-08-24 18:24:51 +00001028 case TK_UPLUS: {
danielk19774adee202004-05-08 08:23:19 +00001029 return sqlite3ExprIsInteger(p->pLeft, pValue);
drh4b59ab52002-08-24 18:24:51 +00001030 }
drhe4de1fe2002-06-02 16:09:01 +00001031 case TK_UMINUS: {
1032 int v;
danielk19774adee202004-05-08 08:23:19 +00001033 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
drhe4de1fe2002-06-02 16:09:01 +00001034 *pValue = -v;
1035 return 1;
1036 }
1037 break;
1038 }
1039 default: break;
1040 }
1041 return 0;
1042}
1043
1044/*
drhc4a3c772001-04-04 11:48:57 +00001045** Return TRUE if the given string is a row-id column name.
1046*/
danielk19774adee202004-05-08 08:23:19 +00001047int sqlite3IsRowid(const char *z){
1048 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
1049 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
1050 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +00001051 return 0;
1052}
1053
1054/*
drh8141f612004-01-25 22:44:58 +00001055** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
1056** that name in the set of source tables in pSrcList and make the pExpr
1057** expression node refer back to that source column. The following changes
1058** are made to pExpr:
1059**
1060** pExpr->iDb Set the index in db->aDb[] of the database holding
1061** the table.
1062** pExpr->iTable Set to the cursor number for the table obtained
1063** from pSrcList.
1064** pExpr->iColumn Set to the column number within the table.
drh8141f612004-01-25 22:44:58 +00001065** pExpr->op Set to TK_COLUMN.
1066** pExpr->pLeft Any expression this points to is deleted
1067** pExpr->pRight Any expression this points to is deleted.
1068**
1069** The pDbToken is the name of the database (the "X"). This value may be
1070** NULL meaning that name is of the form Y.Z or Z. Any available database
1071** can be used. The pTableToken is the name of the table (the "Y"). This
1072** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
1073** means that the form of the name is Z and that columns from any table
1074** can be used.
1075**
1076** If the name cannot be resolved unambiguously, leave an error message
1077** in pParse and return non-zero. Return zero on success.
1078*/
1079static int lookupName(
drhffe07b22005-11-03 00:41:17 +00001080 Parse *pParse, /* The parsing context */
drh8141f612004-01-25 22:44:58 +00001081 Token *pDbToken, /* Name of the database containing table, or NULL */
1082 Token *pTableToken, /* Name of table containing column, or NULL */
1083 Token *pColumnToken, /* Name of the column. */
drh626a8792005-01-17 22:08:19 +00001084 NameContext *pNC, /* The name context used to resolve the name */
drh8141f612004-01-25 22:44:58 +00001085 Expr *pExpr /* Make this EXPR node point to the selected column */
1086){
1087 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
1088 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
1089 char *zCol = 0; /* Name of the column. The "Z" */
1090 int i, j; /* Loop counters */
1091 int cnt = 0; /* Number of matching column names */
1092 int cntTab = 0; /* Number of matching table names */
drh626a8792005-01-17 22:08:19 +00001093 sqlite3 *db = pParse->db; /* The database */
drh51669862004-12-18 18:40:26 +00001094 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
1095 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
drh73b211a2005-01-18 04:00:42 +00001096 NameContext *pTopNC = pNC; /* First namecontext in the list */
drh728b5772007-09-18 15:55:07 +00001097 Schema *pSchema = 0; /* Schema of the expression */
drh8141f612004-01-25 22:44:58 +00001098
1099 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
drh17435752007-08-16 04:30:38 +00001100 zDb = sqlite3NameFromToken(db, pDbToken);
1101 zTab = sqlite3NameFromToken(db, pTableToken);
1102 zCol = sqlite3NameFromToken(db, pColumnToken);
1103 if( db->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +00001104 goto lookupname_end;
drh8141f612004-01-25 22:44:58 +00001105 }
drh8141f612004-01-25 22:44:58 +00001106
1107 pExpr->iTable = -1;
drh626a8792005-01-17 22:08:19 +00001108 while( pNC && cnt==0 ){
drhffe07b22005-11-03 00:41:17 +00001109 ExprList *pEList;
drh626a8792005-01-17 22:08:19 +00001110 SrcList *pSrcList = pNC->pSrcList;
drh8141f612004-01-25 22:44:58 +00001111
danielk1977b3bce662005-01-29 08:32:43 +00001112 if( pSrcList ){
1113 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
drh43617e92006-03-06 20:55:46 +00001114 Table *pTab;
1115 int iDb;
danielk1977b3bce662005-01-29 08:32:43 +00001116 Column *pCol;
1117
drh43617e92006-03-06 20:55:46 +00001118 pTab = pItem->pTab;
1119 assert( pTab!=0 );
1120 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977b3bce662005-01-29 08:32:43 +00001121 assert( pTab->nCol>0 );
1122 if( zTab ){
1123 if( pItem->zAlias ){
1124 char *zTabName = pItem->zAlias;
1125 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1126 }else{
1127 char *zTabName = pTab->zName;
1128 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
danielk1977da184232006-01-05 11:34:32 +00001129 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
danielk1977b3bce662005-01-29 08:32:43 +00001130 continue;
1131 }
drh626a8792005-01-17 22:08:19 +00001132 }
drh8141f612004-01-25 22:44:58 +00001133 }
danielk1977b3bce662005-01-29 08:32:43 +00001134 if( 0==(cntTab++) ){
drh626a8792005-01-17 22:08:19 +00001135 pExpr->iTable = pItem->iCursor;
drh728b5772007-09-18 15:55:07 +00001136 pSchema = pTab->pSchema;
danielk1977b3bce662005-01-29 08:32:43 +00001137 pMatch = pItem;
1138 }
1139 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
1140 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +00001141 const char *zColl = pTab->aCol[j].zColl;
drh873fac02005-06-06 17:11:46 +00001142 IdList *pUsing;
danielk1977b3bce662005-01-29 08:32:43 +00001143 cnt++;
1144 pExpr->iTable = pItem->iCursor;
1145 pMatch = pItem;
drh728b5772007-09-18 15:55:07 +00001146 pSchema = pTab->pSchema;
danielk1977b3bce662005-01-29 08:32:43 +00001147 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
1148 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1149 pExpr->affinity = pTab->aCol[j].affinity;
drh8b4c40d2007-02-01 23:02:45 +00001150 if( (pExpr->flags & EP_ExpCollate)==0 ){
1151 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1152 }
drh61dfc312006-12-16 16:25:15 +00001153 if( i<pSrcList->nSrc-1 ){
1154 if( pItem[1].jointype & JT_NATURAL ){
1155 /* If this match occurred in the left table of a natural join,
1156 ** then skip the right table to avoid a duplicate match */
1157 pItem++;
1158 i++;
1159 }else if( (pUsing = pItem[1].pUsing)!=0 ){
1160 /* If this match occurs on a column that is in the USING clause
1161 ** of a join, skip the search of the right table of the join
1162 ** to avoid a duplicate match there. */
1163 int k;
1164 for(k=0; k<pUsing->nId; k++){
1165 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1166 pItem++;
1167 i++;
1168 break;
1169 }
drh873fac02005-06-06 17:11:46 +00001170 }
1171 }
1172 }
danielk1977b3bce662005-01-29 08:32:43 +00001173 break;
1174 }
drh8141f612004-01-25 22:44:58 +00001175 }
1176 }
1177 }
drh626a8792005-01-17 22:08:19 +00001178
1179#ifndef SQLITE_OMIT_TRIGGER
1180 /* If we have not already resolved the name, then maybe
1181 ** it is a new.* or old.* trigger argument reference
1182 */
1183 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
1184 TriggerStack *pTriggerStack = pParse->trigStack;
1185 Table *pTab = 0;
danielk19778f2c54e2008-01-01 19:02:09 +00001186 u32 *piColMask;
drh626a8792005-01-17 22:08:19 +00001187 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
1188 pExpr->iTable = pTriggerStack->newIdx;
1189 assert( pTriggerStack->pTab );
1190 pTab = pTriggerStack->pTab;
danielk19778f2c54e2008-01-01 19:02:09 +00001191 piColMask = &(pTriggerStack->newColMask);
drh626a8792005-01-17 22:08:19 +00001192 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
1193 pExpr->iTable = pTriggerStack->oldIdx;
1194 assert( pTriggerStack->pTab );
1195 pTab = pTriggerStack->pTab;
danielk19778f2c54e2008-01-01 19:02:09 +00001196 piColMask = &(pTriggerStack->oldColMask);
drh626a8792005-01-17 22:08:19 +00001197 }
1198
1199 if( pTab ){
danielk1977f0113002006-01-24 12:09:17 +00001200 int iCol;
drh626a8792005-01-17 22:08:19 +00001201 Column *pCol = pTab->aCol;
1202
drh728b5772007-09-18 15:55:07 +00001203 pSchema = pTab->pSchema;
drh626a8792005-01-17 22:08:19 +00001204 cntTab++;
danielk1977f0113002006-01-24 12:09:17 +00001205 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
drh626a8792005-01-17 22:08:19 +00001206 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
danielk1977f0113002006-01-24 12:09:17 +00001207 const char *zColl = pTab->aCol[iCol].zColl;
drh626a8792005-01-17 22:08:19 +00001208 cnt++;
danielk1977f0113002006-01-24 12:09:17 +00001209 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1210 pExpr->affinity = pTab->aCol[iCol].affinity;
drh8b4c40d2007-02-01 23:02:45 +00001211 if( (pExpr->flags & EP_ExpCollate)==0 ){
1212 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1213 }
danielk1977aee18ef2005-03-09 12:26:50 +00001214 pExpr->pTab = pTab;
danielk19778f2c54e2008-01-01 19:02:09 +00001215 if( iCol>=0 ){
drhc5499be2008-04-01 15:06:33 +00001216 testcase( iCol==31 );
1217 testcase( iCol==32 );
danielk19778f2c54e2008-01-01 19:02:09 +00001218 *piColMask |= ((u32)1<<iCol) | (iCol>=32?0xffffffff:0);
1219 }
drh626a8792005-01-17 22:08:19 +00001220 break;
1221 }
1222 }
1223 }
1224 }
drhb7f91642004-10-31 02:22:47 +00001225#endif /* !defined(SQLITE_OMIT_TRIGGER) */
drh8141f612004-01-25 22:44:58 +00001226
drh626a8792005-01-17 22:08:19 +00001227 /*
1228 ** Perhaps the name is a reference to the ROWID
1229 */
1230 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
1231 cnt = 1;
1232 pExpr->iColumn = -1;
drh8a512562005-11-14 22:29:05 +00001233 pExpr->affinity = SQLITE_AFF_INTEGER;
drh626a8792005-01-17 22:08:19 +00001234 }
drh8141f612004-01-25 22:44:58 +00001235
drh626a8792005-01-17 22:08:19 +00001236 /*
1237 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
1238 ** might refer to an result-set alias. This happens, for example, when
1239 ** we are resolving names in the WHERE clause of the following command:
1240 **
1241 ** SELECT a+b AS x FROM table WHERE x<10;
1242 **
1243 ** In cases like this, replace pExpr with a copy of the expression that
1244 ** forms the result set entry ("a+b" in the example) and return immediately.
1245 ** Note that the expression in the result set should have already been
1246 ** resolved by the time the WHERE clause is resolved.
1247 */
drhffe07b22005-11-03 00:41:17 +00001248 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
drh626a8792005-01-17 22:08:19 +00001249 for(j=0; j<pEList->nExpr; j++){
1250 char *zAs = pEList->a[j].zName;
1251 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh36379e92007-07-23 22:51:15 +00001252 Expr *pDup, *pOrig;
drh626a8792005-01-17 22:08:19 +00001253 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
drh4f07e5f2007-05-14 11:34:46 +00001254 assert( pExpr->pList==0 );
1255 assert( pExpr->pSelect==0 );
drh36379e92007-07-23 22:51:15 +00001256 pOrig = pEList->a[j].pExpr;
1257 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
1258 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drh17435752007-08-16 04:30:38 +00001259 sqlite3_free(zCol);
drh36379e92007-07-23 22:51:15 +00001260 return 2;
1261 }
danielk19771e536952007-08-16 10:09:01 +00001262 pDup = sqlite3ExprDup(db, pOrig);
drh4f07e5f2007-05-14 11:34:46 +00001263 if( pExpr->flags & EP_ExpCollate ){
1264 pDup->pColl = pExpr->pColl;
1265 pDup->flags |= EP_ExpCollate;
1266 }
drh17435752007-08-16 04:30:38 +00001267 if( pExpr->span.dyn ) sqlite3_free((char*)pExpr->span.z);
1268 if( pExpr->token.dyn ) sqlite3_free((char*)pExpr->token.z);
drh4f07e5f2007-05-14 11:34:46 +00001269 memcpy(pExpr, pDup, sizeof(*pExpr));
drh17435752007-08-16 04:30:38 +00001270 sqlite3_free(pDup);
drh15ccce12005-05-23 15:06:39 +00001271 cnt = 1;
danielk1977c9cf6e32007-06-25 16:29:33 +00001272 pMatch = 0;
drh626a8792005-01-17 22:08:19 +00001273 assert( zTab==0 && zDb==0 );
drh15ccce12005-05-23 15:06:39 +00001274 goto lookupname_end_2;
drh626a8792005-01-17 22:08:19 +00001275 }
1276 }
1277 }
1278
1279 /* Advance to the next name context. The loop will exit when either
1280 ** we have a match (cnt>0) or when we run out of name contexts.
1281 */
1282 if( cnt==0 ){
1283 pNC = pNC->pNext;
1284 }
drh8141f612004-01-25 22:44:58 +00001285 }
1286
1287 /*
1288 ** If X and Y are NULL (in other words if only the column name Z is
1289 ** supplied) and the value of Z is enclosed in double-quotes, then
1290 ** Z is a string literal if it doesn't match any column names. In that
1291 ** case, we need to return right away and not make any changes to
1292 ** pExpr.
drh15ccce12005-05-23 15:06:39 +00001293 **
1294 ** Because no reference was made to outer contexts, the pNC->nRef
1295 ** fields are not changed in any context.
drh8141f612004-01-25 22:44:58 +00001296 */
1297 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
drh17435752007-08-16 04:30:38 +00001298 sqlite3_free(zCol);
drh8141f612004-01-25 22:44:58 +00001299 return 0;
1300 }
1301
1302 /*
1303 ** cnt==0 means there was not match. cnt>1 means there were two or
1304 ** more matches. Either way, we have an error.
1305 */
1306 if( cnt!=1 ){
drhde4fcfd2008-01-19 23:50:26 +00001307 const char *zErr;
1308 zErr = cnt==0 ? "no such column" : "ambiguous column name";
drh8141f612004-01-25 22:44:58 +00001309 if( zDb ){
drhde4fcfd2008-01-19 23:50:26 +00001310 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
drh8141f612004-01-25 22:44:58 +00001311 }else if( zTab ){
drhde4fcfd2008-01-19 23:50:26 +00001312 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
drh8141f612004-01-25 22:44:58 +00001313 }else{
drhde4fcfd2008-01-19 23:50:26 +00001314 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
drh8141f612004-01-25 22:44:58 +00001315 }
drhde4fcfd2008-01-19 23:50:26 +00001316 pTopNC->nErr++;
drh8141f612004-01-25 22:44:58 +00001317 }
1318
drh51669862004-12-18 18:40:26 +00001319 /* If a column from a table in pSrcList is referenced, then record
1320 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
1321 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
1322 ** column number is greater than the number of bits in the bitmask
1323 ** then set the high-order bit of the bitmask.
1324 */
1325 if( pExpr->iColumn>=0 && pMatch!=0 ){
1326 int n = pExpr->iColumn;
drhc5499be2008-04-01 15:06:33 +00001327 testcase( n==sizeof(Bitmask)*8-1 );
drh51669862004-12-18 18:40:26 +00001328 if( n>=sizeof(Bitmask)*8 ){
1329 n = sizeof(Bitmask)*8-1;
1330 }
1331 assert( pMatch->iCursor==pExpr->iTable );
drhca83ac52007-02-01 01:40:44 +00001332 pMatch->colUsed |= ((Bitmask)1)<<n;
drh51669862004-12-18 18:40:26 +00001333 }
1334
danielk1977d5d56522005-03-16 12:15:20 +00001335lookupname_end:
drh8141f612004-01-25 22:44:58 +00001336 /* Clean up and return
1337 */
drh17435752007-08-16 04:30:38 +00001338 sqlite3_free(zDb);
1339 sqlite3_free(zTab);
danielk19774adee202004-05-08 08:23:19 +00001340 sqlite3ExprDelete(pExpr->pLeft);
drh8141f612004-01-25 22:44:58 +00001341 pExpr->pLeft = 0;
danielk19774adee202004-05-08 08:23:19 +00001342 sqlite3ExprDelete(pExpr->pRight);
drh8141f612004-01-25 22:44:58 +00001343 pExpr->pRight = 0;
1344 pExpr->op = TK_COLUMN;
drh15ccce12005-05-23 15:06:39 +00001345lookupname_end_2:
drh17435752007-08-16 04:30:38 +00001346 sqlite3_free(zCol);
drh626a8792005-01-17 22:08:19 +00001347 if( cnt==1 ){
danielk1977b3bce662005-01-29 08:32:43 +00001348 assert( pNC!=0 );
drh728b5772007-09-18 15:55:07 +00001349 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
danielk1977aee18ef2005-03-09 12:26:50 +00001350 if( pMatch && !pMatch->pSelect ){
1351 pExpr->pTab = pMatch->pTab;
1352 }
drh15ccce12005-05-23 15:06:39 +00001353 /* Increment the nRef value on all name contexts from TopNC up to
1354 ** the point where the name matched. */
1355 for(;;){
1356 assert( pTopNC!=0 );
1357 pTopNC->nRef++;
1358 if( pTopNC==pNC ) break;
1359 pTopNC = pTopNC->pNext;
1360 }
1361 return 0;
1362 } else {
1363 return 1;
drh626a8792005-01-17 22:08:19 +00001364 }
drh8141f612004-01-25 22:44:58 +00001365}
1366
1367/*
drh626a8792005-01-17 22:08:19 +00001368** This routine is designed as an xFunc for walkExprTree().
1369**
drh73b211a2005-01-18 04:00:42 +00001370** Resolve symbolic names into TK_COLUMN operators for the current
drh626a8792005-01-17 22:08:19 +00001371** node in the expression tree. Return 0 to continue the search down
drh73b211a2005-01-18 04:00:42 +00001372** the tree or 2 to abort the tree walk.
1373**
1374** This routine also does error checking and name resolution for
1375** function names. The operator for aggregate functions is changed
1376** to TK_AGG_FUNCTION.
drh626a8792005-01-17 22:08:19 +00001377*/
1378static int nameResolverStep(void *pArg, Expr *pExpr){
1379 NameContext *pNC = (NameContext*)pArg;
drh626a8792005-01-17 22:08:19 +00001380 Parse *pParse;
drh626a8792005-01-17 22:08:19 +00001381
danielk1977b3bce662005-01-29 08:32:43 +00001382 if( pExpr==0 ) return 1;
drh626a8792005-01-17 22:08:19 +00001383 assert( pNC!=0 );
drh626a8792005-01-17 22:08:19 +00001384 pParse = pNC->pParse;
danielk1977b3bce662005-01-29 08:32:43 +00001385
drh626a8792005-01-17 22:08:19 +00001386 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1387 ExprSetProperty(pExpr, EP_Resolved);
1388#ifndef NDEBUG
danielk1977f0113002006-01-24 12:09:17 +00001389 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1390 SrcList *pSrcList = pNC->pSrcList;
danielk1977940fac92005-01-23 22:41:37 +00001391 int i;
danielk1977f0113002006-01-24 12:09:17 +00001392 for(i=0; i<pNC->pSrcList->nSrc; i++){
drh626a8792005-01-17 22:08:19 +00001393 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1394 }
1395 }
1396#endif
1397 switch( pExpr->op ){
1398 /* Double-quoted strings (ex: "abc") are used as identifiers if
1399 ** possible. Otherwise they remain as strings. Single-quoted
1400 ** strings (ex: 'abc') are always string literals.
1401 */
1402 case TK_STRING: {
1403 if( pExpr->token.z[0]=='\'' ) break;
1404 /* Fall thru into the TK_ID case if this is a double-quoted string */
1405 }
1406 /* A lone identifier is the name of a column.
1407 */
1408 case TK_ID: {
drh626a8792005-01-17 22:08:19 +00001409 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1410 return 1;
1411 }
1412
1413 /* A table name and column name: ID.ID
1414 ** Or a database, table and column: ID.ID.ID
1415 */
1416 case TK_DOT: {
1417 Token *pColumn;
1418 Token *pTable;
1419 Token *pDb;
1420 Expr *pRight;
1421
danielk1977b3bce662005-01-29 08:32:43 +00001422 /* if( pSrcList==0 ) break; */
drh626a8792005-01-17 22:08:19 +00001423 pRight = pExpr->pRight;
1424 if( pRight->op==TK_ID ){
1425 pDb = 0;
1426 pTable = &pExpr->pLeft->token;
1427 pColumn = &pRight->token;
1428 }else{
1429 assert( pRight->op==TK_DOT );
1430 pDb = &pExpr->pLeft->token;
1431 pTable = &pRight->pLeft->token;
1432 pColumn = &pRight->pRight->token;
1433 }
1434 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1435 return 1;
1436 }
1437
1438 /* Resolve function names
1439 */
drhb71090f2005-05-23 17:26:51 +00001440 case TK_CONST_FUNC:
drh626a8792005-01-17 22:08:19 +00001441 case TK_FUNCTION: {
1442 ExprList *pList = pExpr->pList; /* The argument list */
1443 int n = pList ? pList->nExpr : 0; /* Number of arguments */
1444 int no_such_func = 0; /* True if no such function exists */
1445 int wrong_num_args = 0; /* True if wrong number of arguments */
1446 int is_agg = 0; /* True if is an aggregate function */
1447 int i;
drh5169bbc2006-08-24 14:59:45 +00001448 int auth; /* Authorization to use the function */
drh626a8792005-01-17 22:08:19 +00001449 int nId; /* Number of characters in function name */
1450 const char *zId; /* The function name. */
drh73b211a2005-01-18 04:00:42 +00001451 FuncDef *pDef; /* Information about the function */
danielk197714db2662006-01-09 16:12:04 +00001452 int enc = ENC(pParse->db); /* The database encoding */
drh626a8792005-01-17 22:08:19 +00001453
drh2646da72005-12-09 20:02:05 +00001454 zId = (char*)pExpr->token.z;
drhb71090f2005-05-23 17:26:51 +00001455 nId = pExpr->token.n;
drh626a8792005-01-17 22:08:19 +00001456 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1457 if( pDef==0 ){
1458 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1459 if( pDef==0 ){
1460 no_such_func = 1;
1461 }else{
1462 wrong_num_args = 1;
1463 }
1464 }else{
1465 is_agg = pDef->xFunc==0;
1466 }
drh2fca7fe2006-11-23 11:59:13 +00001467#ifndef SQLITE_OMIT_AUTHORIZATION
drh5169bbc2006-08-24 14:59:45 +00001468 if( pDef ){
1469 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
1470 if( auth!=SQLITE_OK ){
1471 if( auth==SQLITE_DENY ){
1472 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
1473 pDef->zName);
1474 pNC->nErr++;
1475 }
1476 pExpr->op = TK_NULL;
1477 return 1;
1478 }
1479 }
drhb8b14212006-08-24 15:18:25 +00001480#endif
drh626a8792005-01-17 22:08:19 +00001481 if( is_agg && !pNC->allowAgg ){
1482 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1483 pNC->nErr++;
1484 is_agg = 0;
1485 }else if( no_such_func ){
1486 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1487 pNC->nErr++;
1488 }else if( wrong_num_args ){
1489 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1490 nId, zId);
1491 pNC->nErr++;
1492 }
1493 if( is_agg ){
1494 pExpr->op = TK_AGG_FUNCTION;
1495 pNC->hasAgg = 1;
1496 }
drh73b211a2005-01-18 04:00:42 +00001497 if( is_agg ) pNC->allowAgg = 0;
drh626a8792005-01-17 22:08:19 +00001498 for(i=0; pNC->nErr==0 && i<n; i++){
drh73b211a2005-01-18 04:00:42 +00001499 walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
drh626a8792005-01-17 22:08:19 +00001500 }
drh73b211a2005-01-18 04:00:42 +00001501 if( is_agg ) pNC->allowAgg = 1;
drh626a8792005-01-17 22:08:19 +00001502 /* FIX ME: Compute pExpr->affinity based on the expected return
1503 ** type of the function
1504 */
1505 return is_agg;
1506 }
danielk1977b3bce662005-01-29 08:32:43 +00001507#ifndef SQLITE_OMIT_SUBQUERY
1508 case TK_SELECT:
1509 case TK_EXISTS:
1510#endif
1511 case TK_IN: {
1512 if( pExpr->pSelect ){
drh8a9f38f2005-11-05 15:07:55 +00001513 int nRef = pNC->nRef;
drh06f65412005-11-03 02:03:13 +00001514#ifndef SQLITE_OMIT_CHECK
1515 if( pNC->isCheck ){
1516 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
1517 }
1518#endif
danielk1977b3bce662005-01-29 08:32:43 +00001519 sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1520 assert( pNC->nRef>=nRef );
1521 if( nRef!=pNC->nRef ){
1522 ExprSetProperty(pExpr, EP_VarSelect);
1523 }
1524 }
drh4284fb02005-11-03 12:33:28 +00001525 break;
danielk1977b3bce662005-01-29 08:32:43 +00001526 }
drh4284fb02005-11-03 12:33:28 +00001527#ifndef SQLITE_OMIT_CHECK
1528 case TK_VARIABLE: {
1529 if( pNC->isCheck ){
1530 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
1531 }
1532 break;
1533 }
1534#endif
drh626a8792005-01-17 22:08:19 +00001535 }
1536 return 0;
1537}
1538
1539/*
drhcce7d172000-05-31 15:34:51 +00001540** This routine walks an expression tree and resolves references to
drh967e8b72000-06-21 13:59:10 +00001541** table columns. Nodes of the form ID.ID or ID resolve into an
drhaacc5432002-01-06 17:07:40 +00001542** index to the table in the table list and a column offset. The
1543** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
1544** value is changed to the index of the referenced table in pTabList
drh832508b2002-03-02 17:04:07 +00001545** plus the "base" value. The base value will ultimately become the
drhaacc5432002-01-06 17:07:40 +00001546** VDBE cursor number for a cursor that is pointing into the referenced
1547** table. The Expr.iColumn value is changed to the index of the column
1548** of the referenced table. The Expr.iColumn value for the special
1549** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
1550** alias for ROWID.
drh19a775c2000-06-05 18:54:46 +00001551**
drh626a8792005-01-17 22:08:19 +00001552** Also resolve function names and check the functions for proper
1553** usage. Make sure all function names are recognized and all functions
1554** have the correct number of arguments. Leave an error message
1555** in pParse->zErrMsg if anything is amiss. Return the number of errors.
1556**
drh73b211a2005-01-18 04:00:42 +00001557** If the expression contains aggregate functions then set the EP_Agg
1558** property on the expression.
drh626a8792005-01-17 22:08:19 +00001559*/
danielk1977fc976062007-05-10 10:46:56 +00001560int sqlite3ExprResolveNames(
danielk1977b3bce662005-01-29 08:32:43 +00001561 NameContext *pNC, /* Namespace to resolve expressions in. */
1562 Expr *pExpr /* The expression to be analyzed. */
drh626a8792005-01-17 22:08:19 +00001563){
drh13449892005-09-07 21:22:45 +00001564 int savedHasAgg;
drhbb4957f2008-03-20 14:03:29 +00001565
drh73b211a2005-01-18 04:00:42 +00001566 if( pExpr==0 ) return 0;
drhbb4957f2008-03-20 14:03:29 +00001567#if SQLITE_MAX_EXPR_DEPTH>0
1568 {
danielk19774b5255a2008-06-05 16:47:39 +00001569 if( checkExprHeight(pNC->pParse, pExpr->nHeight + pNC->pParse->nHeight) ){
drhbb4957f2008-03-20 14:03:29 +00001570 return 1;
1571 }
1572 pNC->pParse->nHeight += pExpr->nHeight;
danielk1977fc976062007-05-10 10:46:56 +00001573 }
danielk1977fc976062007-05-10 10:46:56 +00001574#endif
drh13449892005-09-07 21:22:45 +00001575 savedHasAgg = pNC->hasAgg;
1576 pNC->hasAgg = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001577 walkExprTree(pExpr, nameResolverStep, pNC);
drhbb4957f2008-03-20 14:03:29 +00001578#if SQLITE_MAX_EXPR_DEPTH>0
danielk1977fc976062007-05-10 10:46:56 +00001579 pNC->pParse->nHeight -= pExpr->nHeight;
1580#endif
danielk1977b3bce662005-01-29 08:32:43 +00001581 if( pNC->nErr>0 ){
drh73b211a2005-01-18 04:00:42 +00001582 ExprSetProperty(pExpr, EP_Error);
drh73b211a2005-01-18 04:00:42 +00001583 }
drh13449892005-09-07 21:22:45 +00001584 if( pNC->hasAgg ){
1585 ExprSetProperty(pExpr, EP_Agg);
1586 }else if( savedHasAgg ){
1587 pNC->hasAgg = 1;
1588 }
drh73b211a2005-01-18 04:00:42 +00001589 return ExprHasProperty(pExpr, EP_Error);
drh626a8792005-01-17 22:08:19 +00001590}
1591
drh1398ad32005-01-19 23:24:50 +00001592/*
1593** A pointer instance of this structure is used to pass information
1594** through walkExprTree into codeSubqueryStep().
1595*/
1596typedef struct QueryCoder QueryCoder;
1597struct QueryCoder {
1598 Parse *pParse; /* The parsing context */
1599 NameContext *pNC; /* Namespace of first enclosing query */
1600};
1601
danielk19779a96b662007-11-29 17:05:18 +00001602#ifdef SQLITE_TEST
1603 int sqlite3_enable_in_opt = 1;
1604#else
1605 #define sqlite3_enable_in_opt 1
1606#endif
1607
1608/*
drhb287f4b2008-04-25 00:08:38 +00001609** Return true if the IN operator optimization is enabled and
1610** the SELECT statement p exists and is of the
1611** simple form:
1612**
1613** SELECT <column> FROM <table>
1614**
1615** If this is the case, it may be possible to use an existing table
1616** or index instead of generating an epheremal table.
1617*/
1618#ifndef SQLITE_OMIT_SUBQUERY
1619static int isCandidateForInOpt(Select *p){
1620 SrcList *pSrc;
1621 ExprList *pEList;
1622 Table *pTab;
1623 if( !sqlite3_enable_in_opt ) return 0; /* IN optimization must be enabled */
1624 if( p==0 ) return 0; /* right-hand side of IN is SELECT */
1625 if( p->pPrior ) return 0; /* Not a compound SELECT */
1626 if( p->isDistinct ) return 0; /* No DISTINCT keyword */
1627 if( p->isAgg ) return 0; /* Contains no aggregate functions */
1628 if( p->pGroupBy ) return 0; /* Has no GROUP BY clause */
1629 if( p->pLimit ) return 0; /* Has no LIMIT clause */
1630 if( p->pOffset ) return 0;
1631 if( p->pWhere ) return 0; /* Has no WHERE clause */
1632 pSrc = p->pSrc;
1633 if( pSrc==0 ) return 0; /* A single table in the FROM clause */
1634 if( pSrc->nSrc!=1 ) return 0;
1635 if( pSrc->a[0].pSelect ) return 0; /* FROM clause is not a subquery */
1636 pTab = pSrc->a[0].pTab;
1637 if( pTab==0 ) return 0;
1638 if( pTab->pSelect ) return 0; /* FROM clause is not a view */
1639 if( IsVirtual(pTab) ) return 0; /* FROM clause not a virtual table */
1640 pEList = p->pEList;
1641 if( pEList->nExpr!=1 ) return 0; /* One column in the result set */
1642 if( pEList->a[0].pExpr->op!=TK_COLUMN ) return 0; /* Result is a column */
1643 return 1;
1644}
1645#endif /* SQLITE_OMIT_SUBQUERY */
1646
1647/*
danielk19779a96b662007-11-29 17:05:18 +00001648** This function is used by the implementation of the IN (...) operator.
1649** It's job is to find or create a b-tree structure that may be used
1650** either to test for membership of the (...) set or to iterate through
drh85b623f2007-12-13 21:54:09 +00001651** its members, skipping duplicates.
danielk19779a96b662007-11-29 17:05:18 +00001652**
1653** The cursor opened on the structure (database table, database index
1654** or ephermal table) is stored in pX->iTable before this function returns.
1655** The returned value indicates the structure type, as follows:
1656**
1657** IN_INDEX_ROWID - The cursor was opened on a database table.
drh2d401ab2008-01-10 23:50:11 +00001658** IN_INDEX_INDEX - The cursor was opened on a database index.
danielk19779a96b662007-11-29 17:05:18 +00001659** IN_INDEX_EPH - The cursor was opened on a specially created and
1660** populated epheremal table.
1661**
1662** An existing structure may only be used if the SELECT is of the simple
1663** form:
1664**
1665** SELECT <column> FROM <table>
1666**
1667** If the mustBeUnique parameter is false, the structure will be used
1668** for fast set membership tests. In this case an epheremal table must
1669** be used unless <column> is an INTEGER PRIMARY KEY or an index can
drh85b623f2007-12-13 21:54:09 +00001670** be found with <column> as its left-most column.
danielk19779a96b662007-11-29 17:05:18 +00001671**
1672** If mustBeUnique is true, then the structure will be used to iterate
1673** through the set members, skipping any duplicates. In this case an
1674** epheremal table must be used unless the selected <column> is guaranteed
1675** to be unique - either because it is an INTEGER PRIMARY KEY or it
1676** is unique by virtue of a constraint or implicit index.
1677*/
danielk1977284f4ac2007-12-10 05:03:46 +00001678#ifndef SQLITE_OMIT_SUBQUERY
danielk19779a96b662007-11-29 17:05:18 +00001679int sqlite3FindInIndex(Parse *pParse, Expr *pX, int mustBeUnique){
1680 Select *p;
1681 int eType = 0;
1682 int iTab = pParse->nTab++;
1683
1684 /* The follwing if(...) expression is true if the SELECT is of the
1685 ** simple form:
1686 **
1687 ** SELECT <column> FROM <table>
1688 **
1689 ** If this is the case, it may be possible to use an existing table
1690 ** or index instead of generating an epheremal table.
1691 */
drhb287f4b2008-04-25 00:08:38 +00001692 p = pX->pSelect;
1693 if( isCandidateForInOpt(p) ){
danielk19779a96b662007-11-29 17:05:18 +00001694 sqlite3 *db = pParse->db;
1695 Index *pIdx;
1696 Expr *pExpr = p->pEList->a[0].pExpr;
1697 int iCol = pExpr->iColumn;
1698 Vdbe *v = sqlite3GetVdbe(pParse);
1699
1700 /* This function is only called from two places. In both cases the vdbe
1701 ** has already been allocated. So assume sqlite3GetVdbe() is always
1702 ** successful here.
1703 */
1704 assert(v);
1705 if( iCol<0 ){
drh0a07c102008-01-03 18:03:08 +00001706 int iMem = ++pParse->nMem;
danielk19779a96b662007-11-29 17:05:18 +00001707 int iAddr;
1708 Table *pTab = p->pSrc->a[0].pTab;
1709 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1710 sqlite3VdbeUsesBtree(v, iDb);
1711
drh892d3172008-01-10 03:46:36 +00001712 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
drh4c583122008-01-04 22:01:03 +00001713 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
danielk19779a96b662007-11-29 17:05:18 +00001714
1715 sqlite3OpenTable(pParse, iTab, iDb, pTab, OP_OpenRead);
1716 eType = IN_INDEX_ROWID;
1717
1718 sqlite3VdbeJumpHere(v, iAddr);
1719 }else{
1720 /* The collation sequence used by the comparison. If an index is to
1721 ** be used in place of a temp-table, it must be ordered according
1722 ** to this collation sequence.
1723 */
1724 CollSeq *pReq = sqlite3BinaryCompareCollSeq(pParse, pX->pLeft, pExpr);
1725
1726 /* Check that the affinity that will be used to perform the
1727 ** comparison is the same as the affinity of the column. If
1728 ** it is not, it is not possible to use any index.
1729 */
1730 Table *pTab = p->pSrc->a[0].pTab;
1731 char aff = comparisonAffinity(pX);
1732 int affinity_ok = (pTab->aCol[iCol].affinity==aff||aff==SQLITE_AFF_NONE);
1733
1734 for(pIdx=pTab->pIndex; pIdx && eType==0 && affinity_ok; pIdx=pIdx->pNext){
1735 if( (pIdx->aiColumn[0]==iCol)
1736 && (pReq==sqlite3FindCollSeq(db, ENC(db), pIdx->azColl[0], -1, 0))
1737 && (!mustBeUnique || (pIdx->nColumn==1 && pIdx->onError!=OE_None))
1738 ){
1739 int iDb;
drh0a07c102008-01-03 18:03:08 +00001740 int iMem = ++pParse->nMem;
danielk19779a96b662007-11-29 17:05:18 +00001741 int iAddr;
1742 char *pKey;
1743
1744 pKey = (char *)sqlite3IndexKeyinfo(pParse, pIdx);
1745 iDb = sqlite3SchemaToIndex(db, pIdx->pSchema);
1746 sqlite3VdbeUsesBtree(v, iDb);
1747
drh892d3172008-01-10 03:46:36 +00001748 iAddr = sqlite3VdbeAddOp1(v, OP_If, iMem);
drh4c583122008-01-04 22:01:03 +00001749 sqlite3VdbeAddOp2(v, OP_Integer, 1, iMem);
danielk19779a96b662007-11-29 17:05:18 +00001750
danielk1977cd3e8f72008-03-25 09:47:35 +00001751 sqlite3VdbeAddOp2(v, OP_SetNumColumns, 0, pIdx->nColumn);
danielk1977207872a2008-01-03 07:54:23 +00001752 sqlite3VdbeAddOp4(v, OP_OpenRead, iTab, pIdx->tnum, iDb,
drh66a51672008-01-03 00:01:23 +00001753 pKey,P4_KEYINFO_HANDOFF);
danielk1977207872a2008-01-03 07:54:23 +00001754 VdbeComment((v, "%s", pIdx->zName));
danielk19779a96b662007-11-29 17:05:18 +00001755 eType = IN_INDEX_INDEX;
danielk19779a96b662007-11-29 17:05:18 +00001756
1757 sqlite3VdbeJumpHere(v, iAddr);
1758 }
1759 }
1760 }
1761 }
1762
1763 if( eType==0 ){
1764 sqlite3CodeSubselect(pParse, pX);
1765 eType = IN_INDEX_EPH;
1766 }else{
1767 pX->iTable = iTab;
1768 }
1769 return eType;
1770}
danielk1977284f4ac2007-12-10 05:03:46 +00001771#endif
drh626a8792005-01-17 22:08:19 +00001772
1773/*
drh9cbe6352005-11-29 03:13:21 +00001774** Generate code for scalar subqueries used as an expression
1775** and IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00001776**
drh9cbe6352005-11-29 03:13:21 +00001777** (SELECT a FROM b) -- subquery
1778** EXISTS (SELECT a FROM b) -- EXISTS subquery
1779** x IN (4,5,11) -- IN operator with list on right-hand side
1780** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00001781**
drh9cbe6352005-11-29 03:13:21 +00001782** The pExpr parameter describes the expression that contains the IN
1783** operator or subquery.
drhcce7d172000-05-31 15:34:51 +00001784*/
drh51522cd2005-01-20 13:36:19 +00001785#ifndef SQLITE_OMIT_SUBQUERY
danielk1977b3bce662005-01-29 08:32:43 +00001786void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
drh57dbd7b2005-07-08 18:25:26 +00001787 int testAddr = 0; /* One-time test address */
danielk1977b3bce662005-01-29 08:32:43 +00001788 Vdbe *v = sqlite3GetVdbe(pParse);
1789 if( v==0 ) return;
1790
danielk1977fc976062007-05-10 10:46:56 +00001791
drh57dbd7b2005-07-08 18:25:26 +00001792 /* This code must be run in its entirety every time it is encountered
1793 ** if any of the following is true:
1794 **
1795 ** * The right-hand side is a correlated subquery
1796 ** * The right-hand side is an expression list containing variables
1797 ** * We are inside a trigger
1798 **
1799 ** If all of the above are false, then we can run this code just once
1800 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00001801 */
1802 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
drh0a07c102008-01-03 18:03:08 +00001803 int mem = ++pParse->nMem;
drh892d3172008-01-10 03:46:36 +00001804 sqlite3VdbeAddOp1(v, OP_If, mem);
1805 testAddr = sqlite3VdbeAddOp2(v, OP_Integer, 1, mem);
drh17435752007-08-16 04:30:38 +00001806 assert( testAddr>0 || pParse->db->mallocFailed );
danielk1977b3bce662005-01-29 08:32:43 +00001807 }
1808
drhcce7d172000-05-31 15:34:51 +00001809 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00001810 case TK_IN: {
danielk1977e014a832004-05-17 10:48:57 +00001811 char affinity;
drhd3d39e92004-05-20 22:16:29 +00001812 KeyInfo keyInfo;
drhb9bb7c12006-06-11 23:41:55 +00001813 int addr; /* Address of OP_OpenEphemeral instruction */
drhd3d39e92004-05-20 22:16:29 +00001814
danielk1977bf3b7212004-05-18 10:06:24 +00001815 affinity = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +00001816
1817 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh57dbd7b2005-07-08 18:25:26 +00001818 ** expression it is handled the same way. A virtual table is
danielk1977e014a832004-05-17 10:48:57 +00001819 ** filled with single-field index keys representing the results
1820 ** from the SELECT or the <exprlist>.
1821 **
1822 ** If the 'x' expression is a column value, or the SELECT...
1823 ** statement returns a column value, then the affinity of that
1824 ** column is used to build the index keys. If both 'x' and the
1825 ** SELECT... statement are columns, then numeric affinity is used
1826 ** if either column has NUMERIC or INTEGER affinity. If neither
1827 ** 'x' nor the SELECT... statement are columns, then numeric affinity
1828 ** is used.
1829 */
1830 pExpr->iTable = pParse->nTab++;
danielk1977cd3e8f72008-03-25 09:47:35 +00001831 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pExpr->iTable, 1);
drhd3d39e92004-05-20 22:16:29 +00001832 memset(&keyInfo, 0, sizeof(keyInfo));
1833 keyInfo.nField = 1;
danielk1977e014a832004-05-17 10:48:57 +00001834
drhfef52082000-06-06 01:50:43 +00001835 if( pExpr->pSelect ){
1836 /* Case 1: expr IN (SELECT ...)
1837 **
danielk1977e014a832004-05-17 10:48:57 +00001838 ** Generate code to write the results of the select into the temporary
1839 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00001840 */
drh1013c932008-01-06 00:25:21 +00001841 SelectDest dest;
drhbe5c89a2004-07-26 00:31:09 +00001842 ExprList *pEList;
drh1013c932008-01-06 00:25:21 +00001843
1844 sqlite3SelectDestInit(&dest, SRT_Set, pExpr->iTable);
1845 dest.affinity = (int)affinity;
danielk1977e014a832004-05-17 10:48:57 +00001846 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
danielk19776c8c8ce2008-01-02 16:27:09 +00001847 if( sqlite3Select(pParse, pExpr->pSelect, &dest, 0, 0, 0, 0) ){
drh94ccde52007-04-13 16:06:32 +00001848 return;
1849 }
drhbe5c89a2004-07-26 00:31:09 +00001850 pEList = pExpr->pSelect->pEList;
1851 if( pEList && pEList->nExpr>0 ){
danielk1977bcbb04e2007-05-29 12:11:29 +00001852 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
drhbe5c89a2004-07-26 00:31:09 +00001853 pEList->a[0].pExpr);
danielk19770202b292004-06-09 09:55:16 +00001854 }
drhfef52082000-06-06 01:50:43 +00001855 }else if( pExpr->pList ){
1856 /* Case 2: expr IN (exprlist)
1857 **
drhfd131da2007-08-07 17:13:03 +00001858 ** For each expression, build an index key from the evaluation and
danielk1977e014a832004-05-17 10:48:57 +00001859 ** store it in the temporary table. If <expr> is a column, then use
1860 ** that columns affinity when building index keys. If <expr> is not
1861 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00001862 */
danielk1977e014a832004-05-17 10:48:57 +00001863 int i;
drh57dbd7b2005-07-08 18:25:26 +00001864 ExprList *pList = pExpr->pList;
1865 struct ExprList_item *pItem;
drh2d401ab2008-01-10 23:50:11 +00001866 int r1, r2;
drh57dbd7b2005-07-08 18:25:26 +00001867
danielk1977e014a832004-05-17 10:48:57 +00001868 if( !affinity ){
drh8159a352006-05-23 23:22:29 +00001869 affinity = SQLITE_AFF_NONE;
danielk1977e014a832004-05-17 10:48:57 +00001870 }
danielk19770202b292004-06-09 09:55:16 +00001871 keyInfo.aColl[0] = pExpr->pLeft->pColl;
danielk1977e014a832004-05-17 10:48:57 +00001872
1873 /* Loop through each expression in <exprlist>. */
drh2d401ab2008-01-10 23:50:11 +00001874 r1 = sqlite3GetTempReg(pParse);
1875 r2 = sqlite3GetTempReg(pParse);
drh57dbd7b2005-07-08 18:25:26 +00001876 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1877 Expr *pE2 = pItem->pExpr;
danielk1977e014a832004-05-17 10:48:57 +00001878
drh57dbd7b2005-07-08 18:25:26 +00001879 /* If the expression is not constant then we will need to
1880 ** disable the test that was generated above that makes sure
1881 ** this code only executes once. Because for a non-constant
1882 ** expression we need to rerun this code each time.
1883 */
drh892d3172008-01-10 03:46:36 +00001884 if( testAddr && !sqlite3ExprIsConstant(pE2) ){
1885 sqlite3VdbeChangeToNoop(v, testAddr-1, 2);
drh57dbd7b2005-07-08 18:25:26 +00001886 testAddr = 0;
drh4794b982000-06-06 13:54:14 +00001887 }
danielk1977e014a832004-05-17 10:48:57 +00001888
1889 /* Evaluate the expression and insert it into the temp table */
drhe55cbd72008-03-31 23:48:03 +00001890 pParse->disableColCache++;
drh2d401ab2008-01-10 23:50:11 +00001891 sqlite3ExprCode(pParse, pE2, r1);
drhc5499be2008-04-01 15:06:33 +00001892 assert( pParse->disableColCache>0 );
drhe55cbd72008-03-31 23:48:03 +00001893 pParse->disableColCache--;
drh1db639c2008-01-17 02:36:28 +00001894 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
drhda250ea2008-04-01 05:07:14 +00001895 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
drh2d401ab2008-01-10 23:50:11 +00001896 sqlite3VdbeAddOp2(v, OP_IdxInsert, pExpr->iTable, r2);
drhfef52082000-06-06 01:50:43 +00001897 }
drh2d401ab2008-01-10 23:50:11 +00001898 sqlite3ReleaseTempReg(pParse, r1);
1899 sqlite3ReleaseTempReg(pParse, r2);
drhfef52082000-06-06 01:50:43 +00001900 }
drh66a51672008-01-03 00:01:23 +00001901 sqlite3VdbeChangeP4(v, addr, (void *)&keyInfo, P4_KEYINFO);
danielk1977b3bce662005-01-29 08:32:43 +00001902 break;
drhfef52082000-06-06 01:50:43 +00001903 }
1904
drh51522cd2005-01-20 13:36:19 +00001905 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00001906 case TK_SELECT: {
drhfef52082000-06-06 01:50:43 +00001907 /* This has to be a scalar SELECT. Generate code to put the
1908 ** value of this select in a memory cell and record the number
drh967e8b72000-06-21 13:59:10 +00001909 ** of the memory cell in iColumn.
drhfef52082000-06-06 01:50:43 +00001910 */
drh2646da72005-12-09 20:02:05 +00001911 static const Token one = { (u8*)"1", 0, 1 };
drh51522cd2005-01-20 13:36:19 +00001912 Select *pSel;
danielk19776c8c8ce2008-01-02 16:27:09 +00001913 SelectDest dest;
drh1398ad32005-01-19 23:24:50 +00001914
drh51522cd2005-01-20 13:36:19 +00001915 pSel = pExpr->pSelect;
drh1013c932008-01-06 00:25:21 +00001916 sqlite3SelectDestInit(&dest, 0, ++pParse->nMem);
drh51522cd2005-01-20 13:36:19 +00001917 if( pExpr->op==TK_SELECT ){
danielk19776c8c8ce2008-01-02 16:27:09 +00001918 dest.eDest = SRT_Mem;
drh4c583122008-01-04 22:01:03 +00001919 sqlite3VdbeAddOp2(v, OP_Null, 0, dest.iParm);
drhd4e70eb2008-01-02 00:34:36 +00001920 VdbeComment((v, "Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00001921 }else{
danielk19776c8c8ce2008-01-02 16:27:09 +00001922 dest.eDest = SRT_Exists;
drh4c583122008-01-04 22:01:03 +00001923 sqlite3VdbeAddOp2(v, OP_Integer, 0, dest.iParm);
drhd4e70eb2008-01-02 00:34:36 +00001924 VdbeComment((v, "Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00001925 }
drhec7429a2005-10-06 16:53:14 +00001926 sqlite3ExprDelete(pSel->pLimit);
danielk1977a1644fd2007-08-29 12:31:25 +00001927 pSel->pLimit = sqlite3PExpr(pParse, TK_INTEGER, 0, 0, &one);
danielk19776c8c8ce2008-01-02 16:27:09 +00001928 if( sqlite3Select(pParse, pSel, &dest, 0, 0, 0, 0) ){
drh94ccde52007-04-13 16:06:32 +00001929 return;
1930 }
danielk19776c8c8ce2008-01-02 16:27:09 +00001931 pExpr->iColumn = dest.iParm;
danielk1977b3bce662005-01-29 08:32:43 +00001932 break;
drhcce7d172000-05-31 15:34:51 +00001933 }
1934 }
danielk1977b3bce662005-01-29 08:32:43 +00001935
drh57dbd7b2005-07-08 18:25:26 +00001936 if( testAddr ){
drh892d3172008-01-10 03:46:36 +00001937 sqlite3VdbeJumpHere(v, testAddr-1);
danielk1977b3bce662005-01-29 08:32:43 +00001938 }
danielk1977fc976062007-05-10 10:46:56 +00001939
danielk1977b3bce662005-01-29 08:32:43 +00001940 return;
drhcce7d172000-05-31 15:34:51 +00001941}
drh51522cd2005-01-20 13:36:19 +00001942#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00001943
drhcce7d172000-05-31 15:34:51 +00001944/*
drh598f1342007-10-23 15:39:45 +00001945** Duplicate an 8-byte value
1946*/
1947static char *dup8bytes(Vdbe *v, const char *in){
1948 char *out = sqlite3DbMallocRaw(sqlite3VdbeDb(v), 8);
1949 if( out ){
1950 memcpy(out, in, 8);
1951 }
1952 return out;
1953}
1954
1955/*
1956** Generate an instruction that will put the floating point
drh9cbf3422008-01-17 16:22:13 +00001957** value described by z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00001958**
1959** The z[] string will probably not be zero-terminated. But the
1960** z[n] character is guaranteed to be something that does not look
1961** like the continuation of the number.
drh598f1342007-10-23 15:39:45 +00001962*/
drh9de221d2008-01-05 06:51:30 +00001963static void codeReal(Vdbe *v, const char *z, int n, int negateFlag, int iMem){
drh598f1342007-10-23 15:39:45 +00001964 assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
1965 if( z ){
1966 double value;
1967 char *zV;
drh0cf19ed2007-10-23 18:55:48 +00001968 assert( !isdigit(z[n]) );
drh598f1342007-10-23 15:39:45 +00001969 sqlite3AtoF(z, &value);
drh2eaf93d2008-04-29 00:15:20 +00001970 if( sqlite3IsNaN(value) ){
1971 sqlite3VdbeAddOp2(v, OP_Null, 0, iMem);
1972 }else{
1973 if( negateFlag ) value = -value;
1974 zV = dup8bytes(v, (char*)&value);
1975 sqlite3VdbeAddOp4(v, OP_Real, 0, iMem, 0, zV, P4_REAL);
1976 }
drh598f1342007-10-23 15:39:45 +00001977 }
1978}
1979
1980
1981/*
drhfec19aa2004-05-19 20:41:03 +00001982** Generate an instruction that will put the integer describe by
drh9cbf3422008-01-17 16:22:13 +00001983** text z[0..n-1] into register iMem.
drh0cf19ed2007-10-23 18:55:48 +00001984**
1985** The z[] string will probably not be zero-terminated. But the
1986** z[n] character is guaranteed to be something that does not look
1987** like the continuation of the number.
drhfec19aa2004-05-19 20:41:03 +00001988*/
drh9de221d2008-01-05 06:51:30 +00001989static void codeInteger(Vdbe *v, const char *z, int n, int negFlag, int iMem){
drhabb6fca2007-08-16 12:24:01 +00001990 assert( z || v==0 || sqlite3VdbeDb(v)->mallocFailed );
danielk1977c9cf9012007-05-30 10:36:47 +00001991 if( z ){
1992 int i;
drh0cf19ed2007-10-23 18:55:48 +00001993 assert( !isdigit(z[n]) );
danielk1977c9cf9012007-05-30 10:36:47 +00001994 if( sqlite3GetInt32(z, &i) ){
drh9de221d2008-01-05 06:51:30 +00001995 if( negFlag ) i = -i;
1996 sqlite3VdbeAddOp2(v, OP_Integer, i, iMem);
1997 }else if( sqlite3FitsIn64Bits(z, negFlag) ){
drh598f1342007-10-23 15:39:45 +00001998 i64 value;
1999 char *zV;
2000 sqlite3Atoi64(z, &value);
drh9de221d2008-01-05 06:51:30 +00002001 if( negFlag ) value = -value;
drh598f1342007-10-23 15:39:45 +00002002 zV = dup8bytes(v, (char*)&value);
drh9de221d2008-01-05 06:51:30 +00002003 sqlite3VdbeAddOp4(v, OP_Int64, 0, iMem, 0, zV, P4_INT64);
danielk1977c9cf9012007-05-30 10:36:47 +00002004 }else{
drh9de221d2008-01-05 06:51:30 +00002005 codeReal(v, z, n, negFlag, iMem);
danielk1977c9cf9012007-05-30 10:36:47 +00002006 }
drhfec19aa2004-05-19 20:41:03 +00002007 }
2008}
2009
drh945498f2007-02-24 11:52:52 +00002010
2011/*
2012** Generate code that will extract the iColumn-th column from
drhe55cbd72008-03-31 23:48:03 +00002013** table pTab and store the column value in a register. An effort
2014** is made to store the column value in register iReg, but this is
2015** not guaranteed. The location of the column value is returned.
2016**
2017** There must be an open cursor to pTab in iTable when this routine
2018** is called. If iColumn<0 then code is generated that extracts the rowid.
drhda250ea2008-04-01 05:07:14 +00002019**
2020** This routine might attempt to reuse the value of the column that
2021** has already been loaded into a register. The value will always
2022** be used if it has not undergone any affinity changes. But if
2023** an affinity change has occurred, then the cached value will only be
2024** used if allowAffChng is true.
drh945498f2007-02-24 11:52:52 +00002025*/
drhe55cbd72008-03-31 23:48:03 +00002026int sqlite3ExprCodeGetColumn(
2027 Parse *pParse, /* Parsing and code generating context */
drh2133d822008-01-03 18:44:59 +00002028 Table *pTab, /* Description of the table we are reading from */
2029 int iColumn, /* Index of the table column */
2030 int iTable, /* The cursor pointing to the table */
drhda250ea2008-04-01 05:07:14 +00002031 int iReg, /* Store results here */
2032 int allowAffChng /* True if prior affinity changes are OK */
drh2133d822008-01-03 18:44:59 +00002033){
drhe55cbd72008-03-31 23:48:03 +00002034 Vdbe *v = pParse->pVdbe;
2035 int i;
drhda250ea2008-04-01 05:07:14 +00002036 struct yColCache *p;
drhe55cbd72008-03-31 23:48:03 +00002037
drhda250ea2008-04-01 05:07:14 +00002038 for(i=0, p=pParse->aColCache; i<pParse->nColCache; i++, p++){
2039 if( p->iTable==iTable && p->iColumn==iColumn
2040 && (!p->affChange || allowAffChng) ){
drhe55cbd72008-03-31 23:48:03 +00002041#if 0
2042 sqlite3VdbeAddOp0(v, OP_Noop);
drhda250ea2008-04-01 05:07:14 +00002043 VdbeComment((v, "OPT: tab%d.col%d -> r%d", iTable, iColumn, p->iReg));
drhe55cbd72008-03-31 23:48:03 +00002044#endif
drhda250ea2008-04-01 05:07:14 +00002045 return p->iReg;
drhe55cbd72008-03-31 23:48:03 +00002046 }
2047 }
2048 assert( v!=0 );
drh945498f2007-02-24 11:52:52 +00002049 if( iColumn<0 ){
2050 int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
drh2133d822008-01-03 18:44:59 +00002051 sqlite3VdbeAddOp2(v, op, iTable, iReg);
drh945498f2007-02-24 11:52:52 +00002052 }else if( pTab==0 ){
drh2133d822008-01-03 18:44:59 +00002053 sqlite3VdbeAddOp3(v, OP_Column, iTable, iColumn, iReg);
drh945498f2007-02-24 11:52:52 +00002054 }else{
2055 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
drh2133d822008-01-03 18:44:59 +00002056 sqlite3VdbeAddOp3(v, op, iTable, iColumn, iReg);
drh945498f2007-02-24 11:52:52 +00002057 sqlite3ColumnDefault(v, pTab, iColumn);
2058#ifndef SQLITE_OMIT_FLOATING_POINT
2059 if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
drh2133d822008-01-03 18:44:59 +00002060 sqlite3VdbeAddOp1(v, OP_RealAffinity, iReg);
drh945498f2007-02-24 11:52:52 +00002061 }
2062#endif
2063 }
drhe55cbd72008-03-31 23:48:03 +00002064 if( pParse->disableColCache==0 ){
2065 i = pParse->iColCache;
drhda250ea2008-04-01 05:07:14 +00002066 p = &pParse->aColCache[i];
2067 p->iTable = iTable;
2068 p->iColumn = iColumn;
2069 p->iReg = iReg;
drhc5499be2008-04-01 15:06:33 +00002070 p->affChange = 0;
drhe55cbd72008-03-31 23:48:03 +00002071 i++;
drh2f7794c2008-04-01 03:27:39 +00002072 if( i>=ArraySize(pParse->aColCache) ) i = 0;
drhe55cbd72008-03-31 23:48:03 +00002073 if( i>pParse->nColCache ) pParse->nColCache = i;
drh2f7794c2008-04-01 03:27:39 +00002074 pParse->iColCache = i;
drhe55cbd72008-03-31 23:48:03 +00002075 }
2076 return iReg;
2077}
2078
2079/*
drhe55cbd72008-03-31 23:48:03 +00002080** Clear all column cache entries associated with the vdbe
2081** cursor with cursor number iTable.
2082*/
2083void sqlite3ExprClearColumnCache(Parse *pParse, int iTable){
2084 if( iTable<0 ){
2085 pParse->nColCache = 0;
2086 pParse->iColCache = 0;
2087 }else{
2088 int i;
2089 for(i=0; i<pParse->nColCache; i++){
2090 if( pParse->aColCache[i].iTable==iTable ){
drhc5499be2008-04-01 15:06:33 +00002091 testcase( i==pParse->nColCache-1 );
drhe55cbd72008-03-31 23:48:03 +00002092 pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
drhda250ea2008-04-01 05:07:14 +00002093 pParse->iColCache = pParse->nColCache;
drhe55cbd72008-03-31 23:48:03 +00002094 }
2095 }
drhe55cbd72008-03-31 23:48:03 +00002096 }
2097}
2098
2099/*
drhda250ea2008-04-01 05:07:14 +00002100** Record the fact that an affinity change has occurred on iCount
2101** registers starting with iStart.
drhe55cbd72008-03-31 23:48:03 +00002102*/
drhda250ea2008-04-01 05:07:14 +00002103void sqlite3ExprCacheAffinityChange(Parse *pParse, int iStart, int iCount){
2104 int iEnd = iStart + iCount - 1;
drhe55cbd72008-03-31 23:48:03 +00002105 int i;
2106 for(i=0; i<pParse->nColCache; i++){
2107 int r = pParse->aColCache[i].iReg;
drhda250ea2008-04-01 05:07:14 +00002108 if( r>=iStart && r<=iEnd ){
2109 pParse->aColCache[i].affChange = 1;
drhe55cbd72008-03-31 23:48:03 +00002110 }
2111 }
drhe55cbd72008-03-31 23:48:03 +00002112}
2113
2114/*
drhb21e7c72008-06-22 12:37:57 +00002115** Generate code to move content from registers iFrom...iFrom+nReg-1
2116** over to iTo..iTo+nReg-1. Keep the column cache up-to-date.
drhe55cbd72008-03-31 23:48:03 +00002117*/
drhb21e7c72008-06-22 12:37:57 +00002118void sqlite3ExprCodeMove(Parse *pParse, int iFrom, int iTo, int nReg){
drhe55cbd72008-03-31 23:48:03 +00002119 int i;
2120 if( iFrom==iTo ) return;
drhb21e7c72008-06-22 12:37:57 +00002121 sqlite3VdbeAddOp3(pParse->pVdbe, OP_Move, iFrom, iTo, nReg);
drhe55cbd72008-03-31 23:48:03 +00002122 for(i=0; i<pParse->nColCache; i++){
drhb21e7c72008-06-22 12:37:57 +00002123 int x = pParse->aColCache[i].iReg;
2124 if( x>=iFrom && x<iFrom+nReg ){
2125 pParse->aColCache[i].iReg += iTo-iFrom;
drhe55cbd72008-03-31 23:48:03 +00002126 }
2127 }
drh945498f2007-02-24 11:52:52 +00002128}
2129
drhfec19aa2004-05-19 20:41:03 +00002130/*
drh652fbf52008-04-01 01:42:41 +00002131** Return true if any register in the range iFrom..iTo (inclusive)
2132** is used as part of the column cache.
2133*/
2134static int usedAsColumnCache(Parse *pParse, int iFrom, int iTo){
2135 int i;
2136 for(i=0; i<pParse->nColCache; i++){
2137 int r = pParse->aColCache[i].iReg;
2138 if( r>=iFrom && r<=iTo ) return 1;
2139 }
2140 return 0;
2141}
2142
2143/*
2144** Theres is a value in register iCurrent. We ultimately want
2145** the value to be in register iTarget. It might be that
2146** iCurrent and iTarget are the same register.
2147**
2148** We are going to modify the value, so we need to make sure it
2149** is not a cached register. If iCurrent is a cached register,
2150** then try to move the value over to iTarget. If iTarget is a
2151** cached register, then clear the corresponding cache line.
2152**
2153** Return the register that the value ends up in.
2154*/
2155int sqlite3ExprWritableRegister(Parse *pParse, int iCurrent, int iTarget){
drhda250ea2008-04-01 05:07:14 +00002156 int i;
drh652fbf52008-04-01 01:42:41 +00002157 assert( pParse->pVdbe!=0 );
2158 if( !usedAsColumnCache(pParse, iCurrent, iCurrent) ){
2159 return iCurrent;
2160 }
drh2f7794c2008-04-01 03:27:39 +00002161 if( iCurrent!=iTarget ){
2162 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, iCurrent, iTarget);
2163 }
drhda250ea2008-04-01 05:07:14 +00002164 for(i=0; i<pParse->nColCache; i++){
2165 if( pParse->aColCache[i].iReg==iTarget ){
2166 pParse->aColCache[i] = pParse->aColCache[--pParse->nColCache];
2167 pParse->iColCache = pParse->nColCache;
2168 }
2169 }
drh652fbf52008-04-01 01:42:41 +00002170 return iTarget;
2171}
2172
2173/*
drh191b54c2008-04-15 12:14:21 +00002174** If the last instruction coded is an ephemeral copy of any of
2175** the registers in the nReg registers beginning with iReg, then
2176** convert the last instruction from OP_SCopy to OP_Copy.
2177*/
2178void sqlite3ExprHardCopy(Parse *pParse, int iReg, int nReg){
2179 int addr;
2180 VdbeOp *pOp;
2181 Vdbe *v;
2182
2183 v = pParse->pVdbe;
2184 addr = sqlite3VdbeCurrentAddr(v);
2185 pOp = sqlite3VdbeGetOp(v, addr-1);
danielk1977d7eb2ed2008-04-24 12:36:35 +00002186 assert( pOp || pParse->db->mallocFailed );
2187 if( pOp && pOp->opcode==OP_SCopy && pOp->p1>=iReg && pOp->p1<iReg+nReg ){
drh191b54c2008-04-15 12:14:21 +00002188 pOp->opcode = OP_Copy;
2189 }
2190}
2191
2192/*
drhcce7d172000-05-31 15:34:51 +00002193** Generate code into the current Vdbe to evaluate the given
drh2dcef112008-01-12 19:03:48 +00002194** expression. Attempt to store the results in register "target".
2195** Return the register where results are stored.
drh389a1ad2008-01-03 23:44:53 +00002196**
drh2dcef112008-01-12 19:03:48 +00002197** With this routine, there is no guaranteed that results will
2198** be stored in target. The result might be stored in some other
2199** register if it is convenient to do so. The calling function
2200** must check the return code and move the results to the desired
2201** register.
drhcce7d172000-05-31 15:34:51 +00002202*/
drh678ccce2008-03-31 18:19:54 +00002203int sqlite3ExprCodeTarget(Parse *pParse, Expr *pExpr, int target){
drh2dcef112008-01-12 19:03:48 +00002204 Vdbe *v = pParse->pVdbe; /* The VM under construction */
2205 int op; /* The opcode being coded */
2206 int inReg = target; /* Results stored in register inReg */
2207 int regFree1 = 0; /* If non-zero free this temporary register */
2208 int regFree2 = 0; /* If non-zero free this temporary register */
drh678ccce2008-03-31 18:19:54 +00002209 int r1, r2, r3, r4; /* Various register numbers */
drhffe07b22005-11-03 00:41:17 +00002210
drh389a1ad2008-01-03 23:44:53 +00002211 assert( v!=0 || pParse->db->mallocFailed );
drh9cbf3422008-01-17 16:22:13 +00002212 assert( target>0 && target<=pParse->nMem );
drh389a1ad2008-01-03 23:44:53 +00002213 if( v==0 ) return 0;
drh389a1ad2008-01-03 23:44:53 +00002214
2215 if( pExpr==0 ){
2216 op = TK_NULL;
2217 }else{
2218 op = pExpr->op;
2219 }
drhf2bc0132004-10-04 13:19:23 +00002220 switch( op ){
drh13449892005-09-07 21:22:45 +00002221 case TK_AGG_COLUMN: {
2222 AggInfo *pAggInfo = pExpr->pAggInfo;
2223 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
2224 if( !pAggInfo->directMode ){
drh9de221d2008-01-05 06:51:30 +00002225 assert( pCol->iMem>0 );
2226 inReg = pCol->iMem;
drh13449892005-09-07 21:22:45 +00002227 break;
2228 }else if( pAggInfo->useSortingIdx ){
drh389a1ad2008-01-03 23:44:53 +00002229 sqlite3VdbeAddOp3(v, OP_Column, pAggInfo->sortingIdx,
2230 pCol->iSorterColumn, target);
drh13449892005-09-07 21:22:45 +00002231 break;
2232 }
2233 /* Otherwise, fall thru into the TK_COLUMN case */
2234 }
drh967e8b72000-06-21 13:59:10 +00002235 case TK_COLUMN: {
drhffe07b22005-11-03 00:41:17 +00002236 if( pExpr->iTable<0 ){
2237 /* This only happens when coding check constraints */
drhaa9b8962008-01-08 02:57:55 +00002238 assert( pParse->ckBase>0 );
2239 inReg = pExpr->iColumn + pParse->ckBase;
drhc4a3c772001-04-04 11:48:57 +00002240 }else{
drhc5499be2008-04-01 15:06:33 +00002241 testcase( (pExpr->flags & EP_AnyAff)!=0 );
drhe55cbd72008-03-31 23:48:03 +00002242 inReg = sqlite3ExprCodeGetColumn(pParse, pExpr->pTab,
drhda250ea2008-04-01 05:07:14 +00002243 pExpr->iColumn, pExpr->iTable, target,
2244 pExpr->flags & EP_AnyAff);
drh22827922000-06-06 17:27:05 +00002245 }
drhcce7d172000-05-31 15:34:51 +00002246 break;
2247 }
2248 case TK_INTEGER: {
drh9de221d2008-01-05 06:51:30 +00002249 codeInteger(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
drhfec19aa2004-05-19 20:41:03 +00002250 break;
2251 }
drh598f1342007-10-23 15:39:45 +00002252 case TK_FLOAT: {
drh9de221d2008-01-05 06:51:30 +00002253 codeReal(v, (char*)pExpr->token.z, pExpr->token.n, 0, target);
drh598f1342007-10-23 15:39:45 +00002254 break;
2255 }
drhfec19aa2004-05-19 20:41:03 +00002256 case TK_STRING: {
danielk19771e536952007-08-16 10:09:01 +00002257 sqlite3DequoteExpr(pParse->db, pExpr);
drh9de221d2008-01-05 06:51:30 +00002258 sqlite3VdbeAddOp4(v,OP_String8, 0, target, 0,
drh66a51672008-01-03 00:01:23 +00002259 (char*)pExpr->token.z, pExpr->token.n);
drhcce7d172000-05-31 15:34:51 +00002260 break;
2261 }
drhf0863fe2005-06-12 21:35:51 +00002262 case TK_NULL: {
drh9de221d2008-01-05 06:51:30 +00002263 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drhf0863fe2005-06-12 21:35:51 +00002264 break;
2265 }
danielk19775338a5f2005-01-20 13:03:10 +00002266#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00002267 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00002268 int n;
2269 const char *z;
drhca48c902008-01-18 14:08:24 +00002270 char *zBlob;
2271 assert( pExpr->token.n>=3 );
2272 assert( pExpr->token.z[0]=='x' || pExpr->token.z[0]=='X' );
2273 assert( pExpr->token.z[1]=='\'' );
2274 assert( pExpr->token.z[pExpr->token.n-1]=='\'' );
drh6c8c6ce2005-08-23 11:17:58 +00002275 n = pExpr->token.n - 3;
drh2646da72005-12-09 20:02:05 +00002276 z = (char*)pExpr->token.z + 2;
drhca48c902008-01-18 14:08:24 +00002277 zBlob = sqlite3HexToBlob(sqlite3VdbeDb(v), z, n);
2278 sqlite3VdbeAddOp4(v, OP_Blob, n/2, target, 0, zBlob, P4_DYNAMIC);
danielk1977c572ef72004-05-27 09:28:41 +00002279 break;
2280 }
danielk19775338a5f2005-01-20 13:03:10 +00002281#endif
drh50457892003-09-06 01:10:47 +00002282 case TK_VARIABLE: {
drh9de221d2008-01-05 06:51:30 +00002283 sqlite3VdbeAddOp2(v, OP_Variable, pExpr->iTable, target);
drh895d7472004-08-20 16:02:39 +00002284 if( pExpr->token.n>1 ){
drh66a51672008-01-03 00:01:23 +00002285 sqlite3VdbeChangeP4(v, -1, (char*)pExpr->token.z, pExpr->token.n);
drh895d7472004-08-20 16:02:39 +00002286 }
drh50457892003-09-06 01:10:47 +00002287 break;
2288 }
drh4e0cff62004-11-05 05:10:28 +00002289 case TK_REGISTER: {
drh9de221d2008-01-05 06:51:30 +00002290 inReg = pExpr->iTable;
drh4e0cff62004-11-05 05:10:28 +00002291 break;
2292 }
drh487e2622005-06-25 18:42:14 +00002293#ifndef SQLITE_OMIT_CAST
2294 case TK_CAST: {
2295 /* Expressions of the form: CAST(pLeft AS token) */
danielk1977f0113002006-01-24 12:09:17 +00002296 int aff, to_op;
drh2dcef112008-01-12 19:03:48 +00002297 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drh8a512562005-11-14 22:29:05 +00002298 aff = sqlite3AffinityType(&pExpr->token);
danielk1977f0113002006-01-24 12:09:17 +00002299 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
2300 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
2301 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
2302 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
2303 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
2304 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
drhc5499be2008-04-01 15:06:33 +00002305 testcase( to_op==OP_ToText );
2306 testcase( to_op==OP_ToBlob );
2307 testcase( to_op==OP_ToNumeric );
2308 testcase( to_op==OP_ToInt );
2309 testcase( to_op==OP_ToReal );
drh2dcef112008-01-12 19:03:48 +00002310 sqlite3VdbeAddOp1(v, to_op, inReg);
drhc5499be2008-04-01 15:06:33 +00002311 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drhb3843a82008-04-01 12:24:11 +00002312 sqlite3ExprCacheAffinityChange(pParse, inReg, 1);
drh487e2622005-06-25 18:42:14 +00002313 break;
2314 }
2315#endif /* SQLITE_OMIT_CAST */
drhc9b84a12002-06-20 11:36:48 +00002316 case TK_LT:
2317 case TK_LE:
2318 case TK_GT:
2319 case TK_GE:
2320 case TK_NE:
2321 case TK_EQ: {
drhf2bc0132004-10-04 13:19:23 +00002322 assert( TK_LT==OP_Lt );
2323 assert( TK_LE==OP_Le );
2324 assert( TK_GT==OP_Gt );
2325 assert( TK_GE==OP_Ge );
2326 assert( TK_EQ==OP_Eq );
2327 assert( TK_NE==OP_Ne );
drhc5499be2008-04-01 15:06:33 +00002328 testcase( op==TK_LT );
2329 testcase( op==TK_LE );
2330 testcase( op==TK_GT );
2331 testcase( op==TK_GE );
2332 testcase( op==TK_EQ );
2333 testcase( op==TK_NE );
drhda250ea2008-04-01 05:07:14 +00002334 codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
2335 pExpr->pRight, &r2, &regFree2);
drh35573352008-01-08 23:54:25 +00002336 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
2337 r1, r2, inReg, SQLITE_STOREP2);
drhc5499be2008-04-01 15:06:33 +00002338 testcase( regFree1==0 );
2339 testcase( regFree2==0 );
danielk1977a37cdde2004-05-16 11:15:36 +00002340 break;
drhc9b84a12002-06-20 11:36:48 +00002341 }
drhcce7d172000-05-31 15:34:51 +00002342 case TK_AND:
2343 case TK_OR:
2344 case TK_PLUS:
2345 case TK_STAR:
2346 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00002347 case TK_REM:
2348 case TK_BITAND:
2349 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00002350 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00002351 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00002352 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00002353 case TK_CONCAT: {
drhf2bc0132004-10-04 13:19:23 +00002354 assert( TK_AND==OP_And );
2355 assert( TK_OR==OP_Or );
2356 assert( TK_PLUS==OP_Add );
2357 assert( TK_MINUS==OP_Subtract );
2358 assert( TK_REM==OP_Remainder );
2359 assert( TK_BITAND==OP_BitAnd );
2360 assert( TK_BITOR==OP_BitOr );
2361 assert( TK_SLASH==OP_Divide );
2362 assert( TK_LSHIFT==OP_ShiftLeft );
2363 assert( TK_RSHIFT==OP_ShiftRight );
2364 assert( TK_CONCAT==OP_Concat );
drhc5499be2008-04-01 15:06:33 +00002365 testcase( op==TK_AND );
2366 testcase( op==TK_OR );
2367 testcase( op==TK_PLUS );
2368 testcase( op==TK_MINUS );
2369 testcase( op==TK_REM );
2370 testcase( op==TK_BITAND );
2371 testcase( op==TK_BITOR );
2372 testcase( op==TK_SLASH );
2373 testcase( op==TK_LSHIFT );
2374 testcase( op==TK_RSHIFT );
2375 testcase( op==TK_CONCAT );
drh2dcef112008-01-12 19:03:48 +00002376 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2377 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pRight, &regFree2);
drh5b6afba2008-01-05 16:29:28 +00002378 sqlite3VdbeAddOp3(v, op, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00002379 testcase( regFree1==0 );
2380 testcase( regFree2==0 );
drh00400772000-06-16 20:51:26 +00002381 break;
2382 }
drhcce7d172000-05-31 15:34:51 +00002383 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00002384 Expr *pLeft = pExpr->pLeft;
2385 assert( pLeft );
2386 if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
2387 Token *p = &pLeft->token;
drhfec19aa2004-05-19 20:41:03 +00002388 if( pLeft->op==TK_FLOAT ){
drh9de221d2008-01-05 06:51:30 +00002389 codeReal(v, (char*)p->z, p->n, 1, target);
drhe6840902002-03-06 03:08:25 +00002390 }else{
drh9de221d2008-01-05 06:51:30 +00002391 codeInteger(v, (char*)p->z, p->n, 1, target);
drhe6840902002-03-06 03:08:25 +00002392 }
drh3c84ddf2008-01-09 02:15:38 +00002393 }else{
drh2dcef112008-01-12 19:03:48 +00002394 regFree1 = r1 = sqlite3GetTempReg(pParse);
drh3c84ddf2008-01-09 02:15:38 +00002395 sqlite3VdbeAddOp2(v, OP_Integer, 0, r1);
drhe55cbd72008-03-31 23:48:03 +00002396 r2 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree2);
drh2dcef112008-01-12 19:03:48 +00002397 sqlite3VdbeAddOp3(v, OP_Subtract, r2, r1, target);
drhc5499be2008-04-01 15:06:33 +00002398 testcase( regFree2==0 );
drh6e142f52000-06-08 13:36:40 +00002399 }
drh3c84ddf2008-01-09 02:15:38 +00002400 inReg = target;
2401 break;
drh6e142f52000-06-08 13:36:40 +00002402 }
drhbf4133c2001-10-13 02:59:08 +00002403 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00002404 case TK_NOT: {
drhf2bc0132004-10-04 13:19:23 +00002405 assert( TK_BITNOT==OP_BitNot );
2406 assert( TK_NOT==OP_Not );
drhc5499be2008-04-01 15:06:33 +00002407 testcase( op==TK_BITNOT );
2408 testcase( op==TK_NOT );
drh2dcef112008-01-12 19:03:48 +00002409 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drhc5499be2008-04-01 15:06:33 +00002410 testcase( inReg==target );
2411 testcase( usedAsColumnCache(pParse, inReg, inReg) );
drh652fbf52008-04-01 01:42:41 +00002412 inReg = sqlite3ExprWritableRegister(pParse, inReg, target);
drh2dcef112008-01-12 19:03:48 +00002413 sqlite3VdbeAddOp1(v, op, inReg);
drhcce7d172000-05-31 15:34:51 +00002414 break;
2415 }
2416 case TK_ISNULL:
2417 case TK_NOTNULL: {
drh6a288a32008-01-07 19:20:24 +00002418 int addr;
drhf2bc0132004-10-04 13:19:23 +00002419 assert( TK_ISNULL==OP_IsNull );
2420 assert( TK_NOTNULL==OP_NotNull );
drhc5499be2008-04-01 15:06:33 +00002421 testcase( op==TK_ISNULL );
2422 testcase( op==TK_NOTNULL );
drh9de221d2008-01-05 06:51:30 +00002423 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
drh2dcef112008-01-12 19:03:48 +00002424 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00002425 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00002426 addr = sqlite3VdbeAddOp1(v, op, r1);
drh9de221d2008-01-05 06:51:30 +00002427 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
drh6a288a32008-01-07 19:20:24 +00002428 sqlite3VdbeJumpHere(v, addr);
drhf2bc0132004-10-04 13:19:23 +00002429 break;
drhcce7d172000-05-31 15:34:51 +00002430 }
drh22827922000-06-06 17:27:05 +00002431 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00002432 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00002433 if( pInfo==0 ){
2434 sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
2435 &pExpr->span);
2436 }else{
drh9de221d2008-01-05 06:51:30 +00002437 inReg = pInfo->aFunc[pExpr->iAgg].iMem;
drh7e56e712005-11-16 12:53:15 +00002438 }
drh22827922000-06-06 17:27:05 +00002439 break;
2440 }
drhb71090f2005-05-23 17:26:51 +00002441 case TK_CONST_FUNC:
drhcce7d172000-05-31 15:34:51 +00002442 case TK_FUNCTION: {
drhcce7d172000-05-31 15:34:51 +00002443 ExprList *pList = pExpr->pList;
drh89425d52002-02-28 03:04:48 +00002444 int nExpr = pList ? pList->nExpr : 0;
drh0bce8352002-02-28 00:41:10 +00002445 FuncDef *pDef;
drh4b59ab52002-08-24 18:24:51 +00002446 int nId;
2447 const char *zId;
drh13449892005-09-07 21:22:45 +00002448 int constMask = 0;
danielk1977682f68b2004-06-05 10:22:17 +00002449 int i;
drh17435752007-08-16 04:30:38 +00002450 sqlite3 *db = pParse->db;
2451 u8 enc = ENC(db);
danielk1977dc1bdc42004-06-11 10:51:27 +00002452 CollSeq *pColl = 0;
drh17435752007-08-16 04:30:38 +00002453
drhc5499be2008-04-01 15:06:33 +00002454 testcase( op==TK_CONST_FUNC );
2455 testcase( op==TK_FUNCTION );
drh2646da72005-12-09 20:02:05 +00002456 zId = (char*)pExpr->token.z;
drhb71090f2005-05-23 17:26:51 +00002457 nId = pExpr->token.n;
danielk1977d8123362004-06-12 09:25:12 +00002458 pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
drh0bce8352002-02-28 00:41:10 +00002459 assert( pDef!=0 );
drh892d3172008-01-10 03:46:36 +00002460 if( pList ){
2461 nExpr = pList->nExpr;
drh2dcef112008-01-12 19:03:48 +00002462 r1 = sqlite3GetTempRange(pParse, nExpr);
drh191b54c2008-04-15 12:14:21 +00002463 sqlite3ExprCodeExprList(pParse, pList, r1, 1);
drh892d3172008-01-10 03:46:36 +00002464 }else{
drhd847eaa2008-01-17 17:15:56 +00002465 nExpr = r1 = 0;
drh892d3172008-01-10 03:46:36 +00002466 }
drhb7f6f682006-07-08 17:06:43 +00002467#ifndef SQLITE_OMIT_VIRTUALTABLE
drha43fa222006-07-08 18:41:37 +00002468 /* Possibly overload the function if the first argument is
2469 ** a virtual table column.
2470 **
2471 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
2472 ** second argument, not the first, as the argument to test to
2473 ** see if it is a column in a virtual table. This is done because
2474 ** the left operand of infix functions (the operand we want to
2475 ** control overloading) ends up as the second argument to the
2476 ** function. The expression "A glob B" is equivalent to
2477 ** "glob(B,A). We want to use the A in "A glob B" to test
2478 ** for function overloading. But we use the B term in "glob(B,A)".
2479 */
drh6a03a1c2006-07-08 18:34:59 +00002480 if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
drh17435752007-08-16 04:30:38 +00002481 pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[1].pExpr);
drh6a03a1c2006-07-08 18:34:59 +00002482 }else if( nExpr>0 ){
drh17435752007-08-16 04:30:38 +00002483 pDef = sqlite3VtabOverloadFunction(db, pDef, nExpr, pList->a[0].pExpr);
drhb7f6f682006-07-08 17:06:43 +00002484 }
2485#endif
danielk1977682f68b2004-06-05 10:22:17 +00002486 for(i=0; i<nExpr && i<32; i++){
danielk1977d02eb1f2004-06-06 09:44:03 +00002487 if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
drh13449892005-09-07 21:22:45 +00002488 constMask |= (1<<i);
danielk1977d02eb1f2004-06-06 09:44:03 +00002489 }
danielk1977dc1bdc42004-06-11 10:51:27 +00002490 if( pDef->needCollSeq && !pColl ){
2491 pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
2492 }
2493 }
2494 if( pDef->needCollSeq ){
2495 if( !pColl ) pColl = pParse->db->pDfltColl;
drh66a51672008-01-03 00:01:23 +00002496 sqlite3VdbeAddOp4(v, OP_CollSeq, 0, 0, 0, (char *)pColl, P4_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00002497 }
drh2dcef112008-01-12 19:03:48 +00002498 sqlite3VdbeAddOp4(v, OP_Function, constMask, r1, target,
drh66a51672008-01-03 00:01:23 +00002499 (char*)pDef, P4_FUNCDEF);
drh98757152008-01-09 23:04:12 +00002500 sqlite3VdbeChangeP5(v, nExpr);
drh2dcef112008-01-12 19:03:48 +00002501 if( nExpr ){
2502 sqlite3ReleaseTempRange(pParse, r1, nExpr);
2503 }
drhda250ea2008-04-01 05:07:14 +00002504 sqlite3ExprCacheAffinityChange(pParse, r1, nExpr);
drhcce7d172000-05-31 15:34:51 +00002505 break;
2506 }
drhfe2093d2005-01-20 22:48:47 +00002507#ifndef SQLITE_OMIT_SUBQUERY
2508 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00002509 case TK_SELECT: {
drhc5499be2008-04-01 15:06:33 +00002510 testcase( op==TK_EXISTS );
2511 testcase( op==TK_SELECT );
drh41714d62006-03-02 04:44:23 +00002512 if( pExpr->iColumn==0 ){
2513 sqlite3CodeSubselect(pParse, pExpr);
2514 }
drh9de221d2008-01-05 06:51:30 +00002515 inReg = pExpr->iColumn;
drh19a775c2000-06-05 18:54:46 +00002516 break;
2517 }
drhfef52082000-06-06 01:50:43 +00002518 case TK_IN: {
drh6a288a32008-01-07 19:20:24 +00002519 int j1, j2, j3, j4, j5;
drh94a11212004-09-25 13:12:14 +00002520 char affinity;
danielk19779a96b662007-11-29 17:05:18 +00002521 int eType;
danielk19779a96b662007-11-29 17:05:18 +00002522
2523 eType = sqlite3FindInIndex(pParse, pExpr, 0);
danielk1977e014a832004-05-17 10:48:57 +00002524
2525 /* Figure out the affinity to use to create a key from the results
2526 ** of the expression. affinityStr stores a static string suitable for
drh66a51672008-01-03 00:01:23 +00002527 ** P4 of OP_MakeRecord.
danielk1977e014a832004-05-17 10:48:57 +00002528 */
drh94a11212004-09-25 13:12:14 +00002529 affinity = comparisonAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +00002530
drh2dcef112008-01-12 19:03:48 +00002531 sqlite3VdbeAddOp2(v, OP_Integer, 1, target);
danielk1977e014a832004-05-17 10:48:57 +00002532
2533 /* Code the <expr> from "<expr> IN (...)". The temporary table
2534 ** pExpr->iTable contains the values that make up the (...) set.
2535 */
drh2dcef112008-01-12 19:03:48 +00002536 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
drhc5499be2008-04-01 15:06:33 +00002537 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00002538 j1 = sqlite3VdbeAddOp1(v, OP_NotNull, r1);
2539 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh6a288a32008-01-07 19:20:24 +00002540 j2 = sqlite3VdbeAddOp0(v, OP_Goto);
2541 sqlite3VdbeJumpHere(v, j1);
danielk19779a96b662007-11-29 17:05:18 +00002542 if( eType==IN_INDEX_ROWID ){
drh678ccce2008-03-31 18:19:54 +00002543 j3 = sqlite3VdbeAddOp1(v, OP_MustBeInt, r1);
drh2dcef112008-01-12 19:03:48 +00002544 j4 = sqlite3VdbeAddOp3(v, OP_NotExists, pExpr->iTable, 0, r1);
drh6a288a32008-01-07 19:20:24 +00002545 j5 = sqlite3VdbeAddOp0(v, OP_Goto);
2546 sqlite3VdbeJumpHere(v, j3);
2547 sqlite3VdbeJumpHere(v, j4);
danielk19779a96b662007-11-29 17:05:18 +00002548 }else{
drh2dcef112008-01-12 19:03:48 +00002549 r2 = regFree2 = sqlite3GetTempReg(pParse);
drh1db639c2008-01-17 02:36:28 +00002550 sqlite3VdbeAddOp4(v, OP_MakeRecord, r1, 1, r2, &affinity, 1);
drhda250ea2008-04-01 05:07:14 +00002551 sqlite3ExprCacheAffinityChange(pParse, r1, 1);
drh2dcef112008-01-12 19:03:48 +00002552 j5 = sqlite3VdbeAddOp3(v, OP_Found, pExpr->iTable, 0, r2);
danielk19779a96b662007-11-29 17:05:18 +00002553 }
drh2dcef112008-01-12 19:03:48 +00002554 sqlite3VdbeAddOp2(v, OP_AddImm, target, -1);
drh6a288a32008-01-07 19:20:24 +00002555 sqlite3VdbeJumpHere(v, j2);
2556 sqlite3VdbeJumpHere(v, j5);
drhfef52082000-06-06 01:50:43 +00002557 break;
2558 }
danielk197793758c82005-01-21 08:13:14 +00002559#endif
drh2dcef112008-01-12 19:03:48 +00002560 /*
2561 ** x BETWEEN y AND z
2562 **
2563 ** This is equivalent to
2564 **
2565 ** x>=y AND x<=z
2566 **
2567 ** X is stored in pExpr->pLeft.
2568 ** Y is stored in pExpr->pList->a[0].pExpr.
2569 ** Z is stored in pExpr->pList->a[1].pExpr.
2570 */
drhfef52082000-06-06 01:50:43 +00002571 case TK_BETWEEN: {
drhbe5c89a2004-07-26 00:31:09 +00002572 Expr *pLeft = pExpr->pLeft;
2573 struct ExprList_item *pLItem = pExpr->pList->a;
2574 Expr *pRight = pLItem->pExpr;
drh35573352008-01-08 23:54:25 +00002575
drhda250ea2008-04-01 05:07:14 +00002576 codeCompareOperands(pParse, pLeft, &r1, &regFree1,
2577 pRight, &r2, &regFree2);
drhc5499be2008-04-01 15:06:33 +00002578 testcase( regFree1==0 );
2579 testcase( regFree2==0 );
drh2dcef112008-01-12 19:03:48 +00002580 r3 = sqlite3GetTempReg(pParse);
drh678ccce2008-03-31 18:19:54 +00002581 r4 = sqlite3GetTempReg(pParse);
drh35573352008-01-08 23:54:25 +00002582 codeCompare(pParse, pLeft, pRight, OP_Ge,
2583 r1, r2, r3, SQLITE_STOREP2);
drhbe5c89a2004-07-26 00:31:09 +00002584 pLItem++;
2585 pRight = pLItem->pExpr;
drh2dcef112008-01-12 19:03:48 +00002586 sqlite3ReleaseTempReg(pParse, regFree2);
2587 r2 = sqlite3ExprCodeTemp(pParse, pRight, &regFree2);
drhc5499be2008-04-01 15:06:33 +00002588 testcase( regFree2==0 );
drh678ccce2008-03-31 18:19:54 +00002589 codeCompare(pParse, pLeft, pRight, OP_Le, r1, r2, r4, SQLITE_STOREP2);
2590 sqlite3VdbeAddOp3(v, OP_And, r3, r4, target);
drh2dcef112008-01-12 19:03:48 +00002591 sqlite3ReleaseTempReg(pParse, r3);
drh678ccce2008-03-31 18:19:54 +00002592 sqlite3ReleaseTempReg(pParse, r4);
drhfef52082000-06-06 01:50:43 +00002593 break;
2594 }
drh4f07e5f2007-05-14 11:34:46 +00002595 case TK_UPLUS: {
drh2dcef112008-01-12 19:03:48 +00002596 inReg = sqlite3ExprCodeTarget(pParse, pExpr->pLeft, target);
drha2e00042002-01-22 03:13:42 +00002597 break;
2598 }
drh2dcef112008-01-12 19:03:48 +00002599
2600 /*
2601 ** Form A:
2602 ** CASE x WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2603 **
2604 ** Form B:
2605 ** CASE WHEN e1 THEN r1 WHEN e2 THEN r2 ... WHEN eN THEN rN ELSE y END
2606 **
2607 ** Form A is can be transformed into the equivalent form B as follows:
2608 ** CASE WHEN x=e1 THEN r1 WHEN x=e2 THEN r2 ...
2609 ** WHEN x=eN THEN rN ELSE y END
2610 **
2611 ** X (if it exists) is in pExpr->pLeft.
2612 ** Y is in pExpr->pRight. The Y is also optional. If there is no
2613 ** ELSE clause and no other term matches, then the result of the
2614 ** exprssion is NULL.
2615 ** Ei is in pExpr->pList->a[i*2] and Ri is pExpr->pList->a[i*2+1].
2616 **
2617 ** The result of the expression is the Ri for the first matching Ei,
2618 ** or if there is no matching Ei, the ELSE term Y, or if there is
2619 ** no ELSE term, NULL.
2620 */
drh17a7f8d2002-03-24 13:13:27 +00002621 case TK_CASE: {
drh2dcef112008-01-12 19:03:48 +00002622 int endLabel; /* GOTO label for end of CASE stmt */
2623 int nextCase; /* GOTO label for next WHEN clause */
2624 int nExpr; /* 2x number of WHEN terms */
2625 int i; /* Loop counter */
2626 ExprList *pEList; /* List of WHEN terms */
2627 struct ExprList_item *aListelem; /* Array of WHEN terms */
2628 Expr opCompare; /* The X==Ei expression */
2629 Expr cacheX; /* Cached expression X */
2630 Expr *pX; /* The X expression */
2631 Expr *pTest; /* X==Ei (form A) or just Ei (form B) */
drh17a7f8d2002-03-24 13:13:27 +00002632
2633 assert(pExpr->pList);
2634 assert((pExpr->pList->nExpr % 2) == 0);
2635 assert(pExpr->pList->nExpr > 0);
drhbe5c89a2004-07-26 00:31:09 +00002636 pEList = pExpr->pList;
2637 aListelem = pEList->a;
2638 nExpr = pEList->nExpr;
drh2dcef112008-01-12 19:03:48 +00002639 endLabel = sqlite3VdbeMakeLabel(v);
2640 if( (pX = pExpr->pLeft)!=0 ){
2641 cacheX = *pX;
drhc5499be2008-04-01 15:06:33 +00002642 testcase( pX->op==TK_COLUMN || pX->op==TK_REGISTER );
drh2dcef112008-01-12 19:03:48 +00002643 cacheX.iTable = sqlite3ExprCodeTemp(pParse, pX, &regFree1);
drhc5499be2008-04-01 15:06:33 +00002644 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00002645 cacheX.op = TK_REGISTER;
drh678ccce2008-03-31 18:19:54 +00002646 cacheX.iColumn = 0;
drh2dcef112008-01-12 19:03:48 +00002647 opCompare.op = TK_EQ;
2648 opCompare.pLeft = &cacheX;
2649 pTest = &opCompare;
drh17a7f8d2002-03-24 13:13:27 +00002650 }
drhc5499be2008-04-01 15:06:33 +00002651 pParse->disableColCache++;
drhf5905aa2002-05-26 20:54:33 +00002652 for(i=0; i<nExpr; i=i+2){
drh2dcef112008-01-12 19:03:48 +00002653 if( pX ){
2654 opCompare.pRight = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00002655 }else{
drh2dcef112008-01-12 19:03:48 +00002656 pTest = aListelem[i].pExpr;
drh17a7f8d2002-03-24 13:13:27 +00002657 }
drh2dcef112008-01-12 19:03:48 +00002658 nextCase = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00002659 testcase( pTest->op==TK_COLUMN || pTest->op==TK_REGISTER );
drh2dcef112008-01-12 19:03:48 +00002660 sqlite3ExprIfFalse(pParse, pTest, nextCase, SQLITE_JUMPIFNULL);
drhc5499be2008-04-01 15:06:33 +00002661 testcase( aListelem[i+1].pExpr->op==TK_COLUMN );
2662 testcase( aListelem[i+1].pExpr->op==TK_REGISTER );
drh9de221d2008-01-05 06:51:30 +00002663 sqlite3ExprCode(pParse, aListelem[i+1].pExpr, target);
drh2dcef112008-01-12 19:03:48 +00002664 sqlite3VdbeAddOp2(v, OP_Goto, 0, endLabel);
2665 sqlite3VdbeResolveLabel(v, nextCase);
drhf570f012002-05-31 15:51:25 +00002666 }
drh17a7f8d2002-03-24 13:13:27 +00002667 if( pExpr->pRight ){
drh9de221d2008-01-05 06:51:30 +00002668 sqlite3ExprCode(pParse, pExpr->pRight, target);
drh17a7f8d2002-03-24 13:13:27 +00002669 }else{
drh9de221d2008-01-05 06:51:30 +00002670 sqlite3VdbeAddOp2(v, OP_Null, 0, target);
drh17a7f8d2002-03-24 13:13:27 +00002671 }
drh2dcef112008-01-12 19:03:48 +00002672 sqlite3VdbeResolveLabel(v, endLabel);
drhc5499be2008-04-01 15:06:33 +00002673 assert( pParse->disableColCache>0 );
2674 pParse->disableColCache--;
danielk19776f349032002-06-11 02:25:40 +00002675 break;
2676 }
danielk19775338a5f2005-01-20 13:03:10 +00002677#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00002678 case TK_RAISE: {
2679 if( !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +00002680 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00002681 "RAISE() may only be used within a trigger-program");
drh389a1ad2008-01-03 23:44:53 +00002682 return 0;
danielk19776f349032002-06-11 02:25:40 +00002683 }
drhad6d9462004-09-19 02:15:24 +00002684 if( pExpr->iColumn!=OE_Ignore ){
2685 assert( pExpr->iColumn==OE_Rollback ||
2686 pExpr->iColumn == OE_Abort ||
2687 pExpr->iColumn == OE_Fail );
danielk19771e536952007-08-16 10:09:01 +00002688 sqlite3DequoteExpr(pParse->db, pExpr);
drh66a51672008-01-03 00:01:23 +00002689 sqlite3VdbeAddOp4(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn, 0,
drh2646da72005-12-09 20:02:05 +00002690 (char*)pExpr->token.z, pExpr->token.n);
danielk19776f349032002-06-11 02:25:40 +00002691 } else {
drhad6d9462004-09-19 02:15:24 +00002692 assert( pExpr->iColumn == OE_Ignore );
drh66a51672008-01-03 00:01:23 +00002693 sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
2694 sqlite3VdbeAddOp2(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
drhd4e70eb2008-01-02 00:34:36 +00002695 VdbeComment((v, "raise(IGNORE)"));
danielk19776f349032002-06-11 02:25:40 +00002696 }
drhffe07b22005-11-03 00:41:17 +00002697 break;
drh17a7f8d2002-03-24 13:13:27 +00002698 }
danielk19775338a5f2005-01-20 13:03:10 +00002699#endif
drhffe07b22005-11-03 00:41:17 +00002700 }
drh2dcef112008-01-12 19:03:48 +00002701 sqlite3ReleaseTempReg(pParse, regFree1);
2702 sqlite3ReleaseTempReg(pParse, regFree2);
2703 return inReg;
2704}
2705
2706/*
2707** Generate code to evaluate an expression and store the results
2708** into a register. Return the register number where the results
2709** are stored.
2710**
2711** If the register is a temporary register that can be deallocated,
drh678ccce2008-03-31 18:19:54 +00002712** then write its number into *pReg. If the result register is not
drh2dcef112008-01-12 19:03:48 +00002713** a temporary, then set *pReg to zero.
2714*/
2715int sqlite3ExprCodeTemp(Parse *pParse, Expr *pExpr, int *pReg){
2716 int r1 = sqlite3GetTempReg(pParse);
2717 int r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
2718 if( r2==r1 ){
2719 *pReg = r1;
2720 }else{
2721 sqlite3ReleaseTempReg(pParse, r1);
2722 *pReg = 0;
2723 }
2724 return r2;
2725}
2726
2727/*
2728** Generate code that will evaluate expression pExpr and store the
2729** results in register target. The results are guaranteed to appear
2730** in register target.
2731*/
2732int sqlite3ExprCode(Parse *pParse, Expr *pExpr, int target){
drh9cbf3422008-01-17 16:22:13 +00002733 int inReg;
2734
2735 assert( target>0 && target<=pParse->nMem );
2736 inReg = sqlite3ExprCodeTarget(pParse, pExpr, target);
drh0e359b32008-01-13 19:02:11 +00002737 assert( pParse->pVdbe || pParse->db->mallocFailed );
2738 if( inReg!=target && pParse->pVdbe ){
drh9cbf3422008-01-17 16:22:13 +00002739 sqlite3VdbeAddOp2(pParse->pVdbe, OP_SCopy, inReg, target);
drhcce7d172000-05-31 15:34:51 +00002740 }
drh389a1ad2008-01-03 23:44:53 +00002741 return target;
drhcce7d172000-05-31 15:34:51 +00002742}
2743
2744/*
drh2dcef112008-01-12 19:03:48 +00002745** Generate code that evalutes the given expression and puts the result
drhde4fcfd2008-01-19 23:50:26 +00002746** in register target.
drh25303782004-12-07 15:41:48 +00002747**
drh2dcef112008-01-12 19:03:48 +00002748** Also make a copy of the expression results into another "cache" register
2749** and modify the expression so that the next time it is evaluated,
2750** the result is a copy of the cache register.
2751**
2752** This routine is used for expressions that are used multiple
2753** times. They are evaluated once and the results of the expression
2754** are reused.
drh25303782004-12-07 15:41:48 +00002755*/
drh2dcef112008-01-12 19:03:48 +00002756int sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr, int target){
drh25303782004-12-07 15:41:48 +00002757 Vdbe *v = pParse->pVdbe;
drh2dcef112008-01-12 19:03:48 +00002758 int inReg;
2759 inReg = sqlite3ExprCode(pParse, pExpr, target);
drhde4fcfd2008-01-19 23:50:26 +00002760 assert( target>0 );
drh2dcef112008-01-12 19:03:48 +00002761 if( pExpr->op!=TK_REGISTER ){
2762 int iMem;
drhde4fcfd2008-01-19 23:50:26 +00002763 iMem = ++pParse->nMem;
2764 sqlite3VdbeAddOp2(v, OP_Copy, inReg, iMem);
drh2dcef112008-01-12 19:03:48 +00002765 pExpr->iTable = iMem;
drh678ccce2008-03-31 18:19:54 +00002766 pExpr->iColumn = pExpr->op;
drh25303782004-12-07 15:41:48 +00002767 pExpr->op = TK_REGISTER;
2768 }
drh2dcef112008-01-12 19:03:48 +00002769 return inReg;
drh25303782004-12-07 15:41:48 +00002770}
drh2dcef112008-01-12 19:03:48 +00002771
drh678ccce2008-03-31 18:19:54 +00002772/*
drh47de9552008-04-01 18:04:11 +00002773** Return TRUE if pExpr is an constant expression that is appropriate
2774** for factoring out of a loop. Appropriate expressions are:
2775**
2776** * Any expression that evaluates to two or more opcodes.
2777**
2778** * Any OP_Integer, OP_Real, OP_String, OP_Blob, OP_Null,
2779** or OP_Variable that does not need to be placed in a
2780** specific register.
2781**
2782** There is no point in factoring out single-instruction constant
2783** expressions that need to be placed in a particular register.
2784** We could factor them out, but then we would end up adding an
2785** OP_SCopy instruction to move the value into the correct register
2786** later. We might as well just use the original instruction and
2787** avoid the OP_SCopy.
2788*/
2789static int isAppropriateForFactoring(Expr *p){
2790 if( !sqlite3ExprIsConstantNotJoin(p) ){
2791 return 0; /* Only constant expressions are appropriate for factoring */
2792 }
2793 if( (p->flags & EP_FixedDest)==0 ){
2794 return 1; /* Any constant without a fixed destination is appropriate */
2795 }
2796 while( p->op==TK_UPLUS ) p = p->pLeft;
2797 switch( p->op ){
2798#ifndef SQLITE_OMIT_BLOB_LITERAL
2799 case TK_BLOB:
2800#endif
2801 case TK_VARIABLE:
2802 case TK_INTEGER:
2803 case TK_FLOAT:
2804 case TK_NULL:
2805 case TK_STRING: {
2806 testcase( p->op==TK_BLOB );
2807 testcase( p->op==TK_VARIABLE );
2808 testcase( p->op==TK_INTEGER );
2809 testcase( p->op==TK_FLOAT );
2810 testcase( p->op==TK_NULL );
2811 testcase( p->op==TK_STRING );
2812 /* Single-instruction constants with a fixed destination are
2813 ** better done in-line. If we factor them, they will just end
2814 ** up generating an OP_SCopy to move the value to the destination
2815 ** register. */
2816 return 0;
2817 }
2818 case TK_UMINUS: {
2819 if( p->pLeft->op==TK_FLOAT || p->pLeft->op==TK_INTEGER ){
2820 return 0;
2821 }
2822 break;
2823 }
2824 default: {
2825 break;
2826 }
2827 }
2828 return 1;
2829}
2830
2831/*
2832** If pExpr is a constant expression that is appropriate for
2833** factoring out of a loop, then evaluate the expression
drh678ccce2008-03-31 18:19:54 +00002834** into a register and convert the expression into a TK_REGISTER
2835** expression.
2836*/
2837static int evalConstExpr(void *pArg, Expr *pExpr){
2838 Parse *pParse = (Parse*)pArg;
drh47de9552008-04-01 18:04:11 +00002839 switch( pExpr->op ){
2840 case TK_REGISTER: {
2841 return 1;
2842 }
2843 case TK_FUNCTION:
2844 case TK_AGG_FUNCTION:
2845 case TK_CONST_FUNC: {
2846 /* The arguments to a function have a fixed destination.
2847 ** Mark them this way to avoid generated unneeded OP_SCopy
2848 ** instructions.
2849 */
2850 ExprList *pList = pExpr->pList;
2851 if( pList ){
2852 int i = pList->nExpr;
2853 struct ExprList_item *pItem = pList->a;
2854 for(; i>0; i--, pItem++){
2855 if( pItem->pExpr ) pItem->pExpr->flags |= EP_FixedDest;
2856 }
2857 }
2858 break;
2859 }
drh678ccce2008-03-31 18:19:54 +00002860 }
drh47de9552008-04-01 18:04:11 +00002861 if( isAppropriateForFactoring(pExpr) ){
drh678ccce2008-03-31 18:19:54 +00002862 int r1 = ++pParse->nMem;
2863 int r2;
2864 r2 = sqlite3ExprCodeTarget(pParse, pExpr, r1);
drhc5499be2008-04-01 15:06:33 +00002865 if( r1!=r2 ) sqlite3ReleaseTempReg(pParse, r1);
drh678ccce2008-03-31 18:19:54 +00002866 pExpr->iColumn = pExpr->op;
2867 pExpr->op = TK_REGISTER;
2868 pExpr->iTable = r2;
2869 return 1;
2870 }
2871 return 0;
2872}
2873
2874/*
2875** Preevaluate constant subexpressions within pExpr and store the
2876** results in registers. Modify pExpr so that the constant subexpresions
2877** are TK_REGISTER opcodes that refer to the precomputed values.
2878*/
2879void sqlite3ExprCodeConstants(Parse *pParse, Expr *pExpr){
2880 walkExprTree(pExpr, evalConstExpr, pParse);
2881}
2882
drh25303782004-12-07 15:41:48 +00002883
2884/*
drh268380c2004-02-25 13:47:31 +00002885** Generate code that pushes the value of every element of the given
drh9cbf3422008-01-17 16:22:13 +00002886** expression list into a sequence of registers beginning at target.
drh268380c2004-02-25 13:47:31 +00002887**
drh892d3172008-01-10 03:46:36 +00002888** Return the number of elements evaluated.
drh268380c2004-02-25 13:47:31 +00002889*/
danielk19774adee202004-05-08 08:23:19 +00002890int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00002891 Parse *pParse, /* Parsing context */
drh389a1ad2008-01-03 23:44:53 +00002892 ExprList *pList, /* The expression list to be coded */
drh191b54c2008-04-15 12:14:21 +00002893 int target, /* Where to write results */
2894 int doHardCopy /* Call sqlite3ExprHardCopy on each element if true */
drh268380c2004-02-25 13:47:31 +00002895){
2896 struct ExprList_item *pItem;
drh9cbf3422008-01-17 16:22:13 +00002897 int i, n;
drh892d3172008-01-10 03:46:36 +00002898 assert( pList!=0 || pParse->db->mallocFailed );
2899 if( pList==0 ){
2900 return 0;
2901 }
drh9cbf3422008-01-17 16:22:13 +00002902 assert( target>0 );
drh268380c2004-02-25 13:47:31 +00002903 n = pList->nExpr;
drh191b54c2008-04-15 12:14:21 +00002904 for(pItem=pList->a, i=0; i<n; i++, pItem++){
2905 sqlite3ExprCode(pParse, pItem->pExpr, target+i);
2906 if( doHardCopy ) sqlite3ExprHardCopy(pParse, target, n);
drh268380c2004-02-25 13:47:31 +00002907 }
drhf9b596e2004-05-26 16:54:42 +00002908 return n;
drh268380c2004-02-25 13:47:31 +00002909}
2910
2911/*
drhcce7d172000-05-31 15:34:51 +00002912** Generate code for a boolean expression such that a jump is made
2913** to the label "dest" if the expression is true but execution
2914** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00002915**
2916** If the expression evaluates to NULL (neither true nor false), then
drh35573352008-01-08 23:54:25 +00002917** take the jump if the jumpIfNull flag is SQLITE_JUMPIFNULL.
drhf2bc0132004-10-04 13:19:23 +00002918**
2919** This code depends on the fact that certain token values (ex: TK_EQ)
2920** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2921** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
2922** the make process cause these values to align. Assert()s in the code
2923** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00002924*/
danielk19774adee202004-05-08 08:23:19 +00002925void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00002926 Vdbe *v = pParse->pVdbe;
2927 int op = 0;
drh2dcef112008-01-12 19:03:48 +00002928 int regFree1 = 0;
2929 int regFree2 = 0;
2930 int r1, r2;
2931
drh35573352008-01-08 23:54:25 +00002932 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
drhdaffd0e2001-04-11 14:28:42 +00002933 if( v==0 || pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00002934 op = pExpr->op;
2935 switch( op ){
drhcce7d172000-05-31 15:34:51 +00002936 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00002937 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00002938 testcase( jumpIfNull==0 );
2939 testcase( pParse->disableColCache==0 );
drh35573352008-01-08 23:54:25 +00002940 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2,jumpIfNull^SQLITE_JUMPIFNULL);
drhe55cbd72008-03-31 23:48:03 +00002941 pParse->disableColCache++;
danielk19774adee202004-05-08 08:23:19 +00002942 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhc5499be2008-04-01 15:06:33 +00002943 assert( pParse->disableColCache>0 );
drhe55cbd72008-03-31 23:48:03 +00002944 pParse->disableColCache--;
danielk19774adee202004-05-08 08:23:19 +00002945 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00002946 break;
2947 }
2948 case TK_OR: {
drhc5499be2008-04-01 15:06:33 +00002949 testcase( jumpIfNull==0 );
2950 testcase( pParse->disableColCache==0 );
danielk19774adee202004-05-08 08:23:19 +00002951 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhe55cbd72008-03-31 23:48:03 +00002952 pParse->disableColCache++;
danielk19774adee202004-05-08 08:23:19 +00002953 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhc5499be2008-04-01 15:06:33 +00002954 assert( pParse->disableColCache>0 );
drhe55cbd72008-03-31 23:48:03 +00002955 pParse->disableColCache--;
drhcce7d172000-05-31 15:34:51 +00002956 break;
2957 }
2958 case TK_NOT: {
drhc5499be2008-04-01 15:06:33 +00002959 testcase( jumpIfNull==0 );
danielk19774adee202004-05-08 08:23:19 +00002960 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00002961 break;
2962 }
2963 case TK_LT:
2964 case TK_LE:
2965 case TK_GT:
2966 case TK_GE:
2967 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00002968 case TK_EQ: {
drhf2bc0132004-10-04 13:19:23 +00002969 assert( TK_LT==OP_Lt );
2970 assert( TK_LE==OP_Le );
2971 assert( TK_GT==OP_Gt );
2972 assert( TK_GE==OP_Ge );
2973 assert( TK_EQ==OP_Eq );
2974 assert( TK_NE==OP_Ne );
drhc5499be2008-04-01 15:06:33 +00002975 testcase( op==TK_LT );
2976 testcase( op==TK_LE );
2977 testcase( op==TK_GT );
2978 testcase( op==TK_GE );
2979 testcase( op==TK_EQ );
2980 testcase( op==TK_NE );
2981 testcase( jumpIfNull==0 );
drhda250ea2008-04-01 05:07:14 +00002982 codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
2983 pExpr->pRight, &r2, &regFree2);
drh35573352008-01-08 23:54:25 +00002984 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00002985 r1, r2, dest, jumpIfNull);
drhc5499be2008-04-01 15:06:33 +00002986 testcase( regFree1==0 );
2987 testcase( regFree2==0 );
drhcce7d172000-05-31 15:34:51 +00002988 break;
2989 }
2990 case TK_ISNULL:
2991 case TK_NOTNULL: {
drhf2bc0132004-10-04 13:19:23 +00002992 assert( TK_ISNULL==OP_IsNull );
2993 assert( TK_NOTNULL==OP_NotNull );
drhc5499be2008-04-01 15:06:33 +00002994 testcase( op==TK_ISNULL );
2995 testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00002996 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
2997 sqlite3VdbeAddOp2(v, op, r1, dest);
drhc5499be2008-04-01 15:06:33 +00002998 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00002999 break;
3000 }
drhfef52082000-06-06 01:50:43 +00003001 case TK_BETWEEN: {
drh2dcef112008-01-12 19:03:48 +00003002 /* x BETWEEN y AND z
danielk19770202b292004-06-09 09:55:16 +00003003 **
drh2dcef112008-01-12 19:03:48 +00003004 ** Is equivalent to
3005 **
3006 ** x>=y AND x<=z
3007 **
3008 ** Code it as such, taking care to do the common subexpression
3009 ** elementation of x.
danielk19770202b292004-06-09 09:55:16 +00003010 */
drh2dcef112008-01-12 19:03:48 +00003011 Expr exprAnd;
3012 Expr compLeft;
3013 Expr compRight;
3014 Expr exprX;
danielk19770202b292004-06-09 09:55:16 +00003015
drh2dcef112008-01-12 19:03:48 +00003016 exprX = *pExpr->pLeft;
3017 exprAnd.op = TK_AND;
3018 exprAnd.pLeft = &compLeft;
3019 exprAnd.pRight = &compRight;
3020 compLeft.op = TK_GE;
3021 compLeft.pLeft = &exprX;
3022 compLeft.pRight = pExpr->pList->a[0].pExpr;
3023 compRight.op = TK_LE;
3024 compRight.pLeft = &exprX;
3025 compRight.pRight = pExpr->pList->a[1].pExpr;
3026 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003027 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003028 exprX.op = TK_REGISTER;
drhc5499be2008-04-01 15:06:33 +00003029 testcase( jumpIfNull==0 );
drh2dcef112008-01-12 19:03:48 +00003030 sqlite3ExprIfTrue(pParse, &exprAnd, dest, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00003031 break;
3032 }
drhcce7d172000-05-31 15:34:51 +00003033 default: {
drh2dcef112008-01-12 19:03:48 +00003034 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3035 sqlite3VdbeAddOp3(v, OP_If, r1, dest, jumpIfNull!=0);
drhc5499be2008-04-01 15:06:33 +00003036 testcase( regFree1==0 );
3037 testcase( jumpIfNull==0 );
drhcce7d172000-05-31 15:34:51 +00003038 break;
3039 }
3040 }
drh2dcef112008-01-12 19:03:48 +00003041 sqlite3ReleaseTempReg(pParse, regFree1);
3042 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00003043}
3044
3045/*
drh66b89c82000-11-28 20:47:17 +00003046** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00003047** to the label "dest" if the expression is false but execution
3048** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00003049**
3050** If the expression evaluates to NULL (neither true nor false) then
drh35573352008-01-08 23:54:25 +00003051** jump if jumpIfNull is SQLITE_JUMPIFNULL or fall through if jumpIfNull
3052** is 0.
drhcce7d172000-05-31 15:34:51 +00003053*/
danielk19774adee202004-05-08 08:23:19 +00003054void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00003055 Vdbe *v = pParse->pVdbe;
3056 int op = 0;
drh2dcef112008-01-12 19:03:48 +00003057 int regFree1 = 0;
3058 int regFree2 = 0;
3059 int r1, r2;
3060
drh35573352008-01-08 23:54:25 +00003061 assert( jumpIfNull==SQLITE_JUMPIFNULL || jumpIfNull==0 );
drhdaffd0e2001-04-11 14:28:42 +00003062 if( v==0 || pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00003063
3064 /* The value of pExpr->op and op are related as follows:
3065 **
3066 ** pExpr->op op
3067 ** --------- ----------
3068 ** TK_ISNULL OP_NotNull
3069 ** TK_NOTNULL OP_IsNull
3070 ** TK_NE OP_Eq
3071 ** TK_EQ OP_Ne
3072 ** TK_GT OP_Le
3073 ** TK_LE OP_Gt
3074 ** TK_GE OP_Lt
3075 ** TK_LT OP_Ge
3076 **
3077 ** For other values of pExpr->op, op is undefined and unused.
3078 ** The value of TK_ and OP_ constants are arranged such that we
3079 ** can compute the mapping above using the following expression.
3080 ** Assert()s verify that the computation is correct.
3081 */
3082 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
3083
3084 /* Verify correct alignment of TK_ and OP_ constants
3085 */
3086 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
3087 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
3088 assert( pExpr->op!=TK_NE || op==OP_Eq );
3089 assert( pExpr->op!=TK_EQ || op==OP_Ne );
3090 assert( pExpr->op!=TK_LT || op==OP_Ge );
3091 assert( pExpr->op!=TK_LE || op==OP_Gt );
3092 assert( pExpr->op!=TK_GT || op==OP_Le );
3093 assert( pExpr->op!=TK_GE || op==OP_Lt );
3094
drhcce7d172000-05-31 15:34:51 +00003095 switch( pExpr->op ){
3096 case TK_AND: {
drhc5499be2008-04-01 15:06:33 +00003097 testcase( jumpIfNull==0 );
3098 testcase( pParse->disableColCache==0 );
danielk19774adee202004-05-08 08:23:19 +00003099 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhe55cbd72008-03-31 23:48:03 +00003100 pParse->disableColCache++;
danielk19774adee202004-05-08 08:23:19 +00003101 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhc5499be2008-04-01 15:06:33 +00003102 assert( pParse->disableColCache>0 );
drhe55cbd72008-03-31 23:48:03 +00003103 pParse->disableColCache--;
drhcce7d172000-05-31 15:34:51 +00003104 break;
3105 }
3106 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00003107 int d2 = sqlite3VdbeMakeLabel(v);
drhc5499be2008-04-01 15:06:33 +00003108 testcase( jumpIfNull==0 );
3109 testcase( pParse->disableColCache==0 );
drh35573352008-01-08 23:54:25 +00003110 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, jumpIfNull^SQLITE_JUMPIFNULL);
drhe55cbd72008-03-31 23:48:03 +00003111 pParse->disableColCache++;
danielk19774adee202004-05-08 08:23:19 +00003112 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhc5499be2008-04-01 15:06:33 +00003113 assert( pParse->disableColCache>0 );
drhe55cbd72008-03-31 23:48:03 +00003114 pParse->disableColCache--;
danielk19774adee202004-05-08 08:23:19 +00003115 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00003116 break;
3117 }
3118 case TK_NOT: {
danielk19774adee202004-05-08 08:23:19 +00003119 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00003120 break;
3121 }
3122 case TK_LT:
3123 case TK_LE:
3124 case TK_GT:
3125 case TK_GE:
3126 case TK_NE:
3127 case TK_EQ: {
drhc5499be2008-04-01 15:06:33 +00003128 testcase( op==TK_LT );
3129 testcase( op==TK_LE );
3130 testcase( op==TK_GT );
3131 testcase( op==TK_GE );
3132 testcase( op==TK_EQ );
3133 testcase( op==TK_NE );
3134 testcase( jumpIfNull==0 );
drhda250ea2008-04-01 05:07:14 +00003135 codeCompareOperands(pParse, pExpr->pLeft, &r1, &regFree1,
3136 pExpr->pRight, &r2, &regFree2);
drh35573352008-01-08 23:54:25 +00003137 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op,
drh2dcef112008-01-12 19:03:48 +00003138 r1, r2, dest, jumpIfNull);
drhc5499be2008-04-01 15:06:33 +00003139 testcase( regFree1==0 );
3140 testcase( regFree2==0 );
drhcce7d172000-05-31 15:34:51 +00003141 break;
3142 }
drhcce7d172000-05-31 15:34:51 +00003143 case TK_ISNULL:
3144 case TK_NOTNULL: {
drhc5499be2008-04-01 15:06:33 +00003145 testcase( op==TK_ISNULL );
3146 testcase( op==TK_NOTNULL );
drh2dcef112008-01-12 19:03:48 +00003147 r1 = sqlite3ExprCodeTemp(pParse, pExpr->pLeft, &regFree1);
3148 sqlite3VdbeAddOp2(v, op, r1, dest);
drhc5499be2008-04-01 15:06:33 +00003149 testcase( regFree1==0 );
drhcce7d172000-05-31 15:34:51 +00003150 break;
3151 }
drhfef52082000-06-06 01:50:43 +00003152 case TK_BETWEEN: {
drh2dcef112008-01-12 19:03:48 +00003153 /* x BETWEEN y AND z
danielk19770202b292004-06-09 09:55:16 +00003154 **
drh2dcef112008-01-12 19:03:48 +00003155 ** Is equivalent to
3156 **
3157 ** x>=y AND x<=z
3158 **
3159 ** Code it as such, taking care to do the common subexpression
3160 ** elementation of x.
danielk19770202b292004-06-09 09:55:16 +00003161 */
drh2dcef112008-01-12 19:03:48 +00003162 Expr exprAnd;
3163 Expr compLeft;
3164 Expr compRight;
3165 Expr exprX;
drhbe5c89a2004-07-26 00:31:09 +00003166
drh2dcef112008-01-12 19:03:48 +00003167 exprX = *pExpr->pLeft;
3168 exprAnd.op = TK_AND;
3169 exprAnd.pLeft = &compLeft;
3170 exprAnd.pRight = &compRight;
3171 compLeft.op = TK_GE;
3172 compLeft.pLeft = &exprX;
3173 compLeft.pRight = pExpr->pList->a[0].pExpr;
3174 compRight.op = TK_LE;
3175 compRight.pLeft = &exprX;
3176 compRight.pRight = pExpr->pList->a[1].pExpr;
3177 exprX.iTable = sqlite3ExprCodeTemp(pParse, &exprX, &regFree1);
drhc5499be2008-04-01 15:06:33 +00003178 testcase( regFree1==0 );
drh2dcef112008-01-12 19:03:48 +00003179 exprX.op = TK_REGISTER;
drhc5499be2008-04-01 15:06:33 +00003180 testcase( jumpIfNull==0 );
drh2dcef112008-01-12 19:03:48 +00003181 sqlite3ExprIfFalse(pParse, &exprAnd, dest, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00003182 break;
3183 }
drhcce7d172000-05-31 15:34:51 +00003184 default: {
drh2dcef112008-01-12 19:03:48 +00003185 r1 = sqlite3ExprCodeTemp(pParse, pExpr, &regFree1);
3186 sqlite3VdbeAddOp3(v, OP_IfNot, r1, dest, jumpIfNull!=0);
drhc5499be2008-04-01 15:06:33 +00003187 testcase( regFree1==0 );
3188 testcase( jumpIfNull==0 );
drhcce7d172000-05-31 15:34:51 +00003189 break;
3190 }
3191 }
drh2dcef112008-01-12 19:03:48 +00003192 sqlite3ReleaseTempReg(pParse, regFree1);
3193 sqlite3ReleaseTempReg(pParse, regFree2);
drhcce7d172000-05-31 15:34:51 +00003194}
drh22827922000-06-06 17:27:05 +00003195
3196/*
3197** Do a deep comparison of two expression trees. Return TRUE (non-zero)
3198** if they are identical and return FALSE if they differ in any way.
drhd40aab02007-02-24 15:29:03 +00003199**
3200** Sometimes this routine will return FALSE even if the two expressions
3201** really are equivalent. If we cannot prove that the expressions are
3202** identical, we return FALSE just to be safe. So if this routine
3203** returns false, then you do not really know for certain if the two
3204** expressions are the same. But if you get a TRUE return, then you
3205** can be sure the expressions are the same. In the places where
3206** this routine is used, it does not hurt to get an extra FALSE - that
3207** just might result in some slightly slower code. But returning
3208** an incorrect TRUE could lead to a malfunction.
drh22827922000-06-06 17:27:05 +00003209*/
danielk19774adee202004-05-08 08:23:19 +00003210int sqlite3ExprCompare(Expr *pA, Expr *pB){
drh22827922000-06-06 17:27:05 +00003211 int i;
danielk19774b202ae2006-01-23 05:50:58 +00003212 if( pA==0||pB==0 ){
3213 return pB==pA;
drh22827922000-06-06 17:27:05 +00003214 }
3215 if( pA->op!=pB->op ) return 0;
drhfd357972005-09-09 01:33:19 +00003216 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
danielk19774adee202004-05-08 08:23:19 +00003217 if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
3218 if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
drh22827922000-06-06 17:27:05 +00003219 if( pA->pList ){
3220 if( pB->pList==0 ) return 0;
3221 if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
3222 for(i=0; i<pA->pList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00003223 if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
drh22827922000-06-06 17:27:05 +00003224 return 0;
3225 }
3226 }
3227 }else if( pB->pList ){
3228 return 0;
3229 }
3230 if( pA->pSelect || pB->pSelect ) return 0;
drh2f2c01e2002-07-02 13:05:04 +00003231 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
drhdd735212007-02-24 13:53:05 +00003232 if( pA->op!=TK_COLUMN && pA->token.z ){
drh22827922000-06-06 17:27:05 +00003233 if( pB->token.z==0 ) return 0;
drh6977fea2002-10-22 23:38:04 +00003234 if( pB->token.n!=pA->token.n ) return 0;
drh2646da72005-12-09 20:02:05 +00003235 if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
3236 return 0;
3237 }
drh22827922000-06-06 17:27:05 +00003238 }
3239 return 1;
3240}
3241
drh13449892005-09-07 21:22:45 +00003242
drh22827922000-06-06 17:27:05 +00003243/*
drh13449892005-09-07 21:22:45 +00003244** Add a new element to the pAggInfo->aCol[] array. Return the index of
3245** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00003246*/
drh17435752007-08-16 04:30:38 +00003247static int addAggInfoColumn(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00003248 int i;
drhcf643722007-03-27 13:36:37 +00003249 pInfo->aCol = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003250 db,
drhcf643722007-03-27 13:36:37 +00003251 pInfo->aCol,
3252 sizeof(pInfo->aCol[0]),
3253 3,
3254 &pInfo->nColumn,
3255 &pInfo->nColumnAlloc,
3256 &i
3257 );
drh13449892005-09-07 21:22:45 +00003258 return i;
3259}
3260
3261/*
3262** Add a new element to the pAggInfo->aFunc[] array. Return the index of
3263** the new element. Return a negative number if malloc fails.
3264*/
drh17435752007-08-16 04:30:38 +00003265static int addAggInfoFunc(sqlite3 *db, AggInfo *pInfo){
drh13449892005-09-07 21:22:45 +00003266 int i;
drhcf643722007-03-27 13:36:37 +00003267 pInfo->aFunc = sqlite3ArrayAllocate(
drh17435752007-08-16 04:30:38 +00003268 db,
drhcf643722007-03-27 13:36:37 +00003269 pInfo->aFunc,
3270 sizeof(pInfo->aFunc[0]),
3271 3,
3272 &pInfo->nFunc,
3273 &pInfo->nFuncAlloc,
3274 &i
3275 );
drh13449892005-09-07 21:22:45 +00003276 return i;
3277}
drh22827922000-06-06 17:27:05 +00003278
3279/*
drh626a8792005-01-17 22:08:19 +00003280** This is an xFunc for walkExprTree() used to implement
3281** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
3282** for additional information.
drh22827922000-06-06 17:27:05 +00003283**
drh626a8792005-01-17 22:08:19 +00003284** This routine analyzes the aggregate function at pExpr.
drh22827922000-06-06 17:27:05 +00003285*/
drh626a8792005-01-17 22:08:19 +00003286static int analyzeAggregate(void *pArg, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00003287 int i;
danielk1977a58fdfb2005-02-08 07:50:40 +00003288 NameContext *pNC = (NameContext *)pArg;
3289 Parse *pParse = pNC->pParse;
3290 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00003291 AggInfo *pAggInfo = pNC->pAggInfo;
drh22827922000-06-06 17:27:05 +00003292
drh22827922000-06-06 17:27:05 +00003293 switch( pExpr->op ){
drh89c69d02007-01-04 01:20:28 +00003294 case TK_AGG_COLUMN:
drh967e8b72000-06-21 13:59:10 +00003295 case TK_COLUMN: {
drh13449892005-09-07 21:22:45 +00003296 /* Check to see if the column is in one of the tables in the FROM
3297 ** clause of the aggregate query */
3298 if( pSrcList ){
3299 struct SrcList_item *pItem = pSrcList->a;
3300 for(i=0; i<pSrcList->nSrc; i++, pItem++){
3301 struct AggInfo_col *pCol;
3302 if( pExpr->iTable==pItem->iCursor ){
3303 /* If we reach this point, it means that pExpr refers to a table
3304 ** that is in the FROM clause of the aggregate query.
3305 **
3306 ** Make an entry for the column in pAggInfo->aCol[] if there
3307 ** is not an entry there already.
3308 */
drh7f906d62007-03-12 23:48:52 +00003309 int k;
drh13449892005-09-07 21:22:45 +00003310 pCol = pAggInfo->aCol;
drh7f906d62007-03-12 23:48:52 +00003311 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
drh13449892005-09-07 21:22:45 +00003312 if( pCol->iTable==pExpr->iTable &&
3313 pCol->iColumn==pExpr->iColumn ){
3314 break;
3315 }
danielk1977a58fdfb2005-02-08 07:50:40 +00003316 }
danielk19771e536952007-08-16 10:09:01 +00003317 if( (k>=pAggInfo->nColumn)
3318 && (k = addAggInfoColumn(pParse->db, pAggInfo))>=0
3319 ){
drh7f906d62007-03-12 23:48:52 +00003320 pCol = &pAggInfo->aCol[k];
danielk19770817d0d2007-02-14 09:19:36 +00003321 pCol->pTab = pExpr->pTab;
drh13449892005-09-07 21:22:45 +00003322 pCol->iTable = pExpr->iTable;
3323 pCol->iColumn = pExpr->iColumn;
drh0a07c102008-01-03 18:03:08 +00003324 pCol->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00003325 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00003326 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00003327 if( pAggInfo->pGroupBy ){
3328 int j, n;
3329 ExprList *pGB = pAggInfo->pGroupBy;
3330 struct ExprList_item *pTerm = pGB->a;
3331 n = pGB->nExpr;
3332 for(j=0; j<n; j++, pTerm++){
3333 Expr *pE = pTerm->pExpr;
3334 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
3335 pE->iColumn==pExpr->iColumn ){
3336 pCol->iSorterColumn = j;
3337 break;
3338 }
3339 }
3340 }
3341 if( pCol->iSorterColumn<0 ){
3342 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
3343 }
3344 }
3345 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
3346 ** because it was there before or because we just created it).
3347 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
3348 ** pAggInfo->aCol[] entry.
3349 */
3350 pExpr->pAggInfo = pAggInfo;
3351 pExpr->op = TK_AGG_COLUMN;
drh7f906d62007-03-12 23:48:52 +00003352 pExpr->iAgg = k;
drh13449892005-09-07 21:22:45 +00003353 break;
3354 } /* endif pExpr->iTable==pItem->iCursor */
3355 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00003356 }
drh626a8792005-01-17 22:08:19 +00003357 return 1;
drh22827922000-06-06 17:27:05 +00003358 }
3359 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00003360 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
3361 ** to be ignored */
danielk1977a58fdfb2005-02-08 07:50:40 +00003362 if( pNC->nDepth==0 ){
drh13449892005-09-07 21:22:45 +00003363 /* Check to see if pExpr is a duplicate of another aggregate
3364 ** function that is already in the pAggInfo structure
3365 */
3366 struct AggInfo_func *pItem = pAggInfo->aFunc;
3367 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
3368 if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
danielk1977a58fdfb2005-02-08 07:50:40 +00003369 break;
3370 }
drh22827922000-06-06 17:27:05 +00003371 }
drh13449892005-09-07 21:22:45 +00003372 if( i>=pAggInfo->nFunc ){
3373 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
3374 */
danielk197714db2662006-01-09 16:12:04 +00003375 u8 enc = ENC(pParse->db);
danielk19771e536952007-08-16 10:09:01 +00003376 i = addAggInfoFunc(pParse->db, pAggInfo);
drh13449892005-09-07 21:22:45 +00003377 if( i>=0 ){
3378 pItem = &pAggInfo->aFunc[i];
3379 pItem->pExpr = pExpr;
drh0a07c102008-01-03 18:03:08 +00003380 pItem->iMem = ++pParse->nMem;
drh13449892005-09-07 21:22:45 +00003381 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh2646da72005-12-09 20:02:05 +00003382 (char*)pExpr->token.z, pExpr->token.n,
drh13449892005-09-07 21:22:45 +00003383 pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00003384 if( pExpr->flags & EP_Distinct ){
3385 pItem->iDistinct = pParse->nTab++;
3386 }else{
3387 pItem->iDistinct = -1;
3388 }
drh13449892005-09-07 21:22:45 +00003389 }
danielk1977a58fdfb2005-02-08 07:50:40 +00003390 }
drh13449892005-09-07 21:22:45 +00003391 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
3392 */
danielk1977a58fdfb2005-02-08 07:50:40 +00003393 pExpr->iAgg = i;
drh13449892005-09-07 21:22:45 +00003394 pExpr->pAggInfo = pAggInfo;
danielk1977a58fdfb2005-02-08 07:50:40 +00003395 return 1;
drh22827922000-06-06 17:27:05 +00003396 }
drh22827922000-06-06 17:27:05 +00003397 }
3398 }
drh13449892005-09-07 21:22:45 +00003399
3400 /* Recursively walk subqueries looking for TK_COLUMN nodes that need
3401 ** to be changed to TK_AGG_COLUMN. But increment nDepth so that
3402 ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
3403 */
danielk1977a58fdfb2005-02-08 07:50:40 +00003404 if( pExpr->pSelect ){
3405 pNC->nDepth++;
3406 walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
3407 pNC->nDepth--;
3408 }
drh626a8792005-01-17 22:08:19 +00003409 return 0;
3410}
3411
3412/*
3413** Analyze the given expression looking for aggregate functions and
3414** for variables that need to be added to the pParse->aAgg[] array.
3415** Make additional entries to the pParse->aAgg[] array as necessary.
3416**
3417** This routine should only be called after the expression has been
3418** analyzed by sqlite3ExprResolveNames().
drh626a8792005-01-17 22:08:19 +00003419*/
drhd2b3e232008-01-23 14:51:49 +00003420void sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
danielk1977a58fdfb2005-02-08 07:50:40 +00003421 walkExprTree(pExpr, analyzeAggregate, pNC);
drh22827922000-06-06 17:27:05 +00003422}
drh5d9a4af2005-08-30 00:54:01 +00003423
3424/*
3425** Call sqlite3ExprAnalyzeAggregates() for every expression in an
3426** expression list. Return the number of errors.
3427**
3428** If an error is found, the analysis is cut short.
3429*/
drhd2b3e232008-01-23 14:51:49 +00003430void sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
drh5d9a4af2005-08-30 00:54:01 +00003431 struct ExprList_item *pItem;
3432 int i;
drh5d9a4af2005-08-30 00:54:01 +00003433 if( pList ){
drhd2b3e232008-01-23 14:51:49 +00003434 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
3435 sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
drh5d9a4af2005-08-30 00:54:01 +00003436 }
3437 }
drh5d9a4af2005-08-30 00:54:01 +00003438}
drh892d3172008-01-10 03:46:36 +00003439
3440/*
3441** Allocate or deallocate temporary use registers during code generation.
3442*/
3443int sqlite3GetTempReg(Parse *pParse){
drhe55cbd72008-03-31 23:48:03 +00003444 int i, r;
3445 if( pParse->nTempReg==0 ){
drh892d3172008-01-10 03:46:36 +00003446 return ++pParse->nMem;
3447 }
drhe55cbd72008-03-31 23:48:03 +00003448 for(i=0; i<pParse->nTempReg; i++){
3449 r = pParse->aTempReg[i];
3450 if( usedAsColumnCache(pParse, r, r) ) continue;
3451 }
3452 if( i>=pParse->nTempReg ){
3453 return ++pParse->nMem;
3454 }
3455 while( i<pParse->nTempReg-1 ){
3456 pParse->aTempReg[i] = pParse->aTempReg[i+1];
3457 }
3458 pParse->nTempReg--;
3459 return r;
drh892d3172008-01-10 03:46:36 +00003460}
3461void sqlite3ReleaseTempReg(Parse *pParse, int iReg){
drh2dcef112008-01-12 19:03:48 +00003462 if( iReg && pParse->nTempReg<ArraySize(pParse->aTempReg) ){
drh892d3172008-01-10 03:46:36 +00003463 pParse->aTempReg[pParse->nTempReg++] = iReg;
3464 }
3465}
3466
3467/*
3468** Allocate or deallocate a block of nReg consecutive registers
3469*/
3470int sqlite3GetTempRange(Parse *pParse, int nReg){
drhe55cbd72008-03-31 23:48:03 +00003471 int i, n;
3472 i = pParse->iRangeReg;
3473 n = pParse->nRangeReg;
3474 if( nReg<=n && !usedAsColumnCache(pParse, i, i+n-1) ){
drh892d3172008-01-10 03:46:36 +00003475 pParse->iRangeReg += nReg;
3476 pParse->nRangeReg -= nReg;
3477 }else{
3478 i = pParse->nMem+1;
3479 pParse->nMem += nReg;
3480 }
3481 return i;
3482}
3483void sqlite3ReleaseTempRange(Parse *pParse, int iReg, int nReg){
3484 if( nReg>pParse->nRangeReg ){
3485 pParse->nRangeReg = nReg;
3486 pParse->iRangeReg = iReg;
3487 }
3488}