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 const char *zDb
/* 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( zDb
==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
, zDb
) ) 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
) ){
472 /* pTab is a potential ROWID match. Keep track of it and match
473 ** the ROWID later if that seems appropriate. (Search for "cntTab"
474 ** to find related code.) Only allow a ROWID match if there is
475 ** a single ROWID match candidate.
477 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
478 /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match
479 ** if there is a single VIEW candidate or if there is a single
480 ** non-VIEW candidate plus multiple VIEW candidates. In other
481 ** words non-VIEW candidate terms take precedence over VIEWs.
486 && ALWAYS(pMatch
->pTab
!=0)
487 && (pMatch
->pTab
->tabFlags
& TF_Ephemeral
)!=0
488 && (pTab
->tabFlags
& TF_Ephemeral
)==0)
496 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
497 ** simpler since we require exactly one candidate, which will
498 ** always be a non-VIEW
506 pExpr
->iTable
= pMatch
->iCursor
;
507 assert( ExprUseYTab(pExpr
) );
508 pExpr
->y
.pTab
= pMatch
->pTab
;
509 if( (pMatch
->fg
.jointype
& (JT_LEFT
|JT_LTORJ
))!=0 ){
510 ExprSetProperty(pExpr
, EP_CanBeNull
);
512 pSchema
= pExpr
->y
.pTab
->pSchema
;
514 } /* if( pSrcList ) */
516 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
517 /* If we have not already resolved the name, then maybe
518 ** it is a new.* or old.* trigger argument reference. Or
519 ** maybe it is an excluded.* from an upsert. Or maybe it is
520 ** a reference in the RETURNING clause to a table being modified.
522 if( cnt
==0 && zDb
==0 ){
524 #ifndef SQLITE_OMIT_TRIGGER
525 if( pParse
->pTriggerTab
!=0 ){
526 int op
= pParse
->eTriggerOp
;
527 assert( op
==TK_DELETE
|| op
==TK_UPDATE
|| op
==TK_INSERT
);
528 if( pParse
->bReturning
){
529 if( (pNC
->ncFlags
& NC_UBaseReg
)!=0
531 || sqlite3StrICmp(zTab
,pParse
->pTriggerTab
->zName
)==0
532 || isValidSchemaTableName(zTab
, pParse
->pTriggerTab
, 0))
534 pExpr
->iTable
= op
!=TK_DELETE
;
535 pTab
= pParse
->pTriggerTab
;
537 }else if( op
!=TK_DELETE
&& zTab
&& sqlite3StrICmp("new",zTab
) == 0 ){
539 pTab
= pParse
->pTriggerTab
;
540 }else if( op
!=TK_INSERT
&& zTab
&& sqlite3StrICmp("old",zTab
)==0 ){
542 pTab
= pParse
->pTriggerTab
;
545 #endif /* SQLITE_OMIT_TRIGGER */
546 #ifndef SQLITE_OMIT_UPSERT
547 if( (pNC
->ncFlags
& NC_UUpsert
)!=0 && zTab
!=0 ){
548 Upsert
*pUpsert
= pNC
->uNC
.pUpsert
;
549 if( pUpsert
&& sqlite3StrICmp("excluded",zTab
)==0 ){
550 pTab
= pUpsert
->pUpsertSrc
->a
[0].pTab
;
551 pExpr
->iTable
= EXCLUDED_TABLE_NUMBER
;
554 #endif /* SQLITE_OMIT_UPSERT */
558 u8 hCol
= sqlite3StrIHash(zCol
);
559 pSchema
= pTab
->pSchema
;
561 for(iCol
=0, pCol
=pTab
->aCol
; iCol
<pTab
->nCol
; iCol
++, pCol
++){
562 if( pCol
->hName
==hCol
563 && sqlite3StrICmp(pCol
->zCnName
, zCol
)==0
565 if( iCol
==pTab
->iPKey
){
571 if( iCol
>=pTab
->nCol
&& sqlite3IsRowid(zCol
) && VisibleRowid(pTab
) ){
572 /* IMP: R-51414-32910 */
575 if( iCol
<pTab
->nCol
){
578 #ifndef SQLITE_OMIT_UPSERT
579 if( pExpr
->iTable
==EXCLUDED_TABLE_NUMBER
){
580 testcase( iCol
==(-1) );
581 assert( ExprUseYTab(pExpr
) );
582 if( IN_RENAME_OBJECT
){
583 pExpr
->iColumn
= iCol
;
584 pExpr
->y
.pTab
= pTab
;
585 eNewExprOp
= TK_COLUMN
;
587 pExpr
->iTable
= pNC
->uNC
.pUpsert
->regData
+
588 sqlite3TableColumnToStorage(pTab
, iCol
);
589 eNewExprOp
= TK_REGISTER
;
592 #endif /* SQLITE_OMIT_UPSERT */
594 assert( ExprUseYTab(pExpr
) );
595 pExpr
->y
.pTab
= pTab
;
596 if( pParse
->bReturning
){
597 eNewExprOp
= TK_REGISTER
;
598 pExpr
->op2
= TK_COLUMN
;
599 pExpr
->iColumn
= iCol
;
600 pExpr
->iTable
= pNC
->uNC
.iBaseReg
+ (pTab
->nCol
+1)*pExpr
->iTable
+
601 sqlite3TableColumnToStorage(pTab
, iCol
) + 1;
603 pExpr
->iColumn
= (i16
)iCol
;
604 eNewExprOp
= TK_TRIGGER
;
605 #ifndef SQLITE_OMIT_TRIGGER
607 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
608 }else if( pExpr
->iTable
==0 ){
609 testcase( iCol
==31 );
610 testcase( iCol
==32 );
611 pParse
->oldmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
613 testcase( iCol
==31 );
614 testcase( iCol
==32 );
615 pParse
->newmask
|= (iCol
>=32 ? 0xffffffff : (((u32
)1)<<iCol
));
617 #endif /* SQLITE_OMIT_TRIGGER */
623 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
626 ** Perhaps the name is a reference to the ROWID
631 && (pNC
->ncFlags
& (NC_IdxExpr
|NC_GenCol
))==0
632 && sqlite3IsRowid(zCol
)
633 && ALWAYS(VisibleRowid(pMatch
->pTab
) || pMatch
->fg
.isNestedFrom
)
636 #if SQLITE_ALLOW_ROWID_IN_VIEW+0==2
637 if( pMatch
->pTab
!=0 && IsView(pMatch
->pTab
) ){
638 eNewExprOp
= TK_NULL
;
641 if( pMatch
->fg
.isNestedFrom
==0 ) pExpr
->iColumn
= -1;
642 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
646 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
647 ** might refer to an result-set alias. This happens, for example, when
648 ** we are resolving names in the WHERE clause of the following command:
650 ** SELECT a+b AS x FROM table WHERE x<10;
652 ** In cases like this, replace pExpr with a copy of the expression that
653 ** forms the result set entry ("a+b" in the example) and return immediately.
654 ** Note that the expression in the result set should have already been
655 ** resolved by the time the WHERE clause is resolved.
657 ** The ability to use an output result-set column in the WHERE, GROUP BY,
658 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
659 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
660 ** is supported for backwards compatibility only. Hence, we issue a warning
661 ** on sqlite3_log() whenever the capability is used.
664 && (pNC
->ncFlags
& NC_UEList
)!=0
667 pEList
= pNC
->uNC
.pEList
;
669 for(j
=0; j
<pEList
->nExpr
; j
++){
670 char *zAs
= pEList
->a
[j
].zEName
;
671 if( pEList
->a
[j
].fg
.eEName
==ENAME_NAME
672 && sqlite3_stricmp(zAs
, zCol
)==0
675 assert( pExpr
->pLeft
==0 && pExpr
->pRight
==0 );
676 assert( ExprUseXList(pExpr
)==0 || pExpr
->x
.pList
==0 );
677 assert( ExprUseXSelect(pExpr
)==0 || pExpr
->x
.pSelect
==0 );
678 pOrig
= pEList
->a
[j
].pExpr
;
679 if( (pNC
->ncFlags
&NC_AllowAgg
)==0 && ExprHasProperty(pOrig
, EP_Agg
) ){
680 sqlite3ErrorMsg(pParse
, "misuse of aliased aggregate %s", zAs
);
683 if( ExprHasProperty(pOrig
, EP_Win
)
684 && ((pNC
->ncFlags
&NC_AllowWin
)==0 || pNC
!=pTopNC
)
686 sqlite3ErrorMsg(pParse
, "misuse of aliased window function %s",zAs
);
689 if( sqlite3ExprVectorSize(pOrig
)!=1 ){
690 sqlite3ErrorMsg(pParse
, "row value misused");
693 resolveAlias(pParse
, pEList
, j
, pExpr
, nSubquery
);
696 assert( zTab
==0 && zDb
==0 );
697 if( IN_RENAME_OBJECT
){
698 sqlite3RenameTokenRemap(pParse
, 0, (void*)pExpr
);
705 /* Advance to the next name context. The loop will exit when either
706 ** we have a match (cnt>0) or when we run out of name contexts.
715 ** If X and Y are NULL (in other words if only the column name Z is
716 ** supplied) and the value of Z is enclosed in double-quotes, then
717 ** Z is a string literal if it doesn't match any column names. In that
718 ** case, we need to return right away and not make any changes to
721 ** Because no reference was made to outer contexts, the pNC->nRef
722 ** fields are not changed in any context.
724 if( cnt
==0 && zTab
==0 ){
725 assert( pExpr
->op
==TK_ID
);
726 if( ExprHasProperty(pExpr
,EP_DblQuoted
)
727 && areDoubleQuotedStringsEnabled(db
, pTopNC
)
729 /* If a double-quoted identifier does not match any known column name,
730 ** then treat it as a string.
732 ** This hack was added in the early days of SQLite in a misguided attempt
733 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
734 ** I now sorely regret putting in this hack. The effect of this hack is
735 ** that misspelled identifier names are silently converted into strings
736 ** rather than causing an error, to the frustration of countless
737 ** programmers. To all those frustrated programmers, my apologies.
739 ** Someday, I hope to get rid of this hack. Unfortunately there is
740 ** a huge amount of legacy SQL that uses it. So for now, we just
743 sqlite3_log(SQLITE_WARNING
,
744 "double-quoted string literal: \"%w\"", zCol
);
745 #ifdef SQLITE_ENABLE_NORMALIZE
746 sqlite3VdbeAddDblquoteStr(db
, pParse
->pVdbe
, zCol
);
748 pExpr
->op
= TK_STRING
;
749 memset(&pExpr
->y
, 0, sizeof(pExpr
->y
));
752 if( sqlite3ExprIdToTrueFalse(pExpr
) ){
758 ** cnt==0 means there was not match.
759 ** cnt>1 means there were two or more matches.
761 ** cnt==0 is always an error. cnt>1 is often an error, but might
762 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
764 assert( pFJMatch
==0 || cnt
>0 );
765 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
769 if( pFJMatch
->nExpr
==cnt
-1 ){
770 if( ExprHasProperty(pExpr
,EP_Leaf
) ){
771 ExprClearProperty(pExpr
,EP_Leaf
);
773 sqlite3ExprDelete(db
, pExpr
->pLeft
);
775 sqlite3ExprDelete(db
, pExpr
->pRight
);
778 extendFJMatch(pParse
, &pFJMatch
, pMatch
, pExpr
->iColumn
);
779 pExpr
->op
= TK_FUNCTION
;
780 pExpr
->u
.zToken
= "coalesce";
781 pExpr
->x
.pList
= pFJMatch
;
785 sqlite3ExprListDelete(db
, pFJMatch
);
789 zErr
= cnt
==0 ? "no such column" : "ambiguous column name";
791 sqlite3ErrorMsg(pParse
, "%s: %s.%s.%s", zErr
, zDb
, zTab
, zCol
);
793 sqlite3ErrorMsg(pParse
, "%s: %s.%s", zErr
, zTab
, zCol
);
794 }else if( cnt
==0 && ExprHasProperty(pRight
,EP_DblQuoted
) ){
795 sqlite3ErrorMsg(pParse
, "%s: \"%s\" - should this be a"
796 " string literal in single-quotes?",
799 sqlite3ErrorMsg(pParse
, "%s: %s", zErr
, zCol
);
801 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
802 pParse
->checkSchema
= 1;
804 eNewExprOp
= TK_NULL
;
806 assert( pFJMatch
==0 );
808 /* Remove all substructure from pExpr */
809 if( !ExprHasProperty(pExpr
,(EP_TokenOnly
|EP_Leaf
)) ){
810 sqlite3ExprDelete(db
, pExpr
->pLeft
);
812 sqlite3ExprDelete(db
, pExpr
->pRight
);
814 ExprSetProperty(pExpr
, EP_Leaf
);
817 /* If a column from a table in pSrcList is referenced, then record
818 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
819 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
820 ** set if the 63rd or any subsequent column is used.
822 ** The colUsed mask is an optimization used to help determine if an
823 ** index is a covering index. The correct answer is still obtained
824 ** if the mask contains extra set bits. However, it is important to
825 ** avoid setting bits beyond the maximum column number of the table.
826 ** (See ticket [b92e5e8ec2cdbaa1]).
828 ** If a generated column is referenced, set bits for every column
832 if( pExpr
->iColumn
>=0 ){
833 pMatch
->colUsed
|= sqlite3ExprColUsed(pExpr
);
835 pMatch
->fg
.rowidUsed
= 1;
839 pExpr
->op
= eNewExprOp
;
843 #ifndef SQLITE_OMIT_AUTHORIZATION
844 if( pParse
->db
->xAuth
845 && (pExpr
->op
==TK_COLUMN
|| pExpr
->op
==TK_TRIGGER
)
847 sqlite3AuthRead(pParse
, pExpr
, pSchema
, pNC
->pSrcList
);
850 /* Increment the nRef value on all name contexts from TopNC up to
851 ** the point where the name matched. */
855 if( pTopNC
==pNC
) break;
856 pTopNC
= pTopNC
->pNext
;
865 ** Allocate and return a pointer to an expression to load the column iCol
866 ** from datasource iSrc in SrcList pSrc.
868 Expr
*sqlite3CreateColumnExpr(sqlite3
*db
, SrcList
*pSrc
, int iSrc
, int iCol
){
869 Expr
*p
= sqlite3ExprAlloc(db
, TK_COLUMN
, 0, 0);
871 SrcItem
*pItem
= &pSrc
->a
[iSrc
];
873 assert( ExprUseYTab(p
) );
874 pTab
= p
->y
.pTab
= pItem
->pTab
;
875 p
->iTable
= pItem
->iCursor
;
876 if( p
->y
.pTab
->iPKey
==iCol
){
879 p
->iColumn
= (ynVar
)iCol
;
880 if( (pTab
->tabFlags
& TF_HasGenerated
)!=0
881 && (pTab
->aCol
[iCol
].colFlags
& COLFLAG_GENERATED
)!=0
883 testcase( pTab
->nCol
==63 );
884 testcase( pTab
->nCol
==64 );
885 pItem
->colUsed
= pTab
->nCol
>=64 ? ALLBITS
: MASKBIT(pTab
->nCol
)-1;
887 testcase( iCol
==BMS
);
888 testcase( iCol
==BMS
-1 );
889 pItem
->colUsed
|= ((Bitmask
)1)<<(iCol
>=BMS
? BMS
-1 : iCol
);
897 ** Report an error that an expression is not valid for some set of
898 ** pNC->ncFlags values determined by validMask.
900 ** static void notValid(
901 ** Parse *pParse, // Leave error message here
902 ** NameContext *pNC, // The name context
903 ** const char *zMsg, // Type of error
904 ** int validMask, // Set of contexts for which prohibited
905 ** Expr *pExpr // Invalidate this expression on error
908 ** As an optimization, since the conditional is almost always false
909 ** (because errors are rare), the conditional is moved outside of the
910 ** function call using a macro.
912 static void notValidImpl(
913 Parse
*pParse
, /* Leave error message here */
914 NameContext
*pNC
, /* The name context */
915 const char *zMsg
, /* Type of error */
916 Expr
*pExpr
, /* Invalidate this expression on error */
917 Expr
*pError
/* Associate error with this expression */
919 const char *zIn
= "partial index WHERE clauses";
920 if( pNC
->ncFlags
& NC_IdxExpr
) zIn
= "index expressions";
921 #ifndef SQLITE_OMIT_CHECK
922 else if( pNC
->ncFlags
& NC_IsCheck
) zIn
= "CHECK constraints";
924 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
925 else if( pNC
->ncFlags
& NC_GenCol
) zIn
= "generated columns";
927 sqlite3ErrorMsg(pParse
, "%s prohibited in %s", zMsg
, zIn
);
928 if( pExpr
) pExpr
->op
= TK_NULL
;
929 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
931 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
932 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
933 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
936 ** Expression p should encode a floating point value between 1.0 and 0.0.
937 ** Return 1024 times this value. Or return -1 if p is not a floating point
938 ** value between 1.0 and 0.0.
940 static int exprProbability(Expr
*p
){
942 if( p
->op
!=TK_FLOAT
) return -1;
943 assert( !ExprHasProperty(p
, EP_IntValue
) );
944 sqlite3AtoF(p
->u
.zToken
, &r
, sqlite3Strlen30(p
->u
.zToken
), SQLITE_UTF8
);
946 if( r
>1.0 ) return -1;
947 return (int)(r
*134217728.0);
951 ** This routine is callback for sqlite3WalkExpr().
953 ** Resolve symbolic names into TK_COLUMN operators for the current
954 ** node in the expression tree. Return 0 to continue the search down
955 ** the tree or 2 to abort the tree walk.
957 ** This routine also does error checking and name resolution for
958 ** function names. The operator for aggregate functions is changed
959 ** to TK_AGG_FUNCTION.
961 static int resolveExprStep(Walker
*pWalker
, Expr
*pExpr
){
965 pNC
= pWalker
->u
.pNC
;
967 pParse
= pNC
->pParse
;
968 assert( pParse
==pWalker
->pParse
);
971 if( pNC
->pSrcList
&& pNC
->pSrcList
->nAlloc
>0 ){
972 SrcList
*pSrcList
= pNC
->pSrcList
;
974 for(i
=0; i
<pNC
->pSrcList
->nSrc
; i
++){
975 assert( pSrcList
->a
[i
].iCursor
>=0 && pSrcList
->a
[i
].iCursor
<pParse
->nTab
);
981 /* The special operator TK_ROW means use the rowid for the first
982 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
983 ** clause processing on UPDATE and DELETE statements, and by
984 ** UPDATE ... FROM statement processing.
987 SrcList
*pSrcList
= pNC
->pSrcList
;
989 assert( pSrcList
&& pSrcList
->nSrc
>=1 );
991 pExpr
->op
= TK_COLUMN
;
992 assert( ExprUseYTab(pExpr
) );
993 pExpr
->y
.pTab
= pItem
->pTab
;
994 pExpr
->iTable
= pItem
->iCursor
;
996 pExpr
->affExpr
= SQLITE_AFF_INTEGER
;
1000 /* An optimization: Attempt to convert
1002 ** "expr IS NOT NULL" --> "TRUE"
1003 ** "expr IS NULL" --> "FALSE"
1005 ** if we can prove that "expr" is never NULL. Call this the
1006 ** "NOT NULL strength reduction optimization".
1008 ** If this optimization occurs, also restore the NameContext ref-counts
1009 ** to the state they where in before the "column" LHS expression was
1010 ** resolved. This prevents "column" from being counted as having been
1011 ** referenced, which might prevent a SELECT from being erroneously
1012 ** marked as correlated.
1014 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
1015 ** can still evaluate to NULL even though it is marked as NOT NULL.
1018 ** CREATE TABLE t1(a INT NOT NULL);
1019 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
1021 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
1022 ** here because at the time this case is hit, we do not yet know whether
1023 ** or not t1 is being aggregated. We have to assume the worst and omit
1024 ** the optimization. The only time it is safe to apply this optimization
1025 ** is within the WHERE clause.
1032 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
1035 sqlite3WalkExpr(pWalker
, pExpr
->pLeft
);
1036 if( IN_RENAME_OBJECT
) return WRC_Prune
;
1037 if( sqlite3ExprCanBeNull(pExpr
->pLeft
) ){
1038 /* The expression can be NULL. So the optimization does not apply */
1042 for(i
=0, p
=pNC
; p
; p
=p
->pNext
, i
++){
1043 if( (p
->ncFlags
& NC_Where
)==0 ){
1044 return WRC_Prune
; /* Not in a WHERE clause. Unsafe to optimize. */
1047 testcase( ExprHasProperty(pExpr
, EP_OuterON
) );
1048 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
1049 #if TREETRACE_ENABLED
1050 if( sqlite3TreeTrace
& 0x80000 ){
1052 "NOT NULL strength reduction converts the following to %d:\n",
1053 pExpr
->op
==TK_NOTNULL
1055 sqlite3ShowExpr(pExpr
);
1057 #endif /* TREETRACE_ENABLED */
1058 pExpr
->u
.iValue
= (pExpr
->op
==TK_NOTNULL
);
1059 pExpr
->flags
|= EP_IntValue
;
1060 pExpr
->op
= TK_INTEGER
;
1061 for(i
=0, p
=pNC
; p
&& i
<ArraySize(anRef
); p
=p
->pNext
, i
++){
1064 sqlite3ExprDelete(pParse
->db
, pExpr
->pLeft
);
1069 /* A column name: ID
1070 ** Or table name and column name: ID.ID
1071 ** Or a database, table and column: ID.ID.ID
1073 ** The TK_ID and TK_OUT cases are combined so that there will only
1074 ** be one call to lookupName(). Then the compiler will in-line
1075 ** lookupName() for a size reduction and performance increase.
1083 if( pExpr
->op
==TK_ID
){
1086 assert( !ExprHasProperty(pExpr
, EP_IntValue
) );
1089 Expr
*pLeft
= pExpr
->pLeft
;
1090 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1091 testcase( pNC
->ncFlags
& NC_GenCol
);
1092 sqlite3ResolveNotValid(pParse
, pNC
, "the \".\" operator",
1093 NC_IdxExpr
|NC_GenCol
, 0, pExpr
);
1094 pRight
= pExpr
->pRight
;
1095 if( pRight
->op
==TK_ID
){
1098 assert( pRight
->op
==TK_DOT
);
1099 assert( !ExprHasProperty(pRight
, EP_IntValue
) );
1100 zDb
= pLeft
->u
.zToken
;
1101 pLeft
= pRight
->pLeft
;
1102 pRight
= pRight
->pRight
;
1104 assert( ExprUseUToken(pLeft
) && ExprUseUToken(pRight
) );
1105 zTable
= pLeft
->u
.zToken
;
1106 assert( ExprUseYTab(pExpr
) );
1107 if( IN_RENAME_OBJECT
){
1108 sqlite3RenameTokenRemap(pParse
, (void*)pExpr
, (void*)pRight
);
1109 sqlite3RenameTokenRemap(pParse
, (void*)&pExpr
->y
.pTab
, (void*)pLeft
);
1112 return lookupName(pParse
, zDb
, zTable
, pRight
, pNC
, pExpr
);
1115 /* Resolve function names
1118 ExprList
*pList
= pExpr
->x
.pList
; /* The argument list */
1119 int n
= pList
? pList
->nExpr
: 0; /* Number of arguments */
1120 int no_such_func
= 0; /* True if no such function exists */
1121 int wrong_num_args
= 0; /* True if wrong number of arguments */
1122 int is_agg
= 0; /* True if is an aggregate function */
1123 const char *zId
; /* The function name. */
1124 FuncDef
*pDef
; /* Information about the function */
1125 u8 enc
= ENC(pParse
->db
); /* The database encoding */
1126 int savedAllowFlags
= (pNC
->ncFlags
& (NC_AllowAgg
| NC_AllowWin
));
1127 #ifndef SQLITE_OMIT_WINDOWFUNC
1128 Window
*pWin
= (IsWindowFunc(pExpr
) ? pExpr
->y
.pWin
: 0);
1130 assert( !ExprHasProperty(pExpr
, EP_xIsSelect
|EP_IntValue
) );
1131 assert( pExpr
->pLeft
==0 || pExpr
->pLeft
->op
==TK_ORDER
);
1132 zId
= pExpr
->u
.zToken
;
1133 pDef
= sqlite3FindFunction(pParse
->db
, zId
, n
, enc
, 0);
1135 pDef
= sqlite3FindFunction(pParse
->db
, zId
, -2, enc
, 0);
1142 is_agg
= pDef
->xFinalize
!=0;
1143 if( pDef
->funcFlags
& SQLITE_FUNC_UNLIKELY
){
1144 ExprSetProperty(pExpr
, EP_Unlikely
);
1146 pExpr
->iTable
= exprProbability(pList
->a
[1].pExpr
);
1147 if( pExpr
->iTable
<0 ){
1148 sqlite3ErrorMsg(pParse
,
1149 "second argument to %#T() must be a "
1150 "constant between 0.0 and 1.0", pExpr
);
1154 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1155 ** equivalent to likelihood(X, 0.0625).
1156 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1157 ** short-hand for likelihood(X,0.0625).
1158 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1159 ** for likelihood(X,0.9375).
1160 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1161 ** to likelihood(X,0.9375). */
1162 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1163 pExpr
->iTable
= pDef
->zName
[0]=='u' ? 8388608 : 125829120;
1166 #ifndef SQLITE_OMIT_AUTHORIZATION
1168 int auth
= sqlite3AuthCheck(pParse
, SQLITE_FUNCTION
, 0,pDef
->zName
,0);
1169 if( auth
!=SQLITE_OK
){
1170 if( auth
==SQLITE_DENY
){
1171 sqlite3ErrorMsg(pParse
, "not authorized to use function: %#T",
1175 pExpr
->op
= TK_NULL
;
1180 if( pDef
->funcFlags
& (SQLITE_FUNC_CONSTANT
|SQLITE_FUNC_SLOCHNG
) ){
1181 /* For the purposes of the EP_ConstFunc flag, date and time
1182 ** functions and other functions that change slowly are considered
1183 ** constant because they are constant for the duration of one query.
1184 ** This allows them to be factored out of inner loops. */
1185 ExprSetProperty(pExpr
,EP_ConstFunc
);
1187 if( (pDef
->funcFlags
& SQLITE_FUNC_CONSTANT
)==0 ){
1188 /* Clearly non-deterministic functions like random(), but also
1189 ** date/time functions that use 'now', and other functions like
1190 ** sqlite_version() that might change over time cannot be used
1191 ** in an index or generated column. Curiously, they can be used
1192 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1194 sqlite3ResolveNotValid(pParse
, pNC
, "non-deterministic functions",
1195 NC_IdxExpr
|NC_PartIdx
|NC_GenCol
, 0, pExpr
);
1197 assert( (NC_SelfRef
& 0xff)==NC_SelfRef
); /* Must fit in 8 bits */
1198 pExpr
->op2
= pNC
->ncFlags
& NC_SelfRef
;
1199 if( pNC
->ncFlags
& NC_FromDDL
) ExprSetProperty(pExpr
, EP_FromDDL
);
1201 if( (pDef
->funcFlags
& SQLITE_FUNC_INTERNAL
)!=0
1202 && pParse
->nested
==0
1203 && (pParse
->db
->mDbFlags
& DBFLAG_InternalFunc
)==0
1205 /* Internal-use-only functions are disallowed unless the
1206 ** SQL is being compiled using sqlite3NestedParse() or
1207 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1208 ** used to activate internal functions for testing purposes */
1212 if( (pDef
->funcFlags
& (SQLITE_FUNC_DIRECT
|SQLITE_FUNC_UNSAFE
))!=0
1213 && !IN_RENAME_OBJECT
1215 sqlite3ExprFunctionUsable(pParse
, pExpr
, pDef
);
1219 if( 0==IN_RENAME_OBJECT
){
1220 #ifndef SQLITE_OMIT_WINDOWFUNC
1221 assert( is_agg
==0 || (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)
1222 || (pDef
->xValue
==0 && pDef
->xInverse
==0)
1223 || (pDef
->xValue
&& pDef
->xInverse
&& pDef
->xSFunc
&& pDef
->xFinalize
)
1225 if( pDef
&& pDef
->xValue
==0 && pWin
){
1226 sqlite3ErrorMsg(pParse
,
1227 "%#T() may not be used as a window function", pExpr
1231 (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0)
1232 || (is_agg
&& (pDef
->funcFlags
&SQLITE_FUNC_WINDOW
) && !pWin
)
1233 || (is_agg
&& pWin
&& (pNC
->ncFlags
& NC_AllowWin
)==0)
1236 if( (pDef
->funcFlags
& SQLITE_FUNC_WINDOW
) || pWin
){
1239 zType
= "aggregate";
1241 sqlite3ErrorMsg(pParse
, "misuse of %s function %#T()",zType
,pExpr
);
1246 if( (is_agg
&& (pNC
->ncFlags
& NC_AllowAgg
)==0) ){
1247 sqlite3ErrorMsg(pParse
,"misuse of aggregate function %#T()",pExpr
);
1252 else if( no_such_func
&& pParse
->db
->init
.busy
==0
1253 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1254 && pParse
->explain
==0
1257 sqlite3ErrorMsg(pParse
, "no such function: %#T", pExpr
);
1259 }else if( wrong_num_args
){
1260 sqlite3ErrorMsg(pParse
,"wrong number of arguments to function %#T()",
1264 #ifndef SQLITE_OMIT_WINDOWFUNC
1265 else if( is_agg
==0 && ExprHasProperty(pExpr
, EP_WinFunc
) ){
1266 sqlite3ErrorMsg(pParse
,
1267 "FILTER may not be used with non-aggregate %#T()",
1273 else if( is_agg
==0 && pExpr
->pLeft
){
1274 sqlite3ExprOrderByAggregateError(pParse
, pExpr
);
1278 /* Window functions may not be arguments of aggregate functions.
1279 ** Or arguments of other window functions. But aggregate functions
1280 ** may be arguments for window functions. */
1281 #ifndef SQLITE_OMIT_WINDOWFUNC
1282 pNC
->ncFlags
&= ~(NC_AllowWin
| (!pWin
? NC_AllowAgg
: 0));
1284 pNC
->ncFlags
&= ~NC_AllowAgg
;
1288 else if( ExprHasProperty(pExpr
, EP_WinFunc
) || pExpr
->pLeft
){
1291 sqlite3WalkExprList(pWalker
, pList
);
1294 assert( pExpr
->pLeft
->op
==TK_ORDER
);
1295 assert( ExprUseXList(pExpr
->pLeft
) );
1296 sqlite3WalkExprList(pWalker
, pExpr
->pLeft
->x
.pList
);
1298 #ifndef SQLITE_OMIT_WINDOWFUNC
1300 Select
*pSel
= pNC
->pWinSelect
;
1301 assert( pWin
==0 || (ExprUseYWin(pExpr
) && pWin
==pExpr
->y
.pWin
) );
1302 if( IN_RENAME_OBJECT
==0 ){
1303 sqlite3WindowUpdate(pParse
, pSel
? pSel
->pWinDefn
: 0, pWin
, pDef
);
1304 if( pParse
->db
->mallocFailed
) break;
1306 sqlite3WalkExprList(pWalker
, pWin
->pPartition
);
1307 sqlite3WalkExprList(pWalker
, pWin
->pOrderBy
);
1308 sqlite3WalkExpr(pWalker
, pWin
->pFilter
);
1309 sqlite3WindowLink(pSel
, pWin
);
1310 pNC
->ncFlags
|= NC_HasWin
;
1312 #endif /* SQLITE_OMIT_WINDOWFUNC */
1314 NameContext
*pNC2
; /* For looping up thru outer contexts */
1315 pExpr
->op
= TK_AGG_FUNCTION
;
1317 #ifndef SQLITE_OMIT_WINDOWFUNC
1318 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1319 sqlite3WalkExpr(pWalker
, pExpr
->y
.pWin
->pFilter
);
1324 && sqlite3ReferencesSrcList(pParse
, pExpr
, pNC2
->pSrcList
)==0
1326 pExpr
->op2
+= (1 + pNC2
->nNestedSelect
);
1329 assert( pDef
!=0 || IN_RENAME_OBJECT
);
1331 pExpr
->op2
+= pNC2
->nNestedSelect
;
1332 assert( SQLITE_FUNC_MINMAX
==NC_MinMaxAgg
);
1333 assert( SQLITE_FUNC_ANYORDER
==NC_OrderAgg
);
1334 testcase( (pDef
->funcFlags
& SQLITE_FUNC_MINMAX
)!=0 );
1335 testcase( (pDef
->funcFlags
& SQLITE_FUNC_ANYORDER
)!=0 );
1336 pNC2
->ncFlags
|= NC_HasAgg
1337 | ((pDef
->funcFlags
^SQLITE_FUNC_ANYORDER
)
1338 & (SQLITE_FUNC_MINMAX
|SQLITE_FUNC_ANYORDER
));
1341 pNC
->ncFlags
|= savedAllowFlags
;
1343 /* FIX ME: Compute pExpr->affinity based on the expected return
1344 ** type of the function
1348 #ifndef SQLITE_OMIT_SUBQUERY
1350 case TK_EXISTS
: testcase( pExpr
->op
==TK_EXISTS
);
1353 testcase( pExpr
->op
==TK_IN
);
1354 if( ExprUseXSelect(pExpr
) ){
1355 int nRef
= pNC
->nRef
;
1356 testcase( pNC
->ncFlags
& NC_IsCheck
);
1357 testcase( pNC
->ncFlags
& NC_PartIdx
);
1358 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1359 testcase( pNC
->ncFlags
& NC_GenCol
);
1360 assert( pExpr
->x
.pSelect
);
1361 if( pNC
->ncFlags
& NC_SelfRef
){
1362 notValidImpl(pParse
, pNC
, "subqueries", pExpr
, pExpr
);
1364 sqlite3WalkSelect(pWalker
, pExpr
->x
.pSelect
);
1366 assert( pNC
->nRef
>=nRef
);
1367 if( nRef
!=pNC
->nRef
){
1368 ExprSetProperty(pExpr
, EP_VarSelect
);
1369 pExpr
->x
.pSelect
->selFlags
|= SF_Correlated
;
1371 pNC
->ncFlags
|= NC_Subquery
;
1376 testcase( pNC
->ncFlags
& NC_IsCheck
);
1377 testcase( pNC
->ncFlags
& NC_PartIdx
);
1378 testcase( pNC
->ncFlags
& NC_IdxExpr
);
1379 testcase( pNC
->ncFlags
& NC_GenCol
);
1380 sqlite3ResolveNotValid(pParse
, pNC
, "parameters",
1381 NC_IsCheck
|NC_PartIdx
|NC_IdxExpr
|NC_GenCol
, pExpr
, pExpr
);
1386 Expr
*pRight
= sqlite3ExprSkipCollateAndLikely(pExpr
->pRight
);
1387 assert( !ExprHasProperty(pExpr
, EP_Reduced
) );
1388 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1389 ** and "x IS NOT FALSE". */
1390 if( ALWAYS(pRight
) && (pRight
->op
==TK_ID
|| pRight
->op
==TK_TRUEFALSE
) ){
1391 int rc
= resolveExprStep(pWalker
, pRight
);
1392 if( rc
==WRC_Abort
) return WRC_Abort
;
1393 if( pRight
->op
==TK_TRUEFALSE
){
1394 pExpr
->op2
= pExpr
->op
;
1395 pExpr
->op
= TK_TRUTH
;
1396 return WRC_Continue
;
1399 /* no break */ deliberate_fall_through
1409 if( pParse
->db
->mallocFailed
) break;
1410 assert( pExpr
->pLeft
!=0 );
1411 nLeft
= sqlite3ExprVectorSize(pExpr
->pLeft
);
1412 if( pExpr
->op
==TK_BETWEEN
){
1413 assert( ExprUseXList(pExpr
) );
1414 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[0].pExpr
);
1415 if( nRight
==nLeft
){
1416 nRight
= sqlite3ExprVectorSize(pExpr
->x
.pList
->a
[1].pExpr
);
1419 assert( pExpr
->pRight
!=0 );
1420 nRight
= sqlite3ExprVectorSize(pExpr
->pRight
);
1422 if( nLeft
!=nRight
){
1423 testcase( pExpr
->op
==TK_EQ
);
1424 testcase( pExpr
->op
==TK_NE
);
1425 testcase( pExpr
->op
==TK_LT
);
1426 testcase( pExpr
->op
==TK_LE
);
1427 testcase( pExpr
->op
==TK_GT
);
1428 testcase( pExpr
->op
==TK_GE
);
1429 testcase( pExpr
->op
==TK_IS
);
1430 testcase( pExpr
->op
==TK_ISNOT
);
1431 testcase( pExpr
->op
==TK_BETWEEN
);
1432 sqlite3ErrorMsg(pParse
, "row value misused");
1433 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pExpr
);
1438 assert( pParse
->db
->mallocFailed
==0 || pParse
->nErr
!=0 );
1439 return pParse
->nErr
? WRC_Abort
: WRC_Continue
;
1443 ** pEList is a list of expressions which are really the result set of the
1444 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1445 ** This routine checks to see if pE is a simple identifier which corresponds
1446 ** to the AS-name of one of the terms of the expression list. If it is,
1447 ** this routine return an integer between 1 and N where N is the number of
1448 ** elements in pEList, corresponding to the matching entry. If there is
1449 ** no match, or if pE is not a simple identifier, then this routine
1452 ** pEList has been resolved. pE has not.
1454 static int resolveAsName(
1455 Parse
*pParse
, /* Parsing context for error messages */
1456 ExprList
*pEList
, /* List of expressions to scan */
1457 Expr
*pE
/* Expression we are trying to match */
1459 int i
; /* Loop counter */
1461 UNUSED_PARAMETER(pParse
);
1463 if( pE
->op
==TK_ID
){
1465 assert( !ExprHasProperty(pE
, EP_IntValue
) );
1466 zCol
= pE
->u
.zToken
;
1467 for(i
=0; i
<pEList
->nExpr
; i
++){
1468 if( pEList
->a
[i
].fg
.eEName
==ENAME_NAME
1469 && sqlite3_stricmp(pEList
->a
[i
].zEName
, zCol
)==0
1479 ** pE is a pointer to an expression which is a single term in the
1480 ** ORDER BY of a compound SELECT. The expression has not been
1483 ** At the point this routine is called, we already know that the
1484 ** ORDER BY term is not an integer index into the result set. That
1485 ** case is handled by the calling routine.
1487 ** Attempt to match pE against result set columns in the left-most
1488 ** SELECT statement. Return the index i of the matching column,
1489 ** as an indication to the caller that it should sort by the i-th column.
1490 ** The left-most column is 1. In other words, the value returned is the
1491 ** same integer value that would be used in the SQL statement to indicate
1494 ** If there is no match, return 0. Return -1 if an error occurs.
1496 static int resolveOrderByTermToExprList(
1497 Parse
*pParse
, /* Parsing context for error messages */
1498 Select
*pSelect
, /* The SELECT statement with the ORDER BY clause */
1499 Expr
*pE
/* The specific ORDER BY term */
1501 int i
; /* Loop counter */
1502 ExprList
*pEList
; /* The columns of the result set */
1503 NameContext nc
; /* Name context for resolving pE */
1504 sqlite3
*db
; /* Database connection */
1505 int rc
; /* Return code from subprocedures */
1506 u8 savedSuppErr
; /* Saved value of db->suppressErr */
1508 assert( sqlite3ExprIsInteger(pE
, &i
)==0 );
1509 pEList
= pSelect
->pEList
;
1511 /* Resolve all names in the ORDER BY term expression
1513 memset(&nc
, 0, sizeof(nc
));
1515 nc
.pSrcList
= pSelect
->pSrc
;
1516 nc
.uNC
.pEList
= pEList
;
1517 nc
.ncFlags
= NC_AllowAgg
|NC_UEList
|NC_NoSelect
;
1520 savedSuppErr
= db
->suppressErr
;
1521 db
->suppressErr
= 1;
1522 rc
= sqlite3ResolveExprNames(&nc
, pE
);
1523 db
->suppressErr
= savedSuppErr
;
1526 /* Try to match the ORDER BY expression against an expression
1527 ** in the result set. Return an 1-based index of the matching
1528 ** result-set entry.
1530 for(i
=0; i
<pEList
->nExpr
; i
++){
1531 if( sqlite3ExprCompare(0, pEList
->a
[i
].pExpr
, pE
, -1)<2 ){
1536 /* If no match, return 0. */
1541 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1543 static void resolveOutOfRangeError(
1544 Parse
*pParse
, /* The error context into which to write the error */
1545 const char *zType
, /* "ORDER" or "GROUP" */
1546 int i
, /* The index (1-based) of the term out of range */
1547 int mx
, /* Largest permissible value of i */
1548 Expr
*pError
/* Associate the error with the expression */
1550 sqlite3ErrorMsg(pParse
,
1551 "%r %s BY term out of range - should be "
1552 "between 1 and %d", i
, zType
, mx
);
1553 sqlite3RecordErrorOffsetOfExpr(pParse
->db
, pError
);
1557 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1558 ** each term of the ORDER BY clause is a constant integer between 1
1559 ** and N where N is the number of columns in the compound SELECT.
1561 ** ORDER BY terms that are already an integer between 1 and N are
1562 ** unmodified. ORDER BY terms that are integers outside the range of
1563 ** 1 through N generate an error. ORDER BY terms that are expressions
1564 ** are matched against result set expressions of compound SELECT
1565 ** beginning with the left-most SELECT and working toward the right.
1566 ** At the first match, the ORDER BY expression is transformed into
1567 ** the integer column number.
1569 ** Return the number of errors seen.
1571 static int resolveCompoundOrderBy(
1572 Parse
*pParse
, /* Parsing context. Leave error messages here */
1573 Select
*pSelect
/* The SELECT statement containing the ORDER BY */
1581 pOrderBy
= pSelect
->pOrderBy
;
1582 if( pOrderBy
==0 ) return 0;
1584 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1585 sqlite3ErrorMsg(pParse
, "too many terms in ORDER BY clause");
1588 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1589 pOrderBy
->a
[i
].fg
.done
= 0;
1592 while( pSelect
->pPrior
){
1593 pSelect
->pPrior
->pNext
= pSelect
;
1594 pSelect
= pSelect
->pPrior
;
1596 while( pSelect
&& moreToDo
){
1597 struct ExprList_item
*pItem
;
1599 pEList
= pSelect
->pEList
;
1600 assert( pEList
!=0 );
1601 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1604 if( pItem
->fg
.done
) continue;
1605 pE
= sqlite3ExprSkipCollateAndLikely(pItem
->pExpr
);
1606 if( NEVER(pE
==0) ) continue;
1607 if( sqlite3ExprIsInteger(pE
, &iCol
) ){
1608 if( iCol
<=0 || iCol
>pEList
->nExpr
){
1609 resolveOutOfRangeError(pParse
, "ORDER", i
+1, pEList
->nExpr
, pE
);
1613 iCol
= resolveAsName(pParse
, pEList
, pE
);
1615 /* Now test if expression pE matches one of the values returned
1616 ** by pSelect. In the usual case this is done by duplicating the
1617 ** expression, resolving any symbols in it, and then comparing
1618 ** it against each expression returned by the SELECT statement.
1619 ** Once the comparisons are finished, the duplicate expression
1622 ** If this is running as part of an ALTER TABLE operation and
1623 ** the symbols resolve successfully, also resolve the symbols in the
1624 ** actual expression. This allows the code in alter.c to modify
1625 ** column references within the ORDER BY expression as required. */
1626 pDup
= sqlite3ExprDup(db
, pE
, 0);
1627 if( !db
->mallocFailed
){
1629 iCol
= resolveOrderByTermToExprList(pParse
, pSelect
, pDup
);
1630 if( IN_RENAME_OBJECT
&& iCol
>0 ){
1631 resolveOrderByTermToExprList(pParse
, pSelect
, pE
);
1634 sqlite3ExprDelete(db
, pDup
);
1638 /* Convert the ORDER BY term into an integer column number iCol,
1639 ** taking care to preserve the COLLATE clause if it exists. */
1640 if( !IN_RENAME_OBJECT
){
1641 Expr
*pNew
= sqlite3Expr(db
, TK_INTEGER
, 0);
1642 if( pNew
==0 ) return 1;
1643 pNew
->flags
|= EP_IntValue
;
1644 pNew
->u
.iValue
= iCol
;
1645 if( pItem
->pExpr
==pE
){
1646 pItem
->pExpr
= pNew
;
1648 Expr
*pParent
= pItem
->pExpr
;
1649 assert( pParent
->op
==TK_COLLATE
);
1650 while( pParent
->pLeft
->op
==TK_COLLATE
) pParent
= pParent
->pLeft
;
1651 assert( pParent
->pLeft
==pE
);
1652 pParent
->pLeft
= pNew
;
1654 sqlite3ExprDelete(db
, pE
);
1655 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1662 pSelect
= pSelect
->pNext
;
1664 for(i
=0; i
<pOrderBy
->nExpr
; i
++){
1665 if( pOrderBy
->a
[i
].fg
.done
==0 ){
1666 sqlite3ErrorMsg(pParse
, "%r ORDER BY term does not match any "
1667 "column in the result set", i
+1);
1675 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1676 ** the SELECT statement pSelect. If any term is reference to a
1677 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1678 ** field) then convert that term into a copy of the corresponding result set
1681 ** If any errors are detected, add an error message to pParse and
1682 ** return non-zero. Return zero if no errors are seen.
1684 int sqlite3ResolveOrderGroupBy(
1685 Parse
*pParse
, /* Parsing context. Leave error messages here */
1686 Select
*pSelect
, /* The SELECT statement containing the clause */
1687 ExprList
*pOrderBy
, /* The ORDER BY or GROUP BY clause to be processed */
1688 const char *zType
/* "ORDER" or "GROUP" */
1691 sqlite3
*db
= pParse
->db
;
1693 struct ExprList_item
*pItem
;
1695 if( pOrderBy
==0 || pParse
->db
->mallocFailed
|| IN_RENAME_OBJECT
) return 0;
1696 if( pOrderBy
->nExpr
>db
->aLimit
[SQLITE_LIMIT_COLUMN
] ){
1697 sqlite3ErrorMsg(pParse
, "too many terms in %s BY clause", zType
);
1700 pEList
= pSelect
->pEList
;
1701 assert( pEList
!=0 ); /* sqlite3SelectNew() guarantees this */
1702 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1703 if( pItem
->u
.x
.iOrderByCol
){
1704 if( pItem
->u
.x
.iOrderByCol
>pEList
->nExpr
){
1705 resolveOutOfRangeError(pParse
, zType
, i
+1, pEList
->nExpr
, 0);
1708 resolveAlias(pParse
, pEList
, pItem
->u
.x
.iOrderByCol
-1, pItem
->pExpr
,0);
1714 #ifndef SQLITE_OMIT_WINDOWFUNC
1716 ** Walker callback for windowRemoveExprFromSelect().
1718 static int resolveRemoveWindowsCb(Walker
*pWalker
, Expr
*pExpr
){
1719 UNUSED_PARAMETER(pWalker
);
1720 if( ExprHasProperty(pExpr
, EP_WinFunc
) ){
1721 Window
*pWin
= pExpr
->y
.pWin
;
1722 sqlite3WindowUnlinkFromSelect(pWin
);
1724 return WRC_Continue
;
1728 ** Remove any Window objects owned by the expression pExpr from the
1729 ** Select.pWin list of Select object pSelect.
1731 static void windowRemoveExprFromSelect(Select
*pSelect
, Expr
*pExpr
){
1732 if( pSelect
->pWin
){
1734 memset(&sWalker
, 0, sizeof(Walker
));
1735 sWalker
.xExprCallback
= resolveRemoveWindowsCb
;
1736 sWalker
.u
.pSelect
= pSelect
;
1737 sqlite3WalkExpr(&sWalker
, pExpr
);
1741 # define windowRemoveExprFromSelect(a, b)
1742 #endif /* SQLITE_OMIT_WINDOWFUNC */
1745 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1746 ** The Name context of the SELECT statement is pNC. zType is either
1747 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1749 ** This routine resolves each term of the clause into an expression.
1750 ** If the order-by term is an integer I between 1 and N (where N is the
1751 ** number of columns in the result set of the SELECT) then the expression
1752 ** in the resolution is a copy of the I-th result-set expression. If
1753 ** the order-by term is an identifier that corresponds to the AS-name of
1754 ** a result-set expression, then the term resolves to a copy of the
1755 ** result-set expression. Otherwise, the expression is resolved in
1756 ** the usual way - using sqlite3ResolveExprNames().
1758 ** This routine returns the number of errors. If errors occur, then
1759 ** an appropriate error message might be left in pParse. (OOM errors
1762 static int resolveOrderGroupBy(
1763 NameContext
*pNC
, /* The name context of the SELECT statement */
1764 Select
*pSelect
, /* The SELECT statement holding pOrderBy */
1765 ExprList
*pOrderBy
, /* An ORDER BY or GROUP BY clause to resolve */
1766 const char *zType
/* Either "ORDER" or "GROUP", as appropriate */
1768 int i
, j
; /* Loop counters */
1769 int iCol
; /* Column number */
1770 struct ExprList_item
*pItem
; /* A term of the ORDER BY clause */
1771 Parse
*pParse
; /* Parsing context */
1772 int nResult
; /* Number of terms in the result set */
1774 assert( pOrderBy
!=0 );
1775 nResult
= pSelect
->pEList
->nExpr
;
1776 pParse
= pNC
->pParse
;
1777 for(i
=0, pItem
=pOrderBy
->a
; i
<pOrderBy
->nExpr
; i
++, pItem
++){
1778 Expr
*pE
= pItem
->pExpr
;
1779 Expr
*pE2
= sqlite3ExprSkipCollateAndLikely(pE
);
1780 if( NEVER(pE2
==0) ) continue;
1781 if( zType
[0]!='G' ){
1782 iCol
= resolveAsName(pParse
, pSelect
->pEList
, pE2
);
1784 /* If an AS-name match is found, mark this ORDER BY column as being
1785 ** a copy of the iCol-th result-set column. The subsequent call to
1786 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1787 ** copy of the iCol-th result-set expression. */
1788 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1792 if( sqlite3ExprIsInteger(pE2
, &iCol
) ){
1793 /* The ORDER BY term is an integer constant. Again, set the column
1794 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1795 ** order-by term to a copy of the result-set expression */
1796 if( iCol
<1 || iCol
>0xffff ){
1797 resolveOutOfRangeError(pParse
, zType
, i
+1, nResult
, pE2
);
1800 pItem
->u
.x
.iOrderByCol
= (u16
)iCol
;
1804 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1805 pItem
->u
.x
.iOrderByCol
= 0;
1806 if( sqlite3ResolveExprNames(pNC
, pE
) ){
1809 for(j
=0; j
<pSelect
->pEList
->nExpr
; j
++){
1810 if( sqlite3ExprCompare(0, pE
, pSelect
->pEList
->a
[j
].pExpr
, -1)==0 ){
1811 /* Since this expression is being changed into a reference
1812 ** to an identical expression in the result set, remove all Window
1813 ** objects belonging to the expression from the Select.pWin list. */
1814 windowRemoveExprFromSelect(pSelect
, pE
);
1815 pItem
->u
.x
.iOrderByCol
= j
+1;
1819 return sqlite3ResolveOrderGroupBy(pParse
, pSelect
, pOrderBy
, zType
);
1823 ** Resolve names in the SELECT statement p and all of its descendants.
1825 static int resolveSelectStep(Walker
*pWalker
, Select
*p
){
1826 NameContext
*pOuterNC
; /* Context that contains this SELECT */
1827 NameContext sNC
; /* Name context of this SELECT */
1828 int isCompound
; /* True if p is a compound select */
1829 int nCompound
; /* Number of compound terms processed so far */
1830 Parse
*pParse
; /* Parsing context */
1831 int i
; /* Loop counter */
1832 ExprList
*pGroupBy
; /* The GROUP BY clause */
1833 Select
*pLeftmost
; /* Left-most of SELECT of a compound */
1834 sqlite3
*db
; /* Database connection */
1838 if( p
->selFlags
& SF_Resolved
){
1841 pOuterNC
= pWalker
->u
.pNC
;
1842 pParse
= pWalker
->pParse
;
1845 /* Normally sqlite3SelectExpand() will be called first and will have
1846 ** already expanded this SELECT. However, if this is a subquery within
1847 ** an expression, sqlite3ResolveExprNames() will be called without a
1848 ** prior call to sqlite3SelectExpand(). When that happens, let
1849 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1850 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1851 ** this routine in the correct order.
1853 if( (p
->selFlags
& SF_Expanded
)==0 ){
1854 sqlite3SelectPrep(pParse
, p
, pOuterNC
);
1855 return pParse
->nErr
? WRC_Abort
: WRC_Prune
;
1858 isCompound
= p
->pPrior
!=0;
1862 assert( (p
->selFlags
& SF_Expanded
)!=0 );
1863 assert( (p
->selFlags
& SF_Resolved
)==0 );
1864 p
->selFlags
|= SF_Resolved
;
1866 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1867 ** are not allowed to refer to any names, so pass an empty NameContext.
1869 memset(&sNC
, 0, sizeof(sNC
));
1870 sNC
.pParse
= pParse
;
1872 if( sqlite3ResolveExprNames(&sNC
, p
->pLimit
) ){
1876 /* If the SF_Converted flags is set, then this Select object was
1877 ** was created by the convertCompoundSelectToSubquery() function.
1878 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1879 ** as if it were part of the sub-query, not the parent. This block
1880 ** moves the pOrderBy down to the sub-query. It will be moved back
1881 ** after the names have been resolved. */
1882 if( p
->selFlags
& SF_Converted
){
1883 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
1884 assert( p
->pSrc
->nSrc
==1 && p
->pOrderBy
);
1885 assert( pSub
->pPrior
&& pSub
->pOrderBy
==0 );
1886 pSub
->pOrderBy
= p
->pOrderBy
;
1890 /* Recursively resolve names in all subqueries in the FROM clause
1892 if( pOuterNC
) pOuterNC
->nNestedSelect
++;
1893 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1894 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1895 assert( pItem
->zName
!=0 || pItem
->pSelect
!=0 );/* Test of tag-20240424-1*/
1896 if( pItem
->pSelect
&& (pItem
->pSelect
->selFlags
& SF_Resolved
)==0 ){
1897 int nRef
= pOuterNC
? pOuterNC
->nRef
: 0;
1898 const char *zSavedContext
= pParse
->zAuthContext
;
1900 if( pItem
->zName
) pParse
->zAuthContext
= pItem
->zName
;
1901 sqlite3ResolveSelectNames(pParse
, pItem
->pSelect
, pOuterNC
);
1902 pParse
->zAuthContext
= zSavedContext
;
1903 if( pParse
->nErr
) return WRC_Abort
;
1904 assert( db
->mallocFailed
==0 );
1906 /* If the number of references to the outer context changed when
1907 ** expressions in the sub-select were resolved, the sub-select
1908 ** is correlated. It is not required to check the refcount on any
1909 ** but the innermost outer context object, as lookupName() increments
1910 ** the refcount on all contexts between the current one and the
1911 ** context containing the column when it resolves a name. */
1913 assert( pItem
->fg
.isCorrelated
==0 && pOuterNC
->nRef
>=nRef
);
1914 pItem
->fg
.isCorrelated
= (pOuterNC
->nRef
>nRef
);
1918 if( pOuterNC
&& ALWAYS(pOuterNC
->nNestedSelect
>0) ){
1919 pOuterNC
->nNestedSelect
--;
1922 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1923 ** resolve the result-set expression list.
1925 sNC
.ncFlags
= NC_AllowAgg
|NC_AllowWin
;
1926 sNC
.pSrcList
= p
->pSrc
;
1927 sNC
.pNext
= pOuterNC
;
1929 /* Resolve names in the result set. */
1930 if( sqlite3ResolveExprListNames(&sNC
, p
->pEList
) ) return WRC_Abort
;
1931 sNC
.ncFlags
&= ~NC_AllowWin
;
1933 /* If there are no aggregate functions in the result-set, and no GROUP BY
1934 ** expression, do not allow aggregates in any of the other expressions.
1936 assert( (p
->selFlags
& SF_Aggregate
)==0 );
1937 pGroupBy
= p
->pGroupBy
;
1938 if( pGroupBy
|| (sNC
.ncFlags
& NC_HasAgg
)!=0 ){
1939 assert( NC_MinMaxAgg
==SF_MinMaxAgg
);
1940 assert( NC_OrderAgg
==SF_OrderByReqd
);
1941 p
->selFlags
|= SF_Aggregate
| (sNC
.ncFlags
&(NC_MinMaxAgg
|NC_OrderAgg
));
1943 sNC
.ncFlags
&= ~NC_AllowAgg
;
1946 /* Add the output column list to the name-context before parsing the
1947 ** other expressions in the SELECT statement. This is so that
1948 ** expressions in the WHERE clause (etc.) can refer to expressions by
1949 ** aliases in the result set.
1951 ** Minor point: If this is the case, then the expression will be
1952 ** re-evaluated for each reference to it.
1954 assert( (sNC
.ncFlags
& (NC_UAggInfo
|NC_UUpsert
|NC_UBaseReg
))==0 );
1955 sNC
.uNC
.pEList
= p
->pEList
;
1956 sNC
.ncFlags
|= NC_UEList
;
1958 if( (p
->selFlags
& SF_Aggregate
)==0 ){
1959 sqlite3ErrorMsg(pParse
, "HAVING clause on a non-aggregate query");
1962 if( sqlite3ResolveExprNames(&sNC
, p
->pHaving
) ) return WRC_Abort
;
1964 sNC
.ncFlags
|= NC_Where
;
1965 if( sqlite3ResolveExprNames(&sNC
, p
->pWhere
) ) return WRC_Abort
;
1966 sNC
.ncFlags
&= ~NC_Where
;
1968 /* Resolve names in table-valued-function arguments */
1969 for(i
=0; i
<p
->pSrc
->nSrc
; i
++){
1970 SrcItem
*pItem
= &p
->pSrc
->a
[i
];
1971 if( pItem
->fg
.isTabFunc
1972 && sqlite3ResolveExprListNames(&sNC
, pItem
->u1
.pFuncArg
)
1978 #ifndef SQLITE_OMIT_WINDOWFUNC
1979 if( IN_RENAME_OBJECT
){
1981 for(pWin
=p
->pWinDefn
; pWin
; pWin
=pWin
->pNextWin
){
1982 if( sqlite3ResolveExprListNames(&sNC
, pWin
->pOrderBy
)
1983 || sqlite3ResolveExprListNames(&sNC
, pWin
->pPartition
)
1991 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1995 sNC
.ncFlags
|= NC_AllowAgg
|NC_AllowWin
;
1997 /* If this is a converted compound query, move the ORDER BY clause from
1998 ** the sub-query back to the parent query. At this point each term
1999 ** within the ORDER BY clause has been transformed to an integer value.
2000 ** These integers will be replaced by copies of the corresponding result
2001 ** set expressions by the call to resolveOrderGroupBy() below. */
2002 if( p
->selFlags
& SF_Converted
){
2003 Select
*pSub
= p
->pSrc
->a
[0].pSelect
;
2004 p
->pOrderBy
= pSub
->pOrderBy
;
2008 /* Process the ORDER BY clause for singleton SELECT statements.
2009 ** The ORDER BY clause for compounds SELECT statements is handled
2010 ** below, after all of the result-sets for all of the elements of
2011 ** the compound have been resolved.
2013 ** If there is an ORDER BY clause on a term of a compound-select other
2014 ** than the right-most term, then that is a syntax error. But the error
2015 ** is not detected until much later, and so we need to go ahead and
2016 ** resolve those symbols on the incorrect ORDER BY for consistency.
2019 && isCompound
<=nCompound
/* Defer right-most ORDER BY of a compound */
2020 && resolveOrderGroupBy(&sNC
, p
, p
->pOrderBy
, "ORDER")
2024 if( db
->mallocFailed
){
2027 sNC
.ncFlags
&= ~NC_AllowWin
;
2029 /* Resolve the GROUP BY clause. At the same time, make sure
2030 ** the GROUP BY clause does not contain aggregate functions.
2033 struct ExprList_item
*pItem
;
2035 if( resolveOrderGroupBy(&sNC
, p
, pGroupBy
, "GROUP") || db
->mallocFailed
){
2038 for(i
=0, pItem
=pGroupBy
->a
; i
<pGroupBy
->nExpr
; i
++, pItem
++){
2039 if( ExprHasProperty(pItem
->pExpr
, EP_Agg
) ){
2040 sqlite3ErrorMsg(pParse
, "aggregate functions are not allowed in "
2041 "the GROUP BY clause");
2047 /* If this is part of a compound SELECT, check that it has the right
2048 ** number of expressions in the select list. */
2049 if( p
->pNext
&& p
->pEList
->nExpr
!=p
->pNext
->pEList
->nExpr
){
2050 sqlite3SelectWrongNumTermsError(pParse
, p
->pNext
);
2054 /* Advance to the next term of the compound
2060 /* Resolve the ORDER BY on a compound SELECT after all terms of
2061 ** the compound have been resolved.
2063 if( isCompound
&& resolveCompoundOrderBy(pParse
, pLeftmost
) ){
2071 ** This routine walks an expression tree and resolves references to
2072 ** table columns and result-set columns. At the same time, do error
2073 ** checking on function usage and set a flag if any aggregate functions
2076 ** To resolve table columns references we look for nodes (or subtrees) of the
2077 ** form X.Y.Z or Y.Z or just Z where
2079 ** X: The name of a database. Ex: "main" or "temp" or
2080 ** the symbolic name assigned to an ATTACH-ed database.
2082 ** Y: The name of a table in a FROM clause. Or in a trigger
2083 ** one of the special names "old" or "new".
2085 ** Z: The name of a column in table Y.
2087 ** The node at the root of the subtree is modified as follows:
2089 ** Expr.op Changed to TK_COLUMN
2090 ** Expr.pTab Points to the Table object for X.Y
2091 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
2092 ** Expr.iTable The VDBE cursor number for X.Y
2095 ** To resolve result-set references, look for expression nodes of the
2096 ** form Z (with no X and Y prefix) where the Z matches the right-hand
2097 ** size of an AS clause in the result-set of a SELECT. The Z expression
2098 ** is replaced by a copy of the left-hand side of the result-set expression.
2099 ** Table-name and function resolution occurs on the substituted expression
2100 ** tree. For example, in:
2102 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2104 ** The "x" term of the order by is replaced by "a+b" to render:
2106 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2108 ** Function calls are checked to make sure that the function is
2109 ** defined and that the correct number of arguments are specified.
2110 ** If the function is an aggregate function, then the NC_HasAgg flag is
2111 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2112 ** If an expression contains aggregate functions then the EP_Agg
2113 ** property on the expression is set.
2115 ** An error message is left in pParse if anything is amiss. The number
2116 ** if errors is returned.
2118 int sqlite3ResolveExprNames(
2119 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2120 Expr
*pExpr
/* The expression to be analyzed. */
2125 if( pExpr
==0 ) return SQLITE_OK
;
2126 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2127 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2128 w
.pParse
= pNC
->pParse
;
2129 w
.xExprCallback
= resolveExprStep
;
2130 w
.xSelectCallback
= (pNC
->ncFlags
& NC_NoSelect
) ? 0 : resolveSelectStep
;
2131 w
.xSelectCallback2
= 0;
2133 #if SQLITE_MAX_EXPR_DEPTH>0
2134 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2135 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2136 return SQLITE_ERROR
;
2140 sqlite3WalkExprNN(&w
, pExpr
);
2141 #if SQLITE_MAX_EXPR_DEPTH>0
2142 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2144 assert( EP_Agg
==NC_HasAgg
);
2145 assert( EP_Win
==NC_HasWin
);
2146 testcase( pNC
->ncFlags
& NC_HasAgg
);
2147 testcase( pNC
->ncFlags
& NC_HasWin
);
2148 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2149 pNC
->ncFlags
|= savedHasAgg
;
2150 return pNC
->nNcErr
>0 || w
.pParse
->nErr
>0;
2154 ** Resolve all names for all expression in an expression list. This is
2155 ** just like sqlite3ResolveExprNames() except that it works for an expression
2156 ** list rather than a single expression.
2158 ** The return value is SQLITE_OK (0) for success or SQLITE_ERROR (1) for a
2161 int sqlite3ResolveExprListNames(
2162 NameContext
*pNC
, /* Namespace to resolve expressions in. */
2163 ExprList
*pList
/* The expression list to be analyzed. */
2166 int savedHasAgg
= 0;
2168 if( pList
==0 ) return SQLITE_OK
;
2169 w
.pParse
= pNC
->pParse
;
2170 w
.xExprCallback
= resolveExprStep
;
2171 w
.xSelectCallback
= resolveSelectStep
;
2172 w
.xSelectCallback2
= 0;
2174 savedHasAgg
= pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2175 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2176 for(i
=0; i
<pList
->nExpr
; i
++){
2177 Expr
*pExpr
= pList
->a
[i
].pExpr
;
2178 if( pExpr
==0 ) continue;
2179 #if SQLITE_MAX_EXPR_DEPTH>0
2180 w
.pParse
->nHeight
+= pExpr
->nHeight
;
2181 if( sqlite3ExprCheckHeight(w
.pParse
, w
.pParse
->nHeight
) ){
2182 return SQLITE_ERROR
;
2185 sqlite3WalkExprNN(&w
, pExpr
);
2186 #if SQLITE_MAX_EXPR_DEPTH>0
2187 w
.pParse
->nHeight
-= pExpr
->nHeight
;
2189 assert( EP_Agg
==NC_HasAgg
);
2190 assert( EP_Win
==NC_HasWin
);
2191 testcase( pNC
->ncFlags
& NC_HasAgg
);
2192 testcase( pNC
->ncFlags
& NC_HasWin
);
2193 if( pNC
->ncFlags
& (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
) ){
2194 ExprSetProperty(pExpr
, pNC
->ncFlags
& (NC_HasAgg
|NC_HasWin
) );
2195 savedHasAgg
|= pNC
->ncFlags
&
2196 (NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2197 pNC
->ncFlags
&= ~(NC_HasAgg
|NC_MinMaxAgg
|NC_HasWin
|NC_OrderAgg
);
2199 if( w
.pParse
->nErr
>0 ) return SQLITE_ERROR
;
2201 pNC
->ncFlags
|= savedHasAgg
;
2206 ** Resolve all names in all expressions of a SELECT and in all
2207 ** descendants of the SELECT, including compounds off of p->pPrior,
2208 ** subqueries in expressions, and subqueries used as FROM clause
2211 ** See sqlite3ResolveExprNames() for a description of the kinds of
2212 ** transformations that occur.
2214 ** All SELECT statements should have been expanded using
2215 ** sqlite3SelectExpand() prior to invoking this routine.
2217 void sqlite3ResolveSelectNames(
2218 Parse
*pParse
, /* The parser context */
2219 Select
*p
, /* The SELECT statement being coded. */
2220 NameContext
*pOuterNC
/* Name context for parent SELECT statement */
2225 w
.xExprCallback
= resolveExprStep
;
2226 w
.xSelectCallback
= resolveSelectStep
;
2227 w
.xSelectCallback2
= 0;
2230 sqlite3WalkSelect(&w
, p
);
2234 ** Resolve names in expressions that can only reference a single table
2235 ** or which cannot reference any tables at all. Examples:
2239 ** (1) CHECK constraints NC_IsCheck
2240 ** (2) WHERE clauses on partial indices NC_PartIdx
2241 ** (3) Expressions in indexes on expressions NC_IdxExpr
2242 ** (4) Expression arguments to VACUUM INTO. 0
2243 ** (5) GENERATED ALWAYS as expressions NC_GenCol
2245 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2246 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2247 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2249 ** Any errors cause an error message to be set in pParse.
2251 int sqlite3ResolveSelfReference(
2252 Parse
*pParse
, /* Parsing context */
2253 Table
*pTab
, /* The table being referenced, or NULL */
2254 int type
, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2255 Expr
*pExpr
, /* Expression to resolve. May be NULL. */
2256 ExprList
*pList
/* Expression list to resolve. May be NULL. */
2258 SrcList sSrc
; /* Fake SrcList for pParse->pNewTable */
2259 NameContext sNC
; /* Name context for pParse->pNewTable */
2262 assert( type
==0 || pTab
!=0 );
2263 assert( type
==NC_IsCheck
|| type
==NC_PartIdx
|| type
==NC_IdxExpr
2264 || type
==NC_GenCol
|| pTab
==0 );
2265 memset(&sNC
, 0, sizeof(sNC
));
2266 memset(&sSrc
, 0, sizeof(sSrc
));
2269 sSrc
.a
[0].zName
= pTab
->zName
;
2270 sSrc
.a
[0].pTab
= pTab
;
2271 sSrc
.a
[0].iCursor
= -1;
2272 if( pTab
->pSchema
!=pParse
->db
->aDb
[1].pSchema
){
2273 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2274 ** schema elements */
2278 sNC
.pParse
= pParse
;
2279 sNC
.pSrcList
= &sSrc
;
2280 sNC
.ncFlags
= type
| NC_IsDDL
;
2281 if( (rc
= sqlite3ResolveExprNames(&sNC
, pExpr
))!=SQLITE_OK
) return rc
;
2282 if( pList
) rc
= sqlite3ResolveExprListNames(&sNC
, pList
);