interplane.Get Omega
Read in your language

sqlite

[Ported from github.com/sqlite/sqlite] Fix bugs in and improve the interface to the ".check" command of the CLI.

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / resolve.c

2407 lines · 88791 bytes Raw Blame History
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.
10**
11*************************************************************************
12**
13** This file contains routines used for walking the parser tree and
14** resolve all identifiers by associating them with a particular
15** table and column.
16*/
17#include "sqliteInt.h"
18
19/*
20** Magic table number to mean the EXCLUDED table in an UPSERT statement.
21*/
22#define EXCLUDED_TABLE_NUMBER 2
23
24/*
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.
29**
30** incrAggFunctionDepth(pExpr,n) is the main routine. incrAggDepth(..)
31** is a helper function - a callback for the tree walker.
32**
33** See also the sqlite3WindowExtraAggFuncDepth() routine in window.c
34*/
35static int incrAggDepth(Walker *pWalker, Expr *pExpr){
36 if( pExpr->op==TK_AGG_FUNCTION ) pExpr->op2 += pWalker->u.n;
37 return WRC_Continue;
38}
39static void incrAggFunctionDepth(Expr *pExpr, int N){
40 if( N>0 ){
41 Walker w;
42 memset(&w, 0, sizeof(w));
43 w.xExprCallback = incrAggDepth;
44 w.u.n = N;
45 sqlite3WalkExpr(&w, pExpr);
46 }
47}
48
49/*
50** Turn the pExpr expression into an alias for the iCol-th column of the
51** result set in pEList.
52**
53** If the reference is followed by a COLLATE operator, then make sure
54** the COLLATE operator is preserved. For example:
55**
56** SELECT a+b, c+d FROM t1 ORDER BY 1 COLLATE nocase;
57**
58** Should be transformed into:
59**
60** SELECT a+b, c+d FROM t1 ORDER BY (a+b) COLLATE nocase;
61**
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.
67*/
68static void resolveAlias(
69 Parse *pParse, /* Parsing context */
70 ExprList *pEList, /* A result set */
71 int iCol, /* A column in the result set. 0..pEList->nExpr-1 */
72 Expr *pExpr, /* Transform this into an alias to the result set */
73 int nSubquery /* Number of subqueries that the label is moving */
74){
75 Expr *pOrig; /* The iCol-th column of the result set */
76 Expr *pDup; /* Copy of pOrig */
77 sqlite3 *db; /* The database connection */
78
79 assert( iCol>=0 && iCol<pEList->nExpr );
80 pOrig = pEList->a[iCol].pExpr;
81 assert( pOrig!=0 );
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);
95 }
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;
102 }
103 }
104 sqlite3ExprDeferredDelete(pParse, pDup);
105 }
106}
107
108/*
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.
113**
114** Check to see if the zSpan/eEName of the expression-list item passed to this
115** routine matches the zDb, zTab, and zCol. If any of zDb, zTab, and zCol are
116** NULL then those fields will match anything. Return true if there is a match,
117** or false otherwise.
118**
119** SF_NestedFrom subqueries also store an entry for the implicit rowid (or
120** _rowid_, or oid) column by setting ExprList.a[].fg.eEName to ENAME_ROWID,
121** and setting zSpan to "DATABASE.TABLE.<rowid-alias>". This type of pItem
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.
124*/
125int sqlite3MatchEName(
126 const struct ExprList_item *pItem,
127 const char *zCol,
128 const char *zTab,
129 const char *zDb,
130 int *pbRowid
131){
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;
137 }
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;
143 }
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;
148 }
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;
153 }
154 if( eEName==ENAME_ROWID ) *pbRowid = 1;
155 return 1;
156}
157
158/*
159** Return TRUE if the double-quoted string mis-feature should be supported.
160*/
161static int areDoubleQuotedStringsEnabled(sqlite3 *db, NameContext *pTopNC){
162 if( db->init.busy ) return 1; /* Always support for legacy schemas */
163 if( pTopNC->ncFlags & NC_IsDDL ){
164 /* Currently parsing a DDL statement */
165 if( sqlite3WritableSchema(db) && (db->flags & SQLITE_DqsDML)!=0 ){
166 return 1;
167 }
168 return (db->flags & SQLITE_DqsDDL)!=0;
169 }else{
170 /* Currently parsing a DML statement */
171 return (db->flags & SQLITE_DqsDML)!=0;
172 }
173}
174
175/*
176** The argument is guaranteed to be a non-NULL Expr node of type TK_COLUMN.
177** return the appropriate colUsed mask.
178*/
179Bitmask sqlite3ExprColUsed(Expr *pExpr){
180 int n;
181 Table *pExTab;
182
183 n = pExpr->iColumn;
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
190 ){
191 testcase( pExTab->nCol==BMS-1 );
192 testcase( pExTab->nCol==BMS );
193 return pExTab->nCol>=BMS ? ALLBITS : MASKBIT(pExTab->nCol)-1;
194 }else{
195 testcase( n==BMS-1 );
196 testcase( n==BMS );
197 if( n>=BMS ) n = BMS-1;
198 return ((Bitmask)1)<<n;
199 }
200}
201
202/*
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.
207*/
208static void extendFJMatch(
209 Parse *pParse, /* Parsing context */
210 ExprList **ppList, /* ExprList to extend */
211 SrcItem *pMatch, /* Source table containing the column */
212 i16 iColumn /* The column number */
213){
214 Expr *pNew = sqlite3ExprAlloc(pParse->db, TK_COLUMN, 0, 0);
215 if( pNew ){
216 pNew->iTable = pMatch->iCursor;
217 pNew->iColumn = iColumn;
218 pNew->y.pTab = pMatch->pSTab;
219 assert( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 );
220 ExprSetProperty(pNew, EP_CanBeNull);
221 *ppList = sqlite3ExprListAppend(pParse, *ppList, pNew);
222 }
223}
224
225/*
226** Return TRUE (non-zero) if zTab is a valid name for the schema table pTab.
227*/
228static SQLITE_NOINLINE int isValidSchemaTableName(
229 const char *zTab, /* Name as it appears in the SQL */
230 Table *pTab, /* The schema table we are trying to match */
231 const char *zDb /* non-NULL if a database qualifier is present */
232){
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;
241 }
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;
247 }
248 return 0;
249}
250
251/*
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:
256**
257** pExpr->iDb Set the index in db->aDb[] of the database X
258** (even if X is implied).
259** pExpr->iTable Set to the cursor number for the table obtained
260** from pSrcList.
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.
267**
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.
274**
275** If the name cannot be resolved unambiguously, leave an error message
276** in pParse and return WRC_Abort. Return WRC_Prune on success.
277*/
278static 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 */
285){
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 ExprList *pFJMatch = 0; /* Matches for FULL JOIN .. USING */
298 const char *zCol = pRight->u.zToken;
299
300 assert( pNC ); /* the name context cannot be NULL. */
301 assert( zCol ); /* The Z in X.Y.Z cannot be NULL */
302 assert( zDb==0 || zTab!=0 );
303 assert( !ExprHasProperty(pExpr, EP_TokenOnly|EP_Reduced) );
304
305 /* Initialize the node to no-match */
306 pExpr->iTable = -1;
307 ExprSetVVAProperty(pExpr, EP_NoReduce);
308
309 /* Translate the schema name in zDb into a pointer to the corresponding
310 ** schema. If not found, pSchema will remain NULL and nothing will match
311 ** resulting in an appropriate error message toward the end of this routine
312 */
313 if( zDb ){
314 testcase( pNC->ncFlags & NC_PartIdx );
315 testcase( pNC->ncFlags & NC_IsCheck );
316 if( (pNC->ncFlags & (NC_PartIdx|NC_IsCheck))!=0 ){
317 /* Silently ignore database qualifiers inside CHECK constraints and
318 ** partial indices. Do not raise errors because that might break
319 ** legacy and because it does not hurt anything to just ignore the
320 ** database name. */
321 zDb = 0;
322 }else{
323 for(i=0; i<db->nDb; i++){
324 assert( db->aDb[i].zDbSName );
325 if( sqlite3StrICmp(db->aDb[i].zDbSName,zDb)==0 ){
326 pSchema = db->aDb[i].pSchema;
327 break;
328 }
329 }
330 if( i==db->nDb && sqlite3StrICmp("main", zDb)==0 ){
331 /* This branch is taken when the main database has been renamed
332 ** using SQLITE_DBCONFIG_MAINDBNAME. */
333 pSchema = db->aDb[0].pSchema;
334 zDb = db->aDb[0].zDbSName;
335 }
336 }
337 }
338
339 /* Start at the inner-most context and move outward until a match is found */
340 assert( pNC && cnt==0 );
341 do{
342 ExprList *pEList;
343 SrcList *pSrcList = pNC->pSrcList;
344
345 if( pSrcList ){
346 for(i=0, pItem=pSrcList->a; i<pSrcList->nSrc; i++, pItem++){
347 pTab = pItem->pSTab;
348 assert( pTab!=0 && pTab->zName!=0 );
349 assert( pTab->nCol>0 || pParse->nErr );
350 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem));
351 if( pItem->fg.isNestedFrom ){
352 /* In this case, pItem is a subquery that has been formed from a
353 ** parenthesized subset of the FROM clause terms. Example:
354 ** .... FROM t1 LEFT JOIN (t2 RIGHT JOIN t3 USING(x)) USING(y) ...
355 ** \_________________________/
356 ** This pItem -------------^
357 */
358 int hit = 0;
359 Select *pSel;
360 assert( pItem->fg.isSubquery );
361 assert( pItem->u4.pSubq!=0 );
362 pSel = pItem->u4.pSubq->pSelect;
363 assert( pSel!=0 );
364 pEList = pSel->pEList;
365 assert( pEList!=0 );
366 assert( pEList->nExpr==pTab->nCol );
367 for(j=0; j<pEList->nExpr; j++){
368 int bRowid = 0; /* True if possible rowid match */
369 if( !sqlite3MatchEName(&pEList->a[j], zCol, zTab, zDb, &bRowid) ){
370 continue;
371 }
372 if( bRowid==0 ){
373 if( cnt>0 ){
374 if( pItem->fg.isUsing==0
375 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
376 || pMatch==pItem
377 ){
378 /* Two or more tables have the same column name which is
379 ** not joined by USING. Or, a single table has two columns
380 ** that match a USING term (if pMatch==pItem). These are both
381 ** "ambiguous column name" errors. Signal as much by clearing
382 ** pFJMatch and letting cnt go above 1. */
383 sqlite3ExprListDelete(db, pFJMatch);
384 pFJMatch = 0;
385 }else
386 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
387 /* An INNER or LEFT JOIN. Use the left-most table */
388 continue;
389 }else
390 if( (pItem->fg.jointype & JT_LEFT)==0 ){
391 /* A RIGHT JOIN. Use the right-most table */
392 cnt = 0;
393 sqlite3ExprListDelete(db, pFJMatch);
394 pFJMatch = 0;
395 }else{
396 /* For a FULL JOIN, we must construct a coalesce() func */
397 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
398 }
399 }
400 cnt++;
401 hit = 1;
402 }else if( cnt>0 ){
403 /* This is a potential rowid match, but there has already been
404 ** a real match found. So this can be ignored. */
405 continue;
406 }
407 cntTab++;
408 pMatch = pItem;
409 pExpr->iColumn = j;
410 pEList->a[j].fg.bUsed = 1;
411
412 /* rowid cannot be part of a USING clause - assert() this. */
413 assert( bRowid==0 || pEList->a[j].fg.bUsingTerm==0 );
414 if( pEList->a[j].fg.bUsingTerm ) break;
415 }
416 if( hit || zTab==0 ) continue;
417 }
418 assert( zDb==0 || zTab!=0 );
419 if( zTab ){
420 if( zDb ){
421 if( pTab->pSchema!=pSchema ) continue;
422 if( pSchema==0 && strcmp(zDb,"*")!=0 ) continue;
423 }
424 if( pItem->zAlias!=0 ){
425 if( sqlite3StrICmp(zTab, pItem->zAlias)!=0 ){
426 continue;
427 }
428 }else if( sqlite3StrICmp(zTab, pTab->zName)!=0 ){
429 if( pTab->tnum!=1 ) continue;
430 if( !isValidSchemaTableName(zTab, pTab, zDb) ) continue;
431 }
432 assert( ExprUseYTab(pExpr) );
433 if( IN_RENAME_OBJECT && pItem->zAlias ){
434 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
435 }
436 }
437 j = sqlite3ColumnIndex(pTab, zCol);
438 if( j>=0 ){
439 if( cnt>0 ){
440 if( pItem->fg.isUsing==0
441 || sqlite3IdListIndex(pItem->u3.pUsing, zCol)<0
442 ){
443 /* Two or more tables have the same column name which is
444 ** not joined by USING. This is an error. Signal as much
445 ** by clearing pFJMatch and letting cnt go above 1. */
446 sqlite3ExprListDelete(db, pFJMatch);
447 pFJMatch = 0;
448 }else
449 if( (pItem->fg.jointype & JT_RIGHT)==0 ){
450 /* An INNER or LEFT JOIN. Use the left-most table */
451 continue;
452 }else
453 if( (pItem->fg.jointype & JT_LEFT)==0 ){
454 /* A RIGHT JOIN. Use the right-most table */
455 cnt = 0;
456 sqlite3ExprListDelete(db, pFJMatch);
457 pFJMatch = 0;
458 }else{
459 /* For a FULL JOIN, we must construct a coalesce() func */
460 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
461 }
462 }
463 cnt++;
464 pMatch = pItem;
465 /* Substitute the rowid (column -1) for the INTEGER PRIMARY KEY.
466 ** Except when parsing for ALTER TABLE. In that case leave
467 ** Expr.iColumn set to iCol so that it can be distinguished from
468 ** literal "rowid" references. */
469 if( j==pTab->iPKey && !IN_RENAME_OBJECT ){
470 pExpr->iColumn = -1;
471 }else{
472 pExpr->iColumn = (i16)j;
473 }
474 if( pItem->fg.isNestedFrom ){
475 sqlite3SrcItemColumnUsed(pItem, j);
476 }
477 }
478 if( 0==cnt && VisibleRowid(pTab) ){
479 /* pTab is a potential ROWID match. Keep track of it and match
480 ** the ROWID later if that seems appropriate. (Search for "cntTab"
481 ** to find related code.) Only allow a ROWID match if there is
482 ** a single ROWID match candidate.
483 */
484#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
485 /* In SQLITE_ALLOW_ROWID_IN_VIEW mode, allow a ROWID match
486 ** if there is a single VIEW candidate or if there is a single
487 ** non-VIEW candidate plus multiple VIEW candidates. In other
488 ** words non-VIEW candidate terms take precedence over VIEWs.
489 */
490 if( cntTab==0
491 || (cntTab==1
492 && pMatch!=0
493 && ALWAYS(pMatch->pSTab!=0)
494 && (pMatch->pSTab->tabFlags & TF_Ephemeral)!=0
495 && (pTab->tabFlags & TF_Ephemeral)==0)
496 ){
497 cntTab = 1;
498 pMatch = pItem;
499 }else{
500 cntTab++;
501 }
502#else
503 /* The (much more common) non-SQLITE_ALLOW_ROWID_IN_VIEW case is
504 ** simpler since we require exactly one candidate, which will
505 ** always be a non-VIEW
506 */
507 cntTab++;
508 pMatch = pItem;
509#endif
510 }
511 }
512 if( pMatch ){
513 pExpr->iTable = pMatch->iCursor;
514 assert( ExprUseYTab(pExpr) );
515 pExpr->y.pTab = pMatch->pSTab;
516 if( (pMatch->fg.jointype & (JT_LEFT|JT_LTORJ))!=0 ){
517 ExprSetProperty(pExpr, EP_CanBeNull);
518 }
519 pSchema = pExpr->y.pTab->pSchema;
520 }
521 } /* if( pSrcList ) */
522
523#if !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT)
524 /* If we have not already resolved the name, then maybe
525 ** it is a new.* or old.* trigger argument reference. Or
526 ** maybe it is an excluded.* from an upsert. Or maybe it is
527 ** a reference in the RETURNING clause to a table being modified.
528 */
529 if( cnt==0 && zDb==0 ){
530 pTab = 0;
531#ifndef SQLITE_OMIT_TRIGGER
532 if( pParse->pTriggerTab!=0 ){
533 int op = pParse->eTriggerOp;
534 assert( op==TK_DELETE || op==TK_UPDATE || op==TK_INSERT );
535 if( pParse->bReturning ){
536 if( (pNC->ncFlags & NC_UBaseReg)!=0
537 && ALWAYS(zTab==0
538 || sqlite3StrICmp(zTab,pParse->pTriggerTab->zName)==0
539 || isValidSchemaTableName(zTab, pParse->pTriggerTab, 0))
540 ){
541 pExpr->iTable = op!=TK_DELETE;
542 pTab = pParse->pTriggerTab;
543 }
544 }else if( op!=TK_DELETE && zTab && sqlite3StrICmp("new",zTab) == 0 ){
545 pExpr->iTable = 1;
546 pTab = pParse->pTriggerTab;
547 }else if( op!=TK_INSERT && zTab && sqlite3StrICmp("old",zTab)==0 ){
548 pExpr->iTable = 0;
549 pTab = pParse->pTriggerTab;
550 }
551 }
552#endif /* SQLITE_OMIT_TRIGGER */
553#ifndef SQLITE_OMIT_UPSERT
554 if( (pNC->ncFlags & NC_UUpsert)!=0 && zTab!=0 ){
555 Upsert *pUpsert = pNC->uNC.pUpsert;
556 if( pUpsert && sqlite3StrICmp("excluded",zTab)==0 ){
557 pTab = pUpsert->pUpsertSrc->a[0].pSTab;
558 pExpr->iTable = EXCLUDED_TABLE_NUMBER;
559 if( IN_RENAME_OBJECT ){
560 sqlite3RenameTokenRemap(pParse, 0, (void*)&pExpr->y.pTab);
561 }
562 }
563 }
564#endif /* SQLITE_OMIT_UPSERT */
565
566 if( pTab ){
567 int iCol;
568 pSchema = pTab->pSchema;
569 cntTab++;
570 iCol = sqlite3ColumnIndex(pTab, zCol);
571 if( iCol>=0 ){
572 if( pTab->iPKey==iCol && !IN_RENAME_OBJECT ) iCol = -1;
573 }else{
574 if( sqlite3IsRowid(zCol) && VisibleRowid(pTab) ){
575 iCol = -1;
576 }else{
577 iCol = pTab->nCol;
578 }
579 }
580 if( iCol<pTab->nCol ){
581 cnt++;
582 pMatch = 0;
583#ifndef SQLITE_OMIT_UPSERT
584 if( pExpr->iTable==EXCLUDED_TABLE_NUMBER ){
585 testcase( iCol==(-1) );
586 assert( ExprUseYTab(pExpr) );
587 if( IN_RENAME_OBJECT ){
588 pExpr->iColumn = iCol;
589 pExpr->y.pTab = pTab;
590 eNewExprOp = TK_COLUMN;
591 }else{
592 pExpr->iTable = pNC->uNC.pUpsert->regData +
593 sqlite3TableColumnToStorage(pTab, iCol);
594 eNewExprOp = TK_REGISTER;
595 }
596 }else
597#endif /* SQLITE_OMIT_UPSERT */
598 {
599 assert( ExprUseYTab(pExpr) );
600 pExpr->y.pTab = pTab;
601 if( pParse->bReturning ){
602 eNewExprOp = TK_REGISTER;
603 pExpr->op2 = TK_COLUMN;
604 pExpr->iColumn = iCol;
605 pExpr->iTable = pNC->uNC.iBaseReg + (pTab->nCol+1)*pExpr->iTable +
606 sqlite3TableColumnToStorage(pTab, iCol) + 1;
607 }else{
608 pExpr->iColumn = (i16)iCol;
609 eNewExprOp = TK_TRIGGER;
610#ifndef SQLITE_OMIT_TRIGGER
611 if( iCol<0 ){
612 pExpr->affExpr = SQLITE_AFF_INTEGER;
613 }else if( pExpr->iTable==0 ){
614 testcase( iCol==31 );
615 testcase( iCol==32 );
616 pParse->oldmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
617 }else{
618 testcase( iCol==31 );
619 testcase( iCol==32 );
620 pParse->newmask |= (iCol>=32 ? 0xffffffff : (((u32)1)<<iCol));
621 }
622#endif /* SQLITE_OMIT_TRIGGER */
623 }
624 }
625 }
626 }
627 }
628#endif /* !defined(SQLITE_OMIT_TRIGGER) || !defined(SQLITE_OMIT_UPSERT) */
629
630 /*
631 ** Perhaps the name is a reference to the ROWID
632 */
633 if( cnt==0
634 && cntTab>=1
635 && pMatch
636 && (pNC->ncFlags & (NC_IdxExpr|NC_GenCol))==0
637 && sqlite3IsRowid(zCol)
638 && ALWAYS(VisibleRowid(pMatch->pSTab) || pMatch->fg.isNestedFrom)
639 ){
640 cnt = cntTab;
641#if SQLITE_ALLOW_ROWID_IN_VIEW+0==2
642 if( pMatch->pSTab!=0 && IsView(pMatch->pSTab) ){
643 eNewExprOp = TK_NULL;
644 }
645#endif
646 if( pMatch->fg.isNestedFrom==0 ) pExpr->iColumn = -1;
647 pExpr->affExpr = SQLITE_AFF_INTEGER;
648 }
649
650 /*
651 ** If the input is of the form Z (not Y.Z or X.Y.Z) then the name Z
652 ** might refer to an result-set alias. This happens, for example, when
653 ** we are resolving names in the WHERE clause of the following command:
654 **
655 ** SELECT a+b AS x FROM table WHERE x<10;
656 **
657 ** In cases like this, replace pExpr with a copy of the expression that
658 ** forms the result set entry ("a+b" in the example) and return immediately.
659 ** Note that the expression in the result set should have already been
660 ** resolved by the time the WHERE clause is resolved.
661 **
662 ** The ability to use an output result-set column in the WHERE, GROUP BY,
663 ** or HAVING clauses, or as part of a larger expression in the ORDER BY
664 ** clause is not standard SQL. This is a (goofy) SQLite extension, that
665 ** is supported for backwards compatibility only. Hence, we issue a warning
666 ** on sqlite3_log() whenever the capability is used.
667 */
668 if( cnt==0
669 && (pNC->ncFlags & NC_UEList)!=0
670 && zTab==0
671 ){
672 pEList = pNC->uNC.pEList;
673 assert( pEList!=0 );
674 for(j=0; j<pEList->nExpr; j++){
675 char *zAs = pEList->a[j].zEName;
676 if( pEList->a[j].fg.eEName==ENAME_NAME
677 && sqlite3_stricmp(zAs, zCol)==0
678 ){
679 Expr *pOrig;
680 assert( pExpr->pLeft==0 && pExpr->pRight==0 );
681 assert( ExprUseXList(pExpr)==0 || pExpr->x.pList==0 );
682 assert( ExprUseXSelect(pExpr)==0 || pExpr->x.pSelect==0 );
683 pOrig = pEList->a[j].pExpr;
684 if( (pNC->ncFlags&NC_AllowAgg)==0 && ExprHasProperty(pOrig, EP_Agg) ){
685 sqlite3ErrorMsg(pParse, "misuse of aliased aggregate %s", zAs);
686 return WRC_Abort;
687 }
688 if( ExprHasProperty(pOrig, EP_Win)
689 && ((pNC->ncFlags&NC_AllowWin)==0 || pNC!=pTopNC )
690 ){
691 sqlite3ErrorMsg(pParse, "misuse of aliased window function %s",zAs);
692 return WRC_Abort;
693 }
694 if( sqlite3ExprVectorSize(pOrig)!=1 ){
695 sqlite3ErrorMsg(pParse, "row value misused");
696 return WRC_Abort;
697 }
698 resolveAlias(pParse, pEList, j, pExpr, nSubquery);
699 cnt = 1;
700 pMatch = 0;
701 assert( zTab==0 && zDb==0 );
702 if( IN_RENAME_OBJECT ){
703 sqlite3RenameTokenRemap(pParse, 0, (void*)pExpr);
704 }
705 goto lookupname_end;
706 }
707 }
708 }
709
710 /* Advance to the next name context. The loop will exit when either
711 ** we have a match (cnt>0) or when we run out of name contexts.
712 */
713 if( cnt ) break;
714 pNC = pNC->pNext;
715 nSubquery++;
716 }while( pNC );
717
718
719 /*
720 ** If X and Y are NULL (in other words if only the column name Z is
721 ** supplied) and the value of Z is enclosed in double-quotes, then
722 ** Z is a string literal if it doesn't match any column names. In that
723 ** case, we need to return right away and not make any changes to
724 ** pExpr.
725 **
726 ** Because no reference was made to outer contexts, the pNC->nRef
727 ** fields are not changed in any context.
728 */
729 if( cnt==0 && zTab==0 ){
730 assert( pExpr->op==TK_ID );
731 if( ExprHasProperty(pExpr,EP_DblQuoted)
732 && areDoubleQuotedStringsEnabled(db, pTopNC)
733 ){
734 /* If a double-quoted identifier does not match any known column name,
735 ** then treat it as a string.
736 **
737 ** This hack was added in the early days of SQLite in a misguided attempt
738 ** to be compatible with MySQL 3.x, which used double-quotes for strings.
739 ** I now sorely regret putting in this hack. The effect of this hack is
740 ** that misspelled identifier names are silently converted into strings
741 ** rather than causing an error, to the frustration of countless
742 ** programmers. To all those frustrated programmers, my apologies.
743 **
744 ** Someday, I hope to get rid of this hack. Unfortunately there is
745 ** a huge amount of legacy SQL that uses it. So for now, we just
746 ** issue a warning.
747 */
748 sqlite3_log(SQLITE_WARNING,
749 "double-quoted string literal: \"%w\"", zCol);
750#ifdef SQLITE_ENABLE_NORMALIZE
751 sqlite3VdbeAddDblquoteStr(db, pParse->pVdbe, zCol);
752#endif
753 pExpr->op = TK_STRING;
754 memset(&pExpr->y, 0, sizeof(pExpr->y));
755 return WRC_Prune;
756 }
757 if( sqlite3ExprIdToTrueFalse(pExpr) ){
758 return WRC_Prune;
759 }
760 }
761
762 /*
763 ** cnt==0 means there was not match.
764 ** cnt>1 means there were two or more matches.
765 **
766 ** cnt==0 is always an error. cnt>1 is often an error, but might
767 ** be multiple matches for a NATURAL OUTER JOIN or a OUTER JOIN USING.
768 */
769 assert( pFJMatch==0 || cnt>0 );
770 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
771 if( cnt!=1 ){
772 const char *zErr;
773 if( pFJMatch ){
774 if( pFJMatch->nExpr==cnt-1 ){
775 if( ExprHasProperty(pExpr,EP_Leaf) ){
776 ExprClearProperty(pExpr,EP_Leaf);
777 }else{
778 sqlite3ExprDelete(db, pExpr->pLeft);
779 pExpr->pLeft = 0;
780 sqlite3ExprDelete(db, pExpr->pRight);
781 pExpr->pRight = 0;
782 }
783 extendFJMatch(pParse, &pFJMatch, pMatch, pExpr->iColumn);
784 pExpr->op = TK_FUNCTION;
785 pExpr->u.zToken = "coalesce";
786 pExpr->x.pList = pFJMatch;
787 pExpr->affExpr = SQLITE_AFF_DEFER;
788 cnt = 1;
789 goto lookupname_end;
790 }else{
791 sqlite3ExprListDelete(db, pFJMatch);
792 pFJMatch = 0;
793 }
794 }
795 zErr = cnt==0 ? "no such column" : "ambiguous column name";
796 if( zDb ){
797 sqlite3ErrorMsg(pParse, "%s: %s.%s.%s", zErr, zDb, zTab, zCol);
798 }else if( zTab ){
799 sqlite3ErrorMsg(pParse, "%s: %s.%s", zErr, zTab, zCol);
800 }else if( cnt==0 && ExprHasProperty(pRight,EP_DblQuoted) ){
801 sqlite3ErrorMsg(pParse, "%s: \"%s\" - should this be a"
802 " string literal in single-quotes?",
803 zErr, zCol);
804 }else{
805 sqlite3ErrorMsg(pParse, "%s: %s", zErr, zCol);
806 }
807 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
808 pParse->checkSchema = 1;
809 pTopNC->nNcErr++;
810 eNewExprOp = TK_NULL;
811 }
812 assert( pFJMatch==0 );
813
814 /* Remove all substructure from pExpr */
815 if( !ExprHasProperty(pExpr,(EP_TokenOnly|EP_Leaf)) ){
816 sqlite3ExprDelete(db, pExpr->pLeft);
817 pExpr->pLeft = 0;
818 sqlite3ExprDelete(db, pExpr->pRight);
819 pExpr->pRight = 0;
820 ExprSetProperty(pExpr, EP_Leaf);
821 }
822
823 /* If a column from a table in pSrcList is referenced, then record
824 ** this fact in the pSrcList.a[].colUsed bitmask. Column 0 causes
825 ** bit 0 to be set. Column 1 sets bit 1. And so forth. Bit 63 is
826 ** set if the 63rd or any subsequent column is used.
827 **
828 ** The colUsed mask is an optimization used to help determine if an
829 ** index is a covering index. The correct answer is still obtained
830 ** if the mask contains extra set bits. However, it is important to
831 ** avoid setting bits beyond the maximum column number of the table.
832 ** (See ticket [b92e5e8ec2cdbaa1]).
833 **
834 ** If a generated column is referenced, set bits for every column
835 ** of the table.
836 */
837 if( pMatch ){
838 if( pExpr->iColumn>=0 ){
839 pMatch->colUsed |= sqlite3ExprColUsed(pExpr);
840 }else{
841 pMatch->fg.rowidUsed = 1;
842 }
843 }
844
845 pExpr->op = eNewExprOp;
846lookupname_end:
847 if( cnt==1 ){
848 assert( pNC!=0 );
849#ifndef SQLITE_OMIT_AUTHORIZATION
850 if( db->xAuth ){
851 if( pFJMatch ){
852 assert( pExpr->op==TK_FUNCTION );
853 assert( sqlite3_stricmp(pExpr->u.zToken,"coalesce")==0 );
854 assert( pExpr->x.pList==pFJMatch );
855 assert( pFJMatch->nExpr>0 );
856 for(i=0; i<pFJMatch->nExpr; i++){
857 assert( pFJMatch->a[i].pExpr->op==TK_COLUMN );
858 sqlite3AuthRead(pParse,pFJMatch->a[i].pExpr,pSchema,pNC->pSrcList);
859 }
860 }else if( pExpr->op==TK_COLUMN || pExpr->op==TK_TRIGGER ){
861 sqlite3AuthRead(pParse, pExpr, pSchema, pNC->pSrcList);
862 }
863 }
864#endif
865 /* Increment the nRef value on all name contexts from TopNC up to
866 ** the point where the name matched. */
867 for(;;){
868 assert( pTopNC!=0 );
869 pTopNC->nRef++;
870 if( pTopNC==pNC ) break;
871 pTopNC = pTopNC->pNext;
872 }
873 return WRC_Prune;
874 } else {
875 return WRC_Abort;
876 }
877}
878
879/*
880** Allocate and return a pointer to an expression to load the column iCol
881** from datasource iSrc in SrcList pSrc.
882*/
883Expr *sqlite3CreateColumnExpr(sqlite3 *db, SrcList *pSrc, int iSrc, int iCol){
884 Expr *p = sqlite3ExprAlloc(db, TK_COLUMN, 0, 0);
885 if( p ){
886 SrcItem *pItem = &pSrc->a[iSrc];
887 Table *pTab;
888 assert( ExprUseYTab(p) );
889 pTab = p->y.pTab = pItem->pSTab;
890 p->iTable = pItem->iCursor;
891 if( p->y.pTab->iPKey==iCol ){
892 p->iColumn = -1;
893 }else{
894 p->iColumn = (ynVar)iCol;
895 if( (pTab->tabFlags & TF_HasGenerated)!=0
896 && (pTab->aCol[iCol].colFlags & COLFLAG_GENERATED)!=0
897 ){
898 testcase( pTab->nCol==63 );
899 testcase( pTab->nCol==64 );
900 pItem->colUsed = pTab->nCol>=64 ? ALLBITS : MASKBIT(pTab->nCol)-1;
901 }else{
902 testcase( iCol==BMS );
903 testcase( iCol==BMS-1 );
904 pItem->colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
905 }
906 }
907 }
908 return p;
909}
910
911/*
912** Report an error that an expression is not valid for some set of
913** pNC->ncFlags values determined by validMask.
914**
915** static void notValid(
916** Parse *pParse, // Leave error message here
917** NameContext *pNC, // The name context
918** const char *zMsg, // Type of error
919** int validMask, // Set of contexts for which prohibited
920** Expr *pExpr // Invalidate this expression on error
921** ){...}
922**
923** As an optimization, since the conditional is almost always false
924** (because errors are rare), the conditional is moved outside of the
925** function call using a macro.
926*/
927static void notValidImpl(
928 Parse *pParse, /* Leave error message here */
929 NameContext *pNC, /* The name context */
930 const char *zMsg, /* Type of error */
931 Expr *pExpr, /* Invalidate this expression on error */
932 Expr *pError /* Associate error with this expression */
933){
934 const char *zIn = "partial index WHERE clauses";
935 if( pNC->ncFlags & NC_IdxExpr ) zIn = "index expressions";
936#ifndef SQLITE_OMIT_CHECK
937 else if( pNC->ncFlags & NC_IsCheck ) zIn = "CHECK constraints";
938#endif
939#ifndef SQLITE_OMIT_GENERATED_COLUMNS
940 else if( pNC->ncFlags & NC_GenCol ) zIn = "generated columns";
941#endif
942 sqlite3ErrorMsg(pParse, "%s prohibited in %s", zMsg, zIn);
943 if( pExpr ) pExpr->op = TK_NULL;
944 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
945}
946#define sqlite3ResolveNotValid(P,N,M,X,E,R) \
947 assert( ((X)&~(NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol))==0 ); \
948 if( ((N)->ncFlags & (X))!=0 ) notValidImpl(P,N,M,E,R);
949
950/*
951** Expression p should encode a floating point value between 1.0 and 0.0.
952** Return 134,217,728 (2^27) times this value. Or return -1 if p is not
953** a floating point value between 1.0 and 0.0.
954*/
955static int exprProbability(Expr *p){
956 double r = -1.0;
957 if( p->op!=TK_FLOAT ) return -1;
958 assert( !ExprHasProperty(p, EP_IntValue) );
959 sqlite3AtoF(p->u.zToken, &r);
960 assert( r>=0.0 );
961 if( r>1.0 ) return -1;
962 return (int)(r*134217728.0);
963}
964
965/*
966** Set the EP_SubtArg property on every expression inside of
967** pList. If any subexpression is actually a subquery, then
968** also set the EP_SubtArg property on the first result-set
969** column of that subquery.
970*/
971static SQLITE_NOINLINE void resolveSetExprSubtypeArg(ExprList *pList){
972 int nn, ii;
973 nn = pList ? pList->nExpr : 0;
974 for(ii=0; ii<nn; ii++){
975 Expr *pExpr = pList->a[ii].pExpr;
976 while( 1 /*exit-by-break*/ ){
977 ExprSetProperty(pExpr, EP_SubtArg);
978 if( pExpr->op==TK_SELECT ){
979 assert( ExprUseXSelect(pExpr) );
980 assert( pExpr->x.pSelect!=0 );
981 resolveSetExprSubtypeArg(pExpr->x.pSelect->pEList);
982 break;
983 }
984 if( pExpr->op==TK_UPLUS ){
985 pExpr = pExpr->pLeft;
986 assert( pExpr!=0 );
987 }else if( pExpr->op==TK_CASE ){
988 assert( ExprUseXList(pExpr) );
989 resolveSetExprSubtypeArg(pExpr->x.pList);
990 break;
991 }else{
992 break;
993 }
994 }
995 }
996}
997
998/*
999** This routine is callback for sqlite3WalkExpr().
1000**
1001** Resolve symbolic names into TK_COLUMN operators for the current
1002** node in the expression tree. Return 0 to continue the search down
1003** the tree or 2 to abort the tree walk.
1004**
1005** This routine also does error checking and name resolution for
1006** function names. The operator for aggregate functions is changed
1007** to TK_AGG_FUNCTION.
1008*/
1009static int resolveExprStep(Walker *pWalker, Expr *pExpr){
1010 NameContext *pNC;
1011 Parse *pParse;
1012
1013 pNC = pWalker->u.pNC;
1014 assert( pNC!=0 );
1015 pParse = pNC->pParse;
1016 assert( pParse==pWalker->pParse );
1017
1018#ifndef NDEBUG
1019 if( pNC->pSrcList && pNC->pSrcList->nAlloc>0 ){
1020 SrcList *pSrcList = pNC->pSrcList;
1021 int i;
1022 for(i=0; i<pNC->pSrcList->nSrc; i++){
1023 assert( pSrcList->a[i].iCursor>=0 && pSrcList->a[i].iCursor<pParse->nTab);
1024 }
1025 }
1026#endif
1027 switch( pExpr->op ){
1028
1029 /* The special operator TK_ROW means use the rowid for the first
1030 ** column in the FROM clause. This is used by the LIMIT and ORDER BY
1031 ** clause processing on UPDATE and DELETE statements, and by
1032 ** UPDATE ... FROM statement processing.
1033 */
1034 case TK_ROW: {
1035 SrcList *pSrcList = pNC->pSrcList;
1036 SrcItem *pItem;
1037 assert( pSrcList && pSrcList->nSrc>=1 );
1038 pItem = pSrcList->a;
1039 pExpr->op = TK_COLUMN;
1040 assert( ExprUseYTab(pExpr) );
1041 pExpr->y.pTab = pItem->pSTab;
1042 pExpr->iTable = pItem->iCursor;
1043 pExpr->iColumn--;
1044 pExpr->affExpr = SQLITE_AFF_INTEGER;
1045 break;
1046 }
1047
1048 /* An optimization: Attempt to convert
1049 **
1050 ** "expr IS NOT NULL" --> "TRUE"
1051 ** "expr IS NULL" --> "FALSE"
1052 **
1053 ** if we can prove that "expr" is never NULL. Call this the
1054 ** "NOT NULL strength reduction optimization".
1055 **
1056 ** If this optimization occurs, also restore the NameContext ref-counts
1057 ** to the state they where in before the "column" LHS expression was
1058 ** resolved. This prevents "column" from being counted as having been
1059 ** referenced, which might prevent a SELECT from being erroneously
1060 ** marked as correlated.
1061 **
1062 ** 2024-03-28: Beware of aggregates. A bare column of aggregated table
1063 ** can still evaluate to NULL even though it is marked as NOT NULL.
1064 ** Example:
1065 **
1066 ** CREATE TABLE t1(a INT NOT NULL);
1067 ** SELECT a, a IS NULL, a IS NOT NULL, count(*) FROM t1;
1068 **
1069 ** The "a IS NULL" and "a IS NOT NULL" expressions cannot be optimized
1070 ** here because at the time this case is hit, we do not yet know whether
1071 ** or not t1 is being aggregated. We have to assume the worst and omit
1072 ** the optimization. The only time it is safe to apply this optimization
1073 ** is within the WHERE clause.
1074 */
1075 case TK_NOTNULL:
1076 case TK_ISNULL: {
1077 int anRef[8];
1078 NameContext *p;
1079 int i;
1080 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1081 anRef[i] = p->nRef;
1082 }
1083 sqlite3WalkExpr(pWalker, pExpr->pLeft);
1084 if( IN_RENAME_OBJECT ) return WRC_Prune;
1085 if( sqlite3ExprCanBeNull(pExpr->pLeft) ){
1086 /* The expression can be NULL. So the optimization does not apply */
1087 return WRC_Prune;
1088 }
1089
1090 for(i=0, p=pNC; p; p=p->pNext, i++){
1091 if( (p->ncFlags & NC_Where)==0 ){
1092 return WRC_Prune; /* Not in a WHERE clause. Unsafe to optimize. */
1093 }
1094 }
1095 testcase( ExprHasProperty(pExpr, EP_OuterON) );
1096 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1097#if TREETRACE_ENABLED
1098 if( sqlite3TreeTrace & 0x80000 ){
1099 sqlite3DebugPrintf(
1100 "NOT NULL strength reduction converts the following to %d:\n",
1101 pExpr->op==TK_NOTNULL
1102 );
1103 sqlite3ShowExpr(pExpr);
1104 }
1105#endif /* TREETRACE_ENABLED */
1106 pExpr->u.iValue = (pExpr->op==TK_NOTNULL);
1107 pExpr->flags |= EP_IntValue;
1108 pExpr->op = TK_INTEGER;
1109 for(i=0, p=pNC; p && i<ArraySize(anRef); p=p->pNext, i++){
1110 p->nRef = anRef[i];
1111 }
1112 sqlite3ExprDelete(pParse->db, pExpr->pLeft);
1113 pExpr->pLeft = 0;
1114 return WRC_Prune;
1115 }
1116
1117 /* A column name: ID
1118 ** Or table name and column name: ID.ID
1119 ** Or a database, table and column: ID.ID.ID
1120 **
1121 ** The TK_ID and TK_OUT cases are combined so that there will only
1122 ** be one call to lookupName(). Then the compiler will in-line
1123 ** lookupName() for a size reduction and performance increase.
1124 */
1125 case TK_ID:
1126 case TK_DOT: {
1127 const char *zTable;
1128 const char *zDb;
1129 Expr *pRight;
1130
1131 if( pExpr->op==TK_ID ){
1132 zDb = 0;
1133 zTable = 0;
1134 assert( !ExprHasProperty(pExpr, EP_IntValue) );
1135 pRight = pExpr;
1136 }else{
1137 Expr *pLeft = pExpr->pLeft;
1138 testcase( pNC->ncFlags & NC_IdxExpr );
1139 testcase( pNC->ncFlags & NC_GenCol );
1140 sqlite3ResolveNotValid(pParse, pNC, "the \".\" operator",
1141 NC_IdxExpr|NC_GenCol, 0, pExpr);
1142 pRight = pExpr->pRight;
1143 if( pRight->op==TK_ID ){
1144 zDb = 0;
1145 }else{
1146 assert( pRight->op==TK_DOT );
1147 assert( !ExprHasProperty(pRight, EP_IntValue) );
1148 zDb = pLeft->u.zToken;
1149 pLeft = pRight->pLeft;
1150 pRight = pRight->pRight;
1151 }
1152 assert( ExprUseUToken(pLeft) && ExprUseUToken(pRight) );
1153 zTable = pLeft->u.zToken;
1154 assert( ExprUseYTab(pExpr) );
1155 if( IN_RENAME_OBJECT ){
1156 sqlite3RenameTokenRemap(pParse, (void*)pExpr, (void*)pRight);
1157 sqlite3RenameTokenRemap(pParse, (void*)&pExpr->y.pTab, (void*)pLeft);
1158 }
1159 }
1160 return lookupName(pParse, zDb, zTable, pRight, pNC, pExpr);
1161 }
1162
1163 /* Resolve function names
1164 */
1165 case TK_FUNCTION: {
1166 ExprList *pList; /* The argument list */
1167 int n; /* Number of arguments */
1168 int no_such_func = 0; /* True if no such function exists */
1169 int wrong_num_args = 0; /* True if wrong number of arguments */
1170 int is_agg = 0; /* True if is an aggregate function */
1171 const char *zId; /* The function name. */
1172 FuncDef *pDef; /* Information about the function */
1173 u8 enc = ENC(pParse->db); /* The database encoding */
1174 int savedAllowFlags = (pNC->ncFlags & (NC_AllowAgg | NC_AllowWin));
1175#ifndef SQLITE_OMIT_WINDOWFUNC
1176 Window *pWin = (IsWindowFunc(pExpr) ? pExpr->y.pWin : 0);
1177#endif
1178 assert( !ExprHasProperty(pExpr, EP_xIsSelect|EP_IntValue) );
1179 assert( pExpr->pLeft==0 || pExpr->pLeft->op==TK_ORDER );
1180 pList = pExpr->x.pList;
1181 n = pList ? pList->nExpr : 0;
1182 zId = pExpr->u.zToken;
1183 pDef = sqlite3FindFunction(pParse->db, zId, n, enc, 0);
1184 if( pDef==0 ){
1185 pDef = sqlite3FindFunction(pParse->db, zId, -2, enc, 0);
1186 if( pDef==0 ){
1187 no_such_func = 1;
1188 }else{
1189 wrong_num_args = 1;
1190 }
1191 }else{
1192 is_agg = pDef->xFinalize!=0;
1193 if( pDef->funcFlags & SQLITE_FUNC_UNLIKELY ){
1194 ExprSetProperty(pExpr, EP_Unlikely);
1195 if( n==2 ){
1196 pExpr->iTable = exprProbability(pList->a[1].pExpr);
1197 if( pExpr->iTable<0 ){
1198 sqlite3ErrorMsg(pParse,
1199 "second argument to %#T() must be a "
1200 "constant between 0.0 and 1.0", pExpr);
1201 pNC->nNcErr++;
1202 }
1203 }else{
1204 /* EVIDENCE-OF: R-61304-29449 The unlikely(X) function is
1205 ** equivalent to likelihood(X, 0.0625).
1206 ** EVIDENCE-OF: R-01283-11636 The unlikely(X) function is
1207 ** short-hand for likelihood(X,0.0625).
1208 ** EVIDENCE-OF: R-36850-34127 The likely(X) function is short-hand
1209 ** for likelihood(X,0.9375).
1210 ** EVIDENCE-OF: R-53436-40973 The likely(X) function is equivalent
1211 ** to likelihood(X,0.9375). */
1212 /* TUNING: unlikely() probability is 0.0625. likely() is 0.9375 */
1213 pExpr->iTable = pDef->zName[0]=='u' ? 8388608 : 125829120;
1214 }
1215 }
1216#ifndef SQLITE_OMIT_AUTHORIZATION
1217 {
1218 int auth = sqlite3AuthCheck(pParse, SQLITE_FUNCTION, 0,pDef->zName,0);
1219 if( auth!=SQLITE_OK ){
1220 if( auth==SQLITE_DENY ){
1221 sqlite3ErrorMsg(pParse, "not authorized to use function: %#T",
1222 pExpr);
1223 pNC->nNcErr++;
1224 }
1225 pExpr->op = TK_NULL;
1226 return WRC_Prune;
1227 }
1228 }
1229#endif
1230
1231 /* If the function may call sqlite3_value_subtype(), then set the
1232 ** EP_SubtArg flag on all of its argument expressions. This prevents
1233 ** where.c from replacing the expression with a value read from an
1234 ** index on the same expression, which will not have the correct
1235 ** subtype. Also set the flag if the function expression itself is
1236 ** an EP_SubtArg expression. In this case subtypes are required as
1237 ** the function may return a value with a subtype back to its
1238 ** caller using sqlite3_result_value(). */
1239 if( (pDef->funcFlags & SQLITE_SUBTYPE)
1240 || ExprHasProperty(pExpr, EP_SubtArg)
1241 ){
1242 resolveSetExprSubtypeArg(pList);
1243 }
1244
1245 if( pDef->funcFlags & (SQLITE_FUNC_CONSTANT|SQLITE_FUNC_SLOCHNG) ){
1246 /* For the purposes of the EP_ConstFunc flag, date and time
1247 ** functions and other functions that change slowly are considered
1248 ** constant because they are constant for the duration of one query.
1249 ** This allows them to be factored out of inner loops. */
1250 ExprSetProperty(pExpr,EP_ConstFunc);
1251 }
1252 if( (pDef->funcFlags & SQLITE_FUNC_CONSTANT)==0 ){
1253 /* Clearly non-deterministic functions like random(), but also
1254 ** date/time functions that use 'now', and other functions like
1255 ** sqlite_version() that might change over time cannot be used
1256 ** in an index or generated column. Curiously, they can be used
1257 ** in a CHECK constraint. SQLServer, MySQL, and PostgreSQL all
1258 ** allow this. */
1259 sqlite3ResolveNotValid(pParse, pNC, "non-deterministic functions",
1260 NC_IdxExpr|NC_PartIdx|NC_GenCol, 0, pExpr);
1261 }else{
1262 assert( (NC_SelfRef & 0xff)==NC_SelfRef ); /* Must fit in 8 bits */
1263 pExpr->op2 = pNC->ncFlags & NC_SelfRef;
1264 }
1265 if( (pDef->funcFlags & SQLITE_FUNC_INTERNAL)!=0
1266 && pParse->nested==0
1267 && (pParse->db->mDbFlags & DBFLAG_InternalFunc)==0
1268 ){
1269 /* Internal-use-only functions are disallowed unless the
1270 ** SQL is being compiled using sqlite3NestedParse() or
1271 ** the SQLITE_TESTCTRL_INTERNAL_FUNCTIONS test-control has be
1272 ** used to activate internal functions for testing purposes.
1273 **
1274 ** The 2 value for no_such_func means that the function is
1275 ** an internal-use-only function which should be treated as a
1276 ** non-existant function for name resolution purposes.
1277 */
1278 no_such_func = 2;
1279 pDef = 0;
1280 }else
1281 if( (pDef->funcFlags & (SQLITE_FUNC_DIRECT|SQLITE_FUNC_UNSAFE))!=0
1282 && !IN_RENAME_OBJECT
1283 ){
1284 if( pNC->ncFlags & NC_FromDDL ) ExprSetProperty(pExpr, EP_FromDDL);
1285 sqlite3ExprFunctionUsable(pParse, pExpr, pDef);
1286 }
1287 }
1288
1289 if( 0==IN_RENAME_OBJECT ){
1290#ifndef SQLITE_OMIT_WINDOWFUNC
1291 assert( is_agg==0 || (pDef->funcFlags & SQLITE_FUNC_MINMAX)
1292 || (pDef->xValue==0 && pDef->xInverse==0)
1293 || (pDef->xValue && pDef->xInverse && pDef->xSFunc && pDef->xFinalize)
1294 );
1295 if( pDef && pDef->xValue==0 && pWin ){
1296 sqlite3ErrorMsg(pParse,
1297 "%#T() may not be used as a window function", pExpr
1298 );
1299 pNC->nNcErr++;
1300 }else if(
1301 (is_agg && (pNC->ncFlags & NC_AllowAgg)==0)
1302 || (is_agg && (pDef->funcFlags&SQLITE_FUNC_WINDOW) && !pWin)
1303 || (is_agg && pWin && (pNC->ncFlags & NC_AllowWin)==0)
1304 ){
1305 const char *zType;
1306 if( (pDef->funcFlags & SQLITE_FUNC_WINDOW) || pWin ){
1307 zType = "window";
1308 }else{
1309 zType = "aggregate";
1310 }
1311 sqlite3ErrorMsg(pParse, "misuse of %s function %#T()",zType,pExpr);
1312 pNC->nNcErr++;
1313 is_agg = 0;
1314 }
1315#else
1316 if( (is_agg && (pNC->ncFlags & NC_AllowAgg)==0) ){
1317 sqlite3ErrorMsg(pParse,"misuse of aggregate function %#T()",pExpr);
1318 pNC->nNcErr++;
1319 is_agg = 0;
1320 }
1321#endif
1322 else if( no_such_func
1323 && (pParse->db->init.busy==0 ||
1324 (no_such_func==2 && pParse->db->init.busy==2))
1325 /* Suppress "no such function" errors when reading
1326 ** the sqlite_schema table. Except, do raise the error
1327 ** if init.busy is 2, meaning the schema parse is due
1328 ** to an ALTER TABLE ADD COLUMN statement, and the function
1329 ** is an internal-use-only function (no_such_func==2). */
1330#ifdef SQLITE_ENABLE_UNKNOWN_SQL_FUNCTION
1331 && pParse->explain==0
1332#endif
1333 ){
1334 sqlite3ErrorMsg(pParse, "no such function: %#T", pExpr);
1335 pNC->nNcErr++;
1336 }else if( wrong_num_args ){
1337 sqlite3ErrorMsg(pParse,"wrong number of arguments to function %#T()",
1338 pExpr);
1339 pNC->nNcErr++;
1340 }
1341#ifndef SQLITE_OMIT_WINDOWFUNC
1342 else if( is_agg==0 && ExprHasProperty(pExpr, EP_WinFunc) ){
1343 sqlite3ErrorMsg(pParse,
1344 "FILTER may not be used with non-aggregate %#T()",
1345 pExpr
1346 );
1347 pNC->nNcErr++;
1348 }
1349#endif
1350 else if( is_agg==0 && pExpr->pLeft ){
1351 sqlite3ExprOrderByAggregateError(pParse, pExpr);
1352 pNC->nNcErr++;
1353 }
1354 if( is_agg ){
1355 /* Window functions may not be arguments of aggregate functions.
1356 ** Or arguments of other window functions. But aggregate functions
1357 ** may be arguments for window functions. */
1358#ifndef SQLITE_OMIT_WINDOWFUNC
1359 pNC->ncFlags &= ~(NC_AllowWin | (!pWin ? NC_AllowAgg : 0));
1360#else
1361 pNC->ncFlags &= ~NC_AllowAgg;
1362#endif
1363 }
1364 }
1365 else if( ExprHasProperty(pExpr, EP_WinFunc) || pExpr->pLeft ){
1366 is_agg = 1;
1367 }
1368 sqlite3WalkExprList(pWalker, pList);
1369 if( is_agg ){
1370 if( pExpr->pLeft ){
1371 assert( pExpr->pLeft->op==TK_ORDER );
1372 assert( ExprUseXList(pExpr->pLeft) );
1373 sqlite3WalkExprList(pWalker, pExpr->pLeft->x.pList);
1374 }
1375#ifndef SQLITE_OMIT_WINDOWFUNC
1376 if( pWin && pParse->nErr==0 ){
1377 Select *pSel = pNC->pWinSelect;
1378 assert( ExprUseYWin(pExpr) && pWin==pExpr->y.pWin );
1379 if( IN_RENAME_OBJECT==0 ){
1380 sqlite3WindowUpdate(pParse, pSel ? pSel->pWinDefn : 0, pWin, pDef);
1381 if( pParse->db->mallocFailed ) break;
1382 }
1383 sqlite3WalkExprList(pWalker, pWin->pPartition);
1384 sqlite3WalkExprList(pWalker, pWin->pOrderBy);
1385 sqlite3WalkExpr(pWalker, pWin->pFilter);
1386 sqlite3WindowLink(pSel, pWin);
1387 pNC->ncFlags |= NC_HasWin;
1388 }else
1389#endif /* SQLITE_OMIT_WINDOWFUNC */
1390 {
1391 NameContext *pNC2; /* For looping up thru outer contexts */
1392 pExpr->op = TK_AGG_FUNCTION;
1393 pExpr->op2 = 0;
1394#ifndef SQLITE_OMIT_WINDOWFUNC
1395 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1396 sqlite3WalkExpr(pWalker, pExpr->y.pWin->pFilter);
1397 }
1398#endif
1399 pNC2 = pNC;
1400 while( pNC2
1401 && sqlite3ReferencesSrcList(pParse, pExpr, pNC2->pSrcList)==0
1402 ){
1403 pExpr->op2 += (1 + pNC2->nNestedSelect);
1404 pNC2 = pNC2->pNext;
1405 }
1406 assert( pDef!=0 || IN_RENAME_OBJECT );
1407 if( pNC2 && pDef ){
1408 pExpr->op2 += pNC2->nNestedSelect;
1409 assert( SQLITE_FUNC_MINMAX==NC_MinMaxAgg );
1410 assert( SQLITE_FUNC_ANYORDER==NC_OrderAgg );
1411 testcase( (pDef->funcFlags & SQLITE_FUNC_MINMAX)!=0 );
1412 testcase( (pDef->funcFlags & SQLITE_FUNC_ANYORDER)!=0 );
1413 pNC2->ncFlags |= NC_HasAgg
1414 | ((pDef->funcFlags^SQLITE_FUNC_ANYORDER)
1415 & (SQLITE_FUNC_MINMAX|SQLITE_FUNC_ANYORDER));
1416 }
1417 }
1418 pNC->ncFlags |= savedAllowFlags;
1419 }
1420 /* FIX ME: Compute pExpr->affinity based on the expected return
1421 ** type of the function
1422 */
1423 return WRC_Prune;
1424 }
1425#ifndef SQLITE_OMIT_SUBQUERY
1426 case TK_EXISTS:
1427 case TK_SELECT:
1428#endif
1429 case TK_IN: {
1430 testcase( pExpr->op==TK_IN );
1431 testcase( pExpr->op==TK_EXISTS );
1432 testcase( pExpr->op==TK_SELECT );
1433 if( ExprUseXSelect(pExpr) ){
1434 int nRef = pNC->nRef;
1435 testcase( pNC->ncFlags & NC_IsCheck );
1436 testcase( pNC->ncFlags & NC_PartIdx );
1437 testcase( pNC->ncFlags & NC_IdxExpr );
1438 testcase( pNC->ncFlags & NC_GenCol );
1439 assert( pExpr->x.pSelect );
1440 if( pExpr->op==TK_EXISTS ) pParse->bHasExists = 1;
1441 if( pNC->ncFlags & NC_SelfRef ){
1442 notValidImpl(pParse, pNC, "subqueries", pExpr, pExpr);
1443 }else{
1444 sqlite3WalkSelect(pWalker, pExpr->x.pSelect);
1445 }
1446 assert( pNC->nRef>=nRef );
1447 if( nRef!=pNC->nRef ){
1448 ExprSetProperty(pExpr, EP_VarSelect);
1449 pExpr->x.pSelect->selFlags |= SF_Correlated;
1450 }
1451 pNC->ncFlags |= NC_Subquery;
1452 }
1453 break;
1454 }
1455 case TK_VARIABLE: {
1456 testcase( pNC->ncFlags & NC_IsCheck );
1457 testcase( pNC->ncFlags & NC_PartIdx );
1458 testcase( pNC->ncFlags & NC_IdxExpr );
1459 testcase( pNC->ncFlags & NC_GenCol );
1460 sqlite3ResolveNotValid(pParse, pNC, "parameters",
1461 NC_IsCheck|NC_PartIdx|NC_IdxExpr|NC_GenCol, pExpr, pExpr);
1462 break;
1463 }
1464 case TK_IS:
1465 case TK_ISNOT: {
1466 Expr *pRight = sqlite3ExprSkipCollateAndLikely(pExpr->pRight);
1467 assert( !ExprHasProperty(pExpr, EP_Reduced) );
1468 /* Handle special cases of "x IS TRUE", "x IS FALSE", "x IS NOT TRUE",
1469 ** and "x IS NOT FALSE". */
1470 if( ALWAYS(pRight) && (pRight->op==TK_ID || pRight->op==TK_TRUEFALSE) ){
1471 int rc = resolveExprStep(pWalker, pRight);
1472 if( rc==WRC_Abort ) return WRC_Abort;
1473 if( pRight->op==TK_TRUEFALSE ){
1474 pExpr->op2 = pExpr->op;
1475 pExpr->op = TK_TRUTH;
1476 return WRC_Continue;
1477 }
1478 }
1479 /* no break */ deliberate_fall_through
1480 }
1481 case TK_BETWEEN:
1482 case TK_EQ:
1483 case TK_NE:
1484 case TK_LT:
1485 case TK_LE:
1486 case TK_GT:
1487 case TK_GE: {
1488 int nLeft, nRight;
1489 if( pParse->db->mallocFailed ) break;
1490 assert( pExpr->pLeft!=0 );
1491 nLeft = sqlite3ExprVectorSize(pExpr->pLeft);
1492 if( pExpr->op==TK_BETWEEN ){
1493 assert( ExprUseXList(pExpr) );
1494 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[0].pExpr);
1495 if( nRight==nLeft ){
1496 nRight = sqlite3ExprVectorSize(pExpr->x.pList->a[1].pExpr);
1497 }
1498 }else{
1499 assert( pExpr->pRight!=0 );
1500 nRight = sqlite3ExprVectorSize(pExpr->pRight);
1501 }
1502 if( nLeft!=nRight ){
1503 testcase( pExpr->op==TK_EQ );
1504 testcase( pExpr->op==TK_NE );
1505 testcase( pExpr->op==TK_LT );
1506 testcase( pExpr->op==TK_LE );
1507 testcase( pExpr->op==TK_GT );
1508 testcase( pExpr->op==TK_GE );
1509 testcase( pExpr->op==TK_IS );
1510 testcase( pExpr->op==TK_ISNOT );
1511 testcase( pExpr->op==TK_BETWEEN );
1512 sqlite3ErrorMsg(pParse, "row value misused");
1513 sqlite3RecordErrorOffsetOfExpr(pParse->db, pExpr);
1514 }
1515 break;
1516 }
1517 }
1518 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
1519 return pParse->nErr ? WRC_Abort : WRC_Continue;
1520}
1521
1522/*
1523** pEList is a list of expressions which are really the result set of the
1524** a SELECT statement. pE is a term in an ORDER BY or GROUP BY clause.
1525** This routine checks to see if pE is a simple identifier which corresponds
1526** to the AS-name of one of the terms of the expression list. If it is,
1527** this routine return an integer between 1 and N where N is the number of
1528** elements in pEList, corresponding to the matching entry. If there is
1529** no match, or if pE is not a simple identifier, then this routine
1530** return 0.
1531**
1532** pEList has been resolved. pE has not.
1533*/
1534static int resolveAsName(
1535 Parse *pParse, /* Parsing context for error messages */
1536 ExprList *pEList, /* List of expressions to scan */
1537 Expr *pE /* Expression we are trying to match */
1538){
1539 int i; /* Loop counter */
1540
1541 UNUSED_PARAMETER(pParse);
1542
1543 if( pE->op==TK_ID ){
1544 const char *zCol;
1545 assert( !ExprHasProperty(pE, EP_IntValue) );
1546 zCol = pE->u.zToken;
1547 for(i=0; i<pEList->nExpr; i++){
1548 if( pEList->a[i].fg.eEName==ENAME_NAME
1549 && sqlite3_stricmp(pEList->a[i].zEName, zCol)==0
1550 ){
1551 return i+1;
1552 }
1553 }
1554 }
1555 return 0;
1556}
1557
1558/*
1559** pE is a pointer to an expression which is a single term in the
1560** ORDER BY of a compound SELECT. The expression has not been
1561** name resolved.
1562**
1563** At the point this routine is called, we already know that the
1564** ORDER BY term is not an integer index into the result set. That
1565** case is handled by the calling routine.
1566**
1567** Attempt to match pE against result set columns in the left-most
1568** SELECT statement. Return the index i of the matching column,
1569** as an indication to the caller that it should sort by the i-th column.
1570** The left-most column is 1. In other words, the value returned is the
1571** same integer value that would be used in the SQL statement to indicate
1572** the column.
1573**
1574** If there is no match, return 0. Return -1 if an error occurs.
1575*/
1576static int resolveOrderByTermToExprList(
1577 Parse *pParse, /* Parsing context for error messages */
1578 Select *pSelect, /* The SELECT statement with the ORDER BY clause */
1579 Expr *pE /* The specific ORDER BY term */
1580){
1581 int i; /* Loop counter */
1582 ExprList *pEList; /* The columns of the result set */
1583 NameContext nc; /* Name context for resolving pE */
1584 sqlite3 *db; /* Database connection */
1585 int rc; /* Return code from subprocedures */
1586 u8 savedSuppErr; /* Saved value of db->suppressErr */
1587
1588 assert( sqlite3ExprIsInteger(pE, &i, 0, 1)==0 );
1589 pEList = pSelect->pEList;
1590
1591 /* Resolve all names in the ORDER BY term expression
1592 */
1593 memset(&nc, 0, sizeof(nc));
1594 nc.pParse = pParse;
1595 nc.pSrcList = pSelect->pSrc;
1596 nc.uNC.pEList = pEList;
1597 nc.ncFlags = NC_AllowAgg|NC_UEList|NC_NoSelect;
1598 nc.nNcErr = 0;
1599 db = pParse->db;
1600 savedSuppErr = db->suppressErr;
1601 db->suppressErr = 1;
1602 rc = sqlite3ResolveExprNames(&nc, pE);
1603 db->suppressErr = savedSuppErr;
1604 if( rc ) return 0;
1605
1606 /* Try to match the ORDER BY expression against an expression
1607 ** in the result set. Return an 1-based index of the matching
1608 ** result-set entry.
1609 */
1610 for(i=0; i<pEList->nExpr; i++){
1611 if( sqlite3ExprCompare(0, pEList->a[i].pExpr, pE, -1)<2 ){
1612 return i+1;
1613 }
1614 }
1615
1616 /* If no match, return 0. */
1617 return 0;
1618}
1619
1620/*
1621** ORDER BY term pE, a simple identifier, has been matched by resolveAsName()
1622** against the iCol-th (1-based) entry of result-set pEList. If this is an
1623** ALTER TABLE rename, and the name of that entry was generated by expanding
1624** "*" or "tbl.*", then modify pE to refer to the table column directly.
1625*/
1626static void resolveRenameStarTerm(
1627 Parse *pParse, /* Parsing context */
1628 ExprList *pEList, /* Result-set that pE was matched against */
1629 int iCol, /* 1-based index of the matching pEList entry */
1630 Expr *pE /* ORDER BY term to convert */
1631){
1632 if( IN_RENAME_OBJECT && pEList->a[iCol-1].fg.bStarName ){
1633 Expr *pX = pEList->a[iCol-1].pExpr;
1634 if( ALWAYS(pX->op==TK_COLUMN) && ALWAYS(pE->op==TK_ID) ){
1635 pE->op = TK_COLUMN;
1636 pE->iTable = pX->iTable;
1637 pE->iColumn = pX->iColumn;
1638 pE->y.pTab = pX->y.pTab;
1639 }
1640 }
1641}
1642
1643/*
1644** Generate an ORDER BY or GROUP BY term out-of-range error.
1645*/
1646static void resolveOutOfRangeError(
1647 Parse *pParse, /* The error context into which to write the error */
1648 const char *zType, /* "ORDER" or "GROUP" */
1649 int i, /* The index (1-based) of the term out of range */
1650 int mx, /* Largest permissible value of i */
1651 Expr *pError /* Associate the error with the expression */
1652){
1653 sqlite3ErrorMsg(pParse,
1654 "%r %s BY term out of range - should be "
1655 "between 1 and %d", i, zType, mx);
1656 sqlite3RecordErrorOffsetOfExpr(pParse->db, pError);
1657}
1658
1659/*
1660** Analyze the ORDER BY clause in a compound SELECT statement. Modify
1661** each term of the ORDER BY clause is a constant integer between 1
1662** and N where N is the number of columns in the compound SELECT.
1663**
1664** ORDER BY terms that are already an integer between 1 and N are
1665** unmodified. ORDER BY terms that are integers outside the range of
1666** 1 through N generate an error. ORDER BY terms that are expressions
1667** are matched against result set expressions of compound SELECT
1668** beginning with the left-most SELECT and working toward the right.
1669** At the first match, the ORDER BY expression is transformed into
1670** the integer column number.
1671**
1672** Return the number of errors seen.
1673*/
1674static int resolveCompoundOrderBy(
1675 Parse *pParse, /* Parsing context. Leave error messages here */
1676 Select *pSelect /* The SELECT statement containing the ORDER BY */
1677){
1678 int i;
1679 ExprList *pOrderBy;
1680 ExprList *pEList;
1681 sqlite3 *db;
1682 int moreToDo = 1;
1683
1684 pOrderBy = pSelect->pOrderBy;
1685 if( pOrderBy==0 ) return 0;
1686 db = pParse->db;
1687 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1688 sqlite3ErrorMsg(pParse, "too many terms in ORDER BY clause");
1689 return 1;
1690 }
1691 for(i=0; i<pOrderBy->nExpr; i++){
1692 pOrderBy->a[i].fg.done = 0;
1693 }
1694 pSelect->pNext = 0;
1695 while( pSelect->pPrior ){
1696 pSelect->pPrior->pNext = pSelect;
1697 pSelect = pSelect->pPrior;
1698 }
1699 while( pSelect && moreToDo ){
1700 struct ExprList_item *pItem;
1701 moreToDo = 0;
1702 pEList = pSelect->pEList;
1703 assert( pEList!=0 );
1704 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1705 int iCol = -1;
1706 Expr *pE, *pDup;
1707 if( pItem->fg.done ) continue;
1708 pE = sqlite3ExprSkipCollateAndLikely(pItem->pExpr);
1709 if( NEVER(pE==0) ) continue;
1710 if( sqlite3ExprIsInteger(pE, &iCol, 0, 1) ){
1711 if( iCol<=0 || iCol>pEList->nExpr ){
1712 resolveOutOfRangeError(pParse, "ORDER", i+1, pEList->nExpr, pE);
1713 return 1;
1714 }
1715 }else{
1716 iCol = resolveAsName(pParse, pEList, pE);
1717 if( iCol>0 ){
1718 resolveRenameStarTerm(pParse, pEList, iCol, pE);
1719 }else{
1720 /* Now test if expression pE matches one of the values returned
1721 ** by pSelect. In the usual case this is done by duplicating the
1722 ** expression, resolving any symbols in it, and then comparing
1723 ** it against each expression returned by the SELECT statement.
1724 ** Once the comparisons are finished, the duplicate expression
1725 ** is deleted.
1726 **
1727 ** If this is running as part of an ALTER TABLE operation and
1728 ** the symbols resolve successfully, also resolve the symbols in the
1729 ** actual expression. This allows the code in alter.c to modify
1730 ** column references within the ORDER BY expression as required. */
1731 pDup = sqlite3ExprDup(db, pE, 0);
1732 if( !db->mallocFailed ){
1733 assert(pDup);
1734 iCol = resolveOrderByTermToExprList(pParse, pSelect, pDup);
1735 if( IN_RENAME_OBJECT && iCol>0 ){
1736 resolveOrderByTermToExprList(pParse, pSelect, pE);
1737 }
1738 }
1739 sqlite3ExprDelete(db, pDup);
1740 }
1741 }
1742 if( iCol>0 ){
1743 /* Convert the ORDER BY term into an integer column number iCol,
1744 ** taking care to preserve the COLLATE clause if it exists. */
1745 if( !IN_RENAME_OBJECT ){
1746 Expr *pNew = sqlite3ExprInt32(db, iCol);
1747 if( pNew==0 ) return 1;
1748 if( pItem->pExpr==pE ){
1749 pItem->pExpr = pNew;
1750 }else{
1751 Expr *pParent = pItem->pExpr;
1752 assert( pParent->op==TK_COLLATE );
1753 while( pParent->pLeft->op==TK_COLLATE ) pParent = pParent->pLeft;
1754 assert( pParent->pLeft==pE );
1755 pParent->pLeft = pNew;
1756 }
1757 sqlite3ExprDelete(db, pE);
1758 pItem->u.x.iOrderByCol = (u16)iCol;
1759 }
1760 pItem->fg.done = 1;
1761 }else{
1762 moreToDo = 1;
1763 }
1764 }
1765 pSelect = pSelect->pNext;
1766 }
1767 for(i=0; i<pOrderBy->nExpr; i++){
1768 if( pOrderBy->a[i].fg.done==0 ){
1769 sqlite3ErrorMsg(pParse, "%r ORDER BY term does not match any "
1770 "column in the result set", i+1);
1771 return 1;
1772 }
1773 }
1774 return 0;
1775}
1776
1777/*
1778** Check every term in the ORDER BY or GROUP BY clause pOrderBy of
1779** the SELECT statement pSelect. If any term is reference to a
1780** result set expression (as determined by the ExprList.a.u.x.iOrderByCol
1781** field) then convert that term into a copy of the corresponding result set
1782** column.
1783**
1784** If any errors are detected, add an error message to pParse and
1785** return non-zero. Return zero if no errors are seen.
1786*/
1787int sqlite3ResolveOrderGroupBy(
1788 Parse *pParse, /* Parsing context. Leave error messages here */
1789 Select *pSelect, /* The SELECT statement containing the clause */
1790 ExprList *pOrderBy, /* The ORDER BY or GROUP BY clause to be processed */
1791 const char *zType /* "ORDER" or "GROUP" */
1792){
1793 int i;
1794 sqlite3 *db = pParse->db;
1795 ExprList *pEList;
1796 struct ExprList_item *pItem;
1797
1798 if( pOrderBy==0 || pParse->db->mallocFailed || IN_RENAME_OBJECT ) return 0;
1799 if( pOrderBy->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
1800 sqlite3ErrorMsg(pParse, "too many terms in %s BY clause", zType);
1801 return 1;
1802 }
1803 pEList = pSelect->pEList;
1804 assert( pEList!=0 ); /* sqlite3SelectNew() guarantees this */
1805 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1806 if( pItem->u.x.iOrderByCol ){
1807 if( pItem->u.x.iOrderByCol>pEList->nExpr ){
1808 resolveOutOfRangeError(pParse, zType, i+1, pEList->nExpr, 0);
1809 return 1;
1810 }
1811 resolveAlias(pParse, pEList, pItem->u.x.iOrderByCol-1, pItem->pExpr,0);
1812 }
1813 }
1814 return 0;
1815}
1816
1817#ifndef SQLITE_OMIT_WINDOWFUNC
1818/*
1819** Walker callback for windowRemoveExprFromSelect().
1820*/
1821static int resolveRemoveWindowsCb(Walker *pWalker, Expr *pExpr){
1822 UNUSED_PARAMETER(pWalker);
1823 if( ExprHasProperty(pExpr, EP_WinFunc) ){
1824 Window *pWin = pExpr->y.pWin;
1825 sqlite3WindowUnlinkFromSelect(pWin);
1826 }
1827 return WRC_Continue;
1828}
1829
1830/*
1831** Remove any Window objects owned by the expression pExpr from the
1832** Select.pWin list of Select object pSelect.
1833*/
1834static void windowRemoveExprFromSelect(Select *pSelect, Expr *pExpr){
1835 if( pSelect->pWin ){
1836 Walker sWalker;
1837 memset(&sWalker, 0, sizeof(Walker));
1838 sWalker.xExprCallback = resolveRemoveWindowsCb;
1839 sWalker.u.pSelect = pSelect;
1840 sqlite3WalkExpr(&sWalker, pExpr);
1841 }
1842}
1843#else
1844# define windowRemoveExprFromSelect(a, b)
1845#endif /* SQLITE_OMIT_WINDOWFUNC */
1846
1847/*
1848** pOrderBy is an ORDER BY or GROUP BY clause in SELECT statement pSelect.
1849** The Name context of the SELECT statement is pNC. zType is either
1850** "ORDER" or "GROUP" depending on which type of clause pOrderBy is.
1851**
1852** This routine resolves each term of the clause into an expression.
1853** If the order-by term is an integer I between 1 and N (where N is the
1854** number of columns in the result set of the SELECT) then the expression
1855** in the resolution is a copy of the I-th result-set expression. If
1856** the order-by term is an identifier that corresponds to the AS-name of
1857** a result-set expression, then the term resolves to a copy of the
1858** result-set expression. Otherwise, the expression is resolved in
1859** the usual way - using sqlite3ResolveExprNames().
1860**
1861** This routine returns the number of errors. If errors occur, then
1862** an appropriate error message might be left in pParse. (OOM errors
1863** excepted.)
1864*/
1865static int resolveOrderGroupBy(
1866 NameContext *pNC, /* The name context of the SELECT statement */
1867 Select *pSelect, /* The SELECT statement holding pOrderBy */
1868 ExprList *pOrderBy, /* An ORDER BY or GROUP BY clause to resolve */
1869 const char *zType /* Either "ORDER" or "GROUP", as appropriate */
1870){
1871 int i, j; /* Loop counters */
1872 int iCol; /* Column number */
1873 struct ExprList_item *pItem; /* A term of the ORDER BY clause */
1874 Parse *pParse; /* Parsing context */
1875 int nResult; /* Number of terms in the result set */
1876
1877 assert( pOrderBy!=0 );
1878 nResult = pSelect->pEList->nExpr;
1879 pParse = pNC->pParse;
1880 for(i=0, pItem=pOrderBy->a; i<pOrderBy->nExpr; i++, pItem++){
1881 Expr *pE = pItem->pExpr;
1882 Expr *pE2 = sqlite3ExprSkipCollateAndLikely(pE);
1883 if( NEVER(pE2==0) ) continue;
1884 if( zType[0]!='G' ){
1885 iCol = resolveAsName(pParse, pSelect->pEList, pE2);
1886 if( iCol>0 ){
1887 resolveRenameStarTerm(pParse, pSelect->pEList, iCol, pE2);
1888 /* If an AS-name match is found, mark this ORDER BY column as being
1889 ** a copy of the iCol-th result-set column. The subsequent call to
1890 ** sqlite3ResolveOrderGroupBy() will convert the expression to a
1891 ** copy of the iCol-th result-set expression. */
1892 pItem->u.x.iOrderByCol = (u16)iCol;
1893 continue;
1894 }
1895 }
1896 if( sqlite3ExprIsInteger(pE2, &iCol, 0, 1) ){
1897 /* The ORDER BY term is an integer constant. Again, set the column
1898 ** number so that sqlite3ResolveOrderGroupBy() will convert the
1899 ** order-by term to a copy of the result-set expression */
1900 if( iCol<1 || iCol>0xffff ){
1901 resolveOutOfRangeError(pParse, zType, i+1, nResult, pE2);
1902 return 1;
1903 }
1904 pItem->u.x.iOrderByCol = (u16)iCol;
1905 continue;
1906 }
1907
1908 /* Otherwise, treat the ORDER BY term as an ordinary expression */
1909 pItem->u.x.iOrderByCol = 0;
1910 if( sqlite3ResolveExprNames(pNC, pE) ){
1911 return 1;
1912 }
1913 for(j=0; j<pSelect->pEList->nExpr; j++){
1914 if( sqlite3ExprCompare(0, pE, pSelect->pEList->a[j].pExpr, -1)==0 ){
1915 /* Since this expression is being changed into a reference
1916 ** to an identical expression in the result set, remove all Window
1917 ** objects belonging to the expression from the Select.pWin list. */
1918 windowRemoveExprFromSelect(pSelect, pE);
1919 pItem->u.x.iOrderByCol = j+1;
1920 }
1921 }
1922 }
1923 return sqlite3ResolveOrderGroupBy(pParse, pSelect, pOrderBy, zType);
1924}
1925
1926/*
1927** Resolve names in the SELECT statement p and all of its descendants.
1928*/
1929static int resolveSelectStep(Walker *pWalker, Select *p){
1930 NameContext *pOuterNC; /* Context that contains this SELECT */
1931 NameContext sNC; /* Name context of this SELECT */
1932 int isCompound; /* True if p is a compound select */
1933 int nCompound; /* Number of compound terms processed so far */
1934 Parse *pParse; /* Parsing context */
1935 int i; /* Loop counter */
1936 ExprList *pGroupBy; /* The GROUP BY clause */
1937 Select *pLeftmost; /* Left-most of SELECT of a compound */
1938 sqlite3 *db; /* Database connection */
1939
1940
1941 assert( p!=0 );
1942 if( p->selFlags & SF_Resolved ){
1943 return WRC_Prune;
1944 }
1945 pOuterNC = pWalker->u.pNC;
1946 pParse = pWalker->pParse;
1947 db = pParse->db;
1948
1949 /* Normally sqlite3SelectExpand() will be called first and will have
1950 ** already expanded this SELECT. However, if this is a subquery within
1951 ** an expression, sqlite3ResolveExprNames() will be called without a
1952 ** prior call to sqlite3SelectExpand(). When that happens, let
1953 ** sqlite3SelectPrep() do all of the processing for this SELECT.
1954 ** sqlite3SelectPrep() will invoke both sqlite3SelectExpand() and
1955 ** this routine in the correct order.
1956 */
1957 if( (p->selFlags & SF_Expanded)==0 ){
1958 sqlite3SelectPrep(pParse, p, pOuterNC);
1959 return pParse->nErr ? WRC_Abort : WRC_Prune;
1960 }
1961
1962 isCompound = p->pPrior!=0;
1963 nCompound = 0;
1964 pLeftmost = p;
1965 while( p ){
1966 assert( (p->selFlags & SF_Expanded)!=0 );
1967 assert( (p->selFlags & SF_Resolved)==0 );
1968 p->selFlags |= SF_Resolved;
1969
1970 /* Resolve the expressions in the LIMIT and OFFSET clauses. These
1971 ** are not allowed to refer to any names, so pass an empty NameContext.
1972 */
1973 memset(&sNC, 0, sizeof(sNC));
1974 sNC.pParse = pParse;
1975 sNC.pWinSelect = p;
1976 if( sqlite3ResolveExprNames(&sNC, p->pLimit) ){
1977 return WRC_Abort;
1978 }
1979
1980 /* If the SF_Converted flags is set, then this Select object was
1981 ** was created by the convertCompoundSelectToSubquery() function.
1982 ** In this case the ORDER BY clause (p->pOrderBy) should be resolved
1983 ** as if it were part of the sub-query, not the parent. This block
1984 ** moves the pOrderBy down to the sub-query. It will be moved back
1985 ** after the names have been resolved. */
1986 if( p->selFlags & SF_Converted ){
1987 Select *pSub;
1988 assert( p->pSrc->a[0].fg.isSubquery );
1989 assert( p->pSrc->a[0].u4.pSubq!=0 );
1990 pSub = p->pSrc->a[0].u4.pSubq->pSelect;
1991 assert( pSub!=0 );
1992 assert( p->pSrc->nSrc==1 && p->pOrderBy );
1993 assert( pSub->pPrior && pSub->pOrderBy==0 );
1994 pSub->pOrderBy = p->pOrderBy;
1995 p->pOrderBy = 0;
1996 }
1997
1998 /* Recursively resolve names in all subqueries in the FROM clause
1999 */
2000 if( pOuterNC ) pOuterNC->nNestedSelect++;
2001 for(i=0; i<p->pSrc->nSrc; i++){
2002 SrcItem *pItem = &p->pSrc->a[i];
2003 assert( pItem->zName!=0
2004 || pItem->fg.isSubquery ); /* Test of tag-20240424-1*/
2005 if( pItem->fg.isSubquery
2006 && (pItem->u4.pSubq->pSelect->selFlags & SF_Resolved)==0
2007 ){
2008 int nRef = pOuterNC ? pOuterNC->nRef : 0;
2009 const char *zSavedContext = pParse->zAuthContext;
2010
2011 if( pItem->zName ) pParse->zAuthContext = pItem->zName;
2012 sqlite3ResolveSelectNames(pParse, pItem->u4.pSubq->pSelect, pOuterNC);
2013 pParse->zAuthContext = zSavedContext;
2014 if( pParse->nErr ) return WRC_Abort;
2015 assert( db->mallocFailed==0 );
2016
2017 /* If the number of references to the outer context changed when
2018 ** expressions in the sub-select were resolved, the sub-select
2019 ** is correlated. It is not required to check the refcount on any
2020 ** but the innermost outer context object, as lookupName() increments
2021 ** the refcount on all contexts between the current one and the
2022 ** context containing the column when it resolves a name. */
2023 if( pOuterNC ){
2024 assert( pItem->fg.isCorrelated==0 && pOuterNC->nRef>=nRef );
2025 pItem->fg.isCorrelated = (pOuterNC->nRef>nRef);
2026 }
2027 }
2028 }
2029 if( pOuterNC && ALWAYS(pOuterNC->nNestedSelect>0) ){
2030 pOuterNC->nNestedSelect--;
2031 }
2032
2033 /* Set up the local name-context to pass to sqlite3ResolveExprNames() to
2034 ** resolve the result-set expression list.
2035 */
2036 sNC.ncFlags = NC_AllowAgg|NC_AllowWin;
2037 sNC.pSrcList = p->pSrc;
2038 sNC.pNext = pOuterNC;
2039
2040 /* Resolve names in the result set. */
2041 if( sqlite3ResolveExprListNames(&sNC, p->pEList) ) return WRC_Abort;
2042 sNC.ncFlags &= ~NC_AllowWin;
2043
2044 /* If there are no aggregate functions in the result-set, and no GROUP BY
2045 ** expression, do not allow aggregates in any of the other expressions.
2046 */
2047 assert( (p->selFlags & SF_Aggregate)==0 );
2048 pGroupBy = p->pGroupBy;
2049 if( pGroupBy || (sNC.ncFlags & NC_HasAgg)!=0 ){
2050 assert( NC_MinMaxAgg==SF_MinMaxAgg );
2051 assert( NC_OrderAgg==SF_OrderByReqd );
2052 p->selFlags |= SF_Aggregate | (sNC.ncFlags&(NC_MinMaxAgg|NC_OrderAgg));
2053 }else{
2054 sNC.ncFlags &= ~NC_AllowAgg;
2055 }
2056
2057 /* Add the output column list to the name-context before parsing the
2058 ** other expressions in the SELECT statement. This is so that
2059 ** expressions in the WHERE clause (etc.) can refer to expressions by
2060 ** aliases in the result set.
2061 **
2062 ** Minor point: If this is the case, then the expression will be
2063 ** re-evaluated for each reference to it.
2064 */
2065 assert( (sNC.ncFlags & (NC_UAggInfo|NC_UUpsert|NC_UBaseReg))==0 );
2066 sNC.uNC.pEList = p->pEList;
2067 sNC.ncFlags |= NC_UEList;
2068 if( p->pHaving ){
2069 if( (p->selFlags & SF_Aggregate)==0 ){
2070 sqlite3ErrorMsg(pParse, "HAVING clause on a non-aggregate query");
2071 return WRC_Abort;
2072 }
2073 if( sqlite3ResolveExprNames(&sNC, p->pHaving) ) return WRC_Abort;
2074 }
2075 sNC.ncFlags |= NC_Where;
2076 if( sqlite3ResolveExprNames(&sNC, p->pWhere) ) return WRC_Abort;
2077 sNC.ncFlags &= ~NC_Where;
2078
2079 /* Resolve names in table-valued-function arguments */
2080 for(i=0; i<p->pSrc->nSrc; i++){
2081 SrcItem *pItem = &p->pSrc->a[i];
2082 if( pItem->fg.isTabFunc
2083 && sqlite3ResolveExprListNames(&sNC, pItem->u1.pFuncArg)
2084 ){
2085 return WRC_Abort;
2086 }
2087 }
2088
2089#ifndef SQLITE_OMIT_WINDOWFUNC
2090 if( IN_RENAME_OBJECT ){
2091 Window *pWin;
2092 for(pWin=p->pWinDefn; pWin; pWin=pWin->pNextWin){
2093 if( sqlite3ResolveExprListNames(&sNC, pWin->pOrderBy)
2094 || sqlite3ResolveExprListNames(&sNC, pWin->pPartition)
2095 ){
2096 return WRC_Abort;
2097 }
2098 }
2099 }
2100#endif
2101
2102 sNC.ncFlags |= NC_AllowAgg|NC_AllowWin;
2103
2104 /* If this is a converted compound query, move the ORDER BY clause from
2105 ** the sub-query back to the parent query. At this point each term
2106 ** within the ORDER BY clause has been transformed to an integer value.
2107 ** These integers will be replaced by copies of the corresponding result
2108 ** set expressions by the call to resolveOrderGroupBy() below. */
2109 if( p->selFlags & SF_Converted ){
2110 Select *pSub;
2111 assert( p->pSrc->a[0].fg.isSubquery );
2112 pSub = p->pSrc->a[0].u4.pSubq->pSelect;
2113 assert( pSub!=0 );
2114 p->pOrderBy = pSub->pOrderBy;
2115 pSub->pOrderBy = 0;
2116 }
2117
2118 /* Process the ORDER BY clause for singleton SELECT statements.
2119 ** The ORDER BY clause for compounds SELECT statements is handled
2120 ** below, after all of the result-sets for all of the elements of
2121 ** the compound have been resolved.
2122 **
2123 ** If there is an ORDER BY clause on a term of a compound-select other
2124 ** than the right-most term, then that is a syntax error. But the error
2125 ** is not detected until much later, and so we need to go ahead and
2126 ** resolve those symbols on the incorrect ORDER BY for consistency.
2127 */
2128 if( p->pOrderBy!=0
2129 && isCompound<=nCompound /* Defer right-most ORDER BY of a compound */
2130 && resolveOrderGroupBy(&sNC, p, p->pOrderBy, "ORDER")
2131 ){
2132 return WRC_Abort;
2133 }
2134 if( db->mallocFailed ){
2135 return WRC_Abort;
2136 }
2137 sNC.ncFlags &= ~NC_AllowWin;
2138
2139 /* Resolve the GROUP BY clause. At the same time, make sure
2140 ** the GROUP BY clause does not contain aggregate functions.
2141 */
2142 if( pGroupBy ){
2143 struct ExprList_item *pItem;
2144
2145 if( resolveOrderGroupBy(&sNC, p, pGroupBy, "GROUP") || db->mallocFailed ){
2146 return WRC_Abort;
2147 }
2148 for(i=0, pItem=pGroupBy->a; i<pGroupBy->nExpr; i++, pItem++){
2149 if( ExprHasProperty(pItem->pExpr, EP_Agg) ){
2150 sqlite3ErrorMsg(pParse, "aggregate functions are not allowed in "
2151 "the GROUP BY clause");
2152 return WRC_Abort;
2153 }
2154 }
2155 }
2156
2157 /* If this is part of a compound SELECT, check that it has the right
2158 ** number of expressions in the select list. */
2159 if( p->pNext && p->pEList->nExpr!=p->pNext->pEList->nExpr ){
2160 sqlite3SelectWrongNumTermsError(pParse, p->pNext);
2161 return WRC_Abort;
2162 }
2163
2164 /* If the SELECT statement contains ON clauses that were moved into
2165 ** the WHERE clause, go through and verify that none of the terms
2166 ** in the ON clauses reference tables to the right of the ON clause. */
2167 if( (p->selFlags & SF_OnToWhere) ){
2168 sqlite3SelectCheckOnClauses(pParse, p);
2169 if( pParse->nErr ) return WRC_Abort;
2170 }
2171
2172 /* Advance to the next term of the compound
2173 */
2174 p = p->pPrior;
2175 nCompound++;
2176 }
2177
2178 /* Resolve the ORDER BY on a compound SELECT after all terms of
2179 ** the compound have been resolved.
2180 */
2181 if( isCompound && resolveCompoundOrderBy(pParse, pLeftmost) ){
2182 return WRC_Abort;
2183 }
2184
2185 return WRC_Prune;
2186}
2187
2188/*
2189** This routine walks an expression tree and resolves references to
2190** table columns and result-set columns. At the same time, do error
2191** checking on function usage and set a flag if any aggregate functions
2192** are seen.
2193**
2194** To resolve table columns references we look for nodes (or subtrees) of the
2195** form X.Y.Z or Y.Z or just Z where
2196**
2197** X: The name of a database. Ex: "main" or "temp" or
2198** the symbolic name assigned to an ATTACH-ed database.
2199**
2200** Y: The name of a table in a FROM clause. Or in a trigger
2201** one of the special names "old" or "new".
2202**
2203** Z: The name of a column in table Y.
2204**
2205** The node at the root of the subtree is modified as follows:
2206**
2207** Expr.op Changed to TK_COLUMN
2208** Expr.pTab Points to the Table object for X.Y
2209** Expr.iColumn The column index in X.Y. -1 for the rowid.
2210** Expr.iTable The VDBE cursor number for X.Y
2211**
2212**
2213** To resolve result-set references, look for expression nodes of the
2214** form Z (with no X and Y prefix) where the Z matches the right-hand
2215** size of an AS clause in the result-set of a SELECT. The Z expression
2216** is replaced by a copy of the left-hand side of the result-set expression.
2217** Table-name and function resolution occurs on the substituted expression
2218** tree. For example, in:
2219**
2220** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY x;
2221**
2222** The "x" term of the order by is replaced by "a+b" to render:
2223**
2224** SELECT a+b AS x, c+d AS y FROM t1 ORDER BY a+b;
2225**
2226** Function calls are checked to make sure that the function is
2227** defined and that the correct number of arguments are specified.
2228** If the function is an aggregate function, then the NC_HasAgg flag is
2229** set and the opcode is changed from TK_FUNCTION to TK_AGG_FUNCTION.
2230** If an expression contains aggregate functions then the EP_Agg
2231** property on the expression is set.
2232**
2233** An error message is left in pParse if anything is amiss. The number
2234** if errors is returned.
2235*/
2236int sqlite3ResolveExprNames(
2237 NameContext *pNC, /* Namespace to resolve expressions in. */
2238 Expr *pExpr /* The expression to be analyzed. */
2239){
2240 int savedHasAgg;
2241 Walker w;
2242
2243 if( pExpr==0 ) return SQLITE_OK;
2244 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2245 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2246 w.pParse = pNC->pParse;
2247 w.xExprCallback = resolveExprStep;
2248 w.xSelectCallback = (pNC->ncFlags & NC_NoSelect) ? 0 : resolveSelectStep;
2249 w.xSelectCallback2 = 0;
2250 w.u.pNC = pNC;
2251#if SQLITE_MAX_EXPR_DEPTH>0
2252 w.pParse->nHeight += pExpr->nHeight;
2253 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2254 return SQLITE_ERROR;
2255 }
2256#endif
2257 assert( pExpr!=0 );
2258 sqlite3WalkExprNN(&w, pExpr);
2259#if SQLITE_MAX_EXPR_DEPTH>0
2260 w.pParse->nHeight -= pExpr->nHeight;
2261#endif
2262 assert( EP_Agg==NC_HasAgg );
2263 assert( EP_Win==NC_HasWin );
2264 testcase( pNC->ncFlags & NC_HasAgg );
2265 testcase( pNC->ncFlags & NC_HasWin );
2266 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2267 pNC->ncFlags |= savedHasAgg;
2268 return pNC->nNcErr>0 || w.pParse->nErr>0;
2269}
2270
2271/*
2272** Resolve all names for all expression in an expression list. This is
2273** just like sqlite3ResolveExprNames() except that it works for an expression
2274** list rather than a single expression.
2275**
2276** The return value is SQLITE_OK (0) for success or SQLITE_ERROR (1) for a
2277** failure.
2278*/
2279int sqlite3ResolveExprListNames(
2280 NameContext *pNC, /* Namespace to resolve expressions in. */
2281 ExprList *pList /* The expression list to be analyzed. */
2282){
2283 int i;
2284 int savedHasAgg = 0;
2285 Walker w;
2286 if( pList==0 ) return SQLITE_OK;
2287 w.pParse = pNC->pParse;
2288 w.xExprCallback = resolveExprStep;
2289 w.xSelectCallback = resolveSelectStep;
2290 w.xSelectCallback2 = 0;
2291 w.u.pNC = pNC;
2292 savedHasAgg = pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2293 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2294 for(i=0; i<pList->nExpr; i++){
2295 Expr *pExpr = pList->a[i].pExpr;
2296 if( pExpr==0 ) continue;
2297#if SQLITE_MAX_EXPR_DEPTH>0
2298 w.pParse->nHeight += pExpr->nHeight;
2299 if( sqlite3ExprCheckHeight(w.pParse, w.pParse->nHeight) ){
2300 return SQLITE_ERROR;
2301 }
2302#endif
2303 sqlite3WalkExprNN(&w, pExpr);
2304#if SQLITE_MAX_EXPR_DEPTH>0
2305 w.pParse->nHeight -= pExpr->nHeight;
2306#endif
2307 assert( EP_Agg==NC_HasAgg );
2308 assert( EP_Win==NC_HasWin );
2309 testcase( pNC->ncFlags & NC_HasAgg );
2310 testcase( pNC->ncFlags & NC_HasWin );
2311 if( pNC->ncFlags & (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg) ){
2312 ExprSetProperty(pExpr, pNC->ncFlags & (NC_HasAgg|NC_HasWin) );
2313 savedHasAgg |= pNC->ncFlags &
2314 (NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2315 pNC->ncFlags &= ~(NC_HasAgg|NC_MinMaxAgg|NC_HasWin|NC_OrderAgg);
2316 }
2317 if( w.pParse->nErr>0 ) return SQLITE_ERROR;
2318 }
2319 pNC->ncFlags |= savedHasAgg;
2320 return SQLITE_OK;
2321}
2322
2323/*
2324** Resolve all names in all expressions of a SELECT and in all
2325** descendants of the SELECT, including compounds off of p->pPrior,
2326** subqueries in expressions, and subqueries used as FROM clause
2327** terms.
2328**
2329** See sqlite3ResolveExprNames() for a description of the kinds of
2330** transformations that occur.
2331**
2332** All SELECT statements should have been expanded using
2333** sqlite3SelectExpand() prior to invoking this routine.
2334*/
2335void sqlite3ResolveSelectNames(
2336 Parse *pParse, /* The parser context */
2337 Select *p, /* The SELECT statement being coded. */
2338 NameContext *pOuterNC /* Name context for parent SELECT statement */
2339){
2340 Walker w;
2341
2342 assert( p!=0 );
2343 w.xExprCallback = resolveExprStep;
2344 w.xSelectCallback = resolveSelectStep;
2345 w.xSelectCallback2 = 0;
2346 w.pParse = pParse;
2347 w.u.pNC = pOuterNC;
2348 sqlite3WalkSelect(&w, p);
2349}
2350
2351/*
2352** Resolve names in expressions that can only reference a single table
2353** or which cannot reference any tables at all. Examples:
2354**
2355** "type" flag
2356** ------------
2357** (1) CHECK constraints NC_IsCheck
2358** (2) WHERE clauses on partial indices NC_PartIdx
2359** (3) Expressions in indexes on expressions NC_IdxExpr
2360** (4) Expression arguments to VACUUM INTO. 0
2361** (5) GENERATED ALWAYS as expressions NC_GenCol
2362**
2363** In all cases except (4), the Expr.iTable value for Expr.op==TK_COLUMN
2364** nodes of the expression is set to -1 and the Expr.iColumn value is
2365** set to the column number. In case (4), TK_COLUMN nodes cause an error.
2366**
2367** Any errors cause an error message to be set in pParse.
2368*/
2369int sqlite3ResolveSelfReference(
2370 Parse *pParse, /* Parsing context */
2371 Table *pTab, /* The table being referenced, or NULL */
2372 int type, /* NC_IsCheck, NC_PartIdx, NC_IdxExpr, NC_GenCol, or 0 */
2373 Expr *pExpr, /* Expression to resolve. May be NULL. */
2374 ExprList *pList /* Expression list to resolve. May be NULL. */
2375){
2376 SrcList *pSrc; /* Fake SrcList for pParse->pNewTable */
2377 NameContext sNC; /* Name context for pParse->pNewTable */
2378 int rc;
2379 union {
2380 SrcList sSrc;
2381 u8 srcSpace[SZ_SRCLIST_1]; /* Memory space for the fake SrcList */
2382 } uSrc;
2383
2384 assert( type==0 || pTab!=0 );
2385 assert( type==NC_IsCheck || type==NC_PartIdx || type==NC_IdxExpr
2386 || type==NC_GenCol || pTab==0 );
2387 memset(&sNC, 0, sizeof(sNC));
2388 memset(&uSrc, 0, sizeof(uSrc));
2389 pSrc = &uSrc.sSrc;
2390 if( pTab ){
2391 pSrc->nSrc = 1;
2392 pSrc->a[0].zName = pTab->zName;
2393 pSrc->a[0].pSTab = pTab;
2394 pSrc->a[0].iCursor = -1;
2395 if( pTab->pSchema!=pParse->db->aDb[1].pSchema ){
2396 /* Cause EP_FromDDL to be set on TK_FUNCTION nodes of non-TEMP
2397 ** schema elements */
2398 type |= NC_FromDDL;
2399 }
2400 }
2401 sNC.pParse = pParse;
2402 sNC.pSrcList = pSrc;
2403 sNC.ncFlags = type | NC_IsDDL;
2404 if( (rc = sqlite3ResolveExprNames(&sNC, pExpr))!=SQLITE_OK ) return rc;
2405 if( pList ) rc = sqlite3ResolveExprListNames(&sNC, pList);
2406 return rc;
2407}