remove files generated buy build automatically
[sqlcipher.git] / src / resolve.c
blob91efcaa1a16bfc98fb35d85cad156b93533e4e06
1 /*
2 ** 2008 August 18
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.
11 *************************************************************************
13 ** This file contains routines used for walking the parser tree and
14 ** resolve all identifiers by associating them with a particular
15 ** table and column.
17 #include "sqliteInt.h"
18 #include <stdlib.h>
19 #include <string.h>
22 ** Walk the expression tree pExpr and increase the aggregate function
23 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
25 ** outer query into an inner subquery.
27 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
28 ** is a helper function - a callback for the tree walker.
30 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
32 return WRC_Continue;
34 static void incrAggFunctionDepth(Expr *pExpr, int N){
35 if( N>0 ){
36 Walker w;
37 memset(&w, 0, sizeof(w));
38 w.xExprCallback = incrAggDepth;
39 w.u.i = N;
40 sqlite3WalkExpr(&w, pExpr);
45 ** Turn the pExpr expression into an alias for the iCol-th column of the
46 ** result set in pEList.
48 ** If the result set column is a simple column reference, then this routine
49 ** makes an exact copy. But for any other kind of expression, this
50 ** routine make a copy of the result set column as the argument to the
51 ** TK_AS operator. The TK_AS operator causes the expression to be
52 ** evaluated just once and then reused for each alias.
54 ** The reason for suppressing the TK_AS term when the expression is a simple
55 ** column reference is so that the column reference will be recognized as
56 ** usable by indices within the WHERE clause processing logic.
58 ** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
59 ** that in a GROUP BY clause, the expression is evaluated twice. Hence:
61 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
63 ** Is equivalent to:
65 ** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
67 ** The result of random()%5 in the GROUP BY clause is probably different
68 ** from the result in the result-set. We might fix this someday. Or
69 ** then again, we might not...
71 ** If the reference is followed by a COLLATE operator, then make sure
72 ** the COLLATE operator is preserved. For example:
74 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
76 ** Should be transformed into:
78 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
80 ** The nSubquery parameter specifies how many levels of subquery the
81 ** alias is removed from the original expression. The usually value is
82 ** zero but it might be more if the alias is contained within a subquery
83 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
84 ** structures must be increased by the nSubquery amount.
86 static void resolveAlias(
87 Parse *pParse, /* Parsing context */
88 ExprList *pEList, /* A result set */
89 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
90 Expr *pExpr, /* Transform this into an alias to the result set */
91 const char *zType, /* "GROUP" or "ORDER" or "" */
92 int nSubquery /* Number of subqueries that the label is moving */
94 Expr *pOrig; /* The iCol-th column of the result set */
95 Expr *pDup; /* Copy of pOrig */
96 sqlite3 *db; /* The database connection */
98 assert( iCol>=0 && iCol<pEList->nExpr );
99 pOrig = pEList->a[iCol].pExpr;
100 assert( pOrig!=0 );
101 assert( pOrig->flags & EP_Resolved );
102 db = pParse->db;
103 pDup = sqlite3ExprDup(db, pOrig, 0);
104 if( pDup==0 ) return;
105 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
106 incrAggFunctionDepth(pDup, nSubquery);
107 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
108 if( pDup==0 ) return;
109 if( pEList->a[iCol].iAlias==0 ){
110 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
112 pDup->iTable = pEList->a[iCol].iAlias;
114 if( pExpr->op==TK_COLLATE ){
115 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
118 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
119 ** prevents ExprDelete() from deleting the Expr structure itself,
120 ** allowing it to be repopulated by the memcpy() on the following line.
121 ** The pExpr->u.zToken might point into memory that will be freed by the
122 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
123 ** make a copy of the token before doing the sqlite3DbFree().
125 ExprSetProperty(pExpr, EP_Static);
126 sqlite3ExprDelete(db, pExpr);
127 memcpy(pExpr, pDup, sizeof(*pExpr));
128 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
129 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
130 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
131 pExpr->flags2 |= EP2_MallocedToken;
133 sqlite3DbFree(db, pDup);
138 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
140 ** Return FALSE if the USING clause is NULL or if it does not contain
141 ** zCol.
143 static int nameInUsingClause(IdList *pUsing, const char *zCol){
144 if( pUsing ){
145 int k;
146 for(k=0; k<pUsing->nId; k++){
147 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
150 return 0;
154 ** Subqueries stores the original database, table and column names for their
155 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
156 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
157 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
158 ** match anything.
160 int sqlite3MatchSpanName(
161 const char *zSpan,
162 const char *zCol,
163 const char *zTab,
164 const char *zDb
166 int n;
167 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
168 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
169 return 0;
171 zSpan += n+1;
172 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
173 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
174 return 0;
176 zSpan += n+1;
177 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
178 return 0;
180 return 1;
184 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
185 ** that name in the set of source tables in pSrcList and make the pExpr
186 ** expression node refer back to that source column. The following changes
187 ** are made to pExpr:
189 ** pExpr->iDb Set the index in db->aDb[] of the database X
190 ** (even if X is implied).
191 ** pExpr->iTable Set to the cursor number for the table obtained
192 ** from pSrcList.
193 ** pExpr->pTab Points to the Table structure of X.Y (even if
194 ** X and/or Y are implied.)
195 ** pExpr->iColumn Set to the column number within the table.
196 ** pExpr->op Set to TK_COLUMN.
197 ** pExpr->pLeft Any expression this points to is deleted
198 ** pExpr->pRight Any expression this points to is deleted.
200 ** The zDb variable is the name of the database (the "X"). This value may be
201 ** NULL meaning that name is of the form Y.Z or Z. Any available database
202 ** can be used. The zTable variable is the name of the table (the "Y"). This
203 ** value can be NULL if zDb is also NULL. If zTable is NULL it
204 ** means that the form of the name is Z and that columns from any table
205 ** can be used.
207 ** If the name cannot be resolved unambiguously, leave an error message
208 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
210 static int lookupName(
211 Parse *pParse, /* The parsing context */
212 const char *zDb, /* Name of the database containing table, or NULL */
213 const char *zTab, /* Name of table containing column, or NULL */
214 const char *zCol, /* Name of the column. */
215 NameContext *pNC, /* The name context used to resolve the name */
216 Expr *pExpr /* Make this EXPR node point to the selected column */
218 int i, j; /* Loop counters */
219 int cnt = 0; /* Number of matching column names */
220 int cntTab = 0; /* Number of matching table names */
221 int nSubquery = 0; /* How many levels of subquery */
222 sqlite3 *db = pParse->db; /* The database connection */
223 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
224 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
225 NameContext *pTopNC = pNC; /* First namecontext in the list */
226 Schema *pSchema = 0; /* Schema of the expression */
227 int isTrigger = 0;
229 assert( pNC ); /* the name context cannot be NULL. */
230 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
231 assert( !ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
233 /* Initialize the node to no-match */
234 pExpr->iTable = -1;
235 pExpr->pTab = 0;
236 ExprSetIrreducible(pExpr);
238 /* Translate the schema name in zDb into a pointer to the corresponding
239 ** schema. If not found, pSchema will remain NULL and nothing will match
240 ** resulting in an appropriate error message toward the end of this routine
242 if( zDb ){
243 for(i=0; i<db->nDb; i++){
244 assert( db->aDb[i].zName );
245 if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
246 pSchema = db->aDb[i].pSchema;
247 break;
252 /* Start at the inner-most context and move outward until a match is found */
253 while( pNC && cnt==0 ){
254 ExprList *pEList;
255 SrcList *pSrcList = pNC->pSrcList;
257 if( pSrcList ){
258 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
259 Table *pTab;
260 Column *pCol;
262 pTab = pItem->pTab;
263 assert( pTab!=0 && pTab->zName!=0 );
264 assert( pTab->nCol>0 );
265 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
266 int hit = 0;
267 pEList = pItem->pSelect->pEList;
268 for(j=0; j<pEList->nExpr; j++){
269 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
270 cnt++;
271 cntTab = 2;
272 pMatch = pItem;
273 pExpr->iColumn = j;
274 hit = 1;
277 if( hit || zTab==0 ) continue;
279 if( zDb && pTab->pSchema!=pSchema ){
280 continue;
282 if( zTab ){
283 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
284 assert( zTabName!=0 );
285 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
286 continue;
289 if( 0==(cntTab++) ){
290 pMatch = pItem;
292 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
293 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
294 /* If there has been exactly one prior match and this match
295 ** is for the right-hand table of a NATURAL JOIN or is in a
296 ** USING clause, then skip this match.
298 if( cnt==1 ){
299 if( pItem->jointype & JT_NATURAL ) continue;
300 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
302 cnt++;
303 pMatch = pItem;
304 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
305 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
306 break;
310 if( pMatch ){
311 pExpr->iTable = pMatch->iCursor;
312 pExpr->pTab = pMatch->pTab;
313 pSchema = pExpr->pTab->pSchema;
315 } /* if( pSrcList ) */
317 #ifndef SQLITE_OMIT_TRIGGER
318 /* If we have not already resolved the name, then maybe
319 ** it is a new.* or old.* trigger argument reference
321 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
322 int op = pParse->eTriggerOp;
323 Table *pTab = 0;
324 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
325 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
326 pExpr->iTable = 1;
327 pTab = pParse->pTriggerTab;
328 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
329 pExpr->iTable = 0;
330 pTab = pParse->pTriggerTab;
333 if( pTab ){
334 int iCol;
335 pSchema = pTab->pSchema;
336 cntTab++;
337 for(iCol=0; iCol<pTab->nCol; iCol++){
338 Column *pCol = &pTab->aCol[iCol];
339 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
340 if( iCol==pTab->iPKey ){
341 iCol = -1;
343 break;
346 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
347 iCol = -1; /* IMP: R-44911-55124 */
349 if( iCol<pTab->nCol ){
350 cnt++;
351 if( iCol<0 ){
352 pExpr->affinity = SQLITE_AFF_INTEGER;
353 }else if( pExpr->iTable==0 ){
354 testcase( iCol==31 );
355 testcase( iCol==32 );
356 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
357 }else{
358 testcase( iCol==31 );
359 testcase( iCol==32 );
360 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
362 pExpr->iColumn = (i16)iCol;
363 pExpr->pTab = pTab;
364 isTrigger = 1;
368 #endif /* !defined(SQLITE_OMIT_TRIGGER) */
371 ** Perhaps the name is a reference to the ROWID
373 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
374 cnt = 1;
375 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
376 pExpr->affinity = SQLITE_AFF_INTEGER;
380 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
381 ** might refer to an result-set alias. This happens, for example, when
382 ** we are resolving names in the WHERE clause of the following command:
384 ** SELECT a+b AS x FROM table WHERE x<10;
386 ** In cases like this, replace pExpr with a copy of the expression that
387 ** forms the result set entry ("a+b" in the example) and return immediately.
388 ** Note that the expression in the result set should have already been
389 ** resolved by the time the WHERE clause is resolved.
391 if( (pEList = pNC->pEList)!=0
392 && zTab==0
393 && ((pNC->ncFlags & NC_AsMaybe)==0 || cnt==0)
395 for(j=0; j<pEList->nExpr; j++){
396 char *zAs = pEList->a[j].zName;
397 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
398 Expr *pOrig;
399 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
400 assert( pExpr->x.pList==0 );
401 assert( pExpr->x.pSelect==0 );
402 pOrig = pEList->a[j].pExpr;
403 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
404 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
405 return WRC_Abort;
407 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
408 cnt = 1;
409 pMatch = 0;
410 assert( zTab==0 && zDb==0 );
411 goto lookupname_end;
416 /* Advance to the next name context. The loop will exit when either
417 ** we have a match (cnt>0) or when we run out of name contexts.
419 if( cnt==0 ){
420 pNC = pNC->pNext;
421 nSubquery++;
426 ** If X and Y are NULL (in other words if only the column name Z is
427 ** supplied) and the value of Z is enclosed in double-quotes, then
428 ** Z is a string literal if it doesn't match any column names. In that
429 ** case, we need to return right away and not make any changes to
430 ** pExpr.
432 ** Because no reference was made to outer contexts, the pNC->nRef
433 ** fields are not changed in any context.
435 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
436 pExpr->op = TK_STRING;
437 pExpr->pTab = 0;
438 return WRC_Prune;
442 ** cnt==0 means there was not match. cnt>1 means there were two or
443 ** more matches. Either way, we have an error.
445 if( cnt!=1 ){
446 const char *zErr;
447 zErr = cnt==0 ? "no such column" : "ambiguous column name";
448 if( zDb ){
449 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
450 }else if( zTab ){
451 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
452 }else{
453 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
455 pParse->checkSchema = 1;
456 pTopNC->nErr++;
459 /* If a column from a table in pSrcList is referenced, then record
460 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
461 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
462 ** column number is greater than the number of bits in the bitmask
463 ** then set the high-order bit of the bitmask.
465 if( pExpr->iColumn>=0 && pMatch!=0 ){
466 int n = pExpr->iColumn;
467 testcase( n==BMS-1 );
468 if( n>=BMS ){
469 n = BMS-1;
471 assert( pMatch->iCursor==pExpr->iTable );
472 pMatch->colUsed |= ((Bitmask)1)<<n;
475 /* Clean up and return
477 sqlite3ExprDelete(db, pExpr->pLeft);
478 pExpr->pLeft = 0;
479 sqlite3ExprDelete(db, pExpr->pRight);
480 pExpr->pRight = 0;
481 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
482 lookupname_end:
483 if( cnt==1 ){
484 assert( pNC!=0 );
485 if( pExpr->op!=TK_AS ){
486 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
488 /* Increment the nRef value on all name contexts from TopNC up to
489 ** the point where the name matched. */
490 for(;;){
491 assert( pTopNC!=0 );
492 pTopNC->nRef++;
493 if( pTopNC==pNC ) break;
494 pTopNC = pTopNC->pNext;
496 return WRC_Prune;
497 } else {
498 return WRC_Abort;
503 ** Allocate and return a pointer to an expression to load the column iCol
504 ** from datasource iSrc in SrcList pSrc.
506 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
507 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
508 if( p ){
509 struct SrcList_item *pItem = &pSrc->a[iSrc];
510 p->pTab = pItem->pTab;
511 p->iTable = pItem->iCursor;
512 if( p->pTab->iPKey==iCol ){
513 p->iColumn = -1;
514 }else{
515 p->iColumn = (ynVar)iCol;
516 testcase( iCol==BMS );
517 testcase( iCol==BMS-1 );
518 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
520 ExprSetProperty(p, EP_Resolved);
522 return p;
526 ** This routine is callback for sqlite3WalkExpr().
528 ** Resolve symbolic names into TK_COLUMN operators for the current
529 ** node in the expression tree. Return 0 to continue the search down
530 ** the tree or 2 to abort the tree walk.
532 ** This routine also does error checking and name resolution for
533 ** function names. The operator for aggregate functions is changed
534 ** to TK_AGG_FUNCTION.
536 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
537 NameContext *pNC;
538 Parse *pParse;
540 pNC = pWalker->u.pNC;
541 assert( pNC!=0 );
542 pParse = pNC->pParse;
543 assert( pParse==pWalker->pParse );
545 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
546 ExprSetProperty(pExpr, EP_Resolved);
547 #ifndef NDEBUG
548 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
549 SrcList *pSrcList = pNC->pSrcList;
550 int i;
551 for(i=0; i<pNC->pSrcList->nSrc; i++){
552 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
555 #endif
556 switch( pExpr->op ){
558 #if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
559 /* The special operator TK_ROW means use the rowid for the first
560 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
561 ** clause processing on UPDATE and DELETE statements.
563 case TK_ROW: {
564 SrcList *pSrcList = pNC->pSrcList;
565 struct SrcList_item *pItem;
566 assert( pSrcList && pSrcList->nSrc==1 );
567 pItem = pSrcList->a;
568 pExpr->op = TK_COLUMN;
569 pExpr->pTab = pItem->pTab;
570 pExpr->iTable = pItem->iCursor;
571 pExpr->iColumn = -1;
572 pExpr->affinity = SQLITE_AFF_INTEGER;
573 break;
575 #endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
577 /* A lone identifier is the name of a column.
579 case TK_ID: {
580 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
583 /* A table name and column name: ID.ID
584 ** Or a database, table and column: ID.ID.ID
586 case TK_DOT: {
587 const char *zColumn;
588 const char *zTable;
589 const char *zDb;
590 Expr *pRight;
592 /* if( pSrcList==0 ) break; */
593 pRight = pExpr->pRight;
594 if( pRight->op==TK_ID ){
595 zDb = 0;
596 zTable = pExpr->pLeft->u.zToken;
597 zColumn = pRight->u.zToken;
598 }else{
599 assert( pRight->op==TK_DOT );
600 zDb = pExpr->pLeft->u.zToken;
601 zTable = pRight->pLeft->u.zToken;
602 zColumn = pRight->pRight->u.zToken;
604 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
607 /* Resolve function names
609 case TK_CONST_FUNC:
610 case TK_FUNCTION: {
611 ExprList *pList = pExpr->x.pList; /* The argument list */
612 int n = pList ? pList->nExpr : 0; /* Number of arguments */
613 int no_such_func = 0; /* True if no such function exists */
614 int wrong_num_args = 0; /* True if wrong number of arguments */
615 int is_agg = 0; /* True if is an aggregate function */
616 int auth; /* Authorization to use the function */
617 int nId; /* Number of characters in function name */
618 const char *zId; /* The function name. */
619 FuncDef *pDef; /* Information about the function */
620 u8 enc = ENC(pParse->db); /* The database encoding */
622 testcase( pExpr->op==TK_CONST_FUNC );
623 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
624 zId = pExpr->u.zToken;
625 nId = sqlite3Strlen30(zId);
626 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
627 if( pDef==0 ){
628 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
629 if( pDef==0 ){
630 no_such_func = 1;
631 }else{
632 wrong_num_args = 1;
634 }else{
635 is_agg = pDef->xFunc==0;
637 #ifndef SQLITE_OMIT_AUTHORIZATION
638 if( pDef ){
639 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
640 if( auth!=SQLITE_OK ){
641 if( auth==SQLITE_DENY ){
642 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
643 pDef->zName);
644 pNC->nErr++;
646 pExpr->op = TK_NULL;
647 return WRC_Prune;
650 #endif
651 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
652 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
653 pNC->nErr++;
654 is_agg = 0;
655 }else if( no_such_func && pParse->db->init.busy==0 ){
656 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
657 pNC->nErr++;
658 }else if( wrong_num_args ){
659 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
660 nId, zId);
661 pNC->nErr++;
663 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
664 sqlite3WalkExprList(pWalker, pList);
665 if( is_agg ){
666 NameContext *pNC2 = pNC;
667 pExpr->op = TK_AGG_FUNCTION;
668 pExpr->op2 = 0;
669 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
670 pExpr->op2++;
671 pNC2 = pNC2->pNext;
673 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
674 pNC->ncFlags |= NC_AllowAgg;
676 /* FIX ME: Compute pExpr->affinity based on the expected return
677 ** type of the function
679 return WRC_Prune;
681 #ifndef SQLITE_OMIT_SUBQUERY
682 case TK_SELECT:
683 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
684 #endif
685 case TK_IN: {
686 testcase( pExpr->op==TK_IN );
687 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
688 int nRef = pNC->nRef;
689 #ifndef SQLITE_OMIT_CHECK
690 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
691 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
693 #endif
694 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
695 assert( pNC->nRef>=nRef );
696 if( nRef!=pNC->nRef ){
697 ExprSetProperty(pExpr, EP_VarSelect);
700 break;
702 #ifndef SQLITE_OMIT_CHECK
703 case TK_VARIABLE: {
704 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
705 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
707 break;
709 #endif
711 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
715 ** pEList is a list of expressions which are really the result set of the
716 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
717 ** This routine checks to see if pE is a simple identifier which corresponds
718 ** to the AS-name of one of the terms of the expression list. If it is,
719 ** this routine return an integer between 1 and N where N is the number of
720 ** elements in pEList, corresponding to the matching entry. If there is
721 ** no match, or if pE is not a simple identifier, then this routine
722 ** return 0.
724 ** pEList has been resolved. pE has not.
726 static int resolveAsName(
727 Parse *pParse, /* Parsing context for error messages */
728 ExprList *pEList, /* List of expressions to scan */
729 Expr *pE /* Expression we are trying to match */
731 int i; /* Loop counter */
733 UNUSED_PARAMETER(pParse);
735 if( pE->op==TK_ID ){
736 char *zCol = pE->u.zToken;
737 for(i=0; i<pEList->nExpr; i++){
738 char *zAs = pEList->a[i].zName;
739 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
740 return i+1;
744 return 0;
748 ** pE is a pointer to an expression which is a single term in the
749 ** ORDER BY of a compound SELECT. The expression has not been
750 ** name resolved.
752 ** At the point this routine is called, we already know that the
753 ** ORDER BY term is not an integer index into the result set. That
754 ** case is handled by the calling routine.
756 ** Attempt to match pE against result set columns in the left-most
757 ** SELECT statement. Return the index i of the matching column,
758 ** as an indication to the caller that it should sort by the i-th column.
759 ** The left-most column is 1. In other words, the value returned is the
760 ** same integer value that would be used in the SQL statement to indicate
761 ** the column.
763 ** If there is no match, return 0. Return -1 if an error occurs.
765 static int resolveOrderByTermToExprList(
766 Parse *pParse, /* Parsing context for error messages */
767 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
768 Expr *pE /* The specific ORDER BY term */
770 int i; /* Loop counter */
771 ExprList *pEList; /* The columns of the result set */
772 NameContext nc; /* Name context for resolving pE */
773 sqlite3 *db; /* Database connection */
774 int rc; /* Return code from subprocedures */
775 u8 savedSuppErr; /* Saved value of db->suppressErr */
777 assert( sqlite3ExprIsInteger(pE, &i)==0 );
778 pEList = pSelect->pEList;
780 /* Resolve all names in the ORDER BY term expression
782 memset(&nc, 0, sizeof(nc));
783 nc.pParse = pParse;
784 nc.pSrcList = pSelect->pSrc;
785 nc.pEList = pEList;
786 nc.ncFlags = NC_AllowAgg;
787 nc.nErr = 0;
788 db = pParse->db;
789 savedSuppErr = db->suppressErr;
790 db->suppressErr = 1;
791 rc = sqlite3ResolveExprNames(&nc, pE);
792 db->suppressErr = savedSuppErr;
793 if( rc ) return 0;
795 /* Try to match the ORDER BY expression against an expression
796 ** in the result set. Return an 1-based index of the matching
797 ** result-set entry.
799 for(i=0; i<pEList->nExpr; i++){
800 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE)<2 ){
801 return i+1;
805 /* If no match, return 0. */
806 return 0;
810 ** Generate an ORDER BY or GROUP BY term out-of-range error.
812 static void resolveOutOfRangeError(
813 Parse *pParse, /* The error context into which to write the error */
814 const char *zType, /* "ORDER" or "GROUP" */
815 int i, /* The index (1-based) of the term out of range */
816 int mx /* Largest permissible value of i */
818 sqlite3ErrorMsg(pParse,
819 "%r %s BY term out of range - should be "
820 "between 1 and %d", i, zType, mx);
824 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
825 ** each term of the ORDER BY clause is a constant integer between 1
826 ** and N where N is the number of columns in the compound SELECT.
828 ** ORDER BY terms that are already an integer between 1 and N are
829 ** unmodified. ORDER BY terms that are integers outside the range of
830 ** 1 through N generate an error. ORDER BY terms that are expressions
831 ** are matched against result set expressions of compound SELECT
832 ** beginning with the left-most SELECT and working toward the right.
833 ** At the first match, the ORDER BY expression is transformed into
834 ** the integer column number.
836 ** Return the number of errors seen.
838 static int resolveCompoundOrderBy(
839 Parse *pParse, /* Parsing context. Leave error messages here */
840 Select *pSelect /* The SELECT statement containing the ORDER BY */
842 int i;
843 ExprList *pOrderBy;
844 ExprList *pEList;
845 sqlite3 *db;
846 int moreToDo = 1;
848 pOrderBy = pSelect->pOrderBy;
849 if( pOrderBy==0 ) return 0;
850 db = pParse->db;
851 #if SQLITE_MAX_COLUMN
852 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
853 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
854 return 1;
856 #endif
857 for(i=0; i<pOrderBy->nExpr; i++){
858 pOrderBy->a[i].done = 0;
860 pSelect->pNext = 0;
861 while( pSelect->pPrior ){
862 pSelect->pPrior->pNext = pSelect;
863 pSelect = pSelect->pPrior;
865 while( pSelect && moreToDo ){
866 struct ExprList_item *pItem;
867 moreToDo = 0;
868 pEList = pSelect->pEList;
869 assert( pEList!=0 );
870 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
871 int iCol = -1;
872 Expr *pE, *pDup;
873 if( pItem->done ) continue;
874 pE = sqlite3ExprSkipCollate(pItem->pExpr);
875 if( sqlite3ExprIsInteger(pE, &iCol) ){
876 if( iCol<=0 || iCol>pEList->nExpr ){
877 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
878 return 1;
880 }else{
881 iCol = resolveAsName(pParse, pEList, pE);
882 if( iCol==0 ){
883 pDup = sqlite3ExprDup(db, pE, 0);
884 if( !db->mallocFailed ){
885 assert(pDup);
886 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
888 sqlite3ExprDelete(db, pDup);
891 if( iCol>0 ){
892 /* Convert the ORDER BY term into an integer column number iCol,
893 ** taking care to preserve the COLLATE clause if it exists */
894 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
895 if( pNew==0 ) return 1;
896 pNew->flags |= EP_IntValue;
897 pNew->u.iValue = iCol;
898 if( pItem->pExpr==pE ){
899 pItem->pExpr = pNew;
900 }else{
901 assert( pItem->pExpr->op==TK_COLLATE );
902 assert( pItem->pExpr->pLeft==pE );
903 pItem->pExpr->pLeft = pNew;
905 sqlite3ExprDelete(db, pE);
906 pItem->iOrderByCol = (u16)iCol;
907 pItem->done = 1;
908 }else{
909 moreToDo = 1;
912 pSelect = pSelect->pNext;
914 for(i=0; i<pOrderBy->nExpr; i++){
915 if( pOrderBy->a[i].done==0 ){
916 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
917 "column in the result set", i+1);
918 return 1;
921 return 0;
925 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
926 ** the SELECT statement pSelect. If any term is reference to a
927 ** result set expression (as determined by the ExprList.a.iCol field)
928 ** then convert that term into a copy of the corresponding result set
929 ** column.
931 ** If any errors are detected, add an error message to pParse and
932 ** return non-zero. Return zero if no errors are seen.
934 int sqlite3ResolveOrderGroupBy(
935 Parse *pParse, /* Parsing context. Leave error messages here */
936 Select *pSelect, /* The SELECT statement containing the clause */
937 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
938 const char *zType /* "ORDER" or "GROUP" */
940 int i;
941 sqlite3 *db = pParse->db;
942 ExprList *pEList;
943 struct ExprList_item *pItem;
945 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
946 #if SQLITE_MAX_COLUMN
947 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
948 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
949 return 1;
951 #endif
952 pEList = pSelect->pEList;
953 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
954 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
955 if( pItem->iOrderByCol ){
956 if( pItem->iOrderByCol>pEList->nExpr ){
957 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
958 return 1;
960 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
963 return 0;
967 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
968 ** The Name context of the SELECT statement is pNC. zType is either
969 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
971 ** This routine resolves each term of the clause into an expression.
972 ** If the order-by term is an integer I between 1 and N (where N is the
973 ** number of columns in the result set of the SELECT) then the expression
974 ** in the resolution is a copy of the I-th result-set expression. If
975 ** the order-by term is an identify that corresponds to the AS-name of
976 ** a result-set expression, then the term resolves to a copy of the
977 ** result-set expression. Otherwise, the expression is resolved in
978 ** the usual way - using sqlite3ResolveExprNames().
980 ** This routine returns the number of errors. If errors occur, then
981 ** an appropriate error message might be left in pParse. (OOM errors
982 ** excepted.)
984 static int resolveOrderGroupBy(
985 NameContext *pNC, /* The name context of the SELECT statement */
986 Select *pSelect, /* The SELECT statement holding pOrderBy */
987 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
988 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
990 int i, j; /* Loop counters */
991 int iCol; /* Column number */
992 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
993 Parse *pParse; /* Parsing context */
994 int nResult; /* Number of terms in the result set */
996 if( pOrderBy==0 ) return 0;
997 nResult = pSelect->pEList->nExpr;
998 pParse = pNC->pParse;
999 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1000 Expr *pE = pItem->pExpr;
1001 iCol = resolveAsName(pParse, pSelect->pEList, pE);
1002 if( iCol>0 ){
1003 /* If an AS-name match is found, mark this ORDER BY column as being
1004 ** a copy of the iCol-th result-set column. The subsequent call to
1005 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1006 ** copy of the iCol-th result-set expression. */
1007 pItem->iOrderByCol = (u16)iCol;
1008 continue;
1010 if( sqlite3ExprIsInteger(sqlite3ExprSkipCollate(pE), &iCol) ){
1011 /* The ORDER BY term is an integer constant. Again, set the column
1012 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1013 ** order-by term to a copy of the result-set expression */
1014 if( iCol<1 || iCol>0xffff ){
1015 resolveOutOfRangeError(pParse, zType, i+1, nResult);
1016 return 1;
1018 pItem->iOrderByCol = (u16)iCol;
1019 continue;
1022 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1023 pItem->iOrderByCol = 0;
1024 if( sqlite3ResolveExprNames(pNC, pE) ){
1025 return 1;
1027 for(j=0; j<pSelect->pEList->nExpr; j++){
1028 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr)==0 ){
1029 pItem->iOrderByCol = j+1;
1033 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1037 ** Resolve names in the SELECT statement p and all of its descendents.
1039 static int resolveSelectStep(Walker *pWalker, Select *p){
1040 NameContext *pOuterNC; /* Context that contains this SELECT */
1041 NameContext sNC; /* Name context of this SELECT */
1042 int isCompound; /* True if p is a compound select */
1043 int nCompound; /* Number of compound terms processed so far */
1044 Parse *pParse; /* Parsing context */
1045 ExprList *pEList; /* Result set expression list */
1046 int i; /* Loop counter */
1047 ExprList *pGroupBy; /* The GROUP BY clause */
1048 Select *pLeftmost; /* Left-most of SELECT of a compound */
1049 sqlite3 *db; /* Database connection */
1052 assert( p!=0 );
1053 if( p->selFlags & SF_Resolved ){
1054 return WRC_Prune;
1056 pOuterNC = pWalker->u.pNC;
1057 pParse = pWalker->pParse;
1058 db = pParse->db;
1060 /* Normally sqlite3SelectExpand() will be called first and will have
1061 ** already expanded this SELECT. However, if this is a subquery within
1062 ** an expression, sqlite3ResolveExprNames() will be called without a
1063 ** prior call to sqlite3SelectExpand(). When that happens, let
1064 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1065 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1066 ** this routine in the correct order.
1068 if( (p->selFlags & SF_Expanded)==0 ){
1069 sqlite3SelectPrep(pParse, p, pOuterNC);
1070 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1073 isCompound = p->pPrior!=0;
1074 nCompound = 0;
1075 pLeftmost = p;
1076 while( p ){
1077 assert( (p->selFlags & SF_Expanded)!=0 );
1078 assert( (p->selFlags & SF_Resolved)==0 );
1079 p->selFlags |= SF_Resolved;
1081 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1082 ** are not allowed to refer to any names, so pass an empty NameContext.
1084 memset(&sNC, 0, sizeof(sNC));
1085 sNC.pParse = pParse;
1086 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1087 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1088 return WRC_Abort;
1091 /* Recursively resolve names in all subqueries
1093 for(i=0; i<p->pSrc->nSrc; i++){
1094 struct SrcList_item *pItem = &p->pSrc->a[i];
1095 if( pItem->pSelect ){
1096 NameContext *pNC; /* Used to iterate name contexts */
1097 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
1098 const char *zSavedContext = pParse->zAuthContext;
1100 /* Count the total number of references to pOuterNC and all of its
1101 ** parent contexts. After resolving references to expressions in
1102 ** pItem->pSelect, check if this value has changed. If so, then
1103 ** SELECT statement pItem->pSelect must be correlated. Set the
1104 ** pItem->isCorrelated flag if this is the case. */
1105 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1107 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1108 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1109 pParse->zAuthContext = zSavedContext;
1110 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
1112 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1113 assert( pItem->isCorrelated==0 && nRef<=0 );
1114 pItem->isCorrelated = (nRef!=0);
1118 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1119 ** resolve the result-set expression list.
1121 sNC.ncFlags = NC_AllowAgg;
1122 sNC.pSrcList = p->pSrc;
1123 sNC.pNext = pOuterNC;
1125 /* Resolve names in the result set. */
1126 pEList = p->pEList;
1127 assert( pEList!=0 );
1128 for(i=0; i<pEList->nExpr; i++){
1129 Expr *pX = pEList->a[i].pExpr;
1130 if( sqlite3ResolveExprNames(&sNC, pX) ){
1131 return WRC_Abort;
1135 /* If there are no aggregate functions in the result-set, and no GROUP BY
1136 ** expression, do not allow aggregates in any of the other expressions.
1138 assert( (p->selFlags & SF_Aggregate)==0 );
1139 pGroupBy = p->pGroupBy;
1140 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1141 p->selFlags |= SF_Aggregate;
1142 }else{
1143 sNC.ncFlags &= ~NC_AllowAgg;
1146 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1148 if( p->pHaving && !pGroupBy ){
1149 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1150 return WRC_Abort;
1153 /* Add the expression list to the name-context before parsing the
1154 ** other expressions in the SELECT statement. This is so that
1155 ** expressions in the WHERE clause (etc.) can refer to expressions by
1156 ** aliases in the result set.
1158 ** Minor point: If this is the case, then the expression will be
1159 ** re-evaluated for each reference to it.
1161 sNC.pEList = p->pEList;
1162 sNC.ncFlags |= NC_AsMaybe;
1163 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1164 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1165 sNC.ncFlags &= ~NC_AsMaybe;
1167 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1168 ** outer queries
1170 sNC.pNext = 0;
1171 sNC.ncFlags |= NC_AllowAgg;
1173 /* Process the ORDER BY clause for singleton SELECT statements.
1174 ** The ORDER BY clause for compounds SELECT statements is handled
1175 ** below, after all of the result-sets for all of the elements of
1176 ** the compound have been resolved.
1178 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1179 return WRC_Abort;
1181 if( db->mallocFailed ){
1182 return WRC_Abort;
1185 /* Resolve the GROUP BY clause. At the same time, make sure
1186 ** the GROUP BY clause does not contain aggregate functions.
1188 if( pGroupBy ){
1189 struct ExprList_item *pItem;
1191 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1192 return WRC_Abort;
1194 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1195 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1196 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1197 "the GROUP BY clause");
1198 return WRC_Abort;
1203 /* Advance to the next term of the compound
1205 p = p->pPrior;
1206 nCompound++;
1209 /* Resolve the ORDER BY on a compound SELECT after all terms of
1210 ** the compound have been resolved.
1212 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1213 return WRC_Abort;
1216 return WRC_Prune;
1220 ** This routine walks an expression tree and resolves references to
1221 ** table columns and result-set columns. At the same time, do error
1222 ** checking on function usage and set a flag if any aggregate functions
1223 ** are seen.
1225 ** To resolve table columns references we look for nodes (or subtrees) of the
1226 ** form X.Y.Z or Y.Z or just Z where
1228 ** X: The name of a database. Ex: "main" or "temp" or
1229 ** the symbolic name assigned to an ATTACH-ed database.
1231 ** Y: The name of a table in a FROM clause. Or in a trigger
1232 ** one of the special names "old" or "new".
1234 ** Z: The name of a column in table Y.
1236 ** The node at the root of the subtree is modified as follows:
1238 ** Expr.op Changed to TK_COLUMN
1239 ** Expr.pTab Points to the Table object for X.Y
1240 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
1241 ** Expr.iTable The VDBE cursor number for X.Y
1244 ** To resolve result-set references, look for expression nodes of the
1245 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1246 ** size of an AS clause in the result-set of a SELECT. The Z expression
1247 ** is replaced by a copy of the left-hand side of the result-set expression.
1248 ** Table-name and function resolution occurs on the substituted expression
1249 ** tree. For example, in:
1251 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1253 ** The "x" term of the order by is replaced by "a+b" to render:
1255 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1257 ** Function calls are checked to make sure that the function is
1258 ** defined and that the correct number of arguments are specified.
1259 ** If the function is an aggregate function, then the NC_HasAgg flag is
1260 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1261 ** If an expression contains aggregate functions then the EP_Agg
1262 ** property on the expression is set.
1264 ** An error message is left in pParse if anything is amiss. The number
1265 ** if errors is returned.
1267 int sqlite3ResolveExprNames(
1268 NameContext *pNC, /* Namespace to resolve expressions in. */
1269 Expr *pExpr /* The expression to be analyzed. */
1271 u8 savedHasAgg;
1272 Walker w;
1274 if( pExpr==0 ) return 0;
1275 #if SQLITE_MAX_EXPR_DEPTH>0
1277 Parse *pParse = pNC->pParse;
1278 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1279 return 1;
1281 pParse->nHeight += pExpr->nHeight;
1283 #endif
1284 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1285 pNC->ncFlags &= ~NC_HasAgg;
1286 memset(&w, 0, sizeof(w));
1287 w.xExprCallback = resolveExprStep;
1288 w.xSelectCallback = resolveSelectStep;
1289 w.pParse = pNC->pParse;
1290 w.u.pNC = pNC;
1291 sqlite3WalkExpr(&w, pExpr);
1292 #if SQLITE_MAX_EXPR_DEPTH>0
1293 pNC->pParse->nHeight -= pExpr->nHeight;
1294 #endif
1295 if( pNC->nErr>0 || w.pParse->nErr>0 ){
1296 ExprSetProperty(pExpr, EP_Error);
1298 if( pNC->ncFlags & NC_HasAgg ){
1299 ExprSetProperty(pExpr, EP_Agg);
1300 }else if( savedHasAgg ){
1301 pNC->ncFlags |= NC_HasAgg;
1303 return ExprHasProperty(pExpr, EP_Error);
1308 ** Resolve all names in all expressions of a SELECT and in all
1309 ** decendents of the SELECT, including compounds off of p->pPrior,
1310 ** subqueries in expressions, and subqueries used as FROM clause
1311 ** terms.
1313 ** See sqlite3ResolveExprNames() for a description of the kinds of
1314 ** transformations that occur.
1316 ** All SELECT statements should have been expanded using
1317 ** sqlite3SelectExpand() prior to invoking this routine.
1319 void sqlite3ResolveSelectNames(
1320 Parse *pParse, /* The parser context */
1321 Select *p, /* The SELECT statement being coded. */
1322 NameContext *pOuterNC /* Name context for parent SELECT statement */
1324 Walker w;
1326 assert( p!=0 );
1327 memset(&w, 0, sizeof(w));
1328 w.xExprCallback = resolveExprStep;
1329 w.xSelectCallback = resolveSelectStep;
1330 w.pParse = pParse;
1331 w.u.pNC = pOuterNC;
1332 sqlite3WalkSelect(&w, p);