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
);
88 incrAggFunctionDepth(pDup
, nSubquery
);
89 if( pExpr
->op
==TK_COLLATE
){
90 pDup
= sqlite3ExprAddCollateString(pParse
, pDup
, pExpr
->u
.zToken
);
93 /* Before calling sqlite3ExprDelete(), set the EP_Static flag. This
94 ** prevents ExprDelete() from deleting the Expr structure itself,
95 ** allowing it to be repopulated by the memcpy() on the following line.
96 ** The pExpr->u.zToken might point into memory that will be freed by the
97 ** sqlite3DbFree(db, pDup) on the last line of this block, so be sure to
98 ** make a copy of the token before doing the sqlite3DbFree().
100 ExprSetProperty(pExpr
, EP_Static
);
101 sqlite3ExprDelete(db
, pExpr
);
102 memcpy(pExpr
, pDup
, sizeof(*pExpr
));
103 if( !ExprHasProperty(pExpr
, EP_IntValue
) && pExpr
->u
.zToken
!=0 ){
104 assert( (pExpr
->flags
& (EP_Reduced
|EP_TokenOnly
))==0 );
105 pExpr
->u
.zToken
= sqlite3DbStrDup(db
, pExpr
->u
.zToken
);
106 pExpr
->flags
|= EP_MemToken
;
108 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
109 if( ALWAYS(pExpr
->y
.pWin
!=0) ){
110 pExpr
->y
.pWin
->pOwner
= pExpr
;
113 sqlite3DbFree(db
, pDup
);
119 ** Return TRUE if the name zCol occurs anywhere in the USING clause.
121 ** Return FALSE if the USING clause is NULL or if it does not contain
124 static int nameInUsingClause(IdList
*pUsing
, const char *zCol
){
127 for(k
=0; k
<pUsing
->nId
; k
++){
128 if( sqlite3StrICmp(pUsing
->a
[k
].zName
, zCol
)==0 ) return 1;
135 ** Subqueries stores the original database, table and column names for their
136 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN".
137 ** Check to see if the zSpan given to this routine matches the zDb, zTab,
138 ** and zCol. If any of zDb, zTab, and zCol are NULL then those fields will
141 int sqlite3MatchEName(
142 const struct ExprList_item
*pItem
,
149 if( pItem
->eEName
!=ENAME_TAB
) return 0;
150 zSpan
= pItem
->zEName
;
151 for(n
=0; ALWAYS(zSpan
[n
]) && zSpan
[n
]!='.'; n
++){}
152 if( zDb
&& (sqlite3StrNICmp(zSpan
, zDb
, n
)!=0 || zDb
[n
]!=0) ){
156 for(n
=0; ALWAYS(zSpan
[n
]) && zSpan
[n
]!='.'; n
++){}
157 if( zTab
&& (sqlite3StrNICmp(zSpan
, zTab
, n
)!=0 || zTab
[n
]!=0) ){
161 if( zCol
&& sqlite3StrICmp(zSpan
, zCol
)!=0 ){
168 ** Return TRUE if the double-quoted string mis-feature should be supported.
170 static int areDoubleQuotedStringsEnabled(sqlite3
*db
, NameContext
*pTopNC
){
171 if( db
->init
.busy
) return 1; /* Always support for legacy schemas */
172 if( pTopNC
->ncFlags
& NC_IsDDL
){
173 /* Currently parsing a DDL statement */
174 if( sqlite3WritableSchema(db
) && (db
->flags
& SQLITE_DqsDML
)!=0 ){
177 return (db
->flags
& SQLITE_DqsDDL
)!=0;
179 /* Currently parsing a DML statement */
180 return (db
->flags
& SQLITE_DqsDML
)!=0;
185 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
186 ** return the appropriate colUsed mask.
188 Bitmask
sqlite3ExprColUsed(Expr
*pExpr
){
193 pExTab
= pExpr
->y
.pTab
;
195 if( (pExTab
->tabFlags
& TF_HasGenerated
)!=0
196 && (pExTab
->aCol
[n
].colFlags
& COLFLAG_GENERATED
)!=0
198 testcase( pExTab
->nCol
==BMS
-1 );
199 testcase( pExTab
->nCol
==BMS
);
200 return pExTab
->nCol
>=BMS
? ALLBITS
: MASKBIT(pExTab
->nCol
)-1;
202 testcase( n
==BMS
-1 );
204 if( n
>=BMS
) n
= BMS
-1;
205 return ((Bitmask
)1)<<n
;
210 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
211 ** that name in the set of source tables in pSrcList and make the pExpr
212 ** expression node refer back to that source column. The following changes
213 ** are made to pExpr:
215 ** pExpr->iDb Set the index in db->aDb[] of the database X
216 ** (even if X is implied).
217 ** pExpr->iTable Set to the cursor number for the table obtained
219 ** pExpr->y.pTab Points to the Table structure of X.Y (even if
220 ** X and/or Y are implied.)
221 ** pExpr->iColumn Set to the column number within the table.
222 ** pExpr->op Set to TK_COLUMN.
223 ** pExpr->pLeft Any expression this points to is deleted
224 ** pExpr->pRight Any expression this points to is deleted.
226 ** The zDb variable is the name of the database (the "X"). This value may be
227 ** NULL meaning that name is of the form Y.Z or Z. Any available database
228 ** can be used. The zTable variable is the name of the table (the "Y"). This
229 ** value can be NULL if zDb is also NULL. If zTable is NULL it
230 ** means that the form of the name is Z and that columns from any table
233 ** If the name cannot be resolved unambiguously, leave an error message
234 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
236 static int lookupName(
237 Parse
*pParse
, /* The parsing context */
238 const char *zDb
, /* Name of the database containing table, or NULL */
239 const char *zTab
, /* Name of table containing column, or NULL */
240 const char *zCol
, /* Name of the column. */
241 NameContext
*pNC
, /* The name context used to resolve the name */
242 Expr
*pExpr
/* Make this EXPR node point to the selected column */
244 int i
, j
; /* Loop counters */
245 int cnt
= 0; /* Number of matching column names */
246 int cntTab
= 0; /* Number of matching table names */
247 int nSubquery
= 0; /* How many levels of subquery */
248 sqlite3
*db
= pParse
->db
; /* The database connection */
249 SrcItem
*pItem
; /* Use for looping over pSrcList items */
250 SrcItem
*pMatch
= 0; /* The matching pSrcList item */
251 NameContext
*pTopNC
= pNC
; /* First namecontext in the list */
252 Schema
*pSchema
= 0; /* Schema of the expression */
253 int eNewExprOp
= TK_COLUMN
; /* New value for pExpr->op on success */
254 Table
*pTab
= 0; /* Table hold the row */
255 Column
*pCol
; /* A column of pTab */
257 assert( pNC
); /* the name context cannot be NULL. */
258 assert( zCol
); /* The Z in X.Y.Z cannot be NULL */
259 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
261 /* Initialize the node to no-match */
263 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
265 /* Translate the schema name in zDb into a pointer to the corresponding
266 ** schema. If not found, pSchema will remain NULL and nothing will match
267 ** resulting in an appropriate error message toward the end of this routine
270 testcase( pNC
->ncFlags
& NC_PartIdx
);
271 testcase( pNC
->ncFlags
& NC_IsCheck
);
272 if( (pNC
->ncFlags
& (NC_PartIdx
|NC_IsCheck
))!=0 ){
273 /* Silently ignore database qualifiers inside CHECK constraints and
274 ** partial indices. Do not raise errors because that might break
275 ** legacy and because it does not hurt anything to just ignore the
279 for(i
=0; i
<db
->nDb
; i
++){
280 assert( db
->aDb
[i
].zDbSName
);
281 if( sqlite3StrICmp(db
->aDb
[i
].zDbSName
,zDb
)==0 ){
282 pSchema
= db
->aDb
[i
].pSchema
;
286 if( i
==db
->nDb
&& sqlite3StrICmp("main", zDb
)==0 ){
287 /* This branch is taken when the main database has been renamed
288 ** using SQLITE_DBCONFIG_MAINDBNAME. */
289 pSchema
= db
->aDb
[0].pSchema
;
290 zDb
= db
->aDb
[0].zDbSName
;
295 /* Start at the inner-most context and move outward until a match is found */
296 assert( pNC
&& cnt
==0 );
299 SrcList
*pSrcList
= pNC
->pSrcList
;
302 for(i
=0, pItem
=pSrcList
->a
; i
<pSrcList
->nSrc
; i
++, pItem
++){
305 assert( pTab
!=0 && pTab
->zName
!=0 );
306 assert( pTab
->nCol
>0 );
307 if( pItem
->pSelect
&& (pItem
->pSelect
->selFlags
& SF_NestedFrom
)!=0 ){
309 pEList
= pItem
->pSelect
->pEList
;
310 for(j
=0; j
<pEList
->nExpr
; j
++){
311 if( sqlite3MatchEName(&pEList
->a
[j
], zCol
, zTab
, zDb
) ){
319 if( hit
|| zTab
==0 ) continue;
321 if( zDb
&& pTab
->pSchema
!=pSchema
){
325 const char *zTabName
= pItem
->zAlias
? pItem
->zAlias
: pTab
->zName
;
326 assert( zTabName
!=0 );
327 if( sqlite3StrICmp(zTabName
, zTab
)!=0 ){
330 if( IN_RENAME_OBJECT
&& pItem
->zAlias
){
331 sqlite3RenameTokenRemap(pParse
, 0, (void*)&pExpr
->y
.pTab
);
337 hCol
= sqlite3StrIHash(zCol
);
338 for(j
=0, pCol
=pTab
->aCol
; j
<pTab
->nCol
; j
++, pCol
++){
339 if( pCol
->hName
==hCol
&& sqlite3StrICmp(pCol
->zName
, zCol
)==0 ){
340 /* If there has been exactly one prior match and this match
341 ** is for the right-hand table of a NATURAL JOIN or is in a
342 ** USING clause, then skip this match.
345 if( pItem
->fg
.jointype
& JT_NATURAL
) continue;
346 if( nameInUsingClause(pItem
->pUsing
, zCol
) ) continue;
350 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
351 pExpr
->iColumn
= j
==pTab
->iPKey
? -1 : (i16
)j
;
357 pExpr
->iTable
= pMatch
->iCursor
;
358 pExpr
->y
.pTab
= pMatch
->pTab
;
359 /* RIGHT JOIN not (yet) supported */
360 assert( (pMatch
->fg
.jointype
& JT_RIGHT
)==0 );
361 if( (pMatch
->fg
.jointype
& JT_LEFT
)!=0 ){
362 ExprSetProperty(pExpr
, EP_CanBeNull
);
364 pSchema
= pExpr
->y
.pTab
->pSchema
;
366 } /* if( pSrcList ) */
368 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
369 /* If we have not already resolved the name, then maybe
370 ** it is a new.* or old.* trigger argument reference. Or
371 ** maybe it is an excluded.* from an upsert. Or maybe it is
372 ** a reference in the RETURNING clause to a table being modified.
374 if( cnt
==0 && zDb
==0 ){
376 #ifndef SQLITE_OMIT_TRIGGER
377 if( pParse
->pTriggerTab
!=0 ){
378 int op
= pParse
->eTriggerOp
;
379 assert( op
==TK_DELETE
|| op
==TK_UPDATE
|| op
==TK_INSERT
);
380 if( pParse
->bReturning
){
381 if( (pNC
->ncFlags
& NC_UBaseReg
)!=0
382 && (zTab
==0 || sqlite3StrICmp(zTab
,pParse
->pTriggerTab
->zName
)==0)
384 pExpr
->iTable
= op
!=TK_DELETE
;
385 pTab
= pParse
->pTriggerTab
;
387 }else if( op
!=TK_DELETE
&& zTab
&& sqlite3StrICmp("new",zTab
) == 0 ){
389 pTab
= pParse
->pTriggerTab
;
390 }else if( op
!=TK_INSERT
&& zTab
&& sqlite3StrICmp("old",zTab
)==0 ){
392 pTab
= pParse
->pTriggerTab
;
395 #endif /* SQLITE_OMIT_TRIGGER */
396 #ifndef SQLITE_OMIT_UPSERT
397 if( (pNC
->ncFlags
& NC_UUpsert
)!=0 && zTab
!=0 ){
398 Upsert
*pUpsert
= pNC
->uNC
.pUpsert
;
399 if( pUpsert
&& sqlite3StrICmp("excluded",zTab
)==0 ){
400 pTab
= pUpsert
->pUpsertSrc
->a
[0].pTab
;
401 pExpr
->iTable
= EXCLUDED_TABLE_NUMBER
;
404 #endif /* SQLITE_OMIT_UPSERT */
408 u8 hCol
= sqlite3StrIHash(zCol
);
409 pSchema
= pTab
->pSchema
;
411 for(iCol
=0, pCol
=pTab
->aCol
; iCol
<pTab
->nCol
; iCol
++, pCol
++){
412 if( pCol
->hName
==hCol
&& sqlite3StrICmp(pCol
->zName
, zCol
)==0 ){
413 if( iCol
==pTab
->iPKey
){
419 if( iCol
>=pTab
->nCol
&& sqlite3IsRowid(zCol
) && VisibleRowid(pTab
) ){
420 /* IMP: R-51414-32910 */
423 if( iCol
<pTab
->nCol
){
426 #ifndef SQLITE_OMIT_UPSERT
427 if( pExpr
->iTable
==EXCLUDED_TABLE_NUMBER
){
428 testcase( iCol
==(-1) );
429 if( IN_RENAME_OBJECT
){
430 pExpr
->iColumn
= iCol
;
431 pExpr
->y
.pTab
= pTab
;
432 eNewExprOp
= TK_COLUMN
;
434 pExpr
->iTable
= pNC
->uNC
.pUpsert
->regData
+
435 sqlite3TableColumnToStorage(pTab
, iCol
);
436 eNewExprOp
= TK_REGISTER
;
439 #endif /* SQLITE_OMIT_UPSERT */
441 pExpr
->y
.pTab
= pTab
;
442 if( pParse
->bReturning
){
443 eNewExprOp
= TK_REGISTER
;
444 pExpr
->iTable
= pNC
->uNC
.iBaseReg
+ (pTab
->nCol
+1)*pExpr
->iTable
+
445 sqlite3TableColumnToStorage(pTab
, iCol
) + 1;
447 pExpr
->iColumn
= (i16
)iCol
;
448 eNewExprOp
= TK_TRIGGER
;
449 #ifndef SQLITE_OMIT_TRIGGER
451 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
452 }else if( pExpr
->iTable
==0 ){
453 testcase( iCol
==31 );
454 testcase( iCol
==32 );
455 pParse
->oldmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
457 testcase( iCol
==31 );
458 testcase( iCol
==32 );
459 pParse
->newmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
461 #endif /* SQLITE_OMIT_TRIGGER */
467 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
470 ** Perhaps the name is a reference to the ROWID
475 && (pNC
->ncFlags
& (NC_IdxExpr
|NC_GenCol
))==0
476 && sqlite3IsRowid(zCol
)
477 && VisibleRowid(pMatch
->pTab
)
481 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
485 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
486 ** might refer to an result-set alias. This happens, for example, when
487 ** we are resolving names in the WHERE clause of the following command:
489 ** SELECT a+b AS x FROM table WHERE x<10;
491 ** In cases like this, replace pExpr with a copy of the expression that
492 ** forms the result set entry ("a+b" in the example) and return immediately.
493 ** Note that the expression in the result set should have already been
494 ** resolved by the time the WHERE clause is resolved.
496 ** The ability to use an output result-set column in the WHERE, GROUP BY,
497 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
498 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
499 ** is supported for backwards compatibility only. Hence, we issue a warning
500 ** on sqlite3_log() whenever the capability is used.
503 && (pNC
->ncFlags
& NC_UEList
)!=0
506 pEList
= pNC
->uNC
.pEList
;
508 for(j
=0; j
<pEList
->nExpr
; j
++){
509 char *zAs
= pEList
->a
[j
].zEName
;
510 if( pEList
->a
[j
].eEName
==ENAME_NAME
511 && sqlite3_stricmp(zAs
, zCol
)==0
514 assert( pExpr
->pLeft
==0 && pExpr
->pRight
==0 );
515 assert( pExpr
->x
.pList
==0 );
516 assert( pExpr
->x
.pSelect
==0 );
517 pOrig
= pEList
->a
[j
].pExpr
;
518 if( (pNC
->ncFlags
&NC_AllowAgg
)==0 && ExprHasProperty(pOrig
, EP_Agg
) ){
519 sqlite3ErrorMsg(pParse
, "misuse of aliased aggregate %s", zAs
);
522 if( ExprHasProperty(pOrig
, EP_Win
)
523 && ((pNC
->ncFlags
&NC_AllowWin
)==0 || pNC
!=pTopNC
)
525 sqlite3ErrorMsg(pParse
, "misuse of aliased window function %s",zAs
);
528 if( sqlite3ExprVectorSize(pOrig
)!=1 ){
529 sqlite3ErrorMsg(pParse
, "row value misused");
532 resolveAlias(pParse
, pEList
, j
, pExpr
, nSubquery
);
535 assert( zTab
==0 && zDb
==0 );
536 if( IN_RENAME_OBJECT
){
537 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
544 /* Advance to the next name context. The loop will exit when either
545 ** we have a match (cnt>0) or when we run out of name contexts.
554 ** If X and Y are NULL (in other words if only the column name Z is
555 ** supplied) and the value of Z is enclosed in double-quotes, then
556 ** Z is a string literal if it doesn't match any column names. In that
557 ** case, we need to return right away and not make any changes to
560 ** Because no reference was made to outer contexts, the pNC->nRef
561 ** fields are not changed in any context.
563 if( cnt
==0 && zTab
==0 ){
564 assert( pExpr
->op
==TK_ID
);
565 if( ExprHasProperty(pExpr
,EP_DblQuoted
)
566 && areDoubleQuotedStringsEnabled(db
, pTopNC
)
568 /* If a double-quoted identifier does not match any known column name,
569 ** then treat it as a string.
571 ** This hack was added in the early days of SQLite in a misguided attempt
572 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
573 ** I now sorely regret putting in this hack. The effect of this hack is
574 ** that misspelled identifier names are silently converted into strings
575 ** rather than causing an error, to the frustration of countless
576 ** programmers. To all those frustrated programmers, my apologies.
578 ** Someday, I hope to get rid of this hack. Unfortunately there is
579 ** a huge amount of legacy SQL that uses it. So for now, we just
582 sqlite3_log(SQLITE_WARNING
,
583 "double-quoted string literal: \"%w\"", zCol
);
584 #ifdef SQLITE_ENABLE_NORMALIZE
585 sqlite3VdbeAddDblquoteStr(db
, pParse
->pVdbe
, zCol
);
587 pExpr
->op
= TK_STRING
;
591 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
597 ** cnt==0 means there was not match. cnt>1 means there were two or
598 ** more matches. Either way, we have an error.
602 zErr
= cnt
==0 ? "no such column" : "ambiguous column name";
604 sqlite3ErrorMsg(pParse
, "%s: %s.%s.%s", zErr
, zDb
, zTab
, zCol
);
606 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zErr
, zTab
, zCol
);
608 sqlite3ErrorMsg(pParse
, "%s: %s", zErr
, zCol
);
610 pParse
->checkSchema
= 1;
614 /* If a column from a table in pSrcList is referenced, then record
615 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
616 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
617 ** set if the 63rd or any subsequent column is used.
619 ** The colUsed mask is an optimization used to help determine if an
620 ** index is a covering index. The correct answer is still obtained
621 ** if the mask contains extra set bits. However, it is important to
622 ** avoid setting bits beyond the maximum column number of the table.
623 ** (See ticket [b92e5e8ec2cdbaa1]).
625 ** If a generated column is referenced, set bits for every column
628 if( pExpr
->iColumn
>=0 && pMatch
!=0 ){
629 pMatch
->colUsed
|= sqlite3ExprColUsed(pExpr
);
632 /* Clean up and return
634 if( !ExprHasProperty(pExpr
,(EP_TokenOnly
|EP_Leaf
)) ){
635 sqlite3ExprDelete(db
, pExpr
->pLeft
);
637 sqlite3ExprDelete(db
, pExpr
->pRight
);
640 pExpr
->op
= eNewExprOp
;
641 ExprSetProperty(pExpr
, EP_Leaf
);
645 #ifndef SQLITE_OMIT_AUTHORIZATION
646 if( pParse
->db
->xAuth
647 && (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_TRIGGER
)
649 sqlite3AuthRead(pParse
, pExpr
, pSchema
, pNC
->pSrcList
);
652 /* Increment the nRef value on all name contexts from TopNC up to
653 ** the point where the name matched. */
657 if( pTopNC
==pNC
) break;
658 pTopNC
= pTopNC
->pNext
;
667 ** Allocate and return a pointer to an expression to load the column iCol
668 ** from datasource iSrc in SrcList pSrc.
670 Expr
*sqlite3CreateColumnExpr(sqlite3
*db
, SrcList
*pSrc
, int iSrc
, int iCol
){
671 Expr
*p
= sqlite3ExprAlloc(db
, TK_COLUMN
, 0, 0);
673 SrcItem
*pItem
= &pSrc
->a
[iSrc
];
674 Table
*pTab
= p
->y
.pTab
= pItem
->pTab
;
675 p
->iTable
= pItem
->iCursor
;
676 if( p
->y
.pTab
->iPKey
==iCol
){
679 p
->iColumn
= (ynVar
)iCol
;
680 if( (pTab
->tabFlags
& TF_HasGenerated
)!=0
681 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_GENERATED
)!=0
683 testcase( pTab
->nCol
==63 );
684 testcase( pTab
->nCol
==64 );
685 pItem
->colUsed
= pTab
->nCol
>=64 ? ALLBITS
: MASKBIT(pTab
->nCol
)-1;
687 testcase( iCol
==BMS
);
688 testcase( iCol
==BMS
-1 );
689 pItem
->colUsed
|= ((Bitmask
)1)<<(iCol
>=BMS
? BMS
-1 : iCol
);
697 ** Report an error that an expression is not valid for some set of
698 ** pNC->ncFlags values determined by validMask.
700 ** static void notValid(
701 ** Parse *pParse, // Leave error message here
702 ** NameContext *pNC, // The name context
703 ** const char *zMsg, // Type of error
704 ** int validMask, // Set of contexts for which prohibited
705 ** Expr *pExpr // Invalidate this expression on error
708 ** As an optimization, since the conditional is almost always false
709 ** (because errors are rare), the conditional is moved outside of the
710 ** function call using a macro.
712 static void notValidImpl(
713 Parse
*pParse
, /* Leave error message here */
714 NameContext
*pNC
, /* The name context */
715 const char *zMsg
, /* Type of error */
716 Expr
*pExpr
/* Invalidate this expression on error */
718 const char *zIn
= "partial index WHERE clauses";
719 if( pNC
->ncFlags
& NC_IdxExpr
) zIn
= "index expressions";
720 #ifndef SQLITE_OMIT_CHECK
721 else if( pNC
->ncFlags
& NC_IsCheck
) zIn
= "CHECK constraints";
723 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
724 else if( pNC
->ncFlags
& NC_GenCol
) zIn
= "generated columns";
726 sqlite3ErrorMsg(pParse
, "%s prohibited in %s", zMsg
, zIn
);
727 if( pExpr
) pExpr
->op
= TK_NULL
;
729 #define sqlite3ResolveNotValid(P,N,M,X,E) \
730 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
731 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E);
734 ** Expression p should encode a floating point value between 1.0 and 0.0.
735 ** Return 1024 times this value. Or return -1 if p is not a floating point
736 ** value between 1.0 and 0.0.
738 static int exprProbability(Expr
*p
){
740 if( p
->op
!=TK_FLOAT
) return -1;
741 sqlite3AtoF(p
->u
.zToken
, &r
, sqlite3Strlen30(p
->u
.zToken
), SQLITE_UTF8
);
743 if( r
>1.0 ) return -1;
744 return (int)(r
*134217728.0);
748 ** This routine is callback for sqlite3WalkExpr().
750 ** Resolve symbolic names into TK_COLUMN operators for the current
751 ** node in the expression tree. Return 0 to continue the search down
752 ** the tree or 2 to abort the tree walk.
754 ** This routine also does error checking and name resolution for
755 ** function names. The operator for aggregate functions is changed
756 ** to TK_AGG_FUNCTION.
758 static int resolveExprStep(Walker
*pWalker
, Expr
*pExpr
){
762 pNC
= pWalker
->u
.pNC
;
764 pParse
= pNC
->pParse
;
765 assert( pParse
==pWalker
->pParse
);
768 if( pNC
->pSrcList
&& pNC
->pSrcList
->nAlloc
>0 ){
769 SrcList
*pSrcList
= pNC
->pSrcList
;
771 for(i
=0; i
<pNC
->pSrcList
->nSrc
; i
++){
772 assert( pSrcList
->a
[i
].iCursor
>=0 && pSrcList
->a
[i
].iCursor
<pParse
->nTab
);
778 /* The special operator TK_ROW means use the rowid for the first
779 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
780 ** clause processing on UPDATE and DELETE statements, and by
781 ** UPDATE ... FROM statement processing.
784 SrcList
*pSrcList
= pNC
->pSrcList
;
786 assert( pSrcList
&& pSrcList
->nSrc
>=1 );
788 pExpr
->op
= TK_COLUMN
;
789 pExpr
->y
.pTab
= pItem
->pTab
;
790 pExpr
->iTable
= pItem
->iCursor
;
792 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
796 /* An optimization: Attempt to convert
798 ** "expr IS NOT NULL" --> "TRUE"
799 ** "expr IS NULL" --> "FALSE"
801 ** if we can prove that "expr" is never NULL. Call this the
802 ** "NOT NULL strength reduction optimization".
804 ** If this optimization occurs, also restore the NameContext ref-counts
805 ** to the state they where in before the "column" LHS expression was
806 ** resolved. This prevents "column" from being counted as having been
807 ** referenced, which might prevent a SELECT from being erroneously
808 ** marked as correlated.
815 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
818 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
819 if( 0==sqlite3ExprCanBeNull(pExpr
->pLeft
) && !IN_RENAME_OBJECT
){
820 if( pExpr
->op
==TK_NOTNULL
){
821 pExpr
->u
.zToken
= "true";
822 ExprSetProperty(pExpr
, EP_IsTrue
);
824 pExpr
->u
.zToken
= "false";
825 ExprSetProperty(pExpr
, EP_IsFalse
);
827 pExpr
->op
= TK_TRUEFALSE
;
828 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
831 sqlite3ExprDelete(pParse
->db
, pExpr
->pLeft
);
838 ** Or table name and column name: ID.ID
839 ** Or a database, table and column: ID.ID.ID
841 ** The TK_ID and TK_OUT cases are combined so that there will only
842 ** be one call to lookupName(). Then the compiler will in-line
843 ** lookupName() for a size reduction and performance increase.
852 if( pExpr
->op
==TK_ID
){
855 zColumn
= pExpr
->u
.zToken
;
857 Expr
*pLeft
= pExpr
->pLeft
;
858 testcase( pNC
->ncFlags
& NC_IdxExpr
);
859 testcase( pNC
->ncFlags
& NC_GenCol
);
860 sqlite3ResolveNotValid(pParse
, pNC
, "the \".\" operator",
861 NC_IdxExpr
|NC_GenCol
, 0);
862 pRight
= pExpr
->pRight
;
863 if( pRight
->op
==TK_ID
){
866 assert( pRight
->op
==TK_DOT
);
867 zDb
= pLeft
->u
.zToken
;
868 pLeft
= pRight
->pLeft
;
869 pRight
= pRight
->pRight
;
871 zTable
= pLeft
->u
.zToken
;
872 zColumn
= pRight
->u
.zToken
;
873 if( IN_RENAME_OBJECT
){
874 sqlite3RenameTokenRemap(pParse
, (void*)pExpr
, (void*)pRight
);
875 sqlite3RenameTokenRemap(pParse
, (void*)&pExpr
->y
.pTab
, (void*)pLeft
);
878 return lookupName(pParse
, zDb
, zTable
, zColumn
, pNC
, pExpr
);
881 /* Resolve function names
884 ExprList
*pList
= pExpr
->x
.pList
; /* The argument list */
885 int n
= pList
? pList
->nExpr
: 0; /* Number of arguments */
886 int no_such_func
= 0; /* True if no such function exists */
887 int wrong_num_args
= 0; /* True if wrong number of arguments */
888 int is_agg
= 0; /* True if is an aggregate function */
889 int nId
; /* Number of characters in function name */
890 const char *zId
; /* The function name. */
891 FuncDef
*pDef
; /* Information about the function */
892 u8 enc
= ENC(pParse
->db
); /* The database encoding */
893 int savedAllowFlags
= (pNC
->ncFlags
& (NC_AllowAgg
| NC_AllowWin
));
894 #ifndef SQLITE_OMIT_WINDOWFUNC
895 Window
*pWin
= (IsWindowFunc(pExpr
) ? pExpr
->y
.pWin
: 0);
897 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
) );
898 zId
= pExpr
->u
.zToken
;
899 nId
= sqlite3Strlen30(zId
);
900 pDef
= sqlite3FindFunction(pParse
->db
, zId
, n
, enc
, 0);
902 pDef
= sqlite3FindFunction(pParse
->db
, zId
, -2, enc
, 0);
909 is_agg
= pDef
->xFinalize
!=0;
910 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
911 ExprSetProperty(pExpr
, EP_Unlikely
);
913 pExpr
->iTable
= exprProbability(pList
->a
[1].pExpr
);
914 if( pExpr
->iTable
<0 ){
915 sqlite3ErrorMsg(pParse
,
916 "second argument to likelihood() must be a "
917 "constant between 0.0 and 1.0");
921 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
922 ** equivalent to likelihood(X, 0.0625).
923 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
924 ** short-hand for likelihood(X,0.0625).
925 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
926 ** for likelihood(X,0.9375).
927 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
928 ** to likelihood(X,0.9375). */
929 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
930 pExpr
->iTable
= pDef
->zName
[0]=='u' ? 8388608 : 125829120;
933 #ifndef SQLITE_OMIT_AUTHORIZATION
935 int auth
= sqlite3AuthCheck(pParse
, SQLITE_FUNCTION
, 0,pDef
->zName
,0);
936 if( auth
!=SQLITE_OK
){
937 if( auth
==SQLITE_DENY
){
938 sqlite3ErrorMsg(pParse
, "not authorized to use function: %s",
947 if( pDef
->funcFlags
& (SQLITE_FUNC_CONSTANT
|SQLITE_FUNC_SLOCHNG
) ){
948 /* For the purposes of the EP_ConstFunc flag, date and time
949 ** functions and other functions that change slowly are considered
950 ** constant because they are constant for the duration of one query.
951 ** This allows them to be factored out of inner loops. */
952 ExprSetProperty(pExpr
,EP_ConstFunc
);
954 if( (pDef
->funcFlags
& SQLITE_FUNC_CONSTANT
)==0 ){
955 /* Clearly non-deterministic functions like random(), but also
956 ** date/time functions that use 'now', and other functions like
957 ** sqlite_version() that might change over time cannot be used
958 ** in an index or generated column. Curiously, they can be used
959 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
961 sqlite3ResolveNotValid(pParse
, pNC
, "non-deterministic functions",
962 NC_IdxExpr
|NC_PartIdx
|NC_GenCol
, 0);
964 assert( (NC_SelfRef
& 0xff)==NC_SelfRef
); /* Must fit in 8 bits */
965 pExpr
->op2
= pNC
->ncFlags
& NC_SelfRef
;
966 if( pNC
->ncFlags
& NC_FromDDL
) ExprSetProperty(pExpr
, EP_FromDDL
);
968 if( (pDef
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
970 && (pParse
->db
->mDbFlags
& DBFLAG_InternalFunc
)==0
972 /* Internal-use-only functions are disallowed unless the
973 ** SQL is being compiled using sqlite3NestedParse() or
974 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
975 ** used to activate internal functionsn for testing purposes */
979 if( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0
982 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
986 if( 0==IN_RENAME_OBJECT
){
987 #ifndef SQLITE_OMIT_WINDOWFUNC
988 assert( is_agg
==0 || (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)
989 || (pDef
->xValue
==0 && pDef
->xInverse
==0)
990 || (pDef
->xValue
&& pDef
->xInverse
&& pDef
->xSFunc
&& pDef
->xFinalize
)
992 if( pDef
&& pDef
->xValue
==0 && pWin
){
993 sqlite3ErrorMsg(pParse
,
994 "%.*s() may not be used as a window function", nId
, zId
998 (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0)
999 || (is_agg
&& (pDef
->funcFlags
&SQLITE_FUNC_WINDOW
) && !pWin
)
1000 || (is_agg
&& pWin
&& (pNC
->ncFlags
& NC_AllowWin
)==0)
1003 if( (pDef
->funcFlags
& SQLITE_FUNC_WINDOW
) || pWin
){
1006 zType
= "aggregate";
1008 sqlite3ErrorMsg(pParse
, "misuse of %s function %.*s()",zType
,nId
,zId
);
1013 if( (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0) ){
1014 sqlite3ErrorMsg(pParse
,"misuse of aggregate function %.*s()",nId
,zId
);
1019 else if( no_such_func
&& pParse
->db
->init
.busy
==0
1020 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1021 && pParse
->explain
==0
1024 sqlite3ErrorMsg(pParse
, "no such function: %.*s", nId
, zId
);
1026 }else if( wrong_num_args
){
1027 sqlite3ErrorMsg(pParse
,"wrong number of arguments to function %.*s()",
1031 #ifndef SQLITE_OMIT_WINDOWFUNC
1032 else if( is_agg
==0 && ExprHasProperty(pExpr
, EP_WinFunc
) ){
1033 sqlite3ErrorMsg(pParse
,
1034 "FILTER may not be used with non-aggregate %.*s()",
1041 /* Window functions may not be arguments of aggregate functions.
1042 ** Or arguments of other window functions. But aggregate functions
1043 ** may be arguments for window functions. */
1044 #ifndef SQLITE_OMIT_WINDOWFUNC
1045 pNC
->ncFlags
&= ~(NC_AllowWin
| (!pWin
? NC_AllowAgg
: 0));
1047 pNC
->ncFlags
&= ~NC_AllowAgg
;
1051 #ifndef SQLITE_OMIT_WINDOWFUNC
1052 else if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1056 sqlite3WalkExprList(pWalker
, pList
);
1058 #ifndef SQLITE_OMIT_WINDOWFUNC
1060 Select
*pSel
= pNC
->pWinSelect
;
1061 assert( pWin
==pExpr
->y
.pWin
);
1062 if( IN_RENAME_OBJECT
==0 ){
1063 sqlite3WindowUpdate(pParse
, pSel
? pSel
->pWinDefn
: 0, pWin
, pDef
);
1064 if( pParse
->db
->mallocFailed
) break;
1066 sqlite3WalkExprList(pWalker
, pWin
->pPartition
);
1067 sqlite3WalkExprList(pWalker
, pWin
->pOrderBy
);
1068 sqlite3WalkExpr(pWalker
, pWin
->pFilter
);
1069 sqlite3WindowLink(pSel
, pWin
);
1070 pNC
->ncFlags
|= NC_HasWin
;
1072 #endif /* SQLITE_OMIT_WINDOWFUNC */
1074 NameContext
*pNC2
= pNC
;
1075 pExpr
->op
= TK_AGG_FUNCTION
;
1077 #ifndef SQLITE_OMIT_WINDOWFUNC
1078 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1079 sqlite3WalkExpr(pWalker
, pExpr
->y
.pWin
->pFilter
);
1082 while( pNC2
&& !sqlite3FunctionUsesThisSrc(pExpr
, pNC2
->pSrcList
) ){
1086 assert( pDef
!=0 || IN_RENAME_OBJECT
);
1088 assert( SQLITE_FUNC_MINMAX
==NC_MinMaxAgg
);
1089 testcase( (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)!=0 );
1090 pNC2
->ncFlags
|= NC_HasAgg
| (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
);
1094 pNC
->ncFlags
|= savedAllowFlags
;
1096 /* FIX ME: Compute pExpr->affinity based on the expected return
1097 ** type of the function
1101 #ifndef SQLITE_OMIT_SUBQUERY
1103 case TK_EXISTS
: testcase( pExpr
->op
==TK_EXISTS
);
1106 testcase( pExpr
->op
==TK_IN
);
1107 if( ExprHasProperty(pExpr
, EP_xIsSelect
) ){
1108 int nRef
= pNC
->nRef
;
1109 testcase( pNC
->ncFlags
& NC_IsCheck
);
1110 testcase( pNC
->ncFlags
& NC_PartIdx
);
1111 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1112 testcase( pNC
->ncFlags
& NC_GenCol
);
1113 sqlite3ResolveNotValid(pParse
, pNC
, "subqueries",
1114 NC_IsCheck
|NC_PartIdx
|NC_IdxExpr
|NC_GenCol
, pExpr
);
1115 sqlite3WalkSelect(pWalker
, pExpr
->x
.pSelect
);
1116 assert( pNC
->nRef
>=nRef
);
1117 if( nRef
!=pNC
->nRef
){
1118 ExprSetProperty(pExpr
, EP_VarSelect
);
1119 pNC
->ncFlags
|= NC_VarSelect
;
1125 testcase( pNC
->ncFlags
& NC_IsCheck
);
1126 testcase( pNC
->ncFlags
& NC_PartIdx
);
1127 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1128 testcase( pNC
->ncFlags
& NC_GenCol
);
1129 sqlite3ResolveNotValid(pParse
, pNC
, "parameters",
1130 NC_IsCheck
|NC_PartIdx
|NC_IdxExpr
|NC_GenCol
, pExpr
);
1135 Expr
*pRight
= sqlite3ExprSkipCollateAndLikely(pExpr
->pRight
);
1136 assert( !ExprHasProperty(pExpr
, EP_Reduced
) );
1137 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1138 ** and "x IS NOT FALSE". */
1139 if( ALWAYS(pRight
) && (pRight
->op
==TK_ID
|| pRight
->op
==TK_TRUEFALSE
) ){
1140 int rc
= resolveExprStep(pWalker
, pRight
);
1141 if( rc
==WRC_Abort
) return WRC_Abort
;
1142 if( pRight
->op
==TK_TRUEFALSE
){
1143 pExpr
->op2
= pExpr
->op
;
1144 pExpr
->op
= TK_TRUTH
;
1145 return WRC_Continue
;
1148 /* no break */ deliberate_fall_through
1158 if( pParse
->db
->mallocFailed
) break;
1159 assert( pExpr
->pLeft
!=0 );
1160 nLeft
= sqlite3ExprVectorSize(pExpr
->pLeft
);
1161 if( pExpr
->op
==TK_BETWEEN
){
1162 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[0].pExpr
);
1163 if( nRight
==nLeft
){
1164 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[1].pExpr
);
1167 assert( pExpr
->pRight
!=0 );
1168 nRight
= sqlite3ExprVectorSize(pExpr
->pRight
);
1170 if( nLeft
!=nRight
){
1171 testcase( pExpr
->op
==TK_EQ
);
1172 testcase( pExpr
->op
==TK_NE
);
1173 testcase( pExpr
->op
==TK_LT
);
1174 testcase( pExpr
->op
==TK_LE
);
1175 testcase( pExpr
->op
==TK_GT
);
1176 testcase( pExpr
->op
==TK_GE
);
1177 testcase( pExpr
->op
==TK_IS
);
1178 testcase( pExpr
->op
==TK_ISNOT
);
1179 testcase( pExpr
->op
==TK_BETWEEN
);
1180 sqlite3ErrorMsg(pParse
, "row value misused");
1185 return (pParse
->nErr
|| pParse
->db
->mallocFailed
) ? WRC_Abort
: WRC_Continue
;
1189 ** pEList is a list of expressions which are really the result set of the
1190 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1191 ** This routine checks to see if pE is a simple identifier which corresponds
1192 ** to the AS-name of one of the terms of the expression list. If it is,
1193 ** this routine return an integer between 1 and N where N is the number of
1194 ** elements in pEList, corresponding to the matching entry. If there is
1195 ** no match, or if pE is not a simple identifier, then this routine
1198 ** pEList has been resolved. pE has not.
1200 static int resolveAsName(
1201 Parse
*pParse
, /* Parsing context for error messages */
1202 ExprList
*pEList
, /* List of expressions to scan */
1203 Expr
*pE
/* Expression we are trying to match */
1205 int i
; /* Loop counter */
1207 UNUSED_PARAMETER(pParse
);
1209 if( pE
->op
==TK_ID
){
1210 char *zCol
= pE
->u
.zToken
;
1211 for(i
=0; i
<pEList
->nExpr
; i
++){
1212 if( pEList
->a
[i
].eEName
==ENAME_NAME
1213 && sqlite3_stricmp(pEList
->a
[i
].zEName
, zCol
)==0
1223 ** pE is a pointer to an expression which is a single term in the
1224 ** ORDER BY of a compound SELECT. The expression has not been
1227 ** At the point this routine is called, we already know that the
1228 ** ORDER BY term is not an integer index into the result set. That
1229 ** case is handled by the calling routine.
1231 ** Attempt to match pE against result set columns in the left-most
1232 ** SELECT statement. Return the index i of the matching column,
1233 ** as an indication to the caller that it should sort by the i-th column.
1234 ** The left-most column is 1. In other words, the value returned is the
1235 ** same integer value that would be used in the SQL statement to indicate
1238 ** If there is no match, return 0. Return -1 if an error occurs.
1240 static int resolveOrderByTermToExprList(
1241 Parse
*pParse
, /* Parsing context for error messages */
1242 Select
*pSelect
, /* The SELECT statement with the ORDER BY clause */
1243 Expr
*pE
/* The specific ORDER BY term */
1245 int i
; /* Loop counter */
1246 ExprList
*pEList
; /* The columns of the result set */
1247 NameContext nc
; /* Name context for resolving pE */
1248 sqlite3
*db
; /* Database connection */
1249 int rc
; /* Return code from subprocedures */
1250 u8 savedSuppErr
; /* Saved value of db->suppressErr */
1252 assert( sqlite3ExprIsInteger(pE
, &i
)==0 );
1253 pEList
= pSelect
->pEList
;
1255 /* Resolve all names in the ORDER BY term expression
1257 memset(&nc
, 0, sizeof(nc
));
1259 nc
.pSrcList
= pSelect
->pSrc
;
1260 nc
.uNC
.pEList
= pEList
;
1261 nc
.ncFlags
= NC_AllowAgg
|NC_UEList
|NC_NoSelect
;
1264 savedSuppErr
= db
->suppressErr
;
1265 db
->suppressErr
= 1;
1266 rc
= sqlite3ResolveExprNames(&nc
, pE
);
1267 db
->suppressErr
= savedSuppErr
;
1270 /* Try to match the ORDER BY expression against an expression
1271 ** in the result set. Return an 1-based index of the matching
1272 ** result-set entry.
1274 for(i
=0; i
<pEList
->nExpr
; i
++){
1275 if( sqlite3ExprCompare(0, pEList
->a
[i
].pExpr
, pE
, -1)<2 ){
1280 /* If no match, return 0. */
1285 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1287 static void resolveOutOfRangeError(
1288 Parse
*pParse
, /* The error context into which to write the error */
1289 const char *zType
, /* "ORDER" or "GROUP" */
1290 int i
, /* The index (1-based) of the term out of range */
1291 int mx
/* Largest permissible value of i */
1293 sqlite3ErrorMsg(pParse
,
1294 "%r %s BY term out of range - should be "
1295 "between 1 and %d", i
, zType
, mx
);
1299 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1300 ** each term of the ORDER BY clause is a constant integer between 1
1301 ** and N where N is the number of columns in the compound SELECT.
1303 ** ORDER BY terms that are already an integer between 1 and N are
1304 ** unmodified. ORDER BY terms that are integers outside the range of
1305 ** 1 through N generate an error. ORDER BY terms that are expressions
1306 ** are matched against result set expressions of compound SELECT
1307 ** beginning with the left-most SELECT and working toward the right.
1308 ** At the first match, the ORDER BY expression is transformed into
1309 ** the integer column number.
1311 ** Return the number of errors seen.
1313 static int resolveCompoundOrderBy(
1314 Parse
*pParse
, /* Parsing context. Leave error messages here */
1315 Select
*pSelect
/* The SELECT statement containing the ORDER BY */
1323 pOrderBy
= pSelect
->pOrderBy
;
1324 if( pOrderBy
==0 ) return 0;
1326 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1327 sqlite3ErrorMsg(pParse
, "too many terms in ORDER BY clause");
1330 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1331 pOrderBy
->a
[i
].done
= 0;
1334 while( pSelect
->pPrior
){
1335 pSelect
->pPrior
->pNext
= pSelect
;
1336 pSelect
= pSelect
->pPrior
;
1338 while( pSelect
&& moreToDo
){
1339 struct ExprList_item
*pItem
;
1341 pEList
= pSelect
->pEList
;
1342 assert( pEList
!=0 );
1343 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1346 if( pItem
->done
) continue;
1347 pE
= sqlite3ExprSkipCollateAndLikely(pItem
->pExpr
);
1348 if( NEVER(pE
==0) ) continue;
1349 if( sqlite3ExprIsInteger(pE
, &iCol
) ){
1350 if( iCol
<=0 || iCol
>pEList
->nExpr
){
1351 resolveOutOfRangeError(pParse
, "ORDER", i
+1, pEList
->nExpr
);
1355 iCol
= resolveAsName(pParse
, pEList
, pE
);
1357 /* Now test if expression pE matches one of the values returned
1358 ** by pSelect. In the usual case this is done by duplicating the
1359 ** expression, resolving any symbols in it, and then comparing
1360 ** it against each expression returned by the SELECT statement.
1361 ** Once the comparisons are finished, the duplicate expression
1364 ** If this is running as part of an ALTER TABLE operation and
1365 ** the symbols resolve successfully, also resolve the symbols in the
1366 ** actual expression. This allows the code in alter.c to modify
1367 ** column references within the ORDER BY expression as required. */
1368 pDup
= sqlite3ExprDup(db
, pE
, 0);
1369 if( !db
->mallocFailed
){
1371 iCol
= resolveOrderByTermToExprList(pParse
, pSelect
, pDup
);
1372 if( IN_RENAME_OBJECT
&& iCol
>0 ){
1373 resolveOrderByTermToExprList(pParse
, pSelect
, pE
);
1376 sqlite3ExprDelete(db
, pDup
);
1380 /* Convert the ORDER BY term into an integer column number iCol,
1381 ** taking care to preserve the COLLATE clause if it exists. */
1382 if( !IN_RENAME_OBJECT
){
1383 Expr
*pNew
= sqlite3Expr(db
, TK_INTEGER
, 0);
1384 if( pNew
==0 ) return 1;
1385 pNew
->flags
|= EP_IntValue
;
1386 pNew
->u
.iValue
= iCol
;
1387 if( pItem
->pExpr
==pE
){
1388 pItem
->pExpr
= pNew
;
1390 Expr
*pParent
= pItem
->pExpr
;
1391 assert( pParent
->op
==TK_COLLATE
);
1392 while( pParent
->pLeft
->op
==TK_COLLATE
) pParent
= pParent
->pLeft
;
1393 assert( pParent
->pLeft
==pE
);
1394 pParent
->pLeft
= pNew
;
1396 sqlite3ExprDelete(db
, pE
);
1397 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1404 pSelect
= pSelect
->pNext
;
1406 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1407 if( pOrderBy
->a
[i
].done
==0 ){
1408 sqlite3ErrorMsg(pParse
, "%r ORDER BY term does not match any "
1409 "column in the result set", i
+1);
1417 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1418 ** the SELECT statement pSelect. If any term is reference to a
1419 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1420 ** field) then convert that term into a copy of the corresponding result set
1423 ** If any errors are detected, add an error message to pParse and
1424 ** return non-zero. Return zero if no errors are seen.
1426 int sqlite3ResolveOrderGroupBy(
1427 Parse
*pParse
, /* Parsing context. Leave error messages here */
1428 Select
*pSelect
, /* The SELECT statement containing the clause */
1429 ExprList
*pOrderBy
, /* The ORDER BY or GROUP BY clause to be processed */
1430 const char *zType
/* "ORDER" or "GROUP" */
1433 sqlite3
*db
= pParse
->db
;
1435 struct ExprList_item
*pItem
;
1437 if( pOrderBy
==0 || pParse
->db
->mallocFailed
|| IN_RENAME_OBJECT
) return 0;
1438 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1439 sqlite3ErrorMsg(pParse
, "too many terms in %s BY clause", zType
);
1442 pEList
= pSelect
->pEList
;
1443 assert( pEList
!=0 ); /* sqlite3SelectNew() guarantees this */
1444 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1445 if( pItem
->u
.x
.iOrderByCol
){
1446 if( pItem
->u
.x
.iOrderByCol
>pEList
->nExpr
){
1447 resolveOutOfRangeError(pParse
, zType
, i
+1, pEList
->nExpr
);
1450 resolveAlias(pParse
, pEList
, pItem
->u
.x
.iOrderByCol
-1, pItem
->pExpr
,0);
1456 #ifndef SQLITE_OMIT_WINDOWFUNC
1458 ** Walker callback for windowRemoveExprFromSelect().
1460 static int resolveRemoveWindowsCb(Walker
*pWalker
, Expr
*pExpr
){
1461 UNUSED_PARAMETER(pWalker
);
1462 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1463 Window
*pWin
= pExpr
->y
.pWin
;
1464 sqlite3WindowUnlinkFromSelect(pWin
);
1466 return WRC_Continue
;
1470 ** Remove any Window objects owned by the expression pExpr from the
1471 ** Select.pWin list of Select object pSelect.
1473 static void windowRemoveExprFromSelect(Select
*pSelect
, Expr
*pExpr
){
1474 if( pSelect
->pWin
){
1476 memset(&sWalker
, 0, sizeof(Walker
));
1477 sWalker
.xExprCallback
= resolveRemoveWindowsCb
;
1478 sWalker
.u
.pSelect
= pSelect
;
1479 sqlite3WalkExpr(&sWalker
, pExpr
);
1483 # define windowRemoveExprFromSelect(a, b)
1484 #endif /* SQLITE_OMIT_WINDOWFUNC */
1487 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1488 ** The Name context of the SELECT statement is pNC. zType is either
1489 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1491 ** This routine resolves each term of the clause into an expression.
1492 ** If the order-by term is an integer I between 1 and N (where N is the
1493 ** number of columns in the result set of the SELECT) then the expression
1494 ** in the resolution is a copy of the I-th result-set expression. If
1495 ** the order-by term is an identifier that corresponds to the AS-name of
1496 ** a result-set expression, then the term resolves to a copy of the
1497 ** result-set expression. Otherwise, the expression is resolved in
1498 ** the usual way - using sqlite3ResolveExprNames().
1500 ** This routine returns the number of errors. If errors occur, then
1501 ** an appropriate error message might be left in pParse. (OOM errors
1504 static int resolveOrderGroupBy(
1505 NameContext
*pNC
, /* The name context of the SELECT statement */
1506 Select
*pSelect
, /* The SELECT statement holding pOrderBy */
1507 ExprList
*pOrderBy
, /* An ORDER BY or GROUP BY clause to resolve */
1508 const char *zType
/* Either "ORDER" or "GROUP", as appropriate */
1510 int i
, j
; /* Loop counters */
1511 int iCol
; /* Column number */
1512 struct ExprList_item
*pItem
; /* A term of the ORDER BY clause */
1513 Parse
*pParse
; /* Parsing context */
1514 int nResult
; /* Number of terms in the result set */
1516 assert( pOrderBy
!=0 );
1517 nResult
= pSelect
->pEList
->nExpr
;
1518 pParse
= pNC
->pParse
;
1519 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1520 Expr
*pE
= pItem
->pExpr
;
1521 Expr
*pE2
= sqlite3ExprSkipCollateAndLikely(pE
);
1522 if( NEVER(pE2
==0) ) continue;
1523 if( zType
[0]!='G' ){
1524 iCol
= resolveAsName(pParse
, pSelect
->pEList
, pE2
);
1526 /* If an AS-name match is found, mark this ORDER BY column as being
1527 ** a copy of the iCol-th result-set column. The subsequent call to
1528 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1529 ** copy of the iCol-th result-set expression. */
1530 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1534 if( sqlite3ExprIsInteger(pE2
, &iCol
) ){
1535 /* The ORDER BY term is an integer constant. Again, set the column
1536 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1537 ** order-by term to a copy of the result-set expression */
1538 if( iCol
<1 || iCol
>0xffff ){
1539 resolveOutOfRangeError(pParse
, zType
, i
+1, nResult
);
1542 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1546 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1547 pItem
->u
.x
.iOrderByCol
= 0;
1548 if( sqlite3ResolveExprNames(pNC
, pE
) ){
1551 for(j
=0; j
<pSelect
->pEList
->nExpr
; j
++){
1552 if( sqlite3ExprCompare(0, pE
, pSelect
->pEList
->a
[j
].pExpr
, -1)==0 ){
1553 /* Since this expresion is being changed into a reference
1554 ** to an identical expression in the result set, remove all Window
1555 ** objects belonging to the expression from the Select.pWin list. */
1556 windowRemoveExprFromSelect(pSelect
, pE
);
1557 pItem
->u
.x
.iOrderByCol
= j
+1;
1561 return sqlite3ResolveOrderGroupBy(pParse
, pSelect
, pOrderBy
, zType
);
1565 ** Resolve names in the SELECT statement p and all of its descendants.
1567 static int resolveSelectStep(Walker
*pWalker
, Select
*p
){
1568 NameContext
*pOuterNC
; /* Context that contains this SELECT */
1569 NameContext sNC
; /* Name context of this SELECT */
1570 int isCompound
; /* True if p is a compound select */
1571 int nCompound
; /* Number of compound terms processed so far */
1572 Parse
*pParse
; /* Parsing context */
1573 int i
; /* Loop counter */
1574 ExprList
*pGroupBy
; /* The GROUP BY clause */
1575 Select
*pLeftmost
; /* Left-most of SELECT of a compound */
1576 sqlite3
*db
; /* Database connection */
1580 if( p
->selFlags
& SF_Resolved
){
1583 pOuterNC
= pWalker
->u
.pNC
;
1584 pParse
= pWalker
->pParse
;
1587 /* Normally sqlite3SelectExpand() will be called first and will have
1588 ** already expanded this SELECT. However, if this is a subquery within
1589 ** an expression, sqlite3ResolveExprNames() will be called without a
1590 ** prior call to sqlite3SelectExpand(). When that happens, let
1591 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1592 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1593 ** this routine in the correct order.
1595 if( (p
->selFlags
& SF_Expanded
)==0 ){
1596 sqlite3SelectPrep(pParse
, p
, pOuterNC
);
1597 return (pParse
->nErr
|| db
->mallocFailed
) ? WRC_Abort
: WRC_Prune
;
1600 isCompound
= p
->pPrior
!=0;
1604 assert( (p
->selFlags
& SF_Expanded
)!=0 );
1605 assert( (p
->selFlags
& SF_Resolved
)==0 );
1606 assert( db
->suppressErr
==0 ); /* SF_Resolved not set if errors suppressed */
1607 p
->selFlags
|= SF_Resolved
;
1610 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1611 ** are not allowed to refer to any names, so pass an empty NameContext.
1613 memset(&sNC
, 0, sizeof(sNC
));
1614 sNC
.pParse
= pParse
;
1616 if( sqlite3ResolveExprNames(&sNC
, p
->pLimit
) ){
1620 /* If the SF_Converted flags is set, then this Select object was
1621 ** was created by the convertCompoundSelectToSubquery() function.
1622 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1623 ** as if it were part of the sub-query, not the parent. This block
1624 ** moves the pOrderBy down to the sub-query. It will be moved back
1625 ** after the names have been resolved. */
1626 if( p
->selFlags
& SF_Converted
){
1627 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1628 assert( p
->pSrc
->nSrc
==1 && p
->pOrderBy
);
1629 assert( pSub
->pPrior
&& pSub
->pOrderBy
==0 );
1630 pSub
->pOrderBy
= p
->pOrderBy
;
1634 /* Recursively resolve names in all subqueries
1636 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1637 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1638 if( pItem
->pSelect
&& (pItem
->pSelect
->selFlags
& SF_Resolved
)==0 ){
1639 int nRef
= pOuterNC
? pOuterNC
->nRef
: 0;
1640 const char *zSavedContext
= pParse
->zAuthContext
;
1642 if( pItem
->zName
) pParse
->zAuthContext
= pItem
->zName
;
1643 sqlite3ResolveSelectNames(pParse
, pItem
->pSelect
, pOuterNC
);
1644 pParse
->zAuthContext
= zSavedContext
;
1645 if( pParse
->nErr
|| db
->mallocFailed
) return WRC_Abort
;
1647 /* If the number of references to the outer context changed when
1648 ** expressions in the sub-select were resolved, the sub-select
1649 ** is correlated. It is not required to check the refcount on any
1650 ** but the innermost outer context object, as lookupName() increments
1651 ** the refcount on all contexts between the current one and the
1652 ** context containing the column when it resolves a name. */
1654 assert( pItem
->fg
.isCorrelated
==0 && pOuterNC
->nRef
>=nRef
);
1655 pItem
->fg
.isCorrelated
= (pOuterNC
->nRef
>nRef
);
1660 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1661 ** resolve the result-set expression list.
1663 sNC
.ncFlags
= NC_AllowAgg
|NC_AllowWin
;
1664 sNC
.pSrcList
= p
->pSrc
;
1665 sNC
.pNext
= pOuterNC
;
1667 /* Resolve names in the result set. */
1668 if( sqlite3ResolveExprListNames(&sNC
, p
->pEList
) ) return WRC_Abort
;
1669 sNC
.ncFlags
&= ~NC_AllowWin
;
1671 /* If there are no aggregate functions in the result-set, and no GROUP BY
1672 ** expression, do not allow aggregates in any of the other expressions.
1674 assert( (p
->selFlags
& SF_Aggregate
)==0 );
1675 pGroupBy
= p
->pGroupBy
;
1676 if( pGroupBy
|| (sNC
.ncFlags
& NC_HasAgg
)!=0 ){
1677 assert( NC_MinMaxAgg
==SF_MinMaxAgg
);
1678 p
->selFlags
|= SF_Aggregate
| (sNC
.ncFlags
&NC_MinMaxAgg
);
1680 sNC
.ncFlags
&= ~NC_AllowAgg
;
1683 /* Add the output column list to the name-context before parsing the
1684 ** other expressions in the SELECT statement. This is so that
1685 ** expressions in the WHERE clause (etc.) can refer to expressions by
1686 ** aliases in the result set.
1688 ** Minor point: If this is the case, then the expression will be
1689 ** re-evaluated for each reference to it.
1691 assert( (sNC
.ncFlags
& (NC_UAggInfo
|NC_UUpsert
|NC_UBaseReg
))==0 );
1692 sNC
.uNC
.pEList
= p
->pEList
;
1693 sNC
.ncFlags
|= NC_UEList
;
1696 sqlite3ErrorMsg(pParse
, "a GROUP BY clause is required before HAVING");
1699 if( sqlite3ResolveExprNames(&sNC
, p
->pHaving
) ) return WRC_Abort
;
1701 if( sqlite3ResolveExprNames(&sNC
, p
->pWhere
) ) return WRC_Abort
;
1703 /* Resolve names in table-valued-function arguments */
1704 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1705 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1706 if( pItem
->fg
.isTabFunc
1707 && sqlite3ResolveExprListNames(&sNC
, pItem
->u1
.pFuncArg
)
1713 #ifndef SQLITE_OMIT_WINDOWFUNC
1714 if( IN_RENAME_OBJECT
){
1716 for(pWin
=p
->pWinDefn
; pWin
; pWin
=pWin
->pNextWin
){
1717 if( sqlite3ResolveExprListNames(&sNC
, pWin
->pOrderBy
)
1718 || sqlite3ResolveExprListNames(&sNC
, pWin
->pPartition
)
1726 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1730 sNC
.ncFlags
|= NC_AllowAgg
|NC_AllowWin
;
1732 /* If this is a converted compound query, move the ORDER BY clause from
1733 ** the sub-query back to the parent query. At this point each term
1734 ** within the ORDER BY clause has been transformed to an integer value.
1735 ** These integers will be replaced by copies of the corresponding result
1736 ** set expressions by the call to resolveOrderGroupBy() below. */
1737 if( p
->selFlags
& SF_Converted
){
1738 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1739 p
->pOrderBy
= pSub
->pOrderBy
;
1743 /* Process the ORDER BY clause for singleton SELECT statements.
1744 ** The ORDER BY clause for compounds SELECT statements is handled
1745 ** below, after all of the result-sets for all of the elements of
1746 ** the compound have been resolved.
1748 ** If there is an ORDER BY clause on a term of a compound-select other
1749 ** than the right-most term, then that is a syntax error. But the error
1750 ** is not detected until much later, and so we need to go ahead and
1751 ** resolve those symbols on the incorrect ORDER BY for consistency.
1754 && isCompound
<=nCompound
/* Defer right-most ORDER BY of a compound */
1755 && resolveOrderGroupBy(&sNC
, p
, p
->pOrderBy
, "ORDER")
1759 if( db
->mallocFailed
){
1762 sNC
.ncFlags
&= ~NC_AllowWin
;
1764 /* Resolve the GROUP BY clause. At the same time, make sure
1765 ** the GROUP BY clause does not contain aggregate functions.
1768 struct ExprList_item
*pItem
;
1770 if( resolveOrderGroupBy(&sNC
, p
, pGroupBy
, "GROUP") || db
->mallocFailed
){
1773 for(i
=0, pItem
=pGroupBy
->a
; i
<pGroupBy
->nExpr
; i
++, pItem
++){
1774 if( ExprHasProperty(pItem
->pExpr
, EP_Agg
) ){
1775 sqlite3ErrorMsg(pParse
, "aggregate functions are not allowed in "
1776 "the GROUP BY clause");
1782 /* If this is part of a compound SELECT, check that it has the right
1783 ** number of expressions in the select list. */
1784 if( p
->pNext
&& p
->pEList
->nExpr
!=p
->pNext
->pEList
->nExpr
){
1785 sqlite3SelectWrongNumTermsError(pParse
, p
->pNext
);
1789 /* Advance to the next term of the compound
1795 /* Resolve the ORDER BY on a compound SELECT after all terms of
1796 ** the compound have been resolved.
1798 if( isCompound
&& resolveCompoundOrderBy(pParse
, pLeftmost
) ){
1806 ** This routine walks an expression tree and resolves references to
1807 ** table columns and result-set columns. At the same time, do error
1808 ** checking on function usage and set a flag if any aggregate functions
1811 ** To resolve table columns references we look for nodes (or subtrees) of the
1812 ** form X.Y.Z or Y.Z or just Z where
1814 ** X: The name of a database. Ex: "main" or "temp" or
1815 ** the symbolic name assigned to an ATTACH-ed database.
1817 ** Y: The name of a table in a FROM clause. Or in a trigger
1818 ** one of the special names "old" or "new".
1820 ** Z: The name of a column in table Y.
1822 ** The node at the root of the subtree is modified as follows:
1824 ** Expr.op Changed to TK_COLUMN
1825 ** Expr.pTab Points to the Table object for X.Y
1826 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
1827 ** Expr.iTable The VDBE cursor number for X.Y
1830 ** To resolve result-set references, look for expression nodes of the
1831 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1832 ** size of an AS clause in the result-set of a SELECT. The Z expression
1833 ** is replaced by a copy of the left-hand side of the result-set expression.
1834 ** Table-name and function resolution occurs on the substituted expression
1835 ** tree. For example, in:
1837 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1839 ** The "x" term of the order by is replaced by "a+b" to render:
1841 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1843 ** Function calls are checked to make sure that the function is
1844 ** defined and that the correct number of arguments are specified.
1845 ** If the function is an aggregate function, then the NC_HasAgg flag is
1846 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1847 ** If an expression contains aggregate functions then the EP_Agg
1848 ** property on the expression is set.
1850 ** An error message is left in pParse if anything is amiss. The number
1851 ** if errors is returned.
1853 int sqlite3ResolveExprNames(
1854 NameContext
*pNC
, /* Namespace to resolve expressions in. */
1855 Expr
*pExpr
/* The expression to be analyzed. */
1860 if( pExpr
==0 ) return SQLITE_OK
;
1861 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
);
1862 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
);
1863 w
.pParse
= pNC
->pParse
;
1864 w
.xExprCallback
= resolveExprStep
;
1865 w
.xSelectCallback
= (pNC
->ncFlags
& NC_NoSelect
) ? 0 : resolveSelectStep
;
1866 w
.xSelectCallback2
= 0;
1868 #if SQLITE_MAX_EXPR_DEPTH>0
1869 w
.pParse
->nHeight
+= pExpr
->nHeight
;
1870 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
1871 return SQLITE_ERROR
;
1874 sqlite3WalkExpr(&w
, pExpr
);
1875 #if SQLITE_MAX_EXPR_DEPTH>0
1876 w
.pParse
->nHeight
-= pExpr
->nHeight
;
1878 assert( EP_Agg
==NC_HasAgg
);
1879 assert( EP_Win
==NC_HasWin
);
1880 testcase( pNC
->ncFlags
& NC_HasAgg
);
1881 testcase( pNC
->ncFlags
& NC_HasWin
);
1882 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
1883 pNC
->ncFlags
|= savedHasAgg
;
1884 return pNC
->nNcErr
>0 || w
.pParse
->nErr
>0;
1888 ** Resolve all names for all expression in an expression list. This is
1889 ** just like sqlite3ResolveExprNames() except that it works for an expression
1890 ** list rather than a single expression.
1892 int sqlite3ResolveExprListNames(
1893 NameContext
*pNC
, /* Namespace to resolve expressions in. */
1894 ExprList
*pList
/* The expression list to be analyzed. */
1897 int savedHasAgg
= 0;
1899 if( pList
==0 ) return WRC_Continue
;
1900 w
.pParse
= pNC
->pParse
;
1901 w
.xExprCallback
= resolveExprStep
;
1902 w
.xSelectCallback
= resolveSelectStep
;
1903 w
.xSelectCallback2
= 0;
1905 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
);
1906 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
);
1907 for(i
=0; i
<pList
->nExpr
; i
++){
1908 Expr
*pExpr
= pList
->a
[i
].pExpr
;
1909 if( pExpr
==0 ) continue;
1910 #if SQLITE_MAX_EXPR_DEPTH>0
1911 w
.pParse
->nHeight
+= pExpr
->nHeight
;
1912 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
1916 sqlite3WalkExpr(&w
, pExpr
);
1917 #if SQLITE_MAX_EXPR_DEPTH>0
1918 w
.pParse
->nHeight
-= pExpr
->nHeight
;
1920 assert( EP_Agg
==NC_HasAgg
);
1921 assert( EP_Win
==NC_HasWin
);
1922 testcase( pNC
->ncFlags
& NC_HasAgg
);
1923 testcase( pNC
->ncFlags
& NC_HasWin
);
1924 if( pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
) ){
1925 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
1926 savedHasAgg
|= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
);
1927 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
);
1929 if( w
.pParse
->nErr
>0 ) return WRC_Abort
;
1931 pNC
->ncFlags
|= savedHasAgg
;
1932 return WRC_Continue
;
1936 ** Resolve all names in all expressions of a SELECT and in all
1937 ** decendents of the SELECT, including compounds off of p->pPrior,
1938 ** subqueries in expressions, and subqueries used as FROM clause
1941 ** See sqlite3ResolveExprNames() for a description of the kinds of
1942 ** transformations that occur.
1944 ** All SELECT statements should have been expanded using
1945 ** sqlite3SelectExpand() prior to invoking this routine.
1947 void sqlite3ResolveSelectNames(
1948 Parse
*pParse
, /* The parser context */
1949 Select
*p
, /* The SELECT statement being coded. */
1950 NameContext
*pOuterNC
/* Name context for parent SELECT statement */
1955 w
.xExprCallback
= resolveExprStep
;
1956 w
.xSelectCallback
= resolveSelectStep
;
1957 w
.xSelectCallback2
= 0;
1960 sqlite3WalkSelect(&w
, p
);
1964 ** Resolve names in expressions that can only reference a single table
1965 ** or which cannot reference any tables at all. Examples:
1969 ** (1) CHECK constraints NC_IsCheck
1970 ** (2) WHERE clauses on partial indices NC_PartIdx
1971 ** (3) Expressions in indexes on expressions NC_IdxExpr
1972 ** (4) Expression arguments to VACUUM INTO. 0
1973 ** (5) GENERATED ALWAYS as expressions NC_GenCol
1975 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
1976 ** nodes of the expression is set to -1 and the Expr.iColumn value is
1977 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
1979 ** Any errors cause an error message to be set in pParse.
1981 int sqlite3ResolveSelfReference(
1982 Parse
*pParse
, /* Parsing context */
1983 Table
*pTab
, /* The table being referenced, or NULL */
1984 int type
, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
1985 Expr
*pExpr
, /* Expression to resolve. May be NULL. */
1986 ExprList
*pList
/* Expression list to resolve. May be NULL. */
1988 SrcList sSrc
; /* Fake SrcList for pParse->pNewTable */
1989 NameContext sNC
; /* Name context for pParse->pNewTable */
1992 assert( type
==0 || pTab
!=0 );
1993 assert( type
==NC_IsCheck
|| type
==NC_PartIdx
|| type
==NC_IdxExpr
1994 || type
==NC_GenCol
|| pTab
==0 );
1995 memset(&sNC
, 0, sizeof(sNC
));
1996 memset(&sSrc
, 0, sizeof(sSrc
));
1999 sSrc
.a
[0].zName
= pTab
->zName
;
2000 sSrc
.a
[0].pTab
= pTab
;
2001 sSrc
.a
[0].iCursor
= -1;
2002 if( pTab
->pSchema
!=pParse
->db
->aDb
[1].pSchema
){
2003 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2004 ** schema elements */
2008 sNC
.pParse
= pParse
;
2009 sNC
.pSrcList
= &sSrc
;
2010 sNC
.ncFlags
= type
| NC_IsDDL
;
2011 if( (rc
= sqlite3ResolveExprNames(&sNC
, pExpr
))!=SQLITE_OK
) return rc
;
2012 if( pList
) rc
= sqlite3ResolveExprListNames(&sNC
, pList
);