1/*
2** 2008 August 18
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
7** May you do good and not evil.
8** May you find forgiveness for yourself and forgive others.
9** May you share freely, never taking more than you give.
10**
11*************************************************************************
12**
13** This file contains routines used for walking the parser tree and
14** resolve all identifiers by associating them with a particular
15** table and column.
16*/
17#include "sqliteInt.h"
18
19/*
20** Magic table number to mean the EXCLUDED table in an UPSERT statement.
21*/
22#define EXCLUDED_TABLE_NUMBER 2
23
24/*
25** Walk the expression tree pExpr and increase the aggregate function
26** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
27** This needs to occur when copying a TK_AGG_FUNCTION node from an
28** outer query into an inner subquery.
29**
30** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
31** is a helper function - a callback for the tree walker.
32**
33** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
34*/
35static int incrAggDepth(Walker *pWalker, Expr *pExpr){
36 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
37 return WRC_Continue;
38}
39static void incrAggFunctionDepth(Expr *pExpr, int N){
40 if( N>0 ){
41 Walker w;
42 memset(&w, 0, sizeof(w));
43 w.xExprCallback = incrAggDepth;
44 w.u.n = N;
45 sqlite3WalkExpr(&w, pExpr);
46 }
47}
48
49/*
50** Turn the pExpr expression into an alias for the iCol-th column of the
51** result set in pEList.
52**
53** If the reference is followed by a COLLATE operator, then make sure
54** the COLLATE operator is preserved. For example:
55**
56** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
57**
58** Should be transformed into:
59**
60** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
61**
62** The nSubquery parameter specifies how many levels of subquery the
63** alias is removed from the original expression. The usual value is
64** zero but it might be more if the alias is contained within a subquery
65** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
66** structures must be increased by the nSubquery amount.
67*/
68static void resolveAlias(
69 Parse *pParse, /* Parsing context */
70 ExprList *pEList, /* A result set */
71 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
72 Expr *pExpr, /* Transform this into an alias to the result set */
73 int nSubquery /* Number of subqueries that the label is moving */
74){
75 Expr *pOrig; /* The iCol-th column of the result set */
76 Expr *pDup; /* Copy of pOrig */
77 sqlite3 *db; /* The database connection */
78
79 assert( iCol>=0 && iCol<pEList->nExpr );
80 pOrig = pEList->a[iCol].pExpr;
81 assert( pOrig!=0 );
82 db = pParse->db;
83 pDup = sqlite3ExprDup(db, pOrig, 0);
84 if( db->mallocFailed ){
85 sqlite3ExprDelete(db, pDup);
86 pDup = 0;
87 }else{
88 Expr temp;
89 incrAggFunctionDepth(pDup, nSubquery);
90 if( pExpr->op==TK_COLLATE ){
91 assert( !ExprHasProperty(pExpr, EP_IntValue) );
92 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
93 }
94 memcpy(&temp, pDup, sizeof(Expr));
95 memcpy(pDup, pExpr, sizeof(Expr));
96 memcpy(pExpr, &temp, sizeof(Expr));
97 if( ExprHasProperty(pExpr, EP_WinFunc) ){
98 if( ALWAYS(pExpr->y.pWin!=0) ){
99 pExpr->y.pWin->pOwner = pExpr;
100 }
101 }
102 sqlite3ExprDeferredDelete(pParse, pDup);
103 }
104}
105
106/*
107** Subqueries stores the original database, table and column names for their
108** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
109** Check to see if the zSpan given to this routine matches the zDb, zTab,
110** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
111** match anything.
112*/
113int sqlite3MatchEName(
114 const struct ExprList_item *pItem,
115 const char *zCol,
116 const char *zTab,
117 const char *zDb
118){
119 int n;
120 const char *zSpan;
121 if( pItem->fg.eEName!=ENAME_TAB ) return 0;
122 zSpan = pItem->zEName;
123 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
124 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
125 return 0;
126 }
127 zSpan += n+1;
128 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
129 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
130 return 0;
131 }
132 zSpan += n+1;
133 if( zCol && sqlite3StrICmp(zSpan, zCol)!=0 ){
134 return 0;
135 }
136 return 1;
137}
138
139/*
140** Return TRUE if the double-quoted string mis-feature should be supported.
141*/
142static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
143 if( db->init.busy ) return 1; /* Always support for legacy schemas */
144 if( pTopNC->ncFlags & NC_IsDDL ){
145 /* Currently parsing a DDL statement */
146 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
147 return 1;
148 }
149 return (db->flags & SQLITE_DqsDDL)!=0;
150 }else{
151 /* Currently parsing a DML statement */
152 return (db->flags & SQLITE_DqsDML)!=0;
153 }
154}
155
156/*
157** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
158** return the appropriate colUsed mask.
159*/
160Bitmask sqlite3ExprColUsed(Expr *pExpr){
161 int n;
162 Table *pExTab;
163
164 n = pExpr->iColumn;
165 assert( ExprUseYTab(pExpr) );
166 pExTab = pExpr->y.pTab;
167 assert( pExTab!=0 );
168 if( (pExTab->tabFlags & TF_HasGenerated)!=0
169 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
170 ){
171 testcase( pExTab->nCol==BMS-1 );
172 testcase( pExTab->nCol==BMS );
173 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
174 }else{
175 testcase( n==BMS-1 );
176 testcase( n==BMS );
177 if( n>=BMS ) n = BMS-1;
178 return ((Bitmask)1)<<n;
179 }
180}
181
182/*
183** Create a new expression term for the column specified by pMatch and
184** iColumn. Append this new expression term to the FULL JOIN Match set
185** in *ppList. Create a new *ppList if this is the first term in the
186** set.
187*/
188static void extendFJMatch(
189 Parse *pParse, /* Parsing context */
190 ExprList **ppList, /* ExprList to extend */
191 SrcItem *pMatch, /* Source table containing the column */
192 i16 iColumn /* The column number */
193){
194 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
195 if( pNew ){
196 pNew->iTable = pMatch->iCursor;
197 pNew->iColumn = iColumn;
198 pNew->y.pTab = pMatch->pTab;
199 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
200 ExprSetProperty(pNew, EP_CanBeNull);
201 *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
202 }
203}
204
205/*
206** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
207** that name in the set of source tables in pSrcList and make the pExpr
208** expression node refer back to that source column. The following changes
209** are made to pExpr:
210**
211** pExpr->iDb Set the index in db->aDb[] of the database X
212** (even if X is implied).
213** pExpr->iTable Set to the cursor number for the table obtained
214** from pSrcList.
215** pExpr->y.pTab Points to the Table structure of X.Y (even if
216** X and/or Y are implied.)
217** pExpr->iColumn Set to the column number within the table.
218** pExpr->op Set to TK_COLUMN.
219** pExpr->pLeft Any expression this points to is deleted
220** pExpr->pRight Any expression this points to is deleted.
221**
222** The zDb variable is the name of the database (the "X"). This value may be
223** NULL meaning that name is of the form Y.Z or Z. Any available database
224** can be used. The zTable variable is the name of the table (the "Y"). This
225** value can be NULL if zDb is also NULL. If zTable is NULL it
226** means that the form of the name is Z and that columns from any table
227** can be used.
228**
229** If the name cannot be resolved unambiguously, leave an error message
230** in pParse and return WRC_Abort. Return WRC_Prune on success.
231*/
232static int lookupName(
233 Parse *pParse, /* The parsing context */
234 const char *zDb, /* Name of the database containing table, or NULL */
235 const char *zTab, /* Name of table containing column, or NULL */
236 const char *zCol, /* Name of the column. */
237 NameContext *pNC, /* The name context used to resolve the name */
238 Expr *pExpr /* Make this EXPR node point to the selected column */
239){
240 int i, j; /* Loop counters */
241 int cnt = 0; /* Number of matching column names */
242 int cntTab = 0; /* Number of matching table names */
243 int nSubquery = 0; /* How many levels of subquery */
244 sqlite3 *db = pParse->db; /* The database connection */
245 SrcItem *pItem; /* Use for looping over pSrcList items */
246 SrcItem *pMatch = 0; /* The matching pSrcList item */
247 NameContext *pTopNC = pNC; /* First namecontext in the list */
248 Schema *pSchema = 0; /* Schema of the expression */
249 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
250 Table *pTab = 0; /* Table holding the row */
251 Column *pCol; /* A column of pTab */
252 ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */
253
254 assert( pNC ); /* the name context cannot be NULL. */
255 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
256 assert( zDb==0 || zTab!=0 );
257 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
258
259 /* Initialize the node to no-match */
260 pExpr->iTable = -1;
261 ExprSetVVAProperty(pExpr, EP_NoReduce);
262
263 /* Translate the schema name in zDb into a pointer to the corresponding
264 ** schema. If not found, pSchema will remain NULL and nothing will match
265 ** resulting in an appropriate error message toward the end of this routine
266 */
267 if( zDb ){
268 testcase( pNC->ncFlags & NC_PartIdx );
269 testcase( pNC->ncFlags & NC_IsCheck );
270 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
271 /* Silently ignore database qualifiers inside CHECK constraints and
272 ** partial indices. Do not raise errors because that might break
273 ** legacy and because it does not hurt anything to just ignore the
274 ** database name. */
275 zDb = 0;
276 }else{
277 for(i=0; i<db->nDb; i++){
278 assert( db->aDb[i].zDbSName );
279 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
280 pSchema = db->aDb[i].pSchema;
281 break;
282 }
283 }
284 if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
285 /* This branch is taken when the main database has been renamed
286 ** using SQLITE_DBCONFIG_MAINDBNAME. */
287 pSchema = db->aDb[0].pSchema;
288 zDb = db->aDb[0].zDbSName;
289 }
290 }
291 }
292
293 /* Start at the inner-most context and move outward until a match is found */
294 assert( pNC && cnt==0 );
295 do{
296 ExprList *pEList;
297 SrcList *pSrcList = pNC->pSrcList;
298
299 if( pSrcList ){
300 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
301 u8 hCol;
302 pTab = pItem->pTab;
303 assert( pTab!=0 && pTab->zName!=0 );
304 assert( pTab->nCol>0 || pParse->nErr );
305 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
306 if( pItem->fg.isNestedFrom ){
307 /* In this case, pItem is a subquery that has been formed from a
308 ** parenthesized subset of the FROM clause terms. Example:
309 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
310 ** \_________________________/
311 ** This pItem -------------^
312 */
313 int hit = 0;
314 assert( pItem->pSelect!=0 );
315 pEList = pItem->pSelect->pEList;
316 assert( pEList!=0 );
317 assert( pEList->nExpr==pTab->nCol );
318 for(j=0; j<pEList->nExpr; j++){
319 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb) ){
320 continue;
321 }
322 if( cnt>0 ){
323 if( pItem->fg.isUsing==0
324 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
325 ){
326 /* Two or more tables have the same column name which is
327 ** not joined by USING. This is an error. Signal as much
328 ** by clearing pFJMatch and letting cnt go above 1. */
329 sqlite3ExprListDelete(db, pFJMatch);
330 pFJMatch = 0;
331 }else
332 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
333 /* An INNER or LEFT JOIN. Use the left-most table */
334 continue;
335 }else
336 if( (pItem->fg.jointype & JT_LEFT)==0 ){
337 /* A RIGHT JOIN. Use the right-most table */
338 cnt = 0;
339 sqlite3ExprListDelete(db, pFJMatch);
340 pFJMatch = 0;
341 }else{
342 /* For a FULL JOIN, we must construct a coalesce() func */
343 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
344 }
345 }
346 cnt++;
347 cntTab = 2;
348 pMatch = pItem;
349 pExpr->iColumn = j;
350 pEList->a[j].fg.bUsed = 1;
351 hit = 1;
352 if( pEList->a[j].fg.bUsingTerm ) break;
353 }
354 if( hit || zTab==0 ) continue;
355 }
356 assert( zDb==0 || zTab!=0 );
357 if( zTab ){
358 const char *zTabName;
359 if( zDb ){
360 if( pTab->pSchema!=pSchema ) continue;
361 if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
362 }
363 zTabName = pItem->zAlias ? pItem->zAlias : pTab->zName;
364 assert( zTabName!=0 );
365 if( sqlite3StrICmp(zTabName, zTab)!=0 ){
366 continue;
367 }
368 assert( ExprUseYTab(pExpr) );
369 if( IN_RENAME_OBJECT && pItem->zAlias ){
370 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
371 }
372 }
373 hCol = sqlite3StrIHash(zCol);
374 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
375 if( pCol->hName==hCol
376 && sqlite3StrICmp(pCol->zCnName, zCol)==0
377 ){
378 if( cnt>0 ){
379 if( pItem->fg.isUsing==0
380 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
381 ){
382 /* Two or more tables have the same column name which is
383 ** not joined by USING. This is an error. Signal as much
384 ** by clearing pFJMatch and letting cnt go above 1. */
385 sqlite3ExprListDelete(db, pFJMatch);
386 pFJMatch = 0;
387 }else
388 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
389 /* An INNER or LEFT JOIN. Use the left-most table */
390 continue;
391 }else
392 if( (pItem->fg.jointype & JT_LEFT)==0 ){
393 /* A RIGHT JOIN. Use the right-most table */
394 cnt = 0;
395 sqlite3ExprListDelete(db, pFJMatch);
396 pFJMatch = 0;
397 }else{
398 /* For a FULL JOIN, we must construct a coalesce() func */
399 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
400 }
401 }
402 cnt++;
403 pMatch = pItem;
404 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
405 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
406 if( pItem->fg.isNestedFrom ){
407 sqlite3SrcItemColumnUsed(pItem, j);
408 }
409 break;
410 }
411 }
412 if( 0==cnt && VisibleRowid(pTab) ){
413 cntTab++;
414 pMatch = pItem;
415 }
416 }
417 if( pMatch ){
418 pExpr->iTable = pMatch->iCursor;
419 assert( ExprUseYTab(pExpr) );
420 pExpr->y.pTab = pMatch->pTab;
421 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
422 ExprSetProperty(pExpr, EP_CanBeNull);
423 }
424 pSchema = pExpr->y.pTab->pSchema;
425 }
426 } /* if( pSrcList ) */
427
428#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
429 /* If we have not already resolved the name, then maybe
430 ** it is a new.* or old.* trigger argument reference. Or
431 ** maybe it is an excluded.* from an upsert. Or maybe it is
432 ** a reference in the RETURNING clause to a table being modified.
433 */
434 if( cnt==0 && zDb==0 ){
435 pTab = 0;
436#ifndef SQLITE_OMIT_TRIGGER
437 if( pParse->pTriggerTab!=0 ){
438 int op = pParse->eTriggerOp;
439 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
440 if( pParse->bReturning ){
441 if( (pNC->ncFlags & NC_UBaseReg)!=0
442 && (zTab==0 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0)
443 ){
444 pExpr->iTable = op!=TK_DELETE;
445 pTab = pParse->pTriggerTab;
446 }
447 }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
448 pExpr->iTable = 1;
449 pTab = pParse->pTriggerTab;
450 }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
451 pExpr->iTable = 0;
452 pTab = pParse->pTriggerTab;
453 }
454 }
455#endif /* SQLITE_OMIT_TRIGGER */
456#ifndef SQLITE_OMIT_UPSERT
457 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
458 Upsert *pUpsert = pNC->uNC.pUpsert;
459 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
460 pTab = pUpsert->pUpsertSrc->a[0].pTab;
461 pExpr->iTable = EXCLUDED_TABLE_NUMBER;
462 }
463 }
464#endif /* SQLITE_OMIT_UPSERT */
465
466 if( pTab ){
467 int iCol;
468 u8 hCol = sqlite3StrIHash(zCol);
469 pSchema = pTab->pSchema;
470 cntTab++;
471 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
472 if( pCol->hName==hCol
473 && sqlite3StrICmp(pCol->zCnName, zCol)==0
474 ){
475 if( iCol==pTab->iPKey ){
476 iCol = -1;
477 }
478 break;
479 }
480 }
481 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
482 /* IMP: R-51414-32910 */
483 iCol = -1;
484 }
485 if( iCol<pTab->nCol ){
486 cnt++;
487 pMatch = 0;
488#ifndef SQLITE_OMIT_UPSERT
489 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
490 testcase( iCol==(-1) );
491 assert( ExprUseYTab(pExpr) );
492 if( IN_RENAME_OBJECT ){
493 pExpr->iColumn = iCol;
494 pExpr->y.pTab = pTab;
495 eNewExprOp = TK_COLUMN;
496 }else{
497 pExpr->iTable = pNC->uNC.pUpsert->regData +
498 sqlite3TableColumnToStorage(pTab, iCol);
499 eNewExprOp = TK_REGISTER;
500 }
501 }else
502#endif /* SQLITE_OMIT_UPSERT */
503 {
504 assert( ExprUseYTab(pExpr) );
505 pExpr->y.pTab = pTab;
506 if( pParse->bReturning ){
507 eNewExprOp = TK_REGISTER;
508 pExpr->op2 = TK_COLUMN;
509 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
510 sqlite3TableColumnToStorage(pTab, iCol) + 1;
511 }else{
512 pExpr->iColumn = (i16)iCol;
513 eNewExprOp = TK_TRIGGER;
514#ifndef SQLITE_OMIT_TRIGGER
515 if( iCol<0 ){
516 pExpr->affExpr = SQLITE_AFF_INTEGER;
517 }else if( pExpr->iTable==0 ){
518 testcase( iCol==31 );
519 testcase( iCol==32 );
520 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
521 }else{
522 testcase( iCol==31 );
523 testcase( iCol==32 );
524 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
525 }
526#endif /* SQLITE_OMIT_TRIGGER */
527 }
528 }
529 }
530 }
531 }
532#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
533
534 /*
535 ** Perhaps the name is a reference to the ROWID
536 */
537 if( cnt==0
538 && cntTab==1
539 && pMatch
540 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
541 && sqlite3IsRowid(zCol)
542 && ALWAYS(VisibleRowid(pMatch->pTab))
543 ){
544 cnt = 1;
545 pExpr->iColumn = -1;
546 pExpr->affExpr = SQLITE_AFF_INTEGER;
547 }
548
549 /*
550 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
551 ** might refer to an result-set alias. This happens, for example, when
552 ** we are resolving names in the WHERE clause of the following command:
553 **
554 ** SELECT a+b AS x FROM table WHERE x<10;
555 **
556 ** In cases like this, replace pExpr with a copy of the expression that
557 ** forms the result set entry ("a+b" in the example) and return immediately.
558 ** Note that the expression in the result set should have already been
559 ** resolved by the time the WHERE clause is resolved.
560 **
561 ** The ability to use an output result-set column in the WHERE, GROUP BY,
562 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
563 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
564 ** is supported for backwards compatibility only. Hence, we issue a warning
565 ** on sqlite3_log() whenever the capability is used.
566 */
567 if( cnt==0
568 && (pNC->ncFlags & NC_UEList)!=0
569 && zTab==0
570 ){
571 pEList = pNC->uNC.pEList;
572 assert( pEList!=0 );
573 for(j=0; j<pEList->nExpr; j++){
574 char *zAs = pEList->a[j].zEName;
575 if( pEList->a[j].fg.eEName==ENAME_NAME
576 && sqlite3_stricmp(zAs, zCol)==0
577 ){
578 Expr *pOrig;
579 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
580 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
581 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
582 pOrig = pEList->a[j].pExpr;
583 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
584 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
585 return WRC_Abort;
586 }
587 if( ExprHasProperty(pOrig, EP_Win)
588 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
589 ){
590 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
591 return WRC_Abort;
592 }
593 if( sqlite3ExprVectorSize(pOrig)!=1 ){
594 sqlite3ErrorMsg(pParse, "row value misused");
595 return WRC_Abort;
596 }
597 resolveAlias(pParse, pEList, j, pExpr, nSubquery);
598 cnt = 1;
599 pMatch = 0;
600 assert( zTab==0 && zDb==0 );
601 if( IN_RENAME_OBJECT ){
602 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
603 }
604 goto lookupname_end;
605 }
606 }
607 }
608
609 /* Advance to the next name context. The loop will exit when either
610 ** we have a match (cnt>0) or when we run out of name contexts.
611 */
612 if( cnt ) break;
613 pNC = pNC->pNext;
614 nSubquery++;
615 }while( pNC );
616
617
618 /*
619 ** If X and Y are NULL (in other words if only the column name Z is
620 ** supplied) and the value of Z is enclosed in double-quotes, then
621 ** Z is a string literal if it doesn't match any column names. In that
622 ** case, we need to return right away and not make any changes to
623 ** pExpr.
624 **
625 ** Because no reference was made to outer contexts, the pNC->nRef
626 ** fields are not changed in any context.
627 */
628 if( cnt==0 && zTab==0 ){
629 assert( pExpr->op==TK_ID );
630 if( ExprHasProperty(pExpr,EP_DblQuoted)
631 && areDoubleQuotedStringsEnabled(db, pTopNC)
632 ){
633 /* If a double-quoted identifier does not match any known column name,
634 ** then treat it as a string.
635 **
636 ** This hack was added in the early days of SQLite in a misguided attempt
637 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
638 ** I now sorely regret putting in this hack. The effect of this hack is
639 ** that misspelled identifier names are silently converted into strings
640 ** rather than causing an error, to the frustration of countless
641 ** programmers. To all those frustrated programmers, my apologies.
642 **
643 ** Someday, I hope to get rid of this hack. Unfortunately there is
644 ** a huge amount of legacy SQL that uses it. So for now, we just
645 ** issue a warning.
646 */
647 sqlite3_log(SQLITE_WARNING,
648 "double-quoted string literal: \"%w\"", zCol);
649#ifdef SQLITE_ENABLE_NORMALIZE
650 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
651#endif
652 pExpr->op = TK_STRING;
653 memset(&pExpr->y, 0, sizeof(pExpr->y));
654 return WRC_Prune;
655 }
656 if( sqlite3ExprIdToTrueFalse(pExpr) ){
657 return WRC_Prune;
658 }
659 }
660
661 /*
662 ** cnt==0 means there was not match.
663 ** cnt>1 means there were two or more matches.
664 **
665 ** cnt==0 is always an error. cnt>1 is often an error, but might
666 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
667 */
668 assert( pFJMatch==0 || cnt>0 );
669 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
670 if( cnt!=1 ){
671 const char *zErr;
672 if( pFJMatch ){
673 if( pFJMatch->nExpr==cnt-1 ){
674 if( ExprHasProperty(pExpr,EP_Leaf) ){
675 ExprClearProperty(pExpr,EP_Leaf);
676 }else{
677 sqlite3ExprDelete(db, pExpr->pLeft);
678 pExpr->pLeft = 0;
679 sqlite3ExprDelete(db, pExpr->pRight);
680 pExpr->pRight = 0;
681 }
682 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
683 pExpr->op = TK_FUNCTION;
684 pExpr->u.zToken = "coalesce";
685 pExpr->x.pList = pFJMatch;
686 cnt = 1;
687 goto lookupname_end;
688 }else{
689 sqlite3ExprListDelete(db, pFJMatch);
690 pFJMatch = 0;
691 }
692 }
693 zErr = cnt==0 ? "no such column" : "ambiguous column name";
694 if( zDb ){
695 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
696 }else if( zTab ){
697 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
698 }else{
699 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
700 }
701 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
702 pParse->checkSchema = 1;
703 pTopNC->nNcErr++;
704 }
705 assert( pFJMatch==0 );
706
707 /* Remove all substructure from pExpr */
708 if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
709 sqlite3ExprDelete(db, pExpr->pLeft);
710 pExpr->pLeft = 0;
711 sqlite3ExprDelete(db, pExpr->pRight);
712 pExpr->pRight = 0;
713 ExprSetProperty(pExpr, EP_Leaf);
714 }
715
716 /* If a column from a table in pSrcList is referenced, then record
717 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
718 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
719 ** set if the 63rd or any subsequent column is used.
720 **
721 ** The colUsed mask is an optimization used to help determine if an
722 ** index is a covering index. The correct answer is still obtained
723 ** if the mask contains extra set bits. However, it is important to
724 ** avoid setting bits beyond the maximum column number of the table.
725 ** (See ticket [b92e5e8ec2cdbaa1]).
726 **
727 ** If a generated column is referenced, set bits for every column
728 ** of the table.
729 */
730 if( pExpr->iColumn>=0 && pMatch!=0 ){
731 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
732 }
733
734 pExpr->op = eNewExprOp;
735lookupname_end:
736 if( cnt==1 ){
737 assert( pNC!=0 );
738#ifndef SQLITE_OMIT_AUTHORIZATION
739 if( pParse->db->xAuth
740 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
741 ){
742 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
743 }
744#endif
745 /* Increment the nRef value on all name contexts from TopNC up to
746 ** the point where the name matched. */
747 for(;;){
748 assert( pTopNC!=0 );
749 pTopNC->nRef++;
750 if( pTopNC==pNC ) break;
751 pTopNC = pTopNC->pNext;
752 }
753 return WRC_Prune;
754 } else {
755 return WRC_Abort;
756 }
757}
758
759/*
760** Allocate and return a pointer to an expression to load the column iCol
761** from datasource iSrc in SrcList pSrc.
762*/
763Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
764 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
765 if( p ){
766 SrcItem *pItem = &pSrc->a[iSrc];
767 Table *pTab;
768 assert( ExprUseYTab(p) );
769 pTab = p->y.pTab = pItem->pTab;
770 p->iTable = pItem->iCursor;
771 if( p->y.pTab->iPKey==iCol ){
772 p->iColumn = -1;
773 }else{
774 p->iColumn = (ynVar)iCol;
775 if( (pTab->tabFlags & TF_HasGenerated)!=0
776 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
777 ){
778 testcase( pTab->nCol==63 );
779 testcase( pTab->nCol==64 );
780 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
781 }else{
782 testcase( iCol==BMS );
783 testcase( iCol==BMS-1 );
784 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
785 }
786 }
787 }
788 return p;
789}
790
791/*
792** Report an error that an expression is not valid for some set of
793** pNC->ncFlags values determined by validMask.
794**
795** static void notValid(
796** Parse *pParse, // Leave error message here
797** NameContext *pNC, // The name context
798** const char *zMsg, // Type of error
799** int validMask, // Set of contexts for which prohibited
800** Expr *pExpr // Invalidate this expression on error
801** ){...}
802**
803** As an optimization, since the conditional is almost always false
804** (because errors are rare), the conditional is moved outside of the
805** function call using a macro.
806*/
807static void notValidImpl(
808 Parse *pParse, /* Leave error message here */
809 NameContext *pNC, /* The name context */
810 const char *zMsg, /* Type of error */
811 Expr *pExpr, /* Invalidate this expression on error */
812 Expr *pError /* Associate error with this expression */
813){
814 const char *zIn = "partial index WHERE clauses";
815 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
816#ifndef SQLITE_OMIT_CHECK
817 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
818#endif
819#ifndef SQLITE_OMIT_GENERATED_COLUMNS
820 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
821#endif
822 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
823 if( pExpr ) pExpr->op = TK_NULL;
824 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
825}
826#define sqlite3ResolveNotValid(P,N,M,X,E,R) \
827 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
828 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
829
830/*
831** Expression p should encode a floating point value between 1.0 and 0.0.
832** Return 1024 times this value. Or return -1 if p is not a floating point
833** value between 1.0 and 0.0.
834*/
835static int exprProbability(Expr *p){
836 double r = -1.0;
837 if( p->op!=TK_FLOAT ) return -1;
838 assert( !ExprHasProperty(p, EP_IntValue) );
839 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
840 assert( r>=0.0 );
841 if( r>1.0 ) return -1;
842 return (int)(r*134217728.0);
843}
844
845/*
846** This routine is callback for sqlite3WalkExpr().
847**
848** Resolve symbolic names into TK_COLUMN operators for the current
849** node in the expression tree. Return 0 to continue the search down
850** the tree or 2 to abort the tree walk.
851**
852** This routine also does error checking and name resolution for
853** function names. The operator for aggregate functions is changed
854** to TK_AGG_FUNCTION.
855*/
856static int resolveExprStep(Walker *pWalker, Expr *pExpr){
857 NameContext *pNC;
858 Parse *pParse;
859
860 pNC = pWalker->u.pNC;
861 assert( pNC!=0 );
862 pParse = pNC->pParse;
863 assert( pParse==pWalker->pParse );
864
865#ifndef NDEBUG
866 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
867 SrcList *pSrcList = pNC->pSrcList;
868 int i;
869 for(i=0; i<pNC->pSrcList->nSrc; i++){
870 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
871 }
872 }
873#endif
874 switch( pExpr->op ){
875
876 /* The special operator TK_ROW means use the rowid for the first
877 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
878 ** clause processing on UPDATE and DELETE statements, and by
879 ** UPDATE ... FROM statement processing.
880 */
881 case TK_ROW: {
882 SrcList *pSrcList = pNC->pSrcList;
883 SrcItem *pItem;
884 assert( pSrcList && pSrcList->nSrc>=1 );
885 pItem = pSrcList->a;
886 pExpr->op = TK_COLUMN;
887 assert( ExprUseYTab(pExpr) );
888 pExpr->y.pTab = pItem->pTab;
889 pExpr->iTable = pItem->iCursor;
890 pExpr->iColumn--;
891 pExpr->affExpr = SQLITE_AFF_INTEGER;
892 break;
893 }
894
895 /* An optimization: Attempt to convert
896 **
897 ** "expr IS NOT NULL" --> "TRUE"
898 ** "expr IS NULL" --> "FALSE"
899 **
900 ** if we can prove that "expr" is never NULL. Call this the
901 ** "NOT NULL strength reduction optimization".
902 **
903 ** If this optimization occurs, also restore the NameContext ref-counts
904 ** to the state they where in before the "column" LHS expression was
905 ** resolved. This prevents "column" from being counted as having been
906 ** referenced, which might prevent a SELECT from being erroneously
907 ** marked as correlated.
908 */
909 case TK_NOTNULL:
910 case TK_ISNULL: {
911 int anRef[8];
912 NameContext *p;
913 int i;
914 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
915 anRef[i] = p->nRef;
916 }
917 sqlite3WalkExpr(pWalker, pExpr->pLeft);
918 if( 0==sqlite3ExprCanBeNull(pExpr->pLeft) && !IN_RENAME_OBJECT ){
919 testcase( ExprHasProperty(pExpr, EP_OuterON) );
920 assert( !ExprHasProperty(pExpr, EP_IntValue) );
921 if( pExpr->op==TK_NOTNULL ){
922 pExpr->u.zToken = "true";
923 ExprSetProperty(pExpr, EP_IsTrue);
924 }else{
925 pExpr->u.zToken = "false";
926 ExprSetProperty(pExpr, EP_IsFalse);
927 }
928 pExpr->op = TK_TRUEFALSE;
929 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
930 p->nRef = anRef[i];
931 }
932 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
933 pExpr->pLeft = 0;
934 }
935 return WRC_Prune;
936 }
937
938 /* A column name: ID
939 ** Or table name and column name: ID.ID
940 ** Or a database, table and column: ID.ID.ID
941 **
942 ** The TK_ID and TK_OUT cases are combined so that there will only
943 ** be one call to lookupName(). Then the compiler will in-line
944 ** lookupName() for a size reduction and performance increase.
945 */
946 case TK_ID:
947 case TK_DOT: {
948 const char *zColumn;
949 const char *zTable;
950 const char *zDb;
951 Expr *pRight;
952
953 if( pExpr->op==TK_ID ){
954 zDb = 0;
955 zTable = 0;
956 assert( !ExprHasProperty(pExpr, EP_IntValue) );
957 zColumn = pExpr->u.zToken;
958 }else{
959 Expr *pLeft = pExpr->pLeft;
960 testcase( pNC->ncFlags & NC_IdxExpr );
961 testcase( pNC->ncFlags & NC_GenCol );
962 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
963 NC_IdxExpr|NC_GenCol, 0, pExpr);
964 pRight = pExpr->pRight;
965 if( pRight->op==TK_ID ){
966 zDb = 0;
967 }else{
968 assert( pRight->op==TK_DOT );
969 assert( !ExprHasProperty(pRight, EP_IntValue) );
970 zDb = pLeft->u.zToken;
971 pLeft = pRight->pLeft;
972 pRight = pRight->pRight;
973 }
974 assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
975 zTable = pLeft->u.zToken;
976 zColumn = pRight->u.zToken;
977 assert( ExprUseYTab(pExpr) );
978 if( IN_RENAME_OBJECT ){
979 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
980 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
981 }
982 }
983 return lookupName(pParse, zDb, zTable, zColumn, pNC, pExpr);
984 }
985
986 /* Resolve function names
987 */
988 case TK_FUNCTION: {
989 ExprList *pList = pExpr->x.pList; /* The argument list */
990 int n = pList ? pList->nExpr : 0; /* Number of arguments */
991 int no_such_func = 0; /* True if no such function exists */
992 int wrong_num_args = 0; /* True if wrong number of arguments */
993 int is_agg = 0; /* True if is an aggregate function */
994 const char *zId; /* The function name. */
995 FuncDef *pDef; /* Information about the function */
996 u8 enc = ENC(pParse->db); /* The database encoding */
997 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
998#ifndef SQLITE_OMIT_WINDOWFUNC
999 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
1000#endif
1001 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
1002 zId = pExpr->u.zToken;
1003 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
1004 if( pDef==0 ){
1005 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
1006 if( pDef==0 ){
1007 no_such_func = 1;
1008 }else{
1009 wrong_num_args = 1;
1010 }
1011 }else{
1012 is_agg = pDef->xFinalize!=0;
1013 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
1014 ExprSetProperty(pExpr, EP_Unlikely);
1015 if( n==2 ){
1016 pExpr->iTable = exprProbability(pList->a[1].pExpr);
1017 if( pExpr->iTable<0 ){
1018 sqlite3ErrorMsg(pParse,
1019 "second argument to %#T() must be a "
1020 "constant between 0.0 and 1.0", pExpr);
1021 pNC->nNcErr++;
1022 }
1023 }else{
1024 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1025 ** equivalent to likelihood(X, 0.0625).
1026 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1027 ** short-hand for likelihood(X,0.0625).
1028 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1029 ** for likelihood(X,0.9375).
1030 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1031 ** to likelihood(X,0.9375). */
1032 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1033 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
1034 }
1035 }
1036#ifndef SQLITE_OMIT_AUTHORIZATION
1037 {
1038 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
1039 if( auth!=SQLITE_OK ){
1040 if( auth==SQLITE_DENY ){
1041 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
1042 pExpr);
1043 pNC->nNcErr++;
1044 }
1045 pExpr->op = TK_NULL;
1046 return WRC_Prune;
1047 }
1048 }
1049#endif
1050 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
1051 /* For the purposes of the EP_ConstFunc flag, date and time
1052 ** functions and other functions that change slowly are considered
1053 ** constant because they are constant for the duration of one query.
1054 ** This allows them to be factored out of inner loops. */
1055 ExprSetProperty(pExpr,EP_ConstFunc);
1056 }
1057 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
1058 /* Clearly non-deterministic functions like random(), but also
1059 ** date/time functions that use 'now', and other functions like
1060 ** sqlite_version() that might change over time cannot be used
1061 ** in an index or generated column. Curiously, they can be used
1062 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1063 ** all this. */
1064 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
1065 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
1066 }else{
1067 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
1068 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
1069 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
1070 }
1071 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
1072 && pParse->nested==0
1073 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
1074 ){
1075 /* Internal-use-only functions are disallowed unless the
1076 ** SQL is being compiled using sqlite3NestedParse() or
1077 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1078 ** used to activate internal functions for testing purposes */
1079 no_such_func = 1;
1080 pDef = 0;
1081 }else
1082 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
1083 && !IN_RENAME_OBJECT
1084 ){
1085 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
1086 }
1087 }
1088
1089 if( 0==IN_RENAME_OBJECT ){
1090#ifndef SQLITE_OMIT_WINDOWFUNC
1091 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
1092 || (pDef->xValue==0 && pDef->xInverse==0)
1093 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
1094 );
1095 if( pDef && pDef->xValue==0 && pWin ){
1096 sqlite3ErrorMsg(pParse,
1097 "%#T() may not be used as a window function", pExpr
1098 );
1099 pNC->nNcErr++;
1100 }else if(
1101 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
1102 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
1103 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
1104 ){
1105 const char *zType;
1106 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
1107 zType = "window";
1108 }else{
1109 zType = "aggregate";
1110 }
1111 sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
1112 pNC->nNcErr++;
1113 is_agg = 0;
1114 }
1115#else
1116 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
1117 sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
1118 pNC->nNcErr++;
1119 is_agg = 0;
1120 }
1121#endif
1122 else if( no_such_func && pParse->db->init.busy==0
1123#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1124 && pParse->explain==0
1125#endif
1126 ){
1127 sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
1128 pNC->nNcErr++;
1129 }else if( wrong_num_args ){
1130 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
1131 pExpr);
1132 pNC->nNcErr++;
1133 }
1134#ifndef SQLITE_OMIT_WINDOWFUNC
1135 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
1136 sqlite3ErrorMsg(pParse,
1137 "FILTER may not be used with non-aggregate %#T()",
1138 pExpr
1139 );
1140 pNC->nNcErr++;
1141 }
1142#endif
1143 if( is_agg ){
1144 /* Window functions may not be arguments of aggregate functions.
1145 ** Or arguments of other window functions. But aggregate functions
1146 ** may be arguments for window functions. */
1147#ifndef SQLITE_OMIT_WINDOWFUNC
1148 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
1149#else
1150 pNC->ncFlags &= ~NC_AllowAgg;
1151#endif
1152 }
1153 }
1154#ifndef SQLITE_OMIT_WINDOWFUNC
1155 else if( ExprHasProperty(pExpr, EP_WinFunc) ){
1156 is_agg = 1;
1157 }
1158#endif
1159 sqlite3WalkExprList(pWalker, pList);
1160 if( is_agg ){
1161#ifndef SQLITE_OMIT_WINDOWFUNC
1162 if( pWin ){
1163 Select *pSel = pNC->pWinSelect;
1164 assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
1165 if( IN_RENAME_OBJECT==0 ){
1166 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
1167 if( pParse->db->mallocFailed ) break;
1168 }
1169 sqlite3WalkExprList(pWalker, pWin->pPartition);
1170 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
1171 sqlite3WalkExpr(pWalker, pWin->pFilter);
1172 sqlite3WindowLink(pSel, pWin);
1173 pNC->ncFlags |= NC_HasWin;
1174 }else
1175#endif /* SQLITE_OMIT_WINDOWFUNC */
1176 {
1177 NameContext *pNC2; /* For looping up thru outer contexts */
1178 pExpr->op = TK_AGG_FUNCTION;
1179 pExpr->op2 = 0;
1180#ifndef SQLITE_OMIT_WINDOWFUNC
1181 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1182 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
1183 }
1184#endif
1185 pNC2 = pNC;
1186 while( pNC2
1187 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
1188 ){
1189 pExpr->op2++;
1190 pNC2 = pNC2->pNext;
1191 }
1192 assert( pDef!=0 || IN_RENAME_OBJECT );
1193 if( pNC2 && pDef ){
1194 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
1195 assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
1196 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
1197 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
1198 pNC2->ncFlags |= NC_HasAgg
1199 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
1200 & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
1201 }
1202 }
1203 pNC->ncFlags |= savedAllowFlags;
1204 }
1205 /* FIX ME: Compute pExpr->affinity based on the expected return
1206 ** type of the function
1207 */
1208 return WRC_Prune;
1209 }
1210#ifndef SQLITE_OMIT_SUBQUERY
1211 case TK_SELECT:
1212 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
1213#endif
1214 case TK_IN: {
1215 testcase( pExpr->op==TK_IN );
1216 if( ExprUseXSelect(pExpr) ){
1217 int nRef = pNC->nRef;
1218 testcase( pNC->ncFlags & NC_IsCheck );
1219 testcase( pNC->ncFlags & NC_PartIdx );
1220 testcase( pNC->ncFlags & NC_IdxExpr );
1221 testcase( pNC->ncFlags & NC_GenCol );
1222 if( pNC->ncFlags & NC_SelfRef ){
1223 notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
1224 }else{
1225 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1226 }
1227 assert( pNC->nRef>=nRef );
1228 if( nRef!=pNC->nRef ){
1229 ExprSetProperty(pExpr, EP_VarSelect);
1230 pNC->ncFlags |= NC_VarSelect;
1231 }
1232 }
1233 break;
1234 }
1235 case TK_VARIABLE: {
1236 testcase( pNC->ncFlags & NC_IsCheck );
1237 testcase( pNC->ncFlags & NC_PartIdx );
1238 testcase( pNC->ncFlags & NC_IdxExpr );
1239 testcase( pNC->ncFlags & NC_GenCol );
1240 sqlite3ResolveNotValid(pParse, pNC, "parameters",
1241 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
1242 break;
1243 }
1244 case TK_IS:
1245 case TK_ISNOT: {
1246 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
1247 assert( !ExprHasProperty(pExpr, EP_Reduced) );
1248 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1249 ** and "x IS NOT FALSE". */
1250 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
1251 int rc = resolveExprStep(pWalker, pRight);
1252 if( rc==WRC_Abort ) return WRC_Abort;
1253 if( pRight->op==TK_TRUEFALSE ){
1254 pExpr->op2 = pExpr->op;
1255 pExpr->op = TK_TRUTH;
1256 return WRC_Continue;
1257 }
1258 }
1259 /* no break */ deliberate_fall_through
1260 }
1261 case TK_BETWEEN:
1262 case TK_EQ:
1263 case TK_NE:
1264 case TK_LT:
1265 case TK_LE:
1266 case TK_GT:
1267 case TK_GE: {
1268 int nLeft, nRight;
1269 if( pParse->db->mallocFailed ) break;
1270 assert( pExpr->pLeft!=0 );
1271 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
1272 if( pExpr->op==TK_BETWEEN ){
1273 assert( ExprUseXList(pExpr) );
1274 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1275 if( nRight==nLeft ){
1276 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1277 }
1278 }else{
1279 assert( pExpr->pRight!=0 );
1280 nRight = sqlite3ExprVectorSize(pExpr->pRight);
1281 }
1282 if( nLeft!=nRight ){
1283 testcase( pExpr->op==TK_EQ );
1284 testcase( pExpr->op==TK_NE );
1285 testcase( pExpr->op==TK_LT );
1286 testcase( pExpr->op==TK_LE );
1287 testcase( pExpr->op==TK_GT );
1288 testcase( pExpr->op==TK_GE );
1289 testcase( pExpr->op==TK_IS );
1290 testcase( pExpr->op==TK_ISNOT );
1291 testcase( pExpr->op==TK_BETWEEN );
1292 sqlite3ErrorMsg(pParse, "row value misused");
1293 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1294 }
1295 break;
1296 }
1297 }
1298 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
1299 return pParse->nErr ? WRC_Abort : WRC_Continue;
1300}
1301
1302/*
1303** pEList is a list of expressions which are really the result set of the
1304** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1305** This routine checks to see if pE is a simple identifier which corresponds
1306** to the AS-name of one of the terms of the expression list. If it is,
1307** this routine return an integer between 1 and N where N is the number of
1308** elements in pEList, corresponding to the matching entry. If there is
1309** no match, or if pE is not a simple identifier, then this routine
1310** return 0.
1311**
1312** pEList has been resolved. pE has not.
1313*/
1314static int resolveAsName(
1315 Parse *pParse, /* Parsing context for error messages */
1316 ExprList *pEList, /* List of expressions to scan */
1317 Expr *pE /* Expression we are trying to match */
1318){
1319 int i; /* Loop counter */
1320
1321 UNUSED_PARAMETER(pParse);
1322
1323 if( pE->op==TK_ID ){
1324 const char *zCol;
1325 assert( !ExprHasProperty(pE, EP_IntValue) );
1326 zCol = pE->u.zToken;
1327 for(i=0; i<pEList->nExpr; i++){
1328 if( pEList->a[i].fg.eEName==ENAME_NAME
1329 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
1330 ){
1331 return i+1;
1332 }
1333 }
1334 }
1335 return 0;
1336}
1337
1338/*
1339** pE is a pointer to an expression which is a single term in the
1340** ORDER BY of a compound SELECT. The expression has not been
1341** name resolved.
1342**
1343** At the point this routine is called, we already know that the
1344** ORDER BY term is not an integer index into the result set. That
1345** case is handled by the calling routine.
1346**
1347** Attempt to match pE against result set columns in the left-most
1348** SELECT statement. Return the index i of the matching column,
1349** as an indication to the caller that it should sort by the i-th column.
1350** The left-most column is 1. In other words, the value returned is the
1351** same integer value that would be used in the SQL statement to indicate
1352** the column.
1353**
1354** If there is no match, return 0. Return -1 if an error occurs.
1355*/
1356static int resolveOrderByTermToExprList(
1357 Parse *pParse, /* Parsing context for error messages */
1358 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
1359 Expr *pE /* The specific ORDER BY term */
1360){
1361 int i; /* Loop counter */
1362 ExprList *pEList; /* The columns of the result set */
1363 NameContext nc; /* Name context for resolving pE */
1364 sqlite3 *db; /* Database connection */
1365 int rc; /* Return code from subprocedures */
1366 u8 savedSuppErr; /* Saved value of db->suppressErr */
1367
1368 assert( sqlite3ExprIsInteger(pE, &i)==0 );
1369 pEList = pSelect->pEList;
1370
1371 /* Resolve all names in the ORDER BY term expression
1372 */
1373 memset(&nc, 0, sizeof(nc));
1374 nc.pParse = pParse;
1375 nc.pSrcList = pSelect->pSrc;
1376 nc.uNC.pEList = pEList;
1377 nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
1378 nc.nNcErr = 0;
1379 db = pParse->db;
1380 savedSuppErr = db->suppressErr;
1381 db->suppressErr = 1;
1382 rc = sqlite3ResolveExprNames(&nc, pE);
1383 db->suppressErr = savedSuppErr;
1384 if( rc ) return 0;
1385
1386 /* Try to match the ORDER BY expression against an expression
1387 ** in the result set. Return an 1-based index of the matching
1388 ** result-set entry.
1389 */
1390 for(i=0; i<pEList->nExpr; i++){
1391 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
1392 return i+1;
1393 }
1394 }
1395
1396 /* If no match, return 0. */
1397 return 0;
1398}
1399
1400/*
1401** Generate an ORDER BY or GROUP BY term out-of-range error.
1402*/
1403static void resolveOutOfRangeError(
1404 Parse *pParse, /* The error context into which to write the error */
1405 const char *zType, /* "ORDER" or "GROUP" */
1406 int i, /* The index (1-based) of the term out of range */
1407 int mx, /* Largest permissible value of i */
1408 Expr *pError /* Associate the error with the expression */
1409){
1410 sqlite3ErrorMsg(pParse,
1411 "%r %s BY term out of range - should be "
1412 "between 1 and %d", i, zType, mx);
1413 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
1414}
1415
1416/*
1417** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1418** each term of the ORDER BY clause is a constant integer between 1
1419** and N where N is the number of columns in the compound SELECT.
1420**
1421** ORDER BY terms that are already an integer between 1 and N are
1422** unmodified. ORDER BY terms that are integers outside the range of
1423** 1 through N generate an error. ORDER BY terms that are expressions
1424** are matched against result set expressions of compound SELECT
1425** beginning with the left-most SELECT and working toward the right.
1426** At the first match, the ORDER BY expression is transformed into
1427** the integer column number.
1428**
1429** Return the number of errors seen.
1430*/
1431static int resolveCompoundOrderBy(
1432 Parse *pParse, /* Parsing context. Leave error messages here */
1433 Select *pSelect /* The SELECT statement containing the ORDER BY */
1434){
1435 int i;
1436 ExprList *pOrderBy;
1437 ExprList *pEList;
1438 sqlite3 *db;
1439 int moreToDo = 1;
1440
1441 pOrderBy = pSelect->pOrderBy;
1442 if( pOrderBy==0 ) return 0;
1443 db = pParse->db;
1444 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1445 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1446 return 1;
1447 }
1448 for(i=0; i<pOrderBy->nExpr; i++){
1449 pOrderBy->a[i].fg.done = 0;
1450 }
1451 pSelect->pNext = 0;
1452 while( pSelect->pPrior ){
1453 pSelect->pPrior->pNext = pSelect;
1454 pSelect = pSelect->pPrior;
1455 }
1456 while( pSelect && moreToDo ){
1457 struct ExprList_item *pItem;
1458 moreToDo = 0;
1459 pEList = pSelect->pEList;
1460 assert( pEList!=0 );
1461 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1462 int iCol = -1;
1463 Expr *pE, *pDup;
1464 if( pItem->fg.done ) continue;
1465 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
1466 if( NEVER(pE==0) ) continue;
1467 if( sqlite3ExprIsInteger(pE, &iCol) ){
1468 if( iCol<=0 || iCol>pEList->nExpr ){
1469 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
1470 return 1;
1471 }
1472 }else{
1473 iCol = resolveAsName(pParse, pEList, pE);
1474 if( iCol==0 ){
1475 /* Now test if expression pE matches one of the values returned
1476 ** by pSelect. In the usual case this is done by duplicating the
1477 ** expression, resolving any symbols in it, and then comparing
1478 ** it against each expression returned by the SELECT statement.
1479 ** Once the comparisons are finished, the duplicate expression
1480 ** is deleted.
1481 **
1482 ** If this is running as part of an ALTER TABLE operation and
1483 ** the symbols resolve successfully, also resolve the symbols in the
1484 ** actual expression. This allows the code in alter.c to modify
1485 ** column references within the ORDER BY expression as required. */
1486 pDup = sqlite3ExprDup(db, pE, 0);
1487 if( !db->mallocFailed ){
1488 assert(pDup);
1489 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
1490 if( IN_RENAME_OBJECT && iCol>0 ){
1491 resolveOrderByTermToExprList(pParse, pSelect, pE);
1492 }
1493 }
1494 sqlite3ExprDelete(db, pDup);
1495 }
1496 }
1497 if( iCol>0 ){
1498 /* Convert the ORDER BY term into an integer column number iCol,
1499 ** taking care to preserve the COLLATE clause if it exists. */
1500 if( !IN_RENAME_OBJECT ){
1501 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1502 if( pNew==0 ) return 1;
1503 pNew->flags |= EP_IntValue;
1504 pNew->u.iValue = iCol;
1505 if( pItem->pExpr==pE ){
1506 pItem->pExpr = pNew;
1507 }else{
1508 Expr *pParent = pItem->pExpr;
1509 assert( pParent->op==TK_COLLATE );
1510 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1511 assert( pParent->pLeft==pE );
1512 pParent->pLeft = pNew;
1513 }
1514 sqlite3ExprDelete(db, pE);
1515 pItem->u.x.iOrderByCol = (u16)iCol;
1516 }
1517 pItem->fg.done = 1;
1518 }else{
1519 moreToDo = 1;
1520 }
1521 }
1522 pSelect = pSelect->pNext;
1523 }
1524 for(i=0; i<pOrderBy->nExpr; i++){
1525 if( pOrderBy->a[i].fg.done==0 ){
1526 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1527 "column in the result set", i+1);
1528 return 1;
1529 }
1530 }
1531 return 0;
1532}
1533
1534/*
1535** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1536** the SELECT statement pSelect. If any term is reference to a
1537** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1538** field) then convert that term into a copy of the corresponding result set
1539** column.
1540**
1541** If any errors are detected, add an error message to pParse and
1542** return non-zero. Return zero if no errors are seen.
1543*/
1544int sqlite3ResolveOrderGroupBy(
1545 Parse *pParse, /* Parsing context. Leave error messages here */
1546 Select *pSelect, /* The SELECT statement containing the clause */
1547 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
1548 const char *zType /* "ORDER" or "GROUP" */
1549){
1550 int i;
1551 sqlite3 *db = pParse->db;
1552 ExprList *pEList;
1553 struct ExprList_item *pItem;
1554
1555 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
1556 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1557 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1558 return 1;
1559 }
1560 pEList = pSelect->pEList;
1561 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
1562 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1563 if( pItem->u.x.iOrderByCol ){
1564 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1565 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
1566 return 1;
1567 }
1568 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
1569 }
1570 }
1571 return 0;
1572}
1573
1574#ifndef SQLITE_OMIT_WINDOWFUNC
1575/*
1576** Walker callback for windowRemoveExprFromSelect().
1577*/
1578static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
1579 UNUSED_PARAMETER(pWalker);
1580 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1581 Window *pWin = pExpr->y.pWin;
1582 sqlite3WindowUnlinkFromSelect(pWin);
1583 }
1584 return WRC_Continue;
1585}
1586
1587/*
1588** Remove any Window objects owned by the expression pExpr from the
1589** Select.pWin list of Select object pSelect.
1590*/
1591static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
1592 if( pSelect->pWin ){
1593 Walker sWalker;
1594 memset(&sWalker, 0, sizeof(Walker));
1595 sWalker.xExprCallback = resolveRemoveWindowsCb;
1596 sWalker.u.pSelect = pSelect;
1597 sqlite3WalkExpr(&sWalker, pExpr);
1598 }
1599}
1600#else
1601# define windowRemoveExprFromSelect(a, b)
1602#endif /* SQLITE_OMIT_WINDOWFUNC */
1603
1604/*
1605** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1606** The Name context of the SELECT statement is pNC. zType is either
1607** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1608**
1609** This routine resolves each term of the clause into an expression.
1610** If the order-by term is an integer I between 1 and N (where N is the
1611** number of columns in the result set of the SELECT) then the expression
1612** in the resolution is a copy of the I-th result-set expression. If
1613** the order-by term is an identifier that corresponds to the AS-name of
1614** a result-set expression, then the term resolves to a copy of the
1615** result-set expression. Otherwise, the expression is resolved in
1616** the usual way - using sqlite3ResolveExprNames().
1617**
1618** This routine returns the number of errors. If errors occur, then
1619** an appropriate error message might be left in pParse. (OOM errors
1620** excepted.)
1621*/
1622static int resolveOrderGroupBy(
1623 NameContext *pNC, /* The name context of the SELECT statement */
1624 Select *pSelect, /* The SELECT statement holding pOrderBy */
1625 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
1626 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
1627){
1628 int i, j; /* Loop counters */
1629 int iCol; /* Column number */
1630 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
1631 Parse *pParse; /* Parsing context */
1632 int nResult; /* Number of terms in the result set */
1633
1634 assert( pOrderBy!=0 );
1635 nResult = pSelect->pEList->nExpr;
1636 pParse = pNC->pParse;
1637 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1638 Expr *pE = pItem->pExpr;
1639 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
1640 if( NEVER(pE2==0) ) continue;
1641 if( zType[0]!='G' ){
1642 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1643 if( iCol>0 ){
1644 /* If an AS-name match is found, mark this ORDER BY column as being
1645 ** a copy of the iCol-th result-set column. The subsequent call to
1646 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1647 ** copy of the iCol-th result-set expression. */
1648 pItem->u.x.iOrderByCol = (u16)iCol;
1649 continue;
1650 }
1651 }
1652 if( sqlite3ExprIsInteger(pE2, &iCol) ){
1653 /* The ORDER BY term is an integer constant. Again, set the column
1654 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1655 ** order-by term to a copy of the result-set expression */
1656 if( iCol<1 || iCol>0xffff ){
1657 resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
1658 return 1;
1659 }
1660 pItem->u.x.iOrderByCol = (u16)iCol;
1661 continue;
1662 }
1663
1664 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1665 pItem->u.x.iOrderByCol = 0;
1666 if( sqlite3ResolveExprNames(pNC, pE) ){
1667 return 1;
1668 }
1669 for(j=0; j<pSelect->pEList->nExpr; j++){
1670 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1671 /* Since this expresion is being changed into a reference
1672 ** to an identical expression in the result set, remove all Window
1673 ** objects belonging to the expression from the Select.pWin list. */
1674 windowRemoveExprFromSelect(pSelect, pE);
1675 pItem->u.x.iOrderByCol = j+1;
1676 }
1677 }
1678 }
1679 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1680}
1681
1682/*
1683** Resolve names in the SELECT statement p and all of its descendants.
1684*/
1685static int resolveSelectStep(Walker *pWalker, Select *p){
1686 NameContext *pOuterNC; /* Context that contains this SELECT */
1687 NameContext sNC; /* Name context of this SELECT */
1688 int isCompound; /* True if p is a compound select */
1689 int nCompound; /* Number of compound terms processed so far */
1690 Parse *pParse; /* Parsing context */
1691 int i; /* Loop counter */
1692 ExprList *pGroupBy; /* The GROUP BY clause */
1693 Select *pLeftmost; /* Left-most of SELECT of a compound */
1694 sqlite3 *db; /* Database connection */
1695
1696
1697 assert( p!=0 );
1698 if( p->selFlags & SF_Resolved ){
1699 return WRC_Prune;
1700 }
1701 pOuterNC = pWalker->u.pNC;
1702 pParse = pWalker->pParse;
1703 db = pParse->db;
1704
1705 /* Normally sqlite3SelectExpand() will be called first and will have
1706 ** already expanded this SELECT. However, if this is a subquery within
1707 ** an expression, sqlite3ResolveExprNames() will be called without a
1708 ** prior call to sqlite3SelectExpand(). When that happens, let
1709 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1710 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1711 ** this routine in the correct order.
1712 */
1713 if( (p->selFlags & SF_Expanded)==0 ){
1714 sqlite3SelectPrep(pParse, p, pOuterNC);
1715 return pParse->nErr ? WRC_Abort : WRC_Prune;
1716 }
1717
1718 isCompound = p->pPrior!=0;
1719 nCompound = 0;
1720 pLeftmost = p;
1721 while( p ){
1722 assert( (p->selFlags & SF_Expanded)!=0 );
1723 assert( (p->selFlags & SF_Resolved)==0 );
1724 assert( db->suppressErr==0 ); /* SF_Resolved not set if errors suppressed */
1725 p->selFlags |= SF_Resolved;
1726
1727
1728 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1729 ** are not allowed to refer to any names, so pass an empty NameContext.
1730 */
1731 memset(&sNC, 0, sizeof(sNC));
1732 sNC.pParse = pParse;
1733 sNC.pWinSelect = p;
1734 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
1735 return WRC_Abort;
1736 }
1737
1738 /* If the SF_Converted flags is set, then this Select object was
1739 ** was created by the convertCompoundSelectToSubquery() function.
1740 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1741 ** as if it were part of the sub-query, not the parent. This block
1742 ** moves the pOrderBy down to the sub-query. It will be moved back
1743 ** after the names have been resolved. */
1744 if( p->selFlags & SF_Converted ){
1745 Select *pSub = p->pSrc->a[0].pSelect;
1746 assert( p->pSrc->nSrc==1 && p->pOrderBy );
1747 assert( pSub->pPrior && pSub->pOrderBy==0 );
1748 pSub->pOrderBy = p->pOrderBy;
1749 p->pOrderBy = 0;
1750 }
1751
1752 /* Recursively resolve names in all subqueries in the FROM clause
1753 */
1754 for(i=0; i<p->pSrc->nSrc; i++){
1755 SrcItem *pItem = &p->pSrc->a[i];
1756 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
1757 int nRef = pOuterNC ? pOuterNC->nRef : 0;
1758 const char *zSavedContext = pParse->zAuthContext;
1759
1760 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1761 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1762 pParse->zAuthContext = zSavedContext;
1763 if( pParse->nErr ) return WRC_Abort;
1764 assert( db->mallocFailed==0 );
1765
1766 /* If the number of references to the outer context changed when
1767 ** expressions in the sub-select were resolved, the sub-select
1768 ** is correlated. It is not required to check the refcount on any
1769 ** but the innermost outer context object, as lookupName() increments
1770 ** the refcount on all contexts between the current one and the
1771 ** context containing the column when it resolves a name. */
1772 if( pOuterNC ){
1773 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
1774 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
1775 }
1776 }
1777 }
1778
1779 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1780 ** resolve the result-set expression list.
1781 */
1782 sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
1783 sNC.pSrcList = p->pSrc;
1784 sNC.pNext = pOuterNC;
1785
1786 /* Resolve names in the result set. */
1787 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
1788 sNC.ncFlags &= ~NC_AllowWin;
1789
1790 /* If there are no aggregate functions in the result-set, and no GROUP BY
1791 ** expression, do not allow aggregates in any of the other expressions.
1792 */
1793 assert( (p->selFlags & SF_Aggregate)==0 );
1794 pGroupBy = p->pGroupBy;
1795 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1796 assert( NC_MinMaxAgg==SF_MinMaxAgg );
1797 assert( NC_OrderAgg==SF_OrderByReqd );
1798 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
1799 }else{
1800 sNC.ncFlags &= ~NC_AllowAgg;
1801 }
1802
1803 /* Add the output column list to the name-context before parsing the
1804 ** other expressions in the SELECT statement. This is so that
1805 ** expressions in the WHERE clause (etc.) can refer to expressions by
1806 ** aliases in the result set.
1807 **
1808 ** Minor point: If this is the case, then the expression will be
1809 ** re-evaluated for each reference to it.
1810 */
1811 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
1812 sNC.uNC.pEList = p->pEList;
1813 sNC.ncFlags |= NC_UEList;
1814 if( p->pHaving ){
1815 if( (p->selFlags & SF_Aggregate)==0 ){
1816 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
1817 return WRC_Abort;
1818 }
1819 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1820 }
1821 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1822
1823 /* Resolve names in table-valued-function arguments */
1824 for(i=0; i<p->pSrc->nSrc; i++){
1825 SrcItem *pItem = &p->pSrc->a[i];
1826 if( pItem->fg.isTabFunc
1827 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
1828 ){
1829 return WRC_Abort;
1830 }
1831 }
1832
1833#ifndef SQLITE_OMIT_WINDOWFUNC
1834 if( IN_RENAME_OBJECT ){
1835 Window *pWin;
1836 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
1837 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
1838 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
1839 ){
1840 return WRC_Abort;
1841 }
1842 }
1843 }
1844#endif
1845
1846 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1847 ** outer queries
1848 */
1849 sNC.pNext = 0;
1850 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
1851
1852 /* If this is a converted compound query, move the ORDER BY clause from
1853 ** the sub-query back to the parent query. At this point each term
1854 ** within the ORDER BY clause has been transformed to an integer value.
1855 ** These integers will be replaced by copies of the corresponding result
1856 ** set expressions by the call to resolveOrderGroupBy() below. */
1857 if( p->selFlags & SF_Converted ){
1858 Select *pSub = p->pSrc->a[0].pSelect;
1859 p->pOrderBy = pSub->pOrderBy;
1860 pSub->pOrderBy = 0;
1861 }
1862
1863 /* Process the ORDER BY clause for singleton SELECT statements.
1864 ** The ORDER BY clause for compounds SELECT statements is handled
1865 ** below, after all of the result-sets for all of the elements of
1866 ** the compound have been resolved.
1867 **
1868 ** If there is an ORDER BY clause on a term of a compound-select other
1869 ** than the right-most term, then that is a syntax error. But the error
1870 ** is not detected until much later, and so we need to go ahead and
1871 ** resolve those symbols on the incorrect ORDER BY for consistency.
1872 */
1873 if( p->pOrderBy!=0
1874 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
1875 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
1876 ){
1877 return WRC_Abort;
1878 }
1879 if( db->mallocFailed ){
1880 return WRC_Abort;
1881 }
1882 sNC.ncFlags &= ~NC_AllowWin;
1883
1884 /* Resolve the GROUP BY clause. At the same time, make sure
1885 ** the GROUP BY clause does not contain aggregate functions.
1886 */
1887 if( pGroupBy ){
1888 struct ExprList_item *pItem;
1889
1890 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
1891 return WRC_Abort;
1892 }
1893 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
1894 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
1895 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
1896 "the GROUP BY clause");
1897 return WRC_Abort;
1898 }
1899 }
1900 }
1901
1902 /* If this is part of a compound SELECT, check that it has the right
1903 ** number of expressions in the select list. */
1904 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
1905 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
1906 return WRC_Abort;
1907 }
1908
1909 /* Advance to the next term of the compound
1910 */
1911 p = p->pPrior;
1912 nCompound++;
1913 }
1914
1915 /* Resolve the ORDER BY on a compound SELECT after all terms of
1916 ** the compound have been resolved.
1917 */
1918 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
1919 return WRC_Abort;
1920 }
1921
1922 return WRC_Prune;
1923}
1924
1925/*
1926** This routine walks an expression tree and resolves references to
1927** table columns and result-set columns. At the same time, do error
1928** checking on function usage and set a flag if any aggregate functions
1929** are seen.
1930**
1931** To resolve table columns references we look for nodes (or subtrees) of the
1932** form X.Y.Z or Y.Z or just Z where
1933**
1934** X: The name of a database. Ex: "main" or "temp" or
1935** the symbolic name assigned to an ATTACH-ed database.
1936**
1937** Y: The name of a table in a FROM clause. Or in a trigger
1938** one of the special names "old" or "new".
1939**
1940** Z: The name of a column in table Y.
1941**
1942** The node at the root of the subtree is modified as follows:
1943**
1944** Expr.op Changed to TK_COLUMN
1945** Expr.pTab Points to the Table object for X.Y
1946** Expr.iColumn The column index in X.Y. -1 for the rowid.
1947** Expr.iTable The VDBE cursor number for X.Y
1948**
1949**
1950** To resolve result-set references, look for expression nodes of the
1951** form Z (with no X and Y prefix) where the Z matches the right-hand
1952** size of an AS clause in the result-set of a SELECT. The Z expression
1953** is replaced by a copy of the left-hand side of the result-set expression.
1954** Table-name and function resolution occurs on the substituted expression
1955** tree. For example, in:
1956**
1957** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1958**
1959** The "x" term of the order by is replaced by "a+b" to render:
1960**
1961** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1962**
1963** Function calls are checked to make sure that the function is
1964** defined and that the correct number of arguments are specified.
1965** If the function is an aggregate function, then the NC_HasAgg flag is
1966** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1967** If an expression contains aggregate functions then the EP_Agg
1968** property on the expression is set.
1969**
1970** An error message is left in pParse if anything is amiss. The number
1971** if errors is returned.
1972*/
1973int sqlite3ResolveExprNames(
1974 NameContext *pNC, /* Namespace to resolve expressions in. */
1975 Expr *pExpr /* The expression to be analyzed. */
1976){
1977 int savedHasAgg;
1978 Walker w;
1979
1980 if( pExpr==0 ) return SQLITE_OK;
1981 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1982 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
1983 w.pParse = pNC->pParse;
1984 w.xExprCallback = resolveExprStep;
1985 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
1986 w.xSelectCallback2 = 0;
1987 w.u.pNC = pNC;
1988#if SQLITE_MAX_EXPR_DEPTH>0
1989 w.pParse->nHeight += pExpr->nHeight;
1990 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
1991 return SQLITE_ERROR;
1992 }
1993#endif
1994 sqlite3WalkExpr(&w, pExpr);
1995#if SQLITE_MAX_EXPR_DEPTH>0
1996 w.pParse->nHeight -= pExpr->nHeight;
1997#endif
1998 assert( EP_Agg==NC_HasAgg );
1999 assert( EP_Win==NC_HasWin );
2000 testcase( pNC->ncFlags & NC_HasAgg );
2001 testcase( pNC->ncFlags & NC_HasWin );
2002 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2003 pNC->ncFlags |= savedHasAgg;
2004 return pNC->nNcErr>0 || w.pParse->nErr>0;
2005}
2006
2007/*
2008** Resolve all names for all expression in an expression list. This is
2009** just like sqlite3ResolveExprNames() except that it works for an expression
2010** list rather than a single expression.
2011*/
2012int sqlite3ResolveExprListNames(
2013 NameContext *pNC, /* Namespace to resolve expressions in. */
2014 ExprList *pList /* The expression list to be analyzed. */
2015){
2016 int i;
2017 int savedHasAgg = 0;
2018 Walker w;
2019 if( pList==0 ) return WRC_Continue;
2020 w.pParse = pNC->pParse;
2021 w.xExprCallback = resolveExprStep;
2022 w.xSelectCallback = resolveSelectStep;
2023 w.xSelectCallback2 = 0;
2024 w.u.pNC = pNC;
2025 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2026 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2027 for(i=0; i<pList->nExpr; i++){
2028 Expr *pExpr = pList->a[i].pExpr;
2029 if( pExpr==0 ) continue;
2030#if SQLITE_MAX_EXPR_DEPTH>0
2031 w.pParse->nHeight += pExpr->nHeight;
2032 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2033 return WRC_Abort;
2034 }
2035#endif
2036 sqlite3WalkExpr(&w, pExpr);
2037#if SQLITE_MAX_EXPR_DEPTH>0
2038 w.pParse->nHeight -= pExpr->nHeight;
2039#endif
2040 assert( EP_Agg==NC_HasAgg );
2041 assert( EP_Win==NC_HasWin );
2042 testcase( pNC->ncFlags & NC_HasAgg );
2043 testcase( pNC->ncFlags & NC_HasWin );
2044 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
2045 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2046 savedHasAgg |= pNC->ncFlags &
2047 (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2048 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2049 }
2050 if( w.pParse->nErr>0 ) return WRC_Abort;
2051 }
2052 pNC->ncFlags |= savedHasAgg;
2053 return WRC_Continue;
2054}
2055
2056/*
2057** Resolve all names in all expressions of a SELECT and in all
2058** decendents of the SELECT, including compounds off of p->pPrior,
2059** subqueries in expressions, and subqueries used as FROM clause
2060** terms.
2061**
2062** See sqlite3ResolveExprNames() for a description of the kinds of
2063** transformations that occur.
2064**
2065** All SELECT statements should have been expanded using
2066** sqlite3SelectExpand() prior to invoking this routine.
2067*/
2068void sqlite3ResolveSelectNames(
2069 Parse *pParse, /* The parser context */
2070 Select *p, /* The SELECT statement being coded. */
2071 NameContext *pOuterNC /* Name context for parent SELECT statement */
2072){
2073 Walker w;
2074
2075 assert( p!=0 );
2076 w.xExprCallback = resolveExprStep;
2077 w.xSelectCallback = resolveSelectStep;
2078 w.xSelectCallback2 = 0;
2079 w.pParse = pParse;
2080 w.u.pNC = pOuterNC;
2081 sqlite3WalkSelect(&w, p);
2082}
2083
2084/*
2085** Resolve names in expressions that can only reference a single table
2086** or which cannot reference any tables at all. Examples:
2087**
2088** "type" flag
2089** ------------
2090** (1) CHECK constraints NC_IsCheck
2091** (2) WHERE clauses on partial indices NC_PartIdx
2092** (3) Expressions in indexes on expressions NC_IdxExpr
2093** (4) Expression arguments to VACUUM INTO. 0
2094** (5) GENERATED ALWAYS as expressions NC_GenCol
2095**
2096** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2097** nodes of the expression is set to -1 and the Expr.iColumn value is
2098** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2099**
2100** Any errors cause an error message to be set in pParse.
2101*/
2102int sqlite3ResolveSelfReference(
2103 Parse *pParse, /* Parsing context */
2104 Table *pTab, /* The table being referenced, or NULL */
2105 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2106 Expr *pExpr, /* Expression to resolve. May be NULL. */
2107 ExprList *pList /* Expression list to resolve. May be NULL. */
2108){
2109 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
2110 NameContext sNC; /* Name context for pParse->pNewTable */
2111 int rc;
2112
2113 assert( type==0 || pTab!=0 );
2114 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2115 || type==NC_GenCol || pTab==0 );
2116 memset(&sNC, 0, sizeof(sNC));
2117 memset(&sSrc, 0, sizeof(sSrc));
2118 if( pTab ){
2119 sSrc.nSrc = 1;
2120 sSrc.a[0].zName = pTab->zName;
2121 sSrc.a[0].pTab = pTab;
2122 sSrc.a[0].iCursor = -1;
2123 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2124 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2125 ** schema elements */
2126 type |= NC_FromDDL;
2127 }
2128 }
2129 sNC.pParse = pParse;
2130 sNC.pSrcList = &sSrc;
2131 sNC.ncFlags = type | NC_IsDDL;
2132 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2133 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2134 return rc;
2135}
2136