blob: fa7be8c35df46e4f25c8456c6724f4ade3097c46 [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**
danielk1977b3bf5562006-01-10 17:58:23 +000015** $Id: expr.c,v 1.247 2006/01/10 17:58:23 danielk1977 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;
38 if( op==TK_AS ){
danielk1977bf3b7212004-05-18 10:06:24 +000039 return sqlite3ExprAffinity(pExpr->pLeft);
danielk1977a37cdde2004-05-16 11:15:36 +000040 }
drh487e2622005-06-25 18:42:14 +000041 if( op==TK_SELECT ){
danielk1977bf3b7212004-05-18 10:06:24 +000042 return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
danielk1977a37cdde2004-05-16 11:15:36 +000043 }
drh487e2622005-06-25 18:42:14 +000044#ifndef SQLITE_OMIT_CAST
45 if( op==TK_CAST ){
drh8a512562005-11-14 22:29:05 +000046 return sqlite3AffinityType(&pExpr->token);
drh487e2622005-06-25 18:42:14 +000047 }
48#endif
danielk1977a37cdde2004-05-16 11:15:36 +000049 return pExpr->affinity;
50}
51
drh53db1452004-05-20 13:54:53 +000052/*
danielk19770202b292004-06-09 09:55:16 +000053** Return the default collation sequence for the expression pExpr. If
54** there is no default collation type, return 0.
55*/
danielk19777cedc8d2004-06-10 10:50:08 +000056CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
57 CollSeq *pColl = 0;
danielk19770202b292004-06-09 09:55:16 +000058 if( pExpr ){
danielk19777cedc8d2004-06-10 10:50:08 +000059 pColl = pExpr->pColl;
drh487e2622005-06-25 18:42:14 +000060 if( (pExpr->op==TK_AS || pExpr->op==TK_CAST) && !pColl ){
danielk19777cedc8d2004-06-10 10:50:08 +000061 return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
danielk19770202b292004-06-09 09:55:16 +000062 }
63 }
danielk19777cedc8d2004-06-10 10:50:08 +000064 if( sqlite3CheckCollSeq(pParse, pColl) ){
65 pColl = 0;
66 }
67 return pColl;
danielk19770202b292004-06-09 09:55:16 +000068}
69
70/*
drh626a8792005-01-17 22:08:19 +000071** pExpr is an operand of a comparison operator. aff2 is the
72** type affinity of the other operand. This routine returns the
drh53db1452004-05-20 13:54:53 +000073** type affinity that should be used for the comparison operator.
74*/
danielk1977e014a832004-05-17 10:48:57 +000075char sqlite3CompareAffinity(Expr *pExpr, char aff2){
danielk1977bf3b7212004-05-18 10:06:24 +000076 char aff1 = sqlite3ExprAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +000077 if( aff1 && aff2 ){
drh8df447f2005-11-01 15:48:24 +000078 /* Both sides of the comparison are columns. If one has numeric
79 ** affinity, use that. Otherwise use no affinity.
danielk1977e014a832004-05-17 10:48:57 +000080 */
drh8a512562005-11-14 22:29:05 +000081 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
danielk1977e014a832004-05-17 10:48:57 +000082 return SQLITE_AFF_NUMERIC;
83 }else{
84 return SQLITE_AFF_NONE;
85 }
86 }else if( !aff1 && !aff2 ){
drh5f6a87b2004-07-19 00:39:45 +000087 /* Neither side of the comparison is a column. Compare the
88 ** results directly.
danielk1977e014a832004-05-17 10:48:57 +000089 */
drh5f6a87b2004-07-19 00:39:45 +000090 return SQLITE_AFF_NONE;
danielk1977e014a832004-05-17 10:48:57 +000091 }else{
92 /* One side is a column, the other is not. Use the columns affinity. */
drhfe05af82005-07-21 03:14:59 +000093 assert( aff1==0 || aff2==0 );
danielk1977e014a832004-05-17 10:48:57 +000094 return (aff1 + aff2);
95 }
96}
97
drh53db1452004-05-20 13:54:53 +000098/*
99** pExpr is a comparison operator. Return the type affinity that should
100** be applied to both operands prior to doing the comparison.
101*/
danielk1977e014a832004-05-17 10:48:57 +0000102static char comparisonAffinity(Expr *pExpr){
103 char aff;
104 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
105 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
106 pExpr->op==TK_NE );
107 assert( pExpr->pLeft );
danielk1977bf3b7212004-05-18 10:06:24 +0000108 aff = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +0000109 if( pExpr->pRight ){
110 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
111 }
112 else if( pExpr->pSelect ){
113 aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
114 }
115 else if( !aff ){
116 aff = SQLITE_AFF_NUMERIC;
117 }
118 return aff;
119}
120
121/*
122** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
123** idx_affinity is the affinity of an indexed column. Return true
124** if the index with affinity idx_affinity may be used to implement
125** the comparison in pExpr.
126*/
127int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
128 char aff = comparisonAffinity(pExpr);
drh8a512562005-11-14 22:29:05 +0000129 switch( aff ){
130 case SQLITE_AFF_NONE:
131 return 1;
132 case SQLITE_AFF_TEXT:
133 return idx_affinity==SQLITE_AFF_TEXT;
134 default:
135 return sqlite3IsNumericAffinity(idx_affinity);
136 }
danielk1977e014a832004-05-17 10:48:57 +0000137}
138
danielk1977a37cdde2004-05-16 11:15:36 +0000139/*
140** Return the P1 value that should be used for a binary comparison
141** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
142** If jumpIfNull is true, then set the low byte of the returned
143** P1 value to tell the opcode to jump if either expression
144** evaluates to NULL.
145*/
danielk1977e014a832004-05-17 10:48:57 +0000146static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
danielk1977bf3b7212004-05-18 10:06:24 +0000147 char aff = sqlite3ExprAffinity(pExpr2);
drhf0863fe2005-06-12 21:35:51 +0000148 return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
danielk1977a37cdde2004-05-16 11:15:36 +0000149}
150
drha2e00042002-01-22 03:13:42 +0000151/*
danielk19770202b292004-06-09 09:55:16 +0000152** Return a pointer to the collation sequence that should be used by
153** a binary comparison operator comparing pLeft and pRight.
154**
155** If the left hand expression has a collating sequence type, then it is
156** used. Otherwise the collation sequence for the right hand expression
157** is used, or the default (BINARY) if neither expression has a collating
158** type.
159*/
danielk19777cedc8d2004-06-10 10:50:08 +0000160static CollSeq* binaryCompareCollSeq(Parse *pParse, Expr *pLeft, Expr *pRight){
161 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pLeft);
danielk19770202b292004-06-09 09:55:16 +0000162 if( !pColl ){
danielk19777cedc8d2004-06-10 10:50:08 +0000163 pColl = sqlite3ExprCollSeq(pParse, pRight);
danielk19770202b292004-06-09 09:55:16 +0000164 }
165 return pColl;
166}
167
168/*
drhbe5c89a2004-07-26 00:31:09 +0000169** Generate code for a comparison operator.
170*/
171static int codeCompare(
172 Parse *pParse, /* The parsing (and code generating) context */
173 Expr *pLeft, /* The left operand */
174 Expr *pRight, /* The right operand */
175 int opcode, /* The comparison opcode */
176 int dest, /* Jump here if true. */
177 int jumpIfNull /* If true, jump if either operand is NULL */
178){
179 int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
180 CollSeq *p3 = binaryCompareCollSeq(pParse, pLeft, pRight);
drh94a11212004-09-25 13:12:14 +0000181 return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
drhbe5c89a2004-07-26 00:31:09 +0000182}
183
184/*
drha76b5df2002-02-23 02:32:10 +0000185** Construct a new expression node and return a pointer to it. Memory
186** for this node is obtained from sqliteMalloc(). The calling function
187** is responsible for making sure the node eventually gets freed.
188*/
drhe4e72072004-11-23 01:47:30 +0000189Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000190 Expr *pNew;
191 pNew = sqliteMalloc( sizeof(Expr) );
192 if( pNew==0 ){
danielk1977d5d56522005-03-16 12:15:20 +0000193 /* When malloc fails, delete pLeft and pRight. Expressions passed to
194 ** this function must always be allocated with sqlite3Expr() for this
195 ** reason.
196 */
197 sqlite3ExprDelete(pLeft);
198 sqlite3ExprDelete(pRight);
drha76b5df2002-02-23 02:32:10 +0000199 return 0;
200 }
201 pNew->op = op;
202 pNew->pLeft = pLeft;
203 pNew->pRight = pRight;
danielk1977a58fdfb2005-02-08 07:50:40 +0000204 pNew->iAgg = -1;
drha76b5df2002-02-23 02:32:10 +0000205 if( pToken ){
drh4b59ab52002-08-24 18:24:51 +0000206 assert( pToken->dyn==0 );
drh145716b2004-09-24 12:24:06 +0000207 pNew->span = pNew->token = *pToken;
208 }else if( pLeft && pRight ){
209 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
drha76b5df2002-02-23 02:32:10 +0000210 }
drha76b5df2002-02-23 02:32:10 +0000211 return pNew;
212}
213
214/*
drh4e0cff62004-11-05 05:10:28 +0000215** When doing a nested parse, you can include terms in an expression
216** that look like this: #0 #1 #2 ... These terms refer to elements
drh288d37f2005-06-22 08:48:06 +0000217** on the stack. "#0" means the top of the stack.
218** "#1" means the next down on the stack. And so forth.
drh4e0cff62004-11-05 05:10:28 +0000219**
220** This routine is called by the parser to deal with on of those terms.
221** It immediately generates code to store the value in a memory location.
222** The returns an expression that will code to extract the value from
223** that memory location as needed.
224*/
225Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
226 Vdbe *v = pParse->pVdbe;
227 Expr *p;
228 int depth;
drh4e0cff62004-11-05 05:10:28 +0000229 if( pParse->nested==0 ){
230 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
231 return 0;
232 }
drhbb7ac002005-08-12 22:58:53 +0000233 if( v==0 ) return 0;
drh4e0cff62004-11-05 05:10:28 +0000234 p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
drh73c42a12004-11-20 18:13:10 +0000235 if( p==0 ){
236 return 0; /* Malloc failed */
237 }
drh2646da72005-12-09 20:02:05 +0000238 depth = atoi((char*)&pToken->z[1]);
drh288d37f2005-06-22 08:48:06 +0000239 p->iTable = pParse->nMem++;
240 sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
241 sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
drh4e0cff62004-11-05 05:10:28 +0000242 return p;
243}
244
245/*
drh91bb0ee2004-09-01 03:06:34 +0000246** Join two expressions using an AND operator. If either expression is
247** NULL, then just return the other expression.
248*/
249Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
250 if( pLeft==0 ){
251 return pRight;
252 }else if( pRight==0 ){
253 return pLeft;
254 }else{
255 return sqlite3Expr(TK_AND, pLeft, pRight, 0);
256 }
257}
258
259/*
drh6977fea2002-10-22 23:38:04 +0000260** Set the Expr.span field of the given expression to span all
drha76b5df2002-02-23 02:32:10 +0000261** text between the two given tokens.
262*/
danielk19774adee202004-05-08 08:23:19 +0000263void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
drh4efc4752004-01-16 15:55:37 +0000264 assert( pRight!=0 );
265 assert( pLeft!=0 );
danielk1977e501b892006-01-09 06:29:47 +0000266 if( !sqlite3ThreadData()->mallocFailed && pRight->z && pLeft->z ){
drhad6d9462004-09-19 02:15:24 +0000267 assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
drh145716b2004-09-24 12:24:06 +0000268 if( pLeft->dyn==0 && pRight->dyn==0 ){
drh6977fea2002-10-22 23:38:04 +0000269 pExpr->span.z = pLeft->z;
drh97903fe2005-05-24 20:19:57 +0000270 pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
drh4b59ab52002-08-24 18:24:51 +0000271 }else{
drh6977fea2002-10-22 23:38:04 +0000272 pExpr->span.z = 0;
drh4b59ab52002-08-24 18:24:51 +0000273 }
drha76b5df2002-02-23 02:32:10 +0000274 }
275}
276
277/*
278** Construct a new expression node for a function with multiple
279** arguments.
280*/
danielk19774adee202004-05-08 08:23:19 +0000281Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
drha76b5df2002-02-23 02:32:10 +0000282 Expr *pNew;
283 pNew = sqliteMalloc( sizeof(Expr) );
284 if( pNew==0 ){
danielk1977d5d56522005-03-16 12:15:20 +0000285 sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
drha76b5df2002-02-23 02:32:10 +0000286 return 0;
287 }
288 pNew->op = TK_FUNCTION;
289 pNew->pList = pList;
290 if( pToken ){
drh4b59ab52002-08-24 18:24:51 +0000291 assert( pToken->dyn==0 );
drha76b5df2002-02-23 02:32:10 +0000292 pNew->token = *pToken;
293 }else{
294 pNew->token.z = 0;
drha76b5df2002-02-23 02:32:10 +0000295 }
drh6977fea2002-10-22 23:38:04 +0000296 pNew->span = pNew->token;
drha76b5df2002-02-23 02:32:10 +0000297 return pNew;
298}
299
300/*
drhfa6bc002004-09-07 16:19:52 +0000301** Assign a variable number to an expression that encodes a wildcard
302** in the original SQL statement.
303**
304** Wildcards consisting of a single "?" are assigned the next sequential
305** variable number.
306**
307** Wildcards of the form "?nnn" are assigned the number "nnn". We make
308** sure "nnn" is not too be to avoid a denial of service attack when
309** the SQL statement comes from an external source.
310**
311** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
312** as the previous instance of the same wildcard. Or if this is the first
313** instance of the wildcard, the next sequenial variable number is
314** assigned.
315*/
316void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
317 Token *pToken;
318 if( pExpr==0 ) return;
319 pToken = &pExpr->token;
320 assert( pToken->n>=1 );
321 assert( pToken->z!=0 );
322 assert( pToken->z[0]!=0 );
323 if( pToken->n==1 ){
324 /* Wildcard of the form "?". Assign the next variable number */
325 pExpr->iTable = ++pParse->nVar;
326 }else if( pToken->z[0]=='?' ){
327 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
328 ** use it as the variable number */
329 int i;
drh2646da72005-12-09 20:02:05 +0000330 pExpr->iTable = i = atoi((char*)&pToken->z[1]);
drhfa6bc002004-09-07 16:19:52 +0000331 if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
332 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
333 SQLITE_MAX_VARIABLE_NUMBER);
334 }
335 if( i>pParse->nVar ){
336 pParse->nVar = i;
337 }
338 }else{
339 /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
340 ** number as the prior appearance of the same name, or if the name
341 ** has never appeared before, reuse the same variable number
342 */
343 int i, n;
344 n = pToken->n;
345 for(i=0; i<pParse->nVarExpr; i++){
346 Expr *pE;
347 if( (pE = pParse->apVarExpr[i])!=0
348 && pE->token.n==n
349 && memcmp(pE->token.z, pToken->z, n)==0 ){
350 pExpr->iTable = pE->iTable;
351 break;
352 }
353 }
354 if( i>=pParse->nVarExpr ){
355 pExpr->iTable = ++pParse->nVar;
356 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
357 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
drh53f733c2005-09-16 02:38:09 +0000358 sqlite3ReallocOrFree((void**)&pParse->apVarExpr,
drhfa6bc002004-09-07 16:19:52 +0000359 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
360 }
danielk1977e501b892006-01-09 06:29:47 +0000361 if( !sqlite3ThreadData()->mallocFailed ){
drhfa6bc002004-09-07 16:19:52 +0000362 assert( pParse->apVarExpr!=0 );
363 pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
364 }
365 }
366 }
367}
368
369/*
drha2e00042002-01-22 03:13:42 +0000370** Recursively delete an expression tree.
371*/
danielk19774adee202004-05-08 08:23:19 +0000372void sqlite3ExprDelete(Expr *p){
drha2e00042002-01-22 03:13:42 +0000373 if( p==0 ) return;
drh4efc4752004-01-16 15:55:37 +0000374 if( p->span.dyn ) sqliteFree((char*)p->span.z);
375 if( p->token.dyn ) sqliteFree((char*)p->token.z);
danielk19774adee202004-05-08 08:23:19 +0000376 sqlite3ExprDelete(p->pLeft);
377 sqlite3ExprDelete(p->pRight);
378 sqlite3ExprListDelete(p->pList);
379 sqlite3SelectDelete(p->pSelect);
drha2e00042002-01-22 03:13:42 +0000380 sqliteFree(p);
381}
382
drhd2687b72005-08-12 22:56:09 +0000383/*
384** The Expr.token field might be a string literal that is quoted.
385** If so, remove the quotation marks.
386*/
387void sqlite3DequoteExpr(Expr *p){
388 if( ExprHasAnyProperty(p, EP_Dequoted) ){
389 return;
390 }
391 ExprSetProperty(p, EP_Dequoted);
392 if( p->token.dyn==0 ){
drhd2687b72005-08-12 22:56:09 +0000393 sqlite3TokenCopy(&p->token, &p->token);
394 }
395 sqlite3Dequote((char*)p->token.z);
396}
397
drha76b5df2002-02-23 02:32:10 +0000398
399/*
drhff78bd22002-02-27 01:47:11 +0000400** The following group of routines make deep copies of expressions,
401** expression lists, ID lists, and select statements. The copies can
402** be deleted (by being passed to their respective ...Delete() routines)
403** without effecting the originals.
404**
danielk19774adee202004-05-08 08:23:19 +0000405** The expression list, ID, and source lists return by sqlite3ExprListDup(),
406** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
drhad3cab52002-05-24 02:04:32 +0000407** by subsequent calls to sqlite*ListAppend() routines.
drhff78bd22002-02-27 01:47:11 +0000408**
drhad3cab52002-05-24 02:04:32 +0000409** Any tables that the SrcList might point to are not duplicated.
drhff78bd22002-02-27 01:47:11 +0000410*/
danielk19774adee202004-05-08 08:23:19 +0000411Expr *sqlite3ExprDup(Expr *p){
drhff78bd22002-02-27 01:47:11 +0000412 Expr *pNew;
413 if( p==0 ) return 0;
drhfcb78a42003-01-18 20:11:05 +0000414 pNew = sqliteMallocRaw( sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +0000415 if( pNew==0 ) return 0;
drh3b167c72002-06-28 12:18:47 +0000416 memcpy(pNew, p, sizeof(*pNew));
drh6977fea2002-10-22 23:38:04 +0000417 if( p->token.z!=0 ){
drh2646da72005-12-09 20:02:05 +0000418 pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
drh4b59ab52002-08-24 18:24:51 +0000419 pNew->token.dyn = 1;
420 }else{
drh4efc4752004-01-16 15:55:37 +0000421 assert( pNew->token.z==0 );
drh4b59ab52002-08-24 18:24:51 +0000422 }
drh6977fea2002-10-22 23:38:04 +0000423 pNew->span.z = 0;
danielk19774adee202004-05-08 08:23:19 +0000424 pNew->pLeft = sqlite3ExprDup(p->pLeft);
425 pNew->pRight = sqlite3ExprDup(p->pRight);
426 pNew->pList = sqlite3ExprListDup(p->pList);
427 pNew->pSelect = sqlite3SelectDup(p->pSelect);
danielk1977aee18ef2005-03-09 12:26:50 +0000428 pNew->pTab = p->pTab;
drhff78bd22002-02-27 01:47:11 +0000429 return pNew;
430}
danielk19774adee202004-05-08 08:23:19 +0000431void sqlite3TokenCopy(Token *pTo, Token *pFrom){
drh4b59ab52002-08-24 18:24:51 +0000432 if( pTo->dyn ) sqliteFree((char*)pTo->z);
drh4b59ab52002-08-24 18:24:51 +0000433 if( pFrom->z ){
434 pTo->n = pFrom->n;
drh2646da72005-12-09 20:02:05 +0000435 pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
drh4b59ab52002-08-24 18:24:51 +0000436 pTo->dyn = 1;
437 }else{
drh4b59ab52002-08-24 18:24:51 +0000438 pTo->z = 0;
drh4b59ab52002-08-24 18:24:51 +0000439 }
440}
danielk19774adee202004-05-08 08:23:19 +0000441ExprList *sqlite3ExprListDup(ExprList *p){
drhff78bd22002-02-27 01:47:11 +0000442 ExprList *pNew;
drh145716b2004-09-24 12:24:06 +0000443 struct ExprList_item *pItem, *pOldItem;
drhff78bd22002-02-27 01:47:11 +0000444 int i;
445 if( p==0 ) return 0;
446 pNew = sqliteMalloc( sizeof(*pNew) );
447 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +0000448 pNew->nExpr = pNew->nAlloc = p->nExpr;
drh3e7bc9c2004-02-21 19:17:17 +0000449 pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
danielk1977e0048402004-06-15 16:51:01 +0000450 if( pItem==0 ){
451 sqliteFree(pNew);
452 return 0;
453 }
drh145716b2004-09-24 12:24:06 +0000454 pOldItem = p->a;
455 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
drh4b59ab52002-08-24 18:24:51 +0000456 Expr *pNewExpr, *pOldExpr;
drh145716b2004-09-24 12:24:06 +0000457 pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
drh6977fea2002-10-22 23:38:04 +0000458 if( pOldExpr->span.z!=0 && pNewExpr ){
459 /* Always make a copy of the span for top-level expressions in the
drh4b59ab52002-08-24 18:24:51 +0000460 ** expression list. The logic in SELECT processing that determines
461 ** the names of columns in the result set needs this information */
danielk19774adee202004-05-08 08:23:19 +0000462 sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
drh4b59ab52002-08-24 18:24:51 +0000463 }
drh1f3e9052002-10-31 00:09:39 +0000464 assert( pNewExpr==0 || pNewExpr->span.z!=0
danielk1977e501b892006-01-09 06:29:47 +0000465 || pOldExpr->span.z==0 || sqlite3ThreadData()->mallocFailed );
drh145716b2004-09-24 12:24:06 +0000466 pItem->zName = sqliteStrDup(pOldItem->zName);
467 pItem->sortOrder = pOldItem->sortOrder;
468 pItem->isAgg = pOldItem->isAgg;
drh3e7bc9c2004-02-21 19:17:17 +0000469 pItem->done = 0;
drhff78bd22002-02-27 01:47:11 +0000470 }
471 return pNew;
472}
danielk197793758c82005-01-21 08:13:14 +0000473
474/*
475** If cursors, triggers, views and subqueries are all omitted from
476** the build, then none of the following routines, except for
477** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
478** called with a NULL argument.
479*/
danielk19776a67fe82005-02-04 04:07:16 +0000480#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
481 || !defined(SQLITE_OMIT_SUBQUERY)
danielk19774adee202004-05-08 08:23:19 +0000482SrcList *sqlite3SrcListDup(SrcList *p){
drhad3cab52002-05-24 02:04:32 +0000483 SrcList *pNew;
484 int i;
drh113088e2003-03-20 01:16:58 +0000485 int nByte;
drhad3cab52002-05-24 02:04:32 +0000486 if( p==0 ) return 0;
drh113088e2003-03-20 01:16:58 +0000487 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
drh4efc4752004-01-16 15:55:37 +0000488 pNew = sqliteMallocRaw( nByte );
drhad3cab52002-05-24 02:04:32 +0000489 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +0000490 pNew->nSrc = pNew->nAlloc = p->nSrc;
drhad3cab52002-05-24 02:04:32 +0000491 for(i=0; i<p->nSrc; i++){
drh4efc4752004-01-16 15:55:37 +0000492 struct SrcList_item *pNewItem = &pNew->a[i];
493 struct SrcList_item *pOldItem = &p->a[i];
drhed8a3bb2005-06-06 21:19:56 +0000494 Table *pTab;
drh4efc4752004-01-16 15:55:37 +0000495 pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
496 pNewItem->zName = sqliteStrDup(pOldItem->zName);
497 pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
498 pNewItem->jointype = pOldItem->jointype;
499 pNewItem->iCursor = pOldItem->iCursor;
drhed8a3bb2005-06-06 21:19:56 +0000500 pTab = pNewItem->pTab = pOldItem->pTab;
501 if( pTab ){
502 pTab->nRef++;
danielk1977a1cb1832005-02-12 08:59:55 +0000503 }
danielk19774adee202004-05-08 08:23:19 +0000504 pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
505 pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
506 pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
danielk19776c18b6e2005-01-30 09:17:58 +0000507 pNewItem->colUsed = pOldItem->colUsed;
drhad3cab52002-05-24 02:04:32 +0000508 }
509 return pNew;
510}
danielk19774adee202004-05-08 08:23:19 +0000511IdList *sqlite3IdListDup(IdList *p){
drhff78bd22002-02-27 01:47:11 +0000512 IdList *pNew;
513 int i;
514 if( p==0 ) return 0;
drh4efc4752004-01-16 15:55:37 +0000515 pNew = sqliteMallocRaw( sizeof(*pNew) );
drhff78bd22002-02-27 01:47:11 +0000516 if( pNew==0 ) return 0;
drh4305d102003-07-30 12:34:12 +0000517 pNew->nId = pNew->nAlloc = p->nId;
drh4efc4752004-01-16 15:55:37 +0000518 pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
danielk1977d5d56522005-03-16 12:15:20 +0000519 if( pNew->a==0 ){
520 sqliteFree(pNew);
521 return 0;
522 }
drhff78bd22002-02-27 01:47:11 +0000523 for(i=0; i<p->nId; i++){
drh4efc4752004-01-16 15:55:37 +0000524 struct IdList_item *pNewItem = &pNew->a[i];
525 struct IdList_item *pOldItem = &p->a[i];
526 pNewItem->zName = sqliteStrDup(pOldItem->zName);
527 pNewItem->idx = pOldItem->idx;
drhff78bd22002-02-27 01:47:11 +0000528 }
529 return pNew;
530}
danielk19774adee202004-05-08 08:23:19 +0000531Select *sqlite3SelectDup(Select *p){
drhff78bd22002-02-27 01:47:11 +0000532 Select *pNew;
533 if( p==0 ) return 0;
drh4efc4752004-01-16 15:55:37 +0000534 pNew = sqliteMallocRaw( sizeof(*p) );
drhff78bd22002-02-27 01:47:11 +0000535 if( pNew==0 ) return 0;
536 pNew->isDistinct = p->isDistinct;
danielk19774adee202004-05-08 08:23:19 +0000537 pNew->pEList = sqlite3ExprListDup(p->pEList);
538 pNew->pSrc = sqlite3SrcListDup(p->pSrc);
539 pNew->pWhere = sqlite3ExprDup(p->pWhere);
540 pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
541 pNew->pHaving = sqlite3ExprDup(p->pHaving);
542 pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
drhff78bd22002-02-27 01:47:11 +0000543 pNew->op = p->op;
danielk19774adee202004-05-08 08:23:19 +0000544 pNew->pPrior = sqlite3SelectDup(p->pPrior);
danielk1977a2dc3b12005-02-05 12:48:48 +0000545 pNew->pLimit = sqlite3ExprDup(p->pLimit);
546 pNew->pOffset = sqlite3ExprDup(p->pOffset);
drh7b58dae2003-07-20 01:16:46 +0000547 pNew->iLimit = -1;
548 pNew->iOffset = -1;
danielk1977a1cb1832005-02-12 08:59:55 +0000549 pNew->isResolved = p->isResolved;
550 pNew->isAgg = p->isAgg;
drh8e647b82005-09-23 21:11:53 +0000551 pNew->usesVirt = 0;
552 pNew->disallowOrderBy = 0;
drh0342b1f2005-09-01 03:07:44 +0000553 pNew->pRightmost = 0;
554 pNew->addrOpenVirt[0] = -1;
555 pNew->addrOpenVirt[1] = -1;
556 pNew->addrOpenVirt[2] = -1;
drhff78bd22002-02-27 01:47:11 +0000557 return pNew;
558}
danielk197793758c82005-01-21 08:13:14 +0000559#else
560Select *sqlite3SelectDup(Select *p){
561 assert( p==0 );
562 return 0;
563}
564#endif
drhff78bd22002-02-27 01:47:11 +0000565
566
567/*
drha76b5df2002-02-23 02:32:10 +0000568** Add a new element to the end of an expression list. If pList is
569** initially NULL, then create a new expression list.
570*/
danielk19774adee202004-05-08 08:23:19 +0000571ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
drha76b5df2002-02-23 02:32:10 +0000572 if( pList==0 ){
573 pList = sqliteMalloc( sizeof(ExprList) );
574 if( pList==0 ){
danielk1977d5d56522005-03-16 12:15:20 +0000575 goto no_mem;
drha76b5df2002-02-23 02:32:10 +0000576 }
drh4efc4752004-01-16 15:55:37 +0000577 assert( pList->nAlloc==0 );
drha76b5df2002-02-23 02:32:10 +0000578 }
drh4305d102003-07-30 12:34:12 +0000579 if( pList->nAlloc<=pList->nExpr ){
danielk1977d5d56522005-03-16 12:15:20 +0000580 struct ExprList_item *a;
581 int n = pList->nAlloc*2 + 4;
582 a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
583 if( a==0 ){
584 goto no_mem;
drha76b5df2002-02-23 02:32:10 +0000585 }
danielk1977d5d56522005-03-16 12:15:20 +0000586 pList->a = a;
587 pList->nAlloc = n;
drha76b5df2002-02-23 02:32:10 +0000588 }
drh4efc4752004-01-16 15:55:37 +0000589 assert( pList->a!=0 );
590 if( pExpr || pName ){
591 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
592 memset(pItem, 0, sizeof(*pItem));
drha99db3b2004-06-19 14:49:12 +0000593 pItem->zName = sqlite3NameFromToken(pName);
danielk1977e94ddc92005-03-21 03:53:38 +0000594 pItem->pExpr = pExpr;
drha76b5df2002-02-23 02:32:10 +0000595 }
596 return pList;
danielk1977d5d56522005-03-16 12:15:20 +0000597
598no_mem:
599 /* Avoid leaking memory if malloc has failed. */
600 sqlite3ExprDelete(pExpr);
601 sqlite3ExprListDelete(pList);
602 return 0;
drha76b5df2002-02-23 02:32:10 +0000603}
604
605/*
606** Delete an entire expression list.
607*/
danielk19774adee202004-05-08 08:23:19 +0000608void sqlite3ExprListDelete(ExprList *pList){
drha76b5df2002-02-23 02:32:10 +0000609 int i;
drhbe5c89a2004-07-26 00:31:09 +0000610 struct ExprList_item *pItem;
drha76b5df2002-02-23 02:32:10 +0000611 if( pList==0 ) return;
drh1bdd9b52004-04-23 17:04:44 +0000612 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
613 assert( pList->nExpr<=pList->nAlloc );
drhbe5c89a2004-07-26 00:31:09 +0000614 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
615 sqlite3ExprDelete(pItem->pExpr);
616 sqliteFree(pItem->zName);
drha76b5df2002-02-23 02:32:10 +0000617 }
618 sqliteFree(pList->a);
619 sqliteFree(pList);
620}
621
622/*
drh626a8792005-01-17 22:08:19 +0000623** Walk an expression tree. Call xFunc for each node visited.
drh73b211a2005-01-18 04:00:42 +0000624**
drh626a8792005-01-17 22:08:19 +0000625** The return value from xFunc determines whether the tree walk continues.
626** 0 means continue walking the tree. 1 means do not walk children
627** of the current node but continue with siblings. 2 means abandon
628** the tree walk completely.
629**
630** The return value from this routine is 1 to abandon the tree walk
631** and 0 to continue.
drh87abf5c2005-08-25 12:45:04 +0000632**
633** NOTICE: This routine does *not* descend into subqueries.
drh626a8792005-01-17 22:08:19 +0000634*/
danielk1977a58fdfb2005-02-08 07:50:40 +0000635static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
drh626a8792005-01-17 22:08:19 +0000636static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
drh626a8792005-01-17 22:08:19 +0000637 int rc;
638 if( pExpr==0 ) return 0;
639 rc = (*xFunc)(pArg, pExpr);
640 if( rc==0 ){
641 if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
642 if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
danielk1977a58fdfb2005-02-08 07:50:40 +0000643 if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
drh626a8792005-01-17 22:08:19 +0000644 }
645 return rc>1;
646}
647
648/*
danielk1977a58fdfb2005-02-08 07:50:40 +0000649** Call walkExprTree() for every expression in list p.
650*/
651static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
652 int i;
653 struct ExprList_item *pItem;
654 if( !p ) return 0;
655 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
656 if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
657 }
658 return 0;
659}
660
661/*
662** Call walkExprTree() for every expression in Select p, not including
663** expressions that are part of sub-selects in any FROM clause or the LIMIT
664** or OFFSET expressions..
665*/
666static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
667 walkExprList(p->pEList, xFunc, pArg);
668 walkExprTree(p->pWhere, xFunc, pArg);
669 walkExprList(p->pGroupBy, xFunc, pArg);
670 walkExprTree(p->pHaving, xFunc, pArg);
671 walkExprList(p->pOrderBy, xFunc, pArg);
672 return 0;
673}
674
675
676/*
drh626a8792005-01-17 22:08:19 +0000677** This routine is designed as an xFunc for walkExprTree().
678**
679** pArg is really a pointer to an integer. If we can tell by looking
drh73b211a2005-01-18 04:00:42 +0000680** at pExpr that the expression that contains pExpr is not a constant
681** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
682** If pExpr does does not disqualify the expression from being a constant
683** then do nothing.
684**
685** After walking the whole tree, if no nodes are found that disqualify
686** the expression as constant, then we assume the whole expression
687** is constant. See sqlite3ExprIsConstant() for additional information.
drh626a8792005-01-17 22:08:19 +0000688*/
689static int exprNodeIsConstant(void *pArg, Expr *pExpr){
690 switch( pExpr->op ){
drheb55bd22005-06-30 17:04:21 +0000691 /* Consider functions to be constant if all their arguments are constant
692 ** and *pArg==2 */
693 case TK_FUNCTION:
694 if( *((int*)pArg)==2 ) return 0;
695 /* Fall through */
drh626a8792005-01-17 22:08:19 +0000696 case TK_ID:
697 case TK_COLUMN:
698 case TK_DOT:
699 case TK_AGG_FUNCTION:
drh13449892005-09-07 21:22:45 +0000700 case TK_AGG_COLUMN:
drhfe2093d2005-01-20 22:48:47 +0000701#ifndef SQLITE_OMIT_SUBQUERY
702 case TK_SELECT:
703 case TK_EXISTS:
704#endif
drh626a8792005-01-17 22:08:19 +0000705 *((int*)pArg) = 0;
706 return 2;
drh87abf5c2005-08-25 12:45:04 +0000707 case TK_IN:
708 if( pExpr->pSelect ){
709 *((int*)pArg) = 0;
710 return 2;
711 }
drh626a8792005-01-17 22:08:19 +0000712 default:
713 return 0;
714 }
715}
716
717/*
drhfef52082000-06-06 01:50:43 +0000718** Walk an expression tree. Return 1 if the expression is constant
drheb55bd22005-06-30 17:04:21 +0000719** and 0 if it involves variables or function calls.
drh23989372002-05-21 13:43:04 +0000720**
721** For the purposes of this function, a double-quoted string (ex: "abc")
722** is considered a variable but a single-quoted string (ex: 'abc') is
723** a constant.
drhfef52082000-06-06 01:50:43 +0000724*/
danielk19774adee202004-05-08 08:23:19 +0000725int sqlite3ExprIsConstant(Expr *p){
drh626a8792005-01-17 22:08:19 +0000726 int isConst = 1;
727 walkExprTree(p, exprNodeIsConstant, &isConst);
728 return isConst;
drhfef52082000-06-06 01:50:43 +0000729}
730
731/*
drheb55bd22005-06-30 17:04:21 +0000732** Walk an expression tree. Return 1 if the expression is constant
733** or a function call with constant arguments. Return and 0 if there
734** are any variables.
735**
736** For the purposes of this function, a double-quoted string (ex: "abc")
737** is considered a variable but a single-quoted string (ex: 'abc') is
738** a constant.
739*/
740int sqlite3ExprIsConstantOrFunction(Expr *p){
741 int isConst = 2;
742 walkExprTree(p, exprNodeIsConstant, &isConst);
743 return isConst!=0;
744}
745
746/*
drh73b211a2005-01-18 04:00:42 +0000747** If the expression p codes a constant integer that is small enough
drh202b2df2004-01-06 01:13:46 +0000748** to fit in a 32-bit integer, return 1 and put the value of the integer
749** in *pValue. If the expression is not an integer or if it is too big
750** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
drhe4de1fe2002-06-02 16:09:01 +0000751*/
danielk19774adee202004-05-08 08:23:19 +0000752int sqlite3ExprIsInteger(Expr *p, int *pValue){
drhe4de1fe2002-06-02 16:09:01 +0000753 switch( p->op ){
754 case TK_INTEGER: {
drh2646da72005-12-09 20:02:05 +0000755 if( sqlite3GetInt32((char*)p->token.z, pValue) ){
drh202b2df2004-01-06 01:13:46 +0000756 return 1;
757 }
758 break;
drhe4de1fe2002-06-02 16:09:01 +0000759 }
drh4b59ab52002-08-24 18:24:51 +0000760 case TK_UPLUS: {
danielk19774adee202004-05-08 08:23:19 +0000761 return sqlite3ExprIsInteger(p->pLeft, pValue);
drh4b59ab52002-08-24 18:24:51 +0000762 }
drhe4de1fe2002-06-02 16:09:01 +0000763 case TK_UMINUS: {
764 int v;
danielk19774adee202004-05-08 08:23:19 +0000765 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
drhe4de1fe2002-06-02 16:09:01 +0000766 *pValue = -v;
767 return 1;
768 }
769 break;
770 }
771 default: break;
772 }
773 return 0;
774}
775
776/*
drhc4a3c772001-04-04 11:48:57 +0000777** Return TRUE if the given string is a row-id column name.
778*/
danielk19774adee202004-05-08 08:23:19 +0000779int sqlite3IsRowid(const char *z){
780 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
781 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
782 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
drhc4a3c772001-04-04 11:48:57 +0000783 return 0;
784}
785
786/*
drh8141f612004-01-25 22:44:58 +0000787** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
788** that name in the set of source tables in pSrcList and make the pExpr
789** expression node refer back to that source column. The following changes
790** are made to pExpr:
791**
792** pExpr->iDb Set the index in db->aDb[] of the database holding
793** the table.
794** pExpr->iTable Set to the cursor number for the table obtained
795** from pSrcList.
796** pExpr->iColumn Set to the column number within the table.
drh8141f612004-01-25 22:44:58 +0000797** pExpr->op Set to TK_COLUMN.
798** pExpr->pLeft Any expression this points to is deleted
799** pExpr->pRight Any expression this points to is deleted.
800**
801** The pDbToken is the name of the database (the "X"). This value may be
802** NULL meaning that name is of the form Y.Z or Z. Any available database
803** can be used. The pTableToken is the name of the table (the "Y"). This
804** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
805** means that the form of the name is Z and that columns from any table
806** can be used.
807**
808** If the name cannot be resolved unambiguously, leave an error message
809** in pParse and return non-zero. Return zero on success.
810*/
811static int lookupName(
drhffe07b22005-11-03 00:41:17 +0000812 Parse *pParse, /* The parsing context */
drh8141f612004-01-25 22:44:58 +0000813 Token *pDbToken, /* Name of the database containing table, or NULL */
814 Token *pTableToken, /* Name of table containing column, or NULL */
815 Token *pColumnToken, /* Name of the column. */
drh626a8792005-01-17 22:08:19 +0000816 NameContext *pNC, /* The name context used to resolve the name */
drh8141f612004-01-25 22:44:58 +0000817 Expr *pExpr /* Make this EXPR node point to the selected column */
818){
819 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
820 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
821 char *zCol = 0; /* Name of the column. The "Z" */
822 int i, j; /* Loop counters */
823 int cnt = 0; /* Number of matching column names */
824 int cntTab = 0; /* Number of matching table names */
drh626a8792005-01-17 22:08:19 +0000825 sqlite3 *db = pParse->db; /* The database */
drh51669862004-12-18 18:40:26 +0000826 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
827 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
drh73b211a2005-01-18 04:00:42 +0000828 NameContext *pTopNC = pNC; /* First namecontext in the list */
drh8141f612004-01-25 22:44:58 +0000829
830 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
drha99db3b2004-06-19 14:49:12 +0000831 zDb = sqlite3NameFromToken(pDbToken);
832 zTab = sqlite3NameFromToken(pTableToken);
833 zCol = sqlite3NameFromToken(pColumnToken);
danielk1977e501b892006-01-09 06:29:47 +0000834 if( sqlite3ThreadData()->mallocFailed ){
danielk1977d5d56522005-03-16 12:15:20 +0000835 goto lookupname_end;
drh8141f612004-01-25 22:44:58 +0000836 }
drh8141f612004-01-25 22:44:58 +0000837
838 pExpr->iTable = -1;
drh626a8792005-01-17 22:08:19 +0000839 while( pNC && cnt==0 ){
drhffe07b22005-11-03 00:41:17 +0000840 ExprList *pEList;
drh626a8792005-01-17 22:08:19 +0000841 SrcList *pSrcList = pNC->pSrcList;
drh8141f612004-01-25 22:44:58 +0000842
danielk1977b3bce662005-01-29 08:32:43 +0000843 if( pSrcList ){
844 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
845 Table *pTab = pItem->pTab;
danielk1977da184232006-01-05 11:34:32 +0000846 int iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
danielk1977b3bce662005-01-29 08:32:43 +0000847 Column *pCol;
848
849 if( pTab==0 ) continue;
850 assert( pTab->nCol>0 );
851 if( zTab ){
852 if( pItem->zAlias ){
853 char *zTabName = pItem->zAlias;
854 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
855 }else{
856 char *zTabName = pTab->zName;
857 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
danielk1977da184232006-01-05 11:34:32 +0000858 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
danielk1977b3bce662005-01-29 08:32:43 +0000859 continue;
860 }
drh626a8792005-01-17 22:08:19 +0000861 }
drh8141f612004-01-25 22:44:58 +0000862 }
danielk1977b3bce662005-01-29 08:32:43 +0000863 if( 0==(cntTab++) ){
drh626a8792005-01-17 22:08:19 +0000864 pExpr->iTable = pItem->iCursor;
danielk1977da184232006-01-05 11:34:32 +0000865 pExpr->pSchema = pTab->pSchema;
danielk1977b3bce662005-01-29 08:32:43 +0000866 pMatch = pItem;
867 }
868 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
869 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +0000870 const char *zColl = pTab->aCol[j].zColl;
drh873fac02005-06-06 17:11:46 +0000871 IdList *pUsing;
danielk1977b3bce662005-01-29 08:32:43 +0000872 cnt++;
873 pExpr->iTable = pItem->iCursor;
874 pMatch = pItem;
danielk1977da184232006-01-05 11:34:32 +0000875 pExpr->pSchema = pTab->pSchema;
danielk1977b3bce662005-01-29 08:32:43 +0000876 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
877 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
878 pExpr->affinity = pTab->aCol[j].affinity;
danielk1977b3bf5562006-01-10 17:58:23 +0000879 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
drh355ef362005-06-06 16:59:24 +0000880 if( pItem->jointype & JT_NATURAL ){
881 /* If this match occurred in the left table of a natural join,
882 ** then skip the right table to avoid a duplicate match */
883 pItem++;
884 i++;
885 }
drh873fac02005-06-06 17:11:46 +0000886 if( (pUsing = pItem->pUsing)!=0 ){
887 /* If this match occurs on a column that is in the USING clause
888 ** of a join, skip the search of the right table of the join
889 ** to avoid a duplicate match there. */
890 int k;
891 for(k=0; k<pUsing->nId; k++){
892 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
893 pItem++;
894 i++;
895 break;
896 }
897 }
898 }
danielk1977b3bce662005-01-29 08:32:43 +0000899 break;
900 }
drh8141f612004-01-25 22:44:58 +0000901 }
902 }
903 }
drh626a8792005-01-17 22:08:19 +0000904
905#ifndef SQLITE_OMIT_TRIGGER
906 /* If we have not already resolved the name, then maybe
907 ** it is a new.* or old.* trigger argument reference
908 */
909 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
910 TriggerStack *pTriggerStack = pParse->trigStack;
911 Table *pTab = 0;
912 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
913 pExpr->iTable = pTriggerStack->newIdx;
914 assert( pTriggerStack->pTab );
915 pTab = pTriggerStack->pTab;
916 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
917 pExpr->iTable = pTriggerStack->oldIdx;
918 assert( pTriggerStack->pTab );
919 pTab = pTriggerStack->pTab;
920 }
921
922 if( pTab ){
923 int j;
924 Column *pCol = pTab->aCol;
925
danielk1977da184232006-01-05 11:34:32 +0000926 pExpr->pSchema = pTab->pSchema;
drh626a8792005-01-17 22:08:19 +0000927 cntTab++;
928 for(j=0; j < pTab->nCol; j++, pCol++) {
929 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
danielk1977b3bf5562006-01-10 17:58:23 +0000930 const char *zColl = pTab->aCol[j].zColl;
drh626a8792005-01-17 22:08:19 +0000931 cnt++;
932 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
933 pExpr->affinity = pTab->aCol[j].affinity;
danielk1977b3bf5562006-01-10 17:58:23 +0000934 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
danielk1977aee18ef2005-03-09 12:26:50 +0000935 pExpr->pTab = pTab;
drh626a8792005-01-17 22:08:19 +0000936 break;
937 }
938 }
939 }
940 }
drhb7f91642004-10-31 02:22:47 +0000941#endif /* !defined(SQLITE_OMIT_TRIGGER) */
drh8141f612004-01-25 22:44:58 +0000942
drh626a8792005-01-17 22:08:19 +0000943 /*
944 ** Perhaps the name is a reference to the ROWID
945 */
946 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
947 cnt = 1;
948 pExpr->iColumn = -1;
drh8a512562005-11-14 22:29:05 +0000949 pExpr->affinity = SQLITE_AFF_INTEGER;
drh626a8792005-01-17 22:08:19 +0000950 }
drh8141f612004-01-25 22:44:58 +0000951
drh626a8792005-01-17 22:08:19 +0000952 /*
953 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
954 ** might refer to an result-set alias. This happens, for example, when
955 ** we are resolving names in the WHERE clause of the following command:
956 **
957 ** SELECT a+b AS x FROM table WHERE x<10;
958 **
959 ** In cases like this, replace pExpr with a copy of the expression that
960 ** forms the result set entry ("a+b" in the example) and return immediately.
961 ** Note that the expression in the result set should have already been
962 ** resolved by the time the WHERE clause is resolved.
963 */
drhffe07b22005-11-03 00:41:17 +0000964 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
drh626a8792005-01-17 22:08:19 +0000965 for(j=0; j<pEList->nExpr; j++){
966 char *zAs = pEList->a[j].zName;
967 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
968 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
969 pExpr->op = TK_AS;
970 pExpr->iColumn = j;
971 pExpr->pLeft = sqlite3ExprDup(pEList->a[j].pExpr);
drh15ccce12005-05-23 15:06:39 +0000972 cnt = 1;
drh626a8792005-01-17 22:08:19 +0000973 assert( zTab==0 && zDb==0 );
drh15ccce12005-05-23 15:06:39 +0000974 goto lookupname_end_2;
drh626a8792005-01-17 22:08:19 +0000975 }
976 }
977 }
978
979 /* Advance to the next name context. The loop will exit when either
980 ** we have a match (cnt>0) or when we run out of name contexts.
981 */
982 if( cnt==0 ){
983 pNC = pNC->pNext;
984 }
drh8141f612004-01-25 22:44:58 +0000985 }
986
987 /*
988 ** If X and Y are NULL (in other words if only the column name Z is
989 ** supplied) and the value of Z is enclosed in double-quotes, then
990 ** Z is a string literal if it doesn't match any column names. In that
991 ** case, we need to return right away and not make any changes to
992 ** pExpr.
drh15ccce12005-05-23 15:06:39 +0000993 **
994 ** Because no reference was made to outer contexts, the pNC->nRef
995 ** fields are not changed in any context.
drh8141f612004-01-25 22:44:58 +0000996 */
997 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
998 sqliteFree(zCol);
999 return 0;
1000 }
1001
1002 /*
1003 ** cnt==0 means there was not match. cnt>1 means there were two or
1004 ** more matches. Either way, we have an error.
1005 */
1006 if( cnt!=1 ){
1007 char *z = 0;
1008 char *zErr;
1009 zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
1010 if( zDb ){
drhf93339d2006-01-03 15:16:26 +00001011 sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
drh8141f612004-01-25 22:44:58 +00001012 }else if( zTab ){
drhf93339d2006-01-03 15:16:26 +00001013 sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
drh8141f612004-01-25 22:44:58 +00001014 }else{
1015 z = sqliteStrDup(zCol);
1016 }
danielk19774adee202004-05-08 08:23:19 +00001017 sqlite3ErrorMsg(pParse, zErr, z);
drh8141f612004-01-25 22:44:58 +00001018 sqliteFree(z);
drh73b211a2005-01-18 04:00:42 +00001019 pTopNC->nErr++;
drh8141f612004-01-25 22:44:58 +00001020 }
1021
drh51669862004-12-18 18:40:26 +00001022 /* If a column from a table in pSrcList is referenced, then record
1023 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
1024 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
1025 ** column number is greater than the number of bits in the bitmask
1026 ** then set the high-order bit of the bitmask.
1027 */
1028 if( pExpr->iColumn>=0 && pMatch!=0 ){
1029 int n = pExpr->iColumn;
1030 if( n>=sizeof(Bitmask)*8 ){
1031 n = sizeof(Bitmask)*8-1;
1032 }
1033 assert( pMatch->iCursor==pExpr->iTable );
1034 pMatch->colUsed |= 1<<n;
1035 }
1036
danielk1977d5d56522005-03-16 12:15:20 +00001037lookupname_end:
drh8141f612004-01-25 22:44:58 +00001038 /* Clean up and return
1039 */
1040 sqliteFree(zDb);
1041 sqliteFree(zTab);
danielk19774adee202004-05-08 08:23:19 +00001042 sqlite3ExprDelete(pExpr->pLeft);
drh8141f612004-01-25 22:44:58 +00001043 pExpr->pLeft = 0;
danielk19774adee202004-05-08 08:23:19 +00001044 sqlite3ExprDelete(pExpr->pRight);
drh8141f612004-01-25 22:44:58 +00001045 pExpr->pRight = 0;
1046 pExpr->op = TK_COLUMN;
drh15ccce12005-05-23 15:06:39 +00001047lookupname_end_2:
1048 sqliteFree(zCol);
drh626a8792005-01-17 22:08:19 +00001049 if( cnt==1 ){
danielk1977b3bce662005-01-29 08:32:43 +00001050 assert( pNC!=0 );
drh626a8792005-01-17 22:08:19 +00001051 sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
danielk1977aee18ef2005-03-09 12:26:50 +00001052 if( pMatch && !pMatch->pSelect ){
1053 pExpr->pTab = pMatch->pTab;
1054 }
drh15ccce12005-05-23 15:06:39 +00001055 /* Increment the nRef value on all name contexts from TopNC up to
1056 ** the point where the name matched. */
1057 for(;;){
1058 assert( pTopNC!=0 );
1059 pTopNC->nRef++;
1060 if( pTopNC==pNC ) break;
1061 pTopNC = pTopNC->pNext;
1062 }
1063 return 0;
1064 } else {
1065 return 1;
drh626a8792005-01-17 22:08:19 +00001066 }
drh8141f612004-01-25 22:44:58 +00001067}
1068
1069/*
drh626a8792005-01-17 22:08:19 +00001070** This routine is designed as an xFunc for walkExprTree().
1071**
drh73b211a2005-01-18 04:00:42 +00001072** Resolve symbolic names into TK_COLUMN operators for the current
drh626a8792005-01-17 22:08:19 +00001073** node in the expression tree. Return 0 to continue the search down
drh73b211a2005-01-18 04:00:42 +00001074** the tree or 2 to abort the tree walk.
1075**
1076** This routine also does error checking and name resolution for
1077** function names. The operator for aggregate functions is changed
1078** to TK_AGG_FUNCTION.
drh626a8792005-01-17 22:08:19 +00001079*/
1080static int nameResolverStep(void *pArg, Expr *pExpr){
1081 NameContext *pNC = (NameContext*)pArg;
1082 SrcList *pSrcList;
1083 Parse *pParse;
drh626a8792005-01-17 22:08:19 +00001084
danielk1977b3bce662005-01-29 08:32:43 +00001085 if( pExpr==0 ) return 1;
drh626a8792005-01-17 22:08:19 +00001086 assert( pNC!=0 );
1087 pSrcList = pNC->pSrcList;
1088 pParse = pNC->pParse;
danielk1977b3bce662005-01-29 08:32:43 +00001089
drh626a8792005-01-17 22:08:19 +00001090 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1091 ExprSetProperty(pExpr, EP_Resolved);
1092#ifndef NDEBUG
drhffe07b22005-11-03 00:41:17 +00001093 if( pSrcList && pSrcList->nAlloc>0 ){
danielk1977940fac92005-01-23 22:41:37 +00001094 int i;
drh626a8792005-01-17 22:08:19 +00001095 for(i=0; i<pSrcList->nSrc; i++){
1096 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1097 }
1098 }
1099#endif
1100 switch( pExpr->op ){
1101 /* Double-quoted strings (ex: "abc") are used as identifiers if
1102 ** possible. Otherwise they remain as strings. Single-quoted
1103 ** strings (ex: 'abc') are always string literals.
1104 */
1105 case TK_STRING: {
1106 if( pExpr->token.z[0]=='\'' ) break;
1107 /* Fall thru into the TK_ID case if this is a double-quoted string */
1108 }
1109 /* A lone identifier is the name of a column.
1110 */
1111 case TK_ID: {
drh626a8792005-01-17 22:08:19 +00001112 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1113 return 1;
1114 }
1115
1116 /* A table name and column name: ID.ID
1117 ** Or a database, table and column: ID.ID.ID
1118 */
1119 case TK_DOT: {
1120 Token *pColumn;
1121 Token *pTable;
1122 Token *pDb;
1123 Expr *pRight;
1124
danielk1977b3bce662005-01-29 08:32:43 +00001125 /* if( pSrcList==0 ) break; */
drh626a8792005-01-17 22:08:19 +00001126 pRight = pExpr->pRight;
1127 if( pRight->op==TK_ID ){
1128 pDb = 0;
1129 pTable = &pExpr->pLeft->token;
1130 pColumn = &pRight->token;
1131 }else{
1132 assert( pRight->op==TK_DOT );
1133 pDb = &pExpr->pLeft->token;
1134 pTable = &pRight->pLeft->token;
1135 pColumn = &pRight->pRight->token;
1136 }
1137 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1138 return 1;
1139 }
1140
1141 /* Resolve function names
1142 */
drhb71090f2005-05-23 17:26:51 +00001143 case TK_CONST_FUNC:
drh626a8792005-01-17 22:08:19 +00001144 case TK_FUNCTION: {
1145 ExprList *pList = pExpr->pList; /* The argument list */
1146 int n = pList ? pList->nExpr : 0; /* Number of arguments */
1147 int no_such_func = 0; /* True if no such function exists */
1148 int wrong_num_args = 0; /* True if wrong number of arguments */
1149 int is_agg = 0; /* True if is an aggregate function */
1150 int i;
1151 int nId; /* Number of characters in function name */
1152 const char *zId; /* The function name. */
drh73b211a2005-01-18 04:00:42 +00001153 FuncDef *pDef; /* Information about the function */
danielk197714db2662006-01-09 16:12:04 +00001154 int enc = ENC(pParse->db); /* The database encoding */
drh626a8792005-01-17 22:08:19 +00001155
drh2646da72005-12-09 20:02:05 +00001156 zId = (char*)pExpr->token.z;
drhb71090f2005-05-23 17:26:51 +00001157 nId = pExpr->token.n;
drh626a8792005-01-17 22:08:19 +00001158 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1159 if( pDef==0 ){
1160 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1161 if( pDef==0 ){
1162 no_such_func = 1;
1163 }else{
1164 wrong_num_args = 1;
1165 }
1166 }else{
1167 is_agg = pDef->xFunc==0;
1168 }
1169 if( is_agg && !pNC->allowAgg ){
1170 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1171 pNC->nErr++;
1172 is_agg = 0;
1173 }else if( no_such_func ){
1174 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1175 pNC->nErr++;
1176 }else if( wrong_num_args ){
1177 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1178 nId, zId);
1179 pNC->nErr++;
1180 }
1181 if( is_agg ){
1182 pExpr->op = TK_AGG_FUNCTION;
1183 pNC->hasAgg = 1;
1184 }
drh73b211a2005-01-18 04:00:42 +00001185 if( is_agg ) pNC->allowAgg = 0;
drh626a8792005-01-17 22:08:19 +00001186 for(i=0; pNC->nErr==0 && i<n; i++){
drh73b211a2005-01-18 04:00:42 +00001187 walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
drh626a8792005-01-17 22:08:19 +00001188 }
drh73b211a2005-01-18 04:00:42 +00001189 if( is_agg ) pNC->allowAgg = 1;
drh626a8792005-01-17 22:08:19 +00001190 /* FIX ME: Compute pExpr->affinity based on the expected return
1191 ** type of the function
1192 */
1193 return is_agg;
1194 }
danielk1977b3bce662005-01-29 08:32:43 +00001195#ifndef SQLITE_OMIT_SUBQUERY
1196 case TK_SELECT:
1197 case TK_EXISTS:
1198#endif
1199 case TK_IN: {
1200 if( pExpr->pSelect ){
drh8a9f38f2005-11-05 15:07:55 +00001201 int nRef = pNC->nRef;
drh06f65412005-11-03 02:03:13 +00001202#ifndef SQLITE_OMIT_CHECK
1203 if( pNC->isCheck ){
1204 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
1205 }
1206#endif
danielk1977b3bce662005-01-29 08:32:43 +00001207 sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1208 assert( pNC->nRef>=nRef );
1209 if( nRef!=pNC->nRef ){
1210 ExprSetProperty(pExpr, EP_VarSelect);
1211 }
1212 }
drh4284fb02005-11-03 12:33:28 +00001213 break;
danielk1977b3bce662005-01-29 08:32:43 +00001214 }
drh4284fb02005-11-03 12:33:28 +00001215#ifndef SQLITE_OMIT_CHECK
1216 case TK_VARIABLE: {
1217 if( pNC->isCheck ){
1218 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
1219 }
1220 break;
1221 }
1222#endif
drh626a8792005-01-17 22:08:19 +00001223 }
1224 return 0;
1225}
1226
1227/*
drhcce7d172000-05-31 15:34:51 +00001228** This routine walks an expression tree and resolves references to
drh967e8b72000-06-21 13:59:10 +00001229** table columns. Nodes of the form ID.ID or ID resolve into an
drhaacc5432002-01-06 17:07:40 +00001230** index to the table in the table list and a column offset. The
1231** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
1232** value is changed to the index of the referenced table in pTabList
drh832508b2002-03-02 17:04:07 +00001233** plus the "base" value. The base value will ultimately become the
drhaacc5432002-01-06 17:07:40 +00001234** VDBE cursor number for a cursor that is pointing into the referenced
1235** table. The Expr.iColumn value is changed to the index of the column
1236** of the referenced table. The Expr.iColumn value for the special
1237** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
1238** alias for ROWID.
drh19a775c2000-06-05 18:54:46 +00001239**
drh626a8792005-01-17 22:08:19 +00001240** Also resolve function names and check the functions for proper
1241** usage. Make sure all function names are recognized and all functions
1242** have the correct number of arguments. Leave an error message
1243** in pParse->zErrMsg if anything is amiss. Return the number of errors.
1244**
drh73b211a2005-01-18 04:00:42 +00001245** If the expression contains aggregate functions then set the EP_Agg
1246** property on the expression.
drh626a8792005-01-17 22:08:19 +00001247*/
1248int sqlite3ExprResolveNames(
danielk1977b3bce662005-01-29 08:32:43 +00001249 NameContext *pNC, /* Namespace to resolve expressions in. */
1250 Expr *pExpr /* The expression to be analyzed. */
drh626a8792005-01-17 22:08:19 +00001251){
drh13449892005-09-07 21:22:45 +00001252 int savedHasAgg;
drh73b211a2005-01-18 04:00:42 +00001253 if( pExpr==0 ) return 0;
drh13449892005-09-07 21:22:45 +00001254 savedHasAgg = pNC->hasAgg;
1255 pNC->hasAgg = 0;
danielk1977b3bce662005-01-29 08:32:43 +00001256 walkExprTree(pExpr, nameResolverStep, pNC);
1257 if( pNC->nErr>0 ){
drh73b211a2005-01-18 04:00:42 +00001258 ExprSetProperty(pExpr, EP_Error);
drh73b211a2005-01-18 04:00:42 +00001259 }
drh13449892005-09-07 21:22:45 +00001260 if( pNC->hasAgg ){
1261 ExprSetProperty(pExpr, EP_Agg);
1262 }else if( savedHasAgg ){
1263 pNC->hasAgg = 1;
1264 }
drh73b211a2005-01-18 04:00:42 +00001265 return ExprHasProperty(pExpr, EP_Error);
drh626a8792005-01-17 22:08:19 +00001266}
1267
drh1398ad32005-01-19 23:24:50 +00001268/*
1269** A pointer instance of this structure is used to pass information
1270** through walkExprTree into codeSubqueryStep().
1271*/
1272typedef struct QueryCoder QueryCoder;
1273struct QueryCoder {
1274 Parse *pParse; /* The parsing context */
1275 NameContext *pNC; /* Namespace of first enclosing query */
1276};
1277
drh626a8792005-01-17 22:08:19 +00001278
1279/*
drh9cbe6352005-11-29 03:13:21 +00001280** Generate code for scalar subqueries used as an expression
1281** and IN operators. Examples:
drh626a8792005-01-17 22:08:19 +00001282**
drh9cbe6352005-11-29 03:13:21 +00001283** (SELECT a FROM b) -- subquery
1284** EXISTS (SELECT a FROM b) -- EXISTS subquery
1285** x IN (4,5,11) -- IN operator with list on right-hand side
1286** x IN (SELECT a FROM b) -- IN operator with subquery on the right
drhfef52082000-06-06 01:50:43 +00001287**
drh9cbe6352005-11-29 03:13:21 +00001288** The pExpr parameter describes the expression that contains the IN
1289** operator or subquery.
drhcce7d172000-05-31 15:34:51 +00001290*/
drh51522cd2005-01-20 13:36:19 +00001291#ifndef SQLITE_OMIT_SUBQUERY
danielk1977b3bce662005-01-29 08:32:43 +00001292void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
drh57dbd7b2005-07-08 18:25:26 +00001293 int testAddr = 0; /* One-time test address */
danielk1977b3bce662005-01-29 08:32:43 +00001294 Vdbe *v = sqlite3GetVdbe(pParse);
1295 if( v==0 ) return;
1296
drh57dbd7b2005-07-08 18:25:26 +00001297 /* This code must be run in its entirety every time it is encountered
1298 ** if any of the following is true:
1299 **
1300 ** * The right-hand side is a correlated subquery
1301 ** * The right-hand side is an expression list containing variables
1302 ** * We are inside a trigger
1303 **
1304 ** If all of the above are false, then we can run this code just once
1305 ** save the results, and reuse the same result on subsequent invocations.
danielk1977b3bce662005-01-29 08:32:43 +00001306 */
1307 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1308 int mem = pParse->nMem++;
1309 sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
drh57dbd7b2005-07-08 18:25:26 +00001310 testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
danielk1977e501b892006-01-09 06:29:47 +00001311 assert( testAddr>0 || sqlite3ThreadData()->mallocFailed );
drhd654be82005-09-20 17:42:23 +00001312 sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
danielk1977b3bce662005-01-29 08:32:43 +00001313 }
1314
drhcce7d172000-05-31 15:34:51 +00001315 switch( pExpr->op ){
drhfef52082000-06-06 01:50:43 +00001316 case TK_IN: {
danielk1977e014a832004-05-17 10:48:57 +00001317 char affinity;
drhd3d39e92004-05-20 22:16:29 +00001318 KeyInfo keyInfo;
drh9170dd72005-07-08 17:13:46 +00001319 int addr; /* Address of OP_OpenVirtual instruction */
drhd3d39e92004-05-20 22:16:29 +00001320
danielk1977bf3b7212004-05-18 10:06:24 +00001321 affinity = sqlite3ExprAffinity(pExpr->pLeft);
danielk1977e014a832004-05-17 10:48:57 +00001322
1323 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
drh57dbd7b2005-07-08 18:25:26 +00001324 ** expression it is handled the same way. A virtual table is
danielk1977e014a832004-05-17 10:48:57 +00001325 ** filled with single-field index keys representing the results
1326 ** from the SELECT or the <exprlist>.
1327 **
1328 ** If the 'x' expression is a column value, or the SELECT...
1329 ** statement returns a column value, then the affinity of that
1330 ** column is used to build the index keys. If both 'x' and the
1331 ** SELECT... statement are columns, then numeric affinity is used
1332 ** if either column has NUMERIC or INTEGER affinity. If neither
1333 ** 'x' nor the SELECT... statement are columns, then numeric affinity
1334 ** is used.
1335 */
1336 pExpr->iTable = pParse->nTab++;
drh9170dd72005-07-08 17:13:46 +00001337 addr = sqlite3VdbeAddOp(v, OP_OpenVirtual, pExpr->iTable, 0);
drhd3d39e92004-05-20 22:16:29 +00001338 memset(&keyInfo, 0, sizeof(keyInfo));
1339 keyInfo.nField = 1;
drhf3218fe2004-05-28 08:21:02 +00001340 sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
danielk1977e014a832004-05-17 10:48:57 +00001341
drhfef52082000-06-06 01:50:43 +00001342 if( pExpr->pSelect ){
1343 /* Case 1: expr IN (SELECT ...)
1344 **
danielk1977e014a832004-05-17 10:48:57 +00001345 ** Generate code to write the results of the select into the temporary
1346 ** table allocated and opened above.
drhfef52082000-06-06 01:50:43 +00001347 */
danielk1977e014a832004-05-17 10:48:57 +00001348 int iParm = pExpr->iTable + (((int)affinity)<<16);
drhbe5c89a2004-07-26 00:31:09 +00001349 ExprList *pEList;
danielk1977e014a832004-05-17 10:48:57 +00001350 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
danielk1977b3bce662005-01-29 08:32:43 +00001351 sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0);
drhbe5c89a2004-07-26 00:31:09 +00001352 pEList = pExpr->pSelect->pEList;
1353 if( pEList && pEList->nExpr>0 ){
danielk19777cedc8d2004-06-10 10:50:08 +00001354 keyInfo.aColl[0] = binaryCompareCollSeq(pParse, pExpr->pLeft,
drhbe5c89a2004-07-26 00:31:09 +00001355 pEList->a[0].pExpr);
danielk19770202b292004-06-09 09:55:16 +00001356 }
drhfef52082000-06-06 01:50:43 +00001357 }else if( pExpr->pList ){
1358 /* Case 2: expr IN (exprlist)
1359 **
danielk1977e014a832004-05-17 10:48:57 +00001360 ** For each expression, build an index key from the evaluation and
1361 ** store it in the temporary table. If <expr> is a column, then use
1362 ** that columns affinity when building index keys. If <expr> is not
1363 ** a column, use numeric affinity.
drhfef52082000-06-06 01:50:43 +00001364 */
danielk1977e014a832004-05-17 10:48:57 +00001365 int i;
drh57dbd7b2005-07-08 18:25:26 +00001366 ExprList *pList = pExpr->pList;
1367 struct ExprList_item *pItem;
1368
danielk1977e014a832004-05-17 10:48:57 +00001369 if( !affinity ){
1370 affinity = SQLITE_AFF_NUMERIC;
1371 }
danielk19770202b292004-06-09 09:55:16 +00001372 keyInfo.aColl[0] = pExpr->pLeft->pColl;
danielk1977e014a832004-05-17 10:48:57 +00001373
1374 /* Loop through each expression in <exprlist>. */
drh57dbd7b2005-07-08 18:25:26 +00001375 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1376 Expr *pE2 = pItem->pExpr;
danielk1977e014a832004-05-17 10:48:57 +00001377
drh57dbd7b2005-07-08 18:25:26 +00001378 /* If the expression is not constant then we will need to
1379 ** disable the test that was generated above that makes sure
1380 ** this code only executes once. Because for a non-constant
1381 ** expression we need to rerun this code each time.
1382 */
drh6c30be82005-07-29 15:10:17 +00001383 if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
drh57dbd7b2005-07-08 18:25:26 +00001384 VdbeOp *aOp = sqlite3VdbeGetOp(v, testAddr-1);
1385 int i;
drhd654be82005-09-20 17:42:23 +00001386 for(i=0; i<3; i++){
drh57dbd7b2005-07-08 18:25:26 +00001387 aOp[i].opcode = OP_Noop;
1388 }
1389 testAddr = 0;
drh4794b982000-06-06 13:54:14 +00001390 }
danielk1977e014a832004-05-17 10:48:57 +00001391
1392 /* Evaluate the expression and insert it into the temp table */
1393 sqlite3ExprCode(pParse, pE2);
drh94a11212004-09-25 13:12:14 +00001394 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
drhf0863fe2005-06-12 21:35:51 +00001395 sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
drhfef52082000-06-06 01:50:43 +00001396 }
1397 }
danielk19770202b292004-06-09 09:55:16 +00001398 sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
danielk1977b3bce662005-01-29 08:32:43 +00001399 break;
drhfef52082000-06-06 01:50:43 +00001400 }
1401
drh51522cd2005-01-20 13:36:19 +00001402 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00001403 case TK_SELECT: {
drhfef52082000-06-06 01:50:43 +00001404 /* This has to be a scalar SELECT. Generate code to put the
1405 ** value of this select in a memory cell and record the number
drh967e8b72000-06-21 13:59:10 +00001406 ** of the memory cell in iColumn.
drhfef52082000-06-06 01:50:43 +00001407 */
drh2646da72005-12-09 20:02:05 +00001408 static const Token one = { (u8*)"1", 0, 1 };
drh51522cd2005-01-20 13:36:19 +00001409 Select *pSel;
drhec7429a2005-10-06 16:53:14 +00001410 int iMem;
1411 int sop;
drh1398ad32005-01-19 23:24:50 +00001412
drhec7429a2005-10-06 16:53:14 +00001413 pExpr->iColumn = iMem = pParse->nMem++;
drh51522cd2005-01-20 13:36:19 +00001414 pSel = pExpr->pSelect;
1415 if( pExpr->op==TK_SELECT ){
1416 sop = SRT_Mem;
drhec7429a2005-10-06 16:53:14 +00001417 sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1418 VdbeComment((v, "# Init subquery result"));
drh51522cd2005-01-20 13:36:19 +00001419 }else{
drh51522cd2005-01-20 13:36:19 +00001420 sop = SRT_Exists;
drhec7429a2005-10-06 16:53:14 +00001421 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1422 VdbeComment((v, "# Init EXISTS result"));
drh51522cd2005-01-20 13:36:19 +00001423 }
drhec7429a2005-10-06 16:53:14 +00001424 sqlite3ExprDelete(pSel->pLimit);
1425 pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
1426 sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0);
danielk1977b3bce662005-01-29 08:32:43 +00001427 break;
drhcce7d172000-05-31 15:34:51 +00001428 }
1429 }
danielk1977b3bce662005-01-29 08:32:43 +00001430
drh57dbd7b2005-07-08 18:25:26 +00001431 if( testAddr ){
drhd654be82005-09-20 17:42:23 +00001432 sqlite3VdbeJumpHere(v, testAddr);
danielk1977b3bce662005-01-29 08:32:43 +00001433 }
1434 return;
drhcce7d172000-05-31 15:34:51 +00001435}
drh51522cd2005-01-20 13:36:19 +00001436#endif /* SQLITE_OMIT_SUBQUERY */
drhcce7d172000-05-31 15:34:51 +00001437
drhcce7d172000-05-31 15:34:51 +00001438/*
drhfec19aa2004-05-19 20:41:03 +00001439** Generate an instruction that will put the integer describe by
1440** text z[0..n-1] on the stack.
1441*/
1442static void codeInteger(Vdbe *v, const char *z, int n){
1443 int i;
drh6fec0762004-05-30 01:38:43 +00001444 if( sqlite3GetInt32(z, &i) ){
1445 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
1446 }else if( sqlite3FitsIn64Bits(z) ){
drh29dda4a2005-07-21 18:23:20 +00001447 sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
drhfec19aa2004-05-19 20:41:03 +00001448 }else{
1449 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1450 }
1451}
1452
1453/*
drhcce7d172000-05-31 15:34:51 +00001454** Generate code into the current Vdbe to evaluate the given
drh1ccde152000-06-17 13:12:39 +00001455** expression and leave the result on the top of stack.
drhf2bc0132004-10-04 13:19:23 +00001456**
1457** This code depends on the fact that certain token values (ex: TK_EQ)
1458** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1459** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
1460** the make process cause these values to align. Assert()s in the code
1461** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00001462*/
danielk19774adee202004-05-08 08:23:19 +00001463void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
drhcce7d172000-05-31 15:34:51 +00001464 Vdbe *v = pParse->pVdbe;
1465 int op;
drhffe07b22005-11-03 00:41:17 +00001466 int stackChng = 1; /* Amount of change to stack depth */
1467
danielk19777977a172004-11-09 12:44:37 +00001468 if( v==0 ) return;
1469 if( pExpr==0 ){
drhf0863fe2005-06-12 21:35:51 +00001470 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk19777977a172004-11-09 12:44:37 +00001471 return;
1472 }
drhf2bc0132004-10-04 13:19:23 +00001473 op = pExpr->op;
1474 switch( op ){
drh13449892005-09-07 21:22:45 +00001475 case TK_AGG_COLUMN: {
1476 AggInfo *pAggInfo = pExpr->pAggInfo;
1477 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
1478 if( !pAggInfo->directMode ){
1479 sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
1480 break;
1481 }else if( pAggInfo->useSortingIdx ){
1482 sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
1483 pCol->iSorterColumn);
1484 break;
1485 }
1486 /* Otherwise, fall thru into the TK_COLUMN case */
1487 }
drh967e8b72000-06-21 13:59:10 +00001488 case TK_COLUMN: {
drhffe07b22005-11-03 00:41:17 +00001489 if( pExpr->iTable<0 ){
1490 /* This only happens when coding check constraints */
1491 assert( pParse->ckOffset>0 );
1492 sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1493 }else if( pExpr->iColumn>=0 ){
drh8a512562005-11-14 22:29:05 +00001494 Table *pTab = pExpr->pTab;
1495 int iCol = pExpr->iColumn;
1496 sqlite3VdbeAddOp(v, OP_Column, pExpr->iTable, iCol);
1497 sqlite3ColumnDefault(v, pTab, iCol);
1498#ifndef SQLITE_OMIT_FLOATING_POINT
1499 if( pTab && pTab->aCol[iCol].affinity==SQLITE_AFF_REAL ){
1500 sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1501 }
1502#endif
drhc4a3c772001-04-04 11:48:57 +00001503 }else{
drhf0863fe2005-06-12 21:35:51 +00001504 sqlite3VdbeAddOp(v, OP_Rowid, pExpr->iTable, 0);
drh22827922000-06-06 17:27:05 +00001505 }
drhcce7d172000-05-31 15:34:51 +00001506 break;
1507 }
1508 case TK_INTEGER: {
drh2646da72005-12-09 20:02:05 +00001509 codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
drhfec19aa2004-05-19 20:41:03 +00001510 break;
1511 }
1512 case TK_FLOAT:
1513 case TK_STRING: {
drhf2bc0132004-10-04 13:19:23 +00001514 assert( TK_FLOAT==OP_Real );
1515 assert( TK_STRING==OP_String8 );
drhd2687b72005-08-12 22:56:09 +00001516 sqlite3DequoteExpr(pExpr);
drh2646da72005-12-09 20:02:05 +00001517 sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
drhcce7d172000-05-31 15:34:51 +00001518 break;
1519 }
drhf0863fe2005-06-12 21:35:51 +00001520 case TK_NULL: {
1521 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1522 break;
1523 }
danielk19775338a5f2005-01-20 13:03:10 +00001524#ifndef SQLITE_OMIT_BLOB_LITERAL
danielk1977c572ef72004-05-27 09:28:41 +00001525 case TK_BLOB: {
drh6c8c6ce2005-08-23 11:17:58 +00001526 int n;
1527 const char *z;
drhf2bc0132004-10-04 13:19:23 +00001528 assert( TK_BLOB==OP_HexBlob );
drh6c8c6ce2005-08-23 11:17:58 +00001529 n = pExpr->token.n - 3;
drh2646da72005-12-09 20:02:05 +00001530 z = (char*)pExpr->token.z + 2;
drh6c8c6ce2005-08-23 11:17:58 +00001531 assert( n>=0 );
1532 if( n==0 ){
1533 z = "";
1534 }
1535 sqlite3VdbeOp3(v, op, 0, 0, z, n);
danielk1977c572ef72004-05-27 09:28:41 +00001536 break;
1537 }
danielk19775338a5f2005-01-20 13:03:10 +00001538#endif
drh50457892003-09-06 01:10:47 +00001539 case TK_VARIABLE: {
danielk19774adee202004-05-08 08:23:19 +00001540 sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
drh895d7472004-08-20 16:02:39 +00001541 if( pExpr->token.n>1 ){
drh2646da72005-12-09 20:02:05 +00001542 sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
drh895d7472004-08-20 16:02:39 +00001543 }
drh50457892003-09-06 01:10:47 +00001544 break;
1545 }
drh4e0cff62004-11-05 05:10:28 +00001546 case TK_REGISTER: {
1547 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
1548 break;
1549 }
drh487e2622005-06-25 18:42:14 +00001550#ifndef SQLITE_OMIT_CAST
1551 case TK_CAST: {
1552 /* Expressions of the form: CAST(pLeft AS token) */
1553 int aff, op;
1554 sqlite3ExprCode(pParse, pExpr->pLeft);
drh8a512562005-11-14 22:29:05 +00001555 aff = sqlite3AffinityType(&pExpr->token);
1556 op = aff - SQLITE_AFF_TEXT + OP_ToText;
1557 assert( op==OP_ToText || aff!=SQLITE_AFF_TEXT );
1558 assert( op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
1559 assert( op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1560 assert( op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
1561 assert( op==OP_ToReal || aff!=SQLITE_AFF_REAL );
drh487e2622005-06-25 18:42:14 +00001562 sqlite3VdbeAddOp(v, op, 0, 0);
drhffe07b22005-11-03 00:41:17 +00001563 stackChng = 0;
drh487e2622005-06-25 18:42:14 +00001564 break;
1565 }
1566#endif /* SQLITE_OMIT_CAST */
drhc9b84a12002-06-20 11:36:48 +00001567 case TK_LT:
1568 case TK_LE:
1569 case TK_GT:
1570 case TK_GE:
1571 case TK_NE:
1572 case TK_EQ: {
drhf2bc0132004-10-04 13:19:23 +00001573 assert( TK_LT==OP_Lt );
1574 assert( TK_LE==OP_Le );
1575 assert( TK_GT==OP_Gt );
1576 assert( TK_GE==OP_Ge );
1577 assert( TK_EQ==OP_Eq );
1578 assert( TK_NE==OP_Ne );
danielk1977a37cdde2004-05-16 11:15:36 +00001579 sqlite3ExprCode(pParse, pExpr->pLeft);
1580 sqlite3ExprCode(pParse, pExpr->pRight);
drhbe5c89a2004-07-26 00:31:09 +00001581 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
drhffe07b22005-11-03 00:41:17 +00001582 stackChng = -1;
danielk1977a37cdde2004-05-16 11:15:36 +00001583 break;
drhc9b84a12002-06-20 11:36:48 +00001584 }
drhcce7d172000-05-31 15:34:51 +00001585 case TK_AND:
1586 case TK_OR:
1587 case TK_PLUS:
1588 case TK_STAR:
1589 case TK_MINUS:
drhbf4133c2001-10-13 02:59:08 +00001590 case TK_REM:
1591 case TK_BITAND:
1592 case TK_BITOR:
drh17c40292004-07-21 02:53:29 +00001593 case TK_SLASH:
drhbf4133c2001-10-13 02:59:08 +00001594 case TK_LSHIFT:
drh855eb1c2004-08-31 13:45:11 +00001595 case TK_RSHIFT:
drh00400772000-06-16 20:51:26 +00001596 case TK_CONCAT: {
drhf2bc0132004-10-04 13:19:23 +00001597 assert( TK_AND==OP_And );
1598 assert( TK_OR==OP_Or );
1599 assert( TK_PLUS==OP_Add );
1600 assert( TK_MINUS==OP_Subtract );
1601 assert( TK_REM==OP_Remainder );
1602 assert( TK_BITAND==OP_BitAnd );
1603 assert( TK_BITOR==OP_BitOr );
1604 assert( TK_SLASH==OP_Divide );
1605 assert( TK_LSHIFT==OP_ShiftLeft );
1606 assert( TK_RSHIFT==OP_ShiftRight );
1607 assert( TK_CONCAT==OP_Concat );
danielk19774adee202004-05-08 08:23:19 +00001608 sqlite3ExprCode(pParse, pExpr->pLeft);
1609 sqlite3ExprCode(pParse, pExpr->pRight);
drh855eb1c2004-08-31 13:45:11 +00001610 sqlite3VdbeAddOp(v, op, 0, 0);
drhffe07b22005-11-03 00:41:17 +00001611 stackChng = -1;
drh00400772000-06-16 20:51:26 +00001612 break;
1613 }
drhcce7d172000-05-31 15:34:51 +00001614 case TK_UMINUS: {
drhfec19aa2004-05-19 20:41:03 +00001615 Expr *pLeft = pExpr->pLeft;
1616 assert( pLeft );
1617 if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1618 Token *p = &pLeft->token;
drh9267bdc2005-11-28 12:36:35 +00001619 char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
drhfec19aa2004-05-19 20:41:03 +00001620 if( pLeft->op==TK_FLOAT ){
1621 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
drhe6840902002-03-06 03:08:25 +00001622 }else{
drhfec19aa2004-05-19 20:41:03 +00001623 codeInteger(v, z, p->n+1);
drhe6840902002-03-06 03:08:25 +00001624 }
drh6e142f52000-06-08 13:36:40 +00001625 sqliteFree(z);
1626 break;
1627 }
drh1ccde152000-06-17 13:12:39 +00001628 /* Fall through into TK_NOT */
drh6e142f52000-06-08 13:36:40 +00001629 }
drhbf4133c2001-10-13 02:59:08 +00001630 case TK_BITNOT:
drh6e142f52000-06-08 13:36:40 +00001631 case TK_NOT: {
drhf2bc0132004-10-04 13:19:23 +00001632 assert( TK_BITNOT==OP_BitNot );
1633 assert( TK_NOT==OP_Not );
danielk19774adee202004-05-08 08:23:19 +00001634 sqlite3ExprCode(pParse, pExpr->pLeft);
1635 sqlite3VdbeAddOp(v, op, 0, 0);
drhffe07b22005-11-03 00:41:17 +00001636 stackChng = 0;
drhcce7d172000-05-31 15:34:51 +00001637 break;
1638 }
1639 case TK_ISNULL:
1640 case TK_NOTNULL: {
1641 int dest;
drhf2bc0132004-10-04 13:19:23 +00001642 assert( TK_ISNULL==OP_IsNull );
1643 assert( TK_NOTNULL==OP_NotNull );
danielk19774adee202004-05-08 08:23:19 +00001644 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1645 sqlite3ExprCode(pParse, pExpr->pLeft);
1646 dest = sqlite3VdbeCurrentAddr(v) + 2;
1647 sqlite3VdbeAddOp(v, op, 1, dest);
1648 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
drhffe07b22005-11-03 00:41:17 +00001649 stackChng = 0;
drhf2bc0132004-10-04 13:19:23 +00001650 break;
drhcce7d172000-05-31 15:34:51 +00001651 }
drh22827922000-06-06 17:27:05 +00001652 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00001653 AggInfo *pInfo = pExpr->pAggInfo;
drh7e56e712005-11-16 12:53:15 +00001654 if( pInfo==0 ){
1655 sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
1656 &pExpr->span);
1657 }else{
1658 sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
1659 }
drh22827922000-06-06 17:27:05 +00001660 break;
1661 }
drhb71090f2005-05-23 17:26:51 +00001662 case TK_CONST_FUNC:
drhcce7d172000-05-31 15:34:51 +00001663 case TK_FUNCTION: {
drhcce7d172000-05-31 15:34:51 +00001664 ExprList *pList = pExpr->pList;
drh89425d52002-02-28 03:04:48 +00001665 int nExpr = pList ? pList->nExpr : 0;
drh0bce8352002-02-28 00:41:10 +00001666 FuncDef *pDef;
drh4b59ab52002-08-24 18:24:51 +00001667 int nId;
1668 const char *zId;
drh13449892005-09-07 21:22:45 +00001669 int constMask = 0;
danielk1977682f68b2004-06-05 10:22:17 +00001670 int i;
danielk197714db2662006-01-09 16:12:04 +00001671 u8 enc = ENC(pParse->db);
danielk1977dc1bdc42004-06-11 10:51:27 +00001672 CollSeq *pColl = 0;
drh2646da72005-12-09 20:02:05 +00001673 zId = (char*)pExpr->token.z;
drhb71090f2005-05-23 17:26:51 +00001674 nId = pExpr->token.n;
danielk1977d8123362004-06-12 09:25:12 +00001675 pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
drh0bce8352002-02-28 00:41:10 +00001676 assert( pDef!=0 );
drhf9b596e2004-05-26 16:54:42 +00001677 nExpr = sqlite3ExprCodeExprList(pParse, pList);
danielk1977682f68b2004-06-05 10:22:17 +00001678 for(i=0; i<nExpr && i<32; i++){
danielk1977d02eb1f2004-06-06 09:44:03 +00001679 if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
drh13449892005-09-07 21:22:45 +00001680 constMask |= (1<<i);
danielk1977d02eb1f2004-06-06 09:44:03 +00001681 }
danielk1977dc1bdc42004-06-11 10:51:27 +00001682 if( pDef->needCollSeq && !pColl ){
1683 pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1684 }
1685 }
1686 if( pDef->needCollSeq ){
1687 if( !pColl ) pColl = pParse->db->pDfltColl;
danielk1977d8123362004-06-12 09:25:12 +00001688 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
danielk1977682f68b2004-06-05 10:22:17 +00001689 }
drh13449892005-09-07 21:22:45 +00001690 sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
drhffe07b22005-11-03 00:41:17 +00001691 stackChng = 1-nExpr;
drhcce7d172000-05-31 15:34:51 +00001692 break;
1693 }
drhfe2093d2005-01-20 22:48:47 +00001694#ifndef SQLITE_OMIT_SUBQUERY
1695 case TK_EXISTS:
drh19a775c2000-06-05 18:54:46 +00001696 case TK_SELECT: {
danielk1977b3bce662005-01-29 08:32:43 +00001697 sqlite3CodeSubselect(pParse, pExpr);
danielk19774adee202004-05-08 08:23:19 +00001698 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
drhad6d9462004-09-19 02:15:24 +00001699 VdbeComment((v, "# load subquery result"));
drh19a775c2000-06-05 18:54:46 +00001700 break;
1701 }
drhfef52082000-06-06 01:50:43 +00001702 case TK_IN: {
1703 int addr;
drh94a11212004-09-25 13:12:14 +00001704 char affinity;
danielk1977b3bce662005-01-29 08:32:43 +00001705 sqlite3CodeSubselect(pParse, pExpr);
danielk1977e014a832004-05-17 10:48:57 +00001706
1707 /* Figure out the affinity to use to create a key from the results
1708 ** of the expression. affinityStr stores a static string suitable for
danielk1977ededfd52004-06-17 07:53:01 +00001709 ** P3 of OP_MakeRecord.
danielk1977e014a832004-05-17 10:48:57 +00001710 */
drh94a11212004-09-25 13:12:14 +00001711 affinity = comparisonAffinity(pExpr);
danielk1977e014a832004-05-17 10:48:57 +00001712
danielk19774adee202004-05-08 08:23:19 +00001713 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
danielk1977e014a832004-05-17 10:48:57 +00001714
1715 /* Code the <expr> from "<expr> IN (...)". The temporary table
1716 ** pExpr->iTable contains the values that make up the (...) set.
1717 */
danielk19774adee202004-05-08 08:23:19 +00001718 sqlite3ExprCode(pParse, pExpr->pLeft);
1719 addr = sqlite3VdbeCurrentAddr(v);
danielk1977e014a832004-05-17 10:48:57 +00001720 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4); /* addr + 0 */
danielk19774adee202004-05-08 08:23:19 +00001721 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
drhf0863fe2005-06-12 21:35:51 +00001722 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
danielk1977e014a832004-05-17 10:48:57 +00001723 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
drh94a11212004-09-25 13:12:14 +00001724 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */
danielk1977e014a832004-05-17 10:48:57 +00001725 sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1726 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */
1727
drhfef52082000-06-06 01:50:43 +00001728 break;
1729 }
danielk197793758c82005-01-21 08:13:14 +00001730#endif
drhfef52082000-06-06 01:50:43 +00001731 case TK_BETWEEN: {
drhbe5c89a2004-07-26 00:31:09 +00001732 Expr *pLeft = pExpr->pLeft;
1733 struct ExprList_item *pLItem = pExpr->pList->a;
1734 Expr *pRight = pLItem->pExpr;
1735 sqlite3ExprCode(pParse, pLeft);
danielk19774adee202004-05-08 08:23:19 +00001736 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhbe5c89a2004-07-26 00:31:09 +00001737 sqlite3ExprCode(pParse, pRight);
1738 codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001739 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
drhbe5c89a2004-07-26 00:31:09 +00001740 pLItem++;
1741 pRight = pLItem->pExpr;
1742 sqlite3ExprCode(pParse, pRight);
1743 codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
danielk19774adee202004-05-08 08:23:19 +00001744 sqlite3VdbeAddOp(v, OP_And, 0, 0);
drhfef52082000-06-06 01:50:43 +00001745 break;
1746 }
drh51e9a442004-01-16 16:42:53 +00001747 case TK_UPLUS:
drha2e00042002-01-22 03:13:42 +00001748 case TK_AS: {
danielk19774adee202004-05-08 08:23:19 +00001749 sqlite3ExprCode(pParse, pExpr->pLeft);
drhffe07b22005-11-03 00:41:17 +00001750 stackChng = 0;
drha2e00042002-01-22 03:13:42 +00001751 break;
1752 }
drh17a7f8d2002-03-24 13:13:27 +00001753 case TK_CASE: {
1754 int expr_end_label;
drhf5905aa2002-05-26 20:54:33 +00001755 int jumpInst;
drhf5905aa2002-05-26 20:54:33 +00001756 int nExpr;
drh17a7f8d2002-03-24 13:13:27 +00001757 int i;
drhbe5c89a2004-07-26 00:31:09 +00001758 ExprList *pEList;
1759 struct ExprList_item *aListelem;
drh17a7f8d2002-03-24 13:13:27 +00001760
1761 assert(pExpr->pList);
1762 assert((pExpr->pList->nExpr % 2) == 0);
1763 assert(pExpr->pList->nExpr > 0);
drhbe5c89a2004-07-26 00:31:09 +00001764 pEList = pExpr->pList;
1765 aListelem = pEList->a;
1766 nExpr = pEList->nExpr;
danielk19774adee202004-05-08 08:23:19 +00001767 expr_end_label = sqlite3VdbeMakeLabel(v);
drh17a7f8d2002-03-24 13:13:27 +00001768 if( pExpr->pLeft ){
danielk19774adee202004-05-08 08:23:19 +00001769 sqlite3ExprCode(pParse, pExpr->pLeft);
drh17a7f8d2002-03-24 13:13:27 +00001770 }
drhf5905aa2002-05-26 20:54:33 +00001771 for(i=0; i<nExpr; i=i+2){
drhbe5c89a2004-07-26 00:31:09 +00001772 sqlite3ExprCode(pParse, aListelem[i].pExpr);
drh17a7f8d2002-03-24 13:13:27 +00001773 if( pExpr->pLeft ){
danielk19774adee202004-05-08 08:23:19 +00001774 sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
drhbe5c89a2004-07-26 00:31:09 +00001775 jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
1776 OP_Ne, 0, 1);
danielk19774adee202004-05-08 08:23:19 +00001777 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drh17a7f8d2002-03-24 13:13:27 +00001778 }else{
danielk19774adee202004-05-08 08:23:19 +00001779 jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
drh17a7f8d2002-03-24 13:13:27 +00001780 }
drhbe5c89a2004-07-26 00:31:09 +00001781 sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
danielk19774adee202004-05-08 08:23:19 +00001782 sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
drhd654be82005-09-20 17:42:23 +00001783 sqlite3VdbeJumpHere(v, jumpInst);
drh17a7f8d2002-03-24 13:13:27 +00001784 }
drhf570f012002-05-31 15:51:25 +00001785 if( pExpr->pLeft ){
danielk19774adee202004-05-08 08:23:19 +00001786 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drhf570f012002-05-31 15:51:25 +00001787 }
drh17a7f8d2002-03-24 13:13:27 +00001788 if( pExpr->pRight ){
danielk19774adee202004-05-08 08:23:19 +00001789 sqlite3ExprCode(pParse, pExpr->pRight);
drh17a7f8d2002-03-24 13:13:27 +00001790 }else{
drhf0863fe2005-06-12 21:35:51 +00001791 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
drh17a7f8d2002-03-24 13:13:27 +00001792 }
danielk19774adee202004-05-08 08:23:19 +00001793 sqlite3VdbeResolveLabel(v, expr_end_label);
danielk19776f349032002-06-11 02:25:40 +00001794 break;
1795 }
danielk19775338a5f2005-01-20 13:03:10 +00001796#ifndef SQLITE_OMIT_TRIGGER
danielk19776f349032002-06-11 02:25:40 +00001797 case TK_RAISE: {
1798 if( !pParse->trigStack ){
danielk19774adee202004-05-08 08:23:19 +00001799 sqlite3ErrorMsg(pParse,
drhda93d232003-03-31 02:12:46 +00001800 "RAISE() may only be used within a trigger-program");
danielk19776f349032002-06-11 02:25:40 +00001801 return;
1802 }
drhad6d9462004-09-19 02:15:24 +00001803 if( pExpr->iColumn!=OE_Ignore ){
1804 assert( pExpr->iColumn==OE_Rollback ||
1805 pExpr->iColumn == OE_Abort ||
1806 pExpr->iColumn == OE_Fail );
drhd2687b72005-08-12 22:56:09 +00001807 sqlite3DequoteExpr(pExpr);
drhad6d9462004-09-19 02:15:24 +00001808 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
drh2646da72005-12-09 20:02:05 +00001809 (char*)pExpr->token.z, pExpr->token.n);
danielk19776f349032002-06-11 02:25:40 +00001810 } else {
drhad6d9462004-09-19 02:15:24 +00001811 assert( pExpr->iColumn == OE_Ignore );
1812 sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
1813 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
1814 VdbeComment((v, "# raise(IGNORE)"));
danielk19776f349032002-06-11 02:25:40 +00001815 }
drhffe07b22005-11-03 00:41:17 +00001816 stackChng = 0;
1817 break;
drh17a7f8d2002-03-24 13:13:27 +00001818 }
danielk19775338a5f2005-01-20 13:03:10 +00001819#endif
drhffe07b22005-11-03 00:41:17 +00001820 }
1821
1822 if( pParse->ckOffset ){
1823 pParse->ckOffset += stackChng;
1824 assert( pParse->ckOffset );
drhcce7d172000-05-31 15:34:51 +00001825 }
drhcce7d172000-05-31 15:34:51 +00001826}
1827
danielk197793758c82005-01-21 08:13:14 +00001828#ifndef SQLITE_OMIT_TRIGGER
drhcce7d172000-05-31 15:34:51 +00001829/*
drh25303782004-12-07 15:41:48 +00001830** Generate code that evalutes the given expression and leaves the result
1831** on the stack. See also sqlite3ExprCode().
1832**
1833** This routine might also cache the result and modify the pExpr tree
1834** so that it will make use of the cached result on subsequent evaluations
1835** rather than evaluate the whole expression again. Trivial expressions are
1836** not cached. If the expression is cached, its result is stored in a
1837** memory location.
1838*/
1839void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
1840 Vdbe *v = pParse->pVdbe;
1841 int iMem;
1842 int addr1, addr2;
1843 if( v==0 ) return;
1844 addr1 = sqlite3VdbeCurrentAddr(v);
1845 sqlite3ExprCode(pParse, pExpr);
1846 addr2 = sqlite3VdbeCurrentAddr(v);
1847 if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
1848 iMem = pExpr->iTable = pParse->nMem++;
1849 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
1850 pExpr->op = TK_REGISTER;
1851 }
1852}
danielk197793758c82005-01-21 08:13:14 +00001853#endif
drh25303782004-12-07 15:41:48 +00001854
1855/*
drh268380c2004-02-25 13:47:31 +00001856** Generate code that pushes the value of every element of the given
drhf9b596e2004-05-26 16:54:42 +00001857** expression list onto the stack.
drh268380c2004-02-25 13:47:31 +00001858**
1859** Return the number of elements pushed onto the stack.
1860*/
danielk19774adee202004-05-08 08:23:19 +00001861int sqlite3ExprCodeExprList(
drh268380c2004-02-25 13:47:31 +00001862 Parse *pParse, /* Parsing context */
drhf9b596e2004-05-26 16:54:42 +00001863 ExprList *pList /* The expression list to be coded */
drh268380c2004-02-25 13:47:31 +00001864){
1865 struct ExprList_item *pItem;
1866 int i, n;
drh268380c2004-02-25 13:47:31 +00001867 if( pList==0 ) return 0;
drh268380c2004-02-25 13:47:31 +00001868 n = pList->nExpr;
drhc182d162005-08-14 20:47:16 +00001869 for(pItem=pList->a, i=n; i>0; i--, pItem++){
danielk19774adee202004-05-08 08:23:19 +00001870 sqlite3ExprCode(pParse, pItem->pExpr);
drh268380c2004-02-25 13:47:31 +00001871 }
drhf9b596e2004-05-26 16:54:42 +00001872 return n;
drh268380c2004-02-25 13:47:31 +00001873}
1874
1875/*
drhcce7d172000-05-31 15:34:51 +00001876** Generate code for a boolean expression such that a jump is made
1877** to the label "dest" if the expression is true but execution
1878** continues straight thru if the expression is false.
drhf5905aa2002-05-26 20:54:33 +00001879**
1880** If the expression evaluates to NULL (neither true nor false), then
1881** take the jump if the jumpIfNull flag is true.
drhf2bc0132004-10-04 13:19:23 +00001882**
1883** This code depends on the fact that certain token values (ex: TK_EQ)
1884** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1885** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
1886** the make process cause these values to align. Assert()s in the code
1887** below verify that the numbers are aligned correctly.
drhcce7d172000-05-31 15:34:51 +00001888*/
danielk19774adee202004-05-08 08:23:19 +00001889void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00001890 Vdbe *v = pParse->pVdbe;
1891 int op = 0;
drhffe07b22005-11-03 00:41:17 +00001892 int ckOffset = pParse->ckOffset;
drhdaffd0e2001-04-11 14:28:42 +00001893 if( v==0 || pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00001894 op = pExpr->op;
1895 switch( op ){
drhcce7d172000-05-31 15:34:51 +00001896 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00001897 int d2 = sqlite3VdbeMakeLabel(v);
1898 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
1899 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
1900 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00001901 break;
1902 }
1903 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00001904 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
1905 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00001906 break;
1907 }
1908 case TK_NOT: {
danielk19774adee202004-05-08 08:23:19 +00001909 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00001910 break;
1911 }
1912 case TK_LT:
1913 case TK_LE:
1914 case TK_GT:
1915 case TK_GE:
1916 case TK_NE:
drh0ac65892002-04-20 14:24:41 +00001917 case TK_EQ: {
drhf2bc0132004-10-04 13:19:23 +00001918 assert( TK_LT==OP_Lt );
1919 assert( TK_LE==OP_Le );
1920 assert( TK_GT==OP_Gt );
1921 assert( TK_GE==OP_Ge );
1922 assert( TK_EQ==OP_Eq );
1923 assert( TK_NE==OP_Ne );
danielk19774adee202004-05-08 08:23:19 +00001924 sqlite3ExprCode(pParse, pExpr->pLeft);
1925 sqlite3ExprCode(pParse, pExpr->pRight);
drhbe5c89a2004-07-26 00:31:09 +00001926 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00001927 break;
1928 }
1929 case TK_ISNULL:
1930 case TK_NOTNULL: {
drhf2bc0132004-10-04 13:19:23 +00001931 assert( TK_ISNULL==OP_IsNull );
1932 assert( TK_NOTNULL==OP_NotNull );
danielk19774adee202004-05-08 08:23:19 +00001933 sqlite3ExprCode(pParse, pExpr->pLeft);
1934 sqlite3VdbeAddOp(v, op, 1, dest);
drhcce7d172000-05-31 15:34:51 +00001935 break;
1936 }
drhfef52082000-06-06 01:50:43 +00001937 case TK_BETWEEN: {
danielk19770202b292004-06-09 09:55:16 +00001938 /* The expression "x BETWEEN y AND z" is implemented as:
1939 **
1940 ** 1 IF (x < y) GOTO 3
1941 ** 2 IF (x <= z) GOTO <dest>
1942 ** 3 ...
1943 */
drhf5905aa2002-05-26 20:54:33 +00001944 int addr;
drhbe5c89a2004-07-26 00:31:09 +00001945 Expr *pLeft = pExpr->pLeft;
1946 Expr *pRight = pExpr->pList->a[0].pExpr;
1947 sqlite3ExprCode(pParse, pLeft);
danielk19774adee202004-05-08 08:23:19 +00001948 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhbe5c89a2004-07-26 00:31:09 +00001949 sqlite3ExprCode(pParse, pRight);
1950 addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
danielk19770202b292004-06-09 09:55:16 +00001951
drhbe5c89a2004-07-26 00:31:09 +00001952 pRight = pExpr->pList->a[1].pExpr;
1953 sqlite3ExprCode(pParse, pRight);
1954 codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
danielk19770202b292004-06-09 09:55:16 +00001955
danielk19774adee202004-05-08 08:23:19 +00001956 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
drhd654be82005-09-20 17:42:23 +00001957 sqlite3VdbeJumpHere(v, addr);
danielk19774adee202004-05-08 08:23:19 +00001958 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
drhfef52082000-06-06 01:50:43 +00001959 break;
1960 }
drhcce7d172000-05-31 15:34:51 +00001961 default: {
danielk19774adee202004-05-08 08:23:19 +00001962 sqlite3ExprCode(pParse, pExpr);
1963 sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
drhcce7d172000-05-31 15:34:51 +00001964 break;
1965 }
1966 }
drhffe07b22005-11-03 00:41:17 +00001967 pParse->ckOffset = ckOffset;
drhcce7d172000-05-31 15:34:51 +00001968}
1969
1970/*
drh66b89c82000-11-28 20:47:17 +00001971** Generate code for a boolean expression such that a jump is made
drhcce7d172000-05-31 15:34:51 +00001972** to the label "dest" if the expression is false but execution
1973** continues straight thru if the expression is true.
drhf5905aa2002-05-26 20:54:33 +00001974**
1975** If the expression evaluates to NULL (neither true nor false) then
1976** jump if jumpIfNull is true or fall through if jumpIfNull is false.
drhcce7d172000-05-31 15:34:51 +00001977*/
danielk19774adee202004-05-08 08:23:19 +00001978void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
drhcce7d172000-05-31 15:34:51 +00001979 Vdbe *v = pParse->pVdbe;
1980 int op = 0;
drhffe07b22005-11-03 00:41:17 +00001981 int ckOffset = pParse->ckOffset;
drhdaffd0e2001-04-11 14:28:42 +00001982 if( v==0 || pExpr==0 ) return;
drhf2bc0132004-10-04 13:19:23 +00001983
1984 /* The value of pExpr->op and op are related as follows:
1985 **
1986 ** pExpr->op op
1987 ** --------- ----------
1988 ** TK_ISNULL OP_NotNull
1989 ** TK_NOTNULL OP_IsNull
1990 ** TK_NE OP_Eq
1991 ** TK_EQ OP_Ne
1992 ** TK_GT OP_Le
1993 ** TK_LE OP_Gt
1994 ** TK_GE OP_Lt
1995 ** TK_LT OP_Ge
1996 **
1997 ** For other values of pExpr->op, op is undefined and unused.
1998 ** The value of TK_ and OP_ constants are arranged such that we
1999 ** can compute the mapping above using the following expression.
2000 ** Assert()s verify that the computation is correct.
2001 */
2002 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2003
2004 /* Verify correct alignment of TK_ and OP_ constants
2005 */
2006 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2007 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2008 assert( pExpr->op!=TK_NE || op==OP_Eq );
2009 assert( pExpr->op!=TK_EQ || op==OP_Ne );
2010 assert( pExpr->op!=TK_LT || op==OP_Ge );
2011 assert( pExpr->op!=TK_LE || op==OP_Gt );
2012 assert( pExpr->op!=TK_GT || op==OP_Le );
2013 assert( pExpr->op!=TK_GE || op==OP_Lt );
2014
drhcce7d172000-05-31 15:34:51 +00002015 switch( pExpr->op ){
2016 case TK_AND: {
danielk19774adee202004-05-08 08:23:19 +00002017 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2018 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00002019 break;
2020 }
2021 case TK_OR: {
danielk19774adee202004-05-08 08:23:19 +00002022 int d2 = sqlite3VdbeMakeLabel(v);
2023 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
2024 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2025 sqlite3VdbeResolveLabel(v, d2);
drhcce7d172000-05-31 15:34:51 +00002026 break;
2027 }
2028 case TK_NOT: {
danielk19774adee202004-05-08 08:23:19 +00002029 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00002030 break;
2031 }
2032 case TK_LT:
2033 case TK_LE:
2034 case TK_GT:
2035 case TK_GE:
2036 case TK_NE:
2037 case TK_EQ: {
danielk19774adee202004-05-08 08:23:19 +00002038 sqlite3ExprCode(pParse, pExpr->pLeft);
2039 sqlite3ExprCode(pParse, pExpr->pRight);
drhbe5c89a2004-07-26 00:31:09 +00002040 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
drhcce7d172000-05-31 15:34:51 +00002041 break;
2042 }
drhcce7d172000-05-31 15:34:51 +00002043 case TK_ISNULL:
2044 case TK_NOTNULL: {
danielk19774adee202004-05-08 08:23:19 +00002045 sqlite3ExprCode(pParse, pExpr->pLeft);
2046 sqlite3VdbeAddOp(v, op, 1, dest);
drhcce7d172000-05-31 15:34:51 +00002047 break;
2048 }
drhfef52082000-06-06 01:50:43 +00002049 case TK_BETWEEN: {
danielk19770202b292004-06-09 09:55:16 +00002050 /* The expression is "x BETWEEN y AND z". It is implemented as:
2051 **
2052 ** 1 IF (x >= y) GOTO 3
2053 ** 2 GOTO <dest>
2054 ** 3 IF (x > z) GOTO <dest>
2055 */
drhfef52082000-06-06 01:50:43 +00002056 int addr;
drhbe5c89a2004-07-26 00:31:09 +00002057 Expr *pLeft = pExpr->pLeft;
2058 Expr *pRight = pExpr->pList->a[0].pExpr;
2059 sqlite3ExprCode(pParse, pLeft);
danielk19774adee202004-05-08 08:23:19 +00002060 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
drhbe5c89a2004-07-26 00:31:09 +00002061 sqlite3ExprCode(pParse, pRight);
danielk19774adee202004-05-08 08:23:19 +00002062 addr = sqlite3VdbeCurrentAddr(v);
drhbe5c89a2004-07-26 00:31:09 +00002063 codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2064
danielk19774adee202004-05-08 08:23:19 +00002065 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2066 sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
drhbe5c89a2004-07-26 00:31:09 +00002067 pRight = pExpr->pList->a[1].pExpr;
2068 sqlite3ExprCode(pParse, pRight);
2069 codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
drhfef52082000-06-06 01:50:43 +00002070 break;
2071 }
drhcce7d172000-05-31 15:34:51 +00002072 default: {
danielk19774adee202004-05-08 08:23:19 +00002073 sqlite3ExprCode(pParse, pExpr);
2074 sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
drhcce7d172000-05-31 15:34:51 +00002075 break;
2076 }
2077 }
drhffe07b22005-11-03 00:41:17 +00002078 pParse->ckOffset = ckOffset;
drhcce7d172000-05-31 15:34:51 +00002079}
drh22827922000-06-06 17:27:05 +00002080
2081/*
2082** Do a deep comparison of two expression trees. Return TRUE (non-zero)
2083** if they are identical and return FALSE if they differ in any way.
2084*/
danielk19774adee202004-05-08 08:23:19 +00002085int sqlite3ExprCompare(Expr *pA, Expr *pB){
drh22827922000-06-06 17:27:05 +00002086 int i;
2087 if( pA==0 ){
2088 return pB==0;
2089 }else if( pB==0 ){
2090 return 0;
2091 }
2092 if( pA->op!=pB->op ) return 0;
drhfd357972005-09-09 01:33:19 +00002093 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
danielk19774adee202004-05-08 08:23:19 +00002094 if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
2095 if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
drh22827922000-06-06 17:27:05 +00002096 if( pA->pList ){
2097 if( pB->pList==0 ) return 0;
2098 if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
2099 for(i=0; i<pA->pList->nExpr; i++){
danielk19774adee202004-05-08 08:23:19 +00002100 if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
drh22827922000-06-06 17:27:05 +00002101 return 0;
2102 }
2103 }
2104 }else if( pB->pList ){
2105 return 0;
2106 }
2107 if( pA->pSelect || pB->pSelect ) return 0;
drh2f2c01e2002-07-02 13:05:04 +00002108 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
drh22827922000-06-06 17:27:05 +00002109 if( pA->token.z ){
2110 if( pB->token.z==0 ) return 0;
drh6977fea2002-10-22 23:38:04 +00002111 if( pB->token.n!=pA->token.n ) return 0;
drh2646da72005-12-09 20:02:05 +00002112 if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
2113 return 0;
2114 }
drh22827922000-06-06 17:27:05 +00002115 }
2116 return 1;
2117}
2118
drh13449892005-09-07 21:22:45 +00002119
drh22827922000-06-06 17:27:05 +00002120/*
drh13449892005-09-07 21:22:45 +00002121** Add a new element to the pAggInfo->aCol[] array. Return the index of
2122** the new element. Return a negative number if malloc fails.
drh22827922000-06-06 17:27:05 +00002123*/
drh13449892005-09-07 21:22:45 +00002124static int addAggInfoColumn(AggInfo *pInfo){
2125 int i;
2126 i = sqlite3ArrayAllocate((void**)&pInfo->aCol, sizeof(pInfo->aCol[0]), 3);
2127 if( i<0 ){
2128 return -1;
drh22827922000-06-06 17:27:05 +00002129 }
drh13449892005-09-07 21:22:45 +00002130 return i;
2131}
2132
2133/*
2134** Add a new element to the pAggInfo->aFunc[] array. Return the index of
2135** the new element. Return a negative number if malloc fails.
2136*/
2137static int addAggInfoFunc(AggInfo *pInfo){
2138 int i;
2139 i = sqlite3ArrayAllocate((void**)&pInfo->aFunc, sizeof(pInfo->aFunc[0]), 2);
2140 if( i<0 ){
2141 return -1;
2142 }
2143 return i;
2144}
drh22827922000-06-06 17:27:05 +00002145
2146/*
drh626a8792005-01-17 22:08:19 +00002147** This is an xFunc for walkExprTree() used to implement
2148** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
2149** for additional information.
drh22827922000-06-06 17:27:05 +00002150**
drh626a8792005-01-17 22:08:19 +00002151** This routine analyzes the aggregate function at pExpr.
drh22827922000-06-06 17:27:05 +00002152*/
drh626a8792005-01-17 22:08:19 +00002153static int analyzeAggregate(void *pArg, Expr *pExpr){
drh22827922000-06-06 17:27:05 +00002154 int i;
danielk1977a58fdfb2005-02-08 07:50:40 +00002155 NameContext *pNC = (NameContext *)pArg;
2156 Parse *pParse = pNC->pParse;
2157 SrcList *pSrcList = pNC->pSrcList;
drh13449892005-09-07 21:22:45 +00002158 AggInfo *pAggInfo = pNC->pAggInfo;
2159
drh22827922000-06-06 17:27:05 +00002160
drh22827922000-06-06 17:27:05 +00002161 switch( pExpr->op ){
drh967e8b72000-06-21 13:59:10 +00002162 case TK_COLUMN: {
drh13449892005-09-07 21:22:45 +00002163 /* Check to see if the column is in one of the tables in the FROM
2164 ** clause of the aggregate query */
2165 if( pSrcList ){
2166 struct SrcList_item *pItem = pSrcList->a;
2167 for(i=0; i<pSrcList->nSrc; i++, pItem++){
2168 struct AggInfo_col *pCol;
2169 if( pExpr->iTable==pItem->iCursor ){
2170 /* If we reach this point, it means that pExpr refers to a table
2171 ** that is in the FROM clause of the aggregate query.
2172 **
2173 ** Make an entry for the column in pAggInfo->aCol[] if there
2174 ** is not an entry there already.
2175 */
2176 pCol = pAggInfo->aCol;
2177 for(i=0; i<pAggInfo->nColumn; i++, pCol++){
2178 if( pCol->iTable==pExpr->iTable &&
2179 pCol->iColumn==pExpr->iColumn ){
2180 break;
2181 }
danielk1977a58fdfb2005-02-08 07:50:40 +00002182 }
drh13449892005-09-07 21:22:45 +00002183 if( i>=pAggInfo->nColumn && (i = addAggInfoColumn(pAggInfo))>=0 ){
2184 pCol = &pAggInfo->aCol[i];
2185 pCol->iTable = pExpr->iTable;
2186 pCol->iColumn = pExpr->iColumn;
2187 pCol->iMem = pParse->nMem++;
2188 pCol->iSorterColumn = -1;
drh5774b802005-09-07 22:48:16 +00002189 pCol->pExpr = pExpr;
drh13449892005-09-07 21:22:45 +00002190 if( pAggInfo->pGroupBy ){
2191 int j, n;
2192 ExprList *pGB = pAggInfo->pGroupBy;
2193 struct ExprList_item *pTerm = pGB->a;
2194 n = pGB->nExpr;
2195 for(j=0; j<n; j++, pTerm++){
2196 Expr *pE = pTerm->pExpr;
2197 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
2198 pE->iColumn==pExpr->iColumn ){
2199 pCol->iSorterColumn = j;
2200 break;
2201 }
2202 }
2203 }
2204 if( pCol->iSorterColumn<0 ){
2205 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
2206 }
2207 }
2208 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
2209 ** because it was there before or because we just created it).
2210 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
2211 ** pAggInfo->aCol[] entry.
2212 */
2213 pExpr->pAggInfo = pAggInfo;
2214 pExpr->op = TK_AGG_COLUMN;
2215 pExpr->iAgg = i;
2216 break;
2217 } /* endif pExpr->iTable==pItem->iCursor */
2218 } /* end loop over pSrcList */
drh22827922000-06-06 17:27:05 +00002219 }
drh626a8792005-01-17 22:08:19 +00002220 return 1;
drh22827922000-06-06 17:27:05 +00002221 }
2222 case TK_AGG_FUNCTION: {
drh13449892005-09-07 21:22:45 +00002223 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
2224 ** to be ignored */
danielk1977a58fdfb2005-02-08 07:50:40 +00002225 if( pNC->nDepth==0 ){
drh13449892005-09-07 21:22:45 +00002226 /* Check to see if pExpr is a duplicate of another aggregate
2227 ** function that is already in the pAggInfo structure
2228 */
2229 struct AggInfo_func *pItem = pAggInfo->aFunc;
2230 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
2231 if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
danielk1977a58fdfb2005-02-08 07:50:40 +00002232 break;
2233 }
drh22827922000-06-06 17:27:05 +00002234 }
drh13449892005-09-07 21:22:45 +00002235 if( i>=pAggInfo->nFunc ){
2236 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
2237 */
danielk197714db2662006-01-09 16:12:04 +00002238 u8 enc = ENC(pParse->db);
drh13449892005-09-07 21:22:45 +00002239 i = addAggInfoFunc(pAggInfo);
2240 if( i>=0 ){
2241 pItem = &pAggInfo->aFunc[i];
2242 pItem->pExpr = pExpr;
2243 pItem->iMem = pParse->nMem++;
2244 pItem->pFunc = sqlite3FindFunction(pParse->db,
drh2646da72005-12-09 20:02:05 +00002245 (char*)pExpr->token.z, pExpr->token.n,
drh13449892005-09-07 21:22:45 +00002246 pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
drhfd357972005-09-09 01:33:19 +00002247 if( pExpr->flags & EP_Distinct ){
2248 pItem->iDistinct = pParse->nTab++;
2249 }else{
2250 pItem->iDistinct = -1;
2251 }
drh13449892005-09-07 21:22:45 +00002252 }
danielk1977a58fdfb2005-02-08 07:50:40 +00002253 }
drh13449892005-09-07 21:22:45 +00002254 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
2255 */
danielk1977a58fdfb2005-02-08 07:50:40 +00002256 pExpr->iAgg = i;
drh13449892005-09-07 21:22:45 +00002257 pExpr->pAggInfo = pAggInfo;
danielk1977a58fdfb2005-02-08 07:50:40 +00002258 return 1;
drh22827922000-06-06 17:27:05 +00002259 }
drh22827922000-06-06 17:27:05 +00002260 }
2261 }
drh13449892005-09-07 21:22:45 +00002262
2263 /* Recursively walk subqueries looking for TK_COLUMN nodes that need
2264 ** to be changed to TK_AGG_COLUMN. But increment nDepth so that
2265 ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
2266 */
danielk1977a58fdfb2005-02-08 07:50:40 +00002267 if( pExpr->pSelect ){
2268 pNC->nDepth++;
2269 walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2270 pNC->nDepth--;
2271 }
drh626a8792005-01-17 22:08:19 +00002272 return 0;
2273}
2274
2275/*
2276** Analyze the given expression looking for aggregate functions and
2277** for variables that need to be added to the pParse->aAgg[] array.
2278** Make additional entries to the pParse->aAgg[] array as necessary.
2279**
2280** This routine should only be called after the expression has been
2281** analyzed by sqlite3ExprResolveNames().
2282**
2283** If errors are seen, leave an error message in zErrMsg and return
2284** the number of errors.
2285*/
danielk1977a58fdfb2005-02-08 07:50:40 +00002286int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2287 int nErr = pNC->pParse->nErr;
2288 walkExprTree(pExpr, analyzeAggregate, pNC);
2289 return pNC->pParse->nErr - nErr;
drh22827922000-06-06 17:27:05 +00002290}
drh5d9a4af2005-08-30 00:54:01 +00002291
2292/*
2293** Call sqlite3ExprAnalyzeAggregates() for every expression in an
2294** expression list. Return the number of errors.
2295**
2296** If an error is found, the analysis is cut short.
2297*/
2298int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
2299 struct ExprList_item *pItem;
2300 int i;
2301 int nErr = 0;
2302 if( pList ){
2303 for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
2304 nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
2305 }
2306 }
2307 return nErr;
2308}