4
** The author disclaims copyright to this source code. In place of
5
** a legal notice, here is a blessing:
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
17
** $Id: resolve.c,v 1.30 2009/06/15 23:15:59 drh Exp $
19
#include "sqliteInt.h"
24
** Turn the pExpr expression into an alias for the iCol-th column of the
25
** result set in pEList.
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.
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.
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:
40
** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
44
** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
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...
50
static 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 "" */
57
Expr *pOrig; /* The iCol-th column of the result set */
58
Expr *pDup; /* Copy of pOrig */
59
sqlite3 *db; /* The database connection */
61
assert( iCol>=0 && iCol<pEList->nExpr );
62
pOrig = pEList->a[iCol].pExpr;
64
assert( pOrig->flags & EP_Resolved );
66
if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
67
pDup = sqlite3ExprDup(db, pOrig, 0);
68
pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
70
if( pEList->a[iCol].iAlias==0 ){
71
pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
73
pDup->iTable = pEList->a[iCol].iAlias;
74
}else if( ExprHasProperty(pOrig, EP_IntValue) || pOrig->u.zToken==0 ){
75
pDup = sqlite3ExprDup(db, pOrig, 0);
78
char *zToken = pOrig->u.zToken;
81
pDup = sqlite3ExprDup(db, pOrig, 0);
82
pOrig->u.zToken = zToken;
84
assert( (pDup->flags & (EP_Reduced|EP_TokenOnly))==0 );
85
pDup->flags2 |= EP2_MallocedToken;
86
pDup->u.zToken = sqlite3DbStrDup(db, zToken);
88
if( pExpr->flags & EP_ExpCollate ){
89
pDup->pColl = pExpr->pColl;
90
pDup->flags |= EP_ExpCollate;
92
sqlite3ExprClear(db, pExpr);
93
memcpy(pExpr, pDup, sizeof(*pExpr));
94
sqlite3DbFree(db, pDup);
98
** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
99
** that name in the set of source tables in pSrcList and make the pExpr
100
** expression node refer back to that source column. The following changes
101
** are made to pExpr:
103
** pExpr->iDb Set the index in db->aDb[] of the database X
104
** (even if X is implied).
105
** pExpr->iTable Set to the cursor number for the table obtained
107
** pExpr->pTab Points to the Table structure of X.Y (even if
108
** X and/or Y are implied.)
109
** pExpr->iColumn Set to the column number within the table.
110
** pExpr->op Set to TK_COLUMN.
111
** pExpr->pLeft Any expression this points to is deleted
112
** pExpr->pRight Any expression this points to is deleted.
114
** The zDb variable is the name of the database (the "X"). This value may be
115
** NULL meaning that name is of the form Y.Z or Z. Any available database
116
** can be used. The zTable variable is the name of the table (the "Y"). This
117
** value can be NULL if zDb is also NULL. If zTable is NULL it
118
** means that the form of the name is Z and that columns from any table
121
** If the name cannot be resolved unambiguously, leave an error message
122
** in pParse and return WRC_Abort. Return WRC_Prune on success.
124
static int lookupName(
125
Parse *pParse, /* The parsing context */
126
const char *zDb, /* Name of the database containing table, or NULL */
127
const char *zTab, /* Name of table containing column, or NULL */
128
const char *zCol, /* Name of the column. */
129
NameContext *pNC, /* The name context used to resolve the name */
130
Expr *pExpr /* Make this EXPR node point to the selected column */
132
int i, j; /* Loop counters */
133
int cnt = 0; /* Number of matching column names */
134
int cntTab = 0; /* Number of matching table names */
135
sqlite3 *db = pParse->db; /* The database connection */
136
struct SrcList_item *pItem; /* Use for looping over pSrcList items */
137
struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
138
NameContext *pTopNC = pNC; /* First namecontext in the list */
139
Schema *pSchema = 0; /* Schema of the expression */
142
assert( pNC ); /* the name context cannot be NULL. */
143
assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
144
assert( ~ExprHasAnyProperty(pExpr, EP_TokenOnly|EP_Reduced) );
146
/* Initialize the node to no-match */
149
ExprSetIrreducible(pExpr);
151
/* Start at the inner-most context and move outward until a match is found */
152
while( pNC && cnt==0 ){
154
SrcList *pSrcList = pNC->pSrcList;
157
for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
163
assert( pTab!=0 && pTab->zName!=0 );
164
iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
165
assert( pTab->nCol>0 );
168
char *zTabName = pItem->zAlias;
169
if( sqlite3StrICmp(zTabName, zTab)!=0 ) continue;
171
char *zTabName = pTab->zName;
172
if( NEVER(zTabName==0) || sqlite3StrICmp(zTabName, zTab)!=0 ){
175
if( zDb!=0 && sqlite3StrICmp(db->aDb[iDb].zName, zDb)!=0 ){
181
pExpr->iTable = pItem->iCursor;
183
pSchema = pTab->pSchema;
186
for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
187
if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
190
pExpr->iTable = pItem->iCursor;
193
pSchema = pTab->pSchema;
194
/* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
195
pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
196
if( i<pSrcList->nSrc-1 ){
197
if( pItem[1].jointype & JT_NATURAL ){
198
/* If this match occurred in the left table of a natural join,
199
** then skip the right table to avoid a duplicate match */
202
}else if( (pUsing = pItem[1].pUsing)!=0 ){
203
/* If this match occurs on a column that is in the USING clause
204
** of a join, skip the search of the right table of the join
205
** to avoid a duplicate match there. */
207
for(k=0; k<pUsing->nId; k++){
208
if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ){
222
#ifndef SQLITE_OMIT_TRIGGER
223
/* If we have not already resolved the name, then maybe
224
** it is a new.* or old.* trigger argument reference
226
if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
227
int op = pParse->eTriggerOp;
229
assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
230
if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
232
pTab = pParse->pTriggerTab;
233
}else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
235
pTab = pParse->pTriggerTab;
240
pSchema = pTab->pSchema;
242
if( sqlite3IsRowid(zCol) ){
245
for(iCol=0; iCol<pTab->nCol; iCol++){
246
Column *pCol = &pTab->aCol[iCol];
247
if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
248
if( iCol==pTab->iPKey ){
255
if( iCol<pTab->nCol ){
258
pExpr->affinity = SQLITE_AFF_INTEGER;
259
}else if( pExpr->iTable==0 ){
260
testcase( iCol==31 );
261
testcase( iCol==32 );
262
pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
264
pExpr->iColumn = (i16)iCol;
270
#endif /* !defined(SQLITE_OMIT_TRIGGER) */
273
** Perhaps the name is a reference to the ROWID
275
if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
278
pExpr->affinity = SQLITE_AFF_INTEGER;
282
** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
283
** might refer to an result-set alias. This happens, for example, when
284
** we are resolving names in the WHERE clause of the following command:
286
** SELECT a+b AS x FROM table WHERE x<10;
288
** In cases like this, replace pExpr with a copy of the expression that
289
** forms the result set entry ("a+b" in the example) and return immediately.
290
** Note that the expression in the result set should have already been
291
** resolved by the time the WHERE clause is resolved.
293
if( cnt==0 && (pEList = pNC->pEList)!=0 && zTab==0 ){
294
for(j=0; j<pEList->nExpr; j++){
295
char *zAs = pEList->a[j].zName;
296
if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
298
assert( pExpr->pLeft==0 && pExpr->pRight==0 );
299
assert( pExpr->x.pList==0 );
300
assert( pExpr->x.pSelect==0 );
301
pOrig = pEList->a[j].pExpr;
302
if( !pNC->allowAgg && ExprHasProperty(pOrig, EP_Agg) ){
303
sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
306
resolveAlias(pParse, pEList, j, pExpr, "");
309
assert( zTab==0 && zDb==0 );
315
/* Advance to the next name context. The loop will exit when either
316
** we have a match (cnt>0) or when we run out of name contexts.
324
** If X and Y are NULL (in other words if only the column name Z is
325
** supplied) and the value of Z is enclosed in double-quotes, then
326
** Z is a string literal if it doesn't match any column names. In that
327
** case, we need to return right away and not make any changes to
330
** Because no reference was made to outer contexts, the pNC->nRef
331
** fields are not changed in any context.
333
if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
334
pExpr->op = TK_STRING;
340
** cnt==0 means there was not match. cnt>1 means there were two or
341
** more matches. Either way, we have an error.
345
zErr = cnt==0 ? "no such column" : "ambiguous column name";
347
sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
349
sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
351
sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
356
/* If a column from a table in pSrcList is referenced, then record
357
** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
358
** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
359
** column number is greater than the number of bits in the bitmask
360
** then set the high-order bit of the bitmask.
362
if( pExpr->iColumn>=0 && pMatch!=0 ){
363
int n = pExpr->iColumn;
364
testcase( n==BMS-1 );
368
assert( pMatch->iCursor==pExpr->iTable );
369
pMatch->colUsed |= ((Bitmask)1)<<n;
372
/* Clean up and return
374
sqlite3ExprDelete(db, pExpr->pLeft);
376
sqlite3ExprDelete(db, pExpr->pRight);
378
pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
382
sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
383
/* Increment the nRef value on all name contexts from TopNC up to
384
** the point where the name matched. */
388
if( pTopNC==pNC ) break;
389
pTopNC = pTopNC->pNext;
398
** This routine is callback for sqlite3WalkExpr().
400
** Resolve symbolic names into TK_COLUMN operators for the current
401
** node in the expression tree. Return 0 to continue the search down
402
** the tree or 2 to abort the tree walk.
404
** This routine also does error checking and name resolution for
405
** function names. The operator for aggregate functions is changed
406
** to TK_AGG_FUNCTION.
408
static int resolveExprStep(Walker *pWalker, Expr *pExpr){
412
pNC = pWalker->u.pNC;
414
pParse = pNC->pParse;
415
assert( pParse==pWalker->pParse );
417
if( ExprHasAnyProperty(pExpr, EP_Resolved) ) return WRC_Prune;
418
ExprSetProperty(pExpr, EP_Resolved);
420
if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
421
SrcList *pSrcList = pNC->pSrcList;
423
for(i=0; i<pNC->pSrcList->nSrc; i++){
424
assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
430
#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
431
/* The special operator TK_ROW means use the rowid for the first
432
** column in the FROM clause. This is used by the LIMIT and ORDER BY
433
** clause processing on UPDATE and DELETE statements.
436
SrcList *pSrcList = pNC->pSrcList;
437
struct SrcList_item *pItem;
438
assert( pSrcList && pSrcList->nSrc==1 );
440
pExpr->op = TK_COLUMN;
441
pExpr->pTab = pItem->pTab;
442
pExpr->iTable = pItem->iCursor;
444
pExpr->affinity = SQLITE_AFF_INTEGER;
447
#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
449
/* A lone identifier is the name of a column.
452
return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
455
/* A table name and column name: ID.ID
456
** Or a database, table and column: ID.ID.ID
464
/* if( pSrcList==0 ) break; */
465
pRight = pExpr->pRight;
466
if( pRight->op==TK_ID ){
468
zTable = pExpr->pLeft->u.zToken;
469
zColumn = pRight->u.zToken;
471
assert( pRight->op==TK_DOT );
472
zDb = pExpr->pLeft->u.zToken;
473
zTable = pRight->pLeft->u.zToken;
474
zColumn = pRight->pRight->u.zToken;
476
return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
479
/* Resolve function names
483
ExprList *pList = pExpr->x.pList; /* The argument list */
484
int n = pList ? pList->nExpr : 0; /* Number of arguments */
485
int no_such_func = 0; /* True if no such function exists */
486
int wrong_num_args = 0; /* True if wrong number of arguments */
487
int is_agg = 0; /* True if is an aggregate function */
488
int auth; /* Authorization to use the function */
489
int nId; /* Number of characters in function name */
490
const char *zId; /* The function name. */
491
FuncDef *pDef; /* Information about the function */
492
u8 enc = ENC(pParse->db); /* The database encoding */
494
testcase( pExpr->op==TK_CONST_FUNC );
495
assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
496
zId = pExpr->u.zToken;
497
nId = sqlite3Strlen30(zId);
498
pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
500
pDef = sqlite3FindFunction(pParse->db, zId, nId, -1, enc, 0);
507
is_agg = pDef->xFunc==0;
509
#ifndef SQLITE_OMIT_AUTHORIZATION
511
auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
512
if( auth!=SQLITE_OK ){
513
if( auth==SQLITE_DENY ){
514
sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
523
if( is_agg && !pNC->allowAgg ){
524
sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
527
}else if( no_such_func ){
528
sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
530
}else if( wrong_num_args ){
531
sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
536
pExpr->op = TK_AGG_FUNCTION;
539
if( is_agg ) pNC->allowAgg = 0;
540
sqlite3WalkExprList(pWalker, pList);
541
if( is_agg ) pNC->allowAgg = 1;
542
/* FIX ME: Compute pExpr->affinity based on the expected return
543
** type of the function
547
#ifndef SQLITE_OMIT_SUBQUERY
549
case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
552
testcase( pExpr->op==TK_IN );
553
if( ExprHasProperty(pExpr, EP_xIsSelect) ){
554
int nRef = pNC->nRef;
555
#ifndef SQLITE_OMIT_CHECK
557
sqlite3ErrorMsg(pParse,"subqueries prohibited in CHECK constraints");
560
sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
561
assert( pNC->nRef>=nRef );
562
if( nRef!=pNC->nRef ){
563
ExprSetProperty(pExpr, EP_VarSelect);
568
#ifndef SQLITE_OMIT_CHECK
571
sqlite3ErrorMsg(pParse,"parameters prohibited in CHECK constraints");
577
return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
581
** pEList is a list of expressions which are really the result set of the
582
** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
583
** This routine checks to see if pE is a simple identifier which corresponds
584
** to the AS-name of one of the terms of the expression list. If it is,
585
** this routine return an integer between 1 and N where N is the number of
586
** elements in pEList, corresponding to the matching entry. If there is
587
** no match, or if pE is not a simple identifier, then this routine
590
** pEList has been resolved. pE has not.
592
static int resolveAsName(
593
Parse *pParse, /* Parsing context for error messages */
594
ExprList *pEList, /* List of expressions to scan */
595
Expr *pE /* Expression we are trying to match */
597
int i; /* Loop counter */
599
UNUSED_PARAMETER(pParse);
602
char *zCol = pE->u.zToken;
603
for(i=0; i<pEList->nExpr; i++){
604
char *zAs = pEList->a[i].zName;
605
if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
614
** pE is a pointer to an expression which is a single term in the
615
** ORDER BY of a compound SELECT. The expression has not been
618
** At the point this routine is called, we already know that the
619
** ORDER BY term is not an integer index into the result set. That
620
** case is handled by the calling routine.
622
** Attempt to match pE against result set columns in the left-most
623
** SELECT statement. Return the index i of the matching column,
624
** as an indication to the caller that it should sort by the i-th column.
625
** The left-most column is 1. In other words, the value returned is the
626
** same integer value that would be used in the SQL statement to indicate
629
** If there is no match, return 0. Return -1 if an error occurs.
631
static int resolveOrderByTermToExprList(
632
Parse *pParse, /* Parsing context for error messages */
633
Select *pSelect, /* The SELECT statement with the ORDER BY clause */
634
Expr *pE /* The specific ORDER BY term */
636
int i; /* Loop counter */
637
ExprList *pEList; /* The columns of the result set */
638
NameContext nc; /* Name context for resolving pE */
640
assert( sqlite3ExprIsInteger(pE, &i)==0 );
641
pEList = pSelect->pEList;
643
/* Resolve all names in the ORDER BY term expression
645
memset(&nc, 0, sizeof(nc));
647
nc.pSrcList = pSelect->pSrc;
651
if( sqlite3ResolveExprNames(&nc, pE) ){
652
sqlite3ErrorClear(pParse);
656
/* Try to match the ORDER BY expression against an expression
657
** in the result set. Return an 1-based index of the matching
660
for(i=0; i<pEList->nExpr; i++){
661
if( sqlite3ExprCompare(pEList->a[i].pExpr, pE) ){
666
/* If no match, return 0. */
671
** Generate an ORDER BY or GROUP BY term out-of-range error.
673
static void resolveOutOfRangeError(
674
Parse *pParse, /* The error context into which to write the error */
675
const char *zType, /* "ORDER" or "GROUP" */
676
int i, /* The index (1-based) of the term out of range */
677
int mx /* Largest permissible value of i */
679
sqlite3ErrorMsg(pParse,
680
"%r %s BY term out of range - should be "
681
"between 1 and %d", i, zType, mx);
685
** Analyze the ORDER BY clause in a compound SELECT statement. Modify
686
** each term of the ORDER BY clause is a constant integer between 1
687
** and N where N is the number of columns in the compound SELECT.
689
** ORDER BY terms that are already an integer between 1 and N are
690
** unmodified. ORDER BY terms that are integers outside the range of
691
** 1 through N generate an error. ORDER BY terms that are expressions
692
** are matched against result set expressions of compound SELECT
693
** beginning with the left-most SELECT and working toward the right.
694
** At the first match, the ORDER BY expression is transformed into
695
** the integer column number.
697
** Return the number of errors seen.
699
static int resolveCompoundOrderBy(
700
Parse *pParse, /* Parsing context. Leave error messages here */
701
Select *pSelect /* The SELECT statement containing the ORDER BY */
709
pOrderBy = pSelect->pOrderBy;
710
if( pOrderBy==0 ) return 0;
712
#if SQLITE_MAX_COLUMN
713
if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
714
sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
718
for(i=0; i<pOrderBy->nExpr; i++){
719
pOrderBy->a[i].done = 0;
722
while( pSelect->pPrior ){
723
pSelect->pPrior->pNext = pSelect;
724
pSelect = pSelect->pPrior;
726
while( pSelect && moreToDo ){
727
struct ExprList_item *pItem;
729
pEList = pSelect->pEList;
731
for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
734
if( pItem->done ) continue;
736
if( sqlite3ExprIsInteger(pE, &iCol) ){
737
if( iCol<=0 || iCol>pEList->nExpr ){
738
resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
742
iCol = resolveAsName(pParse, pEList, pE);
744
pDup = sqlite3ExprDup(db, pE, 0);
745
if( !db->mallocFailed ){
747
iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
749
sqlite3ExprDelete(db, pDup);
753
CollSeq *pColl = pE->pColl;
754
int flags = pE->flags & EP_ExpCollate;
755
sqlite3ExprDelete(db, pE);
756
pItem->pExpr = pE = sqlite3Expr(db, TK_INTEGER, 0);
757
if( pE==0 ) return 1;
759
pE->flags |= EP_IntValue | flags;
761
pItem->iCol = (u16)iCol;
767
pSelect = pSelect->pNext;
769
for(i=0; i<pOrderBy->nExpr; i++){
770
if( pOrderBy->a[i].done==0 ){
771
sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
772
"column in the result set", i+1);
780
** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
781
** the SELECT statement pSelect. If any term is reference to a
782
** result set expression (as determined by the ExprList.a.iCol field)
783
** then convert that term into a copy of the corresponding result set
786
** If any errors are detected, add an error message to pParse and
787
** return non-zero. Return zero if no errors are seen.
789
int sqlite3ResolveOrderGroupBy(
790
Parse *pParse, /* Parsing context. Leave error messages here */
791
Select *pSelect, /* The SELECT statement containing the clause */
792
ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
793
const char *zType /* "ORDER" or "GROUP" */
796
sqlite3 *db = pParse->db;
798
struct ExprList_item *pItem;
800
if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
801
#if SQLITE_MAX_COLUMN
802
if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
803
sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
807
pEList = pSelect->pEList;
808
assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
809
for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
811
if( pItem->iCol>pEList->nExpr ){
812
resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
815
resolveAlias(pParse, pEList, pItem->iCol-1, pItem->pExpr, zType);
822
** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
823
** The Name context of the SELECT statement is pNC. zType is either
824
** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
826
** This routine resolves each term of the clause into an expression.
827
** If the order-by term is an integer I between 1 and N (where N is the
828
** number of columns in the result set of the SELECT) then the expression
829
** in the resolution is a copy of the I-th result-set expression. If
830
** the order-by term is an identify that corresponds to the AS-name of
831
** a result-set expression, then the term resolves to a copy of the
832
** result-set expression. Otherwise, the expression is resolved in
833
** the usual way - using sqlite3ResolveExprNames().
835
** This routine returns the number of errors. If errors occur, then
836
** an appropriate error message might be left in pParse. (OOM errors
839
static int resolveOrderGroupBy(
840
NameContext *pNC, /* The name context of the SELECT statement */
841
Select *pSelect, /* The SELECT statement holding pOrderBy */
842
ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
843
const char *zType /* Either "ORDER" or "GROUP", as appropriate */
845
int i; /* Loop counter */
846
int iCol; /* Column number */
847
struct ExprList_item *pItem; /* A term of the ORDER BY clause */
848
Parse *pParse; /* Parsing context */
849
int nResult; /* Number of terms in the result set */
851
if( pOrderBy==0 ) return 0;
852
nResult = pSelect->pEList->nExpr;
853
pParse = pNC->pParse;
854
for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
855
Expr *pE = pItem->pExpr;
856
iCol = resolveAsName(pParse, pSelect->pEList, pE);
858
/* If an AS-name match is found, mark this ORDER BY column as being
859
** a copy of the iCol-th result-set column. The subsequent call to
860
** sqlite3ResolveOrderGroupBy() will convert the expression to a
861
** copy of the iCol-th result-set expression. */
862
pItem->iCol = (u16)iCol;
865
if( sqlite3ExprIsInteger(pE, &iCol) ){
866
/* The ORDER BY term is an integer constant. Again, set the column
867
** number so that sqlite3ResolveOrderGroupBy() will convert the
868
** order-by term to a copy of the result-set expression */
870
resolveOutOfRangeError(pParse, zType, i+1, nResult);
873
pItem->iCol = (u16)iCol;
877
/* Otherwise, treat the ORDER BY term as an ordinary expression */
879
if( sqlite3ResolveExprNames(pNC, pE) ){
883
return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
887
** Resolve names in the SELECT statement p and all of its descendents.
889
static int resolveSelectStep(Walker *pWalker, Select *p){
890
NameContext *pOuterNC; /* Context that contains this SELECT */
891
NameContext sNC; /* Name context of this SELECT */
892
int isCompound; /* True if p is a compound select */
893
int nCompound; /* Number of compound terms processed so far */
894
Parse *pParse; /* Parsing context */
895
ExprList *pEList; /* Result set expression list */
896
int i; /* Loop counter */
897
ExprList *pGroupBy; /* The GROUP BY clause */
898
Select *pLeftmost; /* Left-most of SELECT of a compound */
899
sqlite3 *db; /* Database connection */
903
if( p->selFlags & SF_Resolved ){
906
pOuterNC = pWalker->u.pNC;
907
pParse = pWalker->pParse;
910
/* Normally sqlite3SelectExpand() will be called first and will have
911
** already expanded this SELECT. However, if this is a subquery within
912
** an expression, sqlite3ResolveExprNames() will be called without a
913
** prior call to sqlite3SelectExpand(). When that happens, let
914
** sqlite3SelectPrep() do all of the processing for this SELECT.
915
** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
916
** this routine in the correct order.
918
if( (p->selFlags & SF_Expanded)==0 ){
919
sqlite3SelectPrep(pParse, p, pOuterNC);
920
return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
923
isCompound = p->pPrior!=0;
927
assert( (p->selFlags & SF_Expanded)!=0 );
928
assert( (p->selFlags & SF_Resolved)==0 );
929
p->selFlags |= SF_Resolved;
931
/* Resolve the expressions in the LIMIT and OFFSET clauses. These
932
** are not allowed to refer to any names, so pass an empty NameContext.
934
memset(&sNC, 0, sizeof(sNC));
936
if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
937
sqlite3ResolveExprNames(&sNC, p->pOffset) ){
941
/* Set up the local name-context to pass to sqlite3ResolveExprNames() to
942
** resolve the result-set expression list.
945
sNC.pSrcList = p->pSrc;
946
sNC.pNext = pOuterNC;
948
/* Resolve names in the result set. */
951
for(i=0; i<pEList->nExpr; i++){
952
Expr *pX = pEList->a[i].pExpr;
953
if( sqlite3ResolveExprNames(&sNC, pX) ){
958
/* Recursively resolve names in all subqueries
960
for(i=0; i<p->pSrc->nSrc; i++){
961
struct SrcList_item *pItem = &p->pSrc->a[i];
962
if( pItem->pSelect ){
963
const char *zSavedContext = pParse->zAuthContext;
964
if( pItem->zName ) pParse->zAuthContext = pItem->zName;
965
sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
966
pParse->zAuthContext = zSavedContext;
967
if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
971
/* If there are no aggregate functions in the result-set, and no GROUP BY
972
** expression, do not allow aggregates in any of the other expressions.
974
assert( (p->selFlags & SF_Aggregate)==0 );
975
pGroupBy = p->pGroupBy;
976
if( pGroupBy || sNC.hasAgg ){
977
p->selFlags |= SF_Aggregate;
982
/* If a HAVING clause is present, then there must be a GROUP BY clause.
984
if( p->pHaving && !pGroupBy ){
985
sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
989
/* Add the expression list to the name-context before parsing the
990
** other expressions in the SELECT statement. This is so that
991
** expressions in the WHERE clause (etc.) can refer to expressions by
992
** aliases in the result set.
994
** Minor point: If this is the case, then the expression will be
995
** re-evaluated for each reference to it.
997
sNC.pEList = p->pEList;
998
if( sqlite3ResolveExprNames(&sNC, p->pWhere) ||
999
sqlite3ResolveExprNames(&sNC, p->pHaving)
1004
/* The ORDER BY and GROUP BY clauses may not refer to terms in
1010
/* Process the ORDER BY clause for singleton SELECT statements.
1011
** The ORDER BY clause for compounds SELECT statements is handled
1012
** below, after all of the result-sets for all of the elements of
1013
** the compound have been resolved.
1015
if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1018
if( db->mallocFailed ){
1022
/* Resolve the GROUP BY clause. At the same time, make sure
1023
** the GROUP BY clause does not contain aggregate functions.
1026
struct ExprList_item *pItem;
1028
if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1031
for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1032
if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1033
sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1034
"the GROUP BY clause");
1040
/* Advance to the next term of the compound
1046
/* Resolve the ORDER BY on a compound SELECT after all terms of
1047
** the compound have been resolved.
1049
if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1057
** This routine walks an expression tree and resolves references to
1058
** table columns and result-set columns. At the same time, do error
1059
** checking on function usage and set a flag if any aggregate functions
1062
** To resolve table columns references we look for nodes (or subtrees) of the
1063
** form X.Y.Z or Y.Z or just Z where
1065
** X: The name of a database. Ex: "main" or "temp" or
1066
** the symbolic name assigned to an ATTACH-ed database.
1068
** Y: The name of a table in a FROM clause. Or in a trigger
1069
** one of the special names "old" or "new".
1071
** Z: The name of a column in table Y.
1073
** The node at the root of the subtree is modified as follows:
1075
** Expr.op Changed to TK_COLUMN
1076
** Expr.pTab Points to the Table object for X.Y
1077
** Expr.iColumn The column index in X.Y. -1 for the rowid.
1078
** Expr.iTable The VDBE cursor number for X.Y
1081
** To resolve result-set references, look for expression nodes of the
1082
** form Z (with no X and Y prefix) where the Z matches the right-hand
1083
** size of an AS clause in the result-set of a SELECT. The Z expression
1084
** is replaced by a copy of the left-hand side of the result-set expression.
1085
** Table-name and function resolution occurs on the substituted expression
1086
** tree. For example, in:
1088
** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1090
** The "x" term of the order by is replaced by "a+b" to render:
1092
** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1094
** Function calls are checked to make sure that the function is
1095
** defined and that the correct number of arguments are specified.
1096
** If the function is an aggregate function, then the pNC->hasAgg is
1097
** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1098
** If an expression contains aggregate functions then the EP_Agg
1099
** property on the expression is set.
1101
** An error message is left in pParse if anything is amiss. The number
1102
** if errors is returned.
1104
int sqlite3ResolveExprNames(
1105
NameContext *pNC, /* Namespace to resolve expressions in. */
1106
Expr *pExpr /* The expression to be analyzed. */
1111
if( pExpr==0 ) return 0;
1112
#if SQLITE_MAX_EXPR_DEPTH>0
1114
Parse *pParse = pNC->pParse;
1115
if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1118
pParse->nHeight += pExpr->nHeight;
1121
savedHasAgg = pNC->hasAgg;
1123
w.xExprCallback = resolveExprStep;
1124
w.xSelectCallback = resolveSelectStep;
1125
w.pParse = pNC->pParse;
1127
sqlite3WalkExpr(&w, pExpr);
1128
#if SQLITE_MAX_EXPR_DEPTH>0
1129
pNC->pParse->nHeight -= pExpr->nHeight;
1131
if( pNC->nErr>0 || w.pParse->nErr>0 ){
1132
ExprSetProperty(pExpr, EP_Error);
1135
ExprSetProperty(pExpr, EP_Agg);
1136
}else if( savedHasAgg ){
1139
return ExprHasProperty(pExpr, EP_Error);
1144
** Resolve all names in all expressions of a SELECT and in all
1145
** decendents of the SELECT, including compounds off of p->pPrior,
1146
** subqueries in expressions, and subqueries used as FROM clause
1149
** See sqlite3ResolveExprNames() for a description of the kinds of
1150
** transformations that occur.
1152
** All SELECT statements should have been expanded using
1153
** sqlite3SelectExpand() prior to invoking this routine.
1155
void sqlite3ResolveSelectNames(
1156
Parse *pParse, /* The parser context */
1157
Select *p, /* The SELECT statement being coded. */
1158
NameContext *pOuterNC /* Name context for parent SELECT statement */
1163
w.xExprCallback = resolveExprStep;
1164
w.xSelectCallback = resolveSelectStep;
1167
sqlite3WalkSelect(&w, p);