Thanks to visit codestin.com
Credit goes to chromium.googlesource.com

blob: f30d1afeb390558ef8a2b31b10fa3a57c0f73297 [file] [log] [blame]
drh7d10d5a2008-08-20 16:35:101/*
2** 2008 August 18
3**
4** The author disclaims copyright to this source code. In place of
5** a legal notice, here is a blessing:
6**
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.
10**
11*************************************************************************
12**
13** This file contains routines used for walking the parser tree and
14** resolve all identifiers by associating them with a particular
15** table and column.
drh7d10d5a2008-08-20 16:35:1016*/
17#include "sqliteInt.h"
drh7d10d5a2008-08-20 16:35:1018
19/*
drhec43d802020-06-29 20:20:4020** Magic table number to mean the EXCLUDED table in an UPSERT statement.
21*/
22#define EXCLUDED_TABLE_NUMBER 2
23
24/*
drhed551b92012-08-23 19:46:1125** 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.
29**
30** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
31** is a helper function - a callback for the tree walker.
drhc37577b2020-05-24 03:38:3732**
33** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
drhed551b92012-08-23 19:46:1134*/
35static int incrAggDepth(Walker *pWalker, Expr *pExpr){
drh059b2d52014-10-24 19:28:0936 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
drhed551b92012-08-23 19:46:1137 return WRC_Continue;
38}
39static void incrAggFunctionDepth(Expr *pExpr, int N){
40 if( N>0 ){
41 Walker w;
42 memset(&w, 0, sizeof(w));
43 w.xExprCallback = incrAggDepth;
drh059b2d52014-10-24 19:28:0944 w.u.n = N;
drhed551b92012-08-23 19:46:1145 sqlite3WalkExpr(&w, pExpr);
46 }
47}
48
49/*
drh8b213892008-08-29 02:14:0250** Turn the pExpr expression into an alias for the iCol-th column of the
51** result set in pEList.
52**
drh0a8a4062012-12-07 18:38:1653** If the reference is followed by a COLLATE operator, then make sure
54** the COLLATE operator is preserved. For example:
55**
56** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
57**
58** Should be transformed into:
59**
60** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
61**
drhed551b92012-08-23 19:46:1162** The nSubquery parameter specifies how many levels of subquery the
drh41148f82015-04-23 13:37:0563** alias is removed from the original expression. The usual value is
drhed551b92012-08-23 19:46:1164** 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.
drh8b213892008-08-29 02:14:0267*/
68static 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 */
drhed551b92012-08-23 19:46:1173 int nSubquery /* Number of subqueries that the label is moving */
drh8b213892008-08-29 02:14:0274){
75 Expr *pOrig; /* The iCol-th column of the result set */
76 Expr *pDup; /* Copy of pOrig */
77 sqlite3 *db; /* The database connection */
78
79 assert( iCol>=0 && iCol<pEList->nExpr );
80 pOrig = pEList->a[iCol].pExpr;
81 assert( pOrig!=0 );
drh3c5a8102024-02-11 20:53:1482 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
83 if( pExpr->pAggInfo ) return;
drh8b213892008-08-29 02:14:0284 db = pParse->db;
drh0a8a4062012-12-07 18:38:1685 pDup = sqlite3ExprDup(db, pOrig, 0);
drh3c6edc82021-04-26 15:28:0686 if( db->mallocFailed ){
87 sqlite3ExprDelete(db, pDup);
88 pDup = 0;
89 }else{
drh3245f3b2022-07-20 16:42:4090 Expr temp;
drhc7e93f52021-02-18 00:26:1191 incrAggFunctionDepth(pDup, nSubquery);
drh4344dbd2018-06-02 11:31:1592 if( pExpr->op==TK_COLLATE ){
drhf9751072021-10-07 13:40:2993 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drh4344dbd2018-06-02 11:31:1594 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
95 }
drh3245f3b2022-07-20 16:42:4096 memcpy(&temp, pDup, sizeof(Expr));
97 memcpy(pDup, pExpr, sizeof(Expr));
98 memcpy(pExpr, &temp, sizeof(Expr));
dana51ddb12019-09-26 15:53:3799 if( ExprHasProperty(pExpr, EP_WinFunc) ){
drhfeef4472021-04-26 21:00:51100 if( ALWAYS(pExpr->y.pWin!=0) ){
drhd79cd922019-09-26 16:08:35101 pExpr->y.pWin->pOwner = pExpr;
drhd79cd922019-09-26 16:08:35102 }
dana51ddb12019-09-26 15:53:37103 }
drh95530162022-07-20 20:36:26104 sqlite3ExprDeferredDelete(pParse, pDup);
drh0a8a4062012-12-07 18:38:16105 }
drh8b213892008-08-29 02:14:02106}
107
drh3e3f1a52013-01-03 00:45:56108/*
dan81b70d92023-09-15 18:36:51109** 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
112** to ENAME_TAB.
113**
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.
118**
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
dan63702bc2023-09-15 20:57:05122** 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.
drh3e3f1a52013-01-03 00:45:56124*/
drhc4938ea2019-12-13 00:49:42125int sqlite3MatchEName(
126 const struct ExprList_item *pItem,
drh3e3f1a52013-01-03 00:45:56127 const char *zCol,
128 const char *zTab,
dan81b70d92023-09-15 18:36:51129 const char *zDb,
dan63702bc2023-09-15 20:57:05130 int *pbRowid
drh3e3f1a52013-01-03 00:45:56131){
132 int n;
drhc4938ea2019-12-13 00:49:42133 const char *zSpan;
dan81b70d92023-09-15 18:36:51134 int eEName = pItem->fg.eEName;
drha91fe452023-09-16 16:39:27135 if( eEName!=ENAME_TAB && (eEName!=ENAME_ROWID || NEVER(pbRowid==0)) ){
dan81b70d92023-09-15 18:36:51136 return 0;
137 }
dan63702bc2023-09-15 20:57:05138 assert( pbRowid==0 || *pbRowid==0 );
drhc4938ea2019-12-13 00:49:42139 zSpan = pItem->zEName;
drh3e3f1a52013-01-03 00:45:56140 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
drhdd1dd482013-02-26 12:57:42141 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
drh3e3f1a52013-01-03 00:45:56142 return 0;
143 }
144 zSpan += n+1;
145 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
drhdd1dd482013-02-26 12:57:42146 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
drh3e3f1a52013-01-03 00:45:56147 return 0;
148 }
149 zSpan += n+1;
dan81b70d92023-09-15 18:36:51150 if( zCol ){
151 if( eEName==ENAME_TAB && sqlite3StrICmp(zSpan, zCol)!=0 ) return 0;
152 if( eEName==ENAME_ROWID && sqlite3IsRowid(zCol)==0 ) return 0;
drh3e3f1a52013-01-03 00:45:56153 }
dan63702bc2023-09-15 20:57:05154 if( eEName==ENAME_ROWID ) *pbRowid = 1;
drh3e3f1a52013-01-03 00:45:56155 return 1;
156}
drhe802c5d2011-10-18 18:10:40157
drh8b213892008-08-29 02:14:02158/*
drhd0ff6012019-06-17 13:56:11159** Return TRUE if the double-quoted string mis-feature should be supported.
160*/
161static 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 ){
166 return 1;
167 }
168 return (db->flags & SQLITE_DqsDDL)!=0;
169 }else{
170 /* Currently parsing a DML statement */
171 return (db->flags & SQLITE_DqsDML)!=0;
172 }
173}
174
175/*
drh74a07982020-03-21 23:10:38176** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
177** return the appropriate colUsed mask.
178*/
179Bitmask sqlite3ExprColUsed(Expr *pExpr){
180 int n;
181 Table *pExTab;
182
183 n = pExpr->iColumn;
drh477572b2021-10-07 20:46:29184 assert( ExprUseYTab(pExpr) );
drh74a07982020-03-21 23:10:38185 pExTab = pExpr->y.pTab;
186 assert( pExTab!=0 );
drh3e4195c2023-12-13 16:45:18187 assert( n < pExTab->nCol );
drh74a07982020-03-21 23:10:38188 if( (pExTab->tabFlags & TF_HasGenerated)!=0
larrybrbc917382023-06-07 08:40:31189 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
drh74a07982020-03-21 23:10:38190 ){
191 testcase( pExTab->nCol==BMS-1 );
192 testcase( pExTab->nCol==BMS );
193 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
194 }else{
195 testcase( n==BMS-1 );
196 testcase( n==BMS );
197 if( n>=BMS ) n = BMS-1;
198 return ((Bitmask)1)<<n;
199 }
200}
201
202/*
drhbb3c62a2022-04-15 19:27:02203** 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
206** set.
207*/
208static 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 */
213){
214 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
215 if( pNew ){
drhbb3c62a2022-04-15 19:27:02216 pNew->iTable = pMatch->iCursor;
drh79a25ee2022-04-18 00:57:11217 pNew->iColumn = iColumn;
drhb204b6a2024-08-17 23:23:23218 pNew->y.pTab = pMatch->pSTab;
drhbb3c62a2022-04-15 19:27:02219 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
220 ExprSetProperty(pNew, EP_CanBeNull);
221 *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
222 }
223}
224
225/*
drh6f31eac2023-02-02 15:28:40226** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
227*/
228static 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 */
dane3eefe02024-06-05 11:36:58231 const char *zDb /* non-NULL if a database qualifier is present */
drh6f31eac2023-02-02 15:28:40232){
233 const char *zLegacy;
drh6f31eac2023-02-02 15:28:40234 assert( pTab!=0 );
235 assert( pTab->tnum==1 );
236 if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0;
237 zLegacy = pTab->zName;
drh2dd3b642023-02-02 16:30:32238 if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
239 if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
drh6f31eac2023-02-02 15:28:40240 return 1;
241 }
dane3eefe02024-06-05 11:36:58242 if( zDb==0 ) return 0;
drh2dd3b642023-02-02 16:30:32243 if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
244 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
245 }else{
246 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
drh6f31eac2023-02-02 15:28:40247 }
248 return 0;
249}
250
251/*
drh7d10d5a2008-08-20 16:35:10252** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
larrybrbc917382023-06-07 08:40:31253** that name in the set of source tables in pSrcList and make the pExpr
drh7d10d5a2008-08-20 16:35:10254** expression node refer back to that source column. The following changes
255** are made to pExpr:
256**
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
260** from pSrcList.
drheda079c2018-09-20 19:02:15261** pExpr->y.pTab Points to the Table structure of X.Y (even if
drh7d10d5a2008-08-20 16:35:10262** 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.
267**
drhb7916a72009-05-27 10:31:29268** The zDb variable is the name of the database (the "X"). This value may be
drh7d10d5a2008-08-20 16:35:10269** NULL meaning that name is of the form Y.Z or Z. Any available database
drhb7916a72009-05-27 10:31:29270** 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
drh7d10d5a2008-08-20 16:35:10272** means that the form of the name is Z and that columns from any table
273** can be used.
274**
275** If the name cannot be resolved unambiguously, leave an error message
drhf7828b52009-06-15 23:15:59276** in pParse and return WRC_Abort. Return WRC_Prune on success.
drh7d10d5a2008-08-20 16:35:10277*/
278static int lookupName(
279 Parse *pParse, /* The parsing context */
drhb7916a72009-05-27 10:31:29280 const char *zDb, /* Name of the database containing table, or NULL */
281 const char *zTab, /* Name of table containing column, or NULL */
drha67d63b2024-01-22 15:26:33282 const Expr *pRight, /* Name of the column. */
drh7d10d5a2008-08-20 16:35:10283 NameContext *pNC, /* The name context used to resolve the name */
284 Expr *pExpr /* Make this EXPR node point to the selected column */
285){
drhed551b92012-08-23 19:46:11286 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:10287 int cnt = 0; /* Number of matching column names */
dan2e8edc12023-09-16 14:42:18288 int cntTab = 0; /* Number of potential "rowid" matches */
drhed551b92012-08-23 19:46:11289 int nSubquery = 0; /* How many levels of subquery */
drh7d10d5a2008-08-20 16:35:10290 sqlite3 *db = pParse->db; /* The database connection */
drh76012942021-02-21 21:04:54291 SrcItem *pItem; /* Use for looping over pSrcList items */
292 SrcItem *pMatch = 0; /* The matching pSrcList item */
drh7d10d5a2008-08-20 16:35:10293 NameContext *pTopNC = pNC; /* First namecontext in the list */
294 Schema *pSchema = 0; /* Schema of the expression */
drheac9fab2018-04-16 13:00:50295 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
drhbb3c62a2022-04-15 19:27:02296 Table *pTab = 0; /* Table holding the row */
drhbb3c62a2022-04-15 19:27:02297 ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */
drha67d63b2024-01-22 15:26:33298 const char *zCol = pRight->u.zToken;
drh7d10d5a2008-08-20 16:35:10299
drhb7916a72009-05-27 10:31:29300 assert( pNC ); /* the name context cannot be NULL. */
301 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
drh18f86002022-04-21 13:11:26302 assert( zDb==0 || zTab!=0 );
drhc5cd1242013-09-12 16:50:49303 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
drh7d10d5a2008-08-20 16:35:10304
305 /* Initialize the node to no-match */
306 pExpr->iTable = -1;
drhebb6a652013-09-12 23:42:22307 ExprSetVVAProperty(pExpr, EP_NoReduce);
drh7d10d5a2008-08-20 16:35:10308
drh8f25d182012-12-19 02:36:45309 /* 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
312 */
313 if( zDb ){
drh1e7d43c2013-08-02 14:18:18314 testcase( pNC->ncFlags & NC_PartIdx );
315 testcase( pNC->ncFlags & NC_IsCheck );
316 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
drh31e71472015-02-09 10:20:19317 /* 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
320 ** database name. */
drh1e7d43c2013-08-02 14:18:18321 zDb = 0;
322 }else{
323 for(i=0; i<db->nDb; i++){
drh69c33822016-08-18 14:33:11324 assert( db->aDb[i].zDbSName );
325 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
drh1e7d43c2013-08-02 14:18:18326 pSchema = db->aDb[i].pSchema;
327 break;
328 }
drh8f25d182012-12-19 02:36:45329 }
dan00bd55e2020-03-20 20:54:28330 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;
335 }
drh8f25d182012-12-19 02:36:45336 }
337 }
338
drh7d10d5a2008-08-20 16:35:10339 /* Start at the inner-most context and move outward until a match is found */
drha92b81f2017-03-07 03:40:48340 assert( pNC && cnt==0 );
341 do{
drh7d10d5a2008-08-20 16:35:10342 ExprList *pEList;
343 SrcList *pSrcList = pNC->pSrcList;
344
345 if( pSrcList ){
346 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
drhb204b6a2024-08-17 23:23:23347 pTab = pItem->pSTab;
drhf4366202008-08-25 12:14:08348 assert( pTab!=0 && pTab->zName!=0 );
drh4d466692021-07-02 12:08:12349 assert( pTab->nCol>0 || pParse->nErr );
drh1521ca42024-08-19 22:48:30350 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem));
drh815b7822022-04-20 15:07:39351 if( pItem->fg.isNestedFrom ){
drh2627cbd2022-04-20 12:02:52352 /* In this case, pItem is a subquery that has been formed from a
353 ** parenthesized subset of the FROM clause terms. Example:
354 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
355 ** \_________________________/
356 ** This pItem -------------^
357 */
drh8f25d182012-12-19 02:36:45358 int hit = 0;
drh1521ca42024-08-19 22:48:30359 Select *pSel;
360 assert( pItem->fg.isSubquery );
361 assert( pItem->u4.pSubq!=0 );
362 pSel = pItem->u4.pSubq->pSelect;
363 assert( pSel!=0 );
364 pEList = pSel->pEList;
drh815b7822022-04-20 15:07:39365 assert( pEList!=0 );
366 assert( pEList->nExpr==pTab->nCol );
drh8f25d182012-12-19 02:36:45367 for(j=0; j<pEList->nExpr; j++){
dan63702bc2023-09-15 20:57:05368 int bRowid = 0; /* True if possible rowid match */
369 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){
drh18f86002022-04-21 13:11:26370 continue;
drh8f25d182012-12-19 02:36:45371 }
dan63702bc2023-09-15 20:57:05372 if( bRowid==0 ){
373 if( cnt>0 ){
374 if( pItem->fg.isUsing==0
375 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
376 ){
377 /* Two or more tables have the same column name which is
378 ** not joined by USING. This is an error. Signal as much
379 ** by clearing pFJMatch and letting cnt go above 1. */
380 sqlite3ExprListDelete(db, pFJMatch);
381 pFJMatch = 0;
382 }else
383 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
384 /* An INNER or LEFT JOIN. Use the left-most table */
385 continue;
386 }else
387 if( (pItem->fg.jointype & JT_LEFT)==0 ){
388 /* A RIGHT JOIN. Use the right-most table */
389 cnt = 0;
390 sqlite3ExprListDelete(db, pFJMatch);
391 pFJMatch = 0;
392 }else{
393 /* For a FULL JOIN, we must construct a coalesce() func */
394 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
395 }
drh18f86002022-04-21 13:11:26396 }
dan63702bc2023-09-15 20:57:05397 cnt++;
398 hit = 1;
399 }else if( cnt>0 ){
dan2e8edc12023-09-16 14:42:18400 /* This is a potential rowid match, but there has already been
401 ** a real match found. So this can be ignored. */
dan63702bc2023-09-15 20:57:05402 continue;
drh18f86002022-04-21 13:11:26403 }
dan63702bc2023-09-15 20:57:05404 cntTab++;
drh18f86002022-04-21 13:11:26405 pMatch = pItem;
406 pExpr->iColumn = j;
drhd88fd532022-05-02 20:49:30407 pEList->a[j].fg.bUsed = 1;
dan2e8edc12023-09-16 14:42:18408
409 /* rowid cannot be part of a USING clause - assert() this. */
410 assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 );
drhd88fd532022-05-02 20:49:30411 if( pEList->a[j].fg.bUsingTerm ) break;
drh8f25d182012-12-19 02:36:45412 }
413 if( hit || zTab==0 ) continue;
414 }
drh18f86002022-04-21 13:11:26415 assert( zDb==0 || zTab!=0 );
drh7d10d5a2008-08-20 16:35:10416 if( zTab ){
drh18f86002022-04-21 13:11:26417 if( zDb ){
418 if( pTab->pSchema!=pSchema ) continue;
419 if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
420 }
drh6f31eac2023-02-02 15:28:40421 if( pItem->zAlias!=0 ){
422 if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
423 continue;
424 }
425 }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
426 if( pTab->tnum!=1 ) continue;
dane3eefe02024-06-05 11:36:58427 if( !isValidSchemaTableName(zTab, pTab, zDb) ) continue;
drh7d10d5a2008-08-20 16:35:10428 }
drh477572b2021-10-07 20:46:29429 assert( ExprUseYTab(pExpr) );
danc9461ec2018-08-29 21:00:16430 if( IN_RENAME_OBJECT && pItem->zAlias ){
drheda079c2018-09-20 19:02:15431 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
danc9461ec2018-08-29 21:00:16432 }
drh7d10d5a2008-08-20 16:35:10433 }
drh9d90a3a2025-02-08 14:15:42434 j = sqlite3ColumnIndex(pTab, zCol);
435 if( j>=0 ){
436 if( cnt>0 ){
437 if( pItem->fg.isUsing==0
438 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
439 ){
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);
444 pFJMatch = 0;
445 }else
446 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
447 /* An INNER or LEFT JOIN. Use the left-most table */
448 continue;
449 }else
450 if( (pItem->fg.jointype & JT_LEFT)==0 ){
451 /* A RIGHT JOIN. Use the right-most table */
452 cnt = 0;
453 sqlite3ExprListDelete(db, pFJMatch);
454 pFJMatch = 0;
455 }else{
456 /* For a FULL JOIN, we must construct a coalesce() func */
457 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
drhe802c5d2011-10-18 18:10:40458 }
drh9d90a3a2025-02-08 14:15:42459 }
460 cnt++;
461 pMatch = pItem;
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);
drh7d10d5a2008-08-20 16:35:10466 }
467 }
danb9248ef2021-07-01 18:19:17468 if( 0==cnt && VisibleRowid(pTab) ){
drhe9feb0a2024-03-19 16:34:32469 /* pTab is a potential ROWID match. Keep track of it and match
470 ** the ROWID later if that seems appropriate. (Search for "cntTab"
471 ** to find related code.) Only allow a ROWID match if there is
472 ** a single ROWID match candidate.
473 */
474#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
475 /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match
476 ** if there is a single VIEW candidate or if there is a single
477 ** non-VIEW candidate plus multiple VIEW candidates. In other
478 ** words non-VIEW candidate terms take precedence over VIEWs.
479 */
480 if( cntTab==0
481 || (cntTab==1
drh7d24e6b2024-09-24 00:53:27482 && pMatch!=0
drhb204b6a2024-08-17 23:23:23483 && ALWAYS(pMatch->pSTab!=0)
484 && (pMatch->pSTab->tabFlags & TF_Ephemeral)!=0
drhe9feb0a2024-03-19 16:34:32485 && (pTab->tabFlags & TF_Ephemeral)==0)
486 ){
487 cntTab = 1;
488 pMatch = pItem;
489 }else{
490 cntTab++;
491 }
492#else
493 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
494 ** simpler since we require exactly one candidate, which will
495 ** always be a non-VIEW
496 */
danb9248ef2021-07-01 18:19:17497 cntTab++;
498 pMatch = pItem;
drhe9feb0a2024-03-19 16:34:32499#endif
danb9248ef2021-07-01 18:19:17500 }
drh7d10d5a2008-08-20 16:35:10501 }
drh8f25d182012-12-19 02:36:45502 if( pMatch ){
503 pExpr->iTable = pMatch->iCursor;
drh477572b2021-10-07 20:46:29504 assert( ExprUseYTab(pExpr) );
drhb204b6a2024-08-17 23:23:23505 pExpr->y.pTab = pMatch->pSTab;
drha76ac882022-04-08 19:20:12506 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
drh72673a22014-12-04 16:27:17507 ExprSetProperty(pExpr, EP_CanBeNull);
508 }
drheda079c2018-09-20 19:02:15509 pSchema = pExpr->y.pTab->pSchema;
drh8f25d182012-12-19 02:36:45510 }
511 } /* if( pSrcList ) */
drh7d10d5a2008-08-20 16:35:10512
drheac9fab2018-04-16 13:00:50513#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
larrybrbc917382023-06-07 08:40:31514 /* If we have not already resolved the name, then maybe
drheac9fab2018-04-16 13:00:50515 ** it is a new.* or old.* trigger argument reference. Or
drhd5101972021-02-08 13:41:17516 ** maybe it is an excluded.* from an upsert. Or maybe it is
517 ** a reference in the RETURNING clause to a table being modified.
drh7d10d5a2008-08-20 16:35:10518 */
drhd5101972021-02-08 13:41:17519 if( cnt==0 && zDb==0 ){
drheac9fab2018-04-16 13:00:50520 pTab = 0;
521#ifndef SQLITE_OMIT_TRIGGER
522 if( pParse->pTriggerTab!=0 ){
523 int op = pParse->eTriggerOp;
524 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
drh22af5842021-03-31 23:56:55525 if( pParse->bReturning ){
526 if( (pNC->ncFlags & NC_UBaseReg)!=0
drh68e976b2023-03-21 14:20:10527 && ALWAYS(zTab==0
dan72814932024-05-02 18:16:23528 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0
529 || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0))
drh22af5842021-03-31 23:56:55530 ){
drhd75aeee2021-03-31 17:42:24531 pExpr->iTable = op!=TK_DELETE;
532 pTab = pParse->pTriggerTab;
533 }
534 }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
drheac9fab2018-04-16 13:00:50535 pExpr->iTable = 1;
536 pTab = pParse->pTriggerTab;
drhb8352472021-01-29 19:32:17537 }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
drheac9fab2018-04-16 13:00:50538 pExpr->iTable = 0;
539 pTab = pParse->pTriggerTab;
540 }
drh7d10d5a2008-08-20 16:35:10541 }
drheac9fab2018-04-16 13:00:50542#endif /* SQLITE_OMIT_TRIGGER */
543#ifndef SQLITE_OMIT_UPSERT
drhd5101972021-02-08 13:41:17544 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
drheac9fab2018-04-16 13:00:50545 Upsert *pUpsert = pNC->uNC.pUpsert;
546 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
drhb204b6a2024-08-17 23:23:23547 pTab = pUpsert->pUpsertSrc->a[0].pSTab;
drhec43d802020-06-29 20:20:40548 pExpr->iTable = EXCLUDED_TABLE_NUMBER;
drheac9fab2018-04-16 13:00:50549 }
550 }
551#endif /* SQLITE_OMIT_UPSERT */
drh7d10d5a2008-08-20 16:35:10552
larrybrbc917382023-06-07 08:40:31553 if( pTab ){
drh7d10d5a2008-08-20 16:35:10554 int iCol;
drh7d10d5a2008-08-20 16:35:10555 pSchema = pTab->pSchema;
556 cntTab++;
drh9d90a3a2025-02-08 14:15:42557 iCol = sqlite3ColumnIndex(pTab, zCol);
558 if( iCol>=0 ){
559 if( pTab->iPKey==iCol ) iCol = -1;
560 }else{
561 if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
562 iCol = -1;
563 }else{
564 iCol = pTab->nCol;
drh7d10d5a2008-08-20 16:35:10565 }
566 }
dan2bd93512009-08-31 08:22:46567 if( iCol<pTab->nCol ){
568 cnt++;
dana7e16a22021-03-05 15:10:33569 pMatch = 0;
drheac9fab2018-04-16 13:00:50570#ifndef SQLITE_OMIT_UPSERT
drhec43d802020-06-29 20:20:40571 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
drh99160482018-04-18 01:34:39572 testcase( iCol==(-1) );
drh477572b2021-10-07 20:46:29573 assert( ExprUseYTab(pExpr) );
danc9461ec2018-08-29 21:00:16574 if( IN_RENAME_OBJECT ){
dan85a9d502018-08-24 20:10:22575 pExpr->iColumn = iCol;
drheda079c2018-09-20 19:02:15576 pExpr->y.pTab = pTab;
dan85a9d502018-08-24 20:10:22577 eNewExprOp = TK_COLUMN;
578 }else{
drhb8fec212020-06-29 20:26:50579 pExpr->iTable = pNC->uNC.pUpsert->regData +
580 sqlite3TableColumnToStorage(pTab, iCol);
dan85a9d502018-08-24 20:10:22581 eNewExprOp = TK_REGISTER;
dan85a9d502018-08-24 20:10:22582 }
drheac9fab2018-04-16 13:00:50583 }else
drh0a6259f2018-04-16 13:26:53584#endif /* SQLITE_OMIT_UPSERT */
drheac9fab2018-04-16 13:00:50585 {
drh477572b2021-10-07 20:46:29586 assert( ExprUseYTab(pExpr) );
drheda079c2018-09-20 19:02:15587 pExpr->y.pTab = pTab;
drh552562c2021-02-04 20:52:20588 if( pParse->bReturning ){
589 eNewExprOp = TK_REGISTER;
drh41584df2021-12-29 04:31:54590 pExpr->op2 = TK_COLUMN;
drh475e76d2023-01-13 19:29:46591 pExpr->iColumn = iCol;
dan0d080722021-03-05 15:29:22592 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
593 sqlite3TableColumnToStorage(pTab, iCol) + 1;
drh552562c2021-02-04 20:52:20594 }else{
595 pExpr->iColumn = (i16)iCol;
596 eNewExprOp = TK_TRIGGER;
597#ifndef SQLITE_OMIT_TRIGGER
drh8873aea2021-02-06 14:37:36598 if( iCol<0 ){
599 pExpr->affExpr = SQLITE_AFF_INTEGER;
600 }else if( pExpr->iTable==0 ){
drh552562c2021-02-04 20:52:20601 testcase( iCol==31 );
602 testcase( iCol==32 );
603 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
604 }else{
605 testcase( iCol==31 );
606 testcase( iCol==32 );
607 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
608 }
drh0a6259f2018-04-16 13:26:53609#endif /* SQLITE_OMIT_TRIGGER */
drh552562c2021-02-04 20:52:20610 }
dan2bd93512009-08-31 08:22:46611 }
dan2bd93512009-08-31 08:22:46612 }
drh7d10d5a2008-08-20 16:35:10613 }
614 }
drheac9fab2018-04-16 13:00:50615#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
drh7d10d5a2008-08-20 16:35:10616
617 /*
618 ** Perhaps the name is a reference to the ROWID
619 */
drh4cbc54b2015-09-19 03:07:30620 if( cnt==0
dana10c2a92024-03-19 14:55:49621 && cntTab>=1
drh4cbc54b2015-09-19 03:07:30622 && pMatch
drh81f7b372019-10-16 12:18:59623 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
drh4cbc54b2015-09-19 03:07:30624 && sqlite3IsRowid(zCol)
drhb204b6a2024-08-17 23:23:23625 && ALWAYS(VisibleRowid(pMatch->pSTab) || pMatch->fg.isNestedFrom)
drh4cbc54b2015-09-19 03:07:30626 ){
dana10c2a92024-03-19 14:55:49627 cnt = cntTab;
drh1152def2024-04-07 18:23:30628#if SQLITE_ALLOW_ROWID_IN_VIEW+0==2
drhb204b6a2024-08-17 23:23:23629 if( pMatch->pSTab!=0 && IsView(pMatch->pSTab) ){
drh1152def2024-04-07 18:23:30630 eNewExprOp = TK_NULL;
631 }
632#endif
dan63702bc2023-09-15 20:57:05633 if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1;
drh11949042019-08-05 18:01:42634 pExpr->affExpr = SQLITE_AFF_INTEGER;
drh7d10d5a2008-08-20 16:35:10635 }
636
637 /*
638 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
639 ** might refer to an result-set alias. This happens, for example, when
640 ** we are resolving names in the WHERE clause of the following command:
641 **
642 ** SELECT a+b AS x FROM table WHERE x<10;
643 **
644 ** In cases like this, replace pExpr with a copy of the expression that
645 ** forms the result set entry ("a+b" in the example) and return immediately.
646 ** Note that the expression in the result set should have already been
647 ** resolved by the time the WHERE clause is resolved.
drhe35463b2013-08-15 20:24:27648 **
649 ** The ability to use an output result-set column in the WHERE, GROUP BY,
drh5579d592015-08-26 14:01:41650 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
drhe35463b2013-08-15 20:24:27651 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
drh5579d592015-08-26 14:01:41652 ** is supported for backwards compatibility only. Hence, we issue a warning
drhe35463b2013-08-15 20:24:27653 ** on sqlite3_log() whenever the capability is used.
drh7d10d5a2008-08-20 16:35:10654 */
drhde0e1b12021-04-16 22:53:57655 if( cnt==0
656 && (pNC->ncFlags & NC_UEList)!=0
drh25c3b8c2018-04-16 10:34:13657 && zTab==0
drha3a5bd92013-04-13 19:59:58658 ){
drh25c3b8c2018-04-16 10:34:13659 pEList = pNC->uNC.pEList;
660 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:10661 for(j=0; j<pEList->nExpr; j++){
drh9fc1b9a2020-01-02 22:23:01662 char *zAs = pEList->a[j].zEName;
drhd88fd532022-05-02 20:49:30663 if( pEList->a[j].fg.eEName==ENAME_NAME
dan607dd6e2020-01-03 14:27:08664 && sqlite3_stricmp(zAs, zCol)==0
drhc4938ea2019-12-13 00:49:42665 ){
drh8b213892008-08-29 02:14:02666 Expr *pOrig;
drh7d10d5a2008-08-20 16:35:10667 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
drha4eeccd2021-10-07 17:43:30668 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
669 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
drh7d10d5a2008-08-20 16:35:10670 pOrig = pEList->a[j].pExpr;
drha51009b2012-05-21 19:11:25671 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
drh7d10d5a2008-08-20 16:35:10672 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
drhf7828b52009-06-15 23:15:59673 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10674 }
dane3735bf2019-12-27 19:46:07675 if( ExprHasProperty(pOrig, EP_Win)
676 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
677 ){
dan4ded26a2019-03-28 16:15:05678 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
679 return WRC_Abort;
680 }
dan3bafded2016-11-11 15:49:01681 if( sqlite3ExprVectorSize(pOrig)!=1 ){
682 sqlite3ErrorMsg(pParse, "row value misused");
683 return WRC_Abort;
684 }
drh6b37b762021-02-16 20:32:17685 resolveAlias(pParse, pEList, j, pExpr, nSubquery);
drh7d10d5a2008-08-20 16:35:10686 cnt = 1;
687 pMatch = 0;
688 assert( zTab==0 && zDb==0 );
danc9461ec2018-08-29 21:00:16689 if( IN_RENAME_OBJECT ){
dan1b0c5de2018-08-24 16:04:26690 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
691 }
drhb7916a72009-05-27 10:31:29692 goto lookupname_end;
drh7d10d5a2008-08-20 16:35:10693 }
larrybrbc917382023-06-07 08:40:31694 }
drh7d10d5a2008-08-20 16:35:10695 }
696
697 /* Advance to the next name context. The loop will exit when either
698 ** we have a match (cnt>0) or when we run out of name contexts.
699 */
drha92b81f2017-03-07 03:40:48700 if( cnt ) break;
701 pNC = pNC->pNext;
702 nSubquery++;
703 }while( pNC );
704
drh7d10d5a2008-08-20 16:35:10705
706 /*
707 ** If X and Y are NULL (in other words if only the column name Z is
708 ** supplied) and the value of Z is enclosed in double-quotes, then
709 ** Z is a string literal if it doesn't match any column names. In that
710 ** case, we need to return right away and not make any changes to
711 ** pExpr.
712 **
713 ** Because no reference was made to outer contexts, the pNC->nRef
714 ** fields are not changed in any context.
715 */
drh007c8432018-02-26 03:20:18716 if( cnt==0 && zTab==0 ){
drh171d16b2018-02-26 20:15:54717 assert( pExpr->op==TK_ID );
drhd0ff6012019-06-17 13:56:11718 if( ExprHasProperty(pExpr,EP_DblQuoted)
719 && areDoubleQuotedStringsEnabled(db, pTopNC)
dan0d925712019-05-20 17:14:25720 ){
drhec8fc622018-12-06 16:11:14721 /* If a double-quoted identifier does not match any known column name,
722 ** then treat it as a string.
723 **
724 ** This hack was added in the early days of SQLite in a misguided attempt
725 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
726 ** I now sorely regret putting in this hack. The effect of this hack is
727 ** that misspelled identifier names are silently converted into strings
728 ** rather than causing an error, to the frustration of countless
729 ** programmers. To all those frustrated programmers, my apologies.
730 **
731 ** Someday, I hope to get rid of this hack. Unfortunately there is
732 ** a huge amount of legacy SQL that uses it. So for now, we just
733 ** issue a warning.
734 */
735 sqlite3_log(SQLITE_WARNING,
736 "double-quoted string literal: \"%w\"", zCol);
drh893bd372018-12-07 16:32:11737#ifdef SQLITE_ENABLE_NORMALIZE
drh1a6c2b12018-12-10 20:01:40738 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
drh893bd372018-12-07 16:32:11739#endif
drh007c8432018-02-26 03:20:18740 pExpr->op = TK_STRING;
drh477572b2021-10-07 20:46:29741 memset(&pExpr->y, 0, sizeof(pExpr->y));
drh007c8432018-02-26 03:20:18742 return WRC_Prune;
743 }
drh171d16b2018-02-26 20:15:54744 if( sqlite3ExprIdToTrueFalse(pExpr) ){
drh007c8432018-02-26 03:20:18745 return WRC_Prune;
746 }
drh7d10d5a2008-08-20 16:35:10747 }
748
drhbb3c62a2022-04-15 19:27:02749 /*
750 ** cnt==0 means there was not match.
751 ** cnt>1 means there were two or more matches.
752 **
753 ** cnt==0 is always an error. cnt>1 is often an error, but might
754 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
755 */
756 assert( pFJMatch==0 || cnt>0 );
drhbdbda1e2022-04-16 12:40:52757 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
drh7d10d5a2008-08-20 16:35:10758 if( cnt!=1 ){
759 const char *zErr;
drhbb3c62a2022-04-15 19:27:02760 if( pFJMatch ){
761 if( pFJMatch->nExpr==cnt-1 ){
drh977eef62022-04-16 13:55:48762 if( ExprHasProperty(pExpr,EP_Leaf) ){
763 ExprClearProperty(pExpr,EP_Leaf);
764 }else{
drhbdbda1e2022-04-16 12:40:52765 sqlite3ExprDelete(db, pExpr->pLeft);
766 pExpr->pLeft = 0;
767 sqlite3ExprDelete(db, pExpr->pRight);
768 pExpr->pRight = 0;
769 }
drhbb3c62a2022-04-15 19:27:02770 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
771 pExpr->op = TK_FUNCTION;
772 pExpr->u.zToken = "coalesce";
773 pExpr->x.pList = pFJMatch;
drha3e25182022-04-17 23:46:18774 cnt = 1;
drhbb3c62a2022-04-15 19:27:02775 goto lookupname_end;
776 }else{
777 sqlite3ExprListDelete(db, pFJMatch);
778 pFJMatch = 0;
779 }
780 }
drh7d10d5a2008-08-20 16:35:10781 zErr = cnt==0 ? "no such column" : "ambiguous column name";
782 if( zDb ){
783 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
784 }else if( zTab ){
785 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
drha67d63b2024-01-22 15:26:33786 }else if( cnt==0 && ExprHasProperty(pRight,EP_DblQuoted) ){
drh727b35c2024-01-22 20:49:47787 sqlite3ErrorMsg(pParse, "%s: \"%s\" - should this be a"
drha67d63b2024-01-22 15:26:33788 " string literal in single-quotes?",
drh727b35c2024-01-22 20:49:47789 zErr, zCol);
drh7d10d5a2008-08-20 16:35:10790 }else{
791 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
792 }
drh4f77c922022-02-05 23:11:19793 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
dan1db95102010-06-28 10:15:19794 pParse->checkSchema = 1;
drh050611a2021-04-10 13:37:04795 pTopNC->nNcErr++;
drh60c435d2023-12-19 12:49:35796 eNewExprOp = TK_NULL;
drh7d10d5a2008-08-20 16:35:10797 }
drhbb3c62a2022-04-15 19:27:02798 assert( pFJMatch==0 );
drh7d10d5a2008-08-20 16:35:10799
drhbdbda1e2022-04-16 12:40:52800 /* Remove all substructure from pExpr */
801 if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
802 sqlite3ExprDelete(db, pExpr->pLeft);
803 pExpr->pLeft = 0;
804 sqlite3ExprDelete(db, pExpr->pRight);
805 pExpr->pRight = 0;
806 ExprSetProperty(pExpr, EP_Leaf);
807 }
808
drh7d10d5a2008-08-20 16:35:10809 /* If a column from a table in pSrcList is referenced, then record
810 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
drhbf9d0992019-12-08 00:06:39811 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
812 ** set if the 63rd or any subsequent column is used.
drh522ebfa2019-11-21 19:37:00813 **
814 ** The colUsed mask is an optimization used to help determine if an
815 ** index is a covering index. The correct answer is still obtained
drhbf9d0992019-12-08 00:06:39816 ** if the mask contains extra set bits. However, it is important to
817 ** avoid setting bits beyond the maximum column number of the table.
818 ** (See ticket [b92e5e8ec2cdbaa1]).
drh522ebfa2019-11-21 19:37:00819 **
drhbf9d0992019-12-08 00:06:39820 ** If a generated column is referenced, set bits for every column
821 ** of the table.
drh7d10d5a2008-08-20 16:35:10822 */
drh04624992024-05-18 20:00:08823 if( pMatch ){
824 if( pExpr->iColumn>=0 ){
825 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
826 }else{
827 pMatch->fg.rowidUsed = 1;
828 }
drh7d10d5a2008-08-20 16:35:10829 }
830
drheac9fab2018-04-16 13:00:50831 pExpr->op = eNewExprOp;
drhb7916a72009-05-27 10:31:29832lookupname_end:
drh7d10d5a2008-08-20 16:35:10833 if( cnt==1 ){
834 assert( pNC!=0 );
drh2d7a6912021-03-01 21:43:25835#ifndef SQLITE_OMIT_AUTHORIZATION
drh552562c2021-02-04 20:52:20836 if( pParse->db->xAuth
drh29f6a362021-02-05 17:34:47837 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
drh552562c2021-02-04 20:52:20838 ){
drha3a5bd92013-04-13 19:59:58839 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
840 }
drh2d7a6912021-03-01 21:43:25841#endif
drh7d10d5a2008-08-20 16:35:10842 /* Increment the nRef value on all name contexts from TopNC up to
843 ** the point where the name matched. */
844 for(;;){
845 assert( pTopNC!=0 );
846 pTopNC->nRef++;
847 if( pTopNC==pNC ) break;
848 pTopNC = pTopNC->pNext;
849 }
drhf7828b52009-06-15 23:15:59850 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:10851 } else {
drhf7828b52009-06-15 23:15:59852 return WRC_Abort;
drh7d10d5a2008-08-20 16:35:10853 }
854}
855
856/*
danf7b0b0a2009-10-19 15:52:32857** Allocate and return a pointer to an expression to load the column iCol
drh9e481652010-04-08 17:35:34858** from datasource iSrc in SrcList pSrc.
danf7b0b0a2009-10-19 15:52:32859*/
860Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
861 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
862 if( p ){
drh76012942021-02-21 21:04:54863 SrcItem *pItem = &pSrc->a[iSrc];
drh477572b2021-10-07 20:46:29864 Table *pTab;
865 assert( ExprUseYTab(p) );
drhb204b6a2024-08-17 23:23:23866 pTab = p->y.pTab = pItem->pSTab;
danf7b0b0a2009-10-19 15:52:32867 p->iTable = pItem->iCursor;
drheda079c2018-09-20 19:02:15868 if( p->y.pTab->iPKey==iCol ){
danf7b0b0a2009-10-19 15:52:32869 p->iColumn = -1;
870 }else{
drh8677d302009-11-04 13:17:14871 p->iColumn = (ynVar)iCol;
drh0824d5b2019-12-09 18:22:17872 if( (pTab->tabFlags & TF_HasGenerated)!=0
873 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
874 ){
875 testcase( pTab->nCol==63 );
876 testcase( pTab->nCol==64 );
877 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
drh926f7962019-12-09 17:14:48878 }else{
879 testcase( iCol==BMS );
880 testcase( iCol==BMS-1 );
881 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
882 }
danf7b0b0a2009-10-19 15:52:32883 }
danf7b0b0a2009-10-19 15:52:32884 }
885 return p;
886}
887
888/*
drha514b8e2015-08-25 00:27:06889** Report an error that an expression is not valid for some set of
drh03bf26d2015-08-31 21:16:36890** pNC->ncFlags values determined by validMask.
drh77318a32019-12-12 15:19:18891**
892** static void notValid(
893** Parse *pParse, // Leave error message here
larrybrbc917382023-06-07 08:40:31894** NameContext *pNC, // The name context
drh77318a32019-12-12 15:19:18895** const char *zMsg, // Type of error
896** int validMask, // Set of contexts for which prohibited
897** Expr *pExpr // Invalidate this expression on error
898** ){...}
899**
900** As an optimization, since the conditional is almost always false
901** (because errors are rare), the conditional is moved outside of the
902** function call using a macro.
drh3780be12013-07-31 19:05:22903*/
drh77318a32019-12-12 15:19:18904static void notValidImpl(
905 Parse *pParse, /* Leave error message here */
906 NameContext *pNC, /* The name context */
907 const char *zMsg, /* Type of error */
drh62fc0692022-02-06 00:30:04908 Expr *pExpr, /* Invalidate this expression on error */
909 Expr *pError /* Associate error with this expression */
drh3780be12013-07-31 19:05:22910){
drh77318a32019-12-12 15:19:18911 const char *zIn = "partial index WHERE clauses";
912 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
drh3780be12013-07-31 19:05:22913#ifndef SQLITE_OMIT_CHECK
drh77318a32019-12-12 15:19:18914 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
drha514b8e2015-08-25 00:27:06915#endif
drh81f7b372019-10-16 12:18:59916#ifndef SQLITE_OMIT_GENERATED_COLUMNS
drh77318a32019-12-12 15:19:18917 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
drh81f7b372019-10-16 12:18:59918#endif
drh77318a32019-12-12 15:19:18919 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
920 if( pExpr ) pExpr->op = TK_NULL;
drh62fc0692022-02-06 00:30:04921 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
drh3780be12013-07-31 19:05:22922}
drh62fc0692022-02-06 00:30:04923#define sqlite3ResolveNotValid(P,N,M,X,E,R) \
drh77318a32019-12-12 15:19:18924 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
drh62fc0692022-02-06 00:30:04925 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
drh3780be12013-07-31 19:05:22926
drhcca9f3d2013-09-06 15:23:29927/*
928** Expression p should encode a floating point value between 1.0 and 0.0.
drhdaa4cdf2025-07-18 19:17:32929** Return 134,217,728 (2^27) times this value. Or return -1 if p is not
930** a floating point value between 1.0 and 0.0.
drhcca9f3d2013-09-06 15:23:29931*/
932static int exprProbability(Expr *p){
933 double r = -1.0;
934 if( p->op!=TK_FLOAT ) return -1;
drhf9751072021-10-07 13:40:29935 assert( !ExprHasProperty(p, EP_IntValue) );
drhcca9f3d2013-09-06 15:23:29936 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
drh09328c02013-09-11 14:34:58937 assert( r>=0.0 );
938 if( r>1.0 ) return -1;
drhd05ab6a2014-10-25 13:42:16939 return (int)(r*134217728.0);
drhcca9f3d2013-09-06 15:23:29940}
drh3780be12013-07-31 19:05:22941
942/*
drh7d10d5a2008-08-20 16:35:10943** This routine is callback for sqlite3WalkExpr().
944**
945** Resolve symbolic names into TK_COLUMN operators for the current
946** node in the expression tree. Return 0 to continue the search down
947** the tree or 2 to abort the tree walk.
948**
949** This routine also does error checking and name resolution for
950** function names. The operator for aggregate functions is changed
951** to TK_AGG_FUNCTION.
952*/
953static int resolveExprStep(Walker *pWalker, Expr *pExpr){
954 NameContext *pNC;
955 Parse *pParse;
956
drh7d10d5a2008-08-20 16:35:10957 pNC = pWalker->u.pNC;
958 assert( pNC!=0 );
959 pParse = pNC->pParse;
960 assert( pParse==pWalker->pParse );
961
drh7d10d5a2008-08-20 16:35:10962#ifndef NDEBUG
963 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
964 SrcList *pSrcList = pNC->pSrcList;
965 int i;
966 for(i=0; i<pNC->pSrcList->nSrc; i++){
967 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
968 }
969 }
970#endif
971 switch( pExpr->op ){
drh41204f12008-10-06 13:54:35972
drh41204f12008-10-06 13:54:35973 /* The special operator TK_ROW means use the rowid for the first
974 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
larrybrbc917382023-06-07 08:40:31975 ** clause processing on UPDATE and DELETE statements, and by
danbe952c12020-07-13 20:10:29976 ** UPDATE ... FROM statement processing.
drh41204f12008-10-06 13:54:35977 */
978 case TK_ROW: {
979 SrcList *pSrcList = pNC->pSrcList;
drh76012942021-02-21 21:04:54980 SrcItem *pItem;
danf2972b62020-04-29 20:11:01981 assert( pSrcList && pSrcList->nSrc>=1 );
drh2fba3942017-11-09 03:55:09982 pItem = pSrcList->a;
drh41204f12008-10-06 13:54:35983 pExpr->op = TK_COLUMN;
drh477572b2021-10-07 20:46:29984 assert( ExprUseYTab(pExpr) );
drhb204b6a2024-08-17 23:23:23985 pExpr->y.pTab = pItem->pSTab;
drh41204f12008-10-06 13:54:35986 pExpr->iTable = pItem->iCursor;
dan576d5a82020-07-15 18:30:01987 pExpr->iColumn--;
drhaf97c3f2019-08-08 18:49:16988 pExpr->affExpr = SQLITE_AFF_INTEGER;
drh41204f12008-10-06 13:54:35989 break;
990 }
drh41204f12008-10-06 13:54:35991
drh45e4cb82021-03-09 19:52:15992 /* An optimization: Attempt to convert
dan8ddf6862021-02-26 20:14:32993 **
drh45e4cb82021-03-09 19:52:15994 ** "expr IS NOT NULL" --> "TRUE"
995 ** "expr IS NULL" --> "FALSE"
996 **
997 ** if we can prove that "expr" is never NULL. Call this the
998 ** "NOT NULL strength reduction optimization".
999 **
1000 ** If this optimization occurs, also restore the NameContext ref-counts
1001 ** to the state they where in before the "column" LHS expression was
1002 ** resolved. This prevents "column" from being counted as having been
1003 ** referenced, which might prevent a SELECT from being erroneously
1004 ** marked as correlated.
drh61b77a62024-03-08 21:37:181005 **
1006 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
1007 ** can still evaluate to NULL even though it is marked as NOT NULL.
1008 ** Example:
1009 **
1010 ** CREATE TABLE t1(a INT NOT NULL);
1011 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
1012 **
1013 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
1014 ** here because at the time this case is hit, we do not yet know whether
1015 ** or not t1 is being aggregated. We have to assume the worst and omit
1016 ** the optimization. The only time it is safe to apply this optimization
1017 ** is within the WHERE clause.
dan8ddf6862021-02-26 20:14:321018 */
1019 case TK_NOTNULL:
1020 case TK_ISNULL: {
1021 int anRef[8];
1022 NameContext *p;
1023 int i;
larrybrbc917382023-06-07 08:40:311024 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
dan8ddf6862021-02-26 20:14:321025 anRef[i] = p->nRef;
1026 }
1027 sqlite3WalkExpr(pWalker, pExpr->pLeft);
drh61b77a62024-03-08 21:37:181028 if( IN_RENAME_OBJECT ) return WRC_Prune;
1029 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
1030 /* The expression can be NULL. So the optimization does not apply */
1031 return WRC_Prune;
dan8ddf6862021-02-26 20:14:321032 }
drh61b77a62024-03-08 21:37:181033
1034 for(i=0, p=pNC; p; p=p->pNext, i++){
1035 if( (p->ncFlags & NC_Where)==0 ){
1036 return WRC_Prune; /* Not in a WHERE clause. Unsafe to optimize. */
1037 }
1038 }
1039 testcase( ExprHasProperty(pExpr, EP_OuterON) );
1040 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1041#if TREETRACE_ENABLED
1042 if( sqlite3TreeTrace & 0x80000 ){
1043 sqlite3DebugPrintf(
1044 "NOT NULL strength reduction converts the following to %d:\n",
1045 pExpr->op==TK_NOTNULL
1046 );
1047 sqlite3ShowExpr(pExpr);
1048 }
1049#endif /* TREETRACE_ENABLED */
1050 pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
1051 pExpr->flags |= EP_IntValue;
1052 pExpr->op = TK_INTEGER;
1053 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1054 p->nRef = anRef[i];
1055 }
1056 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
1057 pExpr->pLeft = 0;
dan8ddf6862021-02-26 20:14:321058 return WRC_Prune;
1059 }
1060
drh3cf48e32017-03-07 03:25:521061 /* A column name: ID
1062 ** Or table name and column name: ID.ID
drh7d10d5a2008-08-20 16:35:101063 ** Or a database, table and column: ID.ID.ID
drh3cf48e32017-03-07 03:25:521064 **
1065 ** The TK_ID and TK_OUT cases are combined so that there will only
larrybrbc917382023-06-07 08:40:311066 ** be one call to lookupName(). Then the compiler will in-line
drh3cf48e32017-03-07 03:25:521067 ** lookupName() for a size reduction and performance increase.
drh7d10d5a2008-08-20 16:35:101068 */
drh3cf48e32017-03-07 03:25:521069 case TK_ID:
drh7d10d5a2008-08-20 16:35:101070 case TK_DOT: {
drhb7916a72009-05-27 10:31:291071 const char *zTable;
1072 const char *zDb;
drh7d10d5a2008-08-20 16:35:101073 Expr *pRight;
1074
drh3cf48e32017-03-07 03:25:521075 if( pExpr->op==TK_ID ){
drhb7916a72009-05-27 10:31:291076 zDb = 0;
drh3cf48e32017-03-07 03:25:521077 zTable = 0;
drhf9751072021-10-07 13:40:291078 assert( !ExprHasProperty(pExpr, EP_IntValue) );
drha67d63b2024-01-22 15:26:331079 pRight = pExpr;
drh7d10d5a2008-08-20 16:35:101080 }else{
danc9461ec2018-08-29 21:00:161081 Expr *pLeft = pExpr->pLeft;
drh77318a32019-12-12 15:19:181082 testcase( pNC->ncFlags & NC_IdxExpr );
1083 testcase( pNC->ncFlags & NC_GenCol );
1084 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
drh62fc0692022-02-06 00:30:041085 NC_IdxExpr|NC_GenCol, 0, pExpr);
drh3cf48e32017-03-07 03:25:521086 pRight = pExpr->pRight;
1087 if( pRight->op==TK_ID ){
1088 zDb = 0;
drh3cf48e32017-03-07 03:25:521089 }else{
1090 assert( pRight->op==TK_DOT );
drhf9751072021-10-07 13:40:291091 assert( !ExprHasProperty(pRight, EP_IntValue) );
danc9461ec2018-08-29 21:00:161092 zDb = pLeft->u.zToken;
1093 pLeft = pRight->pLeft;
dancf8f2892018-08-09 20:47:011094 pRight = pRight->pRight;
1095 }
drh477572b2021-10-07 20:46:291096 assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
danc9461ec2018-08-29 21:00:161097 zTable = pLeft->u.zToken;
drh477572b2021-10-07 20:46:291098 assert( ExprUseYTab(pExpr) );
danc9461ec2018-08-29 21:00:161099 if( IN_RENAME_OBJECT ){
dan07e95232018-08-21 16:32:531100 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
drheda079c2018-09-20 19:02:151101 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
danc9461ec2018-08-29 21:00:161102 }
drh7d10d5a2008-08-20 16:35:101103 }
drha67d63b2024-01-22 15:26:331104 return lookupName(pParse, zDb, zTable, pRight, pNC, pExpr);
drh7d10d5a2008-08-20 16:35:101105 }
1106
1107 /* Resolve function names
1108 */
drh7d10d5a2008-08-20 16:35:101109 case TK_FUNCTION: {
drh7f0e0c72024-09-20 12:58:151110 ExprList *pList; /* The argument list */
1111 int n; /* Number of arguments */
drh7d10d5a2008-08-20 16:35:101112 int no_such_func = 0; /* True if no such function exists */
1113 int wrong_num_args = 0; /* True if wrong number of arguments */
1114 int is_agg = 0; /* True if is an aggregate function */
drh7d10d5a2008-08-20 16:35:101115 const char *zId; /* The function name. */
1116 FuncDef *pDef; /* Information about the function */
drhea678832008-12-10 19:26:221117 u8 enc = ENC(pParse->db); /* The database encoding */
dan4ded26a2019-03-28 16:15:051118 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
dan4f9adee2019-07-13 16:22:501119#ifndef SQLITE_OMIT_WINDOWFUNC
1120 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
1121#endif
drhf9751072021-10-07 13:40:291122 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
drhdb19f482023-10-18 13:58:311123 assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
drh7f0e0c72024-09-20 12:58:151124 pList = pExpr->x.pList;
1125 n = pList ? pList->nExpr : 0;
drh33e619f2009-05-28 01:00:551126 zId = pExpr->u.zToken;
drh80738d92016-02-15 00:34:161127 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
drh7d10d5a2008-08-20 16:35:101128 if( pDef==0 ){
drh80738d92016-02-15 00:34:161129 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
drh7d10d5a2008-08-20 16:35:101130 if( pDef==0 ){
1131 no_such_func = 1;
1132 }else{
1133 wrong_num_args = 1;
1134 }
1135 }else{
drh2d801512016-01-14 22:19:581136 is_agg = pDef->xFinalize!=0;
drhcca9f3d2013-09-06 15:23:291137 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
drha7d6db62019-06-11 21:02:151138 ExprSetProperty(pExpr, EP_Unlikely);
drhcca9f3d2013-09-06 15:23:291139 if( n==2 ){
1140 pExpr->iTable = exprProbability(pList->a[1].pExpr);
1141 if( pExpr->iTable<0 ){
drh31e71472015-02-09 10:20:191142 sqlite3ErrorMsg(pParse,
drh62fc0692022-02-06 00:30:041143 "second argument to %#T() must be a "
1144 "constant between 0.0 and 1.0", pExpr);
drh050611a2021-04-10 13:37:041145 pNC->nNcErr++;
drhcca9f3d2013-09-06 15:23:291146 }
1147 }else{
drh31e71472015-02-09 10:20:191148 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1149 ** equivalent to likelihood(X, 0.0625).
1150 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1151 ** short-hand for likelihood(X,0.0625).
1152 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1153 ** for likelihood(X,0.9375).
1154 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1155 ** to likelihood(X,0.9375). */
drh03202a92014-06-17 16:11:281156 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
drhd05ab6a2014-10-25 13:42:161157 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
larrybrbc917382023-06-07 08:40:311158 }
drhcca9f3d2013-09-06 15:23:291159 }
drh7d10d5a2008-08-20 16:35:101160#ifndef SQLITE_OMIT_AUTHORIZATION
drha0daa752016-09-16 11:53:101161 {
1162 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
1163 if( auth!=SQLITE_OK ){
1164 if( auth==SQLITE_DENY ){
drh62fc0692022-02-06 00:30:041165 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
1166 pExpr);
drh050611a2021-04-10 13:37:041167 pNC->nNcErr++;
drha0daa752016-09-16 11:53:101168 }
1169 pExpr->op = TK_NULL;
1170 return WRC_Prune;
drh7d10d5a2008-08-20 16:35:101171 }
drh7d10d5a2008-08-20 16:35:101172 }
drh9588ad92014-09-15 14:46:021173#endif
dand564bdb2024-10-05 18:10:021174
1175 /* If the function may call sqlite3_value_subtype(), then set the
1176 ** EP_SubtArg flag on all of its argument expressions. This prevents
1177 ** where.c from replacing the expression with a value read from an
1178 ** index on the same expression, which will not have the correct
1179 ** subtype. Also set the flag if the function expression itself is
1180 ** an EP_SubtArg expression. In this case subtypes are required as
1181 ** the function may return a value with a subtype back to its
1182 ** caller using sqlite3_result_value(). */
1183 if( (pDef->funcFlags & SQLITE_SUBTYPE)
1184 || ExprHasProperty(pExpr, EP_SubtArg)
1185 ){
1186 int ii;
1187 for(ii=0; ii<n; ii++){
1188 ExprSetProperty(pList->a[ii].pExpr, EP_SubtArg);
1189 }
1190 }
1191
drha7f910b2015-09-01 13:17:171192 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
drh1d85e402015-08-31 17:34:411193 /* For the purposes of the EP_ConstFunc flag, date and time
drh03bf26d2015-08-31 21:16:361194 ** functions and other functions that change slowly are considered
drh20cee7d2019-10-30 18:50:081195 ** constant because they are constant for the duration of one query.
1196 ** This allows them to be factored out of inner loops. */
drh63f84572015-02-09 14:07:071197 ExprSetProperty(pExpr,EP_ConstFunc);
drh1d85e402015-08-31 17:34:411198 }
1199 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
drhfe704602020-01-18 21:34:311200 /* Clearly non-deterministic functions like random(), but also
1201 ** date/time functions that use 'now', and other functions like
drha7f910b2015-09-01 13:17:171202 ** sqlite_version() that might change over time cannot be used
drhfe704602020-01-18 21:34:311203 ** in an index or generated column. Curiously, they can be used
1204 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
stephancc281372025-05-08 13:51:551205 ** allow this. */
drh77318a32019-12-12 15:19:181206 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
drh62fc0692022-02-06 00:30:041207 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
drh20cee7d2019-10-30 18:50:081208 }else{
1209 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
1210 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
drh31e71472015-02-09 10:20:191211 }
drheea8eb62018-11-26 18:09:151212 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
1213 && pParse->nested==0
drh171c50e2020-01-01 15:43:301214 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
drheea8eb62018-11-26 18:09:151215 ){
1216 /* Internal-use-only functions are disallowed unless the
drh0dfa5252020-01-08 17:28:191217 ** SQL is being compiled using sqlite3NestedParse() or
1218 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
drh7f1c1112022-02-03 18:14:221219 ** used to activate internal functions for testing purposes */
drheea8eb62018-11-26 18:09:151220 no_such_func = 1;
1221 pDef = 0;
drh2eeca202020-01-08 20:37:451222 }else
1223 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
1224 && !IN_RENAME_OBJECT
1225 ){
drh733aff32025-05-08 16:18:181226 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
drh2eeca202020-01-08 20:37:451227 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
drheea8eb62018-11-26 18:09:151228 }
drh7d10d5a2008-08-20 16:35:101229 }
dan26522d12018-06-11 18:16:511230
danc9461ec2018-08-29 21:00:161231 if( 0==IN_RENAME_OBJECT ){
dan67a9b8e2018-06-22 20:51:351232#ifndef SQLITE_OMIT_WINDOWFUNC
dandabc2682018-08-17 17:18:161233 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
dan7262ca92018-07-02 12:07:321234 || (pDef->xValue==0 && pDef->xInverse==0)
1235 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
dan26522d12018-06-11 18:16:511236 );
dan8117f112019-07-10 20:16:531237 if( pDef && pDef->xValue==0 && pWin ){
larrybrbc917382023-06-07 08:40:311238 sqlite3ErrorMsg(pParse,
drh62fc0692022-02-06 00:30:041239 "%#T() may not be used as a window function", pExpr
dandabc2682018-08-17 17:18:161240 );
drh050611a2021-04-10 13:37:041241 pNC->nNcErr++;
larrybrbc917382023-06-07 08:40:311242 }else if(
dandabc2682018-08-17 17:18:161243 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
dan8117f112019-07-10 20:16:531244 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
1245 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
dandabc2682018-08-17 17:18:161246 ){
1247 const char *zType;
dan8117f112019-07-10 20:16:531248 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
dandabc2682018-08-17 17:18:161249 zType = "window";
1250 }else{
1251 zType = "aggregate";
1252 }
drh62fc0692022-02-06 00:30:041253 sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
drh050611a2021-04-10 13:37:041254 pNC->nNcErr++;
dandabc2682018-08-17 17:18:161255 is_agg = 0;
dan26522d12018-06-11 18:16:511256 }
danc3163072018-06-23 19:29:561257#else
dandabc2682018-08-17 17:18:161258 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
drh62fc0692022-02-06 00:30:041259 sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
drh050611a2021-04-10 13:37:041260 pNC->nNcErr++;
dandabc2682018-08-17 17:18:161261 is_agg = 0;
1262 }
danc3163072018-06-23 19:29:561263#endif
drh3a843f52018-08-25 03:29:341264 else if( no_such_func && pParse->db->init.busy==0
drhcc153132016-08-04 12:35:171265#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
dandabc2682018-08-17 17:18:161266 && pParse->explain==0
drhcc153132016-08-04 12:35:171267#endif
dandabc2682018-08-17 17:18:161268 ){
drh62fc0692022-02-06 00:30:041269 sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
drh050611a2021-04-10 13:37:041270 pNC->nNcErr++;
dandabc2682018-08-17 17:18:161271 }else if( wrong_num_args ){
drh62fc0692022-02-06 00:30:041272 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
1273 pExpr);
drh050611a2021-04-10 13:37:041274 pNC->nNcErr++;
dandabc2682018-08-17 17:18:161275 }
dan5e61c1b2019-07-13 17:45:251276#ifndef SQLITE_OMIT_WINDOWFUNC
1277 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
larrybrbc917382023-06-07 08:40:311278 sqlite3ErrorMsg(pParse,
drh62fc0692022-02-06 00:30:041279 "FILTER may not be used with non-aggregate %#T()",
1280 pExpr
dan5e61c1b2019-07-13 17:45:251281 );
drh050611a2021-04-10 13:37:041282 pNC->nNcErr++;
dan5e61c1b2019-07-13 17:45:251283 }
1284#endif
drhdb19f482023-10-18 13:58:311285 else if( is_agg==0 && pExpr->pLeft ){
drh20b95f82023-10-18 22:03:481286 sqlite3ExprOrderByAggregateError(pParse, pExpr);
drhdb19f482023-10-18 13:58:311287 pNC->nNcErr++;
1288 }
dandabc2682018-08-17 17:18:161289 if( is_agg ){
dan4ded26a2019-03-28 16:15:051290 /* Window functions may not be arguments of aggregate functions.
1291 ** Or arguments of other window functions. But aggregate functions
1292 ** may be arguments for window functions. */
dan34a7d792018-06-29 20:43:331293#ifndef SQLITE_OMIT_WINDOWFUNC
dan8117f112019-07-10 20:16:531294 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
dan34a7d792018-06-29 20:43:331295#else
dandabc2682018-08-17 17:18:161296 pNC->ncFlags &= ~NC_AllowAgg;
dan34a7d792018-06-29 20:43:331297#endif
dandabc2682018-08-17 17:18:161298 }
danc3163072018-06-23 19:29:561299 }
dan15507712024-05-15 21:38:041300 else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){
dan9bf022d2019-07-19 14:32:421301 is_agg = 1;
1302 }
drh7d10d5a2008-08-20 16:35:101303 sqlite3WalkExprList(pWalker, pList);
drh030796d2012-08-23 16:18:101304 if( is_agg ){
drhdb19f482023-10-18 13:58:311305 if( pExpr->pLeft ){
1306 assert( pExpr->pLeft->op==TK_ORDER );
1307 assert( ExprUseXList(pExpr->pLeft) );
1308 sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
1309 }
dan67a9b8e2018-06-22 20:51:351310#ifndef SQLITE_OMIT_WINDOWFUNC
dan58b08d72024-08-24 15:54:151311 if( pWin && pParse->nErr==0 ){
dane3bf6322018-06-08 20:58:271312 Select *pSel = pNC->pWinSelect;
drhf9eff902024-08-24 18:42:391313 assert( ExprUseYWin(pExpr) && pWin==pExpr->y.pWin );
dan490e6f22019-04-29 11:27:581314 if( IN_RENAME_OBJECT==0 ){
drh2e2c8812019-12-13 11:42:561315 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
dane8dd6a42021-03-04 16:10:231316 if( pParse->db->mallocFailed ) break;
dan490e6f22019-04-29 11:27:581317 }
dan4f9adee2019-07-13 16:22:501318 sqlite3WalkExprList(pWalker, pWin->pPartition);
1319 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
1320 sqlite3WalkExpr(pWalker, pWin->pFilter);
dana3fcc002019-08-15 13:53:221321 sqlite3WindowLink(pSel, pWin);
dan4ded26a2019-03-28 16:15:051322 pNC->ncFlags |= NC_HasWin;
dan67a9b8e2018-06-22 20:51:351323 }else
1324#endif /* SQLITE_OMIT_WINDOWFUNC */
1325 {
drh90cf38b2021-11-08 23:24:001326 NameContext *pNC2; /* For looping up thru outer contexts */
dan86fb6e12018-05-16 20:58:071327 pExpr->op = TK_AGG_FUNCTION;
1328 pExpr->op2 = 0;
dan6ba7ab02019-07-02 11:56:471329#ifndef SQLITE_OMIT_WINDOWFUNC
dan4f9adee2019-07-13 16:22:501330 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1331 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
1332 }
dan6ba7ab02019-07-02 11:56:471333#endif
drh90cf38b2021-11-08 23:24:001334 pNC2 = pNC;
larrybrbc917382023-06-07 08:40:311335 while( pNC2
drh90cf38b2021-11-08 23:24:001336 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
1337 ){
dan5e4233a2023-11-02 21:02:531338 pExpr->op2 += (1 + pNC2->nNestedSelect);
dan86fb6e12018-05-16 20:58:071339 pNC2 = pNC2->pNext;
1340 }
dan72d1eac2019-08-05 13:19:251341 assert( pDef!=0 || IN_RENAME_OBJECT );
1342 if( pNC2 && pDef ){
dan5e4233a2023-11-02 21:02:531343 pExpr->op2 += pNC2->nNestedSelect;
dan86fb6e12018-05-16 20:58:071344 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
drhbb301232021-07-15 19:29:431345 assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
dan86fb6e12018-05-16 20:58:071346 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
drhbb301232021-07-15 19:29:431347 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
larrybrbc917382023-06-07 08:40:311348 pNC2->ncFlags |= NC_HasAgg
drhbb301232021-07-15 19:29:431349 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
1350 & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
dan86fb6e12018-05-16 20:58:071351 }
drh9588ad92014-09-15 14:46:021352 }
dan4ded26a2019-03-28 16:15:051353 pNC->ncFlags |= savedAllowFlags;
drh030796d2012-08-23 16:18:101354 }
drh7d10d5a2008-08-20 16:35:101355 /* FIX ME: Compute pExpr->affinity based on the expected return
larrybrbc917382023-06-07 08:40:311356 ** type of the function
drh7d10d5a2008-08-20 16:35:101357 */
1358 return WRC_Prune;
1359 }
1360#ifndef SQLITE_OMIT_SUBQUERY
drhdebc8f72025-07-03 00:17:271361 case TK_EXISTS:
drh7d10d5a2008-08-20 16:35:101362 case TK_SELECT:
drh7d10d5a2008-08-20 16:35:101363#endif
1364 case TK_IN: {
drh73c0fdc2009-06-15 18:32:361365 testcase( pExpr->op==TK_IN );
drhdebc8f72025-07-03 00:17:271366 testcase( pExpr->op==TK_EXISTS );
1367 testcase( pExpr->op==TK_SELECT );
drha4eeccd2021-10-07 17:43:301368 if( ExprUseXSelect(pExpr) ){
drh7d10d5a2008-08-20 16:35:101369 int nRef = pNC->nRef;
drh77318a32019-12-12 15:19:181370 testcase( pNC->ncFlags & NC_IsCheck );
1371 testcase( pNC->ncFlags & NC_PartIdx );
1372 testcase( pNC->ncFlags & NC_IdxExpr );
1373 testcase( pNC->ncFlags & NC_GenCol );
drhde6a4be2024-04-06 12:19:501374 assert( pExpr->x.pSelect );
drh8c8443a2025-07-07 19:03:501375 if( pExpr->op==TK_EXISTS ) pParse->bHasExists = 1;
drh84d90312021-09-24 19:57:321376 if( pNC->ncFlags & NC_SelfRef ){
drh62fc0692022-02-06 00:30:041377 notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
drh84d90312021-09-24 19:57:321378 }else{
1379 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1380 }
drh7d10d5a2008-08-20 16:35:101381 assert( pNC->nRef>=nRef );
1382 if( nRef!=pNC->nRef ){
1383 ExprSetProperty(pExpr, EP_VarSelect);
drhde6a4be2024-04-06 12:19:501384 pExpr->x.pSelect->selFlags |= SF_Correlated;
drh7d10d5a2008-08-20 16:35:101385 }
drhffcad582023-03-15 17:58:511386 pNC->ncFlags |= NC_Subquery;
drh7d10d5a2008-08-20 16:35:101387 }
1388 break;
1389 }
drh7d10d5a2008-08-20 16:35:101390 case TK_VARIABLE: {
drh77318a32019-12-12 15:19:181391 testcase( pNC->ncFlags & NC_IsCheck );
1392 testcase( pNC->ncFlags & NC_PartIdx );
1393 testcase( pNC->ncFlags & NC_IdxExpr );
1394 testcase( pNC->ncFlags & NC_GenCol );
1395 sqlite3ResolveNotValid(pParse, pNC, "parameters",
drh62fc0692022-02-06 00:30:041396 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
drh7d10d5a2008-08-20 16:35:101397 break;
1398 }
drh007c8432018-02-26 03:20:181399 case TK_IS:
drh8abed7b2018-02-26 18:49:051400 case TK_ISNOT: {
drh0d950af2019-08-22 16:38:421401 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
drh8abed7b2018-02-26 18:49:051402 assert( !ExprHasProperty(pExpr, EP_Reduced) );
1403 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1404 ** and "x IS NOT FALSE". */
drh91be05a2021-03-04 18:34:541405 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
drh8abed7b2018-02-26 18:49:051406 int rc = resolveExprStep(pWalker, pRight);
drh007c8432018-02-26 03:20:181407 if( rc==WRC_Abort ) return WRC_Abort;
drh8abed7b2018-02-26 18:49:051408 if( pRight->op==TK_TRUEFALSE ){
drh8abed7b2018-02-26 18:49:051409 pExpr->op2 = pExpr->op;
1410 pExpr->op = TK_TRUTH;
drh007c8432018-02-26 03:20:181411 return WRC_Continue;
1412 }
1413 }
drh08b92082020-08-10 14:18:001414 /* no break */ deliberate_fall_through
drh8abed7b2018-02-26 18:49:051415 }
dan3bafded2016-11-11 15:49:011416 case TK_BETWEEN:
drhb29e60c2016-09-05 12:02:341417 case TK_EQ:
1418 case TK_NE:
1419 case TK_LT:
1420 case TK_LE:
1421 case TK_GT:
drh8abed7b2018-02-26 18:49:051422 case TK_GE: {
drhb29e60c2016-09-05 12:02:341423 int nLeft, nRight;
1424 if( pParse->db->mallocFailed ) break;
drhb29e60c2016-09-05 12:02:341425 assert( pExpr->pLeft!=0 );
1426 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
dan3bafded2016-11-11 15:49:011427 if( pExpr->op==TK_BETWEEN ){
drha4eeccd2021-10-07 17:43:301428 assert( ExprUseXList(pExpr) );
dan3bafded2016-11-11 15:49:011429 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1430 if( nRight==nLeft ){
1431 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1432 }
1433 }else{
1434 assert( pExpr->pRight!=0 );
1435 nRight = sqlite3ExprVectorSize(pExpr->pRight);
1436 }
drhb29e60c2016-09-05 12:02:341437 if( nLeft!=nRight ){
1438 testcase( pExpr->op==TK_EQ );
1439 testcase( pExpr->op==TK_NE );
1440 testcase( pExpr->op==TK_LT );
1441 testcase( pExpr->op==TK_LE );
1442 testcase( pExpr->op==TK_GT );
1443 testcase( pExpr->op==TK_GE );
1444 testcase( pExpr->op==TK_IS );
1445 testcase( pExpr->op==TK_ISNOT );
dan3bafded2016-11-11 15:49:011446 testcase( pExpr->op==TK_BETWEEN );
drhb29e60c2016-09-05 12:02:341447 sqlite3ErrorMsg(pParse, "row value misused");
drh62fc0692022-02-06 00:30:041448 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
drhb29e60c2016-09-05 12:02:341449 }
larrybrbc917382023-06-07 08:40:311450 break;
drhb29e60c2016-09-05 12:02:341451 }
drh7d10d5a2008-08-20 16:35:101452 }
drh0c7d3d32022-01-24 16:47:121453 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
1454 return pParse->nErr ? WRC_Abort : WRC_Continue;
drh7d10d5a2008-08-20 16:35:101455}
1456
1457/*
1458** pEList is a list of expressions which are really the result set of the
1459** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1460** This routine checks to see if pE is a simple identifier which corresponds
1461** to the AS-name of one of the terms of the expression list. If it is,
1462** this routine return an integer between 1 and N where N is the number of
1463** elements in pEList, corresponding to the matching entry. If there is
1464** no match, or if pE is not a simple identifier, then this routine
1465** return 0.
1466**
1467** pEList has been resolved. pE has not.
1468*/
1469static int resolveAsName(
1470 Parse *pParse, /* Parsing context for error messages */
1471 ExprList *pEList, /* List of expressions to scan */
1472 Expr *pE /* Expression we are trying to match */
1473){
1474 int i; /* Loop counter */
1475
shanecf697392009-06-01 16:53:091476 UNUSED_PARAMETER(pParse);
1477
drh73c0fdc2009-06-15 18:32:361478 if( pE->op==TK_ID ){
drhf9751072021-10-07 13:40:291479 const char *zCol;
1480 assert( !ExprHasProperty(pE, EP_IntValue) );
1481 zCol = pE->u.zToken;
drh7d10d5a2008-08-20 16:35:101482 for(i=0; i<pEList->nExpr; i++){
drhd88fd532022-05-02 20:49:301483 if( pEList->a[i].fg.eEName==ENAME_NAME
dan607dd6e2020-01-03 14:27:081484 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
drhc4938ea2019-12-13 00:49:421485 ){
drh7d10d5a2008-08-20 16:35:101486 return i+1;
1487 }
1488 }
drh7d10d5a2008-08-20 16:35:101489 }
1490 return 0;
1491}
1492
1493/*
1494** pE is a pointer to an expression which is a single term in the
1495** ORDER BY of a compound SELECT. The expression has not been
1496** name resolved.
1497**
1498** At the point this routine is called, we already know that the
1499** ORDER BY term is not an integer index into the result set. That
1500** case is handled by the calling routine.
1501**
1502** Attempt to match pE against result set columns in the left-most
1503** SELECT statement. Return the index i of the matching column,
1504** as an indication to the caller that it should sort by the i-th column.
1505** The left-most column is 1. In other words, the value returned is the
1506** same integer value that would be used in the SQL statement to indicate
1507** the column.
1508**
1509** If there is no match, return 0. Return -1 if an error occurs.
1510*/
1511static int resolveOrderByTermToExprList(
1512 Parse *pParse, /* Parsing context for error messages */
1513 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
1514 Expr *pE /* The specific ORDER BY term */
1515){
1516 int i; /* Loop counter */
1517 ExprList *pEList; /* The columns of the result set */
1518 NameContext nc; /* Name context for resolving pE */
drha7564662010-02-22 19:32:311519 sqlite3 *db; /* Database connection */
1520 int rc; /* Return code from subprocedures */
1521 u8 savedSuppErr; /* Saved value of db->suppressErr */
drh7d10d5a2008-08-20 16:35:101522
drh4703b7d2024-06-06 15:03:161523 assert( sqlite3ExprIsInteger(pE, &i, 0)==0 );
drh7d10d5a2008-08-20 16:35:101524 pEList = pSelect->pEList;
1525
1526 /* Resolve all names in the ORDER BY term expression
1527 */
1528 memset(&nc, 0, sizeof(nc));
1529 nc.pParse = pParse;
1530 nc.pSrcList = pSelect->pSrc;
drh25c3b8c2018-04-16 10:34:131531 nc.uNC.pEList = pEList;
dand487e372021-04-12 16:59:281532 nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
drh050611a2021-04-10 13:37:041533 nc.nNcErr = 0;
drha7564662010-02-22 19:32:311534 db = pParse->db;
1535 savedSuppErr = db->suppressErr;
danb56a0902021-06-01 15:37:141536 db->suppressErr = 1;
drha7564662010-02-22 19:32:311537 rc = sqlite3ResolveExprNames(&nc, pE);
1538 db->suppressErr = savedSuppErr;
1539 if( rc ) return 0;
drh7d10d5a2008-08-20 16:35:101540
1541 /* Try to match the ORDER BY expression against an expression
1542 ** in the result set. Return an 1-based index of the matching
1543 ** result-set entry.
1544 */
1545 for(i=0; i<pEList->nExpr; i++){
dan5aa550c2017-06-24 18:10:291546 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
drh7d10d5a2008-08-20 16:35:101547 return i+1;
1548 }
1549 }
1550
1551 /* If no match, return 0. */
1552 return 0;
1553}
1554
1555/*
1556** Generate an ORDER BY or GROUP BY term out-of-range error.
1557*/
1558static void resolveOutOfRangeError(
1559 Parse *pParse, /* The error context into which to write the error */
1560 const char *zType, /* "ORDER" or "GROUP" */
1561 int i, /* The index (1-based) of the term out of range */
drh62fc0692022-02-06 00:30:041562 int mx, /* Largest permissible value of i */
1563 Expr *pError /* Associate the error with the expression */
drh7d10d5a2008-08-20 16:35:101564){
larrybrbc917382023-06-07 08:40:311565 sqlite3ErrorMsg(pParse,
drh7d10d5a2008-08-20 16:35:101566 "%r %s BY term out of range - should be "
1567 "between 1 and %d", i, zType, mx);
drh62fc0692022-02-06 00:30:041568 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
drh7d10d5a2008-08-20 16:35:101569}
1570
1571/*
1572** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1573** each term of the ORDER BY clause is a constant integer between 1
1574** and N where N is the number of columns in the compound SELECT.
1575**
1576** ORDER BY terms that are already an integer between 1 and N are
1577** unmodified. ORDER BY terms that are integers outside the range of
1578** 1 through N generate an error. ORDER BY terms that are expressions
1579** are matched against result set expressions of compound SELECT
1580** beginning with the left-most SELECT and working toward the right.
1581** At the first match, the ORDER BY expression is transformed into
1582** the integer column number.
1583**
1584** Return the number of errors seen.
1585*/
1586static int resolveCompoundOrderBy(
1587 Parse *pParse, /* Parsing context. Leave error messages here */
1588 Select *pSelect /* The SELECT statement containing the ORDER BY */
1589){
1590 int i;
1591 ExprList *pOrderBy;
1592 ExprList *pEList;
1593 sqlite3 *db;
1594 int moreToDo = 1;
1595
1596 pOrderBy = pSelect->pOrderBy;
1597 if( pOrderBy==0 ) return 0;
1598 db = pParse->db;
drh7d10d5a2008-08-20 16:35:101599 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1600 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1601 return 1;
1602 }
drh7d10d5a2008-08-20 16:35:101603 for(i=0; i<pOrderBy->nExpr; i++){
drhd88fd532022-05-02 20:49:301604 pOrderBy->a[i].fg.done = 0;
drh7d10d5a2008-08-20 16:35:101605 }
1606 pSelect->pNext = 0;
1607 while( pSelect->pPrior ){
1608 pSelect->pPrior->pNext = pSelect;
1609 pSelect = pSelect->pPrior;
1610 }
1611 while( pSelect && moreToDo ){
1612 struct ExprList_item *pItem;
1613 moreToDo = 0;
1614 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:291615 assert( pEList!=0 );
drh7d10d5a2008-08-20 16:35:101616 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1617 int iCol = -1;
1618 Expr *pE, *pDup;
drhd88fd532022-05-02 20:49:301619 if( pItem->fg.done ) continue;
drh0d950af2019-08-22 16:38:421620 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
drh235667a2020-11-08 20:44:301621 if( NEVER(pE==0) ) continue;
drh4703b7d2024-06-06 15:03:161622 if( sqlite3ExprIsInteger(pE, &iCol, 0) ){
drh73c0fdc2009-06-15 18:32:361623 if( iCol<=0 || iCol>pEList->nExpr ){
drh62fc0692022-02-06 00:30:041624 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
drh7d10d5a2008-08-20 16:35:101625 return 1;
1626 }
1627 }else{
1628 iCol = resolveAsName(pParse, pEList, pE);
1629 if( iCol==0 ){
dan5e970a82019-01-16 14:58:371630 /* Now test if expression pE matches one of the values returned
larrybrbc917382023-06-07 08:40:311631 ** by pSelect. In the usual case this is done by duplicating the
dan5e970a82019-01-16 14:58:371632 ** expression, resolving any symbols in it, and then comparing
1633 ** it against each expression returned by the SELECT statement.
1634 ** Once the comparisons are finished, the duplicate expression
1635 ** is deleted.
1636 **
danb56a0902021-06-01 15:37:141637 ** If this is running as part of an ALTER TABLE operation and
1638 ** the symbols resolve successfully, also resolve the symbols in the
1639 ** actual expression. This allows the code in alter.c to modify
1640 ** column references within the ORDER BY expression as required. */
1641 pDup = sqlite3ExprDup(db, pE, 0);
drh7d10d5a2008-08-20 16:35:101642 if( !db->mallocFailed ){
1643 assert(pDup);
1644 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
danb56a0902021-06-01 15:37:141645 if( IN_RENAME_OBJECT && iCol>0 ){
1646 resolveOrderByTermToExprList(pParse, pSelect, pE);
1647 }
drh7d10d5a2008-08-20 16:35:101648 }
danb56a0902021-06-01 15:37:141649 sqlite3ExprDelete(db, pDup);
drh7d10d5a2008-08-20 16:35:101650 }
drh7d10d5a2008-08-20 16:35:101651 }
1652 if( iCol>0 ){
drhbd13d342012-12-07 21:02:471653 /* Convert the ORDER BY term into an integer column number iCol,
danb56a0902021-06-01 15:37:141654 ** taking care to preserve the COLLATE clause if it exists. */
dana5f9f422019-01-23 19:50:461655 if( !IN_RENAME_OBJECT ){
1656 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1657 if( pNew==0 ) return 1;
1658 pNew->flags |= EP_IntValue;
1659 pNew->u.iValue = iCol;
1660 if( pItem->pExpr==pE ){
1661 pItem->pExpr = pNew;
1662 }else{
1663 Expr *pParent = pItem->pExpr;
1664 assert( pParent->op==TK_COLLATE );
1665 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1666 assert( pParent->pLeft==pE );
1667 pParent->pLeft = pNew;
1668 }
1669 sqlite3ExprDelete(db, pE);
1670 pItem->u.x.iOrderByCol = (u16)iCol;
drhbd13d342012-12-07 21:02:471671 }
drhd88fd532022-05-02 20:49:301672 pItem->fg.done = 1;
drh7d10d5a2008-08-20 16:35:101673 }else{
1674 moreToDo = 1;
1675 }
1676 }
1677 pSelect = pSelect->pNext;
1678 }
1679 for(i=0; i<pOrderBy->nExpr; i++){
drhd88fd532022-05-02 20:49:301680 if( pOrderBy->a[i].fg.done==0 ){
drh7d10d5a2008-08-20 16:35:101681 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1682 "column in the result set", i+1);
1683 return 1;
1684 }
1685 }
1686 return 0;
1687}
1688
1689/*
1690** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1691** the SELECT statement pSelect. If any term is reference to a
drhc2acc4e2013-11-15 18:15:191692** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1693** field) then convert that term into a copy of the corresponding result set
drh7d10d5a2008-08-20 16:35:101694** column.
1695**
1696** If any errors are detected, add an error message to pParse and
1697** return non-zero. Return zero if no errors are seen.
1698*/
1699int sqlite3ResolveOrderGroupBy(
1700 Parse *pParse, /* Parsing context. Leave error messages here */
1701 Select *pSelect, /* The SELECT statement containing the clause */
1702 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
1703 const char *zType /* "ORDER" or "GROUP" */
1704){
1705 int i;
1706 sqlite3 *db = pParse->db;
1707 ExprList *pEList;
1708 struct ExprList_item *pItem;
1709
dan71f059c2019-08-01 10:58:461710 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
drh7d10d5a2008-08-20 16:35:101711 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1712 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1713 return 1;
1714 }
drh7d10d5a2008-08-20 16:35:101715 pEList = pSelect->pEList;
drh0a846f92008-08-25 17:23:291716 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
drh7d10d5a2008-08-20 16:35:101717 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
drhc2acc4e2013-11-15 18:15:191718 if( pItem->u.x.iOrderByCol ){
1719 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
drh62fc0692022-02-06 00:30:041720 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
drh7d10d5a2008-08-20 16:35:101721 return 1;
1722 }
drh6b37b762021-02-16 20:32:171723 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
drh7d10d5a2008-08-20 16:35:101724 }
1725 }
1726 return 0;
1727}
1728
danf030b372019-02-22 19:24:161729#ifndef SQLITE_OMIT_WINDOWFUNC
1730/*
dan75b08212019-07-22 16:20:031731** Walker callback for windowRemoveExprFromSelect().
danf030b372019-02-22 19:24:161732*/
1733static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
drh51755a72019-08-08 19:40:291734 UNUSED_PARAMETER(pWalker);
danf030b372019-02-22 19:24:161735 if( ExprHasProperty(pExpr, EP_WinFunc) ){
dan75b08212019-07-22 16:20:031736 Window *pWin = pExpr->y.pWin;
drhe2094572019-07-22 19:01:381737 sqlite3WindowUnlinkFromSelect(pWin);
danf030b372019-02-22 19:24:161738 }
1739 return WRC_Continue;
1740}
1741
1742/*
1743** Remove any Window objects owned by the expression pExpr from the
1744** Select.pWin list of Select object pSelect.
1745*/
dan75b08212019-07-22 16:20:031746static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
drhfd15e182019-07-20 21:12:311747 if( pSelect->pWin ){
1748 Walker sWalker;
1749 memset(&sWalker, 0, sizeof(Walker));
1750 sWalker.xExprCallback = resolveRemoveWindowsCb;
1751 sWalker.u.pSelect = pSelect;
1752 sqlite3WalkExpr(&sWalker, pExpr);
1753 }
danf030b372019-02-22 19:24:161754}
1755#else
dan75b08212019-07-22 16:20:031756# define windowRemoveExprFromSelect(a, b)
drhfd15e182019-07-20 21:12:311757#endif /* SQLITE_OMIT_WINDOWFUNC */
danf030b372019-02-22 19:24:161758
drh7d10d5a2008-08-20 16:35:101759/*
1760** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1761** The Name context of the SELECT statement is pNC. zType is either
1762** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1763**
1764** This routine resolves each term of the clause into an expression.
1765** If the order-by term is an integer I between 1 and N (where N is the
1766** number of columns in the result set of the SELECT) then the expression
1767** in the resolution is a copy of the I-th result-set expression. If
drh26080d92013-08-15 14:27:421768** the order-by term is an identifier that corresponds to the AS-name of
drh7d10d5a2008-08-20 16:35:101769** a result-set expression, then the term resolves to a copy of the
1770** result-set expression. Otherwise, the expression is resolved in
1771** the usual way - using sqlite3ResolveExprNames().
1772**
1773** This routine returns the number of errors. If errors occur, then
1774** an appropriate error message might be left in pParse. (OOM errors
1775** excepted.)
1776*/
1777static int resolveOrderGroupBy(
1778 NameContext *pNC, /* The name context of the SELECT statement */
1779 Select *pSelect, /* The SELECT statement holding pOrderBy */
1780 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
1781 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
1782){
drh70331cd2012-04-27 01:09:061783 int i, j; /* Loop counters */
drh7d10d5a2008-08-20 16:35:101784 int iCol; /* Column number */
1785 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
1786 Parse *pParse; /* Parsing context */
1787 int nResult; /* Number of terms in the result set */
1788
drhde0e1b12021-04-16 22:53:571789 assert( pOrderBy!=0 );
drh7d10d5a2008-08-20 16:35:101790 nResult = pSelect->pEList->nExpr;
1791 pParse = pNC->pParse;
1792 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1793 Expr *pE = pItem->pExpr;
drh0d950af2019-08-22 16:38:421794 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
drh235667a2020-11-08 20:44:301795 if( NEVER(pE2==0) ) continue;
drh0af16ab2013-08-15 22:40:211796 if( zType[0]!='G' ){
1797 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1798 if( iCol>0 ){
1799 /* If an AS-name match is found, mark this ORDER BY column as being
1800 ** a copy of the iCol-th result-set column. The subsequent call to
1801 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1802 ** copy of the iCol-th result-set expression. */
drhc2acc4e2013-11-15 18:15:191803 pItem->u.x.iOrderByCol = (u16)iCol;
drh0af16ab2013-08-15 22:40:211804 continue;
1805 }
drh7d10d5a2008-08-20 16:35:101806 }
drh4703b7d2024-06-06 15:03:161807 if( sqlite3ExprIsInteger(pE2, &iCol, 0) ){
drh7d10d5a2008-08-20 16:35:101808 /* The ORDER BY term is an integer constant. Again, set the column
1809 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1810 ** order-by term to a copy of the result-set expression */
drh85d641f2012-12-07 23:23:531811 if( iCol<1 || iCol>0xffff ){
drh62fc0692022-02-06 00:30:041812 resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
drh7d10d5a2008-08-20 16:35:101813 return 1;
1814 }
drhc2acc4e2013-11-15 18:15:191815 pItem->u.x.iOrderByCol = (u16)iCol;
drh7d10d5a2008-08-20 16:35:101816 continue;
1817 }
1818
1819 /* Otherwise, treat the ORDER BY term as an ordinary expression */
drhc2acc4e2013-11-15 18:15:191820 pItem->u.x.iOrderByCol = 0;
drh7d10d5a2008-08-20 16:35:101821 if( sqlite3ResolveExprNames(pNC, pE) ){
1822 return 1;
1823 }
drh70331cd2012-04-27 01:09:061824 for(j=0; j<pSelect->pEList->nExpr; j++){
dan5aa550c2017-06-24 18:10:291825 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
larrybrbc917382023-06-07 08:40:311826 /* Since this expression is being changed into a reference
danf030b372019-02-22 19:24:161827 ** to an identical expression in the result set, remove all Window
1828 ** objects belonging to the expression from the Select.pWin list. */
dan75b08212019-07-22 16:20:031829 windowRemoveExprFromSelect(pSelect, pE);
drhc2acc4e2013-11-15 18:15:191830 pItem->u.x.iOrderByCol = j+1;
drh70331cd2012-04-27 01:09:061831 }
1832 }
drh7d10d5a2008-08-20 16:35:101833 }
1834 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1835}
1836
1837/*
peter.d.reid60ec9142014-09-06 16:39:461838** Resolve names in the SELECT statement p and all of its descendants.
drh7d10d5a2008-08-20 16:35:101839*/
1840static int resolveSelectStep(Walker *pWalker, Select *p){
1841 NameContext *pOuterNC; /* Context that contains this SELECT */
1842 NameContext sNC; /* Name context of this SELECT */
1843 int isCompound; /* True if p is a compound select */
1844 int nCompound; /* Number of compound terms processed so far */
1845 Parse *pParse; /* Parsing context */
drh7d10d5a2008-08-20 16:35:101846 int i; /* Loop counter */
1847 ExprList *pGroupBy; /* The GROUP BY clause */
1848 Select *pLeftmost; /* Left-most of SELECT of a compound */
1849 sqlite3 *db; /* Database connection */
larrybrbc917382023-06-07 08:40:311850
drh7d10d5a2008-08-20 16:35:101851
drh0a846f92008-08-25 17:23:291852 assert( p!=0 );
drh7d10d5a2008-08-20 16:35:101853 if( p->selFlags & SF_Resolved ){
1854 return WRC_Prune;
1855 }
1856 pOuterNC = pWalker->u.pNC;
1857 pParse = pWalker->pParse;
1858 db = pParse->db;
1859
1860 /* Normally sqlite3SelectExpand() will be called first and will have
1861 ** already expanded this SELECT. However, if this is a subquery within
1862 ** an expression, sqlite3ResolveExprNames() will be called without a
1863 ** prior call to sqlite3SelectExpand(). When that happens, let
1864 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1865 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1866 ** this routine in the correct order.
1867 */
1868 if( (p->selFlags & SF_Expanded)==0 ){
1869 sqlite3SelectPrep(pParse, p, pOuterNC);
drh0c7d3d32022-01-24 16:47:121870 return pParse->nErr ? WRC_Abort : WRC_Prune;
drh7d10d5a2008-08-20 16:35:101871 }
1872
1873 isCompound = p->pPrior!=0;
1874 nCompound = 0;
1875 pLeftmost = p;
1876 while( p ){
1877 assert( (p->selFlags & SF_Expanded)!=0 );
1878 assert( (p->selFlags & SF_Resolved)==0 );
1879 p->selFlags |= SF_Resolved;
1880
1881 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1882 ** are not allowed to refer to any names, so pass an empty NameContext.
1883 */
1884 memset(&sNC, 0, sizeof(sNC));
1885 sNC.pParse = pParse;
dane3bf6322018-06-08 20:58:271886 sNC.pWinSelect = p;
drh8c0833f2017-11-14 23:48:231887 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
drh7d10d5a2008-08-20 16:35:101888 return WRC_Abort;
1889 }
danb33c50f2015-04-04 16:43:161890
1891 /* If the SF_Converted flags is set, then this Select object was
1892 ** was created by the convertCompoundSelectToSubquery() function.
1893 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1894 ** as if it were part of the sub-query, not the parent. This block
1895 ** moves the pOrderBy down to the sub-query. It will be moved back
1896 ** after the names have been resolved. */
1897 if( p->selFlags & SF_Converted ){
drh1521ca42024-08-19 22:48:301898 Select *pSub;
1899 assert( p->pSrc->a[0].fg.isSubquery );
1900 assert( p->pSrc->a[0].u4.pSubq!=0 );
1901 pSub = p->pSrc->a[0].u4.pSubq->pSelect;
1902 assert( pSub!=0 );
drha43f02e2015-04-15 06:45:131903 assert( p->pSrc->nSrc==1 && p->pOrderBy );
danb33c50f2015-04-04 16:43:161904 assert( pSub->pPrior && pSub->pOrderBy==0 );
1905 pSub->pOrderBy = p->pOrderBy;
1906 p->pOrderBy = 0;
1907 }
larrybrbc917382023-06-07 08:40:311908
drhee612e22021-07-16 20:16:191909 /* Recursively resolve names in all subqueries in the FROM clause
drh7d10d5a2008-08-20 16:35:101910 */
dan5e4233a2023-11-02 21:02:531911 if( pOuterNC ) pOuterNC->nNestedSelect++;
drh7d10d5a2008-08-20 16:35:101912 for(i=0; i<p->pSrc->nSrc; i++){
drh76012942021-02-21 21:04:541913 SrcItem *pItem = &p->pSrc->a[i];
drhb204b6a2024-08-17 23:23:231914 assert( pItem->zName!=0
drh1521ca42024-08-19 22:48:301915 || pItem->fg.isSubquery ); /* Test of tag-20240424-1*/
1916 if( pItem->fg.isSubquery
1917 && (pItem->u4.pSubq->pSelect->selFlags & SF_Resolved)==0
1918 ){
dan4b174552021-02-26 15:20:171919 int nRef = pOuterNC ? pOuterNC->nRef : 0;
drh7d10d5a2008-08-20 16:35:101920 const char *zSavedContext = pParse->zAuthContext;
danda79cf02011-07-08 16:10:541921
drh7d10d5a2008-08-20 16:35:101922 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
drh1521ca42024-08-19 22:48:301923 sqlite3ResolveSelectNames(pParse, pItem->u4.pSubq->pSelect, pOuterNC);
drh7d10d5a2008-08-20 16:35:101924 pParse->zAuthContext = zSavedContext;
drh0c7d3d32022-01-24 16:47:121925 if( pParse->nErr ) return WRC_Abort;
1926 assert( db->mallocFailed==0 );
danda79cf02011-07-08 16:10:541927
dan4b174552021-02-26 15:20:171928 /* If the number of references to the outer context changed when
1929 ** expressions in the sub-select were resolved, the sub-select
1930 ** is correlated. It is not required to check the refcount on any
1931 ** but the innermost outer context object, as lookupName() increments
1932 ** the refcount on all contexts between the current one and the
1933 ** context containing the column when it resolves a name. */
1934 if( pOuterNC ){
1935 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
1936 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
1937 }
drh7d10d5a2008-08-20 16:35:101938 }
1939 }
drh792103a2023-11-02 22:11:351940 if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
1941 pOuterNC->nNestedSelect--;
1942 }
larrybrbc917382023-06-07 08:40:311943
drh92689d22012-12-18 16:07:081944 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1945 ** resolve the result-set expression list.
1946 */
dan86fb6e12018-05-16 20:58:071947 sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
drh92689d22012-12-18 16:07:081948 sNC.pSrcList = p->pSrc;
1949 sNC.pNext = pOuterNC;
larrybrbc917382023-06-07 08:40:311950
drh92689d22012-12-18 16:07:081951 /* Resolve names in the result set. */
drh01d230c2015-08-19 17:11:371952 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
dan86fb6e12018-05-16 20:58:071953 sNC.ncFlags &= ~NC_AllowWin;
larrybrbc917382023-06-07 08:40:311954
1955 /* If there are no aggregate functions in the result-set, and no GROUP BY
drh7d10d5a2008-08-20 16:35:101956 ** expression, do not allow aggregates in any of the other expressions.
1957 */
1958 assert( (p->selFlags & SF_Aggregate)==0 );
1959 pGroupBy = p->pGroupBy;
drha51009b2012-05-21 19:11:251960 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
drh9588ad92014-09-15 14:46:021961 assert( NC_MinMaxAgg==SF_MinMaxAgg );
drhbb301232021-07-15 19:29:431962 assert( NC_OrderAgg==SF_OrderByReqd );
1963 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
drh7d10d5a2008-08-20 16:35:101964 }else{
drha51009b2012-05-21 19:11:251965 sNC.ncFlags &= ~NC_AllowAgg;
drh7d10d5a2008-08-20 16:35:101966 }
larrybrbc917382023-06-07 08:40:311967
drh26080d92013-08-15 14:27:421968 /* Add the output column list to the name-context before parsing the
drh7d10d5a2008-08-20 16:35:101969 ** other expressions in the SELECT statement. This is so that
1970 ** expressions in the WHERE clause (etc.) can refer to expressions by
1971 ** aliases in the result set.
1972 **
1973 ** Minor point: If this is the case, then the expression will be
1974 ** re-evaluated for each reference to it.
1975 */
drhd5101972021-02-08 13:41:171976 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
drh25c3b8c2018-04-16 10:34:131977 sNC.uNC.pEList = p->pEList;
1978 sNC.ncFlags |= NC_UEList;
drhde0e1b12021-04-16 22:53:571979 if( p->pHaving ){
drhb9294de2022-06-21 13:41:241980 if( (p->selFlags & SF_Aggregate)==0 ){
1981 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
drhde0e1b12021-04-16 22:53:571982 return WRC_Abort;
1983 }
1984 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1985 }
drh61b77a62024-03-08 21:37:181986 sNC.ncFlags |= NC_Where;
drha3a5bd92013-04-13 19:59:581987 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
drh61b77a62024-03-08 21:37:181988 sNC.ncFlags &= ~NC_Where;
drh7d10d5a2008-08-20 16:35:101989
drh01d230c2015-08-19 17:11:371990 /* Resolve names in table-valued-function arguments */
1991 for(i=0; i<p->pSrc->nSrc; i++){
drh76012942021-02-21 21:04:541992 SrcItem *pItem = &p->pSrc->a[i];
drh01d230c2015-08-19 17:11:371993 if( pItem->fg.isTabFunc
larrybrbc917382023-06-07 08:40:311994 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
drh01d230c2015-08-19 17:11:371995 ){
1996 return WRC_Abort;
1997 }
1998 }
1999
danbe120832021-05-17 16:20:412000#ifndef SQLITE_OMIT_WINDOWFUNC
2001 if( IN_RENAME_OBJECT ){
2002 Window *pWin;
2003 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
2004 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
2005 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
2006 ){
2007 return WRC_Abort;
2008 }
2009 }
2010 }
2011#endif
2012
drh7d10d5a2008-08-20 16:35:102013 /* The ORDER BY and GROUP BY clauses may not refer to terms in
larrybrbc917382023-06-07 08:40:312014 ** outer queries
drh7d10d5a2008-08-20 16:35:102015 */
2016 sNC.pNext = 0;
dan86fb6e12018-05-16 20:58:072017 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
drh7d10d5a2008-08-20 16:35:102018
larrybrbc917382023-06-07 08:40:312019 /* If this is a converted compound query, move the ORDER BY clause from
danb33c50f2015-04-04 16:43:162020 ** the sub-query back to the parent query. At this point each term
2021 ** within the ORDER BY clause has been transformed to an integer value.
2022 ** These integers will be replaced by copies of the corresponding result
2023 ** set expressions by the call to resolveOrderGroupBy() below. */
2024 if( p->selFlags & SF_Converted ){
drh1521ca42024-08-19 22:48:302025 Select *pSub;
2026 assert( p->pSrc->a[0].fg.isSubquery );
2027 pSub = p->pSrc->a[0].u4.pSubq->pSelect;
2028 assert( pSub!=0 );
danb33c50f2015-04-04 16:43:162029 p->pOrderBy = pSub->pOrderBy;
2030 pSub->pOrderBy = 0;
2031 }
2032
drh7d10d5a2008-08-20 16:35:102033 /* Process the ORDER BY clause for singleton SELECT statements.
2034 ** The ORDER BY clause for compounds SELECT statements is handled
2035 ** below, after all of the result-sets for all of the elements of
2036 ** the compound have been resolved.
drh7b4da152015-04-17 18:52:372037 **
2038 ** If there is an ORDER BY clause on a term of a compound-select other
2039 ** than the right-most term, then that is a syntax error. But the error
2040 ** is not detected until much later, and so we need to go ahead and
2041 ** resolve those symbols on the incorrect ORDER BY for consistency.
drh7d10d5a2008-08-20 16:35:102042 */
drhde0e1b12021-04-16 22:53:572043 if( p->pOrderBy!=0
2044 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
drh7b4da152015-04-17 18:52:372045 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
2046 ){
drh7d10d5a2008-08-20 16:35:102047 return WRC_Abort;
2048 }
2049 if( db->mallocFailed ){
2050 return WRC_Abort;
2051 }
dan86fb6e12018-05-16 20:58:072052 sNC.ncFlags &= ~NC_AllowWin;
larrybrbc917382023-06-07 08:40:312053
2054 /* Resolve the GROUP BY clause. At the same time, make sure
drh7d10d5a2008-08-20 16:35:102055 ** the GROUP BY clause does not contain aggregate functions.
2056 */
2057 if( pGroupBy ){
2058 struct ExprList_item *pItem;
larrybrbc917382023-06-07 08:40:312059
drh7d10d5a2008-08-20 16:35:102060 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
2061 return WRC_Abort;
2062 }
2063 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2064 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2065 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2066 "the GROUP BY clause");
2067 return WRC_Abort;
2068 }
2069 }
2070 }
2071
dan923cadb2015-06-23 12:19:552072 /* If this is part of a compound SELECT, check that it has the right
2073 ** number of expressions in the select list. */
2074 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
2075 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
2076 return WRC_Abort;
2077 }
2078
drh7d10d5a2008-08-20 16:35:102079 /* Advance to the next term of the compound
2080 */
2081 p = p->pPrior;
2082 nCompound++;
2083 }
2084
2085 /* Resolve the ORDER BY on a compound SELECT after all terms of
2086 ** the compound have been resolved.
2087 */
2088 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
2089 return WRC_Abort;
2090 }
2091
2092 return WRC_Prune;
2093}
2094
2095/*
2096** This routine walks an expression tree and resolves references to
2097** table columns and result-set columns. At the same time, do error
2098** checking on function usage and set a flag if any aggregate functions
2099** are seen.
2100**
larrybrbc917382023-06-07 08:40:312101** To resolve table columns references we look for nodes (or subtrees) of the
drh7d10d5a2008-08-20 16:35:102102** form X.Y.Z or Y.Z or just Z where
2103**
2104** X: The name of a database. Ex: "main" or "temp" or
2105** the symbolic name assigned to an ATTACH-ed database.
2106**
2107** Y: The name of a table in a FROM clause. Or in a trigger
2108** one of the special names "old" or "new".
2109**
2110** Z: The name of a column in table Y.
2111**
2112** The node at the root of the subtree is modified as follows:
2113**
2114** Expr.op Changed to TK_COLUMN
2115** Expr.pTab Points to the Table object for X.Y
2116** Expr.iColumn The column index in X.Y. -1 for the rowid.
2117** Expr.iTable The VDBE cursor number for X.Y
2118**
2119**
2120** To resolve result-set references, look for expression nodes of the
2121** form Z (with no X and Y prefix) where the Z matches the right-hand
2122** size of an AS clause in the result-set of a SELECT. The Z expression
2123** is replaced by a copy of the left-hand side of the result-set expression.
2124** Table-name and function resolution occurs on the substituted expression
2125** tree. For example, in:
2126**
2127** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2128**
2129** The "x" term of the order by is replaced by "a+b" to render:
2130**
2131** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2132**
larrybrbc917382023-06-07 08:40:312133** Function calls are checked to make sure that the function is
drh7d10d5a2008-08-20 16:35:102134** defined and that the correct number of arguments are specified.
drha51009b2012-05-21 19:11:252135** If the function is an aggregate function, then the NC_HasAgg flag is
drh7d10d5a2008-08-20 16:35:102136** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2137** If an expression contains aggregate functions then the EP_Agg
2138** property on the expression is set.
2139**
2140** An error message is left in pParse if anything is amiss. The number
2141** if errors is returned.
2142*/
larrybrbc917382023-06-07 08:40:312143int sqlite3ResolveExprNames(
drh7d10d5a2008-08-20 16:35:102144 NameContext *pNC, /* Namespace to resolve expressions in. */
2145 Expr *pExpr /* The expression to be analyzed. */
2146){
dan0d925712019-05-20 17:14:252147 int savedHasAgg;
drh7d10d5a2008-08-20 16:35:102148 Walker w;
2149
drhd03257c2017-05-31 00:49:402150 if( pExpr==0 ) return SQLITE_OK;
drhbb301232021-07-15 19:29:432151 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2152 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
drh9bfb0242016-01-20 02:21:502153 w.pParse = pNC->pParse;
drh7d10d5a2008-08-20 16:35:102154 w.xExprCallback = resolveExprStep;
dand487e372021-04-12 16:59:282155 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
drh9bfb0242016-01-20 02:21:502156 w.xSelectCallback2 = 0;
drh7d10d5a2008-08-20 16:35:102157 w.u.pNC = pNC;
drhd03257c2017-05-31 00:49:402158#if SQLITE_MAX_EXPR_DEPTH>0
2159 w.pParse->nHeight += pExpr->nHeight;
2160 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2161 return SQLITE_ERROR;
2162 }
2163#endif
drhf82c8cb2023-06-19 23:27:222164 assert( pExpr!=0 );
2165 sqlite3WalkExprNN(&w, pExpr);
drh7d10d5a2008-08-20 16:35:102166#if SQLITE_MAX_EXPR_DEPTH>0
drhd03257c2017-05-31 00:49:402167 w.pParse->nHeight -= pExpr->nHeight;
drh7d10d5a2008-08-20 16:35:102168#endif
drhd137f4e2019-03-29 01:15:112169 assert( EP_Agg==NC_HasAgg );
2170 assert( EP_Win==NC_HasWin );
2171 testcase( pNC->ncFlags & NC_HasAgg );
2172 testcase( pNC->ncFlags & NC_HasWin );
2173 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
drh9588ad92014-09-15 14:46:022174 pNC->ncFlags |= savedHasAgg;
drh050611a2021-04-10 13:37:042175 return pNC->nNcErr>0 || w.pParse->nErr>0;
drh7d10d5a2008-08-20 16:35:102176}
drh7d10d5a2008-08-20 16:35:102177
drh01d230c2015-08-19 17:11:372178/*
2179** Resolve all names for all expression in an expression list. This is
2180** just like sqlite3ResolveExprNames() except that it works for an expression
2181** list rather than a single expression.
drh610a5ba2024-08-09 18:18:112182**
2183** The return value is SQLITE_OK (0) for success or SQLITE_ERROR (1) for a
2184** failure.
drh01d230c2015-08-19 17:11:372185*/
larrybrbc917382023-06-07 08:40:312186int sqlite3ResolveExprListNames(
drh01d230c2015-08-19 17:11:372187 NameContext *pNC, /* Namespace to resolve expressions in. */
2188 ExprList *pList /* The expression list to be analyzed. */
2189){
drhd8b1bfc2015-08-20 23:21:342190 int i;
drh4047bdf2020-04-06 20:35:522191 int savedHasAgg = 0;
2192 Walker w;
drh610a5ba2024-08-09 18:18:112193 if( pList==0 ) return SQLITE_OK;
drh4047bdf2020-04-06 20:35:522194 w.pParse = pNC->pParse;
2195 w.xExprCallback = resolveExprStep;
2196 w.xSelectCallback = resolveSelectStep;
2197 w.xSelectCallback2 = 0;
2198 w.u.pNC = pNC;
drhbb301232021-07-15 19:29:432199 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2200 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
drh4047bdf2020-04-06 20:35:522201 for(i=0; i<pList->nExpr; i++){
2202 Expr *pExpr = pList->a[i].pExpr;
2203 if( pExpr==0 ) continue;
2204#if SQLITE_MAX_EXPR_DEPTH>0
2205 w.pParse->nHeight += pExpr->nHeight;
2206 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
drh610a5ba2024-08-09 18:18:112207 return SQLITE_ERROR;
drh20292312015-11-21 13:24:462208 }
drh4047bdf2020-04-06 20:35:522209#endif
drhf82c8cb2023-06-19 23:27:222210 sqlite3WalkExprNN(&w, pExpr);
drh4047bdf2020-04-06 20:35:522211#if SQLITE_MAX_EXPR_DEPTH>0
2212 w.pParse->nHeight -= pExpr->nHeight;
2213#endif
2214 assert( EP_Agg==NC_HasAgg );
2215 assert( EP_Win==NC_HasWin );
2216 testcase( pNC->ncFlags & NC_HasAgg );
2217 testcase( pNC->ncFlags & NC_HasWin );
drhbb301232021-07-15 19:29:432218 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
drh4047bdf2020-04-06 20:35:522219 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
drhbb301232021-07-15 19:29:432220 savedHasAgg |= pNC->ncFlags &
2221 (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2222 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
drh4047bdf2020-04-06 20:35:522223 }
drh610a5ba2024-08-09 18:18:112224 if( w.pParse->nErr>0 ) return SQLITE_ERROR;
drh01d230c2015-08-19 17:11:372225 }
drh4047bdf2020-04-06 20:35:522226 pNC->ncFlags |= savedHasAgg;
drh610a5ba2024-08-09 18:18:112227 return SQLITE_OK;
drh01d230c2015-08-19 17:11:372228}
drh7d10d5a2008-08-20 16:35:102229
2230/*
2231** Resolve all names in all expressions of a SELECT and in all
larrybrbc917382023-06-07 08:40:312232** descendants of the SELECT, including compounds off of p->pPrior,
drh7d10d5a2008-08-20 16:35:102233** subqueries in expressions, and subqueries used as FROM clause
2234** terms.
2235**
2236** See sqlite3ResolveExprNames() for a description of the kinds of
2237** transformations that occur.
2238**
2239** All SELECT statements should have been expanded using
2240** sqlite3SelectExpand() prior to invoking this routine.
2241*/
2242void sqlite3ResolveSelectNames(
2243 Parse *pParse, /* The parser context */
2244 Select *p, /* The SELECT statement being coded. */
2245 NameContext *pOuterNC /* Name context for parent SELECT statement */
2246){
2247 Walker w;
2248
drh0a846f92008-08-25 17:23:292249 assert( p!=0 );
drh0a846f92008-08-25 17:23:292250 w.xExprCallback = resolveExprStep;
2251 w.xSelectCallback = resolveSelectStep;
drh979dd1b2017-05-29 14:26:072252 w.xSelectCallback2 = 0;
drh0a846f92008-08-25 17:23:292253 w.pParse = pParse;
2254 w.u.pNC = pOuterNC;
2255 sqlite3WalkSelect(&w, p);
drh7d10d5a2008-08-20 16:35:102256}
drh3780be12013-07-31 19:05:222257
2258/*
drhee751fa2019-01-02 14:34:462259** Resolve names in expressions that can only reference a single table
2260** or which cannot reference any tables at all. Examples:
drh3780be12013-07-31 19:05:222261**
drh20cee7d2019-10-30 18:50:082262** "type" flag
2263** ------------
2264** (1) CHECK constraints NC_IsCheck
2265** (2) WHERE clauses on partial indices NC_PartIdx
2266** (3) Expressions in indexes on expressions NC_IdxExpr
2267** (4) Expression arguments to VACUUM INTO. 0
2268** (5) GENERATED ALWAYS as expressions NC_GenCol
drh3780be12013-07-31 19:05:222269**
drhee751fa2019-01-02 14:34:462270** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2271** nodes of the expression is set to -1 and the Expr.iColumn value is
2272** set to the column number. In case (4), TK_COLUMN nodes cause an error.
drh3780be12013-07-31 19:05:222273**
2274** Any errors cause an error message to be set in pParse.
2275*/
drhee751fa2019-01-02 14:34:462276int sqlite3ResolveSelfReference(
drh81f7b372019-10-16 12:18:592277 Parse *pParse, /* Parsing context */
2278 Table *pTab, /* The table being referenced, or NULL */
2279 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2280 Expr *pExpr, /* Expression to resolve. May be NULL. */
2281 ExprList *pList /* Expression list to resolve. May be NULL. */
drh3780be12013-07-31 19:05:222282){
drhcebf06c2025-03-14 18:10:022283 SrcList *pSrc; /* Fake SrcList for pParse->pNewTable */
drh3780be12013-07-31 19:05:222284 NameContext sNC; /* Name context for pParse->pNewTable */
drhee751fa2019-01-02 14:34:462285 int rc;
drhcebf06c2025-03-14 18:10:022286 u8 srcSpace[SZ_SRCLIST_1]; /* Memory space for the fake SrcList */
drh3780be12013-07-31 19:05:222287
drhee751fa2019-01-02 14:34:462288 assert( type==0 || pTab!=0 );
drh81f7b372019-10-16 12:18:592289 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2290 || type==NC_GenCol || pTab==0 );
drh3780be12013-07-31 19:05:222291 memset(&sNC, 0, sizeof(sNC));
drhcebf06c2025-03-14 18:10:022292 pSrc = (SrcList*)srcSpace;
2293 memset(pSrc, 0, SZ_SRCLIST_1);
drhee751fa2019-01-02 14:34:462294 if( pTab ){
drhcebf06c2025-03-14 18:10:022295 pSrc->nSrc = 1;
2296 pSrc->a[0].zName = pTab->zName;
2297 pSrc->a[0].pSTab = pTab;
2298 pSrc->a[0].iCursor = -1;
drh05b32ee2020-01-09 01:20:032299 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2300 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2301 ** schema elements */
2302 type |= NC_FromDDL;
2303 }
drhee751fa2019-01-02 14:34:462304 }
drh3780be12013-07-31 19:05:222305 sNC.pParse = pParse;
drhcebf06c2025-03-14 18:10:022306 sNC.pSrcList = pSrc;
drhd0ff6012019-06-17 13:56:112307 sNC.ncFlags = type | NC_IsDDL;
drhee751fa2019-01-02 14:34:462308 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2309 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2310 return rc;
drh3780be12013-07-31 19:05:222311}