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 ** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
208 static SQLITE_NOINLINE
int isValidSchemaTableName(
209 const char *zTab
, /* Name as it appears in the SQL */
210 Table
*pTab
, /* The schema table we are trying to match */
211 Schema
*pSchema
/* non-NULL if a database qualifier is present */
215 assert( pTab
->tnum
==1 );
216 if( sqlite3StrNICmp(zTab
, "sqlite_", 7)!=0 ) return 0;
217 zLegacy
= pTab
->zName
;
218 if( strcmp(zLegacy
+7, &LEGACY_TEMP_SCHEMA_TABLE
[7])==0 ){
219 if( sqlite3StrICmp(zTab
+7, &PREFERRED_TEMP_SCHEMA_TABLE
[7])==0 ){
222 if( pSchema
==0 ) return 0;
223 if( sqlite3StrICmp(zTab
+7, &LEGACY_SCHEMA_TABLE
[7])==0 ) return 1;
224 if( sqlite3StrICmp(zTab
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ) return 1;
226 if( sqlite3StrICmp(zTab
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ) return 1;
232 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
233 ** that name in the set of source tables in pSrcList and make the pExpr
234 ** expression node refer back to that source column. The following changes
235 ** are made to pExpr:
237 ** pExpr->iDb Set the index in db->aDb[] of the database X
238 ** (even if X is implied).
239 ** pExpr->iTable Set to the cursor number for the table obtained
241 ** pExpr->y.pTab Points to the Table structure of X.Y (even if
242 ** X and/or Y are implied.)
243 ** pExpr->iColumn Set to the column number within the table.
244 ** pExpr->op Set to TK_COLUMN.
245 ** pExpr->pLeft Any expression this points to is deleted
246 ** pExpr->pRight Any expression this points to is deleted.
248 ** The zDb variable is the name of the database (the "X"). This value may be
249 ** NULL meaning that name is of the form Y.Z or Z. Any available database
250 ** can be used. The zTable variable is the name of the table (the "Y"). This
251 ** value can be NULL if zDb is also NULL. If zTable is NULL it
252 ** means that the form of the name is Z and that columns from any table
255 ** If the name cannot be resolved unambiguously, leave an error message
256 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
258 static int lookupName(
259 Parse
*pParse
, /* The parsing context */
260 const char *zDb
, /* Name of the database containing table, or NULL */
261 const char *zTab
, /* Name of table containing column, or NULL */
262 const char *zCol
, /* Name of the column. */
263 NameContext
*pNC
, /* The name context used to resolve the name */
264 Expr
*pExpr
/* Make this EXPR node point to the selected column */
266 int i
, j
; /* Loop counters */
267 int cnt
= 0; /* Number of matching column names */
268 int cntTab
= 0; /* Number of matching table names */
269 int nSubquery
= 0; /* How many levels of subquery */
270 sqlite3
*db
= pParse
->db
; /* The database connection */
271 SrcItem
*pItem
; /* Use for looping over pSrcList items */
272 SrcItem
*pMatch
= 0; /* The matching pSrcList item */
273 NameContext
*pTopNC
= pNC
; /* First namecontext in the list */
274 Schema
*pSchema
= 0; /* Schema of the expression */
275 int eNewExprOp
= TK_COLUMN
; /* New value for pExpr->op on success */
276 Table
*pTab
= 0; /* Table holding the row */
277 Column
*pCol
; /* A column of pTab */
278 ExprList
*pFJMatch
= 0; /* Matches for FULL JOIN .. USING */
280 assert( pNC
); /* the name context cannot be NULL. */
281 assert( zCol
); /* The Z in X.Y.Z cannot be NULL */
282 assert( zDb
==0 || zTab
!=0 );
283 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
285 /* Initialize the node to no-match */
287 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
289 /* Translate the schema name in zDb into a pointer to the corresponding
290 ** schema. If not found, pSchema will remain NULL and nothing will match
291 ** resulting in an appropriate error message toward the end of this routine
294 testcase( pNC
->ncFlags
& NC_PartIdx
);
295 testcase( pNC
->ncFlags
& NC_IsCheck
);
296 if( (pNC
->ncFlags
& (NC_PartIdx
|NC_IsCheck
))!=0 ){
297 /* Silently ignore database qualifiers inside CHECK constraints and
298 ** partial indices. Do not raise errors because that might break
299 ** legacy and because it does not hurt anything to just ignore the
303 for(i
=0; i
<db
->nDb
; i
++){
304 assert( db
->aDb
[i
].zDbSName
);
305 if( sqlite3StrICmp(db
->aDb
[i
].zDbSName
,zDb
)==0 ){
306 pSchema
= db
->aDb
[i
].pSchema
;
310 if( i
==db
->nDb
&& sqlite3StrICmp("main", zDb
)==0 ){
311 /* This branch is taken when the main database has been renamed
312 ** using SQLITE_DBCONFIG_MAINDBNAME. */
313 pSchema
= db
->aDb
[0].pSchema
;
314 zDb
= db
->aDb
[0].zDbSName
;
319 /* Start at the inner-most context and move outward until a match is found */
320 assert( pNC
&& cnt
==0 );
323 SrcList
*pSrcList
= pNC
->pSrcList
;
326 for(i
=0, pItem
=pSrcList
->a
; i
<pSrcList
->nSrc
; i
++, pItem
++){
329 assert( pTab
!=0 && pTab
->zName
!=0 );
330 assert( pTab
->nCol
>0 || pParse
->nErr
);
331 assert( (int)pItem
->fg
.isNestedFrom
== IsNestedFrom(pItem
->pSelect
) );
332 if( pItem
->fg
.isNestedFrom
){
333 /* In this case, pItem is a subquery that has been formed from a
334 ** parenthesized subset of the FROM clause terms. Example:
335 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
336 ** \_________________________/
337 ** This pItem -------------^
340 assert( pItem
->pSelect
!=0 );
341 pEList
= pItem
->pSelect
->pEList
;
343 assert( pEList
->nExpr
==pTab
->nCol
);
344 for(j
=0; j
<pEList
->nExpr
; j
++){
345 if( !sqlite3MatchEName(&pEList
->a
[j
], zCol
, zTab
, zDb
) ){
349 if( pItem
->fg
.isUsing
==0
350 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
352 /* Two or more tables have the same column name which is
353 ** not joined by USING. This is an error. Signal as much
354 ** by clearing pFJMatch and letting cnt go above 1. */
355 sqlite3ExprListDelete(db
, pFJMatch
);
358 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
359 /* An INNER or LEFT JOIN. Use the left-most table */
362 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
363 /* A RIGHT JOIN. Use the right-most table */
365 sqlite3ExprListDelete(db
, pFJMatch
);
368 /* For a FULL JOIN, we must construct a coalesce() func */
369 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
376 pEList
->a
[j
].fg
.bUsed
= 1;
378 if( pEList
->a
[j
].fg
.bUsingTerm
) break;
380 if( hit
|| zTab
==0 ) continue;
382 assert( zDb
==0 || zTab
!=0 );
385 if( pTab
->pSchema
!=pSchema
) continue;
386 if( pSchema
==0 && strcmp(zDb
,"*")!=0 ) continue;
388 if( pItem
->zAlias
!=0 ){
389 if( sqlite3StrICmp(zTab
, pItem
->zAlias
)!=0 ){
392 }else if( sqlite3StrICmp(zTab
, pTab
->zName
)!=0 ){
393 if( pTab
->tnum
!=1 ) continue;
394 if( !isValidSchemaTableName(zTab
, pTab
, pSchema
) ) continue;
396 assert( ExprUseYTab(pExpr
) );
397 if( IN_RENAME_OBJECT
&& pItem
->zAlias
){
398 sqlite3RenameTokenRemap(pParse
, 0, (void*)&pExpr
->y
.pTab
);
401 hCol
= sqlite3StrIHash(zCol
);
402 for(j
=0, pCol
=pTab
->aCol
; j
<pTab
->nCol
; j
++, pCol
++){
403 if( pCol
->hName
==hCol
404 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
407 if( pItem
->fg
.isUsing
==0
408 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
410 /* Two or more tables have the same column name which is
411 ** not joined by USING. This is an error. Signal as much
412 ** by clearing pFJMatch and letting cnt go above 1. */
413 sqlite3ExprListDelete(db
, pFJMatch
);
416 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
417 /* An INNER or LEFT JOIN. Use the left-most table */
420 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
421 /* A RIGHT JOIN. Use the right-most table */
423 sqlite3ExprListDelete(db
, pFJMatch
);
426 /* For a FULL JOIN, we must construct a coalesce() func */
427 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
432 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
433 pExpr
->iColumn
= j
==pTab
->iPKey
? -1 : (i16
)j
;
434 if( pItem
->fg
.isNestedFrom
){
435 sqlite3SrcItemColumnUsed(pItem
, j
);
440 if( 0==cnt
&& VisibleRowid(pTab
) ){
446 pExpr
->iTable
= pMatch
->iCursor
;
447 assert( ExprUseYTab(pExpr
) );
448 pExpr
->y
.pTab
= pMatch
->pTab
;
449 if( (pMatch
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
))!=0 ){
450 ExprSetProperty(pExpr
, EP_CanBeNull
);
452 pSchema
= pExpr
->y
.pTab
->pSchema
;
454 } /* if( pSrcList ) */
456 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
457 /* If we have not already resolved the name, then maybe
458 ** it is a new.* or old.* trigger argument reference. Or
459 ** maybe it is an excluded.* from an upsert. Or maybe it is
460 ** a reference in the RETURNING clause to a table being modified.
462 if( cnt
==0 && zDb
==0 ){
464 #ifndef SQLITE_OMIT_TRIGGER
465 if( pParse
->pTriggerTab
!=0 ){
466 int op
= pParse
->eTriggerOp
;
467 assert( op
==TK_DELETE
|| op
==TK_UPDATE
|| op
==TK_INSERT
);
468 if( pParse
->bReturning
){
469 if( (pNC
->ncFlags
& NC_UBaseReg
)!=0
470 && (zTab
==0 || sqlite3StrICmp(zTab
,pParse
->pTriggerTab
->zName
)==0)
472 pExpr
->iTable
= op
!=TK_DELETE
;
473 pTab
= pParse
->pTriggerTab
;
475 }else if( op
!=TK_DELETE
&& zTab
&& sqlite3StrICmp("new",zTab
) == 0 ){
477 pTab
= pParse
->pTriggerTab
;
478 }else if( op
!=TK_INSERT
&& zTab
&& sqlite3StrICmp("old",zTab
)==0 ){
480 pTab
= pParse
->pTriggerTab
;
483 #endif /* SQLITE_OMIT_TRIGGER */
484 #ifndef SQLITE_OMIT_UPSERT
485 if( (pNC
->ncFlags
& NC_UUpsert
)!=0 && zTab
!=0 ){
486 Upsert
*pUpsert
= pNC
->uNC
.pUpsert
;
487 if( pUpsert
&& sqlite3StrICmp("excluded",zTab
)==0 ){
488 pTab
= pUpsert
->pUpsertSrc
->a
[0].pTab
;
489 pExpr
->iTable
= EXCLUDED_TABLE_NUMBER
;
492 #endif /* SQLITE_OMIT_UPSERT */
496 u8 hCol
= sqlite3StrIHash(zCol
);
497 pSchema
= pTab
->pSchema
;
499 for(iCol
=0, pCol
=pTab
->aCol
; iCol
<pTab
->nCol
; iCol
++, pCol
++){
500 if( pCol
->hName
==hCol
501 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
503 if( iCol
==pTab
->iPKey
){
509 if( iCol
>=pTab
->nCol
&& sqlite3IsRowid(zCol
) && VisibleRowid(pTab
) ){
510 /* IMP: R-51414-32910 */
513 if( iCol
<pTab
->nCol
){
516 #ifndef SQLITE_OMIT_UPSERT
517 if( pExpr
->iTable
==EXCLUDED_TABLE_NUMBER
){
518 testcase( iCol
==(-1) );
519 assert( ExprUseYTab(pExpr
) );
520 if( IN_RENAME_OBJECT
){
521 pExpr
->iColumn
= iCol
;
522 pExpr
->y
.pTab
= pTab
;
523 eNewExprOp
= TK_COLUMN
;
525 pExpr
->iTable
= pNC
->uNC
.pUpsert
->regData
+
526 sqlite3TableColumnToStorage(pTab
, iCol
);
527 eNewExprOp
= TK_REGISTER
;
530 #endif /* SQLITE_OMIT_UPSERT */
532 assert( ExprUseYTab(pExpr
) );
533 pExpr
->y
.pTab
= pTab
;
534 if( pParse
->bReturning
){
535 eNewExprOp
= TK_REGISTER
;
536 pExpr
->op2
= TK_COLUMN
;
537 pExpr
->iColumn
= iCol
;
538 pExpr
->iTable
= pNC
->uNC
.iBaseReg
+ (pTab
->nCol
+1)*pExpr
->iTable
+
539 sqlite3TableColumnToStorage(pTab
, iCol
) + 1;
541 pExpr
->iColumn
= (i16
)iCol
;
542 eNewExprOp
= TK_TRIGGER
;
543 #ifndef SQLITE_OMIT_TRIGGER
545 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
546 }else if( pExpr
->iTable
==0 ){
547 testcase( iCol
==31 );
548 testcase( iCol
==32 );
549 pParse
->oldmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
551 testcase( iCol
==31 );
552 testcase( iCol
==32 );
553 pParse
->newmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
555 #endif /* SQLITE_OMIT_TRIGGER */
561 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
564 ** Perhaps the name is a reference to the ROWID
569 && (pNC
->ncFlags
& (NC_IdxExpr
|NC_GenCol
))==0
570 && sqlite3IsRowid(zCol
)
571 && ALWAYS(VisibleRowid(pMatch
->pTab
))
575 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
579 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
580 ** might refer to an result-set alias. This happens, for example, when
581 ** we are resolving names in the WHERE clause of the following command:
583 ** SELECT a+b AS x FROM table WHERE x<10;
585 ** In cases like this, replace pExpr with a copy of the expression that
586 ** forms the result set entry ("a+b" in the example) and return immediately.
587 ** Note that the expression in the result set should have already been
588 ** resolved by the time the WHERE clause is resolved.
590 ** The ability to use an output result-set column in the WHERE, GROUP BY,
591 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
592 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
593 ** is supported for backwards compatibility only. Hence, we issue a warning
594 ** on sqlite3_log() whenever the capability is used.
597 && (pNC
->ncFlags
& NC_UEList
)!=0
600 pEList
= pNC
->uNC
.pEList
;
602 for(j
=0; j
<pEList
->nExpr
; j
++){
603 char *zAs
= pEList
->a
[j
].zEName
;
604 if( pEList
->a
[j
].fg
.eEName
==ENAME_NAME
605 && sqlite3_stricmp(zAs
, zCol
)==0
608 assert( pExpr
->pLeft
==0 && pExpr
->pRight
==0 );
609 assert( ExprUseXList(pExpr
)==0 || pExpr
->x
.pList
==0 );
610 assert( ExprUseXSelect(pExpr
)==0 || pExpr
->x
.pSelect
==0 );
611 pOrig
= pEList
->a
[j
].pExpr
;
612 if( (pNC
->ncFlags
&NC_AllowAgg
)==0 && ExprHasProperty(pOrig
, EP_Agg
) ){
613 sqlite3ErrorMsg(pParse
, "misuse of aliased aggregate %s", zAs
);
616 if( ExprHasProperty(pOrig
, EP_Win
)
617 && ((pNC
->ncFlags
&NC_AllowWin
)==0 || pNC
!=pTopNC
)
619 sqlite3ErrorMsg(pParse
, "misuse of aliased window function %s",zAs
);
622 if( sqlite3ExprVectorSize(pOrig
)!=1 ){
623 sqlite3ErrorMsg(pParse
, "row value misused");
626 resolveAlias(pParse
, pEList
, j
, pExpr
, nSubquery
);
629 assert( zTab
==0 && zDb
==0 );
630 if( IN_RENAME_OBJECT
){
631 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
638 /* Advance to the next name context. The loop will exit when either
639 ** we have a match (cnt>0) or when we run out of name contexts.
648 ** If X and Y are NULL (in other words if only the column name Z is
649 ** supplied) and the value of Z is enclosed in double-quotes, then
650 ** Z is a string literal if it doesn't match any column names. In that
651 ** case, we need to return right away and not make any changes to
654 ** Because no reference was made to outer contexts, the pNC->nRef
655 ** fields are not changed in any context.
657 if( cnt
==0 && zTab
==0 ){
658 assert( pExpr
->op
==TK_ID
);
659 if( ExprHasProperty(pExpr
,EP_DblQuoted
)
660 && areDoubleQuotedStringsEnabled(db
, pTopNC
)
662 /* If a double-quoted identifier does not match any known column name,
663 ** then treat it as a string.
665 ** This hack was added in the early days of SQLite in a misguided attempt
666 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
667 ** I now sorely regret putting in this hack. The effect of this hack is
668 ** that misspelled identifier names are silently converted into strings
669 ** rather than causing an error, to the frustration of countless
670 ** programmers. To all those frustrated programmers, my apologies.
672 ** Someday, I hope to get rid of this hack. Unfortunately there is
673 ** a huge amount of legacy SQL that uses it. So for now, we just
676 sqlite3_log(SQLITE_WARNING
,
677 "double-quoted string literal: \"%w\"", zCol
);
678 #ifdef SQLITE_ENABLE_NORMALIZE
679 sqlite3VdbeAddDblquoteStr(db
, pParse
->pVdbe
, zCol
);
681 pExpr
->op
= TK_STRING
;
682 memset(&pExpr
->y
, 0, sizeof(pExpr
->y
));
685 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
691 ** cnt==0 means there was not match.
692 ** cnt>1 means there were two or more matches.
694 ** cnt==0 is always an error. cnt>1 is often an error, but might
695 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
697 assert( pFJMatch
==0 || cnt
>0 );
698 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
702 if( pFJMatch
->nExpr
==cnt
-1 ){
703 if( ExprHasProperty(pExpr
,EP_Leaf
) ){
704 ExprClearProperty(pExpr
,EP_Leaf
);
706 sqlite3ExprDelete(db
, pExpr
->pLeft
);
708 sqlite3ExprDelete(db
, pExpr
->pRight
);
711 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
712 pExpr
->op
= TK_FUNCTION
;
713 pExpr
->u
.zToken
= "coalesce";
714 pExpr
->x
.pList
= pFJMatch
;
718 sqlite3ExprListDelete(db
, pFJMatch
);
722 zErr
= cnt
==0 ? "no such column" : "ambiguous column name";
724 sqlite3ErrorMsg(pParse
, "%s: %s.%s.%s", zErr
, zDb
, zTab
, zCol
);
726 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zErr
, zTab
, zCol
);
728 sqlite3ErrorMsg(pParse
, "%s: %s", zErr
, zCol
);
730 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
731 pParse
->checkSchema
= 1;
734 assert( pFJMatch
==0 );
736 /* Remove all substructure from pExpr */
737 if( !ExprHasProperty(pExpr
,(EP_TokenOnly
|EP_Leaf
)) ){
738 sqlite3ExprDelete(db
, pExpr
->pLeft
);
740 sqlite3ExprDelete(db
, pExpr
->pRight
);
742 ExprSetProperty(pExpr
, EP_Leaf
);
745 /* If a column from a table in pSrcList is referenced, then record
746 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
747 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
748 ** set if the 63rd or any subsequent column is used.
750 ** The colUsed mask is an optimization used to help determine if an
751 ** index is a covering index. The correct answer is still obtained
752 ** if the mask contains extra set bits. However, it is important to
753 ** avoid setting bits beyond the maximum column number of the table.
754 ** (See ticket [b92e5e8ec2cdbaa1]).
756 ** If a generated column is referenced, set bits for every column
759 if( pExpr
->iColumn
>=0 && pMatch
!=0 ){
760 pMatch
->colUsed
|= sqlite3ExprColUsed(pExpr
);
763 pExpr
->op
= eNewExprOp
;
767 #ifndef SQLITE_OMIT_AUTHORIZATION
768 if( pParse
->db
->xAuth
769 && (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_TRIGGER
)
771 sqlite3AuthRead(pParse
, pExpr
, pSchema
, pNC
->pSrcList
);
774 /* Increment the nRef value on all name contexts from TopNC up to
775 ** the point where the name matched. */
779 if( pTopNC
==pNC
) break;
780 pTopNC
= pTopNC
->pNext
;
789 ** Allocate and return a pointer to an expression to load the column iCol
790 ** from datasource iSrc in SrcList pSrc.
792 Expr
*sqlite3CreateColumnExpr(sqlite3
*db
, SrcList
*pSrc
, int iSrc
, int iCol
){
793 Expr
*p
= sqlite3ExprAlloc(db
, TK_COLUMN
, 0, 0);
795 SrcItem
*pItem
= &pSrc
->a
[iSrc
];
797 assert( ExprUseYTab(p
) );
798 pTab
= p
->y
.pTab
= pItem
->pTab
;
799 p
->iTable
= pItem
->iCursor
;
800 if( p
->y
.pTab
->iPKey
==iCol
){
803 p
->iColumn
= (ynVar
)iCol
;
804 if( (pTab
->tabFlags
& TF_HasGenerated
)!=0
805 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_GENERATED
)!=0
807 testcase( pTab
->nCol
==63 );
808 testcase( pTab
->nCol
==64 );
809 pItem
->colUsed
= pTab
->nCol
>=64 ? ALLBITS
: MASKBIT(pTab
->nCol
)-1;
811 testcase( iCol
==BMS
);
812 testcase( iCol
==BMS
-1 );
813 pItem
->colUsed
|= ((Bitmask
)1)<<(iCol
>=BMS
? BMS
-1 : iCol
);
821 ** Report an error that an expression is not valid for some set of
822 ** pNC->ncFlags values determined by validMask.
824 ** static void notValid(
825 ** Parse *pParse, // Leave error message here
826 ** NameContext *pNC, // The name context
827 ** const char *zMsg, // Type of error
828 ** int validMask, // Set of contexts for which prohibited
829 ** Expr *pExpr // Invalidate this expression on error
832 ** As an optimization, since the conditional is almost always false
833 ** (because errors are rare), the conditional is moved outside of the
834 ** function call using a macro.
836 static void notValidImpl(
837 Parse
*pParse
, /* Leave error message here */
838 NameContext
*pNC
, /* The name context */
839 const char *zMsg
, /* Type of error */
840 Expr
*pExpr
, /* Invalidate this expression on error */
841 Expr
*pError
/* Associate error with this expression */
843 const char *zIn
= "partial index WHERE clauses";
844 if( pNC
->ncFlags
& NC_IdxExpr
) zIn
= "index expressions";
845 #ifndef SQLITE_OMIT_CHECK
846 else if( pNC
->ncFlags
& NC_IsCheck
) zIn
= "CHECK constraints";
848 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
849 else if( pNC
->ncFlags
& NC_GenCol
) zIn
= "generated columns";
851 sqlite3ErrorMsg(pParse
, "%s prohibited in %s", zMsg
, zIn
);
852 if( pExpr
) pExpr
->op
= TK_NULL
;
853 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
855 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
856 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
857 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
860 ** Expression p should encode a floating point value between 1.0 and 0.0.
861 ** Return 1024 times this value. Or return -1 if p is not a floating point
862 ** value between 1.0 and 0.0.
864 static int exprProbability(Expr
*p
){
866 if( p
->op
!=TK_FLOAT
) return -1;
867 assert( !ExprHasProperty(p
, EP_IntValue
) );
868 sqlite3AtoF(p
->u
.zToken
, &r
, sqlite3Strlen30(p
->u
.zToken
), SQLITE_UTF8
);
870 if( r
>1.0 ) return -1;
871 return (int)(r
*134217728.0);
875 ** This routine is callback for sqlite3WalkExpr().
877 ** Resolve symbolic names into TK_COLUMN operators for the current
878 ** node in the expression tree. Return 0 to continue the search down
879 ** the tree or 2 to abort the tree walk.
881 ** This routine also does error checking and name resolution for
882 ** function names. The operator for aggregate functions is changed
883 ** to TK_AGG_FUNCTION.
885 static int resolveExprStep(Walker
*pWalker
, Expr
*pExpr
){
889 pNC
= pWalker
->u
.pNC
;
891 pParse
= pNC
->pParse
;
892 assert( pParse
==pWalker
->pParse
);
895 if( pNC
->pSrcList
&& pNC
->pSrcList
->nAlloc
>0 ){
896 SrcList
*pSrcList
= pNC
->pSrcList
;
898 for(i
=0; i
<pNC
->pSrcList
->nSrc
; i
++){
899 assert( pSrcList
->a
[i
].iCursor
>=0 && pSrcList
->a
[i
].iCursor
<pParse
->nTab
);
905 /* The special operator TK_ROW means use the rowid for the first
906 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
907 ** clause processing on UPDATE and DELETE statements, and by
908 ** UPDATE ... FROM statement processing.
911 SrcList
*pSrcList
= pNC
->pSrcList
;
913 assert( pSrcList
&& pSrcList
->nSrc
>=1 );
915 pExpr
->op
= TK_COLUMN
;
916 assert( ExprUseYTab(pExpr
) );
917 pExpr
->y
.pTab
= pItem
->pTab
;
918 pExpr
->iTable
= pItem
->iCursor
;
920 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
924 /* An optimization: Attempt to convert
926 ** "expr IS NOT NULL" --> "TRUE"
927 ** "expr IS NULL" --> "FALSE"
929 ** if we can prove that "expr" is never NULL. Call this the
930 ** "NOT NULL strength reduction optimization".
932 ** If this optimization occurs, also restore the NameContext ref-counts
933 ** to the state they where in before the "column" LHS expression was
934 ** resolved. This prevents "column" from being counted as having been
935 ** referenced, which might prevent a SELECT from being erroneously
936 ** marked as correlated.
943 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
946 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
947 if( 0==sqlite3ExprCanBeNull(pExpr
->pLeft
) && !IN_RENAME_OBJECT
){
948 testcase( ExprHasProperty(pExpr
, EP_OuterON
) );
949 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
950 pExpr
->u
.iValue
= (pExpr
->op
==TK_NOTNULL
);
951 pExpr
->flags
|= EP_IntValue
;
952 pExpr
->op
= TK_INTEGER
;
954 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
957 sqlite3ExprDelete(pParse
->db
, pExpr
->pLeft
);
964 ** Or table name and column name: ID.ID
965 ** Or a database, table and column: ID.ID.ID
967 ** The TK_ID and TK_OUT cases are combined so that there will only
968 ** be one call to lookupName(). Then the compiler will in-line
969 ** lookupName() for a size reduction and performance increase.
978 if( pExpr
->op
==TK_ID
){
981 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
982 zColumn
= pExpr
->u
.zToken
;
984 Expr
*pLeft
= pExpr
->pLeft
;
985 testcase( pNC
->ncFlags
& NC_IdxExpr
);
986 testcase( pNC
->ncFlags
& NC_GenCol
);
987 sqlite3ResolveNotValid(pParse
, pNC
, "the \".\" operator",
988 NC_IdxExpr
|NC_GenCol
, 0, pExpr
);
989 pRight
= pExpr
->pRight
;
990 if( pRight
->op
==TK_ID
){
993 assert( pRight
->op
==TK_DOT
);
994 assert( !ExprHasProperty(pRight
, EP_IntValue
) );
995 zDb
= pLeft
->u
.zToken
;
996 pLeft
= pRight
->pLeft
;
997 pRight
= pRight
->pRight
;
999 assert( ExprUseUToken(pLeft
) && ExprUseUToken(pRight
) );
1000 zTable
= pLeft
->u
.zToken
;
1001 zColumn
= pRight
->u
.zToken
;
1002 assert( ExprUseYTab(pExpr
) );
1003 if( IN_RENAME_OBJECT
){
1004 sqlite3RenameTokenRemap(pParse
, (void*)pExpr
, (void*)pRight
);
1005 sqlite3RenameTokenRemap(pParse
, (void*)&pExpr
->y
.pTab
, (void*)pLeft
);
1008 return lookupName(pParse
, zDb
, zTable
, zColumn
, pNC
, pExpr
);
1011 /* Resolve function names
1014 ExprList
*pList
= pExpr
->x
.pList
; /* The argument list */
1015 int n
= pList
? pList
->nExpr
: 0; /* Number of arguments */
1016 int no_such_func
= 0; /* True if no such function exists */
1017 int wrong_num_args
= 0; /* True if wrong number of arguments */
1018 int is_agg
= 0; /* True if is an aggregate function */
1019 const char *zId
; /* The function name. */
1020 FuncDef
*pDef
; /* Information about the function */
1021 u8 enc
= ENC(pParse
->db
); /* The database encoding */
1022 int savedAllowFlags
= (pNC
->ncFlags
& (NC_AllowAgg
| NC_AllowWin
));
1023 #ifndef SQLITE_OMIT_WINDOWFUNC
1024 Window
*pWin
= (IsWindowFunc(pExpr
) ? pExpr
->y
.pWin
: 0);
1026 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
1027 zId
= pExpr
->u
.zToken
;
1028 pDef
= sqlite3FindFunction(pParse
->db
, zId
, n
, enc
, 0);
1030 pDef
= sqlite3FindFunction(pParse
->db
, zId
, -2, enc
, 0);
1037 is_agg
= pDef
->xFinalize
!=0;
1038 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
1039 ExprSetProperty(pExpr
, EP_Unlikely
);
1041 pExpr
->iTable
= exprProbability(pList
->a
[1].pExpr
);
1042 if( pExpr
->iTable
<0 ){
1043 sqlite3ErrorMsg(pParse
,
1044 "second argument to %#T() must be a "
1045 "constant between 0.0 and 1.0", pExpr
);
1049 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1050 ** equivalent to likelihood(X, 0.0625).
1051 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1052 ** short-hand for likelihood(X,0.0625).
1053 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1054 ** for likelihood(X,0.9375).
1055 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1056 ** to likelihood(X,0.9375). */
1057 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1058 pExpr
->iTable
= pDef
->zName
[0]=='u' ? 8388608 : 125829120;
1061 #ifndef SQLITE_OMIT_AUTHORIZATION
1063 int auth
= sqlite3AuthCheck(pParse
, SQLITE_FUNCTION
, 0,pDef
->zName
,0);
1064 if( auth
!=SQLITE_OK
){
1065 if( auth
==SQLITE_DENY
){
1066 sqlite3ErrorMsg(pParse
, "not authorized to use function: %#T",
1070 pExpr
->op
= TK_NULL
;
1075 if( pDef
->funcFlags
& (SQLITE_FUNC_CONSTANT
|SQLITE_FUNC_SLOCHNG
) ){
1076 /* For the purposes of the EP_ConstFunc flag, date and time
1077 ** functions and other functions that change slowly are considered
1078 ** constant because they are constant for the duration of one query.
1079 ** This allows them to be factored out of inner loops. */
1080 ExprSetProperty(pExpr
,EP_ConstFunc
);
1082 if( (pDef
->funcFlags
& SQLITE_FUNC_CONSTANT
)==0 ){
1083 /* Clearly non-deterministic functions like random(), but also
1084 ** date/time functions that use 'now', and other functions like
1085 ** sqlite_version() that might change over time cannot be used
1086 ** in an index or generated column. Curiously, they can be used
1087 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1089 sqlite3ResolveNotValid(pParse
, pNC
, "non-deterministic functions",
1090 NC_IdxExpr
|NC_PartIdx
|NC_GenCol
, 0, pExpr
);
1092 assert( (NC_SelfRef
& 0xff)==NC_SelfRef
); /* Must fit in 8 bits */
1093 pExpr
->op2
= pNC
->ncFlags
& NC_SelfRef
;
1094 if( pNC
->ncFlags
& NC_FromDDL
) ExprSetProperty(pExpr
, EP_FromDDL
);
1096 if( (pDef
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
1097 && pParse
->nested
==0
1098 && (pParse
->db
->mDbFlags
& DBFLAG_InternalFunc
)==0
1100 /* Internal-use-only functions are disallowed unless the
1101 ** SQL is being compiled using sqlite3NestedParse() or
1102 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1103 ** used to activate internal functions for testing purposes */
1107 if( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0
1108 && !IN_RENAME_OBJECT
1110 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
1114 if( 0==IN_RENAME_OBJECT
){
1115 #ifndef SQLITE_OMIT_WINDOWFUNC
1116 assert( is_agg
==0 || (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)
1117 || (pDef
->xValue
==0 && pDef
->xInverse
==0)
1118 || (pDef
->xValue
&& pDef
->xInverse
&& pDef
->xSFunc
&& pDef
->xFinalize
)
1120 if( pDef
&& pDef
->xValue
==0 && pWin
){
1121 sqlite3ErrorMsg(pParse
,
1122 "%#T() may not be used as a window function", pExpr
1126 (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0)
1127 || (is_agg
&& (pDef
->funcFlags
&SQLITE_FUNC_WINDOW
) && !pWin
)
1128 || (is_agg
&& pWin
&& (pNC
->ncFlags
& NC_AllowWin
)==0)
1131 if( (pDef
->funcFlags
& SQLITE_FUNC_WINDOW
) || pWin
){
1134 zType
= "aggregate";
1136 sqlite3ErrorMsg(pParse
, "misuse of %s function %#T()",zType
,pExpr
);
1141 if( (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0) ){
1142 sqlite3ErrorMsg(pParse
,"misuse of aggregate function %#T()",pExpr
);
1147 else if( no_such_func
&& pParse
->db
->init
.busy
==0
1148 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1149 && pParse
->explain
==0
1152 sqlite3ErrorMsg(pParse
, "no such function: %#T", pExpr
);
1154 }else if( wrong_num_args
){
1155 sqlite3ErrorMsg(pParse
,"wrong number of arguments to function %#T()",
1159 #ifndef SQLITE_OMIT_WINDOWFUNC
1160 else if( is_agg
==0 && ExprHasProperty(pExpr
, EP_WinFunc
) ){
1161 sqlite3ErrorMsg(pParse
,
1162 "FILTER may not be used with non-aggregate %#T()",
1169 /* Window functions may not be arguments of aggregate functions.
1170 ** Or arguments of other window functions. But aggregate functions
1171 ** may be arguments for window functions. */
1172 #ifndef SQLITE_OMIT_WINDOWFUNC
1173 pNC
->ncFlags
&= ~(NC_AllowWin
| (!pWin
? NC_AllowAgg
: 0));
1175 pNC
->ncFlags
&= ~NC_AllowAgg
;
1179 #ifndef SQLITE_OMIT_WINDOWFUNC
1180 else if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1184 sqlite3WalkExprList(pWalker
, pList
);
1186 #ifndef SQLITE_OMIT_WINDOWFUNC
1188 Select
*pSel
= pNC
->pWinSelect
;
1189 assert( pWin
==0 || (ExprUseYWin(pExpr
) && pWin
==pExpr
->y
.pWin
) );
1190 if( IN_RENAME_OBJECT
==0 ){
1191 sqlite3WindowUpdate(pParse
, pSel
? pSel
->pWinDefn
: 0, pWin
, pDef
);
1192 if( pParse
->db
->mallocFailed
) break;
1194 sqlite3WalkExprList(pWalker
, pWin
->pPartition
);
1195 sqlite3WalkExprList(pWalker
, pWin
->pOrderBy
);
1196 sqlite3WalkExpr(pWalker
, pWin
->pFilter
);
1197 sqlite3WindowLink(pSel
, pWin
);
1198 pNC
->ncFlags
|= NC_HasWin
;
1200 #endif /* SQLITE_OMIT_WINDOWFUNC */
1202 NameContext
*pNC2
; /* For looping up thru outer contexts */
1203 pExpr
->op
= TK_AGG_FUNCTION
;
1205 #ifndef SQLITE_OMIT_WINDOWFUNC
1206 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1207 sqlite3WalkExpr(pWalker
, pExpr
->y
.pWin
->pFilter
);
1212 && sqlite3ReferencesSrcList(pParse
, pExpr
, pNC2
->pSrcList
)==0
1217 assert( pDef
!=0 || IN_RENAME_OBJECT
);
1219 assert( SQLITE_FUNC_MINMAX
==NC_MinMaxAgg
);
1220 assert( SQLITE_FUNC_ANYORDER
==NC_OrderAgg
);
1221 testcase( (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)!=0 );
1222 testcase( (pDef
->funcFlags
& SQLITE_FUNC_ANYORDER
)!=0 );
1223 pNC2
->ncFlags
|= NC_HasAgg
1224 | ((pDef
->funcFlags
^SQLITE_FUNC_ANYORDER
)
1225 & (SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
));
1228 pNC
->ncFlags
|= savedAllowFlags
;
1230 /* FIX ME: Compute pExpr->affinity based on the expected return
1231 ** type of the function
1235 #ifndef SQLITE_OMIT_SUBQUERY
1237 case TK_EXISTS
: testcase( pExpr
->op
==TK_EXISTS
);
1240 testcase( pExpr
->op
==TK_IN
);
1241 if( ExprUseXSelect(pExpr
) ){
1242 int nRef
= pNC
->nRef
;
1243 testcase( pNC
->ncFlags
& NC_IsCheck
);
1244 testcase( pNC
->ncFlags
& NC_PartIdx
);
1245 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1246 testcase( pNC
->ncFlags
& NC_GenCol
);
1247 if( pNC
->ncFlags
& NC_SelfRef
){
1248 notValidImpl(pParse
, pNC
, "subqueries", pExpr
, pExpr
);
1250 sqlite3WalkSelect(pWalker
, pExpr
->x
.pSelect
);
1252 assert( pNC
->nRef
>=nRef
);
1253 if( nRef
!=pNC
->nRef
){
1254 ExprSetProperty(pExpr
, EP_VarSelect
);
1256 pNC
->ncFlags
|= NC_Subquery
;
1261 testcase( pNC
->ncFlags
& NC_IsCheck
);
1262 testcase( pNC
->ncFlags
& NC_PartIdx
);
1263 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1264 testcase( pNC
->ncFlags
& NC_GenCol
);
1265 sqlite3ResolveNotValid(pParse
, pNC
, "parameters",
1266 NC_IsCheck
|NC_PartIdx
|NC_IdxExpr
|NC_GenCol
, pExpr
, pExpr
);
1271 Expr
*pRight
= sqlite3ExprSkipCollateAndLikely(pExpr
->pRight
);
1272 assert( !ExprHasProperty(pExpr
, EP_Reduced
) );
1273 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1274 ** and "x IS NOT FALSE". */
1275 if( ALWAYS(pRight
) && (pRight
->op
==TK_ID
|| pRight
->op
==TK_TRUEFALSE
) ){
1276 int rc
= resolveExprStep(pWalker
, pRight
);
1277 if( rc
==WRC_Abort
) return WRC_Abort
;
1278 if( pRight
->op
==TK_TRUEFALSE
){
1279 pExpr
->op2
= pExpr
->op
;
1280 pExpr
->op
= TK_TRUTH
;
1281 return WRC_Continue
;
1284 /* no break */ deliberate_fall_through
1294 if( pParse
->db
->mallocFailed
) break;
1295 assert( pExpr
->pLeft
!=0 );
1296 nLeft
= sqlite3ExprVectorSize(pExpr
->pLeft
);
1297 if( pExpr
->op
==TK_BETWEEN
){
1298 assert( ExprUseXList(pExpr
) );
1299 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[0].pExpr
);
1300 if( nRight
==nLeft
){
1301 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[1].pExpr
);
1304 assert( pExpr
->pRight
!=0 );
1305 nRight
= sqlite3ExprVectorSize(pExpr
->pRight
);
1307 if( nLeft
!=nRight
){
1308 testcase( pExpr
->op
==TK_EQ
);
1309 testcase( pExpr
->op
==TK_NE
);
1310 testcase( pExpr
->op
==TK_LT
);
1311 testcase( pExpr
->op
==TK_LE
);
1312 testcase( pExpr
->op
==TK_GT
);
1313 testcase( pExpr
->op
==TK_GE
);
1314 testcase( pExpr
->op
==TK_IS
);
1315 testcase( pExpr
->op
==TK_ISNOT
);
1316 testcase( pExpr
->op
==TK_BETWEEN
);
1317 sqlite3ErrorMsg(pParse
, "row value misused");
1318 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1323 assert( pParse
->db
->mallocFailed
==0 || pParse
->nErr
!=0 );
1324 return pParse
->nErr
? WRC_Abort
: WRC_Continue
;
1328 ** pEList is a list of expressions which are really the result set of the
1329 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1330 ** This routine checks to see if pE is a simple identifier which corresponds
1331 ** to the AS-name of one of the terms of the expression list. If it is,
1332 ** this routine return an integer between 1 and N where N is the number of
1333 ** elements in pEList, corresponding to the matching entry. If there is
1334 ** no match, or if pE is not a simple identifier, then this routine
1337 ** pEList has been resolved. pE has not.
1339 static int resolveAsName(
1340 Parse
*pParse
, /* Parsing context for error messages */
1341 ExprList
*pEList
, /* List of expressions to scan */
1342 Expr
*pE
/* Expression we are trying to match */
1344 int i
; /* Loop counter */
1346 UNUSED_PARAMETER(pParse
);
1348 if( pE
->op
==TK_ID
){
1350 assert( !ExprHasProperty(pE
, EP_IntValue
) );
1351 zCol
= pE
->u
.zToken
;
1352 for(i
=0; i
<pEList
->nExpr
; i
++){
1353 if( pEList
->a
[i
].fg
.eEName
==ENAME_NAME
1354 && sqlite3_stricmp(pEList
->a
[i
].zEName
, zCol
)==0
1364 ** pE is a pointer to an expression which is a single term in the
1365 ** ORDER BY of a compound SELECT. The expression has not been
1368 ** At the point this routine is called, we already know that the
1369 ** ORDER BY term is not an integer index into the result set. That
1370 ** case is handled by the calling routine.
1372 ** Attempt to match pE against result set columns in the left-most
1373 ** SELECT statement. Return the index i of the matching column,
1374 ** as an indication to the caller that it should sort by the i-th column.
1375 ** The left-most column is 1. In other words, the value returned is the
1376 ** same integer value that would be used in the SQL statement to indicate
1379 ** If there is no match, return 0. Return -1 if an error occurs.
1381 static int resolveOrderByTermToExprList(
1382 Parse
*pParse
, /* Parsing context for error messages */
1383 Select
*pSelect
, /* The SELECT statement with the ORDER BY clause */
1384 Expr
*pE
/* The specific ORDER BY term */
1386 int i
; /* Loop counter */
1387 ExprList
*pEList
; /* The columns of the result set */
1388 NameContext nc
; /* Name context for resolving pE */
1389 sqlite3
*db
; /* Database connection */
1390 int rc
; /* Return code from subprocedures */
1391 u8 savedSuppErr
; /* Saved value of db->suppressErr */
1393 assert( sqlite3ExprIsInteger(pE
, &i
)==0 );
1394 pEList
= pSelect
->pEList
;
1396 /* Resolve all names in the ORDER BY term expression
1398 memset(&nc
, 0, sizeof(nc
));
1400 nc
.pSrcList
= pSelect
->pSrc
;
1401 nc
.uNC
.pEList
= pEList
;
1402 nc
.ncFlags
= NC_AllowAgg
|NC_UEList
|NC_NoSelect
;
1405 savedSuppErr
= db
->suppressErr
;
1406 db
->suppressErr
= 1;
1407 rc
= sqlite3ResolveExprNames(&nc
, pE
);
1408 db
->suppressErr
= savedSuppErr
;
1411 /* Try to match the ORDER BY expression against an expression
1412 ** in the result set. Return an 1-based index of the matching
1413 ** result-set entry.
1415 for(i
=0; i
<pEList
->nExpr
; i
++){
1416 if( sqlite3ExprCompare(0, pEList
->a
[i
].pExpr
, pE
, -1)<2 ){
1421 /* If no match, return 0. */
1426 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1428 static void resolveOutOfRangeError(
1429 Parse
*pParse
, /* The error context into which to write the error */
1430 const char *zType
, /* "ORDER" or "GROUP" */
1431 int i
, /* The index (1-based) of the term out of range */
1432 int mx
, /* Largest permissible value of i */
1433 Expr
*pError
/* Associate the error with the expression */
1435 sqlite3ErrorMsg(pParse
,
1436 "%r %s BY term out of range - should be "
1437 "between 1 and %d", i
, zType
, mx
);
1438 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
1442 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1443 ** each term of the ORDER BY clause is a constant integer between 1
1444 ** and N where N is the number of columns in the compound SELECT.
1446 ** ORDER BY terms that are already an integer between 1 and N are
1447 ** unmodified. ORDER BY terms that are integers outside the range of
1448 ** 1 through N generate an error. ORDER BY terms that are expressions
1449 ** are matched against result set expressions of compound SELECT
1450 ** beginning with the left-most SELECT and working toward the right.
1451 ** At the first match, the ORDER BY expression is transformed into
1452 ** the integer column number.
1454 ** Return the number of errors seen.
1456 static int resolveCompoundOrderBy(
1457 Parse
*pParse
, /* Parsing context. Leave error messages here */
1458 Select
*pSelect
/* The SELECT statement containing the ORDER BY */
1466 pOrderBy
= pSelect
->pOrderBy
;
1467 if( pOrderBy
==0 ) return 0;
1469 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1470 sqlite3ErrorMsg(pParse
, "too many terms in ORDER BY clause");
1473 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1474 pOrderBy
->a
[i
].fg
.done
= 0;
1477 while( pSelect
->pPrior
){
1478 pSelect
->pPrior
->pNext
= pSelect
;
1479 pSelect
= pSelect
->pPrior
;
1481 while( pSelect
&& moreToDo
){
1482 struct ExprList_item
*pItem
;
1484 pEList
= pSelect
->pEList
;
1485 assert( pEList
!=0 );
1486 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1489 if( pItem
->fg
.done
) continue;
1490 pE
= sqlite3ExprSkipCollateAndLikely(pItem
->pExpr
);
1491 if( NEVER(pE
==0) ) continue;
1492 if( sqlite3ExprIsInteger(pE
, &iCol
) ){
1493 if( iCol
<=0 || iCol
>pEList
->nExpr
){
1494 resolveOutOfRangeError(pParse
, "ORDER", i
+1, pEList
->nExpr
, pE
);
1498 iCol
= resolveAsName(pParse
, pEList
, pE
);
1500 /* Now test if expression pE matches one of the values returned
1501 ** by pSelect. In the usual case this is done by duplicating the
1502 ** expression, resolving any symbols in it, and then comparing
1503 ** it against each expression returned by the SELECT statement.
1504 ** Once the comparisons are finished, the duplicate expression
1507 ** If this is running as part of an ALTER TABLE operation and
1508 ** the symbols resolve successfully, also resolve the symbols in the
1509 ** actual expression. This allows the code in alter.c to modify
1510 ** column references within the ORDER BY expression as required. */
1511 pDup
= sqlite3ExprDup(db
, pE
, 0);
1512 if( !db
->mallocFailed
){
1514 iCol
= resolveOrderByTermToExprList(pParse
, pSelect
, pDup
);
1515 if( IN_RENAME_OBJECT
&& iCol
>0 ){
1516 resolveOrderByTermToExprList(pParse
, pSelect
, pE
);
1519 sqlite3ExprDelete(db
, pDup
);
1523 /* Convert the ORDER BY term into an integer column number iCol,
1524 ** taking care to preserve the COLLATE clause if it exists. */
1525 if( !IN_RENAME_OBJECT
){
1526 Expr
*pNew
= sqlite3Expr(db
, TK_INTEGER
, 0);
1527 if( pNew
==0 ) return 1;
1528 pNew
->flags
|= EP_IntValue
;
1529 pNew
->u
.iValue
= iCol
;
1530 if( pItem
->pExpr
==pE
){
1531 pItem
->pExpr
= pNew
;
1533 Expr
*pParent
= pItem
->pExpr
;
1534 assert( pParent
->op
==TK_COLLATE
);
1535 while( pParent
->pLeft
->op
==TK_COLLATE
) pParent
= pParent
->pLeft
;
1536 assert( pParent
->pLeft
==pE
);
1537 pParent
->pLeft
= pNew
;
1539 sqlite3ExprDelete(db
, pE
);
1540 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1547 pSelect
= pSelect
->pNext
;
1549 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1550 if( pOrderBy
->a
[i
].fg
.done
==0 ){
1551 sqlite3ErrorMsg(pParse
, "%r ORDER BY term does not match any "
1552 "column in the result set", i
+1);
1560 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1561 ** the SELECT statement pSelect. If any term is reference to a
1562 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1563 ** field) then convert that term into a copy of the corresponding result set
1566 ** If any errors are detected, add an error message to pParse and
1567 ** return non-zero. Return zero if no errors are seen.
1569 int sqlite3ResolveOrderGroupBy(
1570 Parse
*pParse
, /* Parsing context. Leave error messages here */
1571 Select
*pSelect
, /* The SELECT statement containing the clause */
1572 ExprList
*pOrderBy
, /* The ORDER BY or GROUP BY clause to be processed */
1573 const char *zType
/* "ORDER" or "GROUP" */
1576 sqlite3
*db
= pParse
->db
;
1578 struct ExprList_item
*pItem
;
1580 if( pOrderBy
==0 || pParse
->db
->mallocFailed
|| IN_RENAME_OBJECT
) return 0;
1581 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1582 sqlite3ErrorMsg(pParse
, "too many terms in %s BY clause", zType
);
1585 pEList
= pSelect
->pEList
;
1586 assert( pEList
!=0 ); /* sqlite3SelectNew() guarantees this */
1587 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1588 if( pItem
->u
.x
.iOrderByCol
){
1589 if( pItem
->u
.x
.iOrderByCol
>pEList
->nExpr
){
1590 resolveOutOfRangeError(pParse
, zType
, i
+1, pEList
->nExpr
, 0);
1593 resolveAlias(pParse
, pEList
, pItem
->u
.x
.iOrderByCol
-1, pItem
->pExpr
,0);
1599 #ifndef SQLITE_OMIT_WINDOWFUNC
1601 ** Walker callback for windowRemoveExprFromSelect().
1603 static int resolveRemoveWindowsCb(Walker
*pWalker
, Expr
*pExpr
){
1604 UNUSED_PARAMETER(pWalker
);
1605 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1606 Window
*pWin
= pExpr
->y
.pWin
;
1607 sqlite3WindowUnlinkFromSelect(pWin
);
1609 return WRC_Continue
;
1613 ** Remove any Window objects owned by the expression pExpr from the
1614 ** Select.pWin list of Select object pSelect.
1616 static void windowRemoveExprFromSelect(Select
*pSelect
, Expr
*pExpr
){
1617 if( pSelect
->pWin
){
1619 memset(&sWalker
, 0, sizeof(Walker
));
1620 sWalker
.xExprCallback
= resolveRemoveWindowsCb
;
1621 sWalker
.u
.pSelect
= pSelect
;
1622 sqlite3WalkExpr(&sWalker
, pExpr
);
1626 # define windowRemoveExprFromSelect(a, b)
1627 #endif /* SQLITE_OMIT_WINDOWFUNC */
1630 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1631 ** The Name context of the SELECT statement is pNC. zType is either
1632 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1634 ** This routine resolves each term of the clause into an expression.
1635 ** If the order-by term is an integer I between 1 and N (where N is the
1636 ** number of columns in the result set of the SELECT) then the expression
1637 ** in the resolution is a copy of the I-th result-set expression. If
1638 ** the order-by term is an identifier that corresponds to the AS-name of
1639 ** a result-set expression, then the term resolves to a copy of the
1640 ** result-set expression. Otherwise, the expression is resolved in
1641 ** the usual way - using sqlite3ResolveExprNames().
1643 ** This routine returns the number of errors. If errors occur, then
1644 ** an appropriate error message might be left in pParse. (OOM errors
1647 static int resolveOrderGroupBy(
1648 NameContext
*pNC
, /* The name context of the SELECT statement */
1649 Select
*pSelect
, /* The SELECT statement holding pOrderBy */
1650 ExprList
*pOrderBy
, /* An ORDER BY or GROUP BY clause to resolve */
1651 const char *zType
/* Either "ORDER" or "GROUP", as appropriate */
1653 int i
, j
; /* Loop counters */
1654 int iCol
; /* Column number */
1655 struct ExprList_item
*pItem
; /* A term of the ORDER BY clause */
1656 Parse
*pParse
; /* Parsing context */
1657 int nResult
; /* Number of terms in the result set */
1659 assert( pOrderBy
!=0 );
1660 nResult
= pSelect
->pEList
->nExpr
;
1661 pParse
= pNC
->pParse
;
1662 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1663 Expr
*pE
= pItem
->pExpr
;
1664 Expr
*pE2
= sqlite3ExprSkipCollateAndLikely(pE
);
1665 if( NEVER(pE2
==0) ) continue;
1666 if( zType
[0]!='G' ){
1667 iCol
= resolveAsName(pParse
, pSelect
->pEList
, pE2
);
1669 /* If an AS-name match is found, mark this ORDER BY column as being
1670 ** a copy of the iCol-th result-set column. The subsequent call to
1671 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1672 ** copy of the iCol-th result-set expression. */
1673 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1677 if( sqlite3ExprIsInteger(pE2
, &iCol
) ){
1678 /* The ORDER BY term is an integer constant. Again, set the column
1679 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1680 ** order-by term to a copy of the result-set expression */
1681 if( iCol
<1 || iCol
>0xffff ){
1682 resolveOutOfRangeError(pParse
, zType
, i
+1, nResult
, pE2
);
1685 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1689 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1690 pItem
->u
.x
.iOrderByCol
= 0;
1691 if( sqlite3ResolveExprNames(pNC
, pE
) ){
1694 for(j
=0; j
<pSelect
->pEList
->nExpr
; j
++){
1695 if( sqlite3ExprCompare(0, pE
, pSelect
->pEList
->a
[j
].pExpr
, -1)==0 ){
1696 /* Since this expresion is being changed into a reference
1697 ** to an identical expression in the result set, remove all Window
1698 ** objects belonging to the expression from the Select.pWin list. */
1699 windowRemoveExprFromSelect(pSelect
, pE
);
1700 pItem
->u
.x
.iOrderByCol
= j
+1;
1704 return sqlite3ResolveOrderGroupBy(pParse
, pSelect
, pOrderBy
, zType
);
1708 ** Resolve names in the SELECT statement p and all of its descendants.
1710 static int resolveSelectStep(Walker
*pWalker
, Select
*p
){
1711 NameContext
*pOuterNC
; /* Context that contains this SELECT */
1712 NameContext sNC
; /* Name context of this SELECT */
1713 int isCompound
; /* True if p is a compound select */
1714 int nCompound
; /* Number of compound terms processed so far */
1715 Parse
*pParse
; /* Parsing context */
1716 int i
; /* Loop counter */
1717 ExprList
*pGroupBy
; /* The GROUP BY clause */
1718 Select
*pLeftmost
; /* Left-most of SELECT of a compound */
1719 sqlite3
*db
; /* Database connection */
1723 if( p
->selFlags
& SF_Resolved
){
1726 pOuterNC
= pWalker
->u
.pNC
;
1727 pParse
= pWalker
->pParse
;
1730 /* Normally sqlite3SelectExpand() will be called first and will have
1731 ** already expanded this SELECT. However, if this is a subquery within
1732 ** an expression, sqlite3ResolveExprNames() will be called without a
1733 ** prior call to sqlite3SelectExpand(). When that happens, let
1734 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1735 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1736 ** this routine in the correct order.
1738 if( (p
->selFlags
& SF_Expanded
)==0 ){
1739 sqlite3SelectPrep(pParse
, p
, pOuterNC
);
1740 return pParse
->nErr
? WRC_Abort
: WRC_Prune
;
1743 isCompound
= p
->pPrior
!=0;
1747 assert( (p
->selFlags
& SF_Expanded
)!=0 );
1748 assert( (p
->selFlags
& SF_Resolved
)==0 );
1749 assert( db
->suppressErr
==0 ); /* SF_Resolved not set if errors suppressed */
1750 p
->selFlags
|= SF_Resolved
;
1753 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1754 ** are not allowed to refer to any names, so pass an empty NameContext.
1756 memset(&sNC
, 0, sizeof(sNC
));
1757 sNC
.pParse
= pParse
;
1759 if( sqlite3ResolveExprNames(&sNC
, p
->pLimit
) ){
1763 /* If the SF_Converted flags is set, then this Select object was
1764 ** was created by the convertCompoundSelectToSubquery() function.
1765 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1766 ** as if it were part of the sub-query, not the parent. This block
1767 ** moves the pOrderBy down to the sub-query. It will be moved back
1768 ** after the names have been resolved. */
1769 if( p
->selFlags
& SF_Converted
){
1770 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1771 assert( p
->pSrc
->nSrc
==1 && p
->pOrderBy
);
1772 assert( pSub
->pPrior
&& pSub
->pOrderBy
==0 );
1773 pSub
->pOrderBy
= p
->pOrderBy
;
1777 /* Recursively resolve names in all subqueries in the FROM clause
1779 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1780 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1781 if( pItem
->pSelect
&& (pItem
->pSelect
->selFlags
& SF_Resolved
)==0 ){
1782 int nRef
= pOuterNC
? pOuterNC
->nRef
: 0;
1783 const char *zSavedContext
= pParse
->zAuthContext
;
1785 if( pItem
->zName
) pParse
->zAuthContext
= pItem
->zName
;
1786 sqlite3ResolveSelectNames(pParse
, pItem
->pSelect
, pOuterNC
);
1787 pParse
->zAuthContext
= zSavedContext
;
1788 if( pParse
->nErr
) return WRC_Abort
;
1789 assert( db
->mallocFailed
==0 );
1791 /* If the number of references to the outer context changed when
1792 ** expressions in the sub-select were resolved, the sub-select
1793 ** is correlated. It is not required to check the refcount on any
1794 ** but the innermost outer context object, as lookupName() increments
1795 ** the refcount on all contexts between the current one and the
1796 ** context containing the column when it resolves a name. */
1798 assert( pItem
->fg
.isCorrelated
==0 && pOuterNC
->nRef
>=nRef
);
1799 pItem
->fg
.isCorrelated
= (pOuterNC
->nRef
>nRef
);
1804 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1805 ** resolve the result-set expression list.
1807 sNC
.ncFlags
= NC_AllowAgg
|NC_AllowWin
;
1808 sNC
.pSrcList
= p
->pSrc
;
1809 sNC
.pNext
= pOuterNC
;
1811 /* Resolve names in the result set. */
1812 if( sqlite3ResolveExprListNames(&sNC
, p
->pEList
) ) return WRC_Abort
;
1813 sNC
.ncFlags
&= ~NC_AllowWin
;
1815 /* If there are no aggregate functions in the result-set, and no GROUP BY
1816 ** expression, do not allow aggregates in any of the other expressions.
1818 assert( (p
->selFlags
& SF_Aggregate
)==0 );
1819 pGroupBy
= p
->pGroupBy
;
1820 if( pGroupBy
|| (sNC
.ncFlags
& NC_HasAgg
)!=0 ){
1821 assert( NC_MinMaxAgg
==SF_MinMaxAgg
);
1822 assert( NC_OrderAgg
==SF_OrderByReqd
);
1823 p
->selFlags
|= SF_Aggregate
| (sNC
.ncFlags
&(NC_MinMaxAgg
|NC_OrderAgg
));
1825 sNC
.ncFlags
&= ~NC_AllowAgg
;
1828 /* Add the output column list to the name-context before parsing the
1829 ** other expressions in the SELECT statement. This is so that
1830 ** expressions in the WHERE clause (etc.) can refer to expressions by
1831 ** aliases in the result set.
1833 ** Minor point: If this is the case, then the expression will be
1834 ** re-evaluated for each reference to it.
1836 assert( (sNC
.ncFlags
& (NC_UAggInfo
|NC_UUpsert
|NC_UBaseReg
))==0 );
1837 sNC
.uNC
.pEList
= p
->pEList
;
1838 sNC
.ncFlags
|= NC_UEList
;
1840 if( (p
->selFlags
& SF_Aggregate
)==0 ){
1841 sqlite3ErrorMsg(pParse
, "HAVING clause on a non-aggregate query");
1844 if( sqlite3ResolveExprNames(&sNC
, p
->pHaving
) ) return WRC_Abort
;
1846 if( sqlite3ResolveExprNames(&sNC
, p
->pWhere
) ) return WRC_Abort
;
1848 /* Resolve names in table-valued-function arguments */
1849 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1850 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1851 if( pItem
->fg
.isTabFunc
1852 && sqlite3ResolveExprListNames(&sNC
, pItem
->u1
.pFuncArg
)
1858 #ifndef SQLITE_OMIT_WINDOWFUNC
1859 if( IN_RENAME_OBJECT
){
1861 for(pWin
=p
->pWinDefn
; pWin
; pWin
=pWin
->pNextWin
){
1862 if( sqlite3ResolveExprListNames(&sNC
, pWin
->pOrderBy
)
1863 || sqlite3ResolveExprListNames(&sNC
, pWin
->pPartition
)
1871 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1875 sNC
.ncFlags
|= NC_AllowAgg
|NC_AllowWin
;
1877 /* If this is a converted compound query, move the ORDER BY clause from
1878 ** the sub-query back to the parent query. At this point each term
1879 ** within the ORDER BY clause has been transformed to an integer value.
1880 ** These integers will be replaced by copies of the corresponding result
1881 ** set expressions by the call to resolveOrderGroupBy() below. */
1882 if( p
->selFlags
& SF_Converted
){
1883 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1884 p
->pOrderBy
= pSub
->pOrderBy
;
1888 /* Process the ORDER BY clause for singleton SELECT statements.
1889 ** The ORDER BY clause for compounds SELECT statements is handled
1890 ** below, after all of the result-sets for all of the elements of
1891 ** the compound have been resolved.
1893 ** If there is an ORDER BY clause on a term of a compound-select other
1894 ** than the right-most term, then that is a syntax error. But the error
1895 ** is not detected until much later, and so we need to go ahead and
1896 ** resolve those symbols on the incorrect ORDER BY for consistency.
1899 && isCompound
<=nCompound
/* Defer right-most ORDER BY of a compound */
1900 && resolveOrderGroupBy(&sNC
, p
, p
->pOrderBy
, "ORDER")
1904 if( db
->mallocFailed
){
1907 sNC
.ncFlags
&= ~NC_AllowWin
;
1909 /* Resolve the GROUP BY clause. At the same time, make sure
1910 ** the GROUP BY clause does not contain aggregate functions.
1913 struct ExprList_item
*pItem
;
1915 if( resolveOrderGroupBy(&sNC
, p
, pGroupBy
, "GROUP") || db
->mallocFailed
){
1918 for(i
=0, pItem
=pGroupBy
->a
; i
<pGroupBy
->nExpr
; i
++, pItem
++){
1919 if( ExprHasProperty(pItem
->pExpr
, EP_Agg
) ){
1920 sqlite3ErrorMsg(pParse
, "aggregate functions are not allowed in "
1921 "the GROUP BY clause");
1927 /* If this is part of a compound SELECT, check that it has the right
1928 ** number of expressions in the select list. */
1929 if( p
->pNext
&& p
->pEList
->nExpr
!=p
->pNext
->pEList
->nExpr
){
1930 sqlite3SelectWrongNumTermsError(pParse
, p
->pNext
);
1934 /* Advance to the next term of the compound
1940 /* Resolve the ORDER BY on a compound SELECT after all terms of
1941 ** the compound have been resolved.
1943 if( isCompound
&& resolveCompoundOrderBy(pParse
, pLeftmost
) ){
1951 ** This routine walks an expression tree and resolves references to
1952 ** table columns and result-set columns. At the same time, do error
1953 ** checking on function usage and set a flag if any aggregate functions
1956 ** To resolve table columns references we look for nodes (or subtrees) of the
1957 ** form X.Y.Z or Y.Z or just Z where
1959 ** X: The name of a database. Ex: "main" or "temp" or
1960 ** the symbolic name assigned to an ATTACH-ed database.
1962 ** Y: The name of a table in a FROM clause. Or in a trigger
1963 ** one of the special names "old" or "new".
1965 ** Z: The name of a column in table Y.
1967 ** The node at the root of the subtree is modified as follows:
1969 ** Expr.op Changed to TK_COLUMN
1970 ** Expr.pTab Points to the Table object for X.Y
1971 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
1972 ** Expr.iTable The VDBE cursor number for X.Y
1975 ** To resolve result-set references, look for expression nodes of the
1976 ** form Z (with no X and Y prefix) where the Z matches the right-hand
1977 ** size of an AS clause in the result-set of a SELECT. The Z expression
1978 ** is replaced by a copy of the left-hand side of the result-set expression.
1979 ** Table-name and function resolution occurs on the substituted expression
1980 ** tree. For example, in:
1982 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
1984 ** The "x" term of the order by is replaced by "a+b" to render:
1986 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
1988 ** Function calls are checked to make sure that the function is
1989 ** defined and that the correct number of arguments are specified.
1990 ** If the function is an aggregate function, then the NC_HasAgg flag is
1991 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
1992 ** If an expression contains aggregate functions then the EP_Agg
1993 ** property on the expression is set.
1995 ** An error message is left in pParse if anything is amiss. The number
1996 ** if errors is returned.
1998 int sqlite3ResolveExprNames(
1999 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2000 Expr
*pExpr
/* The expression to be analyzed. */
2005 if( pExpr
==0 ) return SQLITE_OK
;
2006 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2007 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2008 w
.pParse
= pNC
->pParse
;
2009 w
.xExprCallback
= resolveExprStep
;
2010 w
.xSelectCallback
= (pNC
->ncFlags
& NC_NoSelect
) ? 0 : resolveSelectStep
;
2011 w
.xSelectCallback2
= 0;
2013 #if SQLITE_MAX_EXPR_DEPTH>0
2014 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2015 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2016 return SQLITE_ERROR
;
2019 sqlite3WalkExpr(&w
, pExpr
);
2020 #if SQLITE_MAX_EXPR_DEPTH>0
2021 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2023 assert( EP_Agg
==NC_HasAgg
);
2024 assert( EP_Win
==NC_HasWin
);
2025 testcase( pNC
->ncFlags
& NC_HasAgg
);
2026 testcase( pNC
->ncFlags
& NC_HasWin
);
2027 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2028 pNC
->ncFlags
|= savedHasAgg
;
2029 return pNC
->nNcErr
>0 || w
.pParse
->nErr
>0;
2033 ** Resolve all names for all expression in an expression list. This is
2034 ** just like sqlite3ResolveExprNames() except that it works for an expression
2035 ** list rather than a single expression.
2037 int sqlite3ResolveExprListNames(
2038 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2039 ExprList
*pList
/* The expression list to be analyzed. */
2042 int savedHasAgg
= 0;
2044 if( pList
==0 ) return WRC_Continue
;
2045 w
.pParse
= pNC
->pParse
;
2046 w
.xExprCallback
= resolveExprStep
;
2047 w
.xSelectCallback
= resolveSelectStep
;
2048 w
.xSelectCallback2
= 0;
2050 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2051 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2052 for(i
=0; i
<pList
->nExpr
; i
++){
2053 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2054 if( pExpr
==0 ) continue;
2055 #if SQLITE_MAX_EXPR_DEPTH>0
2056 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2057 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2061 sqlite3WalkExpr(&w
, pExpr
);
2062 #if SQLITE_MAX_EXPR_DEPTH>0
2063 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2065 assert( EP_Agg
==NC_HasAgg
);
2066 assert( EP_Win
==NC_HasWin
);
2067 testcase( pNC
->ncFlags
& NC_HasAgg
);
2068 testcase( pNC
->ncFlags
& NC_HasWin
);
2069 if( pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
) ){
2070 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2071 savedHasAgg
|= pNC
->ncFlags
&
2072 (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2073 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2075 if( w
.pParse
->nErr
>0 ) return WRC_Abort
;
2077 pNC
->ncFlags
|= savedHasAgg
;
2078 return WRC_Continue
;
2082 ** Resolve all names in all expressions of a SELECT and in all
2083 ** decendents of the SELECT, including compounds off of p->pPrior,
2084 ** subqueries in expressions, and subqueries used as FROM clause
2087 ** See sqlite3ResolveExprNames() for a description of the kinds of
2088 ** transformations that occur.
2090 ** All SELECT statements should have been expanded using
2091 ** sqlite3SelectExpand() prior to invoking this routine.
2093 void sqlite3ResolveSelectNames(
2094 Parse
*pParse
, /* The parser context */
2095 Select
*p
, /* The SELECT statement being coded. */
2096 NameContext
*pOuterNC
/* Name context for parent SELECT statement */
2101 w
.xExprCallback
= resolveExprStep
;
2102 w
.xSelectCallback
= resolveSelectStep
;
2103 w
.xSelectCallback2
= 0;
2106 sqlite3WalkSelect(&w
, p
);
2110 ** Resolve names in expressions that can only reference a single table
2111 ** or which cannot reference any tables at all. Examples:
2115 ** (1) CHECK constraints NC_IsCheck
2116 ** (2) WHERE clauses on partial indices NC_PartIdx
2117 ** (3) Expressions in indexes on expressions NC_IdxExpr
2118 ** (4) Expression arguments to VACUUM INTO. 0
2119 ** (5) GENERATED ALWAYS as expressions NC_GenCol
2121 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2122 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2123 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2125 ** Any errors cause an error message to be set in pParse.
2127 int sqlite3ResolveSelfReference(
2128 Parse
*pParse
, /* Parsing context */
2129 Table
*pTab
, /* The table being referenced, or NULL */
2130 int type
, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2131 Expr
*pExpr
, /* Expression to resolve. May be NULL. */
2132 ExprList
*pList
/* Expression list to resolve. May be NULL. */
2134 SrcList sSrc
; /* Fake SrcList for pParse->pNewTable */
2135 NameContext sNC
; /* Name context for pParse->pNewTable */
2138 assert( type
==0 || pTab
!=0 );
2139 assert( type
==NC_IsCheck
|| type
==NC_PartIdx
|| type
==NC_IdxExpr
2140 || type
==NC_GenCol
|| pTab
==0 );
2141 memset(&sNC
, 0, sizeof(sNC
));
2142 memset(&sSrc
, 0, sizeof(sSrc
));
2145 sSrc
.a
[0].zName
= pTab
->zName
;
2146 sSrc
.a
[0].pTab
= pTab
;
2147 sSrc
.a
[0].iCursor
= -1;
2148 if( pTab
->pSchema
!=pParse
->db
->aDb
[1].pSchema
){
2149 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2150 ** schema elements */
2154 sNC
.pParse
= pParse
;
2155 sNC
.pSrcList
= &sSrc
;
2156 sNC
.ncFlags
= type
| NC_IsDDL
;
2157 if( (rc
= sqlite3ResolveExprNames(&sNC
, pExpr
))!=SQLITE_OK
) return rc
;
2158 if( pList
) rc
= sqlite3ResolveExprListNames(&sNC
, pList
);