Snapshot of upstream SQLite 3.42.0
[sqlcipher.git] / src / select.c
blobf32db2c2a04c4a173a25a5e4351d8988136a49bc
1 /*
2 ** 2001 September 15
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 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle SELECT statements in SQLite.
15 #include "sqliteInt.h"
18 ** An instance of the following object is used to record information about
19 ** how to process the DISTINCT keyword, to simplify passing that information
20 ** into the selectInnerLoop() routine.
22 typedef struct DistinctCtx DistinctCtx;
23 struct DistinctCtx {
24 u8 isTnct; /* 0: Not distinct. 1: DISTICT 2: DISTINCT and ORDER BY */
25 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
26 int tabTnct; /* Ephemeral table used for DISTINCT processing */
27 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
31 ** An instance of the following object is used to record information about
32 ** the ORDER BY (or GROUP BY) clause of query is being coded.
34 ** The aDefer[] array is used by the sorter-references optimization. For
35 ** example, assuming there is no index that can be used for the ORDER BY,
36 ** for the query:
38 ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
40 ** it may be more efficient to add just the "a" values to the sorter, and
41 ** retrieve the associated "bigblob" values directly from table t1 as the
42 ** 10 smallest "a" values are extracted from the sorter.
44 ** When the sorter-reference optimization is used, there is one entry in the
45 ** aDefer[] array for each database table that may be read as values are
46 ** extracted from the sorter.
48 typedef struct SortCtx SortCtx;
49 struct SortCtx {
50 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
51 int nOBSat; /* Number of ORDER BY terms satisfied by indices */
52 int iECursor; /* Cursor number for the sorter */
53 int regReturn; /* Register holding block-output return address */
54 int labelBkOut; /* Start label for the block-output subroutine */
55 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
56 int labelDone; /* Jump here when done, ex: LIMIT reached */
57 int labelOBLopt; /* Jump here when sorter is full */
58 u8 sortFlags; /* Zero or more SORTFLAG_* bits */
59 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
60 u8 nDefer; /* Number of valid entries in aDefer[] */
61 struct DeferredCsr {
62 Table *pTab; /* Table definition */
63 int iCsr; /* Cursor number for table */
64 int nKey; /* Number of PK columns for table pTab (>=1) */
65 } aDefer[4];
66 #endif
67 struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
68 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
69 int addrPush; /* First instruction to push data into sorter */
70 int addrPushEnd; /* Last instruction that pushes data into sorter */
71 #endif
73 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
76 ** Delete all the content of a Select structure. Deallocate the structure
77 ** itself depending on the value of bFree
79 ** If bFree==1, call sqlite3DbFree() on the p object.
80 ** If bFree==0, Leave the first Select object unfreed
82 static void clearSelect(sqlite3 *db, Select *p, int bFree){
83 assert( db!=0 );
84 while( p ){
85 Select *pPrior = p->pPrior;
86 sqlite3ExprListDelete(db, p->pEList);
87 sqlite3SrcListDelete(db, p->pSrc);
88 sqlite3ExprDelete(db, p->pWhere);
89 sqlite3ExprListDelete(db, p->pGroupBy);
90 sqlite3ExprDelete(db, p->pHaving);
91 sqlite3ExprListDelete(db, p->pOrderBy);
92 sqlite3ExprDelete(db, p->pLimit);
93 if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
94 #ifndef SQLITE_OMIT_WINDOWFUNC
95 if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
96 sqlite3WindowListDelete(db, p->pWinDefn);
98 while( p->pWin ){
99 assert( p->pWin->ppThis==&p->pWin );
100 sqlite3WindowUnlinkFromSelect(p->pWin);
102 #endif
103 if( bFree ) sqlite3DbNNFreeNN(db, p);
104 p = pPrior;
105 bFree = 1;
110 ** Initialize a SelectDest structure.
112 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
113 pDest->eDest = (u8)eDest;
114 pDest->iSDParm = iParm;
115 pDest->iSDParm2 = 0;
116 pDest->zAffSdst = 0;
117 pDest->iSdst = 0;
118 pDest->nSdst = 0;
123 ** Allocate a new Select structure and return a pointer to that
124 ** structure.
126 Select *sqlite3SelectNew(
127 Parse *pParse, /* Parsing context */
128 ExprList *pEList, /* which columns to include in the result */
129 SrcList *pSrc, /* the FROM clause -- which tables to scan */
130 Expr *pWhere, /* the WHERE clause */
131 ExprList *pGroupBy, /* the GROUP BY clause */
132 Expr *pHaving, /* the HAVING clause */
133 ExprList *pOrderBy, /* the ORDER BY clause */
134 u32 selFlags, /* Flag parameters, such as SF_Distinct */
135 Expr *pLimit /* LIMIT value. NULL means not used */
137 Select *pNew, *pAllocated;
138 Select standin;
139 pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
140 if( pNew==0 ){
141 assert( pParse->db->mallocFailed );
142 pNew = &standin;
144 if( pEList==0 ){
145 pEList = sqlite3ExprListAppend(pParse, 0,
146 sqlite3Expr(pParse->db,TK_ASTERISK,0));
148 pNew->pEList = pEList;
149 pNew->op = TK_SELECT;
150 pNew->selFlags = selFlags;
151 pNew->iLimit = 0;
152 pNew->iOffset = 0;
153 pNew->selId = ++pParse->nSelect;
154 pNew->addrOpenEphm[0] = -1;
155 pNew->addrOpenEphm[1] = -1;
156 pNew->nSelectRow = 0;
157 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
158 pNew->pSrc = pSrc;
159 pNew->pWhere = pWhere;
160 pNew->pGroupBy = pGroupBy;
161 pNew->pHaving = pHaving;
162 pNew->pOrderBy = pOrderBy;
163 pNew->pPrior = 0;
164 pNew->pNext = 0;
165 pNew->pLimit = pLimit;
166 pNew->pWith = 0;
167 #ifndef SQLITE_OMIT_WINDOWFUNC
168 pNew->pWin = 0;
169 pNew->pWinDefn = 0;
170 #endif
171 if( pParse->db->mallocFailed ) {
172 clearSelect(pParse->db, pNew, pNew!=&standin);
173 pAllocated = 0;
174 }else{
175 assert( pNew->pSrc!=0 || pParse->nErr>0 );
177 return pAllocated;
182 ** Delete the given Select structure and all of its substructures.
184 void sqlite3SelectDelete(sqlite3 *db, Select *p){
185 if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
189 ** Return a pointer to the right-most SELECT statement in a compound.
191 static Select *findRightmost(Select *p){
192 while( p->pNext ) p = p->pNext;
193 return p;
197 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
198 ** type of join. Return an integer constant that expresses that type
199 ** in terms of the following bit values:
201 ** JT_INNER
202 ** JT_CROSS
203 ** JT_OUTER
204 ** JT_NATURAL
205 ** JT_LEFT
206 ** JT_RIGHT
208 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
210 ** If an illegal or unsupported join type is seen, then still return
211 ** a join type, but put an error in the pParse structure.
213 ** These are the valid join types:
216 ** pA pB pC Return Value
217 ** ------- ----- ----- ------------
218 ** CROSS - - JT_CROSS
219 ** INNER - - JT_INNER
220 ** LEFT - - JT_LEFT|JT_OUTER
221 ** LEFT OUTER - JT_LEFT|JT_OUTER
222 ** RIGHT - - JT_RIGHT|JT_OUTER
223 ** RIGHT OUTER - JT_RIGHT|JT_OUTER
224 ** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER
225 ** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER
226 ** NATURAL INNER - JT_NATURAL|JT_INNER
227 ** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER
228 ** NATURAL LEFT OUTER JT_NATURAL|JT_LEFT|JT_OUTER
229 ** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER
230 ** NATURAL RIGHT OUTER JT_NATURAL|JT_RIGHT|JT_OUTER
231 ** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT
232 ** NATURAL FULL OUTER JT_NATRUAL|JT_LEFT|JT_RIGHT
234 ** To preserve historical compatibly, SQLite also accepts a variety
235 ** of other non-standard and in many cases non-sensical join types.
236 ** This routine makes as much sense at it can from the nonsense join
237 ** type and returns a result. Examples of accepted nonsense join types
238 ** include but are not limited to:
240 ** INNER CROSS JOIN -> same as JOIN
241 ** NATURAL CROSS JOIN -> same as NATURAL JOIN
242 ** OUTER LEFT JOIN -> same as LEFT JOIN
243 ** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN
244 ** LEFT RIGHT JOIN -> same as FULL JOIN
245 ** RIGHT OUTER FULL JOIN -> same as FULL JOIN
246 ** CROSS CROSS CROSS JOIN -> same as JOIN
248 ** The only restrictions on the join type name are:
250 ** * "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT",
251 ** or "FULL".
253 ** * "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT,
254 ** or "FULL".
256 ** * If "OUTER" is present then there must also be one of
257 ** "LEFT", "RIGHT", or "FULL"
259 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
260 int jointype = 0;
261 Token *apAll[3];
262 Token *p;
263 /* 0123456789 123456789 123456789 123 */
264 static const char zKeyText[] = "naturaleftouterightfullinnercross";
265 static const struct {
266 u8 i; /* Beginning of keyword text in zKeyText[] */
267 u8 nChar; /* Length of the keyword in characters */
268 u8 code; /* Join type mask */
269 } aKeyword[] = {
270 /* (0) natural */ { 0, 7, JT_NATURAL },
271 /* (1) left */ { 6, 4, JT_LEFT|JT_OUTER },
272 /* (2) outer */ { 10, 5, JT_OUTER },
273 /* (3) right */ { 14, 5, JT_RIGHT|JT_OUTER },
274 /* (4) full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
275 /* (5) inner */ { 23, 5, JT_INNER },
276 /* (6) cross */ { 28, 5, JT_INNER|JT_CROSS },
278 int i, j;
279 apAll[0] = pA;
280 apAll[1] = pB;
281 apAll[2] = pC;
282 for(i=0; i<3 && apAll[i]; i++){
283 p = apAll[i];
284 for(j=0; j<ArraySize(aKeyword); j++){
285 if( p->n==aKeyword[j].nChar
286 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
287 jointype |= aKeyword[j].code;
288 break;
291 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
292 if( j>=ArraySize(aKeyword) ){
293 jointype |= JT_ERROR;
294 break;
298 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
299 (jointype & JT_ERROR)!=0 ||
300 (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER
302 const char *zSp1 = " ";
303 const char *zSp2 = " ";
304 if( pB==0 ){ zSp1++; }
305 if( pC==0 ){ zSp2++; }
306 sqlite3ErrorMsg(pParse, "unknown join type: "
307 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
308 jointype = JT_INNER;
310 return jointype;
314 ** Return the index of a column in a table. Return -1 if the column
315 ** is not contained in the table.
317 int sqlite3ColumnIndex(Table *pTab, const char *zCol){
318 int i;
319 u8 h = sqlite3StrIHash(zCol);
320 Column *pCol;
321 for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
322 if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
324 return -1;
328 ** Mark a subquery result column as having been used.
330 void sqlite3SrcItemColumnUsed(SrcItem *pItem, int iCol){
331 assert( pItem!=0 );
332 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
333 if( pItem->fg.isNestedFrom ){
334 ExprList *pResults;
335 assert( pItem->pSelect!=0 );
336 pResults = pItem->pSelect->pEList;
337 assert( pResults!=0 );
338 assert( iCol>=0 && iCol<pResults->nExpr );
339 pResults->a[iCol].fg.bUsed = 1;
344 ** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
345 ** table that has a column named zCol. The search is left-to-right.
346 ** The first match found is returned.
348 ** When found, set *piTab and *piCol to the table index and column index
349 ** of the matching column and return TRUE.
351 ** If not found, return FALSE.
353 static int tableAndColumnIndex(
354 SrcList *pSrc, /* Array of tables to search */
355 int iStart, /* First member of pSrc->a[] to check */
356 int iEnd, /* Last member of pSrc->a[] to check */
357 const char *zCol, /* Name of the column we are looking for */
358 int *piTab, /* Write index of pSrc->a[] here */
359 int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
360 int bIgnoreHidden /* Ignore hidden columns */
362 int i; /* For looping over tables in pSrc */
363 int iCol; /* Index of column matching zCol */
365 assert( iEnd<pSrc->nSrc );
366 assert( iStart>=0 );
367 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
369 for(i=iStart; i<=iEnd; i++){
370 iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
371 if( iCol>=0
372 && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
374 if( piTab ){
375 sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
376 *piTab = i;
377 *piCol = iCol;
379 return 1;
382 return 0;
386 ** Set the EP_OuterON property on all terms of the given expression.
387 ** And set the Expr.w.iJoin to iTable for every term in the
388 ** expression.
390 ** The EP_OuterON property is used on terms of an expression to tell
391 ** the OUTER JOIN processing logic that this term is part of the
392 ** join restriction specified in the ON or USING clause and not a part
393 ** of the more general WHERE clause. These terms are moved over to the
394 ** WHERE clause during join processing but we need to remember that they
395 ** originated in the ON or USING clause.
397 ** The Expr.w.iJoin tells the WHERE clause processing that the
398 ** expression depends on table w.iJoin even if that table is not
399 ** explicitly mentioned in the expression. That information is needed
400 ** for cases like this:
402 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
404 ** The where clause needs to defer the handling of the t1.x=5
405 ** term until after the t2 loop of the join. In that way, a
406 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
407 ** defer the handling of t1.x=5, it will be processed immediately
408 ** after the t1 loop and rows with t1.x!=5 will never appear in
409 ** the output, which is incorrect.
411 void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){
412 assert( joinFlag==EP_OuterON || joinFlag==EP_InnerON );
413 while( p ){
414 ExprSetProperty(p, joinFlag);
415 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
416 ExprSetVVAProperty(p, EP_NoReduce);
417 p->w.iJoin = iTable;
418 if( p->op==TK_FUNCTION ){
419 assert( ExprUseXList(p) );
420 if( p->x.pList ){
421 int i;
422 for(i=0; i<p->x.pList->nExpr; i++){
423 sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
427 sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
428 p = p->pRight;
432 /* Undo the work of sqlite3SetJoinExpr(). This is used when a LEFT JOIN
433 ** is simplified into an ordinary JOIN, and when an ON expression is
434 ** "pushed down" into the WHERE clause of a subquery.
436 ** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
437 ** an ordinary term that omits the EP_OuterON mark. Or if iTable<0, then
438 ** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
440 ** If nullable is true, that means that Expr p might evaluate to NULL even
441 ** if it is a reference to a NOT NULL column. This can happen, for example,
442 ** if the table that p references is on the left side of a RIGHT JOIN.
443 ** If nullable is true, then take care to not remove the EP_CanBeNull bit.
444 ** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
446 static void unsetJoinExpr(Expr *p, int iTable, int nullable){
447 while( p ){
448 if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
449 ExprClearProperty(p, EP_OuterON|EP_InnerON);
450 if( iTable>=0 ) ExprSetProperty(p, EP_InnerON);
452 if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
453 ExprClearProperty(p, EP_CanBeNull);
455 if( p->op==TK_FUNCTION ){
456 assert( ExprUseXList(p) );
457 if( p->x.pList ){
458 int i;
459 for(i=0; i<p->x.pList->nExpr; i++){
460 unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
464 unsetJoinExpr(p->pLeft, iTable, nullable);
465 p = p->pRight;
470 ** This routine processes the join information for a SELECT statement.
472 ** * A NATURAL join is converted into a USING join. After that, we
473 ** do not need to be concerned with NATURAL joins and we only have
474 ** think about USING joins.
476 ** * ON and USING clauses result in extra terms being added to the
477 ** WHERE clause to enforce the specified constraints. The extra
478 ** WHERE clause terms will be tagged with EP_OuterON or
479 ** EP_InnerON so that we know that they originated in ON/USING.
481 ** The terms of a FROM clause are contained in the Select.pSrc structure.
482 ** The left most table is the first entry in Select.pSrc. The right-most
483 ** table is the last entry. The join operator is held in the entry to
484 ** the right. Thus entry 1 contains the join operator for the join between
485 ** entries 0 and 1. Any ON or USING clauses associated with the join are
486 ** also attached to the right entry.
488 ** This routine returns the number of errors encountered.
490 static int sqlite3ProcessJoin(Parse *pParse, Select *p){
491 SrcList *pSrc; /* All tables in the FROM clause */
492 int i, j; /* Loop counters */
493 SrcItem *pLeft; /* Left table being joined */
494 SrcItem *pRight; /* Right table being joined */
496 pSrc = p->pSrc;
497 pLeft = &pSrc->a[0];
498 pRight = &pLeft[1];
499 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
500 Table *pRightTab = pRight->pTab;
501 u32 joinType;
503 if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
504 joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
506 /* If this is a NATURAL join, synthesize an approprate USING clause
507 ** to specify which columns should be joined.
509 if( pRight->fg.jointype & JT_NATURAL ){
510 IdList *pUsing = 0;
511 if( pRight->fg.isUsing || pRight->u3.pOn ){
512 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
513 "an ON or USING clause", 0);
514 return 1;
516 for(j=0; j<pRightTab->nCol; j++){
517 char *zName; /* Name of column in the right table */
519 if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
520 zName = pRightTab->aCol[j].zCnName;
521 if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){
522 pUsing = sqlite3IdListAppend(pParse, pUsing, 0);
523 if( pUsing ){
524 assert( pUsing->nId>0 );
525 assert( pUsing->a[pUsing->nId-1].zName==0 );
526 pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
530 if( pUsing ){
531 pRight->fg.isUsing = 1;
532 pRight->fg.isSynthUsing = 1;
533 pRight->u3.pUsing = pUsing;
535 if( pParse->nErr ) return 1;
538 /* Create extra terms on the WHERE clause for each column named
539 ** in the USING clause. Example: If the two tables to be joined are
540 ** A and B and the USING clause names X, Y, and Z, then add this
541 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
542 ** Report an error if any column mentioned in the USING clause is
543 ** not contained in both tables to be joined.
545 if( pRight->fg.isUsing ){
546 IdList *pList = pRight->u3.pUsing;
547 sqlite3 *db = pParse->db;
548 assert( pList!=0 );
549 for(j=0; j<pList->nId; j++){
550 char *zName; /* Name of the term in the USING clause */
551 int iLeft; /* Table on the left with matching column name */
552 int iLeftCol; /* Column number of matching column on the left */
553 int iRightCol; /* Column number of matching column on the right */
554 Expr *pE1; /* Reference to the column on the LEFT of the join */
555 Expr *pE2; /* Reference to the column on the RIGHT of the join */
556 Expr *pEq; /* Equality constraint. pE1 == pE2 */
558 zName = pList->a[j].zName;
559 iRightCol = sqlite3ColumnIndex(pRightTab, zName);
560 if( iRightCol<0
561 || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol,
562 pRight->fg.isSynthUsing)==0
564 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
565 "not present in both tables", zName);
566 return 1;
568 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
569 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
570 if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
571 /* This branch runs if the query contains one or more RIGHT or FULL
572 ** JOINs. If only a single table on the left side of this join
573 ** contains the zName column, then this branch is a no-op.
574 ** But if there are two or more tables on the left side
575 ** of the join, construct a coalesce() function that gathers all
576 ** such tables. Raise an error if more than one of those references
577 ** to zName is not also within a prior USING clause.
579 ** We really ought to raise an error if there are two or more
580 ** non-USING references to zName on the left of an INNER or LEFT
581 ** JOIN. But older versions of SQLite do not do that, so we avoid
582 ** adding a new error so as to not break legacy applications.
584 ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */
585 static const Token tkCoalesce = { "coalesce", 8 };
586 while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,
587 pRight->fg.isSynthUsing)!=0 ){
588 if( pSrc->a[iLeft].fg.isUsing==0
589 || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
591 sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()",
592 zName);
593 break;
595 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
596 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
597 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
599 if( pFuncArgs ){
600 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
601 pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);
604 pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);
605 sqlite3SrcItemColumnUsed(pRight, iRightCol);
606 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
607 assert( pE2!=0 || pEq==0 );
608 if( pEq ){
609 ExprSetProperty(pEq, joinType);
610 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
611 ExprSetVVAProperty(pEq, EP_NoReduce);
612 pEq->w.iJoin = pE2->iTable;
614 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
618 /* Add the ON clause to the end of the WHERE clause, connected by
619 ** an AND operator.
621 else if( pRight->u3.pOn ){
622 sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
623 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
624 pRight->u3.pOn = 0;
625 pRight->fg.isOn = 1;
628 return 0;
632 ** An instance of this object holds information (beyond pParse and pSelect)
633 ** needed to load the next result row that is to be added to the sorter.
635 typedef struct RowLoadInfo RowLoadInfo;
636 struct RowLoadInfo {
637 int regResult; /* Store results in array of registers here */
638 u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
639 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
640 ExprList *pExtra; /* Extra columns needed by sorter refs */
641 int regExtraResult; /* Where to load the extra columns */
642 #endif
646 ** This routine does the work of loading query data into an array of
647 ** registers so that it can be added to the sorter.
649 static void innerLoopLoadRow(
650 Parse *pParse, /* Statement under construction */
651 Select *pSelect, /* The query being coded */
652 RowLoadInfo *pInfo /* Info needed to complete the row load */
654 sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
655 0, pInfo->ecelFlags);
656 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
657 if( pInfo->pExtra ){
658 sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
659 sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
661 #endif
665 ** Code the OP_MakeRecord instruction that generates the entry to be
666 ** added into the sorter.
668 ** Return the register in which the result is stored.
670 static int makeSorterRecord(
671 Parse *pParse,
672 SortCtx *pSort,
673 Select *pSelect,
674 int regBase,
675 int nBase
677 int nOBSat = pSort->nOBSat;
678 Vdbe *v = pParse->pVdbe;
679 int regOut = ++pParse->nMem;
680 if( pSort->pDeferredRowLoad ){
681 innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
683 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
684 return regOut;
688 ** Generate code that will push the record in registers regData
689 ** through regData+nData-1 onto the sorter.
691 static void pushOntoSorter(
692 Parse *pParse, /* Parser context */
693 SortCtx *pSort, /* Information about the ORDER BY clause */
694 Select *pSelect, /* The whole SELECT statement */
695 int regData, /* First register holding data to be sorted */
696 int regOrigData, /* First register holding data before packing */
697 int nData, /* Number of elements in the regData data array */
698 int nPrefixReg /* No. of reg prior to regData available for use */
700 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
701 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
702 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
703 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
704 int regBase; /* Regs for sorter record */
705 int regRecord = 0; /* Assembled sorter record */
706 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
707 int op; /* Opcode to add sorter record to sorter */
708 int iLimit; /* LIMIT counter */
709 int iSkip = 0; /* End of the sorter insert loop */
711 assert( bSeq==0 || bSeq==1 );
713 /* Three cases:
714 ** (1) The data to be sorted has already been packed into a Record
715 ** by a prior OP_MakeRecord. In this case nData==1 and regData
716 ** will be completely unrelated to regOrigData.
717 ** (2) All output columns are included in the sort record. In that
718 ** case regData==regOrigData.
719 ** (3) Some output columns are omitted from the sort record due to
720 ** the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
721 ** SQLITE_ECEL_OMITREF optimization, or due to the
722 ** SortCtx.pDeferredRowLoad optimiation. In any of these cases
723 ** regOrigData is 0 to prevent this routine from trying to copy
724 ** values that might not yet exist.
726 assert( nData==1 || regData==regOrigData || regOrigData==0 );
728 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
729 pSort->addrPush = sqlite3VdbeCurrentAddr(v);
730 #endif
732 if( nPrefixReg ){
733 assert( nPrefixReg==nExpr+bSeq );
734 regBase = regData - nPrefixReg;
735 }else{
736 regBase = pParse->nMem + 1;
737 pParse->nMem += nBase;
739 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
740 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
741 pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
742 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
743 SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
744 if( bSeq ){
745 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
747 if( nPrefixReg==0 && nData>0 ){
748 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
750 if( nOBSat>0 ){
751 int regPrevKey; /* The first nOBSat columns of the previous row */
752 int addrFirst; /* Address of the OP_IfNot opcode */
753 int addrJmp; /* Address of the OP_Jump opcode */
754 VdbeOp *pOp; /* Opcode that opens the sorter */
755 int nKey; /* Number of sorting key columns, including OP_Sequence */
756 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
758 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
759 regPrevKey = pParse->nMem+1;
760 pParse->nMem += pSort->nOBSat;
761 nKey = nExpr - pSort->nOBSat + bSeq;
762 if( bSeq ){
763 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
764 }else{
765 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
767 VdbeCoverage(v);
768 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
769 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
770 if( pParse->db->mallocFailed ) return;
771 pOp->p2 = nKey + nData;
772 pKI = pOp->p4.pKeyInfo;
773 memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
774 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
775 testcase( pKI->nAllField > pKI->nKeyField+2 );
776 pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
777 pKI->nAllField-pKI->nKeyField-1);
778 pOp = 0; /* Ensure pOp not used after sqltie3VdbeAddOp3() */
779 addrJmp = sqlite3VdbeCurrentAddr(v);
780 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
781 pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
782 pSort->regReturn = ++pParse->nMem;
783 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
784 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
785 if( iLimit ){
786 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
787 VdbeCoverage(v);
789 sqlite3VdbeJumpHere(v, addrFirst);
790 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
791 sqlite3VdbeJumpHere(v, addrJmp);
793 if( iLimit ){
794 /* At this point the values for the new sorter entry are stored
795 ** in an array of registers. They need to be composed into a record
796 ** and inserted into the sorter if either (a) there are currently
797 ** less than LIMIT+OFFSET items or (b) the new record is smaller than
798 ** the largest record currently in the sorter. If (b) is true and there
799 ** are already LIMIT+OFFSET items in the sorter, delete the largest
800 ** entry before inserting the new one. This way there are never more
801 ** than LIMIT+OFFSET items in the sorter.
803 ** If the new record does not need to be inserted into the sorter,
804 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
805 ** value is not zero, then it is a label of where to jump. Otherwise,
806 ** just bypass the row insert logic. See the header comment on the
807 ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
809 int iCsr = pSort->iECursor;
810 sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
811 VdbeCoverage(v);
812 sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
813 iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
814 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
815 VdbeCoverage(v);
816 sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
818 if( regRecord==0 ){
819 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
821 if( pSort->sortFlags & SORTFLAG_UseSorter ){
822 op = OP_SorterInsert;
823 }else{
824 op = OP_IdxInsert;
826 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
827 regBase+nOBSat, nBase-nOBSat);
828 if( iSkip ){
829 sqlite3VdbeChangeP2(v, iSkip,
830 pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
832 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
833 pSort->addrPushEnd = sqlite3VdbeCurrentAddr(v)-1;
834 #endif
838 ** Add code to implement the OFFSET
840 static void codeOffset(
841 Vdbe *v, /* Generate code into this VM */
842 int iOffset, /* Register holding the offset counter */
843 int iContinue /* Jump here to skip the current record */
845 if( iOffset>0 ){
846 sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
847 VdbeComment((v, "OFFSET"));
852 ** Add code that will check to make sure the array of registers starting at
853 ** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
854 ** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
855 ** are available. Which is used depends on the value of parameter eTnctType,
856 ** as follows:
858 ** WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
859 ** Build an ephemeral table that contains all entries seen before and
860 ** skip entries which have been seen before.
862 ** Parameter iTab is the cursor number of an ephemeral table that must
863 ** be opened before the VM code generated by this routine is executed.
864 ** The ephemeral cursor table is queried for a record identical to the
865 ** record formed by the current array of registers. If one is found,
866 ** jump to VM address addrRepeat. Otherwise, insert a new record into
867 ** the ephemeral cursor and proceed.
869 ** The returned value in this case is a copy of parameter iTab.
871 ** WHERE_DISTINCT_ORDERED:
872 ** In this case rows are being delivered sorted order. The ephermal
873 ** table is not required. Instead, the current set of values
874 ** is compared against previous row. If they match, the new row
875 ** is not distinct and control jumps to VM address addrRepeat. Otherwise,
876 ** the VM program proceeds with processing the new row.
878 ** The returned value in this case is the register number of the first
879 ** in an array of registers used to store the previous result row so that
880 ** it can be compared to the next. The caller must ensure that this
881 ** register is initialized to NULL. (The fixDistinctOpenEph() routine
882 ** will take care of this initialization.)
884 ** WHERE_DISTINCT_UNIQUE:
885 ** In this case it has already been determined that the rows are distinct.
886 ** No special action is required. The return value is zero.
888 ** Parameter pEList is the list of expressions used to generated the
889 ** contents of each row. It is used by this routine to determine (a)
890 ** how many elements there are in the array of registers and (b) the
891 ** collation sequences that should be used for the comparisons if
892 ** eTnctType is WHERE_DISTINCT_ORDERED.
894 static int codeDistinct(
895 Parse *pParse, /* Parsing and code generating context */
896 int eTnctType, /* WHERE_DISTINCT_* value */
897 int iTab, /* A sorting index used to test for distinctness */
898 int addrRepeat, /* Jump to here if not distinct */
899 ExprList *pEList, /* Expression for each element */
900 int regElem /* First element */
902 int iRet = 0;
903 int nResultCol = pEList->nExpr;
904 Vdbe *v = pParse->pVdbe;
906 switch( eTnctType ){
907 case WHERE_DISTINCT_ORDERED: {
908 int i;
909 int iJump; /* Jump destination */
910 int regPrev; /* Previous row content */
912 /* Allocate space for the previous row */
913 iRet = regPrev = pParse->nMem+1;
914 pParse->nMem += nResultCol;
916 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
917 for(i=0; i<nResultCol; i++){
918 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
919 if( i<nResultCol-1 ){
920 sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
921 VdbeCoverage(v);
922 }else{
923 sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
924 VdbeCoverage(v);
926 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
927 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
929 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
930 sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
931 break;
934 case WHERE_DISTINCT_UNIQUE: {
935 /* nothing to do */
936 break;
939 default: {
940 int r1 = sqlite3GetTempReg(pParse);
941 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
942 VdbeCoverage(v);
943 sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
944 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
945 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
946 sqlite3ReleaseTempReg(pParse, r1);
947 iRet = iTab;
948 break;
952 return iRet;
956 ** This routine runs after codeDistinct(). It makes necessary
957 ** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
958 ** routine made use of. This processing must be done separately since
959 ** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
960 ** laid down.
962 ** WHERE_DISTINCT_NOOP:
963 ** WHERE_DISTINCT_UNORDERED:
965 ** No adjustments necessary. This function is a no-op.
967 ** WHERE_DISTINCT_UNIQUE:
969 ** The ephemeral table is not needed. So change the
970 ** OP_OpenEphemeral opcode into an OP_Noop.
972 ** WHERE_DISTINCT_ORDERED:
974 ** The ephemeral table is not needed. But we do need register
975 ** iVal to be initialized to NULL. So change the OP_OpenEphemeral
976 ** into an OP_Null on the iVal register.
978 static void fixDistinctOpenEph(
979 Parse *pParse, /* Parsing and code generating context */
980 int eTnctType, /* WHERE_DISTINCT_* value */
981 int iVal, /* Value returned by codeDistinct() */
982 int iOpenEphAddr /* Address of OP_OpenEphemeral instruction for iTab */
984 if( pParse->nErr==0
985 && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
987 Vdbe *v = pParse->pVdbe;
988 sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
989 if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
990 sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
992 if( eTnctType==WHERE_DISTINCT_ORDERED ){
993 /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
994 ** bit on the first register of the previous value. This will cause the
995 ** OP_Ne added in codeDistinct() to always fail on the first iteration of
996 ** the loop even if the first row is all NULLs. */
997 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
998 pOp->opcode = OP_Null;
999 pOp->p1 = 1;
1000 pOp->p2 = iVal;
1005 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1007 ** This function is called as part of inner-loop generation for a SELECT
1008 ** statement with an ORDER BY that is not optimized by an index. It
1009 ** determines the expressions, if any, that the sorter-reference
1010 ** optimization should be used for. The sorter-reference optimization
1011 ** is used for SELECT queries like:
1013 ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
1015 ** If the optimization is used for expression "bigblob", then instead of
1016 ** storing values read from that column in the sorter records, the PK of
1017 ** the row from table t1 is stored instead. Then, as records are extracted from
1018 ** the sorter to return to the user, the required value of bigblob is
1019 ** retrieved directly from table t1. If the values are very large, this
1020 ** can be more efficient than storing them directly in the sorter records.
1022 ** The ExprList_item.fg.bSorterRef flag is set for each expression in pEList
1023 ** for which the sorter-reference optimization should be enabled.
1024 ** Additionally, the pSort->aDefer[] array is populated with entries
1025 ** for all cursors required to evaluate all selected expressions. Finally.
1026 ** output variable (*ppExtra) is set to an expression list containing
1027 ** expressions for all extra PK values that should be stored in the
1028 ** sorter records.
1030 static void selectExprDefer(
1031 Parse *pParse, /* Leave any error here */
1032 SortCtx *pSort, /* Sorter context */
1033 ExprList *pEList, /* Expressions destined for sorter */
1034 ExprList **ppExtra /* Expressions to append to sorter record */
1036 int i;
1037 int nDefer = 0;
1038 ExprList *pExtra = 0;
1039 for(i=0; i<pEList->nExpr; i++){
1040 struct ExprList_item *pItem = &pEList->a[i];
1041 if( pItem->u.x.iOrderByCol==0 ){
1042 Expr *pExpr = pItem->pExpr;
1043 Table *pTab;
1044 if( pExpr->op==TK_COLUMN
1045 && pExpr->iColumn>=0
1046 && ALWAYS( ExprUseYTab(pExpr) )
1047 && (pTab = pExpr->y.pTab)!=0
1048 && IsOrdinaryTable(pTab)
1049 && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
1051 int j;
1052 for(j=0; j<nDefer; j++){
1053 if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
1055 if( j==nDefer ){
1056 if( nDefer==ArraySize(pSort->aDefer) ){
1057 continue;
1058 }else{
1059 int nKey = 1;
1060 int k;
1061 Index *pPk = 0;
1062 if( !HasRowid(pTab) ){
1063 pPk = sqlite3PrimaryKeyIndex(pTab);
1064 nKey = pPk->nKeyCol;
1066 for(k=0; k<nKey; k++){
1067 Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
1068 if( pNew ){
1069 pNew->iTable = pExpr->iTable;
1070 assert( ExprUseYTab(pNew) );
1071 pNew->y.pTab = pExpr->y.pTab;
1072 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
1073 pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
1076 pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
1077 pSort->aDefer[nDefer].iCsr = pExpr->iTable;
1078 pSort->aDefer[nDefer].nKey = nKey;
1079 nDefer++;
1082 pItem->fg.bSorterRef = 1;
1086 pSort->nDefer = (u8)nDefer;
1087 *ppExtra = pExtra;
1089 #endif
1092 ** This routine generates the code for the inside of the inner loop
1093 ** of a SELECT.
1095 ** If srcTab is negative, then the p->pEList expressions
1096 ** are evaluated in order to get the data for this row. If srcTab is
1097 ** zero or more, then data is pulled from srcTab and p->pEList is used only
1098 ** to get the number of columns and the collation sequence for each column.
1100 static void selectInnerLoop(
1101 Parse *pParse, /* The parser context */
1102 Select *p, /* The complete select statement being coded */
1103 int srcTab, /* Pull data from this table if non-negative */
1104 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
1105 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
1106 SelectDest *pDest, /* How to dispose of the results */
1107 int iContinue, /* Jump here to continue with next row */
1108 int iBreak /* Jump here to break out of the inner loop */
1110 Vdbe *v = pParse->pVdbe;
1111 int i;
1112 int hasDistinct; /* True if the DISTINCT keyword is present */
1113 int eDest = pDest->eDest; /* How to dispose of results */
1114 int iParm = pDest->iSDParm; /* First argument to disposal method */
1115 int nResultCol; /* Number of result columns */
1116 int nPrefixReg = 0; /* Number of extra registers before regResult */
1117 RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
1119 /* Usually, regResult is the first cell in an array of memory cells
1120 ** containing the current result row. In this case regOrig is set to the
1121 ** same value. However, if the results are being sent to the sorter, the
1122 ** values for any expressions that are also part of the sort-key are omitted
1123 ** from this array. In this case regOrig is set to zero. */
1124 int regResult; /* Start of memory holding current results */
1125 int regOrig; /* Start of memory holding full result (or 0) */
1127 assert( v );
1128 assert( p->pEList!=0 );
1129 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
1130 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
1131 if( pSort==0 && !hasDistinct ){
1132 assert( iContinue!=0 );
1133 codeOffset(v, p->iOffset, iContinue);
1136 /* Pull the requested columns.
1138 nResultCol = p->pEList->nExpr;
1140 if( pDest->iSdst==0 ){
1141 if( pSort ){
1142 nPrefixReg = pSort->pOrderBy->nExpr;
1143 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
1144 pParse->nMem += nPrefixReg;
1146 pDest->iSdst = pParse->nMem+1;
1147 pParse->nMem += nResultCol;
1148 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
1149 /* This is an error condition that can result, for example, when a SELECT
1150 ** on the right-hand side of an INSERT contains more result columns than
1151 ** there are columns in the table on the left. The error will be caught
1152 ** and reported later. But we need to make sure enough memory is allocated
1153 ** to avoid other spurious errors in the meantime. */
1154 pParse->nMem += nResultCol;
1156 pDest->nSdst = nResultCol;
1157 regOrig = regResult = pDest->iSdst;
1158 if( srcTab>=0 ){
1159 for(i=0; i<nResultCol; i++){
1160 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
1161 VdbeComment((v, "%s", p->pEList->a[i].zEName));
1163 }else if( eDest!=SRT_Exists ){
1164 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1165 ExprList *pExtra = 0;
1166 #endif
1167 /* If the destination is an EXISTS(...) expression, the actual
1168 ** values returned by the SELECT are not required.
1170 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
1171 ExprList *pEList;
1172 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
1173 ecelFlags = SQLITE_ECEL_DUP;
1174 }else{
1175 ecelFlags = 0;
1177 if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
1178 /* For each expression in p->pEList that is a copy of an expression in
1179 ** the ORDER BY clause (pSort->pOrderBy), set the associated
1180 ** iOrderByCol value to one more than the index of the ORDER BY
1181 ** expression within the sort-key that pushOntoSorter() will generate.
1182 ** This allows the p->pEList field to be omitted from the sorted record,
1183 ** saving space and CPU cycles. */
1184 ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
1186 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
1187 int j;
1188 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
1189 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
1192 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1193 selectExprDefer(pParse, pSort, p->pEList, &pExtra);
1194 if( pExtra && pParse->db->mallocFailed==0 ){
1195 /* If there are any extra PK columns to add to the sorter records,
1196 ** allocate extra memory cells and adjust the OpenEphemeral
1197 ** instruction to account for the larger records. This is only
1198 ** required if there are one or more WITHOUT ROWID tables with
1199 ** composite primary keys in the SortCtx.aDefer[] array. */
1200 VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
1201 pOp->p2 += (pExtra->nExpr - pSort->nDefer);
1202 pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
1203 pParse->nMem += pExtra->nExpr;
1205 #endif
1207 /* Adjust nResultCol to account for columns that are omitted
1208 ** from the sorter by the optimizations in this branch */
1209 pEList = p->pEList;
1210 for(i=0; i<pEList->nExpr; i++){
1211 if( pEList->a[i].u.x.iOrderByCol>0
1212 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1213 || pEList->a[i].fg.bSorterRef
1214 #endif
1216 nResultCol--;
1217 regOrig = 0;
1221 testcase( regOrig );
1222 testcase( eDest==SRT_Set );
1223 testcase( eDest==SRT_Mem );
1224 testcase( eDest==SRT_Coroutine );
1225 testcase( eDest==SRT_Output );
1226 assert( eDest==SRT_Set || eDest==SRT_Mem
1227 || eDest==SRT_Coroutine || eDest==SRT_Output
1228 || eDest==SRT_Upfrom );
1230 sRowLoadInfo.regResult = regResult;
1231 sRowLoadInfo.ecelFlags = ecelFlags;
1232 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1233 sRowLoadInfo.pExtra = pExtra;
1234 sRowLoadInfo.regExtraResult = regResult + nResultCol;
1235 if( pExtra ) nResultCol += pExtra->nExpr;
1236 #endif
1237 if( p->iLimit
1238 && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
1239 && nPrefixReg>0
1241 assert( pSort!=0 );
1242 assert( hasDistinct==0 );
1243 pSort->pDeferredRowLoad = &sRowLoadInfo;
1244 regOrig = 0;
1245 }else{
1246 innerLoopLoadRow(pParse, p, &sRowLoadInfo);
1250 /* If the DISTINCT keyword was present on the SELECT statement
1251 ** and this row has been seen before, then do not make this row
1252 ** part of the result.
1254 if( hasDistinct ){
1255 int eType = pDistinct->eTnctType;
1256 int iTab = pDistinct->tabTnct;
1257 assert( nResultCol==p->pEList->nExpr );
1258 iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
1259 fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
1260 if( pSort==0 ){
1261 codeOffset(v, p->iOffset, iContinue);
1265 switch( eDest ){
1266 /* In this mode, write each query result to the key of the temporary
1267 ** table iParm.
1269 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1270 case SRT_Union: {
1271 int r1;
1272 r1 = sqlite3GetTempReg(pParse);
1273 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
1274 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1275 sqlite3ReleaseTempReg(pParse, r1);
1276 break;
1279 /* Construct a record from the query result, but instead of
1280 ** saving that record, use it as a key to delete elements from
1281 ** the temporary table iParm.
1283 case SRT_Except: {
1284 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
1285 break;
1287 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1289 /* Store the result as data using a unique key.
1291 case SRT_Fifo:
1292 case SRT_DistFifo:
1293 case SRT_Table:
1294 case SRT_EphemTab: {
1295 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
1296 testcase( eDest==SRT_Table );
1297 testcase( eDest==SRT_EphemTab );
1298 testcase( eDest==SRT_Fifo );
1299 testcase( eDest==SRT_DistFifo );
1300 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
1301 #ifndef SQLITE_OMIT_CTE
1302 if( eDest==SRT_DistFifo ){
1303 /* If the destination is DistFifo, then cursor (iParm+1) is open
1304 ** on an ephemeral index. If the current row is already present
1305 ** in the index, do not write it to the output. If not, add the
1306 ** current row to the index and proceed with writing it to the
1307 ** output table as well. */
1308 int addr = sqlite3VdbeCurrentAddr(v) + 4;
1309 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
1310 VdbeCoverage(v);
1311 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
1312 assert( pSort==0 );
1314 #endif
1315 if( pSort ){
1316 assert( regResult==regOrig );
1317 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
1318 }else{
1319 int r2 = sqlite3GetTempReg(pParse);
1320 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
1321 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
1322 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1323 sqlite3ReleaseTempReg(pParse, r2);
1325 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
1326 break;
1329 case SRT_Upfrom: {
1330 if( pSort ){
1331 pushOntoSorter(
1332 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1333 }else{
1334 int i2 = pDest->iSDParm2;
1335 int r1 = sqlite3GetTempReg(pParse);
1337 /* If the UPDATE FROM join is an aggregate that matches no rows, it
1338 ** might still be trying to return one row, because that is what
1339 ** aggregates do. Don't record that empty row in the output table. */
1340 sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
1342 sqlite3VdbeAddOp3(v, OP_MakeRecord,
1343 regResult+(i2<0), nResultCol-(i2<0), r1);
1344 if( i2<0 ){
1345 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
1346 }else{
1347 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
1350 break;
1353 #ifndef SQLITE_OMIT_SUBQUERY
1354 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1355 ** then there should be a single item on the stack. Write this
1356 ** item into the set table with bogus data.
1358 case SRT_Set: {
1359 if( pSort ){
1360 /* At first glance you would think we could optimize out the
1361 ** ORDER BY in this case since the order of entries in the set
1362 ** does not matter. But there might be a LIMIT clause, in which
1363 ** case the order does matter */
1364 pushOntoSorter(
1365 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1366 }else{
1367 int r1 = sqlite3GetTempReg(pParse);
1368 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
1369 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
1370 r1, pDest->zAffSdst, nResultCol);
1371 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1372 sqlite3ReleaseTempReg(pParse, r1);
1374 break;
1378 /* If any row exist in the result set, record that fact and abort.
1380 case SRT_Exists: {
1381 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
1382 /* The LIMIT clause will terminate the loop for us */
1383 break;
1386 /* If this is a scalar select that is part of an expression, then
1387 ** store the results in the appropriate memory cell or array of
1388 ** memory cells and break out of the scan loop.
1390 case SRT_Mem: {
1391 if( pSort ){
1392 assert( nResultCol<=pDest->nSdst );
1393 pushOntoSorter(
1394 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1395 }else{
1396 assert( nResultCol==pDest->nSdst );
1397 assert( regResult==iParm );
1398 /* The LIMIT clause will jump out of the loop for us */
1400 break;
1402 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1404 case SRT_Coroutine: /* Send data to a co-routine */
1405 case SRT_Output: { /* Return the results */
1406 testcase( eDest==SRT_Coroutine );
1407 testcase( eDest==SRT_Output );
1408 if( pSort ){
1409 pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
1410 nPrefixReg);
1411 }else if( eDest==SRT_Coroutine ){
1412 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1413 }else{
1414 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
1416 break;
1419 #ifndef SQLITE_OMIT_CTE
1420 /* Write the results into a priority queue that is order according to
1421 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
1422 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
1423 ** pSO->nExpr columns, then make sure all keys are unique by adding a
1424 ** final OP_Sequence column. The last column is the record as a blob.
1426 case SRT_DistQueue:
1427 case SRT_Queue: {
1428 int nKey;
1429 int r1, r2, r3;
1430 int addrTest = 0;
1431 ExprList *pSO;
1432 pSO = pDest->pOrderBy;
1433 assert( pSO );
1434 nKey = pSO->nExpr;
1435 r1 = sqlite3GetTempReg(pParse);
1436 r2 = sqlite3GetTempRange(pParse, nKey+2);
1437 r3 = r2+nKey+1;
1438 if( eDest==SRT_DistQueue ){
1439 /* If the destination is DistQueue, then cursor (iParm+1) is open
1440 ** on a second ephemeral index that holds all values every previously
1441 ** added to the queue. */
1442 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
1443 regResult, nResultCol);
1444 VdbeCoverage(v);
1446 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
1447 if( eDest==SRT_DistQueue ){
1448 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
1449 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1451 for(i=0; i<nKey; i++){
1452 sqlite3VdbeAddOp2(v, OP_SCopy,
1453 regResult + pSO->a[i].u.x.iOrderByCol - 1,
1454 r2+i);
1456 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
1457 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
1458 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
1459 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1460 sqlite3ReleaseTempReg(pParse, r1);
1461 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1462 break;
1464 #endif /* SQLITE_OMIT_CTE */
1468 #if !defined(SQLITE_OMIT_TRIGGER)
1469 /* Discard the results. This is used for SELECT statements inside
1470 ** the body of a TRIGGER. The purpose of such selects is to call
1471 ** user-defined functions that have side effects. We do not care
1472 ** about the actual results of the select.
1474 default: {
1475 assert( eDest==SRT_Discard );
1476 break;
1478 #endif
1481 /* Jump to the end of the loop if the LIMIT is reached. Except, if
1482 ** there is a sorter, in which case the sorter has already limited
1483 ** the output for us.
1485 if( pSort==0 && p->iLimit ){
1486 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1491 ** Allocate a KeyInfo object sufficient for an index of N key columns and
1492 ** X extra columns.
1494 KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1495 int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
1496 KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
1497 if( p ){
1498 p->aSortFlags = (u8*)&p->aColl[N+X];
1499 p->nKeyField = (u16)N;
1500 p->nAllField = (u16)(N+X);
1501 p->enc = ENC(db);
1502 p->db = db;
1503 p->nRef = 1;
1504 memset(&p[1], 0, nExtra);
1505 }else{
1506 return (KeyInfo*)sqlite3OomFault(db);
1508 return p;
1512 ** Deallocate a KeyInfo object
1514 void sqlite3KeyInfoUnref(KeyInfo *p){
1515 if( p ){
1516 assert( p->db!=0 );
1517 assert( p->nRef>0 );
1518 p->nRef--;
1519 if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
1524 ** Make a new pointer to a KeyInfo object
1526 KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
1527 if( p ){
1528 assert( p->nRef>0 );
1529 p->nRef++;
1531 return p;
1534 #ifdef SQLITE_DEBUG
1536 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
1537 ** can only be changed if this is just a single reference to the object.
1539 ** This routine is used only inside of assert() statements.
1541 int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
1542 #endif /* SQLITE_DEBUG */
1545 ** Given an expression list, generate a KeyInfo structure that records
1546 ** the collating sequence for each expression in that expression list.
1548 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
1549 ** KeyInfo structure is appropriate for initializing a virtual index to
1550 ** implement that clause. If the ExprList is the result set of a SELECT
1551 ** then the KeyInfo structure is appropriate for initializing a virtual
1552 ** index to implement a DISTINCT test.
1554 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
1555 ** function is responsible for seeing that this structure is eventually
1556 ** freed.
1558 KeyInfo *sqlite3KeyInfoFromExprList(
1559 Parse *pParse, /* Parsing context */
1560 ExprList *pList, /* Form the KeyInfo object from this ExprList */
1561 int iStart, /* Begin with this column of pList */
1562 int nExtra /* Add this many extra columns to the end */
1564 int nExpr;
1565 KeyInfo *pInfo;
1566 struct ExprList_item *pItem;
1567 sqlite3 *db = pParse->db;
1568 int i;
1570 nExpr = pList->nExpr;
1571 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1572 if( pInfo ){
1573 assert( sqlite3KeyInfoIsWriteable(pInfo) );
1574 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1575 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
1576 pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
1579 return pInfo;
1583 ** Name of the connection operator, used for error messages.
1585 const char *sqlite3SelectOpName(int id){
1586 char *z;
1587 switch( id ){
1588 case TK_ALL: z = "UNION ALL"; break;
1589 case TK_INTERSECT: z = "INTERSECT"; break;
1590 case TK_EXCEPT: z = "EXCEPT"; break;
1591 default: z = "UNION"; break;
1593 return z;
1596 #ifndef SQLITE_OMIT_EXPLAIN
1598 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1599 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1600 ** where the caption is of the form:
1602 ** "USE TEMP B-TREE FOR xxx"
1604 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
1605 ** is determined by the zUsage argument.
1607 static void explainTempTable(Parse *pParse, const char *zUsage){
1608 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
1612 ** Assign expression b to lvalue a. A second, no-op, version of this macro
1613 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1614 ** in sqlite3Select() to assign values to structure member variables that
1615 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1616 ** code with #ifndef directives.
1618 # define explainSetInteger(a, b) a = b
1620 #else
1621 /* No-op versions of the explainXXX() functions and macros. */
1622 # define explainTempTable(y,z)
1623 # define explainSetInteger(y,z)
1624 #endif
1628 ** If the inner loop was generated using a non-null pOrderBy argument,
1629 ** then the results were placed in a sorter. After the loop is terminated
1630 ** we need to run the sorter and output the results. The following
1631 ** routine generates the code needed to do that.
1633 static void generateSortTail(
1634 Parse *pParse, /* Parsing context */
1635 Select *p, /* The SELECT statement */
1636 SortCtx *pSort, /* Information on the ORDER BY clause */
1637 int nColumn, /* Number of columns of data */
1638 SelectDest *pDest /* Write the sorted results here */
1640 Vdbe *v = pParse->pVdbe; /* The prepared statement */
1641 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
1642 int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
1643 int addr; /* Top of output loop. Jump for Next. */
1644 int addrOnce = 0;
1645 int iTab;
1646 ExprList *pOrderBy = pSort->pOrderBy;
1647 int eDest = pDest->eDest;
1648 int iParm = pDest->iSDParm;
1649 int regRow;
1650 int regRowid;
1651 int iCol;
1652 int nKey; /* Number of key columns in sorter record */
1653 int iSortTab; /* Sorter cursor to read from */
1654 int i;
1655 int bSeq; /* True if sorter record includes seq. no. */
1656 int nRefKey = 0;
1657 struct ExprList_item *aOutEx = p->pEList->a;
1658 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1659 int addrExplain; /* Address of OP_Explain instruction */
1660 #endif
1662 ExplainQueryPlan2(addrExplain, (pParse, 0,
1663 "USE TEMP B-TREE FOR %sORDER BY", pSort->nOBSat>0?"RIGHT PART OF ":"")
1665 sqlite3VdbeScanStatusRange(v, addrExplain,pSort->addrPush,pSort->addrPushEnd);
1666 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, pSort->addrPush);
1669 assert( addrBreak<0 );
1670 if( pSort->labelBkOut ){
1671 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1672 sqlite3VdbeGoto(v, addrBreak);
1673 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1676 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1677 /* Open any cursors needed for sorter-reference expressions */
1678 for(i=0; i<pSort->nDefer; i++){
1679 Table *pTab = pSort->aDefer[i].pTab;
1680 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1681 sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
1682 nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
1684 #endif
1686 iTab = pSort->iECursor;
1687 if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
1688 if( eDest==SRT_Mem && p->iOffset ){
1689 sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
1691 regRowid = 0;
1692 regRow = pDest->iSdst;
1693 }else{
1694 regRowid = sqlite3GetTempReg(pParse);
1695 if( eDest==SRT_EphemTab || eDest==SRT_Table ){
1696 regRow = sqlite3GetTempReg(pParse);
1697 nColumn = 0;
1698 }else{
1699 regRow = sqlite3GetTempRange(pParse, nColumn);
1702 nKey = pOrderBy->nExpr - pSort->nOBSat;
1703 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1704 int regSortOut = ++pParse->nMem;
1705 iSortTab = pParse->nTab++;
1706 if( pSort->labelBkOut ){
1707 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1709 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
1710 nKey+1+nColumn+nRefKey);
1711 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1712 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1713 VdbeCoverage(v);
1714 assert( p->iLimit==0 && p->iOffset==0 );
1715 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
1716 bSeq = 0;
1717 }else{
1718 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1719 codeOffset(v, p->iOffset, addrContinue);
1720 iSortTab = iTab;
1721 bSeq = 1;
1722 if( p->iOffset>0 ){
1723 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1726 for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
1727 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1728 if( aOutEx[i].fg.bSorterRef ) continue;
1729 #endif
1730 if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
1732 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1733 if( pSort->nDefer ){
1734 int iKey = iCol+1;
1735 int regKey = sqlite3GetTempRange(pParse, nRefKey);
1737 for(i=0; i<pSort->nDefer; i++){
1738 int iCsr = pSort->aDefer[i].iCsr;
1739 Table *pTab = pSort->aDefer[i].pTab;
1740 int nKey = pSort->aDefer[i].nKey;
1742 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1743 if( HasRowid(pTab) ){
1744 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
1745 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
1746 sqlite3VdbeCurrentAddr(v)+1, regKey);
1747 }else{
1748 int k;
1749 int iJmp;
1750 assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
1751 for(k=0; k<nKey; k++){
1752 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
1754 iJmp = sqlite3VdbeCurrentAddr(v);
1755 sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
1756 sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
1757 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1760 sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
1762 #endif
1763 for(i=nColumn-1; i>=0; i--){
1764 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1765 if( aOutEx[i].fg.bSorterRef ){
1766 sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
1767 }else
1768 #endif
1770 int iRead;
1771 if( aOutEx[i].u.x.iOrderByCol ){
1772 iRead = aOutEx[i].u.x.iOrderByCol-1;
1773 }else{
1774 iRead = iCol--;
1776 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
1777 VdbeComment((v, "%s", aOutEx[i].zEName));
1780 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
1781 switch( eDest ){
1782 case SRT_Table:
1783 case SRT_EphemTab: {
1784 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
1785 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1786 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1787 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1788 break;
1790 #ifndef SQLITE_OMIT_SUBQUERY
1791 case SRT_Set: {
1792 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
1793 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
1794 pDest->zAffSdst, nColumn);
1795 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
1796 break;
1798 case SRT_Mem: {
1799 /* The LIMIT clause will terminate the loop for us */
1800 break;
1802 #endif
1803 case SRT_Upfrom: {
1804 int i2 = pDest->iSDParm2;
1805 int r1 = sqlite3GetTempReg(pParse);
1806 sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
1807 if( i2<0 ){
1808 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
1809 }else{
1810 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
1812 break;
1814 default: {
1815 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
1816 testcase( eDest==SRT_Output );
1817 testcase( eDest==SRT_Coroutine );
1818 if( eDest==SRT_Output ){
1819 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1820 }else{
1821 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1823 break;
1826 if( regRowid ){
1827 if( eDest==SRT_Set ){
1828 sqlite3ReleaseTempRange(pParse, regRow, nColumn);
1829 }else{
1830 sqlite3ReleaseTempReg(pParse, regRow);
1832 sqlite3ReleaseTempReg(pParse, regRowid);
1834 /* The bottom of the loop
1836 sqlite3VdbeResolveLabel(v, addrContinue);
1837 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1838 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1839 }else{
1840 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1842 sqlite3VdbeScanStatusRange(v, addrExplain, sqlite3VdbeCurrentAddr(v)-1, -1);
1843 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1844 sqlite3VdbeResolveLabel(v, addrBreak);
1848 ** Return a pointer to a string containing the 'declaration type' of the
1849 ** expression pExpr. The string may be treated as static by the caller.
1851 ** The declaration type is the exact datatype definition extracted from the
1852 ** original CREATE TABLE statement if the expression is a column. The
1853 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1854 ** is considered a column can be complex in the presence of subqueries. The
1855 ** result-set expression in all of the following SELECT statements is
1856 ** considered a column by this function.
1858 ** SELECT col FROM tbl;
1859 ** SELECT (SELECT col FROM tbl;
1860 ** SELECT (SELECT col FROM tbl);
1861 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
1863 ** The declaration type for any expression other than a column is NULL.
1865 ** This routine has either 3 or 6 parameters depending on whether or not
1866 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1868 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1869 # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
1870 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1871 # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
1872 #endif
1873 static const char *columnTypeImpl(
1874 NameContext *pNC,
1875 #ifndef SQLITE_ENABLE_COLUMN_METADATA
1876 Expr *pExpr
1877 #else
1878 Expr *pExpr,
1879 const char **pzOrigDb,
1880 const char **pzOrigTab,
1881 const char **pzOrigCol
1882 #endif
1884 char const *zType = 0;
1885 int j;
1886 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1887 char const *zOrigDb = 0;
1888 char const *zOrigTab = 0;
1889 char const *zOrigCol = 0;
1890 #endif
1892 assert( pExpr!=0 );
1893 assert( pNC->pSrcList!=0 );
1894 switch( pExpr->op ){
1895 case TK_COLUMN: {
1896 /* The expression is a column. Locate the table the column is being
1897 ** extracted from in NameContext.pSrcList. This table may be real
1898 ** database table or a subquery.
1900 Table *pTab = 0; /* Table structure column is extracted from */
1901 Select *pS = 0; /* Select the column is extracted from */
1902 int iCol = pExpr->iColumn; /* Index of column in pTab */
1903 while( pNC && !pTab ){
1904 SrcList *pTabList = pNC->pSrcList;
1905 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1906 if( j<pTabList->nSrc ){
1907 pTab = pTabList->a[j].pTab;
1908 pS = pTabList->a[j].pSelect;
1909 }else{
1910 pNC = pNC->pNext;
1914 if( pTab==0 ){
1915 /* At one time, code such as "SELECT new.x" within a trigger would
1916 ** cause this condition to run. Since then, we have restructured how
1917 ** trigger code is generated and so this condition is no longer
1918 ** possible. However, it can still be true for statements like
1919 ** the following:
1921 ** CREATE TABLE t1(col INTEGER);
1922 ** SELECT (SELECT t1.col) FROM FROM t1;
1924 ** when columnType() is called on the expression "t1.col" in the
1925 ** sub-select. In this case, set the column type to NULL, even
1926 ** though it should really be "INTEGER".
1928 ** This is not a problem, as the column type of "t1.col" is never
1929 ** used. When columnType() is called on the expression
1930 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
1931 ** branch below. */
1932 break;
1935 assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
1936 if( pS ){
1937 /* The "table" is actually a sub-select or a view in the FROM clause
1938 ** of the SELECT statement. Return the declaration type and origin
1939 ** data for the result-set column of the sub-select.
1941 if( iCol<pS->pEList->nExpr
1942 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1943 && iCol>=0
1944 #else
1945 && ALWAYS(iCol>=0)
1946 #endif
1948 /* If iCol is less than zero, then the expression requests the
1949 ** rowid of the sub-select or view. This expression is legal (see
1950 ** test case misc2.2.2) - it always evaluates to NULL.
1952 NameContext sNC;
1953 Expr *p = pS->pEList->a[iCol].pExpr;
1954 sNC.pSrcList = pS->pSrc;
1955 sNC.pNext = pNC;
1956 sNC.pParse = pNC->pParse;
1957 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
1959 }else{
1960 /* A real table or a CTE table */
1961 assert( !pS );
1962 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1963 if( iCol<0 ) iCol = pTab->iPKey;
1964 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1965 if( iCol<0 ){
1966 zType = "INTEGER";
1967 zOrigCol = "rowid";
1968 }else{
1969 zOrigCol = pTab->aCol[iCol].zCnName;
1970 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
1972 zOrigTab = pTab->zName;
1973 if( pNC->pParse && pTab->pSchema ){
1974 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1975 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
1977 #else
1978 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1979 if( iCol<0 ){
1980 zType = "INTEGER";
1981 }else{
1982 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
1984 #endif
1986 break;
1988 #ifndef SQLITE_OMIT_SUBQUERY
1989 case TK_SELECT: {
1990 /* The expression is a sub-select. Return the declaration type and
1991 ** origin info for the single column in the result set of the SELECT
1992 ** statement.
1994 NameContext sNC;
1995 Select *pS;
1996 Expr *p;
1997 assert( ExprUseXSelect(pExpr) );
1998 pS = pExpr->x.pSelect;
1999 p = pS->pEList->a[0].pExpr;
2000 sNC.pSrcList = pS->pSrc;
2001 sNC.pNext = pNC;
2002 sNC.pParse = pNC->pParse;
2003 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2004 break;
2006 #endif
2009 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2010 if( pzOrigDb ){
2011 assert( pzOrigTab && pzOrigCol );
2012 *pzOrigDb = zOrigDb;
2013 *pzOrigTab = zOrigTab;
2014 *pzOrigCol = zOrigCol;
2016 #endif
2017 return zType;
2021 ** Generate code that will tell the VDBE the declaration types of columns
2022 ** in the result set.
2024 static void generateColumnTypes(
2025 Parse *pParse, /* Parser context */
2026 SrcList *pTabList, /* List of tables */
2027 ExprList *pEList /* Expressions defining the result set */
2029 #ifndef SQLITE_OMIT_DECLTYPE
2030 Vdbe *v = pParse->pVdbe;
2031 int i;
2032 NameContext sNC;
2033 sNC.pSrcList = pTabList;
2034 sNC.pParse = pParse;
2035 sNC.pNext = 0;
2036 for(i=0; i<pEList->nExpr; i++){
2037 Expr *p = pEList->a[i].pExpr;
2038 const char *zType;
2039 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2040 const char *zOrigDb = 0;
2041 const char *zOrigTab = 0;
2042 const char *zOrigCol = 0;
2043 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2045 /* The vdbe must make its own copy of the column-type and other
2046 ** column specific strings, in case the schema is reset before this
2047 ** virtual machine is deleted.
2049 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
2050 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
2051 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
2052 #else
2053 zType = columnType(&sNC, p, 0, 0, 0);
2054 #endif
2055 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
2057 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
2062 ** Compute the column names for a SELECT statement.
2064 ** The only guarantee that SQLite makes about column names is that if the
2065 ** column has an AS clause assigning it a name, that will be the name used.
2066 ** That is the only documented guarantee. However, countless applications
2067 ** developed over the years have made baseless assumptions about column names
2068 ** and will break if those assumptions changes. Hence, use extreme caution
2069 ** when modifying this routine to avoid breaking legacy.
2071 ** See Also: sqlite3ColumnsFromExprList()
2073 ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
2074 ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
2075 ** applications should operate this way. Nevertheless, we need to support the
2076 ** other modes for legacy:
2078 ** short=OFF, full=OFF: Column name is the text of the expression has it
2079 ** originally appears in the SELECT statement. In
2080 ** other words, the zSpan of the result expression.
2082 ** short=ON, full=OFF: (This is the default setting). If the result
2083 ** refers directly to a table column, then the
2084 ** result column name is just the table column
2085 ** name: COLUMN. Otherwise use zSpan.
2087 ** full=ON, short=ANY: If the result refers directly to a table column,
2088 ** then the result column name with the table name
2089 ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
2091 void sqlite3GenerateColumnNames(
2092 Parse *pParse, /* Parser context */
2093 Select *pSelect /* Generate column names for this SELECT statement */
2095 Vdbe *v = pParse->pVdbe;
2096 int i;
2097 Table *pTab;
2098 SrcList *pTabList;
2099 ExprList *pEList;
2100 sqlite3 *db = pParse->db;
2101 int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
2102 int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
2104 #ifndef SQLITE_OMIT_EXPLAIN
2105 /* If this is an EXPLAIN, skip this step */
2106 if( pParse->explain ){
2107 return;
2109 #endif
2111 if( pParse->colNamesSet ) return;
2112 /* Column names are determined by the left-most term of a compound select */
2113 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2114 TREETRACE(0x80,pParse,pSelect,("generating column names\n"));
2115 pTabList = pSelect->pSrc;
2116 pEList = pSelect->pEList;
2117 assert( v!=0 );
2118 assert( pTabList!=0 );
2119 pParse->colNamesSet = 1;
2120 fullName = (db->flags & SQLITE_FullColNames)!=0;
2121 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
2122 sqlite3VdbeSetNumCols(v, pEList->nExpr);
2123 for(i=0; i<pEList->nExpr; i++){
2124 Expr *p = pEList->a[i].pExpr;
2126 assert( p!=0 );
2127 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
2128 assert( p->op!=TK_COLUMN
2129 || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
2130 if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
2131 /* An AS clause always takes first priority */
2132 char *zName = pEList->a[i].zEName;
2133 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
2134 }else if( srcName && p->op==TK_COLUMN ){
2135 char *zCol;
2136 int iCol = p->iColumn;
2137 pTab = p->y.pTab;
2138 assert( pTab!=0 );
2139 if( iCol<0 ) iCol = pTab->iPKey;
2140 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
2141 if( iCol<0 ){
2142 zCol = "rowid";
2143 }else{
2144 zCol = pTab->aCol[iCol].zCnName;
2146 if( fullName ){
2147 char *zName = 0;
2148 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
2149 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
2150 }else{
2151 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
2153 }else{
2154 const char *z = pEList->a[i].zEName;
2155 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
2156 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
2159 generateColumnTypes(pParse, pTabList, pEList);
2163 ** Given an expression list (which is really the list of expressions
2164 ** that form the result set of a SELECT statement) compute appropriate
2165 ** column names for a table that would hold the expression list.
2167 ** All column names will be unique.
2169 ** Only the column names are computed. Column.zType, Column.zColl,
2170 ** and other fields of Column are zeroed.
2172 ** Return SQLITE_OK on success. If a memory allocation error occurs,
2173 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
2175 ** The only guarantee that SQLite makes about column names is that if the
2176 ** column has an AS clause assigning it a name, that will be the name used.
2177 ** That is the only documented guarantee. However, countless applications
2178 ** developed over the years have made baseless assumptions about column names
2179 ** and will break if those assumptions changes. Hence, use extreme caution
2180 ** when modifying this routine to avoid breaking legacy.
2182 ** See Also: sqlite3GenerateColumnNames()
2184 int sqlite3ColumnsFromExprList(
2185 Parse *pParse, /* Parsing context */
2186 ExprList *pEList, /* Expr list from which to derive column names */
2187 i16 *pnCol, /* Write the number of columns here */
2188 Column **paCol /* Write the new column list here */
2190 sqlite3 *db = pParse->db; /* Database connection */
2191 int i, j; /* Loop counters */
2192 u32 cnt; /* Index added to make the name unique */
2193 Column *aCol, *pCol; /* For looping over result columns */
2194 int nCol; /* Number of columns in the result set */
2195 char *zName; /* Column name */
2196 int nName; /* Size of name in zName[] */
2197 Hash ht; /* Hash table of column names */
2198 Table *pTab;
2200 sqlite3HashInit(&ht);
2201 if( pEList ){
2202 nCol = pEList->nExpr;
2203 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
2204 testcase( aCol==0 );
2205 if( NEVER(nCol>32767) ) nCol = 32767;
2206 }else{
2207 nCol = 0;
2208 aCol = 0;
2210 assert( nCol==(i16)nCol );
2211 *pnCol = nCol;
2212 *paCol = aCol;
2214 for(i=0, pCol=aCol; i<nCol && !pParse->nErr; i++, pCol++){
2215 struct ExprList_item *pX = &pEList->a[i];
2216 struct ExprList_item *pCollide;
2217 /* Get an appropriate name for the column
2219 if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
2220 /* If the column contains an "AS <name>" phrase, use <name> as the name */
2221 }else{
2222 Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
2223 while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
2224 pColExpr = pColExpr->pRight;
2225 assert( pColExpr!=0 );
2227 if( pColExpr->op==TK_COLUMN
2228 && ALWAYS( ExprUseYTab(pColExpr) )
2229 && ALWAYS( pColExpr->y.pTab!=0 )
2231 /* For columns use the column name name */
2232 int iCol = pColExpr->iColumn;
2233 pTab = pColExpr->y.pTab;
2234 if( iCol<0 ) iCol = pTab->iPKey;
2235 zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
2236 }else if( pColExpr->op==TK_ID ){
2237 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
2238 zName = pColExpr->u.zToken;
2239 }else{
2240 /* Use the original text of the column expression as its name */
2241 assert( zName==pX->zEName ); /* pointer comparison intended */
2244 if( zName && !sqlite3IsTrueOrFalse(zName) ){
2245 zName = sqlite3DbStrDup(db, zName);
2246 }else{
2247 zName = sqlite3MPrintf(db,"column%d",i+1);
2250 /* Make sure the column name is unique. If the name is not unique,
2251 ** append an integer to the name so that it becomes unique.
2253 cnt = 0;
2254 while( zName && (pCollide = sqlite3HashFind(&ht, zName))!=0 ){
2255 if( pCollide->fg.bUsingTerm ){
2256 pCol->colFlags |= COLFLAG_NOEXPAND;
2258 nName = sqlite3Strlen30(zName);
2259 if( nName>0 ){
2260 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
2261 if( zName[j]==':' ) nName = j;
2263 zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
2264 sqlite3ProgressCheck(pParse);
2265 if( cnt>3 ){
2266 sqlite3_randomness(sizeof(cnt), &cnt);
2269 pCol->zCnName = zName;
2270 pCol->hName = sqlite3StrIHash(zName);
2271 if( pX->fg.bNoExpand ){
2272 pCol->colFlags |= COLFLAG_NOEXPAND;
2274 sqlite3ColumnPropertiesFromName(0, pCol);
2275 if( zName && sqlite3HashInsert(&ht, zName, pX)==pX ){
2276 sqlite3OomFault(db);
2279 sqlite3HashClear(&ht);
2280 if( pParse->nErr ){
2281 for(j=0; j<i; j++){
2282 sqlite3DbFree(db, aCol[j].zCnName);
2284 sqlite3DbFree(db, aCol);
2285 *paCol = 0;
2286 *pnCol = 0;
2287 return pParse->rc;
2289 return SQLITE_OK;
2293 ** pTab is a transient Table object that represents a subquery of some
2294 ** kind (maybe a parenthesized subquery in the FROM clause of a larger
2295 ** query, or a VIEW, or a CTE). This routine computes type information
2296 ** for that Table object based on the Select object that implements the
2297 ** subquery. For the purposes of this routine, "type infomation" means:
2299 ** * The datatype name, as it might appear in a CREATE TABLE statement
2300 ** * Which collating sequence to use for the column
2301 ** * The affinity of the column
2303 void sqlite3SubqueryColumnTypes(
2304 Parse *pParse, /* Parsing contexts */
2305 Table *pTab, /* Add column type information to this table */
2306 Select *pSelect, /* SELECT used to determine types and collations */
2307 char aff /* Default affinity. */
2309 sqlite3 *db = pParse->db;
2310 Column *pCol;
2311 CollSeq *pColl;
2312 int i,j;
2313 Expr *p;
2314 struct ExprList_item *a;
2315 NameContext sNC;
2317 assert( pSelect!=0 );
2318 assert( (pSelect->selFlags & SF_Resolved)!=0 );
2319 assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
2320 assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
2321 if( db->mallocFailed || IN_RENAME_OBJECT ) return;
2322 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2323 a = pSelect->pEList->a;
2324 memset(&sNC, 0, sizeof(sNC));
2325 sNC.pSrcList = pSelect->pSrc;
2326 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
2327 const char *zType;
2328 i64 n;
2329 pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
2330 p = a[i].pExpr;
2331 /* pCol->szEst = ... // Column size est for SELECT tables never used */
2332 pCol->affinity = sqlite3ExprAffinity(p);
2333 if( pCol->affinity<=SQLITE_AFF_NONE ){
2334 pCol->affinity = aff;
2336 if( pCol->affinity>=SQLITE_AFF_TEXT && pSelect->pNext ){
2337 int m = 0;
2338 Select *pS2;
2339 for(m=0, pS2=pSelect->pNext; pS2; pS2=pS2->pNext){
2340 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
2342 if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
2343 pCol->affinity = SQLITE_AFF_BLOB;
2344 }else
2345 if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
2346 pCol->affinity = SQLITE_AFF_BLOB;
2348 if( pCol->affinity>=SQLITE_AFF_NUMERIC && p->op==TK_CAST ){
2349 pCol->affinity = SQLITE_AFF_FLEXNUM;
2352 zType = columnType(&sNC, p, 0, 0, 0);
2353 if( zType==0 || pCol->affinity!=sqlite3AffinityType(zType, 0) ){
2354 if( pCol->affinity==SQLITE_AFF_NUMERIC
2355 || pCol->affinity==SQLITE_AFF_FLEXNUM
2357 zType = "NUM";
2358 }else{
2359 zType = 0;
2360 for(j=1; j<SQLITE_N_STDTYPE; j++){
2361 if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
2362 zType = sqlite3StdType[j];
2363 break;
2368 if( zType ){
2369 i64 m = sqlite3Strlen30(zType);
2370 n = sqlite3Strlen30(pCol->zCnName);
2371 pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
2372 pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
2373 if( pCol->zCnName ){
2374 memcpy(&pCol->zCnName[n+1], zType, m+1);
2375 pCol->colFlags |= COLFLAG_HASTYPE;
2378 pColl = sqlite3ExprCollSeq(pParse, p);
2379 if( pColl ){
2380 assert( pTab->pIndex==0 );
2381 sqlite3ColumnSetColl(db, pCol, pColl->zName);
2384 pTab->szTabRow = 1; /* Any non-zero value works */
2388 ** Given a SELECT statement, generate a Table structure that describes
2389 ** the result set of that SELECT.
2391 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
2392 Table *pTab;
2393 sqlite3 *db = pParse->db;
2394 u64 savedFlags;
2396 savedFlags = db->flags;
2397 db->flags &= ~(u64)SQLITE_FullColNames;
2398 db->flags |= SQLITE_ShortColNames;
2399 sqlite3SelectPrep(pParse, pSelect, 0);
2400 db->flags = savedFlags;
2401 if( pParse->nErr ) return 0;
2402 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2403 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
2404 if( pTab==0 ){
2405 return 0;
2407 pTab->nTabRef = 1;
2408 pTab->zName = 0;
2409 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
2410 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
2411 sqlite3SubqueryColumnTypes(pParse, pTab, pSelect, aff);
2412 pTab->iPKey = -1;
2413 if( db->mallocFailed ){
2414 sqlite3DeleteTable(db, pTab);
2415 return 0;
2417 return pTab;
2421 ** Get a VDBE for the given parser context. Create a new one if necessary.
2422 ** If an error occurs, return NULL and leave a message in pParse.
2424 Vdbe *sqlite3GetVdbe(Parse *pParse){
2425 if( pParse->pVdbe ){
2426 return pParse->pVdbe;
2428 if( pParse->pToplevel==0
2429 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
2431 pParse->okConstFactor = 1;
2433 return sqlite3VdbeCreate(pParse);
2438 ** Compute the iLimit and iOffset fields of the SELECT based on the
2439 ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
2440 ** that appear in the original SQL statement after the LIMIT and OFFSET
2441 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
2442 ** are the integer memory register numbers for counters used to compute
2443 ** the limit and offset. If there is no limit and/or offset, then
2444 ** iLimit and iOffset are negative.
2446 ** This routine changes the values of iLimit and iOffset only if
2447 ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
2448 ** and iOffset should have been preset to appropriate default values (zero)
2449 ** prior to calling this routine.
2451 ** The iOffset register (if it exists) is initialized to the value
2452 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
2453 ** iOffset+1 is initialized to LIMIT+OFFSET.
2455 ** Only if pLimit->pLeft!=0 do the limit registers get
2456 ** redefined. The UNION ALL operator uses this property to force
2457 ** the reuse of the same limit and offset registers across multiple
2458 ** SELECT statements.
2460 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
2461 Vdbe *v = 0;
2462 int iLimit = 0;
2463 int iOffset;
2464 int n;
2465 Expr *pLimit = p->pLimit;
2467 if( p->iLimit ) return;
2470 ** "LIMIT -1" always shows all rows. There is some
2471 ** controversy about what the correct behavior should be.
2472 ** The current implementation interprets "LIMIT 0" to mean
2473 ** no rows.
2475 if( pLimit ){
2476 assert( pLimit->op==TK_LIMIT );
2477 assert( pLimit->pLeft!=0 );
2478 p->iLimit = iLimit = ++pParse->nMem;
2479 v = sqlite3GetVdbe(pParse);
2480 assert( v!=0 );
2481 if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
2482 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
2483 VdbeComment((v, "LIMIT counter"));
2484 if( n==0 ){
2485 sqlite3VdbeGoto(v, iBreak);
2486 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
2487 p->nSelectRow = sqlite3LogEst((u64)n);
2488 p->selFlags |= SF_FixedLimit;
2490 }else{
2491 sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
2492 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
2493 VdbeComment((v, "LIMIT counter"));
2494 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
2496 if( pLimit->pRight ){
2497 p->iOffset = iOffset = ++pParse->nMem;
2498 pParse->nMem++; /* Allocate an extra register for limit+offset */
2499 sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
2500 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
2501 VdbeComment((v, "OFFSET counter"));
2502 sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
2503 VdbeComment((v, "LIMIT+OFFSET"));
2508 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2510 ** Return the appropriate collating sequence for the iCol-th column of
2511 ** the result set for the compound-select statement "p". Return NULL if
2512 ** the column has no default collating sequence.
2514 ** The collating sequence for the compound select is taken from the
2515 ** left-most term of the select that has a collating sequence.
2517 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
2518 CollSeq *pRet;
2519 if( p->pPrior ){
2520 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
2521 }else{
2522 pRet = 0;
2524 assert( iCol>=0 );
2525 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
2526 ** have been thrown during name resolution and we would not have gotten
2527 ** this far */
2528 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
2529 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
2531 return pRet;
2535 ** The select statement passed as the second parameter is a compound SELECT
2536 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
2537 ** structure suitable for implementing the ORDER BY.
2539 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
2540 ** function is responsible for ensuring that this structure is eventually
2541 ** freed.
2543 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
2544 ExprList *pOrderBy = p->pOrderBy;
2545 int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
2546 sqlite3 *db = pParse->db;
2547 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
2548 if( pRet ){
2549 int i;
2550 for(i=0; i<nOrderBy; i++){
2551 struct ExprList_item *pItem = &pOrderBy->a[i];
2552 Expr *pTerm = pItem->pExpr;
2553 CollSeq *pColl;
2555 if( pTerm->flags & EP_Collate ){
2556 pColl = sqlite3ExprCollSeq(pParse, pTerm);
2557 }else{
2558 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
2559 if( pColl==0 ) pColl = db->pDfltColl;
2560 pOrderBy->a[i].pExpr =
2561 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
2563 assert( sqlite3KeyInfoIsWriteable(pRet) );
2564 pRet->aColl[i] = pColl;
2565 pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
2569 return pRet;
2572 #ifndef SQLITE_OMIT_CTE
2574 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
2575 ** query of the form:
2577 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
2578 ** \___________/ \_______________/
2579 ** p->pPrior p
2582 ** There is exactly one reference to the recursive-table in the FROM clause
2583 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
2585 ** The setup-query runs once to generate an initial set of rows that go
2586 ** into a Queue table. Rows are extracted from the Queue table one by
2587 ** one. Each row extracted from Queue is output to pDest. Then the single
2588 ** extracted row (now in the iCurrent table) becomes the content of the
2589 ** recursive-table for a recursive-query run. The output of the recursive-query
2590 ** is added back into the Queue table. Then another row is extracted from Queue
2591 ** and the iteration continues until the Queue table is empty.
2593 ** If the compound query operator is UNION then no duplicate rows are ever
2594 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
2595 ** that have ever been inserted into Queue and causes duplicates to be
2596 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
2598 ** If the query has an ORDER BY, then entries in the Queue table are kept in
2599 ** ORDER BY order and the first entry is extracted for each cycle. Without
2600 ** an ORDER BY, the Queue table is just a FIFO.
2602 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
2603 ** have been output to pDest. A LIMIT of zero means to output no rows and a
2604 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
2605 ** with a positive value, then the first OFFSET outputs are discarded rather
2606 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
2607 ** rows have been skipped.
2609 static void generateWithRecursiveQuery(
2610 Parse *pParse, /* Parsing context */
2611 Select *p, /* The recursive SELECT to be coded */
2612 SelectDest *pDest /* What to do with query results */
2614 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
2615 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
2616 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
2617 Select *pSetup; /* The setup query */
2618 Select *pFirstRec; /* Left-most recursive term */
2619 int addrTop; /* Top of the loop */
2620 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
2621 int iCurrent = 0; /* The Current table */
2622 int regCurrent; /* Register holding Current table */
2623 int iQueue; /* The Queue table */
2624 int iDistinct = 0; /* To ensure unique results if UNION */
2625 int eDest = SRT_Fifo; /* How to write to Queue */
2626 SelectDest destQueue; /* SelectDest targetting the Queue table */
2627 int i; /* Loop counter */
2628 int rc; /* Result code */
2629 ExprList *pOrderBy; /* The ORDER BY clause */
2630 Expr *pLimit; /* Saved LIMIT and OFFSET */
2631 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
2633 #ifndef SQLITE_OMIT_WINDOWFUNC
2634 if( p->pWin ){
2635 sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
2636 return;
2638 #endif
2640 /* Obtain authorization to do a recursive query */
2641 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2643 /* Process the LIMIT and OFFSET clauses, if they exist */
2644 addrBreak = sqlite3VdbeMakeLabel(pParse);
2645 p->nSelectRow = 320; /* 4 billion rows */
2646 computeLimitRegisters(pParse, p, addrBreak);
2647 pLimit = p->pLimit;
2648 regLimit = p->iLimit;
2649 regOffset = p->iOffset;
2650 p->pLimit = 0;
2651 p->iLimit = p->iOffset = 0;
2652 pOrderBy = p->pOrderBy;
2654 /* Locate the cursor number of the Current table */
2655 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
2656 if( pSrc->a[i].fg.isRecursive ){
2657 iCurrent = pSrc->a[i].iCursor;
2658 break;
2662 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
2663 ** the Distinct table must be exactly one greater than Queue in order
2664 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2665 iQueue = pParse->nTab++;
2666 if( p->op==TK_UNION ){
2667 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2668 iDistinct = pParse->nTab++;
2669 }else{
2670 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2672 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2674 /* Allocate cursors for Current, Queue, and Distinct. */
2675 regCurrent = ++pParse->nMem;
2676 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2677 if( pOrderBy ){
2678 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2679 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2680 (char*)pKeyInfo, P4_KEYINFO);
2681 destQueue.pOrderBy = pOrderBy;
2682 }else{
2683 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2685 VdbeComment((v, "Queue table"));
2686 if( iDistinct ){
2687 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2688 p->selFlags |= SF_UsesEphemeral;
2691 /* Detach the ORDER BY clause from the compound SELECT */
2692 p->pOrderBy = 0;
2694 /* Figure out how many elements of the compound SELECT are part of the
2695 ** recursive query. Make sure no recursive elements use aggregate
2696 ** functions. Mark the recursive elements as UNION ALL even if they
2697 ** are really UNION because the distinctness will be enforced by the
2698 ** iDistinct table. pFirstRec is left pointing to the left-most
2699 ** recursive term of the CTE.
2701 for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
2702 if( pFirstRec->selFlags & SF_Aggregate ){
2703 sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2704 goto end_of_recursive_query;
2706 pFirstRec->op = TK_ALL;
2707 if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
2710 /* Store the results of the setup-query in Queue. */
2711 pSetup = pFirstRec->pPrior;
2712 pSetup->pNext = 0;
2713 ExplainQueryPlan((pParse, 1, "SETUP"));
2714 rc = sqlite3Select(pParse, pSetup, &destQueue);
2715 pSetup->pNext = p;
2716 if( rc ) goto end_of_recursive_query;
2718 /* Find the next row in the Queue and output that row */
2719 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2721 /* Transfer the next row in Queue over to Current */
2722 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2723 if( pOrderBy ){
2724 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2725 }else{
2726 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2728 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2730 /* Output the single row in Current */
2731 addrCont = sqlite3VdbeMakeLabel(pParse);
2732 codeOffset(v, regOffset, addrCont);
2733 selectInnerLoop(pParse, p, iCurrent,
2734 0, 0, pDest, addrCont, addrBreak);
2735 if( regLimit ){
2736 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2737 VdbeCoverage(v);
2739 sqlite3VdbeResolveLabel(v, addrCont);
2741 /* Execute the recursive SELECT taking the single row in Current as
2742 ** the value for the recursive-table. Store the results in the Queue.
2744 pFirstRec->pPrior = 0;
2745 ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
2746 sqlite3Select(pParse, p, &destQueue);
2747 assert( pFirstRec->pPrior==0 );
2748 pFirstRec->pPrior = pSetup;
2750 /* Keep running the loop until the Queue is empty */
2751 sqlite3VdbeGoto(v, addrTop);
2752 sqlite3VdbeResolveLabel(v, addrBreak);
2754 end_of_recursive_query:
2755 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2756 p->pOrderBy = pOrderBy;
2757 p->pLimit = pLimit;
2758 return;
2760 #endif /* SQLITE_OMIT_CTE */
2762 /* Forward references */
2763 static int multiSelectOrderBy(
2764 Parse *pParse, /* Parsing context */
2765 Select *p, /* The right-most of SELECTs to be coded */
2766 SelectDest *pDest /* What to do with query results */
2770 ** Handle the special case of a compound-select that originates from a
2771 ** VALUES clause. By handling this as a special case, we avoid deep
2772 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
2773 ** on a VALUES clause.
2775 ** Because the Select object originates from a VALUES clause:
2776 ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
2777 ** (2) All terms are UNION ALL
2778 ** (3) There is no ORDER BY clause
2780 ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
2781 ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
2782 ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
2783 ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
2785 static int multiSelectValues(
2786 Parse *pParse, /* Parsing context */
2787 Select *p, /* The right-most of SELECTs to be coded */
2788 SelectDest *pDest /* What to do with query results */
2790 int nRow = 1;
2791 int rc = 0;
2792 int bShowAll = p->pLimit==0;
2793 assert( p->selFlags & SF_MultiValue );
2795 assert( p->selFlags & SF_Values );
2796 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
2797 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
2798 #ifndef SQLITE_OMIT_WINDOWFUNC
2799 if( p->pWin ) return -1;
2800 #endif
2801 if( p->pPrior==0 ) break;
2802 assert( p->pPrior->pNext==p );
2803 p = p->pPrior;
2804 nRow += bShowAll;
2805 }while(1);
2806 ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
2807 nRow==1 ? "" : "S"));
2808 while( p ){
2809 selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
2810 if( !bShowAll ) break;
2811 p->nSelectRow = nRow;
2812 p = p->pNext;
2814 return rc;
2818 ** Return true if the SELECT statement which is known to be the recursive
2819 ** part of a recursive CTE still has its anchor terms attached. If the
2820 ** anchor terms have already been removed, then return false.
2822 static int hasAnchor(Select *p){
2823 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
2824 return p!=0;
2828 ** This routine is called to process a compound query form from
2829 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
2830 ** INTERSECT
2832 ** "p" points to the right-most of the two queries. the query on the
2833 ** left is p->pPrior. The left query could also be a compound query
2834 ** in which case this routine will be called recursively.
2836 ** The results of the total query are to be written into a destination
2837 ** of type eDest with parameter iParm.
2839 ** Example 1: Consider a three-way compound SQL statement.
2841 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2843 ** This statement is parsed up as follows:
2845 ** SELECT c FROM t3
2846 ** |
2847 ** `-----> SELECT b FROM t2
2848 ** |
2849 ** `------> SELECT a FROM t1
2851 ** The arrows in the diagram above represent the Select.pPrior pointer.
2852 ** So if this routine is called with p equal to the t3 query, then
2853 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
2855 ** Notice that because of the way SQLite parses compound SELECTs, the
2856 ** individual selects always group from left to right.
2858 static int multiSelect(
2859 Parse *pParse, /* Parsing context */
2860 Select *p, /* The right-most of SELECTs to be coded */
2861 SelectDest *pDest /* What to do with query results */
2863 int rc = SQLITE_OK; /* Success code from a subroutine */
2864 Select *pPrior; /* Another SELECT immediately to our left */
2865 Vdbe *v; /* Generate code to this VDBE */
2866 SelectDest dest; /* Alternative data destination */
2867 Select *pDelete = 0; /* Chain of simple selects to delete */
2868 sqlite3 *db; /* Database connection */
2870 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
2871 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
2873 assert( p && p->pPrior ); /* Calling function guarantees this much */
2874 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2875 assert( p->selFlags & SF_Compound );
2876 db = pParse->db;
2877 pPrior = p->pPrior;
2878 dest = *pDest;
2879 assert( pPrior->pOrderBy==0 );
2880 assert( pPrior->pLimit==0 );
2882 v = sqlite3GetVdbe(pParse);
2883 assert( v!=0 ); /* The VDBE already created by calling function */
2885 /* Create the destination temporary table if necessary
2887 if( dest.eDest==SRT_EphemTab ){
2888 assert( p->pEList );
2889 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2890 dest.eDest = SRT_Table;
2893 /* Special handling for a compound-select that originates as a VALUES clause.
2895 if( p->selFlags & SF_MultiValue ){
2896 rc = multiSelectValues(pParse, p, &dest);
2897 if( rc>=0 ) goto multi_select_end;
2898 rc = SQLITE_OK;
2901 /* Make sure all SELECTs in the statement have the same number of elements
2902 ** in their result sets.
2904 assert( p->pEList && pPrior->pEList );
2905 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2907 #ifndef SQLITE_OMIT_CTE
2908 if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
2909 generateWithRecursiveQuery(pParse, p, &dest);
2910 }else
2911 #endif
2913 /* Compound SELECTs that have an ORDER BY clause are handled separately.
2915 if( p->pOrderBy ){
2916 return multiSelectOrderBy(pParse, p, pDest);
2917 }else{
2919 #ifndef SQLITE_OMIT_EXPLAIN
2920 if( pPrior->pPrior==0 ){
2921 ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
2922 ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
2924 #endif
2926 /* Generate code for the left and right SELECT statements.
2928 switch( p->op ){
2929 case TK_ALL: {
2930 int addr = 0;
2931 int nLimit = 0; /* Initialize to suppress harmless compiler warning */
2932 assert( !pPrior->pLimit );
2933 pPrior->iLimit = p->iLimit;
2934 pPrior->iOffset = p->iOffset;
2935 pPrior->pLimit = p->pLimit;
2936 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
2937 rc = sqlite3Select(pParse, pPrior, &dest);
2938 pPrior->pLimit = 0;
2939 if( rc ){
2940 goto multi_select_end;
2942 p->pPrior = 0;
2943 p->iLimit = pPrior->iLimit;
2944 p->iOffset = pPrior->iOffset;
2945 if( p->iLimit ){
2946 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2947 VdbeComment((v, "Jump ahead if LIMIT reached"));
2948 if( p->iOffset ){
2949 sqlite3VdbeAddOp3(v, OP_OffsetLimit,
2950 p->iLimit, p->iOffset+1, p->iOffset);
2953 ExplainQueryPlan((pParse, 1, "UNION ALL"));
2954 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
2955 rc = sqlite3Select(pParse, p, &dest);
2956 testcase( rc!=SQLITE_OK );
2957 pDelete = p->pPrior;
2958 p->pPrior = pPrior;
2959 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2960 if( p->pLimit
2961 && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
2962 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
2964 p->nSelectRow = sqlite3LogEst((u64)nLimit);
2966 if( addr ){
2967 sqlite3VdbeJumpHere(v, addr);
2969 break;
2971 case TK_EXCEPT:
2972 case TK_UNION: {
2973 int unionTab; /* Cursor number of the temp table holding result */
2974 u8 op = 0; /* One of the SRT_ operations to apply to self */
2975 int priorOp; /* The SRT_ operation to apply to prior selects */
2976 Expr *pLimit; /* Saved values of p->nLimit */
2977 int addr;
2978 SelectDest uniondest;
2980 testcase( p->op==TK_EXCEPT );
2981 testcase( p->op==TK_UNION );
2982 priorOp = SRT_Union;
2983 if( dest.eDest==priorOp ){
2984 /* We can reuse a temporary table generated by a SELECT to our
2985 ** right.
2987 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
2988 unionTab = dest.iSDParm;
2989 }else{
2990 /* We will need to create our own temporary table to hold the
2991 ** intermediate results.
2993 unionTab = pParse->nTab++;
2994 assert( p->pOrderBy==0 );
2995 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
2996 assert( p->addrOpenEphm[0] == -1 );
2997 p->addrOpenEphm[0] = addr;
2998 findRightmost(p)->selFlags |= SF_UsesEphemeral;
2999 assert( p->pEList );
3003 /* Code the SELECT statements to our left
3005 assert( !pPrior->pOrderBy );
3006 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
3007 TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
3008 rc = sqlite3Select(pParse, pPrior, &uniondest);
3009 if( rc ){
3010 goto multi_select_end;
3013 /* Code the current SELECT statement
3015 if( p->op==TK_EXCEPT ){
3016 op = SRT_Except;
3017 }else{
3018 assert( p->op==TK_UNION );
3019 op = SRT_Union;
3021 p->pPrior = 0;
3022 pLimit = p->pLimit;
3023 p->pLimit = 0;
3024 uniondest.eDest = op;
3025 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3026 sqlite3SelectOpName(p->op)));
3027 TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
3028 rc = sqlite3Select(pParse, p, &uniondest);
3029 testcase( rc!=SQLITE_OK );
3030 assert( p->pOrderBy==0 );
3031 pDelete = p->pPrior;
3032 p->pPrior = pPrior;
3033 p->pOrderBy = 0;
3034 if( p->op==TK_UNION ){
3035 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3037 sqlite3ExprDelete(db, p->pLimit);
3038 p->pLimit = pLimit;
3039 p->iLimit = 0;
3040 p->iOffset = 0;
3042 /* Convert the data in the temporary table into whatever form
3043 ** it is that we currently need.
3045 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
3046 assert( p->pEList || db->mallocFailed );
3047 if( dest.eDest!=priorOp && db->mallocFailed==0 ){
3048 int iCont, iBreak, iStart;
3049 iBreak = sqlite3VdbeMakeLabel(pParse);
3050 iCont = sqlite3VdbeMakeLabel(pParse);
3051 computeLimitRegisters(pParse, p, iBreak);
3052 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
3053 iStart = sqlite3VdbeCurrentAddr(v);
3054 selectInnerLoop(pParse, p, unionTab,
3055 0, 0, &dest, iCont, iBreak);
3056 sqlite3VdbeResolveLabel(v, iCont);
3057 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
3058 sqlite3VdbeResolveLabel(v, iBreak);
3059 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
3061 break;
3063 default: assert( p->op==TK_INTERSECT ); {
3064 int tab1, tab2;
3065 int iCont, iBreak, iStart;
3066 Expr *pLimit;
3067 int addr;
3068 SelectDest intersectdest;
3069 int r1;
3071 /* INTERSECT is different from the others since it requires
3072 ** two temporary tables. Hence it has its own case. Begin
3073 ** by allocating the tables we will need.
3075 tab1 = pParse->nTab++;
3076 tab2 = pParse->nTab++;
3077 assert( p->pOrderBy==0 );
3079 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
3080 assert( p->addrOpenEphm[0] == -1 );
3081 p->addrOpenEphm[0] = addr;
3082 findRightmost(p)->selFlags |= SF_UsesEphemeral;
3083 assert( p->pEList );
3085 /* Code the SELECTs to our left into temporary table "tab1".
3087 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
3088 TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT left...\n"));
3089 rc = sqlite3Select(pParse, pPrior, &intersectdest);
3090 if( rc ){
3091 goto multi_select_end;
3094 /* Code the current SELECT into temporary table "tab2"
3096 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
3097 assert( p->addrOpenEphm[1] == -1 );
3098 p->addrOpenEphm[1] = addr;
3099 p->pPrior = 0;
3100 pLimit = p->pLimit;
3101 p->pLimit = 0;
3102 intersectdest.iSDParm = tab2;
3103 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3104 sqlite3SelectOpName(p->op)));
3105 TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT right...\n"));
3106 rc = sqlite3Select(pParse, p, &intersectdest);
3107 testcase( rc!=SQLITE_OK );
3108 pDelete = p->pPrior;
3109 p->pPrior = pPrior;
3110 if( p->nSelectRow>pPrior->nSelectRow ){
3111 p->nSelectRow = pPrior->nSelectRow;
3113 sqlite3ExprDelete(db, p->pLimit);
3114 p->pLimit = pLimit;
3116 /* Generate code to take the intersection of the two temporary
3117 ** tables.
3119 if( rc ) break;
3120 assert( p->pEList );
3121 iBreak = sqlite3VdbeMakeLabel(pParse);
3122 iCont = sqlite3VdbeMakeLabel(pParse);
3123 computeLimitRegisters(pParse, p, iBreak);
3124 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
3125 r1 = sqlite3GetTempReg(pParse);
3126 iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
3127 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
3128 VdbeCoverage(v);
3129 sqlite3ReleaseTempReg(pParse, r1);
3130 selectInnerLoop(pParse, p, tab1,
3131 0, 0, &dest, iCont, iBreak);
3132 sqlite3VdbeResolveLabel(v, iCont);
3133 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
3134 sqlite3VdbeResolveLabel(v, iBreak);
3135 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
3136 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
3137 break;
3141 #ifndef SQLITE_OMIT_EXPLAIN
3142 if( p->pNext==0 ){
3143 ExplainQueryPlanPop(pParse);
3145 #endif
3147 if( pParse->nErr ) goto multi_select_end;
3149 /* Compute collating sequences used by
3150 ** temporary tables needed to implement the compound select.
3151 ** Attach the KeyInfo structure to all temporary tables.
3153 ** This section is run by the right-most SELECT statement only.
3154 ** SELECT statements to the left always skip this part. The right-most
3155 ** SELECT might also skip this part if it has no ORDER BY clause and
3156 ** no temp tables are required.
3158 if( p->selFlags & SF_UsesEphemeral ){
3159 int i; /* Loop counter */
3160 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
3161 Select *pLoop; /* For looping through SELECT statements */
3162 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
3163 int nCol; /* Number of columns in result set */
3165 assert( p->pNext==0 );
3166 assert( p->pEList!=0 );
3167 nCol = p->pEList->nExpr;
3168 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
3169 if( !pKeyInfo ){
3170 rc = SQLITE_NOMEM_BKPT;
3171 goto multi_select_end;
3173 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
3174 *apColl = multiSelectCollSeq(pParse, p, i);
3175 if( 0==*apColl ){
3176 *apColl = db->pDfltColl;
3180 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
3181 for(i=0; i<2; i++){
3182 int addr = pLoop->addrOpenEphm[i];
3183 if( addr<0 ){
3184 /* If [0] is unused then [1] is also unused. So we can
3185 ** always safely abort as soon as the first unused slot is found */
3186 assert( pLoop->addrOpenEphm[1]<0 );
3187 break;
3189 sqlite3VdbeChangeP2(v, addr, nCol);
3190 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
3191 P4_KEYINFO);
3192 pLoop->addrOpenEphm[i] = -1;
3195 sqlite3KeyInfoUnref(pKeyInfo);
3198 multi_select_end:
3199 pDest->iSdst = dest.iSdst;
3200 pDest->nSdst = dest.nSdst;
3201 if( pDelete ){
3202 sqlite3ParserAddCleanup(pParse,
3203 (void(*)(sqlite3*,void*))sqlite3SelectDelete,
3204 pDelete);
3206 return rc;
3208 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
3211 ** Error message for when two or more terms of a compound select have different
3212 ** size result sets.
3214 void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
3215 if( p->selFlags & SF_Values ){
3216 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
3217 }else{
3218 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
3219 " do not have the same number of result columns",
3220 sqlite3SelectOpName(p->op));
3225 ** Code an output subroutine for a coroutine implementation of a
3226 ** SELECT statment.
3228 ** The data to be output is contained in pIn->iSdst. There are
3229 ** pIn->nSdst columns to be output. pDest is where the output should
3230 ** be sent.
3232 ** regReturn is the number of the register holding the subroutine
3233 ** return address.
3235 ** If regPrev>0 then it is the first register in a vector that
3236 ** records the previous output. mem[regPrev] is a flag that is false
3237 ** if there has been no previous output. If regPrev>0 then code is
3238 ** generated to suppress duplicates. pKeyInfo is used for comparing
3239 ** keys.
3241 ** If the LIMIT found in p->iLimit is reached, jump immediately to
3242 ** iBreak.
3244 static int generateOutputSubroutine(
3245 Parse *pParse, /* Parsing context */
3246 Select *p, /* The SELECT statement */
3247 SelectDest *pIn, /* Coroutine supplying data */
3248 SelectDest *pDest, /* Where to send the data */
3249 int regReturn, /* The return address register */
3250 int regPrev, /* Previous result register. No uniqueness if 0 */
3251 KeyInfo *pKeyInfo, /* For comparing with previous entry */
3252 int iBreak /* Jump here if we hit the LIMIT */
3254 Vdbe *v = pParse->pVdbe;
3255 int iContinue;
3256 int addr;
3258 addr = sqlite3VdbeCurrentAddr(v);
3259 iContinue = sqlite3VdbeMakeLabel(pParse);
3261 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
3263 if( regPrev ){
3264 int addr1, addr2;
3265 addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
3266 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
3267 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
3268 sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
3269 sqlite3VdbeJumpHere(v, addr1);
3270 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
3271 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
3273 if( pParse->db->mallocFailed ) return 0;
3275 /* Suppress the first OFFSET entries if there is an OFFSET clause
3277 codeOffset(v, p->iOffset, iContinue);
3279 assert( pDest->eDest!=SRT_Exists );
3280 assert( pDest->eDest!=SRT_Table );
3281 switch( pDest->eDest ){
3282 /* Store the result as data using a unique key.
3284 case SRT_EphemTab: {
3285 int r1 = sqlite3GetTempReg(pParse);
3286 int r2 = sqlite3GetTempReg(pParse);
3287 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
3288 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
3289 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
3290 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3291 sqlite3ReleaseTempReg(pParse, r2);
3292 sqlite3ReleaseTempReg(pParse, r1);
3293 break;
3296 #ifndef SQLITE_OMIT_SUBQUERY
3297 /* If we are creating a set for an "expr IN (SELECT ...)".
3299 case SRT_Set: {
3300 int r1;
3301 testcase( pIn->nSdst>1 );
3302 r1 = sqlite3GetTempReg(pParse);
3303 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
3304 r1, pDest->zAffSdst, pIn->nSdst);
3305 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
3306 pIn->iSdst, pIn->nSdst);
3307 sqlite3ReleaseTempReg(pParse, r1);
3308 break;
3311 /* If this is a scalar select that is part of an expression, then
3312 ** store the results in the appropriate memory cell and break out
3313 ** of the scan loop. Note that the select might return multiple columns
3314 ** if it is the RHS of a row-value IN operator.
3316 case SRT_Mem: {
3317 testcase( pIn->nSdst>1 );
3318 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
3319 /* The LIMIT clause will jump out of the loop for us */
3320 break;
3322 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
3324 /* The results are stored in a sequence of registers
3325 ** starting at pDest->iSdst. Then the co-routine yields.
3327 case SRT_Coroutine: {
3328 if( pDest->iSdst==0 ){
3329 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
3330 pDest->nSdst = pIn->nSdst;
3332 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
3333 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
3334 break;
3337 /* If none of the above, then the result destination must be
3338 ** SRT_Output. This routine is never called with any other
3339 ** destination other than the ones handled above or SRT_Output.
3341 ** For SRT_Output, results are stored in a sequence of registers.
3342 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
3343 ** return the next row of result.
3345 default: {
3346 assert( pDest->eDest==SRT_Output );
3347 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
3348 break;
3352 /* Jump to the end of the loop if the LIMIT is reached.
3354 if( p->iLimit ){
3355 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
3358 /* Generate the subroutine return
3360 sqlite3VdbeResolveLabel(v, iContinue);
3361 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
3363 return addr;
3367 ** Alternative compound select code generator for cases when there
3368 ** is an ORDER BY clause.
3370 ** We assume a query of the following form:
3372 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
3374 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
3375 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
3376 ** co-routines. Then run the co-routines in parallel and merge the results
3377 ** into the output. In addition to the two coroutines (called selectA and
3378 ** selectB) there are 7 subroutines:
3380 ** outA: Move the output of the selectA coroutine into the output
3381 ** of the compound query.
3383 ** outB: Move the output of the selectB coroutine into the output
3384 ** of the compound query. (Only generated for UNION and
3385 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
3386 ** appears only in B.)
3388 ** AltB: Called when there is data from both coroutines and A<B.
3390 ** AeqB: Called when there is data from both coroutines and A==B.
3392 ** AgtB: Called when there is data from both coroutines and A>B.
3394 ** EofA: Called when data is exhausted from selectA.
3396 ** EofB: Called when data is exhausted from selectB.
3398 ** The implementation of the latter five subroutines depend on which
3399 ** <operator> is used:
3402 ** UNION ALL UNION EXCEPT INTERSECT
3403 ** ------------- ----------------- -------------- -----------------
3404 ** AltB: outA, nextA outA, nextA outA, nextA nextA
3406 ** AeqB: outA, nextA nextA nextA outA, nextA
3408 ** AgtB: outB, nextB outB, nextB nextB nextB
3410 ** EofA: outB, nextB outB, nextB halt halt
3412 ** EofB: outA, nextA outA, nextA outA, nextA halt
3414 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
3415 ** causes an immediate jump to EofA and an EOF on B following nextB causes
3416 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
3417 ** following nextX causes a jump to the end of the select processing.
3419 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
3420 ** within the output subroutine. The regPrev register set holds the previously
3421 ** output value. A comparison is made against this value and the output
3422 ** is skipped if the next results would be the same as the previous.
3424 ** The implementation plan is to implement the two coroutines and seven
3425 ** subroutines first, then put the control logic at the bottom. Like this:
3427 ** goto Init
3428 ** coA: coroutine for left query (A)
3429 ** coB: coroutine for right query (B)
3430 ** outA: output one row of A
3431 ** outB: output one row of B (UNION and UNION ALL only)
3432 ** EofA: ...
3433 ** EofB: ...
3434 ** AltB: ...
3435 ** AeqB: ...
3436 ** AgtB: ...
3437 ** Init: initialize coroutine registers
3438 ** yield coA
3439 ** if eof(A) goto EofA
3440 ** yield coB
3441 ** if eof(B) goto EofB
3442 ** Cmpr: Compare A, B
3443 ** Jump AltB, AeqB, AgtB
3444 ** End: ...
3446 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
3447 ** actually called using Gosub and they do not Return. EofA and EofB loop
3448 ** until all data is exhausted then jump to the "end" labe. AltB, AeqB,
3449 ** and AgtB jump to either L2 or to one of EofA or EofB.
3451 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3452 static int multiSelectOrderBy(
3453 Parse *pParse, /* Parsing context */
3454 Select *p, /* The right-most of SELECTs to be coded */
3455 SelectDest *pDest /* What to do with query results */
3457 int i, j; /* Loop counters */
3458 Select *pPrior; /* Another SELECT immediately to our left */
3459 Select *pSplit; /* Left-most SELECT in the right-hand group */
3460 int nSelect; /* Number of SELECT statements in the compound */
3461 Vdbe *v; /* Generate code to this VDBE */
3462 SelectDest destA; /* Destination for coroutine A */
3463 SelectDest destB; /* Destination for coroutine B */
3464 int regAddrA; /* Address register for select-A coroutine */
3465 int regAddrB; /* Address register for select-B coroutine */
3466 int addrSelectA; /* Address of the select-A coroutine */
3467 int addrSelectB; /* Address of the select-B coroutine */
3468 int regOutA; /* Address register for the output-A subroutine */
3469 int regOutB; /* Address register for the output-B subroutine */
3470 int addrOutA; /* Address of the output-A subroutine */
3471 int addrOutB = 0; /* Address of the output-B subroutine */
3472 int addrEofA; /* Address of the select-A-exhausted subroutine */
3473 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
3474 int addrEofB; /* Address of the select-B-exhausted subroutine */
3475 int addrAltB; /* Address of the A<B subroutine */
3476 int addrAeqB; /* Address of the A==B subroutine */
3477 int addrAgtB; /* Address of the A>B subroutine */
3478 int regLimitA; /* Limit register for select-A */
3479 int regLimitB; /* Limit register for select-A */
3480 int regPrev; /* A range of registers to hold previous output */
3481 int savedLimit; /* Saved value of p->iLimit */
3482 int savedOffset; /* Saved value of p->iOffset */
3483 int labelCmpr; /* Label for the start of the merge algorithm */
3484 int labelEnd; /* Label for the end of the overall SELECT stmt */
3485 int addr1; /* Jump instructions that get retargetted */
3486 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
3487 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
3488 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
3489 sqlite3 *db; /* Database connection */
3490 ExprList *pOrderBy; /* The ORDER BY clause */
3491 int nOrderBy; /* Number of terms in the ORDER BY clause */
3492 u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */
3494 assert( p->pOrderBy!=0 );
3495 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
3496 db = pParse->db;
3497 v = pParse->pVdbe;
3498 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
3499 labelEnd = sqlite3VdbeMakeLabel(pParse);
3500 labelCmpr = sqlite3VdbeMakeLabel(pParse);
3503 /* Patch up the ORDER BY clause
3505 op = p->op;
3506 assert( p->pPrior->pOrderBy==0 );
3507 pOrderBy = p->pOrderBy;
3508 assert( pOrderBy );
3509 nOrderBy = pOrderBy->nExpr;
3511 /* For operators other than UNION ALL we have to make sure that
3512 ** the ORDER BY clause covers every term of the result set. Add
3513 ** terms to the ORDER BY clause as necessary.
3515 if( op!=TK_ALL ){
3516 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
3517 struct ExprList_item *pItem;
3518 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
3519 assert( pItem!=0 );
3520 assert( pItem->u.x.iOrderByCol>0 );
3521 if( pItem->u.x.iOrderByCol==i ) break;
3523 if( j==nOrderBy ){
3524 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
3525 if( pNew==0 ) return SQLITE_NOMEM_BKPT;
3526 pNew->flags |= EP_IntValue;
3527 pNew->u.iValue = i;
3528 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
3529 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
3534 /* Compute the comparison permutation and keyinfo that is used with
3535 ** the permutation used to determine if the next
3536 ** row of results comes from selectA or selectB. Also add explicit
3537 ** collations to the ORDER BY clause terms so that when the subqueries
3538 ** to the right and the left are evaluated, they use the correct
3539 ** collation.
3541 aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
3542 if( aPermute ){
3543 struct ExprList_item *pItem;
3544 aPermute[0] = nOrderBy;
3545 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
3546 assert( pItem!=0 );
3547 assert( pItem->u.x.iOrderByCol>0 );
3548 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
3549 aPermute[i] = pItem->u.x.iOrderByCol - 1;
3551 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
3552 }else{
3553 pKeyMerge = 0;
3556 /* Allocate a range of temporary registers and the KeyInfo needed
3557 ** for the logic that removes duplicate result rows when the
3558 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
3560 if( op==TK_ALL ){
3561 regPrev = 0;
3562 }else{
3563 int nExpr = p->pEList->nExpr;
3564 assert( nOrderBy>=nExpr || db->mallocFailed );
3565 regPrev = pParse->nMem+1;
3566 pParse->nMem += nExpr+1;
3567 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
3568 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
3569 if( pKeyDup ){
3570 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
3571 for(i=0; i<nExpr; i++){
3572 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
3573 pKeyDup->aSortFlags[i] = 0;
3578 /* Separate the left and the right query from one another
3580 nSelect = 1;
3581 if( (op==TK_ALL || op==TK_UNION)
3582 && OptimizationEnabled(db, SQLITE_BalancedMerge)
3584 for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
3585 nSelect++;
3586 assert( pSplit->pPrior->pNext==pSplit );
3589 if( nSelect<=3 ){
3590 pSplit = p;
3591 }else{
3592 pSplit = p;
3593 for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
3595 pPrior = pSplit->pPrior;
3596 assert( pPrior!=0 );
3597 pSplit->pPrior = 0;
3598 pPrior->pNext = 0;
3599 assert( p->pOrderBy == pOrderBy );
3600 assert( pOrderBy!=0 || db->mallocFailed );
3601 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
3602 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
3603 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
3605 /* Compute the limit registers */
3606 computeLimitRegisters(pParse, p, labelEnd);
3607 if( p->iLimit && op==TK_ALL ){
3608 regLimitA = ++pParse->nMem;
3609 regLimitB = ++pParse->nMem;
3610 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
3611 regLimitA);
3612 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
3613 }else{
3614 regLimitA = regLimitB = 0;
3616 sqlite3ExprDelete(db, p->pLimit);
3617 p->pLimit = 0;
3619 regAddrA = ++pParse->nMem;
3620 regAddrB = ++pParse->nMem;
3621 regOutA = ++pParse->nMem;
3622 regOutB = ++pParse->nMem;
3623 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
3624 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
3626 ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
3628 /* Generate a coroutine to evaluate the SELECT statement to the
3629 ** left of the compound operator - the "A" select.
3631 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
3632 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
3633 VdbeComment((v, "left SELECT"));
3634 pPrior->iLimit = regLimitA;
3635 ExplainQueryPlan((pParse, 1, "LEFT"));
3636 sqlite3Select(pParse, pPrior, &destA);
3637 sqlite3VdbeEndCoroutine(v, regAddrA);
3638 sqlite3VdbeJumpHere(v, addr1);
3640 /* Generate a coroutine to evaluate the SELECT statement on
3641 ** the right - the "B" select
3643 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
3644 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
3645 VdbeComment((v, "right SELECT"));
3646 savedLimit = p->iLimit;
3647 savedOffset = p->iOffset;
3648 p->iLimit = regLimitB;
3649 p->iOffset = 0;
3650 ExplainQueryPlan((pParse, 1, "RIGHT"));
3651 sqlite3Select(pParse, p, &destB);
3652 p->iLimit = savedLimit;
3653 p->iOffset = savedOffset;
3654 sqlite3VdbeEndCoroutine(v, regAddrB);
3656 /* Generate a subroutine that outputs the current row of the A
3657 ** select as the next output row of the compound select.
3659 VdbeNoopComment((v, "Output routine for A"));
3660 addrOutA = generateOutputSubroutine(pParse,
3661 p, &destA, pDest, regOutA,
3662 regPrev, pKeyDup, labelEnd);
3664 /* Generate a subroutine that outputs the current row of the B
3665 ** select as the next output row of the compound select.
3667 if( op==TK_ALL || op==TK_UNION ){
3668 VdbeNoopComment((v, "Output routine for B"));
3669 addrOutB = generateOutputSubroutine(pParse,
3670 p, &destB, pDest, regOutB,
3671 regPrev, pKeyDup, labelEnd);
3673 sqlite3KeyInfoUnref(pKeyDup);
3675 /* Generate a subroutine to run when the results from select A
3676 ** are exhausted and only data in select B remains.
3678 if( op==TK_EXCEPT || op==TK_INTERSECT ){
3679 addrEofA_noB = addrEofA = labelEnd;
3680 }else{
3681 VdbeNoopComment((v, "eof-A subroutine"));
3682 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3683 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3684 VdbeCoverage(v);
3685 sqlite3VdbeGoto(v, addrEofA);
3686 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3689 /* Generate a subroutine to run when the results from select B
3690 ** are exhausted and only data in select A remains.
3692 if( op==TK_INTERSECT ){
3693 addrEofB = addrEofA;
3694 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3695 }else{
3696 VdbeNoopComment((v, "eof-B subroutine"));
3697 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3698 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3699 sqlite3VdbeGoto(v, addrEofB);
3702 /* Generate code to handle the case of A<B
3704 VdbeNoopComment((v, "A-lt-B subroutine"));
3705 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3706 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3707 sqlite3VdbeGoto(v, labelCmpr);
3709 /* Generate code to handle the case of A==B
3711 if( op==TK_ALL ){
3712 addrAeqB = addrAltB;
3713 }else if( op==TK_INTERSECT ){
3714 addrAeqB = addrAltB;
3715 addrAltB++;
3716 }else{
3717 VdbeNoopComment((v, "A-eq-B subroutine"));
3718 addrAeqB =
3719 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3720 sqlite3VdbeGoto(v, labelCmpr);
3723 /* Generate code to handle the case of A>B
3725 VdbeNoopComment((v, "A-gt-B subroutine"));
3726 addrAgtB = sqlite3VdbeCurrentAddr(v);
3727 if( op==TK_ALL || op==TK_UNION ){
3728 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3730 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3731 sqlite3VdbeGoto(v, labelCmpr);
3733 /* This code runs once to initialize everything.
3735 sqlite3VdbeJumpHere(v, addr1);
3736 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3737 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3739 /* Implement the main merge loop
3741 sqlite3VdbeResolveLabel(v, labelCmpr);
3742 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
3743 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
3744 (char*)pKeyMerge, P4_KEYINFO);
3745 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3746 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
3748 /* Jump to the this point in order to terminate the query.
3750 sqlite3VdbeResolveLabel(v, labelEnd);
3752 /* Make arrangements to free the 2nd and subsequent arms of the compound
3753 ** after the parse has finished */
3754 if( pSplit->pPrior ){
3755 sqlite3ParserAddCleanup(pParse,
3756 (void(*)(sqlite3*,void*))sqlite3SelectDelete, pSplit->pPrior);
3758 pSplit->pPrior = pPrior;
3759 pPrior->pNext = pSplit;
3760 sqlite3ExprListDelete(db, pPrior->pOrderBy);
3761 pPrior->pOrderBy = 0;
3763 /*** TBD: Insert subroutine calls to close cursors on incomplete
3764 **** subqueries ****/
3765 ExplainQueryPlanPop(pParse);
3766 return pParse->nErr!=0;
3768 #endif
3770 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3772 /* An instance of the SubstContext object describes an substitution edit
3773 ** to be performed on a parse tree.
3775 ** All references to columns in table iTable are to be replaced by corresponding
3776 ** expressions in pEList.
3778 ** ## About "isOuterJoin":
3780 ** The isOuterJoin column indicates that the replacement will occur into a
3781 ** position in the parent that NULL-able due to an OUTER JOIN. Either the
3782 ** target slot in the parent is the right operand of a LEFT JOIN, or one of
3783 ** the left operands of a RIGHT JOIN. In either case, we need to potentially
3784 ** bypass the substituted expression with OP_IfNullRow.
3786 ** Suppose the original expression is an integer constant. Even though the table
3787 ** has the nullRow flag set, because the expression is an integer constant,
3788 ** it will not be NULLed out. So instead, we insert an OP_IfNullRow opcode
3789 ** that checks to see if the nullRow flag is set on the table. If the nullRow
3790 ** flag is set, then the value in the register is set to NULL and the original
3791 ** expression is bypassed. If the nullRow flag is not set, then the original
3792 ** expression runs to populate the register.
3794 ** Example where this is needed:
3796 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
3797 ** CREATE TABLE t2(x INT UNIQUE);
3799 ** SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x;
3801 ** When the subquery on the right side of the LEFT JOIN is flattened, we
3802 ** have to add OP_IfNullRow in front of the OP_Integer that implements the
3803 ** "m" value of the subquery so that a NULL will be loaded instead of 59
3804 ** when processing a non-matched row of the left.
3806 typedef struct SubstContext {
3807 Parse *pParse; /* The parsing context */
3808 int iTable; /* Replace references to this table */
3809 int iNewTable; /* New table number */
3810 int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
3811 ExprList *pEList; /* Replacement expressions */
3812 ExprList *pCList; /* Collation sequences for replacement expr */
3813 } SubstContext;
3815 /* Forward Declarations */
3816 static void substExprList(SubstContext*, ExprList*);
3817 static void substSelect(SubstContext*, Select*, int);
3820 ** Scan through the expression pExpr. Replace every reference to
3821 ** a column in table number iTable with a copy of the iColumn-th
3822 ** entry in pEList. (But leave references to the ROWID column
3823 ** unchanged.)
3825 ** This routine is part of the flattening procedure. A subquery
3826 ** whose result set is defined by pEList appears as entry in the
3827 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3828 ** FORM clause entry is iTable. This routine makes the necessary
3829 ** changes to pExpr so that it refers directly to the source table
3830 ** of the subquery rather the result set of the subquery.
3832 static Expr *substExpr(
3833 SubstContext *pSubst, /* Description of the substitution */
3834 Expr *pExpr /* Expr in which substitution occurs */
3836 if( pExpr==0 ) return 0;
3837 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)
3838 && pExpr->w.iJoin==pSubst->iTable
3840 testcase( ExprHasProperty(pExpr, EP_InnerON) );
3841 pExpr->w.iJoin = pSubst->iNewTable;
3843 if( pExpr->op==TK_COLUMN
3844 && pExpr->iTable==pSubst->iTable
3845 && !ExprHasProperty(pExpr, EP_FixedCol)
3847 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
3848 if( pExpr->iColumn<0 ){
3849 pExpr->op = TK_NULL;
3850 }else
3851 #endif
3853 Expr *pNew;
3854 int iColumn = pExpr->iColumn;
3855 Expr *pCopy = pSubst->pEList->a[iColumn].pExpr;
3856 Expr ifNullRow;
3857 assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
3858 assert( pExpr->pRight==0 );
3859 if( sqlite3ExprIsVector(pCopy) ){
3860 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
3861 }else{
3862 sqlite3 *db = pSubst->pParse->db;
3863 if( pSubst->isOuterJoin
3864 && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
3866 memset(&ifNullRow, 0, sizeof(ifNullRow));
3867 ifNullRow.op = TK_IF_NULL_ROW;
3868 ifNullRow.pLeft = pCopy;
3869 ifNullRow.iTable = pSubst->iNewTable;
3870 ifNullRow.iColumn = -99;
3871 ifNullRow.flags = EP_IfNullRow;
3872 pCopy = &ifNullRow;
3874 testcase( ExprHasProperty(pCopy, EP_Subquery) );
3875 pNew = sqlite3ExprDup(db, pCopy, 0);
3876 if( db->mallocFailed ){
3877 sqlite3ExprDelete(db, pNew);
3878 return pExpr;
3880 if( pSubst->isOuterJoin ){
3881 ExprSetProperty(pNew, EP_CanBeNull);
3883 if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){
3884 sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
3885 pExpr->flags & (EP_OuterON|EP_InnerON));
3887 sqlite3ExprDelete(db, pExpr);
3888 pExpr = pNew;
3889 if( pExpr->op==TK_TRUEFALSE ){
3890 pExpr->u.iValue = sqlite3ExprTruthValue(pExpr);
3891 pExpr->op = TK_INTEGER;
3892 ExprSetProperty(pExpr, EP_IntValue);
3895 /* Ensure that the expression now has an implicit collation sequence,
3896 ** just as it did when it was a column of a view or sub-query. */
3898 CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
3899 CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
3900 pSubst->pCList->a[iColumn].pExpr
3902 if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){
3903 pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
3904 (pColl ? pColl->zName : "BINARY")
3908 ExprClearProperty(pExpr, EP_Collate);
3911 }else{
3912 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
3913 pExpr->iTable = pSubst->iNewTable;
3915 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
3916 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
3917 if( ExprUseXSelect(pExpr) ){
3918 substSelect(pSubst, pExpr->x.pSelect, 1);
3919 }else{
3920 substExprList(pSubst, pExpr->x.pList);
3922 #ifndef SQLITE_OMIT_WINDOWFUNC
3923 if( ExprHasProperty(pExpr, EP_WinFunc) ){
3924 Window *pWin = pExpr->y.pWin;
3925 pWin->pFilter = substExpr(pSubst, pWin->pFilter);
3926 substExprList(pSubst, pWin->pPartition);
3927 substExprList(pSubst, pWin->pOrderBy);
3929 #endif
3931 return pExpr;
3933 static void substExprList(
3934 SubstContext *pSubst, /* Description of the substitution */
3935 ExprList *pList /* List to scan and in which to make substitutes */
3937 int i;
3938 if( pList==0 ) return;
3939 for(i=0; i<pList->nExpr; i++){
3940 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
3943 static void substSelect(
3944 SubstContext *pSubst, /* Description of the substitution */
3945 Select *p, /* SELECT statement in which to make substitutions */
3946 int doPrior /* Do substitutes on p->pPrior too */
3948 SrcList *pSrc;
3949 SrcItem *pItem;
3950 int i;
3951 if( !p ) return;
3953 substExprList(pSubst, p->pEList);
3954 substExprList(pSubst, p->pGroupBy);
3955 substExprList(pSubst, p->pOrderBy);
3956 p->pHaving = substExpr(pSubst, p->pHaving);
3957 p->pWhere = substExpr(pSubst, p->pWhere);
3958 pSrc = p->pSrc;
3959 assert( pSrc!=0 );
3960 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
3961 substSelect(pSubst, pItem->pSelect, 1);
3962 if( pItem->fg.isTabFunc ){
3963 substExprList(pSubst, pItem->u1.pFuncArg);
3966 }while( doPrior && (p = p->pPrior)!=0 );
3968 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3970 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3972 ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
3973 ** clause of that SELECT.
3975 ** This routine scans the entire SELECT statement and recomputes the
3976 ** pSrcItem->colUsed mask.
3978 static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
3979 SrcItem *pItem;
3980 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
3981 pItem = pWalker->u.pSrcItem;
3982 if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
3983 if( pExpr->iColumn<0 ) return WRC_Continue;
3984 pItem->colUsed |= sqlite3ExprColUsed(pExpr);
3985 return WRC_Continue;
3987 static void recomputeColumnsUsed(
3988 Select *pSelect, /* The complete SELECT statement */
3989 SrcItem *pSrcItem /* Which FROM clause item to recompute */
3991 Walker w;
3992 if( NEVER(pSrcItem->pTab==0) ) return;
3993 memset(&w, 0, sizeof(w));
3994 w.xExprCallback = recomputeColumnsUsedExpr;
3995 w.xSelectCallback = sqlite3SelectWalkNoop;
3996 w.u.pSrcItem = pSrcItem;
3997 pSrcItem->colUsed = 0;
3998 sqlite3WalkSelect(&w, pSelect);
4000 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4002 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4004 ** Assign new cursor numbers to each of the items in pSrc. For each
4005 ** new cursor number assigned, set an entry in the aCsrMap[] array
4006 ** to map the old cursor number to the new:
4008 ** aCsrMap[iOld+1] = iNew;
4010 ** The array is guaranteed by the caller to be large enough for all
4011 ** existing cursor numbers in pSrc. aCsrMap[0] is the array size.
4013 ** If pSrc contains any sub-selects, call this routine recursively
4014 ** on the FROM clause of each such sub-select, with iExcept set to -1.
4016 static void srclistRenumberCursors(
4017 Parse *pParse, /* Parse context */
4018 int *aCsrMap, /* Array to store cursor mappings in */
4019 SrcList *pSrc, /* FROM clause to renumber */
4020 int iExcept /* FROM clause item to skip */
4022 int i;
4023 SrcItem *pItem;
4024 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
4025 if( i!=iExcept ){
4026 Select *p;
4027 assert( pItem->iCursor < aCsrMap[0] );
4028 if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
4029 aCsrMap[pItem->iCursor+1] = pParse->nTab++;
4031 pItem->iCursor = aCsrMap[pItem->iCursor+1];
4032 for(p=pItem->pSelect; p; p=p->pPrior){
4033 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
4040 ** *piCursor is a cursor number. Change it if it needs to be mapped.
4042 static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
4043 int *aCsrMap = pWalker->u.aiCol;
4044 int iCsr = *piCursor;
4045 if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
4046 *piCursor = aCsrMap[iCsr+1];
4051 ** Expression walker callback used by renumberCursors() to update
4052 ** Expr objects to match newly assigned cursor numbers.
4054 static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
4055 int op = pExpr->op;
4056 if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
4057 renumberCursorDoMapping(pWalker, &pExpr->iTable);
4059 if( ExprHasProperty(pExpr, EP_OuterON) ){
4060 renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
4062 return WRC_Continue;
4066 ** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
4067 ** of the SELECT statement passed as the second argument, and to each
4068 ** cursor in the FROM clause of any FROM clause sub-selects, recursively.
4069 ** Except, do not assign a new cursor number to the iExcept'th element in
4070 ** the FROM clause of (*p). Update all expressions and other references
4071 ** to refer to the new cursor numbers.
4073 ** Argument aCsrMap is an array that may be used for temporary working
4074 ** space. Two guarantees are made by the caller:
4076 ** * the array is larger than the largest cursor number used within the
4077 ** select statement passed as an argument, and
4079 ** * the array entries for all cursor numbers that do *not* appear in
4080 ** FROM clauses of the select statement as described above are
4081 ** initialized to zero.
4083 static void renumberCursors(
4084 Parse *pParse, /* Parse context */
4085 Select *p, /* Select to renumber cursors within */
4086 int iExcept, /* FROM clause item to skip */
4087 int *aCsrMap /* Working space */
4089 Walker w;
4090 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
4091 memset(&w, 0, sizeof(w));
4092 w.u.aiCol = aCsrMap;
4093 w.xExprCallback = renumberCursorsCb;
4094 w.xSelectCallback = sqlite3SelectWalkNoop;
4095 sqlite3WalkSelect(&w, p);
4097 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4100 ** If pSel is not part of a compound SELECT, return a pointer to its
4101 ** expression list. Otherwise, return a pointer to the expression list
4102 ** of the leftmost SELECT in the compound.
4104 static ExprList *findLeftmostExprlist(Select *pSel){
4105 while( pSel->pPrior ){
4106 pSel = pSel->pPrior;
4108 return pSel->pEList;
4112 ** Return true if any of the result-set columns in the compound query
4113 ** have incompatible affinities on one or more arms of the compound.
4115 static int compoundHasDifferentAffinities(Select *p){
4116 int ii;
4117 ExprList *pList;
4118 assert( p!=0 );
4119 assert( p->pEList!=0 );
4120 assert( p->pPrior!=0 );
4121 pList = p->pEList;
4122 for(ii=0; ii<pList->nExpr; ii++){
4123 char aff;
4124 Select *pSub1;
4125 assert( pList->a[ii].pExpr!=0 );
4126 aff = sqlite3ExprAffinity(pList->a[ii].pExpr);
4127 for(pSub1=p->pPrior; pSub1; pSub1=pSub1->pPrior){
4128 assert( pSub1->pEList!=0 );
4129 assert( pSub1->pEList->nExpr>ii );
4130 assert( pSub1->pEList->a[ii].pExpr!=0 );
4131 if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
4132 return 1;
4136 return 0;
4139 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4141 ** This routine attempts to flatten subqueries as a performance optimization.
4142 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
4144 ** To understand the concept of flattening, consider the following
4145 ** query:
4147 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
4149 ** The default way of implementing this query is to execute the
4150 ** subquery first and store the results in a temporary table, then
4151 ** run the outer query on that temporary table. This requires two
4152 ** passes over the data. Furthermore, because the temporary table
4153 ** has no indices, the WHERE clause on the outer query cannot be
4154 ** optimized.
4156 ** This routine attempts to rewrite queries such as the above into
4157 ** a single flat select, like this:
4159 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
4161 ** The code generated for this simplification gives the same result
4162 ** but only has to scan the data once. And because indices might
4163 ** exist on the table t1, a complete scan of the data might be
4164 ** avoided.
4166 ** Flattening is subject to the following constraints:
4168 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4169 ** The subquery and the outer query cannot both be aggregates.
4171 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4172 ** (2) If the subquery is an aggregate then
4173 ** (2a) the outer query must not be a join and
4174 ** (2b) the outer query must not use subqueries
4175 ** other than the one FROM-clause subquery that is a candidate
4176 ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
4177 ** from 2015-02-09.)
4179 ** (3) If the subquery is the right operand of a LEFT JOIN then
4180 ** (3a) the subquery may not be a join and
4181 ** (3b) the FROM clause of the subquery may not contain a virtual
4182 ** table and
4183 ** (**) Was: "The outer query may not have a GROUP BY." This case
4184 ** is now managed correctly
4185 ** (3d) the outer query may not be DISTINCT.
4186 ** See also (26) for restrictions on RIGHT JOIN.
4188 ** (4) The subquery can not be DISTINCT.
4190 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
4191 ** sub-queries that were excluded from this optimization. Restriction
4192 ** (4) has since been expanded to exclude all DISTINCT subqueries.
4194 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4195 ** If the subquery is aggregate, the outer query may not be DISTINCT.
4197 ** (7) The subquery must have a FROM clause. TODO: For subqueries without
4198 ** A FROM clause, consider adding a FROM clause with the special
4199 ** table sqlite_once that consists of a single row containing a
4200 ** single NULL.
4202 ** (8) If the subquery uses LIMIT then the outer query may not be a join.
4204 ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
4206 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
4207 ** accidently carried the comment forward until 2014-09-15. Original
4208 ** constraint: "If the subquery is aggregate then the outer query
4209 ** may not use LIMIT."
4211 ** (11) The subquery and the outer query may not both have ORDER BY clauses.
4213 ** (**) Not implemented. Subsumed into restriction (3). Was previously
4214 ** a separate restriction deriving from ticket #350.
4216 ** (13) The subquery and outer query may not both use LIMIT.
4218 ** (14) The subquery may not use OFFSET.
4220 ** (15) If the outer query is part of a compound select, then the
4221 ** subquery may not use LIMIT.
4222 ** (See ticket #2339 and ticket [02a8e81d44]).
4224 ** (16) If the outer query is aggregate, then the subquery may not
4225 ** use ORDER BY. (Ticket #2942) This used to not matter
4226 ** until we introduced the group_concat() function.
4228 ** (17) If the subquery is a compound select, then
4229 ** (17a) all compound operators must be a UNION ALL, and
4230 ** (17b) no terms within the subquery compound may be aggregate
4231 ** or DISTINCT, and
4232 ** (17c) every term within the subquery compound must have a FROM clause
4233 ** (17d) the outer query may not be
4234 ** (17d1) aggregate, or
4235 ** (17d2) DISTINCT
4236 ** (17e) the subquery may not contain window functions, and
4237 ** (17f) the subquery must not be the RHS of a LEFT JOIN.
4238 ** (17g) either the subquery is the first element of the outer
4239 ** query or there are no RIGHT or FULL JOINs in any arm
4240 ** of the subquery. (This is a duplicate of condition (27b).)
4241 ** (17h) The corresponding result set expressions in all arms of the
4242 ** compound must have the same affinity.
4244 ** The parent and sub-query may contain WHERE clauses. Subject to
4245 ** rules (11), (13) and (14), they may also contain ORDER BY,
4246 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
4247 ** operator other than UNION ALL because all the other compound
4248 ** operators have an implied DISTINCT which is disallowed by
4249 ** restriction (4).
4251 ** Also, each component of the sub-query must return the same number
4252 ** of result columns. This is actually a requirement for any compound
4253 ** SELECT statement, but all the code here does is make sure that no
4254 ** such (illegal) sub-query is flattened. The caller will detect the
4255 ** syntax error and return a detailed message.
4257 ** (18) If the sub-query is a compound select, then all terms of the
4258 ** ORDER BY clause of the parent must be copies of a term returned
4259 ** by the parent query.
4261 ** (19) If the subquery uses LIMIT then the outer query may not
4262 ** have a WHERE clause.
4264 ** (20) If the sub-query is a compound select, then it must not use
4265 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
4266 ** somewhat by saying that the terms of the ORDER BY clause must
4267 ** appear as unmodified result columns in the outer query. But we
4268 ** have other optimizations in mind to deal with that case.
4270 ** (21) If the subquery uses LIMIT then the outer query may not be
4271 ** DISTINCT. (See ticket [752e1646fc]).
4273 ** (22) The subquery may not be a recursive CTE.
4275 ** (23) If the outer query is a recursive CTE, then the sub-query may not be
4276 ** a compound query. This restriction is because transforming the
4277 ** parent to a compound query confuses the code that handles
4278 ** recursive queries in multiSelect().
4280 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4281 ** The subquery may not be an aggregate that uses the built-in min() or
4282 ** or max() functions. (Without this restriction, a query like:
4283 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
4284 ** return the value X for which Y was maximal.)
4286 ** (25) If either the subquery or the parent query contains a window
4287 ** function in the select list or ORDER BY clause, flattening
4288 ** is not attempted.
4290 ** (26) The subquery may not be the right operand of a RIGHT JOIN.
4291 ** See also (3) for restrictions on LEFT JOIN.
4293 ** (27) The subquery may not contain a FULL or RIGHT JOIN unless it
4294 ** is the first element of the parent query. Two subcases:
4295 ** (27a) the subquery is not a compound query.
4296 ** (27b) the subquery is a compound query and the RIGHT JOIN occurs
4297 ** in any arm of the compound query. (See also (17g).)
4299 ** (28) The subquery is not a MATERIALIZED CTE.
4302 ** In this routine, the "p" parameter is a pointer to the outer query.
4303 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
4304 ** uses aggregates.
4306 ** If flattening is not attempted, this routine is a no-op and returns 0.
4307 ** If flattening is attempted this routine returns 1.
4309 ** All of the expression analysis must occur on both the outer query and
4310 ** the subquery before this routine runs.
4312 static int flattenSubquery(
4313 Parse *pParse, /* Parsing context */
4314 Select *p, /* The parent or outer SELECT statement */
4315 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
4316 int isAgg /* True if outer SELECT uses aggregate functions */
4318 const char *zSavedAuthContext = pParse->zAuthContext;
4319 Select *pParent; /* Current UNION ALL term of the other query */
4320 Select *pSub; /* The inner query or "subquery" */
4321 Select *pSub1; /* Pointer to the rightmost select in sub-query */
4322 SrcList *pSrc; /* The FROM clause of the outer query */
4323 SrcList *pSubSrc; /* The FROM clause of the subquery */
4324 int iParent; /* VDBE cursor number of the pSub result set temp table */
4325 int iNewParent = -1;/* Replacement table for iParent */
4326 int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
4327 int i; /* Loop counter */
4328 Expr *pWhere; /* The WHERE clause */
4329 SrcItem *pSubitem; /* The subquery */
4330 sqlite3 *db = pParse->db;
4331 Walker w; /* Walker to persist agginfo data */
4332 int *aCsrMap = 0;
4334 /* Check to see if flattening is permitted. Return 0 if not.
4336 assert( p!=0 );
4337 assert( p->pPrior==0 );
4338 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
4339 pSrc = p->pSrc;
4340 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
4341 pSubitem = &pSrc->a[iFrom];
4342 iParent = pSubitem->iCursor;
4343 pSub = pSubitem->pSelect;
4344 assert( pSub!=0 );
4346 #ifndef SQLITE_OMIT_WINDOWFUNC
4347 if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
4348 #endif
4350 pSubSrc = pSub->pSrc;
4351 assert( pSubSrc );
4352 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
4353 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
4354 ** because they could be computed at compile-time. But when LIMIT and OFFSET
4355 ** became arbitrary expressions, we were forced to add restrictions (13)
4356 ** and (14). */
4357 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
4358 if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
4359 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
4360 return 0; /* Restriction (15) */
4362 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
4363 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
4364 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
4365 return 0; /* Restrictions (8)(9) */
4367 if( p->pOrderBy && pSub->pOrderBy ){
4368 return 0; /* Restriction (11) */
4370 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
4371 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
4372 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
4373 return 0; /* Restriction (21) */
4375 if( pSub->selFlags & (SF_Recursive) ){
4376 return 0; /* Restrictions (22) */
4380 ** If the subquery is the right operand of a LEFT JOIN, then the
4381 ** subquery may not be a join itself (3a). Example of why this is not
4382 ** allowed:
4384 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
4386 ** If we flatten the above, we would get
4388 ** (t1 LEFT OUTER JOIN t2) JOIN t3
4390 ** which is not at all the same thing.
4392 ** See also tickets #306, #350, and #3300.
4394 if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
4395 if( pSubSrc->nSrc>1 /* (3a) */
4396 || IsVirtual(pSubSrc->a[0].pTab) /* (3b) */
4397 || (p->selFlags & SF_Distinct)!=0 /* (3d) */
4398 || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */
4400 return 0;
4402 isOuterJoin = 1;
4405 assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */
4406 if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4407 return 0; /* Restriction (27a) */
4409 if( pSubitem->fg.isCte && pSubitem->u2.pCteUse->eM10d==M10d_Yes ){
4410 return 0; /* (28) */
4413 /* Restriction (17): If the sub-query is a compound SELECT, then it must
4414 ** use only the UNION ALL operator. And none of the simple select queries
4415 ** that make up the compound SELECT are allowed to be aggregate or distinct
4416 ** queries.
4418 if( pSub->pPrior ){
4419 int ii;
4420 if( pSub->pOrderBy ){
4421 return 0; /* Restriction (20) */
4423 if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
4424 return 0; /* (17d1), (17d2), or (17f) */
4426 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
4427 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
4428 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
4429 assert( pSub->pSrc!=0 );
4430 assert( (pSub->selFlags & SF_Recursive)==0 );
4431 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
4432 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
4433 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
4434 || pSub1->pSrc->nSrc<1 /* (17c) */
4435 #ifndef SQLITE_OMIT_WINDOWFUNC
4436 || pSub1->pWin /* (17e) */
4437 #endif
4439 return 0;
4441 if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4442 /* Without this restriction, the JT_LTORJ flag would end up being
4443 ** omitted on left-hand tables of the right join that is being
4444 ** flattened. */
4445 return 0; /* Restrictions (17g), (27b) */
4447 testcase( pSub1->pSrc->nSrc>1 );
4450 /* Restriction (18). */
4451 if( p->pOrderBy ){
4452 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
4453 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
4457 /* Restriction (23) */
4458 if( (p->selFlags & SF_Recursive) ) return 0;
4460 /* Restriction (17h) */
4461 if( compoundHasDifferentAffinities(pSub) ) return 0;
4463 if( pSrc->nSrc>1 ){
4464 if( pParse->nSelect>500 ) return 0;
4465 if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
4466 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
4467 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
4471 /***** If we reach this point, flattening is permitted. *****/
4472 TREETRACE(0x4,pParse,p,("flatten %u.%p from term %d\n",
4473 pSub->selId, pSub, iFrom));
4475 /* Authorize the subquery */
4476 pParse->zAuthContext = pSubitem->zName;
4477 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
4478 testcase( i==SQLITE_DENY );
4479 pParse->zAuthContext = zSavedAuthContext;
4481 /* Delete the transient structures associated with thesubquery */
4482 pSub1 = pSubitem->pSelect;
4483 sqlite3DbFree(db, pSubitem->zDatabase);
4484 sqlite3DbFree(db, pSubitem->zName);
4485 sqlite3DbFree(db, pSubitem->zAlias);
4486 pSubitem->zDatabase = 0;
4487 pSubitem->zName = 0;
4488 pSubitem->zAlias = 0;
4489 pSubitem->pSelect = 0;
4490 assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
4492 /* If the sub-query is a compound SELECT statement, then (by restrictions
4493 ** 17 and 18 above) it must be a UNION ALL and the parent query must
4494 ** be of the form:
4496 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
4498 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
4499 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
4500 ** OFFSET clauses and joins them to the left-hand-side of the original
4501 ** using UNION ALL operators. In this case N is the number of simple
4502 ** select statements in the compound sub-query.
4504 ** Example:
4506 ** SELECT a+1 FROM (
4507 ** SELECT x FROM tab
4508 ** UNION ALL
4509 ** SELECT y FROM tab
4510 ** UNION ALL
4511 ** SELECT abs(z*2) FROM tab2
4512 ** ) WHERE a!=5 ORDER BY 1
4514 ** Transformed into:
4516 ** SELECT x+1 FROM tab WHERE x+1!=5
4517 ** UNION ALL
4518 ** SELECT y+1 FROM tab WHERE y+1!=5
4519 ** UNION ALL
4520 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
4521 ** ORDER BY 1
4523 ** We call this the "compound-subquery flattening".
4525 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
4526 Select *pNew;
4527 ExprList *pOrderBy = p->pOrderBy;
4528 Expr *pLimit = p->pLimit;
4529 Select *pPrior = p->pPrior;
4530 Table *pItemTab = pSubitem->pTab;
4531 pSubitem->pTab = 0;
4532 p->pOrderBy = 0;
4533 p->pPrior = 0;
4534 p->pLimit = 0;
4535 pNew = sqlite3SelectDup(db, p, 0);
4536 p->pLimit = pLimit;
4537 p->pOrderBy = pOrderBy;
4538 p->op = TK_ALL;
4539 pSubitem->pTab = pItemTab;
4540 if( pNew==0 ){
4541 p->pPrior = pPrior;
4542 }else{
4543 pNew->selId = ++pParse->nSelect;
4544 if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
4545 renumberCursors(pParse, pNew, iFrom, aCsrMap);
4547 pNew->pPrior = pPrior;
4548 if( pPrior ) pPrior->pNext = pNew;
4549 pNew->pNext = p;
4550 p->pPrior = pNew;
4551 TREETRACE(0x4,pParse,p,("compound-subquery flattener"
4552 " creates %u as peer\n",pNew->selId));
4554 assert( pSubitem->pSelect==0 );
4556 sqlite3DbFree(db, aCsrMap);
4557 if( db->mallocFailed ){
4558 pSubitem->pSelect = pSub1;
4559 return 1;
4562 /* Defer deleting the Table object associated with the
4563 ** subquery until code generation is
4564 ** complete, since there may still exist Expr.pTab entries that
4565 ** refer to the subquery even after flattening. Ticket #3346.
4567 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
4569 if( ALWAYS(pSubitem->pTab!=0) ){
4570 Table *pTabToDel = pSubitem->pTab;
4571 if( pTabToDel->nTabRef==1 ){
4572 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4573 sqlite3ParserAddCleanup(pToplevel,
4574 (void(*)(sqlite3*,void*))sqlite3DeleteTable,
4575 pTabToDel);
4576 testcase( pToplevel->earlyCleanup );
4577 }else{
4578 pTabToDel->nTabRef--;
4580 pSubitem->pTab = 0;
4583 /* The following loop runs once for each term in a compound-subquery
4584 ** flattening (as described above). If we are doing a different kind
4585 ** of flattening - a flattening other than a compound-subquery flattening -
4586 ** then this loop only runs once.
4588 ** This loop moves all of the FROM elements of the subquery into the
4589 ** the FROM clause of the outer query. Before doing this, remember
4590 ** the cursor number for the original outer query FROM element in
4591 ** iParent. The iParent cursor will never be used. Subsequent code
4592 ** will scan expressions looking for iParent references and replace
4593 ** those references with expressions that resolve to the subquery FROM
4594 ** elements we are now copying in.
4596 pSub = pSub1;
4597 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
4598 int nSubSrc;
4599 u8 jointype = 0;
4600 u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
4601 assert( pSub!=0 );
4602 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
4603 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
4604 pSrc = pParent->pSrc; /* FROM clause of the outer query */
4606 if( pParent==p ){
4607 jointype = pSubitem->fg.jointype; /* First time through the loop */
4610 /* The subquery uses a single slot of the FROM clause of the outer
4611 ** query. If the subquery has more than one element in its FROM clause,
4612 ** then expand the outer query to make space for it to hold all elements
4613 ** of the subquery.
4615 ** Example:
4617 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
4619 ** The outer query has 3 slots in its FROM clause. One slot of the
4620 ** outer query (the middle slot) is used by the subquery. The next
4621 ** block of code will expand the outer query FROM clause to 4 slots.
4622 ** The middle slot is expanded to two slots in order to make space
4623 ** for the two elements in the FROM clause of the subquery.
4625 if( nSubSrc>1 ){
4626 pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
4627 if( pSrc==0 ) break;
4628 pParent->pSrc = pSrc;
4631 /* Transfer the FROM clause terms from the subquery into the
4632 ** outer query.
4634 for(i=0; i<nSubSrc; i++){
4635 SrcItem *pItem = &pSrc->a[i+iFrom];
4636 if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
4637 assert( pItem->fg.isTabFunc==0 );
4638 *pItem = pSubSrc->a[i];
4639 pItem->fg.jointype |= ltorj;
4640 iNewParent = pSubSrc->a[i].iCursor;
4641 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
4643 pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
4644 pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
4646 /* Now begin substituting subquery result set expressions for
4647 ** references to the iParent in the outer query.
4649 ** Example:
4651 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
4652 ** \ \_____________ subquery __________/ /
4653 ** \_____________________ outer query ______________________________/
4655 ** We look at every expression in the outer query and every place we see
4656 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
4658 if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
4659 /* At this point, any non-zero iOrderByCol values indicate that the
4660 ** ORDER BY column expression is identical to the iOrderByCol'th
4661 ** expression returned by SELECT statement pSub. Since these values
4662 ** do not necessarily correspond to columns in SELECT statement pParent,
4663 ** zero them before transfering the ORDER BY clause.
4665 ** Not doing this may cause an error if a subsequent call to this
4666 ** function attempts to flatten a compound sub-query into pParent
4667 ** (the only way this can happen is if the compound sub-query is
4668 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
4669 ExprList *pOrderBy = pSub->pOrderBy;
4670 for(i=0; i<pOrderBy->nExpr; i++){
4671 pOrderBy->a[i].u.x.iOrderByCol = 0;
4673 assert( pParent->pOrderBy==0 );
4674 pParent->pOrderBy = pOrderBy;
4675 pSub->pOrderBy = 0;
4677 pWhere = pSub->pWhere;
4678 pSub->pWhere = 0;
4679 if( isOuterJoin>0 ){
4680 sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON);
4682 if( pWhere ){
4683 if( pParent->pWhere ){
4684 pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
4685 }else{
4686 pParent->pWhere = pWhere;
4689 if( db->mallocFailed==0 ){
4690 SubstContext x;
4691 x.pParse = pParse;
4692 x.iTable = iParent;
4693 x.iNewTable = iNewParent;
4694 x.isOuterJoin = isOuterJoin;
4695 x.pEList = pSub->pEList;
4696 x.pCList = findLeftmostExprlist(pSub);
4697 substSelect(&x, pParent, 0);
4700 /* The flattened query is a compound if either the inner or the
4701 ** outer query is a compound. */
4702 pParent->selFlags |= pSub->selFlags & SF_Compound;
4703 assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
4706 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
4708 ** One is tempted to try to add a and b to combine the limits. But this
4709 ** does not work if either limit is negative.
4711 if( pSub->pLimit ){
4712 pParent->pLimit = pSub->pLimit;
4713 pSub->pLimit = 0;
4716 /* Recompute the SrcItem.colUsed masks for the flattened
4717 ** tables. */
4718 for(i=0; i<nSubSrc; i++){
4719 recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
4723 /* Finially, delete what is left of the subquery and return
4724 ** success.
4726 sqlite3AggInfoPersistWalkerInit(&w, pParse);
4727 sqlite3WalkSelect(&w,pSub1);
4728 sqlite3SelectDelete(db, pSub1);
4730 #if TREETRACE_ENABLED
4731 if( sqlite3TreeTrace & 0x4 ){
4732 TREETRACE(0x4,pParse,p,("After flattening:\n"));
4733 sqlite3TreeViewSelect(0, p, 0);
4735 #endif
4737 return 1;
4739 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4742 ** A structure to keep track of all of the column values that are fixed to
4743 ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
4745 typedef struct WhereConst WhereConst;
4746 struct WhereConst {
4747 Parse *pParse; /* Parsing context */
4748 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
4749 int nConst; /* Number for COLUMN=CONSTANT terms */
4750 int nChng; /* Number of times a constant is propagated */
4751 int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
4752 u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
4753 ** Either EP_OuterON or EP_InnerON|EP_OuterON */
4754 Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
4758 ** Add a new entry to the pConst object. Except, do not add duplicate
4759 ** pColumn entires. Also, do not add if doing so would not be appropriate.
4761 ** The caller guarantees the pColumn is a column and pValue is a constant.
4762 ** This routine has to do some additional checks before completing the
4763 ** insert.
4765 static void constInsert(
4766 WhereConst *pConst, /* The WhereConst into which we are inserting */
4767 Expr *pColumn, /* The COLUMN part of the constraint */
4768 Expr *pValue, /* The VALUE part of the constraint */
4769 Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
4771 int i;
4772 assert( pColumn->op==TK_COLUMN );
4773 assert( sqlite3ExprIsConstant(pValue) );
4775 if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
4776 if( sqlite3ExprAffinity(pValue)!=0 ) return;
4777 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
4778 return;
4781 /* 2018-10-25 ticket [cf5ed20f]
4782 ** Make sure the same pColumn is not inserted more than once */
4783 for(i=0; i<pConst->nConst; i++){
4784 const Expr *pE2 = pConst->apExpr[i*2];
4785 assert( pE2->op==TK_COLUMN );
4786 if( pE2->iTable==pColumn->iTable
4787 && pE2->iColumn==pColumn->iColumn
4789 return; /* Already present. Return without doing anything. */
4792 if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4793 pConst->bHasAffBlob = 1;
4796 pConst->nConst++;
4797 pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
4798 pConst->nConst*2*sizeof(Expr*));
4799 if( pConst->apExpr==0 ){
4800 pConst->nConst = 0;
4801 }else{
4802 pConst->apExpr[pConst->nConst*2-2] = pColumn;
4803 pConst->apExpr[pConst->nConst*2-1] = pValue;
4808 ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
4809 ** is a constant expression and where the term must be true because it
4810 ** is part of the AND-connected terms of the expression. For each term
4811 ** found, add it to the pConst structure.
4813 static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
4814 Expr *pRight, *pLeft;
4815 if( NEVER(pExpr==0) ) return;
4816 if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
4817 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4818 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4819 return;
4821 if( pExpr->op==TK_AND ){
4822 findConstInWhere(pConst, pExpr->pRight);
4823 findConstInWhere(pConst, pExpr->pLeft);
4824 return;
4826 if( pExpr->op!=TK_EQ ) return;
4827 pRight = pExpr->pRight;
4828 pLeft = pExpr->pLeft;
4829 assert( pRight!=0 );
4830 assert( pLeft!=0 );
4831 if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
4832 constInsert(pConst,pRight,pLeft,pExpr);
4834 if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
4835 constInsert(pConst,pLeft,pRight,pExpr);
4840 ** This is a helper function for Walker callback propagateConstantExprRewrite().
4842 ** Argument pExpr is a candidate expression to be replaced by a value. If
4843 ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
4844 ** then overwrite it with the corresponding value. Except, do not do so
4845 ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
4846 ** is SQLITE_AFF_BLOB.
4848 static int propagateConstantExprRewriteOne(
4849 WhereConst *pConst,
4850 Expr *pExpr,
4851 int bIgnoreAffBlob
4853 int i;
4854 if( pConst->pOomFault[0] ) return WRC_Prune;
4855 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
4856 if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
4857 testcase( ExprHasProperty(pExpr, EP_FixedCol) );
4858 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4859 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4860 return WRC_Continue;
4862 for(i=0; i<pConst->nConst; i++){
4863 Expr *pColumn = pConst->apExpr[i*2];
4864 if( pColumn==pExpr ) continue;
4865 if( pColumn->iTable!=pExpr->iTable ) continue;
4866 if( pColumn->iColumn!=pExpr->iColumn ) continue;
4867 if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4868 break;
4870 /* A match is found. Add the EP_FixedCol property */
4871 pConst->nChng++;
4872 ExprClearProperty(pExpr, EP_Leaf);
4873 ExprSetProperty(pExpr, EP_FixedCol);
4874 assert( pExpr->pLeft==0 );
4875 pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
4876 if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
4877 break;
4879 return WRC_Prune;
4883 ** This is a Walker expression callback. pExpr is a node from the WHERE
4884 ** clause of a SELECT statement. This function examines pExpr to see if
4885 ** any substitutions based on the contents of pWalker->u.pConst should
4886 ** be made to pExpr or its immediate children.
4888 ** A substitution is made if:
4890 ** + pExpr is a column with an affinity other than BLOB that matches
4891 ** one of the columns in pWalker->u.pConst, or
4893 ** + pExpr is a binary comparison operator (=, <=, >=, <, >) that
4894 ** uses an affinity other than TEXT and one of its immediate
4895 ** children is a column that matches one of the columns in
4896 ** pWalker->u.pConst.
4898 static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
4899 WhereConst *pConst = pWalker->u.pConst;
4900 assert( TK_GT==TK_EQ+1 );
4901 assert( TK_LE==TK_EQ+2 );
4902 assert( TK_LT==TK_EQ+3 );
4903 assert( TK_GE==TK_EQ+4 );
4904 if( pConst->bHasAffBlob ){
4905 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
4906 || pExpr->op==TK_IS
4908 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
4909 if( pConst->pOomFault[0] ) return WRC_Prune;
4910 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
4911 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
4915 return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
4919 ** The WHERE-clause constant propagation optimization.
4921 ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
4922 ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
4923 ** part of a ON clause from a LEFT JOIN, then throughout the query
4924 ** replace all other occurrences of COLUMN with CONSTANT.
4926 ** For example, the query:
4928 ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
4930 ** Is transformed into
4932 ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
4934 ** Return true if any transformations where made and false if not.
4936 ** Implementation note: Constant propagation is tricky due to affinity
4937 ** and collating sequence interactions. Consider this example:
4939 ** CREATE TABLE t1(a INT,b TEXT);
4940 ** INSERT INTO t1 VALUES(123,'0123');
4941 ** SELECT * FROM t1 WHERE a=123 AND b=a;
4942 ** SELECT * FROM t1 WHERE a=123 AND b=123;
4944 ** The two SELECT statements above should return different answers. b=a
4945 ** is alway true because the comparison uses numeric affinity, but b=123
4946 ** is false because it uses text affinity and '0123' is not the same as '123'.
4947 ** To work around this, the expression tree is not actually changed from
4948 ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
4949 ** and the "123" value is hung off of the pLeft pointer. Code generator
4950 ** routines know to generate the constant "123" instead of looking up the
4951 ** column value. Also, to avoid collation problems, this optimization is
4952 ** only attempted if the "a=123" term uses the default BINARY collation.
4954 ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
4956 ** CREATE TABLE t1(x);
4957 ** INSERT INTO t1 VALUES(10.0);
4958 ** SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
4960 ** The query should return no rows, because the t1.x value is '10.0' not '10'
4961 ** and '10.0' is not LIKE '10'. But if we are not careful, the first WHERE
4962 ** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
4963 ** resulting in a false positive. To avoid this, constant propagation for
4964 ** columns with BLOB affinity is only allowed if the constant is used with
4965 ** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
4966 ** type conversions to occur. See logic associated with the bHasAffBlob flag
4967 ** for details.
4969 static int propagateConstants(
4970 Parse *pParse, /* The parsing context */
4971 Select *p /* The query in which to propagate constants */
4973 WhereConst x;
4974 Walker w;
4975 int nChng = 0;
4976 x.pParse = pParse;
4977 x.pOomFault = &pParse->db->mallocFailed;
4979 x.nConst = 0;
4980 x.nChng = 0;
4981 x.apExpr = 0;
4982 x.bHasAffBlob = 0;
4983 if( ALWAYS(p->pSrc!=0)
4984 && p->pSrc->nSrc>0
4985 && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
4987 /* Do not propagate constants on any ON clause if there is a
4988 ** RIGHT JOIN anywhere in the query */
4989 x.mExcludeOn = EP_InnerON | EP_OuterON;
4990 }else{
4991 /* Do not propagate constants through the ON clause of a LEFT JOIN */
4992 x.mExcludeOn = EP_OuterON;
4994 findConstInWhere(&x, p->pWhere);
4995 if( x.nConst ){
4996 memset(&w, 0, sizeof(w));
4997 w.pParse = pParse;
4998 w.xExprCallback = propagateConstantExprRewrite;
4999 w.xSelectCallback = sqlite3SelectWalkNoop;
5000 w.xSelectCallback2 = 0;
5001 w.walkerDepth = 0;
5002 w.u.pConst = &x;
5003 sqlite3WalkExpr(&w, p->pWhere);
5004 sqlite3DbFree(x.pParse->db, x.apExpr);
5005 nChng += x.nChng;
5007 }while( x.nChng );
5008 return nChng;
5011 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5012 # if !defined(SQLITE_OMIT_WINDOWFUNC)
5014 ** This function is called to determine whether or not it is safe to
5015 ** push WHERE clause expression pExpr down to FROM clause sub-query
5016 ** pSubq, which contains at least one window function. Return 1
5017 ** if it is safe and the expression should be pushed down, or 0
5018 ** otherwise.
5020 ** It is only safe to push the expression down if it consists only
5021 ** of constants and copies of expressions that appear in the PARTITION
5022 ** BY clause of all window function used by the sub-query. It is safe
5023 ** to filter out entire partitions, but not rows within partitions, as
5024 ** this may change the results of the window functions.
5026 ** At the time this function is called it is guaranteed that
5028 ** * the sub-query uses only one distinct window frame, and
5029 ** * that the window frame has a PARTITION BY clase.
5031 static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
5032 assert( pSubq->pWin->pPartition );
5033 assert( (pSubq->selFlags & SF_MultiPart)==0 );
5034 assert( pSubq->pPrior==0 );
5035 return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
5037 # endif /* SQLITE_OMIT_WINDOWFUNC */
5038 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5040 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5042 ** Make copies of relevant WHERE clause terms of the outer query into
5043 ** the WHERE clause of subquery. Example:
5045 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
5047 ** Transformed into:
5049 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
5050 ** WHERE x=5 AND y=10;
5052 ** The hope is that the terms added to the inner query will make it more
5053 ** efficient.
5055 ** Do not attempt this optimization if:
5057 ** (1) (** This restriction was removed on 2017-09-29. We used to
5058 ** disallow this optimization for aggregate subqueries, but now
5059 ** it is allowed by putting the extra terms on the HAVING clause.
5060 ** The added HAVING clause is pointless if the subquery lacks
5061 ** a GROUP BY clause. But such a HAVING clause is also harmless
5062 ** so there does not appear to be any reason to add extra logic
5063 ** to suppress it. **)
5065 ** (2) The inner query is the recursive part of a common table expression.
5067 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
5068 ** clause would change the meaning of the LIMIT).
5070 ** (4) The inner query is the right operand of a LEFT JOIN and the
5071 ** expression to be pushed down does not come from the ON clause
5072 ** on that LEFT JOIN.
5074 ** (5) The WHERE clause expression originates in the ON or USING clause
5075 ** of a LEFT JOIN where iCursor is not the right-hand table of that
5076 ** left join. An example:
5078 ** SELECT *
5079 ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
5080 ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
5081 ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
5083 ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
5084 ** But if the (b2=2) term were to be pushed down into the bb subquery,
5085 ** then the (1,1,NULL) row would be suppressed.
5087 ** (6) Window functions make things tricky as changes to the WHERE clause
5088 ** of the inner query could change the window over which window
5089 ** functions are calculated. Therefore, do not attempt the optimization
5090 ** if:
5092 ** (6a) The inner query uses multiple incompatible window partitions.
5094 ** (6b) The inner query is a compound and uses window-functions.
5096 ** (6c) The WHERE clause does not consist entirely of constants and
5097 ** copies of expressions found in the PARTITION BY clause of
5098 ** all window-functions used by the sub-query. It is safe to
5099 ** filter out entire partitions, as this does not change the
5100 ** window over which any window-function is calculated.
5102 ** (7) The inner query is a Common Table Expression (CTE) that should
5103 ** be materialized. (This restriction is implemented in the calling
5104 ** routine.)
5106 ** (8) If the subquery is a compound that uses UNION, INTERSECT,
5107 ** or EXCEPT, then all of the result set columns for all arms of
5108 ** the compound must use the BINARY collating sequence.
5110 ** (9) All three of the following are true:
5112 ** (9a) The WHERE clause expression originates in the ON or USING clause
5113 ** of a join (either an INNER or an OUTER join), and
5115 ** (9b) The subquery is to the right of the ON/USING clause
5117 ** (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
5118 ** clause and the subquery.
5120 ** Without this restriction, the push-down optimization might move
5121 ** the ON/USING filter expression from the left side of a RIGHT JOIN
5122 ** over to the right side, which leads to incorrect answers. See
5123 ** also restriction (6) in sqlite3ExprIsSingleTableConstraint().
5125 ** (10) The inner query is not the right-hand table of a RIGHT JOIN.
5127 ** (11) The subquery is not a VALUES clause
5129 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
5130 ** terms are duplicated into the subquery.
5132 static int pushDownWhereTerms(
5133 Parse *pParse, /* Parse context (for malloc() and error reporting) */
5134 Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
5135 Expr *pWhere, /* The WHERE clause of the outer query */
5136 SrcList *pSrcList, /* The complete from clause of the outer query */
5137 int iSrc /* Which FROM clause term to try to push into */
5139 Expr *pNew;
5140 SrcItem *pSrc; /* The subquery FROM term into which WHERE is pushed */
5141 int nChng = 0;
5142 pSrc = &pSrcList->a[iSrc];
5143 if( pWhere==0 ) return 0;
5144 if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
5145 return 0; /* restrictions (2) and (11) */
5147 if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
5148 return 0; /* restrictions (10) */
5151 if( pSubq->pPrior ){
5152 Select *pSel;
5153 int notUnionAll = 0;
5154 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5155 u8 op = pSel->op;
5156 assert( op==TK_ALL || op==TK_SELECT
5157 || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
5158 if( op!=TK_ALL && op!=TK_SELECT ){
5159 notUnionAll = 1;
5161 #ifndef SQLITE_OMIT_WINDOWFUNC
5162 if( pSel->pWin ) return 0; /* restriction (6b) */
5163 #endif
5165 if( notUnionAll ){
5166 /* If any of the compound arms are connected using UNION, INTERSECT,
5167 ** or EXCEPT, then we must ensure that none of the columns use a
5168 ** non-BINARY collating sequence. */
5169 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5170 int ii;
5171 const ExprList *pList = pSel->pEList;
5172 assert( pList!=0 );
5173 for(ii=0; ii<pList->nExpr; ii++){
5174 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[ii].pExpr);
5175 if( !sqlite3IsBinary(pColl) ){
5176 return 0; /* Restriction (8) */
5181 }else{
5182 #ifndef SQLITE_OMIT_WINDOWFUNC
5183 if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
5184 #endif
5187 #ifdef SQLITE_DEBUG
5188 /* Only the first term of a compound can have a WITH clause. But make
5189 ** sure no other terms are marked SF_Recursive in case something changes
5190 ** in the future.
5193 Select *pX;
5194 for(pX=pSubq; pX; pX=pX->pPrior){
5195 assert( (pX->selFlags & (SF_Recursive))==0 );
5198 #endif
5200 if( pSubq->pLimit!=0 ){
5201 return 0; /* restriction (3) */
5203 while( pWhere->op==TK_AND ){
5204 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
5205 pWhere = pWhere->pLeft;
5208 #if 0 /* These checks now done by sqlite3ExprIsSingleTableConstraint() */
5209 if( ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) /* (9a) */
5210 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (9c) */
5212 int jj;
5213 for(jj=0; jj<iSrc; jj++){
5214 if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
5215 /* If we reach this point, both (9a) and (9b) are satisfied.
5216 ** The following loop checks (9c):
5218 for(jj++; jj<iSrc; jj++){
5219 if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
5220 return 0; /* restriction (9) */
5226 if( isLeftJoin
5227 && (ExprHasProperty(pWhere,EP_OuterON)==0
5228 || pWhere->w.iJoin!=iCursor)
5230 return 0; /* restriction (4) */
5232 if( ExprHasProperty(pWhere,EP_OuterON)
5233 && pWhere->w.iJoin!=iCursor
5235 return 0; /* restriction (5) */
5237 #endif
5239 if( sqlite3ExprIsSingleTableConstraint(pWhere, pSrcList, iSrc) ){
5240 nChng++;
5241 pSubq->selFlags |= SF_PushDown;
5242 while( pSubq ){
5243 SubstContext x;
5244 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
5245 unsetJoinExpr(pNew, -1, 1);
5246 x.pParse = pParse;
5247 x.iTable = pSrc->iCursor;
5248 x.iNewTable = pSrc->iCursor;
5249 x.isOuterJoin = 0;
5250 x.pEList = pSubq->pEList;
5251 x.pCList = findLeftmostExprlist(pSubq);
5252 pNew = substExpr(&x, pNew);
5253 #ifndef SQLITE_OMIT_WINDOWFUNC
5254 if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
5255 /* Restriction 6c has prevented push-down in this case */
5256 sqlite3ExprDelete(pParse->db, pNew);
5257 nChng--;
5258 break;
5260 #endif
5261 if( pSubq->selFlags & SF_Aggregate ){
5262 pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
5263 }else{
5264 pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
5266 pSubq = pSubq->pPrior;
5269 return nChng;
5271 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5274 ** Check to see if a subquery contains result-set columns that are
5275 ** never used. If it does, change the value of those result-set columns
5276 ** to NULL so that they do not cause unnecessary work to compute.
5278 ** Return the number of column that were changed to NULL.
5280 static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
5281 int nCol;
5282 Select *pSub; /* The subquery to be simplified */
5283 Select *pX; /* For looping over compound elements of pSub */
5284 Table *pTab; /* The table that describes the subquery */
5285 int j; /* Column number */
5286 int nChng = 0; /* Number of columns converted to NULL */
5287 Bitmask colUsed; /* Columns that may not be NULLed out */
5289 assert( pItem!=0 );
5290 if( pItem->fg.isCorrelated || pItem->fg.isCte ){
5291 return 0;
5293 assert( pItem->pTab!=0 );
5294 pTab = pItem->pTab;
5295 assert( pItem->pSelect!=0 );
5296 pSub = pItem->pSelect;
5297 assert( pSub->pEList->nExpr==pTab->nCol );
5298 if( (pSub->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
5299 testcase( pSub->selFlags & SF_Distinct );
5300 testcase( pSub->selFlags & SF_Aggregate );
5301 return 0;
5303 for(pX=pSub; pX; pX=pX->pPrior){
5304 if( pX->pPrior && pX->op!=TK_ALL ){
5305 /* This optimization does not work for compound subqueries that
5306 ** use UNION, INTERSECT, or EXCEPT. Only UNION ALL is allowed. */
5307 return 0;
5309 #ifndef SQLITE_OMIT_WINDOWFUNC
5310 if( pX->pWin ){
5311 /* This optimization does not work for subqueries that use window
5312 ** functions. */
5313 return 0;
5315 #endif
5317 colUsed = pItem->colUsed;
5318 if( pSub->pOrderBy ){
5319 ExprList *pList = pSub->pOrderBy;
5320 for(j=0; j<pList->nExpr; j++){
5321 u16 iCol = pList->a[j].u.x.iOrderByCol;
5322 if( iCol>0 ){
5323 iCol--;
5324 colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
5328 nCol = pTab->nCol;
5329 for(j=0; j<nCol; j++){
5330 Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
5331 if( (m & colUsed)!=0 ) continue;
5332 for(pX=pSub; pX; pX=pX->pPrior) {
5333 Expr *pY = pX->pEList->a[j].pExpr;
5334 if( pY->op==TK_NULL ) continue;
5335 pY->op = TK_NULL;
5336 ExprClearProperty(pY, EP_Skip|EP_Unlikely);
5337 pX->selFlags |= SF_PushDown;
5338 nChng++;
5341 return nChng;
5346 ** The pFunc is the only aggregate function in the query. Check to see
5347 ** if the query is a candidate for the min/max optimization.
5349 ** If the query is a candidate for the min/max optimization, then set
5350 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
5351 ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
5352 ** whether pFunc is a min() or max() function.
5354 ** If the query is not a candidate for the min/max optimization, return
5355 ** WHERE_ORDERBY_NORMAL (which must be zero).
5357 ** This routine must be called after aggregate functions have been
5358 ** located but before their arguments have been subjected to aggregate
5359 ** analysis.
5361 static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
5362 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
5363 ExprList *pEList; /* Arguments to agg function */
5364 const char *zFunc; /* Name of aggregate function pFunc */
5365 ExprList *pOrderBy;
5366 u8 sortFlags = 0;
5368 assert( *ppMinMax==0 );
5369 assert( pFunc->op==TK_AGG_FUNCTION );
5370 assert( !IsWindowFunc(pFunc) );
5371 assert( ExprUseXList(pFunc) );
5372 pEList = pFunc->x.pList;
5373 if( pEList==0
5374 || pEList->nExpr!=1
5375 || ExprHasProperty(pFunc, EP_WinFunc)
5376 || OptimizationDisabled(db, SQLITE_MinMaxOpt)
5378 return eRet;
5380 assert( !ExprHasProperty(pFunc, EP_IntValue) );
5381 zFunc = pFunc->u.zToken;
5382 if( sqlite3StrICmp(zFunc, "min")==0 ){
5383 eRet = WHERE_ORDERBY_MIN;
5384 if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
5385 sortFlags = KEYINFO_ORDER_BIGNULL;
5387 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
5388 eRet = WHERE_ORDERBY_MAX;
5389 sortFlags = KEYINFO_ORDER_DESC;
5390 }else{
5391 return eRet;
5393 *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
5394 assert( pOrderBy!=0 || db->mallocFailed );
5395 if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
5396 return eRet;
5400 ** The select statement passed as the first argument is an aggregate query.
5401 ** The second argument is the associated aggregate-info object. This
5402 ** function tests if the SELECT is of the form:
5404 ** SELECT count(*) FROM <tbl>
5406 ** where table is a database table, not a sub-select or view. If the query
5407 ** does match this pattern, then a pointer to the Table object representing
5408 ** <tbl> is returned. Otherwise, NULL is returned.
5410 ** This routine checks to see if it is safe to use the count optimization.
5411 ** A correct answer is still obtained (though perhaps more slowly) if
5412 ** this routine returns NULL when it could have returned a table pointer.
5413 ** But returning the pointer when NULL should have been returned can
5414 ** result in incorrect answers and/or crashes. So, when in doubt, return NULL.
5416 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
5417 Table *pTab;
5418 Expr *pExpr;
5420 assert( !p->pGroupBy );
5422 if( p->pWhere
5423 || p->pEList->nExpr!=1
5424 || p->pSrc->nSrc!=1
5425 || p->pSrc->a[0].pSelect
5426 || pAggInfo->nFunc!=1
5427 || p->pHaving
5429 return 0;
5431 pTab = p->pSrc->a[0].pTab;
5432 assert( pTab!=0 );
5433 assert( !IsView(pTab) );
5434 if( !IsOrdinaryTable(pTab) ) return 0;
5435 pExpr = p->pEList->a[0].pExpr;
5436 assert( pExpr!=0 );
5437 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
5438 if( pExpr->pAggInfo!=pAggInfo ) return 0;
5439 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
5440 assert( pAggInfo->aFunc[0].pFExpr==pExpr );
5441 testcase( ExprHasProperty(pExpr, EP_Distinct) );
5442 testcase( ExprHasProperty(pExpr, EP_WinFunc) );
5443 if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
5445 return pTab;
5449 ** If the source-list item passed as an argument was augmented with an
5450 ** INDEXED BY clause, then try to locate the specified index. If there
5451 ** was such a clause and the named index cannot be found, return
5452 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
5453 ** pFrom->pIndex and return SQLITE_OK.
5455 int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
5456 Table *pTab = pFrom->pTab;
5457 char *zIndexedBy = pFrom->u1.zIndexedBy;
5458 Index *pIdx;
5459 assert( pTab!=0 );
5460 assert( pFrom->fg.isIndexedBy!=0 );
5462 for(pIdx=pTab->pIndex;
5463 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
5464 pIdx=pIdx->pNext
5466 if( !pIdx ){
5467 sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
5468 pParse->checkSchema = 1;
5469 return SQLITE_ERROR;
5471 assert( pFrom->fg.isCte==0 );
5472 pFrom->u2.pIBIndex = pIdx;
5473 return SQLITE_OK;
5477 ** Detect compound SELECT statements that use an ORDER BY clause with
5478 ** an alternative collating sequence.
5480 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
5482 ** These are rewritten as a subquery:
5484 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
5485 ** ORDER BY ... COLLATE ...
5487 ** This transformation is necessary because the multiSelectOrderBy() routine
5488 ** above that generates the code for a compound SELECT with an ORDER BY clause
5489 ** uses a merge algorithm that requires the same collating sequence on the
5490 ** result columns as on the ORDER BY clause. See ticket
5491 ** http://www.sqlite.org/src/info/6709574d2a
5493 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
5494 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
5495 ** there are COLLATE terms in the ORDER BY.
5497 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
5498 int i;
5499 Select *pNew;
5500 Select *pX;
5501 sqlite3 *db;
5502 struct ExprList_item *a;
5503 SrcList *pNewSrc;
5504 Parse *pParse;
5505 Token dummy;
5507 if( p->pPrior==0 ) return WRC_Continue;
5508 if( p->pOrderBy==0 ) return WRC_Continue;
5509 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
5510 if( pX==0 ) return WRC_Continue;
5511 a = p->pOrderBy->a;
5512 #ifndef SQLITE_OMIT_WINDOWFUNC
5513 /* If iOrderByCol is already non-zero, then it has already been matched
5514 ** to a result column of the SELECT statement. This occurs when the
5515 ** SELECT is rewritten for window-functions processing and then passed
5516 ** to sqlite3SelectPrep() and similar a second time. The rewriting done
5517 ** by this function is not required in this case. */
5518 if( a[0].u.x.iOrderByCol ) return WRC_Continue;
5519 #endif
5520 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
5521 if( a[i].pExpr->flags & EP_Collate ) break;
5523 if( i<0 ) return WRC_Continue;
5525 /* If we reach this point, that means the transformation is required. */
5527 pParse = pWalker->pParse;
5528 db = pParse->db;
5529 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
5530 if( pNew==0 ) return WRC_Abort;
5531 memset(&dummy, 0, sizeof(dummy));
5532 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
5533 if( pNewSrc==0 ) return WRC_Abort;
5534 *pNew = *p;
5535 p->pSrc = pNewSrc;
5536 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
5537 p->op = TK_SELECT;
5538 p->pWhere = 0;
5539 pNew->pGroupBy = 0;
5540 pNew->pHaving = 0;
5541 pNew->pOrderBy = 0;
5542 p->pPrior = 0;
5543 p->pNext = 0;
5544 p->pWith = 0;
5545 #ifndef SQLITE_OMIT_WINDOWFUNC
5546 p->pWinDefn = 0;
5547 #endif
5548 p->selFlags &= ~SF_Compound;
5549 assert( (p->selFlags & SF_Converted)==0 );
5550 p->selFlags |= SF_Converted;
5551 assert( pNew->pPrior!=0 );
5552 pNew->pPrior->pNext = pNew;
5553 pNew->pLimit = 0;
5554 return WRC_Continue;
5558 ** Check to see if the FROM clause term pFrom has table-valued function
5559 ** arguments. If it does, leave an error message in pParse and return
5560 ** non-zero, since pFrom is not allowed to be a table-valued function.
5562 static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
5563 if( pFrom->fg.isTabFunc ){
5564 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
5565 return 1;
5567 return 0;
5570 #ifndef SQLITE_OMIT_CTE
5572 ** Argument pWith (which may be NULL) points to a linked list of nested
5573 ** WITH contexts, from inner to outermost. If the table identified by
5574 ** FROM clause element pItem is really a common-table-expression (CTE)
5575 ** then return a pointer to the CTE definition for that table. Otherwise
5576 ** return NULL.
5578 ** If a non-NULL value is returned, set *ppContext to point to the With
5579 ** object that the returned CTE belongs to.
5581 static struct Cte *searchWith(
5582 With *pWith, /* Current innermost WITH clause */
5583 SrcItem *pItem, /* FROM clause element to resolve */
5584 With **ppContext /* OUT: WITH clause return value belongs to */
5586 const char *zName = pItem->zName;
5587 With *p;
5588 assert( pItem->zDatabase==0 );
5589 assert( zName!=0 );
5590 for(p=pWith; p; p=p->pOuter){
5591 int i;
5592 for(i=0; i<p->nCte; i++){
5593 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
5594 *ppContext = p;
5595 return &p->a[i];
5598 if( p->bView ) break;
5600 return 0;
5603 /* The code generator maintains a stack of active WITH clauses
5604 ** with the inner-most WITH clause being at the top of the stack.
5606 ** This routine pushes the WITH clause passed as the second argument
5607 ** onto the top of the stack. If argument bFree is true, then this
5608 ** WITH clause will never be popped from the stack but should instead
5609 ** be freed along with the Parse object. In other cases, when
5610 ** bFree==0, the With object will be freed along with the SELECT
5611 ** statement with which it is associated.
5613 ** This routine returns a copy of pWith. Or, if bFree is true and
5614 ** the pWith object is destroyed immediately due to an OOM condition,
5615 ** then this routine return NULL.
5617 ** If bFree is true, do not continue to use the pWith pointer after
5618 ** calling this routine, Instead, use only the return value.
5620 With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
5621 if( pWith ){
5622 if( bFree ){
5623 pWith = (With*)sqlite3ParserAddCleanup(pParse,
5624 (void(*)(sqlite3*,void*))sqlite3WithDelete,
5625 pWith);
5626 if( pWith==0 ) return 0;
5628 if( pParse->nErr==0 ){
5629 assert( pParse->pWith!=pWith );
5630 pWith->pOuter = pParse->pWith;
5631 pParse->pWith = pWith;
5634 return pWith;
5638 ** This function checks if argument pFrom refers to a CTE declared by
5639 ** a WITH clause on the stack currently maintained by the parser (on the
5640 ** pParse->pWith linked list). And if currently processing a CTE
5641 ** CTE expression, through routine checks to see if the reference is
5642 ** a recursive reference to the CTE.
5644 ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
5645 ** and other fields are populated accordingly.
5647 ** Return 0 if no match is found.
5648 ** Return 1 if a match is found.
5649 ** Return 2 if an error condition is detected.
5651 static int resolveFromTermToCte(
5652 Parse *pParse, /* The parsing context */
5653 Walker *pWalker, /* Current tree walker */
5654 SrcItem *pFrom /* The FROM clause term to check */
5656 Cte *pCte; /* Matched CTE (or NULL if no match) */
5657 With *pWith; /* The matching WITH */
5659 assert( pFrom->pTab==0 );
5660 if( pParse->pWith==0 ){
5661 /* There are no WITH clauses in the stack. No match is possible */
5662 return 0;
5664 if( pParse->nErr ){
5665 /* Prior errors might have left pParse->pWith in a goofy state, so
5666 ** go no further. */
5667 return 0;
5669 if( pFrom->zDatabase!=0 ){
5670 /* The FROM term contains a schema qualifier (ex: main.t1) and so
5671 ** it cannot possibly be a CTE reference. */
5672 return 0;
5674 if( pFrom->fg.notCte ){
5675 /* The FROM term is specifically excluded from matching a CTE.
5676 ** (1) It is part of a trigger that used to have zDatabase but had
5677 ** zDatabase removed by sqlite3FixTriggerStep().
5678 ** (2) This is the first term in the FROM clause of an UPDATE.
5680 return 0;
5682 pCte = searchWith(pParse->pWith, pFrom, &pWith);
5683 if( pCte ){
5684 sqlite3 *db = pParse->db;
5685 Table *pTab;
5686 ExprList *pEList;
5687 Select *pSel;
5688 Select *pLeft; /* Left-most SELECT statement */
5689 Select *pRecTerm; /* Left-most recursive term */
5690 int bMayRecursive; /* True if compound joined by UNION [ALL] */
5691 With *pSavedWith; /* Initial value of pParse->pWith */
5692 int iRecTab = -1; /* Cursor for recursive table */
5693 CteUse *pCteUse;
5695 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
5696 ** recursive reference to CTE pCte. Leave an error in pParse and return
5697 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
5698 ** In this case, proceed. */
5699 if( pCte->zCteErr ){
5700 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
5701 return 2;
5703 if( cannotBeFunction(pParse, pFrom) ) return 2;
5705 assert( pFrom->pTab==0 );
5706 pTab = sqlite3DbMallocZero(db, sizeof(Table));
5707 if( pTab==0 ) return 2;
5708 pCteUse = pCte->pUse;
5709 if( pCteUse==0 ){
5710 pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
5711 if( pCteUse==0
5712 || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
5714 sqlite3DbFree(db, pTab);
5715 return 2;
5717 pCteUse->eM10d = pCte->eM10d;
5719 pFrom->pTab = pTab;
5720 pTab->nTabRef = 1;
5721 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
5722 pTab->iPKey = -1;
5723 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5724 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5725 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
5726 if( db->mallocFailed ) return 2;
5727 pFrom->pSelect->selFlags |= SF_CopyCte;
5728 assert( pFrom->pSelect );
5729 if( pFrom->fg.isIndexedBy ){
5730 sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
5731 return 2;
5733 pFrom->fg.isCte = 1;
5734 pFrom->u2.pCteUse = pCteUse;
5735 pCteUse->nUse++;
5737 /* Check if this is a recursive CTE. */
5738 pRecTerm = pSel = pFrom->pSelect;
5739 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
5740 while( bMayRecursive && pRecTerm->op==pSel->op ){
5741 int i;
5742 SrcList *pSrc = pRecTerm->pSrc;
5743 assert( pRecTerm->pPrior!=0 );
5744 for(i=0; i<pSrc->nSrc; i++){
5745 SrcItem *pItem = &pSrc->a[i];
5746 if( pItem->zDatabase==0
5747 && pItem->zName!=0
5748 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
5750 pItem->pTab = pTab;
5751 pTab->nTabRef++;
5752 pItem->fg.isRecursive = 1;
5753 if( pRecTerm->selFlags & SF_Recursive ){
5754 sqlite3ErrorMsg(pParse,
5755 "multiple references to recursive table: %s", pCte->zName
5757 return 2;
5759 pRecTerm->selFlags |= SF_Recursive;
5760 if( iRecTab<0 ) iRecTab = pParse->nTab++;
5761 pItem->iCursor = iRecTab;
5764 if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
5765 pRecTerm = pRecTerm->pPrior;
5768 pCte->zCteErr = "circular reference: %s";
5769 pSavedWith = pParse->pWith;
5770 pParse->pWith = pWith;
5771 if( pSel->selFlags & SF_Recursive ){
5772 int rc;
5773 assert( pRecTerm!=0 );
5774 assert( (pRecTerm->selFlags & SF_Recursive)==0 );
5775 assert( pRecTerm->pNext!=0 );
5776 assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
5777 assert( pRecTerm->pWith==0 );
5778 pRecTerm->pWith = pSel->pWith;
5779 rc = sqlite3WalkSelect(pWalker, pRecTerm);
5780 pRecTerm->pWith = 0;
5781 if( rc ){
5782 pParse->pWith = pSavedWith;
5783 return 2;
5785 }else{
5786 if( sqlite3WalkSelect(pWalker, pSel) ){
5787 pParse->pWith = pSavedWith;
5788 return 2;
5791 pParse->pWith = pWith;
5793 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
5794 pEList = pLeft->pEList;
5795 if( pCte->pCols ){
5796 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
5797 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
5798 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
5800 pParse->pWith = pSavedWith;
5801 return 2;
5803 pEList = pCte->pCols;
5806 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
5807 if( bMayRecursive ){
5808 if( pSel->selFlags & SF_Recursive ){
5809 pCte->zCteErr = "multiple recursive references: %s";
5810 }else{
5811 pCte->zCteErr = "recursive reference in a subquery: %s";
5813 sqlite3WalkSelect(pWalker, pSel);
5815 pCte->zCteErr = 0;
5816 pParse->pWith = pSavedWith;
5817 return 1; /* Success */
5819 return 0; /* No match */
5821 #endif
5823 #ifndef SQLITE_OMIT_CTE
5825 ** If the SELECT passed as the second argument has an associated WITH
5826 ** clause, pop it from the stack stored as part of the Parse object.
5828 ** This function is used as the xSelectCallback2() callback by
5829 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
5830 ** names and other FROM clause elements.
5832 void sqlite3SelectPopWith(Walker *pWalker, Select *p){
5833 Parse *pParse = pWalker->pParse;
5834 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
5835 With *pWith = findRightmost(p)->pWith;
5836 if( pWith!=0 ){
5837 assert( pParse->pWith==pWith || pParse->nErr );
5838 pParse->pWith = pWith->pOuter;
5842 #endif
5845 ** The SrcItem structure passed as the second argument represents a
5846 ** sub-query in the FROM clause of a SELECT statement. This function
5847 ** allocates and populates the SrcItem.pTab object. If successful,
5848 ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
5849 ** SQLITE_NOMEM.
5851 int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
5852 Select *pSel = pFrom->pSelect;
5853 Table *pTab;
5855 assert( pSel );
5856 pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
5857 if( pTab==0 ) return SQLITE_NOMEM;
5858 pTab->nTabRef = 1;
5859 if( pFrom->zAlias ){
5860 pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
5861 }else{
5862 pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
5864 while( pSel->pPrior ){ pSel = pSel->pPrior; }
5865 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
5866 pTab->iPKey = -1;
5867 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5868 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
5869 /* The usual case - do not allow ROWID on a subquery */
5870 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5871 #else
5872 pTab->tabFlags |= TF_Ephemeral; /* Legacy compatibility mode */
5873 #endif
5874 return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
5879 ** Check the N SrcItem objects to the right of pBase. (N might be zero!)
5880 ** If any of those SrcItem objects have a USING clause containing zName
5881 ** then return true.
5883 ** If N is zero, or none of the N SrcItem objects to the right of pBase
5884 ** contains a USING clause, or if none of the USING clauses contain zName,
5885 ** then return false.
5887 static int inAnyUsingClause(
5888 const char *zName, /* Name we are looking for */
5889 SrcItem *pBase, /* The base SrcItem. Looking at pBase[1] and following */
5890 int N /* How many SrcItems to check */
5892 while( N>0 ){
5893 N--;
5894 pBase++;
5895 if( pBase->fg.isUsing==0 ) continue;
5896 if( NEVER(pBase->u3.pUsing==0) ) continue;
5897 if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
5899 return 0;
5904 ** This routine is a Walker callback for "expanding" a SELECT statement.
5905 ** "Expanding" means to do the following:
5907 ** (1) Make sure VDBE cursor numbers have been assigned to every
5908 ** element of the FROM clause.
5910 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
5911 ** defines FROM clause. When views appear in the FROM clause,
5912 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
5913 ** that implements the view. A copy is made of the view's SELECT
5914 ** statement so that we can freely modify or delete that statement
5915 ** without worrying about messing up the persistent representation
5916 ** of the view.
5918 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
5919 ** on joins and the ON and USING clause of joins.
5921 ** (4) Scan the list of columns in the result set (pEList) looking
5922 ** for instances of the "*" operator or the TABLE.* operator.
5923 ** If found, expand each "*" to be every column in every table
5924 ** and TABLE.* to be every column in TABLE.
5927 static int selectExpander(Walker *pWalker, Select *p){
5928 Parse *pParse = pWalker->pParse;
5929 int i, j, k, rc;
5930 SrcList *pTabList;
5931 ExprList *pEList;
5932 SrcItem *pFrom;
5933 sqlite3 *db = pParse->db;
5934 Expr *pE, *pRight, *pExpr;
5935 u16 selFlags = p->selFlags;
5936 u32 elistFlags = 0;
5938 p->selFlags |= SF_Expanded;
5939 if( db->mallocFailed ){
5940 return WRC_Abort;
5942 assert( p->pSrc!=0 );
5943 if( (selFlags & SF_Expanded)!=0 ){
5944 return WRC_Prune;
5946 if( pWalker->eCode ){
5947 /* Renumber selId because it has been copied from a view */
5948 p->selId = ++pParse->nSelect;
5950 pTabList = p->pSrc;
5951 pEList = p->pEList;
5952 if( pParse->pWith && (p->selFlags & SF_View) ){
5953 if( p->pWith==0 ){
5954 p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
5955 if( p->pWith==0 ){
5956 return WRC_Abort;
5959 p->pWith->bView = 1;
5961 sqlite3WithPush(pParse, p->pWith, 0);
5963 /* Make sure cursor numbers have been assigned to all entries in
5964 ** the FROM clause of the SELECT statement.
5966 sqlite3SrcListAssignCursors(pParse, pTabList);
5968 /* Look up every table named in the FROM clause of the select. If
5969 ** an entry of the FROM clause is a subquery instead of a table or view,
5970 ** then create a transient table structure to describe the subquery.
5972 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
5973 Table *pTab;
5974 assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
5975 if( pFrom->pTab ) continue;
5976 assert( pFrom->fg.isRecursive==0 );
5977 if( pFrom->zName==0 ){
5978 #ifndef SQLITE_OMIT_SUBQUERY
5979 Select *pSel = pFrom->pSelect;
5980 /* A sub-query in the FROM clause of a SELECT */
5981 assert( pSel!=0 );
5982 assert( pFrom->pTab==0 );
5983 if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
5984 if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
5985 #endif
5986 #ifndef SQLITE_OMIT_CTE
5987 }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
5988 if( rc>1 ) return WRC_Abort;
5989 pTab = pFrom->pTab;
5990 assert( pTab!=0 );
5991 #endif
5992 }else{
5993 /* An ordinary table or view name in the FROM clause */
5994 assert( pFrom->pTab==0 );
5995 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
5996 if( pTab==0 ) return WRC_Abort;
5997 if( pTab->nTabRef>=0xffff ){
5998 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
5999 pTab->zName);
6000 pFrom->pTab = 0;
6001 return WRC_Abort;
6003 pTab->nTabRef++;
6004 if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
6005 return WRC_Abort;
6007 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
6008 if( !IsOrdinaryTable(pTab) ){
6009 i16 nCol;
6010 u8 eCodeOrig = pWalker->eCode;
6011 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
6012 assert( pFrom->pSelect==0 );
6013 if( IsView(pTab) ){
6014 if( (db->flags & SQLITE_EnableView)==0
6015 && pTab->pSchema!=db->aDb[1].pSchema
6017 sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
6018 pTab->zName);
6020 pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
6022 #ifndef SQLITE_OMIT_VIRTUALTABLE
6023 else if( ALWAYS(IsVirtual(pTab))
6024 && pFrom->fg.fromDDL
6025 && ALWAYS(pTab->u.vtab.p!=0)
6026 && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
6028 sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
6029 pTab->zName);
6031 assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
6032 #endif
6033 nCol = pTab->nCol;
6034 pTab->nCol = -1;
6035 pWalker->eCode = 1; /* Turn on Select.selId renumbering */
6036 sqlite3WalkSelect(pWalker, pFrom->pSelect);
6037 pWalker->eCode = eCodeOrig;
6038 pTab->nCol = nCol;
6040 #endif
6043 /* Locate the index named by the INDEXED BY clause, if any. */
6044 if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
6045 return WRC_Abort;
6049 /* Process NATURAL keywords, and ON and USING clauses of joins.
6051 assert( db->mallocFailed==0 || pParse->nErr!=0 );
6052 if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
6053 return WRC_Abort;
6056 /* For every "*" that occurs in the column list, insert the names of
6057 ** all columns in all tables. And for every TABLE.* insert the names
6058 ** of all columns in TABLE. The parser inserted a special expression
6059 ** with the TK_ASTERISK operator for each "*" that it found in the column
6060 ** list. The following code just has to locate the TK_ASTERISK
6061 ** expressions and expand each one to the list of all columns in
6062 ** all tables.
6064 ** The first loop just checks to see if there are any "*" operators
6065 ** that need expanding.
6067 for(k=0; k<pEList->nExpr; k++){
6068 pE = pEList->a[k].pExpr;
6069 if( pE->op==TK_ASTERISK ) break;
6070 assert( pE->op!=TK_DOT || pE->pRight!=0 );
6071 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
6072 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
6073 elistFlags |= pE->flags;
6075 if( k<pEList->nExpr ){
6077 ** If we get here it means the result set contains one or more "*"
6078 ** operators that need to be expanded. Loop through each expression
6079 ** in the result set and expand them one by one.
6081 struct ExprList_item *a = pEList->a;
6082 ExprList *pNew = 0;
6083 int flags = pParse->db->flags;
6084 int longNames = (flags & SQLITE_FullColNames)!=0
6085 && (flags & SQLITE_ShortColNames)==0;
6087 for(k=0; k<pEList->nExpr; k++){
6088 pE = a[k].pExpr;
6089 elistFlags |= pE->flags;
6090 pRight = pE->pRight;
6091 assert( pE->op!=TK_DOT || pRight!=0 );
6092 if( pE->op!=TK_ASTERISK
6093 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
6095 /* This particular expression does not need to be expanded.
6097 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
6098 if( pNew ){
6099 pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
6100 pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
6101 a[k].zEName = 0;
6103 a[k].pExpr = 0;
6104 }else{
6105 /* This expression is a "*" or a "TABLE.*" and needs to be
6106 ** expanded. */
6107 int tableSeen = 0; /* Set to 1 when TABLE matches */
6108 char *zTName = 0; /* text of name of TABLE */
6109 if( pE->op==TK_DOT ){
6110 assert( pE->pLeft!=0 );
6111 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
6112 zTName = pE->pLeft->u.zToken;
6114 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6115 Table *pTab = pFrom->pTab; /* Table for this data source */
6116 ExprList *pNestedFrom; /* Result-set of a nested FROM clause */
6117 char *zTabName; /* AS name for this data source */
6118 const char *zSchemaName = 0; /* Schema name for this data source */
6119 int iDb; /* Schema index for this data src */
6120 IdList *pUsing; /* USING clause for pFrom[1] */
6122 if( (zTabName = pFrom->zAlias)==0 ){
6123 zTabName = pTab->zName;
6125 if( db->mallocFailed ) break;
6126 assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
6127 if( pFrom->fg.isNestedFrom ){
6128 assert( pFrom->pSelect!=0 );
6129 pNestedFrom = pFrom->pSelect->pEList;
6130 assert( pNestedFrom!=0 );
6131 assert( pNestedFrom->nExpr==pTab->nCol );
6132 }else{
6133 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
6134 continue;
6136 pNestedFrom = 0;
6137 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6138 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
6140 if( i+1<pTabList->nSrc
6141 && pFrom[1].fg.isUsing
6142 && (selFlags & SF_NestedFrom)!=0
6144 int ii;
6145 pUsing = pFrom[1].u3.pUsing;
6146 for(ii=0; ii<pUsing->nId; ii++){
6147 const char *zUName = pUsing->a[ii].zName;
6148 pRight = sqlite3Expr(db, TK_ID, zUName);
6149 pNew = sqlite3ExprListAppend(pParse, pNew, pRight);
6150 if( pNew ){
6151 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
6152 assert( pX->zEName==0 );
6153 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
6154 pX->fg.eEName = ENAME_TAB;
6155 pX->fg.bUsingTerm = 1;
6158 }else{
6159 pUsing = 0;
6161 for(j=0; j<pTab->nCol; j++){
6162 char *zName = pTab->aCol[j].zCnName;
6163 struct ExprList_item *pX; /* Newly added ExprList term */
6165 assert( zName );
6166 if( zTName
6167 && pNestedFrom
6168 && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0)==0
6170 continue;
6173 /* If a column is marked as 'hidden', omit it from the expanded
6174 ** result-set list unless the SELECT has the SF_IncludeHidden
6175 ** bit set.
6177 if( (p->selFlags & SF_IncludeHidden)==0
6178 && IsHiddenColumn(&pTab->aCol[j])
6180 continue;
6182 if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
6183 && zTName==0
6184 && (selFlags & (SF_NestedFrom))==0
6186 continue;
6188 tableSeen = 1;
6190 if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
6191 if( pFrom->fg.isUsing
6192 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
6194 /* In a join with a USING clause, omit columns in the
6195 ** using clause from the table on the right. */
6196 continue;
6199 pRight = sqlite3Expr(db, TK_ID, zName);
6200 if( (pTabList->nSrc>1
6201 && ( (pFrom->fg.jointype & JT_LTORJ)==0
6202 || (selFlags & SF_NestedFrom)!=0
6203 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
6206 || IN_RENAME_OBJECT
6208 Expr *pLeft;
6209 pLeft = sqlite3Expr(db, TK_ID, zTabName);
6210 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
6211 if( IN_RENAME_OBJECT && pE->pLeft ){
6212 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
6214 if( zSchemaName ){
6215 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
6216 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
6218 }else{
6219 pExpr = pRight;
6221 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
6222 if( pNew==0 ){
6223 break; /* OOM */
6225 pX = &pNew->a[pNew->nExpr-1];
6226 assert( pX->zEName==0 );
6227 if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
6228 if( pNestedFrom ){
6229 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
6230 testcase( pX->zEName==0 );
6231 }else{
6232 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
6233 zSchemaName, zTabName, zName);
6234 testcase( pX->zEName==0 );
6236 pX->fg.eEName = ENAME_TAB;
6237 if( (pFrom->fg.isUsing
6238 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
6239 || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
6240 || (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
6242 pX->fg.bNoExpand = 1;
6244 }else if( longNames ){
6245 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
6246 pX->fg.eEName = ENAME_NAME;
6247 }else{
6248 pX->zEName = sqlite3DbStrDup(db, zName);
6249 pX->fg.eEName = ENAME_NAME;
6253 if( !tableSeen ){
6254 if( zTName ){
6255 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
6256 }else{
6257 sqlite3ErrorMsg(pParse, "no tables specified");
6262 sqlite3ExprListDelete(db, pEList);
6263 p->pEList = pNew;
6265 if( p->pEList ){
6266 if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
6267 sqlite3ErrorMsg(pParse, "too many columns in result set");
6268 return WRC_Abort;
6270 if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
6271 p->selFlags |= SF_ComplexResult;
6274 #if TREETRACE_ENABLED
6275 if( sqlite3TreeTrace & 0x8 ){
6276 TREETRACE(0x8,pParse,p,("After result-set wildcard expansion:\n"));
6277 sqlite3TreeViewSelect(0, p, 0);
6279 #endif
6280 return WRC_Continue;
6283 #if SQLITE_DEBUG
6285 ** Always assert. This xSelectCallback2 implementation proves that the
6286 ** xSelectCallback2 is never invoked.
6288 void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
6289 UNUSED_PARAMETER2(NotUsed, NotUsed2);
6290 assert( 0 );
6292 #endif
6294 ** This routine "expands" a SELECT statement and all of its subqueries.
6295 ** For additional information on what it means to "expand" a SELECT
6296 ** statement, see the comment on the selectExpand worker callback above.
6298 ** Expanding a SELECT statement is the first step in processing a
6299 ** SELECT statement. The SELECT statement must be expanded before
6300 ** name resolution is performed.
6302 ** If anything goes wrong, an error message is written into pParse.
6303 ** The calling function can detect the problem by looking at pParse->nErr
6304 ** and/or pParse->db->mallocFailed.
6306 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
6307 Walker w;
6308 w.xExprCallback = sqlite3ExprWalkNoop;
6309 w.pParse = pParse;
6310 if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
6311 w.xSelectCallback = convertCompoundSelectToSubquery;
6312 w.xSelectCallback2 = 0;
6313 sqlite3WalkSelect(&w, pSelect);
6315 w.xSelectCallback = selectExpander;
6316 w.xSelectCallback2 = sqlite3SelectPopWith;
6317 w.eCode = 0;
6318 sqlite3WalkSelect(&w, pSelect);
6322 #ifndef SQLITE_OMIT_SUBQUERY
6324 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
6325 ** interface.
6327 ** For each FROM-clause subquery, add Column.zType, Column.zColl, and
6328 ** Column.affinity information to the Table structure that represents
6329 ** the result set of that subquery.
6331 ** The Table structure that represents the result set was constructed
6332 ** by selectExpander() but the type and collation and affinity information
6333 ** was omitted at that point because identifiers had not yet been resolved.
6334 ** This routine is called after identifier resolution.
6336 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
6337 Parse *pParse;
6338 int i;
6339 SrcList *pTabList;
6340 SrcItem *pFrom;
6342 assert( p->selFlags & SF_Resolved );
6343 if( p->selFlags & SF_HasTypeInfo ) return;
6344 p->selFlags |= SF_HasTypeInfo;
6345 pParse = pWalker->pParse;
6346 pTabList = p->pSrc;
6347 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6348 Table *pTab = pFrom->pTab;
6349 assert( pTab!=0 );
6350 if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
6351 /* A sub-query in the FROM clause of a SELECT */
6352 Select *pSel = pFrom->pSelect;
6353 if( pSel ){
6354 sqlite3SubqueryColumnTypes(pParse, pTab, pSel, SQLITE_AFF_NONE);
6359 #endif
6363 ** This routine adds datatype and collating sequence information to
6364 ** the Table structures of all FROM-clause subqueries in a
6365 ** SELECT statement.
6367 ** Use this routine after name resolution.
6369 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
6370 #ifndef SQLITE_OMIT_SUBQUERY
6371 Walker w;
6372 w.xSelectCallback = sqlite3SelectWalkNoop;
6373 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
6374 w.xExprCallback = sqlite3ExprWalkNoop;
6375 w.pParse = pParse;
6376 sqlite3WalkSelect(&w, pSelect);
6377 #endif
6382 ** This routine sets up a SELECT statement for processing. The
6383 ** following is accomplished:
6385 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
6386 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
6387 ** * ON and USING clauses are shifted into WHERE statements
6388 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
6389 ** * Identifiers in expression are matched to tables.
6391 ** This routine acts recursively on all subqueries within the SELECT.
6393 void sqlite3SelectPrep(
6394 Parse *pParse, /* The parser context */
6395 Select *p, /* The SELECT statement being coded. */
6396 NameContext *pOuterNC /* Name context for container */
6398 assert( p!=0 || pParse->db->mallocFailed );
6399 assert( pParse->db->pParse==pParse );
6400 if( pParse->db->mallocFailed ) return;
6401 if( p->selFlags & SF_HasTypeInfo ) return;
6402 sqlite3SelectExpand(pParse, p);
6403 if( pParse->nErr ) return;
6404 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
6405 if( pParse->nErr ) return;
6406 sqlite3SelectAddTypeInfo(pParse, p);
6409 #if TREETRACE_ENABLED
6411 ** Display all information about an AggInfo object
6413 static void printAggInfo(AggInfo *pAggInfo){
6414 int ii;
6415 for(ii=0; ii<pAggInfo->nColumn; ii++){
6416 struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
6417 sqlite3DebugPrintf(
6418 "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
6419 " iSorterColumn=%d %s\n",
6420 ii, pCol->pTab ? pCol->pTab->zName : "NULL",
6421 pCol->iTable, pCol->iColumn, pAggInfo->iFirstReg+ii,
6422 pCol->iSorterColumn,
6423 ii>=pAggInfo->nAccumulator ? "" : " Accumulator");
6424 sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
6426 for(ii=0; ii<pAggInfo->nFunc; ii++){
6427 sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
6428 ii, pAggInfo->iFirstReg+pAggInfo->nColumn+ii);
6429 sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
6432 #endif /* TREETRACE_ENABLED */
6435 ** Analyze the arguments to aggregate functions. Create new pAggInfo->aCol[]
6436 ** entries for columns that are arguments to aggregate functions but which
6437 ** are not otherwise used.
6439 ** The aCol[] entries in AggInfo prior to nAccumulator are columns that
6440 ** are referenced outside of aggregate functions. These might be columns
6441 ** that are part of the GROUP by clause, for example. Other database engines
6442 ** would throw an error if there is a column reference that is not in the
6443 ** GROUP BY clause and that is not part of an aggregate function argument.
6444 ** But SQLite allows this.
6446 ** The aCol[] entries beginning with the aCol[nAccumulator] and following
6447 ** are column references that are used exclusively as arguments to
6448 ** aggregate functions. This routine is responsible for computing
6449 ** (or recomputing) those aCol[] entries.
6451 static void analyzeAggFuncArgs(
6452 AggInfo *pAggInfo,
6453 NameContext *pNC
6455 int i;
6456 assert( pAggInfo!=0 );
6457 assert( pAggInfo->iFirstReg==0 );
6458 pNC->ncFlags |= NC_InAggFunc;
6459 for(i=0; i<pAggInfo->nFunc; i++){
6460 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
6461 assert( ExprUseXList(pExpr) );
6462 sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
6463 #ifndef SQLITE_OMIT_WINDOWFUNC
6464 assert( !IsWindowFunc(pExpr) );
6465 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6466 sqlite3ExprAnalyzeAggregates(pNC, pExpr->y.pWin->pFilter);
6468 #endif
6470 pNC->ncFlags &= ~NC_InAggFunc;
6474 ** An index on expressions is being used in the inner loop of an
6475 ** aggregate query with a GROUP BY clause. This routine attempts
6476 ** to adjust the AggInfo object to take advantage of index and to
6477 ** perhaps use the index as a covering index.
6480 static void optimizeAggregateUseOfIndexedExpr(
6481 Parse *pParse, /* Parsing context */
6482 Select *pSelect, /* The SELECT statement being processed */
6483 AggInfo *pAggInfo, /* The aggregate info */
6484 NameContext *pNC /* Name context used to resolve agg-func args */
6486 assert( pAggInfo->iFirstReg==0 );
6487 assert( pSelect!=0 );
6488 assert( pSelect->pGroupBy!=0 );
6489 pAggInfo->nColumn = pAggInfo->nAccumulator;
6490 if( ALWAYS(pAggInfo->nSortingColumn>0) ){
6491 int mx = pSelect->pGroupBy->nExpr - 1;
6492 int j, k;
6493 for(j=0; j<pAggInfo->nColumn; j++){
6494 k = pAggInfo->aCol[j].iSorterColumn;
6495 if( k>mx ) mx = k;
6497 pAggInfo->nSortingColumn = mx+1;
6499 analyzeAggFuncArgs(pAggInfo, pNC);
6500 #if TREETRACE_ENABLED
6501 if( sqlite3TreeTrace & 0x20 ){
6502 IndexedExpr *pIEpr;
6503 TREETRACE(0x20, pParse, pSelect,
6504 ("AggInfo (possibly) adjusted for Indexed Exprs\n"));
6505 sqlite3TreeViewSelect(0, pSelect, 0);
6506 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6507 printf("data-cursor=%d index={%d,%d}\n",
6508 pIEpr->iDataCur, pIEpr->iIdxCur, pIEpr->iIdxCol);
6509 sqlite3TreeViewExpr(0, pIEpr->pExpr, 0);
6511 printAggInfo(pAggInfo);
6513 #else
6514 UNUSED_PARAMETER(pSelect);
6515 UNUSED_PARAMETER(pParse);
6516 #endif
6520 ** Walker callback for aggregateConvertIndexedExprRefToColumn().
6522 static int aggregateIdxEprRefToColCallback(Walker *pWalker, Expr *pExpr){
6523 AggInfo *pAggInfo;
6524 struct AggInfo_col *pCol;
6525 UNUSED_PARAMETER(pWalker);
6526 if( pExpr->pAggInfo==0 ) return WRC_Continue;
6527 if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
6528 if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
6529 if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
6530 pAggInfo = pExpr->pAggInfo;
6531 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
6532 assert( pExpr->iAgg>=0 );
6533 pCol = &pAggInfo->aCol[pExpr->iAgg];
6534 pExpr->op = TK_AGG_COLUMN;
6535 pExpr->iTable = pCol->iTable;
6536 pExpr->iColumn = pCol->iColumn;
6537 ExprClearProperty(pExpr, EP_Skip|EP_Collate);
6538 return WRC_Prune;
6542 ** Convert every pAggInfo->aFunc[].pExpr such that any node within
6543 ** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
6544 ** opcode.
6546 static void aggregateConvertIndexedExprRefToColumn(AggInfo *pAggInfo){
6547 int i;
6548 Walker w;
6549 memset(&w, 0, sizeof(w));
6550 w.xExprCallback = aggregateIdxEprRefToColCallback;
6551 for(i=0; i<pAggInfo->nFunc; i++){
6552 sqlite3WalkExpr(&w, pAggInfo->aFunc[i].pFExpr);
6558 ** Allocate a block of registers so that there is one register for each
6559 ** pAggInfo->aCol[] and pAggInfo->aFunc[] entry in pAggInfo. The first
6560 ** register in this block is stored in pAggInfo->iFirstReg.
6562 ** This routine may only be called once for each AggInfo object. Prior
6563 ** to calling this routine:
6565 ** * The aCol[] and aFunc[] arrays may be modified
6566 ** * The AggInfoColumnReg() and AggInfoFuncReg() macros may not be used
6568 ** After clling this routine:
6570 ** * The aCol[] and aFunc[] arrays are fixed
6571 ** * The AggInfoColumnReg() and AggInfoFuncReg() macros may be used
6574 static void assignAggregateRegisters(Parse *pParse, AggInfo *pAggInfo){
6575 assert( pAggInfo!=0 );
6576 assert( pAggInfo->iFirstReg==0 );
6577 pAggInfo->iFirstReg = pParse->nMem + 1;
6578 pParse->nMem += pAggInfo->nColumn + pAggInfo->nFunc;
6582 ** Reset the aggregate accumulator.
6584 ** The aggregate accumulator is a set of memory cells that hold
6585 ** intermediate results while calculating an aggregate. This
6586 ** routine generates code that stores NULLs in all of those memory
6587 ** cells.
6589 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
6590 Vdbe *v = pParse->pVdbe;
6591 int i;
6592 struct AggInfo_func *pFunc;
6593 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
6594 assert( pAggInfo->iFirstReg>0 );
6595 assert( pParse->db->pParse==pParse );
6596 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
6597 if( nReg==0 ) return;
6598 if( pParse->nErr ) return;
6599 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
6600 pAggInfo->iFirstReg+nReg-1);
6601 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
6602 if( pFunc->iDistinct>=0 ){
6603 Expr *pE = pFunc->pFExpr;
6604 assert( ExprUseXList(pE) );
6605 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
6606 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
6607 "argument");
6608 pFunc->iDistinct = -1;
6609 }else{
6610 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
6611 pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6612 pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
6613 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
6614 pFunc->pFunc->zName));
6621 ** Invoke the OP_AggFinalize opcode for every aggregate function
6622 ** in the AggInfo structure.
6624 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
6625 Vdbe *v = pParse->pVdbe;
6626 int i;
6627 struct AggInfo_func *pF;
6628 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6629 ExprList *pList;
6630 assert( ExprUseXList(pF->pFExpr) );
6631 pList = pF->pFExpr->x.pList;
6632 sqlite3VdbeAddOp2(v, OP_AggFinal, AggInfoFuncReg(pAggInfo,i),
6633 pList ? pList->nExpr : 0);
6634 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6640 ** Generate code that will update the accumulator memory cells for an
6641 ** aggregate based on the current cursor position.
6643 ** If regAcc is non-zero and there are no min() or max() aggregates
6644 ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
6645 ** registers if register regAcc contains 0. The caller will take care
6646 ** of setting and clearing regAcc.
6648 static void updateAccumulator(
6649 Parse *pParse,
6650 int regAcc,
6651 AggInfo *pAggInfo,
6652 int eDistinctType
6654 Vdbe *v = pParse->pVdbe;
6655 int i;
6656 int regHit = 0;
6657 int addrHitTest = 0;
6658 struct AggInfo_func *pF;
6659 struct AggInfo_col *pC;
6661 assert( pAggInfo->iFirstReg>0 );
6662 if( pParse->nErr ) return;
6663 pAggInfo->directMode = 1;
6664 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6665 int nArg;
6666 int addrNext = 0;
6667 int regAgg;
6668 ExprList *pList;
6669 assert( ExprUseXList(pF->pFExpr) );
6670 assert( !IsWindowFunc(pF->pFExpr) );
6671 pList = pF->pFExpr->x.pList;
6672 if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
6673 Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
6674 if( pAggInfo->nAccumulator
6675 && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
6676 && regAcc
6678 /* If regAcc==0, there there exists some min() or max() function
6679 ** without a FILTER clause that will ensure the magnet registers
6680 ** are populated. */
6681 if( regHit==0 ) regHit = ++pParse->nMem;
6682 /* If this is the first row of the group (regAcc contains 0), clear the
6683 ** "magnet" register regHit so that the accumulator registers
6684 ** are populated if the FILTER clause jumps over the the
6685 ** invocation of min() or max() altogether. Or, if this is not
6686 ** the first row (regAcc contains 1), set the magnet register so that
6687 ** the accumulators are not populated unless the min()/max() is invoked
6688 ** and indicates that they should be. */
6689 sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
6691 addrNext = sqlite3VdbeMakeLabel(pParse);
6692 sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
6694 if( pList ){
6695 nArg = pList->nExpr;
6696 regAgg = sqlite3GetTempRange(pParse, nArg);
6697 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
6698 }else{
6699 nArg = 0;
6700 regAgg = 0;
6702 if( pF->iDistinct>=0 && pList ){
6703 if( addrNext==0 ){
6704 addrNext = sqlite3VdbeMakeLabel(pParse);
6706 pF->iDistinct = codeDistinct(pParse, eDistinctType,
6707 pF->iDistinct, addrNext, pList, regAgg);
6709 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
6710 CollSeq *pColl = 0;
6711 struct ExprList_item *pItem;
6712 int j;
6713 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
6714 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
6715 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
6717 if( !pColl ){
6718 pColl = pParse->db->pDfltColl;
6720 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
6721 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0, (char *)pColl, P4_COLLSEQ);
6723 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
6724 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6725 sqlite3VdbeChangeP5(v, (u8)nArg);
6726 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6727 if( addrNext ){
6728 sqlite3VdbeResolveLabel(v, addrNext);
6731 if( regHit==0 && pAggInfo->nAccumulator ){
6732 regHit = regAcc;
6734 if( regHit ){
6735 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
6737 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
6738 sqlite3ExprCode(pParse, pC->pCExpr, AggInfoColumnReg(pAggInfo,i));
6741 pAggInfo->directMode = 0;
6742 if( addrHitTest ){
6743 sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
6748 ** Add a single OP_Explain instruction to the VDBE to explain a simple
6749 ** count(*) query ("SELECT count(*) FROM pTab").
6751 #ifndef SQLITE_OMIT_EXPLAIN
6752 static void explainSimpleCount(
6753 Parse *pParse, /* Parse context */
6754 Table *pTab, /* Table being queried */
6755 Index *pIdx /* Index used to optimize scan, or NULL */
6757 if( pParse->explain==2 ){
6758 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
6759 sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
6760 pTab->zName,
6761 bCover ? " USING COVERING INDEX " : "",
6762 bCover ? pIdx->zName : ""
6766 #else
6767 # define explainSimpleCount(a,b,c)
6768 #endif
6771 ** sqlite3WalkExpr() callback used by havingToWhere().
6773 ** If the node passed to the callback is a TK_AND node, return
6774 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
6776 ** Otherwise, return WRC_Prune. In this case, also check if the
6777 ** sub-expression matches the criteria for being moved to the WHERE
6778 ** clause. If so, add it to the WHERE clause and replace the sub-expression
6779 ** within the HAVING expression with a constant "1".
6781 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
6782 if( pExpr->op!=TK_AND ){
6783 Select *pS = pWalker->u.pSelect;
6784 /* This routine is called before the HAVING clause of the current
6785 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
6786 ** here, it indicates that the expression is a correlated reference to a
6787 ** column from an outer aggregate query, or an aggregate function that
6788 ** belongs to an outer query. Do not move the expression to the WHERE
6789 ** clause in this obscure case, as doing so may corrupt the outer Select
6790 ** statements AggInfo structure. */
6791 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
6792 && ExprAlwaysFalse(pExpr)==0
6793 && pExpr->pAggInfo==0
6795 sqlite3 *db = pWalker->pParse->db;
6796 Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
6797 if( pNew ){
6798 Expr *pWhere = pS->pWhere;
6799 SWAP(Expr, *pNew, *pExpr);
6800 pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
6801 pS->pWhere = pNew;
6802 pWalker->eCode = 1;
6805 return WRC_Prune;
6807 return WRC_Continue;
6811 ** Transfer eligible terms from the HAVING clause of a query, which is
6812 ** processed after grouping, to the WHERE clause, which is processed before
6813 ** grouping. For example, the query:
6815 ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
6817 ** can be rewritten as:
6819 ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
6821 ** A term of the HAVING expression is eligible for transfer if it consists
6822 ** entirely of constants and expressions that are also GROUP BY terms that
6823 ** use the "BINARY" collation sequence.
6825 static void havingToWhere(Parse *pParse, Select *p){
6826 Walker sWalker;
6827 memset(&sWalker, 0, sizeof(sWalker));
6828 sWalker.pParse = pParse;
6829 sWalker.xExprCallback = havingToWhereExprCb;
6830 sWalker.u.pSelect = p;
6831 sqlite3WalkExpr(&sWalker, p->pHaving);
6832 #if TREETRACE_ENABLED
6833 if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
6834 TREETRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
6835 sqlite3TreeViewSelect(0, p, 0);
6837 #endif
6841 ** Check to see if the pThis entry of pTabList is a self-join of another view.
6842 ** Search FROM-clause entries in the range of iFirst..iEnd, including iFirst
6843 ** but stopping before iEnd.
6845 ** If pThis is a self-join, then return the SrcItem for the first other
6846 ** instance of that view found. If pThis is not a self-join then return 0.
6848 static SrcItem *isSelfJoinView(
6849 SrcList *pTabList, /* Search for self-joins in this FROM clause */
6850 SrcItem *pThis, /* Search for prior reference to this subquery */
6851 int iFirst, int iEnd /* Range of FROM-clause entries to search. */
6853 SrcItem *pItem;
6854 assert( pThis->pSelect!=0 );
6855 if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
6856 while( iFirst<iEnd ){
6857 Select *pS1;
6858 pItem = &pTabList->a[iFirst++];
6859 if( pItem->pSelect==0 ) continue;
6860 if( pItem->fg.viaCoroutine ) continue;
6861 if( pItem->zName==0 ) continue;
6862 assert( pItem->pTab!=0 );
6863 assert( pThis->pTab!=0 );
6864 if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
6865 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
6866 pS1 = pItem->pSelect;
6867 if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
6868 /* The query flattener left two different CTE tables with identical
6869 ** names in the same FROM clause. */
6870 continue;
6872 if( pItem->pSelect->selFlags & SF_PushDown ){
6873 /* The view was modified by some other optimization such as
6874 ** pushDownWhereTerms() */
6875 continue;
6877 return pItem;
6879 return 0;
6883 ** Deallocate a single AggInfo object
6885 static void agginfoFree(sqlite3 *db, AggInfo *p){
6886 sqlite3DbFree(db, p->aCol);
6887 sqlite3DbFree(db, p->aFunc);
6888 sqlite3DbFreeNN(db, p);
6892 ** Attempt to transform a query of the form
6894 ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
6896 ** Into this:
6898 ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
6900 ** The transformation only works if all of the following are true:
6902 ** * The subquery is a UNION ALL of two or more terms
6903 ** * The subquery does not have a LIMIT clause
6904 ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
6905 ** * The outer query is a simple count(*) with no WHERE clause or other
6906 ** extraneous syntax.
6908 ** Return TRUE if the optimization is undertaken.
6910 static int countOfViewOptimization(Parse *pParse, Select *p){
6911 Select *pSub, *pPrior;
6912 Expr *pExpr;
6913 Expr *pCount;
6914 sqlite3 *db;
6915 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
6916 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
6917 if( p->pWhere ) return 0;
6918 if( p->pHaving ) return 0;
6919 if( p->pGroupBy ) return 0;
6920 if( p->pOrderBy ) return 0;
6921 pExpr = p->pEList->a[0].pExpr;
6922 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
6923 assert( ExprUseUToken(pExpr) );
6924 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
6925 assert( ExprUseXList(pExpr) );
6926 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
6927 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
6928 if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
6929 pSub = p->pSrc->a[0].pSelect;
6930 if( pSub==0 ) return 0; /* The FROM is a subquery */
6931 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
6932 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
6934 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
6935 if( pSub->pWhere ) return 0; /* No WHERE clause */
6936 if( pSub->pLimit ) return 0; /* No LIMIT clause */
6937 if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
6938 assert( pSub->pHaving==0 ); /* Due to the previous */
6939 pSub = pSub->pPrior; /* Repeat over compound */
6940 }while( pSub );
6942 /* If we reach this point then it is OK to perform the transformation */
6944 db = pParse->db;
6945 pCount = pExpr;
6946 pExpr = 0;
6947 pSub = p->pSrc->a[0].pSelect;
6948 p->pSrc->a[0].pSelect = 0;
6949 sqlite3SrcListDelete(db, p->pSrc);
6950 p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
6951 while( pSub ){
6952 Expr *pTerm;
6953 pPrior = pSub->pPrior;
6954 pSub->pPrior = 0;
6955 pSub->pNext = 0;
6956 pSub->selFlags |= SF_Aggregate;
6957 pSub->selFlags &= ~SF_Compound;
6958 pSub->nSelectRow = 0;
6959 sqlite3ExprListDelete(db, pSub->pEList);
6960 pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
6961 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
6962 pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
6963 sqlite3PExprAddSelect(pParse, pTerm, pSub);
6964 if( pExpr==0 ){
6965 pExpr = pTerm;
6966 }else{
6967 pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
6969 pSub = pPrior;
6971 p->pEList->a[0].pExpr = pExpr;
6972 p->selFlags &= ~SF_Aggregate;
6974 #if TREETRACE_ENABLED
6975 if( sqlite3TreeTrace & 0x200 ){
6976 TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
6977 sqlite3TreeViewSelect(0, p, 0);
6979 #endif
6980 return 1;
6984 ** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
6985 ** as pSrcItem but has the same alias as p0, then return true.
6986 ** Otherwise return false.
6988 static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
6989 int i;
6990 for(i=0; i<pSrc->nSrc; i++){
6991 SrcItem *p1 = &pSrc->a[i];
6992 if( p1==p0 ) continue;
6993 if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
6994 return 1;
6996 if( p1->pSelect
6997 && (p1->pSelect->selFlags & SF_NestedFrom)!=0
6998 && sameSrcAlias(p0, p1->pSelect->pSrc)
7000 return 1;
7003 return 0;
7007 ** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
7008 ** be implemented as a co-routine. The i-th entry is guaranteed to be
7009 ** a subquery.
7011 ** The subquery is implemented as a co-routine if all of the following are
7012 ** true:
7014 ** (1) The subquery will likely be implemented in the outer loop of
7015 ** the query. This will be the case if any one of the following
7016 ** conditions hold:
7017 ** (a) The subquery is the only term in the FROM clause
7018 ** (b) The subquery is the left-most term and a CROSS JOIN or similar
7019 ** requires it to be the outer loop
7020 ** (c) All of the following are true:
7021 ** (i) The subquery is the left-most subquery in the FROM clause
7022 ** (ii) There is nothing that would prevent the subquery from
7023 ** being used as the outer loop if the sqlite3WhereBegin()
7024 ** routine nominates it to that position.
7025 ** (iii) The query is not a UPDATE ... FROM
7026 ** (2) The subquery is not a CTE that should be materialized because
7027 ** (a) the AS MATERIALIZED keyword is used, or
7028 ** (b) the CTE is used multiple times and does not have the
7029 ** NOT MATERIALIZED keyword
7030 ** (3) The subquery is not part of a left operand for a RIGHT JOIN
7031 ** (4) The SQLITE_Coroutine optimization disable flag is not set
7032 ** (5) The subquery is not self-joined
7034 static int fromClauseTermCanBeCoroutine(
7035 Parse *pParse, /* Parsing context */
7036 SrcList *pTabList, /* FROM clause */
7037 int i, /* Which term of the FROM clause holds the subquery */
7038 int selFlags /* Flags on the SELECT statement */
7040 SrcItem *pItem = &pTabList->a[i];
7041 if( pItem->fg.isCte ){
7042 const CteUse *pCteUse = pItem->u2.pCteUse;
7043 if( pCteUse->eM10d==M10d_Yes ) return 0; /* (2a) */
7044 if( pCteUse->nUse>=2 && pCteUse->eM10d!=M10d_No ) return 0; /* (2b) */
7046 if( pTabList->a[0].fg.jointype & JT_LTORJ ) return 0; /* (3) */
7047 if( OptimizationDisabled(pParse->db, SQLITE_Coroutines) ) return 0; /* (4) */
7048 if( isSelfJoinView(pTabList, pItem, i+1, pTabList->nSrc)!=0 ){
7049 return 0; /* (5) */
7051 if( i==0 ){
7052 if( pTabList->nSrc==1 ) return 1; /* (1a) */
7053 if( pTabList->a[1].fg.jointype & JT_CROSS ) return 1; /* (1b) */
7054 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7055 return 1;
7057 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7058 while( 1 /*exit-by-break*/ ){
7059 if( pItem->fg.jointype & (JT_OUTER|JT_CROSS) ) return 0; /* (1c-ii) */
7060 if( i==0 ) break;
7061 i--;
7062 pItem--;
7063 if( pItem->pSelect!=0 ) return 0; /* (1c-i) */
7065 return 1;
7069 ** Generate code for the SELECT statement given in the p argument.
7071 ** The results are returned according to the SelectDest structure.
7072 ** See comments in sqliteInt.h for further information.
7074 ** This routine returns the number of errors. If any errors are
7075 ** encountered, then an appropriate error message is left in
7076 ** pParse->zErrMsg.
7078 ** This routine does NOT free the Select structure passed in. The
7079 ** calling function needs to do that.
7081 int sqlite3Select(
7082 Parse *pParse, /* The parser context */
7083 Select *p, /* The SELECT statement being coded. */
7084 SelectDest *pDest /* What to do with the query results */
7086 int i, j; /* Loop counters */
7087 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
7088 Vdbe *v; /* The virtual machine under construction */
7089 int isAgg; /* True for select lists like "count(*)" */
7090 ExprList *pEList = 0; /* List of columns to extract. */
7091 SrcList *pTabList; /* List of tables to select from */
7092 Expr *pWhere; /* The WHERE clause. May be NULL */
7093 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
7094 Expr *pHaving; /* The HAVING clause. May be NULL */
7095 AggInfo *pAggInfo = 0; /* Aggregate information */
7096 int rc = 1; /* Value to return from this function */
7097 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
7098 SortCtx sSort; /* Info on how to code the ORDER BY clause */
7099 int iEnd; /* Address of the end of the query */
7100 sqlite3 *db; /* The database connection */
7101 ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
7102 u8 minMaxFlag; /* Flag for min/max queries */
7104 db = pParse->db;
7105 assert( pParse==db->pParse );
7106 v = sqlite3GetVdbe(pParse);
7107 if( p==0 || pParse->nErr ){
7108 return 1;
7110 assert( db->mallocFailed==0 );
7111 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
7112 #if TREETRACE_ENABLED
7113 TREETRACE(0x1,pParse,p, ("begin processing:\n", pParse->addrExplain));
7114 if( sqlite3TreeTrace & 0x10000 ){
7115 if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
7116 sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
7117 __FILE__, __LINE__);
7119 sqlite3ShowSelect(p);
7121 #endif
7123 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
7124 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
7125 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
7126 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
7127 if( IgnorableDistinct(pDest) ){
7128 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
7129 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
7130 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
7131 /* All of these destinations are also able to ignore the ORDER BY clause */
7132 if( p->pOrderBy ){
7133 #if TREETRACE_ENABLED
7134 TREETRACE(0x800,pParse,p, ("dropping superfluous ORDER BY:\n"));
7135 if( sqlite3TreeTrace & 0x800 ){
7136 sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
7138 #endif
7139 sqlite3ParserAddCleanup(pParse,
7140 (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
7141 p->pOrderBy);
7142 testcase( pParse->earlyCleanup );
7143 p->pOrderBy = 0;
7145 p->selFlags &= ~SF_Distinct;
7146 p->selFlags |= SF_NoopOrderBy;
7148 sqlite3SelectPrep(pParse, p, 0);
7149 if( pParse->nErr ){
7150 goto select_end;
7152 assert( db->mallocFailed==0 );
7153 assert( p->pEList!=0 );
7154 #if TREETRACE_ENABLED
7155 if( sqlite3TreeTrace & 0x10 ){
7156 TREETRACE(0x10,pParse,p, ("after name resolution:\n"));
7157 sqlite3TreeViewSelect(0, p, 0);
7159 #endif
7161 /* If the SF_UFSrcCheck flag is set, then this function is being called
7162 ** as part of populating the temp table for an UPDATE...FROM statement.
7163 ** In this case, it is an error if the target object (pSrc->a[0]) name
7164 ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
7166 ** Postgres disallows this case too. The reason is that some other
7167 ** systems handle this case differently, and not all the same way,
7168 ** which is just confusing. To avoid this, we follow PG's lead and
7169 ** disallow it altogether. */
7170 if( p->selFlags & SF_UFSrcCheck ){
7171 SrcItem *p0 = &p->pSrc->a[0];
7172 if( sameSrcAlias(p0, p->pSrc) ){
7173 sqlite3ErrorMsg(pParse,
7174 "target object/alias may not appear in FROM clause: %s",
7175 p0->zAlias ? p0->zAlias : p0->pTab->zName
7177 goto select_end;
7180 /* Clear the SF_UFSrcCheck flag. The check has already been performed,
7181 ** and leaving this flag set can cause errors if a compound sub-query
7182 ** in p->pSrc is flattened into this query and this function called
7183 ** again as part of compound SELECT processing. */
7184 p->selFlags &= ~SF_UFSrcCheck;
7187 if( pDest->eDest==SRT_Output ){
7188 sqlite3GenerateColumnNames(pParse, p);
7191 #ifndef SQLITE_OMIT_WINDOWFUNC
7192 if( sqlite3WindowRewrite(pParse, p) ){
7193 assert( pParse->nErr );
7194 goto select_end;
7196 #if TREETRACE_ENABLED
7197 if( p->pWin && (sqlite3TreeTrace & 0x40)!=0 ){
7198 TREETRACE(0x40,pParse,p, ("after window rewrite:\n"));
7199 sqlite3TreeViewSelect(0, p, 0);
7201 #endif
7202 #endif /* SQLITE_OMIT_WINDOWFUNC */
7203 pTabList = p->pSrc;
7204 isAgg = (p->selFlags & SF_Aggregate)!=0;
7205 memset(&sSort, 0, sizeof(sSort));
7206 sSort.pOrderBy = p->pOrderBy;
7208 /* Try to do various optimizations (flattening subqueries, and strength
7209 ** reduction of join operators) in the FROM clause up into the main query
7211 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7212 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
7213 SrcItem *pItem = &pTabList->a[i];
7214 Select *pSub = pItem->pSelect;
7215 Table *pTab = pItem->pTab;
7217 /* The expander should have already created transient Table objects
7218 ** even for FROM clause elements such as subqueries that do not correspond
7219 ** to a real table */
7220 assert( pTab!=0 );
7222 /* Convert LEFT JOIN into JOIN if there are terms of the right table
7223 ** of the LEFT JOIN used in the WHERE clause.
7225 if( (pItem->fg.jointype & (JT_LEFT|JT_RIGHT))==JT_LEFT
7226 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor)
7227 && OptimizationEnabled(db, SQLITE_SimplifyJoin)
7229 TREETRACE(0x1000,pParse,p,
7230 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
7231 pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
7232 assert( pItem->iCursor>=0 );
7233 unsetJoinExpr(p->pWhere, pItem->iCursor,
7234 pTabList->a[0].fg.jointype & JT_LTORJ);
7237 /* No futher action if this term of the FROM clause is not a subquery */
7238 if( pSub==0 ) continue;
7240 /* Catch mismatch in the declared columns of a view and the number of
7241 ** columns in the SELECT on the RHS */
7242 if( pTab->nCol!=pSub->pEList->nExpr ){
7243 sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
7244 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
7245 goto select_end;
7248 /* Do not try to flatten an aggregate subquery.
7250 ** Flattening an aggregate subquery is only possible if the outer query
7251 ** is not a join. But if the outer query is not a join, then the subquery
7252 ** will be implemented as a co-routine and there is no advantage to
7253 ** flattening in that case.
7255 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
7256 assert( pSub->pGroupBy==0 );
7258 /* If a FROM-clause subquery has an ORDER BY clause that is not
7259 ** really doing anything, then delete it now so that it does not
7260 ** interfere with query flattening. See the discussion at
7261 ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
7263 ** Beware of these cases where the ORDER BY clause may not be safely
7264 ** omitted:
7266 ** (1) There is also a LIMIT clause
7267 ** (2) The subquery was added to help with window-function
7268 ** processing
7269 ** (3) The subquery is in the FROM clause of an UPDATE
7270 ** (4) The outer query uses an aggregate function other than
7271 ** the built-in count(), min(), or max().
7272 ** (5) The ORDER BY isn't going to accomplish anything because
7273 ** one of:
7274 ** (a) The outer query has a different ORDER BY clause
7275 ** (b) The subquery is part of a join
7276 ** See forum post 062d576715d277c8
7278 if( pSub->pOrderBy!=0
7279 && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */
7280 && pSub->pLimit==0 /* Condition (1) */
7281 && (pSub->selFlags & SF_OrderByReqd)==0 /* Condition (2) */
7282 && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
7283 && OptimizationEnabled(db, SQLITE_OmitOrderBy)
7285 TREETRACE(0x800,pParse,p,
7286 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
7287 sqlite3ParserAddCleanup(pParse,
7288 (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
7289 pSub->pOrderBy);
7290 pSub->pOrderBy = 0;
7293 /* If the outer query contains a "complex" result set (that is,
7294 ** if the result set of the outer query uses functions or subqueries)
7295 ** and if the subquery contains an ORDER BY clause and if
7296 ** it will be implemented as a co-routine, then do not flatten. This
7297 ** restriction allows SQL constructs like this:
7299 ** SELECT expensive_function(x)
7300 ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
7302 ** The expensive_function() is only computed on the 10 rows that
7303 ** are output, rather than every row of the table.
7305 ** The requirement that the outer query have a complex result set
7306 ** means that flattening does occur on simpler SQL constraints without
7307 ** the expensive_function() like:
7309 ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
7311 if( pSub->pOrderBy!=0
7312 && i==0
7313 && (p->selFlags & SF_ComplexResult)!=0
7314 && (pTabList->nSrc==1
7315 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
7317 continue;
7320 if( flattenSubquery(pParse, p, i, isAgg) ){
7321 if( pParse->nErr ) goto select_end;
7322 /* This subquery can be absorbed into its parent. */
7323 i = -1;
7325 pTabList = p->pSrc;
7326 if( db->mallocFailed ) goto select_end;
7327 if( !IgnorableOrderby(pDest) ){
7328 sSort.pOrderBy = p->pOrderBy;
7331 #endif
7333 #ifndef SQLITE_OMIT_COMPOUND_SELECT
7334 /* Handle compound SELECT statements using the separate multiSelect()
7335 ** procedure.
7337 if( p->pPrior ){
7338 rc = multiSelect(pParse, p, pDest);
7339 #if TREETRACE_ENABLED
7340 TREETRACE(0x400,pParse,p,("end compound-select processing\n"));
7341 if( (sqlite3TreeTrace & 0x400)!=0 && ExplainQueryPlanParent(pParse)==0 ){
7342 sqlite3TreeViewSelect(0, p, 0);
7344 #endif
7345 if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
7346 return rc;
7348 #endif
7350 /* Do the WHERE-clause constant propagation optimization if this is
7351 ** a join. No need to speed time on this operation for non-join queries
7352 ** as the equivalent optimization will be handled by query planner in
7353 ** sqlite3WhereBegin().
7355 if( p->pWhere!=0
7356 && p->pWhere->op==TK_AND
7357 && OptimizationEnabled(db, SQLITE_PropagateConst)
7358 && propagateConstants(pParse, p)
7360 #if TREETRACE_ENABLED
7361 if( sqlite3TreeTrace & 0x2000 ){
7362 TREETRACE(0x2000,pParse,p,("After constant propagation:\n"));
7363 sqlite3TreeViewSelect(0, p, 0);
7365 #endif
7366 }else{
7367 TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
7370 if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
7371 && countOfViewOptimization(pParse, p)
7373 if( db->mallocFailed ) goto select_end;
7374 pTabList = p->pSrc;
7377 /* For each term in the FROM clause, do two things:
7378 ** (1) Authorized unreferenced tables
7379 ** (2) Generate code for all sub-queries
7381 for(i=0; i<pTabList->nSrc; i++){
7382 SrcItem *pItem = &pTabList->a[i];
7383 SrcItem *pPrior;
7384 SelectDest dest;
7385 Select *pSub;
7386 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7387 const char *zSavedAuthContext;
7388 #endif
7390 /* Issue SQLITE_READ authorizations with a fake column name for any
7391 ** tables that are referenced but from which no values are extracted.
7392 ** Examples of where these kinds of null SQLITE_READ authorizations
7393 ** would occur:
7395 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
7396 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
7398 ** The fake column name is an empty string. It is possible for a table to
7399 ** have a column named by the empty string, in which case there is no way to
7400 ** distinguish between an unreferenced table and an actual reference to the
7401 ** "" column. The original design was for the fake column name to be a NULL,
7402 ** which would be unambiguous. But legacy authorization callbacks might
7403 ** assume the column name is non-NULL and segfault. The use of an empty
7404 ** string for the fake column name seems safer.
7406 if( pItem->colUsed==0 && pItem->zName!=0 ){
7407 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
7410 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7411 /* Generate code for all sub-queries in the FROM clause
7413 pSub = pItem->pSelect;
7414 if( pSub==0 ) continue;
7416 /* The code for a subquery should only be generated once. */
7417 assert( pItem->addrFillSub==0 );
7419 /* Increment Parse.nHeight by the height of the largest expression
7420 ** tree referred to by this, the parent select. The child select
7421 ** may contain expression trees of at most
7422 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
7423 ** more conservative than necessary, but much easier than enforcing
7424 ** an exact limit.
7426 pParse->nHeight += sqlite3SelectExprHeight(p);
7428 /* Make copies of constant WHERE-clause terms in the outer query down
7429 ** inside the subquery. This can help the subquery to run more efficiently.
7431 if( OptimizationEnabled(db, SQLITE_PushDown)
7432 && (pItem->fg.isCte==0
7433 || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
7434 && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
7436 #if TREETRACE_ENABLED
7437 if( sqlite3TreeTrace & 0x4000 ){
7438 TREETRACE(0x4000,pParse,p,
7439 ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
7440 sqlite3TreeViewSelect(0, p, 0);
7442 #endif
7443 assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
7444 }else{
7445 TREETRACE(0x4000,pParse,p,("Push-down not possible\n"));
7448 /* Convert unused result columns of the subquery into simple NULL
7449 ** expressions, to avoid unneeded searching and computation.
7451 if( OptimizationEnabled(db, SQLITE_NullUnusedCols)
7452 && disableUnusedSubqueryResultColumns(pItem)
7454 #if TREETRACE_ENABLED
7455 if( sqlite3TreeTrace & 0x4000 ){
7456 TREETRACE(0x4000,pParse,p,
7457 ("Change unused result columns to NULL for subquery %d:\n",
7458 pSub->selId));
7459 sqlite3TreeViewSelect(0, p, 0);
7461 #endif
7464 zSavedAuthContext = pParse->zAuthContext;
7465 pParse->zAuthContext = pItem->zName;
7467 /* Generate code to implement the subquery
7469 if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
7470 /* Implement a co-routine that will return a single row of the result
7471 ** set on each invocation.
7473 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
7475 pItem->regReturn = ++pParse->nMem;
7476 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
7477 VdbeComment((v, "%!S", pItem));
7478 pItem->addrFillSub = addrTop;
7479 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
7480 ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
7481 sqlite3Select(pParse, pSub, &dest);
7482 pItem->pTab->nRowLogEst = pSub->nSelectRow;
7483 pItem->fg.viaCoroutine = 1;
7484 pItem->regResult = dest.iSdst;
7485 sqlite3VdbeEndCoroutine(v, pItem->regReturn);
7486 sqlite3VdbeJumpHere(v, addrTop-1);
7487 sqlite3ClearTempRegCache(pParse);
7488 }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
7489 /* This is a CTE for which materialization code has already been
7490 ** generated. Invoke the subroutine to compute the materialization,
7491 ** the make the pItem->iCursor be a copy of the ephemerial table that
7492 ** holds the result of the materialization. */
7493 CteUse *pCteUse = pItem->u2.pCteUse;
7494 sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
7495 if( pItem->iCursor!=pCteUse->iCur ){
7496 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
7497 VdbeComment((v, "%!S", pItem));
7499 pSub->nSelectRow = pCteUse->nRowEst;
7500 }else if( (pPrior = isSelfJoinView(pTabList, pItem, 0, i))!=0 ){
7501 /* This view has already been materialized by a prior entry in
7502 ** this same FROM clause. Reuse it. */
7503 if( pPrior->addrFillSub ){
7504 sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
7506 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
7507 pSub->nSelectRow = pPrior->pSelect->nSelectRow;
7508 }else{
7509 /* Materialize the view. If the view is not correlated, generate a
7510 ** subroutine to do the materialization so that subsequent uses of
7511 ** the same view can reuse the materialization. */
7512 int topAddr;
7513 int onceAddr = 0;
7514 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
7515 int addrExplain;
7516 #endif
7518 pItem->regReturn = ++pParse->nMem;
7519 topAddr = sqlite3VdbeAddOp0(v, OP_Goto);
7520 pItem->addrFillSub = topAddr+1;
7521 pItem->fg.isMaterialized = 1;
7522 if( pItem->fg.isCorrelated==0 ){
7523 /* If the subquery is not correlated and if we are not inside of
7524 ** a trigger, then we only need to compute the value of the subquery
7525 ** once. */
7526 onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
7527 VdbeComment((v, "materialize %!S", pItem));
7528 }else{
7529 VdbeNoopComment((v, "materialize %!S", pItem));
7531 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
7533 ExplainQueryPlan2(addrExplain, (pParse, 1, "MATERIALIZE %!S", pItem));
7534 sqlite3Select(pParse, pSub, &dest);
7535 pItem->pTab->nRowLogEst = pSub->nSelectRow;
7536 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
7537 sqlite3VdbeAddOp2(v, OP_Return, pItem->regReturn, topAddr+1);
7538 VdbeComment((v, "end %!S", pItem));
7539 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
7540 sqlite3VdbeJumpHere(v, topAddr);
7541 sqlite3ClearTempRegCache(pParse);
7542 if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
7543 CteUse *pCteUse = pItem->u2.pCteUse;
7544 pCteUse->addrM9e = pItem->addrFillSub;
7545 pCteUse->regRtn = pItem->regReturn;
7546 pCteUse->iCur = pItem->iCursor;
7547 pCteUse->nRowEst = pSub->nSelectRow;
7550 if( db->mallocFailed ) goto select_end;
7551 pParse->nHeight -= sqlite3SelectExprHeight(p);
7552 pParse->zAuthContext = zSavedAuthContext;
7553 #endif
7556 /* Various elements of the SELECT copied into local variables for
7557 ** convenience */
7558 pEList = p->pEList;
7559 pWhere = p->pWhere;
7560 pGroupBy = p->pGroupBy;
7561 pHaving = p->pHaving;
7562 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
7564 #if TREETRACE_ENABLED
7565 if( sqlite3TreeTrace & 0x8000 ){
7566 TREETRACE(0x8000,pParse,p,("After all FROM-clause analysis:\n"));
7567 sqlite3TreeViewSelect(0, p, 0);
7569 #endif
7571 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
7572 ** if the select-list is the same as the ORDER BY list, then this query
7573 ** can be rewritten as a GROUP BY. In other words, this:
7575 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
7577 ** is transformed to:
7579 ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
7581 ** The second form is preferred as a single index (or temp-table) may be
7582 ** used for both the ORDER BY and DISTINCT processing. As originally
7583 ** written the query must use a temp-table for at least one of the ORDER
7584 ** BY and DISTINCT, and an index or separate temp-table for the other.
7586 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
7587 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
7588 #ifndef SQLITE_OMIT_WINDOWFUNC
7589 && p->pWin==0
7590 #endif
7592 p->selFlags &= ~SF_Distinct;
7593 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
7594 p->selFlags |= SF_Aggregate;
7595 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
7596 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
7597 ** original setting of the SF_Distinct flag, not the current setting */
7598 assert( sDistinct.isTnct );
7599 sDistinct.isTnct = 2;
7601 #if TREETRACE_ENABLED
7602 if( sqlite3TreeTrace & 0x20000 ){
7603 TREETRACE(0x20000,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
7604 sqlite3TreeViewSelect(0, p, 0);
7606 #endif
7609 /* If there is an ORDER BY clause, then create an ephemeral index to
7610 ** do the sorting. But this sorting ephemeral index might end up
7611 ** being unused if the data can be extracted in pre-sorted order.
7612 ** If that is the case, then the OP_OpenEphemeral instruction will be
7613 ** changed to an OP_Noop once we figure out that the sorting index is
7614 ** not needed. The sSort.addrSortIndex variable is used to facilitate
7615 ** that change.
7617 if( sSort.pOrderBy ){
7618 KeyInfo *pKeyInfo;
7619 pKeyInfo = sqlite3KeyInfoFromExprList(
7620 pParse, sSort.pOrderBy, 0, pEList->nExpr);
7621 sSort.iECursor = pParse->nTab++;
7622 sSort.addrSortIndex =
7623 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7624 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
7625 (char*)pKeyInfo, P4_KEYINFO
7627 }else{
7628 sSort.addrSortIndex = -1;
7631 /* If the output is destined for a temporary table, open that table.
7633 if( pDest->eDest==SRT_EphemTab ){
7634 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
7635 if( p->selFlags & SF_NestedFrom ){
7636 /* Delete or NULL-out result columns that will never be used */
7637 int ii;
7638 for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
7639 sqlite3ExprDelete(db, pEList->a[ii].pExpr);
7640 sqlite3DbFree(db, pEList->a[ii].zEName);
7641 pEList->nExpr--;
7643 for(ii=0; ii<pEList->nExpr; ii++){
7644 if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
7649 /* Set the limiter.
7651 iEnd = sqlite3VdbeMakeLabel(pParse);
7652 if( (p->selFlags & SF_FixedLimit)==0 ){
7653 p->nSelectRow = 320; /* 4 billion rows */
7655 if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
7656 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
7657 sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
7658 sSort.sortFlags |= SORTFLAG_UseSorter;
7661 /* Open an ephemeral index to use for the distinct set.
7663 if( p->selFlags & SF_Distinct ){
7664 sDistinct.tabTnct = pParse->nTab++;
7665 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7666 sDistinct.tabTnct, 0, 0,
7667 (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
7668 P4_KEYINFO);
7669 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
7670 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
7671 }else{
7672 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
7675 if( !isAgg && pGroupBy==0 ){
7676 /* No aggregate functions and no GROUP BY clause */
7677 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
7678 | (p->selFlags & SF_FixedLimit);
7679 #ifndef SQLITE_OMIT_WINDOWFUNC
7680 Window *pWin = p->pWin; /* Main window object (or NULL) */
7681 if( pWin ){
7682 sqlite3WindowCodeInit(pParse, p);
7684 #endif
7685 assert( WHERE_USE_LIMIT==SF_FixedLimit );
7688 /* Begin the database scan. */
7689 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
7690 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
7691 p->pEList, p, wctrlFlags, p->nSelectRow);
7692 if( pWInfo==0 ) goto select_end;
7693 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
7694 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
7696 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
7697 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
7699 if( sSort.pOrderBy ){
7700 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
7701 sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
7702 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
7703 sSort.pOrderBy = 0;
7706 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
7708 /* If sorting index that was created by a prior OP_OpenEphemeral
7709 ** instruction ended up not being needed, then change the OP_OpenEphemeral
7710 ** into an OP_Noop.
7712 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
7713 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
7716 assert( p->pEList==pEList );
7717 #ifndef SQLITE_OMIT_WINDOWFUNC
7718 if( pWin ){
7719 int addrGosub = sqlite3VdbeMakeLabel(pParse);
7720 int iCont = sqlite3VdbeMakeLabel(pParse);
7721 int iBreak = sqlite3VdbeMakeLabel(pParse);
7722 int regGosub = ++pParse->nMem;
7724 sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
7726 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
7727 sqlite3VdbeResolveLabel(v, addrGosub);
7728 VdbeNoopComment((v, "inner-loop subroutine"));
7729 sSort.labelOBLopt = 0;
7730 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
7731 sqlite3VdbeResolveLabel(v, iCont);
7732 sqlite3VdbeAddOp1(v, OP_Return, regGosub);
7733 VdbeComment((v, "end inner-loop subroutine"));
7734 sqlite3VdbeResolveLabel(v, iBreak);
7735 }else
7736 #endif /* SQLITE_OMIT_WINDOWFUNC */
7738 /* Use the standard inner loop. */
7739 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
7740 sqlite3WhereContinueLabel(pWInfo),
7741 sqlite3WhereBreakLabel(pWInfo));
7743 /* End the database scan loop.
7745 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
7746 sqlite3WhereEnd(pWInfo);
7748 }else{
7749 /* This case when there exist aggregate functions or a GROUP BY clause
7750 ** or both */
7751 NameContext sNC; /* Name context for processing aggregate information */
7752 int iAMem; /* First Mem address for storing current GROUP BY */
7753 int iBMem; /* First Mem address for previous GROUP BY */
7754 int iUseFlag; /* Mem address holding flag indicating that at least
7755 ** one row of the input to the aggregator has been
7756 ** processed */
7757 int iAbortFlag; /* Mem address which causes query abort if positive */
7758 int groupBySort; /* Rows come from source in GROUP BY order */
7759 int addrEnd; /* End of processing for this SELECT */
7760 int sortPTab = 0; /* Pseudotable used to decode sorting results */
7761 int sortOut = 0; /* Output register from the sorter */
7762 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
7764 /* Remove any and all aliases between the result set and the
7765 ** GROUP BY clause.
7767 if( pGroupBy ){
7768 int k; /* Loop counter */
7769 struct ExprList_item *pItem; /* For looping over expression in a list */
7771 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
7772 pItem->u.x.iAlias = 0;
7774 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
7775 pItem->u.x.iAlias = 0;
7777 assert( 66==sqlite3LogEst(100) );
7778 if( p->nSelectRow>66 ) p->nSelectRow = 66;
7780 /* If there is both a GROUP BY and an ORDER BY clause and they are
7781 ** identical, then it may be possible to disable the ORDER BY clause
7782 ** on the grounds that the GROUP BY will cause elements to come out
7783 ** in the correct order. It also may not - the GROUP BY might use a
7784 ** database index that causes rows to be grouped together as required
7785 ** but not actually sorted. Either way, record the fact that the
7786 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
7787 ** variable. */
7788 if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
7789 int ii;
7790 /* The GROUP BY processing doesn't care whether rows are delivered in
7791 ** ASC or DESC order - only that each group is returned contiguously.
7792 ** So set the ASC/DESC flags in the GROUP BY to match those in the
7793 ** ORDER BY to maximize the chances of rows being delivered in an
7794 ** order that makes the ORDER BY redundant. */
7795 for(ii=0; ii<pGroupBy->nExpr; ii++){
7796 u8 sortFlags;
7797 sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
7798 pGroupBy->a[ii].fg.sortFlags = sortFlags;
7800 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
7801 orderByGrp = 1;
7804 }else{
7805 assert( 0==sqlite3LogEst(1) );
7806 p->nSelectRow = 0;
7809 /* Create a label to jump to when we want to abort the query */
7810 addrEnd = sqlite3VdbeMakeLabel(pParse);
7812 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
7813 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
7814 ** SELECT statement.
7816 pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
7817 if( pAggInfo ){
7818 sqlite3ParserAddCleanup(pParse,
7819 (void(*)(sqlite3*,void*))agginfoFree, pAggInfo);
7820 testcase( pParse->earlyCleanup );
7822 if( db->mallocFailed ){
7823 goto select_end;
7825 pAggInfo->selId = p->selId;
7826 #ifdef SQLITE_DEBUG
7827 pAggInfo->pSelect = p;
7828 #endif
7829 memset(&sNC, 0, sizeof(sNC));
7830 sNC.pParse = pParse;
7831 sNC.pSrcList = pTabList;
7832 sNC.uNC.pAggInfo = pAggInfo;
7833 VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
7834 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
7835 pAggInfo->pGroupBy = pGroupBy;
7836 sqlite3ExprAnalyzeAggList(&sNC, pEList);
7837 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
7838 if( pHaving ){
7839 if( pGroupBy ){
7840 assert( pWhere==p->pWhere );
7841 assert( pHaving==p->pHaving );
7842 assert( pGroupBy==p->pGroupBy );
7843 havingToWhere(pParse, p);
7844 pWhere = p->pWhere;
7846 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
7848 pAggInfo->nAccumulator = pAggInfo->nColumn;
7849 if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
7850 minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
7851 }else{
7852 minMaxFlag = WHERE_ORDERBY_NORMAL;
7854 analyzeAggFuncArgs(pAggInfo, &sNC);
7855 if( db->mallocFailed ) goto select_end;
7856 #if TREETRACE_ENABLED
7857 if( sqlite3TreeTrace & 0x20 ){
7858 TREETRACE(0x20,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
7859 sqlite3TreeViewSelect(0, p, 0);
7860 if( minMaxFlag ){
7861 sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
7862 sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
7864 printAggInfo(pAggInfo);
7866 #endif
7869 /* Processing for aggregates with GROUP BY is very different and
7870 ** much more complex than aggregates without a GROUP BY.
7872 if( pGroupBy ){
7873 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
7874 int addr1; /* A-vs-B comparision jump */
7875 int addrOutputRow; /* Start of subroutine that outputs a result row */
7876 int regOutputRow; /* Return address register for output subroutine */
7877 int addrSetAbort; /* Set the abort flag and return */
7878 int addrTopOfLoop; /* Top of the input loop */
7879 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
7880 int addrReset; /* Subroutine for resetting the accumulator */
7881 int regReset; /* Return address register for reset subroutine */
7882 ExprList *pDistinct = 0;
7883 u16 distFlag = 0;
7884 int eDist = WHERE_DISTINCT_NOOP;
7886 if( pAggInfo->nFunc==1
7887 && pAggInfo->aFunc[0].iDistinct>=0
7888 && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
7889 && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
7890 && pAggInfo->aFunc[0].pFExpr->x.pList!=0
7892 Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
7893 pExpr = sqlite3ExprDup(db, pExpr, 0);
7894 pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
7895 pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
7896 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
7899 /* If there is a GROUP BY clause we might need a sorting index to
7900 ** implement it. Allocate that sorting index now. If it turns out
7901 ** that we do not need it after all, the OP_SorterOpen instruction
7902 ** will be converted into a Noop.
7904 pAggInfo->sortingIdx = pParse->nTab++;
7905 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
7906 0, pAggInfo->nColumn);
7907 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
7908 pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
7909 0, (char*)pKeyInfo, P4_KEYINFO);
7911 /* Initialize memory locations used by GROUP BY aggregate processing
7913 iUseFlag = ++pParse->nMem;
7914 iAbortFlag = ++pParse->nMem;
7915 regOutputRow = ++pParse->nMem;
7916 addrOutputRow = sqlite3VdbeMakeLabel(pParse);
7917 regReset = ++pParse->nMem;
7918 addrReset = sqlite3VdbeMakeLabel(pParse);
7919 iAMem = pParse->nMem + 1;
7920 pParse->nMem += pGroupBy->nExpr;
7921 iBMem = pParse->nMem + 1;
7922 pParse->nMem += pGroupBy->nExpr;
7923 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
7924 VdbeComment((v, "clear abort flag"));
7925 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
7927 /* Begin a loop that will extract all source rows in GROUP BY order.
7928 ** This might involve two separate loops with an OP_Sort in between, or
7929 ** it might be a single loop that uses an index to extract information
7930 ** in the right order to begin with.
7932 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
7933 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
7934 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
7935 p, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
7936 | (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
7938 if( pWInfo==0 ){
7939 sqlite3ExprListDelete(db, pDistinct);
7940 goto select_end;
7942 if( pParse->pIdxEpr ){
7943 optimizeAggregateUseOfIndexedExpr(pParse, p, pAggInfo, &sNC);
7945 assignAggregateRegisters(pParse, pAggInfo);
7946 eDist = sqlite3WhereIsDistinct(pWInfo);
7947 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
7948 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
7949 /* The optimizer is able to deliver rows in group by order so
7950 ** we do not have to sort. The OP_OpenEphemeral table will be
7951 ** cancelled later because we still need to use the pKeyInfo
7953 groupBySort = 0;
7954 }else{
7955 /* Rows are coming out in undetermined order. We have to push
7956 ** each row into a sorting index, terminate the first loop,
7957 ** then loop over the sorting index in order to get the output
7958 ** in sorted order
7960 int regBase;
7961 int regRecord;
7962 int nCol;
7963 int nGroupBy;
7965 explainTempTable(pParse,
7966 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
7967 "DISTINCT" : "GROUP BY");
7969 groupBySort = 1;
7970 nGroupBy = pGroupBy->nExpr;
7971 nCol = nGroupBy;
7972 j = nGroupBy;
7973 for(i=0; i<pAggInfo->nColumn; i++){
7974 if( pAggInfo->aCol[i].iSorterColumn>=j ){
7975 nCol++;
7976 j++;
7979 regBase = sqlite3GetTempRange(pParse, nCol);
7980 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
7981 j = nGroupBy;
7982 pAggInfo->directMode = 1;
7983 for(i=0; i<pAggInfo->nColumn; i++){
7984 struct AggInfo_col *pCol = &pAggInfo->aCol[i];
7985 if( pCol->iSorterColumn>=j ){
7986 sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
7987 j++;
7990 pAggInfo->directMode = 0;
7991 regRecord = sqlite3GetTempReg(pParse);
7992 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
7993 sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
7994 sqlite3ReleaseTempReg(pParse, regRecord);
7995 sqlite3ReleaseTempRange(pParse, regBase, nCol);
7996 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
7997 sqlite3WhereEnd(pWInfo);
7998 pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
7999 sortOut = sqlite3GetTempReg(pParse);
8000 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
8001 sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
8002 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
8003 pAggInfo->useSortingIdx = 1;
8006 /* If there are entries in pAgggInfo->aFunc[] that contain subexpressions
8007 ** that are indexed (and that were previously identified and tagged
8008 ** in optimizeAggregateUseOfIndexedExpr()) then those subexpressions
8009 ** must now be converted into a TK_AGG_COLUMN node so that the value
8010 ** is correctly pulled from the index rather than being recomputed. */
8011 if( pParse->pIdxEpr ){
8012 aggregateConvertIndexedExprRefToColumn(pAggInfo);
8013 #if TREETRACE_ENABLED
8014 if( sqlite3TreeTrace & 0x20 ){
8015 TREETRACE(0x20, pParse, p,
8016 ("AggInfo function expressions converted to reference index\n"));
8017 sqlite3TreeViewSelect(0, p, 0);
8018 printAggInfo(pAggInfo);
8020 #endif
8023 /* If the index or temporary table used by the GROUP BY sort
8024 ** will naturally deliver rows in the order required by the ORDER BY
8025 ** clause, cancel the ephemeral table open coded earlier.
8027 ** This is an optimization - the correct answer should result regardless.
8028 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
8029 ** disable this optimization for testing purposes. */
8030 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
8031 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
8033 sSort.pOrderBy = 0;
8034 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
8037 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
8038 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
8039 ** Then compare the current GROUP BY terms against the GROUP BY terms
8040 ** from the previous row currently stored in a0, a1, a2...
8042 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
8043 if( groupBySort ){
8044 sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
8045 sortOut, sortPTab);
8047 for(j=0; j<pGroupBy->nExpr; j++){
8048 if( groupBySort ){
8049 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
8050 }else{
8051 pAggInfo->directMode = 1;
8052 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
8055 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
8056 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
8057 addr1 = sqlite3VdbeCurrentAddr(v);
8058 sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
8060 /* Generate code that runs whenever the GROUP BY changes.
8061 ** Changes in the GROUP BY are detected by the previous code
8062 ** block. If there were no changes, this block is skipped.
8064 ** This code copies current group by terms in b0,b1,b2,...
8065 ** over to a0,a1,a2. It then calls the output subroutine
8066 ** and resets the aggregate accumulator registers in preparation
8067 ** for the next GROUP BY batch.
8069 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
8070 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
8071 VdbeComment((v, "output one row"));
8072 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
8073 VdbeComment((v, "check abort flag"));
8074 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
8075 VdbeComment((v, "reset accumulator"));
8077 /* Update the aggregate accumulators based on the content of
8078 ** the current row
8080 sqlite3VdbeJumpHere(v, addr1);
8081 updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
8082 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
8083 VdbeComment((v, "indicate data in accumulator"));
8085 /* End of the loop
8087 if( groupBySort ){
8088 sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
8089 VdbeCoverage(v);
8090 }else{
8091 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8092 sqlite3WhereEnd(pWInfo);
8093 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
8095 sqlite3ExprListDelete(db, pDistinct);
8097 /* Output the final row of result
8099 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
8100 VdbeComment((v, "output final row"));
8102 /* Jump over the subroutines
8104 sqlite3VdbeGoto(v, addrEnd);
8106 /* Generate a subroutine that outputs a single row of the result
8107 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
8108 ** is less than or equal to zero, the subroutine is a no-op. If
8109 ** the processing calls for the query to abort, this subroutine
8110 ** increments the iAbortFlag memory location before returning in
8111 ** order to signal the caller to abort.
8113 addrSetAbort = sqlite3VdbeCurrentAddr(v);
8114 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
8115 VdbeComment((v, "set abort flag"));
8116 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8117 sqlite3VdbeResolveLabel(v, addrOutputRow);
8118 addrOutputRow = sqlite3VdbeCurrentAddr(v);
8119 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
8120 VdbeCoverage(v);
8121 VdbeComment((v, "Groupby result generator entry point"));
8122 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8123 finalizeAggFunctions(pParse, pAggInfo);
8124 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
8125 selectInnerLoop(pParse, p, -1, &sSort,
8126 &sDistinct, pDest,
8127 addrOutputRow+1, addrSetAbort);
8128 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8129 VdbeComment((v, "end groupby result generator"));
8131 /* Generate a subroutine that will reset the group-by accumulator
8133 sqlite3VdbeResolveLabel(v, addrReset);
8134 resetAccumulator(pParse, pAggInfo);
8135 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
8136 VdbeComment((v, "indicate accumulator empty"));
8137 sqlite3VdbeAddOp1(v, OP_Return, regReset);
8139 if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
8140 struct AggInfo_func *pF = &pAggInfo->aFunc[0];
8141 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
8143 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
8144 else {
8145 Table *pTab;
8146 if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
8147 /* If isSimpleCount() returns a pointer to a Table structure, then
8148 ** the SQL statement is of the form:
8150 ** SELECT count(*) FROM <tbl>
8152 ** where the Table structure returned represents table <tbl>.
8154 ** This statement is so common that it is optimized specially. The
8155 ** OP_Count instruction is executed either on the intkey table that
8156 ** contains the data for table <tbl> or on one of its indexes. It
8157 ** is better to execute the op on an index, as indexes are almost
8158 ** always spread across less pages than their corresponding tables.
8160 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
8161 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
8162 Index *pIdx; /* Iterator variable */
8163 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
8164 Index *pBest = 0; /* Best index found so far */
8165 Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
8167 sqlite3CodeVerifySchema(pParse, iDb);
8168 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
8170 /* Search for the index that has the lowest scan cost.
8172 ** (2011-04-15) Do not do a full scan of an unordered index.
8174 ** (2013-10-03) Do not count the entries in a partial index.
8176 ** In practice the KeyInfo structure will not be used. It is only
8177 ** passed to keep OP_OpenRead happy.
8179 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
8180 if( !p->pSrc->a[0].fg.notIndexed ){
8181 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
8182 if( pIdx->bUnordered==0
8183 && pIdx->szIdxRow<pTab->szTabRow
8184 && pIdx->pPartIdxWhere==0
8185 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
8187 pBest = pIdx;
8191 if( pBest ){
8192 iRoot = pBest->tnum;
8193 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
8196 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
8197 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
8198 if( pKeyInfo ){
8199 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
8201 assignAggregateRegisters(pParse, pAggInfo);
8202 sqlite3VdbeAddOp2(v, OP_Count, iCsr, AggInfoFuncReg(pAggInfo,0));
8203 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
8204 explainSimpleCount(pParse, pTab, pBest);
8205 }else{
8206 int regAcc = 0; /* "populate accumulators" flag */
8207 ExprList *pDistinct = 0;
8208 u16 distFlag = 0;
8209 int eDist;
8211 /* If there are accumulator registers but no min() or max() functions
8212 ** without FILTER clauses, allocate register regAcc. Register regAcc
8213 ** will contain 0 the first time the inner loop runs, and 1 thereafter.
8214 ** The code generated by updateAccumulator() uses this to ensure
8215 ** that the accumulator registers are (a) updated only once if
8216 ** there are no min() or max functions or (b) always updated for the
8217 ** first row visited by the aggregate, so that they are updated at
8218 ** least once even if the FILTER clause means the min() or max()
8219 ** function visits zero rows. */
8220 if( pAggInfo->nAccumulator ){
8221 for(i=0; i<pAggInfo->nFunc; i++){
8222 if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
8223 continue;
8225 if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
8226 break;
8229 if( i==pAggInfo->nFunc ){
8230 regAcc = ++pParse->nMem;
8231 sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
8233 }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
8234 assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
8235 pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
8236 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
8238 assignAggregateRegisters(pParse, pAggInfo);
8240 /* This case runs if the aggregate has no GROUP BY clause. The
8241 ** processing is much simpler since there is only a single row
8242 ** of output.
8244 assert( p->pGroupBy==0 );
8245 resetAccumulator(pParse, pAggInfo);
8247 /* If this query is a candidate for the min/max optimization, then
8248 ** minMaxFlag will have been previously set to either
8249 ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
8250 ** be an appropriate ORDER BY expression for the optimization.
8252 assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
8253 assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
8255 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8256 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
8257 pDistinct, p, minMaxFlag|distFlag, 0);
8258 if( pWInfo==0 ){
8259 goto select_end;
8261 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8262 eDist = sqlite3WhereIsDistinct(pWInfo);
8263 updateAccumulator(pParse, regAcc, pAggInfo, eDist);
8264 if( eDist!=WHERE_DISTINCT_NOOP ){
8265 struct AggInfo_func *pF = pAggInfo->aFunc;
8266 if( pF ){
8267 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
8271 if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
8272 if( minMaxFlag ){
8273 sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
8275 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8276 sqlite3WhereEnd(pWInfo);
8277 finalizeAggFunctions(pParse, pAggInfo);
8280 sSort.pOrderBy = 0;
8281 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
8282 selectInnerLoop(pParse, p, -1, 0, 0,
8283 pDest, addrEnd, addrEnd);
8285 sqlite3VdbeResolveLabel(v, addrEnd);
8287 } /* endif aggregate query */
8289 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
8290 explainTempTable(pParse, "DISTINCT");
8293 /* If there is an ORDER BY clause, then we need to sort the results
8294 ** and send them to the callback one by one.
8296 if( sSort.pOrderBy ){
8297 assert( p->pEList==pEList );
8298 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
8301 /* Jump here to skip this query
8303 sqlite3VdbeResolveLabel(v, iEnd);
8305 /* The SELECT has been coded. If there is an error in the Parse structure,
8306 ** set the return code to 1. Otherwise 0. */
8307 rc = (pParse->nErr>0);
8309 /* Control jumps to here if an error is encountered above, or upon
8310 ** successful coding of the SELECT.
8312 select_end:
8313 assert( db->mallocFailed==0 || db->mallocFailed==1 );
8314 assert( db->mallocFailed==0 || pParse->nErr!=0 );
8315 sqlite3ExprListDelete(db, pMinMaxOrderBy);
8316 #ifdef SQLITE_DEBUG
8317 if( pAggInfo && !db->mallocFailed ){
8318 for(i=0; i<pAggInfo->nColumn; i++){
8319 Expr *pExpr = pAggInfo->aCol[i].pCExpr;
8320 if( pExpr==0 ) continue;
8321 assert( pExpr->pAggInfo==pAggInfo );
8322 assert( pExpr->iAgg==i );
8324 for(i=0; i<pAggInfo->nFunc; i++){
8325 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
8326 assert( pExpr!=0 );
8327 assert( pExpr->pAggInfo==pAggInfo );
8328 assert( pExpr->iAgg==i );
8331 #endif
8333 #if TREETRACE_ENABLED
8334 TREETRACE(0x1,pParse,p,("end processing\n"));
8335 if( (sqlite3TreeTrace & 0x40000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
8336 sqlite3TreeViewSelect(0, p, 0);
8338 #endif
8339 ExplainQueryPlanPop(pParse);
8340 return rc;