monotone

monotone Mtn Source Tree

Root/sqlite/expr.c

1/*
2** 2001 September 15
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** 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.
10**
11*************************************************************************
12** This file contains routines used for analyzing expressions and
13** for generating VDBE code that evaluates expressions in SQLite.
14**
15** $Id: expr.c,v 1.298 2007/06/15 16:37:29 danielk1977 Exp $
16*/
17#include "sqliteInt.h"
18#include <ctype.h>
19
20/*
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*/
36char sqlite3ExprAffinity(Expr *pExpr){
37 int op = pExpr->op;
38 if( op==TK_SELECT ){
39 return sqlite3ExprAffinity(pExpr->pSelect->pEList->a[0].pExpr);
40 }
41#ifndef SQLITE_OMIT_CAST
42 if( op==TK_CAST ){
43 return sqlite3AffinityType(&pExpr->token);
44 }
45#endif
46 return pExpr->affinity;
47}
48
49/*
50** Set the collating sequence for expression pExpr to be the collating
51** sequence named by pToken. Return a pointer to the revised expression.
52** The collating sequence is marked as "explicit" using the EP_ExpCollate
53** flag. An explicit collating sequence will override implicit
54** collating sequences.
55*/
56Expr *sqlite3ExprSetColl(Parse *pParse, Expr *pExpr, Token *pName){
57 CollSeq *pColl;
58 if( pExpr==0 ) return 0;
59 pColl = sqlite3LocateCollSeq(pParse, (char*)pName->z, pName->n);
60 if( pColl ){
61 pExpr->pColl = pColl;
62 pExpr->flags |= EP_ExpCollate;
63 }
64 return pExpr;
65}
66
67/*
68** Return the default collation sequence for the expression pExpr. If
69** there is no default collation type, return 0.
70*/
71CollSeq *sqlite3ExprCollSeq(Parse *pParse, Expr *pExpr){
72 CollSeq *pColl = 0;
73 if( pExpr ){
74 pColl = pExpr->pColl;
75 if( pExpr->op==TK_CAST && !pColl ){
76 return sqlite3ExprCollSeq(pParse, pExpr->pLeft);
77 }
78 }
79 if( sqlite3CheckCollSeq(pParse, pColl) ){
80 pColl = 0;
81 }
82 return pColl;
83}
84
85/*
86** pExpr is an operand of a comparison operator. aff2 is the
87** type affinity of the other operand. This routine returns the
88** type affinity that should be used for the comparison operator.
89*/
90char sqlite3CompareAffinity(Expr *pExpr, char aff2){
91 char aff1 = sqlite3ExprAffinity(pExpr);
92 if( aff1 && aff2 ){
93 /* Both sides of the comparison are columns. If one has numeric
94 ** affinity, use that. Otherwise use no affinity.
95 */
96 if( sqlite3IsNumericAffinity(aff1) || sqlite3IsNumericAffinity(aff2) ){
97 return SQLITE_AFF_NUMERIC;
98 }else{
99 return SQLITE_AFF_NONE;
100 }
101 }else if( !aff1 && !aff2 ){
102 /* Neither side of the comparison is a column. Compare the
103 ** results directly.
104 */
105 return SQLITE_AFF_NONE;
106 }else{
107 /* One side is a column, the other is not. Use the columns affinity. */
108 assert( aff1==0 || aff2==0 );
109 return (aff1 + aff2);
110 }
111}
112
113/*
114** pExpr is a comparison operator. Return the type affinity that should
115** be applied to both operands prior to doing the comparison.
116*/
117static char comparisonAffinity(Expr *pExpr){
118 char aff;
119 assert( pExpr->op==TK_EQ || pExpr->op==TK_IN || pExpr->op==TK_LT ||
120 pExpr->op==TK_GT || pExpr->op==TK_GE || pExpr->op==TK_LE ||
121 pExpr->op==TK_NE );
122 assert( pExpr->pLeft );
123 aff = sqlite3ExprAffinity(pExpr->pLeft);
124 if( pExpr->pRight ){
125 aff = sqlite3CompareAffinity(pExpr->pRight, aff);
126 }
127 else if( pExpr->pSelect ){
128 aff = sqlite3CompareAffinity(pExpr->pSelect->pEList->a[0].pExpr, aff);
129 }
130 else if( !aff ){
131 aff = SQLITE_AFF_NONE;
132 }
133 return aff;
134}
135
136/*
137** pExpr is a comparison expression, eg. '=', '<', IN(...) etc.
138** idx_affinity is the affinity of an indexed column. Return true
139** if the index with affinity idx_affinity may be used to implement
140** the comparison in pExpr.
141*/
142int sqlite3IndexAffinityOk(Expr *pExpr, char idx_affinity){
143 char aff = comparisonAffinity(pExpr);
144 switch( aff ){
145 case SQLITE_AFF_NONE:
146 return 1;
147 case SQLITE_AFF_TEXT:
148 return idx_affinity==SQLITE_AFF_TEXT;
149 default:
150 return sqlite3IsNumericAffinity(idx_affinity);
151 }
152}
153
154/*
155** Return the P1 value that should be used for a binary comparison
156** opcode (OP_Eq, OP_Ge etc.) used to compare pExpr1 and pExpr2.
157** If jumpIfNull is true, then set the low byte of the returned
158** P1 value to tell the opcode to jump if either expression
159** evaluates to NULL.
160*/
161static int binaryCompareP1(Expr *pExpr1, Expr *pExpr2, int jumpIfNull){
162 char aff = sqlite3ExprAffinity(pExpr2);
163 return ((int)sqlite3CompareAffinity(pExpr1, aff))+(jumpIfNull?0x100:0);
164}
165
166/*
167** Return a pointer to the collation sequence that should be used by
168** a binary comparison operator comparing pLeft and pRight.
169**
170** If the left hand expression has a collating sequence type, then it is
171** used. Otherwise the collation sequence for the right hand expression
172** is used, or the default (BINARY) if neither expression has a collating
173** type.
174**
175** Argument pRight (but not pLeft) may be a null pointer. In this case,
176** it is not considered.
177*/
178CollSeq* sqlite3BinaryCompareCollSeq(
179 Parse *pParse,
180 Expr *pLeft,
181 Expr *pRight
182){
183 CollSeq *pColl;
184 assert( pLeft );
185 if( pLeft->flags & EP_ExpCollate ){
186 assert( pLeft->pColl );
187 pColl = pLeft->pColl;
188 }else if( pRight && pRight->flags & EP_ExpCollate ){
189 assert( pRight->pColl );
190 pColl = pRight->pColl;
191 }else{
192 pColl = sqlite3ExprCollSeq(pParse, pLeft);
193 if( !pColl ){
194 pColl = sqlite3ExprCollSeq(pParse, pRight);
195 }
196 }
197 return pColl;
198}
199
200/*
201** Generate code for a comparison operator.
202*/
203static int codeCompare(
204 Parse *pParse, /* The parsing (and code generating) context */
205 Expr *pLeft, /* The left operand */
206 Expr *pRight, /* The right operand */
207 int opcode, /* The comparison opcode */
208 int dest, /* Jump here if true. */
209 int jumpIfNull /* If true, jump if either operand is NULL */
210){
211 int p1 = binaryCompareP1(pLeft, pRight, jumpIfNull);
212 CollSeq *p3 = sqlite3BinaryCompareCollSeq(pParse, pLeft, pRight);
213 return sqlite3VdbeOp3(pParse->pVdbe, opcode, p1, dest, (void*)p3, P3_COLLSEQ);
214}
215
216/*
217** Construct a new expression node and return a pointer to it. Memory
218** for this node is obtained from sqliteMalloc(). The calling function
219** is responsible for making sure the node eventually gets freed.
220*/
221Expr *sqlite3Expr(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
222 Expr *pNew;
223 pNew = sqliteMalloc( sizeof(Expr) );
224 if( pNew==0 ){
225 /* When malloc fails, delete pLeft and pRight. Expressions passed to
226 ** this function must always be allocated with sqlite3Expr() for this
227 ** reason.
228 */
229 sqlite3ExprDelete(pLeft);
230 sqlite3ExprDelete(pRight);
231 return 0;
232 }
233 pNew->op = op;
234 pNew->pLeft = pLeft;
235 pNew->pRight = pRight;
236 pNew->iAgg = -1;
237 if( pToken ){
238 assert( pToken->dyn==0 );
239 pNew->span = pNew->token = *pToken;
240 }else if( pLeft ){
241 if( pRight ){
242 sqlite3ExprSpan(pNew, &pLeft->span, &pRight->span);
243 if( pRight->flags & EP_ExpCollate ){
244 pNew->flags |= EP_ExpCollate;
245 pNew->pColl = pRight->pColl;
246 }
247 }
248 if( pLeft->flags & EP_ExpCollate ){
249 pNew->flags |= EP_ExpCollate;
250 pNew->pColl = pLeft->pColl;
251 }
252 }
253
254 sqlite3ExprSetHeight(pNew);
255 return pNew;
256}
257
258/*
259** Works like sqlite3Expr() but frees its pLeft and pRight arguments
260** if it fails due to a malloc problem.
261*/
262Expr *sqlite3ExprOrFree(int op, Expr *pLeft, Expr *pRight, const Token *pToken){
263 Expr *pNew = sqlite3Expr(op, pLeft, pRight, pToken);
264 if( pNew==0 ){
265 sqlite3ExprDelete(pLeft);
266 sqlite3ExprDelete(pRight);
267 }
268 return pNew;
269}
270
271/*
272** When doing a nested parse, you can include terms in an expression
273** that look like this: #0 #1 #2 ... These terms refer to elements
274** on the stack. "#0" means the top of the stack.
275** "#1" means the next down on the stack. And so forth.
276**
277** This routine is called by the parser to deal with on of those terms.
278** It immediately generates code to store the value in a memory location.
279** The returns an expression that will code to extract the value from
280** that memory location as needed.
281*/
282Expr *sqlite3RegisterExpr(Parse *pParse, Token *pToken){
283 Vdbe *v = pParse->pVdbe;
284 Expr *p;
285 int depth;
286 if( pParse->nested==0 ){
287 sqlite3ErrorMsg(pParse, "near \"%T\": syntax error", pToken);
288 return sqlite3Expr(TK_NULL, 0, 0, 0);
289 }
290 if( v==0 ) return 0;
291 p = sqlite3Expr(TK_REGISTER, 0, 0, pToken);
292 if( p==0 ){
293 return 0; /* Malloc failed */
294 }
295 depth = atoi((char*)&pToken->z[1]);
296 p->iTable = pParse->nMem++;
297 sqlite3VdbeAddOp(v, OP_Dup, depth, 0);
298 sqlite3VdbeAddOp(v, OP_MemStore, p->iTable, 1);
299 return p;
300}
301
302/*
303** Join two expressions using an AND operator. If either expression is
304** NULL, then just return the other expression.
305*/
306Expr *sqlite3ExprAnd(Expr *pLeft, Expr *pRight){
307 if( pLeft==0 ){
308 return pRight;
309 }else if( pRight==0 ){
310 return pLeft;
311 }else{
312 return sqlite3Expr(TK_AND, pLeft, pRight, 0);
313 }
314}
315
316/*
317** Set the Expr.span field of the given expression to span all
318** text between the two given tokens.
319*/
320void sqlite3ExprSpan(Expr *pExpr, Token *pLeft, Token *pRight){
321 assert( pRight!=0 );
322 assert( pLeft!=0 );
323 if( !sqlite3MallocFailed() && pRight->z && pLeft->z ){
324 assert( pLeft->dyn==0 || pLeft->z[pLeft->n]==0 );
325 if( pLeft->dyn==0 && pRight->dyn==0 ){
326 pExpr->span.z = pLeft->z;
327 pExpr->span.n = pRight->n + (pRight->z - pLeft->z);
328 }else{
329 pExpr->span.z = 0;
330 }
331 }
332}
333
334/*
335** Construct a new expression node for a function with multiple
336** arguments.
337*/
338Expr *sqlite3ExprFunction(ExprList *pList, Token *pToken){
339 Expr *pNew;
340 assert( pToken );
341 pNew = sqliteMalloc( sizeof(Expr) );
342 if( pNew==0 ){
343 sqlite3ExprListDelete(pList); /* Avoid leaking memory when malloc fails */
344 return 0;
345 }
346 pNew->op = TK_FUNCTION;
347 pNew->pList = pList;
348 assert( pToken->dyn==0 );
349 pNew->token = *pToken;
350 pNew->span = pNew->token;
351
352 sqlite3ExprSetHeight(pNew);
353 return pNew;
354}
355
356/*
357** Assign a variable number to an expression that encodes a wildcard
358** in the original SQL statement.
359**
360** Wildcards consisting of a single "?" are assigned the next sequential
361** variable number.
362**
363** Wildcards of the form "?nnn" are assigned the number "nnn". We make
364** sure "nnn" is not too be to avoid a denial of service attack when
365** the SQL statement comes from an external source.
366**
367** Wildcards of the form ":aaa" or "$aaa" are assigned the same number
368** as the previous instance of the same wildcard. Or if this is the first
369** instance of the wildcard, the next sequenial variable number is
370** assigned.
371*/
372void sqlite3ExprAssignVarNumber(Parse *pParse, Expr *pExpr){
373 Token *pToken;
374 if( pExpr==0 ) return;
375 pToken = &pExpr->token;
376 assert( pToken->n>=1 );
377 assert( pToken->z!=0 );
378 assert( pToken->z[0]!=0 );
379 if( pToken->n==1 ){
380 /* Wildcard of the form "?". Assign the next variable number */
381 pExpr->iTable = ++pParse->nVar;
382 }else if( pToken->z[0]=='?' ){
383 /* Wildcard of the form "?nnn". Convert "nnn" to an integer and
384 ** use it as the variable number */
385 int i;
386 pExpr->iTable = i = atoi((char*)&pToken->z[1]);
387 if( i<1 || i>SQLITE_MAX_VARIABLE_NUMBER ){
388 sqlite3ErrorMsg(pParse, "variable number must be between ?1 and ?%d",
389 SQLITE_MAX_VARIABLE_NUMBER);
390 }
391 if( i>pParse->nVar ){
392 pParse->nVar = i;
393 }
394 }else{
395 /* Wildcards of the form ":aaa" or "$aaa". Reuse the same variable
396 ** number as the prior appearance of the same name, or if the name
397 ** has never appeared before, reuse the same variable number
398 */
399 int i, n;
400 n = pToken->n;
401 for(i=0; i<pParse->nVarExpr; i++){
402 Expr *pE;
403 if( (pE = pParse->apVarExpr[i])!=0
404 && pE->token.n==n
405 && memcmp(pE->token.z, pToken->z, n)==0 ){
406 pExpr->iTable = pE->iTable;
407 break;
408 }
409 }
410 if( i>=pParse->nVarExpr ){
411 pExpr->iTable = ++pParse->nVar;
412 if( pParse->nVarExpr>=pParse->nVarExprAlloc-1 ){
413 pParse->nVarExprAlloc += pParse->nVarExprAlloc + 10;
414 pParse->apVarExpr = sqliteReallocOrFree(pParse->apVarExpr,
415 pParse->nVarExprAlloc*sizeof(pParse->apVarExpr[0]) );
416 }
417 if( !sqlite3MallocFailed() ){
418 assert( pParse->apVarExpr!=0 );
419 pParse->apVarExpr[pParse->nVarExpr++] = pExpr;
420 }
421 }
422 }
423 if( !pParse->nErr && pParse->nVar>SQLITE_MAX_VARIABLE_NUMBER ){
424 sqlite3ErrorMsg(pParse, "too many SQL variables");
425 }
426}
427
428/*
429** Recursively delete an expression tree.
430*/
431void sqlite3ExprDelete(Expr *p){
432 if( p==0 ) return;
433 if( p->span.dyn ) sqliteFree((char*)p->span.z);
434 if( p->token.dyn ) sqliteFree((char*)p->token.z);
435 sqlite3ExprDelete(p->pLeft);
436 sqlite3ExprDelete(p->pRight);
437 sqlite3ExprListDelete(p->pList);
438 sqlite3SelectDelete(p->pSelect);
439 sqliteFree(p);
440}
441
442/*
443** The Expr.token field might be a string literal that is quoted.
444** If so, remove the quotation marks.
445*/
446void sqlite3DequoteExpr(Expr *p){
447 if( ExprHasAnyProperty(p, EP_Dequoted) ){
448 return;
449 }
450 ExprSetProperty(p, EP_Dequoted);
451 if( p->token.dyn==0 ){
452 sqlite3TokenCopy(&p->token, &p->token);
453 }
454 sqlite3Dequote((char*)p->token.z);
455}
456
457
458/*
459** The following group of routines make deep copies of expressions,
460** expression lists, ID lists, and select statements. The copies can
461** be deleted (by being passed to their respective ...Delete() routines)
462** without effecting the originals.
463**
464** The expression list, ID, and source lists return by sqlite3ExprListDup(),
465** sqlite3IdListDup(), and sqlite3SrcListDup() can not be further expanded
466** by subsequent calls to sqlite*ListAppend() routines.
467**
468** Any tables that the SrcList might point to are not duplicated.
469*/
470Expr *sqlite3ExprDup(Expr *p){
471 Expr *pNew;
472 if( p==0 ) return 0;
473 pNew = sqliteMallocRaw( sizeof(*p) );
474 if( pNew==0 ) return 0;
475 memcpy(pNew, p, sizeof(*pNew));
476 if( p->token.z!=0 ){
477 pNew->token.z = (u8*)sqliteStrNDup((char*)p->token.z, p->token.n);
478 pNew->token.dyn = 1;
479 }else{
480 assert( pNew->token.z==0 );
481 }
482 pNew->span.z = 0;
483 pNew->pLeft = sqlite3ExprDup(p->pLeft);
484 pNew->pRight = sqlite3ExprDup(p->pRight);
485 pNew->pList = sqlite3ExprListDup(p->pList);
486 pNew->pSelect = sqlite3SelectDup(p->pSelect);
487 return pNew;
488}
489void sqlite3TokenCopy(Token *pTo, Token *pFrom){
490 if( pTo->dyn ) sqliteFree((char*)pTo->z);
491 if( pFrom->z ){
492 pTo->n = pFrom->n;
493 pTo->z = (u8*)sqliteStrNDup((char*)pFrom->z, pFrom->n);
494 pTo->dyn = 1;
495 }else{
496 pTo->z = 0;
497 }
498}
499ExprList *sqlite3ExprListDup(ExprList *p){
500 ExprList *pNew;
501 struct ExprList_item *pItem, *pOldItem;
502 int i;
503 if( p==0 ) return 0;
504 pNew = sqliteMalloc( sizeof(*pNew) );
505 if( pNew==0 ) return 0;
506 pNew->nExpr = pNew->nAlloc = p->nExpr;
507 pNew->a = pItem = sqliteMalloc( p->nExpr*sizeof(p->a[0]) );
508 if( pItem==0 ){
509 sqliteFree(pNew);
510 return 0;
511 }
512 pOldItem = p->a;
513 for(i=0; i<p->nExpr; i++, pItem++, pOldItem++){
514 Expr *pNewExpr, *pOldExpr;
515 pItem->pExpr = pNewExpr = sqlite3ExprDup(pOldExpr = pOldItem->pExpr);
516 if( pOldExpr->span.z!=0 && pNewExpr ){
517 /* Always make a copy of the span for top-level expressions in the
518 ** expression list. The logic in SELECT processing that determines
519 ** the names of columns in the result set needs this information */
520 sqlite3TokenCopy(&pNewExpr->span, &pOldExpr->span);
521 }
522 assert( pNewExpr==0 || pNewExpr->span.z!=0
523 || pOldExpr->span.z==0
524 || sqlite3MallocFailed() );
525 pItem->zName = sqliteStrDup(pOldItem->zName);
526 pItem->sortOrder = pOldItem->sortOrder;
527 pItem->isAgg = pOldItem->isAgg;
528 pItem->done = 0;
529 }
530 return pNew;
531}
532
533/*
534** If cursors, triggers, views and subqueries are all omitted from
535** the build, then none of the following routines, except for
536** sqlite3SelectDup(), can be called. sqlite3SelectDup() is sometimes
537** called with a NULL argument.
538*/
539#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_TRIGGER) \
540 || !defined(SQLITE_OMIT_SUBQUERY)
541SrcList *sqlite3SrcListDup(SrcList *p){
542 SrcList *pNew;
543 int i;
544 int nByte;
545 if( p==0 ) return 0;
546 nByte = sizeof(*p) + (p->nSrc>0 ? sizeof(p->a[0]) * (p->nSrc-1) : 0);
547 pNew = sqliteMallocRaw( nByte );
548 if( pNew==0 ) return 0;
549 pNew->nSrc = pNew->nAlloc = p->nSrc;
550 for(i=0; i<p->nSrc; i++){
551 struct SrcList_item *pNewItem = &pNew->a[i];
552 struct SrcList_item *pOldItem = &p->a[i];
553 Table *pTab;
554 pNewItem->zDatabase = sqliteStrDup(pOldItem->zDatabase);
555 pNewItem->zName = sqliteStrDup(pOldItem->zName);
556 pNewItem->zAlias = sqliteStrDup(pOldItem->zAlias);
557 pNewItem->jointype = pOldItem->jointype;
558 pNewItem->iCursor = pOldItem->iCursor;
559 pNewItem->isPopulated = pOldItem->isPopulated;
560 pTab = pNewItem->pTab = pOldItem->pTab;
561 if( pTab ){
562 pTab->nRef++;
563 }
564 pNewItem->pSelect = sqlite3SelectDup(pOldItem->pSelect);
565 pNewItem->pOn = sqlite3ExprDup(pOldItem->pOn);
566 pNewItem->pUsing = sqlite3IdListDup(pOldItem->pUsing);
567 pNewItem->colUsed = pOldItem->colUsed;
568 }
569 return pNew;
570}
571IdList *sqlite3IdListDup(IdList *p){
572 IdList *pNew;
573 int i;
574 if( p==0 ) return 0;
575 pNew = sqliteMallocRaw( sizeof(*pNew) );
576 if( pNew==0 ) return 0;
577 pNew->nId = pNew->nAlloc = p->nId;
578 pNew->a = sqliteMallocRaw( p->nId*sizeof(p->a[0]) );
579 if( pNew->a==0 ){
580 sqliteFree(pNew);
581 return 0;
582 }
583 for(i=0; i<p->nId; i++){
584 struct IdList_item *pNewItem = &pNew->a[i];
585 struct IdList_item *pOldItem = &p->a[i];
586 pNewItem->zName = sqliteStrDup(pOldItem->zName);
587 pNewItem->idx = pOldItem->idx;
588 }
589 return pNew;
590}
591Select *sqlite3SelectDup(Select *p){
592 Select *pNew;
593 if( p==0 ) return 0;
594 pNew = sqliteMallocRaw( sizeof(*p) );
595 if( pNew==0 ) return 0;
596 pNew->isDistinct = p->isDistinct;
597 pNew->pEList = sqlite3ExprListDup(p->pEList);
598 pNew->pSrc = sqlite3SrcListDup(p->pSrc);
599 pNew->pWhere = sqlite3ExprDup(p->pWhere);
600 pNew->pGroupBy = sqlite3ExprListDup(p->pGroupBy);
601 pNew->pHaving = sqlite3ExprDup(p->pHaving);
602 pNew->pOrderBy = sqlite3ExprListDup(p->pOrderBy);
603 pNew->op = p->op;
604 pNew->pPrior = sqlite3SelectDup(p->pPrior);
605 pNew->pLimit = sqlite3ExprDup(p->pLimit);
606 pNew->pOffset = sqlite3ExprDup(p->pOffset);
607 pNew->iLimit = -1;
608 pNew->iOffset = -1;
609 pNew->isResolved = p->isResolved;
610 pNew->isAgg = p->isAgg;
611 pNew->usesEphm = 0;
612 pNew->disallowOrderBy = 0;
613 pNew->pRightmost = 0;
614 pNew->addrOpenEphm[0] = -1;
615 pNew->addrOpenEphm[1] = -1;
616 pNew->addrOpenEphm[2] = -1;
617 return pNew;
618}
619#else
620Select *sqlite3SelectDup(Select *p){
621 assert( p==0 );
622 return 0;
623}
624#endif
625
626
627/*
628** Add a new element to the end of an expression list. If pList is
629** initially NULL, then create a new expression list.
630*/
631ExprList *sqlite3ExprListAppend(ExprList *pList, Expr *pExpr, Token *pName){
632 if( pList==0 ){
633 pList = sqliteMalloc( sizeof(ExprList) );
634 if( pList==0 ){
635 goto no_mem;
636 }
637 assert( pList->nAlloc==0 );
638 }
639 if( pList->nAlloc<=pList->nExpr ){
640 struct ExprList_item *a;
641 int n = pList->nAlloc*2 + 4;
642 a = sqliteRealloc(pList->a, n*sizeof(pList->a[0]));
643 if( a==0 ){
644 goto no_mem;
645 }
646 pList->a = a;
647 pList->nAlloc = n;
648 }
649 assert( pList->a!=0 );
650 if( pExpr || pName ){
651 struct ExprList_item *pItem = &pList->a[pList->nExpr++];
652 memset(pItem, 0, sizeof(*pItem));
653 pItem->zName = sqlite3NameFromToken(pName);
654 pItem->pExpr = pExpr;
655 }
656 return pList;
657
658no_mem:
659 /* Avoid leaking memory if malloc has failed. */
660 sqlite3ExprDelete(pExpr);
661 sqlite3ExprListDelete(pList);
662 return 0;
663}
664
665/*
666** If the expression list pEList contains more than iLimit elements,
667** leave an error message in pParse.
668*/
669void sqlite3ExprListCheckLength(
670 Parse *pParse,
671 ExprList *pEList,
672 int iLimit,
673 const char *zObject
674){
675 if( pEList && pEList->nExpr>iLimit ){
676 sqlite3ErrorMsg(pParse, "too many columns in %s", zObject);
677 }
678}
679
680
681#if SQLITE_MAX_EXPR_DEPTH>0
682/* The following three functions, heightOfExpr(), heightOfExprList()
683** and heightOfSelect(), are used to determine the maximum height
684** of any expression tree referenced by the structure passed as the
685** first argument.
686**
687** If this maximum height is greater than the current value pointed
688** to by pnHeight, the second parameter, then set *pnHeight to that
689** value.
690*/
691static void heightOfExpr(Expr *p, int *pnHeight){
692 if( p ){
693 if( p->nHeight>*pnHeight ){
694 *pnHeight = p->nHeight;
695 }
696 }
697}
698static void heightOfExprList(ExprList *p, int *pnHeight){
699 if( p ){
700 int i;
701 for(i=0; i<p->nExpr; i++){
702 heightOfExpr(p->a[i].pExpr, pnHeight);
703 }
704 }
705}
706static void heightOfSelect(Select *p, int *pnHeight){
707 if( p ){
708 heightOfExpr(p->pWhere, pnHeight);
709 heightOfExpr(p->pHaving, pnHeight);
710 heightOfExpr(p->pLimit, pnHeight);
711 heightOfExpr(p->pOffset, pnHeight);
712 heightOfExprList(p->pEList, pnHeight);
713 heightOfExprList(p->pGroupBy, pnHeight);
714 heightOfExprList(p->pOrderBy, pnHeight);
715 heightOfSelect(p->pPrior, pnHeight);
716 }
717}
718
719/*
720** Set the Expr.nHeight variable in the structure passed as an
721** argument. An expression with no children, Expr.pList or
722** Expr.pSelect member has a height of 1. Any other expression
723** has a height equal to the maximum height of any other
724** referenced Expr plus one.
725*/
726void sqlite3ExprSetHeight(Expr *p){
727 int nHeight = 0;
728 heightOfExpr(p->pLeft, &nHeight);
729 heightOfExpr(p->pRight, &nHeight);
730 heightOfExprList(p->pList, &nHeight);
731 heightOfSelect(p->pSelect, &nHeight);
732 p->nHeight = nHeight + 1;
733}
734
735/*
736** Return the maximum height of any expression tree referenced
737** by the select statement passed as an argument.
738*/
739int sqlite3SelectExprHeight(Select *p){
740 int nHeight = 0;
741 heightOfSelect(p, &nHeight);
742 return nHeight;
743}
744#endif
745
746/*
747** Delete an entire expression list.
748*/
749void sqlite3ExprListDelete(ExprList *pList){
750 int i;
751 struct ExprList_item *pItem;
752 if( pList==0 ) return;
753 assert( pList->a!=0 || (pList->nExpr==0 && pList->nAlloc==0) );
754 assert( pList->nExpr<=pList->nAlloc );
755 for(pItem=pList->a, i=0; i<pList->nExpr; i++, pItem++){
756 sqlite3ExprDelete(pItem->pExpr);
757 sqliteFree(pItem->zName);
758 }
759 sqliteFree(pList->a);
760 sqliteFree(pList);
761}
762
763/*
764** Walk an expression tree. Call xFunc for each node visited.
765**
766** The return value from xFunc determines whether the tree walk continues.
767** 0 means continue walking the tree. 1 means do not walk children
768** of the current node but continue with siblings. 2 means abandon
769** the tree walk completely.
770**
771** The return value from this routine is 1 to abandon the tree walk
772** and 0 to continue.
773**
774** NOTICE: This routine does *not* descend into subqueries.
775*/
776static int walkExprList(ExprList *, int (*)(void *, Expr*), void *);
777static int walkExprTree(Expr *pExpr, int (*xFunc)(void*,Expr*), void *pArg){
778 int rc;
779 if( pExpr==0 ) return 0;
780 rc = (*xFunc)(pArg, pExpr);
781 if( rc==0 ){
782 if( walkExprTree(pExpr->pLeft, xFunc, pArg) ) return 1;
783 if( walkExprTree(pExpr->pRight, xFunc, pArg) ) return 1;
784 if( walkExprList(pExpr->pList, xFunc, pArg) ) return 1;
785 }
786 return rc>1;
787}
788
789/*
790** Call walkExprTree() for every expression in list p.
791*/
792static int walkExprList(ExprList *p, int (*xFunc)(void *, Expr*), void *pArg){
793 int i;
794 struct ExprList_item *pItem;
795 if( !p ) return 0;
796 for(i=p->nExpr, pItem=p->a; i>0; i--, pItem++){
797 if( walkExprTree(pItem->pExpr, xFunc, pArg) ) return 1;
798 }
799 return 0;
800}
801
802/*
803** Call walkExprTree() for every expression in Select p, not including
804** expressions that are part of sub-selects in any FROM clause or the LIMIT
805** or OFFSET expressions..
806*/
807static int walkSelectExpr(Select *p, int (*xFunc)(void *, Expr*), void *pArg){
808 walkExprList(p->pEList, xFunc, pArg);
809 walkExprTree(p->pWhere, xFunc, pArg);
810 walkExprList(p->pGroupBy, xFunc, pArg);
811 walkExprTree(p->pHaving, xFunc, pArg);
812 walkExprList(p->pOrderBy, xFunc, pArg);
813 if( p->pPrior ){
814 walkSelectExpr(p->pPrior, xFunc, pArg);
815 }
816 return 0;
817}
818
819
820/*
821** This routine is designed as an xFunc for walkExprTree().
822**
823** pArg is really a pointer to an integer. If we can tell by looking
824** at pExpr that the expression that contains pExpr is not a constant
825** expression, then set *pArg to 0 and return 2 to abandon the tree walk.
826** If pExpr does does not disqualify the expression from being a constant
827** then do nothing.
828**
829** After walking the whole tree, if no nodes are found that disqualify
830** the expression as constant, then we assume the whole expression
831** is constant. See sqlite3ExprIsConstant() for additional information.
832*/
833static int exprNodeIsConstant(void *pArg, Expr *pExpr){
834 int *pN = (int*)pArg;
835
836 /* If *pArg is 3 then any term of the expression that comes from
837 ** the ON or USING clauses of a join disqualifies the expression
838 ** from being considered constant. */
839 if( (*pN)==3 && ExprHasAnyProperty(pExpr, EP_FromJoin) ){
840 *pN = 0;
841 return 2;
842 }
843
844 switch( pExpr->op ){
845 /* Consider functions to be constant if all their arguments are constant
846 ** and *pArg==2 */
847 case TK_FUNCTION:
848 if( (*pN)==2 ) return 0;
849 /* Fall through */
850 case TK_ID:
851 case TK_COLUMN:
852 case TK_DOT:
853 case TK_AGG_FUNCTION:
854 case TK_AGG_COLUMN:
855#ifndef SQLITE_OMIT_SUBQUERY
856 case TK_SELECT:
857 case TK_EXISTS:
858#endif
859 *pN = 0;
860 return 2;
861 case TK_IN:
862 if( pExpr->pSelect ){
863 *pN = 0;
864 return 2;
865 }
866 default:
867 return 0;
868 }
869}
870
871/*
872** Walk an expression tree. Return 1 if the expression is constant
873** and 0 if it involves variables or function calls.
874**
875** For the purposes of this function, a double-quoted string (ex: "abc")
876** is considered a variable but a single-quoted string (ex: 'abc') is
877** a constant.
878*/
879int sqlite3ExprIsConstant(Expr *p){
880 int isConst = 1;
881 walkExprTree(p, exprNodeIsConstant, &isConst);
882 return isConst;
883}
884
885/*
886** Walk an expression tree. Return 1 if the expression is constant
887** that does no originate from the ON or USING clauses of a join.
888** Return 0 if it involves variables or function calls or terms from
889** an ON or USING clause.
890*/
891int sqlite3ExprIsConstantNotJoin(Expr *p){
892 int isConst = 3;
893 walkExprTree(p, exprNodeIsConstant, &isConst);
894 return isConst!=0;
895}
896
897/*
898** Walk an expression tree. Return 1 if the expression is constant
899** or a function call with constant arguments. Return and 0 if there
900** are any variables.
901**
902** For the purposes of this function, a double-quoted string (ex: "abc")
903** is considered a variable but a single-quoted string (ex: 'abc') is
904** a constant.
905*/
906int sqlite3ExprIsConstantOrFunction(Expr *p){
907 int isConst = 2;
908 walkExprTree(p, exprNodeIsConstant, &isConst);
909 return isConst!=0;
910}
911
912/*
913** If the expression p codes a constant integer that is small enough
914** to fit in a 32-bit integer, return 1 and put the value of the integer
915** in *pValue. If the expression is not an integer or if it is too big
916** to fit in a signed 32-bit integer, return 0 and leave *pValue unchanged.
917*/
918int sqlite3ExprIsInteger(Expr *p, int *pValue){
919 switch( p->op ){
920 case TK_INTEGER: {
921 if( sqlite3GetInt32((char*)p->token.z, pValue) ){
922 return 1;
923 }
924 break;
925 }
926 case TK_UPLUS: {
927 return sqlite3ExprIsInteger(p->pLeft, pValue);
928 }
929 case TK_UMINUS: {
930 int v;
931 if( sqlite3ExprIsInteger(p->pLeft, &v) ){
932 *pValue = -v;
933 return 1;
934 }
935 break;
936 }
937 default: break;
938 }
939 return 0;
940}
941
942/*
943** Return TRUE if the given string is a row-id column name.
944*/
945int sqlite3IsRowid(const char *z){
946 if( sqlite3StrICmp(z, "_ROWID_")==0 ) return 1;
947 if( sqlite3StrICmp(z, "ROWID")==0 ) return 1;
948 if( sqlite3StrICmp(z, "OID")==0 ) return 1;
949 return 0;
950}
951
952/*
953** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
954** that name in the set of source tables in pSrcList and make the pExpr
955** expression node refer back to that source column. The following changes
956** are made to pExpr:
957**
958** pExpr->iDb Set the index in db->aDb[] of the database holding
959** the table.
960** pExpr->iTable Set to the cursor number for the table obtained
961** from pSrcList.
962** pExpr->iColumn Set to the column number within the table.
963** pExpr->op Set to TK_COLUMN.
964** pExpr->pLeft Any expression this points to is deleted
965** pExpr->pRight Any expression this points to is deleted.
966**
967** The pDbToken is the name of the database (the "X"). This value may be
968** NULL meaning that name is of the form Y.Z or Z. Any available database
969** can be used. The pTableToken is the name of the table (the "Y"). This
970** value can be NULL if pDbToken is also NULL. If pTableToken is NULL it
971** means that the form of the name is Z and that columns from any table
972** can be used.
973**
974** If the name cannot be resolved unambiguously, leave an error message
975** in pParse and return non-zero. Return zero on success.
976*/
977static int lookupName(
978 Parse *pParse, /* The parsing context */
979 Token *pDbToken, /* Name of the database containing table, or NULL */
980 Token *pTableToken, /* Name of table containing column, or NULL */
981 Token *pColumnToken, /* Name of the column. */
982 NameContext *pNC, /* The name context used to resolve the name */
983 Expr *pExpr /* Make this EXPR node point to the selected column */
984){
985 char *zDb = 0; /* Name of the database. The "X" in X.Y.Z */
986 char *zTab = 0; /* Name of the table. The "Y" in X.Y.Z or Y.Z */
987 char *zCol = 0; /* Name of the column. The "Z" */
988 int i, j; /* Loop counters */
989 int cnt = 0; /* Number of matching column names */
990 int cntTab = 0; /* Number of matching table names */
991 sqlite3 *db = pParse->db; /* The database */
992 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
993 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
994 NameContext *pTopNC = pNC; /* First namecontext in the list */
995
996 assert( pColumnToken && pColumnToken->z ); /* The Z in X.Y.Z cannot be NULL */
997 zDb = sqlite3NameFromToken(pDbToken);
998 zTab = sqlite3NameFromToken(pTableToken);
999 zCol = sqlite3NameFromToken(pColumnToken);
1000 if( sqlite3MallocFailed() ){
1001 goto lookupname_end;
1002 }
1003
1004 pExpr->iTable = -1;
1005 while( pNC && cnt==0 ){
1006 ExprList *pEList;
1007 SrcList *pSrcList = pNC->pSrcList;
1008
1009 if( pSrcList ){
1010 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
1011 Table *pTab;
1012 int iDb;
1013 Column *pCol;
1014
1015 pTab = pItem->pTab;
1016 assert( pTab!=0 );
1017 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
1018 assert( pTab->nCol>0 );
1019 if( zTab ){
1020 if( pItem->zAlias ){
1021 char *zTabName = pItem->zAlias;
1022 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1023 }else{
1024 char *zTabName = pTab->zName;
1025 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
1026 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
1027 continue;
1028 }
1029 }
1030 }
1031 if( 0==(cntTab++) ){
1032 pExpr->iTable = pItem->iCursor;
1033 pExpr->pSchema = pTab->pSchema;
1034 pMatch = pItem;
1035 }
1036 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
1037 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1038 const char *zColl = pTab->aCol[j].zColl;
1039 IdList *pUsing;
1040 cnt++;
1041 pExpr->iTable = pItem->iCursor;
1042 pMatch = pItem;
1043 pExpr->pSchema = pTab->pSchema;
1044 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
1045 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
1046 pExpr->affinity = pTab->aCol[j].affinity;
1047 if( (pExpr->flags & EP_ExpCollate)==0 ){
1048 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1049 }
1050 if( i<pSrcList->nSrc-1 ){
1051 if( pItem[1].jointype & JT_NATURAL ){
1052 /* If this match occurred in the left table of a natural join,
1053 ** then skip the right table to avoid a duplicate match */
1054 pItem++;
1055 i++;
1056 }else if( (pUsing = pItem[1].pUsing)!=0 ){
1057 /* If this match occurs on a column that is in the USING clause
1058 ** of a join, skip the search of the right table of the join
1059 ** to avoid a duplicate match there. */
1060 int k;
1061 for(k=0; k<pUsing->nId; k++){
1062 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
1063 pItem++;
1064 i++;
1065 break;
1066 }
1067 }
1068 }
1069 }
1070 break;
1071 }
1072 }
1073 }
1074 }
1075
1076#ifndef SQLITE_OMIT_TRIGGER
1077 /* If we have not already resolved the name, then maybe
1078 ** it is a new.* or old.* trigger argument reference
1079 */
1080 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
1081 TriggerStack *pTriggerStack = pParse->trigStack;
1082 Table *pTab = 0;
1083 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
1084 pExpr->iTable = pTriggerStack->newIdx;
1085 assert( pTriggerStack->pTab );
1086 pTab = pTriggerStack->pTab;
1087 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
1088 pExpr->iTable = pTriggerStack->oldIdx;
1089 assert( pTriggerStack->pTab );
1090 pTab = pTriggerStack->pTab;
1091 }
1092
1093 if( pTab ){
1094 int iCol;
1095 Column *pCol = pTab->aCol;
1096
1097 pExpr->pSchema = pTab->pSchema;
1098 cntTab++;
1099 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
1100 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
1101 const char *zColl = pTab->aCol[iCol].zColl;
1102 cnt++;
1103 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
1104 pExpr->affinity = pTab->aCol[iCol].affinity;
1105 if( (pExpr->flags & EP_ExpCollate)==0 ){
1106 pExpr->pColl = sqlite3FindCollSeq(db, ENC(db), zColl,-1, 0);
1107 }
1108 pExpr->pTab = pTab;
1109 break;
1110 }
1111 }
1112 }
1113 }
1114#endif /* !defined(SQLITE_OMIT_TRIGGER) */
1115
1116 /*
1117 ** Perhaps the name is a reference to the ROWID
1118 */
1119 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
1120 cnt = 1;
1121 pExpr->iColumn = -1;
1122 pExpr->affinity = SQLITE_AFF_INTEGER;
1123 }
1124
1125 /*
1126 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
1127 ** might refer to an result-set alias. This happens, for example, when
1128 ** we are resolving names in the WHERE clause of the following command:
1129 **
1130 ** SELECT a+b AS x FROM table WHERE x<10;
1131 **
1132 ** In cases like this, replace pExpr with a copy of the expression that
1133 ** forms the result set entry ("a+b" in the example) and return immediately.
1134 ** Note that the expression in the result set should have already been
1135 ** resolved by the time the WHERE clause is resolved.
1136 */
1137 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
1138 for(j=0; j<pEList->nExpr; j++){
1139 char *zAs = pEList->a[j].zName;
1140 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
1141 Expr *pDup;
1142 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
1143 assert( pExpr->pList==0 );
1144 assert( pExpr->pSelect==0 );
1145 pDup = sqlite3ExprDup(pEList->a[j].pExpr);
1146 if( pExpr->flags & EP_ExpCollate ){
1147 pDup->pColl = pExpr->pColl;
1148 pDup->flags |= EP_ExpCollate;
1149 }
1150 if( pExpr->span.dyn ) sqliteFree((char*)pExpr->span.z);
1151 if( pExpr->token.dyn ) sqliteFree((char*)pExpr->token.z);
1152 memcpy(pExpr, pDup, sizeof(*pExpr));
1153 sqliteFree(pDup);
1154 cnt = 1;
1155 assert( zTab==0 && zDb==0 );
1156 goto lookupname_end_2;
1157 }
1158 }
1159 }
1160
1161 /* Advance to the next name context. The loop will exit when either
1162 ** we have a match (cnt>0) or when we run out of name contexts.
1163 */
1164 if( cnt==0 ){
1165 pNC = pNC->pNext;
1166 }
1167 }
1168
1169 /*
1170 ** If X and Y are NULL (in other words if only the column name Z is
1171 ** supplied) and the value of Z is enclosed in double-quotes, then
1172 ** Z is a string literal if it doesn't match any column names. In that
1173 ** case, we need to return right away and not make any changes to
1174 ** pExpr.
1175 **
1176 ** Because no reference was made to outer contexts, the pNC->nRef
1177 ** fields are not changed in any context.
1178 */
1179 if( cnt==0 && zTab==0 && pColumnToken->z[0]=='"' ){
1180 sqliteFree(zCol);
1181 return 0;
1182 }
1183
1184 /*
1185 ** cnt==0 means there was not match. cnt>1 means there were two or
1186 ** more matches. Either way, we have an error.
1187 */
1188 if( cnt!=1 ){
1189 char *z = 0;
1190 char *zErr;
1191 zErr = cnt==0 ? "no such column: %s" : "ambiguous column name: %s";
1192 if( zDb ){
1193 sqlite3SetString(&z, zDb, ".", zTab, ".", zCol, (char*)0);
1194 }else if( zTab ){
1195 sqlite3SetString(&z, zTab, ".", zCol, (char*)0);
1196 }else{
1197 z = sqliteStrDup(zCol);
1198 }
1199 sqlite3ErrorMsg(pParse, zErr, z);
1200 sqliteFree(z);
1201 pTopNC->nErr++;
1202 }
1203
1204 /* If a column from a table in pSrcList is referenced, then record
1205 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
1206 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
1207 ** column number is greater than the number of bits in the bitmask
1208 ** then set the high-order bit of the bitmask.
1209 */
1210 if( pExpr->iColumn>=0 && pMatch!=0 ){
1211 int n = pExpr->iColumn;
1212 if( n>=sizeof(Bitmask)*8 ){
1213 n = sizeof(Bitmask)*8-1;
1214 }
1215 assert( pMatch->iCursor==pExpr->iTable );
1216 pMatch->colUsed |= ((Bitmask)1)<<n;
1217 }
1218
1219lookupname_end:
1220 /* Clean up and return
1221 */
1222 sqliteFree(zDb);
1223 sqliteFree(zTab);
1224 sqlite3ExprDelete(pExpr->pLeft);
1225 pExpr->pLeft = 0;
1226 sqlite3ExprDelete(pExpr->pRight);
1227 pExpr->pRight = 0;
1228 pExpr->op = TK_COLUMN;
1229lookupname_end_2:
1230 sqliteFree(zCol);
1231 if( cnt==1 ){
1232 assert( pNC!=0 );
1233 sqlite3AuthRead(pParse, pExpr, pNC->pSrcList);
1234 if( pMatch && !pMatch->pSelect ){
1235 pExpr->pTab = pMatch->pTab;
1236 }
1237 /* Increment the nRef value on all name contexts from TopNC up to
1238 ** the point where the name matched. */
1239 for(;;){
1240 assert( pTopNC!=0 );
1241 pTopNC->nRef++;
1242 if( pTopNC==pNC ) break;
1243 pTopNC = pTopNC->pNext;
1244 }
1245 return 0;
1246 } else {
1247 return 1;
1248 }
1249}
1250
1251/*
1252** This routine is designed as an xFunc for walkExprTree().
1253**
1254** Resolve symbolic names into TK_COLUMN operators for the current
1255** node in the expression tree. Return 0 to continue the search down
1256** the tree or 2 to abort the tree walk.
1257**
1258** This routine also does error checking and name resolution for
1259** function names. The operator for aggregate functions is changed
1260** to TK_AGG_FUNCTION.
1261*/
1262static int nameResolverStep(void *pArg, Expr *pExpr){
1263 NameContext *pNC = (NameContext*)pArg;
1264 Parse *pParse;
1265
1266 if( pExpr==0 ) return 1;
1267 assert( pNC!=0 );
1268 pParse = pNC->pParse;
1269
1270 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return 1;
1271 ExprSetProperty(pExpr, EP_Resolved);
1272#ifndef NDEBUG
1273 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1274 SrcList *pSrcList = pNC->pSrcList;
1275 int i;
1276 for(i=0; i<pNC->pSrcList->nSrc; i++){
1277 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1278 }
1279 }
1280#endif
1281 switch( pExpr->op ){
1282 /* Double-quoted strings (ex: "abc") are used as identifiers if
1283 ** possible. Otherwise they remain as strings. Single-quoted
1284 ** strings (ex: 'abc') are always string literals.
1285 */
1286 case TK_STRING: {
1287 if( pExpr->token.z[0]=='\'' ) break;
1288 /* Fall thru into the TK_ID case if this is a double-quoted string */
1289 }
1290 /* A lone identifier is the name of a column.
1291 */
1292 case TK_ID: {
1293 lookupName(pParse, 0, 0, &pExpr->token, pNC, pExpr);
1294 return 1;
1295 }
1296
1297 /* A table name and column name: ID.ID
1298 ** Or a database, table and column: ID.ID.ID
1299 */
1300 case TK_DOT: {
1301 Token *pColumn;
1302 Token *pTable;
1303 Token *pDb;
1304 Expr *pRight;
1305
1306 /* if( pSrcList==0 ) break; */
1307 pRight = pExpr->pRight;
1308 if( pRight->op==TK_ID ){
1309 pDb = 0;
1310 pTable = &pExpr->pLeft->token;
1311 pColumn = &pRight->token;
1312 }else{
1313 assert( pRight->op==TK_DOT );
1314 pDb = &pExpr->pLeft->token;
1315 pTable = &pRight->pLeft->token;
1316 pColumn = &pRight->pRight->token;
1317 }
1318 lookupName(pParse, pDb, pTable, pColumn, pNC, pExpr);
1319 return 1;
1320 }
1321
1322 /* Resolve function names
1323 */
1324 case TK_CONST_FUNC:
1325 case TK_FUNCTION: {
1326 ExprList *pList = pExpr->pList; /* The argument list */
1327 int n = pList ? pList->nExpr : 0; /* Number of arguments */
1328 int no_such_func = 0; /* True if no such function exists */
1329 int wrong_num_args = 0; /* True if wrong number of arguments */
1330 int is_agg = 0; /* True if is an aggregate function */
1331 int i;
1332 int auth; /* Authorization to use the function */
1333 int nId; /* Number of characters in function name */
1334 const char *zId; /* The function name. */
1335 FuncDef *pDef; /* Information about the function */
1336 int enc = ENC(pParse->db); /* The database encoding */
1337
1338 zId = (char*)pExpr->token.z;
1339 nId = pExpr->token.n;
1340 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
1341 if( pDef==0 ){
1342 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
1343 if( pDef==0 ){
1344 no_such_func = 1;
1345 }else{
1346 wrong_num_args = 1;
1347 }
1348 }else{
1349 is_agg = pDef->xFunc==0;
1350 }
1351#ifndef SQLITE_OMIT_AUTHORIZATION
1352 if( pDef ){
1353 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
1354 if( auth!=SQLITE_OK ){
1355 if( auth==SQLITE_DENY ){
1356 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
1357 pDef->zName);
1358 pNC->nErr++;
1359 }
1360 pExpr->op = TK_NULL;
1361 return 1;
1362 }
1363 }
1364#endif
1365 if( is_agg && !pNC->allowAgg ){
1366 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
1367 pNC->nErr++;
1368 is_agg = 0;
1369 }else if( no_such_func ){
1370 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
1371 pNC->nErr++;
1372 }else if( wrong_num_args ){
1373 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
1374 nId, zId);
1375 pNC->nErr++;
1376 }
1377 if( is_agg ){
1378 pExpr->op = TK_AGG_FUNCTION;
1379 pNC->hasAgg = 1;
1380 }
1381 if( is_agg ) pNC->allowAgg = 0;
1382 for(i=0; pNC->nErr==0 && i<n; i++){
1383 walkExprTree(pList->a[i].pExpr, nameResolverStep, pNC);
1384 }
1385 if( is_agg ) pNC->allowAgg = 1;
1386 /* FIX ME: Compute pExpr->affinity based on the expected return
1387 ** type of the function
1388 */
1389 return is_agg;
1390 }
1391#ifndef SQLITE_OMIT_SUBQUERY
1392 case TK_SELECT:
1393 case TK_EXISTS:
1394#endif
1395 case TK_IN: {
1396 if( pExpr->pSelect ){
1397 int nRef = pNC->nRef;
1398#ifndef SQLITE_OMIT_CHECK
1399 if( pNC->isCheck ){
1400 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
1401 }
1402#endif
1403 sqlite3SelectResolve(pParse, pExpr->pSelect, pNC);
1404 assert( pNC->nRef>=nRef );
1405 if( nRef!=pNC->nRef ){
1406 ExprSetProperty(pExpr, EP_VarSelect);
1407 }
1408 }
1409 break;
1410 }
1411#ifndef SQLITE_OMIT_CHECK
1412 case TK_VARIABLE: {
1413 if( pNC->isCheck ){
1414 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
1415 }
1416 break;
1417 }
1418#endif
1419 }
1420 return 0;
1421}
1422
1423/*
1424** This routine walks an expression tree and resolves references to
1425** table columns. Nodes of the form ID.ID or ID resolve into an
1426** index to the table in the table list and a column offset. The
1427** Expr.opcode for such nodes is changed to TK_COLUMN. The Expr.iTable
1428** value is changed to the index of the referenced table in pTabList
1429** plus the "base" value. The base value will ultimately become the
1430** VDBE cursor number for a cursor that is pointing into the referenced
1431** table. The Expr.iColumn value is changed to the index of the column
1432** of the referenced table. The Expr.iColumn value for the special
1433** ROWID column is -1. Any INTEGER PRIMARY KEY column is tried as an
1434** alias for ROWID.
1435**
1436** Also resolve function names and check the functions for proper
1437** usage. Make sure all function names are recognized and all functions
1438** have the correct number of arguments. Leave an error message
1439** in pParse->zErrMsg if anything is amiss. Return the number of errors.
1440**
1441** If the expression contains aggregate functions then set the EP_Agg
1442** property on the expression.
1443*/
1444int sqlite3ExprResolveNames(
1445 NameContext *pNC, /* Namespace to resolve expressions in. */
1446 Expr *pExpr /* The expression to be analyzed. */
1447){
1448 int savedHasAgg;
1449 if( pExpr==0 ) return 0;
1450#if SQLITE_MAX_EXPR_DEPTH>0
1451 if( (pExpr->nHeight+pNC->pParse->nHeight)>SQLITE_MAX_EXPR_DEPTH ){
1452 sqlite3ErrorMsg(pNC->pParse,
1453 "Expression tree is too large (maximum depth %d)",
1454 SQLITE_MAX_EXPR_DEPTH
1455 );
1456 return 1;
1457 }
1458 pNC->pParse->nHeight += pExpr->nHeight;
1459#endif
1460 savedHasAgg = pNC->hasAgg;
1461 pNC->hasAgg = 0;
1462 walkExprTree(pExpr, nameResolverStep, pNC);
1463#if SQLITE_MAX_EXPR_DEPTH>0
1464 pNC->pParse->nHeight -= pExpr->nHeight;
1465#endif
1466 if( pNC->nErr>0 ){
1467 ExprSetProperty(pExpr, EP_Error);
1468 }
1469 if( pNC->hasAgg ){
1470 ExprSetProperty(pExpr, EP_Agg);
1471 }else if( savedHasAgg ){
1472 pNC->hasAgg = 1;
1473 }
1474 return ExprHasProperty(pExpr, EP_Error);
1475}
1476
1477/*
1478** A pointer instance of this structure is used to pass information
1479** through walkExprTree into codeSubqueryStep().
1480*/
1481typedef struct QueryCoder QueryCoder;
1482struct QueryCoder {
1483 Parse *pParse; /* The parsing context */
1484 NameContext *pNC; /* Namespace of first enclosing query */
1485};
1486
1487
1488/*
1489** Generate code for scalar subqueries used as an expression
1490** and IN operators. Examples:
1491**
1492** (SELECT a FROM b) -- subquery
1493** EXISTS (SELECT a FROM b) -- EXISTS subquery
1494** x IN (4,5,11) -- IN operator with list on right-hand side
1495** x IN (SELECT a FROM b) -- IN operator with subquery on the right
1496**
1497** The pExpr parameter describes the expression that contains the IN
1498** operator or subquery.
1499*/
1500#ifndef SQLITE_OMIT_SUBQUERY
1501void sqlite3CodeSubselect(Parse *pParse, Expr *pExpr){
1502 int testAddr = 0; /* One-time test address */
1503 Vdbe *v = sqlite3GetVdbe(pParse);
1504 if( v==0 ) return;
1505
1506
1507 /* This code must be run in its entirety every time it is encountered
1508 ** if any of the following is true:
1509 **
1510 ** * The right-hand side is a correlated subquery
1511 ** * The right-hand side is an expression list containing variables
1512 ** * We are inside a trigger
1513 **
1514 ** If all of the above are false, then we can run this code just once
1515 ** save the results, and reuse the same result on subsequent invocations.
1516 */
1517 if( !ExprHasAnyProperty(pExpr, EP_VarSelect) && !pParse->trigStack ){
1518 int mem = pParse->nMem++;
1519 sqlite3VdbeAddOp(v, OP_MemLoad, mem, 0);
1520 testAddr = sqlite3VdbeAddOp(v, OP_If, 0, 0);
1521 assert( testAddr>0 || sqlite3MallocFailed() );
1522 sqlite3VdbeAddOp(v, OP_MemInt, 1, mem);
1523 }
1524
1525 switch( pExpr->op ){
1526 case TK_IN: {
1527 char affinity;
1528 KeyInfo keyInfo;
1529 int addr; /* Address of OP_OpenEphemeral instruction */
1530
1531 affinity = sqlite3ExprAffinity(pExpr->pLeft);
1532
1533 /* Whether this is an 'x IN(SELECT...)' or an 'x IN(<exprlist>)'
1534 ** expression it is handled the same way. A virtual table is
1535 ** filled with single-field index keys representing the results
1536 ** from the SELECT or the <exprlist>.
1537 **
1538 ** If the 'x' expression is a column value, or the SELECT...
1539 ** statement returns a column value, then the affinity of that
1540 ** column is used to build the index keys. If both 'x' and the
1541 ** SELECT... statement are columns, then numeric affinity is used
1542 ** if either column has NUMERIC or INTEGER affinity. If neither
1543 ** 'x' nor the SELECT... statement are columns, then numeric affinity
1544 ** is used.
1545 */
1546 pExpr->iTable = pParse->nTab++;
1547 addr = sqlite3VdbeAddOp(v, OP_OpenEphemeral, pExpr->iTable, 0);
1548 memset(&keyInfo, 0, sizeof(keyInfo));
1549 keyInfo.nField = 1;
1550 sqlite3VdbeAddOp(v, OP_SetNumColumns, pExpr->iTable, 1);
1551
1552 if( pExpr->pSelect ){
1553 /* Case 1: expr IN (SELECT ...)
1554 **
1555 ** Generate code to write the results of the select into the temporary
1556 ** table allocated and opened above.
1557 */
1558 int iParm = pExpr->iTable + (((int)affinity)<<16);
1559 ExprList *pEList;
1560 assert( (pExpr->iTable&0x0000FFFF)==pExpr->iTable );
1561 if( sqlite3Select(pParse, pExpr->pSelect, SRT_Set, iParm, 0, 0, 0, 0) ){
1562 return;
1563 }
1564 pEList = pExpr->pSelect->pEList;
1565 if( pEList && pEList->nExpr>0 ){
1566 keyInfo.aColl[0] = sqlite3BinaryCompareCollSeq(pParse, pExpr->pLeft,
1567 pEList->a[0].pExpr);
1568 }
1569 }else if( pExpr->pList ){
1570 /* Case 2: expr IN (exprlist)
1571 **
1572** For each expression, build an index key from the evaluation and
1573 ** store it in the temporary table. If <expr> is a column, then use
1574 ** that columns affinity when building index keys. If <expr> is not
1575 ** a column, use numeric affinity.
1576 */
1577 int i;
1578 ExprList *pList = pExpr->pList;
1579 struct ExprList_item *pItem;
1580
1581 if( !affinity ){
1582 affinity = SQLITE_AFF_NONE;
1583 }
1584 keyInfo.aColl[0] = pExpr->pLeft->pColl;
1585
1586 /* Loop through each expression in <exprlist>. */
1587 for(i=pList->nExpr, pItem=pList->a; i>0; i--, pItem++){
1588 Expr *pE2 = pItem->pExpr;
1589
1590 /* If the expression is not constant then we will need to
1591 ** disable the test that was generated above that makes sure
1592 ** this code only executes once. Because for a non-constant
1593 ** expression we need to rerun this code each time.
1594 */
1595 if( testAddr>0 && !sqlite3ExprIsConstant(pE2) ){
1596 sqlite3VdbeChangeToNoop(v, testAddr-1, 3);
1597 testAddr = 0;
1598 }
1599
1600 /* Evaluate the expression and insert it into the temp table */
1601 sqlite3ExprCode(pParse, pE2);
1602 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1);
1603 sqlite3VdbeAddOp(v, OP_IdxInsert, pExpr->iTable, 0);
1604 }
1605 }
1606 sqlite3VdbeChangeP3(v, addr, (void *)&keyInfo, P3_KEYINFO);
1607 break;
1608 }
1609
1610 case TK_EXISTS:
1611 case TK_SELECT: {
1612 /* This has to be a scalar SELECT. Generate code to put the
1613 ** value of this select in a memory cell and record the number
1614 ** of the memory cell in iColumn.
1615 */
1616 static const Token one = { (u8*)"1", 0, 1 };
1617 Select *pSel;
1618 int iMem;
1619 int sop;
1620
1621 pExpr->iColumn = iMem = pParse->nMem++;
1622 pSel = pExpr->pSelect;
1623 if( pExpr->op==TK_SELECT ){
1624 sop = SRT_Mem;
1625 sqlite3VdbeAddOp(v, OP_MemNull, iMem, 0);
1626 VdbeComment((v, "# Init subquery result"));
1627 }else{
1628 sop = SRT_Exists;
1629 sqlite3VdbeAddOp(v, OP_MemInt, 0, iMem);
1630 VdbeComment((v, "# Init EXISTS result"));
1631 }
1632 sqlite3ExprDelete(pSel->pLimit);
1633 pSel->pLimit = sqlite3Expr(TK_INTEGER, 0, 0, &one);
1634 if( sqlite3Select(pParse, pSel, sop, iMem, 0, 0, 0, 0) ){
1635 return;
1636 }
1637 break;
1638 }
1639 }
1640
1641 if( testAddr ){
1642 sqlite3VdbeJumpHere(v, testAddr);
1643 }
1644
1645 return;
1646}
1647#endif /* SQLITE_OMIT_SUBQUERY */
1648
1649/*
1650** Generate an instruction that will put the integer describe by
1651** text z[0..n-1] on the stack.
1652*/
1653static void codeInteger(Vdbe *v, const char *z, int n){
1654 assert( z || sqlite3MallocFailed() );
1655 if( z ){
1656 int i;
1657 if( sqlite3GetInt32(z, &i) ){
1658 sqlite3VdbeAddOp(v, OP_Integer, i, 0);
1659 }else if( sqlite3FitsIn64Bits(z) ){
1660 sqlite3VdbeOp3(v, OP_Int64, 0, 0, z, n);
1661 }else{
1662 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, n);
1663 }
1664 }
1665}
1666
1667
1668/*
1669** Generate code that will extract the iColumn-th column from
1670** table pTab and push that column value on the stack. There
1671** is an open cursor to pTab in iTable. If iColumn<0 then
1672** code is generated that extracts the rowid.
1673*/
1674void sqlite3ExprCodeGetColumn(Vdbe *v, Table *pTab, int iColumn, int iTable){
1675 if( iColumn<0 ){
1676 int op = (pTab && IsVirtual(pTab)) ? OP_VRowid : OP_Rowid;
1677 sqlite3VdbeAddOp(v, op, iTable, 0);
1678 }else if( pTab==0 ){
1679 sqlite3VdbeAddOp(v, OP_Column, iTable, iColumn);
1680 }else{
1681 int op = IsVirtual(pTab) ? OP_VColumn : OP_Column;
1682 sqlite3VdbeAddOp(v, op, iTable, iColumn);
1683 sqlite3ColumnDefault(v, pTab, iColumn);
1684#ifndef SQLITE_OMIT_FLOATING_POINT
1685 if( pTab->aCol[iColumn].affinity==SQLITE_AFF_REAL ){
1686 sqlite3VdbeAddOp(v, OP_RealAffinity, 0, 0);
1687 }
1688#endif
1689 }
1690}
1691
1692/*
1693** Generate code into the current Vdbe to evaluate the given
1694** expression and leave the result on the top of stack.
1695**
1696** This code depends on the fact that certain token values (ex: TK_EQ)
1697** are the same as opcode values (ex: OP_Eq) that implement the corresponding
1698** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
1699** the make process cause these values to align. Assert()s in the code
1700** below verify that the numbers are aligned correctly.
1701*/
1702void sqlite3ExprCode(Parse *pParse, Expr *pExpr){
1703 Vdbe *v = pParse->pVdbe;
1704 int op;
1705 int stackChng = 1; /* Amount of change to stack depth */
1706
1707 if( v==0 ) return;
1708 if( pExpr==0 ){
1709 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1710 return;
1711 }
1712 op = pExpr->op;
1713 switch( op ){
1714 case TK_AGG_COLUMN: {
1715 AggInfo *pAggInfo = pExpr->pAggInfo;
1716 struct AggInfo_col *pCol = &pAggInfo->aCol[pExpr->iAgg];
1717 if( !pAggInfo->directMode ){
1718 sqlite3VdbeAddOp(v, OP_MemLoad, pCol->iMem, 0);
1719 break;
1720 }else if( pAggInfo->useSortingIdx ){
1721 sqlite3VdbeAddOp(v, OP_Column, pAggInfo->sortingIdx,
1722 pCol->iSorterColumn);
1723 break;
1724 }
1725 /* Otherwise, fall thru into the TK_COLUMN case */
1726 }
1727 case TK_COLUMN: {
1728 if( pExpr->iTable<0 ){
1729 /* This only happens when coding check constraints */
1730 assert( pParse->ckOffset>0 );
1731 sqlite3VdbeAddOp(v, OP_Dup, pParse->ckOffset-pExpr->iColumn-1, 1);
1732 }else{
1733 sqlite3ExprCodeGetColumn(v, pExpr->pTab, pExpr->iColumn, pExpr->iTable);
1734 }
1735 break;
1736 }
1737 case TK_INTEGER: {
1738 codeInteger(v, (char*)pExpr->token.z, pExpr->token.n);
1739 break;
1740 }
1741 case TK_FLOAT:
1742 case TK_STRING: {
1743 assert( TK_FLOAT==OP_Real );
1744 assert( TK_STRING==OP_String8 );
1745 sqlite3DequoteExpr(pExpr);
1746 sqlite3VdbeOp3(v, op, 0, 0, (char*)pExpr->token.z, pExpr->token.n);
1747 break;
1748 }
1749 case TK_NULL: {
1750 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1751 break;
1752 }
1753#ifndef SQLITE_OMIT_BLOB_LITERAL
1754 case TK_BLOB: {
1755 int n;
1756 const char *z;
1757 assert( TK_BLOB==OP_HexBlob );
1758 n = pExpr->token.n - 3;
1759 z = (char*)pExpr->token.z + 2;
1760 assert( n>=0 );
1761 if( n==0 ){
1762 z = "";
1763 }
1764 sqlite3VdbeOp3(v, op, 0, 0, z, n);
1765 break;
1766 }
1767#endif
1768 case TK_VARIABLE: {
1769 sqlite3VdbeAddOp(v, OP_Variable, pExpr->iTable, 0);
1770 if( pExpr->token.n>1 ){
1771 sqlite3VdbeChangeP3(v, -1, (char*)pExpr->token.z, pExpr->token.n);
1772 }
1773 break;
1774 }
1775 case TK_REGISTER: {
1776 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iTable, 0);
1777 break;
1778 }
1779#ifndef SQLITE_OMIT_CAST
1780 case TK_CAST: {
1781 /* Expressions of the form: CAST(pLeft AS token) */
1782 int aff, to_op;
1783 sqlite3ExprCode(pParse, pExpr->pLeft);
1784 aff = sqlite3AffinityType(&pExpr->token);
1785 to_op = aff - SQLITE_AFF_TEXT + OP_ToText;
1786 assert( to_op==OP_ToText || aff!=SQLITE_AFF_TEXT );
1787 assert( to_op==OP_ToBlob || aff!=SQLITE_AFF_NONE );
1788 assert( to_op==OP_ToNumeric || aff!=SQLITE_AFF_NUMERIC );
1789 assert( to_op==OP_ToInt || aff!=SQLITE_AFF_INTEGER );
1790 assert( to_op==OP_ToReal || aff!=SQLITE_AFF_REAL );
1791 sqlite3VdbeAddOp(v, to_op, 0, 0);
1792 stackChng = 0;
1793 break;
1794 }
1795#endif /* SQLITE_OMIT_CAST */
1796 case TK_LT:
1797 case TK_LE:
1798 case TK_GT:
1799 case TK_GE:
1800 case TK_NE:
1801 case TK_EQ: {
1802 assert( TK_LT==OP_Lt );
1803 assert( TK_LE==OP_Le );
1804 assert( TK_GT==OP_Gt );
1805 assert( TK_GE==OP_Ge );
1806 assert( TK_EQ==OP_Eq );
1807 assert( TK_NE==OP_Ne );
1808 sqlite3ExprCode(pParse, pExpr->pLeft);
1809 sqlite3ExprCode(pParse, pExpr->pRight);
1810 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, 0, 0);
1811 stackChng = -1;
1812 break;
1813 }
1814 case TK_AND:
1815 case TK_OR:
1816 case TK_PLUS:
1817 case TK_STAR:
1818 case TK_MINUS:
1819 case TK_REM:
1820 case TK_BITAND:
1821 case TK_BITOR:
1822 case TK_SLASH:
1823 case TK_LSHIFT:
1824 case TK_RSHIFT:
1825 case TK_CONCAT: {
1826 assert( TK_AND==OP_And );
1827 assert( TK_OR==OP_Or );
1828 assert( TK_PLUS==OP_Add );
1829 assert( TK_MINUS==OP_Subtract );
1830 assert( TK_REM==OP_Remainder );
1831 assert( TK_BITAND==OP_BitAnd );
1832 assert( TK_BITOR==OP_BitOr );
1833 assert( TK_SLASH==OP_Divide );
1834 assert( TK_LSHIFT==OP_ShiftLeft );
1835 assert( TK_RSHIFT==OP_ShiftRight );
1836 assert( TK_CONCAT==OP_Concat );
1837 sqlite3ExprCode(pParse, pExpr->pLeft);
1838 sqlite3ExprCode(pParse, pExpr->pRight);
1839 sqlite3VdbeAddOp(v, op, 0, 0);
1840 stackChng = -1;
1841 break;
1842 }
1843 case TK_UMINUS: {
1844 Expr *pLeft = pExpr->pLeft;
1845 assert( pLeft );
1846 if( pLeft->op==TK_FLOAT || pLeft->op==TK_INTEGER ){
1847 Token *p = &pLeft->token;
1848 char *z = sqlite3MPrintf("-%.*s", p->n, p->z);
1849 if( pLeft->op==TK_FLOAT ){
1850 sqlite3VdbeOp3(v, OP_Real, 0, 0, z, p->n+1);
1851 }else{
1852 codeInteger(v, z, p->n+1);
1853 }
1854 sqliteFree(z);
1855 break;
1856 }
1857 /* Fall through into TK_NOT */
1858 }
1859 case TK_BITNOT:
1860 case TK_NOT: {
1861 assert( TK_BITNOT==OP_BitNot );
1862 assert( TK_NOT==OP_Not );
1863 sqlite3ExprCode(pParse, pExpr->pLeft);
1864 sqlite3VdbeAddOp(v, op, 0, 0);
1865 stackChng = 0;
1866 break;
1867 }
1868 case TK_ISNULL:
1869 case TK_NOTNULL: {
1870 int dest;
1871 assert( TK_ISNULL==OP_IsNull );
1872 assert( TK_NOTNULL==OP_NotNull );
1873 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1874 sqlite3ExprCode(pParse, pExpr->pLeft);
1875 dest = sqlite3VdbeCurrentAddr(v) + 2;
1876 sqlite3VdbeAddOp(v, op, 1, dest);
1877 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0);
1878 stackChng = 0;
1879 break;
1880 }
1881 case TK_AGG_FUNCTION: {
1882 AggInfo *pInfo = pExpr->pAggInfo;
1883 if( pInfo==0 ){
1884 sqlite3ErrorMsg(pParse, "misuse of aggregate: %T",
1885 &pExpr->span);
1886 }else{
1887 sqlite3VdbeAddOp(v, OP_MemLoad, pInfo->aFunc[pExpr->iAgg].iMem, 0);
1888 }
1889 break;
1890 }
1891 case TK_CONST_FUNC:
1892 case TK_FUNCTION: {
1893 ExprList *pList = pExpr->pList;
1894 int nExpr = pList ? pList->nExpr : 0;
1895 FuncDef *pDef;
1896 int nId;
1897 const char *zId;
1898 int constMask = 0;
1899 int i;
1900 u8 enc = ENC(pParse->db);
1901 CollSeq *pColl = 0;
1902 zId = (char*)pExpr->token.z;
1903 nId = pExpr->token.n;
1904 pDef = sqlite3FindFunction(pParse->db, zId, nId, nExpr, enc, 0);
1905 assert( pDef!=0 );
1906 nExpr = sqlite3ExprCodeExprList(pParse, pList);
1907#ifndef SQLITE_OMIT_VIRTUALTABLE
1908 /* Possibly overload the function if the first argument is
1909 ** a virtual table column.
1910 **
1911 ** For infix functions (LIKE, GLOB, REGEXP, and MATCH) use the
1912 ** second argument, not the first, as the argument to test to
1913 ** see if it is a column in a virtual table. This is done because
1914 ** the left operand of infix functions (the operand we want to
1915 ** control overloading) ends up as the second argument to the
1916 ** function. The expression "A glob B" is equivalent to
1917 ** "glob(B,A). We want to use the A in "A glob B" to test
1918 ** for function overloading. But we use the B term in "glob(B,A)".
1919 */
1920 if( nExpr>=2 && (pExpr->flags & EP_InfixFunc) ){
1921 pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[1].pExpr);
1922 }else if( nExpr>0 ){
1923 pDef = sqlite3VtabOverloadFunction(pDef, nExpr, pList->a[0].pExpr);
1924 }
1925#endif
1926 for(i=0; i<nExpr && i<32; i++){
1927 if( sqlite3ExprIsConstant(pList->a[i].pExpr) ){
1928 constMask |= (1<<i);
1929 }
1930 if( pDef->needCollSeq && !pColl ){
1931 pColl = sqlite3ExprCollSeq(pParse, pList->a[i].pExpr);
1932 }
1933 }
1934 if( pDef->needCollSeq ){
1935 if( !pColl ) pColl = pParse->db->pDfltColl;
1936 sqlite3VdbeOp3(v, OP_CollSeq, 0, 0, (char *)pColl, P3_COLLSEQ);
1937 }
1938 sqlite3VdbeOp3(v, OP_Function, constMask, nExpr, (char*)pDef, P3_FUNCDEF);
1939 stackChng = 1-nExpr;
1940 break;
1941 }
1942#ifndef SQLITE_OMIT_SUBQUERY
1943 case TK_EXISTS:
1944 case TK_SELECT: {
1945 if( pExpr->iColumn==0 ){
1946 sqlite3CodeSubselect(pParse, pExpr);
1947 }
1948 sqlite3VdbeAddOp(v, OP_MemLoad, pExpr->iColumn, 0);
1949 VdbeComment((v, "# load subquery result"));
1950 break;
1951 }
1952 case TK_IN: {
1953 int addr;
1954 char affinity;
1955 int ckOffset = pParse->ckOffset;
1956 sqlite3CodeSubselect(pParse, pExpr);
1957
1958 /* Figure out the affinity to use to create a key from the results
1959 ** of the expression. affinityStr stores a static string suitable for
1960 ** P3 of OP_MakeRecord.
1961 */
1962 affinity = comparisonAffinity(pExpr);
1963
1964 sqlite3VdbeAddOp(v, OP_Integer, 1, 0);
1965 pParse->ckOffset = (ckOffset ? (ckOffset+1) : 0);
1966
1967 /* Code the <expr> from "<expr> IN (...)". The temporary table
1968 ** pExpr->iTable contains the values that make up the (...) set.
1969 */
1970 sqlite3ExprCode(pParse, pExpr->pLeft);
1971 addr = sqlite3VdbeCurrentAddr(v);
1972 sqlite3VdbeAddOp(v, OP_NotNull, -1, addr+4); /* addr + 0 */
1973 sqlite3VdbeAddOp(v, OP_Pop, 2, 0);
1974 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
1975 sqlite3VdbeAddOp(v, OP_Goto, 0, addr+7);
1976 sqlite3VdbeOp3(v, OP_MakeRecord, 1, 0, &affinity, 1); /* addr + 4 */
1977 sqlite3VdbeAddOp(v, OP_Found, pExpr->iTable, addr+7);
1978 sqlite3VdbeAddOp(v, OP_AddImm, -1, 0); /* addr + 6 */
1979
1980 break;
1981 }
1982#endif
1983 case TK_BETWEEN: {
1984 Expr *pLeft = pExpr->pLeft;
1985 struct ExprList_item *pLItem = pExpr->pList->a;
1986 Expr *pRight = pLItem->pExpr;
1987 sqlite3ExprCode(pParse, pLeft);
1988 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
1989 sqlite3ExprCode(pParse, pRight);
1990 codeCompare(pParse, pLeft, pRight, OP_Ge, 0, 0);
1991 sqlite3VdbeAddOp(v, OP_Pull, 1, 0);
1992 pLItem++;
1993 pRight = pLItem->pExpr;
1994 sqlite3ExprCode(pParse, pRight);
1995 codeCompare(pParse, pLeft, pRight, OP_Le, 0, 0);
1996 sqlite3VdbeAddOp(v, OP_And, 0, 0);
1997 break;
1998 }
1999 case TK_UPLUS: {
2000 sqlite3ExprCode(pParse, pExpr->pLeft);
2001 stackChng = 0;
2002 break;
2003 }
2004 case TK_CASE: {
2005 int expr_end_label;
2006 int jumpInst;
2007 int nExpr;
2008 int i;
2009 ExprList *pEList;
2010 struct ExprList_item *aListelem;
2011
2012 assert(pExpr->pList);
2013 assert((pExpr->pList->nExpr % 2) == 0);
2014 assert(pExpr->pList->nExpr > 0);
2015 pEList = pExpr->pList;
2016 aListelem = pEList->a;
2017 nExpr = pEList->nExpr;
2018 expr_end_label = sqlite3VdbeMakeLabel(v);
2019 if( pExpr->pLeft ){
2020 sqlite3ExprCode(pParse, pExpr->pLeft);
2021 }
2022 for(i=0; i<nExpr; i=i+2){
2023 sqlite3ExprCode(pParse, aListelem[i].pExpr);
2024 if( pExpr->pLeft ){
2025 sqlite3VdbeAddOp(v, OP_Dup, 1, 1);
2026 jumpInst = codeCompare(pParse, pExpr->pLeft, aListelem[i].pExpr,
2027 OP_Ne, 0, 1);
2028 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2029 }else{
2030 jumpInst = sqlite3VdbeAddOp(v, OP_IfNot, 1, 0);
2031 }
2032 sqlite3ExprCode(pParse, aListelem[i+1].pExpr);
2033 sqlite3VdbeAddOp(v, OP_Goto, 0, expr_end_label);
2034 sqlite3VdbeJumpHere(v, jumpInst);
2035 }
2036 if( pExpr->pLeft ){
2037 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2038 }
2039 if( pExpr->pRight ){
2040 sqlite3ExprCode(pParse, pExpr->pRight);
2041 }else{
2042 sqlite3VdbeAddOp(v, OP_Null, 0, 0);
2043 }
2044 sqlite3VdbeResolveLabel(v, expr_end_label);
2045 break;
2046 }
2047#ifndef SQLITE_OMIT_TRIGGER
2048 case TK_RAISE: {
2049 if( !pParse->trigStack ){
2050 sqlite3ErrorMsg(pParse,
2051 "RAISE() may only be used within a trigger-program");
2052return;
2053 }
2054 if( pExpr->iColumn!=OE_Ignore ){
2055 assert( pExpr->iColumn==OE_Rollback ||
2056 pExpr->iColumn == OE_Abort ||
2057 pExpr->iColumn == OE_Fail );
2058 sqlite3DequoteExpr(pExpr);
2059 sqlite3VdbeOp3(v, OP_Halt, SQLITE_CONSTRAINT, pExpr->iColumn,
2060 (char*)pExpr->token.z, pExpr->token.n);
2061 } else {
2062 assert( pExpr->iColumn == OE_Ignore );
2063 sqlite3VdbeAddOp(v, OP_ContextPop, 0, 0);
2064 sqlite3VdbeAddOp(v, OP_Goto, 0, pParse->trigStack->ignoreJump);
2065 VdbeComment((v, "# raise(IGNORE)"));
2066 }
2067 stackChng = 0;
2068 break;
2069 }
2070#endif
2071 }
2072
2073 if( pParse->ckOffset ){
2074 pParse->ckOffset += stackChng;
2075 assert( pParse->ckOffset );
2076 }
2077}
2078
2079#ifndef SQLITE_OMIT_TRIGGER
2080/*
2081** Generate code that evalutes the given expression and leaves the result
2082** on the stack. See also sqlite3ExprCode().
2083**
2084** This routine might also cache the result and modify the pExpr tree
2085** so that it will make use of the cached result on subsequent evaluations
2086** rather than evaluate the whole expression again. Trivial expressions are
2087** not cached. If the expression is cached, its result is stored in a
2088** memory location.
2089*/
2090void sqlite3ExprCodeAndCache(Parse *pParse, Expr *pExpr){
2091 Vdbe *v = pParse->pVdbe;
2092 int iMem;
2093 int addr1, addr2;
2094 if( v==0 ) return;
2095 addr1 = sqlite3VdbeCurrentAddr(v);
2096 sqlite3ExprCode(pParse, pExpr);
2097 addr2 = sqlite3VdbeCurrentAddr(v);
2098 if( addr2>addr1+1 || sqlite3VdbeGetOp(v, addr1)->opcode==OP_Function ){
2099 iMem = pExpr->iTable = pParse->nMem++;
2100 sqlite3VdbeAddOp(v, OP_MemStore, iMem, 0);
2101 pExpr->op = TK_REGISTER;
2102 }
2103}
2104#endif
2105
2106/*
2107** Generate code that pushes the value of every element of the given
2108** expression list onto the stack.
2109**
2110** Return the number of elements pushed onto the stack.
2111*/
2112int sqlite3ExprCodeExprList(
2113 Parse *pParse, /* Parsing context */
2114 ExprList *pList /* The expression list to be coded */
2115){
2116 struct ExprList_item *pItem;
2117 int i, n;
2118 if( pList==0 ) return 0;
2119 n = pList->nExpr;
2120 for(pItem=pList->a, i=n; i>0; i--, pItem++){
2121 sqlite3ExprCode(pParse, pItem->pExpr);
2122 }
2123 return n;
2124}
2125
2126/*
2127** Generate code for a boolean expression such that a jump is made
2128** to the label "dest" if the expression is true but execution
2129** continues straight thru if the expression is false.
2130**
2131** If the expression evaluates to NULL (neither true nor false), then
2132** take the jump if the jumpIfNull flag is true.
2133**
2134** This code depends on the fact that certain token values (ex: TK_EQ)
2135** are the same as opcode values (ex: OP_Eq) that implement the corresponding
2136** operation. Special comments in vdbe.c and the mkopcodeh.awk script in
2137** the make process cause these values to align. Assert()s in the code
2138** below verify that the numbers are aligned correctly.
2139*/
2140void sqlite3ExprIfTrue(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2141 Vdbe *v = pParse->pVdbe;
2142 int op = 0;
2143 int ckOffset = pParse->ckOffset;
2144 if( v==0 || pExpr==0 ) return;
2145 op = pExpr->op;
2146 switch( op ){
2147 case TK_AND: {
2148 int d2 = sqlite3VdbeMakeLabel(v);
2149 sqlite3ExprIfFalse(pParse, pExpr->pLeft, d2, !jumpIfNull);
2150 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2151 sqlite3VdbeResolveLabel(v, d2);
2152 break;
2153 }
2154 case TK_OR: {
2155 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2156 sqlite3ExprIfTrue(pParse, pExpr->pRight, dest, jumpIfNull);
2157 break;
2158 }
2159 case TK_NOT: {
2160 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2161 break;
2162 }
2163 case TK_LT:
2164 case TK_LE:
2165 case TK_GT:
2166 case TK_GE:
2167 case TK_NE:
2168 case TK_EQ: {
2169 assert( TK_LT==OP_Lt );
2170 assert( TK_LE==OP_Le );
2171 assert( TK_GT==OP_Gt );
2172 assert( TK_GE==OP_Ge );
2173 assert( TK_EQ==OP_Eq );
2174 assert( TK_NE==OP_Ne );
2175 sqlite3ExprCode(pParse, pExpr->pLeft);
2176 sqlite3ExprCode(pParse, pExpr->pRight);
2177 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2178 break;
2179 }
2180 case TK_ISNULL:
2181 case TK_NOTNULL: {
2182 assert( TK_ISNULL==OP_IsNull );
2183 assert( TK_NOTNULL==OP_NotNull );
2184 sqlite3ExprCode(pParse, pExpr->pLeft);
2185 sqlite3VdbeAddOp(v, op, 1, dest);
2186 break;
2187 }
2188 case TK_BETWEEN: {
2189 /* The expression "x BETWEEN y AND z" is implemented as:
2190 **
2191 ** 1 IF (x < y) GOTO 3
2192 ** 2 IF (x <= z) GOTO <dest>
2193 ** 3 ...
2194 */
2195 int addr;
2196 Expr *pLeft = pExpr->pLeft;
2197 Expr *pRight = pExpr->pList->a[0].pExpr;
2198 sqlite3ExprCode(pParse, pLeft);
2199 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2200 sqlite3ExprCode(pParse, pRight);
2201 addr = codeCompare(pParse, pLeft, pRight, OP_Lt, 0, !jumpIfNull);
2202
2203 pRight = pExpr->pList->a[1].pExpr;
2204 sqlite3ExprCode(pParse, pRight);
2205 codeCompare(pParse, pLeft, pRight, OP_Le, dest, jumpIfNull);
2206
2207 sqlite3VdbeAddOp(v, OP_Integer, 0, 0);
2208 sqlite3VdbeJumpHere(v, addr);
2209 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2210 break;
2211 }
2212 default: {
2213 sqlite3ExprCode(pParse, pExpr);
2214 sqlite3VdbeAddOp(v, OP_If, jumpIfNull, dest);
2215 break;
2216 }
2217 }
2218 pParse->ckOffset = ckOffset;
2219}
2220
2221/*
2222** Generate code for a boolean expression such that a jump is made
2223** to the label "dest" if the expression is false but execution
2224** continues straight thru if the expression is true.
2225**
2226** If the expression evaluates to NULL (neither true nor false) then
2227** jump if jumpIfNull is true or fall through if jumpIfNull is false.
2228*/
2229void sqlite3ExprIfFalse(Parse *pParse, Expr *pExpr, int dest, int jumpIfNull){
2230 Vdbe *v = pParse->pVdbe;
2231 int op = 0;
2232 int ckOffset = pParse->ckOffset;
2233 if( v==0 || pExpr==0 ) return;
2234
2235 /* The value of pExpr->op and op are related as follows:
2236 **
2237 ** pExpr->op op
2238 ** --------- ----------
2239 ** TK_ISNULL OP_NotNull
2240 ** TK_NOTNULL OP_IsNull
2241 ** TK_NE OP_Eq
2242 ** TK_EQ OP_Ne
2243 ** TK_GT OP_Le
2244 ** TK_LE OP_Gt
2245 ** TK_GE OP_Lt
2246 ** TK_LT OP_Ge
2247 **
2248 ** For other values of pExpr->op, op is undefined and unused.
2249 ** The value of TK_ and OP_ constants are arranged such that we
2250 ** can compute the mapping above using the following expression.
2251 ** Assert()s verify that the computation is correct.
2252 */
2253 op = ((pExpr->op+(TK_ISNULL&1))^1)-(TK_ISNULL&1);
2254
2255 /* Verify correct alignment of TK_ and OP_ constants
2256 */
2257 assert( pExpr->op!=TK_ISNULL || op==OP_NotNull );
2258 assert( pExpr->op!=TK_NOTNULL || op==OP_IsNull );
2259 assert( pExpr->op!=TK_NE || op==OP_Eq );
2260 assert( pExpr->op!=TK_EQ || op==OP_Ne );
2261 assert( pExpr->op!=TK_LT || op==OP_Ge );
2262 assert( pExpr->op!=TK_LE || op==OP_Gt );
2263 assert( pExpr->op!=TK_GT || op==OP_Le );
2264 assert( pExpr->op!=TK_GE || op==OP_Lt );
2265
2266 switch( pExpr->op ){
2267 case TK_AND: {
2268 sqlite3ExprIfFalse(pParse, pExpr->pLeft, dest, jumpIfNull);
2269 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2270 break;
2271 }
2272 case TK_OR: {
2273 int d2 = sqlite3VdbeMakeLabel(v);
2274 sqlite3ExprIfTrue(pParse, pExpr->pLeft, d2, !jumpIfNull);
2275 sqlite3ExprIfFalse(pParse, pExpr->pRight, dest, jumpIfNull);
2276 sqlite3VdbeResolveLabel(v, d2);
2277 break;
2278 }
2279 case TK_NOT: {
2280 sqlite3ExprIfTrue(pParse, pExpr->pLeft, dest, jumpIfNull);
2281 break;
2282 }
2283 case TK_LT:
2284 case TK_LE:
2285 case TK_GT:
2286 case TK_GE:
2287 case TK_NE:
2288 case TK_EQ: {
2289 sqlite3ExprCode(pParse, pExpr->pLeft);
2290 sqlite3ExprCode(pParse, pExpr->pRight);
2291 codeCompare(pParse, pExpr->pLeft, pExpr->pRight, op, dest, jumpIfNull);
2292 break;
2293 }
2294 case TK_ISNULL:
2295 case TK_NOTNULL: {
2296 sqlite3ExprCode(pParse, pExpr->pLeft);
2297 sqlite3VdbeAddOp(v, op, 1, dest);
2298 break;
2299 }
2300 case TK_BETWEEN: {
2301 /* The expression is "x BETWEEN y AND z". It is implemented as:
2302 **
2303 ** 1 IF (x >= y) GOTO 3
2304 ** 2 GOTO <dest>
2305 ** 3 IF (x > z) GOTO <dest>
2306 */
2307 int addr;
2308 Expr *pLeft = pExpr->pLeft;
2309 Expr *pRight = pExpr->pList->a[0].pExpr;
2310 sqlite3ExprCode(pParse, pLeft);
2311 sqlite3VdbeAddOp(v, OP_Dup, 0, 0);
2312 sqlite3ExprCode(pParse, pRight);
2313 addr = sqlite3VdbeCurrentAddr(v);
2314 codeCompare(pParse, pLeft, pRight, OP_Ge, addr+3, !jumpIfNull);
2315
2316 sqlite3VdbeAddOp(v, OP_Pop, 1, 0);
2317 sqlite3VdbeAddOp(v, OP_Goto, 0, dest);
2318 pRight = pExpr->pList->a[1].pExpr;
2319 sqlite3ExprCode(pParse, pRight);
2320 codeCompare(pParse, pLeft, pRight, OP_Gt, dest, jumpIfNull);
2321 break;
2322 }
2323 default: {
2324 sqlite3ExprCode(pParse, pExpr);
2325 sqlite3VdbeAddOp(v, OP_IfNot, jumpIfNull, dest);
2326 break;
2327 }
2328 }
2329 pParse->ckOffset = ckOffset;
2330}
2331
2332/*
2333** Do a deep comparison of two expression trees. Return TRUE (non-zero)
2334** if they are identical and return FALSE if they differ in any way.
2335**
2336** Sometimes this routine will return FALSE even if the two expressions
2337** really are equivalent. If we cannot prove that the expressions are
2338** identical, we return FALSE just to be safe. So if this routine
2339** returns false, then you do not really know for certain if the two
2340** expressions are the same. But if you get a TRUE return, then you
2341** can be sure the expressions are the same. In the places where
2342** this routine is used, it does not hurt to get an extra FALSE - that
2343** just might result in some slightly slower code. But returning
2344** an incorrect TRUE could lead to a malfunction.
2345*/
2346int sqlite3ExprCompare(Expr *pA, Expr *pB){
2347 int i;
2348 if( pA==0||pB==0 ){
2349 return pB==pA;
2350 }
2351 if( pA->op!=pB->op ) return 0;
2352 if( (pA->flags & EP_Distinct)!=(pB->flags & EP_Distinct) ) return 0;
2353 if( !sqlite3ExprCompare(pA->pLeft, pB->pLeft) ) return 0;
2354 if( !sqlite3ExprCompare(pA->pRight, pB->pRight) ) return 0;
2355 if( pA->pList ){
2356 if( pB->pList==0 ) return 0;
2357 if( pA->pList->nExpr!=pB->pList->nExpr ) return 0;
2358 for(i=0; i<pA->pList->nExpr; i++){
2359 if( !sqlite3ExprCompare(pA->pList->a[i].pExpr, pB->pList->a[i].pExpr) ){
2360 return 0;
2361 }
2362 }
2363 }else if( pB->pList ){
2364 return 0;
2365 }
2366 if( pA->pSelect || pB->pSelect ) return 0;
2367 if( pA->iTable!=pB->iTable || pA->iColumn!=pB->iColumn ) return 0;
2368 if( pA->op!=TK_COLUMN && pA->token.z ){
2369 if( pB->token.z==0 ) return 0;
2370 if( pB->token.n!=pA->token.n ) return 0;
2371 if( sqlite3StrNICmp((char*)pA->token.z,(char*)pB->token.z,pB->token.n)!=0 ){
2372 return 0;
2373 }
2374 }
2375 return 1;
2376}
2377
2378
2379/*
2380** Add a new element to the pAggInfo->aCol[] array. Return the index of
2381** the new element. Return a negative number if malloc fails.
2382*/
2383static int addAggInfoColumn(AggInfo *pInfo){
2384 int i;
2385 pInfo->aCol = sqlite3ArrayAllocate(
2386 pInfo->aCol,
2387 sizeof(pInfo->aCol[0]),
2388 3,
2389 &pInfo->nColumn,
2390 &pInfo->nColumnAlloc,
2391 &i
2392 );
2393 return i;
2394}
2395
2396/*
2397** Add a new element to the pAggInfo->aFunc[] array. Return the index of
2398** the new element. Return a negative number if malloc fails.
2399*/
2400static int addAggInfoFunc(AggInfo *pInfo){
2401 int i;
2402 pInfo->aFunc = sqlite3ArrayAllocate(
2403 pInfo->aFunc,
2404 sizeof(pInfo->aFunc[0]),
2405 3,
2406 &pInfo->nFunc,
2407 &pInfo->nFuncAlloc,
2408 &i
2409 );
2410 return i;
2411}
2412
2413/*
2414** This is an xFunc for walkExprTree() used to implement
2415** sqlite3ExprAnalyzeAggregates(). See sqlite3ExprAnalyzeAggregates
2416** for additional information.
2417**
2418** This routine analyzes the aggregate function at pExpr.
2419*/
2420static int analyzeAggregate(void *pArg, Expr *pExpr){
2421 int i;
2422 NameContext *pNC = (NameContext *)pArg;
2423 Parse *pParse = pNC->pParse;
2424 SrcList *pSrcList = pNC->pSrcList;
2425 AggInfo *pAggInfo = pNC->pAggInfo;
2426
2427
2428 switch( pExpr->op ){
2429 case TK_AGG_COLUMN:
2430 case TK_COLUMN: {
2431 /* Check to see if the column is in one of the tables in the FROM
2432 ** clause of the aggregate query */
2433 if( pSrcList ){
2434 struct SrcList_item *pItem = pSrcList->a;
2435 for(i=0; i<pSrcList->nSrc; i++, pItem++){
2436 struct AggInfo_col *pCol;
2437 if( pExpr->iTable==pItem->iCursor ){
2438 /* If we reach this point, it means that pExpr refers to a table
2439 ** that is in the FROM clause of the aggregate query.
2440 **
2441 ** Make an entry for the column in pAggInfo->aCol[] if there
2442 ** is not an entry there already.
2443 */
2444 int k;
2445 pCol = pAggInfo->aCol;
2446 for(k=0; k<pAggInfo->nColumn; k++, pCol++){
2447 if( pCol->iTable==pExpr->iTable &&
2448 pCol->iColumn==pExpr->iColumn ){
2449 break;
2450 }
2451 }
2452 if( k>=pAggInfo->nColumn && (k = addAggInfoColumn(pAggInfo))>=0 ){
2453 pCol = &pAggInfo->aCol[k];
2454 pCol->pTab = pExpr->pTab;
2455 pCol->iTable = pExpr->iTable;
2456 pCol->iColumn = pExpr->iColumn;
2457 pCol->iMem = pParse->nMem++;
2458 pCol->iSorterColumn = -1;
2459 pCol->pExpr = pExpr;
2460 if( pAggInfo->pGroupBy ){
2461 int j, n;
2462 ExprList *pGB = pAggInfo->pGroupBy;
2463 struct ExprList_item *pTerm = pGB->a;
2464 n = pGB->nExpr;
2465 for(j=0; j<n; j++, pTerm++){
2466 Expr *pE = pTerm->pExpr;
2467 if( pE->op==TK_COLUMN && pE->iTable==pExpr->iTable &&
2468 pE->iColumn==pExpr->iColumn ){
2469 pCol->iSorterColumn = j;
2470 break;
2471 }
2472 }
2473 }
2474 if( pCol->iSorterColumn<0 ){
2475 pCol->iSorterColumn = pAggInfo->nSortingColumn++;
2476 }
2477 }
2478 /* There is now an entry for pExpr in pAggInfo->aCol[] (either
2479 ** because it was there before or because we just created it).
2480 ** Convert the pExpr to be a TK_AGG_COLUMN referring to that
2481 ** pAggInfo->aCol[] entry.
2482 */
2483 pExpr->pAggInfo = pAggInfo;
2484 pExpr->op = TK_AGG_COLUMN;
2485 pExpr->iAgg = k;
2486 break;
2487 } /* endif pExpr->iTable==pItem->iCursor */
2488 } /* end loop over pSrcList */
2489 }
2490 return 1;
2491 }
2492 case TK_AGG_FUNCTION: {
2493 /* The pNC->nDepth==0 test causes aggregate functions in subqueries
2494 ** to be ignored */
2495 if( pNC->nDepth==0 ){
2496 /* Check to see if pExpr is a duplicate of another aggregate
2497 ** function that is already in the pAggInfo structure
2498 */
2499 struct AggInfo_func *pItem = pAggInfo->aFunc;
2500 for(i=0; i<pAggInfo->nFunc; i++, pItem++){
2501 if( sqlite3ExprCompare(pItem->pExpr, pExpr) ){
2502 break;
2503 }
2504 }
2505 if( i>=pAggInfo->nFunc ){
2506 /* pExpr is original. Make a new entry in pAggInfo->aFunc[]
2507 */
2508 u8 enc = ENC(pParse->db);
2509 i = addAggInfoFunc(pAggInfo);
2510 if( i>=0 ){
2511 pItem = &pAggInfo->aFunc[i];
2512 pItem->pExpr = pExpr;
2513 pItem->iMem = pParse->nMem++;
2514 pItem->pFunc = sqlite3FindFunction(pParse->db,
2515 (char*)pExpr->token.z, pExpr->token.n,
2516 pExpr->pList ? pExpr->pList->nExpr : 0, enc, 0);
2517 if( pExpr->flags & EP_Distinct ){
2518 pItem->iDistinct = pParse->nTab++;
2519 }else{
2520 pItem->iDistinct = -1;
2521 }
2522 }
2523 }
2524 /* Make pExpr point to the appropriate pAggInfo->aFunc[] entry
2525 */
2526 pExpr->iAgg = i;
2527 pExpr->pAggInfo = pAggInfo;
2528 return 1;
2529 }
2530 }
2531 }
2532
2533 /* Recursively walk subqueries looking for TK_COLUMN nodes that need
2534 ** to be changed to TK_AGG_COLUMN. But increment nDepth so that
2535 ** TK_AGG_FUNCTION nodes in subqueries will be unchanged.
2536 */
2537 if( pExpr->pSelect ){
2538 pNC->nDepth++;
2539 walkSelectExpr(pExpr->pSelect, analyzeAggregate, pNC);
2540 pNC->nDepth--;
2541 }
2542 return 0;
2543}
2544
2545/*
2546** Analyze the given expression looking for aggregate functions and
2547** for variables that need to be added to the pParse->aAgg[] array.
2548** Make additional entries to the pParse->aAgg[] array as necessary.
2549**
2550** This routine should only be called after the expression has been
2551** analyzed by sqlite3ExprResolveNames().
2552**
2553** If errors are seen, leave an error message in zErrMsg and return
2554** the number of errors.
2555*/
2556int sqlite3ExprAnalyzeAggregates(NameContext *pNC, Expr *pExpr){
2557 int nErr = pNC->pParse->nErr;
2558 walkExprTree(pExpr, analyzeAggregate, pNC);
2559 return pNC->pParse->nErr - nErr;
2560}
2561
2562/*
2563** Call sqlite3ExprAnalyzeAggregates() for every expression in an
2564** expression list. Return the number of errors.
2565**
2566** If an error is found, the analysis is cut short.
2567*/
2568int sqlite3ExprAnalyzeAggList(NameContext *pNC, ExprList *pList){
2569 struct ExprList_item *pItem;
2570 int i;
2571 int nErr = 0;
2572 if( pList ){
2573 for(pItem=pList->a, i=0; nErr==0 && i<pList->nExpr; i++, pItem++){
2574 nErr += sqlite3ExprAnalyzeAggregates(pNC, pItem->pExpr);
2575 }
2576 }
2577 return nErr;
2578}

Archive Download this file

Branches

Tags

Quick Links:     www.monotone.ca    -     Downloads    -     Documentation    -     Wiki    -     Code Forge    -     Build Status