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
;
82 assert( !ExprHasProperty(pExpr
, EP_Reduced
|EP_TokenOnly
) );
83 if( pExpr
->pAggInfo
) return;
85 pDup
= sqlite3ExprDup(db
, pOrig
, 0);
86 if( db
->mallocFailed
){
87 sqlite3ExprDelete(db
, pDup
);
91 incrAggFunctionDepth(pDup
, nSubquery
);
92 if( pExpr
->op
==TK_COLLATE
){
93 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
94 pDup
= sqlite3ExprAddCollateString(pParse
, pDup
, pExpr
->u
.zToken
);
96 memcpy(&temp
, pDup
, sizeof(Expr
));
97 memcpy(pDup
, pExpr
, sizeof(Expr
));
98 memcpy(pExpr
, &temp
, sizeof(Expr
));
99 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
100 if( ALWAYS(pExpr
->y
.pWin
!=0) ){
101 pExpr
->y
.pWin
->pOwner
= pExpr
;
104 sqlite3ExprDeferredDelete(pParse
, pDup
);
109 ** Subqueries store the original database, table and column names for their
110 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN",
111 ** and mark the expression-list item by setting ExprList.a[].fg.eEName
114 ** Check to see if the zSpan/eEName of the expression-list item passed to this
115 ** routine matches the zDb, zTab, and zCol. If any of zDb, zTab, and zCol are
116 ** NULL then those fields will match anything. Return true if there is a match,
117 ** or false otherwise.
119 ** SF_NestedFrom subqueries also store an entry for the implicit rowid (or
120 ** _rowid_, or oid) column by setting ExprList.a[].fg.eEName to ENAME_ROWID,
121 ** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem
122 ** argument matches if zCol is a rowid alias. If it is not NULL, (*pbRowid)
123 ** is set to 1 if there is this kind of match.
125 int sqlite3MatchEName(
126 const struct ExprList_item
*pItem
,
134 int eEName
= pItem
->fg
.eEName
;
135 if( eEName
!=ENAME_TAB
&& (eEName
!=ENAME_ROWID
|| NEVER(pbRowid
==0)) ){
138 assert( pbRowid
==0 || *pbRowid
==0 );
139 zSpan
= pItem
->zEName
;
140 for(n
=0; ALWAYS(zSpan
[n
]) && zSpan
[n
]!='.'; n
++){}
141 if( zDb
&& (sqlite3StrNICmp(zSpan
, zDb
, n
)!=0 || zDb
[n
]!=0) ){
145 for(n
=0; ALWAYS(zSpan
[n
]) && zSpan
[n
]!='.'; n
++){}
146 if( zTab
&& (sqlite3StrNICmp(zSpan
, zTab
, n
)!=0 || zTab
[n
]!=0) ){
151 if( eEName
==ENAME_TAB
&& sqlite3StrICmp(zSpan
, zCol
)!=0 ) return 0;
152 if( eEName
==ENAME_ROWID
&& sqlite3IsRowid(zCol
)==0 ) return 0;
154 if( eEName
==ENAME_ROWID
) *pbRowid
= 1;
159 ** Return TRUE if the double-quoted string mis-feature should be supported.
161 static int areDoubleQuotedStringsEnabled(sqlite3
*db
, NameContext
*pTopNC
){
162 if( db
->init
.busy
) return 1; /* Always support for legacy schemas */
163 if( pTopNC
->ncFlags
& NC_IsDDL
){
164 /* Currently parsing a DDL statement */
165 if( sqlite3WritableSchema(db
) && (db
->flags
& SQLITE_DqsDML
)!=0 ){
168 return (db
->flags
& SQLITE_DqsDDL
)!=0;
170 /* Currently parsing a DML statement */
171 return (db
->flags
& SQLITE_DqsDML
)!=0;
176 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
177 ** return the appropriate colUsed mask.
179 Bitmask
sqlite3ExprColUsed(Expr
*pExpr
){
184 assert( ExprUseYTab(pExpr
) );
185 pExTab
= pExpr
->y
.pTab
;
187 assert( n
< pExTab
->nCol
);
188 if( (pExTab
->tabFlags
& TF_HasGenerated
)!=0
189 && (pExTab
->aCol
[n
].colFlags
& COLFLAG_GENERATED
)!=0
191 testcase( pExTab
->nCol
==BMS
-1 );
192 testcase( pExTab
->nCol
==BMS
);
193 return pExTab
->nCol
>=BMS
? ALLBITS
: MASKBIT(pExTab
->nCol
)-1;
195 testcase( n
==BMS
-1 );
197 if( n
>=BMS
) n
= BMS
-1;
198 return ((Bitmask
)1)<<n
;
203 ** Create a new expression term for the column specified by pMatch and
204 ** iColumn. Append this new expression term to the FULL JOIN Match set
205 ** in *ppList. Create a new *ppList if this is the first term in the
208 static void extendFJMatch(
209 Parse
*pParse
, /* Parsing context */
210 ExprList
**ppList
, /* ExprList to extend */
211 SrcItem
*pMatch
, /* Source table containing the column */
212 i16 iColumn
/* The column number */
214 Expr
*pNew
= sqlite3ExprAlloc(pParse
->db
, TK_COLUMN
, 0, 0);
216 pNew
->iTable
= pMatch
->iCursor
;
217 pNew
->iColumn
= iColumn
;
218 pNew
->y
.pTab
= pMatch
->pTab
;
219 assert( (pMatch
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
))!=0 );
220 ExprSetProperty(pNew
, EP_CanBeNull
);
221 *ppList
= sqlite3ExprListAppend(pParse
, *ppList
, pNew
);
226 ** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
228 static SQLITE_NOINLINE
int isValidSchemaTableName(
229 const char *zTab
, /* Name as it appears in the SQL */
230 Table
*pTab
, /* The schema table we are trying to match */
231 Schema
*pSchema
/* non-NULL if a database qualifier is present */
235 assert( pTab
->tnum
==1 );
236 if( sqlite3StrNICmp(zTab
, "sqlite_", 7)!=0 ) return 0;
237 zLegacy
= pTab
->zName
;
238 if( strcmp(zLegacy
+7, &LEGACY_TEMP_SCHEMA_TABLE
[7])==0 ){
239 if( sqlite3StrICmp(zTab
+7, &PREFERRED_TEMP_SCHEMA_TABLE
[7])==0 ){
242 if( pSchema
==0 ) return 0;
243 if( sqlite3StrICmp(zTab
+7, &LEGACY_SCHEMA_TABLE
[7])==0 ) return 1;
244 if( sqlite3StrICmp(zTab
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ) return 1;
246 if( sqlite3StrICmp(zTab
+7, &PREFERRED_SCHEMA_TABLE
[7])==0 ) return 1;
252 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
253 ** that name in the set of source tables in pSrcList and make the pExpr
254 ** expression node refer back to that source column. The following changes
255 ** are made to pExpr:
257 ** pExpr->iDb Set the index in db->aDb[] of the database X
258 ** (even if X is implied).
259 ** pExpr->iTable Set to the cursor number for the table obtained
261 ** pExpr->y.pTab Points to the Table structure of X.Y (even if
262 ** X and/or Y are implied.)
263 ** pExpr->iColumn Set to the column number within the table.
264 ** pExpr->op Set to TK_COLUMN.
265 ** pExpr->pLeft Any expression this points to is deleted
266 ** pExpr->pRight Any expression this points to is deleted.
268 ** The zDb variable is the name of the database (the "X"). This value may be
269 ** NULL meaning that name is of the form Y.Z or Z. Any available database
270 ** can be used. The zTable variable is the name of the table (the "Y"). This
271 ** value can be NULL if zDb is also NULL. If zTable is NULL it
272 ** means that the form of the name is Z and that columns from any table
275 ** If the name cannot be resolved unambiguously, leave an error message
276 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
278 static int lookupName(
279 Parse
*pParse
, /* The parsing context */
280 const char *zDb
, /* Name of the database containing table, or NULL */
281 const char *zTab
, /* Name of table containing column, or NULL */
282 const Expr
*pRight
, /* Name of the column. */
283 NameContext
*pNC
, /* The name context used to resolve the name */
284 Expr
*pExpr
/* Make this EXPR node point to the selected column */
286 int i
, j
; /* Loop counters */
287 int cnt
= 0; /* Number of matching column names */
288 int cntTab
= 0; /* Number of potential "rowid" matches */
289 int nSubquery
= 0; /* How many levels of subquery */
290 sqlite3
*db
= pParse
->db
; /* The database connection */
291 SrcItem
*pItem
; /* Use for looping over pSrcList items */
292 SrcItem
*pMatch
= 0; /* The matching pSrcList item */
293 NameContext
*pTopNC
= pNC
; /* First namecontext in the list */
294 Schema
*pSchema
= 0; /* Schema of the expression */
295 int eNewExprOp
= TK_COLUMN
; /* New value for pExpr->op on success */
296 Table
*pTab
= 0; /* Table holding the row */
297 Column
*pCol
; /* A column of pTab */
298 ExprList
*pFJMatch
= 0; /* Matches for FULL JOIN .. USING */
299 const char *zCol
= pRight
->u
.zToken
;
301 assert( pNC
); /* the name context cannot be NULL. */
302 assert( zCol
); /* The Z in X.Y.Z cannot be NULL */
303 assert( zDb
==0 || zTab
!=0 );
304 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
306 /* Initialize the node to no-match */
308 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
310 /* Translate the schema name in zDb into a pointer to the corresponding
311 ** schema. If not found, pSchema will remain NULL and nothing will match
312 ** resulting in an appropriate error message toward the end of this routine
315 testcase( pNC
->ncFlags
& NC_PartIdx
);
316 testcase( pNC
->ncFlags
& NC_IsCheck
);
317 if( (pNC
->ncFlags
& (NC_PartIdx
|NC_IsCheck
))!=0 ){
318 /* Silently ignore database qualifiers inside CHECK constraints and
319 ** partial indices. Do not raise errors because that might break
320 ** legacy and because it does not hurt anything to just ignore the
324 for(i
=0; i
<db
->nDb
; i
++){
325 assert( db
->aDb
[i
].zDbSName
);
326 if( sqlite3StrICmp(db
->aDb
[i
].zDbSName
,zDb
)==0 ){
327 pSchema
= db
->aDb
[i
].pSchema
;
331 if( i
==db
->nDb
&& sqlite3StrICmp("main", zDb
)==0 ){
332 /* This branch is taken when the main database has been renamed
333 ** using SQLITE_DBCONFIG_MAINDBNAME. */
334 pSchema
= db
->aDb
[0].pSchema
;
335 zDb
= db
->aDb
[0].zDbSName
;
340 /* Start at the inner-most context and move outward until a match is found */
341 assert( pNC
&& cnt
==0 );
344 SrcList
*pSrcList
= pNC
->pSrcList
;
347 for(i
=0, pItem
=pSrcList
->a
; i
<pSrcList
->nSrc
; i
++, pItem
++){
350 assert( pTab
!=0 && pTab
->zName
!=0 );
351 assert( pTab
->nCol
>0 || pParse
->nErr
);
352 assert( (int)pItem
->fg
.isNestedFrom
== IsNestedFrom(pItem
->pSelect
) );
353 if( pItem
->fg
.isNestedFrom
){
354 /* In this case, pItem is a subquery that has been formed from a
355 ** parenthesized subset of the FROM clause terms. Example:
356 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
357 ** \_________________________/
358 ** This pItem -------------^
361 assert( pItem
->pSelect
!=0 );
362 pEList
= pItem
->pSelect
->pEList
;
364 assert( pEList
->nExpr
==pTab
->nCol
);
365 for(j
=0; j
<pEList
->nExpr
; j
++){
366 int bRowid
= 0; /* True if possible rowid match */
367 if( !sqlite3MatchEName(&pEList
->a
[j
], zCol
, zTab
, zDb
, &bRowid
) ){
372 if( pItem
->fg
.isUsing
==0
373 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
375 /* Two or more tables have the same column name which is
376 ** not joined by USING. This is an error. Signal as much
377 ** by clearing pFJMatch and letting cnt go above 1. */
378 sqlite3ExprListDelete(db
, pFJMatch
);
381 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
382 /* An INNER or LEFT JOIN. Use the left-most table */
385 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
386 /* A RIGHT JOIN. Use the right-most table */
388 sqlite3ExprListDelete(db
, pFJMatch
);
391 /* For a FULL JOIN, we must construct a coalesce() func */
392 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
398 /* This is a potential rowid match, but there has already been
399 ** a real match found. So this can be ignored. */
405 pEList
->a
[j
].fg
.bUsed
= 1;
407 /* rowid cannot be part of a USING clause - assert() this. */
408 assert( bRowid
==0 || pEList
->a
[j
].fg
.bUsingTerm
==0 );
409 if( pEList
->a
[j
].fg
.bUsingTerm
) break;
411 if( hit
|| zTab
==0 ) continue;
413 assert( zDb
==0 || zTab
!=0 );
416 if( pTab
->pSchema
!=pSchema
) continue;
417 if( pSchema
==0 && strcmp(zDb
,"*")!=0 ) continue;
419 if( pItem
->zAlias
!=0 ){
420 if( sqlite3StrICmp(zTab
, pItem
->zAlias
)!=0 ){
423 }else if( sqlite3StrICmp(zTab
, pTab
->zName
)!=0 ){
424 if( pTab
->tnum
!=1 ) continue;
425 if( !isValidSchemaTableName(zTab
, pTab
, pSchema
) ) continue;
427 assert( ExprUseYTab(pExpr
) );
428 if( IN_RENAME_OBJECT
&& pItem
->zAlias
){
429 sqlite3RenameTokenRemap(pParse
, 0, (void*)&pExpr
->y
.pTab
);
432 hCol
= sqlite3StrIHash(zCol
);
433 for(j
=0, pCol
=pTab
->aCol
; j
<pTab
->nCol
; j
++, pCol
++){
434 if( pCol
->hName
==hCol
435 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
438 if( pItem
->fg
.isUsing
==0
439 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
441 /* Two or more tables have the same column name which is
442 ** not joined by USING. This is an error. Signal as much
443 ** by clearing pFJMatch and letting cnt go above 1. */
444 sqlite3ExprListDelete(db
, pFJMatch
);
447 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
448 /* An INNER or LEFT JOIN. Use the left-most table */
451 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
452 /* A RIGHT JOIN. Use the right-most table */
454 sqlite3ExprListDelete(db
, pFJMatch
);
457 /* For a FULL JOIN, we must construct a coalesce() func */
458 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
463 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
464 pExpr
->iColumn
= j
==pTab
->iPKey
? -1 : (i16
)j
;
465 if( pItem
->fg
.isNestedFrom
){
466 sqlite3SrcItemColumnUsed(pItem
, j
);
471 if( 0==cnt
&& VisibleRowid(pTab
) ){
477 pExpr
->iTable
= pMatch
->iCursor
;
478 assert( ExprUseYTab(pExpr
) );
479 pExpr
->y
.pTab
= pMatch
->pTab
;
480 if( (pMatch
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
))!=0 ){
481 ExprSetProperty(pExpr
, EP_CanBeNull
);
483 pSchema
= pExpr
->y
.pTab
->pSchema
;
485 } /* if( pSrcList ) */
487 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
488 /* If we have not already resolved the name, then maybe
489 ** it is a new.* or old.* trigger argument reference. Or
490 ** maybe it is an excluded.* from an upsert. Or maybe it is
491 ** a reference in the RETURNING clause to a table being modified.
493 if( cnt
==0 && zDb
==0 ){
495 #ifndef SQLITE_OMIT_TRIGGER
496 if( pParse
->pTriggerTab
!=0 ){
497 int op
= pParse
->eTriggerOp
;
498 assert( op
==TK_DELETE
|| op
==TK_UPDATE
|| op
==TK_INSERT
);
499 if( pParse
->bReturning
){
500 if( (pNC
->ncFlags
& NC_UBaseReg
)!=0
502 || sqlite3StrICmp(zTab
,pParse
->pTriggerTab
->zName
)==0)
504 pExpr
->iTable
= op
!=TK_DELETE
;
505 pTab
= pParse
->pTriggerTab
;
507 }else if( op
!=TK_DELETE
&& zTab
&& sqlite3StrICmp("new",zTab
) == 0 ){
509 pTab
= pParse
->pTriggerTab
;
510 }else if( op
!=TK_INSERT
&& zTab
&& sqlite3StrICmp("old",zTab
)==0 ){
512 pTab
= pParse
->pTriggerTab
;
515 #endif /* SQLITE_OMIT_TRIGGER */
516 #ifndef SQLITE_OMIT_UPSERT
517 if( (pNC
->ncFlags
& NC_UUpsert
)!=0 && zTab
!=0 ){
518 Upsert
*pUpsert
= pNC
->uNC
.pUpsert
;
519 if( pUpsert
&& sqlite3StrICmp("excluded",zTab
)==0 ){
520 pTab
= pUpsert
->pUpsertSrc
->a
[0].pTab
;
521 pExpr
->iTable
= EXCLUDED_TABLE_NUMBER
;
524 #endif /* SQLITE_OMIT_UPSERT */
528 u8 hCol
= sqlite3StrIHash(zCol
);
529 pSchema
= pTab
->pSchema
;
531 for(iCol
=0, pCol
=pTab
->aCol
; iCol
<pTab
->nCol
; iCol
++, pCol
++){
532 if( pCol
->hName
==hCol
533 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
535 if( iCol
==pTab
->iPKey
){
541 if( iCol
>=pTab
->nCol
&& sqlite3IsRowid(zCol
) && VisibleRowid(pTab
) ){
542 /* IMP: R-51414-32910 */
545 if( iCol
<pTab
->nCol
){
548 #ifndef SQLITE_OMIT_UPSERT
549 if( pExpr
->iTable
==EXCLUDED_TABLE_NUMBER
){
550 testcase( iCol
==(-1) );
551 assert( ExprUseYTab(pExpr
) );
552 if( IN_RENAME_OBJECT
){
553 pExpr
->iColumn
= iCol
;
554 pExpr
->y
.pTab
= pTab
;
555 eNewExprOp
= TK_COLUMN
;
557 pExpr
->iTable
= pNC
->uNC
.pUpsert
->regData
+
558 sqlite3TableColumnToStorage(pTab
, iCol
);
559 eNewExprOp
= TK_REGISTER
;
562 #endif /* SQLITE_OMIT_UPSERT */
564 assert( ExprUseYTab(pExpr
) );
565 pExpr
->y
.pTab
= pTab
;
566 if( pParse
->bReturning
){
567 eNewExprOp
= TK_REGISTER
;
568 pExpr
->op2
= TK_COLUMN
;
569 pExpr
->iColumn
= iCol
;
570 pExpr
->iTable
= pNC
->uNC
.iBaseReg
+ (pTab
->nCol
+1)*pExpr
->iTable
+
571 sqlite3TableColumnToStorage(pTab
, iCol
) + 1;
573 pExpr
->iColumn
= (i16
)iCol
;
574 eNewExprOp
= TK_TRIGGER
;
575 #ifndef SQLITE_OMIT_TRIGGER
577 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
578 }else if( pExpr
->iTable
==0 ){
579 testcase( iCol
==31 );
580 testcase( iCol
==32 );
581 pParse
->oldmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
583 testcase( iCol
==31 );
584 testcase( iCol
==32 );
585 pParse
->newmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
587 #endif /* SQLITE_OMIT_TRIGGER */
593 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
596 ** Perhaps the name is a reference to the ROWID
601 && (pNC
->ncFlags
& (NC_IdxExpr
|NC_GenCol
))==0
602 && sqlite3IsRowid(zCol
)
603 && ALWAYS(VisibleRowid(pMatch
->pTab
) || pMatch
->fg
.isNestedFrom
)
606 if( pMatch
->fg
.isNestedFrom
==0 ) pExpr
->iColumn
= -1;
607 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
611 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
612 ** might refer to an result-set alias. This happens, for example, when
613 ** we are resolving names in the WHERE clause of the following command:
615 ** SELECT a+b AS x FROM table WHERE x<10;
617 ** In cases like this, replace pExpr with a copy of the expression that
618 ** forms the result set entry ("a+b" in the example) and return immediately.
619 ** Note that the expression in the result set should have already been
620 ** resolved by the time the WHERE clause is resolved.
622 ** The ability to use an output result-set column in the WHERE, GROUP BY,
623 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
624 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
625 ** is supported for backwards compatibility only. Hence, we issue a warning
626 ** on sqlite3_log() whenever the capability is used.
629 && (pNC
->ncFlags
& NC_UEList
)!=0
632 pEList
= pNC
->uNC
.pEList
;
634 for(j
=0; j
<pEList
->nExpr
; j
++){
635 char *zAs
= pEList
->a
[j
].zEName
;
636 if( pEList
->a
[j
].fg
.eEName
==ENAME_NAME
637 && sqlite3_stricmp(zAs
, zCol
)==0
640 assert( pExpr
->pLeft
==0 && pExpr
->pRight
==0 );
641 assert( ExprUseXList(pExpr
)==0 || pExpr
->x
.pList
==0 );
642 assert( ExprUseXSelect(pExpr
)==0 || pExpr
->x
.pSelect
==0 );
643 pOrig
= pEList
->a
[j
].pExpr
;
644 if( (pNC
->ncFlags
&NC_AllowAgg
)==0 && ExprHasProperty(pOrig
, EP_Agg
) ){
645 sqlite3ErrorMsg(pParse
, "misuse of aliased aggregate %s", zAs
);
648 if( ExprHasProperty(pOrig
, EP_Win
)
649 && ((pNC
->ncFlags
&NC_AllowWin
)==0 || pNC
!=pTopNC
)
651 sqlite3ErrorMsg(pParse
, "misuse of aliased window function %s",zAs
);
654 if( sqlite3ExprVectorSize(pOrig
)!=1 ){
655 sqlite3ErrorMsg(pParse
, "row value misused");
658 resolveAlias(pParse
, pEList
, j
, pExpr
, nSubquery
);
661 assert( zTab
==0 && zDb
==0 );
662 if( IN_RENAME_OBJECT
){
663 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
670 /* Advance to the next name context. The loop will exit when either
671 ** we have a match (cnt>0) or when we run out of name contexts.
680 ** If X and Y are NULL (in other words if only the column name Z is
681 ** supplied) and the value of Z is enclosed in double-quotes, then
682 ** Z is a string literal if it doesn't match any column names. In that
683 ** case, we need to return right away and not make any changes to
686 ** Because no reference was made to outer contexts, the pNC->nRef
687 ** fields are not changed in any context.
689 if( cnt
==0 && zTab
==0 ){
690 assert( pExpr
->op
==TK_ID
);
691 if( ExprHasProperty(pExpr
,EP_DblQuoted
)
692 && areDoubleQuotedStringsEnabled(db
, pTopNC
)
694 /* If a double-quoted identifier does not match any known column name,
695 ** then treat it as a string.
697 ** This hack was added in the early days of SQLite in a misguided attempt
698 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
699 ** I now sorely regret putting in this hack. The effect of this hack is
700 ** that misspelled identifier names are silently converted into strings
701 ** rather than causing an error, to the frustration of countless
702 ** programmers. To all those frustrated programmers, my apologies.
704 ** Someday, I hope to get rid of this hack. Unfortunately there is
705 ** a huge amount of legacy SQL that uses it. So for now, we just
708 sqlite3_log(SQLITE_WARNING
,
709 "double-quoted string literal: \"%w\"", zCol
);
710 #ifdef SQLITE_ENABLE_NORMALIZE
711 sqlite3VdbeAddDblquoteStr(db
, pParse
->pVdbe
, zCol
);
713 pExpr
->op
= TK_STRING
;
714 memset(&pExpr
->y
, 0, sizeof(pExpr
->y
));
717 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
723 ** cnt==0 means there was not match.
724 ** cnt>1 means there were two or more matches.
726 ** cnt==0 is always an error. cnt>1 is often an error, but might
727 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
729 assert( pFJMatch
==0 || cnt
>0 );
730 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
734 if( pFJMatch
->nExpr
==cnt
-1 ){
735 if( ExprHasProperty(pExpr
,EP_Leaf
) ){
736 ExprClearProperty(pExpr
,EP_Leaf
);
738 sqlite3ExprDelete(db
, pExpr
->pLeft
);
740 sqlite3ExprDelete(db
, pExpr
->pRight
);
743 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
744 pExpr
->op
= TK_FUNCTION
;
745 pExpr
->u
.zToken
= "coalesce";
746 pExpr
->x
.pList
= pFJMatch
;
750 sqlite3ExprListDelete(db
, pFJMatch
);
754 zErr
= cnt
==0 ? "no such column" : "ambiguous column name";
756 sqlite3ErrorMsg(pParse
, "%s: %s.%s.%s", zErr
, zDb
, zTab
, zCol
);
758 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zErr
, zTab
, zCol
);
759 }else if( cnt
==0 && ExprHasProperty(pRight
,EP_DblQuoted
) ){
760 sqlite3ErrorMsg(pParse
, "%s: \"%s\" - should this be a"
761 " string literal in single-quotes?",
764 sqlite3ErrorMsg(pParse
, "%s: %s", zErr
, zCol
);
766 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
767 pParse
->checkSchema
= 1;
769 eNewExprOp
= TK_NULL
;
771 assert( pFJMatch
==0 );
773 /* Remove all substructure from pExpr */
774 if( !ExprHasProperty(pExpr
,(EP_TokenOnly
|EP_Leaf
)) ){
775 sqlite3ExprDelete(db
, pExpr
->pLeft
);
777 sqlite3ExprDelete(db
, pExpr
->pRight
);
779 ExprSetProperty(pExpr
, EP_Leaf
);
782 /* If a column from a table in pSrcList is referenced, then record
783 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
784 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
785 ** set if the 63rd or any subsequent column is used.
787 ** The colUsed mask is an optimization used to help determine if an
788 ** index is a covering index. The correct answer is still obtained
789 ** if the mask contains extra set bits. However, it is important to
790 ** avoid setting bits beyond the maximum column number of the table.
791 ** (See ticket [b92e5e8ec2cdbaa1]).
793 ** If a generated column is referenced, set bits for every column
796 if( pExpr
->iColumn
>=0 && cnt
==1 && pMatch
!=0 ){
797 pMatch
->colUsed
|= sqlite3ExprColUsed(pExpr
);
800 pExpr
->op
= eNewExprOp
;
804 #ifndef SQLITE_OMIT_AUTHORIZATION
805 if( pParse
->db
->xAuth
806 && (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_TRIGGER
)
808 sqlite3AuthRead(pParse
, pExpr
, pSchema
, pNC
->pSrcList
);
811 /* Increment the nRef value on all name contexts from TopNC up to
812 ** the point where the name matched. */
816 if( pTopNC
==pNC
) break;
817 pTopNC
= pTopNC
->pNext
;
826 ** Allocate and return a pointer to an expression to load the column iCol
827 ** from datasource iSrc in SrcList pSrc.
829 Expr
*sqlite3CreateColumnExpr(sqlite3
*db
, SrcList
*pSrc
, int iSrc
, int iCol
){
830 Expr
*p
= sqlite3ExprAlloc(db
, TK_COLUMN
, 0, 0);
832 SrcItem
*pItem
= &pSrc
->a
[iSrc
];
834 assert( ExprUseYTab(p
) );
835 pTab
= p
->y
.pTab
= pItem
->pTab
;
836 p
->iTable
= pItem
->iCursor
;
837 if( p
->y
.pTab
->iPKey
==iCol
){
840 p
->iColumn
= (ynVar
)iCol
;
841 if( (pTab
->tabFlags
& TF_HasGenerated
)!=0
842 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_GENERATED
)!=0
844 testcase( pTab
->nCol
==63 );
845 testcase( pTab
->nCol
==64 );
846 pItem
->colUsed
= pTab
->nCol
>=64 ? ALLBITS
: MASKBIT(pTab
->nCol
)-1;
848 testcase( iCol
==BMS
);
849 testcase( iCol
==BMS
-1 );
850 pItem
->colUsed
|= ((Bitmask
)1)<<(iCol
>=BMS
? BMS
-1 : iCol
);
858 ** Report an error that an expression is not valid for some set of
859 ** pNC->ncFlags values determined by validMask.
861 ** static void notValid(
862 ** Parse *pParse, // Leave error message here
863 ** NameContext *pNC, // The name context
864 ** const char *zMsg, // Type of error
865 ** int validMask, // Set of contexts for which prohibited
866 ** Expr *pExpr // Invalidate this expression on error
869 ** As an optimization, since the conditional is almost always false
870 ** (because errors are rare), the conditional is moved outside of the
871 ** function call using a macro.
873 static void notValidImpl(
874 Parse
*pParse
, /* Leave error message here */
875 NameContext
*pNC
, /* The name context */
876 const char *zMsg
, /* Type of error */
877 Expr
*pExpr
, /* Invalidate this expression on error */
878 Expr
*pError
/* Associate error with this expression */
880 const char *zIn
= "partial index WHERE clauses";
881 if( pNC
->ncFlags
& NC_IdxExpr
) zIn
= "index expressions";
882 #ifndef SQLITE_OMIT_CHECK
883 else if( pNC
->ncFlags
& NC_IsCheck
) zIn
= "CHECK constraints";
885 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
886 else if( pNC
->ncFlags
& NC_GenCol
) zIn
= "generated columns";
888 sqlite3ErrorMsg(pParse
, "%s prohibited in %s", zMsg
, zIn
);
889 if( pExpr
) pExpr
->op
= TK_NULL
;
890 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
892 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
893 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
894 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
897 ** Expression p should encode a floating point value between 1.0 and 0.0.
898 ** Return 1024 times this value. Or return -1 if p is not a floating point
899 ** value between 1.0 and 0.0.
901 static int exprProbability(Expr
*p
){
903 if( p
->op
!=TK_FLOAT
) return -1;
904 assert( !ExprHasProperty(p
, EP_IntValue
) );
905 sqlite3AtoF(p
->u
.zToken
, &r
, sqlite3Strlen30(p
->u
.zToken
), SQLITE_UTF8
);
907 if( r
>1.0 ) return -1;
908 return (int)(r
*134217728.0);
912 ** This routine is callback for sqlite3WalkExpr().
914 ** Resolve symbolic names into TK_COLUMN operators for the current
915 ** node in the expression tree. Return 0 to continue the search down
916 ** the tree or 2 to abort the tree walk.
918 ** This routine also does error checking and name resolution for
919 ** function names. The operator for aggregate functions is changed
920 ** to TK_AGG_FUNCTION.
922 static int resolveExprStep(Walker
*pWalker
, Expr
*pExpr
){
926 pNC
= pWalker
->u
.pNC
;
928 pParse
= pNC
->pParse
;
929 assert( pParse
==pWalker
->pParse
);
932 if( pNC
->pSrcList
&& pNC
->pSrcList
->nAlloc
>0 ){
933 SrcList
*pSrcList
= pNC
->pSrcList
;
935 for(i
=0; i
<pNC
->pSrcList
->nSrc
; i
++){
936 assert( pSrcList
->a
[i
].iCursor
>=0 && pSrcList
->a
[i
].iCursor
<pParse
->nTab
);
942 /* The special operator TK_ROW means use the rowid for the first
943 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
944 ** clause processing on UPDATE and DELETE statements, and by
945 ** UPDATE ... FROM statement processing.
948 SrcList
*pSrcList
= pNC
->pSrcList
;
950 assert( pSrcList
&& pSrcList
->nSrc
>=1 );
952 pExpr
->op
= TK_COLUMN
;
953 assert( ExprUseYTab(pExpr
) );
954 pExpr
->y
.pTab
= pItem
->pTab
;
955 pExpr
->iTable
= pItem
->iCursor
;
957 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
961 /* An optimization: Attempt to convert
963 ** "expr IS NOT NULL" --> "TRUE"
964 ** "expr IS NULL" --> "FALSE"
966 ** if we can prove that "expr" is never NULL. Call this the
967 ** "NOT NULL strength reduction optimization".
969 ** If this optimization occurs, also restore the NameContext ref-counts
970 ** to the state they where in before the "column" LHS expression was
971 ** resolved. This prevents "column" from being counted as having been
972 ** referenced, which might prevent a SELECT from being erroneously
973 ** marked as correlated.
980 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
983 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
984 if( 0==sqlite3ExprCanBeNull(pExpr
->pLeft
) && !IN_RENAME_OBJECT
){
985 testcase( ExprHasProperty(pExpr
, EP_OuterON
) );
986 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
987 pExpr
->u
.iValue
= (pExpr
->op
==TK_NOTNULL
);
988 pExpr
->flags
|= EP_IntValue
;
989 pExpr
->op
= TK_INTEGER
;
991 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
994 sqlite3ExprDelete(pParse
->db
, pExpr
->pLeft
);
1000 /* A column name: ID
1001 ** Or table name and column name: ID.ID
1002 ** Or a database, table and column: ID.ID.ID
1004 ** The TK_ID and TK_OUT cases are combined so that there will only
1005 ** be one call to lookupName(). Then the compiler will in-line
1006 ** lookupName() for a size reduction and performance increase.
1014 if( pExpr
->op
==TK_ID
){
1017 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
1020 Expr
*pLeft
= pExpr
->pLeft
;
1021 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1022 testcase( pNC
->ncFlags
& NC_GenCol
);
1023 sqlite3ResolveNotValid(pParse
, pNC
, "the \".\" operator",
1024 NC_IdxExpr
|NC_GenCol
, 0, pExpr
);
1025 pRight
= pExpr
->pRight
;
1026 if( pRight
->op
==TK_ID
){
1029 assert( pRight
->op
==TK_DOT
);
1030 assert( !ExprHasProperty(pRight
, EP_IntValue
) );
1031 zDb
= pLeft
->u
.zToken
;
1032 pLeft
= pRight
->pLeft
;
1033 pRight
= pRight
->pRight
;
1035 assert( ExprUseUToken(pLeft
) && ExprUseUToken(pRight
) );
1036 zTable
= pLeft
->u
.zToken
;
1037 assert( ExprUseYTab(pExpr
) );
1038 if( IN_RENAME_OBJECT
){
1039 sqlite3RenameTokenRemap(pParse
, (void*)pExpr
, (void*)pRight
);
1040 sqlite3RenameTokenRemap(pParse
, (void*)&pExpr
->y
.pTab
, (void*)pLeft
);
1043 return lookupName(pParse
, zDb
, zTable
, pRight
, pNC
, pExpr
);
1046 /* Resolve function names
1049 ExprList
*pList
= pExpr
->x
.pList
; /* The argument list */
1050 int n
= pList
? pList
->nExpr
: 0; /* Number of arguments */
1051 int no_such_func
= 0; /* True if no such function exists */
1052 int wrong_num_args
= 0; /* True if wrong number of arguments */
1053 int is_agg
= 0; /* True if is an aggregate function */
1054 const char *zId
; /* The function name. */
1055 FuncDef
*pDef
; /* Information about the function */
1056 u8 enc
= ENC(pParse
->db
); /* The database encoding */
1057 int savedAllowFlags
= (pNC
->ncFlags
& (NC_AllowAgg
| NC_AllowWin
));
1058 #ifndef SQLITE_OMIT_WINDOWFUNC
1059 Window
*pWin
= (IsWindowFunc(pExpr
) ? pExpr
->y
.pWin
: 0);
1061 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
1062 assert( pExpr
->pLeft
==0 || pExpr
->pLeft
->op
==TK_ORDER
);
1063 zId
= pExpr
->u
.zToken
;
1064 pDef
= sqlite3FindFunction(pParse
->db
, zId
, n
, enc
, 0);
1066 pDef
= sqlite3FindFunction(pParse
->db
, zId
, -2, enc
, 0);
1073 is_agg
= pDef
->xFinalize
!=0;
1074 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
1075 ExprSetProperty(pExpr
, EP_Unlikely
);
1077 pExpr
->iTable
= exprProbability(pList
->a
[1].pExpr
);
1078 if( pExpr
->iTable
<0 ){
1079 sqlite3ErrorMsg(pParse
,
1080 "second argument to %#T() must be a "
1081 "constant between 0.0 and 1.0", pExpr
);
1085 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1086 ** equivalent to likelihood(X, 0.0625).
1087 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1088 ** short-hand for likelihood(X,0.0625).
1089 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1090 ** for likelihood(X,0.9375).
1091 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1092 ** to likelihood(X,0.9375). */
1093 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1094 pExpr
->iTable
= pDef
->zName
[0]=='u' ? 8388608 : 125829120;
1097 #ifndef SQLITE_OMIT_AUTHORIZATION
1099 int auth
= sqlite3AuthCheck(pParse
, SQLITE_FUNCTION
, 0,pDef
->zName
,0);
1100 if( auth
!=SQLITE_OK
){
1101 if( auth
==SQLITE_DENY
){
1102 sqlite3ErrorMsg(pParse
, "not authorized to use function: %#T",
1106 pExpr
->op
= TK_NULL
;
1111 if( pDef
->funcFlags
& (SQLITE_FUNC_CONSTANT
|SQLITE_FUNC_SLOCHNG
) ){
1112 /* For the purposes of the EP_ConstFunc flag, date and time
1113 ** functions and other functions that change slowly are considered
1114 ** constant because they are constant for the duration of one query.
1115 ** This allows them to be factored out of inner loops. */
1116 ExprSetProperty(pExpr
,EP_ConstFunc
);
1118 if( (pDef
->funcFlags
& SQLITE_FUNC_CONSTANT
)==0 ){
1119 /* Clearly non-deterministic functions like random(), but also
1120 ** date/time functions that use 'now', and other functions like
1121 ** sqlite_version() that might change over time cannot be used
1122 ** in an index or generated column. Curiously, they can be used
1123 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1125 sqlite3ResolveNotValid(pParse
, pNC
, "non-deterministic functions",
1126 NC_IdxExpr
|NC_PartIdx
|NC_GenCol
, 0, pExpr
);
1128 assert( (NC_SelfRef
& 0xff)==NC_SelfRef
); /* Must fit in 8 bits */
1129 pExpr
->op2
= pNC
->ncFlags
& NC_SelfRef
;
1130 if( pNC
->ncFlags
& NC_FromDDL
) ExprSetProperty(pExpr
, EP_FromDDL
);
1132 if( (pDef
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
1133 && pParse
->nested
==0
1134 && (pParse
->db
->mDbFlags
& DBFLAG_InternalFunc
)==0
1136 /* Internal-use-only functions are disallowed unless the
1137 ** SQL is being compiled using sqlite3NestedParse() or
1138 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1139 ** used to activate internal functions for testing purposes */
1143 if( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0
1144 && !IN_RENAME_OBJECT
1146 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
1150 if( 0==IN_RENAME_OBJECT
){
1151 #ifndef SQLITE_OMIT_WINDOWFUNC
1152 assert( is_agg
==0 || (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)
1153 || (pDef
->xValue
==0 && pDef
->xInverse
==0)
1154 || (pDef
->xValue
&& pDef
->xInverse
&& pDef
->xSFunc
&& pDef
->xFinalize
)
1156 if( pDef
&& pDef
->xValue
==0 && pWin
){
1157 sqlite3ErrorMsg(pParse
,
1158 "%#T() may not be used as a window function", pExpr
1162 (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0)
1163 || (is_agg
&& (pDef
->funcFlags
&SQLITE_FUNC_WINDOW
) && !pWin
)
1164 || (is_agg
&& pWin
&& (pNC
->ncFlags
& NC_AllowWin
)==0)
1167 if( (pDef
->funcFlags
& SQLITE_FUNC_WINDOW
) || pWin
){
1170 zType
= "aggregate";
1172 sqlite3ErrorMsg(pParse
, "misuse of %s function %#T()",zType
,pExpr
);
1177 if( (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0) ){
1178 sqlite3ErrorMsg(pParse
,"misuse of aggregate function %#T()",pExpr
);
1183 else if( no_such_func
&& pParse
->db
->init
.busy
==0
1184 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1185 && pParse
->explain
==0
1188 sqlite3ErrorMsg(pParse
, "no such function: %#T", pExpr
);
1190 }else if( wrong_num_args
){
1191 sqlite3ErrorMsg(pParse
,"wrong number of arguments to function %#T()",
1195 #ifndef SQLITE_OMIT_WINDOWFUNC
1196 else if( is_agg
==0 && ExprHasProperty(pExpr
, EP_WinFunc
) ){
1197 sqlite3ErrorMsg(pParse
,
1198 "FILTER may not be used with non-aggregate %#T()",
1204 else if( is_agg
==0 && pExpr
->pLeft
){
1205 sqlite3ExprOrderByAggregateError(pParse
, pExpr
);
1209 /* Window functions may not be arguments of aggregate functions.
1210 ** Or arguments of other window functions. But aggregate functions
1211 ** may be arguments for window functions. */
1212 #ifndef SQLITE_OMIT_WINDOWFUNC
1213 pNC
->ncFlags
&= ~(NC_AllowWin
| (!pWin
? NC_AllowAgg
: 0));
1215 pNC
->ncFlags
&= ~NC_AllowAgg
;
1219 #ifndef SQLITE_OMIT_WINDOWFUNC
1220 else if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1224 sqlite3WalkExprList(pWalker
, pList
);
1227 assert( pExpr
->pLeft
->op
==TK_ORDER
);
1228 assert( ExprUseXList(pExpr
->pLeft
) );
1229 sqlite3WalkExprList(pWalker
, pExpr
->pLeft
->x
.pList
);
1231 #ifndef SQLITE_OMIT_WINDOWFUNC
1233 Select
*pSel
= pNC
->pWinSelect
;
1234 assert( pWin
==0 || (ExprUseYWin(pExpr
) && pWin
==pExpr
->y
.pWin
) );
1235 if( IN_RENAME_OBJECT
==0 ){
1236 sqlite3WindowUpdate(pParse
, pSel
? pSel
->pWinDefn
: 0, pWin
, pDef
);
1237 if( pParse
->db
->mallocFailed
) break;
1239 sqlite3WalkExprList(pWalker
, pWin
->pPartition
);
1240 sqlite3WalkExprList(pWalker
, pWin
->pOrderBy
);
1241 sqlite3WalkExpr(pWalker
, pWin
->pFilter
);
1242 sqlite3WindowLink(pSel
, pWin
);
1243 pNC
->ncFlags
|= NC_HasWin
;
1245 #endif /* SQLITE_OMIT_WINDOWFUNC */
1247 NameContext
*pNC2
; /* For looping up thru outer contexts */
1248 pExpr
->op
= TK_AGG_FUNCTION
;
1250 #ifndef SQLITE_OMIT_WINDOWFUNC
1251 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1252 sqlite3WalkExpr(pWalker
, pExpr
->y
.pWin
->pFilter
);
1257 && sqlite3ReferencesSrcList(pParse
, pExpr
, pNC2
->pSrcList
)==0
1259 pExpr
->op2
+= (1 + pNC2
->nNestedSelect
);
1262 assert( pDef
!=0 || IN_RENAME_OBJECT
);
1264 pExpr
->op2
+= pNC2
->nNestedSelect
;
1265 assert( SQLITE_FUNC_MINMAX
==NC_MinMaxAgg
);
1266 assert( SQLITE_FUNC_ANYORDER
==NC_OrderAgg
);
1267 testcase( (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)!=0 );
1268 testcase( (pDef
->funcFlags
& SQLITE_FUNC_ANYORDER
)!=0 );
1269 pNC2
->ncFlags
|= NC_HasAgg
1270 | ((pDef
->funcFlags
^SQLITE_FUNC_ANYORDER
)
1271 & (SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
));
1274 pNC
->ncFlags
|= savedAllowFlags
;
1276 /* FIX ME: Compute pExpr->affinity based on the expected return
1277 ** type of the function
1281 #ifndef SQLITE_OMIT_SUBQUERY
1283 case TK_EXISTS
: testcase( pExpr
->op
==TK_EXISTS
);
1286 testcase( pExpr
->op
==TK_IN
);
1287 if( ExprUseXSelect(pExpr
) ){
1288 int nRef
= pNC
->nRef
;
1289 testcase( pNC
->ncFlags
& NC_IsCheck
);
1290 testcase( pNC
->ncFlags
& NC_PartIdx
);
1291 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1292 testcase( pNC
->ncFlags
& NC_GenCol
);
1293 if( pNC
->ncFlags
& NC_SelfRef
){
1294 notValidImpl(pParse
, pNC
, "subqueries", pExpr
, pExpr
);
1296 sqlite3WalkSelect(pWalker
, pExpr
->x
.pSelect
);
1298 assert( pNC
->nRef
>=nRef
);
1299 if( nRef
!=pNC
->nRef
){
1300 ExprSetProperty(pExpr
, EP_VarSelect
);
1302 pNC
->ncFlags
|= NC_Subquery
;
1307 testcase( pNC
->ncFlags
& NC_IsCheck
);
1308 testcase( pNC
->ncFlags
& NC_PartIdx
);
1309 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1310 testcase( pNC
->ncFlags
& NC_GenCol
);
1311 sqlite3ResolveNotValid(pParse
, pNC
, "parameters",
1312 NC_IsCheck
|NC_PartIdx
|NC_IdxExpr
|NC_GenCol
, pExpr
, pExpr
);
1317 Expr
*pRight
= sqlite3ExprSkipCollateAndLikely(pExpr
->pRight
);
1318 assert( !ExprHasProperty(pExpr
, EP_Reduced
) );
1319 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1320 ** and "x IS NOT FALSE". */
1321 if( ALWAYS(pRight
) && (pRight
->op
==TK_ID
|| pRight
->op
==TK_TRUEFALSE
) ){
1322 int rc
= resolveExprStep(pWalker
, pRight
);
1323 if( rc
==WRC_Abort
) return WRC_Abort
;
1324 if( pRight
->op
==TK_TRUEFALSE
){
1325 pExpr
->op2
= pExpr
->op
;
1326 pExpr
->op
= TK_TRUTH
;
1327 return WRC_Continue
;
1330 /* no break */ deliberate_fall_through
1340 if( pParse
->db
->mallocFailed
) break;
1341 assert( pExpr
->pLeft
!=0 );
1342 nLeft
= sqlite3ExprVectorSize(pExpr
->pLeft
);
1343 if( pExpr
->op
==TK_BETWEEN
){
1344 assert( ExprUseXList(pExpr
) );
1345 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[0].pExpr
);
1346 if( nRight
==nLeft
){
1347 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[1].pExpr
);
1350 assert( pExpr
->pRight
!=0 );
1351 nRight
= sqlite3ExprVectorSize(pExpr
->pRight
);
1353 if( nLeft
!=nRight
){
1354 testcase( pExpr
->op
==TK_EQ
);
1355 testcase( pExpr
->op
==TK_NE
);
1356 testcase( pExpr
->op
==TK_LT
);
1357 testcase( pExpr
->op
==TK_LE
);
1358 testcase( pExpr
->op
==TK_GT
);
1359 testcase( pExpr
->op
==TK_GE
);
1360 testcase( pExpr
->op
==TK_IS
);
1361 testcase( pExpr
->op
==TK_ISNOT
);
1362 testcase( pExpr
->op
==TK_BETWEEN
);
1363 sqlite3ErrorMsg(pParse
, "row value misused");
1364 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1369 assert( pParse
->db
->mallocFailed
==0 || pParse
->nErr
!=0 );
1370 return pParse
->nErr
? WRC_Abort
: WRC_Continue
;
1374 ** pEList is a list of expressions which are really the result set of the
1375 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1376 ** This routine checks to see if pE is a simple identifier which corresponds
1377 ** to the AS-name of one of the terms of the expression list. If it is,
1378 ** this routine return an integer between 1 and N where N is the number of
1379 ** elements in pEList, corresponding to the matching entry. If there is
1380 ** no match, or if pE is not a simple identifier, then this routine
1383 ** pEList has been resolved. pE has not.
1385 static int resolveAsName(
1386 Parse
*pParse
, /* Parsing context for error messages */
1387 ExprList
*pEList
, /* List of expressions to scan */
1388 Expr
*pE
/* Expression we are trying to match */
1390 int i
; /* Loop counter */
1392 UNUSED_PARAMETER(pParse
);
1394 if( pE
->op
==TK_ID
){
1396 assert( !ExprHasProperty(pE
, EP_IntValue
) );
1397 zCol
= pE
->u
.zToken
;
1398 for(i
=0; i
<pEList
->nExpr
; i
++){
1399 if( pEList
->a
[i
].fg
.eEName
==ENAME_NAME
1400 && sqlite3_stricmp(pEList
->a
[i
].zEName
, zCol
)==0
1410 ** pE is a pointer to an expression which is a single term in the
1411 ** ORDER BY of a compound SELECT. The expression has not been
1414 ** At the point this routine is called, we already know that the
1415 ** ORDER BY term is not an integer index into the result set. That
1416 ** case is handled by the calling routine.
1418 ** Attempt to match pE against result set columns in the left-most
1419 ** SELECT statement. Return the index i of the matching column,
1420 ** as an indication to the caller that it should sort by the i-th column.
1421 ** The left-most column is 1. In other words, the value returned is the
1422 ** same integer value that would be used in the SQL statement to indicate
1425 ** If there is no match, return 0. Return -1 if an error occurs.
1427 static int resolveOrderByTermToExprList(
1428 Parse
*pParse
, /* Parsing context for error messages */
1429 Select
*pSelect
, /* The SELECT statement with the ORDER BY clause */
1430 Expr
*pE
/* The specific ORDER BY term */
1432 int i
; /* Loop counter */
1433 ExprList
*pEList
; /* The columns of the result set */
1434 NameContext nc
; /* Name context for resolving pE */
1435 sqlite3
*db
; /* Database connection */
1436 int rc
; /* Return code from subprocedures */
1437 u8 savedSuppErr
; /* Saved value of db->suppressErr */
1439 assert( sqlite3ExprIsInteger(pE
, &i
)==0 );
1440 pEList
= pSelect
->pEList
;
1442 /* Resolve all names in the ORDER BY term expression
1444 memset(&nc
, 0, sizeof(nc
));
1446 nc
.pSrcList
= pSelect
->pSrc
;
1447 nc
.uNC
.pEList
= pEList
;
1448 nc
.ncFlags
= NC_AllowAgg
|NC_UEList
|NC_NoSelect
;
1451 savedSuppErr
= db
->suppressErr
;
1452 db
->suppressErr
= 1;
1453 rc
= sqlite3ResolveExprNames(&nc
, pE
);
1454 db
->suppressErr
= savedSuppErr
;
1457 /* Try to match the ORDER BY expression against an expression
1458 ** in the result set. Return an 1-based index of the matching
1459 ** result-set entry.
1461 for(i
=0; i
<pEList
->nExpr
; i
++){
1462 if( sqlite3ExprCompare(0, pEList
->a
[i
].pExpr
, pE
, -1)<2 ){
1467 /* If no match, return 0. */
1472 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1474 static void resolveOutOfRangeError(
1475 Parse
*pParse
, /* The error context into which to write the error */
1476 const char *zType
, /* "ORDER" or "GROUP" */
1477 int i
, /* The index (1-based) of the term out of range */
1478 int mx
, /* Largest permissible value of i */
1479 Expr
*pError
/* Associate the error with the expression */
1481 sqlite3ErrorMsg(pParse
,
1482 "%r %s BY term out of range - should be "
1483 "between 1 and %d", i
, zType
, mx
);
1484 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
1488 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1489 ** each term of the ORDER BY clause is a constant integer between 1
1490 ** and N where N is the number of columns in the compound SELECT.
1492 ** ORDER BY terms that are already an integer between 1 and N are
1493 ** unmodified. ORDER BY terms that are integers outside the range of
1494 ** 1 through N generate an error. ORDER BY terms that are expressions
1495 ** are matched against result set expressions of compound SELECT
1496 ** beginning with the left-most SELECT and working toward the right.
1497 ** At the first match, the ORDER BY expression is transformed into
1498 ** the integer column number.
1500 ** Return the number of errors seen.
1502 static int resolveCompoundOrderBy(
1503 Parse
*pParse
, /* Parsing context. Leave error messages here */
1504 Select
*pSelect
/* The SELECT statement containing the ORDER BY */
1512 pOrderBy
= pSelect
->pOrderBy
;
1513 if( pOrderBy
==0 ) return 0;
1515 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1516 sqlite3ErrorMsg(pParse
, "too many terms in ORDER BY clause");
1519 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1520 pOrderBy
->a
[i
].fg
.done
= 0;
1523 while( pSelect
->pPrior
){
1524 pSelect
->pPrior
->pNext
= pSelect
;
1525 pSelect
= pSelect
->pPrior
;
1527 while( pSelect
&& moreToDo
){
1528 struct ExprList_item
*pItem
;
1530 pEList
= pSelect
->pEList
;
1531 assert( pEList
!=0 );
1532 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1535 if( pItem
->fg
.done
) continue;
1536 pE
= sqlite3ExprSkipCollateAndLikely(pItem
->pExpr
);
1537 if( NEVER(pE
==0) ) continue;
1538 if( sqlite3ExprIsInteger(pE
, &iCol
) ){
1539 if( iCol
<=0 || iCol
>pEList
->nExpr
){
1540 resolveOutOfRangeError(pParse
, "ORDER", i
+1, pEList
->nExpr
, pE
);
1544 iCol
= resolveAsName(pParse
, pEList
, pE
);
1546 /* Now test if expression pE matches one of the values returned
1547 ** by pSelect. In the usual case this is done by duplicating the
1548 ** expression, resolving any symbols in it, and then comparing
1549 ** it against each expression returned by the SELECT statement.
1550 ** Once the comparisons are finished, the duplicate expression
1553 ** If this is running as part of an ALTER TABLE operation and
1554 ** the symbols resolve successfully, also resolve the symbols in the
1555 ** actual expression. This allows the code in alter.c to modify
1556 ** column references within the ORDER BY expression as required. */
1557 pDup
= sqlite3ExprDup(db
, pE
, 0);
1558 if( !db
->mallocFailed
){
1560 iCol
= resolveOrderByTermToExprList(pParse
, pSelect
, pDup
);
1561 if( IN_RENAME_OBJECT
&& iCol
>0 ){
1562 resolveOrderByTermToExprList(pParse
, pSelect
, pE
);
1565 sqlite3ExprDelete(db
, pDup
);
1569 /* Convert the ORDER BY term into an integer column number iCol,
1570 ** taking care to preserve the COLLATE clause if it exists. */
1571 if( !IN_RENAME_OBJECT
){
1572 Expr
*pNew
= sqlite3Expr(db
, TK_INTEGER
, 0);
1573 if( pNew
==0 ) return 1;
1574 pNew
->flags
|= EP_IntValue
;
1575 pNew
->u
.iValue
= iCol
;
1576 if( pItem
->pExpr
==pE
){
1577 pItem
->pExpr
= pNew
;
1579 Expr
*pParent
= pItem
->pExpr
;
1580 assert( pParent
->op
==TK_COLLATE
);
1581 while( pParent
->pLeft
->op
==TK_COLLATE
) pParent
= pParent
->pLeft
;
1582 assert( pParent
->pLeft
==pE
);
1583 pParent
->pLeft
= pNew
;
1585 sqlite3ExprDelete(db
, pE
);
1586 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1593 pSelect
= pSelect
->pNext
;
1595 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1596 if( pOrderBy
->a
[i
].fg
.done
==0 ){
1597 sqlite3ErrorMsg(pParse
, "%r ORDER BY term does not match any "
1598 "column in the result set", i
+1);
1606 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1607 ** the SELECT statement pSelect. If any term is reference to a
1608 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1609 ** field) then convert that term into a copy of the corresponding result set
1612 ** If any errors are detected, add an error message to pParse and
1613 ** return non-zero. Return zero if no errors are seen.
1615 int sqlite3ResolveOrderGroupBy(
1616 Parse
*pParse
, /* Parsing context. Leave error messages here */
1617 Select
*pSelect
, /* The SELECT statement containing the clause */
1618 ExprList
*pOrderBy
, /* The ORDER BY or GROUP BY clause to be processed */
1619 const char *zType
/* "ORDER" or "GROUP" */
1622 sqlite3
*db
= pParse
->db
;
1624 struct ExprList_item
*pItem
;
1626 if( pOrderBy
==0 || pParse
->db
->mallocFailed
|| IN_RENAME_OBJECT
) return 0;
1627 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1628 sqlite3ErrorMsg(pParse
, "too many terms in %s BY clause", zType
);
1631 pEList
= pSelect
->pEList
;
1632 assert( pEList
!=0 ); /* sqlite3SelectNew() guarantees this */
1633 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1634 if( pItem
->u
.x
.iOrderByCol
){
1635 if( pItem
->u
.x
.iOrderByCol
>pEList
->nExpr
){
1636 resolveOutOfRangeError(pParse
, zType
, i
+1, pEList
->nExpr
, 0);
1639 resolveAlias(pParse
, pEList
, pItem
->u
.x
.iOrderByCol
-1, pItem
->pExpr
,0);
1645 #ifndef SQLITE_OMIT_WINDOWFUNC
1647 ** Walker callback for windowRemoveExprFromSelect().
1649 static int resolveRemoveWindowsCb(Walker
*pWalker
, Expr
*pExpr
){
1650 UNUSED_PARAMETER(pWalker
);
1651 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1652 Window
*pWin
= pExpr
->y
.pWin
;
1653 sqlite3WindowUnlinkFromSelect(pWin
);
1655 return WRC_Continue
;
1659 ** Remove any Window objects owned by the expression pExpr from the
1660 ** Select.pWin list of Select object pSelect.
1662 static void windowRemoveExprFromSelect(Select
*pSelect
, Expr
*pExpr
){
1663 if( pSelect
->pWin
){
1665 memset(&sWalker
, 0, sizeof(Walker
));
1666 sWalker
.xExprCallback
= resolveRemoveWindowsCb
;
1667 sWalker
.u
.pSelect
= pSelect
;
1668 sqlite3WalkExpr(&sWalker
, pExpr
);
1672 # define windowRemoveExprFromSelect(a, b)
1673 #endif /* SQLITE_OMIT_WINDOWFUNC */
1676 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1677 ** The Name context of the SELECT statement is pNC. zType is either
1678 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1680 ** This routine resolves each term of the clause into an expression.
1681 ** If the order-by term is an integer I between 1 and N (where N is the
1682 ** number of columns in the result set of the SELECT) then the expression
1683 ** in the resolution is a copy of the I-th result-set expression. If
1684 ** the order-by term is an identifier that corresponds to the AS-name of
1685 ** a result-set expression, then the term resolves to a copy of the
1686 ** result-set expression. Otherwise, the expression is resolved in
1687 ** the usual way - using sqlite3ResolveExprNames().
1689 ** This routine returns the number of errors. If errors occur, then
1690 ** an appropriate error message might be left in pParse. (OOM errors
1693 static int resolveOrderGroupBy(
1694 NameContext
*pNC
, /* The name context of the SELECT statement */
1695 Select
*pSelect
, /* The SELECT statement holding pOrderBy */
1696 ExprList
*pOrderBy
, /* An ORDER BY or GROUP BY clause to resolve */
1697 const char *zType
/* Either "ORDER" or "GROUP", as appropriate */
1699 int i
, j
; /* Loop counters */
1700 int iCol
; /* Column number */
1701 struct ExprList_item
*pItem
; /* A term of the ORDER BY clause */
1702 Parse
*pParse
; /* Parsing context */
1703 int nResult
; /* Number of terms in the result set */
1705 assert( pOrderBy
!=0 );
1706 nResult
= pSelect
->pEList
->nExpr
;
1707 pParse
= pNC
->pParse
;
1708 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1709 Expr
*pE
= pItem
->pExpr
;
1710 Expr
*pE2
= sqlite3ExprSkipCollateAndLikely(pE
);
1711 if( NEVER(pE2
==0) ) continue;
1712 if( zType
[0]!='G' ){
1713 iCol
= resolveAsName(pParse
, pSelect
->pEList
, pE2
);
1715 /* If an AS-name match is found, mark this ORDER BY column as being
1716 ** a copy of the iCol-th result-set column. The subsequent call to
1717 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1718 ** copy of the iCol-th result-set expression. */
1719 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1723 if( sqlite3ExprIsInteger(pE2
, &iCol
) ){
1724 /* The ORDER BY term is an integer constant. Again, set the column
1725 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1726 ** order-by term to a copy of the result-set expression */
1727 if( iCol
<1 || iCol
>0xffff ){
1728 resolveOutOfRangeError(pParse
, zType
, i
+1, nResult
, pE2
);
1731 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1735 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1736 pItem
->u
.x
.iOrderByCol
= 0;
1737 if( sqlite3ResolveExprNames(pNC
, pE
) ){
1740 for(j
=0; j
<pSelect
->pEList
->nExpr
; j
++){
1741 if( sqlite3ExprCompare(0, pE
, pSelect
->pEList
->a
[j
].pExpr
, -1)==0 ){
1742 /* Since this expression is being changed into a reference
1743 ** to an identical expression in the result set, remove all Window
1744 ** objects belonging to the expression from the Select.pWin list. */
1745 windowRemoveExprFromSelect(pSelect
, pE
);
1746 pItem
->u
.x
.iOrderByCol
= j
+1;
1750 return sqlite3ResolveOrderGroupBy(pParse
, pSelect
, pOrderBy
, zType
);
1754 ** Resolve names in the SELECT statement p and all of its descendants.
1756 static int resolveSelectStep(Walker
*pWalker
, Select
*p
){
1757 NameContext
*pOuterNC
; /* Context that contains this SELECT */
1758 NameContext sNC
; /* Name context of this SELECT */
1759 int isCompound
; /* True if p is a compound select */
1760 int nCompound
; /* Number of compound terms processed so far */
1761 Parse
*pParse
; /* Parsing context */
1762 int i
; /* Loop counter */
1763 ExprList
*pGroupBy
; /* The GROUP BY clause */
1764 Select
*pLeftmost
; /* Left-most of SELECT of a compound */
1765 sqlite3
*db
; /* Database connection */
1769 if( p
->selFlags
& SF_Resolved
){
1772 pOuterNC
= pWalker
->u
.pNC
;
1773 pParse
= pWalker
->pParse
;
1776 /* Normally sqlite3SelectExpand() will be called first and will have
1777 ** already expanded this SELECT. However, if this is a subquery within
1778 ** an expression, sqlite3ResolveExprNames() will be called without a
1779 ** prior call to sqlite3SelectExpand(). When that happens, let
1780 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1781 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1782 ** this routine in the correct order.
1784 if( (p
->selFlags
& SF_Expanded
)==0 ){
1785 sqlite3SelectPrep(pParse
, p
, pOuterNC
);
1786 return pParse
->nErr
? WRC_Abort
: WRC_Prune
;
1789 isCompound
= p
->pPrior
!=0;
1793 assert( (p
->selFlags
& SF_Expanded
)!=0 );
1794 assert( (p
->selFlags
& SF_Resolved
)==0 );
1795 p
->selFlags
|= SF_Resolved
;
1797 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1798 ** are not allowed to refer to any names, so pass an empty NameContext.
1800 memset(&sNC
, 0, sizeof(sNC
));
1801 sNC
.pParse
= pParse
;
1803 if( sqlite3ResolveExprNames(&sNC
, p
->pLimit
) ){
1807 /* If the SF_Converted flags is set, then this Select object was
1808 ** was created by the convertCompoundSelectToSubquery() function.
1809 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1810 ** as if it were part of the sub-query, not the parent. This block
1811 ** moves the pOrderBy down to the sub-query. It will be moved back
1812 ** after the names have been resolved. */
1813 if( p
->selFlags
& SF_Converted
){
1814 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1815 assert( p
->pSrc
->nSrc
==1 && p
->pOrderBy
);
1816 assert( pSub
->pPrior
&& pSub
->pOrderBy
==0 );
1817 pSub
->pOrderBy
= p
->pOrderBy
;
1821 /* Recursively resolve names in all subqueries in the FROM clause
1823 if( pOuterNC
) pOuterNC
->nNestedSelect
++;
1824 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1825 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1826 if( pItem
->pSelect
&& (pItem
->pSelect
->selFlags
& SF_Resolved
)==0 ){
1827 int nRef
= pOuterNC
? pOuterNC
->nRef
: 0;
1828 const char *zSavedContext
= pParse
->zAuthContext
;
1830 if( pItem
->zName
) pParse
->zAuthContext
= pItem
->zName
;
1831 sqlite3ResolveSelectNames(pParse
, pItem
->pSelect
, pOuterNC
);
1832 pParse
->zAuthContext
= zSavedContext
;
1833 if( pParse
->nErr
) return WRC_Abort
;
1834 assert( db
->mallocFailed
==0 );
1836 /* If the number of references to the outer context changed when
1837 ** expressions in the sub-select were resolved, the sub-select
1838 ** is correlated. It is not required to check the refcount on any
1839 ** but the innermost outer context object, as lookupName() increments
1840 ** the refcount on all contexts between the current one and the
1841 ** context containing the column when it resolves a name. */
1843 assert( pItem
->fg
.isCorrelated
==0 && pOuterNC
->nRef
>=nRef
);
1844 pItem
->fg
.isCorrelated
= (pOuterNC
->nRef
>nRef
);
1848 if( pOuterNC
&& ALWAYS(pOuterNC
->nNestedSelect
>0) ){
1849 pOuterNC
->nNestedSelect
--;
1852 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1853 ** resolve the result-set expression list.
1855 sNC
.ncFlags
= NC_AllowAgg
|NC_AllowWin
;
1856 sNC
.pSrcList
= p
->pSrc
;
1857 sNC
.pNext
= pOuterNC
;
1859 /* Resolve names in the result set. */
1860 if( sqlite3ResolveExprListNames(&sNC
, p
->pEList
) ) return WRC_Abort
;
1861 sNC
.ncFlags
&= ~NC_AllowWin
;
1863 /* If there are no aggregate functions in the result-set, and no GROUP BY
1864 ** expression, do not allow aggregates in any of the other expressions.
1866 assert( (p
->selFlags
& SF_Aggregate
)==0 );
1867 pGroupBy
= p
->pGroupBy
;
1868 if( pGroupBy
|| (sNC
.ncFlags
& NC_HasAgg
)!=0 ){
1869 assert( NC_MinMaxAgg
==SF_MinMaxAgg
);
1870 assert( NC_OrderAgg
==SF_OrderByReqd
);
1871 p
->selFlags
|= SF_Aggregate
| (sNC
.ncFlags
&(NC_MinMaxAgg
|NC_OrderAgg
));
1873 sNC
.ncFlags
&= ~NC_AllowAgg
;
1876 /* Add the output column list to the name-context before parsing the
1877 ** other expressions in the SELECT statement. This is so that
1878 ** expressions in the WHERE clause (etc.) can refer to expressions by
1879 ** aliases in the result set.
1881 ** Minor point: If this is the case, then the expression will be
1882 ** re-evaluated for each reference to it.
1884 assert( (sNC
.ncFlags
& (NC_UAggInfo
|NC_UUpsert
|NC_UBaseReg
))==0 );
1885 sNC
.uNC
.pEList
= p
->pEList
;
1886 sNC
.ncFlags
|= NC_UEList
;
1888 if( (p
->selFlags
& SF_Aggregate
)==0 ){
1889 sqlite3ErrorMsg(pParse
, "HAVING clause on a non-aggregate query");
1892 if( sqlite3ResolveExprNames(&sNC
, p
->pHaving
) ) return WRC_Abort
;
1894 if( sqlite3ResolveExprNames(&sNC
, p
->pWhere
) ) return WRC_Abort
;
1896 /* Resolve names in table-valued-function arguments */
1897 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1898 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1899 if( pItem
->fg
.isTabFunc
1900 && sqlite3ResolveExprListNames(&sNC
, pItem
->u1
.pFuncArg
)
1906 #ifndef SQLITE_OMIT_WINDOWFUNC
1907 if( IN_RENAME_OBJECT
){
1909 for(pWin
=p
->pWinDefn
; pWin
; pWin
=pWin
->pNextWin
){
1910 if( sqlite3ResolveExprListNames(&sNC
, pWin
->pOrderBy
)
1911 || sqlite3ResolveExprListNames(&sNC
, pWin
->pPartition
)
1919 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1923 sNC
.ncFlags
|= NC_AllowAgg
|NC_AllowWin
;
1925 /* If this is a converted compound query, move the ORDER BY clause from
1926 ** the sub-query back to the parent query. At this point each term
1927 ** within the ORDER BY clause has been transformed to an integer value.
1928 ** These integers will be replaced by copies of the corresponding result
1929 ** set expressions by the call to resolveOrderGroupBy() below. */
1930 if( p
->selFlags
& SF_Converted
){
1931 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1932 p
->pOrderBy
= pSub
->pOrderBy
;
1936 /* Process the ORDER BY clause for singleton SELECT statements.
1937 ** The ORDER BY clause for compounds SELECT statements is handled
1938 ** below, after all of the result-sets for all of the elements of
1939 ** the compound have been resolved.
1941 ** If there is an ORDER BY clause on a term of a compound-select other
1942 ** than the right-most term, then that is a syntax error. But the error
1943 ** is not detected until much later, and so we need to go ahead and
1944 ** resolve those symbols on the incorrect ORDER BY for consistency.
1947 && isCompound
<=nCompound
/* Defer right-most ORDER BY of a compound */
1948 && resolveOrderGroupBy(&sNC
, p
, p
->pOrderBy
, "ORDER")
1952 if( db
->mallocFailed
){
1955 sNC
.ncFlags
&= ~NC_AllowWin
;
1957 /* Resolve the GROUP BY clause. At the same time, make sure
1958 ** the GROUP BY clause does not contain aggregate functions.
1961 struct ExprList_item
*pItem
;
1963 if( resolveOrderGroupBy(&sNC
, p
, pGroupBy
, "GROUP") || db
->mallocFailed
){
1966 for(i
=0, pItem
=pGroupBy
->a
; i
<pGroupBy
->nExpr
; i
++, pItem
++){
1967 if( ExprHasProperty(pItem
->pExpr
, EP_Agg
) ){
1968 sqlite3ErrorMsg(pParse
, "aggregate functions are not allowed in "
1969 "the GROUP BY clause");
1975 /* If this is part of a compound SELECT, check that it has the right
1976 ** number of expressions in the select list. */
1977 if( p
->pNext
&& p
->pEList
->nExpr
!=p
->pNext
->pEList
->nExpr
){
1978 sqlite3SelectWrongNumTermsError(pParse
, p
->pNext
);
1982 /* Advance to the next term of the compound
1988 /* Resolve the ORDER BY on a compound SELECT after all terms of
1989 ** the compound have been resolved.
1991 if( isCompound
&& resolveCompoundOrderBy(pParse
, pLeftmost
) ){
1999 ** This routine walks an expression tree and resolves references to
2000 ** table columns and result-set columns. At the same time, do error
2001 ** checking on function usage and set a flag if any aggregate functions
2004 ** To resolve table columns references we look for nodes (or subtrees) of the
2005 ** form X.Y.Z or Y.Z or just Z where
2007 ** X: The name of a database. Ex: "main" or "temp" or
2008 ** the symbolic name assigned to an ATTACH-ed database.
2010 ** Y: The name of a table in a FROM clause. Or in a trigger
2011 ** one of the special names "old" or "new".
2013 ** Z: The name of a column in table Y.
2015 ** The node at the root of the subtree is modified as follows:
2017 ** Expr.op Changed to TK_COLUMN
2018 ** Expr.pTab Points to the Table object for X.Y
2019 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
2020 ** Expr.iTable The VDBE cursor number for X.Y
2023 ** To resolve result-set references, look for expression nodes of the
2024 ** form Z (with no X and Y prefix) where the Z matches the right-hand
2025 ** size of an AS clause in the result-set of a SELECT. The Z expression
2026 ** is replaced by a copy of the left-hand side of the result-set expression.
2027 ** Table-name and function resolution occurs on the substituted expression
2028 ** tree. For example, in:
2030 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2032 ** The "x" term of the order by is replaced by "a+b" to render:
2034 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2036 ** Function calls are checked to make sure that the function is
2037 ** defined and that the correct number of arguments are specified.
2038 ** If the function is an aggregate function, then the NC_HasAgg flag is
2039 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2040 ** If an expression contains aggregate functions then the EP_Agg
2041 ** property on the expression is set.
2043 ** An error message is left in pParse if anything is amiss. The number
2044 ** if errors is returned.
2046 int sqlite3ResolveExprNames(
2047 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2048 Expr
*pExpr
/* The expression to be analyzed. */
2053 if( pExpr
==0 ) return SQLITE_OK
;
2054 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2055 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2056 w
.pParse
= pNC
->pParse
;
2057 w
.xExprCallback
= resolveExprStep
;
2058 w
.xSelectCallback
= (pNC
->ncFlags
& NC_NoSelect
) ? 0 : resolveSelectStep
;
2059 w
.xSelectCallback2
= 0;
2061 #if SQLITE_MAX_EXPR_DEPTH>0
2062 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2063 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2064 return SQLITE_ERROR
;
2068 sqlite3WalkExprNN(&w
, pExpr
);
2069 #if SQLITE_MAX_EXPR_DEPTH>0
2070 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2072 assert( EP_Agg
==NC_HasAgg
);
2073 assert( EP_Win
==NC_HasWin
);
2074 testcase( pNC
->ncFlags
& NC_HasAgg
);
2075 testcase( pNC
->ncFlags
& NC_HasWin
);
2076 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2077 pNC
->ncFlags
|= savedHasAgg
;
2078 return pNC
->nNcErr
>0 || w
.pParse
->nErr
>0;
2082 ** Resolve all names for all expression in an expression list. This is
2083 ** just like sqlite3ResolveExprNames() except that it works for an expression
2084 ** list rather than a single expression.
2086 int sqlite3ResolveExprListNames(
2087 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2088 ExprList
*pList
/* The expression list to be analyzed. */
2091 int savedHasAgg
= 0;
2093 if( pList
==0 ) return WRC_Continue
;
2094 w
.pParse
= pNC
->pParse
;
2095 w
.xExprCallback
= resolveExprStep
;
2096 w
.xSelectCallback
= resolveSelectStep
;
2097 w
.xSelectCallback2
= 0;
2099 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2100 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2101 for(i
=0; i
<pList
->nExpr
; i
++){
2102 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2103 if( pExpr
==0 ) continue;
2104 #if SQLITE_MAX_EXPR_DEPTH>0
2105 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2106 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2110 sqlite3WalkExprNN(&w
, pExpr
);
2111 #if SQLITE_MAX_EXPR_DEPTH>0
2112 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2114 assert( EP_Agg
==NC_HasAgg
);
2115 assert( EP_Win
==NC_HasWin
);
2116 testcase( pNC
->ncFlags
& NC_HasAgg
);
2117 testcase( pNC
->ncFlags
& NC_HasWin
);
2118 if( pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
) ){
2119 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2120 savedHasAgg
|= pNC
->ncFlags
&
2121 (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2122 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2124 if( w
.pParse
->nErr
>0 ) return WRC_Abort
;
2126 pNC
->ncFlags
|= savedHasAgg
;
2127 return WRC_Continue
;
2131 ** Resolve all names in all expressions of a SELECT and in all
2132 ** descendants of the SELECT, including compounds off of p->pPrior,
2133 ** subqueries in expressions, and subqueries used as FROM clause
2136 ** See sqlite3ResolveExprNames() for a description of the kinds of
2137 ** transformations that occur.
2139 ** All SELECT statements should have been expanded using
2140 ** sqlite3SelectExpand() prior to invoking this routine.
2142 void sqlite3ResolveSelectNames(
2143 Parse
*pParse
, /* The parser context */
2144 Select
*p
, /* The SELECT statement being coded. */
2145 NameContext
*pOuterNC
/* Name context for parent SELECT statement */
2150 w
.xExprCallback
= resolveExprStep
;
2151 w
.xSelectCallback
= resolveSelectStep
;
2152 w
.xSelectCallback2
= 0;
2155 sqlite3WalkSelect(&w
, p
);
2159 ** Resolve names in expressions that can only reference a single table
2160 ** or which cannot reference any tables at all. Examples:
2164 ** (1) CHECK constraints NC_IsCheck
2165 ** (2) WHERE clauses on partial indices NC_PartIdx
2166 ** (3) Expressions in indexes on expressions NC_IdxExpr
2167 ** (4) Expression arguments to VACUUM INTO. 0
2168 ** (5) GENERATED ALWAYS as expressions NC_GenCol
2170 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2171 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2172 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2174 ** Any errors cause an error message to be set in pParse.
2176 int sqlite3ResolveSelfReference(
2177 Parse
*pParse
, /* Parsing context */
2178 Table
*pTab
, /* The table being referenced, or NULL */
2179 int type
, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2180 Expr
*pExpr
, /* Expression to resolve. May be NULL. */
2181 ExprList
*pList
/* Expression list to resolve. May be NULL. */
2183 SrcList sSrc
; /* Fake SrcList for pParse->pNewTable */
2184 NameContext sNC
; /* Name context for pParse->pNewTable */
2187 assert( type
==0 || pTab
!=0 );
2188 assert( type
==NC_IsCheck
|| type
==NC_PartIdx
|| type
==NC_IdxExpr
2189 || type
==NC_GenCol
|| pTab
==0 );
2190 memset(&sNC
, 0, sizeof(sNC
));
2191 memset(&sSrc
, 0, sizeof(sSrc
));
2194 sSrc
.a
[0].zName
= pTab
->zName
;
2195 sSrc
.a
[0].pTab
= pTab
;
2196 sSrc
.a
[0].iCursor
= -1;
2197 if( pTab
->pSchema
!=pParse
->db
->aDb
[1].pSchema
){
2198 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2199 ** schema elements */
2203 sNC
.pParse
= pParse
;
2204 sNC
.pSrcList
= &sSrc
;
2205 sNC
.ncFlags
= type
| NC_IsDDL
;
2206 if( (rc
= sqlite3ResolveExprNames(&sNC
, pExpr
))!=SQLITE_OK
) return rc
;
2207 if( pList
) rc
= sqlite3ResolveExprListNames(&sNC
, pList
);