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