Fix an incorrect tcl comment that appeared in many fts5 test files.
[sqlite.git] / src / resolve.c
blobd5c1515a7470b9a7e9e077aa388905092a6cb9f8
1 /*
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.
11 *************************************************************************
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.
17 #include "sqliteInt.h"
20 ** Magic table number to mean the EXCLUDED table in an UPSERT statement.
22 #define EXCLUDED_TABLE_NUMBER 2
25 ** Walk the expression tree pExpr and increase the aggregate function
26 ** depth (the Expr.op2 field) by N on every TK_AGG_FUNCTION node.
27 ** This needs to occur when copying a TK_AGG_FUNCTION node from an
28 ** outer query into an inner subquery.
30 ** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
31 ** is a helper function - a callback for the tree walker.
33 ** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
35 static int incrAggDepth(Walker *pWalker, Expr *pExpr){
36 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
37 return WRC_Continue;
39 static void incrAggFunctionDepth(Expr *pExpr, int N){
40 if( N>0 ){
41 Walker w;
42 memset(&w, 0, sizeof(w));
43 w.xExprCallback = incrAggDepth;
44 w.u.n = N;
45 sqlite3WalkExpr(&w, pExpr);
50 ** Turn the pExpr expression into an alias for the iCol-th column of the
51 ** result set in pEList.
53 ** If the reference is followed by a COLLATE operator, then make sure
54 ** the COLLATE operator is preserved. For example:
56 ** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
58 ** Should be transformed into:
60 ** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
62 ** The nSubquery parameter specifies how many levels of subquery the
63 ** alias is removed from the original expression. The usual value is
64 ** zero but it might be more if the alias is contained within a subquery
65 ** of the original expression. The Expr.op2 field of TK_AGG_FUNCTION
66 ** structures must be increased by the nSubquery amount.
68 static void resolveAlias(
69 Parse *pParse, /* Parsing context */
70 ExprList *pEList, /* A result set */
71 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
72 Expr *pExpr, /* Transform this into an alias to the result set */
73 int nSubquery /* Number of subqueries that the label is moving */
75 Expr *pOrig; /* The iCol-th column of the result set */
76 Expr *pDup; /* Copy of pOrig */
77 sqlite3 *db; /* The database connection */
79 assert( iCol>=0 && iCol<pEList->nExpr );
80 pOrig = pEList->a[iCol].pExpr;
81 assert( pOrig!=0 );
82 assert( !ExprHasProperty(pExpr, EP_Reduced|EP_TokenOnly) );
83 if( pExpr->pAggInfo ) return;
84 db = pParse->db;
85 pDup = sqlite3ExprDup(db, pOrig, 0);
86 if( db->mallocFailed ){
87 sqlite3ExprDelete(db, pDup);
88 pDup = 0;
89 }else{
90 Expr temp;
91 incrAggFunctionDepth(pDup, nSubquery);
92 if( pExpr->op==TK_COLLATE ){
93 assert( !ExprHasProperty(pExpr, EP_IntValue) );
94 pDup = sqlite3ExprAddCollateString(pParse, pDup, pExpr->u.zToken);
96 memcpy(&temp, pDup, sizeof(Expr));
97 memcpy(pDup, pExpr, sizeof(Expr));
98 memcpy(pExpr, &temp, sizeof(Expr));
99 if( ExprHasProperty(pExpr, EP_WinFunc) ){
100 if( ALWAYS(pExpr->y.pWin!=0) ){
101 pExpr->y.pWin->pOwner = pExpr;
104 sqlite3ExprDeferredDelete(pParse, pDup);
109 ** Subqueries store the original database, table and column names for their
110 ** result sets in ExprList.a[].zSpan, in the form "DATABASE.TABLE.COLUMN",
111 ** and mark the expression-list item by setting ExprList.a[].fg.eEName
112 ** to ENAME_TAB.
114 ** Check to see if the zSpan/eEName of the expression-list item passed to this
115 ** routine matches the zDb, zTab, and zCol. If any of zDb, zTab, and zCol are
116 ** NULL then those fields will match anything. Return true if there is a match,
117 ** or false otherwise.
119 ** SF_NestedFrom subqueries also store an entry for the implicit rowid (or
120 ** _rowid_, or oid) column by setting ExprList.a[].fg.eEName to ENAME_ROWID,
121 ** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem
122 ** argument matches if zCol is a rowid alias. If it is not NULL, (*pbRowid)
123 ** is set to 1 if there is this kind of match.
125 int sqlite3MatchEName(
126 const struct ExprList_item *pItem,
127 const char *zCol,
128 const char *zTab,
129 const char *zDb,
130 int *pbRowid
132 int n;
133 const char *zSpan;
134 int eEName = pItem->fg.eEName;
135 if( eEName!=ENAME_TAB && (eEName!=ENAME_ROWID || NEVER(pbRowid==0)) ){
136 return 0;
138 assert( pbRowid==0 || *pbRowid==0 );
139 zSpan = pItem->zEName;
140 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
141 if( zDb && (sqlite3StrNICmp(zSpan, zDb, n)!=0 || zDb[n]!=0) ){
142 return 0;
144 zSpan += n+1;
145 for(n=0; ALWAYS(zSpan[n]) && zSpan[n]!='.'; n++){}
146 if( zTab && (sqlite3StrNICmp(zSpan, zTab, n)!=0 || zTab[n]!=0) ){
147 return 0;
149 zSpan += n+1;
150 if( zCol ){
151 if( eEName==ENAME_TAB && sqlite3StrICmp(zSpan, zCol)!=0 ) return 0;
152 if( eEName==ENAME_ROWID && sqlite3IsRowid(zCol)==0 ) return 0;
154 if( eEName==ENAME_ROWID ) *pbRowid = 1;
155 return 1;
159 ** Return TRUE if the double-quoted string mis-feature should be supported.
161 static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
162 if( db->init.busy ) return 1; /* Always support for legacy schemas */
163 if( pTopNC->ncFlags & NC_IsDDL ){
164 /* Currently parsing a DDL statement */
165 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
166 return 1;
168 return (db->flags & SQLITE_DqsDDL)!=0;
169 }else{
170 /* Currently parsing a DML statement */
171 return (db->flags & SQLITE_DqsDML)!=0;
176 ** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
177 ** return the appropriate colUsed mask.
179 Bitmask sqlite3ExprColUsed(Expr *pExpr){
180 int n;
181 Table *pExTab;
183 n = pExpr->iColumn;
184 assert( ExprUseYTab(pExpr) );
185 pExTab = pExpr->y.pTab;
186 assert( pExTab!=0 );
187 assert( n < pExTab->nCol );
188 if( (pExTab->tabFlags & TF_HasGenerated)!=0
189 && (pExTab->aCol[n].colFlags & COLFLAG_GENERATED)!=0
191 testcase( pExTab->nCol==BMS-1 );
192 testcase( pExTab->nCol==BMS );
193 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
194 }else{
195 testcase( n==BMS-1 );
196 testcase( n==BMS );
197 if( n>=BMS ) n = BMS-1;
198 return ((Bitmask)1)<<n;
203 ** Create a new expression term for the column specified by pMatch and
204 ** iColumn. Append this new expression term to the FULL JOIN Match set
205 ** in *ppList. Create a new *ppList if this is the first term in the
206 ** set.
208 static void extendFJMatch(
209 Parse *pParse, /* Parsing context */
210 ExprList **ppList, /* ExprList to extend */
211 SrcItem *pMatch, /* Source table containing the column */
212 i16 iColumn /* The column number */
214 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
215 if( pNew ){
216 pNew->iTable = pMatch->iCursor;
217 pNew->iColumn = iColumn;
218 pNew->y.pTab = pMatch->pTab;
219 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
220 ExprSetProperty(pNew, EP_CanBeNull);
221 *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
226 ** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
228 static SQLITE_NOINLINE int isValidSchemaTableName(
229 const char *zTab, /* Name as it appears in the SQL */
230 Table *pTab, /* The schema table we are trying to match */
231 const char *zDb /* non-NULL if a database qualifier is present */
233 const char *zLegacy;
234 assert( pTab!=0 );
235 assert( pTab->tnum==1 );
236 if( sqlite3StrNICmp(zTab, "sqlite_", 7)!=0 ) return 0;
237 zLegacy = pTab->zName;
238 if( strcmp(zLegacy+7, &LEGACY_TEMP_SCHEMA_TABLE[7])==0 ){
239 if( sqlite3StrICmp(zTab+7, &PREFERRED_TEMP_SCHEMA_TABLE[7])==0 ){
240 return 1;
242 if( zDb==0 ) return 0;
243 if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
244 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
245 }else{
246 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
248 return 0;
252 ** Given the name of a column of the form X.Y.Z or Y.Z or just Z, look up
253 ** that name in the set of source tables in pSrcList and make the pExpr
254 ** expression node refer back to that source column. The following changes
255 ** are made to pExpr:
257 ** pExpr->iDb Set the index in db->aDb[] of the database X
258 ** (even if X is implied).
259 ** pExpr->iTable Set to the cursor number for the table obtained
260 ** from pSrcList.
261 ** pExpr->y.pTab Points to the Table structure of X.Y (even if
262 ** X and/or Y are implied.)
263 ** pExpr->iColumn Set to the column number within the table.
264 ** pExpr->op Set to TK_COLUMN.
265 ** pExpr->pLeft Any expression this points to is deleted
266 ** pExpr->pRight Any expression this points to is deleted.
268 ** The zDb variable is the name of the database (the "X"). This value may be
269 ** NULL meaning that name is of the form Y.Z or Z. Any available database
270 ** can be used. The zTable variable is the name of the table (the "Y"). This
271 ** value can be NULL if zDb is also NULL. If zTable is NULL it
272 ** means that the form of the name is Z and that columns from any table
273 ** can be used.
275 ** If the name cannot be resolved unambiguously, leave an error message
276 ** in pParse and return WRC_Abort. Return WRC_Prune on success.
278 static int lookupName(
279 Parse *pParse, /* The parsing context */
280 const char *zDb, /* Name of the database containing table, or NULL */
281 const char *zTab, /* Name of table containing column, or NULL */
282 const Expr *pRight, /* Name of the column. */
283 NameContext *pNC, /* The name context used to resolve the name */
284 Expr *pExpr /* Make this EXPR node point to the selected column */
286 int i, j; /* Loop counters */
287 int cnt = 0; /* Number of matching column names */
288 int cntTab = 0; /* Number of potential "rowid" matches */
289 int nSubquery = 0; /* How many levels of subquery */
290 sqlite3 *db = pParse->db; /* The database connection */
291 SrcItem *pItem; /* Use for looping over pSrcList items */
292 SrcItem *pMatch = 0; /* The matching pSrcList item */
293 NameContext *pTopNC = pNC; /* First namecontext in the list */
294 Schema *pSchema = 0; /* Schema of the expression */
295 int eNewExprOp = TK_COLUMN; /* New value for pExpr->op on success */
296 Table *pTab = 0; /* Table holding the row */
297 Column *pCol; /* A column of pTab */
298 ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */
299 const char *zCol = pRight->u.zToken;
301 assert( pNC ); /* the name context cannot be NULL. */
302 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
303 assert( zDb==0 || zTab!=0 );
304 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
306 /* Initialize the node to no-match */
307 pExpr->iTable = -1;
308 ExprSetVVAProperty(pExpr, EP_NoReduce);
310 /* Translate the schema name in zDb into a pointer to the corresponding
311 ** schema. If not found, pSchema will remain NULL and nothing will match
312 ** resulting in an appropriate error message toward the end of this routine
314 if( zDb ){
315 testcase( pNC->ncFlags & NC_PartIdx );
316 testcase( pNC->ncFlags & NC_IsCheck );
317 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
318 /* Silently ignore database qualifiers inside CHECK constraints and
319 ** partial indices. Do not raise errors because that might break
320 ** legacy and because it does not hurt anything to just ignore the
321 ** database name. */
322 zDb = 0;
323 }else{
324 for(i=0; i<db->nDb; i++){
325 assert( db->aDb[i].zDbSName );
326 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
327 pSchema = db->aDb[i].pSchema;
328 break;
331 if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
332 /* This branch is taken when the main database has been renamed
333 ** using SQLITE_DBCONFIG_MAINDBNAME. */
334 pSchema = db->aDb[0].pSchema;
335 zDb = db->aDb[0].zDbSName;
340 /* Start at the inner-most context and move outward until a match is found */
341 assert( pNC && cnt==0 );
343 ExprList *pEList;
344 SrcList *pSrcList = pNC->pSrcList;
346 if( pSrcList ){
347 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
348 u8 hCol;
349 pTab = pItem->pTab;
350 assert( pTab!=0 && pTab->zName!=0 );
351 assert( pTab->nCol>0 || pParse->nErr );
352 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
353 if( pItem->fg.isNestedFrom ){
354 /* In this case, pItem is a subquery that has been formed from a
355 ** parenthesized subset of the FROM clause terms. Example:
356 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
357 ** \_________________________/
358 ** This pItem -------------^
360 int hit = 0;
361 assert( pItem->pSelect!=0 );
362 pEList = pItem->pSelect->pEList;
363 assert( pEList!=0 );
364 assert( pEList->nExpr==pTab->nCol );
365 for(j=0; j<pEList->nExpr; j++){
366 int bRowid = 0; /* True if possible rowid match */
367 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){
368 continue;
370 if( bRowid==0 ){
371 if( cnt>0 ){
372 if( pItem->fg.isUsing==0
373 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
375 /* Two or more tables have the same column name which is
376 ** not joined by USING. This is an error. Signal as much
377 ** by clearing pFJMatch and letting cnt go above 1. */
378 sqlite3ExprListDelete(db, pFJMatch);
379 pFJMatch = 0;
380 }else
381 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
382 /* An INNER or LEFT JOIN. Use the left-most table */
383 continue;
384 }else
385 if( (pItem->fg.jointype & JT_LEFT)==0 ){
386 /* A RIGHT JOIN. Use the right-most table */
387 cnt = 0;
388 sqlite3ExprListDelete(db, pFJMatch);
389 pFJMatch = 0;
390 }else{
391 /* For a FULL JOIN, we must construct a coalesce() func */
392 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
395 cnt++;
396 hit = 1;
397 }else if( cnt>0 ){
398 /* This is a potential rowid match, but there has already been
399 ** a real match found. So this can be ignored. */
400 continue;
402 cntTab++;
403 pMatch = pItem;
404 pExpr->iColumn = j;
405 pEList->a[j].fg.bUsed = 1;
407 /* rowid cannot be part of a USING clause - assert() this. */
408 assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 );
409 if( pEList->a[j].fg.bUsingTerm ) break;
411 if( hit || zTab==0 ) continue;
413 assert( zDb==0 || zTab!=0 );
414 if( zTab ){
415 if( zDb ){
416 if( pTab->pSchema!=pSchema ) continue;
417 if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
419 if( pItem->zAlias!=0 ){
420 if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
421 continue;
423 }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
424 if( pTab->tnum!=1 ) continue;
425 if( !isValidSchemaTableName(zTab, pTab, zDb) ) continue;
427 assert( ExprUseYTab(pExpr) );
428 if( IN_RENAME_OBJECT && pItem->zAlias ){
429 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
432 hCol = sqlite3StrIHash(zCol);
433 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
434 if( pCol->hName==hCol
435 && sqlite3StrICmp(pCol->zCnName, zCol)==0
437 if( cnt>0 ){
438 if( pItem->fg.isUsing==0
439 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
441 /* Two or more tables have the same column name which is
442 ** not joined by USING. This is an error. Signal as much
443 ** by clearing pFJMatch and letting cnt go above 1. */
444 sqlite3ExprListDelete(db, pFJMatch);
445 pFJMatch = 0;
446 }else
447 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
448 /* An INNER or LEFT JOIN. Use the left-most table */
449 continue;
450 }else
451 if( (pItem->fg.jointype & JT_LEFT)==0 ){
452 /* A RIGHT JOIN. Use the right-most table */
453 cnt = 0;
454 sqlite3ExprListDelete(db, pFJMatch);
455 pFJMatch = 0;
456 }else{
457 /* For a FULL JOIN, we must construct a coalesce() func */
458 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
461 cnt++;
462 pMatch = pItem;
463 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY */
464 pExpr->iColumn = j==pTab->iPKey ? -1 : (i16)j;
465 if( pItem->fg.isNestedFrom ){
466 sqlite3SrcItemColumnUsed(pItem, j);
468 break;
471 if( 0==cnt && VisibleRowid(pTab) ){
472 /* pTab is a potential ROWID match. Keep track of it and match
473 ** the ROWID later if that seems appropriate. (Search for "cntTab"
474 ** to find related code.) Only allow a ROWID match if there is
475 ** a single ROWID match candidate.
477 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
478 /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match
479 ** if there is a single VIEW candidate or if there is a single
480 ** non-VIEW candidate plus multiple VIEW candidates. In other
481 ** words non-VIEW candidate terms take precedence over VIEWs.
483 if( cntTab==0
484 || (cntTab==1
485 && ALWAYS(pMatch!=0)
486 && ALWAYS(pMatch->pTab!=0)
487 && (pMatch->pTab->tabFlags & TF_Ephemeral)!=0
488 && (pTab->tabFlags & TF_Ephemeral)==0)
490 cntTab = 1;
491 pMatch = pItem;
492 }else{
493 cntTab++;
495 #else
496 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
497 ** simpler since we require exactly one candidate, which will
498 ** always be a non-VIEW
500 cntTab++;
501 pMatch = pItem;
502 #endif
505 if( pMatch ){
506 pExpr->iTable = pMatch->iCursor;
507 assert( ExprUseYTab(pExpr) );
508 pExpr->y.pTab = pMatch->pTab;
509 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
510 ExprSetProperty(pExpr, EP_CanBeNull);
512 pSchema = pExpr->y.pTab->pSchema;
514 } /* if( pSrcList ) */
516 #if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
517 /* If we have not already resolved the name, then maybe
518 ** it is a new.* or old.* trigger argument reference. Or
519 ** maybe it is an excluded.* from an upsert. Or maybe it is
520 ** a reference in the RETURNING clause to a table being modified.
522 if( cnt==0 && zDb==0 ){
523 pTab = 0;
524 #ifndef SQLITE_OMIT_TRIGGER
525 if( pParse->pTriggerTab!=0 ){
526 int op = pParse->eTriggerOp;
527 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
528 if( pParse->bReturning ){
529 if( (pNC->ncFlags & NC_UBaseReg)!=0
530 && ALWAYS(zTab==0
531 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0
532 || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0))
534 pExpr->iTable = op!=TK_DELETE;
535 pTab = pParse->pTriggerTab;
537 }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
538 pExpr->iTable = 1;
539 pTab = pParse->pTriggerTab;
540 }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
541 pExpr->iTable = 0;
542 pTab = pParse->pTriggerTab;
545 #endif /* SQLITE_OMIT_TRIGGER */
546 #ifndef SQLITE_OMIT_UPSERT
547 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
548 Upsert *pUpsert = pNC->uNC.pUpsert;
549 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
550 pTab = pUpsert->pUpsertSrc->a[0].pTab;
551 pExpr->iTable = EXCLUDED_TABLE_NUMBER;
554 #endif /* SQLITE_OMIT_UPSERT */
556 if( pTab ){
557 int iCol;
558 u8 hCol = sqlite3StrIHash(zCol);
559 pSchema = pTab->pSchema;
560 cntTab++;
561 for(iCol=0, pCol=pTab->aCol; iCol<pTab->nCol; iCol++, pCol++){
562 if( pCol->hName==hCol
563 && sqlite3StrICmp(pCol->zCnName, zCol)==0
565 if( iCol==pTab->iPKey ){
566 iCol = -1;
568 break;
571 if( iCol>=pTab->nCol && sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
572 /* IMP: R-51414-32910 */
573 iCol = -1;
575 if( iCol<pTab->nCol ){
576 cnt++;
577 pMatch = 0;
578 #ifndef SQLITE_OMIT_UPSERT
579 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
580 testcase( iCol==(-1) );
581 assert( ExprUseYTab(pExpr) );
582 if( IN_RENAME_OBJECT ){
583 pExpr->iColumn = iCol;
584 pExpr->y.pTab = pTab;
585 eNewExprOp = TK_COLUMN;
586 }else{
587 pExpr->iTable = pNC->uNC.pUpsert->regData +
588 sqlite3TableColumnToStorage(pTab, iCol);
589 eNewExprOp = TK_REGISTER;
591 }else
592 #endif /* SQLITE_OMIT_UPSERT */
594 assert( ExprUseYTab(pExpr) );
595 pExpr->y.pTab = pTab;
596 if( pParse->bReturning ){
597 eNewExprOp = TK_REGISTER;
598 pExpr->op2 = TK_COLUMN;
599 pExpr->iColumn = iCol;
600 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
601 sqlite3TableColumnToStorage(pTab, iCol) + 1;
602 }else{
603 pExpr->iColumn = (i16)iCol;
604 eNewExprOp = TK_TRIGGER;
605 #ifndef SQLITE_OMIT_TRIGGER
606 if( iCol<0 ){
607 pExpr->affExpr = SQLITE_AFF_INTEGER;
608 }else if( pExpr->iTable==0 ){
609 testcase( iCol==31 );
610 testcase( iCol==32 );
611 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
612 }else{
613 testcase( iCol==31 );
614 testcase( iCol==32 );
615 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
617 #endif /* SQLITE_OMIT_TRIGGER */
623 #endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
626 ** Perhaps the name is a reference to the ROWID
628 if( cnt==0
629 && cntTab>=1
630 && pMatch
631 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
632 && sqlite3IsRowid(zCol)
633 && ALWAYS(VisibleRowid(pMatch->pTab) || pMatch->fg.isNestedFrom)
635 cnt = cntTab;
636 #if SQLITE_ALLOW_ROWID_IN_VIEW+0==2
637 if( pMatch->pTab!=0 && IsView(pMatch->pTab) ){
638 eNewExprOp = TK_NULL;
640 #endif
641 if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1;
642 pExpr->affExpr = SQLITE_AFF_INTEGER;
646 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
647 ** might refer to an result-set alias. This happens, for example, when
648 ** we are resolving names in the WHERE clause of the following command:
650 ** SELECT a+b AS x FROM table WHERE x<10;
652 ** In cases like this, replace pExpr with a copy of the expression that
653 ** forms the result set entry ("a+b" in the example) and return immediately.
654 ** Note that the expression in the result set should have already been
655 ** resolved by the time the WHERE clause is resolved.
657 ** The ability to use an output result-set column in the WHERE, GROUP BY,
658 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
659 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
660 ** is supported for backwards compatibility only. Hence, we issue a warning
661 ** on sqlite3_log() whenever the capability is used.
663 if( cnt==0
664 && (pNC->ncFlags & NC_UEList)!=0
665 && zTab==0
667 pEList = pNC->uNC.pEList;
668 assert( pEList!=0 );
669 for(j=0; j<pEList->nExpr; j++){
670 char *zAs = pEList->a[j].zEName;
671 if( pEList->a[j].fg.eEName==ENAME_NAME
672 && sqlite3_stricmp(zAs, zCol)==0
674 Expr *pOrig;
675 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
676 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
677 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
678 pOrig = pEList->a[j].pExpr;
679 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
680 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
681 return WRC_Abort;
683 if( ExprHasProperty(pOrig, EP_Win)
684 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
686 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
687 return WRC_Abort;
689 if( sqlite3ExprVectorSize(pOrig)!=1 ){
690 sqlite3ErrorMsg(pParse, "row value misused");
691 return WRC_Abort;
693 resolveAlias(pParse, pEList, j, pExpr, nSubquery);
694 cnt = 1;
695 pMatch = 0;
696 assert( zTab==0 && zDb==0 );
697 if( IN_RENAME_OBJECT ){
698 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
700 goto lookupname_end;
705 /* Advance to the next name context. The loop will exit when either
706 ** we have a match (cnt>0) or when we run out of name contexts.
708 if( cnt ) break;
709 pNC = pNC->pNext;
710 nSubquery++;
711 }while( pNC );
715 ** If X and Y are NULL (in other words if only the column name Z is
716 ** supplied) and the value of Z is enclosed in double-quotes, then
717 ** Z is a string literal if it doesn't match any column names. In that
718 ** case, we need to return right away and not make any changes to
719 ** pExpr.
721 ** Because no reference was made to outer contexts, the pNC->nRef
722 ** fields are not changed in any context.
724 if( cnt==0 && zTab==0 ){
725 assert( pExpr->op==TK_ID );
726 if( ExprHasProperty(pExpr,EP_DblQuoted)
727 && areDoubleQuotedStringsEnabled(db, pTopNC)
729 /* If a double-quoted identifier does not match any known column name,
730 ** then treat it as a string.
732 ** This hack was added in the early days of SQLite in a misguided attempt
733 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
734 ** I now sorely regret putting in this hack. The effect of this hack is
735 ** that misspelled identifier names are silently converted into strings
736 ** rather than causing an error, to the frustration of countless
737 ** programmers. To all those frustrated programmers, my apologies.
739 ** Someday, I hope to get rid of this hack. Unfortunately there is
740 ** a huge amount of legacy SQL that uses it. So for now, we just
741 ** issue a warning.
743 sqlite3_log(SQLITE_WARNING,
744 "double-quoted string literal: \"%w\"", zCol);
745 #ifdef SQLITE_ENABLE_NORMALIZE
746 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
747 #endif
748 pExpr->op = TK_STRING;
749 memset(&pExpr->y, 0, sizeof(pExpr->y));
750 return WRC_Prune;
752 if( sqlite3ExprIdToTrueFalse(pExpr) ){
753 return WRC_Prune;
758 ** cnt==0 means there was not match.
759 ** cnt>1 means there were two or more matches.
761 ** cnt==0 is always an error. cnt>1 is often an error, but might
762 ** be multiple matches for a NATURAL LEFT JOIN or a LEFT JOIN USING.
764 assert( pFJMatch==0 || cnt>0 );
765 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
766 if( cnt!=1 ){
767 const char *zErr;
768 if( pFJMatch ){
769 if( pFJMatch->nExpr==cnt-1 ){
770 if( ExprHasProperty(pExpr,EP_Leaf) ){
771 ExprClearProperty(pExpr,EP_Leaf);
772 }else{
773 sqlite3ExprDelete(db, pExpr->pLeft);
774 pExpr->pLeft = 0;
775 sqlite3ExprDelete(db, pExpr->pRight);
776 pExpr->pRight = 0;
778 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
779 pExpr->op = TK_FUNCTION;
780 pExpr->u.zToken = "coalesce";
781 pExpr->x.pList = pFJMatch;
782 cnt = 1;
783 goto lookupname_end;
784 }else{
785 sqlite3ExprListDelete(db, pFJMatch);
786 pFJMatch = 0;
789 zErr = cnt==0 ? "no such column" : "ambiguous column name";
790 if( zDb ){
791 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
792 }else if( zTab ){
793 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
794 }else if( cnt==0 && ExprHasProperty(pRight,EP_DblQuoted) ){
795 sqlite3ErrorMsg(pParse, "%s: \"%s\" - should this be a"
796 " string literal in single-quotes?",
797 zErr, zCol);
798 }else{
799 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
801 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
802 pParse->checkSchema = 1;
803 pTopNC->nNcErr++;
804 eNewExprOp = TK_NULL;
806 assert( pFJMatch==0 );
808 /* Remove all substructure from pExpr */
809 if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
810 sqlite3ExprDelete(db, pExpr->pLeft);
811 pExpr->pLeft = 0;
812 sqlite3ExprDelete(db, pExpr->pRight);
813 pExpr->pRight = 0;
814 ExprSetProperty(pExpr, EP_Leaf);
817 /* If a column from a table in pSrcList is referenced, then record
818 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
819 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
820 ** set if the 63rd or any subsequent column is used.
822 ** The colUsed mask is an optimization used to help determine if an
823 ** index is a covering index. The correct answer is still obtained
824 ** if the mask contains extra set bits. However, it is important to
825 ** avoid setting bits beyond the maximum column number of the table.
826 ** (See ticket [b92e5e8ec2cdbaa1]).
828 ** If a generated column is referenced, set bits for every column
829 ** of the table.
831 if( pMatch ){
832 if( pExpr->iColumn>=0 ){
833 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
834 }else{
835 pMatch->fg.rowidUsed = 1;
839 pExpr->op = eNewExprOp;
840 lookupname_end:
841 if( cnt==1 ){
842 assert( pNC!=0 );
843 #ifndef SQLITE_OMIT_AUTHORIZATION
844 if( pParse->db->xAuth
845 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
847 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
849 #endif
850 /* Increment the nRef value on all name contexts from TopNC up to
851 ** the point where the name matched. */
852 for(;;){
853 assert( pTopNC!=0 );
854 pTopNC->nRef++;
855 if( pTopNC==pNC ) break;
856 pTopNC = pTopNC->pNext;
858 return WRC_Prune;
859 } else {
860 return WRC_Abort;
865 ** Allocate and return a pointer to an expression to load the column iCol
866 ** from datasource iSrc in SrcList pSrc.
868 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
869 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
870 if( p ){
871 SrcItem *pItem = &pSrc->a[iSrc];
872 Table *pTab;
873 assert( ExprUseYTab(p) );
874 pTab = p->y.pTab = pItem->pTab;
875 p->iTable = pItem->iCursor;
876 if( p->y.pTab->iPKey==iCol ){
877 p->iColumn = -1;
878 }else{
879 p->iColumn = (ynVar)iCol;
880 if( (pTab->tabFlags & TF_HasGenerated)!=0
881 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
883 testcase( pTab->nCol==63 );
884 testcase( pTab->nCol==64 );
885 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
886 }else{
887 testcase( iCol==BMS );
888 testcase( iCol==BMS-1 );
889 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
893 return p;
897 ** Report an error that an expression is not valid for some set of
898 ** pNC->ncFlags values determined by validMask.
900 ** static void notValid(
901 ** Parse *pParse, // Leave error message here
902 ** NameContext *pNC, // The name context
903 ** const char *zMsg, // Type of error
904 ** int validMask, // Set of contexts for which prohibited
905 ** Expr *pExpr // Invalidate this expression on error
906 ** ){...}
908 ** As an optimization, since the conditional is almost always false
909 ** (because errors are rare), the conditional is moved outside of the
910 ** function call using a macro.
912 static void notValidImpl(
913 Parse *pParse, /* Leave error message here */
914 NameContext *pNC, /* The name context */
915 const char *zMsg, /* Type of error */
916 Expr *pExpr, /* Invalidate this expression on error */
917 Expr *pError /* Associate error with this expression */
919 const char *zIn = "partial index WHERE clauses";
920 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
921 #ifndef SQLITE_OMIT_CHECK
922 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
923 #endif
924 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
925 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
926 #endif
927 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
928 if( pExpr ) pExpr->op = TK_NULL;
929 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
931 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
932 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
933 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
936 ** Expression p should encode a floating point value between 1.0 and 0.0.
937 ** Return 1024 times this value. Or return -1 if p is not a floating point
938 ** value between 1.0 and 0.0.
940 static int exprProbability(Expr *p){
941 double r = -1.0;
942 if( p->op!=TK_FLOAT ) return -1;
943 assert( !ExprHasProperty(p, EP_IntValue) );
944 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
945 assert( r>=0.0 );
946 if( r>1.0 ) return -1;
947 return (int)(r*134217728.0);
951 ** This routine is callback for sqlite3WalkExpr().
953 ** Resolve symbolic names into TK_COLUMN operators for the current
954 ** node in the expression tree. Return 0 to continue the search down
955 ** the tree or 2 to abort the tree walk.
957 ** This routine also does error checking and name resolution for
958 ** function names. The operator for aggregate functions is changed
959 ** to TK_AGG_FUNCTION.
961 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
962 NameContext *pNC;
963 Parse *pParse;
965 pNC = pWalker->u.pNC;
966 assert( pNC!=0 );
967 pParse = pNC->pParse;
968 assert( pParse==pWalker->pParse );
970 #ifndef NDEBUG
971 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
972 SrcList *pSrcList = pNC->pSrcList;
973 int i;
974 for(i=0; i<pNC->pSrcList->nSrc; i++){
975 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
978 #endif
979 switch( pExpr->op ){
981 /* The special operator TK_ROW means use the rowid for the first
982 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
983 ** clause processing on UPDATE and DELETE statements, and by
984 ** UPDATE ... FROM statement processing.
986 case TK_ROW: {
987 SrcList *pSrcList = pNC->pSrcList;
988 SrcItem *pItem;
989 assert( pSrcList && pSrcList->nSrc>=1 );
990 pItem = pSrcList->a;
991 pExpr->op = TK_COLUMN;
992 assert( ExprUseYTab(pExpr) );
993 pExpr->y.pTab = pItem->pTab;
994 pExpr->iTable = pItem->iCursor;
995 pExpr->iColumn--;
996 pExpr->affExpr = SQLITE_AFF_INTEGER;
997 break;
1000 /* An optimization: Attempt to convert
1002 ** "expr IS NOT NULL" --> "TRUE"
1003 ** "expr IS NULL" --> "FALSE"
1005 ** if we can prove that "expr" is never NULL. Call this the
1006 ** "NOT NULL strength reduction optimization".
1008 ** If this optimization occurs, also restore the NameContext ref-counts
1009 ** to the state they where in before the "column" LHS expression was
1010 ** resolved. This prevents "column" from being counted as having been
1011 ** referenced, which might prevent a SELECT from being erroneously
1012 ** marked as correlated.
1014 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
1015 ** can still evaluate to NULL even though it is marked as NOT NULL.
1016 ** Example:
1018 ** CREATE TABLE t1(a INT NOT NULL);
1019 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
1021 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
1022 ** here because at the time this case is hit, we do not yet know whether
1023 ** or not t1 is being aggregated. We have to assume the worst and omit
1024 ** the optimization. The only time it is safe to apply this optimization
1025 ** is within the WHERE clause.
1027 case TK_NOTNULL:
1028 case TK_ISNULL: {
1029 int anRef[8];
1030 NameContext *p;
1031 int i;
1032 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1033 anRef[i] = p->nRef;
1035 sqlite3WalkExpr(pWalker, pExpr->pLeft);
1036 if( IN_RENAME_OBJECT ) return WRC_Prune;
1037 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
1038 /* The expression can be NULL. So the optimization does not apply */
1039 return WRC_Prune;
1042 for(i=0, p=pNC; p; p=p->pNext, i++){
1043 if( (p->ncFlags & NC_Where)==0 ){
1044 return WRC_Prune; /* Not in a WHERE clause. Unsafe to optimize. */
1047 testcase( ExprHasProperty(pExpr, EP_OuterON) );
1048 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1049 #if TREETRACE_ENABLED
1050 if( sqlite3TreeTrace & 0x80000 ){
1051 sqlite3DebugPrintf(
1052 "NOT NULL strength reduction converts the following to %d:\n",
1053 pExpr->op==TK_NOTNULL
1055 sqlite3ShowExpr(pExpr);
1057 #endif /* TREETRACE_ENABLED */
1058 pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
1059 pExpr->flags |= EP_IntValue;
1060 pExpr->op = TK_INTEGER;
1061 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1062 p->nRef = anRef[i];
1064 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
1065 pExpr->pLeft = 0;
1066 return WRC_Prune;
1069 /* A column name: ID
1070 ** Or table name and column name: ID.ID
1071 ** Or a database, table and column: ID.ID.ID
1073 ** The TK_ID and TK_OUT cases are combined so that there will only
1074 ** be one call to lookupName(). Then the compiler will in-line
1075 ** lookupName() for a size reduction and performance increase.
1077 case TK_ID:
1078 case TK_DOT: {
1079 const char *zTable;
1080 const char *zDb;
1081 Expr *pRight;
1083 if( pExpr->op==TK_ID ){
1084 zDb = 0;
1085 zTable = 0;
1086 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1087 pRight = pExpr;
1088 }else{
1089 Expr *pLeft = pExpr->pLeft;
1090 testcase( pNC->ncFlags & NC_IdxExpr );
1091 testcase( pNC->ncFlags & NC_GenCol );
1092 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
1093 NC_IdxExpr|NC_GenCol, 0, pExpr);
1094 pRight = pExpr->pRight;
1095 if( pRight->op==TK_ID ){
1096 zDb = 0;
1097 }else{
1098 assert( pRight->op==TK_DOT );
1099 assert( !ExprHasProperty(pRight, EP_IntValue) );
1100 zDb = pLeft->u.zToken;
1101 pLeft = pRight->pLeft;
1102 pRight = pRight->pRight;
1104 assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
1105 zTable = pLeft->u.zToken;
1106 assert( ExprUseYTab(pExpr) );
1107 if( IN_RENAME_OBJECT ){
1108 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
1109 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
1112 return lookupName(pParse, zDb, zTable, pRight, pNC, pExpr);
1115 /* Resolve function names
1117 case TK_FUNCTION: {
1118 ExprList *pList = pExpr->x.pList; /* The argument list */
1119 int n = pList ? pList->nExpr : 0; /* Number of arguments */
1120 int no_such_func = 0; /* True if no such function exists */
1121 int wrong_num_args = 0; /* True if wrong number of arguments */
1122 int is_agg = 0; /* True if is an aggregate function */
1123 const char *zId; /* The function name. */
1124 FuncDef *pDef; /* Information about the function */
1125 u8 enc = ENC(pParse->db); /* The database encoding */
1126 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
1127 #ifndef SQLITE_OMIT_WINDOWFUNC
1128 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
1129 #endif
1130 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
1131 assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
1132 zId = pExpr->u.zToken;
1133 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
1134 if( pDef==0 ){
1135 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
1136 if( pDef==0 ){
1137 no_such_func = 1;
1138 }else{
1139 wrong_num_args = 1;
1141 }else{
1142 is_agg = pDef->xFinalize!=0;
1143 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
1144 ExprSetProperty(pExpr, EP_Unlikely);
1145 if( n==2 ){
1146 pExpr->iTable = exprProbability(pList->a[1].pExpr);
1147 if( pExpr->iTable<0 ){
1148 sqlite3ErrorMsg(pParse,
1149 "second argument to %#T() must be a "
1150 "constant between 0.0 and 1.0", pExpr);
1151 pNC->nNcErr++;
1153 }else{
1154 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1155 ** equivalent to likelihood(X, 0.0625).
1156 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1157 ** short-hand for likelihood(X,0.0625).
1158 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1159 ** for likelihood(X,0.9375).
1160 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1161 ** to likelihood(X,0.9375). */
1162 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1163 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
1166 #ifndef SQLITE_OMIT_AUTHORIZATION
1168 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
1169 if( auth!=SQLITE_OK ){
1170 if( auth==SQLITE_DENY ){
1171 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
1172 pExpr);
1173 pNC->nNcErr++;
1175 pExpr->op = TK_NULL;
1176 return WRC_Prune;
1179 #endif
1180 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
1181 /* For the purposes of the EP_ConstFunc flag, date and time
1182 ** functions and other functions that change slowly are considered
1183 ** constant because they are constant for the duration of one query.
1184 ** This allows them to be factored out of inner loops. */
1185 ExprSetProperty(pExpr,EP_ConstFunc);
1187 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
1188 /* Clearly non-deterministic functions like random(), but also
1189 ** date/time functions that use 'now', and other functions like
1190 ** sqlite_version() that might change over time cannot be used
1191 ** in an index or generated column. Curiously, they can be used
1192 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1193 ** all this. */
1194 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
1195 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
1196 }else{
1197 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
1198 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
1199 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
1201 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
1202 && pParse->nested==0
1203 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
1205 /* Internal-use-only functions are disallowed unless the
1206 ** SQL is being compiled using sqlite3NestedParse() or
1207 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1208 ** used to activate internal functions for testing purposes */
1209 no_such_func = 1;
1210 pDef = 0;
1211 }else
1212 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
1213 && !IN_RENAME_OBJECT
1215 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
1219 if( 0==IN_RENAME_OBJECT ){
1220 #ifndef SQLITE_OMIT_WINDOWFUNC
1221 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
1222 || (pDef->xValue==0 && pDef->xInverse==0)
1223 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
1225 if( pDef && pDef->xValue==0 && pWin ){
1226 sqlite3ErrorMsg(pParse,
1227 "%#T() may not be used as a window function", pExpr
1229 pNC->nNcErr++;
1230 }else if(
1231 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
1232 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
1233 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
1235 const char *zType;
1236 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
1237 zType = "window";
1238 }else{
1239 zType = "aggregate";
1241 sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
1242 pNC->nNcErr++;
1243 is_agg = 0;
1245 #else
1246 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
1247 sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
1248 pNC->nNcErr++;
1249 is_agg = 0;
1251 #endif
1252 else if( no_such_func && pParse->db->init.busy==0
1253 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1254 && pParse->explain==0
1255 #endif
1257 sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
1258 pNC->nNcErr++;
1259 }else if( wrong_num_args ){
1260 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
1261 pExpr);
1262 pNC->nNcErr++;
1264 #ifndef SQLITE_OMIT_WINDOWFUNC
1265 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
1266 sqlite3ErrorMsg(pParse,
1267 "FILTER may not be used with non-aggregate %#T()",
1268 pExpr
1270 pNC->nNcErr++;
1272 #endif
1273 else if( is_agg==0 && pExpr->pLeft ){
1274 sqlite3ExprOrderByAggregateError(pParse, pExpr);
1275 pNC->nNcErr++;
1277 if( is_agg ){
1278 /* Window functions may not be arguments of aggregate functions.
1279 ** Or arguments of other window functions. But aggregate functions
1280 ** may be arguments for window functions. */
1281 #ifndef SQLITE_OMIT_WINDOWFUNC
1282 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
1283 #else
1284 pNC->ncFlags &= ~NC_AllowAgg;
1285 #endif
1288 else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){
1289 is_agg = 1;
1291 sqlite3WalkExprList(pWalker, pList);
1292 if( is_agg ){
1293 if( pExpr->pLeft ){
1294 assert( pExpr->pLeft->op==TK_ORDER );
1295 assert( ExprUseXList(pExpr->pLeft) );
1296 sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
1298 #ifndef SQLITE_OMIT_WINDOWFUNC
1299 if( pWin ){
1300 Select *pSel = pNC->pWinSelect;
1301 assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
1302 if( IN_RENAME_OBJECT==0 ){
1303 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
1304 if( pParse->db->mallocFailed ) break;
1306 sqlite3WalkExprList(pWalker, pWin->pPartition);
1307 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
1308 sqlite3WalkExpr(pWalker, pWin->pFilter);
1309 sqlite3WindowLink(pSel, pWin);
1310 pNC->ncFlags |= NC_HasWin;
1311 }else
1312 #endif /* SQLITE_OMIT_WINDOWFUNC */
1314 NameContext *pNC2; /* For looping up thru outer contexts */
1315 pExpr->op = TK_AGG_FUNCTION;
1316 pExpr->op2 = 0;
1317 #ifndef SQLITE_OMIT_WINDOWFUNC
1318 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1319 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
1321 #endif
1322 pNC2 = pNC;
1323 while( pNC2
1324 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
1326 pExpr->op2 += (1 + pNC2->nNestedSelect);
1327 pNC2 = pNC2->pNext;
1329 assert( pDef!=0 || IN_RENAME_OBJECT );
1330 if( pNC2 && pDef ){
1331 pExpr->op2 += pNC2->nNestedSelect;
1332 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
1333 assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
1334 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
1335 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
1336 pNC2->ncFlags |= NC_HasAgg
1337 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
1338 & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
1341 pNC->ncFlags |= savedAllowFlags;
1343 /* FIX ME: Compute pExpr->affinity based on the expected return
1344 ** type of the function
1346 return WRC_Prune;
1348 #ifndef SQLITE_OMIT_SUBQUERY
1349 case TK_SELECT:
1350 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
1351 #endif
1352 case TK_IN: {
1353 testcase( pExpr->op==TK_IN );
1354 if( ExprUseXSelect(pExpr) ){
1355 int nRef = pNC->nRef;
1356 testcase( pNC->ncFlags & NC_IsCheck );
1357 testcase( pNC->ncFlags & NC_PartIdx );
1358 testcase( pNC->ncFlags & NC_IdxExpr );
1359 testcase( pNC->ncFlags & NC_GenCol );
1360 assert( pExpr->x.pSelect );
1361 if( pNC->ncFlags & NC_SelfRef ){
1362 notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
1363 }else{
1364 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1366 assert( pNC->nRef>=nRef );
1367 if( nRef!=pNC->nRef ){
1368 ExprSetProperty(pExpr, EP_VarSelect);
1369 pExpr->x.pSelect->selFlags |= SF_Correlated;
1371 pNC->ncFlags |= NC_Subquery;
1373 break;
1375 case TK_VARIABLE: {
1376 testcase( pNC->ncFlags & NC_IsCheck );
1377 testcase( pNC->ncFlags & NC_PartIdx );
1378 testcase( pNC->ncFlags & NC_IdxExpr );
1379 testcase( pNC->ncFlags & NC_GenCol );
1380 sqlite3ResolveNotValid(pParse, pNC, "parameters",
1381 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
1382 break;
1384 case TK_IS:
1385 case TK_ISNOT: {
1386 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
1387 assert( !ExprHasProperty(pExpr, EP_Reduced) );
1388 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1389 ** and "x IS NOT FALSE". */
1390 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
1391 int rc = resolveExprStep(pWalker, pRight);
1392 if( rc==WRC_Abort ) return WRC_Abort;
1393 if( pRight->op==TK_TRUEFALSE ){
1394 pExpr->op2 = pExpr->op;
1395 pExpr->op = TK_TRUTH;
1396 return WRC_Continue;
1399 /* no break */ deliberate_fall_through
1401 case TK_BETWEEN:
1402 case TK_EQ:
1403 case TK_NE:
1404 case TK_LT:
1405 case TK_LE:
1406 case TK_GT:
1407 case TK_GE: {
1408 int nLeft, nRight;
1409 if( pParse->db->mallocFailed ) break;
1410 assert( pExpr->pLeft!=0 );
1411 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
1412 if( pExpr->op==TK_BETWEEN ){
1413 assert( ExprUseXList(pExpr) );
1414 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1415 if( nRight==nLeft ){
1416 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1418 }else{
1419 assert( pExpr->pRight!=0 );
1420 nRight = sqlite3ExprVectorSize(pExpr->pRight);
1422 if( nLeft!=nRight ){
1423 testcase( pExpr->op==TK_EQ );
1424 testcase( pExpr->op==TK_NE );
1425 testcase( pExpr->op==TK_LT );
1426 testcase( pExpr->op==TK_LE );
1427 testcase( pExpr->op==TK_GT );
1428 testcase( pExpr->op==TK_GE );
1429 testcase( pExpr->op==TK_IS );
1430 testcase( pExpr->op==TK_ISNOT );
1431 testcase( pExpr->op==TK_BETWEEN );
1432 sqlite3ErrorMsg(pParse, "row value misused");
1433 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1435 break;
1438 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
1439 return pParse->nErr ? WRC_Abort : WRC_Continue;
1443 ** pEList is a list of expressions which are really the result set of the
1444 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1445 ** This routine checks to see if pE is a simple identifier which corresponds
1446 ** to the AS-name of one of the terms of the expression list. If it is,
1447 ** this routine return an integer between 1 and N where N is the number of
1448 ** elements in pEList, corresponding to the matching entry. If there is
1449 ** no match, or if pE is not a simple identifier, then this routine
1450 ** return 0.
1452 ** pEList has been resolved. pE has not.
1454 static int resolveAsName(
1455 Parse *pParse, /* Parsing context for error messages */
1456 ExprList *pEList, /* List of expressions to scan */
1457 Expr *pE /* Expression we are trying to match */
1459 int i; /* Loop counter */
1461 UNUSED_PARAMETER(pParse);
1463 if( pE->op==TK_ID ){
1464 const char *zCol;
1465 assert( !ExprHasProperty(pE, EP_IntValue) );
1466 zCol = pE->u.zToken;
1467 for(i=0; i<pEList->nExpr; i++){
1468 if( pEList->a[i].fg.eEName==ENAME_NAME
1469 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
1471 return i+1;
1475 return 0;
1479 ** pE is a pointer to an expression which is a single term in the
1480 ** ORDER BY of a compound SELECT. The expression has not been
1481 ** name resolved.
1483 ** At the point this routine is called, we already know that the
1484 ** ORDER BY term is not an integer index into the result set. That
1485 ** case is handled by the calling routine.
1487 ** Attempt to match pE against result set columns in the left-most
1488 ** SELECT statement. Return the index i of the matching column,
1489 ** as an indication to the caller that it should sort by the i-th column.
1490 ** The left-most column is 1. In other words, the value returned is the
1491 ** same integer value that would be used in the SQL statement to indicate
1492 ** the column.
1494 ** If there is no match, return 0. Return -1 if an error occurs.
1496 static int resolveOrderByTermToExprList(
1497 Parse *pParse, /* Parsing context for error messages */
1498 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
1499 Expr *pE /* The specific ORDER BY term */
1501 int i; /* Loop counter */
1502 ExprList *pEList; /* The columns of the result set */
1503 NameContext nc; /* Name context for resolving pE */
1504 sqlite3 *db; /* Database connection */
1505 int rc; /* Return code from subprocedures */
1506 u8 savedSuppErr; /* Saved value of db->suppressErr */
1508 assert( sqlite3ExprIsInteger(pE, &i, 0)==0 );
1509 pEList = pSelect->pEList;
1511 /* Resolve all names in the ORDER BY term expression
1513 memset(&nc, 0, sizeof(nc));
1514 nc.pParse = pParse;
1515 nc.pSrcList = pSelect->pSrc;
1516 nc.uNC.pEList = pEList;
1517 nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
1518 nc.nNcErr = 0;
1519 db = pParse->db;
1520 savedSuppErr = db->suppressErr;
1521 db->suppressErr = 1;
1522 rc = sqlite3ResolveExprNames(&nc, pE);
1523 db->suppressErr = savedSuppErr;
1524 if( rc ) return 0;
1526 /* Try to match the ORDER BY expression against an expression
1527 ** in the result set. Return an 1-based index of the matching
1528 ** result-set entry.
1530 for(i=0; i<pEList->nExpr; i++){
1531 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
1532 return i+1;
1536 /* If no match, return 0. */
1537 return 0;
1541 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1543 static void resolveOutOfRangeError(
1544 Parse *pParse, /* The error context into which to write the error */
1545 const char *zType, /* "ORDER" or "GROUP" */
1546 int i, /* The index (1-based) of the term out of range */
1547 int mx, /* Largest permissible value of i */
1548 Expr *pError /* Associate the error with the expression */
1550 sqlite3ErrorMsg(pParse,
1551 "%r %s BY term out of range - should be "
1552 "between 1 and %d", i, zType, mx);
1553 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
1557 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1558 ** each term of the ORDER BY clause is a constant integer between 1
1559 ** and N where N is the number of columns in the compound SELECT.
1561 ** ORDER BY terms that are already an integer between 1 and N are
1562 ** unmodified. ORDER BY terms that are integers outside the range of
1563 ** 1 through N generate an error. ORDER BY terms that are expressions
1564 ** are matched against result set expressions of compound SELECT
1565 ** beginning with the left-most SELECT and working toward the right.
1566 ** At the first match, the ORDER BY expression is transformed into
1567 ** the integer column number.
1569 ** Return the number of errors seen.
1571 static int resolveCompoundOrderBy(
1572 Parse *pParse, /* Parsing context. Leave error messages here */
1573 Select *pSelect /* The SELECT statement containing the ORDER BY */
1575 int i;
1576 ExprList *pOrderBy;
1577 ExprList *pEList;
1578 sqlite3 *db;
1579 int moreToDo = 1;
1581 pOrderBy = pSelect->pOrderBy;
1582 if( pOrderBy==0 ) return 0;
1583 db = pParse->db;
1584 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1585 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1586 return 1;
1588 for(i=0; i<pOrderBy->nExpr; i++){
1589 pOrderBy->a[i].fg.done = 0;
1591 pSelect->pNext = 0;
1592 while( pSelect->pPrior ){
1593 pSelect->pPrior->pNext = pSelect;
1594 pSelect = pSelect->pPrior;
1596 while( pSelect && moreToDo ){
1597 struct ExprList_item *pItem;
1598 moreToDo = 0;
1599 pEList = pSelect->pEList;
1600 assert( pEList!=0 );
1601 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1602 int iCol = -1;
1603 Expr *pE, *pDup;
1604 if( pItem->fg.done ) continue;
1605 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
1606 if( NEVER(pE==0) ) continue;
1607 if( sqlite3ExprIsInteger(pE, &iCol, 0) ){
1608 if( iCol<=0 || iCol>pEList->nExpr ){
1609 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
1610 return 1;
1612 }else{
1613 iCol = resolveAsName(pParse, pEList, pE);
1614 if( iCol==0 ){
1615 /* Now test if expression pE matches one of the values returned
1616 ** by pSelect. In the usual case this is done by duplicating the
1617 ** expression, resolving any symbols in it, and then comparing
1618 ** it against each expression returned by the SELECT statement.
1619 ** Once the comparisons are finished, the duplicate expression
1620 ** is deleted.
1622 ** If this is running as part of an ALTER TABLE operation and
1623 ** the symbols resolve successfully, also resolve the symbols in the
1624 ** actual expression. This allows the code in alter.c to modify
1625 ** column references within the ORDER BY expression as required. */
1626 pDup = sqlite3ExprDup(db, pE, 0);
1627 if( !db->mallocFailed ){
1628 assert(pDup);
1629 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
1630 if( IN_RENAME_OBJECT && iCol>0 ){
1631 resolveOrderByTermToExprList(pParse, pSelect, pE);
1634 sqlite3ExprDelete(db, pDup);
1637 if( iCol>0 ){
1638 /* Convert the ORDER BY term into an integer column number iCol,
1639 ** taking care to preserve the COLLATE clause if it exists. */
1640 if( !IN_RENAME_OBJECT ){
1641 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1642 if( pNew==0 ) return 1;
1643 pNew->flags |= EP_IntValue;
1644 pNew->u.iValue = iCol;
1645 if( pItem->pExpr==pE ){
1646 pItem->pExpr = pNew;
1647 }else{
1648 Expr *pParent = pItem->pExpr;
1649 assert( pParent->op==TK_COLLATE );
1650 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1651 assert( pParent->pLeft==pE );
1652 pParent->pLeft = pNew;
1654 sqlite3ExprDelete(db, pE);
1655 pItem->u.x.iOrderByCol = (u16)iCol;
1657 pItem->fg.done = 1;
1658 }else{
1659 moreToDo = 1;
1662 pSelect = pSelect->pNext;
1664 for(i=0; i<pOrderBy->nExpr; i++){
1665 if( pOrderBy->a[i].fg.done==0 ){
1666 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1667 "column in the result set", i+1);
1668 return 1;
1671 return 0;
1675 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1676 ** the SELECT statement pSelect. If any term is reference to a
1677 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1678 ** field) then convert that term into a copy of the corresponding result set
1679 ** column.
1681 ** If any errors are detected, add an error message to pParse and
1682 ** return non-zero. Return zero if no errors are seen.
1684 int sqlite3ResolveOrderGroupBy(
1685 Parse *pParse, /* Parsing context. Leave error messages here */
1686 Select *pSelect, /* The SELECT statement containing the clause */
1687 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
1688 const char *zType /* "ORDER" or "GROUP" */
1690 int i;
1691 sqlite3 *db = pParse->db;
1692 ExprList *pEList;
1693 struct ExprList_item *pItem;
1695 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
1696 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1697 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1698 return 1;
1700 pEList = pSelect->pEList;
1701 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
1702 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1703 if( pItem->u.x.iOrderByCol ){
1704 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1705 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
1706 return 1;
1708 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
1711 return 0;
1714 #ifndef SQLITE_OMIT_WINDOWFUNC
1716 ** Walker callback for windowRemoveExprFromSelect().
1718 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
1719 UNUSED_PARAMETER(pWalker);
1720 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1721 Window *pWin = pExpr->y.pWin;
1722 sqlite3WindowUnlinkFromSelect(pWin);
1724 return WRC_Continue;
1728 ** Remove any Window objects owned by the expression pExpr from the
1729 ** Select.pWin list of Select object pSelect.
1731 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
1732 if( pSelect->pWin ){
1733 Walker sWalker;
1734 memset(&sWalker, 0, sizeof(Walker));
1735 sWalker.xExprCallback = resolveRemoveWindowsCb;
1736 sWalker.u.pSelect = pSelect;
1737 sqlite3WalkExpr(&sWalker, pExpr);
1740 #else
1741 # define windowRemoveExprFromSelect(a, b)
1742 #endif /* SQLITE_OMIT_WINDOWFUNC */
1745 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1746 ** The Name context of the SELECT statement is pNC. zType is either
1747 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1749 ** This routine resolves each term of the clause into an expression.
1750 ** If the order-by term is an integer I between 1 and N (where N is the
1751 ** number of columns in the result set of the SELECT) then the expression
1752 ** in the resolution is a copy of the I-th result-set expression. If
1753 ** the order-by term is an identifier that corresponds to the AS-name of
1754 ** a result-set expression, then the term resolves to a copy of the
1755 ** result-set expression. Otherwise, the expression is resolved in
1756 ** the usual way - using sqlite3ResolveExprNames().
1758 ** This routine returns the number of errors. If errors occur, then
1759 ** an appropriate error message might be left in pParse. (OOM errors
1760 ** excepted.)
1762 static int resolveOrderGroupBy(
1763 NameContext *pNC, /* The name context of the SELECT statement */
1764 Select *pSelect, /* The SELECT statement holding pOrderBy */
1765 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
1766 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
1768 int i, j; /* Loop counters */
1769 int iCol; /* Column number */
1770 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
1771 Parse *pParse; /* Parsing context */
1772 int nResult; /* Number of terms in the result set */
1774 assert( pOrderBy!=0 );
1775 nResult = pSelect->pEList->nExpr;
1776 pParse = pNC->pParse;
1777 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1778 Expr *pE = pItem->pExpr;
1779 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
1780 if( NEVER(pE2==0) ) continue;
1781 if( zType[0]!='G' ){
1782 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1783 if( iCol>0 ){
1784 /* If an AS-name match is found, mark this ORDER BY column as being
1785 ** a copy of the iCol-th result-set column. The subsequent call to
1786 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1787 ** copy of the iCol-th result-set expression. */
1788 pItem->u.x.iOrderByCol = (u16)iCol;
1789 continue;
1792 if( sqlite3ExprIsInteger(pE2, &iCol, 0) ){
1793 /* The ORDER BY term is an integer constant. Again, set the column
1794 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1795 ** order-by term to a copy of the result-set expression */
1796 if( iCol<1 || iCol>0xffff ){
1797 resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
1798 return 1;
1800 pItem->u.x.iOrderByCol = (u16)iCol;
1801 continue;
1804 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1805 pItem->u.x.iOrderByCol = 0;
1806 if( sqlite3ResolveExprNames(pNC, pE) ){
1807 return 1;
1809 for(j=0; j<pSelect->pEList->nExpr; j++){
1810 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1811 /* Since this expression is being changed into a reference
1812 ** to an identical expression in the result set, remove all Window
1813 ** objects belonging to the expression from the Select.pWin list. */
1814 windowRemoveExprFromSelect(pSelect, pE);
1815 pItem->u.x.iOrderByCol = j+1;
1819 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1823 ** Resolve names in the SELECT statement p and all of its descendants.
1825 static int resolveSelectStep(Walker *pWalker, Select *p){
1826 NameContext *pOuterNC; /* Context that contains this SELECT */
1827 NameContext sNC; /* Name context of this SELECT */
1828 int isCompound; /* True if p is a compound select */
1829 int nCompound; /* Number of compound terms processed so far */
1830 Parse *pParse; /* Parsing context */
1831 int i; /* Loop counter */
1832 ExprList *pGroupBy; /* The GROUP BY clause */
1833 Select *pLeftmost; /* Left-most of SELECT of a compound */
1834 sqlite3 *db; /* Database connection */
1837 assert( p!=0 );
1838 if( p->selFlags & SF_Resolved ){
1839 return WRC_Prune;
1841 pOuterNC = pWalker->u.pNC;
1842 pParse = pWalker->pParse;
1843 db = pParse->db;
1845 /* Normally sqlite3SelectExpand() will be called first and will have
1846 ** already expanded this SELECT. However, if this is a subquery within
1847 ** an expression, sqlite3ResolveExprNames() will be called without a
1848 ** prior call to sqlite3SelectExpand(). When that happens, let
1849 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1850 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1851 ** this routine in the correct order.
1853 if( (p->selFlags & SF_Expanded)==0 ){
1854 sqlite3SelectPrep(pParse, p, pOuterNC);
1855 return pParse->nErr ? WRC_Abort : WRC_Prune;
1858 isCompound = p->pPrior!=0;
1859 nCompound = 0;
1860 pLeftmost = p;
1861 while( p ){
1862 assert( (p->selFlags & SF_Expanded)!=0 );
1863 assert( (p->selFlags & SF_Resolved)==0 );
1864 p->selFlags |= SF_Resolved;
1866 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1867 ** are not allowed to refer to any names, so pass an empty NameContext.
1869 memset(&sNC, 0, sizeof(sNC));
1870 sNC.pParse = pParse;
1871 sNC.pWinSelect = p;
1872 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
1873 return WRC_Abort;
1876 /* If the SF_Converted flags is set, then this Select object was
1877 ** was created by the convertCompoundSelectToSubquery() function.
1878 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1879 ** as if it were part of the sub-query, not the parent. This block
1880 ** moves the pOrderBy down to the sub-query. It will be moved back
1881 ** after the names have been resolved. */
1882 if( p->selFlags & SF_Converted ){
1883 Select *pSub = p->pSrc->a[0].pSelect;
1884 assert( p->pSrc->nSrc==1 && p->pOrderBy );
1885 assert( pSub->pPrior && pSub->pOrderBy==0 );
1886 pSub->pOrderBy = p->pOrderBy;
1887 p->pOrderBy = 0;
1890 /* Recursively resolve names in all subqueries in the FROM clause
1892 if( pOuterNC ) pOuterNC->nNestedSelect++;
1893 for(i=0; i<p->pSrc->nSrc; i++){
1894 SrcItem *pItem = &p->pSrc->a[i];
1895 assert( pItem->zName!=0 || pItem->pSelect!=0 );/* Test of tag-20240424-1*/
1896 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
1897 int nRef = pOuterNC ? pOuterNC->nRef : 0;
1898 const char *zSavedContext = pParse->zAuthContext;
1900 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1901 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1902 pParse->zAuthContext = zSavedContext;
1903 if( pParse->nErr ) return WRC_Abort;
1904 assert( db->mallocFailed==0 );
1906 /* If the number of references to the outer context changed when
1907 ** expressions in the sub-select were resolved, the sub-select
1908 ** is correlated. It is not required to check the refcount on any
1909 ** but the innermost outer context object, as lookupName() increments
1910 ** the refcount on all contexts between the current one and the
1911 ** context containing the column when it resolves a name. */
1912 if( pOuterNC ){
1913 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
1914 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
1918 if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
1919 pOuterNC->nNestedSelect--;
1922 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1923 ** resolve the result-set expression list.
1925 sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
1926 sNC.pSrcList = p->pSrc;
1927 sNC.pNext = pOuterNC;
1929 /* Resolve names in the result set. */
1930 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
1931 sNC.ncFlags &= ~NC_AllowWin;
1933 /* If there are no aggregate functions in the result-set, and no GROUP BY
1934 ** expression, do not allow aggregates in any of the other expressions.
1936 assert( (p->selFlags & SF_Aggregate)==0 );
1937 pGroupBy = p->pGroupBy;
1938 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1939 assert( NC_MinMaxAgg==SF_MinMaxAgg );
1940 assert( NC_OrderAgg==SF_OrderByReqd );
1941 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
1942 }else{
1943 sNC.ncFlags &= ~NC_AllowAgg;
1946 /* Add the output column list to the name-context before parsing the
1947 ** other expressions in the SELECT statement. This is so that
1948 ** expressions in the WHERE clause (etc.) can refer to expressions by
1949 ** aliases in the result set.
1951 ** Minor point: If this is the case, then the expression will be
1952 ** re-evaluated for each reference to it.
1954 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
1955 sNC.uNC.pEList = p->pEList;
1956 sNC.ncFlags |= NC_UEList;
1957 if( p->pHaving ){
1958 if( (p->selFlags & SF_Aggregate)==0 ){
1959 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
1960 return WRC_Abort;
1962 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1964 sNC.ncFlags |= NC_Where;
1965 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1966 sNC.ncFlags &= ~NC_Where;
1968 /* Resolve names in table-valued-function arguments */
1969 for(i=0; i<p->pSrc->nSrc; i++){
1970 SrcItem *pItem = &p->pSrc->a[i];
1971 if( pItem->fg.isTabFunc
1972 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
1974 return WRC_Abort;
1978 #ifndef SQLITE_OMIT_WINDOWFUNC
1979 if( IN_RENAME_OBJECT ){
1980 Window *pWin;
1981 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
1982 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
1983 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
1985 return WRC_Abort;
1989 #endif
1991 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1992 ** outer queries
1994 sNC.pNext = 0;
1995 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
1997 /* If this is a converted compound query, move the ORDER BY clause from
1998 ** the sub-query back to the parent query. At this point each term
1999 ** within the ORDER BY clause has been transformed to an integer value.
2000 ** These integers will be replaced by copies of the corresponding result
2001 ** set expressions by the call to resolveOrderGroupBy() below. */
2002 if( p->selFlags & SF_Converted ){
2003 Select *pSub = p->pSrc->a[0].pSelect;
2004 p->pOrderBy = pSub->pOrderBy;
2005 pSub->pOrderBy = 0;
2008 /* Process the ORDER BY clause for singleton SELECT statements.
2009 ** The ORDER BY clause for compounds SELECT statements is handled
2010 ** below, after all of the result-sets for all of the elements of
2011 ** the compound have been resolved.
2013 ** If there is an ORDER BY clause on a term of a compound-select other
2014 ** than the right-most term, then that is a syntax error. But the error
2015 ** is not detected until much later, and so we need to go ahead and
2016 ** resolve those symbols on the incorrect ORDER BY for consistency.
2018 if( p->pOrderBy!=0
2019 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
2020 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
2022 return WRC_Abort;
2024 if( db->mallocFailed ){
2025 return WRC_Abort;
2027 sNC.ncFlags &= ~NC_AllowWin;
2029 /* Resolve the GROUP BY clause. At the same time, make sure
2030 ** the GROUP BY clause does not contain aggregate functions.
2032 if( pGroupBy ){
2033 struct ExprList_item *pItem;
2035 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
2036 return WRC_Abort;
2038 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2039 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2040 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2041 "the GROUP BY clause");
2042 return WRC_Abort;
2047 /* If this is part of a compound SELECT, check that it has the right
2048 ** number of expressions in the select list. */
2049 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
2050 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
2051 return WRC_Abort;
2054 /* Advance to the next term of the compound
2056 p = p->pPrior;
2057 nCompound++;
2060 /* Resolve the ORDER BY on a compound SELECT after all terms of
2061 ** the compound have been resolved.
2063 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
2064 return WRC_Abort;
2067 return WRC_Prune;
2071 ** This routine walks an expression tree and resolves references to
2072 ** table columns and result-set columns. At the same time, do error
2073 ** checking on function usage and set a flag if any aggregate functions
2074 ** are seen.
2076 ** To resolve table columns references we look for nodes (or subtrees) of the
2077 ** form X.Y.Z or Y.Z or just Z where
2079 ** X: The name of a database. Ex: "main" or "temp" or
2080 ** the symbolic name assigned to an ATTACH-ed database.
2082 ** Y: The name of a table in a FROM clause. Or in a trigger
2083 ** one of the special names "old" or "new".
2085 ** Z: The name of a column in table Y.
2087 ** The node at the root of the subtree is modified as follows:
2089 ** Expr.op Changed to TK_COLUMN
2090 ** Expr.pTab Points to the Table object for X.Y
2091 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
2092 ** Expr.iTable The VDBE cursor number for X.Y
2095 ** To resolve result-set references, look for expression nodes of the
2096 ** form Z (with no X and Y prefix) where the Z matches the right-hand
2097 ** size of an AS clause in the result-set of a SELECT. The Z expression
2098 ** is replaced by a copy of the left-hand side of the result-set expression.
2099 ** Table-name and function resolution occurs on the substituted expression
2100 ** tree. For example, in:
2102 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2104 ** The "x" term of the order by is replaced by "a+b" to render:
2106 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2108 ** Function calls are checked to make sure that the function is
2109 ** defined and that the correct number of arguments are specified.
2110 ** If the function is an aggregate function, then the NC_HasAgg flag is
2111 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2112 ** If an expression contains aggregate functions then the EP_Agg
2113 ** property on the expression is set.
2115 ** An error message is left in pParse if anything is amiss. The number
2116 ** if errors is returned.
2118 int sqlite3ResolveExprNames(
2119 NameContext *pNC, /* Namespace to resolve expressions in. */
2120 Expr *pExpr /* The expression to be analyzed. */
2122 int savedHasAgg;
2123 Walker w;
2125 if( pExpr==0 ) return SQLITE_OK;
2126 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2127 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2128 w.pParse = pNC->pParse;
2129 w.xExprCallback = resolveExprStep;
2130 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
2131 w.xSelectCallback2 = 0;
2132 w.u.pNC = pNC;
2133 #if SQLITE_MAX_EXPR_DEPTH>0
2134 w.pParse->nHeight += pExpr->nHeight;
2135 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2136 return SQLITE_ERROR;
2138 #endif
2139 assert( pExpr!=0 );
2140 sqlite3WalkExprNN(&w, pExpr);
2141 #if SQLITE_MAX_EXPR_DEPTH>0
2142 w.pParse->nHeight -= pExpr->nHeight;
2143 #endif
2144 assert( EP_Agg==NC_HasAgg );
2145 assert( EP_Win==NC_HasWin );
2146 testcase( pNC->ncFlags & NC_HasAgg );
2147 testcase( pNC->ncFlags & NC_HasWin );
2148 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2149 pNC->ncFlags |= savedHasAgg;
2150 return pNC->nNcErr>0 || w.pParse->nErr>0;
2154 ** Resolve all names for all expression in an expression list. This is
2155 ** just like sqlite3ResolveExprNames() except that it works for an expression
2156 ** list rather than a single expression.
2158 int sqlite3ResolveExprListNames(
2159 NameContext *pNC, /* Namespace to resolve expressions in. */
2160 ExprList *pList /* The expression list to be analyzed. */
2162 int i;
2163 int savedHasAgg = 0;
2164 Walker w;
2165 if( pList==0 ) return WRC_Continue;
2166 w.pParse = pNC->pParse;
2167 w.xExprCallback = resolveExprStep;
2168 w.xSelectCallback = resolveSelectStep;
2169 w.xSelectCallback2 = 0;
2170 w.u.pNC = pNC;
2171 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2172 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2173 for(i=0; i<pList->nExpr; i++){
2174 Expr *pExpr = pList->a[i].pExpr;
2175 if( pExpr==0 ) continue;
2176 #if SQLITE_MAX_EXPR_DEPTH>0
2177 w.pParse->nHeight += pExpr->nHeight;
2178 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2179 return WRC_Abort;
2181 #endif
2182 sqlite3WalkExprNN(&w, pExpr);
2183 #if SQLITE_MAX_EXPR_DEPTH>0
2184 w.pParse->nHeight -= pExpr->nHeight;
2185 #endif
2186 assert( EP_Agg==NC_HasAgg );
2187 assert( EP_Win==NC_HasWin );
2188 testcase( pNC->ncFlags & NC_HasAgg );
2189 testcase( pNC->ncFlags & NC_HasWin );
2190 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
2191 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2192 savedHasAgg |= pNC->ncFlags &
2193 (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2194 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2196 if( w.pParse->nErr>0 ) return WRC_Abort;
2198 pNC->ncFlags |= savedHasAgg;
2199 return WRC_Continue;
2203 ** Resolve all names in all expressions of a SELECT and in all
2204 ** descendants of the SELECT, including compounds off of p->pPrior,
2205 ** subqueries in expressions, and subqueries used as FROM clause
2206 ** terms.
2208 ** See sqlite3ResolveExprNames() for a description of the kinds of
2209 ** transformations that occur.
2211 ** All SELECT statements should have been expanded using
2212 ** sqlite3SelectExpand() prior to invoking this routine.
2214 void sqlite3ResolveSelectNames(
2215 Parse *pParse, /* The parser context */
2216 Select *p, /* The SELECT statement being coded. */
2217 NameContext *pOuterNC /* Name context for parent SELECT statement */
2219 Walker w;
2221 assert( p!=0 );
2222 w.xExprCallback = resolveExprStep;
2223 w.xSelectCallback = resolveSelectStep;
2224 w.xSelectCallback2 = 0;
2225 w.pParse = pParse;
2226 w.u.pNC = pOuterNC;
2227 sqlite3WalkSelect(&w, p);
2231 ** Resolve names in expressions that can only reference a single table
2232 ** or which cannot reference any tables at all. Examples:
2234 ** "type" flag
2235 ** ------------
2236 ** (1) CHECK constraints NC_IsCheck
2237 ** (2) WHERE clauses on partial indices NC_PartIdx
2238 ** (3) Expressions in indexes on expressions NC_IdxExpr
2239 ** (4) Expression arguments to VACUUM INTO. 0
2240 ** (5) GENERATED ALWAYS as expressions NC_GenCol
2242 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2243 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2244 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2246 ** Any errors cause an error message to be set in pParse.
2248 int sqlite3ResolveSelfReference(
2249 Parse *pParse, /* Parsing context */
2250 Table *pTab, /* The table being referenced, or NULL */
2251 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2252 Expr *pExpr, /* Expression to resolve. May be NULL. */
2253 ExprList *pList /* Expression list to resolve. May be NULL. */
2255 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
2256 NameContext sNC; /* Name context for pParse->pNewTable */
2257 int rc;
2259 assert( type==0 || pTab!=0 );
2260 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2261 || type==NC_GenCol || pTab==0 );
2262 memset(&sNC, 0, sizeof(sNC));
2263 memset(&sSrc, 0, sizeof(sSrc));
2264 if( pTab ){
2265 sSrc.nSrc = 1;
2266 sSrc.a[0].zName = pTab->zName;
2267 sSrc.a[0].pTab = pTab;
2268 sSrc.a[0].iCursor = -1;
2269 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2270 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2271 ** schema elements */
2272 type |= NC_FromDDL;
2275 sNC.pParse = pParse;
2276 sNC.pSrcList = &sSrc;
2277 sNC.ncFlags = type | NC_IsDDL;
2278 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2279 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2280 return rc;