Add tests to bestindexC.test. No changes to code.
[sqlite.git] / src / resolve.c
blob898c78654c98fed94f87fb887a7dfb5ad79217ec
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 Schema *pSchema /* 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( pSchema==0 ) return 0;
243 if( sqlite3StrICmp(zTab+7, &LEGACY_SCHEMA_TABLE[7])==0 ) return 1;
244 if( sqlite3StrICmp(zTab+7, &PREFERRED_SCHEMA_TABLE[7])==0 ) return 1;
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, pSchema) ) continue;
427 assert( ExprUseYTab(pExpr) );
428 if( IN_RENAME_OBJECT && pItem->zAlias ){
429 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
432 hCol = sqlite3StrIHash(zCol);
433 for(j=0, pCol=pTab->aCol; j<pTab->nCol; j++, pCol++){
434 if( pCol->hName==hCol
435 && sqlite3StrICmp(pCol->zCnName, zCol)==0
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( pExpr->iColumn>=0 && cnt==1 && pMatch!=0 ){
832 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
835 pExpr->op = eNewExprOp;
836 lookupname_end:
837 if( cnt==1 ){
838 assert( pNC!=0 );
839 #ifndef SQLITE_OMIT_AUTHORIZATION
840 if( pParse->db->xAuth
841 && (pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER)
843 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
845 #endif
846 /* Increment the nRef value on all name contexts from TopNC up to
847 ** the point where the name matched. */
848 for(;;){
849 assert( pTopNC!=0 );
850 pTopNC->nRef++;
851 if( pTopNC==pNC ) break;
852 pTopNC = pTopNC->pNext;
854 return WRC_Prune;
855 } else {
856 return WRC_Abort;
861 ** Allocate and return a pointer to an expression to load the column iCol
862 ** from datasource iSrc in SrcList pSrc.
864 Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
865 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
866 if( p ){
867 SrcItem *pItem = &pSrc->a[iSrc];
868 Table *pTab;
869 assert( ExprUseYTab(p) );
870 pTab = p->y.pTab = pItem->pTab;
871 p->iTable = pItem->iCursor;
872 if( p->y.pTab->iPKey==iCol ){
873 p->iColumn = -1;
874 }else{
875 p->iColumn = (ynVar)iCol;
876 if( (pTab->tabFlags & TF_HasGenerated)!=0
877 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
879 testcase( pTab->nCol==63 );
880 testcase( pTab->nCol==64 );
881 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
882 }else{
883 testcase( iCol==BMS );
884 testcase( iCol==BMS-1 );
885 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
889 return p;
893 ** Report an error that an expression is not valid for some set of
894 ** pNC->ncFlags values determined by validMask.
896 ** static void notValid(
897 ** Parse *pParse, // Leave error message here
898 ** NameContext *pNC, // The name context
899 ** const char *zMsg, // Type of error
900 ** int validMask, // Set of contexts for which prohibited
901 ** Expr *pExpr // Invalidate this expression on error
902 ** ){...}
904 ** As an optimization, since the conditional is almost always false
905 ** (because errors are rare), the conditional is moved outside of the
906 ** function call using a macro.
908 static void notValidImpl(
909 Parse *pParse, /* Leave error message here */
910 NameContext *pNC, /* The name context */
911 const char *zMsg, /* Type of error */
912 Expr *pExpr, /* Invalidate this expression on error */
913 Expr *pError /* Associate error with this expression */
915 const char *zIn = "partial index WHERE clauses";
916 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
917 #ifndef SQLITE_OMIT_CHECK
918 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
919 #endif
920 #ifndef SQLITE_OMIT_GENERATED_COLUMNS
921 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
922 #endif
923 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
924 if( pExpr ) pExpr->op = TK_NULL;
925 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
927 #define sqlite3ResolveNotValid(P,N,M,X,E,R) \
928 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
929 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
932 ** Expression p should encode a floating point value between 1.0 and 0.0.
933 ** Return 1024 times this value. Or return -1 if p is not a floating point
934 ** value between 1.0 and 0.0.
936 static int exprProbability(Expr *p){
937 double r = -1.0;
938 if( p->op!=TK_FLOAT ) return -1;
939 assert( !ExprHasProperty(p, EP_IntValue) );
940 sqlite3AtoF(p->u.zToken, &r, sqlite3Strlen30(p->u.zToken), SQLITE_UTF8);
941 assert( r>=0.0 );
942 if( r>1.0 ) return -1;
943 return (int)(r*134217728.0);
947 ** This routine is callback for sqlite3WalkExpr().
949 ** Resolve symbolic names into TK_COLUMN operators for the current
950 ** node in the expression tree. Return 0 to continue the search down
951 ** the tree or 2 to abort the tree walk.
953 ** This routine also does error checking and name resolution for
954 ** function names. The operator for aggregate functions is changed
955 ** to TK_AGG_FUNCTION.
957 static int resolveExprStep(Walker *pWalker, Expr *pExpr){
958 NameContext *pNC;
959 Parse *pParse;
961 pNC = pWalker->u.pNC;
962 assert( pNC!=0 );
963 pParse = pNC->pParse;
964 assert( pParse==pWalker->pParse );
966 #ifndef NDEBUG
967 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
968 SrcList *pSrcList = pNC->pSrcList;
969 int i;
970 for(i=0; i<pNC->pSrcList->nSrc; i++){
971 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
974 #endif
975 switch( pExpr->op ){
977 /* The special operator TK_ROW means use the rowid for the first
978 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
979 ** clause processing on UPDATE and DELETE statements, and by
980 ** UPDATE ... FROM statement processing.
982 case TK_ROW: {
983 SrcList *pSrcList = pNC->pSrcList;
984 SrcItem *pItem;
985 assert( pSrcList && pSrcList->nSrc>=1 );
986 pItem = pSrcList->a;
987 pExpr->op = TK_COLUMN;
988 assert( ExprUseYTab(pExpr) );
989 pExpr->y.pTab = pItem->pTab;
990 pExpr->iTable = pItem->iCursor;
991 pExpr->iColumn--;
992 pExpr->affExpr = SQLITE_AFF_INTEGER;
993 break;
996 /* An optimization: Attempt to convert
998 ** "expr IS NOT NULL" --> "TRUE"
999 ** "expr IS NULL" --> "FALSE"
1001 ** if we can prove that "expr" is never NULL. Call this the
1002 ** "NOT NULL strength reduction optimization".
1004 ** If this optimization occurs, also restore the NameContext ref-counts
1005 ** to the state they where in before the "column" LHS expression was
1006 ** resolved. This prevents "column" from being counted as having been
1007 ** referenced, which might prevent a SELECT from being erroneously
1008 ** marked as correlated.
1010 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
1011 ** can still evaluate to NULL even though it is marked as NOT NULL.
1012 ** Example:
1014 ** CREATE TABLE t1(a INT NOT NULL);
1015 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
1017 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
1018 ** here because at the time this case is hit, we do not yet know whether
1019 ** or not t1 is being aggregated. We have to assume the worst and omit
1020 ** the optimization. The only time it is safe to apply this optimization
1021 ** is within the WHERE clause.
1023 case TK_NOTNULL:
1024 case TK_ISNULL: {
1025 int anRef[8];
1026 NameContext *p;
1027 int i;
1028 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1029 anRef[i] = p->nRef;
1031 sqlite3WalkExpr(pWalker, pExpr->pLeft);
1032 if( IN_RENAME_OBJECT ) return WRC_Prune;
1033 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
1034 /* The expression can be NULL. So the optimization does not apply */
1035 return WRC_Prune;
1038 for(i=0, p=pNC; p; p=p->pNext, i++){
1039 if( (p->ncFlags & NC_Where)==0 ){
1040 return WRC_Prune; /* Not in a WHERE clause. Unsafe to optimize. */
1043 testcase( ExprHasProperty(pExpr, EP_OuterON) );
1044 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1045 #if TREETRACE_ENABLED
1046 if( sqlite3TreeTrace & 0x80000 ){
1047 sqlite3DebugPrintf(
1048 "NOT NULL strength reduction converts the following to %d:\n",
1049 pExpr->op==TK_NOTNULL
1051 sqlite3ShowExpr(pExpr);
1053 #endif /* TREETRACE_ENABLED */
1054 pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
1055 pExpr->flags |= EP_IntValue;
1056 pExpr->op = TK_INTEGER;
1057 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1058 p->nRef = anRef[i];
1060 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
1061 pExpr->pLeft = 0;
1062 return WRC_Prune;
1065 /* A column name: ID
1066 ** Or table name and column name: ID.ID
1067 ** Or a database, table and column: ID.ID.ID
1069 ** The TK_ID and TK_OUT cases are combined so that there will only
1070 ** be one call to lookupName(). Then the compiler will in-line
1071 ** lookupName() for a size reduction and performance increase.
1073 case TK_ID:
1074 case TK_DOT: {
1075 const char *zTable;
1076 const char *zDb;
1077 Expr *pRight;
1079 if( pExpr->op==TK_ID ){
1080 zDb = 0;
1081 zTable = 0;
1082 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1083 pRight = pExpr;
1084 }else{
1085 Expr *pLeft = pExpr->pLeft;
1086 testcase( pNC->ncFlags & NC_IdxExpr );
1087 testcase( pNC->ncFlags & NC_GenCol );
1088 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
1089 NC_IdxExpr|NC_GenCol, 0, pExpr);
1090 pRight = pExpr->pRight;
1091 if( pRight->op==TK_ID ){
1092 zDb = 0;
1093 }else{
1094 assert( pRight->op==TK_DOT );
1095 assert( !ExprHasProperty(pRight, EP_IntValue) );
1096 zDb = pLeft->u.zToken;
1097 pLeft = pRight->pLeft;
1098 pRight = pRight->pRight;
1100 assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
1101 zTable = pLeft->u.zToken;
1102 assert( ExprUseYTab(pExpr) );
1103 if( IN_RENAME_OBJECT ){
1104 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
1105 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
1108 return lookupName(pParse, zDb, zTable, pRight, pNC, pExpr);
1111 /* Resolve function names
1113 case TK_FUNCTION: {
1114 ExprList *pList = pExpr->x.pList; /* The argument list */
1115 int n = pList ? pList->nExpr : 0; /* Number of arguments */
1116 int no_such_func = 0; /* True if no such function exists */
1117 int wrong_num_args = 0; /* True if wrong number of arguments */
1118 int is_agg = 0; /* True if is an aggregate function */
1119 const char *zId; /* The function name. */
1120 FuncDef *pDef; /* Information about the function */
1121 u8 enc = ENC(pParse->db); /* The database encoding */
1122 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
1123 #ifndef SQLITE_OMIT_WINDOWFUNC
1124 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
1125 #endif
1126 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
1127 assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
1128 zId = pExpr->u.zToken;
1129 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
1130 if( pDef==0 ){
1131 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
1132 if( pDef==0 ){
1133 no_such_func = 1;
1134 }else{
1135 wrong_num_args = 1;
1137 }else{
1138 is_agg = pDef->xFinalize!=0;
1139 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
1140 ExprSetProperty(pExpr, EP_Unlikely);
1141 if( n==2 ){
1142 pExpr->iTable = exprProbability(pList->a[1].pExpr);
1143 if( pExpr->iTable<0 ){
1144 sqlite3ErrorMsg(pParse,
1145 "second argument to %#T() must be a "
1146 "constant between 0.0 and 1.0", pExpr);
1147 pNC->nNcErr++;
1149 }else{
1150 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1151 ** equivalent to likelihood(X, 0.0625).
1152 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1153 ** short-hand for likelihood(X,0.0625).
1154 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1155 ** for likelihood(X,0.9375).
1156 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1157 ** to likelihood(X,0.9375). */
1158 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1159 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
1162 #ifndef SQLITE_OMIT_AUTHORIZATION
1164 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
1165 if( auth!=SQLITE_OK ){
1166 if( auth==SQLITE_DENY ){
1167 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
1168 pExpr);
1169 pNC->nNcErr++;
1171 pExpr->op = TK_NULL;
1172 return WRC_Prune;
1175 #endif
1176 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
1177 /* For the purposes of the EP_ConstFunc flag, date and time
1178 ** functions and other functions that change slowly are considered
1179 ** constant because they are constant for the duration of one query.
1180 ** This allows them to be factored out of inner loops. */
1181 ExprSetProperty(pExpr,EP_ConstFunc);
1183 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
1184 /* Clearly non-deterministic functions like random(), but also
1185 ** date/time functions that use 'now', and other functions like
1186 ** sqlite_version() that might change over time cannot be used
1187 ** in an index or generated column. Curiously, they can be used
1188 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1189 ** all this. */
1190 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
1191 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
1192 }else{
1193 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
1194 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
1195 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
1197 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
1198 && pParse->nested==0
1199 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
1201 /* Internal-use-only functions are disallowed unless the
1202 ** SQL is being compiled using sqlite3NestedParse() or
1203 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1204 ** used to activate internal functions for testing purposes */
1205 no_such_func = 1;
1206 pDef = 0;
1207 }else
1208 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
1209 && !IN_RENAME_OBJECT
1211 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
1215 if( 0==IN_RENAME_OBJECT ){
1216 #ifndef SQLITE_OMIT_WINDOWFUNC
1217 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
1218 || (pDef->xValue==0 && pDef->xInverse==0)
1219 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
1221 if( pDef && pDef->xValue==0 && pWin ){
1222 sqlite3ErrorMsg(pParse,
1223 "%#T() may not be used as a window function", pExpr
1225 pNC->nNcErr++;
1226 }else if(
1227 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
1228 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
1229 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
1231 const char *zType;
1232 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
1233 zType = "window";
1234 }else{
1235 zType = "aggregate";
1237 sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
1238 pNC->nNcErr++;
1239 is_agg = 0;
1241 #else
1242 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
1243 sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
1244 pNC->nNcErr++;
1245 is_agg = 0;
1247 #endif
1248 else if( no_such_func && pParse->db->init.busy==0
1249 #ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1250 && pParse->explain==0
1251 #endif
1253 sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
1254 pNC->nNcErr++;
1255 }else if( wrong_num_args ){
1256 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
1257 pExpr);
1258 pNC->nNcErr++;
1260 #ifndef SQLITE_OMIT_WINDOWFUNC
1261 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
1262 sqlite3ErrorMsg(pParse,
1263 "FILTER may not be used with non-aggregate %#T()",
1264 pExpr
1266 pNC->nNcErr++;
1268 #endif
1269 else if( is_agg==0 && pExpr->pLeft ){
1270 sqlite3ExprOrderByAggregateError(pParse, pExpr);
1271 pNC->nNcErr++;
1273 if( is_agg ){
1274 /* Window functions may not be arguments of aggregate functions.
1275 ** Or arguments of other window functions. But aggregate functions
1276 ** may be arguments for window functions. */
1277 #ifndef SQLITE_OMIT_WINDOWFUNC
1278 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
1279 #else
1280 pNC->ncFlags &= ~NC_AllowAgg;
1281 #endif
1284 #ifndef SQLITE_OMIT_WINDOWFUNC
1285 else if( ExprHasProperty(pExpr, EP_WinFunc) ){
1286 is_agg = 1;
1288 #endif
1289 sqlite3WalkExprList(pWalker, pList);
1290 if( is_agg ){
1291 if( pExpr->pLeft ){
1292 assert( pExpr->pLeft->op==TK_ORDER );
1293 assert( ExprUseXList(pExpr->pLeft) );
1294 sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
1296 #ifndef SQLITE_OMIT_WINDOWFUNC
1297 if( pWin ){
1298 Select *pSel = pNC->pWinSelect;
1299 assert( pWin==0 || (ExprUseYWin(pExpr) && pWin==pExpr->y.pWin) );
1300 if( IN_RENAME_OBJECT==0 ){
1301 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
1302 if( pParse->db->mallocFailed ) break;
1304 sqlite3WalkExprList(pWalker, pWin->pPartition);
1305 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
1306 sqlite3WalkExpr(pWalker, pWin->pFilter);
1307 sqlite3WindowLink(pSel, pWin);
1308 pNC->ncFlags |= NC_HasWin;
1309 }else
1310 #endif /* SQLITE_OMIT_WINDOWFUNC */
1312 NameContext *pNC2; /* For looping up thru outer contexts */
1313 pExpr->op = TK_AGG_FUNCTION;
1314 pExpr->op2 = 0;
1315 #ifndef SQLITE_OMIT_WINDOWFUNC
1316 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1317 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
1319 #endif
1320 pNC2 = pNC;
1321 while( pNC2
1322 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
1324 pExpr->op2 += (1 + pNC2->nNestedSelect);
1325 pNC2 = pNC2->pNext;
1327 assert( pDef!=0 || IN_RENAME_OBJECT );
1328 if( pNC2 && pDef ){
1329 pExpr->op2 += pNC2->nNestedSelect;
1330 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
1331 assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
1332 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
1333 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
1334 pNC2->ncFlags |= NC_HasAgg
1335 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
1336 & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
1339 pNC->ncFlags |= savedAllowFlags;
1341 /* FIX ME: Compute pExpr->affinity based on the expected return
1342 ** type of the function
1344 return WRC_Prune;
1346 #ifndef SQLITE_OMIT_SUBQUERY
1347 case TK_SELECT:
1348 case TK_EXISTS: testcase( pExpr->op==TK_EXISTS );
1349 #endif
1350 case TK_IN: {
1351 testcase( pExpr->op==TK_IN );
1352 if( ExprUseXSelect(pExpr) ){
1353 int nRef = pNC->nRef;
1354 testcase( pNC->ncFlags & NC_IsCheck );
1355 testcase( pNC->ncFlags & NC_PartIdx );
1356 testcase( pNC->ncFlags & NC_IdxExpr );
1357 testcase( pNC->ncFlags & NC_GenCol );
1358 assert( pExpr->x.pSelect );
1359 if( pNC->ncFlags & NC_SelfRef ){
1360 notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
1361 }else{
1362 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1364 assert( pNC->nRef>=nRef );
1365 if( nRef!=pNC->nRef ){
1366 ExprSetProperty(pExpr, EP_VarSelect);
1367 pExpr->x.pSelect->selFlags |= SF_Correlated;
1369 pNC->ncFlags |= NC_Subquery;
1371 break;
1373 case TK_VARIABLE: {
1374 testcase( pNC->ncFlags & NC_IsCheck );
1375 testcase( pNC->ncFlags & NC_PartIdx );
1376 testcase( pNC->ncFlags & NC_IdxExpr );
1377 testcase( pNC->ncFlags & NC_GenCol );
1378 sqlite3ResolveNotValid(pParse, pNC, "parameters",
1379 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
1380 break;
1382 case TK_IS:
1383 case TK_ISNOT: {
1384 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
1385 assert( !ExprHasProperty(pExpr, EP_Reduced) );
1386 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1387 ** and "x IS NOT FALSE". */
1388 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
1389 int rc = resolveExprStep(pWalker, pRight);
1390 if( rc==WRC_Abort ) return WRC_Abort;
1391 if( pRight->op==TK_TRUEFALSE ){
1392 pExpr->op2 = pExpr->op;
1393 pExpr->op = TK_TRUTH;
1394 return WRC_Continue;
1397 /* no break */ deliberate_fall_through
1399 case TK_BETWEEN:
1400 case TK_EQ:
1401 case TK_NE:
1402 case TK_LT:
1403 case TK_LE:
1404 case TK_GT:
1405 case TK_GE: {
1406 int nLeft, nRight;
1407 if( pParse->db->mallocFailed ) break;
1408 assert( pExpr->pLeft!=0 );
1409 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
1410 if( pExpr->op==TK_BETWEEN ){
1411 assert( ExprUseXList(pExpr) );
1412 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1413 if( nRight==nLeft ){
1414 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1416 }else{
1417 assert( pExpr->pRight!=0 );
1418 nRight = sqlite3ExprVectorSize(pExpr->pRight);
1420 if( nLeft!=nRight ){
1421 testcase( pExpr->op==TK_EQ );
1422 testcase( pExpr->op==TK_NE );
1423 testcase( pExpr->op==TK_LT );
1424 testcase( pExpr->op==TK_LE );
1425 testcase( pExpr->op==TK_GT );
1426 testcase( pExpr->op==TK_GE );
1427 testcase( pExpr->op==TK_IS );
1428 testcase( pExpr->op==TK_ISNOT );
1429 testcase( pExpr->op==TK_BETWEEN );
1430 sqlite3ErrorMsg(pParse, "row value misused");
1431 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1433 break;
1436 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
1437 return pParse->nErr ? WRC_Abort : WRC_Continue;
1441 ** pEList is a list of expressions which are really the result set of the
1442 ** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1443 ** This routine checks to see if pE is a simple identifier which corresponds
1444 ** to the AS-name of one of the terms of the expression list. If it is,
1445 ** this routine return an integer between 1 and N where N is the number of
1446 ** elements in pEList, corresponding to the matching entry. If there is
1447 ** no match, or if pE is not a simple identifier, then this routine
1448 ** return 0.
1450 ** pEList has been resolved. pE has not.
1452 static int resolveAsName(
1453 Parse *pParse, /* Parsing context for error messages */
1454 ExprList *pEList, /* List of expressions to scan */
1455 Expr *pE /* Expression we are trying to match */
1457 int i; /* Loop counter */
1459 UNUSED_PARAMETER(pParse);
1461 if( pE->op==TK_ID ){
1462 const char *zCol;
1463 assert( !ExprHasProperty(pE, EP_IntValue) );
1464 zCol = pE->u.zToken;
1465 for(i=0; i<pEList->nExpr; i++){
1466 if( pEList->a[i].fg.eEName==ENAME_NAME
1467 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
1469 return i+1;
1473 return 0;
1477 ** pE is a pointer to an expression which is a single term in the
1478 ** ORDER BY of a compound SELECT. The expression has not been
1479 ** name resolved.
1481 ** At the point this routine is called, we already know that the
1482 ** ORDER BY term is not an integer index into the result set. That
1483 ** case is handled by the calling routine.
1485 ** Attempt to match pE against result set columns in the left-most
1486 ** SELECT statement. Return the index i of the matching column,
1487 ** as an indication to the caller that it should sort by the i-th column.
1488 ** The left-most column is 1. In other words, the value returned is the
1489 ** same integer value that would be used in the SQL statement to indicate
1490 ** the column.
1492 ** If there is no match, return 0. Return -1 if an error occurs.
1494 static int resolveOrderByTermToExprList(
1495 Parse *pParse, /* Parsing context for error messages */
1496 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
1497 Expr *pE /* The specific ORDER BY term */
1499 int i; /* Loop counter */
1500 ExprList *pEList; /* The columns of the result set */
1501 NameContext nc; /* Name context for resolving pE */
1502 sqlite3 *db; /* Database connection */
1503 int rc; /* Return code from subprocedures */
1504 u8 savedSuppErr; /* Saved value of db->suppressErr */
1506 assert( sqlite3ExprIsInteger(pE, &i)==0 );
1507 pEList = pSelect->pEList;
1509 /* Resolve all names in the ORDER BY term expression
1511 memset(&nc, 0, sizeof(nc));
1512 nc.pParse = pParse;
1513 nc.pSrcList = pSelect->pSrc;
1514 nc.uNC.pEList = pEList;
1515 nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
1516 nc.nNcErr = 0;
1517 db = pParse->db;
1518 savedSuppErr = db->suppressErr;
1519 db->suppressErr = 1;
1520 rc = sqlite3ResolveExprNames(&nc, pE);
1521 db->suppressErr = savedSuppErr;
1522 if( rc ) return 0;
1524 /* Try to match the ORDER BY expression against an expression
1525 ** in the result set. Return an 1-based index of the matching
1526 ** result-set entry.
1528 for(i=0; i<pEList->nExpr; i++){
1529 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
1530 return i+1;
1534 /* If no match, return 0. */
1535 return 0;
1539 ** Generate an ORDER BY or GROUP BY term out-of-range error.
1541 static void resolveOutOfRangeError(
1542 Parse *pParse, /* The error context into which to write the error */
1543 const char *zType, /* "ORDER" or "GROUP" */
1544 int i, /* The index (1-based) of the term out of range */
1545 int mx, /* Largest permissible value of i */
1546 Expr *pError /* Associate the error with the expression */
1548 sqlite3ErrorMsg(pParse,
1549 "%r %s BY term out of range - should be "
1550 "between 1 and %d", i, zType, mx);
1551 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
1555 ** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1556 ** each term of the ORDER BY clause is a constant integer between 1
1557 ** and N where N is the number of columns in the compound SELECT.
1559 ** ORDER BY terms that are already an integer between 1 and N are
1560 ** unmodified. ORDER BY terms that are integers outside the range of
1561 ** 1 through N generate an error. ORDER BY terms that are expressions
1562 ** are matched against result set expressions of compound SELECT
1563 ** beginning with the left-most SELECT and working toward the right.
1564 ** At the first match, the ORDER BY expression is transformed into
1565 ** the integer column number.
1567 ** Return the number of errors seen.
1569 static int resolveCompoundOrderBy(
1570 Parse *pParse, /* Parsing context. Leave error messages here */
1571 Select *pSelect /* The SELECT statement containing the ORDER BY */
1573 int i;
1574 ExprList *pOrderBy;
1575 ExprList *pEList;
1576 sqlite3 *db;
1577 int moreToDo = 1;
1579 pOrderBy = pSelect->pOrderBy;
1580 if( pOrderBy==0 ) return 0;
1581 db = pParse->db;
1582 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1583 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1584 return 1;
1586 for(i=0; i<pOrderBy->nExpr; i++){
1587 pOrderBy->a[i].fg.done = 0;
1589 pSelect->pNext = 0;
1590 while( pSelect->pPrior ){
1591 pSelect->pPrior->pNext = pSelect;
1592 pSelect = pSelect->pPrior;
1594 while( pSelect && moreToDo ){
1595 struct ExprList_item *pItem;
1596 moreToDo = 0;
1597 pEList = pSelect->pEList;
1598 assert( pEList!=0 );
1599 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1600 int iCol = -1;
1601 Expr *pE, *pDup;
1602 if( pItem->fg.done ) continue;
1603 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
1604 if( NEVER(pE==0) ) continue;
1605 if( sqlite3ExprIsInteger(pE, &iCol) ){
1606 if( iCol<=0 || iCol>pEList->nExpr ){
1607 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
1608 return 1;
1610 }else{
1611 iCol = resolveAsName(pParse, pEList, pE);
1612 if( iCol==0 ){
1613 /* Now test if expression pE matches one of the values returned
1614 ** by pSelect. In the usual case this is done by duplicating the
1615 ** expression, resolving any symbols in it, and then comparing
1616 ** it against each expression returned by the SELECT statement.
1617 ** Once the comparisons are finished, the duplicate expression
1618 ** is deleted.
1620 ** If this is running as part of an ALTER TABLE operation and
1621 ** the symbols resolve successfully, also resolve the symbols in the
1622 ** actual expression. This allows the code in alter.c to modify
1623 ** column references within the ORDER BY expression as required. */
1624 pDup = sqlite3ExprDup(db, pE, 0);
1625 if( !db->mallocFailed ){
1626 assert(pDup);
1627 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
1628 if( IN_RENAME_OBJECT && iCol>0 ){
1629 resolveOrderByTermToExprList(pParse, pSelect, pE);
1632 sqlite3ExprDelete(db, pDup);
1635 if( iCol>0 ){
1636 /* Convert the ORDER BY term into an integer column number iCol,
1637 ** taking care to preserve the COLLATE clause if it exists. */
1638 if( !IN_RENAME_OBJECT ){
1639 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
1640 if( pNew==0 ) return 1;
1641 pNew->flags |= EP_IntValue;
1642 pNew->u.iValue = iCol;
1643 if( pItem->pExpr==pE ){
1644 pItem->pExpr = pNew;
1645 }else{
1646 Expr *pParent = pItem->pExpr;
1647 assert( pParent->op==TK_COLLATE );
1648 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1649 assert( pParent->pLeft==pE );
1650 pParent->pLeft = pNew;
1652 sqlite3ExprDelete(db, pE);
1653 pItem->u.x.iOrderByCol = (u16)iCol;
1655 pItem->fg.done = 1;
1656 }else{
1657 moreToDo = 1;
1660 pSelect = pSelect->pNext;
1662 for(i=0; i<pOrderBy->nExpr; i++){
1663 if( pOrderBy->a[i].fg.done==0 ){
1664 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1665 "column in the result set", i+1);
1666 return 1;
1669 return 0;
1673 ** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1674 ** the SELECT statement pSelect. If any term is reference to a
1675 ** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1676 ** field) then convert that term into a copy of the corresponding result set
1677 ** column.
1679 ** If any errors are detected, add an error message to pParse and
1680 ** return non-zero. Return zero if no errors are seen.
1682 int sqlite3ResolveOrderGroupBy(
1683 Parse *pParse, /* Parsing context. Leave error messages here */
1684 Select *pSelect, /* The SELECT statement containing the clause */
1685 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
1686 const char *zType /* "ORDER" or "GROUP" */
1688 int i;
1689 sqlite3 *db = pParse->db;
1690 ExprList *pEList;
1691 struct ExprList_item *pItem;
1693 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
1694 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1695 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1696 return 1;
1698 pEList = pSelect->pEList;
1699 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
1700 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1701 if( pItem->u.x.iOrderByCol ){
1702 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1703 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
1704 return 1;
1706 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
1709 return 0;
1712 #ifndef SQLITE_OMIT_WINDOWFUNC
1714 ** Walker callback for windowRemoveExprFromSelect().
1716 static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
1717 UNUSED_PARAMETER(pWalker);
1718 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1719 Window *pWin = pExpr->y.pWin;
1720 sqlite3WindowUnlinkFromSelect(pWin);
1722 return WRC_Continue;
1726 ** Remove any Window objects owned by the expression pExpr from the
1727 ** Select.pWin list of Select object pSelect.
1729 static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
1730 if( pSelect->pWin ){
1731 Walker sWalker;
1732 memset(&sWalker, 0, sizeof(Walker));
1733 sWalker.xExprCallback = resolveRemoveWindowsCb;
1734 sWalker.u.pSelect = pSelect;
1735 sqlite3WalkExpr(&sWalker, pExpr);
1738 #else
1739 # define windowRemoveExprFromSelect(a, b)
1740 #endif /* SQLITE_OMIT_WINDOWFUNC */
1743 ** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1744 ** The Name context of the SELECT statement is pNC. zType is either
1745 ** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1747 ** This routine resolves each term of the clause into an expression.
1748 ** If the order-by term is an integer I between 1 and N (where N is the
1749 ** number of columns in the result set of the SELECT) then the expression
1750 ** in the resolution is a copy of the I-th result-set expression. If
1751 ** the order-by term is an identifier that corresponds to the AS-name of
1752 ** a result-set expression, then the term resolves to a copy of the
1753 ** result-set expression. Otherwise, the expression is resolved in
1754 ** the usual way - using sqlite3ResolveExprNames().
1756 ** This routine returns the number of errors. If errors occur, then
1757 ** an appropriate error message might be left in pParse. (OOM errors
1758 ** excepted.)
1760 static int resolveOrderGroupBy(
1761 NameContext *pNC, /* The name context of the SELECT statement */
1762 Select *pSelect, /* The SELECT statement holding pOrderBy */
1763 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
1764 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
1766 int i, j; /* Loop counters */
1767 int iCol; /* Column number */
1768 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
1769 Parse *pParse; /* Parsing context */
1770 int nResult; /* Number of terms in the result set */
1772 assert( pOrderBy!=0 );
1773 nResult = pSelect->pEList->nExpr;
1774 pParse = pNC->pParse;
1775 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1776 Expr *pE = pItem->pExpr;
1777 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
1778 if( NEVER(pE2==0) ) continue;
1779 if( zType[0]!='G' ){
1780 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1781 if( iCol>0 ){
1782 /* If an AS-name match is found, mark this ORDER BY column as being
1783 ** a copy of the iCol-th result-set column. The subsequent call to
1784 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1785 ** copy of the iCol-th result-set expression. */
1786 pItem->u.x.iOrderByCol = (u16)iCol;
1787 continue;
1790 if( sqlite3ExprIsInteger(pE2, &iCol) ){
1791 /* The ORDER BY term is an integer constant. Again, set the column
1792 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1793 ** order-by term to a copy of the result-set expression */
1794 if( iCol<1 || iCol>0xffff ){
1795 resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
1796 return 1;
1798 pItem->u.x.iOrderByCol = (u16)iCol;
1799 continue;
1802 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1803 pItem->u.x.iOrderByCol = 0;
1804 if( sqlite3ResolveExprNames(pNC, pE) ){
1805 return 1;
1807 for(j=0; j<pSelect->pEList->nExpr; j++){
1808 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1809 /* Since this expression is being changed into a reference
1810 ** to an identical expression in the result set, remove all Window
1811 ** objects belonging to the expression from the Select.pWin list. */
1812 windowRemoveExprFromSelect(pSelect, pE);
1813 pItem->u.x.iOrderByCol = j+1;
1817 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1821 ** Resolve names in the SELECT statement p and all of its descendants.
1823 static int resolveSelectStep(Walker *pWalker, Select *p){
1824 NameContext *pOuterNC; /* Context that contains this SELECT */
1825 NameContext sNC; /* Name context of this SELECT */
1826 int isCompound; /* True if p is a compound select */
1827 int nCompound; /* Number of compound terms processed so far */
1828 Parse *pParse; /* Parsing context */
1829 int i; /* Loop counter */
1830 ExprList *pGroupBy; /* The GROUP BY clause */
1831 Select *pLeftmost; /* Left-most of SELECT of a compound */
1832 sqlite3 *db; /* Database connection */
1835 assert( p!=0 );
1836 if( p->selFlags & SF_Resolved ){
1837 return WRC_Prune;
1839 pOuterNC = pWalker->u.pNC;
1840 pParse = pWalker->pParse;
1841 db = pParse->db;
1843 /* Normally sqlite3SelectExpand() will be called first and will have
1844 ** already expanded this SELECT. However, if this is a subquery within
1845 ** an expression, sqlite3ResolveExprNames() will be called without a
1846 ** prior call to sqlite3SelectExpand(). When that happens, let
1847 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1848 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1849 ** this routine in the correct order.
1851 if( (p->selFlags & SF_Expanded)==0 ){
1852 sqlite3SelectPrep(pParse, p, pOuterNC);
1853 return pParse->nErr ? WRC_Abort : WRC_Prune;
1856 isCompound = p->pPrior!=0;
1857 nCompound = 0;
1858 pLeftmost = p;
1859 while( p ){
1860 assert( (p->selFlags & SF_Expanded)!=0 );
1861 assert( (p->selFlags & SF_Resolved)==0 );
1862 p->selFlags |= SF_Resolved;
1864 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1865 ** are not allowed to refer to any names, so pass an empty NameContext.
1867 memset(&sNC, 0, sizeof(sNC));
1868 sNC.pParse = pParse;
1869 sNC.pWinSelect = p;
1870 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
1871 return WRC_Abort;
1874 /* If the SF_Converted flags is set, then this Select object was
1875 ** was created by the convertCompoundSelectToSubquery() function.
1876 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1877 ** as if it were part of the sub-query, not the parent. This block
1878 ** moves the pOrderBy down to the sub-query. It will be moved back
1879 ** after the names have been resolved. */
1880 if( p->selFlags & SF_Converted ){
1881 Select *pSub = p->pSrc->a[0].pSelect;
1882 assert( p->pSrc->nSrc==1 && p->pOrderBy );
1883 assert( pSub->pPrior && pSub->pOrderBy==0 );
1884 pSub->pOrderBy = p->pOrderBy;
1885 p->pOrderBy = 0;
1888 /* Recursively resolve names in all subqueries in the FROM clause
1890 if( pOuterNC ) pOuterNC->nNestedSelect++;
1891 for(i=0; i<p->pSrc->nSrc; i++){
1892 SrcItem *pItem = &p->pSrc->a[i];
1893 assert( pItem->zName!=0 || pItem->pSelect!=0 );/* Test of tag-20240424-1*/
1894 if( pItem->pSelect && (pItem->pSelect->selFlags & SF_Resolved)==0 ){
1895 int nRef = pOuterNC ? pOuterNC->nRef : 0;
1896 const char *zSavedContext = pParse->zAuthContext;
1898 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
1899 sqlite3ResolveSelectNames(pParse, pItem->pSelect, pOuterNC);
1900 pParse->zAuthContext = zSavedContext;
1901 if( pParse->nErr ) return WRC_Abort;
1902 assert( db->mallocFailed==0 );
1904 /* If the number of references to the outer context changed when
1905 ** expressions in the sub-select were resolved, the sub-select
1906 ** is correlated. It is not required to check the refcount on any
1907 ** but the innermost outer context object, as lookupName() increments
1908 ** the refcount on all contexts between the current one and the
1909 ** context containing the column when it resolves a name. */
1910 if( pOuterNC ){
1911 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
1912 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
1916 if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
1917 pOuterNC->nNestedSelect--;
1920 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
1921 ** resolve the result-set expression list.
1923 sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
1924 sNC.pSrcList = p->pSrc;
1925 sNC.pNext = pOuterNC;
1927 /* Resolve names in the result set. */
1928 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
1929 sNC.ncFlags &= ~NC_AllowWin;
1931 /* If there are no aggregate functions in the result-set, and no GROUP BY
1932 ** expression, do not allow aggregates in any of the other expressions.
1934 assert( (p->selFlags & SF_Aggregate)==0 );
1935 pGroupBy = p->pGroupBy;
1936 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
1937 assert( NC_MinMaxAgg==SF_MinMaxAgg );
1938 assert( NC_OrderAgg==SF_OrderByReqd );
1939 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
1940 }else{
1941 sNC.ncFlags &= ~NC_AllowAgg;
1944 /* Add the output column list to the name-context before parsing the
1945 ** other expressions in the SELECT statement. This is so that
1946 ** expressions in the WHERE clause (etc.) can refer to expressions by
1947 ** aliases in the result set.
1949 ** Minor point: If this is the case, then the expression will be
1950 ** re-evaluated for each reference to it.
1952 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
1953 sNC.uNC.pEList = p->pEList;
1954 sNC.ncFlags |= NC_UEList;
1955 if( p->pHaving ){
1956 if( (p->selFlags & SF_Aggregate)==0 ){
1957 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
1958 return WRC_Abort;
1960 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
1962 sNC.ncFlags |= NC_Where;
1963 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
1964 sNC.ncFlags &= ~NC_Where;
1966 /* Resolve names in table-valued-function arguments */
1967 for(i=0; i<p->pSrc->nSrc; i++){
1968 SrcItem *pItem = &p->pSrc->a[i];
1969 if( pItem->fg.isTabFunc
1970 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
1972 return WRC_Abort;
1976 #ifndef SQLITE_OMIT_WINDOWFUNC
1977 if( IN_RENAME_OBJECT ){
1978 Window *pWin;
1979 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
1980 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
1981 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
1983 return WRC_Abort;
1987 #endif
1989 /* The ORDER BY and GROUP BY clauses may not refer to terms in
1990 ** outer queries
1992 sNC.pNext = 0;
1993 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
1995 /* If this is a converted compound query, move the ORDER BY clause from
1996 ** the sub-query back to the parent query. At this point each term
1997 ** within the ORDER BY clause has been transformed to an integer value.
1998 ** These integers will be replaced by copies of the corresponding result
1999 ** set expressions by the call to resolveOrderGroupBy() below. */
2000 if( p->selFlags & SF_Converted ){
2001 Select *pSub = p->pSrc->a[0].pSelect;
2002 p->pOrderBy = pSub->pOrderBy;
2003 pSub->pOrderBy = 0;
2006 /* Process the ORDER BY clause for singleton SELECT statements.
2007 ** The ORDER BY clause for compounds SELECT statements is handled
2008 ** below, after all of the result-sets for all of the elements of
2009 ** the compound have been resolved.
2011 ** If there is an ORDER BY clause on a term of a compound-select other
2012 ** than the right-most term, then that is a syntax error. But the error
2013 ** is not detected until much later, and so we need to go ahead and
2014 ** resolve those symbols on the incorrect ORDER BY for consistency.
2016 if( p->pOrderBy!=0
2017 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
2018 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
2020 return WRC_Abort;
2022 if( db->mallocFailed ){
2023 return WRC_Abort;
2025 sNC.ncFlags &= ~NC_AllowWin;
2027 /* Resolve the GROUP BY clause. At the same time, make sure
2028 ** the GROUP BY clause does not contain aggregate functions.
2030 if( pGroupBy ){
2031 struct ExprList_item *pItem;
2033 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
2034 return WRC_Abort;
2036 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2037 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2038 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2039 "the GROUP BY clause");
2040 return WRC_Abort;
2045 /* If this is part of a compound SELECT, check that it has the right
2046 ** number of expressions in the select list. */
2047 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
2048 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
2049 return WRC_Abort;
2052 /* Advance to the next term of the compound
2054 p = p->pPrior;
2055 nCompound++;
2058 /* Resolve the ORDER BY on a compound SELECT after all terms of
2059 ** the compound have been resolved.
2061 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
2062 return WRC_Abort;
2065 return WRC_Prune;
2069 ** This routine walks an expression tree and resolves references to
2070 ** table columns and result-set columns. At the same time, do error
2071 ** checking on function usage and set a flag if any aggregate functions
2072 ** are seen.
2074 ** To resolve table columns references we look for nodes (or subtrees) of the
2075 ** form X.Y.Z or Y.Z or just Z where
2077 ** X: The name of a database. Ex: "main" or "temp" or
2078 ** the symbolic name assigned to an ATTACH-ed database.
2080 ** Y: The name of a table in a FROM clause. Or in a trigger
2081 ** one of the special names "old" or "new".
2083 ** Z: The name of a column in table Y.
2085 ** The node at the root of the subtree is modified as follows:
2087 ** Expr.op Changed to TK_COLUMN
2088 ** Expr.pTab Points to the Table object for X.Y
2089 ** Expr.iColumn The column index in X.Y. -1 for the rowid.
2090 ** Expr.iTable The VDBE cursor number for X.Y
2093 ** To resolve result-set references, look for expression nodes of the
2094 ** form Z (with no X and Y prefix) where the Z matches the right-hand
2095 ** size of an AS clause in the result-set of a SELECT. The Z expression
2096 ** is replaced by a copy of the left-hand side of the result-set expression.
2097 ** Table-name and function resolution occurs on the substituted expression
2098 ** tree. For example, in:
2100 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2102 ** The "x" term of the order by is replaced by "a+b" to render:
2104 ** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2106 ** Function calls are checked to make sure that the function is
2107 ** defined and that the correct number of arguments are specified.
2108 ** If the function is an aggregate function, then the NC_HasAgg flag is
2109 ** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2110 ** If an expression contains aggregate functions then the EP_Agg
2111 ** property on the expression is set.
2113 ** An error message is left in pParse if anything is amiss. The number
2114 ** if errors is returned.
2116 int sqlite3ResolveExprNames(
2117 NameContext *pNC, /* Namespace to resolve expressions in. */
2118 Expr *pExpr /* The expression to be analyzed. */
2120 int savedHasAgg;
2121 Walker w;
2123 if( pExpr==0 ) return SQLITE_OK;
2124 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2125 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2126 w.pParse = pNC->pParse;
2127 w.xExprCallback = resolveExprStep;
2128 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
2129 w.xSelectCallback2 = 0;
2130 w.u.pNC = pNC;
2131 #if SQLITE_MAX_EXPR_DEPTH>0
2132 w.pParse->nHeight += pExpr->nHeight;
2133 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2134 return SQLITE_ERROR;
2136 #endif
2137 assert( pExpr!=0 );
2138 sqlite3WalkExprNN(&w, pExpr);
2139 #if SQLITE_MAX_EXPR_DEPTH>0
2140 w.pParse->nHeight -= pExpr->nHeight;
2141 #endif
2142 assert( EP_Agg==NC_HasAgg );
2143 assert( EP_Win==NC_HasWin );
2144 testcase( pNC->ncFlags & NC_HasAgg );
2145 testcase( pNC->ncFlags & NC_HasWin );
2146 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2147 pNC->ncFlags |= savedHasAgg;
2148 return pNC->nNcErr>0 || w.pParse->nErr>0;
2152 ** Resolve all names for all expression in an expression list. This is
2153 ** just like sqlite3ResolveExprNames() except that it works for an expression
2154 ** list rather than a single expression.
2156 int sqlite3ResolveExprListNames(
2157 NameContext *pNC, /* Namespace to resolve expressions in. */
2158 ExprList *pList /* The expression list to be analyzed. */
2160 int i;
2161 int savedHasAgg = 0;
2162 Walker w;
2163 if( pList==0 ) return WRC_Continue;
2164 w.pParse = pNC->pParse;
2165 w.xExprCallback = resolveExprStep;
2166 w.xSelectCallback = resolveSelectStep;
2167 w.xSelectCallback2 = 0;
2168 w.u.pNC = pNC;
2169 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2170 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2171 for(i=0; i<pList->nExpr; i++){
2172 Expr *pExpr = pList->a[i].pExpr;
2173 if( pExpr==0 ) continue;
2174 #if SQLITE_MAX_EXPR_DEPTH>0
2175 w.pParse->nHeight += pExpr->nHeight;
2176 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2177 return WRC_Abort;
2179 #endif
2180 sqlite3WalkExprNN(&w, pExpr);
2181 #if SQLITE_MAX_EXPR_DEPTH>0
2182 w.pParse->nHeight -= pExpr->nHeight;
2183 #endif
2184 assert( EP_Agg==NC_HasAgg );
2185 assert( EP_Win==NC_HasWin );
2186 testcase( pNC->ncFlags & NC_HasAgg );
2187 testcase( pNC->ncFlags & NC_HasWin );
2188 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
2189 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2190 savedHasAgg |= pNC->ncFlags &
2191 (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2192 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2194 if( w.pParse->nErr>0 ) return WRC_Abort;
2196 pNC->ncFlags |= savedHasAgg;
2197 return WRC_Continue;
2201 ** Resolve all names in all expressions of a SELECT and in all
2202 ** descendants of the SELECT, including compounds off of p->pPrior,
2203 ** subqueries in expressions, and subqueries used as FROM clause
2204 ** terms.
2206 ** See sqlite3ResolveExprNames() for a description of the kinds of
2207 ** transformations that occur.
2209 ** All SELECT statements should have been expanded using
2210 ** sqlite3SelectExpand() prior to invoking this routine.
2212 void sqlite3ResolveSelectNames(
2213 Parse *pParse, /* The parser context */
2214 Select *p, /* The SELECT statement being coded. */
2215 NameContext *pOuterNC /* Name context for parent SELECT statement */
2217 Walker w;
2219 assert( p!=0 );
2220 w.xExprCallback = resolveExprStep;
2221 w.xSelectCallback = resolveSelectStep;
2222 w.xSelectCallback2 = 0;
2223 w.pParse = pParse;
2224 w.u.pNC = pOuterNC;
2225 sqlite3WalkSelect(&w, p);
2229 ** Resolve names in expressions that can only reference a single table
2230 ** or which cannot reference any tables at all. Examples:
2232 ** "type" flag
2233 ** ------------
2234 ** (1) CHECK constraints NC_IsCheck
2235 ** (2) WHERE clauses on partial indices NC_PartIdx
2236 ** (3) Expressions in indexes on expressions NC_IdxExpr
2237 ** (4) Expression arguments to VACUUM INTO. 0
2238 ** (5) GENERATED ALWAYS as expressions NC_GenCol
2240 ** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2241 ** nodes of the expression is set to -1 and the Expr.iColumn value is
2242 ** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2244 ** Any errors cause an error message to be set in pParse.
2246 int sqlite3ResolveSelfReference(
2247 Parse *pParse, /* Parsing context */
2248 Table *pTab, /* The table being referenced, or NULL */
2249 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2250 Expr *pExpr, /* Expression to resolve. May be NULL. */
2251 ExprList *pList /* Expression list to resolve. May be NULL. */
2253 SrcList sSrc; /* Fake SrcList for pParse->pNewTable */
2254 NameContext sNC; /* Name context for pParse->pNewTable */
2255 int rc;
2257 assert( type==0 || pTab!=0 );
2258 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2259 || type==NC_GenCol || pTab==0 );
2260 memset(&sNC, 0, sizeof(sNC));
2261 memset(&sSrc, 0, sizeof(sSrc));
2262 if( pTab ){
2263 sSrc.nSrc = 1;
2264 sSrc.a[0].zName = pTab->zName;
2265 sSrc.a[0].pTab = pTab;
2266 sSrc.a[0].iCursor = -1;
2267 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2268 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2269 ** schema elements */
2270 type |= NC_FromDDL;
2273 sNC.pParse = pParse;
2274 sNC.pSrcList = &sSrc;
2275 sNC.ncFlags = type | NC_IsDDL;
2276 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2277 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2278 return rc;