blob: c1e8cb7987a410f3a5840298e6c9090d65c84de1 [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.
drh7d10d5a2008-08-20 16:35:10 +000016*/
17#include "sqliteInt.h"
18#include <stdlib.h>
19#include <string.h>
20
21/*
drhed551b92012-08-23 19:46:11 +000022** Walk the expression tree pExpr and increase the aggregate function
23** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
24** This needs to occur when copying a TK_AGG_FUNCTION node from an
25** outer query into an inner subquery.
26**
27** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
28** is a helper function - a callback for the tree walker.
29*/
30static int incrAggDepth(Walker *pWalker, Expr *pExpr){
31 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.i;
32 return WRC_Continue;
33}
34static void incrAggFunctionDepth(Expr *pExpr, int N){
35 if( N>0 ){
36 Walker w;
37 memset(&w, 0, sizeof(w));
38 w.xExprCallback = incrAggDepth;
39 w.u.i = N;
40 sqlite3WalkExpr(&w, pExpr);
41 }
42}
43
44/*
drh8b213892008-08-29 02:14:02 +000045** Turn the pExpr expression into an alias for the iCol-th column of the
46** result set in pEList.
47**
48** If the result set column is a simple column reference, then this routine
49** makes an exact copy. But for any other kind of expression, this
50** routine make a copy of the result set column as the argument to the
51** TK_AS operator. The TK_AS operator causes the expression to be
52** evaluated just once and then reused for each alias.
53**
54** The reason for suppressing the TK_AS term when the expression is a simple
55** column reference is so that the column reference will be recognized as
56** usable by indices within the WHERE clause processing logic.
57**
drhe35463b2013-08-15 20:24:27 +000058** The TK_AS operator is inhibited if zType[0]=='G'. This means
drh8b213892008-08-29 02:14:02 +000059** that in a GROUP BY clause, the expression is evaluated twice. Hence:
60**
61** SELECT random()%5 AS x, count(*) FROM tab GROUP BY x
62**
63** Is equivalent to:
64**
65** SELECT random()%5 AS x, count(*) FROM tab GROUP BY random()%5
66**
67** The result of random()%5 in the GROUP BY clause is probably different
drhe35463b2013-08-15 20:24:27 +000068** from the result in the result-set. On the other hand Standard SQL does
69** not allow the GROUP BY clause to contain references to result-set columns.
70** So this should never come up in well-formed queries.
drhed551b92012-08-23 19:46:11 +000071**
drh0a8a4062012-12-07 18:38:16 +000072** If the reference is followed by a COLLATE operator, then make sure
73** the COLLATE operator is preserved. For example:
74**
75** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
76**
77** Should be transformed into:
78**
79** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
80**
drhed551b92012-08-23 19:46:11 +000081** The nSubquery parameter specifies how many levels of subquery the
82** alias is removed from the original expression. The usually value is
83** zero but it might be more if the alias is contained within a subquery
84** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
85** structures must be increased by the nSubquery amount.
drh8b213892008-08-29 02:14:02 +000086*/
87static void resolveAlias(
88 Parse *pParse, /* Parsing context */
89 ExprList *pEList, /* A result set */
90 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
91 Expr *pExpr, /* Transform this into an alias to the result set */
drhed551b92012-08-23 19:46:11 +000092 const char *zType, /* "GROUP" or "ORDER" or "" */
93 int nSubquery /* Number of subqueries that the label is moving */
drh8b213892008-08-29 02:14:02 +000094){
95 Expr *pOrig; /* The iCol-th column of the result set */
96 Expr *pDup; /* Copy of pOrig */
97 sqlite3 *db; /* The database connection */
98
99 assert( iCol>=0 && iCol<pEList->nExpr );
100 pOrig = pEList->a[iCol].pExpr;
101 assert( pOrig!=0 );
102 assert( pOrig->flags & EP_Resolved );
103 db = pParse->db;
drh0a8a4062012-12-07 18:38:16 +0000104 pDup = sqlite3ExprDup(db, pOrig, 0);
105 if( pDup==0 ) return;
drhb7916a72009-05-27 10:31:29 +0000106 if( pOrig->op!=TK_COLUMN && zType[0]!='G' ){
drhed551b92012-08-23 19:46:11 +0000107 incrAggFunctionDepth(pDup, nSubquery);
drh8b213892008-08-29 02:14:02 +0000108 pDup = sqlite3PExpr(pParse, TK_AS, pDup, 0, 0);
109 if( pDup==0 ) return;
drha4c3c872013-09-12 17:29:25 +0000110 ExprSetProperty(pDup, EP_Skip);
drh8b213892008-08-29 02:14:02 +0000111 if( pEList->a[iCol].iAlias==0 ){
drhea678832008-12-10 19:26:22 +0000112 pEList->a[iCol].iAlias = (u16)(++pParse->nAlias);
drh8b213892008-08-29 02:14:02 +0000113 }
114 pDup->iTable = pEList->a[iCol].iAlias;
115 }
drh0a8a4062012-12-07 18:38:16 +0000116 if( pExpr->op==TK_COLLATE ){
117 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
118 }
danf6963f92009-11-23 14:39:14 +0000119
120 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
121 ** prevents ExprDelete() from deleting the Expr structure itself,
122 ** allowing it to be repopulated by the memcpy() on the following line.
drhbd13d342012-12-07 21:02:47 +0000123 ** The pExpr->u.zToken might point into memory that will be freed by the
124 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
125 ** make a copy of the token before doing the sqlite3DbFree().
danf6963f92009-11-23 14:39:14 +0000126 */
127 ExprSetProperty(pExpr, EP_Static);
128 sqlite3ExprDelete(db, pExpr);
drh8b213892008-08-29 02:14:02 +0000129 memcpy(pExpr, pDup, sizeof(*pExpr));
drh0a8a4062012-12-07 18:38:16 +0000130 if( !ExprHasProperty(pExpr, EP_IntValue) && pExpr->u.zToken!=0 ){
131 assert( (pExpr->flags & (EP_Reduced|EP_TokenOnly))==0 );
132 pExpr->u.zToken = sqlite3DbStrDup(db, pExpr->u.zToken);
drhc5cd1242013-09-12 16:50:49 +0000133 pExpr->flags |= EP_MemToken;
drh0a8a4062012-12-07 18:38:16 +0000134 }
drh8b213892008-08-29 02:14:02 +0000135 sqlite3DbFree(db, pDup);
136}
137
drhe802c5d2011-10-18 18:10:40 +0000138
139/*
140** Return TRUE if the name zCol occurs anywhere in the USING clause.
141**
142** Return FALSE if the USING clause is NULL or if it does not contain
143** zCol.
144*/
145static int nameInUsingClause(IdList *pUsing, const char *zCol){
146 if( pUsing ){
147 int k;
148 for(k=0; k<pUsing->nId; k++){
149 if( sqlite3StrICmp(pUsing->a[k].zName, zCol)==0 ) return 1;
150 }
151 }
152 return 0;
153}
154
drh3e3f1a52013-01-03 00:45:56 +0000155/*
156** Subqueries stores the original database, table and column names for their
157** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
158** Check to see if the zSpan given to this routine matches the zDb, zTab,
159** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
160** match anything.
161*/
162int sqlite3MatchSpanName(
163 const char *zSpan,
164 const char *zCol,
165 const char *zTab,
166 const char *zDb
167){
168 int n;
169 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
drhdd1dd482013-02-26 12:57:42 +0000170 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
drh3e3f1a52013-01-03 00:45:56 +0000171 return 0;
172 }
173 zSpan += n+1;
174 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
drhdd1dd482013-02-26 12:57:42 +0000175 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
drh3e3f1a52013-01-03 00:45:56 +0000176 return 0;
177 }
178 zSpan += n+1;
179 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
180 return 0;
181 }
182 return 1;
183}
drhe802c5d2011-10-18 18:10:40 +0000184
drh8b213892008-08-29 02:14:02 +0000185/*
drh7d10d5a2008-08-20 16:35:10 +0000186** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
187** that name in the set of source tables in pSrcList and make the pExpr
188** expression node refer back to that source column. The following changes
189** are made to pExpr:
190**
191** pExpr->iDb Set the index in db->aDb[] of the database X
192** (even if X is implied).
193** pExpr->iTable Set to the cursor number for the table obtained
194** from pSrcList.
195** pExpr->pTab Points to the Table structure of X.Y (even if
196** X and/or Y are implied.)
197** pExpr->iColumn Set to the column number within the table.
198** pExpr->op Set to TK_COLUMN.
199** pExpr->pLeft Any expression this points to is deleted
200** pExpr->pRight Any expression this points to is deleted.
201**
drhb7916a72009-05-27 10:31:29 +0000202** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10 +0000203** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29 +0000204** can be used. The zTable variable is the name of the table (the "Y"). This
205** value can be NULL if zDb is also NULL. If zTable is NULL it
drh7d10d5a2008-08-20 16:35:10 +0000206** means that the form of the name is Z and that columns from any table
207** can be used.
208**
209** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59 +0000210** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10 +0000211*/
212static int lookupName(
213 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29 +0000214 const char *zDb, /* Name of the database containing table, or NULL */
215 const char *zTab, /* Name of table containing column, or NULL */
216 const char *zCol, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10 +0000217 NameContext *pNC, /* The name context used to resolve the name */
218 Expr *pExpr /* Make this EXPR node point to the selected column */
219){
drhed551b92012-08-23 19:46:11 +0000220 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +0000221 int cnt = 0; /* Number of matching column names */
222 int cntTab = 0; /* Number of matching table names */
drhed551b92012-08-23 19:46:11 +0000223 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10 +0000224 sqlite3 *db = pParse->db; /* The database connection */
225 struct SrcList_item *pItem; /* Use for looping over pSrcList items */
226 struct SrcList_item *pMatch = 0; /* The matching pSrcList item */
227 NameContext *pTopNC = pNC; /* First namecontext in the list */
228 Schema *pSchema = 0; /* Schema of the expression */
dan2bd93512009-08-31 08:22:46 +0000229 int isTrigger = 0;
drh7d10d5a2008-08-20 16:35:10 +0000230
drhb7916a72009-05-27 10:31:29 +0000231 assert( pNC ); /* the name context cannot be NULL. */
232 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drhc5cd1242013-09-12 16:50:49 +0000233 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10 +0000234
235 /* Initialize the node to no-match */
236 pExpr->iTable = -1;
237 pExpr->pTab = 0;
drh33e619f2009-05-28 01:00:55 +0000238 ExprSetIrreducible(pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000239
drh8f25d182012-12-19 02:36:45 +0000240 /* Translate the schema name in zDb into a pointer to the corresponding
241 ** schema. If not found, pSchema will remain NULL and nothing will match
242 ** resulting in an appropriate error message toward the end of this routine
243 */
244 if( zDb ){
drh1e7d43c2013-08-02 14:18:18 +0000245 testcase( pNC->ncFlags & NC_PartIdx );
246 testcase( pNC->ncFlags & NC_IsCheck );
247 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
248 /* Silently ignore database qualifiers inside CHECK constraints and partial
249 ** indices. Do not raise errors because that might break legacy and
250 ** because it does not hurt anything to just ignore the database name. */
251 zDb = 0;
252 }else{
253 for(i=0; i<db->nDb; i++){
254 assert( db->aDb[i].zName );
255 if( sqlite3StrICmp(db->aDb[i].zName,zDb)==0 ){
256 pSchema = db->aDb[i].pSchema;
257 break;
258 }
drh8f25d182012-12-19 02:36:45 +0000259 }
260 }
261 }
262
drh7d10d5a2008-08-20 16:35:10 +0000263 /* Start at the inner-most context and move outward until a match is found */
264 while( pNC && cnt==0 ){
265 ExprList *pEList;
266 SrcList *pSrcList = pNC->pSrcList;
267
268 if( pSrcList ){
269 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
270 Table *pTab;
drh7d10d5a2008-08-20 16:35:10 +0000271 Column *pCol;
272
273 pTab = pItem->pTab;
drhf4366202008-08-25 12:14:08 +0000274 assert( pTab!=0 && pTab->zName!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000275 assert( pTab->nCol>0 );
drh8f25d182012-12-19 02:36:45 +0000276 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_NestedFrom)!=0 ){
drh8f25d182012-12-19 02:36:45 +0000277 int hit = 0;
drh928d9c62013-02-07 09:33:56 +0000278 pEList = pItem->pSelect->pEList;
drh8f25d182012-12-19 02:36:45 +0000279 for(j=0; j<pEList->nExpr; j++){
drh3e3f1a52013-01-03 00:45:56 +0000280 if( sqlite3MatchSpanName(pEList->a[j].zSpan, zCol, zTab, zDb) ){
drh8f25d182012-12-19 02:36:45 +0000281 cnt++;
282 cntTab = 2;
283 pMatch = pItem;
284 pExpr->iColumn = j;
drh38b384a2013-01-03 17:34:28 +0000285 hit = 1;
drh8f25d182012-12-19 02:36:45 +0000286 }
287 }
288 if( hit || zTab==0 ) continue;
289 }
drhc75e09c2013-01-03 16:54:20 +0000290 if( zDb && pTab->pSchema!=pSchema ){
291 continue;
292 }
drh7d10d5a2008-08-20 16:35:10 +0000293 if( zTab ){
drh8f25d182012-12-19 02:36:45 +0000294 const char *zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
295 assert( zTabName!=0 );
296 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
297 continue;
drh7d10d5a2008-08-20 16:35:10 +0000298 }
299 }
300 if( 0==(cntTab++) ){
drh7d10d5a2008-08-20 16:35:10 +0000301 pMatch = pItem;
302 }
303 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
304 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
drhe802c5d2011-10-18 18:10:40 +0000305 /* If there has been exactly one prior match and this match
306 ** is for the right-hand table of a NATURAL JOIN or is in a
307 ** USING clause, then skip this match.
308 */
309 if( cnt==1 ){
310 if( pItem->jointype & JT_NATURAL ) continue;
311 if( nameInUsingClause(pItem->pUsing, zCol) ) continue;
312 }
drh7d10d5a2008-08-20 16:35:10 +0000313 cnt++;
drh7d10d5a2008-08-20 16:35:10 +0000314 pMatch = pItem;
drh7d10d5a2008-08-20 16:35:10 +0000315 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
shanecf697392009-06-01 16:53:09 +0000316 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
drh7d10d5a2008-08-20 16:35:10 +0000317 break;
318 }
319 }
320 }
drh8f25d182012-12-19 02:36:45 +0000321 if( pMatch ){
322 pExpr->iTable = pMatch->iCursor;
323 pExpr->pTab = pMatch->pTab;
324 pSchema = pExpr->pTab->pSchema;
325 }
326 } /* if( pSrcList ) */
drh7d10d5a2008-08-20 16:35:10 +0000327
328#ifndef SQLITE_OMIT_TRIGGER
329 /* If we have not already resolved the name, then maybe
330 ** it is a new.* or old.* trigger argument reference
331 */
dan165921a2009-08-28 18:53:45 +0000332 if( zDb==0 && zTab!=0 && cnt==0 && pParse->pTriggerTab!=0 ){
dan65a7cd12009-09-01 12:16:01 +0000333 int op = pParse->eTriggerOp;
drh7d10d5a2008-08-20 16:35:10 +0000334 Table *pTab = 0;
dan65a7cd12009-09-01 12:16:01 +0000335 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
336 if( op!=TK_DELETE && sqlite3StrICmp("new",zTab) == 0 ){
dan165921a2009-08-28 18:53:45 +0000337 pExpr->iTable = 1;
338 pTab = pParse->pTriggerTab;
dan65a7cd12009-09-01 12:16:01 +0000339 }else if( op!=TK_INSERT && sqlite3StrICmp("old",zTab)==0 ){
dan165921a2009-08-28 18:53:45 +0000340 pExpr->iTable = 0;
341 pTab = pParse->pTriggerTab;
drh7d10d5a2008-08-20 16:35:10 +0000342 }
343
344 if( pTab ){
345 int iCol;
drh7d10d5a2008-08-20 16:35:10 +0000346 pSchema = pTab->pSchema;
347 cntTab++;
drh25e978d2009-12-29 23:39:04 +0000348 for(iCol=0; iCol<pTab->nCol; iCol++){
349 Column *pCol = &pTab->aCol[iCol];
350 if( sqlite3StrICmp(pCol->zName, zCol)==0 ){
351 if( iCol==pTab->iPKey ){
352 iCol = -1;
drh7d10d5a2008-08-20 16:35:10 +0000353 }
drh25e978d2009-12-29 23:39:04 +0000354 break;
drh7d10d5a2008-08-20 16:35:10 +0000355 }
356 }
drh25e978d2009-12-29 23:39:04 +0000357 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) ){
drhc79c7612010-01-01 18:57:48 +0000358 iCol = -1; /* IMP: R-44911-55124 */
drh25e978d2009-12-29 23:39:04 +0000359 }
dan2bd93512009-08-31 08:22:46 +0000360 if( iCol<pTab->nCol ){
361 cnt++;
362 if( iCol<0 ){
363 pExpr->affinity = SQLITE_AFF_INTEGER;
dan2832ad42009-08-31 15:27:27 +0000364 }else if( pExpr->iTable==0 ){
365 testcase( iCol==31 );
366 testcase( iCol==32 );
367 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
danbb5f1682009-11-27 12:12:34 +0000368 }else{
369 testcase( iCol==31 );
370 testcase( iCol==32 );
371 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
dan2bd93512009-08-31 08:22:46 +0000372 }
shanecea72b22009-09-07 04:38:36 +0000373 pExpr->iColumn = (i16)iCol;
dan2bd93512009-08-31 08:22:46 +0000374 pExpr->pTab = pTab;
375 isTrigger = 1;
376 }
drh7d10d5a2008-08-20 16:35:10 +0000377 }
378 }
379#endif /* !defined(SQLITE_OMIT_TRIGGER) */
380
381 /*
382 ** Perhaps the name is a reference to the ROWID
383 */
384 if( cnt==0 && cntTab==1 && sqlite3IsRowid(zCol) ){
385 cnt = 1;
drhc79c7612010-01-01 18:57:48 +0000386 pExpr->iColumn = -1; /* IMP: R-44911-55124 */
drh7d10d5a2008-08-20 16:35:10 +0000387 pExpr->affinity = SQLITE_AFF_INTEGER;
388 }
389
390 /*
391 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
392 ** might refer to an result-set alias. This happens, for example, when
393 ** we are resolving names in the WHERE clause of the following command:
394 **
395 ** SELECT a+b AS x FROM table WHERE x<10;
396 **
397 ** In cases like this, replace pExpr with a copy of the expression that
398 ** forms the result set entry ("a+b" in the example) and return immediately.
399 ** Note that the expression in the result set should have already been
400 ** resolved by the time the WHERE clause is resolved.
drhe35463b2013-08-15 20:24:27 +0000401 **
402 ** The ability to use an output result-set column in the WHERE, GROUP BY,
403 ** or HAVING clauses, or as part of a larger expression in the ORDRE BY
404 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
405 ** is supported for backwards compatibility only. TO DO: Issue a warning
406 ** on sqlite3_log() whenever the capability is used.
drh7d10d5a2008-08-20 16:35:10 +0000407 */
drha3a5bd92013-04-13 19:59:58 +0000408 if( (pEList = pNC->pEList)!=0
409 && zTab==0
drhe35463b2013-08-15 20:24:27 +0000410 && cnt==0
drha3a5bd92013-04-13 19:59:58 +0000411 ){
drh7d10d5a2008-08-20 16:35:10 +0000412 for(j=0; j<pEList->nExpr; j++){
413 char *zAs = pEList->a[j].zName;
414 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh8b213892008-08-29 02:14:02 +0000415 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10 +0000416 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
danielk19776ab3a2e2009-02-19 14:39:25 +0000417 assert( pExpr->x.pList==0 );
418 assert( pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10 +0000419 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25 +0000420 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10 +0000421 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59 +0000422 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000423 }
drhed551b92012-08-23 19:46:11 +0000424 resolveAlias(pParse, pEList, j, pExpr, "", nSubquery);
drh7d10d5a2008-08-20 16:35:10 +0000425 cnt = 1;
426 pMatch = 0;
427 assert( zTab==0 && zDb==0 );
drhb7916a72009-05-27 10:31:29 +0000428 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10 +0000429 }
430 }
431 }
432
433 /* Advance to the next name context. The loop will exit when either
434 ** we have a match (cnt>0) or when we run out of name contexts.
435 */
436 if( cnt==0 ){
437 pNC = pNC->pNext;
drhed551b92012-08-23 19:46:11 +0000438 nSubquery++;
drh7d10d5a2008-08-20 16:35:10 +0000439 }
440 }
441
442 /*
443 ** If X and Y are NULL (in other words if only the column name Z is
444 ** supplied) and the value of Z is enclosed in double-quotes, then
445 ** Z is a string literal if it doesn't match any column names. In that
446 ** case, we need to return right away and not make any changes to
447 ** pExpr.
448 **
449 ** Because no reference was made to outer contexts, the pNC->nRef
450 ** fields are not changed in any context.
451 */
drh24fb6272009-05-01 21:13:36 +0000452 if( cnt==0 && zTab==0 && ExprHasProperty(pExpr,EP_DblQuoted) ){
drh7d10d5a2008-08-20 16:35:10 +0000453 pExpr->op = TK_STRING;
drh1885d1c2008-10-19 21:03:27 +0000454 pExpr->pTab = 0;
drhf7828b52009-06-15 23:15:59 +0000455 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000456 }
457
458 /*
459 ** cnt==0 means there was not match. cnt>1 means there were two or
460 ** more matches. Either way, we have an error.
461 */
462 if( cnt!=1 ){
463 const char *zErr;
464 zErr = cnt==0 ? "no such column" : "ambiguous column name";
465 if( zDb ){
466 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
467 }else if( zTab ){
468 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
469 }else{
470 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
471 }
dan1db95102010-06-28 10:15:19 +0000472 pParse->checkSchema = 1;
drh7d10d5a2008-08-20 16:35:10 +0000473 pTopNC->nErr++;
474 }
475
476 /* If a column from a table in pSrcList is referenced, then record
477 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
478 ** bit 0 to be set. Column 1 sets bit 1. And so forth. If the
479 ** column number is greater than the number of bits in the bitmask
480 ** then set the high-order bit of the bitmask.
481 */
danielk19772d2e7bd2009-02-24 10:14:40 +0000482 if( pExpr->iColumn>=0 && pMatch!=0 ){
483 int n = pExpr->iColumn;
484 testcase( n==BMS-1 );
485 if( n>=BMS ){
486 n = BMS-1;
drh7d10d5a2008-08-20 16:35:10 +0000487 }
danielk19772d2e7bd2009-02-24 10:14:40 +0000488 assert( pMatch->iCursor==pExpr->iTable );
489 pMatch->colUsed |= ((Bitmask)1)<<n;
drh7d10d5a2008-08-20 16:35:10 +0000490 }
491
drh7d10d5a2008-08-20 16:35:10 +0000492 /* Clean up and return
493 */
drh7d10d5a2008-08-20 16:35:10 +0000494 sqlite3ExprDelete(db, pExpr->pLeft);
495 pExpr->pLeft = 0;
496 sqlite3ExprDelete(db, pExpr->pRight);
497 pExpr->pRight = 0;
dan2bd93512009-08-31 08:22:46 +0000498 pExpr->op = (isTrigger ? TK_TRIGGER : TK_COLUMN);
drhb7916a72009-05-27 10:31:29 +0000499lookupname_end:
drh7d10d5a2008-08-20 16:35:10 +0000500 if( cnt==1 ){
501 assert( pNC!=0 );
drha3a5bd92013-04-13 19:59:58 +0000502 if( pExpr->op!=TK_AS ){
503 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
504 }
drh7d10d5a2008-08-20 16:35:10 +0000505 /* Increment the nRef value on all name contexts from TopNC up to
506 ** the point where the name matched. */
507 for(;;){
508 assert( pTopNC!=0 );
509 pTopNC->nRef++;
510 if( pTopNC==pNC ) break;
511 pTopNC = pTopNC->pNext;
512 }
drhf7828b52009-06-15 23:15:59 +0000513 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000514 } else {
drhf7828b52009-06-15 23:15:59 +0000515 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +0000516 }
517}
518
519/*
danf7b0b0a2009-10-19 15:52:32 +0000520** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34 +0000521** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32 +0000522*/
523Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
524 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
525 if( p ){
526 struct SrcList_item *pItem = &pSrc->a[iSrc];
527 p->pTab = pItem->pTab;
528 p->iTable = pItem->iCursor;
529 if( p->pTab->iPKey==iCol ){
530 p->iColumn = -1;
531 }else{
drh8677d302009-11-04 13:17:14 +0000532 p->iColumn = (ynVar)iCol;
drh7caba662010-04-08 15:01:44 +0000533 testcase( iCol==BMS );
534 testcase( iCol==BMS-1 );
danf7b0b0a2009-10-19 15:52:32 +0000535 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
536 }
537 ExprSetProperty(p, EP_Resolved);
538 }
539 return p;
540}
541
542/*
drh3780be12013-07-31 19:05:22 +0000543** Report an error that an expression is not valid for a partial index WHERE
544** clause.
545*/
546static void notValidPartIdxWhere(
547 Parse *pParse, /* Leave error message here */
548 NameContext *pNC, /* The name context */
549 const char *zMsg /* Type of error */
550){
551 if( (pNC->ncFlags & NC_PartIdx)!=0 ){
552 sqlite3ErrorMsg(pParse, "%s prohibited in partial index WHERE clauses",
553 zMsg);
554 }
555}
556
557#ifndef SQLITE_OMIT_CHECK
558/*
559** Report an error that an expression is not valid for a CHECK constraint.
560*/
561static void notValidCheckConstraint(
562 Parse *pParse, /* Leave error message here */
563 NameContext *pNC, /* The name context */
564 const char *zMsg /* Type of error */
565){
566 if( (pNC->ncFlags & NC_IsCheck)!=0 ){
567 sqlite3ErrorMsg(pParse,"%s prohibited in CHECK constraints", zMsg);
568 }
569}
570#else
571# define notValidCheckConstraint(P,N,M)
572#endif
573
drhcca9f3d2013-09-06 15:23:29 +0000574/*
575** Expression p should encode a floating point value between 1.0 and 0.0.
576** Return 1024 times this value. Or return -1 if p is not a floating point
577** value between 1.0 and 0.0.
578*/
579static int exprProbability(Expr *p){
580 double r = -1.0;
581 if( p->op!=TK_FLOAT ) return -1;
582 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
drh09328c02013-09-11 14:34:58 +0000583 assert( r>=0.0 );
584 if( r>1.0 ) return -1;
drhcca9f3d2013-09-06 15:23:29 +0000585 return (int)(r*1000.0);
586}
drh3780be12013-07-31 19:05:22 +0000587
588/*
drh7d10d5a2008-08-20 16:35:10 +0000589** This routine is callback for sqlite3WalkExpr().
590**
591** Resolve symbolic names into TK_COLUMN operators for the current
592** node in the expression tree. Return 0 to continue the search down
593** the tree or 2 to abort the tree walk.
594**
595** This routine also does error checking and name resolution for
596** function names. The operator for aggregate functions is changed
597** to TK_AGG_FUNCTION.
598*/
599static int resolveExprStep(Walker *pWalker, Expr *pExpr){
600 NameContext *pNC;
601 Parse *pParse;
602
drh7d10d5a2008-08-20 16:35:10 +0000603 pNC = pWalker->u.pNC;
604 assert( pNC!=0 );
605 pParse = pNC->pParse;
606 assert( pParse==pWalker->pParse );
607
drhc5cd1242013-09-12 16:50:49 +0000608 if( ExprHasProperty(pExpr, EP_Resolved) ) return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10 +0000609 ExprSetProperty(pExpr, EP_Resolved);
610#ifndef NDEBUG
611 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
612 SrcList *pSrcList = pNC->pSrcList;
613 int i;
614 for(i=0; i<pNC->pSrcList->nSrc; i++){
615 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
616 }
617 }
618#endif
619 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35 +0000620
shane273f6192008-10-10 04:34:16 +0000621#if defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY)
drh41204f12008-10-06 13:54:35 +0000622 /* The special operator TK_ROW means use the rowid for the first
623 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
624 ** clause processing on UPDATE and DELETE statements.
625 */
626 case TK_ROW: {
627 SrcList *pSrcList = pNC->pSrcList;
628 struct SrcList_item *pItem;
629 assert( pSrcList && pSrcList->nSrc==1 );
630 pItem = pSrcList->a;
631 pExpr->op = TK_COLUMN;
632 pExpr->pTab = pItem->pTab;
633 pExpr->iTable = pItem->iCursor;
634 pExpr->iColumn = -1;
635 pExpr->affinity = SQLITE_AFF_INTEGER;
636 break;
637 }
shane273f6192008-10-10 04:34:16 +0000638#endif /* defined(SQLITE_ENABLE_UPDATE_DELETE_LIMIT) && !defined(SQLITE_OMIT_SUBQUERY) */
drh41204f12008-10-06 13:54:35 +0000639
drh7d10d5a2008-08-20 16:35:10 +0000640 /* A lone identifier is the name of a column.
641 */
642 case TK_ID: {
drhf7828b52009-06-15 23:15:59 +0000643 return lookupName(pParse, 0, 0, pExpr->u.zToken, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000644 }
645
646 /* A table name and column name: ID.ID
647 ** Or a database, table and column: ID.ID.ID
648 */
649 case TK_DOT: {
drhb7916a72009-05-27 10:31:29 +0000650 const char *zColumn;
651 const char *zTable;
652 const char *zDb;
drh7d10d5a2008-08-20 16:35:10 +0000653 Expr *pRight;
654
655 /* if( pSrcList==0 ) break; */
656 pRight = pExpr->pRight;
657 if( pRight->op==TK_ID ){
drhb7916a72009-05-27 10:31:29 +0000658 zDb = 0;
drh33e619f2009-05-28 01:00:55 +0000659 zTable = pExpr->pLeft->u.zToken;
660 zColumn = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000661 }else{
662 assert( pRight->op==TK_DOT );
drh33e619f2009-05-28 01:00:55 +0000663 zDb = pExpr->pLeft->u.zToken;
664 zTable = pRight->pLeft->u.zToken;
665 zColumn = pRight->pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000666 }
drhf7828b52009-06-15 23:15:59 +0000667 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000668 }
669
670 /* Resolve function names
671 */
672 case TK_CONST_FUNC:
673 case TK_FUNCTION: {
danielk19776ab3a2e2009-02-19 14:39:25 +0000674 ExprList *pList = pExpr->x.pList; /* The argument list */
675 int n = pList ? pList->nExpr : 0; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:10 +0000676 int no_such_func = 0; /* True if no such function exists */
677 int wrong_num_args = 0; /* True if wrong number of arguments */
678 int is_agg = 0; /* True if is an aggregate function */
679 int auth; /* Authorization to use the function */
680 int nId; /* Number of characters in function name */
681 const char *zId; /* The function name. */
682 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:22 +0000683 u8 enc = ENC(pParse->db); /* The database encoding */
drh7d10d5a2008-08-20 16:35:10 +0000684
drh73c0fdc2009-06-15 18:32:36 +0000685 testcase( pExpr->op==TK_CONST_FUNC );
danielk19776ab3a2e2009-02-19 14:39:25 +0000686 assert( !ExprHasProperty(pExpr, EP_xIsSelect) );
drh3780be12013-07-31 19:05:22 +0000687 notValidPartIdxWhere(pParse, pNC, "functions");
drh33e619f2009-05-28 01:00:55 +0000688 zId = pExpr->u.zToken;
drhb7916a72009-05-27 10:31:29 +0000689 nId = sqlite3Strlen30(zId);
drh7d10d5a2008-08-20 16:35:10 +0000690 pDef = sqlite3FindFunction(pParse->db, zId, nId, n, enc, 0);
691 if( pDef==0 ){
drh89d5d6a2012-04-07 00:09:21 +0000692 pDef = sqlite3FindFunction(pParse->db, zId, nId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:10 +0000693 if( pDef==0 ){
694 no_such_func = 1;
695 }else{
696 wrong_num_args = 1;
697 }
698 }else{
699 is_agg = pDef->xFunc==0;
drhcca9f3d2013-09-06 15:23:29 +0000700 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
drha4c3c872013-09-12 17:29:25 +0000701 ExprSetProperty(pExpr, EP_Unlikely|EP_Skip);
drhcca9f3d2013-09-06 15:23:29 +0000702 if( n==2 ){
703 pExpr->iTable = exprProbability(pList->a[1].pExpr);
704 if( pExpr->iTable<0 ){
drhaae0f9e2013-09-11 11:38:58 +0000705 sqlite3ErrorMsg(pParse, "second argument to likelihood() must be a "
706 "constant between 0.0 and 1.0");
drhcca9f3d2013-09-06 15:23:29 +0000707 pNC->nErr++;
708 }
709 }else{
drhabfa6d52013-09-11 03:53:22 +0000710 pExpr->iTable = 62; /* TUNING: Default 2nd arg to unlikely() is 0.0625 */
drhcca9f3d2013-09-06 15:23:29 +0000711 }
712 }
drh7d10d5a2008-08-20 16:35:10 +0000713 }
714#ifndef SQLITE_OMIT_AUTHORIZATION
715 if( pDef ){
716 auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0, pDef->zName, 0);
717 if( auth!=SQLITE_OK ){
718 if( auth==SQLITE_DENY ){
719 sqlite3ErrorMsg(pParse, "not authorized to use function: %s",
720 pDef->zName);
721 pNC->nErr++;
722 }
723 pExpr->op = TK_NULL;
724 return WRC_Prune;
725 }
726 }
727#endif
drha51009b2012-05-21 19:11:25 +0000728 if( is_agg && (pNC->ncFlags & NC_AllowAgg)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000729 sqlite3ErrorMsg(pParse, "misuse of aggregate function %.*s()", nId,zId);
730 pNC->nErr++;
731 is_agg = 0;
drhddd1fc72013-01-08 12:48:10 +0000732 }else if( no_such_func && pParse->db->init.busy==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000733 sqlite3ErrorMsg(pParse, "no such function: %.*s", nId, zId);
734 pNC->nErr++;
735 }else if( wrong_num_args ){
736 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %.*s()",
737 nId, zId);
738 pNC->nErr++;
739 }
drha51009b2012-05-21 19:11:25 +0000740 if( is_agg ) pNC->ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000741 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:10 +0000742 if( is_agg ){
743 NameContext *pNC2 = pNC;
744 pExpr->op = TK_AGG_FUNCTION;
745 pExpr->op2 = 0;
746 while( pNC2 && !sqlite3FunctionUsesThisSrc(pExpr, pNC2->pSrcList) ){
747 pExpr->op2++;
748 pNC2 = pNC2->pNext;
749 }
750 if( pNC2 ) pNC2->ncFlags |= NC_HasAgg;
751 pNC->ncFlags |= NC_AllowAgg;
752 }
drh7d10d5a2008-08-20 16:35:10 +0000753 /* FIX ME: Compute pExpr->affinity based on the expected return
754 ** type of the function
755 */
756 return WRC_Prune;
757 }
758#ifndef SQLITE_OMIT_SUBQUERY
759 case TK_SELECT:
drh73c0fdc2009-06-15 18:32:36 +0000760 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
drh7d10d5a2008-08-20 16:35:10 +0000761#endif
762 case TK_IN: {
drh73c0fdc2009-06-15 18:32:36 +0000763 testcase( pExpr->op==TK_IN );
danielk19776ab3a2e2009-02-19 14:39:25 +0000764 if( ExprHasProperty(pExpr, EP_xIsSelect) ){
drh7d10d5a2008-08-20 16:35:10 +0000765 int nRef = pNC->nRef;
drh3780be12013-07-31 19:05:22 +0000766 notValidCheckConstraint(pParse, pNC, "subqueries");
767 notValidPartIdxWhere(pParse, pNC, "subqueries");
danielk19776ab3a2e2009-02-19 14:39:25 +0000768 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
drh7d10d5a2008-08-20 16:35:10 +0000769 assert( pNC->nRef>=nRef );
770 if( nRef!=pNC->nRef ){
771 ExprSetProperty(pExpr, EP_VarSelect);
772 }
773 }
774 break;
775 }
drh7d10d5a2008-08-20 16:35:10 +0000776 case TK_VARIABLE: {
drh3780be12013-07-31 19:05:22 +0000777 notValidCheckConstraint(pParse, pNC, "parameters");
778 notValidPartIdxWhere(pParse, pNC, "parameters");
drh7d10d5a2008-08-20 16:35:10 +0000779 break;
780 }
drh7d10d5a2008-08-20 16:35:10 +0000781 }
782 return (pParse->nErr || pParse->db->mallocFailed) ? WRC_Abort : WRC_Continue;
783}
784
785/*
786** pEList is a list of expressions which are really the result set of the
787** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
788** This routine checks to see if pE is a simple identifier which corresponds
789** to the AS-name of one of the terms of the expression list. If it is,
790** this routine return an integer between 1 and N where N is the number of
791** elements in pEList, corresponding to the matching entry. If there is
792** no match, or if pE is not a simple identifier, then this routine
793** return 0.
794**
795** pEList has been resolved. pE has not.
796*/
797static int resolveAsName(
798 Parse *pParse, /* Parsing context for error messages */
799 ExprList *pEList, /* List of expressions to scan */
800 Expr *pE /* Expression we are trying to match */
801){
802 int i; /* Loop counter */
803
shanecf697392009-06-01 16:53:09 +0000804 UNUSED_PARAMETER(pParse);
805
drh73c0fdc2009-06-15 18:32:36 +0000806 if( pE->op==TK_ID ){
drh33e619f2009-05-28 01:00:55 +0000807 char *zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:10 +0000808 for(i=0; i<pEList->nExpr; i++){
809 char *zAs = pEList->a[i].zName;
810 if( zAs!=0 && sqlite3StrICmp(zAs, zCol)==0 ){
drh7d10d5a2008-08-20 16:35:10 +0000811 return i+1;
812 }
813 }
drh7d10d5a2008-08-20 16:35:10 +0000814 }
815 return 0;
816}
817
818/*
819** pE is a pointer to an expression which is a single term in the
820** ORDER BY of a compound SELECT. The expression has not been
821** name resolved.
822**
823** At the point this routine is called, we already know that the
824** ORDER BY term is not an integer index into the result set. That
825** case is handled by the calling routine.
826**
827** Attempt to match pE against result set columns in the left-most
828** SELECT statement. Return the index i of the matching column,
829** as an indication to the caller that it should sort by the i-th column.
830** The left-most column is 1. In other words, the value returned is the
831** same integer value that would be used in the SQL statement to indicate
832** the column.
833**
834** If there is no match, return 0. Return -1 if an error occurs.
835*/
836static int resolveOrderByTermToExprList(
837 Parse *pParse, /* Parsing context for error messages */
838 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
839 Expr *pE /* The specific ORDER BY term */
840){
841 int i; /* Loop counter */
842 ExprList *pEList; /* The columns of the result set */
843 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:31 +0000844 sqlite3 *db; /* Database connection */
845 int rc; /* Return code from subprocedures */
846 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:10 +0000847
848 assert( sqlite3ExprIsInteger(pE, &i)==0 );
849 pEList = pSelect->pEList;
850
851 /* Resolve all names in the ORDER BY term expression
852 */
853 memset(&nc, 0, sizeof(nc));
854 nc.pParse = pParse;
855 nc.pSrcList = pSelect->pSrc;
856 nc.pEList = pEList;
drha51009b2012-05-21 19:11:25 +0000857 nc.ncFlags = NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +0000858 nc.nErr = 0;
drha7564662010-02-22 19:32:31 +0000859 db = pParse->db;
860 savedSuppErr = db->suppressErr;
861 db->suppressErr = 1;
862 rc = sqlite3ResolveExprNames(&nc, pE);
863 db->suppressErr = savedSuppErr;
864 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:10 +0000865
866 /* Try to match the ORDER BY expression against an expression
867 ** in the result set. Return an 1-based index of the matching
868 ** result-set entry.
869 */
870 for(i=0; i<pEList->nExpr; i++){
drh619a1302013-08-01 13:04:46 +0000871 if( sqlite3ExprCompare(pEList->a[i].pExpr, pE, -1)<2 ){
drh7d10d5a2008-08-20 16:35:10 +0000872 return i+1;
873 }
874 }
875
876 /* If no match, return 0. */
877 return 0;
878}
879
880/*
881** Generate an ORDER BY or GROUP BY term out-of-range error.
882*/
883static void resolveOutOfRangeError(
884 Parse *pParse, /* The error context into which to write the error */
885 const char *zType, /* "ORDER" or "GROUP" */
886 int i, /* The index (1-based) of the term out of range */
887 int mx /* Largest permissible value of i */
888){
889 sqlite3ErrorMsg(pParse,
890 "%r %s BY term out of range - should be "
891 "between 1 and %d", i, zType, mx);
892}
893
894/*
895** Analyze the ORDER BY clause in a compound SELECT statement. Modify
896** each term of the ORDER BY clause is a constant integer between 1
897** and N where N is the number of columns in the compound SELECT.
898**
899** ORDER BY terms that are already an integer between 1 and N are
900** unmodified. ORDER BY terms that are integers outside the range of
901** 1 through N generate an error. ORDER BY terms that are expressions
902** are matched against result set expressions of compound SELECT
903** beginning with the left-most SELECT and working toward the right.
904** At the first match, the ORDER BY expression is transformed into
905** the integer column number.
906**
907** Return the number of errors seen.
908*/
909static int resolveCompoundOrderBy(
910 Parse *pParse, /* Parsing context. Leave error messages here */
911 Select *pSelect /* The SELECT statement containing the ORDER BY */
912){
913 int i;
914 ExprList *pOrderBy;
915 ExprList *pEList;
916 sqlite3 *db;
917 int moreToDo = 1;
918
919 pOrderBy = pSelect->pOrderBy;
920 if( pOrderBy==0 ) return 0;
921 db = pParse->db;
922#if SQLITE_MAX_COLUMN
923 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
924 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
925 return 1;
926 }
927#endif
928 for(i=0; i<pOrderBy->nExpr; i++){
929 pOrderBy->a[i].done = 0;
930 }
931 pSelect->pNext = 0;
932 while( pSelect->pPrior ){
933 pSelect->pPrior->pNext = pSelect;
934 pSelect = pSelect->pPrior;
935 }
936 while( pSelect && moreToDo ){
937 struct ExprList_item *pItem;
938 moreToDo = 0;
939 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +0000940 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10 +0000941 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
942 int iCol = -1;
943 Expr *pE, *pDup;
944 if( pItem->done ) continue;
drhbd13d342012-12-07 21:02:47 +0000945 pE = sqlite3ExprSkipCollate(pItem->pExpr);
drh7d10d5a2008-08-20 16:35:10 +0000946 if( sqlite3ExprIsInteger(pE, &iCol) ){
drh73c0fdc2009-06-15 18:32:36 +0000947 if( iCol<=0 || iCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +0000948 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr);
949 return 1;
950 }
951 }else{
952 iCol = resolveAsName(pParse, pEList, pE);
953 if( iCol==0 ){
danielk19776ab3a2e2009-02-19 14:39:25 +0000954 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:10 +0000955 if( !db->mallocFailed ){
956 assert(pDup);
957 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
958 }
959 sqlite3ExprDelete(db, pDup);
960 }
drh7d10d5a2008-08-20 16:35:10 +0000961 }
962 if( iCol>0 ){
drhbd13d342012-12-07 21:02:47 +0000963 /* Convert the ORDER BY term into an integer column number iCol,
964 ** taking care to preserve the COLLATE clause if it exists */
965 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
966 if( pNew==0 ) return 1;
967 pNew->flags |= EP_IntValue;
968 pNew->u.iValue = iCol;
969 if( pItem->pExpr==pE ){
970 pItem->pExpr = pNew;
971 }else{
972 assert( pItem->pExpr->op==TK_COLLATE );
973 assert( pItem->pExpr->pLeft==pE );
974 pItem->pExpr->pLeft = pNew;
975 }
drh7d10d5a2008-08-20 16:35:10 +0000976 sqlite3ExprDelete(db, pE);
drh4b3ac732011-12-10 23:18:32 +0000977 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +0000978 pItem->done = 1;
979 }else{
980 moreToDo = 1;
981 }
982 }
983 pSelect = pSelect->pNext;
984 }
985 for(i=0; i<pOrderBy->nExpr; i++){
986 if( pOrderBy->a[i].done==0 ){
987 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
988 "column in the result set", i+1);
989 return 1;
990 }
991 }
992 return 0;
993}
994
995/*
996** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
997** the SELECT statement pSelect. If any term is reference to a
drhe35463b2013-08-15 20:24:27 +0000998** result set expression (as determined by the ExprList.a.iOrderByCol field)
drh7d10d5a2008-08-20 16:35:10 +0000999** then convert that term into a copy of the corresponding result set
1000** column.
1001**
1002** If any errors are detected, add an error message to pParse and
1003** return non-zero. Return zero if no errors are seen.
1004*/
1005int sqlite3ResolveOrderGroupBy(
1006 Parse *pParse, /* Parsing context. Leave error messages here */
1007 Select *pSelect, /* The SELECT statement containing the clause */
1008 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
1009 const char *zType /* "ORDER" or "GROUP" */
1010){
1011 int i;
1012 sqlite3 *db = pParse->db;
1013 ExprList *pEList;
1014 struct ExprList_item *pItem;
1015
1016 if( pOrderBy==0 || pParse->db->mallocFailed ) return 0;
1017#if SQLITE_MAX_COLUMN
1018 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1019 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1020 return 1;
1021 }
1022#endif
1023 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:29 +00001024 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:10 +00001025 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drh4b3ac732011-12-10 23:18:32 +00001026 if( pItem->iOrderByCol ){
1027 if( pItem->iOrderByCol>pEList->nExpr ){
drh7d10d5a2008-08-20 16:35:10 +00001028 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr);
1029 return 1;
1030 }
drhed551b92012-08-23 19:46:11 +00001031 resolveAlias(pParse, pEList, pItem->iOrderByCol-1, pItem->pExpr, zType,0);
drh7d10d5a2008-08-20 16:35:10 +00001032 }
1033 }
1034 return 0;
1035}
1036
1037/*
1038** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1039** The Name context of the SELECT statement is pNC. zType is either
1040** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1041**
1042** This routine resolves each term of the clause into an expression.
1043** If the order-by term is an integer I between 1 and N (where N is the
1044** number of columns in the result set of the SELECT) then the expression
1045** in the resolution is a copy of the I-th result-set expression. If
drh26080d92013-08-15 14:27:42 +00001046** the order-by term is an identifier that corresponds to the AS-name of
drh7d10d5a2008-08-20 16:35:10 +00001047** a result-set expression, then the term resolves to a copy of the
1048** result-set expression. Otherwise, the expression is resolved in
1049** the usual way - using sqlite3ResolveExprNames().
1050**
1051** This routine returns the number of errors. If errors occur, then
1052** an appropriate error message might be left in pParse. (OOM errors
1053** excepted.)
1054*/
1055static int resolveOrderGroupBy(
1056 NameContext *pNC, /* The name context of the SELECT statement */
1057 Select *pSelect, /* The SELECT statement holding pOrderBy */
1058 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
1059 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
1060){
drh70331cd2012-04-27 01:09:06 +00001061 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10 +00001062 int iCol; /* Column number */
1063 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
1064 Parse *pParse; /* Parsing context */
1065 int nResult; /* Number of terms in the result set */
1066
1067 if( pOrderBy==0 ) return 0;
1068 nResult = pSelect->pEList->nExpr;
1069 pParse = pNC->pParse;
1070 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1071 Expr *pE = pItem->pExpr;
drhe35463b2013-08-15 20:24:27 +00001072 Expr *pE2 = sqlite3ExprSkipCollate(pE);
drh0af16ab2013-08-15 22:40:21 +00001073 if( zType[0]!='G' ){
1074 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1075 if( iCol>0 ){
1076 /* If an AS-name match is found, mark this ORDER BY column as being
1077 ** a copy of the iCol-th result-set column. The subsequent call to
1078 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1079 ** copy of the iCol-th result-set expression. */
1080 pItem->iOrderByCol = (u16)iCol;
1081 continue;
1082 }
drh7d10d5a2008-08-20 16:35:10 +00001083 }
drhe35463b2013-08-15 20:24:27 +00001084 if( sqlite3ExprIsInteger(pE2, &iCol) ){
drh7d10d5a2008-08-20 16:35:10 +00001085 /* The ORDER BY term is an integer constant. Again, set the column
1086 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1087 ** order-by term to a copy of the result-set expression */
drh85d641f2012-12-07 23:23:53 +00001088 if( iCol<1 || iCol>0xffff ){
drh7d10d5a2008-08-20 16:35:10 +00001089 resolveOutOfRangeError(pParse, zType, i+1, nResult);
1090 return 1;
1091 }
drh4b3ac732011-12-10 23:18:32 +00001092 pItem->iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:10 +00001093 continue;
1094 }
1095
1096 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drh4b3ac732011-12-10 23:18:32 +00001097 pItem->iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:10 +00001098 if( sqlite3ResolveExprNames(pNC, pE) ){
1099 return 1;
1100 }
drh70331cd2012-04-27 01:09:06 +00001101 for(j=0; j<pSelect->pEList->nExpr; j++){
drh619a1302013-08-01 13:04:46 +00001102 if( sqlite3ExprCompare(pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
drh70331cd2012-04-27 01:09:06 +00001103 pItem->iOrderByCol = j+1;
1104 }
1105 }
drh7d10d5a2008-08-20 16:35:10 +00001106 }
1107 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1108}
1109
1110/*
1111** Resolve names in the SELECT statement p and all of its descendents.
1112*/
1113static int resolveSelectStep(Walker *pWalker, Select *p){
1114 NameContext *pOuterNC; /* Context that contains this SELECT */
1115 NameContext sNC; /* Name context of this SELECT */
1116 int isCompound; /* True if p is a compound select */
1117 int nCompound; /* Number of compound terms processed so far */
1118 Parse *pParse; /* Parsing context */
1119 ExprList *pEList; /* Result set expression list */
1120 int i; /* Loop counter */
1121 ExprList *pGroupBy; /* The GROUP BY clause */
1122 Select *pLeftmost; /* Left-most of SELECT of a compound */
1123 sqlite3 *db; /* Database connection */
1124
1125
drh0a846f92008-08-25 17:23:29 +00001126 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:10 +00001127 if( p->selFlags & SF_Resolved ){
1128 return WRC_Prune;
1129 }
1130 pOuterNC = pWalker->u.pNC;
1131 pParse = pWalker->pParse;
1132 db = pParse->db;
1133
1134 /* Normally sqlite3SelectExpand() will be called first and will have
1135 ** already expanded this SELECT. However, if this is a subquery within
1136 ** an expression, sqlite3ResolveExprNames() will be called without a
1137 ** prior call to sqlite3SelectExpand(). When that happens, let
1138 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1139 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1140 ** this routine in the correct order.
1141 */
1142 if( (p->selFlags & SF_Expanded)==0 ){
1143 sqlite3SelectPrep(pParse, p, pOuterNC);
1144 return (pParse->nErr || db->mallocFailed) ? WRC_Abort : WRC_Prune;
1145 }
1146
1147 isCompound = p->pPrior!=0;
1148 nCompound = 0;
1149 pLeftmost = p;
1150 while( p ){
1151 assert( (p->selFlags & SF_Expanded)!=0 );
1152 assert( (p->selFlags & SF_Resolved)==0 );
1153 p->selFlags |= SF_Resolved;
1154
1155 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1156 ** are not allowed to refer to any names, so pass an empty NameContext.
1157 */
1158 memset(&sNC, 0, sizeof(sNC));
1159 sNC.pParse = pParse;
1160 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ||
1161 sqlite3ResolveExprNames(&sNC, p->pOffset) ){
1162 return WRC_Abort;
1163 }
1164
drh7d10d5a2008-08-20 16:35:10 +00001165 /* Recursively resolve names in all subqueries
1166 */
1167 for(i=0; i<p->pSrc->nSrc; i++){
1168 struct SrcList_item *pItem = &p->pSrc->a[i];
1169 if( pItem->pSelect ){
danda79cf02011-07-08 16:10:54 +00001170 NameContext *pNC; /* Used to iterate name contexts */
1171 int nRef = 0; /* Refcount for pOuterNC and outer contexts */
drh7d10d5a2008-08-20 16:35:10 +00001172 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:54 +00001173
1174 /* Count the total number of references to pOuterNC and all of its
1175 ** parent contexts. After resolving references to expressions in
1176 ** pItem->pSelect, check if this value has changed. If so, then
1177 ** SELECT statement pItem->pSelect must be correlated. Set the
1178 ** pItem->isCorrelated flag if this is the case. */
1179 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef += pNC->nRef;
1180
drh7d10d5a2008-08-20 16:35:10 +00001181 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drhcd2b5612008-12-09 14:03:22 +00001182 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:10 +00001183 pParse->zAuthContext = zSavedContext;
1184 if( pParse->nErr || db->mallocFailed ) return WRC_Abort;
danda79cf02011-07-08 16:10:54 +00001185
1186 for(pNC=pOuterNC; pNC; pNC=pNC->pNext) nRef -= pNC->nRef;
1187 assert( pItem->isCorrelated==0 && nRef<=0 );
1188 pItem->isCorrelated = (nRef!=0);
drh7d10d5a2008-08-20 16:35:10 +00001189 }
1190 }
1191
drh92689d22012-12-18 16:07:08 +00001192 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1193 ** resolve the result-set expression list.
1194 */
1195 sNC.ncFlags = NC_AllowAgg;
1196 sNC.pSrcList = p->pSrc;
1197 sNC.pNext = pOuterNC;
1198
1199 /* Resolve names in the result set. */
1200 pEList = p->pEList;
1201 assert( pEList!=0 );
1202 for(i=0; i<pEList->nExpr; i++){
1203 Expr *pX = pEList->a[i].pExpr;
1204 if( sqlite3ResolveExprNames(&sNC, pX) ){
1205 return WRC_Abort;
1206 }
1207 }
1208
drh7d10d5a2008-08-20 16:35:10 +00001209 /* If there are no aggregate functions in the result-set, and no GROUP BY
1210 ** expression, do not allow aggregates in any of the other expressions.
1211 */
1212 assert( (p->selFlags & SF_Aggregate)==0 );
1213 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:25 +00001214 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh7d10d5a2008-08-20 16:35:10 +00001215 p->selFlags |= SF_Aggregate;
1216 }else{
drha51009b2012-05-21 19:11:25 +00001217 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001218 }
1219
1220 /* If a HAVING clause is present, then there must be a GROUP BY clause.
1221 */
1222 if( p->pHaving && !pGroupBy ){
1223 sqlite3ErrorMsg(pParse, "a GROUP BY clause is required before HAVING");
1224 return WRC_Abort;
1225 }
1226
drh26080d92013-08-15 14:27:42 +00001227 /* Add the output column list to the name-context before parsing the
drh7d10d5a2008-08-20 16:35:10 +00001228 ** other expressions in the SELECT statement. This is so that
1229 ** expressions in the WHERE clause (etc.) can refer to expressions by
1230 ** aliases in the result set.
1231 **
1232 ** Minor point: If this is the case, then the expression will be
1233 ** re-evaluated for each reference to it.
1234 */
1235 sNC.pEList = p->pEList;
drh58a450c2013-05-16 01:02:45 +00001236 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
drha3a5bd92013-04-13 19:59:58 +00001237 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10 +00001238
1239 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1240 ** outer queries
1241 */
1242 sNC.pNext = 0;
drha51009b2012-05-21 19:11:25 +00001243 sNC.ncFlags |= NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:10 +00001244
1245 /* Process the ORDER BY clause for singleton SELECT statements.
1246 ** The ORDER BY clause for compounds SELECT statements is handled
1247 ** below, after all of the result-sets for all of the elements of
1248 ** the compound have been resolved.
1249 */
1250 if( !isCompound && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER") ){
1251 return WRC_Abort;
1252 }
1253 if( db->mallocFailed ){
1254 return WRC_Abort;
1255 }
1256
1257 /* Resolve the GROUP BY clause. At the same time, make sure
1258 ** the GROUP BY clause does not contain aggregate functions.
1259 */
1260 if( pGroupBy ){
1261 struct ExprList_item *pItem;
1262
1263 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1264 return WRC_Abort;
1265 }
1266 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1267 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1268 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1269 "the GROUP BY clause");
1270 return WRC_Abort;
1271 }
1272 }
1273 }
1274
1275 /* Advance to the next term of the compound
1276 */
1277 p = p->pPrior;
1278 nCompound++;
1279 }
1280
1281 /* Resolve the ORDER BY on a compound SELECT after all terms of
1282 ** the compound have been resolved.
1283 */
1284 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1285 return WRC_Abort;
1286 }
1287
1288 return WRC_Prune;
1289}
1290
1291/*
1292** This routine walks an expression tree and resolves references to
1293** table columns and result-set columns. At the same time, do error
1294** checking on function usage and set a flag if any aggregate functions
1295** are seen.
1296**
1297** To resolve table columns references we look for nodes (or subtrees) of the
1298** form X.Y.Z or Y.Z or just Z where
1299**
1300** X: The name of a database. Ex: "main" or "temp" or
1301** the symbolic name assigned to an ATTACH-ed database.
1302**
1303** Y: The name of a table in a FROM clause. Or in a trigger
1304** one of the special names "old" or "new".
1305**
1306** Z: The name of a column in table Y.
1307**
1308** The node at the root of the subtree is modified as follows:
1309**
1310** Expr.op Changed to TK_COLUMN
1311** Expr.pTab Points to the Table object for X.Y
1312** Expr.iColumn The column index in X.Y. -1 for the rowid.
1313** Expr.iTable The VDBE cursor number for X.Y
1314**
1315**
1316** To resolve result-set references, look for expression nodes of the
1317** form Z (with no X and Y prefix) where the Z matches the right-hand
1318** size of an AS clause in the result-set of a SELECT. The Z expression
1319** is replaced by a copy of the left-hand side of the result-set expression.
1320** Table-name and function resolution occurs on the substituted expression
1321** tree. For example, in:
1322**
1323** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1324**
1325** The "x" term of the order by is replaced by "a+b" to render:
1326**
1327** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1328**
1329** Function calls are checked to make sure that the function is
1330** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:25 +00001331** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:10 +00001332** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1333** If an expression contains aggregate functions then the EP_Agg
1334** property on the expression is set.
1335**
1336** An error message is left in pParse if anything is amiss. The number
1337** if errors is returned.
1338*/
1339int sqlite3ResolveExprNames(
1340 NameContext *pNC, /* Namespace to resolve expressions in. */
1341 Expr *pExpr /* The expression to be analyzed. */
1342){
drha51009b2012-05-21 19:11:25 +00001343 u8 savedHasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001344 Walker w;
1345
1346 if( pExpr==0 ) return 0;
1347#if SQLITE_MAX_EXPR_DEPTH>0
1348 {
1349 Parse *pParse = pNC->pParse;
1350 if( sqlite3ExprCheckHeight(pParse, pExpr->nHeight+pNC->pParse->nHeight) ){
1351 return 1;
1352 }
1353 pParse->nHeight += pExpr->nHeight;
1354 }
1355#endif
drha51009b2012-05-21 19:11:25 +00001356 savedHasAgg = pNC->ncFlags & NC_HasAgg;
1357 pNC->ncFlags &= ~NC_HasAgg;
drhaa87f9a2013-04-25 00:57:10 +00001358 memset(&w, 0, sizeof(w));
drh7d10d5a2008-08-20 16:35:10 +00001359 w.xExprCallback = resolveExprStep;
1360 w.xSelectCallback = resolveSelectStep;
1361 w.pParse = pNC->pParse;
1362 w.u.pNC = pNC;
1363 sqlite3WalkExpr(&w, pExpr);
1364#if SQLITE_MAX_EXPR_DEPTH>0
1365 pNC->pParse->nHeight -= pExpr->nHeight;
1366#endif
drhfd773cf2009-05-29 14:39:07 +00001367 if( pNC->nErr>0 || w.pParse->nErr>0 ){
drh7d10d5a2008-08-20 16:35:10 +00001368 ExprSetProperty(pExpr, EP_Error);
1369 }
drha51009b2012-05-21 19:11:25 +00001370 if( pNC->ncFlags & NC_HasAgg ){
drh7d10d5a2008-08-20 16:35:10 +00001371 ExprSetProperty(pExpr, EP_Agg);
1372 }else if( savedHasAgg ){
drha51009b2012-05-21 19:11:25 +00001373 pNC->ncFlags |= NC_HasAgg;
drh7d10d5a2008-08-20 16:35:10 +00001374 }
1375 return ExprHasProperty(pExpr, EP_Error);
1376}
drh7d10d5a2008-08-20 16:35:10 +00001377
1378
1379/*
1380** Resolve all names in all expressions of a SELECT and in all
1381** decendents of the SELECT, including compounds off of p->pPrior,
1382** subqueries in expressions, and subqueries used as FROM clause
1383** terms.
1384**
1385** See sqlite3ResolveExprNames() for a description of the kinds of
1386** transformations that occur.
1387**
1388** All SELECT statements should have been expanded using
1389** sqlite3SelectExpand() prior to invoking this routine.
1390*/
1391void sqlite3ResolveSelectNames(
1392 Parse *pParse, /* The parser context */
1393 Select *p, /* The SELECT statement being coded. */
1394 NameContext *pOuterNC /* Name context for parent SELECT statement */
1395){
1396 Walker w;
1397
drh0a846f92008-08-25 17:23:29 +00001398 assert( p!=0 );
drhaa87f9a2013-04-25 00:57:10 +00001399 memset(&w, 0, sizeof(w));
drh0a846f92008-08-25 17:23:29 +00001400 w.xExprCallback = resolveExprStep;
1401 w.xSelectCallback = resolveSelectStep;
1402 w.pParse = pParse;
1403 w.u.pNC = pOuterNC;
1404 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:10 +00001405}
drh3780be12013-07-31 19:05:22 +00001406
1407/*
1408** Resolve names in expressions that can only reference a single table:
1409**
1410** * CHECK constraints
1411** * WHERE clauses on partial indices
1412**
1413** The Expr.iTable value for Expr.op==TK_COLUMN nodes of the expression
1414** is set to -1 and the Expr.iColumn value is set to the column number.
1415**
1416** Any errors cause an error message to be set in pParse.
1417*/
1418void sqlite3ResolveSelfReference(
1419 Parse *pParse, /* Parsing context */
1420 Table *pTab, /* The table being referenced */
1421 int type, /* NC_IsCheck or NC_PartIdx */
1422 Expr *pExpr, /* Expression to resolve. May be NULL. */
1423 ExprList *pList /* Expression list to resolve. May be NUL. */
1424){
1425 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
1426 NameContext sNC; /* Name context for pParse->pNewTable */
1427 int i; /* Loop counter */
1428
1429 assert( type==NC_IsCheck || type==NC_PartIdx );
1430 memset(&sNC, 0, sizeof(sNC));
1431 memset(&sSrc, 0, sizeof(sSrc));
1432 sSrc.nSrc = 1;
1433 sSrc.a[0].zName = pTab->zName;
1434 sSrc.a[0].pTab = pTab;
1435 sSrc.a[0].iCursor = -1;
1436 sNC.pParse = pParse;
1437 sNC.pSrcList = &sSrc;
1438 sNC.ncFlags = type;
1439 if( sqlite3ResolveExprNames(&sNC, pExpr) ) return;
1440 if( pList ){
1441 for(i=0; i<pList->nExpr; i++){
1442 if( sqlite3ResolveExprNames(&sNC, pList->a[i].pExpr) ){
1443 return;
1444 }
1445 }
1446 }
1447}