blob: 55a47ca4447b95835a902d237bb6c1133631e4d8 [file] [log] [blame]
drh7d10d5a2008-08-20 16:35:10 +00001/*
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.
10**
11*************************************************************************
12**
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.
16**
drhfd773cf2009-05-29 14:39:07 +000017** $Id: resolve.c,v 1.27 2009/05/29 14:39:08 drh Exp $
drh7d10d5a2008-08-20 16:35:10 +000018*/
19#include "sqliteInt.h"
20#include <stdlib.h>
21#include <string.h>
22
23/*
drh8b213892008-08-29 02:14:02 +000024** Turn the pExpr expression into an alias for the iCol-th column of the
25** result set in pEList.
26**
27** If the result set column is a simple column reference, then this routine
28** makes an exact copy. But for any other kind of expression, this
29** routine make a copy of the result set column as the argument to the
30** TK_AS operator. The TK_AS operator causes the expression to be
31** evaluated just once and then reused for each alias.
32**
33** The reason for suppressing the TK_AS term when the expression is a simple
34** column reference is so that the column reference will be recognized as
35** usable by indices within the WHERE clause processing logic.
36**
37** Hack: The TK_AS operator is inhibited if zType[0]=='G'. This means
38** that in a GROUP BY clause, the expression is evaluated twice. Hence:
39**
40** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
41**
42** Is equivalent to:
43**
44** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
45**
46** The result of random()%5 in the GROUP BY clause is probably different
47** from the result in the result-set. We might fix this someday. Or
48** then again, we might not...
49*/
50static void resolveAlias(
51 Parse *pParse, /* Parsing context */
52 ExprList *pEList, /* A result set */
53 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
54 Expr *pExpr, /* Transform this into an alias to the result set */
55 const char *zType /* "GROUP" or "ORDER" or "" */
56){
57 Expr *pOrig; /* The iCol-th column of the result set */
58 Expr *pDup; /* Copy of pOrig */
59 sqlite3 *db; /* The database connection */
60
61 assert( iCol>=0 && iCol<pEList->nExpr );
62 pOrig = pEList->a[iCol].pExpr;
63 assert( pOrig!=0 );
64 assert( pOrig->flags & EP_Resolved );
65 db = pParse->db;
drhb7916a72009-05-27 10:31:29 +000066 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
67 pDup = sqlite3ExprDup(db, pOrig, 0);
drh8b213892008-08-29 02:14:02 +000068 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
69 if( pDup==0 ) return;
70 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +000071 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +000072 }
73 pDup->iTable = pEList->a[iCol].iAlias;
drh0b0745a2009-05-28 12:49:53 +000074 }else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
75 pDup = sqlite3ExprDup(db, pOrig, 0);
drh2c220452009-05-28 14:34:49 +000076 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +000077 }else{
drh33e619f2009-05-28 01:00:55 +000078 char *zToken = pOrig->u.zToken;
79 pOrig->u.zToken = 0;
drhb7916a72009-05-27 10:31:29 +000080 pDup = sqlite3ExprDup(db, pOrig, 0);
drh33e619f2009-05-28 01:00:55 +000081 pOrig->u.zToken = zToken;
drhb7916a72009-05-27 10:31:29 +000082 if( pDup==0 ) return;
83 if( zToken ){
84 assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
drh33e619f2009-05-28 01:00:55 +000085 pDup->flags2 |= EP2_MallocedToken;
86 pDup->u.zToken = sqlite3DbStrDup(db, zToken);
drhb7916a72009-05-27 10:31:29 +000087 }
drh8b213892008-08-29 02:14:02 +000088 }
89 if( pExpr->flags & EP_ExpCollate ){
90 pDup->pColl = pExpr->pColl;
91 pDup->flags |= EP_ExpCollate;
92 }
drh10fe8402008-10-11 16:47:35 +000093 sqlite3ExprClear(db, pExpr);
drh8b213892008-08-29 02:14:02 +000094 memcpy(pExpr, pDup, sizeof(*pExpr));
95 sqlite3DbFree(db, pDup);
96}
97
98/*
drh7d10d5a2008-08-20 16:35:10 +000099** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
100** that name in the set of source tables in pSrcList and make the pExpr
101** expression node refer back to that source column. The following changes
102** are made to pExpr:
103**
104** pExpr->iDb Set the index in db->aDb[] of the database X
105** (even if X is implied).
106** pExpr->iTable Set to the cursor number for the table obtained
107** from pSrcList.
108** pExpr->pTab Points to the Table structure of X.Y (even if
109** X and/or Y are implied.)
110** pExpr->iColumn Set to the column number within the table.
111** pExpr->op Set to TK_COLUMN.
112** pExpr->pLeft Any expression this points to is deleted
113** pExpr->pRight Any expression this points to is deleted.
114**
drhb7916a72009-05-27 10:31:29 +0000115** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000116** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000117** can be used. The zTable variable is the name of the table (the "Y"). This
118** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000119** means that the form of the name is Z and that columns from any table
120** can be used.
121**
122** If the name cannot be resolved unambiguously, leave an error message
123** in pParse and return non-zero. Return zero on success.
124*/
125static int lookupName(
126 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000127 const char *zDb, /* Name of the database containing table, or NULL */
128 const char *zTab, /* Name of table containing column, or NULL */
129 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000130 NameContext *pNC, /* The name context used to resolve the name */
131 Expr *pExpr /* Make this EXPR node point to the selected column */
132){
drh7d10d5a2008-08-20 16:35:10 +0000133 int i, j; /* Loop counters */
134 int cnt = 0; /* Number of matching column names */
135 int cntTab = 0; /* Number of matching table names */
136 sqlite3 *db = pParse->db; /* The database connection */
137 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
138 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
139 NameContext *pTopNC = pNC; /* First namecontext in the list */
140 Schema *pSchema = 0; /* Schema of the expression */
141
drhb7916a72009-05-27 10:31:29 +0000142 assert( pNC ); /* the name context cannot be NULL. */
143 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh33e619f2009-05-28 01:00:55 +0000144 assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000145
146 /* Initialize the node to no-match */
147 pExpr->iTable = -1;
148 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000149 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000150
151 /* Start at the inner-most context and move outward until a match is found */
152 while( pNC && cnt==0 ){
153 ExprList *pEList;
154 SrcList *pSrcList = pNC->pSrcList;
155
156 if( pSrcList ){
157 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
158 Table *pTab;
159 int iDb;
160 Column *pCol;
161
162 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000163 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000164 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
165 assert( pTab->nCol>0 );
166 if( zTab ){
167 if( pItem->zAlias ){
168 char *zTabName = pItem->zAlias;
169 if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
170 }else{
171 char *zTabName = pTab->zName;
172 if( zTabName==0 || sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
173 if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
174 continue;
175 }
176 }
177 }
178 if( 0==(cntTab++) ){
179 pExpr->iTable = pItem->iCursor;
180 pExpr->pTab = pTab;
181 pSchema = pTab->pSchema;
182 pMatch = pItem;
183 }
184 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
185 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
186 IdList *pUsing;
187 cnt++;
188 pExpr->iTable = pItem->iCursor;
189 pExpr->pTab = pTab;
190 pMatch = pItem;
191 pSchema = pTab->pSchema;
192 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
193 pExpr->iColumn = j==pTab->iPKey ? -1 : j;
194 if( i<pSrcList->nSrc-1 ){
195 if( pItem[1].jointype & JT_NATURAL ){
196 /* If this match occurred in the left table of a natural join,
197 ** then skip the right table to avoid a duplicate match */
198 pItem++;
199 i++;
200 }else if( (pUsing = pItem[1].pUsing)!=0 ){
201 /* If this match occurs on a column that is in the USING clause
202 ** of a join, skip the search of the right table of the join
203 ** to avoid a duplicate match there. */
204 int k;
205 for(k=0; k<pUsing->nId; k++){
206 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
207 pItem++;
208 i++;
209 break;
210 }
211 }
212 }
213 }
214 break;
215 }
216 }
217 }
218 }
219
220#ifndef SQLITE_OMIT_TRIGGER
221 /* If we have not already resolved the name, then maybe
222 ** it is a new.* or old.* trigger argument reference
223 */
224 if( zDb==0 && zTab!=0 && cnt==0 && pParse->trigStack!=0 ){
225 TriggerStack *pTriggerStack = pParse->trigStack;
226 Table *pTab = 0;
drhb27b7f52008-12-10 18:03:45 +0000227 u32 *piColMask = 0;
drh7d10d5a2008-08-20 16:35:10 +0000228 if( pTriggerStack->newIdx != -1 && sqlite3StrICmp("new", zTab) == 0 ){
229 pExpr->iTable = pTriggerStack->newIdx;
230 assert( pTriggerStack->pTab );
231 pTab = pTriggerStack->pTab;
232 piColMask = &(pTriggerStack->newColMask);
233 }else if( pTriggerStack->oldIdx != -1 && sqlite3StrICmp("old", zTab)==0 ){
234 pExpr->iTable = pTriggerStack->oldIdx;
235 assert( pTriggerStack->pTab );
236 pTab = pTriggerStack->pTab;
237 piColMask = &(pTriggerStack->oldColMask);
238 }
239
240 if( pTab ){
241 int iCol;
242 Column *pCol = pTab->aCol;
243
244 pSchema = pTab->pSchema;
245 cntTab++;
246 for(iCol=0; iCol < pTab->nCol; iCol++, pCol++) {
247 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
248 cnt++;
249 pExpr->iColumn = iCol==pTab->iPKey ? -1 : iCol;
250 pExpr->pTab = pTab;
251 if( iCol>=0 ){
252 testcase( iCol==31 );
253 testcase( iCol==32 );
drh3500ed62009-05-05 15:46:43 +0000254 if( iCol>=32 ){
255 *piColMask = 0xffffffff;
256 }else{
257 *piColMask |= ((u32)1)<<iCol;
258 }
drh7d10d5a2008-08-20 16:35:10 +0000259 }
260 break;
261 }
262 }
263 }
264 }
265#endif /* !defined(SQLITE_OMIT_TRIGGER) */
266
267 /*
268 ** Perhaps the name is a reference to the ROWID
269 */
270 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
271 cnt = 1;
272 pExpr->iColumn = -1;
273 pExpr->affinity = SQLITE_AFF_INTEGER;
274 }
275
276 /*
277 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
278 ** might refer to an result-set alias. This happens, for example, when
279 ** we are resolving names in the WHERE clause of the following command:
280 **
281 ** SELECT a+b AS x FROM table WHERE x<10;
282 **
283 ** In cases like this, replace pExpr with a copy of the expression that
284 ** forms the result set entry ("a+b" in the example) and return immediately.
285 ** Note that the expression in the result set should have already been
286 ** resolved by the time the WHERE clause is resolved.
287 */
288 if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
289 for(j=0; j<pEList->nExpr; j++){
290 char *zAs = pEList->a[j].zName;
291 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000292 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000293 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000294 assert( pExpr->x.pList==0 );
295 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000296 pOrig = pEList->a[j].pExpr;
297 if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
298 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drh7d10d5a2008-08-20 16:35:10 +0000299 return 2;
300 }
drh8b213892008-08-29 02:14:02 +0000301 resolveAlias(pParse, pEList, j, pExpr, "");
drh7d10d5a2008-08-20 16:35:10 +0000302 cnt = 1;
303 pMatch = 0;
304 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000305 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000306 }
307 }
308 }
309
310 /* Advance to the next name context. The loop will exit when either
311 ** we have a match (cnt>0) or when we run out of name contexts.
312 */
313 if( cnt==0 ){
314 pNC = pNC->pNext;
315 }
316 }
317
318 /*
319 ** If X and Y are NULL (in other words if only the column name Z is
320 ** supplied) and the value of Z is enclosed in double-quotes, then
321 ** Z is a string literal if it doesn't match any column names. In that
322 ** case, we need to return right away and not make any changes to
323 ** pExpr.
324 **
325 ** Because no reference was made to outer contexts, the pNC->nRef
326 ** fields are not changed in any context.
327 */
drh24fb6272009-05-01 21:13:36 +0000328 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000329 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000330 pExpr->pTab = 0;
drh7d10d5a2008-08-20 16:35:10 +0000331 return 0;
332 }
333
334 /*
335 ** cnt==0 means there was not match. cnt>1 means there were two or
336 ** more matches. Either way, we have an error.
337 */
338 if( cnt!=1 ){
339 const char *zErr;
340 zErr = cnt==0 ? "no such column" : "ambiguous column name";
341 if( zDb ){
342 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
343 }else if( zTab ){
344 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
345 }else{
346 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
347 }
348 pTopNC->nErr++;
349 }
350
351 /* If a column from a table in pSrcList is referenced, then record
352 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
353 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
354 ** column number is greater than the number of bits in the bitmask
355 ** then set the high-order bit of the bitmask.
356 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000357 if( pExpr->iColumn>=0 && pMatch!=0 ){
358 int n = pExpr->iColumn;
359 testcase( n==BMS-1 );
360 if( n>=BMS ){
361 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000362 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000363 assert( pMatch->iCursor==pExpr->iTable );
364 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000365 }
366
drh7d10d5a2008-08-20 16:35:10 +0000367 /* Clean up and return
368 */
drh7d10d5a2008-08-20 16:35:10 +0000369 sqlite3ExprDelete(db, pExpr->pLeft);
370 pExpr->pLeft = 0;
371 sqlite3ExprDelete(db, pExpr->pRight);
372 pExpr->pRight = 0;
373 pExpr->op = TK_COLUMN;
drhb7916a72009-05-27 10:31:29 +0000374lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000375 if( cnt==1 ){
376 assert( pNC!=0 );
377 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
378 /* Increment the nRef value on all name contexts from TopNC up to
379 ** the point where the name matched. */
380 for(;;){
381 assert( pTopNC!=0 );
382 pTopNC->nRef++;
383 if( pTopNC==pNC ) break;
384 pTopNC = pTopNC->pNext;
385 }
386 return 0;
387 } else {
388 return 1;
389 }
390}
391
392/*
393** This routine is callback for sqlite3WalkExpr().
394**
395** Resolve symbolic names into TK_COLUMN operators for the current
396** node in the expression tree. Return 0 to continue the search down
397** the tree or 2 to abort the tree walk.
398**
399** This routine also does error checking and name resolution for
400** function names. The operator for aggregate functions is changed
401** to TK_AGG_FUNCTION.
402*/
403static int resolveExprStep(Walker *pWalker, Expr *pExpr){
404 NameContext *pNC;
405 Parse *pParse;
406
drh7d10d5a2008-08-20 16:35:10 +0000407 pNC = pWalker->u.pNC;
408 assert( pNC!=0 );
409 pParse = pNC->pParse;
410 assert( pParse==pWalker->pParse );
411
412 if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
413 ExprSetProperty(pExpr, EP_Resolved);
414#ifndef NDEBUG
415 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
416 SrcList *pSrcList = pNC->pSrcList;
417 int i;
418 for(i=0; i<pNC->pSrcList->nSrc; i++){
419 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
420 }
421 }
422#endif
423 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000424
shane273f6192008-10-10 04:34:16 +0000425#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000426 /* The special operator TK_ROW means use the rowid for the first
427 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
428 ** clause processing on UPDATE and DELETE statements.
429 */
430 case TK_ROW: {
431 SrcList *pSrcList = pNC->pSrcList;
432 struct SrcList_item *pItem;
433 assert( pSrcList && pSrcList->nSrc==1 );
434 pItem = pSrcList->a;
435 pExpr->op = TK_COLUMN;
436 pExpr->pTab = pItem->pTab;
437 pExpr->iTable = pItem->iCursor;
438 pExpr->iColumn = -1;
439 pExpr->affinity = SQLITE_AFF_INTEGER;
440 break;
441 }
shane273f6192008-10-10 04:34:16 +0000442#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000443
drh7d10d5a2008-08-20 16:35:10 +0000444 /* A lone identifier is the name of a column.
445 */
446 case TK_ID: {
drh33e619f2009-05-28 01:00:55 +0000447 lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000448 return WRC_Prune;
449 }
450
451 /* A table name and column name: ID.ID
452 ** Or a database, table and column: ID.ID.ID
453 */
454 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000455 const char *zColumn;
456 const char *zTable;
457 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000458 Expr *pRight;
459
460 /* if( pSrcList==0 ) break; */
461 pRight = pExpr->pRight;
462 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000463 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000464 zTable = pExpr->pLeft->u.zToken;
465 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000466 }else{
467 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000468 zDb = pExpr->pLeft->u.zToken;
469 zTable = pRight->pLeft->u.zToken;
470 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000471 }
drhb7916a72009-05-27 10:31:29 +0000472 lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000473 return WRC_Prune;
474 }
475
476 /* Resolve function names
477 */
478 case TK_CONST_FUNC:
479 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000480 ExprList *pList = pExpr->x.pList; /* The argument list */
481 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000482 int no_such_func = 0; /* True if no such function exists */
483 int wrong_num_args = 0; /* True if wrong number of arguments */
484 int is_agg = 0; /* True if is an aggregate function */
485 int auth; /* Authorization to use the function */
486 int nId; /* Number of characters in function name */
487 const char *zId; /* The function name. */
488 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000489 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000490
danielk19776ab3a2e2009-02-19 14:39:25 +0000491 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh33e619f2009-05-28 01:00:55 +0000492 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000493 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000494 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
495 if( pDef==0 ){
496 pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
497 if( pDef==0 ){
498 no_such_func = 1;
499 }else{
500 wrong_num_args = 1;
501 }
502 }else{
503 is_agg = pDef->xFunc==0;
504 }
505#ifndef SQLITE_OMIT_AUTHORIZATION
506 if( pDef ){
507 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
508 if( auth!=SQLITE_OK ){
509 if( auth==SQLITE_DENY ){
510 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
511 pDef->zName);
512 pNC->nErr++;
513 }
514 pExpr->op = TK_NULL;
515 return WRC_Prune;
516 }
517 }
518#endif
519 if( is_agg && !pNC->allowAgg ){
520 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
521 pNC->nErr++;
522 is_agg = 0;
523 }else if( no_such_func ){
524 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
525 pNC->nErr++;
526 }else if( wrong_num_args ){
527 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
528 nId, zId);
529 pNC->nErr++;
530 }
531 if( is_agg ){
532 pExpr->op = TK_AGG_FUNCTION;
533 pNC->hasAgg = 1;
534 }
535 if( is_agg ) pNC->allowAgg = 0;
536 sqlite3WalkExprList(pWalker, pList);
537 if( is_agg ) pNC->allowAgg = 1;
538 /* FIX ME: Compute pExpr->affinity based on the expected return
539 ** type of the function
540 */
541 return WRC_Prune;
542 }
543#ifndef SQLITE_OMIT_SUBQUERY
544 case TK_SELECT:
545 case TK_EXISTS:
546#endif
547 case TK_IN: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000548 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000549 int nRef = pNC->nRef;
550#ifndef SQLITE_OMIT_CHECK
551 if( pNC->isCheck ){
552 sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
553 }
554#endif
danielk19776ab3a2e2009-02-19 14:39:25 +0000555 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000556 assert( pNC->nRef>=nRef );
557 if( nRef!=pNC->nRef ){
558 ExprSetProperty(pExpr, EP_VarSelect);
559 }
560 }
561 break;
562 }
563#ifndef SQLITE_OMIT_CHECK
564 case TK_VARIABLE: {
565 if( pNC->isCheck ){
566 sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
567 }
568 break;
569 }
570#endif
571 }
572 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
573}
574
575/*
576** pEList is a list of expressions which are really the result set of the
577** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
578** This routine checks to see if pE is a simple identifier which corresponds
579** to the AS-name of one of the terms of the expression list. If it is,
580** this routine return an integer between 1 and N where N is the number of
581** elements in pEList, corresponding to the matching entry. If there is
582** no match, or if pE is not a simple identifier, then this routine
583** return 0.
584**
585** pEList has been resolved. pE has not.
586*/
587static int resolveAsName(
588 Parse *pParse, /* Parsing context for error messages */
589 ExprList *pEList, /* List of expressions to scan */
590 Expr *pE /* Expression we are trying to match */
591){
592 int i; /* Loop counter */
593
drh33e619f2009-05-28 01:00:55 +0000594 if( pE->op==TK_ID || (pE->op==TK_STRING && pE->u.zToken[0]!='\'') ){
595 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000596 for(i=0; i<pEList->nExpr; i++){
597 char *zAs = pEList->a[i].zName;
598 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000599 return i+1;
600 }
601 }
drh7d10d5a2008-08-20 16:35:10 +0000602 }
603 return 0;
604}
605
606/*
607** pE is a pointer to an expression which is a single term in the
608** ORDER BY of a compound SELECT. The expression has not been
609** name resolved.
610**
611** At the point this routine is called, we already know that the
612** ORDER BY term is not an integer index into the result set. That
613** case is handled by the calling routine.
614**
615** Attempt to match pE against result set columns in the left-most
616** SELECT statement. Return the index i of the matching column,
617** as an indication to the caller that it should sort by the i-th column.
618** The left-most column is 1. In other words, the value returned is the
619** same integer value that would be used in the SQL statement to indicate
620** the column.
621**
622** If there is no match, return 0. Return -1 if an error occurs.
623*/
624static int resolveOrderByTermToExprList(
625 Parse *pParse, /* Parsing context for error messages */
626 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
627 Expr *pE /* The specific ORDER BY term */
628){
629 int i; /* Loop counter */
630 ExprList *pEList; /* The columns of the result set */
631 NameContext nc; /* Name context for resolving pE */
632
633 assert( sqlite3ExprIsInteger(pE, &i)==0 );
634 pEList = pSelect->pEList;
635
636 /* Resolve all names in the ORDER BY term expression
637 */
638 memset(&nc, 0, sizeof(nc));
639 nc.pParse = pParse;
640 nc.pSrcList = pSelect->pSrc;
641 nc.pEList = pEList;
642 nc.allowAgg = 1;
643 nc.nErr = 0;
644 if( sqlite3ResolveExprNames(&nc, pE) ){
645 sqlite3ErrorClear(pParse);
646 return 0;
647 }
648
649 /* Try to match the ORDER BY expression against an expression
650 ** in the result set. Return an 1-based index of the matching
651 ** result-set entry.
652 */
653 for(i=0; i<pEList->nExpr; i++){
654 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
655 return i+1;
656 }
657 }
658
659 /* If no match, return 0. */
660 return 0;
661}
662
663/*
664** Generate an ORDER BY or GROUP BY term out-of-range error.
665*/
666static void resolveOutOfRangeError(
667 Parse *pParse, /* The error context into which to write the error */
668 const char *zType, /* "ORDER" or "GROUP" */
669 int i, /* The index (1-based) of the term out of range */
670 int mx /* Largest permissible value of i */
671){
672 sqlite3ErrorMsg(pParse,
673 "%r %s BY term out of range - should be "
674 "between 1 and %d", i, zType, mx);
675}
676
677/*
678** Analyze the ORDER BY clause in a compound SELECT statement. Modify
679** each term of the ORDER BY clause is a constant integer between 1
680** and N where N is the number of columns in the compound SELECT.
681**
682** ORDER BY terms that are already an integer between 1 and N are
683** unmodified. ORDER BY terms that are integers outside the range of
684** 1 through N generate an error. ORDER BY terms that are expressions
685** are matched against result set expressions of compound SELECT
686** beginning with the left-most SELECT and working toward the right.
687** At the first match, the ORDER BY expression is transformed into
688** the integer column number.
689**
690** Return the number of errors seen.
691*/
692static int resolveCompoundOrderBy(
693 Parse *pParse, /* Parsing context. Leave error messages here */
694 Select *pSelect /* The SELECT statement containing the ORDER BY */
695){
696 int i;
697 ExprList *pOrderBy;
698 ExprList *pEList;
699 sqlite3 *db;
700 int moreToDo = 1;
701
702 pOrderBy = pSelect->pOrderBy;
703 if( pOrderBy==0 ) return 0;
704 db = pParse->db;
705#if SQLITE_MAX_COLUMN
706 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
707 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
708 return 1;
709 }
710#endif
711 for(i=0; i<pOrderBy->nExpr; i++){
712 pOrderBy->a[i].done = 0;
713 }
714 pSelect->pNext = 0;
715 while( pSelect->pPrior ){
716 pSelect->pPrior->pNext = pSelect;
717 pSelect = pSelect->pPrior;
718 }
719 while( pSelect && moreToDo ){
720 struct ExprList_item *pItem;
721 moreToDo = 0;
722 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000723 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000724 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
725 int iCol = -1;
726 Expr *pE, *pDup;
727 if( pItem->done ) continue;
728 pE = pItem->pExpr;
729 if( sqlite3ExprIsInteger(pE, &iCol) ){
730 if( iCol<0 || iCol>pEList->nExpr ){
731 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
732 return 1;
733 }
734 }else{
735 iCol = resolveAsName(pParse, pEList, pE);
736 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000737 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000738 if( !db->mallocFailed ){
739 assert(pDup);
740 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
741 }
742 sqlite3ExprDelete(db, pDup);
743 }
744 if( iCol<0 ){
745 return 1;
746 }
747 }
748 if( iCol>0 ){
749 CollSeq *pColl = pE->pColl;
750 int flags = pE->flags & EP_ExpCollate;
751 sqlite3ExprDelete(db, pE);
drhb7916a72009-05-27 10:31:29 +0000752 pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
drh7d10d5a2008-08-20 16:35:10 +0000753 if( pE==0 ) return 1;
754 pE->pColl = pColl;
755 pE->flags |= EP_IntValue | flags;
drh33e619f2009-05-28 01:00:55 +0000756 pE->u.iValue = iCol;
drhea678832008-12-10 19:26:22 +0000757 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000758 pItem->done = 1;
759 }else{
760 moreToDo = 1;
761 }
762 }
763 pSelect = pSelect->pNext;
764 }
765 for(i=0; i<pOrderBy->nExpr; i++){
766 if( pOrderBy->a[i].done==0 ){
767 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
768 "column in the result set", i+1);
769 return 1;
770 }
771 }
772 return 0;
773}
774
775/*
776** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
777** the SELECT statement pSelect. If any term is reference to a
778** result set expression (as determined by the ExprList.a.iCol field)
779** then convert that term into a copy of the corresponding result set
780** column.
781**
782** If any errors are detected, add an error message to pParse and
783** return non-zero. Return zero if no errors are seen.
784*/
785int sqlite3ResolveOrderGroupBy(
786 Parse *pParse, /* Parsing context. Leave error messages here */
787 Select *pSelect, /* The SELECT statement containing the clause */
788 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
789 const char *zType /* "ORDER" or "GROUP" */
790){
791 int i;
792 sqlite3 *db = pParse->db;
793 ExprList *pEList;
794 struct ExprList_item *pItem;
795
796 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
797#if SQLITE_MAX_COLUMN
798 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
799 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
800 return 1;
801 }
802#endif
803 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000804 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +0000805 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
806 if( pItem->iCol ){
drh7d10d5a2008-08-20 16:35:10 +0000807 if( pItem->iCol>pEList->nExpr ){
808 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
809 return 1;
810 }
drh8b213892008-08-29 02:14:02 +0000811 resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
drh7d10d5a2008-08-20 16:35:10 +0000812 }
813 }
814 return 0;
815}
816
817/*
818** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
819** The Name context of the SELECT statement is pNC. zType is either
820** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
821**
822** This routine resolves each term of the clause into an expression.
823** If the order-by term is an integer I between 1 and N (where N is the
824** number of columns in the result set of the SELECT) then the expression
825** in the resolution is a copy of the I-th result-set expression. If
826** the order-by term is an identify that corresponds to the AS-name of
827** a result-set expression, then the term resolves to a copy of the
828** result-set expression. Otherwise, the expression is resolved in
829** the usual way - using sqlite3ResolveExprNames().
830**
831** This routine returns the number of errors. If errors occur, then
832** an appropriate error message might be left in pParse. (OOM errors
833** excepted.)
834*/
835static int resolveOrderGroupBy(
836 NameContext *pNC, /* The name context of the SELECT statement */
837 Select *pSelect, /* The SELECT statement holding pOrderBy */
838 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
839 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
840){
841 int i; /* Loop counter */
842 int iCol; /* Column number */
843 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
844 Parse *pParse; /* Parsing context */
845 int nResult; /* Number of terms in the result set */
846
847 if( pOrderBy==0 ) return 0;
848 nResult = pSelect->pEList->nExpr;
849 pParse = pNC->pParse;
850 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
851 Expr *pE = pItem->pExpr;
852 iCol = resolveAsName(pParse, pSelect->pEList, pE);
853 if( iCol<0 ){
854 return 1; /* OOM error */
855 }
856 if( iCol>0 ){
857 /* If an AS-name match is found, mark this ORDER BY column as being
858 ** a copy of the iCol-th result-set column. The subsequent call to
859 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
860 ** copy of the iCol-th result-set expression. */
drhea678832008-12-10 19:26:22 +0000861 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000862 continue;
863 }
864 if( sqlite3ExprIsInteger(pE, &iCol) ){
865 /* The ORDER BY term is an integer constant. Again, set the column
866 ** number so that sqlite3ResolveOrderGroupBy() will convert the
867 ** order-by term to a copy of the result-set expression */
drh0a846f92008-08-25 17:23:29 +0000868 if( iCol<1 ){
drh7d10d5a2008-08-20 16:35:10 +0000869 resolveOutOfRangeError(pParse, zType, i+1, nResult);
870 return 1;
871 }
drhea678832008-12-10 19:26:22 +0000872 pItem->iCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000873 continue;
874 }
875
876 /* Otherwise, treat the ORDER BY term as an ordinary expression */
877 pItem->iCol = 0;
878 if( sqlite3ResolveExprNames(pNC, pE) ){
879 return 1;
880 }
881 }
882 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
883}
884
885/*
886** Resolve names in the SELECT statement p and all of its descendents.
887*/
888static int resolveSelectStep(Walker *pWalker, Select *p){
889 NameContext *pOuterNC; /* Context that contains this SELECT */
890 NameContext sNC; /* Name context of this SELECT */
891 int isCompound; /* True if p is a compound select */
892 int nCompound; /* Number of compound terms processed so far */
893 Parse *pParse; /* Parsing context */
894 ExprList *pEList; /* Result set expression list */
895 int i; /* Loop counter */
896 ExprList *pGroupBy; /* The GROUP BY clause */
897 Select *pLeftmost; /* Left-most of SELECT of a compound */
898 sqlite3 *db; /* Database connection */
899
900
drh0a846f92008-08-25 17:23:29 +0000901 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000902 if( p->selFlags & SF_Resolved ){
903 return WRC_Prune;
904 }
905 pOuterNC = pWalker->u.pNC;
906 pParse = pWalker->pParse;
907 db = pParse->db;
908
909 /* Normally sqlite3SelectExpand() will be called first and will have
910 ** already expanded this SELECT. However, if this is a subquery within
911 ** an expression, sqlite3ResolveExprNames() will be called without a
912 ** prior call to sqlite3SelectExpand(). When that happens, let
913 ** sqlite3SelectPrep() do all of the processing for this SELECT.
914 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
915 ** this routine in the correct order.
916 */
917 if( (p->selFlags & SF_Expanded)==0 ){
918 sqlite3SelectPrep(pParse, p, pOuterNC);
919 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
920 }
921
922 isCompound = p->pPrior!=0;
923 nCompound = 0;
924 pLeftmost = p;
925 while( p ){
926 assert( (p->selFlags & SF_Expanded)!=0 );
927 assert( (p->selFlags & SF_Resolved)==0 );
928 p->selFlags |= SF_Resolved;
929
930 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
931 ** are not allowed to refer to any names, so pass an empty NameContext.
932 */
933 memset(&sNC, 0, sizeof(sNC));
934 sNC.pParse = pParse;
935 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
936 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
937 return WRC_Abort;
938 }
939
940 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
941 ** resolve the result-set expression list.
942 */
943 sNC.allowAgg = 1;
944 sNC.pSrcList = p->pSrc;
945 sNC.pNext = pOuterNC;
946
947 /* Resolve names in the result set. */
948 pEList = p->pEList;
drh0a846f92008-08-25 17:23:29 +0000949 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000950 for(i=0; i<pEList->nExpr; i++){
951 Expr *pX = pEList->a[i].pExpr;
952 if( sqlite3ResolveExprNames(&sNC, pX) ){
953 return WRC_Abort;
954 }
955 }
956
957 /* Recursively resolve names in all subqueries
958 */
959 for(i=0; i<p->pSrc->nSrc; i++){
960 struct SrcList_item *pItem = &p->pSrc->a[i];
961 if( pItem->pSelect ){
962 const char *zSavedContext = pParse->zAuthContext;
963 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +0000964 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +0000965 pParse->zAuthContext = zSavedContext;
966 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
967 }
968 }
969
970 /* If there are no aggregate functions in the result-set, and no GROUP BY
971 ** expression, do not allow aggregates in any of the other expressions.
972 */
973 assert( (p->selFlags & SF_Aggregate)==0 );
974 pGroupBy = p->pGroupBy;
975 if( pGroupBy || sNC.hasAgg ){
976 p->selFlags |= SF_Aggregate;
977 }else{
978 sNC.allowAgg = 0;
979 }
980
981 /* If a HAVING clause is present, then there must be a GROUP BY clause.
982 */
983 if( p->pHaving && !pGroupBy ){
984 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
985 return WRC_Abort;
986 }
987
988 /* Add the expression list to the name-context before parsing the
989 ** other expressions in the SELECT statement. This is so that
990 ** expressions in the WHERE clause (etc.) can refer to expressions by
991 ** aliases in the result set.
992 **
993 ** Minor point: If this is the case, then the expression will be
994 ** re-evaluated for each reference to it.
995 */
996 sNC.pEList = p->pEList;
997 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
998 sqlite3ResolveExprNames(&sNC, p->pHaving)
999 ){
1000 return WRC_Abort;
1001 }
1002
1003 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1004 ** outer queries
1005 */
1006 sNC.pNext = 0;
1007 sNC.allowAgg = 1;
1008
1009 /* Process the ORDER BY clause for singleton SELECT statements.
1010 ** The ORDER BY clause for compounds SELECT statements is handled
1011 ** below, after all of the result-sets for all of the elements of
1012 ** the compound have been resolved.
1013 */
1014 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1015 return WRC_Abort;
1016 }
1017 if( db->mallocFailed ){
1018 return WRC_Abort;
1019 }
1020
1021 /* Resolve the GROUP BY clause. At the same time, make sure
1022 ** the GROUP BY clause does not contain aggregate functions.
1023 */
1024 if( pGroupBy ){
1025 struct ExprList_item *pItem;
1026
1027 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1028 return WRC_Abort;
1029 }
1030 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1031 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1032 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1033 "the GROUP BY clause");
1034 return WRC_Abort;
1035 }
1036 }
1037 }
1038
1039 /* Advance to the next term of the compound
1040 */
1041 p = p->pPrior;
1042 nCompound++;
1043 }
1044
1045 /* Resolve the ORDER BY on a compound SELECT after all terms of
1046 ** the compound have been resolved.
1047 */
1048 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1049 return WRC_Abort;
1050 }
1051
1052 return WRC_Prune;
1053}
1054
1055/*
1056** This routine walks an expression tree and resolves references to
1057** table columns and result-set columns. At the same time, do error
1058** checking on function usage and set a flag if any aggregate functions
1059** are seen.
1060**
1061** To resolve table columns references we look for nodes (or subtrees) of the
1062** form X.Y.Z or Y.Z or just Z where
1063**
1064** X: The name of a database. Ex: "main" or "temp" or
1065** the symbolic name assigned to an ATTACH-ed database.
1066**
1067** Y: The name of a table in a FROM clause. Or in a trigger
1068** one of the special names "old" or "new".
1069**
1070** Z: The name of a column in table Y.
1071**
1072** The node at the root of the subtree is modified as follows:
1073**
1074** Expr.op Changed to TK_COLUMN
1075** Expr.pTab Points to the Table object for X.Y
1076** Expr.iColumn The column index in X.Y. -1 for the rowid.
1077** Expr.iTable The VDBE cursor number for X.Y
1078**
1079**
1080** To resolve result-set references, look for expression nodes of the
1081** form Z (with no X and Y prefix) where the Z matches the right-hand
1082** size of an AS clause in the result-set of a SELECT. The Z expression
1083** is replaced by a copy of the left-hand side of the result-set expression.
1084** Table-name and function resolution occurs on the substituted expression
1085** tree. For example, in:
1086**
1087** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1088**
1089** The "x" term of the order by is replaced by "a+b" to render:
1090**
1091** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1092**
1093** Function calls are checked to make sure that the function is
1094** defined and that the correct number of arguments are specified.
1095** If the function is an aggregate function, then the pNC->hasAgg is
1096** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1097** If an expression contains aggregate functions then the EP_Agg
1098** property on the expression is set.
1099**
1100** An error message is left in pParse if anything is amiss. The number
1101** if errors is returned.
1102*/
1103int sqlite3ResolveExprNames(
1104 NameContext *pNC, /* Namespace to resolve expressions in. */
1105 Expr *pExpr /* The expression to be analyzed. */
1106){
1107 int savedHasAgg;
1108 Walker w;
1109
1110 if( pExpr==0 ) return 0;
1111#if SQLITE_MAX_EXPR_DEPTH>0
1112 {
1113 Parse *pParse = pNC->pParse;
1114 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1115 return 1;
1116 }
1117 pParse->nHeight += pExpr->nHeight;
1118 }
1119#endif
1120 savedHasAgg = pNC->hasAgg;
1121 pNC->hasAgg = 0;
1122 w.xExprCallback = resolveExprStep;
1123 w.xSelectCallback = resolveSelectStep;
1124 w.pParse = pNC->pParse;
1125 w.u.pNC = pNC;
1126 sqlite3WalkExpr(&w, pExpr);
1127#if SQLITE_MAX_EXPR_DEPTH>0
1128 pNC->pParse->nHeight -= pExpr->nHeight;
1129#endif
drhfd773cf2009-05-29 14:39:07 +00001130 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001131 ExprSetProperty(pExpr, EP_Error);
1132 }
1133 if( pNC->hasAgg ){
1134 ExprSetProperty(pExpr, EP_Agg);
1135 }else if( savedHasAgg ){
1136 pNC->hasAgg = 1;
1137 }
1138 return ExprHasProperty(pExpr, EP_Error);
1139}
drh7d10d5a2008-08-20 16:35:10 +00001140
1141
1142/*
1143** Resolve all names in all expressions of a SELECT and in all
1144** decendents of the SELECT, including compounds off of p->pPrior,
1145** subqueries in expressions, and subqueries used as FROM clause
1146** terms.
1147**
1148** See sqlite3ResolveExprNames() for a description of the kinds of
1149** transformations that occur.
1150**
1151** All SELECT statements should have been expanded using
1152** sqlite3SelectExpand() prior to invoking this routine.
1153*/
1154void sqlite3ResolveSelectNames(
1155 Parse *pParse, /* The parser context */
1156 Select *p, /* The SELECT statement being coded. */
1157 NameContext *pOuterNC /* Name context for parent SELECT statement */
1158){
1159 Walker w;
1160
drh0a846f92008-08-25 17:23:29 +00001161 assert( p!=0 );
1162 w.xExprCallback = resolveExprStep;
1163 w.xSelectCallback = resolveSelectStep;
1164 w.pParse = pParse;
1165 w.u.pNC = pOuterNC;
1166 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001167}