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 char *zCol
, /* 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 */
300 assert( pNC
); /* the name context cannot be NULL. */
301 assert( zCol
); /* The Z in X.Y.Z cannot be NULL */
302 assert( zDb
==0 || zTab
!=0 );
303 assert( !ExprHasProperty(pExpr
, EP_TokenOnly
|EP_Reduced
) );
305 /* Initialize the node to no-match */
307 ExprSetVVAProperty(pExpr
, EP_NoReduce
);
309 /* Translate the schema name in zDb into a pointer to the corresponding
310 ** schema. If not found, pSchema will remain NULL and nothing will match
311 ** resulting in an appropriate error message toward the end of this routine
314 testcase( pNC
->ncFlags
& NC_PartIdx
);
315 testcase( pNC
->ncFlags
& NC_IsCheck
);
316 if( (pNC
->ncFlags
& (NC_PartIdx
|NC_IsCheck
))!=0 ){
317 /* Silently ignore database qualifiers inside CHECK constraints and
318 ** partial indices. Do not raise errors because that might break
319 ** legacy and because it does not hurt anything to just ignore the
323 for(i
=0; i
<db
->nDb
; i
++){
324 assert( db
->aDb
[i
].zDbSName
);
325 if( sqlite3StrICmp(db
->aDb
[i
].zDbSName
,zDb
)==0 ){
326 pSchema
= db
->aDb
[i
].pSchema
;
330 if( i
==db
->nDb
&& sqlite3StrICmp("main", zDb
)==0 ){
331 /* This branch is taken when the main database has been renamed
332 ** using SQLITE_DBCONFIG_MAINDBNAME. */
333 pSchema
= db
->aDb
[0].pSchema
;
334 zDb
= db
->aDb
[0].zDbSName
;
339 /* Start at the inner-most context and move outward until a match is found */
340 assert( pNC
&& cnt
==0 );
343 SrcList
*pSrcList
= pNC
->pSrcList
;
346 for(i
=0, pItem
=pSrcList
->a
; i
<pSrcList
->nSrc
; i
++, pItem
++){
349 assert( pTab
!=0 && pTab
->zName
!=0 );
350 assert( pTab
->nCol
>0 || pParse
->nErr
);
351 assert( (int)pItem
->fg
.isNestedFrom
== IsNestedFrom(pItem
->pSelect
) );
352 if( pItem
->fg
.isNestedFrom
){
353 /* In this case, pItem is a subquery that has been formed from a
354 ** parenthesized subset of the FROM clause terms. Example:
355 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
356 ** \_________________________/
357 ** This pItem -------------^
360 assert( pItem
->pSelect
!=0 );
361 pEList
= pItem
->pSelect
->pEList
;
363 assert( pEList
->nExpr
==pTab
->nCol
);
364 for(j
=0; j
<pEList
->nExpr
; j
++){
365 int bRowid
= 0; /* True if possible rowid match */
366 if( !sqlite3MatchEName(&pEList
->a
[j
], zCol
, zTab
, zDb
, &bRowid
) ){
371 if( pItem
->fg
.isUsing
==0
372 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
374 /* Two or more tables have the same column name which is
375 ** not joined by USING. This is an error. Signal as much
376 ** by clearing pFJMatch and letting cnt go above 1. */
377 sqlite3ExprListDelete(db
, pFJMatch
);
380 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
381 /* An INNER or LEFT JOIN. Use the left-most table */
384 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
385 /* A RIGHT JOIN. Use the right-most table */
387 sqlite3ExprListDelete(db
, pFJMatch
);
390 /* For a FULL JOIN, we must construct a coalesce() func */
391 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
397 /* This is a potential rowid match, but there has already been
398 ** a real match found. So this can be ignored. */
404 pEList
->a
[j
].fg
.bUsed
= 1;
406 /* rowid cannot be part of a USING clause - assert() this. */
407 assert( bRowid
==0 || pEList
->a
[j
].fg
.bUsingTerm
==0 );
408 if( pEList
->a
[j
].fg
.bUsingTerm
) break;
410 if( hit
|| zTab
==0 ) continue;
412 assert( zDb
==0 || zTab
!=0 );
415 if( pTab
->pSchema
!=pSchema
) continue;
416 if( pSchema
==0 && strcmp(zDb
,"*")!=0 ) continue;
418 if( pItem
->zAlias
!=0 ){
419 if( sqlite3StrICmp(zTab
, pItem
->zAlias
)!=0 ){
422 }else if( sqlite3StrICmp(zTab
, pTab
->zName
)!=0 ){
423 if( pTab
->tnum
!=1 ) continue;
424 if( !isValidSchemaTableName(zTab
, pTab
, pSchema
) ) continue;
426 assert( ExprUseYTab(pExpr
) );
427 if( IN_RENAME_OBJECT
&& pItem
->zAlias
){
428 sqlite3RenameTokenRemap(pParse
, 0, (void*)&pExpr
->y
.pTab
);
431 hCol
= sqlite3StrIHash(zCol
);
432 for(j
=0, pCol
=pTab
->aCol
; j
<pTab
->nCol
; j
++, pCol
++){
433 if( pCol
->hName
==hCol
434 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
437 if( pItem
->fg
.isUsing
==0
438 || sqlite3IdListIndex(pItem
->u3
.pUsing
, zCol
)<0
440 /* Two or more tables have the same column name which is
441 ** not joined by USING. This is an error. Signal as much
442 ** by clearing pFJMatch and letting cnt go above 1. */
443 sqlite3ExprListDelete(db
, pFJMatch
);
446 if( (pItem
->fg
.jointype
& JT_RIGHT
)==0 ){
447 /* An INNER or LEFT JOIN. Use the left-most table */
450 if( (pItem
->fg
.jointype
& JT_LEFT
)==0 ){
451 /* A RIGHT JOIN. Use the right-most table */
453 sqlite3ExprListDelete(db
, pFJMatch
);
456 /* For a FULL JOIN, we must construct a coalesce() func */
457 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
462 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
463 pExpr
->iColumn
= j
==pTab
->iPKey
? -1 : (i16
)j
;
464 if( pItem
->fg
.isNestedFrom
){
465 sqlite3SrcItemColumnUsed(pItem
, j
);
470 if( 0==cnt
&& VisibleRowid(pTab
) ){
471 /* pTab is a potential ROWID match. Keep track of it and match
472 ** the ROWID later if that seems appropriate. (Search for "cntTab"
473 ** to find related code.) Only allow a ROWID match if there is
474 ** a single ROWID match candidate.
476 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
477 /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match
478 ** if there is a single VIEW candidate or if there is a single
479 ** non-VIEW candidate plus multiple VIEW candidates. In other
480 ** words non-VIEW candidate terms take precedence over VIEWs.
485 && ALWAYS(pMatch
->pTab
!=0)
486 && (pMatch
->pTab
->tabFlags
& TF_Ephemeral
)!=0
487 && (pTab
->tabFlags
& TF_Ephemeral
)==0)
495 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
496 ** simpler since we require exactly one candidate, which will
497 ** always be a non-VIEW
505 pExpr
->iTable
= pMatch
->iCursor
;
506 assert( ExprUseYTab(pExpr
) );
507 pExpr
->y
.pTab
= pMatch
->pTab
;
508 if( (pMatch
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
))!=0 ){
509 ExprSetProperty(pExpr
, EP_CanBeNull
);
511 pSchema
= pExpr
->y
.pTab
->pSchema
;
513 } /* if( pSrcList ) */
515 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
516 /* If we have not already resolved the name, then maybe
517 ** it is a new.* or old.* trigger argument reference. Or
518 ** maybe it is an excluded.* from an upsert. Or maybe it is
519 ** a reference in the RETURNING clause to a table being modified.
521 if( cnt
==0 && zDb
==0 ){
523 #ifndef SQLITE_OMIT_TRIGGER
524 if( pParse
->pTriggerTab
!=0 ){
525 int op
= pParse
->eTriggerOp
;
526 assert( op
==TK_DELETE
|| op
==TK_UPDATE
|| op
==TK_INSERT
);
527 if( pParse
->bReturning
){
528 if( (pNC
->ncFlags
& NC_UBaseReg
)!=0
530 || sqlite3StrICmp(zTab
,pParse
->pTriggerTab
->zName
)==0)
532 pExpr
->iTable
= op
!=TK_DELETE
;
533 pTab
= pParse
->pTriggerTab
;
535 }else if( op
!=TK_DELETE
&& zTab
&& sqlite3StrICmp("new",zTab
) == 0 ){
537 pTab
= pParse
->pTriggerTab
;
538 }else if( op
!=TK_INSERT
&& zTab
&& sqlite3StrICmp("old",zTab
)==0 ){
540 pTab
= pParse
->pTriggerTab
;
543 #endif /* SQLITE_OMIT_TRIGGER */
544 #ifndef SQLITE_OMIT_UPSERT
545 if( (pNC
->ncFlags
& NC_UUpsert
)!=0 && zTab
!=0 ){
546 Upsert
*pUpsert
= pNC
->uNC
.pUpsert
;
547 if( pUpsert
&& sqlite3StrICmp("excluded",zTab
)==0 ){
548 pTab
= pUpsert
->pUpsertSrc
->a
[0].pTab
;
549 pExpr
->iTable
= EXCLUDED_TABLE_NUMBER
;
552 #endif /* SQLITE_OMIT_UPSERT */
556 u8 hCol
= sqlite3StrIHash(zCol
);
557 pSchema
= pTab
->pSchema
;
559 for(iCol
=0, pCol
=pTab
->aCol
; iCol
<pTab
->nCol
; iCol
++, pCol
++){
560 if( pCol
->hName
==hCol
561 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
563 if( iCol
==pTab
->iPKey
){
569 if( iCol
>=pTab
->nCol
&& sqlite3IsRowid(zCol
) && VisibleRowid(pTab
) ){
570 /* IMP: R-51414-32910 */
573 if( iCol
<pTab
->nCol
){
576 #ifndef SQLITE_OMIT_UPSERT
577 if( pExpr
->iTable
==EXCLUDED_TABLE_NUMBER
){
578 testcase( iCol
==(-1) );
579 assert( ExprUseYTab(pExpr
) );
580 if( IN_RENAME_OBJECT
){
581 pExpr
->iColumn
= iCol
;
582 pExpr
->y
.pTab
= pTab
;
583 eNewExprOp
= TK_COLUMN
;
585 pExpr
->iTable
= pNC
->uNC
.pUpsert
->regData
+
586 sqlite3TableColumnToStorage(pTab
, iCol
);
587 eNewExprOp
= TK_REGISTER
;
590 #endif /* SQLITE_OMIT_UPSERT */
592 assert( ExprUseYTab(pExpr
) );
593 pExpr
->y
.pTab
= pTab
;
594 if( pParse
->bReturning
){
595 eNewExprOp
= TK_REGISTER
;
596 pExpr
->op2
= TK_COLUMN
;
597 pExpr
->iColumn
= iCol
;
598 pExpr
->iTable
= pNC
->uNC
.iBaseReg
+ (pTab
->nCol
+1)*pExpr
->iTable
+
599 sqlite3TableColumnToStorage(pTab
, iCol
) + 1;
601 pExpr
->iColumn
= (i16
)iCol
;
602 eNewExprOp
= TK_TRIGGER
;
603 #ifndef SQLITE_OMIT_TRIGGER
605 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
606 }else if( pExpr
->iTable
==0 ){
607 testcase( iCol
==31 );
608 testcase( iCol
==32 );
609 pParse
->oldmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
611 testcase( iCol
==31 );
612 testcase( iCol
==32 );
613 pParse
->newmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
615 #endif /* SQLITE_OMIT_TRIGGER */
621 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
624 ** Perhaps the name is a reference to the ROWID
629 && (pNC
->ncFlags
& (NC_IdxExpr
|NC_GenCol
))==0
630 && sqlite3IsRowid(zCol
)
631 && ALWAYS(VisibleRowid(pMatch
->pTab
) || pMatch
->fg
.isNestedFrom
)
634 if( pMatch
->fg
.isNestedFrom
==0 ) pExpr
->iColumn
= -1;
635 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
639 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
640 ** might refer to an result-set alias. This happens, for example, when
641 ** we are resolving names in the WHERE clause of the following command:
643 ** SELECT a+b AS x FROM table WHERE x<10;
645 ** In cases like this, replace pExpr with a copy of the expression that
646 ** forms the result set entry ("a+b" in the example) and return immediately.
647 ** Note that the expression in the result set should have already been
648 ** resolved by the time the WHERE clause is resolved.
650 ** The ability to use an output result-set column in the WHERE, GROUP BY,
651 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
652 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
653 ** is supported for backwards compatibility only. Hence, we issue a warning
654 ** on sqlite3_log() whenever the capability is used.
657 && (pNC
->ncFlags
& NC_UEList
)!=0
660 pEList
= pNC
->uNC
.pEList
;
662 for(j
=0; j
<pEList
->nExpr
; j
++){
663 char *zAs
= pEList
->a
[j
].zEName
;
664 if( pEList
->a
[j
].fg
.eEName
==ENAME_NAME
665 && sqlite3_stricmp(zAs
, zCol
)==0
668 assert( pExpr
->pLeft
==0 && pExpr
->pRight
==0 );
669 assert( ExprUseXList(pExpr
)==0 || pExpr
->x
.pList
==0 );
670 assert( ExprUseXSelect(pExpr
)==0 || pExpr
->x
.pSelect
==0 );
671 pOrig
= pEList
->a
[j
].pExpr
;
672 if( (pNC
->ncFlags
&NC_AllowAgg
)==0 && ExprHasProperty(pOrig
, EP_Agg
) ){
673 sqlite3ErrorMsg(pParse
, "misuse of aliased aggregate %s", zAs
);
676 if( ExprHasProperty(pOrig
, EP_Win
)
677 && ((pNC
->ncFlags
&NC_AllowWin
)==0 || pNC
!=pTopNC
)
679 sqlite3ErrorMsg(pParse
, "misuse of aliased window function %s",zAs
);
682 if( sqlite3ExprVectorSize(pOrig
)!=1 ){
683 sqlite3ErrorMsg(pParse
, "row value misused");
686 resolveAlias(pParse
, pEList
, j
, pExpr
, nSubquery
);
689 assert( zTab
==0 && zDb
==0 );
690 if( IN_RENAME_OBJECT
){
691 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
698 /* Advance to the next name context. The loop will exit when either
699 ** we have a match (cnt>0) or when we run out of name contexts.
708 ** If X and Y are NULL (in other words if only the column name Z is
709 ** supplied) and the value of Z is enclosed in double-quotes, then
710 ** Z is a string literal if it doesn't match any column names. In that
711 ** case, we need to return right away and not make any changes to
714 ** Because no reference was made to outer contexts, the pNC->nRef
715 ** fields are not changed in any context.
717 if( cnt
==0 && zTab
==0 ){
718 assert( pExpr
->op
==TK_ID
);
719 if( ExprHasProperty(pExpr
,EP_DblQuoted
)
720 && areDoubleQuotedStringsEnabled(db
, pTopNC
)
722 /* If a double-quoted identifier does not match any known column name,
723 ** then treat it as a string.
725 ** This hack was added in the early days of SQLite in a misguided attempt
726 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
727 ** I now sorely regret putting in this hack. The effect of this hack is
728 ** that misspelled identifier names are silently converted into strings
729 ** rather than causing an error, to the frustration of countless
730 ** programmers. To all those frustrated programmers, my apologies.
732 ** Someday, I hope to get rid of this hack. Unfortunately there is
733 ** a huge amount of legacy SQL that uses it. So for now, we just
736 sqlite3_log(SQLITE_WARNING
,
737 "double-quoted string literal: \"%w\"", zCol
);
738 #ifdef SQLITE_ENABLE_NORMALIZE
739 sqlite3VdbeAddDblquoteStr(db
, pParse
->pVdbe
, zCol
);
741 pExpr
->op
= TK_STRING
;
742 memset(&pExpr
->y
, 0, sizeof(pExpr
->y
));
745 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
751 ** cnt==0 means there was not match.
752 ** cnt>1 means there were two or more matches.
754 ** cnt==0 is always an error. cnt>1 is often an error, but might
755 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
757 assert( pFJMatch
==0 || cnt
>0 );
758 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
762 if( pFJMatch
->nExpr
==cnt
-1 ){
763 if( ExprHasProperty(pExpr
,EP_Leaf
) ){
764 ExprClearProperty(pExpr
,EP_Leaf
);
766 sqlite3ExprDelete(db
, pExpr
->pLeft
);
768 sqlite3ExprDelete(db
, pExpr
->pRight
);
771 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
772 pExpr
->op
= TK_FUNCTION
;
773 pExpr
->u
.zToken
= "coalesce";
774 pExpr
->x
.pList
= pFJMatch
;
778 sqlite3ExprListDelete(db
, pFJMatch
);
782 zErr
= cnt
==0 ? "no such column" : "ambiguous column name";
784 sqlite3ErrorMsg(pParse
, "%s: %s.%s.%s", zErr
, zDb
, zTab
, zCol
);
786 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zErr
, zTab
, zCol
);
788 sqlite3ErrorMsg(pParse
, "%s: %s", zErr
, zCol
);
790 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
791 pParse
->checkSchema
= 1;
793 eNewExprOp
= TK_NULL
;
795 assert( pFJMatch
==0 );
797 /* Remove all substructure from pExpr */
798 if( !ExprHasProperty(pExpr
,(EP_TokenOnly
|EP_Leaf
)) ){
799 sqlite3ExprDelete(db
, pExpr
->pLeft
);
801 sqlite3ExprDelete(db
, pExpr
->pRight
);
803 ExprSetProperty(pExpr
, EP_Leaf
);
806 /* If a column from a table in pSrcList is referenced, then record
807 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
808 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
809 ** set if the 63rd or any subsequent column is used.
811 ** The colUsed mask is an optimization used to help determine if an
812 ** index is a covering index. The correct answer is still obtained
813 ** if the mask contains extra set bits. However, it is important to
814 ** avoid setting bits beyond the maximum column number of the table.
815 ** (See ticket [b92e5e8ec2cdbaa1]).
817 ** If a generated column is referenced, set bits for every column
820 if( pExpr
->iColumn
>=0 && cnt
==1 && pMatch
!=0 ){
821 pMatch
->colUsed
|= sqlite3ExprColUsed(pExpr
);
824 pExpr
->op
= eNewExprOp
;
828 #ifndef SQLITE_OMIT_AUTHORIZATION
829 if( pParse
->db
->xAuth
830 && (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_TRIGGER
)
832 sqlite3AuthRead(pParse
, pExpr
, pSchema
, pNC
->pSrcList
);
835 /* Increment the nRef value on all name contexts from TopNC up to
836 ** the point where the name matched. */
840 if( pTopNC
==pNC
) break;
841 pTopNC
= pTopNC
->pNext
;
850 ** Allocate and return a pointer to an expression to load the column iCol
851 ** from datasource iSrc in SrcList pSrc.
853 Expr
*sqlite3CreateColumnExpr(sqlite3
*db
, SrcList
*pSrc
, int iSrc
, int iCol
){
854 Expr
*p
= sqlite3ExprAlloc(db
, TK_COLUMN
, 0, 0);
856 SrcItem
*pItem
= &pSrc
->a
[iSrc
];
858 assert( ExprUseYTab(p
) );
859 pTab
= p
->y
.pTab
= pItem
->pTab
;
860 p
->iTable
= pItem
->iCursor
;
861 if( p
->y
.pTab
->iPKey
==iCol
){
864 p
->iColumn
= (ynVar
)iCol
;
865 if( (pTab
->tabFlags
& TF_HasGenerated
)!=0
866 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_GENERATED
)!=0
868 testcase( pTab
->nCol
==63 );
869 testcase( pTab
->nCol
==64 );
870 pItem
->colUsed
= pTab
->nCol
>=64 ? ALLBITS
: MASKBIT(pTab
->nCol
)-1;
872 testcase( iCol
==BMS
);
873 testcase( iCol
==BMS
-1 );
874 pItem
->colUsed
|= ((Bitmask
)1)<<(iCol
>=BMS
? BMS
-1 : iCol
);
882 ** Report an error that an expression is not valid for some set of
883 ** pNC->ncFlags values determined by validMask.
885 ** static void notValid(
886 ** Parse *pParse, // Leave error message here
887 ** NameContext *pNC, // The name context
888 ** const char *zMsg, // Type of error
889 ** int validMask, // Set of contexts for which prohibited
890 ** Expr *pExpr // Invalidate this expression on error
893 ** As an optimization, since the conditional is almost always false
894 ** (because errors are rare), the conditional is moved outside of the
895 ** function call using a macro.
897 static void notValidImpl(
898 Parse
*pParse
, /* Leave error message here */
899 NameContext
*pNC
, /* The name context */
900 const char *zMsg
, /* Type of error */
901 Expr
*pExpr
, /* Invalidate this expression on error */
902 Expr
*pError
/* Associate error with this expression */
904 const char *zIn
= "partial index WHERE clauses";
905 if( pNC
->ncFlags
& NC_IdxExpr
) zIn
= "index expressions";
906 #ifndef SQLITE_OMIT_CHECK
907 else if( pNC
->ncFlags
& NC_IsCheck
) zIn
= "CHECK constraints";
909 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
910 else if( pNC
->ncFlags
& NC_GenCol
) zIn
= "generated columns";
912 sqlite3ErrorMsg(pParse
, "%s prohibited in %s", zMsg
, zIn
);
913 if( pExpr
) pExpr
->op
= TK_NULL
;
914 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
916 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
917 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
918 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
921 ** Expression p should encode a floating point value between 1.0 and 0.0.
922 ** Return 1024 times this value. Or return -1 if p is not a floating point
923 ** value between 1.0 and 0.0.
925 static int exprProbability(Expr
*p
){
927 if( p
->op
!=TK_FLOAT
) return -1;
928 assert( !ExprHasProperty(p
, EP_IntValue
) );
929 sqlite3AtoF(p
->u
.zToken
, &r
, sqlite3Strlen30(p
->u
.zToken
), SQLITE_UTF8
);
931 if( r
>1.0 ) return -1;
932 return (int)(r
*134217728.0);
936 ** This routine is callback for sqlite3WalkExpr().
938 ** Resolve symbolic names into TK_COLUMN operators for the current
939 ** node in the expression tree. Return 0 to continue the search down
940 ** the tree or 2 to abort the tree walk.
942 ** This routine also does error checking and name resolution for
943 ** function names. The operator for aggregate functions is changed
944 ** to TK_AGG_FUNCTION.
946 static int resolveExprStep(Walker
*pWalker
, Expr
*pExpr
){
950 pNC
= pWalker
->u
.pNC
;
952 pParse
= pNC
->pParse
;
953 assert( pParse
==pWalker
->pParse
);
956 if( pNC
->pSrcList
&& pNC
->pSrcList
->nAlloc
>0 ){
957 SrcList
*pSrcList
= pNC
->pSrcList
;
959 for(i
=0; i
<pNC
->pSrcList
->nSrc
; i
++){
960 assert( pSrcList
->a
[i
].iCursor
>=0 && pSrcList
->a
[i
].iCursor
<pParse
->nTab
);
966 /* The special operator TK_ROW means use the rowid for the first
967 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
968 ** clause processing on UPDATE and DELETE statements, and by
969 ** UPDATE ... FROM statement processing.
972 SrcList
*pSrcList
= pNC
->pSrcList
;
974 assert( pSrcList
&& pSrcList
->nSrc
>=1 );
976 pExpr
->op
= TK_COLUMN
;
977 assert( ExprUseYTab(pExpr
) );
978 pExpr
->y
.pTab
= pItem
->pTab
;
979 pExpr
->iTable
= pItem
->iCursor
;
981 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
985 /* An optimization: Attempt to convert
987 ** "expr IS NOT NULL" --> "TRUE"
988 ** "expr IS NULL" --> "FALSE"
990 ** if we can prove that "expr" is never NULL. Call this the
991 ** "NOT NULL strength reduction optimization".
993 ** If this optimization occurs, also restore the NameContext ref-counts
994 ** to the state they where in before the "column" LHS expression was
995 ** resolved. This prevents "column" from being counted as having been
996 ** referenced, which might prevent a SELECT from being erroneously
997 ** marked as correlated.
999 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
1000 ** can still evaluate to NULL even though it is marked as NOT NULL.
1003 ** CREATE TABLE t1(a INT NOT NULL);
1004 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
1006 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
1007 ** here because at the time this case is hit, we do not yet know whether
1008 ** or not t1 is being aggregated. We have to assume the worst and omit
1009 ** the optimization. The only time it is safe to apply this optimization
1010 ** is within the WHERE clause.
1017 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
1020 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
1021 if( IN_RENAME_OBJECT
) return WRC_Prune
;
1022 if( sqlite3ExprCanBeNull(pExpr
->pLeft
) ){
1023 /* The expression can be NULL. So the optimization does not apply */
1027 for(i
=0, p
=pNC
; p
; p
=p
->pNext
, i
++){
1028 if( (p
->ncFlags
& NC_Where
)==0 ){
1029 return WRC_Prune
; /* Not in a WHERE clause. Unsafe to optimize. */
1032 testcase( ExprHasProperty(pExpr
, EP_OuterON
) );
1033 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
1034 #if TREETRACE_ENABLED
1035 if( sqlite3TreeTrace
& 0x80000 ){
1037 "NOT NULL strength reduction converts the following to %d:\n",
1038 pExpr
->op
==TK_NOTNULL
1040 sqlite3ShowExpr(pExpr
);
1042 #endif /* TREETRACE_ENABLED */
1043 pExpr
->u
.iValue
= (pExpr
->op
==TK_NOTNULL
);
1044 pExpr
->flags
|= EP_IntValue
;
1045 pExpr
->op
= TK_INTEGER
;
1046 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
1049 sqlite3ExprDelete(pParse
->db
, pExpr
->pLeft
);
1054 /* A column name: ID
1055 ** Or table name and column name: ID.ID
1056 ** Or a database, table and column: ID.ID.ID
1058 ** The TK_ID and TK_OUT cases are combined so that there will only
1059 ** be one call to lookupName(). Then the compiler will in-line
1060 ** lookupName() for a size reduction and performance increase.
1064 const char *zColumn
;
1069 if( pExpr
->op
==TK_ID
){
1072 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
1073 zColumn
= pExpr
->u
.zToken
;
1075 Expr
*pLeft
= pExpr
->pLeft
;
1076 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1077 testcase( pNC
->ncFlags
& NC_GenCol
);
1078 sqlite3ResolveNotValid(pParse
, pNC
, "the \".\" operator",
1079 NC_IdxExpr
|NC_GenCol
, 0, pExpr
);
1080 pRight
= pExpr
->pRight
;
1081 if( pRight
->op
==TK_ID
){
1084 assert( pRight
->op
==TK_DOT
);
1085 assert( !ExprHasProperty(pRight
, EP_IntValue
) );
1086 zDb
= pLeft
->u
.zToken
;
1087 pLeft
= pRight
->pLeft
;
1088 pRight
= pRight
->pRight
;
1090 assert( ExprUseUToken(pLeft
) && ExprUseUToken(pRight
) );
1091 zTable
= pLeft
->u
.zToken
;
1092 zColumn
= pRight
->u
.zToken
;
1093 assert( ExprUseYTab(pExpr
) );
1094 if( IN_RENAME_OBJECT
){
1095 sqlite3RenameTokenRemap(pParse
, (void*)pExpr
, (void*)pRight
);
1096 sqlite3RenameTokenRemap(pParse
, (void*)&pExpr
->y
.pTab
, (void*)pLeft
);
1099 return lookupName(pParse
, zDb
, zTable
, zColumn
, pNC
, pExpr
);
1102 /* Resolve function names
1105 ExprList
*pList
= pExpr
->x
.pList
; /* The argument list */
1106 int n
= pList
? pList
->nExpr
: 0; /* Number of arguments */
1107 int no_such_func
= 0; /* True if no such function exists */
1108 int wrong_num_args
= 0; /* True if wrong number of arguments */
1109 int is_agg
= 0; /* True if is an aggregate function */
1110 const char *zId
; /* The function name. */
1111 FuncDef
*pDef
; /* Information about the function */
1112 u8 enc
= ENC(pParse
->db
); /* The database encoding */
1113 int savedAllowFlags
= (pNC
->ncFlags
& (NC_AllowAgg
| NC_AllowWin
));
1114 #ifndef SQLITE_OMIT_WINDOWFUNC
1115 Window
*pWin
= (IsWindowFunc(pExpr
) ? pExpr
->y
.pWin
: 0);
1117 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
1118 assert( pExpr
->pLeft
==0 || pExpr
->pLeft
->op
==TK_ORDER
);
1119 zId
= pExpr
->u
.zToken
;
1120 pDef
= sqlite3FindFunction(pParse
->db
, zId
, n
, enc
, 0);
1122 pDef
= sqlite3FindFunction(pParse
->db
, zId
, -2, enc
, 0);
1129 is_agg
= pDef
->xFinalize
!=0;
1130 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
1131 ExprSetProperty(pExpr
, EP_Unlikely
);
1133 pExpr
->iTable
= exprProbability(pList
->a
[1].pExpr
);
1134 if( pExpr
->iTable
<0 ){
1135 sqlite3ErrorMsg(pParse
,
1136 "second argument to %#T() must be a "
1137 "constant between 0.0 and 1.0", pExpr
);
1141 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1142 ** equivalent to likelihood(X, 0.0625).
1143 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1144 ** short-hand for likelihood(X,0.0625).
1145 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1146 ** for likelihood(X,0.9375).
1147 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1148 ** to likelihood(X,0.9375). */
1149 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1150 pExpr
->iTable
= pDef
->zName
[0]=='u' ? 8388608 : 125829120;
1153 #ifndef SQLITE_OMIT_AUTHORIZATION
1155 int auth
= sqlite3AuthCheck(pParse
, SQLITE_FUNCTION
, 0,pDef
->zName
,0);
1156 if( auth
!=SQLITE_OK
){
1157 if( auth
==SQLITE_DENY
){
1158 sqlite3ErrorMsg(pParse
, "not authorized to use function: %#T",
1162 pExpr
->op
= TK_NULL
;
1167 if( pDef
->funcFlags
& (SQLITE_FUNC_CONSTANT
|SQLITE_FUNC_SLOCHNG
) ){
1168 /* For the purposes of the EP_ConstFunc flag, date and time
1169 ** functions and other functions that change slowly are considered
1170 ** constant because they are constant for the duration of one query.
1171 ** This allows them to be factored out of inner loops. */
1172 ExprSetProperty(pExpr
,EP_ConstFunc
);
1174 if( (pDef
->funcFlags
& SQLITE_FUNC_CONSTANT
)==0 ){
1175 /* Clearly non-deterministic functions like random(), but also
1176 ** date/time functions that use 'now', and other functions like
1177 ** sqlite_version() that might change over time cannot be used
1178 ** in an index or generated column. Curiously, they can be used
1179 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1181 sqlite3ResolveNotValid(pParse
, pNC
, "non-deterministic functions",
1182 NC_IdxExpr
|NC_PartIdx
|NC_GenCol
, 0, pExpr
);
1184 assert( (NC_SelfRef
& 0xff)==NC_SelfRef
); /* Must fit in 8 bits */
1185 pExpr
->op2
= pNC
->ncFlags
& NC_SelfRef
;
1186 if( pNC
->ncFlags
& NC_FromDDL
) ExprSetProperty(pExpr
, EP_FromDDL
);
1188 if( (pDef
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
1189 && pParse
->nested
==0
1190 && (pParse
->db
->mDbFlags
& DBFLAG_InternalFunc
)==0
1192 /* Internal-use-only functions are disallowed unless the
1193 ** SQL is being compiled using sqlite3NestedParse() or
1194 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1195 ** used to activate internal functions for testing purposes */
1199 if( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0
1200 && !IN_RENAME_OBJECT
1202 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
1206 if( 0==IN_RENAME_OBJECT
){
1207 #ifndef SQLITE_OMIT_WINDOWFUNC
1208 assert( is_agg
==0 || (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)
1209 || (pDef
->xValue
==0 && pDef
->xInverse
==0)
1210 || (pDef
->xValue
&& pDef
->xInverse
&& pDef
->xSFunc
&& pDef
->xFinalize
)
1212 if( pDef
&& pDef
->xValue
==0 && pWin
){
1213 sqlite3ErrorMsg(pParse
,
1214 "%#T() may not be used as a window function", pExpr
1218 (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0)
1219 || (is_agg
&& (pDef
->funcFlags
&SQLITE_FUNC_WINDOW
) && !pWin
)
1220 || (is_agg
&& pWin
&& (pNC
->ncFlags
& NC_AllowWin
)==0)
1223 if( (pDef
->funcFlags
& SQLITE_FUNC_WINDOW
) || pWin
){
1226 zType
= "aggregate";
1228 sqlite3ErrorMsg(pParse
, "misuse of %s function %#T()",zType
,pExpr
);
1233 if( (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0) ){
1234 sqlite3ErrorMsg(pParse
,"misuse of aggregate function %#T()",pExpr
);
1239 else if( no_such_func
&& pParse
->db
->init
.busy
==0
1240 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1241 && pParse
->explain
==0
1244 sqlite3ErrorMsg(pParse
, "no such function: %#T", pExpr
);
1246 }else if( wrong_num_args
){
1247 sqlite3ErrorMsg(pParse
,"wrong number of arguments to function %#T()",
1251 #ifndef SQLITE_OMIT_WINDOWFUNC
1252 else if( is_agg
==0 && ExprHasProperty(pExpr
, EP_WinFunc
) ){
1253 sqlite3ErrorMsg(pParse
,
1254 "FILTER may not be used with non-aggregate %#T()",
1260 else if( is_agg
==0 && pExpr
->pLeft
){
1261 sqlite3ExprOrderByAggregateError(pParse
, pExpr
);
1265 /* Window functions may not be arguments of aggregate functions.
1266 ** Or arguments of other window functions. But aggregate functions
1267 ** may be arguments for window functions. */
1268 #ifndef SQLITE_OMIT_WINDOWFUNC
1269 pNC
->ncFlags
&= ~(NC_AllowWin
| (!pWin
? NC_AllowAgg
: 0));
1271 pNC
->ncFlags
&= ~NC_AllowAgg
;
1275 #ifndef SQLITE_OMIT_WINDOWFUNC
1276 else if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1280 sqlite3WalkExprList(pWalker
, pList
);
1283 assert( pExpr
->pLeft
->op
==TK_ORDER
);
1284 assert( ExprUseXList(pExpr
->pLeft
) );
1285 sqlite3WalkExprList(pWalker
, pExpr
->pLeft
->x
.pList
);
1287 #ifndef SQLITE_OMIT_WINDOWFUNC
1289 Select
*pSel
= pNC
->pWinSelect
;
1290 assert( pWin
==0 || (ExprUseYWin(pExpr
) && pWin
==pExpr
->y
.pWin
) );
1291 if( IN_RENAME_OBJECT
==0 ){
1292 sqlite3WindowUpdate(pParse
, pSel
? pSel
->pWinDefn
: 0, pWin
, pDef
);
1293 if( pParse
->db
->mallocFailed
) break;
1295 sqlite3WalkExprList(pWalker
, pWin
->pPartition
);
1296 sqlite3WalkExprList(pWalker
, pWin
->pOrderBy
);
1297 sqlite3WalkExpr(pWalker
, pWin
->pFilter
);
1298 sqlite3WindowLink(pSel
, pWin
);
1299 pNC
->ncFlags
|= NC_HasWin
;
1301 #endif /* SQLITE_OMIT_WINDOWFUNC */
1303 NameContext
*pNC2
; /* For looping up thru outer contexts */
1304 pExpr
->op
= TK_AGG_FUNCTION
;
1306 #ifndef SQLITE_OMIT_WINDOWFUNC
1307 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1308 sqlite3WalkExpr(pWalker
, pExpr
->y
.pWin
->pFilter
);
1313 && sqlite3ReferencesSrcList(pParse
, pExpr
, pNC2
->pSrcList
)==0
1315 pExpr
->op2
+= (1 + pNC2
->nNestedSelect
);
1318 assert( pDef
!=0 || IN_RENAME_OBJECT
);
1320 pExpr
->op2
+= pNC2
->nNestedSelect
;
1321 assert( SQLITE_FUNC_MINMAX
==NC_MinMaxAgg
);
1322 assert( SQLITE_FUNC_ANYORDER
==NC_OrderAgg
);
1323 testcase( (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)!=0 );
1324 testcase( (pDef
->funcFlags
& SQLITE_FUNC_ANYORDER
)!=0 );
1325 pNC2
->ncFlags
|= NC_HasAgg
1326 | ((pDef
->funcFlags
^SQLITE_FUNC_ANYORDER
)
1327 & (SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
));
1330 pNC
->ncFlags
|= savedAllowFlags
;
1332 /* FIX ME: Compute pExpr->affinity based on the expected return
1333 ** type of the function
1337 #ifndef SQLITE_OMIT_SUBQUERY
1339 case TK_EXISTS
: testcase( pExpr
->op
==TK_EXISTS
);
1342 testcase( pExpr
->op
==TK_IN
);
1343 if( ExprUseXSelect(pExpr
) ){
1344 int nRef
= pNC
->nRef
;
1345 testcase( pNC
->ncFlags
& NC_IsCheck
);
1346 testcase( pNC
->ncFlags
& NC_PartIdx
);
1347 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1348 testcase( pNC
->ncFlags
& NC_GenCol
);
1349 if( pNC
->ncFlags
& NC_SelfRef
){
1350 notValidImpl(pParse
, pNC
, "subqueries", pExpr
, pExpr
);
1352 sqlite3WalkSelect(pWalker
, pExpr
->x
.pSelect
);
1354 assert( pNC
->nRef
>=nRef
);
1355 if( nRef
!=pNC
->nRef
){
1356 ExprSetProperty(pExpr
, EP_VarSelect
);
1358 pNC
->ncFlags
|= NC_Subquery
;
1363 testcase( pNC
->ncFlags
& NC_IsCheck
);
1364 testcase( pNC
->ncFlags
& NC_PartIdx
);
1365 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1366 testcase( pNC
->ncFlags
& NC_GenCol
);
1367 sqlite3ResolveNotValid(pParse
, pNC
, "parameters",
1368 NC_IsCheck
|NC_PartIdx
|NC_IdxExpr
|NC_GenCol
, pExpr
, pExpr
);
1373 Expr
*pRight
= sqlite3ExprSkipCollateAndLikely(pExpr
->pRight
);
1374 assert( !ExprHasProperty(pExpr
, EP_Reduced
) );
1375 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1376 ** and "x IS NOT FALSE". */
1377 if( ALWAYS(pRight
) && (pRight
->op
==TK_ID
|| pRight
->op
==TK_TRUEFALSE
) ){
1378 int rc
= resolveExprStep(pWalker
, pRight
);
1379 if( rc
==WRC_Abort
) return WRC_Abort
;
1380 if( pRight
->op
==TK_TRUEFALSE
){
1381 pExpr
->op2
= pExpr
->op
;
1382 pExpr
->op
= TK_TRUTH
;
1383 return WRC_Continue
;
1386 /* no break */ deliberate_fall_through
1396 if( pParse
->db
->mallocFailed
) break;
1397 assert( pExpr
->pLeft
!=0 );
1398 nLeft
= sqlite3ExprVectorSize(pExpr
->pLeft
);
1399 if( pExpr
->op
==TK_BETWEEN
){
1400 assert( ExprUseXList(pExpr
) );
1401 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[0].pExpr
);
1402 if( nRight
==nLeft
){
1403 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[1].pExpr
);
1406 assert( pExpr
->pRight
!=0 );
1407 nRight
= sqlite3ExprVectorSize(pExpr
->pRight
);
1409 if( nLeft
!=nRight
){
1410 testcase( pExpr
->op
==TK_EQ
);
1411 testcase( pExpr
->op
==TK_NE
);
1412 testcase( pExpr
->op
==TK_LT
);
1413 testcase( pExpr
->op
==TK_LE
);
1414 testcase( pExpr
->op
==TK_GT
);
1415 testcase( pExpr
->op
==TK_GE
);
1416 testcase( pExpr
->op
==TK_IS
);
1417 testcase( pExpr
->op
==TK_ISNOT
);
1418 testcase( pExpr
->op
==TK_BETWEEN
);
1419 sqlite3ErrorMsg(pParse
, "row value misused");
1420 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1425 assert( pParse
->db
->mallocFailed
==0 || pParse
->nErr
!=0 );
1426 return pParse
->nErr
? WRC_Abort
: WRC_Continue
;
1430 ** pEList is a list of expressions which are really the result set of the
1431 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1432 ** This routine checks to see if pE is a simple identifier which corresponds
1433 ** to the AS-name of one of the terms of the expression list. If it is,
1434 ** this routine return an integer between 1 and N where N is the number of
1435 ** elements in pEList, corresponding to the matching entry. If there is
1436 ** no match, or if pE is not a simple identifier, then this routine
1439 ** pEList has been resolved. pE has not.
1441 static int resolveAsName(
1442 Parse
*pParse
, /* Parsing context for error messages */
1443 ExprList
*pEList
, /* List of expressions to scan */
1444 Expr
*pE
/* Expression we are trying to match */
1446 int i
; /* Loop counter */
1448 UNUSED_PARAMETER(pParse
);
1450 if( pE
->op
==TK_ID
){
1452 assert( !ExprHasProperty(pE
, EP_IntValue
) );
1453 zCol
= pE
->u
.zToken
;
1454 for(i
=0; i
<pEList
->nExpr
; i
++){
1455 if( pEList
->a
[i
].fg
.eEName
==ENAME_NAME
1456 && sqlite3_stricmp(pEList
->a
[i
].zEName
, zCol
)==0
1466 ** pE is a pointer to an expression which is a single term in the
1467 ** ORDER BY of a compound SELECT. The expression has not been
1470 ** At the point this routine is called, we already know that the
1471 ** ORDER BY term is not an integer index into the result set. That
1472 ** case is handled by the calling routine.
1474 ** Attempt to match pE against result set columns in the left-most
1475 ** SELECT statement. Return the index i of the matching column,
1476 ** as an indication to the caller that it should sort by the i-th column.
1477 ** The left-most column is 1. In other words, the value returned is the
1478 ** same integer value that would be used in the SQL statement to indicate
1481 ** If there is no match, return 0. Return -1 if an error occurs.
1483 static int resolveOrderByTermToExprList(
1484 Parse
*pParse
, /* Parsing context for error messages */
1485 Select
*pSelect
, /* The SELECT statement with the ORDER BY clause */
1486 Expr
*pE
/* The specific ORDER BY term */
1488 int i
; /* Loop counter */
1489 ExprList
*pEList
; /* The columns of the result set */
1490 NameContext nc
; /* Name context for resolving pE */
1491 sqlite3
*db
; /* Database connection */
1492 int rc
; /* Return code from subprocedures */
1493 u8 savedSuppErr
; /* Saved value of db->suppressErr */
1495 assert( sqlite3ExprIsInteger(pE
, &i
)==0 );
1496 pEList
= pSelect
->pEList
;
1498 /* Resolve all names in the ORDER BY term expression
1500 memset(&nc
, 0, sizeof(nc
));
1502 nc
.pSrcList
= pSelect
->pSrc
;
1503 nc
.uNC
.pEList
= pEList
;
1504 nc
.ncFlags
= NC_AllowAgg
|NC_UEList
|NC_NoSelect
;
1507 savedSuppErr
= db
->suppressErr
;
1508 db
->suppressErr
= 1;
1509 rc
= sqlite3ResolveExprNames(&nc
, pE
);
1510 db
->suppressErr
= savedSuppErr
;
1513 /* Try to match the ORDER BY expression against an expression
1514 ** in the result set. Return an 1-based index of the matching
1515 ** result-set entry.
1517 for(i
=0; i
<pEList
->nExpr
; i
++){
1518 if( sqlite3ExprCompare(0, pEList
->a
[i
].pExpr
, pE
, -1)<2 ){
1523 /* If no match, return 0. */
1528 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1530 static void resolveOutOfRangeError(
1531 Parse
*pParse
, /* The error context into which to write the error */
1532 const char *zType
, /* "ORDER" or "GROUP" */
1533 int i
, /* The index (1-based) of the term out of range */
1534 int mx
, /* Largest permissible value of i */
1535 Expr
*pError
/* Associate the error with the expression */
1537 sqlite3ErrorMsg(pParse
,
1538 "%r %s BY term out of range - should be "
1539 "between 1 and %d", i
, zType
, mx
);
1540 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
1544 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1545 ** each term of the ORDER BY clause is a constant integer between 1
1546 ** and N where N is the number of columns in the compound SELECT.
1548 ** ORDER BY terms that are already an integer between 1 and N are
1549 ** unmodified. ORDER BY terms that are integers outside the range of
1550 ** 1 through N generate an error. ORDER BY terms that are expressions
1551 ** are matched against result set expressions of compound SELECT
1552 ** beginning with the left-most SELECT and working toward the right.
1553 ** At the first match, the ORDER BY expression is transformed into
1554 ** the integer column number.
1556 ** Return the number of errors seen.
1558 static int resolveCompoundOrderBy(
1559 Parse
*pParse
, /* Parsing context. Leave error messages here */
1560 Select
*pSelect
/* The SELECT statement containing the ORDER BY */
1568 pOrderBy
= pSelect
->pOrderBy
;
1569 if( pOrderBy
==0 ) return 0;
1571 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1572 sqlite3ErrorMsg(pParse
, "too many terms in ORDER BY clause");
1575 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1576 pOrderBy
->a
[i
].fg
.done
= 0;
1579 while( pSelect
->pPrior
){
1580 pSelect
->pPrior
->pNext
= pSelect
;
1581 pSelect
= pSelect
->pPrior
;
1583 while( pSelect
&& moreToDo
){
1584 struct ExprList_item
*pItem
;
1586 pEList
= pSelect
->pEList
;
1587 assert( pEList
!=0 );
1588 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1591 if( pItem
->fg
.done
) continue;
1592 pE
= sqlite3ExprSkipCollateAndLikely(pItem
->pExpr
);
1593 if( NEVER(pE
==0) ) continue;
1594 if( sqlite3ExprIsInteger(pE
, &iCol
) ){
1595 if( iCol
<=0 || iCol
>pEList
->nExpr
){
1596 resolveOutOfRangeError(pParse
, "ORDER", i
+1, pEList
->nExpr
, pE
);
1600 iCol
= resolveAsName(pParse
, pEList
, pE
);
1602 /* Now test if expression pE matches one of the values returned
1603 ** by pSelect. In the usual case this is done by duplicating the
1604 ** expression, resolving any symbols in it, and then comparing
1605 ** it against each expression returned by the SELECT statement.
1606 ** Once the comparisons are finished, the duplicate expression
1609 ** If this is running as part of an ALTER TABLE operation and
1610 ** the symbols resolve successfully, also resolve the symbols in the
1611 ** actual expression. This allows the code in alter.c to modify
1612 ** column references within the ORDER BY expression as required. */
1613 pDup
= sqlite3ExprDup(db
, pE
, 0);
1614 if( !db
->mallocFailed
){
1616 iCol
= resolveOrderByTermToExprList(pParse
, pSelect
, pDup
);
1617 if( IN_RENAME_OBJECT
&& iCol
>0 ){
1618 resolveOrderByTermToExprList(pParse
, pSelect
, pE
);
1621 sqlite3ExprDelete(db
, pDup
);
1625 /* Convert the ORDER BY term into an integer column number iCol,
1626 ** taking care to preserve the COLLATE clause if it exists. */
1627 if( !IN_RENAME_OBJECT
){
1628 Expr
*pNew
= sqlite3Expr(db
, TK_INTEGER
, 0);
1629 if( pNew
==0 ) return 1;
1630 pNew
->flags
|= EP_IntValue
;
1631 pNew
->u
.iValue
= iCol
;
1632 if( pItem
->pExpr
==pE
){
1633 pItem
->pExpr
= pNew
;
1635 Expr
*pParent
= pItem
->pExpr
;
1636 assert( pParent
->op
==TK_COLLATE
);
1637 while( pParent
->pLeft
->op
==TK_COLLATE
) pParent
= pParent
->pLeft
;
1638 assert( pParent
->pLeft
==pE
);
1639 pParent
->pLeft
= pNew
;
1641 sqlite3ExprDelete(db
, pE
);
1642 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1649 pSelect
= pSelect
->pNext
;
1651 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1652 if( pOrderBy
->a
[i
].fg
.done
==0 ){
1653 sqlite3ErrorMsg(pParse
, "%r ORDER BY term does not match any "
1654 "column in the result set", i
+1);
1662 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1663 ** the SELECT statement pSelect. If any term is reference to a
1664 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1665 ** field) then convert that term into a copy of the corresponding result set
1668 ** If any errors are detected, add an error message to pParse and
1669 ** return non-zero. Return zero if no errors are seen.
1671 int sqlite3ResolveOrderGroupBy(
1672 Parse
*pParse
, /* Parsing context. Leave error messages here */
1673 Select
*pSelect
, /* The SELECT statement containing the clause */
1674 ExprList
*pOrderBy
, /* The ORDER BY or GROUP BY clause to be processed */
1675 const char *zType
/* "ORDER" or "GROUP" */
1678 sqlite3
*db
= pParse
->db
;
1680 struct ExprList_item
*pItem
;
1682 if( pOrderBy
==0 || pParse
->db
->mallocFailed
|| IN_RENAME_OBJECT
) return 0;
1683 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1684 sqlite3ErrorMsg(pParse
, "too many terms in %s BY clause", zType
);
1687 pEList
= pSelect
->pEList
;
1688 assert( pEList
!=0 ); /* sqlite3SelectNew() guarantees this */
1689 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1690 if( pItem
->u
.x
.iOrderByCol
){
1691 if( pItem
->u
.x
.iOrderByCol
>pEList
->nExpr
){
1692 resolveOutOfRangeError(pParse
, zType
, i
+1, pEList
->nExpr
, 0);
1695 resolveAlias(pParse
, pEList
, pItem
->u
.x
.iOrderByCol
-1, pItem
->pExpr
,0);
1701 #ifndef SQLITE_OMIT_WINDOWFUNC
1703 ** Walker callback for windowRemoveExprFromSelect().
1705 static int resolveRemoveWindowsCb(Walker
*pWalker
, Expr
*pExpr
){
1706 UNUSED_PARAMETER(pWalker
);
1707 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1708 Window
*pWin
= pExpr
->y
.pWin
;
1709 sqlite3WindowUnlinkFromSelect(pWin
);
1711 return WRC_Continue
;
1715 ** Remove any Window objects owned by the expression pExpr from the
1716 ** Select.pWin list of Select object pSelect.
1718 static void windowRemoveExprFromSelect(Select
*pSelect
, Expr
*pExpr
){
1719 if( pSelect
->pWin
){
1721 memset(&sWalker
, 0, sizeof(Walker
));
1722 sWalker
.xExprCallback
= resolveRemoveWindowsCb
;
1723 sWalker
.u
.pSelect
= pSelect
;
1724 sqlite3WalkExpr(&sWalker
, pExpr
);
1728 # define windowRemoveExprFromSelect(a, b)
1729 #endif /* SQLITE_OMIT_WINDOWFUNC */
1732 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1733 ** The Name context of the SELECT statement is pNC. zType is either
1734 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1736 ** This routine resolves each term of the clause into an expression.
1737 ** If the order-by term is an integer I between 1 and N (where N is the
1738 ** number of columns in the result set of the SELECT) then the expression
1739 ** in the resolution is a copy of the I-th result-set expression. If
1740 ** the order-by term is an identifier that corresponds to the AS-name of
1741 ** a result-set expression, then the term resolves to a copy of the
1742 ** result-set expression. Otherwise, the expression is resolved in
1743 ** the usual way - using sqlite3ResolveExprNames().
1745 ** This routine returns the number of errors. If errors occur, then
1746 ** an appropriate error message might be left in pParse. (OOM errors
1749 static int resolveOrderGroupBy(
1750 NameContext
*pNC
, /* The name context of the SELECT statement */
1751 Select
*pSelect
, /* The SELECT statement holding pOrderBy */
1752 ExprList
*pOrderBy
, /* An ORDER BY or GROUP BY clause to resolve */
1753 const char *zType
/* Either "ORDER" or "GROUP", as appropriate */
1755 int i
, j
; /* Loop counters */
1756 int iCol
; /* Column number */
1757 struct ExprList_item
*pItem
; /* A term of the ORDER BY clause */
1758 Parse
*pParse
; /* Parsing context */
1759 int nResult
; /* Number of terms in the result set */
1761 assert( pOrderBy
!=0 );
1762 nResult
= pSelect
->pEList
->nExpr
;
1763 pParse
= pNC
->pParse
;
1764 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1765 Expr
*pE
= pItem
->pExpr
;
1766 Expr
*pE2
= sqlite3ExprSkipCollateAndLikely(pE
);
1767 if( NEVER(pE2
==0) ) continue;
1768 if( zType
[0]!='G' ){
1769 iCol
= resolveAsName(pParse
, pSelect
->pEList
, pE2
);
1771 /* If an AS-name match is found, mark this ORDER BY column as being
1772 ** a copy of the iCol-th result-set column. The subsequent call to
1773 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1774 ** copy of the iCol-th result-set expression. */
1775 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1779 if( sqlite3ExprIsInteger(pE2
, &iCol
) ){
1780 /* The ORDER BY term is an integer constant. Again, set the column
1781 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1782 ** order-by term to a copy of the result-set expression */
1783 if( iCol
<1 || iCol
>0xffff ){
1784 resolveOutOfRangeError(pParse
, zType
, i
+1, nResult
, pE2
);
1787 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1791 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1792 pItem
->u
.x
.iOrderByCol
= 0;
1793 if( sqlite3ResolveExprNames(pNC
, pE
) ){
1796 for(j
=0; j
<pSelect
->pEList
->nExpr
; j
++){
1797 if( sqlite3ExprCompare(0, pE
, pSelect
->pEList
->a
[j
].pExpr
, -1)==0 ){
1798 /* Since this expression is being changed into a reference
1799 ** to an identical expression in the result set, remove all Window
1800 ** objects belonging to the expression from the Select.pWin list. */
1801 windowRemoveExprFromSelect(pSelect
, pE
);
1802 pItem
->u
.x
.iOrderByCol
= j
+1;
1806 return sqlite3ResolveOrderGroupBy(pParse
, pSelect
, pOrderBy
, zType
);
1810 ** Resolve names in the SELECT statement p and all of its descendants.
1812 static int resolveSelectStep(Walker
*pWalker
, Select
*p
){
1813 NameContext
*pOuterNC
; /* Context that contains this SELECT */
1814 NameContext sNC
; /* Name context of this SELECT */
1815 int isCompound
; /* True if p is a compound select */
1816 int nCompound
; /* Number of compound terms processed so far */
1817 Parse
*pParse
; /* Parsing context */
1818 int i
; /* Loop counter */
1819 ExprList
*pGroupBy
; /* The GROUP BY clause */
1820 Select
*pLeftmost
; /* Left-most of SELECT of a compound */
1821 sqlite3
*db
; /* Database connection */
1825 if( p
->selFlags
& SF_Resolved
){
1828 pOuterNC
= pWalker
->u
.pNC
;
1829 pParse
= pWalker
->pParse
;
1832 /* Normally sqlite3SelectExpand() will be called first and will have
1833 ** already expanded this SELECT. However, if this is a subquery within
1834 ** an expression, sqlite3ResolveExprNames() will be called without a
1835 ** prior call to sqlite3SelectExpand(). When that happens, let
1836 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1837 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1838 ** this routine in the correct order.
1840 if( (p
->selFlags
& SF_Expanded
)==0 ){
1841 sqlite3SelectPrep(pParse
, p
, pOuterNC
);
1842 return pParse
->nErr
? WRC_Abort
: WRC_Prune
;
1845 isCompound
= p
->pPrior
!=0;
1849 assert( (p
->selFlags
& SF_Expanded
)!=0 );
1850 assert( (p
->selFlags
& SF_Resolved
)==0 );
1851 p
->selFlags
|= SF_Resolved
;
1853 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1854 ** are not allowed to refer to any names, so pass an empty NameContext.
1856 memset(&sNC
, 0, sizeof(sNC
));
1857 sNC
.pParse
= pParse
;
1859 if( sqlite3ResolveExprNames(&sNC
, p
->pLimit
) ){
1863 /* If the SF_Converted flags is set, then this Select object was
1864 ** was created by the convertCompoundSelectToSubquery() function.
1865 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1866 ** as if it were part of the sub-query, not the parent. This block
1867 ** moves the pOrderBy down to the sub-query. It will be moved back
1868 ** after the names have been resolved. */
1869 if( p
->selFlags
& SF_Converted
){
1870 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1871 assert( p
->pSrc
->nSrc
==1 && p
->pOrderBy
);
1872 assert( pSub
->pPrior
&& pSub
->pOrderBy
==0 );
1873 pSub
->pOrderBy
= p
->pOrderBy
;
1877 /* Recursively resolve names in all subqueries in the FROM clause
1879 if( pOuterNC
) pOuterNC
->nNestedSelect
++;
1880 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1881 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1882 if( pItem
->pSelect
&& (pItem
->pSelect
->selFlags
& SF_Resolved
)==0 ){
1883 int nRef
= pOuterNC
? pOuterNC
->nRef
: 0;
1884 const char *zSavedContext
= pParse
->zAuthContext
;
1886 if( pItem
->zName
) pParse
->zAuthContext
= pItem
->zName
;
1887 sqlite3ResolveSelectNames(pParse
, pItem
->pSelect
, pOuterNC
);
1888 pParse
->zAuthContext
= zSavedContext
;
1889 if( pParse
->nErr
) return WRC_Abort
;
1890 assert( db
->mallocFailed
==0 );
1892 /* If the number of references to the outer context changed when
1893 ** expressions in the sub-select were resolved, the sub-select
1894 ** is correlated. It is not required to check the refcount on any
1895 ** but the innermost outer context object, as lookupName() increments
1896 ** the refcount on all contexts between the current one and the
1897 ** context containing the column when it resolves a name. */
1899 assert( pItem
->fg
.isCorrelated
==0 && pOuterNC
->nRef
>=nRef
);
1900 pItem
->fg
.isCorrelated
= (pOuterNC
->nRef
>nRef
);
1904 if( pOuterNC
&& ALWAYS(pOuterNC
->nNestedSelect
>0) ){
1905 pOuterNC
->nNestedSelect
--;
1908 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1909 ** resolve the result-set expression list.
1911 sNC
.ncFlags
= NC_AllowAgg
|NC_AllowWin
;
1912 sNC
.pSrcList
= p
->pSrc
;
1913 sNC
.pNext
= pOuterNC
;
1915 /* Resolve names in the result set. */
1916 if( sqlite3ResolveExprListNames(&sNC
, p
->pEList
) ) return WRC_Abort
;
1917 sNC
.ncFlags
&= ~NC_AllowWin
;
1919 /* If there are no aggregate functions in the result-set, and no GROUP BY
1920 ** expression, do not allow aggregates in any of the other expressions.
1922 assert( (p
->selFlags
& SF_Aggregate
)==0 );
1923 pGroupBy
= p
->pGroupBy
;
1924 if( pGroupBy
|| (sNC
.ncFlags
& NC_HasAgg
)!=0 ){
1925 assert( NC_MinMaxAgg
==SF_MinMaxAgg
);
1926 assert( NC_OrderAgg
==SF_OrderByReqd
);
1927 p
->selFlags
|= SF_Aggregate
| (sNC
.ncFlags
&(NC_MinMaxAgg
|NC_OrderAgg
));
1929 sNC
.ncFlags
&= ~NC_AllowAgg
;
1932 /* Add the output column list to the name-context before parsing the
1933 ** other expressions in the SELECT statement. This is so that
1934 ** expressions in the WHERE clause (etc.) can refer to expressions by
1935 ** aliases in the result set.
1937 ** Minor point: If this is the case, then the expression will be
1938 ** re-evaluated for each reference to it.
1940 assert( (sNC
.ncFlags
& (NC_UAggInfo
|NC_UUpsert
|NC_UBaseReg
))==0 );
1941 sNC
.uNC
.pEList
= p
->pEList
;
1942 sNC
.ncFlags
|= NC_UEList
;
1944 if( (p
->selFlags
& SF_Aggregate
)==0 ){
1945 sqlite3ErrorMsg(pParse
, "HAVING clause on a non-aggregate query");
1948 if( sqlite3ResolveExprNames(&sNC
, p
->pHaving
) ) return WRC_Abort
;
1950 sNC
.ncFlags
|= NC_Where
;
1951 if( sqlite3ResolveExprNames(&sNC
, p
->pWhere
) ) return WRC_Abort
;
1952 sNC
.ncFlags
&= ~NC_Where
;
1954 /* Resolve names in table-valued-function arguments */
1955 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1956 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1957 if( pItem
->fg
.isTabFunc
1958 && sqlite3ResolveExprListNames(&sNC
, pItem
->u1
.pFuncArg
)
1964 #ifndef SQLITE_OMIT_WINDOWFUNC
1965 if( IN_RENAME_OBJECT
){
1967 for(pWin
=p
->pWinDefn
; pWin
; pWin
=pWin
->pNextWin
){
1968 if( sqlite3ResolveExprListNames(&sNC
, pWin
->pOrderBy
)
1969 || sqlite3ResolveExprListNames(&sNC
, pWin
->pPartition
)
1977 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1981 sNC
.ncFlags
|= NC_AllowAgg
|NC_AllowWin
;
1983 /* If this is a converted compound query, move the ORDER BY clause from
1984 ** the sub-query back to the parent query. At this point each term
1985 ** within the ORDER BY clause has been transformed to an integer value.
1986 ** These integers will be replaced by copies of the corresponding result
1987 ** set expressions by the call to resolveOrderGroupBy() below. */
1988 if( p
->selFlags
& SF_Converted
){
1989 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1990 p
->pOrderBy
= pSub
->pOrderBy
;
1994 /* Process the ORDER BY clause for singleton SELECT statements.
1995 ** The ORDER BY clause for compounds SELECT statements is handled
1996 ** below, after all of the result-sets for all of the elements of
1997 ** the compound have been resolved.
1999 ** If there is an ORDER BY clause on a term of a compound-select other
2000 ** than the right-most term, then that is a syntax error. But the error
2001 ** is not detected until much later, and so we need to go ahead and
2002 ** resolve those symbols on the incorrect ORDER BY for consistency.
2005 && isCompound
<=nCompound
/* Defer right-most ORDER BY of a compound */
2006 && resolveOrderGroupBy(&sNC
, p
, p
->pOrderBy
, "ORDER")
2010 if( db
->mallocFailed
){
2013 sNC
.ncFlags
&= ~NC_AllowWin
;
2015 /* Resolve the GROUP BY clause. At the same time, make sure
2016 ** the GROUP BY clause does not contain aggregate functions.
2019 struct ExprList_item
*pItem
;
2021 if( resolveOrderGroupBy(&sNC
, p
, pGroupBy
, "GROUP") || db
->mallocFailed
){
2024 for(i
=0, pItem
=pGroupBy
->a
; i
<pGroupBy
->nExpr
; i
++, pItem
++){
2025 if( ExprHasProperty(pItem
->pExpr
, EP_Agg
) ){
2026 sqlite3ErrorMsg(pParse
, "aggregate functions are not allowed in "
2027 "the GROUP BY clause");
2033 /* If this is part of a compound SELECT, check that it has the right
2034 ** number of expressions in the select list. */
2035 if( p
->pNext
&& p
->pEList
->nExpr
!=p
->pNext
->pEList
->nExpr
){
2036 sqlite3SelectWrongNumTermsError(pParse
, p
->pNext
);
2040 /* Advance to the next term of the compound
2046 /* Resolve the ORDER BY on a compound SELECT after all terms of
2047 ** the compound have been resolved.
2049 if( isCompound
&& resolveCompoundOrderBy(pParse
, pLeftmost
) ){
2057 ** This routine walks an expression tree and resolves references to
2058 ** table columns and result-set columns. At the same time, do error
2059 ** checking on function usage and set a flag if any aggregate functions
2062 ** To resolve table columns references we look for nodes (or subtrees) of the
2063 ** form X.Y.Z or Y.Z or just Z where
2065 ** X: The name of a database. Ex: "main" or "temp" or
2066 ** the symbolic name assigned to an ATTACH-ed database.
2068 ** Y: The name of a table in a FROM clause. Or in a trigger
2069 ** one of the special names "old" or "new".
2071 ** Z: The name of a column in table Y.
2073 ** The node at the root of the subtree is modified as follows:
2075 ** Expr.op Changed to TK_COLUMN
2076 ** Expr.pTab Points to the Table object for X.Y
2077 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
2078 ** Expr.iTable The VDBE cursor number for X.Y
2081 ** To resolve result-set references, look for expression nodes of the
2082 ** form Z (with no X and Y prefix) where the Z matches the right-hand
2083 ** size of an AS clause in the result-set of a SELECT. The Z expression
2084 ** is replaced by a copy of the left-hand side of the result-set expression.
2085 ** Table-name and function resolution occurs on the substituted expression
2086 ** tree. For example, in:
2088 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2090 ** The "x" term of the order by is replaced by "a+b" to render:
2092 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2094 ** Function calls are checked to make sure that the function is
2095 ** defined and that the correct number of arguments are specified.
2096 ** If the function is an aggregate function, then the NC_HasAgg flag is
2097 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2098 ** If an expression contains aggregate functions then the EP_Agg
2099 ** property on the expression is set.
2101 ** An error message is left in pParse if anything is amiss. The number
2102 ** if errors is returned.
2104 int sqlite3ResolveExprNames(
2105 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2106 Expr
*pExpr
/* The expression to be analyzed. */
2111 if( pExpr
==0 ) return SQLITE_OK
;
2112 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2113 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2114 w
.pParse
= pNC
->pParse
;
2115 w
.xExprCallback
= resolveExprStep
;
2116 w
.xSelectCallback
= (pNC
->ncFlags
& NC_NoSelect
) ? 0 : resolveSelectStep
;
2117 w
.xSelectCallback2
= 0;
2119 #if SQLITE_MAX_EXPR_DEPTH>0
2120 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2121 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2122 return SQLITE_ERROR
;
2126 sqlite3WalkExprNN(&w
, pExpr
);
2127 #if SQLITE_MAX_EXPR_DEPTH>0
2128 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2130 assert( EP_Agg
==NC_HasAgg
);
2131 assert( EP_Win
==NC_HasWin
);
2132 testcase( pNC
->ncFlags
& NC_HasAgg
);
2133 testcase( pNC
->ncFlags
& NC_HasWin
);
2134 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2135 pNC
->ncFlags
|= savedHasAgg
;
2136 return pNC
->nNcErr
>0 || w
.pParse
->nErr
>0;
2140 ** Resolve all names for all expression in an expression list. This is
2141 ** just like sqlite3ResolveExprNames() except that it works for an expression
2142 ** list rather than a single expression.
2144 int sqlite3ResolveExprListNames(
2145 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2146 ExprList
*pList
/* The expression list to be analyzed. */
2149 int savedHasAgg
= 0;
2151 if( pList
==0 ) return WRC_Continue
;
2152 w
.pParse
= pNC
->pParse
;
2153 w
.xExprCallback
= resolveExprStep
;
2154 w
.xSelectCallback
= resolveSelectStep
;
2155 w
.xSelectCallback2
= 0;
2157 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2158 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2159 for(i
=0; i
<pList
->nExpr
; i
++){
2160 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2161 if( pExpr
==0 ) continue;
2162 #if SQLITE_MAX_EXPR_DEPTH>0
2163 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2164 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2168 sqlite3WalkExprNN(&w
, pExpr
);
2169 #if SQLITE_MAX_EXPR_DEPTH>0
2170 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2172 assert( EP_Agg
==NC_HasAgg
);
2173 assert( EP_Win
==NC_HasWin
);
2174 testcase( pNC
->ncFlags
& NC_HasAgg
);
2175 testcase( pNC
->ncFlags
& NC_HasWin
);
2176 if( pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
) ){
2177 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2178 savedHasAgg
|= pNC
->ncFlags
&
2179 (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2180 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2182 if( w
.pParse
->nErr
>0 ) return WRC_Abort
;
2184 pNC
->ncFlags
|= savedHasAgg
;
2185 return WRC_Continue
;
2189 ** Resolve all names in all expressions of a SELECT and in all
2190 ** descendants of the SELECT, including compounds off of p->pPrior,
2191 ** subqueries in expressions, and subqueries used as FROM clause
2194 ** See sqlite3ResolveExprNames() for a description of the kinds of
2195 ** transformations that occur.
2197 ** All SELECT statements should have been expanded using
2198 ** sqlite3SelectExpand() prior to invoking this routine.
2200 void sqlite3ResolveSelectNames(
2201 Parse
*pParse
, /* The parser context */
2202 Select
*p
, /* The SELECT statement being coded. */
2203 NameContext
*pOuterNC
/* Name context for parent SELECT statement */
2208 w
.xExprCallback
= resolveExprStep
;
2209 w
.xSelectCallback
= resolveSelectStep
;
2210 w
.xSelectCallback2
= 0;
2213 sqlite3WalkSelect(&w
, p
);
2217 ** Resolve names in expressions that can only reference a single table
2218 ** or which cannot reference any tables at all. Examples:
2222 ** (1) CHECK constraints NC_IsCheck
2223 ** (2) WHERE clauses on partial indices NC_PartIdx
2224 ** (3) Expressions in indexes on expressions NC_IdxExpr
2225 ** (4) Expression arguments to VACUUM INTO. 0
2226 ** (5) GENERATED ALWAYS as expressions NC_GenCol
2228 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2229 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2230 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2232 ** Any errors cause an error message to be set in pParse.
2234 int sqlite3ResolveSelfReference(
2235 Parse
*pParse
, /* Parsing context */
2236 Table
*pTab
, /* The table being referenced, or NULL */
2237 int type
, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2238 Expr
*pExpr
, /* Expression to resolve. May be NULL. */
2239 ExprList
*pList
/* Expression list to resolve. May be NULL. */
2241 SrcList sSrc
; /* Fake SrcList for pParse->pNewTable */
2242 NameContext sNC
; /* Name context for pParse->pNewTable */
2245 assert( type
==0 || pTab
!=0 );
2246 assert( type
==NC_IsCheck
|| type
==NC_PartIdx
|| type
==NC_IdxExpr
2247 || type
==NC_GenCol
|| pTab
==0 );
2248 memset(&sNC
, 0, sizeof(sNC
));
2249 memset(&sSrc
, 0, sizeof(sSrc
));
2252 sSrc
.a
[0].zName
= pTab
->zName
;
2253 sSrc
.a
[0].pTab
= pTab
;
2254 sSrc
.a
[0].iCursor
= -1;
2255 if( pTab
->pSchema
!=pParse
->db
->aDb
[1].pSchema
){
2256 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2257 ** schema elements */
2261 sNC
.pParse
= pParse
;
2262 sNC
.pSrcList
= &sSrc
;
2263 sNC
.ncFlags
= type
| NC_IsDDL
;
2264 if( (rc
= sqlite3ResolveExprNames(&sNC
, pExpr
))!=SQLITE_OK
) return rc
;
2265 if( pList
) rc
= sqlite3ResolveExprListNames(&sNC
, pList
);