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