4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
13 ** This file contains routines used for walking the parser tree and
14 ** resolve all identifiers by associating them with a particular
17 #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
;
39 static void incrAggFunctionDepth(Expr
*pExpr
, int N
){
42 memset(&w
, 0, sizeof(w
));
43 w
.xExprCallback
= incrAggDepth
;
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
;
83 pDup
= sqlite3ExprDup(db
, pOrig
, 0);
84 if( db
->mallocFailed
){
85 sqlite3ExprDelete(db
, pDup
);
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
113 int sqlite3MatchEName(
114 const struct ExprList_item
*pItem
,
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) ){
128 for(n
=0; ALWAYS(zSpan
[n
]) && zSpan
[n
]!='.'; n
++){}
129 if( zTab
&& (sqlite3StrNICmp(zSpan
, zTab
, n
)!=0 || zTab
[n
]!=0) ){
133 if( zCol
&& sqlite3StrICmp(zSpan
, zCol
)!=0 ){
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 ){
149 return (db
->flags
& SQLITE_DqsDDL
)!=0;
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
){
165 assert( ExprUseYTab(pExpr
) );
166 pExTab
= pExpr
->y
.pTab
;
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;
175 testcase( n
==BMS
-1 );
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
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);
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 ** 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:
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
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.
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
229 ** If the name cannot be resolved unambiguously, leave an error message
230 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
232 static 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 */
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 */
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
) );
259 /* Initialize the node to no-match */
261 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
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
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
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
;
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
;
293 /* Start at the inner-most context and move outward until a match is found */
294 assert( pNC
&& cnt
==0 );
297 SrcList
*pSrcList
= pNC
->pSrcList
;
300 for(i
=0, pItem
=pSrcList
->a
; i
<pSrcList
->nSrc
; i
++, pItem
++){
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 -------------^
314 assert( pItem
->pSelect
!=0 );
315 pEList
= pItem
->pSelect
->pEList
;
317 assert( pEList
->nExpr
==pTab
->nCol
);
318 for(j
=0; j
<pEList
->nExpr
; j
++){
319 if( !sqlite3MatchEName(&pEList
->a
[j
], zCol
, zTab
, zDb
) ){
323 if( pItem
->fg
.isUsing
==0
324 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
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
);
332 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
333 /* An INNER or LEFT JOIN. Use the left-most table */
336 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
337 /* A RIGHT JOIN. Use the right-most table */
339 sqlite3ExprListDelete(db
, pFJMatch
);
342 /* For a FULL JOIN, we must construct a coalesce() func */
343 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
350 pEList
->a
[j
].fg
.bUsed
= 1;
352 if( pEList
->a
[j
].fg
.bUsingTerm
) break;
354 if( hit
|| zTab
==0 ) continue;
356 assert( zDb
==0 || zTab
!=0 );
358 const char *zTabName
;
360 if( pTab
->pSchema
!=pSchema
) continue;
361 if( pSchema
==0 && strcmp(zDb
,"*")!=0 ) continue;
363 zTabName
= pItem
->zAlias
? pItem
->zAlias
: pTab
->zName
;
364 assert( zTabName
!=0 );
365 if( sqlite3StrICmp(zTabName
, zTab
)!=0 ){
368 assert( ExprUseYTab(pExpr
) );
369 if( IN_RENAME_OBJECT
&& pItem
->zAlias
){
370 sqlite3RenameTokenRemap(pParse
, 0, (void*)&pExpr
->y
.pTab
);
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
379 if( pItem
->fg
.isUsing
==0
380 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
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
);
388 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
389 /* An INNER or LEFT JOIN. Use the left-most table */
392 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
393 /* A RIGHT JOIN. Use the right-most table */
395 sqlite3ExprListDelete(db
, pFJMatch
);
398 /* For a FULL JOIN, we must construct a coalesce() func */
399 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
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
);
412 if( 0==cnt
&& VisibleRowid(pTab
) ){
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
);
424 pSchema
= pExpr
->y
.pTab
->pSchema
;
426 } /* if( pSrcList ) */
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.
434 if( cnt
==0 && zDb
==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)
444 pExpr
->iTable
= op
!=TK_DELETE
;
445 pTab
= pParse
->pTriggerTab
;
447 }else if( op
!=TK_DELETE
&& zTab
&& sqlite3StrICmp("new",zTab
) == 0 ){
449 pTab
= pParse
->pTriggerTab
;
450 }else if( op
!=TK_INSERT
&& zTab
&& sqlite3StrICmp("old",zTab
)==0 ){
452 pTab
= pParse
->pTriggerTab
;
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
;
464 #endif /* SQLITE_OMIT_UPSERT */
468 u8 hCol
= sqlite3StrIHash(zCol
);
469 pSchema
= pTab
->pSchema
;
471 for(iCol
=0, pCol
=pTab
->aCol
; iCol
<pTab
->nCol
; iCol
++, pCol
++){
472 if( pCol
->hName
==hCol
473 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
475 if( iCol
==pTab
->iPKey
){
481 if( iCol
>=pTab
->nCol
&& sqlite3IsRowid(zCol
) && VisibleRowid(pTab
) ){
482 /* IMP: R-51414-32910 */
485 if( iCol
<pTab
->nCol
){
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
;
497 pExpr
->iTable
= pNC
->uNC
.pUpsert
->regData
+
498 sqlite3TableColumnToStorage(pTab
, iCol
);
499 eNewExprOp
= TK_REGISTER
;
502 #endif /* SQLITE_OMIT_UPSERT */
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;
512 pExpr
->iColumn
= (i16
)iCol
;
513 eNewExprOp
= TK_TRIGGER
;
514 #ifndef SQLITE_OMIT_TRIGGER
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
));
522 testcase( iCol
==31 );
523 testcase( iCol
==32 );
524 pParse
->newmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
526 #endif /* SQLITE_OMIT_TRIGGER */
532 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
535 ** Perhaps the name is a reference to the ROWID
540 && (pNC
->ncFlags
& (NC_IdxExpr
|NC_GenCol
))==0
541 && sqlite3IsRowid(zCol
)
542 && ALWAYS(VisibleRowid(pMatch
->pTab
))
546 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
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:
554 ** SELECT a+b AS x FROM table WHERE x<10;
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.
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.
568 && (pNC
->ncFlags
& NC_UEList
)!=0
571 pEList
= pNC
->uNC
.pEList
;
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
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
);
587 if( ExprHasProperty(pOrig
, EP_Win
)
588 && ((pNC
->ncFlags
&NC_AllowWin
)==0 || pNC
!=pTopNC
)
590 sqlite3ErrorMsg(pParse
, "misuse of aliased window function %s",zAs
);
593 if( sqlite3ExprVectorSize(pOrig
)!=1 ){
594 sqlite3ErrorMsg(pParse
, "row value misused");
597 resolveAlias(pParse
, pEList
, j
, pExpr
, nSubquery
);
600 assert( zTab
==0 && zDb
==0 );
601 if( IN_RENAME_OBJECT
){
602 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
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.
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
625 ** Because no reference was made to outer contexts, the pNC->nRef
626 ** fields are not changed in any context.
628 if( cnt
==0 && zTab
==0 ){
629 assert( pExpr
->op
==TK_ID
);
630 if( ExprHasProperty(pExpr
,EP_DblQuoted
)
631 && areDoubleQuotedStringsEnabled(db
, pTopNC
)
633 /* If a double-quoted identifier does not match any known column name,
634 ** then treat it as a string.
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.
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
647 sqlite3_log(SQLITE_WARNING
,
648 "double-quoted string literal: \"%w\"", zCol
);
649 #ifdef SQLITE_ENABLE_NORMALIZE
650 sqlite3VdbeAddDblquoteStr(db
, pParse
->pVdbe
, zCol
);
652 pExpr
->op
= TK_STRING
;
653 memset(&pExpr
->y
, 0, sizeof(pExpr
->y
));
656 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
662 ** cnt==0 means there was not match.
663 ** cnt>1 means there were two or more matches.
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.
668 assert( pFJMatch
==0 || cnt
>0 );
669 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
673 if( pFJMatch
->nExpr
==cnt
-1 ){
674 if( ExprHasProperty(pExpr
,EP_Leaf
) ){
675 ExprClearProperty(pExpr
,EP_Leaf
);
677 sqlite3ExprDelete(db
, pExpr
->pLeft
);
679 sqlite3ExprDelete(db
, pExpr
->pRight
);
682 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
683 pExpr
->op
= TK_FUNCTION
;
684 pExpr
->u
.zToken
= "coalesce";
685 pExpr
->x
.pList
= pFJMatch
;
689 sqlite3ExprListDelete(db
, pFJMatch
);
693 zErr
= cnt
==0 ? "no such column" : "ambiguous column name";
695 sqlite3ErrorMsg(pParse
, "%s: %s.%s.%s", zErr
, zDb
, zTab
, zCol
);
697 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zErr
, zTab
, zCol
);
699 sqlite3ErrorMsg(pParse
, "%s: %s", zErr
, zCol
);
701 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
702 pParse
->checkSchema
= 1;
705 assert( pFJMatch
==0 );
707 /* Remove all substructure from pExpr */
708 if( !ExprHasProperty(pExpr
,(EP_TokenOnly
|EP_Leaf
)) ){
709 sqlite3ExprDelete(db
, pExpr
->pLeft
);
711 sqlite3ExprDelete(db
, pExpr
->pRight
);
713 ExprSetProperty(pExpr
, EP_Leaf
);
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.
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]).
727 ** If a generated column is referenced, set bits for every column
730 if( pExpr
->iColumn
>=0 && pMatch
!=0 ){
731 pMatch
->colUsed
|= sqlite3ExprColUsed(pExpr
);
734 pExpr
->op
= eNewExprOp
;
738 #ifndef SQLITE_OMIT_AUTHORIZATION
739 if( pParse
->db
->xAuth
740 && (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_TRIGGER
)
742 sqlite3AuthRead(pParse
, pExpr
, pSchema
, pNC
->pSrcList
);
745 /* Increment the nRef value on all name contexts from TopNC up to
746 ** the point where the name matched. */
750 if( pTopNC
==pNC
) break;
751 pTopNC
= pTopNC
->pNext
;
760 ** Allocate and return a pointer to an expression to load the column iCol
761 ** from datasource iSrc in SrcList pSrc.
763 Expr
*sqlite3CreateColumnExpr(sqlite3
*db
, SrcList
*pSrc
, int iSrc
, int iCol
){
764 Expr
*p
= sqlite3ExprAlloc(db
, TK_COLUMN
, 0, 0);
766 SrcItem
*pItem
= &pSrc
->a
[iSrc
];
768 assert( ExprUseYTab(p
) );
769 pTab
= p
->y
.pTab
= pItem
->pTab
;
770 p
->iTable
= pItem
->iCursor
;
771 if( p
->y
.pTab
->iPKey
==iCol
){
774 p
->iColumn
= (ynVar
)iCol
;
775 if( (pTab
->tabFlags
& TF_HasGenerated
)!=0
776 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_GENERATED
)!=0
778 testcase( pTab
->nCol
==63 );
779 testcase( pTab
->nCol
==64 );
780 pItem
->colUsed
= pTab
->nCol
>=64 ? ALLBITS
: MASKBIT(pTab
->nCol
)-1;
782 testcase( iCol
==BMS
);
783 testcase( iCol
==BMS
-1 );
784 pItem
->colUsed
|= ((Bitmask
)1)<<(iCol
>=BMS
? BMS
-1 : iCol
);
792 ** Report an error that an expression is not valid for some set of
793 ** pNC->ncFlags values determined by validMask.
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
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.
807 static 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 */
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";
819 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
820 else if( pNC
->ncFlags
& NC_GenCol
) zIn
= "generated columns";
822 sqlite3ErrorMsg(pParse
, "%s prohibited in %s", zMsg
, zIn
);
823 if( pExpr
) pExpr
->op
= TK_NULL
;
824 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
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);
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.
835 static int exprProbability(Expr
*p
){
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
);
841 if( r
>1.0 ) return -1;
842 return (int)(r
*134217728.0);
846 ** This routine is callback for sqlite3WalkExpr().
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.
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.
856 static int resolveExprStep(Walker
*pWalker
, Expr
*pExpr
){
860 pNC
= pWalker
->u
.pNC
;
862 pParse
= pNC
->pParse
;
863 assert( pParse
==pWalker
->pParse
);
866 if( pNC
->pSrcList
&& pNC
->pSrcList
->nAlloc
>0 ){
867 SrcList
*pSrcList
= pNC
->pSrcList
;
869 for(i
=0; i
<pNC
->pSrcList
->nSrc
; i
++){
870 assert( pSrcList
->a
[i
].iCursor
>=0 && pSrcList
->a
[i
].iCursor
<pParse
->nTab
);
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.
882 SrcList
*pSrcList
= pNC
->pSrcList
;
884 assert( pSrcList
&& pSrcList
->nSrc
>=1 );
886 pExpr
->op
= TK_COLUMN
;
887 assert( ExprUseYTab(pExpr
) );
888 pExpr
->y
.pTab
= pItem
->pTab
;
889 pExpr
->iTable
= pItem
->iCursor
;
891 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
895 /* An optimization: Attempt to convert
897 ** "expr IS NOT NULL" --> "TRUE"
898 ** "expr IS NULL" --> "FALSE"
900 ** if we can prove that "expr" is never NULL. Call this the
901 ** "NOT NULL strength reduction optimization".
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.
914 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
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
);
925 pExpr
->u
.zToken
= "false";
926 ExprSetProperty(pExpr
, EP_IsFalse
);
928 pExpr
->op
= TK_TRUEFALSE
;
929 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
932 sqlite3ExprDelete(pParse
->db
, pExpr
->pLeft
);
939 ** Or table name and column name: ID.ID
940 ** Or a database, table and column: ID.ID.ID
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.
953 if( pExpr
->op
==TK_ID
){
956 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
957 zColumn
= pExpr
->u
.zToken
;
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
){
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
;
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
);
983 return lookupName(pParse
, zDb
, zTable
, zColumn
, pNC
, pExpr
);
986 /* Resolve function names
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);
1001 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
1002 zId
= pExpr
->u
.zToken
;
1003 pDef
= sqlite3FindFunction(pParse
->db
, zId
, n
, enc
, 0);
1005 pDef
= sqlite3FindFunction(pParse
->db
, zId
, -2, enc
, 0);
1012 is_agg
= pDef
->xFinalize
!=0;
1013 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
1014 ExprSetProperty(pExpr
, EP_Unlikely
);
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
);
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;
1036 #ifndef SQLITE_OMIT_AUTHORIZATION
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",
1045 pExpr
->op
= TK_NULL
;
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
);
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
1064 sqlite3ResolveNotValid(pParse
, pNC
, "non-deterministic functions",
1065 NC_IdxExpr
|NC_PartIdx
|NC_GenCol
, 0, pExpr
);
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
);
1071 if( (pDef
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
1072 && pParse
->nested
==0
1073 && (pParse
->db
->mDbFlags
& DBFLAG_InternalFunc
)==0
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 */
1082 if( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0
1083 && !IN_RENAME_OBJECT
1085 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
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
)
1095 if( pDef
&& pDef
->xValue
==0 && pWin
){
1096 sqlite3ErrorMsg(pParse
,
1097 "%#T() may not be used as a window function", pExpr
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)
1106 if( (pDef
->funcFlags
& SQLITE_FUNC_WINDOW
) || pWin
){
1109 zType
= "aggregate";
1111 sqlite3ErrorMsg(pParse
, "misuse of %s function %#T()",zType
,pExpr
);
1116 if( (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0) ){
1117 sqlite3ErrorMsg(pParse
,"misuse of aggregate function %#T()",pExpr
);
1122 else if( no_such_func
&& pParse
->db
->init
.busy
==0
1123 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1124 && pParse
->explain
==0
1127 sqlite3ErrorMsg(pParse
, "no such function: %#T", pExpr
);
1129 }else if( wrong_num_args
){
1130 sqlite3ErrorMsg(pParse
,"wrong number of arguments to function %#T()",
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()",
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));
1150 pNC
->ncFlags
&= ~NC_AllowAgg
;
1154 #ifndef SQLITE_OMIT_WINDOWFUNC
1155 else if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1159 sqlite3WalkExprList(pWalker
, pList
);
1161 #ifndef SQLITE_OMIT_WINDOWFUNC
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;
1169 sqlite3WalkExprList(pWalker
, pWin
->pPartition
);
1170 sqlite3WalkExprList(pWalker
, pWin
->pOrderBy
);
1171 sqlite3WalkExpr(pWalker
, pWin
->pFilter
);
1172 sqlite3WindowLink(pSel
, pWin
);
1173 pNC
->ncFlags
|= NC_HasWin
;
1175 #endif /* SQLITE_OMIT_WINDOWFUNC */
1177 NameContext
*pNC2
; /* For looping up thru outer contexts */
1178 pExpr
->op
= TK_AGG_FUNCTION
;
1180 #ifndef SQLITE_OMIT_WINDOWFUNC
1181 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1182 sqlite3WalkExpr(pWalker
, pExpr
->y
.pWin
->pFilter
);
1187 && sqlite3ReferencesSrcList(pParse
, pExpr
, pNC2
->pSrcList
)==0
1192 assert( pDef
!=0 || IN_RENAME_OBJECT
);
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
));
1203 pNC
->ncFlags
|= savedAllowFlags
;
1205 /* FIX ME: Compute pExpr->affinity based on the expected return
1206 ** type of the function
1210 #ifndef SQLITE_OMIT_SUBQUERY
1212 case TK_EXISTS
: testcase( pExpr
->op
==TK_EXISTS
);
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
);
1225 sqlite3WalkSelect(pWalker
, pExpr
->x
.pSelect
);
1227 assert( pNC
->nRef
>=nRef
);
1228 if( nRef
!=pNC
->nRef
){
1229 ExprSetProperty(pExpr
, EP_VarSelect
);
1230 pNC
->ncFlags
|= NC_VarSelect
;
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
);
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
;
1259 /* no break */ deliberate_fall_through
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
);
1279 assert( pExpr
->pRight
!=0 );
1280 nRight
= sqlite3ExprVectorSize(pExpr
->pRight
);
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
);
1298 assert( pParse
->db
->mallocFailed
==0 || pParse
->nErr
!=0 );
1299 return pParse
->nErr
? WRC_Abort
: WRC_Continue
;
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
1312 ** pEList has been resolved. pE has not.
1314 static 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 */
1319 int i
; /* Loop counter */
1321 UNUSED_PARAMETER(pParse
);
1323 if( pE
->op
==TK_ID
){
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
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
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.
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
1354 ** If there is no match, return 0. Return -1 if an error occurs.
1356 static 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 */
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 */
1368 assert( sqlite3ExprIsInteger(pE
, &i
)==0 );
1369 pEList
= pSelect
->pEList
;
1371 /* Resolve all names in the ORDER BY term expression
1373 memset(&nc
, 0, sizeof(nc
));
1375 nc
.pSrcList
= pSelect
->pSrc
;
1376 nc
.uNC
.pEList
= pEList
;
1377 nc
.ncFlags
= NC_AllowAgg
|NC_UEList
|NC_NoSelect
;
1380 savedSuppErr
= db
->suppressErr
;
1381 db
->suppressErr
= 1;
1382 rc
= sqlite3ResolveExprNames(&nc
, pE
);
1383 db
->suppressErr
= savedSuppErr
;
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.
1390 for(i
=0; i
<pEList
->nExpr
; i
++){
1391 if( sqlite3ExprCompare(0, pEList
->a
[i
].pExpr
, pE
, -1)<2 ){
1396 /* If no match, return 0. */
1401 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1403 static 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 */
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
);
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.
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.
1429 ** Return the number of errors seen.
1431 static int resolveCompoundOrderBy(
1432 Parse
*pParse
, /* Parsing context. Leave error messages here */
1433 Select
*pSelect
/* The SELECT statement containing the ORDER BY */
1441 pOrderBy
= pSelect
->pOrderBy
;
1442 if( pOrderBy
==0 ) return 0;
1444 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1445 sqlite3ErrorMsg(pParse
, "too many terms in ORDER BY clause");
1448 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1449 pOrderBy
->a
[i
].fg
.done
= 0;
1452 while( pSelect
->pPrior
){
1453 pSelect
->pPrior
->pNext
= pSelect
;
1454 pSelect
= pSelect
->pPrior
;
1456 while( pSelect
&& moreToDo
){
1457 struct ExprList_item
*pItem
;
1459 pEList
= pSelect
->pEList
;
1460 assert( pEList
!=0 );
1461 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
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
);
1473 iCol
= resolveAsName(pParse
, pEList
, pE
);
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
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
){
1489 iCol
= resolveOrderByTermToExprList(pParse
, pSelect
, pDup
);
1490 if( IN_RENAME_OBJECT
&& iCol
>0 ){
1491 resolveOrderByTermToExprList(pParse
, pSelect
, pE
);
1494 sqlite3ExprDelete(db
, pDup
);
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
;
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
;
1514 sqlite3ExprDelete(db
, pE
);
1515 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1522 pSelect
= pSelect
->pNext
;
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);
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
1541 ** If any errors are detected, add an error message to pParse and
1542 ** return non-zero. Return zero if no errors are seen.
1544 int 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" */
1551 sqlite3
*db
= pParse
->db
;
1553 struct ExprList_item
*pItem
;
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
);
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);
1568 resolveAlias(pParse
, pEList
, pItem
->u
.x
.iOrderByCol
-1, pItem
->pExpr
,0);
1574 #ifndef SQLITE_OMIT_WINDOWFUNC
1576 ** Walker callback for windowRemoveExprFromSelect().
1578 static 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
);
1584 return WRC_Continue
;
1588 ** Remove any Window objects owned by the expression pExpr from the
1589 ** Select.pWin list of Select object pSelect.
1591 static void windowRemoveExprFromSelect(Select
*pSelect
, Expr
*pExpr
){
1592 if( pSelect
->pWin
){
1594 memset(&sWalker
, 0, sizeof(Walker
));
1595 sWalker
.xExprCallback
= resolveRemoveWindowsCb
;
1596 sWalker
.u
.pSelect
= pSelect
;
1597 sqlite3WalkExpr(&sWalker
, pExpr
);
1601 # define windowRemoveExprFromSelect(a, b)
1602 #endif /* SQLITE_OMIT_WINDOWFUNC */
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.
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().
1618 ** This routine returns the number of errors. If errors occur, then
1619 ** an appropriate error message might be left in pParse. (OOM errors
1622 static 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 */
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 */
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
);
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
;
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
);
1660 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1664 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1665 pItem
->u
.x
.iOrderByCol
= 0;
1666 if( sqlite3ResolveExprNames(pNC
, pE
) ){
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;
1679 return sqlite3ResolveOrderGroupBy(pParse
, pSelect
, pOrderBy
, zType
);
1683 ** Resolve names in the SELECT statement p and all of its descendants.
1685 static 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 */
1698 if( p
->selFlags
& SF_Resolved
){
1701 pOuterNC
= pWalker
->u
.pNC
;
1702 pParse
= pWalker
->pParse
;
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.
1713 if( (p
->selFlags
& SF_Expanded
)==0 ){
1714 sqlite3SelectPrep(pParse
, p
, pOuterNC
);
1715 return pParse
->nErr
? WRC_Abort
: WRC_Prune
;
1718 isCompound
= p
->pPrior
!=0;
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
;
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.
1731 memset(&sNC
, 0, sizeof(sNC
));
1732 sNC
.pParse
= pParse
;
1734 if( sqlite3ResolveExprNames(&sNC
, p
->pLimit
) ){
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
;
1752 /* Recursively resolve names in all subqueries in the FROM clause
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
;
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 );
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. */
1773 assert( pItem
->fg
.isCorrelated
==0 && pOuterNC
->nRef
>=nRef
);
1774 pItem
->fg
.isCorrelated
= (pOuterNC
->nRef
>nRef
);
1779 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1780 ** resolve the result-set expression list.
1782 sNC
.ncFlags
= NC_AllowAgg
|NC_AllowWin
;
1783 sNC
.pSrcList
= p
->pSrc
;
1784 sNC
.pNext
= pOuterNC
;
1786 /* Resolve names in the result set. */
1787 if( sqlite3ResolveExprListNames(&sNC
, p
->pEList
) ) return WRC_Abort
;
1788 sNC
.ncFlags
&= ~NC_AllowWin
;
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.
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
));
1800 sNC
.ncFlags
&= ~NC_AllowAgg
;
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.
1808 ** Minor point: If this is the case, then the expression will be
1809 ** re-evaluated for each reference to it.
1811 assert( (sNC
.ncFlags
& (NC_UAggInfo
|NC_UUpsert
|NC_UBaseReg
))==0 );
1812 sNC
.uNC
.pEList
= p
->pEList
;
1813 sNC
.ncFlags
|= NC_UEList
;
1815 if( (p
->selFlags
& SF_Aggregate
)==0 ){
1816 sqlite3ErrorMsg(pParse
, "HAVING clause on a non-aggregate query");
1819 if( sqlite3ResolveExprNames(&sNC
, p
->pHaving
) ) return WRC_Abort
;
1821 if( sqlite3ResolveExprNames(&sNC
, p
->pWhere
) ) return WRC_Abort
;
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
)
1833 #ifndef SQLITE_OMIT_WINDOWFUNC
1834 if( IN_RENAME_OBJECT
){
1836 for(pWin
=p
->pWinDefn
; pWin
; pWin
=pWin
->pNextWin
){
1837 if( sqlite3ResolveExprListNames(&sNC
, pWin
->pOrderBy
)
1838 || sqlite3ResolveExprListNames(&sNC
, pWin
->pPartition
)
1846 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1850 sNC
.ncFlags
|= NC_AllowAgg
|NC_AllowWin
;
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
;
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.
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.
1874 && isCompound
<=nCompound
/* Defer right-most ORDER BY of a compound */
1875 && resolveOrderGroupBy(&sNC
, p
, p
->pOrderBy
, "ORDER")
1879 if( db
->mallocFailed
){
1882 sNC
.ncFlags
&= ~NC_AllowWin
;
1884 /* Resolve the GROUP BY clause. At the same time, make sure
1885 ** the GROUP BY clause does not contain aggregate functions.
1888 struct ExprList_item
*pItem
;
1890 if( resolveOrderGroupBy(&sNC
, p
, pGroupBy
, "GROUP") || db
->mallocFailed
){
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");
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
);
1909 /* Advance to the next term of the compound
1915 /* Resolve the ORDER BY on a compound SELECT after all terms of
1916 ** the compound have been resolved.
1918 if( isCompound
&& resolveCompoundOrderBy(pParse
, pLeftmost
) ){
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
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
1934 ** X: The name of a database. Ex: "main" or "temp" or
1935 ** the symbolic name assigned to an ATTACH-ed database.
1937 ** Y: The name of a table in a FROM clause. Or in a trigger
1938 ** one of the special names "old" or "new".
1940 ** Z: The name of a column in table Y.
1942 ** The node at the root of the subtree is modified as follows:
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
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:
1957 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1959 ** The "x" term of the order by is replaced by "a+b" to render:
1961 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
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.
1970 ** An error message is left in pParse if anything is amiss. The number
1971 ** if errors is returned.
1973 int sqlite3ResolveExprNames(
1974 NameContext
*pNC
, /* Namespace to resolve expressions in. */
1975 Expr
*pExpr
/* The expression to be analyzed. */
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;
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
;
1994 sqlite3WalkExpr(&w
, pExpr
);
1995 #if SQLITE_MAX_EXPR_DEPTH>0
1996 w
.pParse
->nHeight
-= pExpr
->nHeight
;
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;
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.
2012 int sqlite3ResolveExprListNames(
2013 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2014 ExprList
*pList
/* The expression list to be analyzed. */
2017 int savedHasAgg
= 0;
2019 if( pList
==0 ) return WRC_Continue
;
2020 w
.pParse
= pNC
->pParse
;
2021 w
.xExprCallback
= resolveExprStep
;
2022 w
.xSelectCallback
= resolveSelectStep
;
2023 w
.xSelectCallback2
= 0;
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
) ){
2036 sqlite3WalkExpr(&w
, pExpr
);
2037 #if SQLITE_MAX_EXPR_DEPTH>0
2038 w
.pParse
->nHeight
-= pExpr
->nHeight
;
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
);
2050 if( w
.pParse
->nErr
>0 ) return WRC_Abort
;
2052 pNC
->ncFlags
|= savedHasAgg
;
2053 return WRC_Continue
;
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
2062 ** See sqlite3ResolveExprNames() for a description of the kinds of
2063 ** transformations that occur.
2065 ** All SELECT statements should have been expanded using
2066 ** sqlite3SelectExpand() prior to invoking this routine.
2068 void sqlite3ResolveSelectNames(
2069 Parse
*pParse
, /* The parser context */
2070 Select
*p
, /* The SELECT statement being coded. */
2071 NameContext
*pOuterNC
/* Name context for parent SELECT statement */
2076 w
.xExprCallback
= resolveExprStep
;
2077 w
.xSelectCallback
= resolveSelectStep
;
2078 w
.xSelectCallback2
= 0;
2081 sqlite3WalkSelect(&w
, p
);
2085 ** Resolve names in expressions that can only reference a single table
2086 ** or which cannot reference any tables at all. Examples:
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
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.
2100 ** Any errors cause an error message to be set in pParse.
2102 int 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. */
2109 SrcList sSrc
; /* Fake SrcList for pParse->pNewTable */
2110 NameContext sNC
; /* Name context for pParse->pNewTable */
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
));
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 */
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
);