Fixes default log output to console for macOS
[sqlcipher.git] / src / select.c
blob9278ea18b89f97fd6cb483fc1f5b3dab5d9ad23e
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);
187 void sqlite3SelectDeleteGeneric(sqlite3 *db, void *p){
188 if( ALWAYS(p) ) clearSelect(db, (Select*)p, 1);
192 ** Return a pointer to the right-most SELECT statement in a compound.
194 static Select *findRightmost(Select *p){
195 while( p->pNext ) p = p->pNext;
196 return p;
200 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
201 ** type of join. Return an integer constant that expresses that type
202 ** in terms of the following bit values:
204 ** JT_INNER
205 ** JT_CROSS
206 ** JT_OUTER
207 ** JT_NATURAL
208 ** JT_LEFT
209 ** JT_RIGHT
211 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
213 ** If an illegal or unsupported join type is seen, then still return
214 ** a join type, but put an error in the pParse structure.
216 ** These are the valid join types:
219 ** pA pB pC Return Value
220 ** ------- ----- ----- ------------
221 ** CROSS - - JT_CROSS
222 ** INNER - - JT_INNER
223 ** LEFT - - JT_LEFT|JT_OUTER
224 ** LEFT OUTER - JT_LEFT|JT_OUTER
225 ** RIGHT - - JT_RIGHT|JT_OUTER
226 ** RIGHT OUTER - JT_RIGHT|JT_OUTER
227 ** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER
228 ** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER
229 ** NATURAL INNER - JT_NATURAL|JT_INNER
230 ** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER
231 ** NATURAL LEFT OUTER JT_NATURAL|JT_LEFT|JT_OUTER
232 ** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER
233 ** NATURAL RIGHT OUTER JT_NATURAL|JT_RIGHT|JT_OUTER
234 ** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT
235 ** NATURAL FULL OUTER JT_NATRUAL|JT_LEFT|JT_RIGHT
237 ** To preserve historical compatibly, SQLite also accepts a variety
238 ** of other non-standard and in many cases nonsensical join types.
239 ** This routine makes as much sense at it can from the nonsense join
240 ** type and returns a result. Examples of accepted nonsense join types
241 ** include but are not limited to:
243 ** INNER CROSS JOIN -> same as JOIN
244 ** NATURAL CROSS JOIN -> same as NATURAL JOIN
245 ** OUTER LEFT JOIN -> same as LEFT JOIN
246 ** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN
247 ** LEFT RIGHT JOIN -> same as FULL JOIN
248 ** RIGHT OUTER FULL JOIN -> same as FULL JOIN
249 ** CROSS CROSS CROSS JOIN -> same as JOIN
251 ** The only restrictions on the join type name are:
253 ** * "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT",
254 ** or "FULL".
256 ** * "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT,
257 ** or "FULL".
259 ** * If "OUTER" is present then there must also be one of
260 ** "LEFT", "RIGHT", or "FULL"
262 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
263 int jointype = 0;
264 Token *apAll[3];
265 Token *p;
266 /* 0123456789 123456789 123456789 123 */
267 static const char zKeyText[] = "naturaleftouterightfullinnercross";
268 static const struct {
269 u8 i; /* Beginning of keyword text in zKeyText[] */
270 u8 nChar; /* Length of the keyword in characters */
271 u8 code; /* Join type mask */
272 } aKeyword[] = {
273 /* (0) natural */ { 0, 7, JT_NATURAL },
274 /* (1) left */ { 6, 4, JT_LEFT|JT_OUTER },
275 /* (2) outer */ { 10, 5, JT_OUTER },
276 /* (3) right */ { 14, 5, JT_RIGHT|JT_OUTER },
277 /* (4) full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
278 /* (5) inner */ { 23, 5, JT_INNER },
279 /* (6) cross */ { 28, 5, JT_INNER|JT_CROSS },
281 int i, j;
282 apAll[0] = pA;
283 apAll[1] = pB;
284 apAll[2] = pC;
285 for(i=0; i<3 && apAll[i]; i++){
286 p = apAll[i];
287 for(j=0; j<ArraySize(aKeyword); j++){
288 if( p->n==aKeyword[j].nChar
289 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
290 jointype |= aKeyword[j].code;
291 break;
294 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
295 if( j>=ArraySize(aKeyword) ){
296 jointype |= JT_ERROR;
297 break;
301 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
302 (jointype & JT_ERROR)!=0 ||
303 (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER
305 const char *zSp1 = " ";
306 const char *zSp2 = " ";
307 if( pB==0 ){ zSp1++; }
308 if( pC==0 ){ zSp2++; }
309 sqlite3ErrorMsg(pParse, "unknown join type: "
310 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
311 jointype = JT_INNER;
313 return jointype;
317 ** Return the index of a column in a table. Return -1 if the column
318 ** is not contained in the table.
320 int sqlite3ColumnIndex(Table *pTab, const char *zCol){
321 int i;
322 u8 h = sqlite3StrIHash(zCol);
323 Column *pCol;
324 for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
325 if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
327 return -1;
331 ** Mark a subquery result column as having been used.
333 void sqlite3SrcItemColumnUsed(SrcItem *pItem, int iCol){
334 assert( pItem!=0 );
335 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
336 if( pItem->fg.isNestedFrom ){
337 ExprList *pResults;
338 assert( pItem->pSelect!=0 );
339 pResults = pItem->pSelect->pEList;
340 assert( pResults!=0 );
341 assert( iCol>=0 && iCol<pResults->nExpr );
342 pResults->a[iCol].fg.bUsed = 1;
347 ** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
348 ** table that has a column named zCol. The search is left-to-right.
349 ** The first match found is returned.
351 ** When found, set *piTab and *piCol to the table index and column index
352 ** of the matching column and return TRUE.
354 ** If not found, return FALSE.
356 static int tableAndColumnIndex(
357 SrcList *pSrc, /* Array of tables to search */
358 int iStart, /* First member of pSrc->a[] to check */
359 int iEnd, /* Last member of pSrc->a[] to check */
360 const char *zCol, /* Name of the column we are looking for */
361 int *piTab, /* Write index of pSrc->a[] here */
362 int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
363 int bIgnoreHidden /* Ignore hidden columns */
365 int i; /* For looping over tables in pSrc */
366 int iCol; /* Index of column matching zCol */
368 assert( iEnd<pSrc->nSrc );
369 assert( iStart>=0 );
370 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
372 for(i=iStart; i<=iEnd; i++){
373 iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
374 if( iCol>=0
375 && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
377 if( piTab ){
378 sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
379 *piTab = i;
380 *piCol = iCol;
382 return 1;
385 return 0;
389 ** Set the EP_OuterON property on all terms of the given expression.
390 ** And set the Expr.w.iJoin to iTable for every term in the
391 ** expression.
393 ** The EP_OuterON property is used on terms of an expression to tell
394 ** the OUTER JOIN processing logic that this term is part of the
395 ** join restriction specified in the ON or USING clause and not a part
396 ** of the more general WHERE clause. These terms are moved over to the
397 ** WHERE clause during join processing but we need to remember that they
398 ** originated in the ON or USING clause.
400 ** The Expr.w.iJoin tells the WHERE clause processing that the
401 ** expression depends on table w.iJoin even if that table is not
402 ** explicitly mentioned in the expression. That information is needed
403 ** for cases like this:
405 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
407 ** The where clause needs to defer the handling of the t1.x=5
408 ** term until after the t2 loop of the join. In that way, a
409 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
410 ** defer the handling of t1.x=5, it will be processed immediately
411 ** after the t1 loop and rows with t1.x!=5 will never appear in
412 ** the output, which is incorrect.
414 void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){
415 assert( joinFlag==EP_OuterON || joinFlag==EP_InnerON );
416 while( p ){
417 ExprSetProperty(p, joinFlag);
418 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
419 ExprSetVVAProperty(p, EP_NoReduce);
420 p->w.iJoin = iTable;
421 if( p->op==TK_FUNCTION ){
422 assert( ExprUseXList(p) );
423 if( p->x.pList ){
424 int i;
425 for(i=0; i<p->x.pList->nExpr; i++){
426 sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
430 sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
431 p = p->pRight;
435 /* Undo the work of sqlite3SetJoinExpr(). This is used when a LEFT JOIN
436 ** is simplified into an ordinary JOIN, and when an ON expression is
437 ** "pushed down" into the WHERE clause of a subquery.
439 ** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
440 ** an ordinary term that omits the EP_OuterON mark. Or if iTable<0, then
441 ** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
443 ** If nullable is true, that means that Expr p might evaluate to NULL even
444 ** if it is a reference to a NOT NULL column. This can happen, for example,
445 ** if the table that p references is on the left side of a RIGHT JOIN.
446 ** If nullable is true, then take care to not remove the EP_CanBeNull bit.
447 ** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
449 static void unsetJoinExpr(Expr *p, int iTable, int nullable){
450 while( p ){
451 if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
452 ExprClearProperty(p, EP_OuterON|EP_InnerON);
453 if( iTable>=0 ) ExprSetProperty(p, EP_InnerON);
455 if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
456 ExprClearProperty(p, EP_CanBeNull);
458 if( p->op==TK_FUNCTION ){
459 assert( ExprUseXList(p) );
460 assert( p->pLeft==0 );
461 if( p->x.pList ){
462 int i;
463 for(i=0; i<p->x.pList->nExpr; i++){
464 unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
468 unsetJoinExpr(p->pLeft, iTable, nullable);
469 p = p->pRight;
474 ** This routine processes the join information for a SELECT statement.
476 ** * A NATURAL join is converted into a USING join. After that, we
477 ** do not need to be concerned with NATURAL joins and we only have
478 ** think about USING joins.
480 ** * ON and USING clauses result in extra terms being added to the
481 ** WHERE clause to enforce the specified constraints. The extra
482 ** WHERE clause terms will be tagged with EP_OuterON or
483 ** EP_InnerON so that we know that they originated in ON/USING.
485 ** The terms of a FROM clause are contained in the Select.pSrc structure.
486 ** The left most table is the first entry in Select.pSrc. The right-most
487 ** table is the last entry. The join operator is held in the entry to
488 ** the right. Thus entry 1 contains the join operator for the join between
489 ** entries 0 and 1. Any ON or USING clauses associated with the join are
490 ** also attached to the right entry.
492 ** This routine returns the number of errors encountered.
494 static int sqlite3ProcessJoin(Parse *pParse, Select *p){
495 SrcList *pSrc; /* All tables in the FROM clause */
496 int i, j; /* Loop counters */
497 SrcItem *pLeft; /* Left table being joined */
498 SrcItem *pRight; /* Right table being joined */
500 pSrc = p->pSrc;
501 pLeft = &pSrc->a[0];
502 pRight = &pLeft[1];
503 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
504 Table *pRightTab = pRight->pTab;
505 u32 joinType;
507 if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
508 joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
510 /* If this is a NATURAL join, synthesize an appropriate USING clause
511 ** to specify which columns should be joined.
513 if( pRight->fg.jointype & JT_NATURAL ){
514 IdList *pUsing = 0;
515 if( pRight->fg.isUsing || pRight->u3.pOn ){
516 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
517 "an ON or USING clause", 0);
518 return 1;
520 for(j=0; j<pRightTab->nCol; j++){
521 char *zName; /* Name of column in the right table */
523 if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
524 zName = pRightTab->aCol[j].zCnName;
525 if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){
526 pUsing = sqlite3IdListAppend(pParse, pUsing, 0);
527 if( pUsing ){
528 assert( pUsing->nId>0 );
529 assert( pUsing->a[pUsing->nId-1].zName==0 );
530 pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
534 if( pUsing ){
535 pRight->fg.isUsing = 1;
536 pRight->fg.isSynthUsing = 1;
537 pRight->u3.pUsing = pUsing;
539 if( pParse->nErr ) return 1;
542 /* Create extra terms on the WHERE clause for each column named
543 ** in the USING clause. Example: If the two tables to be joined are
544 ** A and B and the USING clause names X, Y, and Z, then add this
545 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
546 ** Report an error if any column mentioned in the USING clause is
547 ** not contained in both tables to be joined.
549 if( pRight->fg.isUsing ){
550 IdList *pList = pRight->u3.pUsing;
551 sqlite3 *db = pParse->db;
552 assert( pList!=0 );
553 for(j=0; j<pList->nId; j++){
554 char *zName; /* Name of the term in the USING clause */
555 int iLeft; /* Table on the left with matching column name */
556 int iLeftCol; /* Column number of matching column on the left */
557 int iRightCol; /* Column number of matching column on the right */
558 Expr *pE1; /* Reference to the column on the LEFT of the join */
559 Expr *pE2; /* Reference to the column on the RIGHT of the join */
560 Expr *pEq; /* Equality constraint. pE1 == pE2 */
562 zName = pList->a[j].zName;
563 iRightCol = sqlite3ColumnIndex(pRightTab, zName);
564 if( iRightCol<0
565 || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol,
566 pRight->fg.isSynthUsing)==0
568 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
569 "not present in both tables", zName);
570 return 1;
572 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
573 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
574 if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
575 /* This branch runs if the query contains one or more RIGHT or FULL
576 ** JOINs. If only a single table on the left side of this join
577 ** contains the zName column, then this branch is a no-op.
578 ** But if there are two or more tables on the left side
579 ** of the join, construct a coalesce() function that gathers all
580 ** such tables. Raise an error if more than one of those references
581 ** to zName is not also within a prior USING clause.
583 ** We really ought to raise an error if there are two or more
584 ** non-USING references to zName on the left of an INNER or LEFT
585 ** JOIN. But older versions of SQLite do not do that, so we avoid
586 ** adding a new error so as to not break legacy applications.
588 ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */
589 static const Token tkCoalesce = { "coalesce", 8 };
590 while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,
591 pRight->fg.isSynthUsing)!=0 ){
592 if( pSrc->a[iLeft].fg.isUsing==0
593 || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
595 sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()",
596 zName);
597 break;
599 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
600 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
601 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
603 if( pFuncArgs ){
604 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
605 pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);
608 pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);
609 sqlite3SrcItemColumnUsed(pRight, iRightCol);
610 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
611 assert( pE2!=0 || pEq==0 );
612 if( pEq ){
613 ExprSetProperty(pEq, joinType);
614 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
615 ExprSetVVAProperty(pEq, EP_NoReduce);
616 pEq->w.iJoin = pE2->iTable;
618 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
622 /* Add the ON clause to the end of the WHERE clause, connected by
623 ** an AND operator.
625 else if( pRight->u3.pOn ){
626 sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
627 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
628 pRight->u3.pOn = 0;
629 pRight->fg.isOn = 1;
632 return 0;
636 ** An instance of this object holds information (beyond pParse and pSelect)
637 ** needed to load the next result row that is to be added to the sorter.
639 typedef struct RowLoadInfo RowLoadInfo;
640 struct RowLoadInfo {
641 int regResult; /* Store results in array of registers here */
642 u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
643 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
644 ExprList *pExtra; /* Extra columns needed by sorter refs */
645 int regExtraResult; /* Where to load the extra columns */
646 #endif
650 ** This routine does the work of loading query data into an array of
651 ** registers so that it can be added to the sorter.
653 static void innerLoopLoadRow(
654 Parse *pParse, /* Statement under construction */
655 Select *pSelect, /* The query being coded */
656 RowLoadInfo *pInfo /* Info needed to complete the row load */
658 sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
659 0, pInfo->ecelFlags);
660 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
661 if( pInfo->pExtra ){
662 sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
663 sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
665 #endif
669 ** Code the OP_MakeRecord instruction that generates the entry to be
670 ** added into the sorter.
672 ** Return the register in which the result is stored.
674 static int makeSorterRecord(
675 Parse *pParse,
676 SortCtx *pSort,
677 Select *pSelect,
678 int regBase,
679 int nBase
681 int nOBSat = pSort->nOBSat;
682 Vdbe *v = pParse->pVdbe;
683 int regOut = ++pParse->nMem;
684 if( pSort->pDeferredRowLoad ){
685 innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
687 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
688 return regOut;
692 ** Generate code that will push the record in registers regData
693 ** through regData+nData-1 onto the sorter.
695 static void pushOntoSorter(
696 Parse *pParse, /* Parser context */
697 SortCtx *pSort, /* Information about the ORDER BY clause */
698 Select *pSelect, /* The whole SELECT statement */
699 int regData, /* First register holding data to be sorted */
700 int regOrigData, /* First register holding data before packing */
701 int nData, /* Number of elements in the regData data array */
702 int nPrefixReg /* No. of reg prior to regData available for use */
704 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
705 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
706 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
707 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
708 int regBase; /* Regs for sorter record */
709 int regRecord = 0; /* Assembled sorter record */
710 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
711 int op; /* Opcode to add sorter record to sorter */
712 int iLimit; /* LIMIT counter */
713 int iSkip = 0; /* End of the sorter insert loop */
715 assert( bSeq==0 || bSeq==1 );
717 /* Three cases:
718 ** (1) The data to be sorted has already been packed into a Record
719 ** by a prior OP_MakeRecord. In this case nData==1 and regData
720 ** will be completely unrelated to regOrigData.
721 ** (2) All output columns are included in the sort record. In that
722 ** case regData==regOrigData.
723 ** (3) Some output columns are omitted from the sort record due to
724 ** the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
725 ** SQLITE_ECEL_OMITREF optimization, or due to the
726 ** SortCtx.pDeferredRowLoad optimization. In any of these cases
727 ** regOrigData is 0 to prevent this routine from trying to copy
728 ** values that might not yet exist.
730 assert( nData==1 || regData==regOrigData || regOrigData==0 );
732 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
733 pSort->addrPush = sqlite3VdbeCurrentAddr(v);
734 #endif
736 if( nPrefixReg ){
737 assert( nPrefixReg==nExpr+bSeq );
738 regBase = regData - nPrefixReg;
739 }else{
740 regBase = pParse->nMem + 1;
741 pParse->nMem += nBase;
743 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
744 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
745 pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
746 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
747 SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
748 if( bSeq ){
749 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
751 if( nPrefixReg==0 && nData>0 ){
752 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
754 if( nOBSat>0 ){
755 int regPrevKey; /* The first nOBSat columns of the previous row */
756 int addrFirst; /* Address of the OP_IfNot opcode */
757 int addrJmp; /* Address of the OP_Jump opcode */
758 VdbeOp *pOp; /* Opcode that opens the sorter */
759 int nKey; /* Number of sorting key columns, including OP_Sequence */
760 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
762 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
763 regPrevKey = pParse->nMem+1;
764 pParse->nMem += pSort->nOBSat;
765 nKey = nExpr - pSort->nOBSat + bSeq;
766 if( bSeq ){
767 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
768 }else{
769 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
771 VdbeCoverage(v);
772 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
773 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
774 if( pParse->db->mallocFailed ) return;
775 pOp->p2 = nKey + nData;
776 pKI = pOp->p4.pKeyInfo;
777 memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
778 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
779 testcase( pKI->nAllField > pKI->nKeyField+2 );
780 pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
781 pKI->nAllField-pKI->nKeyField-1);
782 pOp = 0; /* Ensure pOp not used after sqlite3VdbeAddOp3() */
783 addrJmp = sqlite3VdbeCurrentAddr(v);
784 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
785 pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
786 pSort->regReturn = ++pParse->nMem;
787 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
788 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
789 if( iLimit ){
790 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
791 VdbeCoverage(v);
793 sqlite3VdbeJumpHere(v, addrFirst);
794 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
795 sqlite3VdbeJumpHere(v, addrJmp);
797 if( iLimit ){
798 /* At this point the values for the new sorter entry are stored
799 ** in an array of registers. They need to be composed into a record
800 ** and inserted into the sorter if either (a) there are currently
801 ** less than LIMIT+OFFSET items or (b) the new record is smaller than
802 ** the largest record currently in the sorter. If (b) is true and there
803 ** are already LIMIT+OFFSET items in the sorter, delete the largest
804 ** entry before inserting the new one. This way there are never more
805 ** than LIMIT+OFFSET items in the sorter.
807 ** If the new record does not need to be inserted into the sorter,
808 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
809 ** value is not zero, then it is a label of where to jump. Otherwise,
810 ** just bypass the row insert logic. See the header comment on the
811 ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
813 int iCsr = pSort->iECursor;
814 sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
815 VdbeCoverage(v);
816 sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
817 iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
818 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
819 VdbeCoverage(v);
820 sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
822 if( regRecord==0 ){
823 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
825 if( pSort->sortFlags & SORTFLAG_UseSorter ){
826 op = OP_SorterInsert;
827 }else{
828 op = OP_IdxInsert;
830 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
831 regBase+nOBSat, nBase-nOBSat);
832 if( iSkip ){
833 sqlite3VdbeChangeP2(v, iSkip,
834 pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
836 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
837 pSort->addrPushEnd = sqlite3VdbeCurrentAddr(v)-1;
838 #endif
842 ** Add code to implement the OFFSET
844 static void codeOffset(
845 Vdbe *v, /* Generate code into this VM */
846 int iOffset, /* Register holding the offset counter */
847 int iContinue /* Jump here to skip the current record */
849 if( iOffset>0 ){
850 sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
851 VdbeComment((v, "OFFSET"));
856 ** Add code that will check to make sure the array of registers starting at
857 ** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
858 ** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
859 ** are available. Which is used depends on the value of parameter eTnctType,
860 ** as follows:
862 ** WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
863 ** Build an ephemeral table that contains all entries seen before and
864 ** skip entries which have been seen before.
866 ** Parameter iTab is the cursor number of an ephemeral table that must
867 ** be opened before the VM code generated by this routine is executed.
868 ** The ephemeral cursor table is queried for a record identical to the
869 ** record formed by the current array of registers. If one is found,
870 ** jump to VM address addrRepeat. Otherwise, insert a new record into
871 ** the ephemeral cursor and proceed.
873 ** The returned value in this case is a copy of parameter iTab.
875 ** WHERE_DISTINCT_ORDERED:
876 ** In this case rows are being delivered sorted order. The ephemeral
877 ** table is not required. Instead, the current set of values
878 ** is compared against previous row. If they match, the new row
879 ** is not distinct and control jumps to VM address addrRepeat. Otherwise,
880 ** the VM program proceeds with processing the new row.
882 ** The returned value in this case is the register number of the first
883 ** in an array of registers used to store the previous result row so that
884 ** it can be compared to the next. The caller must ensure that this
885 ** register is initialized to NULL. (The fixDistinctOpenEph() routine
886 ** will take care of this initialization.)
888 ** WHERE_DISTINCT_UNIQUE:
889 ** In this case it has already been determined that the rows are distinct.
890 ** No special action is required. The return value is zero.
892 ** Parameter pEList is the list of expressions used to generated the
893 ** contents of each row. It is used by this routine to determine (a)
894 ** how many elements there are in the array of registers and (b) the
895 ** collation sequences that should be used for the comparisons if
896 ** eTnctType is WHERE_DISTINCT_ORDERED.
898 static int codeDistinct(
899 Parse *pParse, /* Parsing and code generating context */
900 int eTnctType, /* WHERE_DISTINCT_* value */
901 int iTab, /* A sorting index used to test for distinctness */
902 int addrRepeat, /* Jump to here if not distinct */
903 ExprList *pEList, /* Expression for each element */
904 int regElem /* First element */
906 int iRet = 0;
907 int nResultCol = pEList->nExpr;
908 Vdbe *v = pParse->pVdbe;
910 switch( eTnctType ){
911 case WHERE_DISTINCT_ORDERED: {
912 int i;
913 int iJump; /* Jump destination */
914 int regPrev; /* Previous row content */
916 /* Allocate space for the previous row */
917 iRet = regPrev = pParse->nMem+1;
918 pParse->nMem += nResultCol;
920 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
921 for(i=0; i<nResultCol; i++){
922 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
923 if( i<nResultCol-1 ){
924 sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
925 VdbeCoverage(v);
926 }else{
927 sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
928 VdbeCoverage(v);
930 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
931 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
933 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
934 sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
935 break;
938 case WHERE_DISTINCT_UNIQUE: {
939 /* nothing to do */
940 break;
943 default: {
944 int r1 = sqlite3GetTempReg(pParse);
945 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
946 VdbeCoverage(v);
947 sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
948 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
949 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
950 sqlite3ReleaseTempReg(pParse, r1);
951 iRet = iTab;
952 break;
956 return iRet;
960 ** This routine runs after codeDistinct(). It makes necessary
961 ** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
962 ** routine made use of. This processing must be done separately since
963 ** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
964 ** laid down.
966 ** WHERE_DISTINCT_NOOP:
967 ** WHERE_DISTINCT_UNORDERED:
969 ** No adjustments necessary. This function is a no-op.
971 ** WHERE_DISTINCT_UNIQUE:
973 ** The ephemeral table is not needed. So change the
974 ** OP_OpenEphemeral opcode into an OP_Noop.
976 ** WHERE_DISTINCT_ORDERED:
978 ** The ephemeral table is not needed. But we do need register
979 ** iVal to be initialized to NULL. So change the OP_OpenEphemeral
980 ** into an OP_Null on the iVal register.
982 static void fixDistinctOpenEph(
983 Parse *pParse, /* Parsing and code generating context */
984 int eTnctType, /* WHERE_DISTINCT_* value */
985 int iVal, /* Value returned by codeDistinct() */
986 int iOpenEphAddr /* Address of OP_OpenEphemeral instruction for iTab */
988 if( pParse->nErr==0
989 && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
991 Vdbe *v = pParse->pVdbe;
992 sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
993 if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
994 sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
996 if( eTnctType==WHERE_DISTINCT_ORDERED ){
997 /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
998 ** bit on the first register of the previous value. This will cause the
999 ** OP_Ne added in codeDistinct() to always fail on the first iteration of
1000 ** the loop even if the first row is all NULLs. */
1001 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
1002 pOp->opcode = OP_Null;
1003 pOp->p1 = 1;
1004 pOp->p2 = iVal;
1009 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1011 ** This function is called as part of inner-loop generation for a SELECT
1012 ** statement with an ORDER BY that is not optimized by an index. It
1013 ** determines the expressions, if any, that the sorter-reference
1014 ** optimization should be used for. The sorter-reference optimization
1015 ** is used for SELECT queries like:
1017 ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
1019 ** If the optimization is used for expression "bigblob", then instead of
1020 ** storing values read from that column in the sorter records, the PK of
1021 ** the row from table t1 is stored instead. Then, as records are extracted from
1022 ** the sorter to return to the user, the required value of bigblob is
1023 ** retrieved directly from table t1. If the values are very large, this
1024 ** can be more efficient than storing them directly in the sorter records.
1026 ** The ExprList_item.fg.bSorterRef flag is set for each expression in pEList
1027 ** for which the sorter-reference optimization should be enabled.
1028 ** Additionally, the pSort->aDefer[] array is populated with entries
1029 ** for all cursors required to evaluate all selected expressions. Finally.
1030 ** output variable (*ppExtra) is set to an expression list containing
1031 ** expressions for all extra PK values that should be stored in the
1032 ** sorter records.
1034 static void selectExprDefer(
1035 Parse *pParse, /* Leave any error here */
1036 SortCtx *pSort, /* Sorter context */
1037 ExprList *pEList, /* Expressions destined for sorter */
1038 ExprList **ppExtra /* Expressions to append to sorter record */
1040 int i;
1041 int nDefer = 0;
1042 ExprList *pExtra = 0;
1043 for(i=0; i<pEList->nExpr; i++){
1044 struct ExprList_item *pItem = &pEList->a[i];
1045 if( pItem->u.x.iOrderByCol==0 ){
1046 Expr *pExpr = pItem->pExpr;
1047 Table *pTab;
1048 if( pExpr->op==TK_COLUMN
1049 && pExpr->iColumn>=0
1050 && ALWAYS( ExprUseYTab(pExpr) )
1051 && (pTab = pExpr->y.pTab)!=0
1052 && IsOrdinaryTable(pTab)
1053 && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
1055 int j;
1056 for(j=0; j<nDefer; j++){
1057 if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
1059 if( j==nDefer ){
1060 if( nDefer==ArraySize(pSort->aDefer) ){
1061 continue;
1062 }else{
1063 int nKey = 1;
1064 int k;
1065 Index *pPk = 0;
1066 if( !HasRowid(pTab) ){
1067 pPk = sqlite3PrimaryKeyIndex(pTab);
1068 nKey = pPk->nKeyCol;
1070 for(k=0; k<nKey; k++){
1071 Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
1072 if( pNew ){
1073 pNew->iTable = pExpr->iTable;
1074 assert( ExprUseYTab(pNew) );
1075 pNew->y.pTab = pExpr->y.pTab;
1076 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
1077 pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
1080 pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
1081 pSort->aDefer[nDefer].iCsr = pExpr->iTable;
1082 pSort->aDefer[nDefer].nKey = nKey;
1083 nDefer++;
1086 pItem->fg.bSorterRef = 1;
1090 pSort->nDefer = (u8)nDefer;
1091 *ppExtra = pExtra;
1093 #endif
1096 ** This routine generates the code for the inside of the inner loop
1097 ** of a SELECT.
1099 ** If srcTab is negative, then the p->pEList expressions
1100 ** are evaluated in order to get the data for this row. If srcTab is
1101 ** zero or more, then data is pulled from srcTab and p->pEList is used only
1102 ** to get the number of columns and the collation sequence for each column.
1104 static void selectInnerLoop(
1105 Parse *pParse, /* The parser context */
1106 Select *p, /* The complete select statement being coded */
1107 int srcTab, /* Pull data from this table if non-negative */
1108 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
1109 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
1110 SelectDest *pDest, /* How to dispose of the results */
1111 int iContinue, /* Jump here to continue with next row */
1112 int iBreak /* Jump here to break out of the inner loop */
1114 Vdbe *v = pParse->pVdbe;
1115 int i;
1116 int hasDistinct; /* True if the DISTINCT keyword is present */
1117 int eDest = pDest->eDest; /* How to dispose of results */
1118 int iParm = pDest->iSDParm; /* First argument to disposal method */
1119 int nResultCol; /* Number of result columns */
1120 int nPrefixReg = 0; /* Number of extra registers before regResult */
1121 RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
1123 /* Usually, regResult is the first cell in an array of memory cells
1124 ** containing the current result row. In this case regOrig is set to the
1125 ** same value. However, if the results are being sent to the sorter, the
1126 ** values for any expressions that are also part of the sort-key are omitted
1127 ** from this array. In this case regOrig is set to zero. */
1128 int regResult; /* Start of memory holding current results */
1129 int regOrig; /* Start of memory holding full result (or 0) */
1131 assert( v );
1132 assert( p->pEList!=0 );
1133 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
1134 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
1135 if( pSort==0 && !hasDistinct ){
1136 assert( iContinue!=0 );
1137 codeOffset(v, p->iOffset, iContinue);
1140 /* Pull the requested columns.
1142 nResultCol = p->pEList->nExpr;
1144 if( pDest->iSdst==0 ){
1145 if( pSort ){
1146 nPrefixReg = pSort->pOrderBy->nExpr;
1147 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
1148 pParse->nMem += nPrefixReg;
1150 pDest->iSdst = pParse->nMem+1;
1151 pParse->nMem += nResultCol;
1152 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
1153 /* This is an error condition that can result, for example, when a SELECT
1154 ** on the right-hand side of an INSERT contains more result columns than
1155 ** there are columns in the table on the left. The error will be caught
1156 ** and reported later. But we need to make sure enough memory is allocated
1157 ** to avoid other spurious errors in the meantime. */
1158 pParse->nMem += nResultCol;
1160 pDest->nSdst = nResultCol;
1161 regOrig = regResult = pDest->iSdst;
1162 if( srcTab>=0 ){
1163 for(i=0; i<nResultCol; i++){
1164 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
1165 VdbeComment((v, "%s", p->pEList->a[i].zEName));
1167 }else if( eDest!=SRT_Exists ){
1168 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1169 ExprList *pExtra = 0;
1170 #endif
1171 /* If the destination is an EXISTS(...) expression, the actual
1172 ** values returned by the SELECT are not required.
1174 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
1175 ExprList *pEList;
1176 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
1177 ecelFlags = SQLITE_ECEL_DUP;
1178 }else{
1179 ecelFlags = 0;
1181 if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
1182 /* For each expression in p->pEList that is a copy of an expression in
1183 ** the ORDER BY clause (pSort->pOrderBy), set the associated
1184 ** iOrderByCol value to one more than the index of the ORDER BY
1185 ** expression within the sort-key that pushOntoSorter() will generate.
1186 ** This allows the p->pEList field to be omitted from the sorted record,
1187 ** saving space and CPU cycles. */
1188 ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
1190 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
1191 int j;
1192 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
1193 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
1196 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1197 selectExprDefer(pParse, pSort, p->pEList, &pExtra);
1198 if( pExtra && pParse->db->mallocFailed==0 ){
1199 /* If there are any extra PK columns to add to the sorter records,
1200 ** allocate extra memory cells and adjust the OpenEphemeral
1201 ** instruction to account for the larger records. This is only
1202 ** required if there are one or more WITHOUT ROWID tables with
1203 ** composite primary keys in the SortCtx.aDefer[] array. */
1204 VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
1205 pOp->p2 += (pExtra->nExpr - pSort->nDefer);
1206 pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
1207 pParse->nMem += pExtra->nExpr;
1209 #endif
1211 /* Adjust nResultCol to account for columns that are omitted
1212 ** from the sorter by the optimizations in this branch */
1213 pEList = p->pEList;
1214 for(i=0; i<pEList->nExpr; i++){
1215 if( pEList->a[i].u.x.iOrderByCol>0
1216 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1217 || pEList->a[i].fg.bSorterRef
1218 #endif
1220 nResultCol--;
1221 regOrig = 0;
1225 testcase( regOrig );
1226 testcase( eDest==SRT_Set );
1227 testcase( eDest==SRT_Mem );
1228 testcase( eDest==SRT_Coroutine );
1229 testcase( eDest==SRT_Output );
1230 assert( eDest==SRT_Set || eDest==SRT_Mem
1231 || eDest==SRT_Coroutine || eDest==SRT_Output
1232 || eDest==SRT_Upfrom );
1234 sRowLoadInfo.regResult = regResult;
1235 sRowLoadInfo.ecelFlags = ecelFlags;
1236 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1237 sRowLoadInfo.pExtra = pExtra;
1238 sRowLoadInfo.regExtraResult = regResult + nResultCol;
1239 if( pExtra ) nResultCol += pExtra->nExpr;
1240 #endif
1241 if( p->iLimit
1242 && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
1243 && nPrefixReg>0
1245 assert( pSort!=0 );
1246 assert( hasDistinct==0 );
1247 pSort->pDeferredRowLoad = &sRowLoadInfo;
1248 regOrig = 0;
1249 }else{
1250 innerLoopLoadRow(pParse, p, &sRowLoadInfo);
1254 /* If the DISTINCT keyword was present on the SELECT statement
1255 ** and this row has been seen before, then do not make this row
1256 ** part of the result.
1258 if( hasDistinct ){
1259 int eType = pDistinct->eTnctType;
1260 int iTab = pDistinct->tabTnct;
1261 assert( nResultCol==p->pEList->nExpr );
1262 iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
1263 fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
1264 if( pSort==0 ){
1265 codeOffset(v, p->iOffset, iContinue);
1269 switch( eDest ){
1270 /* In this mode, write each query result to the key of the temporary
1271 ** table iParm.
1273 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1274 case SRT_Union: {
1275 int r1;
1276 r1 = sqlite3GetTempReg(pParse);
1277 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
1278 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1279 sqlite3ReleaseTempReg(pParse, r1);
1280 break;
1283 /* Construct a record from the query result, but instead of
1284 ** saving that record, use it as a key to delete elements from
1285 ** the temporary table iParm.
1287 case SRT_Except: {
1288 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
1289 break;
1291 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1293 /* Store the result as data using a unique key.
1295 case SRT_Fifo:
1296 case SRT_DistFifo:
1297 case SRT_Table:
1298 case SRT_EphemTab: {
1299 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
1300 testcase( eDest==SRT_Table );
1301 testcase( eDest==SRT_EphemTab );
1302 testcase( eDest==SRT_Fifo );
1303 testcase( eDest==SRT_DistFifo );
1304 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
1305 #if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
1306 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
1307 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
1308 ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
1309 ** This does not affect operation in any way - it just allows MakeRecord
1310 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
1311 if( eDest==SRT_Table && pDest->iSDParm2 ){
1312 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
1314 #endif
1315 #ifndef SQLITE_OMIT_CTE
1316 if( eDest==SRT_DistFifo ){
1317 /* If the destination is DistFifo, then cursor (iParm+1) is open
1318 ** on an ephemeral index. If the current row is already present
1319 ** in the index, do not write it to the output. If not, add the
1320 ** current row to the index and proceed with writing it to the
1321 ** output table as well. */
1322 int addr = sqlite3VdbeCurrentAddr(v) + 4;
1323 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
1324 VdbeCoverage(v);
1325 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
1326 assert( pSort==0 );
1328 #endif
1329 if( pSort ){
1330 assert( regResult==regOrig );
1331 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
1332 }else{
1333 int r2 = sqlite3GetTempReg(pParse);
1334 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
1335 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
1336 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1337 sqlite3ReleaseTempReg(pParse, r2);
1339 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
1340 break;
1343 case SRT_Upfrom: {
1344 if( pSort ){
1345 pushOntoSorter(
1346 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1347 }else{
1348 int i2 = pDest->iSDParm2;
1349 int r1 = sqlite3GetTempReg(pParse);
1351 /* If the UPDATE FROM join is an aggregate that matches no rows, it
1352 ** might still be trying to return one row, because that is what
1353 ** aggregates do. Don't record that empty row in the output table. */
1354 sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
1356 sqlite3VdbeAddOp3(v, OP_MakeRecord,
1357 regResult+(i2<0), nResultCol-(i2<0), r1);
1358 if( i2<0 ){
1359 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
1360 }else{
1361 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
1364 break;
1367 #ifndef SQLITE_OMIT_SUBQUERY
1368 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1369 ** then there should be a single item on the stack. Write this
1370 ** item into the set table with bogus data.
1372 case SRT_Set: {
1373 if( pSort ){
1374 /* At first glance you would think we could optimize out the
1375 ** ORDER BY in this case since the order of entries in the set
1376 ** does not matter. But there might be a LIMIT clause, in which
1377 ** case the order does matter */
1378 pushOntoSorter(
1379 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1380 }else{
1381 int r1 = sqlite3GetTempReg(pParse);
1382 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
1383 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
1384 r1, pDest->zAffSdst, nResultCol);
1385 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1386 sqlite3ReleaseTempReg(pParse, r1);
1388 break;
1392 /* If any row exist in the result set, record that fact and abort.
1394 case SRT_Exists: {
1395 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
1396 /* The LIMIT clause will terminate the loop for us */
1397 break;
1400 /* If this is a scalar select that is part of an expression, then
1401 ** store the results in the appropriate memory cell or array of
1402 ** memory cells and break out of the scan loop.
1404 case SRT_Mem: {
1405 if( pSort ){
1406 assert( nResultCol<=pDest->nSdst );
1407 pushOntoSorter(
1408 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1409 }else{
1410 assert( nResultCol==pDest->nSdst );
1411 assert( regResult==iParm );
1412 /* The LIMIT clause will jump out of the loop for us */
1414 break;
1416 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1418 case SRT_Coroutine: /* Send data to a co-routine */
1419 case SRT_Output: { /* Return the results */
1420 testcase( eDest==SRT_Coroutine );
1421 testcase( eDest==SRT_Output );
1422 if( pSort ){
1423 pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
1424 nPrefixReg);
1425 }else if( eDest==SRT_Coroutine ){
1426 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1427 }else{
1428 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
1430 break;
1433 #ifndef SQLITE_OMIT_CTE
1434 /* Write the results into a priority queue that is order according to
1435 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
1436 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
1437 ** pSO->nExpr columns, then make sure all keys are unique by adding a
1438 ** final OP_Sequence column. The last column is the record as a blob.
1440 case SRT_DistQueue:
1441 case SRT_Queue: {
1442 int nKey;
1443 int r1, r2, r3;
1444 int addrTest = 0;
1445 ExprList *pSO;
1446 pSO = pDest->pOrderBy;
1447 assert( pSO );
1448 nKey = pSO->nExpr;
1449 r1 = sqlite3GetTempReg(pParse);
1450 r2 = sqlite3GetTempRange(pParse, nKey+2);
1451 r3 = r2+nKey+1;
1452 if( eDest==SRT_DistQueue ){
1453 /* If the destination is DistQueue, then cursor (iParm+1) is open
1454 ** on a second ephemeral index that holds all values every previously
1455 ** added to the queue. */
1456 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
1457 regResult, nResultCol);
1458 VdbeCoverage(v);
1460 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
1461 if( eDest==SRT_DistQueue ){
1462 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
1463 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1465 for(i=0; i<nKey; i++){
1466 sqlite3VdbeAddOp2(v, OP_SCopy,
1467 regResult + pSO->a[i].u.x.iOrderByCol - 1,
1468 r2+i);
1470 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
1471 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
1472 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
1473 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1474 sqlite3ReleaseTempReg(pParse, r1);
1475 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1476 break;
1478 #endif /* SQLITE_OMIT_CTE */
1482 #if !defined(SQLITE_OMIT_TRIGGER)
1483 /* Discard the results. This is used for SELECT statements inside
1484 ** the body of a TRIGGER. The purpose of such selects is to call
1485 ** user-defined functions that have side effects. We do not care
1486 ** about the actual results of the select.
1488 default: {
1489 assert( eDest==SRT_Discard );
1490 break;
1492 #endif
1495 /* Jump to the end of the loop if the LIMIT is reached. Except, if
1496 ** there is a sorter, in which case the sorter has already limited
1497 ** the output for us.
1499 if( pSort==0 && p->iLimit ){
1500 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1505 ** Allocate a KeyInfo object sufficient for an index of N key columns and
1506 ** X extra columns.
1508 KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1509 int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
1510 KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
1511 if( p ){
1512 p->aSortFlags = (u8*)&p->aColl[N+X];
1513 p->nKeyField = (u16)N;
1514 p->nAllField = (u16)(N+X);
1515 p->enc = ENC(db);
1516 p->db = db;
1517 p->nRef = 1;
1518 memset(&p[1], 0, nExtra);
1519 }else{
1520 return (KeyInfo*)sqlite3OomFault(db);
1522 return p;
1526 ** Deallocate a KeyInfo object
1528 void sqlite3KeyInfoUnref(KeyInfo *p){
1529 if( p ){
1530 assert( p->db!=0 );
1531 assert( p->nRef>0 );
1532 p->nRef--;
1533 if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
1538 ** Make a new pointer to a KeyInfo object
1540 KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
1541 if( p ){
1542 assert( p->nRef>0 );
1543 p->nRef++;
1545 return p;
1548 #ifdef SQLITE_DEBUG
1550 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
1551 ** can only be changed if this is just a single reference to the object.
1553 ** This routine is used only inside of assert() statements.
1555 int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
1556 #endif /* SQLITE_DEBUG */
1559 ** Given an expression list, generate a KeyInfo structure that records
1560 ** the collating sequence for each expression in that expression list.
1562 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
1563 ** KeyInfo structure is appropriate for initializing a virtual index to
1564 ** implement that clause. If the ExprList is the result set of a SELECT
1565 ** then the KeyInfo structure is appropriate for initializing a virtual
1566 ** index to implement a DISTINCT test.
1568 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
1569 ** function is responsible for seeing that this structure is eventually
1570 ** freed.
1572 KeyInfo *sqlite3KeyInfoFromExprList(
1573 Parse *pParse, /* Parsing context */
1574 ExprList *pList, /* Form the KeyInfo object from this ExprList */
1575 int iStart, /* Begin with this column of pList */
1576 int nExtra /* Add this many extra columns to the end */
1578 int nExpr;
1579 KeyInfo *pInfo;
1580 struct ExprList_item *pItem;
1581 sqlite3 *db = pParse->db;
1582 int i;
1584 nExpr = pList->nExpr;
1585 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1586 if( pInfo ){
1587 assert( sqlite3KeyInfoIsWriteable(pInfo) );
1588 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1589 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
1590 pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
1593 return pInfo;
1597 ** Name of the connection operator, used for error messages.
1599 const char *sqlite3SelectOpName(int id){
1600 char *z;
1601 switch( id ){
1602 case TK_ALL: z = "UNION ALL"; break;
1603 case TK_INTERSECT: z = "INTERSECT"; break;
1604 case TK_EXCEPT: z = "EXCEPT"; break;
1605 default: z = "UNION"; break;
1607 return z;
1610 #ifndef SQLITE_OMIT_EXPLAIN
1612 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1613 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1614 ** where the caption is of the form:
1616 ** "USE TEMP B-TREE FOR xxx"
1618 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
1619 ** is determined by the zUsage argument.
1621 static void explainTempTable(Parse *pParse, const char *zUsage){
1622 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
1626 ** Assign expression b to lvalue a. A second, no-op, version of this macro
1627 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1628 ** in sqlite3Select() to assign values to structure member variables that
1629 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1630 ** code with #ifndef directives.
1632 # define explainSetInteger(a, b) a = b
1634 #else
1635 /* No-op versions of the explainXXX() functions and macros. */
1636 # define explainTempTable(y,z)
1637 # define explainSetInteger(y,z)
1638 #endif
1642 ** If the inner loop was generated using a non-null pOrderBy argument,
1643 ** then the results were placed in a sorter. After the loop is terminated
1644 ** we need to run the sorter and output the results. The following
1645 ** routine generates the code needed to do that.
1647 static void generateSortTail(
1648 Parse *pParse, /* Parsing context */
1649 Select *p, /* The SELECT statement */
1650 SortCtx *pSort, /* Information on the ORDER BY clause */
1651 int nColumn, /* Number of columns of data */
1652 SelectDest *pDest /* Write the sorted results here */
1654 Vdbe *v = pParse->pVdbe; /* The prepared statement */
1655 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
1656 int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
1657 int addr; /* Top of output loop. Jump for Next. */
1658 int addrOnce = 0;
1659 int iTab;
1660 ExprList *pOrderBy = pSort->pOrderBy;
1661 int eDest = pDest->eDest;
1662 int iParm = pDest->iSDParm;
1663 int regRow;
1664 int regRowid;
1665 int iCol;
1666 int nKey; /* Number of key columns in sorter record */
1667 int iSortTab; /* Sorter cursor to read from */
1668 int i;
1669 int bSeq; /* True if sorter record includes seq. no. */
1670 int nRefKey = 0;
1671 struct ExprList_item *aOutEx = p->pEList->a;
1672 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1673 int addrExplain; /* Address of OP_Explain instruction */
1674 #endif
1676 nKey = pOrderBy->nExpr - pSort->nOBSat;
1677 if( pSort->nOBSat==0 || nKey==1 ){
1678 ExplainQueryPlan2(addrExplain, (pParse, 0,
1679 "USE TEMP B-TREE FOR %sORDER BY", pSort->nOBSat?"LAST TERM OF ":""
1681 }else{
1682 ExplainQueryPlan2(addrExplain, (pParse, 0,
1683 "USE TEMP B-TREE FOR LAST %d TERMS OF ORDER BY", nKey
1686 sqlite3VdbeScanStatusRange(v, addrExplain,pSort->addrPush,pSort->addrPushEnd);
1687 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, pSort->addrPush);
1690 assert( addrBreak<0 );
1691 if( pSort->labelBkOut ){
1692 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1693 sqlite3VdbeGoto(v, addrBreak);
1694 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1697 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1698 /* Open any cursors needed for sorter-reference expressions */
1699 for(i=0; i<pSort->nDefer; i++){
1700 Table *pTab = pSort->aDefer[i].pTab;
1701 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1702 sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
1703 nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
1705 #endif
1707 iTab = pSort->iECursor;
1708 if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
1709 if( eDest==SRT_Mem && p->iOffset ){
1710 sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
1712 regRowid = 0;
1713 regRow = pDest->iSdst;
1714 }else{
1715 regRowid = sqlite3GetTempReg(pParse);
1716 if( eDest==SRT_EphemTab || eDest==SRT_Table ){
1717 regRow = sqlite3GetTempReg(pParse);
1718 nColumn = 0;
1719 }else{
1720 regRow = sqlite3GetTempRange(pParse, nColumn);
1723 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1724 int regSortOut = ++pParse->nMem;
1725 iSortTab = pParse->nTab++;
1726 if( pSort->labelBkOut ){
1727 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1729 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
1730 nKey+1+nColumn+nRefKey);
1731 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1732 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1733 VdbeCoverage(v);
1734 assert( p->iLimit==0 && p->iOffset==0 );
1735 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
1736 bSeq = 0;
1737 }else{
1738 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1739 codeOffset(v, p->iOffset, addrContinue);
1740 iSortTab = iTab;
1741 bSeq = 1;
1742 if( p->iOffset>0 ){
1743 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1746 for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
1747 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1748 if( aOutEx[i].fg.bSorterRef ) continue;
1749 #endif
1750 if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
1752 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1753 if( pSort->nDefer ){
1754 int iKey = iCol+1;
1755 int regKey = sqlite3GetTempRange(pParse, nRefKey);
1757 for(i=0; i<pSort->nDefer; i++){
1758 int iCsr = pSort->aDefer[i].iCsr;
1759 Table *pTab = pSort->aDefer[i].pTab;
1760 int nKey = pSort->aDefer[i].nKey;
1762 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1763 if( HasRowid(pTab) ){
1764 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
1765 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
1766 sqlite3VdbeCurrentAddr(v)+1, regKey);
1767 }else{
1768 int k;
1769 int iJmp;
1770 assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
1771 for(k=0; k<nKey; k++){
1772 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
1774 iJmp = sqlite3VdbeCurrentAddr(v);
1775 sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
1776 sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
1777 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1780 sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
1782 #endif
1783 for(i=nColumn-1; i>=0; i--){
1784 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1785 if( aOutEx[i].fg.bSorterRef ){
1786 sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
1787 }else
1788 #endif
1790 int iRead;
1791 if( aOutEx[i].u.x.iOrderByCol ){
1792 iRead = aOutEx[i].u.x.iOrderByCol-1;
1793 }else{
1794 iRead = iCol--;
1796 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
1797 VdbeComment((v, "%s", aOutEx[i].zEName));
1800 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
1801 switch( eDest ){
1802 case SRT_Table:
1803 case SRT_EphemTab: {
1804 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
1805 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1806 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1807 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1808 break;
1810 #ifndef SQLITE_OMIT_SUBQUERY
1811 case SRT_Set: {
1812 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
1813 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
1814 pDest->zAffSdst, nColumn);
1815 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
1816 break;
1818 case SRT_Mem: {
1819 /* The LIMIT clause will terminate the loop for us */
1820 break;
1822 #endif
1823 case SRT_Upfrom: {
1824 int i2 = pDest->iSDParm2;
1825 int r1 = sqlite3GetTempReg(pParse);
1826 sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
1827 if( i2<0 ){
1828 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
1829 }else{
1830 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
1832 break;
1834 default: {
1835 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
1836 testcase( eDest==SRT_Output );
1837 testcase( eDest==SRT_Coroutine );
1838 if( eDest==SRT_Output ){
1839 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1840 }else{
1841 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1843 break;
1846 if( regRowid ){
1847 if( eDest==SRT_Set ){
1848 sqlite3ReleaseTempRange(pParse, regRow, nColumn);
1849 }else{
1850 sqlite3ReleaseTempReg(pParse, regRow);
1852 sqlite3ReleaseTempReg(pParse, regRowid);
1854 /* The bottom of the loop
1856 sqlite3VdbeResolveLabel(v, addrContinue);
1857 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1858 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1859 }else{
1860 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1862 sqlite3VdbeScanStatusRange(v, addrExplain, sqlite3VdbeCurrentAddr(v)-1, -1);
1863 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1864 sqlite3VdbeResolveLabel(v, addrBreak);
1868 ** Return a pointer to a string containing the 'declaration type' of the
1869 ** expression pExpr. The string may be treated as static by the caller.
1871 ** The declaration type is the exact datatype definition extracted from the
1872 ** original CREATE TABLE statement if the expression is a column. The
1873 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1874 ** is considered a column can be complex in the presence of subqueries. The
1875 ** result-set expression in all of the following SELECT statements is
1876 ** considered a column by this function.
1878 ** SELECT col FROM tbl;
1879 ** SELECT (SELECT col FROM tbl;
1880 ** SELECT (SELECT col FROM tbl);
1881 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
1883 ** The declaration type for any expression other than a column is NULL.
1885 ** This routine has either 3 or 6 parameters depending on whether or not
1886 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1888 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1889 # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
1890 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1891 # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
1892 #endif
1893 static const char *columnTypeImpl(
1894 NameContext *pNC,
1895 #ifndef SQLITE_ENABLE_COLUMN_METADATA
1896 Expr *pExpr
1897 #else
1898 Expr *pExpr,
1899 const char **pzOrigDb,
1900 const char **pzOrigTab,
1901 const char **pzOrigCol
1902 #endif
1904 char const *zType = 0;
1905 int j;
1906 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1907 char const *zOrigDb = 0;
1908 char const *zOrigTab = 0;
1909 char const *zOrigCol = 0;
1910 #endif
1912 assert( pExpr!=0 );
1913 assert( pNC->pSrcList!=0 );
1914 switch( pExpr->op ){
1915 case TK_COLUMN: {
1916 /* The expression is a column. Locate the table the column is being
1917 ** extracted from in NameContext.pSrcList. This table may be real
1918 ** database table or a subquery.
1920 Table *pTab = 0; /* Table structure column is extracted from */
1921 Select *pS = 0; /* Select the column is extracted from */
1922 int iCol = pExpr->iColumn; /* Index of column in pTab */
1923 while( pNC && !pTab ){
1924 SrcList *pTabList = pNC->pSrcList;
1925 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1926 if( j<pTabList->nSrc ){
1927 pTab = pTabList->a[j].pTab;
1928 pS = pTabList->a[j].pSelect;
1929 }else{
1930 pNC = pNC->pNext;
1934 if( pTab==0 ){
1935 /* At one time, code such as "SELECT new.x" within a trigger would
1936 ** cause this condition to run. Since then, we have restructured how
1937 ** trigger code is generated and so this condition is no longer
1938 ** possible. However, it can still be true for statements like
1939 ** the following:
1941 ** CREATE TABLE t1(col INTEGER);
1942 ** SELECT (SELECT t1.col) FROM FROM t1;
1944 ** when columnType() is called on the expression "t1.col" in the
1945 ** sub-select. In this case, set the column type to NULL, even
1946 ** though it should really be "INTEGER".
1948 ** This is not a problem, as the column type of "t1.col" is never
1949 ** used. When columnType() is called on the expression
1950 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
1951 ** branch below. */
1952 break;
1955 assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
1956 if( pS ){
1957 /* The "table" is actually a sub-select or a view in the FROM clause
1958 ** of the SELECT statement. Return the declaration type and origin
1959 ** data for the result-set column of the sub-select.
1961 if( iCol<pS->pEList->nExpr
1962 && (!ViewCanHaveRowid || iCol>=0)
1964 /* If iCol is less than zero, then the expression requests the
1965 ** rowid of the sub-select or view. This expression is legal (see
1966 ** test case misc2.2.2) - it always evaluates to NULL.
1968 NameContext sNC;
1969 Expr *p = pS->pEList->a[iCol].pExpr;
1970 sNC.pSrcList = pS->pSrc;
1971 sNC.pNext = pNC;
1972 sNC.pParse = pNC->pParse;
1973 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
1975 }else{
1976 /* A real table or a CTE table */
1977 assert( !pS );
1978 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1979 if( iCol<0 ) iCol = pTab->iPKey;
1980 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1981 if( iCol<0 ){
1982 zType = "INTEGER";
1983 zOrigCol = "rowid";
1984 }else{
1985 zOrigCol = pTab->aCol[iCol].zCnName;
1986 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
1988 zOrigTab = pTab->zName;
1989 if( pNC->pParse && pTab->pSchema ){
1990 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1991 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
1993 #else
1994 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1995 if( iCol<0 ){
1996 zType = "INTEGER";
1997 }else{
1998 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
2000 #endif
2002 break;
2004 #ifndef SQLITE_OMIT_SUBQUERY
2005 case TK_SELECT: {
2006 /* The expression is a sub-select. Return the declaration type and
2007 ** origin info for the single column in the result set of the SELECT
2008 ** statement.
2010 NameContext sNC;
2011 Select *pS;
2012 Expr *p;
2013 assert( ExprUseXSelect(pExpr) );
2014 pS = pExpr->x.pSelect;
2015 p = pS->pEList->a[0].pExpr;
2016 sNC.pSrcList = pS->pSrc;
2017 sNC.pNext = pNC;
2018 sNC.pParse = pNC->pParse;
2019 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2020 break;
2022 #endif
2025 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2026 if( pzOrigDb ){
2027 assert( pzOrigTab && pzOrigCol );
2028 *pzOrigDb = zOrigDb;
2029 *pzOrigTab = zOrigTab;
2030 *pzOrigCol = zOrigCol;
2032 #endif
2033 return zType;
2037 ** Generate code that will tell the VDBE the declaration types of columns
2038 ** in the result set.
2040 static void generateColumnTypes(
2041 Parse *pParse, /* Parser context */
2042 SrcList *pTabList, /* List of tables */
2043 ExprList *pEList /* Expressions defining the result set */
2045 #ifndef SQLITE_OMIT_DECLTYPE
2046 Vdbe *v = pParse->pVdbe;
2047 int i;
2048 NameContext sNC;
2049 sNC.pSrcList = pTabList;
2050 sNC.pParse = pParse;
2051 sNC.pNext = 0;
2052 for(i=0; i<pEList->nExpr; i++){
2053 Expr *p = pEList->a[i].pExpr;
2054 const char *zType;
2055 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2056 const char *zOrigDb = 0;
2057 const char *zOrigTab = 0;
2058 const char *zOrigCol = 0;
2059 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2061 /* The vdbe must make its own copy of the column-type and other
2062 ** column specific strings, in case the schema is reset before this
2063 ** virtual machine is deleted.
2065 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
2066 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
2067 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
2068 #else
2069 zType = columnType(&sNC, p, 0, 0, 0);
2070 #endif
2071 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
2073 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
2078 ** Compute the column names for a SELECT statement.
2080 ** The only guarantee that SQLite makes about column names is that if the
2081 ** column has an AS clause assigning it a name, that will be the name used.
2082 ** That is the only documented guarantee. However, countless applications
2083 ** developed over the years have made baseless assumptions about column names
2084 ** and will break if those assumptions changes. Hence, use extreme caution
2085 ** when modifying this routine to avoid breaking legacy.
2087 ** See Also: sqlite3ColumnsFromExprList()
2089 ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
2090 ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
2091 ** applications should operate this way. Nevertheless, we need to support the
2092 ** other modes for legacy:
2094 ** short=OFF, full=OFF: Column name is the text of the expression has it
2095 ** originally appears in the SELECT statement. In
2096 ** other words, the zSpan of the result expression.
2098 ** short=ON, full=OFF: (This is the default setting). If the result
2099 ** refers directly to a table column, then the
2100 ** result column name is just the table column
2101 ** name: COLUMN. Otherwise use zSpan.
2103 ** full=ON, short=ANY: If the result refers directly to a table column,
2104 ** then the result column name with the table name
2105 ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
2107 void sqlite3GenerateColumnNames(
2108 Parse *pParse, /* Parser context */
2109 Select *pSelect /* Generate column names for this SELECT statement */
2111 Vdbe *v = pParse->pVdbe;
2112 int i;
2113 Table *pTab;
2114 SrcList *pTabList;
2115 ExprList *pEList;
2116 sqlite3 *db = pParse->db;
2117 int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
2118 int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
2120 if( pParse->colNamesSet ) return;
2121 /* Column names are determined by the left-most term of a compound select */
2122 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2123 TREETRACE(0x80,pParse,pSelect,("generating column names\n"));
2124 pTabList = pSelect->pSrc;
2125 pEList = pSelect->pEList;
2126 assert( v!=0 );
2127 assert( pTabList!=0 );
2128 pParse->colNamesSet = 1;
2129 fullName = (db->flags & SQLITE_FullColNames)!=0;
2130 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
2131 sqlite3VdbeSetNumCols(v, pEList->nExpr);
2132 for(i=0; i<pEList->nExpr; i++){
2133 Expr *p = pEList->a[i].pExpr;
2135 assert( p!=0 );
2136 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
2137 assert( p->op!=TK_COLUMN
2138 || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
2139 if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
2140 /* An AS clause always takes first priority */
2141 char *zName = pEList->a[i].zEName;
2142 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
2143 }else if( srcName && p->op==TK_COLUMN ){
2144 char *zCol;
2145 int iCol = p->iColumn;
2146 pTab = p->y.pTab;
2147 assert( pTab!=0 );
2148 if( iCol<0 ) iCol = pTab->iPKey;
2149 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
2150 if( iCol<0 ){
2151 zCol = "rowid";
2152 }else{
2153 zCol = pTab->aCol[iCol].zCnName;
2155 if( fullName ){
2156 char *zName = 0;
2157 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
2158 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
2159 }else{
2160 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
2162 }else{
2163 const char *z = pEList->a[i].zEName;
2164 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
2165 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
2168 generateColumnTypes(pParse, pTabList, pEList);
2172 ** Given an expression list (which is really the list of expressions
2173 ** that form the result set of a SELECT statement) compute appropriate
2174 ** column names for a table that would hold the expression list.
2176 ** All column names will be unique.
2178 ** Only the column names are computed. Column.zType, Column.zColl,
2179 ** and other fields of Column are zeroed.
2181 ** Return SQLITE_OK on success. If a memory allocation error occurs,
2182 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
2184 ** The only guarantee that SQLite makes about column names is that if the
2185 ** column has an AS clause assigning it a name, that will be the name used.
2186 ** That is the only documented guarantee. However, countless applications
2187 ** developed over the years have made baseless assumptions about column names
2188 ** and will break if those assumptions changes. Hence, use extreme caution
2189 ** when modifying this routine to avoid breaking legacy.
2191 ** See Also: sqlite3GenerateColumnNames()
2193 int sqlite3ColumnsFromExprList(
2194 Parse *pParse, /* Parsing context */
2195 ExprList *pEList, /* Expr list from which to derive column names */
2196 i16 *pnCol, /* Write the number of columns here */
2197 Column **paCol /* Write the new column list here */
2199 sqlite3 *db = pParse->db; /* Database connection */
2200 int i, j; /* Loop counters */
2201 u32 cnt; /* Index added to make the name unique */
2202 Column *aCol, *pCol; /* For looping over result columns */
2203 int nCol; /* Number of columns in the result set */
2204 char *zName; /* Column name */
2205 int nName; /* Size of name in zName[] */
2206 Hash ht; /* Hash table of column names */
2207 Table *pTab;
2209 sqlite3HashInit(&ht);
2210 if( pEList ){
2211 nCol = pEList->nExpr;
2212 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
2213 testcase( aCol==0 );
2214 if( NEVER(nCol>32767) ) nCol = 32767;
2215 }else{
2216 nCol = 0;
2217 aCol = 0;
2219 assert( nCol==(i16)nCol );
2220 *pnCol = nCol;
2221 *paCol = aCol;
2223 for(i=0, pCol=aCol; i<nCol && !pParse->nErr; i++, pCol++){
2224 struct ExprList_item *pX = &pEList->a[i];
2225 struct ExprList_item *pCollide;
2226 /* Get an appropriate name for the column
2228 if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
2229 /* If the column contains an "AS <name>" phrase, use <name> as the name */
2230 }else{
2231 Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
2232 while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
2233 pColExpr = pColExpr->pRight;
2234 assert( pColExpr!=0 );
2236 if( pColExpr->op==TK_COLUMN
2237 && ALWAYS( ExprUseYTab(pColExpr) )
2238 && ALWAYS( pColExpr->y.pTab!=0 )
2240 /* For columns use the column name name */
2241 int iCol = pColExpr->iColumn;
2242 pTab = pColExpr->y.pTab;
2243 if( iCol<0 ) iCol = pTab->iPKey;
2244 zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
2245 }else if( pColExpr->op==TK_ID ){
2246 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
2247 zName = pColExpr->u.zToken;
2248 }else{
2249 /* Use the original text of the column expression as its name */
2250 assert( zName==pX->zEName ); /* pointer comparison intended */
2253 if( zName && !sqlite3IsTrueOrFalse(zName) ){
2254 zName = sqlite3DbStrDup(db, zName);
2255 }else{
2256 zName = sqlite3MPrintf(db,"column%d",i+1);
2259 /* Make sure the column name is unique. If the name is not unique,
2260 ** append an integer to the name so that it becomes unique.
2262 cnt = 0;
2263 while( zName && (pCollide = sqlite3HashFind(&ht, zName))!=0 ){
2264 if( pCollide->fg.bUsingTerm ){
2265 pCol->colFlags |= COLFLAG_NOEXPAND;
2267 nName = sqlite3Strlen30(zName);
2268 if( nName>0 ){
2269 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
2270 if( zName[j]==':' ) nName = j;
2272 zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
2273 sqlite3ProgressCheck(pParse);
2274 if( cnt>3 ){
2275 sqlite3_randomness(sizeof(cnt), &cnt);
2278 pCol->zCnName = zName;
2279 pCol->hName = sqlite3StrIHash(zName);
2280 if( pX->fg.bNoExpand ){
2281 pCol->colFlags |= COLFLAG_NOEXPAND;
2283 sqlite3ColumnPropertiesFromName(0, pCol);
2284 if( zName && sqlite3HashInsert(&ht, zName, pX)==pX ){
2285 sqlite3OomFault(db);
2288 sqlite3HashClear(&ht);
2289 if( pParse->nErr ){
2290 for(j=0; j<i; j++){
2291 sqlite3DbFree(db, aCol[j].zCnName);
2293 sqlite3DbFree(db, aCol);
2294 *paCol = 0;
2295 *pnCol = 0;
2296 return pParse->rc;
2298 return SQLITE_OK;
2302 ** pTab is a transient Table object that represents a subquery of some
2303 ** kind (maybe a parenthesized subquery in the FROM clause of a larger
2304 ** query, or a VIEW, or a CTE). This routine computes type information
2305 ** for that Table object based on the Select object that implements the
2306 ** subquery. For the purposes of this routine, "type information" means:
2308 ** * The datatype name, as it might appear in a CREATE TABLE statement
2309 ** * Which collating sequence to use for the column
2310 ** * The affinity of the column
2312 void sqlite3SubqueryColumnTypes(
2313 Parse *pParse, /* Parsing contexts */
2314 Table *pTab, /* Add column type information to this table */
2315 Select *pSelect, /* SELECT used to determine types and collations */
2316 char aff /* Default affinity. */
2318 sqlite3 *db = pParse->db;
2319 Column *pCol;
2320 CollSeq *pColl;
2321 int i,j;
2322 Expr *p;
2323 struct ExprList_item *a;
2324 NameContext sNC;
2326 assert( pSelect!=0 );
2327 assert( (pSelect->selFlags & SF_Resolved)!=0 );
2328 assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
2329 assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
2330 if( db->mallocFailed || IN_RENAME_OBJECT ) return;
2331 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2332 a = pSelect->pEList->a;
2333 memset(&sNC, 0, sizeof(sNC));
2334 sNC.pSrcList = pSelect->pSrc;
2335 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
2336 const char *zType;
2337 i64 n;
2338 int m = 0;
2339 Select *pS2 = pSelect;
2340 pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
2341 p = a[i].pExpr;
2342 /* pCol->szEst = ... // Column size est for SELECT tables never used */
2343 pCol->affinity = sqlite3ExprAffinity(p);
2344 while( pCol->affinity<=SQLITE_AFF_NONE && pS2->pNext!=0 ){
2345 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
2346 pS2 = pS2->pNext;
2347 pCol->affinity = sqlite3ExprAffinity(pS2->pEList->a[i].pExpr);
2349 if( pCol->affinity<=SQLITE_AFF_NONE ){
2350 pCol->affinity = aff;
2352 if( pCol->affinity>=SQLITE_AFF_TEXT && (pS2->pNext || pS2!=pSelect) ){
2353 for(pS2=pS2->pNext; pS2; pS2=pS2->pNext){
2354 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
2356 if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
2357 pCol->affinity = SQLITE_AFF_BLOB;
2358 }else
2359 if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
2360 pCol->affinity = SQLITE_AFF_BLOB;
2362 if( pCol->affinity>=SQLITE_AFF_NUMERIC && p->op==TK_CAST ){
2363 pCol->affinity = SQLITE_AFF_FLEXNUM;
2366 zType = columnType(&sNC, p, 0, 0, 0);
2367 if( zType==0 || pCol->affinity!=sqlite3AffinityType(zType, 0) ){
2368 if( pCol->affinity==SQLITE_AFF_NUMERIC
2369 || pCol->affinity==SQLITE_AFF_FLEXNUM
2371 zType = "NUM";
2372 }else{
2373 zType = 0;
2374 for(j=1; j<SQLITE_N_STDTYPE; j++){
2375 if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
2376 zType = sqlite3StdType[j];
2377 break;
2382 if( zType ){
2383 const i64 k = sqlite3Strlen30(zType);
2384 n = sqlite3Strlen30(pCol->zCnName);
2385 pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+k+2);
2386 pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
2387 if( pCol->zCnName ){
2388 memcpy(&pCol->zCnName[n+1], zType, k+1);
2389 pCol->colFlags |= COLFLAG_HASTYPE;
2392 pColl = sqlite3ExprCollSeq(pParse, p);
2393 if( pColl ){
2394 assert( pTab->pIndex==0 );
2395 sqlite3ColumnSetColl(db, pCol, pColl->zName);
2398 pTab->szTabRow = 1; /* Any non-zero value works */
2402 ** Given a SELECT statement, generate a Table structure that describes
2403 ** the result set of that SELECT.
2405 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
2406 Table *pTab;
2407 sqlite3 *db = pParse->db;
2408 u64 savedFlags;
2410 savedFlags = db->flags;
2411 db->flags &= ~(u64)SQLITE_FullColNames;
2412 db->flags |= SQLITE_ShortColNames;
2413 sqlite3SelectPrep(pParse, pSelect, 0);
2414 db->flags = savedFlags;
2415 if( pParse->nErr ) return 0;
2416 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2417 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
2418 if( pTab==0 ){
2419 return 0;
2421 pTab->nTabRef = 1;
2422 pTab->zName = 0;
2423 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
2424 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
2425 sqlite3SubqueryColumnTypes(pParse, pTab, pSelect, aff);
2426 pTab->iPKey = -1;
2427 if( db->mallocFailed ){
2428 sqlite3DeleteTable(db, pTab);
2429 return 0;
2431 return pTab;
2435 ** Get a VDBE for the given parser context. Create a new one if necessary.
2436 ** If an error occurs, return NULL and leave a message in pParse.
2438 Vdbe *sqlite3GetVdbe(Parse *pParse){
2439 if( pParse->pVdbe ){
2440 return pParse->pVdbe;
2442 if( pParse->pToplevel==0
2443 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
2445 pParse->okConstFactor = 1;
2447 return sqlite3VdbeCreate(pParse);
2452 ** Compute the iLimit and iOffset fields of the SELECT based on the
2453 ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
2454 ** that appear in the original SQL statement after the LIMIT and OFFSET
2455 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
2456 ** are the integer memory register numbers for counters used to compute
2457 ** the limit and offset. If there is no limit and/or offset, then
2458 ** iLimit and iOffset are negative.
2460 ** This routine changes the values of iLimit and iOffset only if
2461 ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
2462 ** and iOffset should have been preset to appropriate default values (zero)
2463 ** prior to calling this routine.
2465 ** The iOffset register (if it exists) is initialized to the value
2466 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
2467 ** iOffset+1 is initialized to LIMIT+OFFSET.
2469 ** Only if pLimit->pLeft!=0 do the limit registers get
2470 ** redefined. The UNION ALL operator uses this property to force
2471 ** the reuse of the same limit and offset registers across multiple
2472 ** SELECT statements.
2474 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
2475 Vdbe *v = 0;
2476 int iLimit = 0;
2477 int iOffset;
2478 int n;
2479 Expr *pLimit = p->pLimit;
2481 if( p->iLimit ) return;
2484 ** "LIMIT -1" always shows all rows. There is some
2485 ** controversy about what the correct behavior should be.
2486 ** The current implementation interprets "LIMIT 0" to mean
2487 ** no rows.
2489 if( pLimit ){
2490 assert( pLimit->op==TK_LIMIT );
2491 assert( pLimit->pLeft!=0 );
2492 p->iLimit = iLimit = ++pParse->nMem;
2493 v = sqlite3GetVdbe(pParse);
2494 assert( v!=0 );
2495 if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
2496 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
2497 VdbeComment((v, "LIMIT counter"));
2498 if( n==0 ){
2499 sqlite3VdbeGoto(v, iBreak);
2500 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
2501 p->nSelectRow = sqlite3LogEst((u64)n);
2502 p->selFlags |= SF_FixedLimit;
2504 }else{
2505 sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
2506 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
2507 VdbeComment((v, "LIMIT counter"));
2508 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
2510 if( pLimit->pRight ){
2511 p->iOffset = iOffset = ++pParse->nMem;
2512 pParse->nMem++; /* Allocate an extra register for limit+offset */
2513 sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
2514 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
2515 VdbeComment((v, "OFFSET counter"));
2516 sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
2517 VdbeComment((v, "LIMIT+OFFSET"));
2522 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2524 ** Return the appropriate collating sequence for the iCol-th column of
2525 ** the result set for the compound-select statement "p". Return NULL if
2526 ** the column has no default collating sequence.
2528 ** The collating sequence for the compound select is taken from the
2529 ** left-most term of the select that has a collating sequence.
2531 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
2532 CollSeq *pRet;
2533 if( p->pPrior ){
2534 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
2535 }else{
2536 pRet = 0;
2538 assert( iCol>=0 );
2539 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
2540 ** have been thrown during name resolution and we would not have gotten
2541 ** this far */
2542 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
2543 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
2545 return pRet;
2549 ** The select statement passed as the second parameter is a compound SELECT
2550 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
2551 ** structure suitable for implementing the ORDER BY.
2553 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
2554 ** function is responsible for ensuring that this structure is eventually
2555 ** freed.
2557 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
2558 ExprList *pOrderBy = p->pOrderBy;
2559 int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
2560 sqlite3 *db = pParse->db;
2561 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
2562 if( pRet ){
2563 int i;
2564 for(i=0; i<nOrderBy; i++){
2565 struct ExprList_item *pItem = &pOrderBy->a[i];
2566 Expr *pTerm = pItem->pExpr;
2567 CollSeq *pColl;
2569 if( pTerm->flags & EP_Collate ){
2570 pColl = sqlite3ExprCollSeq(pParse, pTerm);
2571 }else{
2572 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
2573 if( pColl==0 ) pColl = db->pDfltColl;
2574 pOrderBy->a[i].pExpr =
2575 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
2577 assert( sqlite3KeyInfoIsWriteable(pRet) );
2578 pRet->aColl[i] = pColl;
2579 pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
2583 return pRet;
2586 #ifndef SQLITE_OMIT_CTE
2588 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
2589 ** query of the form:
2591 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
2592 ** \___________/ \_______________/
2593 ** p->pPrior p
2596 ** There is exactly one reference to the recursive-table in the FROM clause
2597 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
2599 ** The setup-query runs once to generate an initial set of rows that go
2600 ** into a Queue table. Rows are extracted from the Queue table one by
2601 ** one. Each row extracted from Queue is output to pDest. Then the single
2602 ** extracted row (now in the iCurrent table) becomes the content of the
2603 ** recursive-table for a recursive-query run. The output of the recursive-query
2604 ** is added back into the Queue table. Then another row is extracted from Queue
2605 ** and the iteration continues until the Queue table is empty.
2607 ** If the compound query operator is UNION then no duplicate rows are ever
2608 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
2609 ** that have ever been inserted into Queue and causes duplicates to be
2610 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
2612 ** If the query has an ORDER BY, then entries in the Queue table are kept in
2613 ** ORDER BY order and the first entry is extracted for each cycle. Without
2614 ** an ORDER BY, the Queue table is just a FIFO.
2616 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
2617 ** have been output to pDest. A LIMIT of zero means to output no rows and a
2618 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
2619 ** with a positive value, then the first OFFSET outputs are discarded rather
2620 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
2621 ** rows have been skipped.
2623 static void generateWithRecursiveQuery(
2624 Parse *pParse, /* Parsing context */
2625 Select *p, /* The recursive SELECT to be coded */
2626 SelectDest *pDest /* What to do with query results */
2628 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
2629 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
2630 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
2631 Select *pSetup; /* The setup query */
2632 Select *pFirstRec; /* Left-most recursive term */
2633 int addrTop; /* Top of the loop */
2634 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
2635 int iCurrent = 0; /* The Current table */
2636 int regCurrent; /* Register holding Current table */
2637 int iQueue; /* The Queue table */
2638 int iDistinct = 0; /* To ensure unique results if UNION */
2639 int eDest = SRT_Fifo; /* How to write to Queue */
2640 SelectDest destQueue; /* SelectDest targeting the Queue table */
2641 int i; /* Loop counter */
2642 int rc; /* Result code */
2643 ExprList *pOrderBy; /* The ORDER BY clause */
2644 Expr *pLimit; /* Saved LIMIT and OFFSET */
2645 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
2647 #ifndef SQLITE_OMIT_WINDOWFUNC
2648 if( p->pWin ){
2649 sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
2650 return;
2652 #endif
2654 /* Obtain authorization to do a recursive query */
2655 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2657 /* Process the LIMIT and OFFSET clauses, if they exist */
2658 addrBreak = sqlite3VdbeMakeLabel(pParse);
2659 p->nSelectRow = 320; /* 4 billion rows */
2660 computeLimitRegisters(pParse, p, addrBreak);
2661 pLimit = p->pLimit;
2662 regLimit = p->iLimit;
2663 regOffset = p->iOffset;
2664 p->pLimit = 0;
2665 p->iLimit = p->iOffset = 0;
2666 pOrderBy = p->pOrderBy;
2668 /* Locate the cursor number of the Current table */
2669 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
2670 if( pSrc->a[i].fg.isRecursive ){
2671 iCurrent = pSrc->a[i].iCursor;
2672 break;
2676 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
2677 ** the Distinct table must be exactly one greater than Queue in order
2678 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2679 iQueue = pParse->nTab++;
2680 if( p->op==TK_UNION ){
2681 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2682 iDistinct = pParse->nTab++;
2683 }else{
2684 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2686 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2688 /* Allocate cursors for Current, Queue, and Distinct. */
2689 regCurrent = ++pParse->nMem;
2690 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2691 if( pOrderBy ){
2692 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2693 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2694 (char*)pKeyInfo, P4_KEYINFO);
2695 destQueue.pOrderBy = pOrderBy;
2696 }else{
2697 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2699 VdbeComment((v, "Queue table"));
2700 if( iDistinct ){
2701 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2702 p->selFlags |= SF_UsesEphemeral;
2705 /* Detach the ORDER BY clause from the compound SELECT */
2706 p->pOrderBy = 0;
2708 /* Figure out how many elements of the compound SELECT are part of the
2709 ** recursive query. Make sure no recursive elements use aggregate
2710 ** functions. Mark the recursive elements as UNION ALL even if they
2711 ** are really UNION because the distinctness will be enforced by the
2712 ** iDistinct table. pFirstRec is left pointing to the left-most
2713 ** recursive term of the CTE.
2715 for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
2716 if( pFirstRec->selFlags & SF_Aggregate ){
2717 sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2718 goto end_of_recursive_query;
2720 pFirstRec->op = TK_ALL;
2721 if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
2724 /* Store the results of the setup-query in Queue. */
2725 pSetup = pFirstRec->pPrior;
2726 pSetup->pNext = 0;
2727 ExplainQueryPlan((pParse, 1, "SETUP"));
2728 rc = sqlite3Select(pParse, pSetup, &destQueue);
2729 pSetup->pNext = p;
2730 if( rc ) goto end_of_recursive_query;
2732 /* Find the next row in the Queue and output that row */
2733 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2735 /* Transfer the next row in Queue over to Current */
2736 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2737 if( pOrderBy ){
2738 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2739 }else{
2740 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2742 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2744 /* Output the single row in Current */
2745 addrCont = sqlite3VdbeMakeLabel(pParse);
2746 codeOffset(v, regOffset, addrCont);
2747 selectInnerLoop(pParse, p, iCurrent,
2748 0, 0, pDest, addrCont, addrBreak);
2749 if( regLimit ){
2750 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2751 VdbeCoverage(v);
2753 sqlite3VdbeResolveLabel(v, addrCont);
2755 /* Execute the recursive SELECT taking the single row in Current as
2756 ** the value for the recursive-table. Store the results in the Queue.
2758 pFirstRec->pPrior = 0;
2759 ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
2760 sqlite3Select(pParse, p, &destQueue);
2761 assert( pFirstRec->pPrior==0 );
2762 pFirstRec->pPrior = pSetup;
2764 /* Keep running the loop until the Queue is empty */
2765 sqlite3VdbeGoto(v, addrTop);
2766 sqlite3VdbeResolveLabel(v, addrBreak);
2768 end_of_recursive_query:
2769 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2770 p->pOrderBy = pOrderBy;
2771 p->pLimit = pLimit;
2772 return;
2774 #endif /* SQLITE_OMIT_CTE */
2776 /* Forward references */
2777 static int multiSelectOrderBy(
2778 Parse *pParse, /* Parsing context */
2779 Select *p, /* The right-most of SELECTs to be coded */
2780 SelectDest *pDest /* What to do with query results */
2784 ** Handle the special case of a compound-select that originates from a
2785 ** VALUES clause. By handling this as a special case, we avoid deep
2786 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
2787 ** on a VALUES clause.
2789 ** Because the Select object originates from a VALUES clause:
2790 ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
2791 ** (2) All terms are UNION ALL
2792 ** (3) There is no ORDER BY clause
2794 ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
2795 ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
2796 ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
2797 ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
2799 static int multiSelectValues(
2800 Parse *pParse, /* Parsing context */
2801 Select *p, /* The right-most of SELECTs to be coded */
2802 SelectDest *pDest /* What to do with query results */
2804 int nRow = 1;
2805 int rc = 0;
2806 int bShowAll = p->pLimit==0;
2807 assert( p->selFlags & SF_MultiValue );
2809 assert( p->selFlags & SF_Values );
2810 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
2811 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
2812 #ifndef SQLITE_OMIT_WINDOWFUNC
2813 if( p->pWin ) return -1;
2814 #endif
2815 if( p->pPrior==0 ) break;
2816 assert( p->pPrior->pNext==p );
2817 p = p->pPrior;
2818 nRow += bShowAll;
2819 }while(1);
2820 ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
2821 nRow==1 ? "" : "S"));
2822 while( p ){
2823 selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
2824 if( !bShowAll ) break;
2825 p->nSelectRow = nRow;
2826 p = p->pNext;
2828 return rc;
2832 ** Return true if the SELECT statement which is known to be the recursive
2833 ** part of a recursive CTE still has its anchor terms attached. If the
2834 ** anchor terms have already been removed, then return false.
2836 static int hasAnchor(Select *p){
2837 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
2838 return p!=0;
2842 ** This routine is called to process a compound query form from
2843 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
2844 ** INTERSECT
2846 ** "p" points to the right-most of the two queries. the query on the
2847 ** left is p->pPrior. The left query could also be a compound query
2848 ** in which case this routine will be called recursively.
2850 ** The results of the total query are to be written into a destination
2851 ** of type eDest with parameter iParm.
2853 ** Example 1: Consider a three-way compound SQL statement.
2855 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2857 ** This statement is parsed up as follows:
2859 ** SELECT c FROM t3
2860 ** |
2861 ** `-----> SELECT b FROM t2
2862 ** |
2863 ** `------> SELECT a FROM t1
2865 ** The arrows in the diagram above represent the Select.pPrior pointer.
2866 ** So if this routine is called with p equal to the t3 query, then
2867 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
2869 ** Notice that because of the way SQLite parses compound SELECTs, the
2870 ** individual selects always group from left to right.
2872 static int multiSelect(
2873 Parse *pParse, /* Parsing context */
2874 Select *p, /* The right-most of SELECTs to be coded */
2875 SelectDest *pDest /* What to do with query results */
2877 int rc = SQLITE_OK; /* Success code from a subroutine */
2878 Select *pPrior; /* Another SELECT immediately to our left */
2879 Vdbe *v; /* Generate code to this VDBE */
2880 SelectDest dest; /* Alternative data destination */
2881 Select *pDelete = 0; /* Chain of simple selects to delete */
2882 sqlite3 *db; /* Database connection */
2884 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
2885 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
2887 assert( p && p->pPrior ); /* Calling function guarantees this much */
2888 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2889 assert( p->selFlags & SF_Compound );
2890 db = pParse->db;
2891 pPrior = p->pPrior;
2892 dest = *pDest;
2893 assert( pPrior->pOrderBy==0 );
2894 assert( pPrior->pLimit==0 );
2896 v = sqlite3GetVdbe(pParse);
2897 assert( v!=0 ); /* The VDBE already created by calling function */
2899 /* Create the destination temporary table if necessary
2901 if( dest.eDest==SRT_EphemTab ){
2902 assert( p->pEList );
2903 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2904 dest.eDest = SRT_Table;
2907 /* Special handling for a compound-select that originates as a VALUES clause.
2909 if( p->selFlags & SF_MultiValue ){
2910 rc = multiSelectValues(pParse, p, &dest);
2911 if( rc>=0 ) goto multi_select_end;
2912 rc = SQLITE_OK;
2915 /* Make sure all SELECTs in the statement have the same number of elements
2916 ** in their result sets.
2918 assert( p->pEList && pPrior->pEList );
2919 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2921 #ifndef SQLITE_OMIT_CTE
2922 if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
2923 generateWithRecursiveQuery(pParse, p, &dest);
2924 }else
2925 #endif
2927 /* Compound SELECTs that have an ORDER BY clause are handled separately.
2929 if( p->pOrderBy ){
2930 return multiSelectOrderBy(pParse, p, pDest);
2931 }else{
2933 #ifndef SQLITE_OMIT_EXPLAIN
2934 if( pPrior->pPrior==0 ){
2935 ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
2936 ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
2938 #endif
2940 /* Generate code for the left and right SELECT statements.
2942 switch( p->op ){
2943 case TK_ALL: {
2944 int addr = 0;
2945 int nLimit = 0; /* Initialize to suppress harmless compiler warning */
2946 assert( !pPrior->pLimit );
2947 pPrior->iLimit = p->iLimit;
2948 pPrior->iOffset = p->iOffset;
2949 pPrior->pLimit = p->pLimit;
2950 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
2951 rc = sqlite3Select(pParse, pPrior, &dest);
2952 pPrior->pLimit = 0;
2953 if( rc ){
2954 goto multi_select_end;
2956 p->pPrior = 0;
2957 p->iLimit = pPrior->iLimit;
2958 p->iOffset = pPrior->iOffset;
2959 if( p->iLimit ){
2960 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2961 VdbeComment((v, "Jump ahead if LIMIT reached"));
2962 if( p->iOffset ){
2963 sqlite3VdbeAddOp3(v, OP_OffsetLimit,
2964 p->iLimit, p->iOffset+1, p->iOffset);
2967 ExplainQueryPlan((pParse, 1, "UNION ALL"));
2968 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
2969 rc = sqlite3Select(pParse, p, &dest);
2970 testcase( rc!=SQLITE_OK );
2971 pDelete = p->pPrior;
2972 p->pPrior = pPrior;
2973 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2974 if( p->pLimit
2975 && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
2976 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
2978 p->nSelectRow = sqlite3LogEst((u64)nLimit);
2980 if( addr ){
2981 sqlite3VdbeJumpHere(v, addr);
2983 break;
2985 case TK_EXCEPT:
2986 case TK_UNION: {
2987 int unionTab; /* Cursor number of the temp table holding result */
2988 u8 op = 0; /* One of the SRT_ operations to apply to self */
2989 int priorOp; /* The SRT_ operation to apply to prior selects */
2990 Expr *pLimit; /* Saved values of p->nLimit */
2991 int addr;
2992 SelectDest uniondest;
2994 testcase( p->op==TK_EXCEPT );
2995 testcase( p->op==TK_UNION );
2996 priorOp = SRT_Union;
2997 if( dest.eDest==priorOp ){
2998 /* We can reuse a temporary table generated by a SELECT to our
2999 ** right.
3001 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
3002 unionTab = dest.iSDParm;
3003 }else{
3004 /* We will need to create our own temporary table to hold the
3005 ** intermediate results.
3007 unionTab = pParse->nTab++;
3008 assert( p->pOrderBy==0 );
3009 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
3010 assert( p->addrOpenEphm[0] == -1 );
3011 p->addrOpenEphm[0] = addr;
3012 findRightmost(p)->selFlags |= SF_UsesEphemeral;
3013 assert( p->pEList );
3017 /* Code the SELECT statements to our left
3019 assert( !pPrior->pOrderBy );
3020 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
3021 TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
3022 rc = sqlite3Select(pParse, pPrior, &uniondest);
3023 if( rc ){
3024 goto multi_select_end;
3027 /* Code the current SELECT statement
3029 if( p->op==TK_EXCEPT ){
3030 op = SRT_Except;
3031 }else{
3032 assert( p->op==TK_UNION );
3033 op = SRT_Union;
3035 p->pPrior = 0;
3036 pLimit = p->pLimit;
3037 p->pLimit = 0;
3038 uniondest.eDest = op;
3039 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3040 sqlite3SelectOpName(p->op)));
3041 TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
3042 rc = sqlite3Select(pParse, p, &uniondest);
3043 testcase( rc!=SQLITE_OK );
3044 assert( p->pOrderBy==0 );
3045 pDelete = p->pPrior;
3046 p->pPrior = pPrior;
3047 p->pOrderBy = 0;
3048 if( p->op==TK_UNION ){
3049 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3051 sqlite3ExprDelete(db, p->pLimit);
3052 p->pLimit = pLimit;
3053 p->iLimit = 0;
3054 p->iOffset = 0;
3056 /* Convert the data in the temporary table into whatever form
3057 ** it is that we currently need.
3059 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
3060 assert( p->pEList || db->mallocFailed );
3061 if( dest.eDest!=priorOp && db->mallocFailed==0 ){
3062 int iCont, iBreak, iStart;
3063 iBreak = sqlite3VdbeMakeLabel(pParse);
3064 iCont = sqlite3VdbeMakeLabel(pParse);
3065 computeLimitRegisters(pParse, p, iBreak);
3066 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
3067 iStart = sqlite3VdbeCurrentAddr(v);
3068 selectInnerLoop(pParse, p, unionTab,
3069 0, 0, &dest, iCont, iBreak);
3070 sqlite3VdbeResolveLabel(v, iCont);
3071 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
3072 sqlite3VdbeResolveLabel(v, iBreak);
3073 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
3075 break;
3077 default: assert( p->op==TK_INTERSECT ); {
3078 int tab1, tab2;
3079 int iCont, iBreak, iStart;
3080 Expr *pLimit;
3081 int addr;
3082 SelectDest intersectdest;
3083 int r1;
3085 /* INTERSECT is different from the others since it requires
3086 ** two temporary tables. Hence it has its own case. Begin
3087 ** by allocating the tables we will need.
3089 tab1 = pParse->nTab++;
3090 tab2 = pParse->nTab++;
3091 assert( p->pOrderBy==0 );
3093 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
3094 assert( p->addrOpenEphm[0] == -1 );
3095 p->addrOpenEphm[0] = addr;
3096 findRightmost(p)->selFlags |= SF_UsesEphemeral;
3097 assert( p->pEList );
3099 /* Code the SELECTs to our left into temporary table "tab1".
3101 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
3102 TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT left...\n"));
3103 rc = sqlite3Select(pParse, pPrior, &intersectdest);
3104 if( rc ){
3105 goto multi_select_end;
3108 /* Code the current SELECT into temporary table "tab2"
3110 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
3111 assert( p->addrOpenEphm[1] == -1 );
3112 p->addrOpenEphm[1] = addr;
3113 p->pPrior = 0;
3114 pLimit = p->pLimit;
3115 p->pLimit = 0;
3116 intersectdest.iSDParm = tab2;
3117 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3118 sqlite3SelectOpName(p->op)));
3119 TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT right...\n"));
3120 rc = sqlite3Select(pParse, p, &intersectdest);
3121 testcase( rc!=SQLITE_OK );
3122 pDelete = p->pPrior;
3123 p->pPrior = pPrior;
3124 if( p->nSelectRow>pPrior->nSelectRow ){
3125 p->nSelectRow = pPrior->nSelectRow;
3127 sqlite3ExprDelete(db, p->pLimit);
3128 p->pLimit = pLimit;
3130 /* Generate code to take the intersection of the two temporary
3131 ** tables.
3133 if( rc ) break;
3134 assert( p->pEList );
3135 iBreak = sqlite3VdbeMakeLabel(pParse);
3136 iCont = sqlite3VdbeMakeLabel(pParse);
3137 computeLimitRegisters(pParse, p, iBreak);
3138 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
3139 r1 = sqlite3GetTempReg(pParse);
3140 iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
3141 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
3142 VdbeCoverage(v);
3143 sqlite3ReleaseTempReg(pParse, r1);
3144 selectInnerLoop(pParse, p, tab1,
3145 0, 0, &dest, iCont, iBreak);
3146 sqlite3VdbeResolveLabel(v, iCont);
3147 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
3148 sqlite3VdbeResolveLabel(v, iBreak);
3149 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
3150 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
3151 break;
3155 #ifndef SQLITE_OMIT_EXPLAIN
3156 if( p->pNext==0 ){
3157 ExplainQueryPlanPop(pParse);
3159 #endif
3161 if( pParse->nErr ) goto multi_select_end;
3163 /* Compute collating sequences used by
3164 ** temporary tables needed to implement the compound select.
3165 ** Attach the KeyInfo structure to all temporary tables.
3167 ** This section is run by the right-most SELECT statement only.
3168 ** SELECT statements to the left always skip this part. The right-most
3169 ** SELECT might also skip this part if it has no ORDER BY clause and
3170 ** no temp tables are required.
3172 if( p->selFlags & SF_UsesEphemeral ){
3173 int i; /* Loop counter */
3174 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
3175 Select *pLoop; /* For looping through SELECT statements */
3176 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
3177 int nCol; /* Number of columns in result set */
3179 assert( p->pNext==0 );
3180 assert( p->pEList!=0 );
3181 nCol = p->pEList->nExpr;
3182 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
3183 if( !pKeyInfo ){
3184 rc = SQLITE_NOMEM_BKPT;
3185 goto multi_select_end;
3187 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
3188 *apColl = multiSelectCollSeq(pParse, p, i);
3189 if( 0==*apColl ){
3190 *apColl = db->pDfltColl;
3194 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
3195 for(i=0; i<2; i++){
3196 int addr = pLoop->addrOpenEphm[i];
3197 if( addr<0 ){
3198 /* If [0] is unused then [1] is also unused. So we can
3199 ** always safely abort as soon as the first unused slot is found */
3200 assert( pLoop->addrOpenEphm[1]<0 );
3201 break;
3203 sqlite3VdbeChangeP2(v, addr, nCol);
3204 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
3205 P4_KEYINFO);
3206 pLoop->addrOpenEphm[i] = -1;
3209 sqlite3KeyInfoUnref(pKeyInfo);
3212 multi_select_end:
3213 pDest->iSdst = dest.iSdst;
3214 pDest->nSdst = dest.nSdst;
3215 if( pDelete ){
3216 sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pDelete);
3218 return rc;
3220 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
3223 ** Error message for when two or more terms of a compound select have different
3224 ** size result sets.
3226 void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
3227 if( p->selFlags & SF_Values ){
3228 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
3229 }else{
3230 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
3231 " do not have the same number of result columns",
3232 sqlite3SelectOpName(p->op));
3237 ** Code an output subroutine for a coroutine implementation of a
3238 ** SELECT statement.
3240 ** The data to be output is contained in pIn->iSdst. There are
3241 ** pIn->nSdst columns to be output. pDest is where the output should
3242 ** be sent.
3244 ** regReturn is the number of the register holding the subroutine
3245 ** return address.
3247 ** If regPrev>0 then it is the first register in a vector that
3248 ** records the previous output. mem[regPrev] is a flag that is false
3249 ** if there has been no previous output. If regPrev>0 then code is
3250 ** generated to suppress duplicates. pKeyInfo is used for comparing
3251 ** keys.
3253 ** If the LIMIT found in p->iLimit is reached, jump immediately to
3254 ** iBreak.
3256 static int generateOutputSubroutine(
3257 Parse *pParse, /* Parsing context */
3258 Select *p, /* The SELECT statement */
3259 SelectDest *pIn, /* Coroutine supplying data */
3260 SelectDest *pDest, /* Where to send the data */
3261 int regReturn, /* The return address register */
3262 int regPrev, /* Previous result register. No uniqueness if 0 */
3263 KeyInfo *pKeyInfo, /* For comparing with previous entry */
3264 int iBreak /* Jump here if we hit the LIMIT */
3266 Vdbe *v = pParse->pVdbe;
3267 int iContinue;
3268 int addr;
3270 addr = sqlite3VdbeCurrentAddr(v);
3271 iContinue = sqlite3VdbeMakeLabel(pParse);
3273 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
3275 if( regPrev ){
3276 int addr1, addr2;
3277 addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
3278 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
3279 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
3280 sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
3281 sqlite3VdbeJumpHere(v, addr1);
3282 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
3283 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
3285 if( pParse->db->mallocFailed ) return 0;
3287 /* Suppress the first OFFSET entries if there is an OFFSET clause
3289 codeOffset(v, p->iOffset, iContinue);
3291 assert( pDest->eDest!=SRT_Exists );
3292 assert( pDest->eDest!=SRT_Table );
3293 switch( pDest->eDest ){
3294 /* Store the result as data using a unique key.
3296 case SRT_EphemTab: {
3297 int r1 = sqlite3GetTempReg(pParse);
3298 int r2 = sqlite3GetTempReg(pParse);
3299 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
3300 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
3301 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
3302 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3303 sqlite3ReleaseTempReg(pParse, r2);
3304 sqlite3ReleaseTempReg(pParse, r1);
3305 break;
3308 #ifndef SQLITE_OMIT_SUBQUERY
3309 /* If we are creating a set for an "expr IN (SELECT ...)".
3311 case SRT_Set: {
3312 int r1;
3313 testcase( pIn->nSdst>1 );
3314 r1 = sqlite3GetTempReg(pParse);
3315 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
3316 r1, pDest->zAffSdst, pIn->nSdst);
3317 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
3318 pIn->iSdst, pIn->nSdst);
3319 sqlite3ReleaseTempReg(pParse, r1);
3320 break;
3323 /* If this is a scalar select that is part of an expression, then
3324 ** store the results in the appropriate memory cell and break out
3325 ** of the scan loop. Note that the select might return multiple columns
3326 ** if it is the RHS of a row-value IN operator.
3328 case SRT_Mem: {
3329 testcase( pIn->nSdst>1 );
3330 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
3331 /* The LIMIT clause will jump out of the loop for us */
3332 break;
3334 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
3336 /* The results are stored in a sequence of registers
3337 ** starting at pDest->iSdst. Then the co-routine yields.
3339 case SRT_Coroutine: {
3340 if( pDest->iSdst==0 ){
3341 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
3342 pDest->nSdst = pIn->nSdst;
3344 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
3345 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
3346 break;
3349 /* If none of the above, then the result destination must be
3350 ** SRT_Output. This routine is never called with any other
3351 ** destination other than the ones handled above or SRT_Output.
3353 ** For SRT_Output, results are stored in a sequence of registers.
3354 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
3355 ** return the next row of result.
3357 default: {
3358 assert( pDest->eDest==SRT_Output );
3359 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
3360 break;
3364 /* Jump to the end of the loop if the LIMIT is reached.
3366 if( p->iLimit ){
3367 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
3370 /* Generate the subroutine return
3372 sqlite3VdbeResolveLabel(v, iContinue);
3373 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
3375 return addr;
3379 ** Alternative compound select code generator for cases when there
3380 ** is an ORDER BY clause.
3382 ** We assume a query of the following form:
3384 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
3386 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
3387 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
3388 ** co-routines. Then run the co-routines in parallel and merge the results
3389 ** into the output. In addition to the two coroutines (called selectA and
3390 ** selectB) there are 7 subroutines:
3392 ** outA: Move the output of the selectA coroutine into the output
3393 ** of the compound query.
3395 ** outB: Move the output of the selectB coroutine into the output
3396 ** of the compound query. (Only generated for UNION and
3397 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
3398 ** appears only in B.)
3400 ** AltB: Called when there is data from both coroutines and A<B.
3402 ** AeqB: Called when there is data from both coroutines and A==B.
3404 ** AgtB: Called when there is data from both coroutines and A>B.
3406 ** EofA: Called when data is exhausted from selectA.
3408 ** EofB: Called when data is exhausted from selectB.
3410 ** The implementation of the latter five subroutines depend on which
3411 ** <operator> is used:
3414 ** UNION ALL UNION EXCEPT INTERSECT
3415 ** ------------- ----------------- -------------- -----------------
3416 ** AltB: outA, nextA outA, nextA outA, nextA nextA
3418 ** AeqB: outA, nextA nextA nextA outA, nextA
3420 ** AgtB: outB, nextB outB, nextB nextB nextB
3422 ** EofA: outB, nextB outB, nextB halt halt
3424 ** EofB: outA, nextA outA, nextA outA, nextA halt
3426 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
3427 ** causes an immediate jump to EofA and an EOF on B following nextB causes
3428 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
3429 ** following nextX causes a jump to the end of the select processing.
3431 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
3432 ** within the output subroutine. The regPrev register set holds the previously
3433 ** output value. A comparison is made against this value and the output
3434 ** is skipped if the next results would be the same as the previous.
3436 ** The implementation plan is to implement the two coroutines and seven
3437 ** subroutines first, then put the control logic at the bottom. Like this:
3439 ** goto Init
3440 ** coA: coroutine for left query (A)
3441 ** coB: coroutine for right query (B)
3442 ** outA: output one row of A
3443 ** outB: output one row of B (UNION and UNION ALL only)
3444 ** EofA: ...
3445 ** EofB: ...
3446 ** AltB: ...
3447 ** AeqB: ...
3448 ** AgtB: ...
3449 ** Init: initialize coroutine registers
3450 ** yield coA
3451 ** if eof(A) goto EofA
3452 ** yield coB
3453 ** if eof(B) goto EofB
3454 ** Cmpr: Compare A, B
3455 ** Jump AltB, AeqB, AgtB
3456 ** End: ...
3458 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
3459 ** actually called using Gosub and they do not Return. EofA and EofB loop
3460 ** until all data is exhausted then jump to the "end" label. AltB, AeqB,
3461 ** and AgtB jump to either L2 or to one of EofA or EofB.
3463 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3464 static int multiSelectOrderBy(
3465 Parse *pParse, /* Parsing context */
3466 Select *p, /* The right-most of SELECTs to be coded */
3467 SelectDest *pDest /* What to do with query results */
3469 int i, j; /* Loop counters */
3470 Select *pPrior; /* Another SELECT immediately to our left */
3471 Select *pSplit; /* Left-most SELECT in the right-hand group */
3472 int nSelect; /* Number of SELECT statements in the compound */
3473 Vdbe *v; /* Generate code to this VDBE */
3474 SelectDest destA; /* Destination for coroutine A */
3475 SelectDest destB; /* Destination for coroutine B */
3476 int regAddrA; /* Address register for select-A coroutine */
3477 int regAddrB; /* Address register for select-B coroutine */
3478 int addrSelectA; /* Address of the select-A coroutine */
3479 int addrSelectB; /* Address of the select-B coroutine */
3480 int regOutA; /* Address register for the output-A subroutine */
3481 int regOutB; /* Address register for the output-B subroutine */
3482 int addrOutA; /* Address of the output-A subroutine */
3483 int addrOutB = 0; /* Address of the output-B subroutine */
3484 int addrEofA; /* Address of the select-A-exhausted subroutine */
3485 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
3486 int addrEofB; /* Address of the select-B-exhausted subroutine */
3487 int addrAltB; /* Address of the A<B subroutine */
3488 int addrAeqB; /* Address of the A==B subroutine */
3489 int addrAgtB; /* Address of the A>B subroutine */
3490 int regLimitA; /* Limit register for select-A */
3491 int regLimitB; /* Limit register for select-A */
3492 int regPrev; /* A range of registers to hold previous output */
3493 int savedLimit; /* Saved value of p->iLimit */
3494 int savedOffset; /* Saved value of p->iOffset */
3495 int labelCmpr; /* Label for the start of the merge algorithm */
3496 int labelEnd; /* Label for the end of the overall SELECT stmt */
3497 int addr1; /* Jump instructions that get retargeted */
3498 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
3499 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
3500 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
3501 sqlite3 *db; /* Database connection */
3502 ExprList *pOrderBy; /* The ORDER BY clause */
3503 int nOrderBy; /* Number of terms in the ORDER BY clause */
3504 u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */
3506 assert( p->pOrderBy!=0 );
3507 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
3508 db = pParse->db;
3509 v = pParse->pVdbe;
3510 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
3511 labelEnd = sqlite3VdbeMakeLabel(pParse);
3512 labelCmpr = sqlite3VdbeMakeLabel(pParse);
3515 /* Patch up the ORDER BY clause
3517 op = p->op;
3518 assert( p->pPrior->pOrderBy==0 );
3519 pOrderBy = p->pOrderBy;
3520 assert( pOrderBy );
3521 nOrderBy = pOrderBy->nExpr;
3523 /* For operators other than UNION ALL we have to make sure that
3524 ** the ORDER BY clause covers every term of the result set. Add
3525 ** terms to the ORDER BY clause as necessary.
3527 if( op!=TK_ALL ){
3528 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
3529 struct ExprList_item *pItem;
3530 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
3531 assert( pItem!=0 );
3532 assert( pItem->u.x.iOrderByCol>0 );
3533 if( pItem->u.x.iOrderByCol==i ) break;
3535 if( j==nOrderBy ){
3536 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
3537 if( pNew==0 ) return SQLITE_NOMEM_BKPT;
3538 pNew->flags |= EP_IntValue;
3539 pNew->u.iValue = i;
3540 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
3541 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
3546 /* Compute the comparison permutation and keyinfo that is used with
3547 ** the permutation used to determine if the next
3548 ** row of results comes from selectA or selectB. Also add explicit
3549 ** collations to the ORDER BY clause terms so that when the subqueries
3550 ** to the right and the left are evaluated, they use the correct
3551 ** collation.
3553 aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
3554 if( aPermute ){
3555 struct ExprList_item *pItem;
3556 aPermute[0] = nOrderBy;
3557 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
3558 assert( pItem!=0 );
3559 assert( pItem->u.x.iOrderByCol>0 );
3560 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
3561 aPermute[i] = pItem->u.x.iOrderByCol - 1;
3563 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
3564 }else{
3565 pKeyMerge = 0;
3568 /* Allocate a range of temporary registers and the KeyInfo needed
3569 ** for the logic that removes duplicate result rows when the
3570 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
3572 if( op==TK_ALL ){
3573 regPrev = 0;
3574 }else{
3575 int nExpr = p->pEList->nExpr;
3576 assert( nOrderBy>=nExpr || db->mallocFailed );
3577 regPrev = pParse->nMem+1;
3578 pParse->nMem += nExpr+1;
3579 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
3580 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
3581 if( pKeyDup ){
3582 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
3583 for(i=0; i<nExpr; i++){
3584 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
3585 pKeyDup->aSortFlags[i] = 0;
3590 /* Separate the left and the right query from one another
3592 nSelect = 1;
3593 if( (op==TK_ALL || op==TK_UNION)
3594 && OptimizationEnabled(db, SQLITE_BalancedMerge)
3596 for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
3597 nSelect++;
3598 assert( pSplit->pPrior->pNext==pSplit );
3601 if( nSelect<=3 ){
3602 pSplit = p;
3603 }else{
3604 pSplit = p;
3605 for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
3607 pPrior = pSplit->pPrior;
3608 assert( pPrior!=0 );
3609 pSplit->pPrior = 0;
3610 pPrior->pNext = 0;
3611 assert( p->pOrderBy == pOrderBy );
3612 assert( pOrderBy!=0 || db->mallocFailed );
3613 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
3614 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
3615 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
3617 /* Compute the limit registers */
3618 computeLimitRegisters(pParse, p, labelEnd);
3619 if( p->iLimit && op==TK_ALL ){
3620 regLimitA = ++pParse->nMem;
3621 regLimitB = ++pParse->nMem;
3622 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
3623 regLimitA);
3624 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
3625 }else{
3626 regLimitA = regLimitB = 0;
3628 sqlite3ExprDelete(db, p->pLimit);
3629 p->pLimit = 0;
3631 regAddrA = ++pParse->nMem;
3632 regAddrB = ++pParse->nMem;
3633 regOutA = ++pParse->nMem;
3634 regOutB = ++pParse->nMem;
3635 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
3636 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
3638 ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
3640 /* Generate a coroutine to evaluate the SELECT statement to the
3641 ** left of the compound operator - the "A" select.
3643 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
3644 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
3645 VdbeComment((v, "left SELECT"));
3646 pPrior->iLimit = regLimitA;
3647 ExplainQueryPlan((pParse, 1, "LEFT"));
3648 sqlite3Select(pParse, pPrior, &destA);
3649 sqlite3VdbeEndCoroutine(v, regAddrA);
3650 sqlite3VdbeJumpHere(v, addr1);
3652 /* Generate a coroutine to evaluate the SELECT statement on
3653 ** the right - the "B" select
3655 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
3656 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
3657 VdbeComment((v, "right SELECT"));
3658 savedLimit = p->iLimit;
3659 savedOffset = p->iOffset;
3660 p->iLimit = regLimitB;
3661 p->iOffset = 0;
3662 ExplainQueryPlan((pParse, 1, "RIGHT"));
3663 sqlite3Select(pParse, p, &destB);
3664 p->iLimit = savedLimit;
3665 p->iOffset = savedOffset;
3666 sqlite3VdbeEndCoroutine(v, regAddrB);
3668 /* Generate a subroutine that outputs the current row of the A
3669 ** select as the next output row of the compound select.
3671 VdbeNoopComment((v, "Output routine for A"));
3672 addrOutA = generateOutputSubroutine(pParse,
3673 p, &destA, pDest, regOutA,
3674 regPrev, pKeyDup, labelEnd);
3676 /* Generate a subroutine that outputs the current row of the B
3677 ** select as the next output row of the compound select.
3679 if( op==TK_ALL || op==TK_UNION ){
3680 VdbeNoopComment((v, "Output routine for B"));
3681 addrOutB = generateOutputSubroutine(pParse,
3682 p, &destB, pDest, regOutB,
3683 regPrev, pKeyDup, labelEnd);
3685 sqlite3KeyInfoUnref(pKeyDup);
3687 /* Generate a subroutine to run when the results from select A
3688 ** are exhausted and only data in select B remains.
3690 if( op==TK_EXCEPT || op==TK_INTERSECT ){
3691 addrEofA_noB = addrEofA = labelEnd;
3692 }else{
3693 VdbeNoopComment((v, "eof-A subroutine"));
3694 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3695 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3696 VdbeCoverage(v);
3697 sqlite3VdbeGoto(v, addrEofA);
3698 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3701 /* Generate a subroutine to run when the results from select B
3702 ** are exhausted and only data in select A remains.
3704 if( op==TK_INTERSECT ){
3705 addrEofB = addrEofA;
3706 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3707 }else{
3708 VdbeNoopComment((v, "eof-B subroutine"));
3709 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3710 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3711 sqlite3VdbeGoto(v, addrEofB);
3714 /* Generate code to handle the case of A<B
3716 VdbeNoopComment((v, "A-lt-B subroutine"));
3717 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3718 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3719 sqlite3VdbeGoto(v, labelCmpr);
3721 /* Generate code to handle the case of A==B
3723 if( op==TK_ALL ){
3724 addrAeqB = addrAltB;
3725 }else if( op==TK_INTERSECT ){
3726 addrAeqB = addrAltB;
3727 addrAltB++;
3728 }else{
3729 VdbeNoopComment((v, "A-eq-B subroutine"));
3730 addrAeqB =
3731 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3732 sqlite3VdbeGoto(v, labelCmpr);
3735 /* Generate code to handle the case of A>B
3737 VdbeNoopComment((v, "A-gt-B subroutine"));
3738 addrAgtB = sqlite3VdbeCurrentAddr(v);
3739 if( op==TK_ALL || op==TK_UNION ){
3740 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3742 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3743 sqlite3VdbeGoto(v, labelCmpr);
3745 /* This code runs once to initialize everything.
3747 sqlite3VdbeJumpHere(v, addr1);
3748 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3749 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3751 /* Implement the main merge loop
3753 sqlite3VdbeResolveLabel(v, labelCmpr);
3754 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
3755 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
3756 (char*)pKeyMerge, P4_KEYINFO);
3757 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3758 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
3760 /* Jump to the this point in order to terminate the query.
3762 sqlite3VdbeResolveLabel(v, labelEnd);
3764 /* Make arrangements to free the 2nd and subsequent arms of the compound
3765 ** after the parse has finished */
3766 if( pSplit->pPrior ){
3767 sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSplit->pPrior);
3769 pSplit->pPrior = pPrior;
3770 pPrior->pNext = pSplit;
3771 sqlite3ExprListDelete(db, pPrior->pOrderBy);
3772 pPrior->pOrderBy = 0;
3774 /*** TBD: Insert subroutine calls to close cursors on incomplete
3775 **** subqueries ****/
3776 ExplainQueryPlanPop(pParse);
3777 return pParse->nErr!=0;
3779 #endif
3781 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3783 /* An instance of the SubstContext object describes an substitution edit
3784 ** to be performed on a parse tree.
3786 ** All references to columns in table iTable are to be replaced by corresponding
3787 ** expressions in pEList.
3789 ** ## About "isOuterJoin":
3791 ** The isOuterJoin column indicates that the replacement will occur into a
3792 ** position in the parent that NULL-able due to an OUTER JOIN. Either the
3793 ** target slot in the parent is the right operand of a LEFT JOIN, or one of
3794 ** the left operands of a RIGHT JOIN. In either case, we need to potentially
3795 ** bypass the substituted expression with OP_IfNullRow.
3797 ** Suppose the original expression is an integer constant. Even though the table
3798 ** has the nullRow flag set, because the expression is an integer constant,
3799 ** it will not be NULLed out. So instead, we insert an OP_IfNullRow opcode
3800 ** that checks to see if the nullRow flag is set on the table. If the nullRow
3801 ** flag is set, then the value in the register is set to NULL and the original
3802 ** expression is bypassed. If the nullRow flag is not set, then the original
3803 ** expression runs to populate the register.
3805 ** Example where this is needed:
3807 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
3808 ** CREATE TABLE t2(x INT UNIQUE);
3810 ** SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x;
3812 ** When the subquery on the right side of the LEFT JOIN is flattened, we
3813 ** have to add OP_IfNullRow in front of the OP_Integer that implements the
3814 ** "m" value of the subquery so that a NULL will be loaded instead of 59
3815 ** when processing a non-matched row of the left.
3817 typedef struct SubstContext {
3818 Parse *pParse; /* The parsing context */
3819 int iTable; /* Replace references to this table */
3820 int iNewTable; /* New table number */
3821 int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
3822 ExprList *pEList; /* Replacement expressions */
3823 ExprList *pCList; /* Collation sequences for replacement expr */
3824 } SubstContext;
3826 /* Forward Declarations */
3827 static void substExprList(SubstContext*, ExprList*);
3828 static void substSelect(SubstContext*, Select*, int);
3831 ** Scan through the expression pExpr. Replace every reference to
3832 ** a column in table number iTable with a copy of the iColumn-th
3833 ** entry in pEList. (But leave references to the ROWID column
3834 ** unchanged.)
3836 ** This routine is part of the flattening procedure. A subquery
3837 ** whose result set is defined by pEList appears as entry in the
3838 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3839 ** FORM clause entry is iTable. This routine makes the necessary
3840 ** changes to pExpr so that it refers directly to the source table
3841 ** of the subquery rather the result set of the subquery.
3843 static Expr *substExpr(
3844 SubstContext *pSubst, /* Description of the substitution */
3845 Expr *pExpr /* Expr in which substitution occurs */
3847 if( pExpr==0 ) return 0;
3848 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)
3849 && pExpr->w.iJoin==pSubst->iTable
3851 testcase( ExprHasProperty(pExpr, EP_InnerON) );
3852 pExpr->w.iJoin = pSubst->iNewTable;
3854 if( pExpr->op==TK_COLUMN
3855 && pExpr->iTable==pSubst->iTable
3856 && !ExprHasProperty(pExpr, EP_FixedCol)
3858 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
3859 if( pExpr->iColumn<0 ){
3860 pExpr->op = TK_NULL;
3861 }else
3862 #endif
3864 Expr *pNew;
3865 int iColumn;
3866 Expr *pCopy;
3867 Expr ifNullRow;
3868 iColumn = pExpr->iColumn;
3869 assert( iColumn>=0 );
3870 assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
3871 assert( pExpr->pRight==0 );
3872 pCopy = pSubst->pEList->a[iColumn].pExpr;
3873 if( sqlite3ExprIsVector(pCopy) ){
3874 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
3875 }else{
3876 sqlite3 *db = pSubst->pParse->db;
3877 if( pSubst->isOuterJoin
3878 && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
3880 memset(&ifNullRow, 0, sizeof(ifNullRow));
3881 ifNullRow.op = TK_IF_NULL_ROW;
3882 ifNullRow.pLeft = pCopy;
3883 ifNullRow.iTable = pSubst->iNewTable;
3884 ifNullRow.iColumn = -99;
3885 ifNullRow.flags = EP_IfNullRow;
3886 pCopy = &ifNullRow;
3888 testcase( ExprHasProperty(pCopy, EP_Subquery) );
3889 pNew = sqlite3ExprDup(db, pCopy, 0);
3890 if( db->mallocFailed ){
3891 sqlite3ExprDelete(db, pNew);
3892 return pExpr;
3894 if( pSubst->isOuterJoin ){
3895 ExprSetProperty(pNew, EP_CanBeNull);
3897 if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){
3898 sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
3899 pExpr->flags & (EP_OuterON|EP_InnerON));
3901 sqlite3ExprDelete(db, pExpr);
3902 pExpr = pNew;
3903 if( pExpr->op==TK_TRUEFALSE ){
3904 pExpr->u.iValue = sqlite3ExprTruthValue(pExpr);
3905 pExpr->op = TK_INTEGER;
3906 ExprSetProperty(pExpr, EP_IntValue);
3909 /* Ensure that the expression now has an implicit collation sequence,
3910 ** just as it did when it was a column of a view or sub-query. */
3912 CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
3913 CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
3914 pSubst->pCList->a[iColumn].pExpr
3916 if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){
3917 pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
3918 (pColl ? pColl->zName : "BINARY")
3922 ExprClearProperty(pExpr, EP_Collate);
3925 }else{
3926 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
3927 pExpr->iTable = pSubst->iNewTable;
3929 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
3930 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
3931 if( ExprUseXSelect(pExpr) ){
3932 substSelect(pSubst, pExpr->x.pSelect, 1);
3933 }else{
3934 substExprList(pSubst, pExpr->x.pList);
3936 #ifndef SQLITE_OMIT_WINDOWFUNC
3937 if( ExprHasProperty(pExpr, EP_WinFunc) ){
3938 Window *pWin = pExpr->y.pWin;
3939 pWin->pFilter = substExpr(pSubst, pWin->pFilter);
3940 substExprList(pSubst, pWin->pPartition);
3941 substExprList(pSubst, pWin->pOrderBy);
3943 #endif
3945 return pExpr;
3947 static void substExprList(
3948 SubstContext *pSubst, /* Description of the substitution */
3949 ExprList *pList /* List to scan and in which to make substitutes */
3951 int i;
3952 if( pList==0 ) return;
3953 for(i=0; i<pList->nExpr; i++){
3954 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
3957 static void substSelect(
3958 SubstContext *pSubst, /* Description of the substitution */
3959 Select *p, /* SELECT statement in which to make substitutions */
3960 int doPrior /* Do substitutes on p->pPrior too */
3962 SrcList *pSrc;
3963 SrcItem *pItem;
3964 int i;
3965 if( !p ) return;
3967 substExprList(pSubst, p->pEList);
3968 substExprList(pSubst, p->pGroupBy);
3969 substExprList(pSubst, p->pOrderBy);
3970 p->pHaving = substExpr(pSubst, p->pHaving);
3971 p->pWhere = substExpr(pSubst, p->pWhere);
3972 pSrc = p->pSrc;
3973 assert( pSrc!=0 );
3974 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
3975 substSelect(pSubst, pItem->pSelect, 1);
3976 if( pItem->fg.isTabFunc ){
3977 substExprList(pSubst, pItem->u1.pFuncArg);
3980 }while( doPrior && (p = p->pPrior)!=0 );
3982 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3984 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3986 ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
3987 ** clause of that SELECT.
3989 ** This routine scans the entire SELECT statement and recomputes the
3990 ** pSrcItem->colUsed mask.
3992 static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
3993 SrcItem *pItem;
3994 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
3995 pItem = pWalker->u.pSrcItem;
3996 if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
3997 if( pExpr->iColumn<0 ) return WRC_Continue;
3998 pItem->colUsed |= sqlite3ExprColUsed(pExpr);
3999 return WRC_Continue;
4001 static void recomputeColumnsUsed(
4002 Select *pSelect, /* The complete SELECT statement */
4003 SrcItem *pSrcItem /* Which FROM clause item to recompute */
4005 Walker w;
4006 if( NEVER(pSrcItem->pTab==0) ) return;
4007 memset(&w, 0, sizeof(w));
4008 w.xExprCallback = recomputeColumnsUsedExpr;
4009 w.xSelectCallback = sqlite3SelectWalkNoop;
4010 w.u.pSrcItem = pSrcItem;
4011 pSrcItem->colUsed = 0;
4012 sqlite3WalkSelect(&w, pSelect);
4014 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4016 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4018 ** Assign new cursor numbers to each of the items in pSrc. For each
4019 ** new cursor number assigned, set an entry in the aCsrMap[] array
4020 ** to map the old cursor number to the new:
4022 ** aCsrMap[iOld+1] = iNew;
4024 ** The array is guaranteed by the caller to be large enough for all
4025 ** existing cursor numbers in pSrc. aCsrMap[0] is the array size.
4027 ** If pSrc contains any sub-selects, call this routine recursively
4028 ** on the FROM clause of each such sub-select, with iExcept set to -1.
4030 static void srclistRenumberCursors(
4031 Parse *pParse, /* Parse context */
4032 int *aCsrMap, /* Array to store cursor mappings in */
4033 SrcList *pSrc, /* FROM clause to renumber */
4034 int iExcept /* FROM clause item to skip */
4036 int i;
4037 SrcItem *pItem;
4038 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
4039 if( i!=iExcept ){
4040 Select *p;
4041 assert( pItem->iCursor < aCsrMap[0] );
4042 if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
4043 aCsrMap[pItem->iCursor+1] = pParse->nTab++;
4045 pItem->iCursor = aCsrMap[pItem->iCursor+1];
4046 for(p=pItem->pSelect; p; p=p->pPrior){
4047 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
4054 ** *piCursor is a cursor number. Change it if it needs to be mapped.
4056 static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
4057 int *aCsrMap = pWalker->u.aiCol;
4058 int iCsr = *piCursor;
4059 if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
4060 *piCursor = aCsrMap[iCsr+1];
4065 ** Expression walker callback used by renumberCursors() to update
4066 ** Expr objects to match newly assigned cursor numbers.
4068 static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
4069 int op = pExpr->op;
4070 if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
4071 renumberCursorDoMapping(pWalker, &pExpr->iTable);
4073 if( ExprHasProperty(pExpr, EP_OuterON) ){
4074 renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
4076 return WRC_Continue;
4080 ** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
4081 ** of the SELECT statement passed as the second argument, and to each
4082 ** cursor in the FROM clause of any FROM clause sub-selects, recursively.
4083 ** Except, do not assign a new cursor number to the iExcept'th element in
4084 ** the FROM clause of (*p). Update all expressions and other references
4085 ** to refer to the new cursor numbers.
4087 ** Argument aCsrMap is an array that may be used for temporary working
4088 ** space. Two guarantees are made by the caller:
4090 ** * the array is larger than the largest cursor number used within the
4091 ** select statement passed as an argument, and
4093 ** * the array entries for all cursor numbers that do *not* appear in
4094 ** FROM clauses of the select statement as described above are
4095 ** initialized to zero.
4097 static void renumberCursors(
4098 Parse *pParse, /* Parse context */
4099 Select *p, /* Select to renumber cursors within */
4100 int iExcept, /* FROM clause item to skip */
4101 int *aCsrMap /* Working space */
4103 Walker w;
4104 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
4105 memset(&w, 0, sizeof(w));
4106 w.u.aiCol = aCsrMap;
4107 w.xExprCallback = renumberCursorsCb;
4108 w.xSelectCallback = sqlite3SelectWalkNoop;
4109 sqlite3WalkSelect(&w, p);
4111 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4114 ** If pSel is not part of a compound SELECT, return a pointer to its
4115 ** expression list. Otherwise, return a pointer to the expression list
4116 ** of the leftmost SELECT in the compound.
4118 static ExprList *findLeftmostExprlist(Select *pSel){
4119 while( pSel->pPrior ){
4120 pSel = pSel->pPrior;
4122 return pSel->pEList;
4126 ** Return true if any of the result-set columns in the compound query
4127 ** have incompatible affinities on one or more arms of the compound.
4129 static int compoundHasDifferentAffinities(Select *p){
4130 int ii;
4131 ExprList *pList;
4132 assert( p!=0 );
4133 assert( p->pEList!=0 );
4134 assert( p->pPrior!=0 );
4135 pList = p->pEList;
4136 for(ii=0; ii<pList->nExpr; ii++){
4137 char aff;
4138 Select *pSub1;
4139 assert( pList->a[ii].pExpr!=0 );
4140 aff = sqlite3ExprAffinity(pList->a[ii].pExpr);
4141 for(pSub1=p->pPrior; pSub1; pSub1=pSub1->pPrior){
4142 assert( pSub1->pEList!=0 );
4143 assert( pSub1->pEList->nExpr>ii );
4144 assert( pSub1->pEList->a[ii].pExpr!=0 );
4145 if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
4146 return 1;
4150 return 0;
4153 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4155 ** This routine attempts to flatten subqueries as a performance optimization.
4156 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
4158 ** To understand the concept of flattening, consider the following
4159 ** query:
4161 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
4163 ** The default way of implementing this query is to execute the
4164 ** subquery first and store the results in a temporary table, then
4165 ** run the outer query on that temporary table. This requires two
4166 ** passes over the data. Furthermore, because the temporary table
4167 ** has no indices, the WHERE clause on the outer query cannot be
4168 ** optimized.
4170 ** This routine attempts to rewrite queries such as the above into
4171 ** a single flat select, like this:
4173 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
4175 ** The code generated for this simplification gives the same result
4176 ** but only has to scan the data once. And because indices might
4177 ** exist on the table t1, a complete scan of the data might be
4178 ** avoided.
4180 ** Flattening is subject to the following constraints:
4182 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4183 ** The subquery and the outer query cannot both be aggregates.
4185 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4186 ** (2) If the subquery is an aggregate then
4187 ** (2a) the outer query must not be a join and
4188 ** (2b) the outer query must not use subqueries
4189 ** other than the one FROM-clause subquery that is a candidate
4190 ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
4191 ** from 2015-02-09.)
4193 ** (3) If the subquery is the right operand of a LEFT JOIN then
4194 ** (3a) the subquery may not be a join and
4195 ** (3b) the FROM clause of the subquery may not contain a virtual
4196 ** table and
4197 ** (**) Was: "The outer query may not have a GROUP BY." This case
4198 ** is now managed correctly
4199 ** (3d) the outer query may not be DISTINCT.
4200 ** See also (26) for restrictions on RIGHT JOIN.
4202 ** (4) The subquery can not be DISTINCT.
4204 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
4205 ** sub-queries that were excluded from this optimization. Restriction
4206 ** (4) has since been expanded to exclude all DISTINCT subqueries.
4208 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4209 ** If the subquery is aggregate, the outer query may not be DISTINCT.
4211 ** (7) The subquery must have a FROM clause. TODO: For subqueries without
4212 ** A FROM clause, consider adding a FROM clause with the special
4213 ** table sqlite_once that consists of a single row containing a
4214 ** single NULL.
4216 ** (8) If the subquery uses LIMIT then the outer query may not be a join.
4218 ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
4220 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
4221 ** accidentally carried the comment forward until 2014-09-15. Original
4222 ** constraint: "If the subquery is aggregate then the outer query
4223 ** may not use LIMIT."
4225 ** (11) The subquery and the outer query may not both have ORDER BY clauses.
4227 ** (**) Not implemented. Subsumed into restriction (3). Was previously
4228 ** a separate restriction deriving from ticket #350.
4230 ** (13) The subquery and outer query may not both use LIMIT.
4232 ** (14) The subquery may not use OFFSET.
4234 ** (15) If the outer query is part of a compound select, then the
4235 ** subquery may not use LIMIT.
4236 ** (See ticket #2339 and ticket [02a8e81d44]).
4238 ** (16) If the outer query is aggregate, then the subquery may not
4239 ** use ORDER BY. (Ticket #2942) This used to not matter
4240 ** until we introduced the group_concat() function.
4242 ** (17) If the subquery is a compound select, then
4243 ** (17a) all compound operators must be a UNION ALL, and
4244 ** (17b) no terms within the subquery compound may be aggregate
4245 ** or DISTINCT, and
4246 ** (17c) every term within the subquery compound must have a FROM clause
4247 ** (17d) the outer query may not be
4248 ** (17d1) aggregate, or
4249 ** (17d2) DISTINCT
4250 ** (17e) the subquery may not contain window functions, and
4251 ** (17f) the subquery must not be the RHS of a LEFT JOIN.
4252 ** (17g) either the subquery is the first element of the outer
4253 ** query or there are no RIGHT or FULL JOINs in any arm
4254 ** of the subquery. (This is a duplicate of condition (27b).)
4255 ** (17h) The corresponding result set expressions in all arms of the
4256 ** compound must have the same affinity.
4258 ** The parent and sub-query may contain WHERE clauses. Subject to
4259 ** rules (11), (13) and (14), they may also contain ORDER BY,
4260 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
4261 ** operator other than UNION ALL because all the other compound
4262 ** operators have an implied DISTINCT which is disallowed by
4263 ** restriction (4).
4265 ** Also, each component of the sub-query must return the same number
4266 ** of result columns. This is actually a requirement for any compound
4267 ** SELECT statement, but all the code here does is make sure that no
4268 ** such (illegal) sub-query is flattened. The caller will detect the
4269 ** syntax error and return a detailed message.
4271 ** (18) If the sub-query is a compound select, then all terms of the
4272 ** ORDER BY clause of the parent must be copies of a term returned
4273 ** by the parent query.
4275 ** (19) If the subquery uses LIMIT then the outer query may not
4276 ** have a WHERE clause.
4278 ** (20) If the sub-query is a compound select, then it must not use
4279 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
4280 ** somewhat by saying that the terms of the ORDER BY clause must
4281 ** appear as unmodified result columns in the outer query. But we
4282 ** have other optimizations in mind to deal with that case.
4284 ** (21) If the subquery uses LIMIT then the outer query may not be
4285 ** DISTINCT. (See ticket [752e1646fc]).
4287 ** (22) The subquery may not be a recursive CTE.
4289 ** (23) If the outer query is a recursive CTE, then the sub-query may not be
4290 ** a compound query. This restriction is because transforming the
4291 ** parent to a compound query confuses the code that handles
4292 ** recursive queries in multiSelect().
4294 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4295 ** The subquery may not be an aggregate that uses the built-in min() or
4296 ** or max() functions. (Without this restriction, a query like:
4297 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
4298 ** return the value X for which Y was maximal.)
4300 ** (25) If either the subquery or the parent query contains a window
4301 ** function in the select list or ORDER BY clause, flattening
4302 ** is not attempted.
4304 ** (26) The subquery may not be the right operand of a RIGHT JOIN.
4305 ** See also (3) for restrictions on LEFT JOIN.
4307 ** (27) The subquery may not contain a FULL or RIGHT JOIN unless it
4308 ** is the first element of the parent query. Two subcases:
4309 ** (27a) the subquery is not a compound query.
4310 ** (27b) the subquery is a compound query and the RIGHT JOIN occurs
4311 ** in any arm of the compound query. (See also (17g).)
4313 ** (28) The subquery is not a MATERIALIZED CTE. (This is handled
4314 ** in the caller before ever reaching this routine.)
4317 ** In this routine, the "p" parameter is a pointer to the outer query.
4318 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
4319 ** uses aggregates.
4321 ** If flattening is not attempted, this routine is a no-op and returns 0.
4322 ** If flattening is attempted this routine returns 1.
4324 ** All of the expression analysis must occur on both the outer query and
4325 ** the subquery before this routine runs.
4327 static int flattenSubquery(
4328 Parse *pParse, /* Parsing context */
4329 Select *p, /* The parent or outer SELECT statement */
4330 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
4331 int isAgg /* True if outer SELECT uses aggregate functions */
4333 const char *zSavedAuthContext = pParse->zAuthContext;
4334 Select *pParent; /* Current UNION ALL term of the other query */
4335 Select *pSub; /* The inner query or "subquery" */
4336 Select *pSub1; /* Pointer to the rightmost select in sub-query */
4337 SrcList *pSrc; /* The FROM clause of the outer query */
4338 SrcList *pSubSrc; /* The FROM clause of the subquery */
4339 int iParent; /* VDBE cursor number of the pSub result set temp table */
4340 int iNewParent = -1;/* Replacement table for iParent */
4341 int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
4342 int i; /* Loop counter */
4343 Expr *pWhere; /* The WHERE clause */
4344 SrcItem *pSubitem; /* The subquery */
4345 sqlite3 *db = pParse->db;
4346 Walker w; /* Walker to persist agginfo data */
4347 int *aCsrMap = 0;
4349 /* Check to see if flattening is permitted. Return 0 if not.
4351 assert( p!=0 );
4352 assert( p->pPrior==0 );
4353 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
4354 pSrc = p->pSrc;
4355 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
4356 pSubitem = &pSrc->a[iFrom];
4357 iParent = pSubitem->iCursor;
4358 pSub = pSubitem->pSelect;
4359 assert( pSub!=0 );
4361 #ifndef SQLITE_OMIT_WINDOWFUNC
4362 if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
4363 #endif
4365 pSubSrc = pSub->pSrc;
4366 assert( pSubSrc );
4367 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
4368 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
4369 ** because they could be computed at compile-time. But when LIMIT and OFFSET
4370 ** became arbitrary expressions, we were forced to add restrictions (13)
4371 ** and (14). */
4372 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
4373 if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
4374 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
4375 return 0; /* Restriction (15) */
4377 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
4378 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
4379 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
4380 return 0; /* Restrictions (8)(9) */
4382 if( p->pOrderBy && pSub->pOrderBy ){
4383 return 0; /* Restriction (11) */
4385 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
4386 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
4387 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
4388 return 0; /* Restriction (21) */
4390 if( pSub->selFlags & (SF_Recursive) ){
4391 return 0; /* Restrictions (22) */
4395 ** If the subquery is the right operand of a LEFT JOIN, then the
4396 ** subquery may not be a join itself (3a). Example of why this is not
4397 ** allowed:
4399 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
4401 ** If we flatten the above, we would get
4403 ** (t1 LEFT OUTER JOIN t2) JOIN t3
4405 ** which is not at all the same thing.
4407 ** See also tickets #306, #350, and #3300.
4409 if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
4410 if( pSubSrc->nSrc>1 /* (3a) */
4411 || IsVirtual(pSubSrc->a[0].pTab) /* (3b) */
4412 || (p->selFlags & SF_Distinct)!=0 /* (3d) */
4413 || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */
4415 return 0;
4417 isOuterJoin = 1;
4420 assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */
4421 if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4422 return 0; /* Restriction (27a) */
4425 /* Condition (28) is blocked by the caller */
4426 assert( !pSubitem->fg.isCte || pSubitem->u2.pCteUse->eM10d!=M10d_Yes );
4428 /* Restriction (17): If the sub-query is a compound SELECT, then it must
4429 ** use only the UNION ALL operator. And none of the simple select queries
4430 ** that make up the compound SELECT are allowed to be aggregate or distinct
4431 ** queries.
4433 if( pSub->pPrior ){
4434 int ii;
4435 if( pSub->pOrderBy ){
4436 return 0; /* Restriction (20) */
4438 if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
4439 return 0; /* (17d1), (17d2), or (17f) */
4441 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
4442 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
4443 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
4444 assert( pSub->pSrc!=0 );
4445 assert( (pSub->selFlags & SF_Recursive)==0 );
4446 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
4447 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
4448 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
4449 || pSub1->pSrc->nSrc<1 /* (17c) */
4450 #ifndef SQLITE_OMIT_WINDOWFUNC
4451 || pSub1->pWin /* (17e) */
4452 #endif
4454 return 0;
4456 if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4457 /* Without this restriction, the JT_LTORJ flag would end up being
4458 ** omitted on left-hand tables of the right join that is being
4459 ** flattened. */
4460 return 0; /* Restrictions (17g), (27b) */
4462 testcase( pSub1->pSrc->nSrc>1 );
4465 /* Restriction (18). */
4466 if( p->pOrderBy ){
4467 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
4468 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
4472 /* Restriction (23) */
4473 if( (p->selFlags & SF_Recursive) ) return 0;
4475 /* Restriction (17h) */
4476 if( compoundHasDifferentAffinities(pSub) ) return 0;
4478 if( pSrc->nSrc>1 ){
4479 if( pParse->nSelect>500 ) return 0;
4480 if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
4481 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
4482 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
4486 /***** If we reach this point, flattening is permitted. *****/
4487 TREETRACE(0x4,pParse,p,("flatten %u.%p from term %d\n",
4488 pSub->selId, pSub, iFrom));
4490 /* Authorize the subquery */
4491 pParse->zAuthContext = pSubitem->zName;
4492 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
4493 testcase( i==SQLITE_DENY );
4494 pParse->zAuthContext = zSavedAuthContext;
4496 /* Delete the transient structures associated with the subquery */
4497 pSub1 = pSubitem->pSelect;
4498 sqlite3DbFree(db, pSubitem->zDatabase);
4499 sqlite3DbFree(db, pSubitem->zName);
4500 sqlite3DbFree(db, pSubitem->zAlias);
4501 pSubitem->zDatabase = 0;
4502 pSubitem->zName = 0;
4503 pSubitem->zAlias = 0;
4504 pSubitem->pSelect = 0;
4505 assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
4507 /* If the sub-query is a compound SELECT statement, then (by restrictions
4508 ** 17 and 18 above) it must be a UNION ALL and the parent query must
4509 ** be of the form:
4511 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
4513 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
4514 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
4515 ** OFFSET clauses and joins them to the left-hand-side of the original
4516 ** using UNION ALL operators. In this case N is the number of simple
4517 ** select statements in the compound sub-query.
4519 ** Example:
4521 ** SELECT a+1 FROM (
4522 ** SELECT x FROM tab
4523 ** UNION ALL
4524 ** SELECT y FROM tab
4525 ** UNION ALL
4526 ** SELECT abs(z*2) FROM tab2
4527 ** ) WHERE a!=5 ORDER BY 1
4529 ** Transformed into:
4531 ** SELECT x+1 FROM tab WHERE x+1!=5
4532 ** UNION ALL
4533 ** SELECT y+1 FROM tab WHERE y+1!=5
4534 ** UNION ALL
4535 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
4536 ** ORDER BY 1
4538 ** We call this the "compound-subquery flattening".
4540 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
4541 Select *pNew;
4542 ExprList *pOrderBy = p->pOrderBy;
4543 Expr *pLimit = p->pLimit;
4544 Select *pPrior = p->pPrior;
4545 Table *pItemTab = pSubitem->pTab;
4546 pSubitem->pTab = 0;
4547 p->pOrderBy = 0;
4548 p->pPrior = 0;
4549 p->pLimit = 0;
4550 pNew = sqlite3SelectDup(db, p, 0);
4551 p->pLimit = pLimit;
4552 p->pOrderBy = pOrderBy;
4553 p->op = TK_ALL;
4554 pSubitem->pTab = pItemTab;
4555 if( pNew==0 ){
4556 p->pPrior = pPrior;
4557 }else{
4558 pNew->selId = ++pParse->nSelect;
4559 if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
4560 renumberCursors(pParse, pNew, iFrom, aCsrMap);
4562 pNew->pPrior = pPrior;
4563 if( pPrior ) pPrior->pNext = pNew;
4564 pNew->pNext = p;
4565 p->pPrior = pNew;
4566 TREETRACE(0x4,pParse,p,("compound-subquery flattener"
4567 " creates %u as peer\n",pNew->selId));
4569 assert( pSubitem->pSelect==0 );
4571 sqlite3DbFree(db, aCsrMap);
4572 if( db->mallocFailed ){
4573 pSubitem->pSelect = pSub1;
4574 return 1;
4577 /* Defer deleting the Table object associated with the
4578 ** subquery until code generation is
4579 ** complete, since there may still exist Expr.pTab entries that
4580 ** refer to the subquery even after flattening. Ticket #3346.
4582 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
4584 if( ALWAYS(pSubitem->pTab!=0) ){
4585 Table *pTabToDel = pSubitem->pTab;
4586 if( pTabToDel->nTabRef==1 ){
4587 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4588 sqlite3ParserAddCleanup(pToplevel, sqlite3DeleteTableGeneric, pTabToDel);
4589 testcase( pToplevel->earlyCleanup );
4590 }else{
4591 pTabToDel->nTabRef--;
4593 pSubitem->pTab = 0;
4596 /* The following loop runs once for each term in a compound-subquery
4597 ** flattening (as described above). If we are doing a different kind
4598 ** of flattening - a flattening other than a compound-subquery flattening -
4599 ** then this loop only runs once.
4601 ** This loop moves all of the FROM elements of the subquery into the
4602 ** the FROM clause of the outer query. Before doing this, remember
4603 ** the cursor number for the original outer query FROM element in
4604 ** iParent. The iParent cursor will never be used. Subsequent code
4605 ** will scan expressions looking for iParent references and replace
4606 ** those references with expressions that resolve to the subquery FROM
4607 ** elements we are now copying in.
4609 pSub = pSub1;
4610 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
4611 int nSubSrc;
4612 u8 jointype = 0;
4613 u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
4614 assert( pSub!=0 );
4615 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
4616 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
4617 pSrc = pParent->pSrc; /* FROM clause of the outer query */
4619 if( pParent==p ){
4620 jointype = pSubitem->fg.jointype; /* First time through the loop */
4623 /* The subquery uses a single slot of the FROM clause of the outer
4624 ** query. If the subquery has more than one element in its FROM clause,
4625 ** then expand the outer query to make space for it to hold all elements
4626 ** of the subquery.
4628 ** Example:
4630 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
4632 ** The outer query has 3 slots in its FROM clause. One slot of the
4633 ** outer query (the middle slot) is used by the subquery. The next
4634 ** block of code will expand the outer query FROM clause to 4 slots.
4635 ** The middle slot is expanded to two slots in order to make space
4636 ** for the two elements in the FROM clause of the subquery.
4638 if( nSubSrc>1 ){
4639 pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
4640 if( pSrc==0 ) break;
4641 pParent->pSrc = pSrc;
4644 /* Transfer the FROM clause terms from the subquery into the
4645 ** outer query.
4647 for(i=0; i<nSubSrc; i++){
4648 SrcItem *pItem = &pSrc->a[i+iFrom];
4649 if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
4650 assert( pItem->fg.isTabFunc==0 );
4651 *pItem = pSubSrc->a[i];
4652 pItem->fg.jointype |= ltorj;
4653 iNewParent = pSubSrc->a[i].iCursor;
4654 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
4656 pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
4657 pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
4659 /* Now begin substituting subquery result set expressions for
4660 ** references to the iParent in the outer query.
4662 ** Example:
4664 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
4665 ** \ \_____________ subquery __________/ /
4666 ** \_____________________ outer query ______________________________/
4668 ** We look at every expression in the outer query and every place we see
4669 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
4671 if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
4672 /* At this point, any non-zero iOrderByCol values indicate that the
4673 ** ORDER BY column expression is identical to the iOrderByCol'th
4674 ** expression returned by SELECT statement pSub. Since these values
4675 ** do not necessarily correspond to columns in SELECT statement pParent,
4676 ** zero them before transferring the ORDER BY clause.
4678 ** Not doing this may cause an error if a subsequent call to this
4679 ** function attempts to flatten a compound sub-query into pParent
4680 ** (the only way this can happen is if the compound sub-query is
4681 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
4682 ExprList *pOrderBy = pSub->pOrderBy;
4683 for(i=0; i<pOrderBy->nExpr; i++){
4684 pOrderBy->a[i].u.x.iOrderByCol = 0;
4686 assert( pParent->pOrderBy==0 );
4687 pParent->pOrderBy = pOrderBy;
4688 pSub->pOrderBy = 0;
4690 pWhere = pSub->pWhere;
4691 pSub->pWhere = 0;
4692 if( isOuterJoin>0 ){
4693 sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON);
4695 if( pWhere ){
4696 if( pParent->pWhere ){
4697 pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
4698 }else{
4699 pParent->pWhere = pWhere;
4702 if( db->mallocFailed==0 ){
4703 SubstContext x;
4704 x.pParse = pParse;
4705 x.iTable = iParent;
4706 x.iNewTable = iNewParent;
4707 x.isOuterJoin = isOuterJoin;
4708 x.pEList = pSub->pEList;
4709 x.pCList = findLeftmostExprlist(pSub);
4710 substSelect(&x, pParent, 0);
4713 /* The flattened query is a compound if either the inner or the
4714 ** outer query is a compound. */
4715 pParent->selFlags |= pSub->selFlags & SF_Compound;
4716 assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
4719 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
4721 ** One is tempted to try to add a and b to combine the limits. But this
4722 ** does not work if either limit is negative.
4724 if( pSub->pLimit ){
4725 pParent->pLimit = pSub->pLimit;
4726 pSub->pLimit = 0;
4729 /* Recompute the SrcItem.colUsed masks for the flattened
4730 ** tables. */
4731 for(i=0; i<nSubSrc; i++){
4732 recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
4736 /* Finally, delete what is left of the subquery and return success.
4738 sqlite3AggInfoPersistWalkerInit(&w, pParse);
4739 sqlite3WalkSelect(&w,pSub1);
4740 sqlite3SelectDelete(db, pSub1);
4742 #if TREETRACE_ENABLED
4743 if( sqlite3TreeTrace & 0x4 ){
4744 TREETRACE(0x4,pParse,p,("After flattening:\n"));
4745 sqlite3TreeViewSelect(0, p, 0);
4747 #endif
4749 return 1;
4751 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4754 ** A structure to keep track of all of the column values that are fixed to
4755 ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
4757 typedef struct WhereConst WhereConst;
4758 struct WhereConst {
4759 Parse *pParse; /* Parsing context */
4760 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
4761 int nConst; /* Number for COLUMN=CONSTANT terms */
4762 int nChng; /* Number of times a constant is propagated */
4763 int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
4764 u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
4765 ** Either EP_OuterON or EP_InnerON|EP_OuterON */
4766 Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
4770 ** Add a new entry to the pConst object. Except, do not add duplicate
4771 ** pColumn entries. Also, do not add if doing so would not be appropriate.
4773 ** The caller guarantees the pColumn is a column and pValue is a constant.
4774 ** This routine has to do some additional checks before completing the
4775 ** insert.
4777 static void constInsert(
4778 WhereConst *pConst, /* The WhereConst into which we are inserting */
4779 Expr *pColumn, /* The COLUMN part of the constraint */
4780 Expr *pValue, /* The VALUE part of the constraint */
4781 Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
4783 int i;
4784 assert( pColumn->op==TK_COLUMN );
4785 assert( sqlite3ExprIsConstant(pConst->pParse, pValue) );
4787 if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
4788 if( sqlite3ExprAffinity(pValue)!=0 ) return;
4789 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
4790 return;
4793 /* 2018-10-25 ticket [cf5ed20f]
4794 ** Make sure the same pColumn is not inserted more than once */
4795 for(i=0; i<pConst->nConst; i++){
4796 const Expr *pE2 = pConst->apExpr[i*2];
4797 assert( pE2->op==TK_COLUMN );
4798 if( pE2->iTable==pColumn->iTable
4799 && pE2->iColumn==pColumn->iColumn
4801 return; /* Already present. Return without doing anything. */
4804 if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4805 pConst->bHasAffBlob = 1;
4808 pConst->nConst++;
4809 pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
4810 pConst->nConst*2*sizeof(Expr*));
4811 if( pConst->apExpr==0 ){
4812 pConst->nConst = 0;
4813 }else{
4814 pConst->apExpr[pConst->nConst*2-2] = pColumn;
4815 pConst->apExpr[pConst->nConst*2-1] = pValue;
4820 ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
4821 ** is a constant expression and where the term must be true because it
4822 ** is part of the AND-connected terms of the expression. For each term
4823 ** found, add it to the pConst structure.
4825 static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
4826 Expr *pRight, *pLeft;
4827 if( NEVER(pExpr==0) ) return;
4828 if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
4829 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4830 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4831 return;
4833 if( pExpr->op==TK_AND ){
4834 findConstInWhere(pConst, pExpr->pRight);
4835 findConstInWhere(pConst, pExpr->pLeft);
4836 return;
4838 if( pExpr->op!=TK_EQ ) return;
4839 pRight = pExpr->pRight;
4840 pLeft = pExpr->pLeft;
4841 assert( pRight!=0 );
4842 assert( pLeft!=0 );
4843 if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pLeft) ){
4844 constInsert(pConst,pRight,pLeft,pExpr);
4846 if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pRight) ){
4847 constInsert(pConst,pLeft,pRight,pExpr);
4852 ** This is a helper function for Walker callback propagateConstantExprRewrite().
4854 ** Argument pExpr is a candidate expression to be replaced by a value. If
4855 ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
4856 ** then overwrite it with the corresponding value. Except, do not do so
4857 ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
4858 ** is SQLITE_AFF_BLOB.
4860 static int propagateConstantExprRewriteOne(
4861 WhereConst *pConst,
4862 Expr *pExpr,
4863 int bIgnoreAffBlob
4865 int i;
4866 if( pConst->pOomFault[0] ) return WRC_Prune;
4867 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
4868 if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
4869 testcase( ExprHasProperty(pExpr, EP_FixedCol) );
4870 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4871 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4872 return WRC_Continue;
4874 for(i=0; i<pConst->nConst; i++){
4875 Expr *pColumn = pConst->apExpr[i*2];
4876 if( pColumn==pExpr ) continue;
4877 if( pColumn->iTable!=pExpr->iTable ) continue;
4878 if( pColumn->iColumn!=pExpr->iColumn ) continue;
4879 if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4880 break;
4882 /* A match is found. Add the EP_FixedCol property */
4883 pConst->nChng++;
4884 ExprClearProperty(pExpr, EP_Leaf);
4885 ExprSetProperty(pExpr, EP_FixedCol);
4886 assert( pExpr->pLeft==0 );
4887 pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
4888 if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
4889 break;
4891 return WRC_Prune;
4895 ** This is a Walker expression callback. pExpr is a node from the WHERE
4896 ** clause of a SELECT statement. This function examines pExpr to see if
4897 ** any substitutions based on the contents of pWalker->u.pConst should
4898 ** be made to pExpr or its immediate children.
4900 ** A substitution is made if:
4902 ** + pExpr is a column with an affinity other than BLOB that matches
4903 ** one of the columns in pWalker->u.pConst, or
4905 ** + pExpr is a binary comparison operator (=, <=, >=, <, >) that
4906 ** uses an affinity other than TEXT and one of its immediate
4907 ** children is a column that matches one of the columns in
4908 ** pWalker->u.pConst.
4910 static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
4911 WhereConst *pConst = pWalker->u.pConst;
4912 assert( TK_GT==TK_EQ+1 );
4913 assert( TK_LE==TK_EQ+2 );
4914 assert( TK_LT==TK_EQ+3 );
4915 assert( TK_GE==TK_EQ+4 );
4916 if( pConst->bHasAffBlob ){
4917 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
4918 || pExpr->op==TK_IS
4920 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
4921 if( pConst->pOomFault[0] ) return WRC_Prune;
4922 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
4923 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
4927 return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
4931 ** The WHERE-clause constant propagation optimization.
4933 ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
4934 ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
4935 ** part of a ON clause from a LEFT JOIN, then throughout the query
4936 ** replace all other occurrences of COLUMN with CONSTANT.
4938 ** For example, the query:
4940 ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
4942 ** Is transformed into
4944 ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
4946 ** Return true if any transformations where made and false if not.
4948 ** Implementation note: Constant propagation is tricky due to affinity
4949 ** and collating sequence interactions. Consider this example:
4951 ** CREATE TABLE t1(a INT,b TEXT);
4952 ** INSERT INTO t1 VALUES(123,'0123');
4953 ** SELECT * FROM t1 WHERE a=123 AND b=a;
4954 ** SELECT * FROM t1 WHERE a=123 AND b=123;
4956 ** The two SELECT statements above should return different answers. b=a
4957 ** is always true because the comparison uses numeric affinity, but b=123
4958 ** is false because it uses text affinity and '0123' is not the same as '123'.
4959 ** To work around this, the expression tree is not actually changed from
4960 ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
4961 ** and the "123" value is hung off of the pLeft pointer. Code generator
4962 ** routines know to generate the constant "123" instead of looking up the
4963 ** column value. Also, to avoid collation problems, this optimization is
4964 ** only attempted if the "a=123" term uses the default BINARY collation.
4966 ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
4968 ** CREATE TABLE t1(x);
4969 ** INSERT INTO t1 VALUES(10.0);
4970 ** SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
4972 ** The query should return no rows, because the t1.x value is '10.0' not '10'
4973 ** and '10.0' is not LIKE '10'. But if we are not careful, the first WHERE
4974 ** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
4975 ** resulting in a false positive. To avoid this, constant propagation for
4976 ** columns with BLOB affinity is only allowed if the constant is used with
4977 ** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
4978 ** type conversions to occur. See logic associated with the bHasAffBlob flag
4979 ** for details.
4981 static int propagateConstants(
4982 Parse *pParse, /* The parsing context */
4983 Select *p /* The query in which to propagate constants */
4985 WhereConst x;
4986 Walker w;
4987 int nChng = 0;
4988 x.pParse = pParse;
4989 x.pOomFault = &pParse->db->mallocFailed;
4991 x.nConst = 0;
4992 x.nChng = 0;
4993 x.apExpr = 0;
4994 x.bHasAffBlob = 0;
4995 if( ALWAYS(p->pSrc!=0)
4996 && p->pSrc->nSrc>0
4997 && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
4999 /* Do not propagate constants on any ON clause if there is a
5000 ** RIGHT JOIN anywhere in the query */
5001 x.mExcludeOn = EP_InnerON | EP_OuterON;
5002 }else{
5003 /* Do not propagate constants through the ON clause of a LEFT JOIN */
5004 x.mExcludeOn = EP_OuterON;
5006 findConstInWhere(&x, p->pWhere);
5007 if( x.nConst ){
5008 memset(&w, 0, sizeof(w));
5009 w.pParse = pParse;
5010 w.xExprCallback = propagateConstantExprRewrite;
5011 w.xSelectCallback = sqlite3SelectWalkNoop;
5012 w.xSelectCallback2 = 0;
5013 w.walkerDepth = 0;
5014 w.u.pConst = &x;
5015 sqlite3WalkExpr(&w, p->pWhere);
5016 sqlite3DbFree(x.pParse->db, x.apExpr);
5017 nChng += x.nChng;
5019 }while( x.nChng );
5020 return nChng;
5023 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5024 # if !defined(SQLITE_OMIT_WINDOWFUNC)
5026 ** This function is called to determine whether or not it is safe to
5027 ** push WHERE clause expression pExpr down to FROM clause sub-query
5028 ** pSubq, which contains at least one window function. Return 1
5029 ** if it is safe and the expression should be pushed down, or 0
5030 ** otherwise.
5032 ** It is only safe to push the expression down if it consists only
5033 ** of constants and copies of expressions that appear in the PARTITION
5034 ** BY clause of all window function used by the sub-query. It is safe
5035 ** to filter out entire partitions, but not rows within partitions, as
5036 ** this may change the results of the window functions.
5038 ** At the time this function is called it is guaranteed that
5040 ** * the sub-query uses only one distinct window frame, and
5041 ** * that the window frame has a PARTITION BY clause.
5043 static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
5044 assert( pSubq->pWin->pPartition );
5045 assert( (pSubq->selFlags & SF_MultiPart)==0 );
5046 assert( pSubq->pPrior==0 );
5047 return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
5049 # endif /* SQLITE_OMIT_WINDOWFUNC */
5050 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5052 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5054 ** Make copies of relevant WHERE clause terms of the outer query into
5055 ** the WHERE clause of subquery. Example:
5057 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
5059 ** Transformed into:
5061 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
5062 ** WHERE x=5 AND y=10;
5064 ** The hope is that the terms added to the inner query will make it more
5065 ** efficient.
5067 ** NAME AMBIGUITY
5069 ** This optimization is called the "WHERE-clause push-down optimization".
5071 ** Do not confuse this optimization with another unrelated optimization
5072 ** with a similar name: The "MySQL push-down optimization" causes WHERE
5073 ** clause terms that can be evaluated using only the index and without
5074 ** reference to the table are run first, so that if they are false,
5075 ** unnecessary table seeks are avoided.
5077 ** RULES
5079 ** Do not attempt this optimization if:
5081 ** (1) (** This restriction was removed on 2017-09-29. We used to
5082 ** disallow this optimization for aggregate subqueries, but now
5083 ** it is allowed by putting the extra terms on the HAVING clause.
5084 ** The added HAVING clause is pointless if the subquery lacks
5085 ** a GROUP BY clause. But such a HAVING clause is also harmless
5086 ** so there does not appear to be any reason to add extra logic
5087 ** to suppress it. **)
5089 ** (2) The inner query is the recursive part of a common table expression.
5091 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
5092 ** clause would change the meaning of the LIMIT).
5094 ** (4) The inner query is the right operand of a LEFT JOIN and the
5095 ** expression to be pushed down does not come from the ON clause
5096 ** on that LEFT JOIN.
5098 ** (5) The WHERE clause expression originates in the ON or USING clause
5099 ** of a LEFT JOIN where iCursor is not the right-hand table of that
5100 ** left join. An example:
5102 ** SELECT *
5103 ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
5104 ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
5105 ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
5107 ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
5108 ** But if the (b2=2) term were to be pushed down into the bb subquery,
5109 ** then the (1,1,NULL) row would be suppressed.
5111 ** (6) Window functions make things tricky as changes to the WHERE clause
5112 ** of the inner query could change the window over which window
5113 ** functions are calculated. Therefore, do not attempt the optimization
5114 ** if:
5116 ** (6a) The inner query uses multiple incompatible window partitions.
5118 ** (6b) The inner query is a compound and uses window-functions.
5120 ** (6c) The WHERE clause does not consist entirely of constants and
5121 ** copies of expressions found in the PARTITION BY clause of
5122 ** all window-functions used by the sub-query. It is safe to
5123 ** filter out entire partitions, as this does not change the
5124 ** window over which any window-function is calculated.
5126 ** (7) The inner query is a Common Table Expression (CTE) that should
5127 ** be materialized. (This restriction is implemented in the calling
5128 ** routine.)
5130 ** (8) If the subquery is a compound that uses UNION, INTERSECT,
5131 ** or EXCEPT, then all of the result set columns for all arms of
5132 ** the compound must use the BINARY collating sequence.
5134 ** (9) All three of the following are true:
5136 ** (9a) The WHERE clause expression originates in the ON or USING clause
5137 ** of a join (either an INNER or an OUTER join), and
5139 ** (9b) The subquery is to the right of the ON/USING clause
5141 ** (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
5142 ** clause and the subquery.
5144 ** Without this restriction, the WHERE-clause push-down optimization
5145 ** might move the ON/USING filter expression from the left side of a
5146 ** RIGHT JOIN over to the right side, which leads to incorrect answers.
5147 ** See also restriction (6) in sqlite3ExprIsSingleTableConstraint().
5149 ** (10) The inner query is not the right-hand table of a RIGHT JOIN.
5151 ** (11) The subquery is not a VALUES clause
5153 ** (12) The WHERE clause is not "rowid ISNULL" or the equivalent. This
5154 ** case only comes up if SQLite is compiled using
5155 ** SQLITE_ALLOW_ROWID_IN_VIEW.
5157 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
5158 ** terms are duplicated into the subquery.
5160 static int pushDownWhereTerms(
5161 Parse *pParse, /* Parse context (for malloc() and error reporting) */
5162 Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
5163 Expr *pWhere, /* The WHERE clause of the outer query */
5164 SrcList *pSrcList, /* The complete from clause of the outer query */
5165 int iSrc /* Which FROM clause term to try to push into */
5167 Expr *pNew;
5168 SrcItem *pSrc; /* The subquery FROM term into which WHERE is pushed */
5169 int nChng = 0;
5170 pSrc = &pSrcList->a[iSrc];
5171 if( pWhere==0 ) return 0;
5172 if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
5173 return 0; /* restrictions (2) and (11) */
5175 if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
5176 return 0; /* restrictions (10) */
5179 if( pSubq->pPrior ){
5180 Select *pSel;
5181 int notUnionAll = 0;
5182 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5183 u8 op = pSel->op;
5184 assert( op==TK_ALL || op==TK_SELECT
5185 || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
5186 if( op!=TK_ALL && op!=TK_SELECT ){
5187 notUnionAll = 1;
5189 #ifndef SQLITE_OMIT_WINDOWFUNC
5190 if( pSel->pWin ) return 0; /* restriction (6b) */
5191 #endif
5193 if( notUnionAll ){
5194 /* If any of the compound arms are connected using UNION, INTERSECT,
5195 ** or EXCEPT, then we must ensure that none of the columns use a
5196 ** non-BINARY collating sequence. */
5197 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5198 int ii;
5199 const ExprList *pList = pSel->pEList;
5200 assert( pList!=0 );
5201 for(ii=0; ii<pList->nExpr; ii++){
5202 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[ii].pExpr);
5203 if( !sqlite3IsBinary(pColl) ){
5204 return 0; /* Restriction (8) */
5209 }else{
5210 #ifndef SQLITE_OMIT_WINDOWFUNC
5211 if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
5212 #endif
5215 #ifdef SQLITE_DEBUG
5216 /* Only the first term of a compound can have a WITH clause. But make
5217 ** sure no other terms are marked SF_Recursive in case something changes
5218 ** in the future.
5221 Select *pX;
5222 for(pX=pSubq; pX; pX=pX->pPrior){
5223 assert( (pX->selFlags & (SF_Recursive))==0 );
5226 #endif
5228 if( pSubq->pLimit!=0 ){
5229 return 0; /* restriction (3) */
5231 while( pWhere->op==TK_AND ){
5232 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
5233 pWhere = pWhere->pLeft;
5236 #if 0 /* These checks now done by sqlite3ExprIsSingleTableConstraint() */
5237 if( ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) /* (9a) */
5238 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (9c) */
5240 int jj;
5241 for(jj=0; jj<iSrc; jj++){
5242 if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
5243 /* If we reach this point, both (9a) and (9b) are satisfied.
5244 ** The following loop checks (9c):
5246 for(jj++; jj<iSrc; jj++){
5247 if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
5248 return 0; /* restriction (9) */
5254 if( isLeftJoin
5255 && (ExprHasProperty(pWhere,EP_OuterON)==0
5256 || pWhere->w.iJoin!=iCursor)
5258 return 0; /* restriction (4) */
5260 if( ExprHasProperty(pWhere,EP_OuterON)
5261 && pWhere->w.iJoin!=iCursor
5263 return 0; /* restriction (5) */
5265 #endif
5267 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
5268 if( ViewCanHaveRowid && (pWhere->op==TK_ISNULL || pWhere->op==TK_NOTNULL) ){
5269 Expr *pLeft = pWhere->pLeft;
5270 if( ALWAYS(pLeft)
5271 && pLeft->op==TK_COLUMN
5272 && pLeft->iColumn < 0
5274 return 0; /* Restriction (12) */
5277 #endif
5279 if( sqlite3ExprIsSingleTableConstraint(pWhere, pSrcList, iSrc, 1) ){
5280 nChng++;
5281 pSubq->selFlags |= SF_PushDown;
5282 while( pSubq ){
5283 SubstContext x;
5284 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
5285 unsetJoinExpr(pNew, -1, 1);
5286 x.pParse = pParse;
5287 x.iTable = pSrc->iCursor;
5288 x.iNewTable = pSrc->iCursor;
5289 x.isOuterJoin = 0;
5290 x.pEList = pSubq->pEList;
5291 x.pCList = findLeftmostExprlist(pSubq);
5292 pNew = substExpr(&x, pNew);
5293 #ifndef SQLITE_OMIT_WINDOWFUNC
5294 if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
5295 /* Restriction 6c has prevented push-down in this case */
5296 sqlite3ExprDelete(pParse->db, pNew);
5297 nChng--;
5298 break;
5300 #endif
5301 if( pSubq->selFlags & SF_Aggregate ){
5302 pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
5303 }else{
5304 pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
5306 pSubq = pSubq->pPrior;
5309 return nChng;
5311 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5314 ** Check to see if a subquery contains result-set columns that are
5315 ** never used. If it does, change the value of those result-set columns
5316 ** to NULL so that they do not cause unnecessary work to compute.
5318 ** Return the number of column that were changed to NULL.
5320 static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
5321 int nCol;
5322 Select *pSub; /* The subquery to be simplified */
5323 Select *pX; /* For looping over compound elements of pSub */
5324 Table *pTab; /* The table that describes the subquery */
5325 int j; /* Column number */
5326 int nChng = 0; /* Number of columns converted to NULL */
5327 Bitmask colUsed; /* Columns that may not be NULLed out */
5329 assert( pItem!=0 );
5330 if( pItem->fg.isCorrelated || pItem->fg.isCte ){
5331 return 0;
5333 assert( pItem->pTab!=0 );
5334 pTab = pItem->pTab;
5335 assert( pItem->pSelect!=0 );
5336 pSub = pItem->pSelect;
5337 assert( pSub->pEList->nExpr==pTab->nCol );
5338 for(pX=pSub; pX; pX=pX->pPrior){
5339 if( (pX->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
5340 testcase( pX->selFlags & SF_Distinct );
5341 testcase( pX->selFlags & SF_Aggregate );
5342 return 0;
5344 if( pX->pPrior && pX->op!=TK_ALL ){
5345 /* This optimization does not work for compound subqueries that
5346 ** use UNION, INTERSECT, or EXCEPT. Only UNION ALL is allowed. */
5347 return 0;
5349 #ifndef SQLITE_OMIT_WINDOWFUNC
5350 if( pX->pWin ){
5351 /* This optimization does not work for subqueries that use window
5352 ** functions. */
5353 return 0;
5355 #endif
5357 colUsed = pItem->colUsed;
5358 if( pSub->pOrderBy ){
5359 ExprList *pList = pSub->pOrderBy;
5360 for(j=0; j<pList->nExpr; j++){
5361 u16 iCol = pList->a[j].u.x.iOrderByCol;
5362 if( iCol>0 ){
5363 iCol--;
5364 colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
5368 nCol = pTab->nCol;
5369 for(j=0; j<nCol; j++){
5370 Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
5371 if( (m & colUsed)!=0 ) continue;
5372 for(pX=pSub; pX; pX=pX->pPrior) {
5373 Expr *pY = pX->pEList->a[j].pExpr;
5374 if( pY->op==TK_NULL ) continue;
5375 pY->op = TK_NULL;
5376 ExprClearProperty(pY, EP_Skip|EP_Unlikely);
5377 pX->selFlags |= SF_PushDown;
5378 nChng++;
5381 return nChng;
5386 ** The pFunc is the only aggregate function in the query. Check to see
5387 ** if the query is a candidate for the min/max optimization.
5389 ** If the query is a candidate for the min/max optimization, then set
5390 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
5391 ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
5392 ** whether pFunc is a min() or max() function.
5394 ** If the query is not a candidate for the min/max optimization, return
5395 ** WHERE_ORDERBY_NORMAL (which must be zero).
5397 ** This routine must be called after aggregate functions have been
5398 ** located but before their arguments have been subjected to aggregate
5399 ** analysis.
5401 static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
5402 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
5403 ExprList *pEList; /* Arguments to agg function */
5404 const char *zFunc; /* Name of aggregate function pFunc */
5405 ExprList *pOrderBy;
5406 u8 sortFlags = 0;
5408 assert( *ppMinMax==0 );
5409 assert( pFunc->op==TK_AGG_FUNCTION );
5410 assert( !IsWindowFunc(pFunc) );
5411 assert( ExprUseXList(pFunc) );
5412 pEList = pFunc->x.pList;
5413 if( pEList==0
5414 || pEList->nExpr!=1
5415 || ExprHasProperty(pFunc, EP_WinFunc)
5416 || OptimizationDisabled(db, SQLITE_MinMaxOpt)
5418 return eRet;
5420 assert( !ExprHasProperty(pFunc, EP_IntValue) );
5421 zFunc = pFunc->u.zToken;
5422 if( sqlite3StrICmp(zFunc, "min")==0 ){
5423 eRet = WHERE_ORDERBY_MIN;
5424 if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
5425 sortFlags = KEYINFO_ORDER_BIGNULL;
5427 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
5428 eRet = WHERE_ORDERBY_MAX;
5429 sortFlags = KEYINFO_ORDER_DESC;
5430 }else{
5431 return eRet;
5433 *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
5434 assert( pOrderBy!=0 || db->mallocFailed );
5435 if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
5436 return eRet;
5440 ** The select statement passed as the first argument is an aggregate query.
5441 ** The second argument is the associated aggregate-info object. This
5442 ** function tests if the SELECT is of the form:
5444 ** SELECT count(*) FROM <tbl>
5446 ** where table is a database table, not a sub-select or view. If the query
5447 ** does match this pattern, then a pointer to the Table object representing
5448 ** <tbl> is returned. Otherwise, NULL is returned.
5450 ** This routine checks to see if it is safe to use the count optimization.
5451 ** A correct answer is still obtained (though perhaps more slowly) if
5452 ** this routine returns NULL when it could have returned a table pointer.
5453 ** But returning the pointer when NULL should have been returned can
5454 ** result in incorrect answers and/or crashes. So, when in doubt, return NULL.
5456 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
5457 Table *pTab;
5458 Expr *pExpr;
5460 assert( !p->pGroupBy );
5462 if( p->pWhere
5463 || p->pEList->nExpr!=1
5464 || p->pSrc->nSrc!=1
5465 || p->pSrc->a[0].pSelect
5466 || pAggInfo->nFunc!=1
5467 || p->pHaving
5469 return 0;
5471 pTab = p->pSrc->a[0].pTab;
5472 assert( pTab!=0 );
5473 assert( !IsView(pTab) );
5474 if( !IsOrdinaryTable(pTab) ) return 0;
5475 pExpr = p->pEList->a[0].pExpr;
5476 assert( pExpr!=0 );
5477 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
5478 if( pExpr->pAggInfo!=pAggInfo ) return 0;
5479 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
5480 assert( pAggInfo->aFunc[0].pFExpr==pExpr );
5481 testcase( ExprHasProperty(pExpr, EP_Distinct) );
5482 testcase( ExprHasProperty(pExpr, EP_WinFunc) );
5483 if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
5485 return pTab;
5489 ** If the source-list item passed as an argument was augmented with an
5490 ** INDEXED BY clause, then try to locate the specified index. If there
5491 ** was such a clause and the named index cannot be found, return
5492 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
5493 ** pFrom->pIndex and return SQLITE_OK.
5495 int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
5496 Table *pTab = pFrom->pTab;
5497 char *zIndexedBy = pFrom->u1.zIndexedBy;
5498 Index *pIdx;
5499 assert( pTab!=0 );
5500 assert( pFrom->fg.isIndexedBy!=0 );
5502 for(pIdx=pTab->pIndex;
5503 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
5504 pIdx=pIdx->pNext
5506 if( !pIdx ){
5507 sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
5508 pParse->checkSchema = 1;
5509 return SQLITE_ERROR;
5511 assert( pFrom->fg.isCte==0 );
5512 pFrom->u2.pIBIndex = pIdx;
5513 return SQLITE_OK;
5517 ** Detect compound SELECT statements that use an ORDER BY clause with
5518 ** an alternative collating sequence.
5520 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
5522 ** These are rewritten as a subquery:
5524 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
5525 ** ORDER BY ... COLLATE ...
5527 ** This transformation is necessary because the multiSelectOrderBy() routine
5528 ** above that generates the code for a compound SELECT with an ORDER BY clause
5529 ** uses a merge algorithm that requires the same collating sequence on the
5530 ** result columns as on the ORDER BY clause. See ticket
5531 ** http://www.sqlite.org/src/info/6709574d2a
5533 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
5534 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
5535 ** there are COLLATE terms in the ORDER BY.
5537 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
5538 int i;
5539 Select *pNew;
5540 Select *pX;
5541 sqlite3 *db;
5542 struct ExprList_item *a;
5543 SrcList *pNewSrc;
5544 Parse *pParse;
5545 Token dummy;
5547 if( p->pPrior==0 ) return WRC_Continue;
5548 if( p->pOrderBy==0 ) return WRC_Continue;
5549 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
5550 if( pX==0 ) return WRC_Continue;
5551 a = p->pOrderBy->a;
5552 #ifndef SQLITE_OMIT_WINDOWFUNC
5553 /* If iOrderByCol is already non-zero, then it has already been matched
5554 ** to a result column of the SELECT statement. This occurs when the
5555 ** SELECT is rewritten for window-functions processing and then passed
5556 ** to sqlite3SelectPrep() and similar a second time. The rewriting done
5557 ** by this function is not required in this case. */
5558 if( a[0].u.x.iOrderByCol ) return WRC_Continue;
5559 #endif
5560 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
5561 if( a[i].pExpr->flags & EP_Collate ) break;
5563 if( i<0 ) return WRC_Continue;
5565 /* If we reach this point, that means the transformation is required. */
5567 pParse = pWalker->pParse;
5568 db = pParse->db;
5569 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
5570 if( pNew==0 ) return WRC_Abort;
5571 memset(&dummy, 0, sizeof(dummy));
5572 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
5573 if( pNewSrc==0 ) return WRC_Abort;
5574 *pNew = *p;
5575 p->pSrc = pNewSrc;
5576 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
5577 p->op = TK_SELECT;
5578 p->pWhere = 0;
5579 pNew->pGroupBy = 0;
5580 pNew->pHaving = 0;
5581 pNew->pOrderBy = 0;
5582 p->pPrior = 0;
5583 p->pNext = 0;
5584 p->pWith = 0;
5585 #ifndef SQLITE_OMIT_WINDOWFUNC
5586 p->pWinDefn = 0;
5587 #endif
5588 p->selFlags &= ~SF_Compound;
5589 assert( (p->selFlags & SF_Converted)==0 );
5590 p->selFlags |= SF_Converted;
5591 assert( pNew->pPrior!=0 );
5592 pNew->pPrior->pNext = pNew;
5593 pNew->pLimit = 0;
5594 return WRC_Continue;
5598 ** Check to see if the FROM clause term pFrom has table-valued function
5599 ** arguments. If it does, leave an error message in pParse and return
5600 ** non-zero, since pFrom is not allowed to be a table-valued function.
5602 static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
5603 if( pFrom->fg.isTabFunc ){
5604 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
5605 return 1;
5607 return 0;
5610 #ifndef SQLITE_OMIT_CTE
5612 ** Argument pWith (which may be NULL) points to a linked list of nested
5613 ** WITH contexts, from inner to outermost. If the table identified by
5614 ** FROM clause element pItem is really a common-table-expression (CTE)
5615 ** then return a pointer to the CTE definition for that table. Otherwise
5616 ** return NULL.
5618 ** If a non-NULL value is returned, set *ppContext to point to the With
5619 ** object that the returned CTE belongs to.
5621 static struct Cte *searchWith(
5622 With *pWith, /* Current innermost WITH clause */
5623 SrcItem *pItem, /* FROM clause element to resolve */
5624 With **ppContext /* OUT: WITH clause return value belongs to */
5626 const char *zName = pItem->zName;
5627 With *p;
5628 assert( pItem->zDatabase==0 );
5629 assert( zName!=0 );
5630 for(p=pWith; p; p=p->pOuter){
5631 int i;
5632 for(i=0; i<p->nCte; i++){
5633 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
5634 *ppContext = p;
5635 return &p->a[i];
5638 if( p->bView ) break;
5640 return 0;
5643 /* The code generator maintains a stack of active WITH clauses
5644 ** with the inner-most WITH clause being at the top of the stack.
5646 ** This routine pushes the WITH clause passed as the second argument
5647 ** onto the top of the stack. If argument bFree is true, then this
5648 ** WITH clause will never be popped from the stack but should instead
5649 ** be freed along with the Parse object. In other cases, when
5650 ** bFree==0, the With object will be freed along with the SELECT
5651 ** statement with which it is associated.
5653 ** This routine returns a copy of pWith. Or, if bFree is true and
5654 ** the pWith object is destroyed immediately due to an OOM condition,
5655 ** then this routine return NULL.
5657 ** If bFree is true, do not continue to use the pWith pointer after
5658 ** calling this routine, Instead, use only the return value.
5660 With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
5661 if( pWith ){
5662 if( bFree ){
5663 pWith = (With*)sqlite3ParserAddCleanup(pParse, sqlite3WithDeleteGeneric,
5664 pWith);
5665 if( pWith==0 ) return 0;
5667 if( pParse->nErr==0 ){
5668 assert( pParse->pWith!=pWith );
5669 pWith->pOuter = pParse->pWith;
5670 pParse->pWith = pWith;
5673 return pWith;
5677 ** This function checks if argument pFrom refers to a CTE declared by
5678 ** a WITH clause on the stack currently maintained by the parser (on the
5679 ** pParse->pWith linked list). And if currently processing a CTE
5680 ** CTE expression, through routine checks to see if the reference is
5681 ** a recursive reference to the CTE.
5683 ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
5684 ** and other fields are populated accordingly.
5686 ** Return 0 if no match is found.
5687 ** Return 1 if a match is found.
5688 ** Return 2 if an error condition is detected.
5690 static int resolveFromTermToCte(
5691 Parse *pParse, /* The parsing context */
5692 Walker *pWalker, /* Current tree walker */
5693 SrcItem *pFrom /* The FROM clause term to check */
5695 Cte *pCte; /* Matched CTE (or NULL if no match) */
5696 With *pWith; /* The matching WITH */
5698 assert( pFrom->pTab==0 );
5699 if( pParse->pWith==0 ){
5700 /* There are no WITH clauses in the stack. No match is possible */
5701 return 0;
5703 if( pParse->nErr ){
5704 /* Prior errors might have left pParse->pWith in a goofy state, so
5705 ** go no further. */
5706 return 0;
5708 if( pFrom->zDatabase!=0 ){
5709 /* The FROM term contains a schema qualifier (ex: main.t1) and so
5710 ** it cannot possibly be a CTE reference. */
5711 return 0;
5713 if( pFrom->fg.notCte ){
5714 /* The FROM term is specifically excluded from matching a CTE.
5715 ** (1) It is part of a trigger that used to have zDatabase but had
5716 ** zDatabase removed by sqlite3FixTriggerStep().
5717 ** (2) This is the first term in the FROM clause of an UPDATE.
5719 return 0;
5721 pCte = searchWith(pParse->pWith, pFrom, &pWith);
5722 if( pCte ){
5723 sqlite3 *db = pParse->db;
5724 Table *pTab;
5725 ExprList *pEList;
5726 Select *pSel;
5727 Select *pLeft; /* Left-most SELECT statement */
5728 Select *pRecTerm; /* Left-most recursive term */
5729 int bMayRecursive; /* True if compound joined by UNION [ALL] */
5730 With *pSavedWith; /* Initial value of pParse->pWith */
5731 int iRecTab = -1; /* Cursor for recursive table */
5732 CteUse *pCteUse;
5734 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
5735 ** recursive reference to CTE pCte. Leave an error in pParse and return
5736 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
5737 ** In this case, proceed. */
5738 if( pCte->zCteErr ){
5739 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
5740 return 2;
5742 if( cannotBeFunction(pParse, pFrom) ) return 2;
5744 assert( pFrom->pTab==0 );
5745 pTab = sqlite3DbMallocZero(db, sizeof(Table));
5746 if( pTab==0 ) return 2;
5747 pCteUse = pCte->pUse;
5748 if( pCteUse==0 ){
5749 pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
5750 if( pCteUse==0
5751 || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
5753 sqlite3DbFree(db, pTab);
5754 return 2;
5756 pCteUse->eM10d = pCte->eM10d;
5758 pFrom->pTab = pTab;
5759 pTab->nTabRef = 1;
5760 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
5761 pTab->iPKey = -1;
5762 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5763 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5764 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
5765 if( db->mallocFailed ) return 2;
5766 pFrom->pSelect->selFlags |= SF_CopyCte;
5767 assert( pFrom->pSelect );
5768 if( pFrom->fg.isIndexedBy ){
5769 sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
5770 return 2;
5772 pFrom->fg.isCte = 1;
5773 pFrom->u2.pCteUse = pCteUse;
5774 pCteUse->nUse++;
5776 /* Check if this is a recursive CTE. */
5777 pRecTerm = pSel = pFrom->pSelect;
5778 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
5779 while( bMayRecursive && pRecTerm->op==pSel->op ){
5780 int i;
5781 SrcList *pSrc = pRecTerm->pSrc;
5782 assert( pRecTerm->pPrior!=0 );
5783 for(i=0; i<pSrc->nSrc; i++){
5784 SrcItem *pItem = &pSrc->a[i];
5785 if( pItem->zDatabase==0
5786 && pItem->zName!=0
5787 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
5789 pItem->pTab = pTab;
5790 pTab->nTabRef++;
5791 pItem->fg.isRecursive = 1;
5792 if( pRecTerm->selFlags & SF_Recursive ){
5793 sqlite3ErrorMsg(pParse,
5794 "multiple references to recursive table: %s", pCte->zName
5796 return 2;
5798 pRecTerm->selFlags |= SF_Recursive;
5799 if( iRecTab<0 ) iRecTab = pParse->nTab++;
5800 pItem->iCursor = iRecTab;
5803 if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
5804 pRecTerm = pRecTerm->pPrior;
5807 pCte->zCteErr = "circular reference: %s";
5808 pSavedWith = pParse->pWith;
5809 pParse->pWith = pWith;
5810 if( pSel->selFlags & SF_Recursive ){
5811 int rc;
5812 assert( pRecTerm!=0 );
5813 assert( (pRecTerm->selFlags & SF_Recursive)==0 );
5814 assert( pRecTerm->pNext!=0 );
5815 assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
5816 assert( pRecTerm->pWith==0 );
5817 pRecTerm->pWith = pSel->pWith;
5818 rc = sqlite3WalkSelect(pWalker, pRecTerm);
5819 pRecTerm->pWith = 0;
5820 if( rc ){
5821 pParse->pWith = pSavedWith;
5822 return 2;
5824 }else{
5825 if( sqlite3WalkSelect(pWalker, pSel) ){
5826 pParse->pWith = pSavedWith;
5827 return 2;
5830 pParse->pWith = pWith;
5832 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
5833 pEList = pLeft->pEList;
5834 if( pCte->pCols ){
5835 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
5836 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
5837 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
5839 pParse->pWith = pSavedWith;
5840 return 2;
5842 pEList = pCte->pCols;
5845 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
5846 if( bMayRecursive ){
5847 if( pSel->selFlags & SF_Recursive ){
5848 pCte->zCteErr = "multiple recursive references: %s";
5849 }else{
5850 pCte->zCteErr = "recursive reference in a subquery: %s";
5852 sqlite3WalkSelect(pWalker, pSel);
5854 pCte->zCteErr = 0;
5855 pParse->pWith = pSavedWith;
5856 return 1; /* Success */
5858 return 0; /* No match */
5860 #endif
5862 #ifndef SQLITE_OMIT_CTE
5864 ** If the SELECT passed as the second argument has an associated WITH
5865 ** clause, pop it from the stack stored as part of the Parse object.
5867 ** This function is used as the xSelectCallback2() callback by
5868 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
5869 ** names and other FROM clause elements.
5871 void sqlite3SelectPopWith(Walker *pWalker, Select *p){
5872 Parse *pParse = pWalker->pParse;
5873 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
5874 With *pWith = findRightmost(p)->pWith;
5875 if( pWith!=0 ){
5876 assert( pParse->pWith==pWith || pParse->nErr );
5877 pParse->pWith = pWith->pOuter;
5881 #endif
5884 ** The SrcItem structure passed as the second argument represents a
5885 ** sub-query in the FROM clause of a SELECT statement. This function
5886 ** allocates and populates the SrcItem.pTab object. If successful,
5887 ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
5888 ** SQLITE_NOMEM.
5890 int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
5891 Select *pSel = pFrom->pSelect;
5892 Table *pTab;
5894 assert( pSel );
5895 pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
5896 if( pTab==0 ) return SQLITE_NOMEM;
5897 pTab->nTabRef = 1;
5898 if( pFrom->zAlias ){
5899 pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
5900 }else{
5901 pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
5903 while( pSel->pPrior ){ pSel = pSel->pPrior; }
5904 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
5905 pTab->iPKey = -1;
5906 pTab->eTabType = TABTYP_VIEW;
5907 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5908 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
5909 /* The usual case - do not allow ROWID on a subquery */
5910 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5911 #else
5912 /* Legacy compatibility mode */
5913 pTab->tabFlags |= TF_Ephemeral | sqlite3Config.mNoVisibleRowid;
5914 #endif
5915 return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
5920 ** Check the N SrcItem objects to the right of pBase. (N might be zero!)
5921 ** If any of those SrcItem objects have a USING clause containing zName
5922 ** then return true.
5924 ** If N is zero, or none of the N SrcItem objects to the right of pBase
5925 ** contains a USING clause, or if none of the USING clauses contain zName,
5926 ** then return false.
5928 static int inAnyUsingClause(
5929 const char *zName, /* Name we are looking for */
5930 SrcItem *pBase, /* The base SrcItem. Looking at pBase[1] and following */
5931 int N /* How many SrcItems to check */
5933 while( N>0 ){
5934 N--;
5935 pBase++;
5936 if( pBase->fg.isUsing==0 ) continue;
5937 if( NEVER(pBase->u3.pUsing==0) ) continue;
5938 if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
5940 return 0;
5945 ** This routine is a Walker callback for "expanding" a SELECT statement.
5946 ** "Expanding" means to do the following:
5948 ** (1) Make sure VDBE cursor numbers have been assigned to every
5949 ** element of the FROM clause.
5951 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
5952 ** defines FROM clause. When views appear in the FROM clause,
5953 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
5954 ** that implements the view. A copy is made of the view's SELECT
5955 ** statement so that we can freely modify or delete that statement
5956 ** without worrying about messing up the persistent representation
5957 ** of the view.
5959 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
5960 ** on joins and the ON and USING clause of joins.
5962 ** (4) Scan the list of columns in the result set (pEList) looking
5963 ** for instances of the "*" operator or the TABLE.* operator.
5964 ** If found, expand each "*" to be every column in every table
5965 ** and TABLE.* to be every column in TABLE.
5968 static int selectExpander(Walker *pWalker, Select *p){
5969 Parse *pParse = pWalker->pParse;
5970 int i, j, k, rc;
5971 SrcList *pTabList;
5972 ExprList *pEList;
5973 SrcItem *pFrom;
5974 sqlite3 *db = pParse->db;
5975 Expr *pE, *pRight, *pExpr;
5976 u16 selFlags = p->selFlags;
5977 u32 elistFlags = 0;
5979 p->selFlags |= SF_Expanded;
5980 if( db->mallocFailed ){
5981 return WRC_Abort;
5983 assert( p->pSrc!=0 );
5984 if( (selFlags & SF_Expanded)!=0 ){
5985 return WRC_Prune;
5987 if( pWalker->eCode ){
5988 /* Renumber selId because it has been copied from a view */
5989 p->selId = ++pParse->nSelect;
5991 pTabList = p->pSrc;
5992 pEList = p->pEList;
5993 if( pParse->pWith && (p->selFlags & SF_View) ){
5994 if( p->pWith==0 ){
5995 p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
5996 if( p->pWith==0 ){
5997 return WRC_Abort;
6000 p->pWith->bView = 1;
6002 sqlite3WithPush(pParse, p->pWith, 0);
6004 /* Make sure cursor numbers have been assigned to all entries in
6005 ** the FROM clause of the SELECT statement.
6007 sqlite3SrcListAssignCursors(pParse, pTabList);
6009 /* Look up every table named in the FROM clause of the select. If
6010 ** an entry of the FROM clause is a subquery instead of a table or view,
6011 ** then create a transient table structure to describe the subquery.
6013 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6014 Table *pTab;
6015 assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
6016 if( pFrom->pTab ) continue;
6017 assert( pFrom->fg.isRecursive==0 );
6018 if( pFrom->zName==0 ){
6019 #ifndef SQLITE_OMIT_SUBQUERY
6020 Select *pSel = pFrom->pSelect;
6021 /* A sub-query in the FROM clause of a SELECT */
6022 assert( pSel!=0 );
6023 assert( pFrom->pTab==0 );
6024 if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
6025 if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
6026 #endif
6027 #ifndef SQLITE_OMIT_CTE
6028 }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
6029 if( rc>1 ) return WRC_Abort;
6030 pTab = pFrom->pTab;
6031 assert( pTab!=0 );
6032 #endif
6033 }else{
6034 /* An ordinary table or view name in the FROM clause */
6035 assert( pFrom->pTab==0 );
6036 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
6037 if( pTab==0 ) return WRC_Abort;
6038 if( pTab->nTabRef>=0xffff ){
6039 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
6040 pTab->zName);
6041 pFrom->pTab = 0;
6042 return WRC_Abort;
6044 pTab->nTabRef++;
6045 if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
6046 return WRC_Abort;
6048 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
6049 if( !IsOrdinaryTable(pTab) ){
6050 i16 nCol;
6051 u8 eCodeOrig = pWalker->eCode;
6052 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
6053 assert( pFrom->pSelect==0 );
6054 if( IsView(pTab) ){
6055 if( (db->flags & SQLITE_EnableView)==0
6056 && pTab->pSchema!=db->aDb[1].pSchema
6058 sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
6059 pTab->zName);
6061 pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
6063 #ifndef SQLITE_OMIT_VIRTUALTABLE
6064 else if( ALWAYS(IsVirtual(pTab))
6065 && pFrom->fg.fromDDL
6066 && ALWAYS(pTab->u.vtab.p!=0)
6067 && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
6069 sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
6070 pTab->zName);
6072 assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
6073 #endif
6074 nCol = pTab->nCol;
6075 pTab->nCol = -1;
6076 pWalker->eCode = 1; /* Turn on Select.selId renumbering */
6077 sqlite3WalkSelect(pWalker, pFrom->pSelect);
6078 pWalker->eCode = eCodeOrig;
6079 pTab->nCol = nCol;
6081 #endif
6084 /* Locate the index named by the INDEXED BY clause, if any. */
6085 if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
6086 return WRC_Abort;
6090 /* Process NATURAL keywords, and ON and USING clauses of joins.
6092 assert( db->mallocFailed==0 || pParse->nErr!=0 );
6093 if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
6094 return WRC_Abort;
6097 /* For every "*" that occurs in the column list, insert the names of
6098 ** all columns in all tables. And for every TABLE.* insert the names
6099 ** of all columns in TABLE. The parser inserted a special expression
6100 ** with the TK_ASTERISK operator for each "*" that it found in the column
6101 ** list. The following code just has to locate the TK_ASTERISK
6102 ** expressions and expand each one to the list of all columns in
6103 ** all tables.
6105 ** The first loop just checks to see if there are any "*" operators
6106 ** that need expanding.
6108 for(k=0; k<pEList->nExpr; k++){
6109 pE = pEList->a[k].pExpr;
6110 if( pE->op==TK_ASTERISK ) break;
6111 assert( pE->op!=TK_DOT || pE->pRight!=0 );
6112 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
6113 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
6114 elistFlags |= pE->flags;
6116 if( k<pEList->nExpr ){
6118 ** If we get here it means the result set contains one or more "*"
6119 ** operators that need to be expanded. Loop through each expression
6120 ** in the result set and expand them one by one.
6122 struct ExprList_item *a = pEList->a;
6123 ExprList *pNew = 0;
6124 int flags = pParse->db->flags;
6125 int longNames = (flags & SQLITE_FullColNames)!=0
6126 && (flags & SQLITE_ShortColNames)==0;
6128 for(k=0; k<pEList->nExpr; k++){
6129 pE = a[k].pExpr;
6130 elistFlags |= pE->flags;
6131 pRight = pE->pRight;
6132 assert( pE->op!=TK_DOT || pRight!=0 );
6133 if( pE->op!=TK_ASTERISK
6134 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
6136 /* This particular expression does not need to be expanded.
6138 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
6139 if( pNew ){
6140 pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
6141 pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
6142 a[k].zEName = 0;
6144 a[k].pExpr = 0;
6145 }else{
6146 /* This expression is a "*" or a "TABLE.*" and needs to be
6147 ** expanded. */
6148 int tableSeen = 0; /* Set to 1 when TABLE matches */
6149 char *zTName = 0; /* text of name of TABLE */
6150 int iErrOfst;
6151 if( pE->op==TK_DOT ){
6152 assert( (selFlags & SF_NestedFrom)==0 );
6153 assert( pE->pLeft!=0 );
6154 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
6155 zTName = pE->pLeft->u.zToken;
6156 assert( ExprUseWOfst(pE->pLeft) );
6157 iErrOfst = pE->pRight->w.iOfst;
6158 }else{
6159 assert( ExprUseWOfst(pE) );
6160 iErrOfst = pE->w.iOfst;
6162 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6163 int nAdd; /* Number of cols including rowid */
6164 Table *pTab = pFrom->pTab; /* Table for this data source */
6165 ExprList *pNestedFrom; /* Result-set of a nested FROM clause */
6166 char *zTabName; /* AS name for this data source */
6167 const char *zSchemaName = 0; /* Schema name for this data source */
6168 int iDb; /* Schema index for this data src */
6169 IdList *pUsing; /* USING clause for pFrom[1] */
6171 if( (zTabName = pFrom->zAlias)==0 ){
6172 zTabName = pTab->zName;
6174 if( db->mallocFailed ) break;
6175 assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
6176 if( pFrom->fg.isNestedFrom ){
6177 assert( pFrom->pSelect!=0 );
6178 pNestedFrom = pFrom->pSelect->pEList;
6179 assert( pNestedFrom!=0 );
6180 assert( pNestedFrom->nExpr==pTab->nCol );
6181 assert( VisibleRowid(pTab)==0 || ViewCanHaveRowid );
6182 }else{
6183 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
6184 continue;
6186 pNestedFrom = 0;
6187 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6188 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
6190 if( i+1<pTabList->nSrc
6191 && pFrom[1].fg.isUsing
6192 && (selFlags & SF_NestedFrom)!=0
6194 int ii;
6195 pUsing = pFrom[1].u3.pUsing;
6196 for(ii=0; ii<pUsing->nId; ii++){
6197 const char *zUName = pUsing->a[ii].zName;
6198 pRight = sqlite3Expr(db, TK_ID, zUName);
6199 sqlite3ExprSetErrorOffset(pRight, iErrOfst);
6200 pNew = sqlite3ExprListAppend(pParse, pNew, pRight);
6201 if( pNew ){
6202 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
6203 assert( pX->zEName==0 );
6204 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
6205 pX->fg.eEName = ENAME_TAB;
6206 pX->fg.bUsingTerm = 1;
6209 }else{
6210 pUsing = 0;
6213 nAdd = pTab->nCol;
6214 if( VisibleRowid(pTab) && (selFlags & SF_NestedFrom)!=0 ) nAdd++;
6215 for(j=0; j<nAdd; j++){
6216 const char *zName;
6217 struct ExprList_item *pX; /* Newly added ExprList term */
6219 if( j==pTab->nCol ){
6220 zName = sqlite3RowidAlias(pTab);
6221 if( zName==0 ) continue;
6222 }else{
6223 zName = pTab->aCol[j].zCnName;
6225 /* If pTab is actually an SF_NestedFrom sub-select, do not
6226 ** expand any ENAME_ROWID columns. */
6227 if( pNestedFrom && pNestedFrom->a[j].fg.eEName==ENAME_ROWID ){
6228 continue;
6231 if( zTName
6232 && pNestedFrom
6233 && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0, 0)==0
6235 continue;
6238 /* If a column is marked as 'hidden', omit it from the expanded
6239 ** result-set list unless the SELECT has the SF_IncludeHidden
6240 ** bit set.
6242 if( (p->selFlags & SF_IncludeHidden)==0
6243 && IsHiddenColumn(&pTab->aCol[j])
6245 continue;
6247 if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
6248 && zTName==0
6249 && (selFlags & (SF_NestedFrom))==0
6251 continue;
6254 assert( zName );
6255 tableSeen = 1;
6257 if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
6258 if( pFrom->fg.isUsing
6259 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
6261 /* In a join with a USING clause, omit columns in the
6262 ** using clause from the table on the right. */
6263 continue;
6266 pRight = sqlite3Expr(db, TK_ID, zName);
6267 if( (pTabList->nSrc>1
6268 && ( (pFrom->fg.jointype & JT_LTORJ)==0
6269 || (selFlags & SF_NestedFrom)!=0
6270 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
6273 || IN_RENAME_OBJECT
6275 Expr *pLeft;
6276 pLeft = sqlite3Expr(db, TK_ID, zTabName);
6277 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
6278 if( IN_RENAME_OBJECT && pE->pLeft ){
6279 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
6281 if( zSchemaName ){
6282 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
6283 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
6285 }else{
6286 pExpr = pRight;
6288 sqlite3ExprSetErrorOffset(pExpr, iErrOfst);
6289 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
6290 if( pNew==0 ){
6291 break; /* OOM */
6293 pX = &pNew->a[pNew->nExpr-1];
6294 assert( pX->zEName==0 );
6295 if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
6296 if( pNestedFrom && (!ViewCanHaveRowid || j<pNestedFrom->nExpr) ){
6297 assert( j<pNestedFrom->nExpr );
6298 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
6299 testcase( pX->zEName==0 );
6300 }else{
6301 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
6302 zSchemaName, zTabName, zName);
6303 testcase( pX->zEName==0 );
6305 pX->fg.eEName = (j==pTab->nCol ? ENAME_ROWID : ENAME_TAB);
6306 if( (pFrom->fg.isUsing
6307 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
6308 || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
6309 || (j<pTab->nCol && (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND))
6311 pX->fg.bNoExpand = 1;
6313 }else if( longNames ){
6314 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
6315 pX->fg.eEName = ENAME_NAME;
6316 }else{
6317 pX->zEName = sqlite3DbStrDup(db, zName);
6318 pX->fg.eEName = ENAME_NAME;
6322 if( !tableSeen ){
6323 if( zTName ){
6324 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
6325 }else{
6326 sqlite3ErrorMsg(pParse, "no tables specified");
6331 sqlite3ExprListDelete(db, pEList);
6332 p->pEList = pNew;
6334 if( p->pEList ){
6335 if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
6336 sqlite3ErrorMsg(pParse, "too many columns in result set");
6337 return WRC_Abort;
6339 if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
6340 p->selFlags |= SF_ComplexResult;
6343 #if TREETRACE_ENABLED
6344 if( sqlite3TreeTrace & 0x8 ){
6345 TREETRACE(0x8,pParse,p,("After result-set wildcard expansion:\n"));
6346 sqlite3TreeViewSelect(0, p, 0);
6348 #endif
6349 return WRC_Continue;
6352 #if SQLITE_DEBUG
6354 ** Always assert. This xSelectCallback2 implementation proves that the
6355 ** xSelectCallback2 is never invoked.
6357 void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
6358 UNUSED_PARAMETER2(NotUsed, NotUsed2);
6359 assert( 0 );
6361 #endif
6363 ** This routine "expands" a SELECT statement and all of its subqueries.
6364 ** For additional information on what it means to "expand" a SELECT
6365 ** statement, see the comment on the selectExpand worker callback above.
6367 ** Expanding a SELECT statement is the first step in processing a
6368 ** SELECT statement. The SELECT statement must be expanded before
6369 ** name resolution is performed.
6371 ** If anything goes wrong, an error message is written into pParse.
6372 ** The calling function can detect the problem by looking at pParse->nErr
6373 ** and/or pParse->db->mallocFailed.
6375 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
6376 Walker w;
6377 w.xExprCallback = sqlite3ExprWalkNoop;
6378 w.pParse = pParse;
6379 if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
6380 w.xSelectCallback = convertCompoundSelectToSubquery;
6381 w.xSelectCallback2 = 0;
6382 sqlite3WalkSelect(&w, pSelect);
6384 w.xSelectCallback = selectExpander;
6385 w.xSelectCallback2 = sqlite3SelectPopWith;
6386 w.eCode = 0;
6387 sqlite3WalkSelect(&w, pSelect);
6391 #ifndef SQLITE_OMIT_SUBQUERY
6393 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
6394 ** interface.
6396 ** For each FROM-clause subquery, add Column.zType, Column.zColl, and
6397 ** Column.affinity information to the Table structure that represents
6398 ** the result set of that subquery.
6400 ** The Table structure that represents the result set was constructed
6401 ** by selectExpander() but the type and collation and affinity information
6402 ** was omitted at that point because identifiers had not yet been resolved.
6403 ** This routine is called after identifier resolution.
6405 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
6406 Parse *pParse;
6407 int i;
6408 SrcList *pTabList;
6409 SrcItem *pFrom;
6411 if( p->selFlags & SF_HasTypeInfo ) return;
6412 p->selFlags |= SF_HasTypeInfo;
6413 pParse = pWalker->pParse;
6414 assert( (p->selFlags & SF_Resolved) );
6415 pTabList = p->pSrc;
6416 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6417 Table *pTab = pFrom->pTab;
6418 assert( pTab!=0 );
6419 if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
6420 /* A sub-query in the FROM clause of a SELECT */
6421 Select *pSel = pFrom->pSelect;
6422 if( pSel ){
6423 sqlite3SubqueryColumnTypes(pParse, pTab, pSel, SQLITE_AFF_NONE);
6428 #endif
6432 ** This routine adds datatype and collating sequence information to
6433 ** the Table structures of all FROM-clause subqueries in a
6434 ** SELECT statement.
6436 ** Use this routine after name resolution.
6438 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
6439 #ifndef SQLITE_OMIT_SUBQUERY
6440 Walker w;
6441 w.xSelectCallback = sqlite3SelectWalkNoop;
6442 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
6443 w.xExprCallback = sqlite3ExprWalkNoop;
6444 w.pParse = pParse;
6445 sqlite3WalkSelect(&w, pSelect);
6446 #endif
6451 ** This routine sets up a SELECT statement for processing. The
6452 ** following is accomplished:
6454 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
6455 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
6456 ** * ON and USING clauses are shifted into WHERE statements
6457 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
6458 ** * Identifiers in expression are matched to tables.
6460 ** This routine acts recursively on all subqueries within the SELECT.
6462 void sqlite3SelectPrep(
6463 Parse *pParse, /* The parser context */
6464 Select *p, /* The SELECT statement being coded. */
6465 NameContext *pOuterNC /* Name context for container */
6467 assert( p!=0 || pParse->db->mallocFailed );
6468 assert( pParse->db->pParse==pParse );
6469 if( pParse->db->mallocFailed ) return;
6470 if( p->selFlags & SF_HasTypeInfo ) return;
6471 sqlite3SelectExpand(pParse, p);
6472 if( pParse->nErr ) return;
6473 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
6474 if( pParse->nErr ) return;
6475 sqlite3SelectAddTypeInfo(pParse, p);
6478 #if TREETRACE_ENABLED
6480 ** Display all information about an AggInfo object
6482 static void printAggInfo(AggInfo *pAggInfo){
6483 int ii;
6484 sqlite3DebugPrintf("AggInfo %d/%p:\n",
6485 pAggInfo->selId, pAggInfo);
6486 for(ii=0; ii<pAggInfo->nColumn; ii++){
6487 struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
6488 sqlite3DebugPrintf(
6489 "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
6490 " iSorterColumn=%d %s\n",
6491 ii, pCol->pTab ? pCol->pTab->zName : "NULL",
6492 pCol->iTable, pCol->iColumn, pAggInfo->iFirstReg+ii,
6493 pCol->iSorterColumn,
6494 ii>=pAggInfo->nAccumulator ? "" : " Accumulator");
6495 sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
6497 for(ii=0; ii<pAggInfo->nFunc; ii++){
6498 sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
6499 ii, pAggInfo->iFirstReg+pAggInfo->nColumn+ii);
6500 sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
6503 #endif /* TREETRACE_ENABLED */
6506 ** Analyze the arguments to aggregate functions. Create new pAggInfo->aCol[]
6507 ** entries for columns that are arguments to aggregate functions but which
6508 ** are not otherwise used.
6510 ** The aCol[] entries in AggInfo prior to nAccumulator are columns that
6511 ** are referenced outside of aggregate functions. These might be columns
6512 ** that are part of the GROUP by clause, for example. Other database engines
6513 ** would throw an error if there is a column reference that is not in the
6514 ** GROUP BY clause and that is not part of an aggregate function argument.
6515 ** But SQLite allows this.
6517 ** The aCol[] entries beginning with the aCol[nAccumulator] and following
6518 ** are column references that are used exclusively as arguments to
6519 ** aggregate functions. This routine is responsible for computing
6520 ** (or recomputing) those aCol[] entries.
6522 static void analyzeAggFuncArgs(
6523 AggInfo *pAggInfo,
6524 NameContext *pNC
6526 int i;
6527 assert( pAggInfo!=0 );
6528 assert( pAggInfo->iFirstReg==0 );
6529 pNC->ncFlags |= NC_InAggFunc;
6530 for(i=0; i<pAggInfo->nFunc; i++){
6531 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
6532 assert( pExpr->op==TK_FUNCTION || pExpr->op==TK_AGG_FUNCTION );
6533 assert( ExprUseXList(pExpr) );
6534 sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
6535 if( pExpr->pLeft ){
6536 assert( pExpr->pLeft->op==TK_ORDER );
6537 assert( ExprUseXList(pExpr->pLeft) );
6538 sqlite3ExprAnalyzeAggList(pNC, pExpr->pLeft->x.pList);
6540 #ifndef SQLITE_OMIT_WINDOWFUNC
6541 assert( !IsWindowFunc(pExpr) );
6542 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6543 sqlite3ExprAnalyzeAggregates(pNC, pExpr->y.pWin->pFilter);
6545 #endif
6547 pNC->ncFlags &= ~NC_InAggFunc;
6551 ** An index on expressions is being used in the inner loop of an
6552 ** aggregate query with a GROUP BY clause. This routine attempts
6553 ** to adjust the AggInfo object to take advantage of index and to
6554 ** perhaps use the index as a covering index.
6557 static void optimizeAggregateUseOfIndexedExpr(
6558 Parse *pParse, /* Parsing context */
6559 Select *pSelect, /* The SELECT statement being processed */
6560 AggInfo *pAggInfo, /* The aggregate info */
6561 NameContext *pNC /* Name context used to resolve agg-func args */
6563 assert( pAggInfo->iFirstReg==0 );
6564 assert( pSelect!=0 );
6565 assert( pSelect->pGroupBy!=0 );
6566 pAggInfo->nColumn = pAggInfo->nAccumulator;
6567 if( ALWAYS(pAggInfo->nSortingColumn>0) ){
6568 int mx = pSelect->pGroupBy->nExpr - 1;
6569 int j, k;
6570 for(j=0; j<pAggInfo->nColumn; j++){
6571 k = pAggInfo->aCol[j].iSorterColumn;
6572 if( k>mx ) mx = k;
6574 pAggInfo->nSortingColumn = mx+1;
6576 analyzeAggFuncArgs(pAggInfo, pNC);
6577 #if TREETRACE_ENABLED
6578 if( sqlite3TreeTrace & 0x20 ){
6579 IndexedExpr *pIEpr;
6580 TREETRACE(0x20, pParse, pSelect,
6581 ("AggInfo (possibly) adjusted for Indexed Exprs\n"));
6582 sqlite3TreeViewSelect(0, pSelect, 0);
6583 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6584 printf("data-cursor=%d index={%d,%d}\n",
6585 pIEpr->iDataCur, pIEpr->iIdxCur, pIEpr->iIdxCol);
6586 sqlite3TreeViewExpr(0, pIEpr->pExpr, 0);
6588 printAggInfo(pAggInfo);
6590 #else
6591 UNUSED_PARAMETER(pSelect);
6592 UNUSED_PARAMETER(pParse);
6593 #endif
6597 ** Walker callback for aggregateConvertIndexedExprRefToColumn().
6599 static int aggregateIdxEprRefToColCallback(Walker *pWalker, Expr *pExpr){
6600 AggInfo *pAggInfo;
6601 struct AggInfo_col *pCol;
6602 UNUSED_PARAMETER(pWalker);
6603 if( pExpr->pAggInfo==0 ) return WRC_Continue;
6604 if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
6605 if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
6606 if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
6607 pAggInfo = pExpr->pAggInfo;
6608 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
6609 assert( pExpr->iAgg>=0 );
6610 pCol = &pAggInfo->aCol[pExpr->iAgg];
6611 pExpr->op = TK_AGG_COLUMN;
6612 pExpr->iTable = pCol->iTable;
6613 pExpr->iColumn = pCol->iColumn;
6614 ExprClearProperty(pExpr, EP_Skip|EP_Collate|EP_Unlikely);
6615 return WRC_Prune;
6619 ** Convert every pAggInfo->aFunc[].pExpr such that any node within
6620 ** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
6621 ** opcode.
6623 static void aggregateConvertIndexedExprRefToColumn(AggInfo *pAggInfo){
6624 int i;
6625 Walker w;
6626 memset(&w, 0, sizeof(w));
6627 w.xExprCallback = aggregateIdxEprRefToColCallback;
6628 for(i=0; i<pAggInfo->nFunc; i++){
6629 sqlite3WalkExpr(&w, pAggInfo->aFunc[i].pFExpr);
6635 ** Allocate a block of registers so that there is one register for each
6636 ** pAggInfo->aCol[] and pAggInfo->aFunc[] entry in pAggInfo. The first
6637 ** register in this block is stored in pAggInfo->iFirstReg.
6639 ** This routine may only be called once for each AggInfo object. Prior
6640 ** to calling this routine:
6642 ** * The aCol[] and aFunc[] arrays may be modified
6643 ** * The AggInfoColumnReg() and AggInfoFuncReg() macros may not be used
6645 ** After calling this routine:
6647 ** * The aCol[] and aFunc[] arrays are fixed
6648 ** * The AggInfoColumnReg() and AggInfoFuncReg() macros may be used
6651 static void assignAggregateRegisters(Parse *pParse, AggInfo *pAggInfo){
6652 assert( pAggInfo!=0 );
6653 assert( pAggInfo->iFirstReg==0 );
6654 pAggInfo->iFirstReg = pParse->nMem + 1;
6655 pParse->nMem += pAggInfo->nColumn + pAggInfo->nFunc;
6659 ** Reset the aggregate accumulator.
6661 ** The aggregate accumulator is a set of memory cells that hold
6662 ** intermediate results while calculating an aggregate. This
6663 ** routine generates code that stores NULLs in all of those memory
6664 ** cells.
6666 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
6667 Vdbe *v = pParse->pVdbe;
6668 int i;
6669 struct AggInfo_func *pFunc;
6670 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
6671 assert( pAggInfo->iFirstReg>0 );
6672 assert( pParse->db->pParse==pParse );
6673 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
6674 if( nReg==0 ) return;
6675 if( pParse->nErr ) return;
6676 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
6677 pAggInfo->iFirstReg+nReg-1);
6678 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
6679 if( pFunc->iDistinct>=0 ){
6680 Expr *pE = pFunc->pFExpr;
6681 assert( ExprUseXList(pE) );
6682 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
6683 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
6684 "argument");
6685 pFunc->iDistinct = -1;
6686 }else{
6687 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
6688 pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6689 pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
6690 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
6691 pFunc->pFunc->zName));
6694 if( pFunc->iOBTab>=0 ){
6695 ExprList *pOBList;
6696 KeyInfo *pKeyInfo;
6697 int nExtra = 0;
6698 assert( pFunc->pFExpr->pLeft!=0 );
6699 assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
6700 assert( ExprUseXList(pFunc->pFExpr->pLeft) );
6701 assert( pFunc->pFunc!=0 );
6702 pOBList = pFunc->pFExpr->pLeft->x.pList;
6703 if( !pFunc->bOBUnique ){
6704 nExtra++; /* One extra column for the OP_Sequence */
6706 if( pFunc->bOBPayload ){
6707 /* extra columns for the function arguments */
6708 assert( ExprUseXList(pFunc->pFExpr) );
6709 nExtra += pFunc->pFExpr->x.pList->nExpr;
6711 if( pFunc->bUseSubtype ){
6712 nExtra += pFunc->pFExpr->x.pList->nExpr;
6714 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOBList, 0, nExtra);
6715 if( !pFunc->bOBUnique && pParse->nErr==0 ){
6716 pKeyInfo->nKeyField++;
6718 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6719 pFunc->iOBTab, pOBList->nExpr+nExtra, 0,
6720 (char*)pKeyInfo, P4_KEYINFO);
6721 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(ORDER BY)",
6722 pFunc->pFunc->zName));
6728 ** Invoke the OP_AggFinalize opcode for every aggregate function
6729 ** in the AggInfo structure.
6731 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
6732 Vdbe *v = pParse->pVdbe;
6733 int i;
6734 struct AggInfo_func *pF;
6735 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6736 ExprList *pList;
6737 assert( ExprUseXList(pF->pFExpr) );
6738 pList = pF->pFExpr->x.pList;
6739 if( pF->iOBTab>=0 ){
6740 /* For an ORDER BY aggregate, calls to OP_AggStep were deferred. Inputs
6741 ** were stored in emphermal table pF->iOBTab. Here, we extract those
6742 ** inputs (in ORDER BY order) and make all calls to OP_AggStep
6743 ** before doing the OP_AggFinal call. */
6744 int iTop; /* Start of loop for extracting columns */
6745 int nArg; /* Number of columns to extract */
6746 int nKey; /* Key columns to be skipped */
6747 int regAgg; /* Extract into this array */
6748 int j; /* Loop counter */
6750 assert( pF->pFunc!=0 );
6751 nArg = pList->nExpr;
6752 regAgg = sqlite3GetTempRange(pParse, nArg);
6754 if( pF->bOBPayload==0 ){
6755 nKey = 0;
6756 }else{
6757 assert( pF->pFExpr->pLeft!=0 );
6758 assert( ExprUseXList(pF->pFExpr->pLeft) );
6759 assert( pF->pFExpr->pLeft->x.pList!=0 );
6760 nKey = pF->pFExpr->pLeft->x.pList->nExpr;
6761 if( ALWAYS(!pF->bOBUnique) ) nKey++;
6763 iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
6764 for(j=nArg-1; j>=0; j--){
6765 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
6767 if( pF->bUseSubtype ){
6768 int regSubtype = sqlite3GetTempReg(pParse);
6769 int iBaseCol = nKey + nArg + (pF->bOBPayload==0 && pF->bOBUnique==0);
6770 for(j=nArg-1; j>=0; j--){
6771 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, iBaseCol+j, regSubtype);
6772 sqlite3VdbeAddOp2(v, OP_SetSubtype, regSubtype, regAgg+j);
6774 sqlite3ReleaseTempReg(pParse, regSubtype);
6776 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
6777 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6778 sqlite3VdbeChangeP5(v, (u8)nArg);
6779 sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
6780 sqlite3VdbeJumpHere(v, iTop);
6781 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6783 sqlite3VdbeAddOp2(v, OP_AggFinal, AggInfoFuncReg(pAggInfo,i),
6784 pList ? pList->nExpr : 0);
6785 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6790 ** Generate code that will update the accumulator memory cells for an
6791 ** aggregate based on the current cursor position.
6793 ** If regAcc is non-zero and there are no min() or max() aggregates
6794 ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
6795 ** registers if register regAcc contains 0. The caller will take care
6796 ** of setting and clearing regAcc.
6798 ** For an ORDER BY aggregate, the actual accumulator memory cell update
6799 ** is deferred until after all input rows have been received, so that they
6800 ** can be run in the requested order. In that case, instead of invoking
6801 ** OP_AggStep to update the accumulator, just add the arguments that would
6802 ** have been passed into OP_AggStep into the sorting ephemeral table
6803 ** (along with the appropriate sort key).
6805 static void updateAccumulator(
6806 Parse *pParse,
6807 int regAcc,
6808 AggInfo *pAggInfo,
6809 int eDistinctType
6811 Vdbe *v = pParse->pVdbe;
6812 int i;
6813 int regHit = 0;
6814 int addrHitTest = 0;
6815 struct AggInfo_func *pF;
6816 struct AggInfo_col *pC;
6818 assert( pAggInfo->iFirstReg>0 );
6819 if( pParse->nErr ) return;
6820 pAggInfo->directMode = 1;
6821 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6822 int nArg;
6823 int addrNext = 0;
6824 int regAgg;
6825 int regAggSz = 0;
6826 int regDistinct = 0;
6827 ExprList *pList;
6828 assert( ExprUseXList(pF->pFExpr) );
6829 assert( !IsWindowFunc(pF->pFExpr) );
6830 assert( pF->pFunc!=0 );
6831 pList = pF->pFExpr->x.pList;
6832 if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
6833 Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
6834 if( pAggInfo->nAccumulator
6835 && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
6836 && regAcc
6838 /* If regAcc==0, there there exists some min() or max() function
6839 ** without a FILTER clause that will ensure the magnet registers
6840 ** are populated. */
6841 if( regHit==0 ) regHit = ++pParse->nMem;
6842 /* If this is the first row of the group (regAcc contains 0), clear the
6843 ** "magnet" register regHit so that the accumulator registers
6844 ** are populated if the FILTER clause jumps over the the
6845 ** invocation of min() or max() altogether. Or, if this is not
6846 ** the first row (regAcc contains 1), set the magnet register so that
6847 ** the accumulators are not populated unless the min()/max() is invoked
6848 ** and indicates that they should be. */
6849 sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
6851 addrNext = sqlite3VdbeMakeLabel(pParse);
6852 sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
6854 if( pF->iOBTab>=0 ){
6855 /* Instead of invoking AggStep, we must push the arguments that would
6856 ** have been passed to AggStep onto the sorting table. */
6857 int jj; /* Registered used so far in building the record */
6858 ExprList *pOBList; /* The ORDER BY clause */
6859 assert( pList!=0 );
6860 nArg = pList->nExpr;
6861 assert( nArg>0 );
6862 assert( pF->pFExpr->pLeft!=0 );
6863 assert( pF->pFExpr->pLeft->op==TK_ORDER );
6864 assert( ExprUseXList(pF->pFExpr->pLeft) );
6865 pOBList = pF->pFExpr->pLeft->x.pList;
6866 assert( pOBList!=0 );
6867 assert( pOBList->nExpr>0 );
6868 regAggSz = pOBList->nExpr;
6869 if( !pF->bOBUnique ){
6870 regAggSz++; /* One register for OP_Sequence */
6872 if( pF->bOBPayload ){
6873 regAggSz += nArg;
6875 if( pF->bUseSubtype ){
6876 regAggSz += nArg;
6878 regAggSz++; /* One extra register to hold result of MakeRecord */
6879 regAgg = sqlite3GetTempRange(pParse, regAggSz);
6880 regDistinct = regAgg;
6881 sqlite3ExprCodeExprList(pParse, pOBList, regAgg, 0, SQLITE_ECEL_DUP);
6882 jj = pOBList->nExpr;
6883 if( !pF->bOBUnique ){
6884 sqlite3VdbeAddOp2(v, OP_Sequence, pF->iOBTab, regAgg+jj);
6885 jj++;
6887 if( pF->bOBPayload ){
6888 regDistinct = regAgg+jj;
6889 sqlite3ExprCodeExprList(pParse, pList, regDistinct, 0, SQLITE_ECEL_DUP);
6890 jj += nArg;
6892 if( pF->bUseSubtype ){
6893 int kk;
6894 int regBase = pF->bOBPayload ? regDistinct : regAgg;
6895 for(kk=0; kk<nArg; kk++, jj++){
6896 sqlite3VdbeAddOp2(v, OP_GetSubtype, regBase+kk, regAgg+jj);
6899 }else if( pList ){
6900 nArg = pList->nExpr;
6901 regAgg = sqlite3GetTempRange(pParse, nArg);
6902 regDistinct = regAgg;
6903 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
6904 }else{
6905 nArg = 0;
6906 regAgg = 0;
6908 if( pF->iDistinct>=0 && pList ){
6909 if( addrNext==0 ){
6910 addrNext = sqlite3VdbeMakeLabel(pParse);
6912 pF->iDistinct = codeDistinct(pParse, eDistinctType,
6913 pF->iDistinct, addrNext, pList, regDistinct);
6915 if( pF->iOBTab>=0 ){
6916 /* Insert a new record into the ORDER BY table */
6917 sqlite3VdbeAddOp3(v, OP_MakeRecord, regAgg, regAggSz-1,
6918 regAgg+regAggSz-1);
6919 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pF->iOBTab, regAgg+regAggSz-1,
6920 regAgg, regAggSz-1);
6921 sqlite3ReleaseTempRange(pParse, regAgg, regAggSz);
6922 }else{
6923 /* Invoke the AggStep function */
6924 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
6925 CollSeq *pColl = 0;
6926 struct ExprList_item *pItem;
6927 int j;
6928 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
6929 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
6930 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
6932 if( !pColl ){
6933 pColl = pParse->db->pDfltColl;
6935 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
6936 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0,
6937 (char *)pColl, P4_COLLSEQ);
6939 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
6940 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6941 sqlite3VdbeChangeP5(v, (u8)nArg);
6942 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6944 if( addrNext ){
6945 sqlite3VdbeResolveLabel(v, addrNext);
6948 if( regHit==0 && pAggInfo->nAccumulator ){
6949 regHit = regAcc;
6951 if( regHit ){
6952 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
6954 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
6955 sqlite3ExprCode(pParse, pC->pCExpr, AggInfoColumnReg(pAggInfo,i));
6958 pAggInfo->directMode = 0;
6959 if( addrHitTest ){
6960 sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
6965 ** Add a single OP_Explain instruction to the VDBE to explain a simple
6966 ** count(*) query ("SELECT count(*) FROM pTab").
6968 #ifndef SQLITE_OMIT_EXPLAIN
6969 static void explainSimpleCount(
6970 Parse *pParse, /* Parse context */
6971 Table *pTab, /* Table being queried */
6972 Index *pIdx /* Index used to optimize scan, or NULL */
6974 if( pParse->explain==2 ){
6975 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
6976 sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
6977 pTab->zName,
6978 bCover ? " USING COVERING INDEX " : "",
6979 bCover ? pIdx->zName : ""
6983 #else
6984 # define explainSimpleCount(a,b,c)
6985 #endif
6988 ** sqlite3WalkExpr() callback used by havingToWhere().
6990 ** If the node passed to the callback is a TK_AND node, return
6991 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
6993 ** Otherwise, return WRC_Prune. In this case, also check if the
6994 ** sub-expression matches the criteria for being moved to the WHERE
6995 ** clause. If so, add it to the WHERE clause and replace the sub-expression
6996 ** within the HAVING expression with a constant "1".
6998 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
6999 if( pExpr->op!=TK_AND ){
7000 Select *pS = pWalker->u.pSelect;
7001 /* This routine is called before the HAVING clause of the current
7002 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
7003 ** here, it indicates that the expression is a correlated reference to a
7004 ** column from an outer aggregate query, or an aggregate function that
7005 ** belongs to an outer query. Do not move the expression to the WHERE
7006 ** clause in this obscure case, as doing so may corrupt the outer Select
7007 ** statements AggInfo structure. */
7008 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
7009 && ExprAlwaysFalse(pExpr)==0
7010 && pExpr->pAggInfo==0
7012 sqlite3 *db = pWalker->pParse->db;
7013 Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
7014 if( pNew ){
7015 Expr *pWhere = pS->pWhere;
7016 SWAP(Expr, *pNew, *pExpr);
7017 pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
7018 pS->pWhere = pNew;
7019 pWalker->eCode = 1;
7022 return WRC_Prune;
7024 return WRC_Continue;
7028 ** Transfer eligible terms from the HAVING clause of a query, which is
7029 ** processed after grouping, to the WHERE clause, which is processed before
7030 ** grouping. For example, the query:
7032 ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
7034 ** can be rewritten as:
7036 ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
7038 ** A term of the HAVING expression is eligible for transfer if it consists
7039 ** entirely of constants and expressions that are also GROUP BY terms that
7040 ** use the "BINARY" collation sequence.
7042 static void havingToWhere(Parse *pParse, Select *p){
7043 Walker sWalker;
7044 memset(&sWalker, 0, sizeof(sWalker));
7045 sWalker.pParse = pParse;
7046 sWalker.xExprCallback = havingToWhereExprCb;
7047 sWalker.u.pSelect = p;
7048 sqlite3WalkExpr(&sWalker, p->pHaving);
7049 #if TREETRACE_ENABLED
7050 if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
7051 TREETRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
7052 sqlite3TreeViewSelect(0, p, 0);
7054 #endif
7058 ** Check to see if the pThis entry of pTabList is a self-join of another view.
7059 ** Search FROM-clause entries in the range of iFirst..iEnd, including iFirst
7060 ** but stopping before iEnd.
7062 ** If pThis is a self-join, then return the SrcItem for the first other
7063 ** instance of that view found. If pThis is not a self-join then return 0.
7065 static SrcItem *isSelfJoinView(
7066 SrcList *pTabList, /* Search for self-joins in this FROM clause */
7067 SrcItem *pThis, /* Search for prior reference to this subquery */
7068 int iFirst, int iEnd /* Range of FROM-clause entries to search. */
7070 SrcItem *pItem;
7071 assert( pThis->pSelect!=0 );
7072 if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
7073 while( iFirst<iEnd ){
7074 Select *pS1;
7075 pItem = &pTabList->a[iFirst++];
7076 if( pItem->pSelect==0 ) continue;
7077 if( pItem->fg.viaCoroutine ) continue;
7078 if( pItem->zName==0 ) continue;
7079 assert( pItem->pTab!=0 );
7080 assert( pThis->pTab!=0 );
7081 if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
7082 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
7083 pS1 = pItem->pSelect;
7084 if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
7085 /* The query flattener left two different CTE tables with identical
7086 ** names in the same FROM clause. */
7087 continue;
7089 if( pItem->pSelect->selFlags & SF_PushDown ){
7090 /* The view was modified by some other optimization such as
7091 ** pushDownWhereTerms() */
7092 continue;
7094 return pItem;
7096 return 0;
7100 ** Deallocate a single AggInfo object
7102 static void agginfoFree(sqlite3 *db, void *pArg){
7103 AggInfo *p = (AggInfo*)pArg;
7104 sqlite3DbFree(db, p->aCol);
7105 sqlite3DbFree(db, p->aFunc);
7106 sqlite3DbFreeNN(db, p);
7110 ** Attempt to transform a query of the form
7112 ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
7114 ** Into this:
7116 ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
7118 ** The transformation only works if all of the following are true:
7120 ** * The subquery is a UNION ALL of two or more terms
7121 ** * The subquery does not have a LIMIT clause
7122 ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
7123 ** * The outer query is a simple count(*) with no WHERE clause or other
7124 ** extraneous syntax.
7126 ** Return TRUE if the optimization is undertaken.
7128 static int countOfViewOptimization(Parse *pParse, Select *p){
7129 Select *pSub, *pPrior;
7130 Expr *pExpr;
7131 Expr *pCount;
7132 sqlite3 *db;
7133 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
7134 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
7135 if( p->pWhere ) return 0;
7136 if( p->pHaving ) return 0;
7137 if( p->pGroupBy ) return 0;
7138 if( p->pOrderBy ) return 0;
7139 pExpr = p->pEList->a[0].pExpr;
7140 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
7141 assert( ExprUseUToken(pExpr) );
7142 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
7143 assert( ExprUseXList(pExpr) );
7144 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
7145 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
7146 if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
7147 pSub = p->pSrc->a[0].pSelect;
7148 if( pSub==0 ) return 0; /* The FROM is a subquery */
7149 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
7150 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
7152 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
7153 if( pSub->pWhere ) return 0; /* No WHERE clause */
7154 if( pSub->pLimit ) return 0; /* No LIMIT clause */
7155 if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
7156 assert( pSub->pHaving==0 ); /* Due to the previous */
7157 pSub = pSub->pPrior; /* Repeat over compound */
7158 }while( pSub );
7160 /* If we reach this point then it is OK to perform the transformation */
7162 db = pParse->db;
7163 pCount = pExpr;
7164 pExpr = 0;
7165 pSub = p->pSrc->a[0].pSelect;
7166 p->pSrc->a[0].pSelect = 0;
7167 sqlite3SrcListDelete(db, p->pSrc);
7168 p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
7169 while( pSub ){
7170 Expr *pTerm;
7171 pPrior = pSub->pPrior;
7172 pSub->pPrior = 0;
7173 pSub->pNext = 0;
7174 pSub->selFlags |= SF_Aggregate;
7175 pSub->selFlags &= ~SF_Compound;
7176 pSub->nSelectRow = 0;
7177 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList);
7178 pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
7179 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
7180 pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
7181 sqlite3PExprAddSelect(pParse, pTerm, pSub);
7182 if( pExpr==0 ){
7183 pExpr = pTerm;
7184 }else{
7185 pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
7187 pSub = pPrior;
7189 p->pEList->a[0].pExpr = pExpr;
7190 p->selFlags &= ~SF_Aggregate;
7192 #if TREETRACE_ENABLED
7193 if( sqlite3TreeTrace & 0x200 ){
7194 TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
7195 sqlite3TreeViewSelect(0, p, 0);
7197 #endif
7198 return 1;
7202 ** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
7203 ** as pSrcItem but has the same alias as p0, then return true.
7204 ** Otherwise return false.
7206 static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
7207 int i;
7208 for(i=0; i<pSrc->nSrc; i++){
7209 SrcItem *p1 = &pSrc->a[i];
7210 if( p1==p0 ) continue;
7211 if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
7212 return 1;
7214 if( p1->pSelect
7215 && (p1->pSelect->selFlags & SF_NestedFrom)!=0
7216 && sameSrcAlias(p0, p1->pSelect->pSrc)
7218 return 1;
7221 return 0;
7225 ** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
7226 ** be implemented as a co-routine. The i-th entry is guaranteed to be
7227 ** a subquery.
7229 ** The subquery is implemented as a co-routine if all of the following are
7230 ** true:
7232 ** (1) The subquery will likely be implemented in the outer loop of
7233 ** the query. This will be the case if any one of the following
7234 ** conditions hold:
7235 ** (a) The subquery is the only term in the FROM clause
7236 ** (b) The subquery is the left-most term and a CROSS JOIN or similar
7237 ** requires it to be the outer loop
7238 ** (c) All of the following are true:
7239 ** (i) The subquery is the left-most subquery in the FROM clause
7240 ** (ii) There is nothing that would prevent the subquery from
7241 ** being used as the outer loop if the sqlite3WhereBegin()
7242 ** routine nominates it to that position.
7243 ** (iii) The query is not a UPDATE ... FROM
7244 ** (2) The subquery is not a CTE that should be materialized because
7245 ** (a) the AS MATERIALIZED keyword is used, or
7246 ** (b) the CTE is used multiple times and does not have the
7247 ** NOT MATERIALIZED keyword
7248 ** (3) The subquery is not part of a left operand for a RIGHT JOIN
7249 ** (4) The SQLITE_Coroutine optimization disable flag is not set
7250 ** (5) The subquery is not self-joined
7252 static int fromClauseTermCanBeCoroutine(
7253 Parse *pParse, /* Parsing context */
7254 SrcList *pTabList, /* FROM clause */
7255 int i, /* Which term of the FROM clause holds the subquery */
7256 int selFlags /* Flags on the SELECT statement */
7258 SrcItem *pItem = &pTabList->a[i];
7259 if( pItem->fg.isCte ){
7260 const CteUse *pCteUse = pItem->u2.pCteUse;
7261 if( pCteUse->eM10d==M10d_Yes ) return 0; /* (2a) */
7262 if( pCteUse->nUse>=2 && pCteUse->eM10d!=M10d_No ) return 0; /* (2b) */
7264 if( pTabList->a[0].fg.jointype & JT_LTORJ ) return 0; /* (3) */
7265 if( OptimizationDisabled(pParse->db, SQLITE_Coroutines) ) return 0; /* (4) */
7266 if( isSelfJoinView(pTabList, pItem, i+1, pTabList->nSrc)!=0 ){
7267 return 0; /* (5) */
7269 if( i==0 ){
7270 if( pTabList->nSrc==1 ) return 1; /* (1a) */
7271 if( pTabList->a[1].fg.jointype & JT_CROSS ) return 1; /* (1b) */
7272 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7273 return 1;
7275 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7276 while( 1 /*exit-by-break*/ ){
7277 if( pItem->fg.jointype & (JT_OUTER|JT_CROSS) ) return 0; /* (1c-ii) */
7278 if( i==0 ) break;
7279 i--;
7280 pItem--;
7281 if( pItem->pSelect!=0 ) return 0; /* (1c-i) */
7283 return 1;
7287 ** Generate code for the SELECT statement given in the p argument.
7289 ** The results are returned according to the SelectDest structure.
7290 ** See comments in sqliteInt.h for further information.
7292 ** This routine returns the number of errors. If any errors are
7293 ** encountered, then an appropriate error message is left in
7294 ** pParse->zErrMsg.
7296 ** This routine does NOT free the Select structure passed in. The
7297 ** calling function needs to do that.
7299 int sqlite3Select(
7300 Parse *pParse, /* The parser context */
7301 Select *p, /* The SELECT statement being coded. */
7302 SelectDest *pDest /* What to do with the query results */
7304 int i, j; /* Loop counters */
7305 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
7306 Vdbe *v; /* The virtual machine under construction */
7307 int isAgg; /* True for select lists like "count(*)" */
7308 ExprList *pEList = 0; /* List of columns to extract. */
7309 SrcList *pTabList; /* List of tables to select from */
7310 Expr *pWhere; /* The WHERE clause. May be NULL */
7311 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
7312 Expr *pHaving; /* The HAVING clause. May be NULL */
7313 AggInfo *pAggInfo = 0; /* Aggregate information */
7314 int rc = 1; /* Value to return from this function */
7315 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
7316 SortCtx sSort; /* Info on how to code the ORDER BY clause */
7317 int iEnd; /* Address of the end of the query */
7318 sqlite3 *db; /* The database connection */
7319 ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
7320 u8 minMaxFlag; /* Flag for min/max queries */
7322 db = pParse->db;
7323 assert( pParse==db->pParse );
7324 v = sqlite3GetVdbe(pParse);
7325 if( p==0 || pParse->nErr ){
7326 return 1;
7328 assert( db->mallocFailed==0 );
7329 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
7330 #if TREETRACE_ENABLED
7331 TREETRACE(0x1,pParse,p, ("begin processing:\n", pParse->addrExplain));
7332 if( sqlite3TreeTrace & 0x10000 ){
7333 if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
7334 sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
7335 __FILE__, __LINE__);
7337 sqlite3ShowSelect(p);
7339 #endif
7341 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
7342 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
7343 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
7344 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
7345 if( IgnorableDistinct(pDest) ){
7346 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
7347 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
7348 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
7349 /* All of these destinations are also able to ignore the ORDER BY clause */
7350 if( p->pOrderBy ){
7351 #if TREETRACE_ENABLED
7352 TREETRACE(0x800,pParse,p, ("dropping superfluous ORDER BY:\n"));
7353 if( sqlite3TreeTrace & 0x800 ){
7354 sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
7356 #endif
7357 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
7358 p->pOrderBy);
7359 testcase( pParse->earlyCleanup );
7360 p->pOrderBy = 0;
7362 p->selFlags &= ~SF_Distinct;
7363 p->selFlags |= SF_NoopOrderBy;
7365 sqlite3SelectPrep(pParse, p, 0);
7366 if( pParse->nErr ){
7367 goto select_end;
7369 assert( db->mallocFailed==0 );
7370 assert( p->pEList!=0 );
7371 #if TREETRACE_ENABLED
7372 if( sqlite3TreeTrace & 0x10 ){
7373 TREETRACE(0x10,pParse,p, ("after name resolution:\n"));
7374 sqlite3TreeViewSelect(0, p, 0);
7376 #endif
7378 /* If the SF_UFSrcCheck flag is set, then this function is being called
7379 ** as part of populating the temp table for an UPDATE...FROM statement.
7380 ** In this case, it is an error if the target object (pSrc->a[0]) name
7381 ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
7383 ** Postgres disallows this case too. The reason is that some other
7384 ** systems handle this case differently, and not all the same way,
7385 ** which is just confusing. To avoid this, we follow PG's lead and
7386 ** disallow it altogether. */
7387 if( p->selFlags & SF_UFSrcCheck ){
7388 SrcItem *p0 = &p->pSrc->a[0];
7389 if( sameSrcAlias(p0, p->pSrc) ){
7390 sqlite3ErrorMsg(pParse,
7391 "target object/alias may not appear in FROM clause: %s",
7392 p0->zAlias ? p0->zAlias : p0->pTab->zName
7394 goto select_end;
7397 /* Clear the SF_UFSrcCheck flag. The check has already been performed,
7398 ** and leaving this flag set can cause errors if a compound sub-query
7399 ** in p->pSrc is flattened into this query and this function called
7400 ** again as part of compound SELECT processing. */
7401 p->selFlags &= ~SF_UFSrcCheck;
7404 if( pDest->eDest==SRT_Output ){
7405 sqlite3GenerateColumnNames(pParse, p);
7408 #ifndef SQLITE_OMIT_WINDOWFUNC
7409 if( sqlite3WindowRewrite(pParse, p) ){
7410 assert( pParse->nErr );
7411 goto select_end;
7413 #if TREETRACE_ENABLED
7414 if( p->pWin && (sqlite3TreeTrace & 0x40)!=0 ){
7415 TREETRACE(0x40,pParse,p, ("after window rewrite:\n"));
7416 sqlite3TreeViewSelect(0, p, 0);
7418 #endif
7419 #endif /* SQLITE_OMIT_WINDOWFUNC */
7420 pTabList = p->pSrc;
7421 isAgg = (p->selFlags & SF_Aggregate)!=0;
7422 memset(&sSort, 0, sizeof(sSort));
7423 sSort.pOrderBy = p->pOrderBy;
7425 /* Try to do various optimizations (flattening subqueries, and strength
7426 ** reduction of join operators) in the FROM clause up into the main query
7428 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7429 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
7430 SrcItem *pItem = &pTabList->a[i];
7431 Select *pSub = pItem->pSelect;
7432 Table *pTab = pItem->pTab;
7434 /* The expander should have already created transient Table objects
7435 ** even for FROM clause elements such as subqueries that do not correspond
7436 ** to a real table */
7437 assert( pTab!=0 );
7439 /* Try to simplify joins:
7441 ** LEFT JOIN -> JOIN
7442 ** RIGHT JOIN -> JOIN
7443 ** FULL JOIN -> RIGHT JOIN
7445 ** If terms of the i-th table are used in the WHERE clause in such a
7446 ** way that the i-th table cannot be the NULL row of a join, then
7447 ** perform the appropriate simplification. This is called
7448 ** "OUTER JOIN strength reduction" in the SQLite documentation.
7450 if( (pItem->fg.jointype & (JT_LEFT|JT_LTORJ))!=0
7451 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor,
7452 pItem->fg.jointype & JT_LTORJ)
7453 && OptimizationEnabled(db, SQLITE_SimplifyJoin)
7455 if( pItem->fg.jointype & JT_LEFT ){
7456 if( pItem->fg.jointype & JT_RIGHT ){
7457 TREETRACE(0x1000,pParse,p,
7458 ("FULL-JOIN simplifies to RIGHT-JOIN on term %d\n",i));
7459 pItem->fg.jointype &= ~JT_LEFT;
7460 }else{
7461 TREETRACE(0x1000,pParse,p,
7462 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
7463 pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
7464 unsetJoinExpr(p->pWhere, pItem->iCursor, 0);
7467 if( pItem->fg.jointype & JT_LTORJ ){
7468 for(j=i+1; j<pTabList->nSrc; j++){
7469 SrcItem *pI2 = &pTabList->a[j];
7470 if( pI2->fg.jointype & JT_RIGHT ){
7471 if( pI2->fg.jointype & JT_LEFT ){
7472 TREETRACE(0x1000,pParse,p,
7473 ("FULL-JOIN simplifies to LEFT-JOIN on term %d\n",j));
7474 pI2->fg.jointype &= ~JT_RIGHT;
7475 }else{
7476 TREETRACE(0x1000,pParse,p,
7477 ("RIGHT-JOIN simplifies to JOIN on term %d\n",j));
7478 pI2->fg.jointype &= ~(JT_RIGHT|JT_OUTER);
7479 unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
7483 for(j=pTabList->nSrc-1; j>=0; j--){
7484 pTabList->a[j].fg.jointype &= ~JT_LTORJ;
7485 if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
7490 /* No further action if this term of the FROM clause is not a subquery */
7491 if( pSub==0 ) continue;
7493 /* Catch mismatch in the declared columns of a view and the number of
7494 ** columns in the SELECT on the RHS */
7495 if( pTab->nCol!=pSub->pEList->nExpr ){
7496 sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
7497 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
7498 goto select_end;
7501 /* Do not attempt the usual optimizations (flattening and ORDER BY
7502 ** elimination) on a MATERIALIZED common table expression because
7503 ** a MATERIALIZED common table expression is an optimization fence.
7505 if( pItem->fg.isCte && pItem->u2.pCteUse->eM10d==M10d_Yes ){
7506 continue;
7509 /* Do not try to flatten an aggregate subquery.
7511 ** Flattening an aggregate subquery is only possible if the outer query
7512 ** is not a join. But if the outer query is not a join, then the subquery
7513 ** will be implemented as a co-routine and there is no advantage to
7514 ** flattening in that case.
7516 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
7517 assert( pSub->pGroupBy==0 );
7519 /* If a FROM-clause subquery has an ORDER BY clause that is not
7520 ** really doing anything, then delete it now so that it does not
7521 ** interfere with query flattening. See the discussion at
7522 ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
7524 ** Beware of these cases where the ORDER BY clause may not be safely
7525 ** omitted:
7527 ** (1) There is also a LIMIT clause
7528 ** (2) The subquery was added to help with window-function
7529 ** processing
7530 ** (3) The subquery is in the FROM clause of an UPDATE
7531 ** (4) The outer query uses an aggregate function other than
7532 ** the built-in count(), min(), or max().
7533 ** (5) The ORDER BY isn't going to accomplish anything because
7534 ** one of:
7535 ** (a) The outer query has a different ORDER BY clause
7536 ** (b) The subquery is part of a join
7537 ** See forum post 062d576715d277c8
7539 ** Also retain the ORDER BY if the OmitOrderBy optimization is disabled.
7541 if( pSub->pOrderBy!=0
7542 && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */
7543 && pSub->pLimit==0 /* Condition (1) */
7544 && (pSub->selFlags & SF_OrderByReqd)==0 /* Condition (2) */
7545 && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
7546 && OptimizationEnabled(db, SQLITE_OmitOrderBy)
7548 TREETRACE(0x800,pParse,p,
7549 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
7550 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
7551 pSub->pOrderBy);
7552 pSub->pOrderBy = 0;
7555 /* If the outer query contains a "complex" result set (that is,
7556 ** if the result set of the outer query uses functions or subqueries)
7557 ** and if the subquery contains an ORDER BY clause and if
7558 ** it will be implemented as a co-routine, then do not flatten. This
7559 ** restriction allows SQL constructs like this:
7561 ** SELECT expensive_function(x)
7562 ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
7564 ** The expensive_function() is only computed on the 10 rows that
7565 ** are output, rather than every row of the table.
7567 ** The requirement that the outer query have a complex result set
7568 ** means that flattening does occur on simpler SQL constraints without
7569 ** the expensive_function() like:
7571 ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
7573 if( pSub->pOrderBy!=0
7574 && i==0
7575 && (p->selFlags & SF_ComplexResult)!=0
7576 && (pTabList->nSrc==1
7577 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
7579 continue;
7582 if( flattenSubquery(pParse, p, i, isAgg) ){
7583 if( pParse->nErr ) goto select_end;
7584 /* This subquery can be absorbed into its parent. */
7585 i = -1;
7587 pTabList = p->pSrc;
7588 if( db->mallocFailed ) goto select_end;
7589 if( !IgnorableOrderby(pDest) ){
7590 sSort.pOrderBy = p->pOrderBy;
7593 #endif
7595 #ifndef SQLITE_OMIT_COMPOUND_SELECT
7596 /* Handle compound SELECT statements using the separate multiSelect()
7597 ** procedure.
7599 if( p->pPrior ){
7600 rc = multiSelect(pParse, p, pDest);
7601 #if TREETRACE_ENABLED
7602 TREETRACE(0x400,pParse,p,("end compound-select processing\n"));
7603 if( (sqlite3TreeTrace & 0x400)!=0 && ExplainQueryPlanParent(pParse)==0 ){
7604 sqlite3TreeViewSelect(0, p, 0);
7606 #endif
7607 if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
7608 return rc;
7610 #endif
7612 /* Do the WHERE-clause constant propagation optimization if this is
7613 ** a join. No need to speed time on this operation for non-join queries
7614 ** as the equivalent optimization will be handled by query planner in
7615 ** sqlite3WhereBegin().
7617 if( p->pWhere!=0
7618 && p->pWhere->op==TK_AND
7619 && OptimizationEnabled(db, SQLITE_PropagateConst)
7620 && propagateConstants(pParse, p)
7622 #if TREETRACE_ENABLED
7623 if( sqlite3TreeTrace & 0x2000 ){
7624 TREETRACE(0x2000,pParse,p,("After constant propagation:\n"));
7625 sqlite3TreeViewSelect(0, p, 0);
7627 #endif
7628 }else{
7629 TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
7632 if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
7633 && countOfViewOptimization(pParse, p)
7635 if( db->mallocFailed ) goto select_end;
7636 pTabList = p->pSrc;
7639 /* For each term in the FROM clause, do two things:
7640 ** (1) Authorized unreferenced tables
7641 ** (2) Generate code for all sub-queries
7643 for(i=0; i<pTabList->nSrc; i++){
7644 SrcItem *pItem = &pTabList->a[i];
7645 SrcItem *pPrior;
7646 SelectDest dest;
7647 Select *pSub;
7648 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7649 const char *zSavedAuthContext;
7650 #endif
7652 /* Issue SQLITE_READ authorizations with a fake column name for any
7653 ** tables that are referenced but from which no values are extracted.
7654 ** Examples of where these kinds of null SQLITE_READ authorizations
7655 ** would occur:
7657 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
7658 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
7660 ** The fake column name is an empty string. It is possible for a table to
7661 ** have a column named by the empty string, in which case there is no way to
7662 ** distinguish between an unreferenced table and an actual reference to the
7663 ** "" column. The original design was for the fake column name to be a NULL,
7664 ** which would be unambiguous. But legacy authorization callbacks might
7665 ** assume the column name is non-NULL and segfault. The use of an empty
7666 ** string for the fake column name seems safer.
7668 if( pItem->colUsed==0 && pItem->zName!=0 ){
7669 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
7672 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7673 /* Generate code for all sub-queries in the FROM clause
7675 pSub = pItem->pSelect;
7676 if( pSub==0 || pItem->addrFillSub!=0 ) continue;
7678 /* The code for a subquery should only be generated once. */
7679 assert( pItem->addrFillSub==0 );
7681 /* Increment Parse.nHeight by the height of the largest expression
7682 ** tree referred to by this, the parent select. The child select
7683 ** may contain expression trees of at most
7684 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
7685 ** more conservative than necessary, but much easier than enforcing
7686 ** an exact limit.
7688 pParse->nHeight += sqlite3SelectExprHeight(p);
7690 /* Make copies of constant WHERE-clause terms in the outer query down
7691 ** inside the subquery. This can help the subquery to run more efficiently.
7693 if( OptimizationEnabled(db, SQLITE_PushDown)
7694 && (pItem->fg.isCte==0
7695 || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
7696 && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
7698 #if TREETRACE_ENABLED
7699 if( sqlite3TreeTrace & 0x4000 ){
7700 TREETRACE(0x4000,pParse,p,
7701 ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
7702 sqlite3TreeViewSelect(0, p, 0);
7704 #endif
7705 assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
7706 }else{
7707 TREETRACE(0x4000,pParse,p,("WHERE-lcause push-down not possible\n"));
7710 /* Convert unused result columns of the subquery into simple NULL
7711 ** expressions, to avoid unneeded searching and computation.
7713 if( OptimizationEnabled(db, SQLITE_NullUnusedCols)
7714 && disableUnusedSubqueryResultColumns(pItem)
7716 #if TREETRACE_ENABLED
7717 if( sqlite3TreeTrace & 0x4000 ){
7718 TREETRACE(0x4000,pParse,p,
7719 ("Change unused result columns to NULL for subquery %d:\n",
7720 pSub->selId));
7721 sqlite3TreeViewSelect(0, p, 0);
7723 #endif
7726 zSavedAuthContext = pParse->zAuthContext;
7727 pParse->zAuthContext = pItem->zName;
7729 /* Generate code to implement the subquery
7731 if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
7732 /* Implement a co-routine that will return a single row of the result
7733 ** set on each invocation.
7735 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
7737 pItem->regReturn = ++pParse->nMem;
7738 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
7739 VdbeComment((v, "%!S", pItem));
7740 pItem->addrFillSub = addrTop;
7741 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
7742 ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
7743 sqlite3Select(pParse, pSub, &dest);
7744 pItem->pTab->nRowLogEst = pSub->nSelectRow;
7745 pItem->fg.viaCoroutine = 1;
7746 pItem->regResult = dest.iSdst;
7747 sqlite3VdbeEndCoroutine(v, pItem->regReturn);
7748 sqlite3VdbeJumpHere(v, addrTop-1);
7749 sqlite3ClearTempRegCache(pParse);
7750 }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
7751 /* This is a CTE for which materialization code has already been
7752 ** generated. Invoke the subroutine to compute the materialization,
7753 ** the make the pItem->iCursor be a copy of the ephemeral table that
7754 ** holds the result of the materialization. */
7755 CteUse *pCteUse = pItem->u2.pCteUse;
7756 sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
7757 if( pItem->iCursor!=pCteUse->iCur ){
7758 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
7759 VdbeComment((v, "%!S", pItem));
7761 pSub->nSelectRow = pCteUse->nRowEst;
7762 }else if( (pPrior = isSelfJoinView(pTabList, pItem, 0, i))!=0 ){
7763 /* This view has already been materialized by a prior entry in
7764 ** this same FROM clause. Reuse it. */
7765 if( pPrior->addrFillSub ){
7766 sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
7768 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
7769 pSub->nSelectRow = pPrior->pSelect->nSelectRow;
7770 }else{
7771 /* Materialize the view. If the view is not correlated, generate a
7772 ** subroutine to do the materialization so that subsequent uses of
7773 ** the same view can reuse the materialization. */
7774 int topAddr;
7775 int onceAddr = 0;
7776 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
7777 int addrExplain;
7778 #endif
7780 pItem->regReturn = ++pParse->nMem;
7781 topAddr = sqlite3VdbeAddOp0(v, OP_Goto);
7782 pItem->addrFillSub = topAddr+1;
7783 pItem->fg.isMaterialized = 1;
7784 if( pItem->fg.isCorrelated==0 ){
7785 /* If the subquery is not correlated and if we are not inside of
7786 ** a trigger, then we only need to compute the value of the subquery
7787 ** once. */
7788 onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
7789 VdbeComment((v, "materialize %!S", pItem));
7790 }else{
7791 VdbeNoopComment((v, "materialize %!S", pItem));
7793 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
7795 ExplainQueryPlan2(addrExplain, (pParse, 1, "MATERIALIZE %!S", pItem));
7796 sqlite3Select(pParse, pSub, &dest);
7797 pItem->pTab->nRowLogEst = pSub->nSelectRow;
7798 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
7799 sqlite3VdbeAddOp2(v, OP_Return, pItem->regReturn, topAddr+1);
7800 VdbeComment((v, "end %!S", pItem));
7801 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
7802 sqlite3VdbeJumpHere(v, topAddr);
7803 sqlite3ClearTempRegCache(pParse);
7804 if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
7805 CteUse *pCteUse = pItem->u2.pCteUse;
7806 pCteUse->addrM9e = pItem->addrFillSub;
7807 pCteUse->regRtn = pItem->regReturn;
7808 pCteUse->iCur = pItem->iCursor;
7809 pCteUse->nRowEst = pSub->nSelectRow;
7812 if( db->mallocFailed ) goto select_end;
7813 pParse->nHeight -= sqlite3SelectExprHeight(p);
7814 pParse->zAuthContext = zSavedAuthContext;
7815 #endif
7818 /* Various elements of the SELECT copied into local variables for
7819 ** convenience */
7820 pEList = p->pEList;
7821 pWhere = p->pWhere;
7822 pGroupBy = p->pGroupBy;
7823 pHaving = p->pHaving;
7824 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
7826 #if TREETRACE_ENABLED
7827 if( sqlite3TreeTrace & 0x8000 ){
7828 TREETRACE(0x8000,pParse,p,("After all FROM-clause analysis:\n"));
7829 sqlite3TreeViewSelect(0, p, 0);
7831 #endif
7833 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
7834 ** if the select-list is the same as the ORDER BY list, then this query
7835 ** can be rewritten as a GROUP BY. In other words, this:
7837 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
7839 ** is transformed to:
7841 ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
7843 ** The second form is preferred as a single index (or temp-table) may be
7844 ** used for both the ORDER BY and DISTINCT processing. As originally
7845 ** written the query must use a temp-table for at least one of the ORDER
7846 ** BY and DISTINCT, and an index or separate temp-table for the other.
7848 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
7849 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
7850 #ifndef SQLITE_OMIT_WINDOWFUNC
7851 && p->pWin==0
7852 #endif
7854 p->selFlags &= ~SF_Distinct;
7855 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
7856 p->selFlags |= SF_Aggregate;
7857 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
7858 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
7859 ** original setting of the SF_Distinct flag, not the current setting */
7860 assert( sDistinct.isTnct );
7861 sDistinct.isTnct = 2;
7863 #if TREETRACE_ENABLED
7864 if( sqlite3TreeTrace & 0x20000 ){
7865 TREETRACE(0x20000,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
7866 sqlite3TreeViewSelect(0, p, 0);
7868 #endif
7871 /* If there is an ORDER BY clause, then create an ephemeral index to
7872 ** do the sorting. But this sorting ephemeral index might end up
7873 ** being unused if the data can be extracted in pre-sorted order.
7874 ** If that is the case, then the OP_OpenEphemeral instruction will be
7875 ** changed to an OP_Noop once we figure out that the sorting index is
7876 ** not needed. The sSort.addrSortIndex variable is used to facilitate
7877 ** that change.
7879 if( sSort.pOrderBy ){
7880 KeyInfo *pKeyInfo;
7881 pKeyInfo = sqlite3KeyInfoFromExprList(
7882 pParse, sSort.pOrderBy, 0, pEList->nExpr);
7883 sSort.iECursor = pParse->nTab++;
7884 sSort.addrSortIndex =
7885 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7886 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
7887 (char*)pKeyInfo, P4_KEYINFO
7889 }else{
7890 sSort.addrSortIndex = -1;
7893 /* If the output is destined for a temporary table, open that table.
7895 if( pDest->eDest==SRT_EphemTab ){
7896 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
7897 if( p->selFlags & SF_NestedFrom ){
7898 /* Delete or NULL-out result columns that will never be used */
7899 int ii;
7900 for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
7901 sqlite3ExprDelete(db, pEList->a[ii].pExpr);
7902 sqlite3DbFree(db, pEList->a[ii].zEName);
7903 pEList->nExpr--;
7905 for(ii=0; ii<pEList->nExpr; ii++){
7906 if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
7911 /* Set the limiter.
7913 iEnd = sqlite3VdbeMakeLabel(pParse);
7914 if( (p->selFlags & SF_FixedLimit)==0 ){
7915 p->nSelectRow = 320; /* 4 billion rows */
7917 if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
7918 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
7919 sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
7920 sSort.sortFlags |= SORTFLAG_UseSorter;
7923 /* Open an ephemeral index to use for the distinct set.
7925 if( p->selFlags & SF_Distinct ){
7926 sDistinct.tabTnct = pParse->nTab++;
7927 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7928 sDistinct.tabTnct, 0, 0,
7929 (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
7930 P4_KEYINFO);
7931 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
7932 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
7933 }else{
7934 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
7937 if( !isAgg && pGroupBy==0 ){
7938 /* No aggregate functions and no GROUP BY clause */
7939 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
7940 | (p->selFlags & SF_FixedLimit);
7941 #ifndef SQLITE_OMIT_WINDOWFUNC
7942 Window *pWin = p->pWin; /* Main window object (or NULL) */
7943 if( pWin ){
7944 sqlite3WindowCodeInit(pParse, p);
7946 #endif
7947 assert( WHERE_USE_LIMIT==SF_FixedLimit );
7950 /* Begin the database scan. */
7951 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
7952 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
7953 p->pEList, p, wctrlFlags, p->nSelectRow);
7954 if( pWInfo==0 ) goto select_end;
7955 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
7956 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
7958 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
7959 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
7961 if( sSort.pOrderBy ){
7962 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
7963 sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
7964 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
7965 sSort.pOrderBy = 0;
7968 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
7970 /* If sorting index that was created by a prior OP_OpenEphemeral
7971 ** instruction ended up not being needed, then change the OP_OpenEphemeral
7972 ** into an OP_Noop.
7974 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
7975 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
7978 assert( p->pEList==pEList );
7979 #ifndef SQLITE_OMIT_WINDOWFUNC
7980 if( pWin ){
7981 int addrGosub = sqlite3VdbeMakeLabel(pParse);
7982 int iCont = sqlite3VdbeMakeLabel(pParse);
7983 int iBreak = sqlite3VdbeMakeLabel(pParse);
7984 int regGosub = ++pParse->nMem;
7986 sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
7988 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
7989 sqlite3VdbeResolveLabel(v, addrGosub);
7990 VdbeNoopComment((v, "inner-loop subroutine"));
7991 sSort.labelOBLopt = 0;
7992 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
7993 sqlite3VdbeResolveLabel(v, iCont);
7994 sqlite3VdbeAddOp1(v, OP_Return, regGosub);
7995 VdbeComment((v, "end inner-loop subroutine"));
7996 sqlite3VdbeResolveLabel(v, iBreak);
7997 }else
7998 #endif /* SQLITE_OMIT_WINDOWFUNC */
8000 /* Use the standard inner loop. */
8001 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
8002 sqlite3WhereContinueLabel(pWInfo),
8003 sqlite3WhereBreakLabel(pWInfo));
8005 /* End the database scan loop.
8007 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8008 sqlite3WhereEnd(pWInfo);
8010 }else{
8011 /* This case when there exist aggregate functions or a GROUP BY clause
8012 ** or both */
8013 NameContext sNC; /* Name context for processing aggregate information */
8014 int iAMem; /* First Mem address for storing current GROUP BY */
8015 int iBMem; /* First Mem address for previous GROUP BY */
8016 int iUseFlag; /* Mem address holding flag indicating that at least
8017 ** one row of the input to the aggregator has been
8018 ** processed */
8019 int iAbortFlag; /* Mem address which causes query abort if positive */
8020 int groupBySort; /* Rows come from source in GROUP BY order */
8021 int addrEnd; /* End of processing for this SELECT */
8022 int sortPTab = 0; /* Pseudotable used to decode sorting results */
8023 int sortOut = 0; /* Output register from the sorter */
8024 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
8026 /* Remove any and all aliases between the result set and the
8027 ** GROUP BY clause.
8029 if( pGroupBy ){
8030 int k; /* Loop counter */
8031 struct ExprList_item *pItem; /* For looping over expression in a list */
8033 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
8034 pItem->u.x.iAlias = 0;
8036 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
8037 pItem->u.x.iAlias = 0;
8039 assert( 66==sqlite3LogEst(100) );
8040 if( p->nSelectRow>66 ) p->nSelectRow = 66;
8042 /* If there is both a GROUP BY and an ORDER BY clause and they are
8043 ** identical, then it may be possible to disable the ORDER BY clause
8044 ** on the grounds that the GROUP BY will cause elements to come out
8045 ** in the correct order. It also may not - the GROUP BY might use a
8046 ** database index that causes rows to be grouped together as required
8047 ** but not actually sorted. Either way, record the fact that the
8048 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
8049 ** variable. */
8050 if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
8051 int ii;
8052 /* The GROUP BY processing doesn't care whether rows are delivered in
8053 ** ASC or DESC order - only that each group is returned contiguously.
8054 ** So set the ASC/DESC flags in the GROUP BY to match those in the
8055 ** ORDER BY to maximize the chances of rows being delivered in an
8056 ** order that makes the ORDER BY redundant. */
8057 for(ii=0; ii<pGroupBy->nExpr; ii++){
8058 u8 sortFlags;
8059 sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
8060 pGroupBy->a[ii].fg.sortFlags = sortFlags;
8062 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
8063 orderByGrp = 1;
8066 }else{
8067 assert( 0==sqlite3LogEst(1) );
8068 p->nSelectRow = 0;
8071 /* Create a label to jump to when we want to abort the query */
8072 addrEnd = sqlite3VdbeMakeLabel(pParse);
8074 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
8075 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
8076 ** SELECT statement.
8078 pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
8079 if( pAggInfo ){
8080 sqlite3ParserAddCleanup(pParse, agginfoFree, pAggInfo);
8081 testcase( pParse->earlyCleanup );
8083 if( db->mallocFailed ){
8084 goto select_end;
8086 pAggInfo->selId = p->selId;
8087 #ifdef SQLITE_DEBUG
8088 pAggInfo->pSelect = p;
8089 #endif
8090 memset(&sNC, 0, sizeof(sNC));
8091 sNC.pParse = pParse;
8092 sNC.pSrcList = pTabList;
8093 sNC.uNC.pAggInfo = pAggInfo;
8094 VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
8095 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
8096 pAggInfo->pGroupBy = pGroupBy;
8097 sqlite3ExprAnalyzeAggList(&sNC, pEList);
8098 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
8099 if( pHaving ){
8100 if( pGroupBy ){
8101 assert( pWhere==p->pWhere );
8102 assert( pHaving==p->pHaving );
8103 assert( pGroupBy==p->pGroupBy );
8104 havingToWhere(pParse, p);
8105 pWhere = p->pWhere;
8107 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
8109 pAggInfo->nAccumulator = pAggInfo->nColumn;
8110 if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
8111 minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
8112 }else{
8113 minMaxFlag = WHERE_ORDERBY_NORMAL;
8115 analyzeAggFuncArgs(pAggInfo, &sNC);
8116 if( db->mallocFailed ) goto select_end;
8117 #if TREETRACE_ENABLED
8118 if( sqlite3TreeTrace & 0x20 ){
8119 TREETRACE(0x20,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
8120 sqlite3TreeViewSelect(0, p, 0);
8121 if( minMaxFlag ){
8122 sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
8123 sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
8125 printAggInfo(pAggInfo);
8127 #endif
8130 /* Processing for aggregates with GROUP BY is very different and
8131 ** much more complex than aggregates without a GROUP BY.
8133 if( pGroupBy ){
8134 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
8135 int addr1; /* A-vs-B comparison jump */
8136 int addrOutputRow; /* Start of subroutine that outputs a result row */
8137 int regOutputRow; /* Return address register for output subroutine */
8138 int addrSetAbort; /* Set the abort flag and return */
8139 int addrTopOfLoop; /* Top of the input loop */
8140 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
8141 int addrReset; /* Subroutine for resetting the accumulator */
8142 int regReset; /* Return address register for reset subroutine */
8143 ExprList *pDistinct = 0;
8144 u16 distFlag = 0;
8145 int eDist = WHERE_DISTINCT_NOOP;
8147 if( pAggInfo->nFunc==1
8148 && pAggInfo->aFunc[0].iDistinct>=0
8149 && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
8150 && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
8151 && pAggInfo->aFunc[0].pFExpr->x.pList!=0
8153 Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
8154 pExpr = sqlite3ExprDup(db, pExpr, 0);
8155 pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
8156 pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
8157 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
8160 /* If there is a GROUP BY clause we might need a sorting index to
8161 ** implement it. Allocate that sorting index now. If it turns out
8162 ** that we do not need it after all, the OP_SorterOpen instruction
8163 ** will be converted into a Noop.
8165 pAggInfo->sortingIdx = pParse->nTab++;
8166 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
8167 0, pAggInfo->nColumn);
8168 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
8169 pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
8170 0, (char*)pKeyInfo, P4_KEYINFO);
8172 /* Initialize memory locations used by GROUP BY aggregate processing
8174 iUseFlag = ++pParse->nMem;
8175 iAbortFlag = ++pParse->nMem;
8176 regOutputRow = ++pParse->nMem;
8177 addrOutputRow = sqlite3VdbeMakeLabel(pParse);
8178 regReset = ++pParse->nMem;
8179 addrReset = sqlite3VdbeMakeLabel(pParse);
8180 iAMem = pParse->nMem + 1;
8181 pParse->nMem += pGroupBy->nExpr;
8182 iBMem = pParse->nMem + 1;
8183 pParse->nMem += pGroupBy->nExpr;
8184 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
8185 VdbeComment((v, "clear abort flag"));
8186 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
8188 /* Begin a loop that will extract all source rows in GROUP BY order.
8189 ** This might involve two separate loops with an OP_Sort in between, or
8190 ** it might be a single loop that uses an index to extract information
8191 ** in the right order to begin with.
8193 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
8194 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8195 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
8196 p, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
8197 | (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
8199 if( pWInfo==0 ){
8200 sqlite3ExprListDelete(db, pDistinct);
8201 goto select_end;
8203 if( pParse->pIdxEpr ){
8204 optimizeAggregateUseOfIndexedExpr(pParse, p, pAggInfo, &sNC);
8206 assignAggregateRegisters(pParse, pAggInfo);
8207 eDist = sqlite3WhereIsDistinct(pWInfo);
8208 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8209 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
8210 /* The optimizer is able to deliver rows in group by order so
8211 ** we do not have to sort. The OP_OpenEphemeral table will be
8212 ** cancelled later because we still need to use the pKeyInfo
8214 groupBySort = 0;
8215 }else{
8216 /* Rows are coming out in undetermined order. We have to push
8217 ** each row into a sorting index, terminate the first loop,
8218 ** then loop over the sorting index in order to get the output
8219 ** in sorted order
8221 int regBase;
8222 int regRecord;
8223 int nCol;
8224 int nGroupBy;
8226 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
8227 int addrExp; /* Address of OP_Explain instruction */
8228 #endif
8229 ExplainQueryPlan2(addrExp, (pParse, 0, "USE TEMP B-TREE FOR %s",
8230 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
8231 "DISTINCT" : "GROUP BY"
8234 groupBySort = 1;
8235 nGroupBy = pGroupBy->nExpr;
8236 nCol = nGroupBy;
8237 j = nGroupBy;
8238 for(i=0; i<pAggInfo->nColumn; i++){
8239 if( pAggInfo->aCol[i].iSorterColumn>=j ){
8240 nCol++;
8241 j++;
8244 regBase = sqlite3GetTempRange(pParse, nCol);
8245 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
8246 j = nGroupBy;
8247 pAggInfo->directMode = 1;
8248 for(i=0; i<pAggInfo->nColumn; i++){
8249 struct AggInfo_col *pCol = &pAggInfo->aCol[i];
8250 if( pCol->iSorterColumn>=j ){
8251 sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
8252 j++;
8255 pAggInfo->directMode = 0;
8256 regRecord = sqlite3GetTempReg(pParse);
8257 sqlite3VdbeScanStatusCounters(v, addrExp, 0, sqlite3VdbeCurrentAddr(v));
8258 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
8259 sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
8260 sqlite3VdbeScanStatusRange(v, addrExp, sqlite3VdbeCurrentAddr(v)-2, -1);
8261 sqlite3ReleaseTempReg(pParse, regRecord);
8262 sqlite3ReleaseTempRange(pParse, regBase, nCol);
8263 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8264 sqlite3WhereEnd(pWInfo);
8265 pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
8266 sortOut = sqlite3GetTempReg(pParse);
8267 sqlite3VdbeScanStatusCounters(v, addrExp, sqlite3VdbeCurrentAddr(v), 0);
8268 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
8269 sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
8270 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
8271 pAggInfo->useSortingIdx = 1;
8272 sqlite3VdbeScanStatusRange(v, addrExp, -1, sortPTab);
8273 sqlite3VdbeScanStatusRange(v, addrExp, -1, pAggInfo->sortingIdx);
8276 /* If there are entries in pAgggInfo->aFunc[] that contain subexpressions
8277 ** that are indexed (and that were previously identified and tagged
8278 ** in optimizeAggregateUseOfIndexedExpr()) then those subexpressions
8279 ** must now be converted into a TK_AGG_COLUMN node so that the value
8280 ** is correctly pulled from the index rather than being recomputed. */
8281 if( pParse->pIdxEpr ){
8282 aggregateConvertIndexedExprRefToColumn(pAggInfo);
8283 #if TREETRACE_ENABLED
8284 if( sqlite3TreeTrace & 0x20 ){
8285 TREETRACE(0x20, pParse, p,
8286 ("AggInfo function expressions converted to reference index\n"));
8287 sqlite3TreeViewSelect(0, p, 0);
8288 printAggInfo(pAggInfo);
8290 #endif
8293 /* If the index or temporary table used by the GROUP BY sort
8294 ** will naturally deliver rows in the order required by the ORDER BY
8295 ** clause, cancel the ephemeral table open coded earlier.
8297 ** This is an optimization - the correct answer should result regardless.
8298 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
8299 ** disable this optimization for testing purposes. */
8300 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
8301 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
8303 sSort.pOrderBy = 0;
8304 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
8307 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
8308 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
8309 ** Then compare the current GROUP BY terms against the GROUP BY terms
8310 ** from the previous row currently stored in a0, a1, a2...
8312 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
8313 if( groupBySort ){
8314 sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
8315 sortOut, sortPTab);
8317 for(j=0; j<pGroupBy->nExpr; j++){
8318 if( groupBySort ){
8319 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
8320 }else{
8321 pAggInfo->directMode = 1;
8322 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
8325 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
8326 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
8327 addr1 = sqlite3VdbeCurrentAddr(v);
8328 sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
8330 /* Generate code that runs whenever the GROUP BY changes.
8331 ** Changes in the GROUP BY are detected by the previous code
8332 ** block. If there were no changes, this block is skipped.
8334 ** This code copies current group by terms in b0,b1,b2,...
8335 ** over to a0,a1,a2. It then calls the output subroutine
8336 ** and resets the aggregate accumulator registers in preparation
8337 ** for the next GROUP BY batch.
8339 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
8340 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
8341 VdbeComment((v, "output one row"));
8342 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
8343 VdbeComment((v, "check abort flag"));
8344 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
8345 VdbeComment((v, "reset accumulator"));
8347 /* Update the aggregate accumulators based on the content of
8348 ** the current row
8350 sqlite3VdbeJumpHere(v, addr1);
8351 updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
8352 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
8353 VdbeComment((v, "indicate data in accumulator"));
8355 /* End of the loop
8357 if( groupBySort ){
8358 sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
8359 VdbeCoverage(v);
8360 }else{
8361 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8362 sqlite3WhereEnd(pWInfo);
8363 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
8365 sqlite3ExprListDelete(db, pDistinct);
8367 /* Output the final row of result
8369 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
8370 VdbeComment((v, "output final row"));
8372 /* Jump over the subroutines
8374 sqlite3VdbeGoto(v, addrEnd);
8376 /* Generate a subroutine that outputs a single row of the result
8377 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
8378 ** is less than or equal to zero, the subroutine is a no-op. If
8379 ** the processing calls for the query to abort, this subroutine
8380 ** increments the iAbortFlag memory location before returning in
8381 ** order to signal the caller to abort.
8383 addrSetAbort = sqlite3VdbeCurrentAddr(v);
8384 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
8385 VdbeComment((v, "set abort flag"));
8386 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8387 sqlite3VdbeResolveLabel(v, addrOutputRow);
8388 addrOutputRow = sqlite3VdbeCurrentAddr(v);
8389 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
8390 VdbeCoverage(v);
8391 VdbeComment((v, "Groupby result generator entry point"));
8392 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8393 finalizeAggFunctions(pParse, pAggInfo);
8394 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
8395 selectInnerLoop(pParse, p, -1, &sSort,
8396 &sDistinct, pDest,
8397 addrOutputRow+1, addrSetAbort);
8398 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8399 VdbeComment((v, "end groupby result generator"));
8401 /* Generate a subroutine that will reset the group-by accumulator
8403 sqlite3VdbeResolveLabel(v, addrReset);
8404 resetAccumulator(pParse, pAggInfo);
8405 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
8406 VdbeComment((v, "indicate accumulator empty"));
8407 sqlite3VdbeAddOp1(v, OP_Return, regReset);
8409 if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
8410 struct AggInfo_func *pF = &pAggInfo->aFunc[0];
8411 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
8413 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
8414 else {
8415 Table *pTab;
8416 if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
8417 /* If isSimpleCount() returns a pointer to a Table structure, then
8418 ** the SQL statement is of the form:
8420 ** SELECT count(*) FROM <tbl>
8422 ** where the Table structure returned represents table <tbl>.
8424 ** This statement is so common that it is optimized specially. The
8425 ** OP_Count instruction is executed either on the intkey table that
8426 ** contains the data for table <tbl> or on one of its indexes. It
8427 ** is better to execute the op on an index, as indexes are almost
8428 ** always spread across less pages than their corresponding tables.
8430 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
8431 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
8432 Index *pIdx; /* Iterator variable */
8433 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
8434 Index *pBest = 0; /* Best index found so far */
8435 Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
8437 sqlite3CodeVerifySchema(pParse, iDb);
8438 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
8440 /* Search for the index that has the lowest scan cost.
8442 ** (2011-04-15) Do not do a full scan of an unordered index.
8444 ** (2013-10-03) Do not count the entries in a partial index.
8446 ** In practice the KeyInfo structure will not be used. It is only
8447 ** passed to keep OP_OpenRead happy.
8449 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
8450 if( !p->pSrc->a[0].fg.notIndexed ){
8451 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
8452 if( pIdx->bUnordered==0
8453 && pIdx->szIdxRow<pTab->szTabRow
8454 && pIdx->pPartIdxWhere==0
8455 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
8457 pBest = pIdx;
8461 if( pBest ){
8462 iRoot = pBest->tnum;
8463 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
8466 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
8467 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
8468 if( pKeyInfo ){
8469 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
8471 assignAggregateRegisters(pParse, pAggInfo);
8472 sqlite3VdbeAddOp2(v, OP_Count, iCsr, AggInfoFuncReg(pAggInfo,0));
8473 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
8474 explainSimpleCount(pParse, pTab, pBest);
8475 }else{
8476 int regAcc = 0; /* "populate accumulators" flag */
8477 ExprList *pDistinct = 0;
8478 u16 distFlag = 0;
8479 int eDist;
8481 /* If there are accumulator registers but no min() or max() functions
8482 ** without FILTER clauses, allocate register regAcc. Register regAcc
8483 ** will contain 0 the first time the inner loop runs, and 1 thereafter.
8484 ** The code generated by updateAccumulator() uses this to ensure
8485 ** that the accumulator registers are (a) updated only once if
8486 ** there are no min() or max functions or (b) always updated for the
8487 ** first row visited by the aggregate, so that they are updated at
8488 ** least once even if the FILTER clause means the min() or max()
8489 ** function visits zero rows. */
8490 if( pAggInfo->nAccumulator ){
8491 for(i=0; i<pAggInfo->nFunc; i++){
8492 if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
8493 continue;
8495 if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
8496 break;
8499 if( i==pAggInfo->nFunc ){
8500 regAcc = ++pParse->nMem;
8501 sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
8503 }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
8504 assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
8505 pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
8506 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
8508 assignAggregateRegisters(pParse, pAggInfo);
8510 /* This case runs if the aggregate has no GROUP BY clause. The
8511 ** processing is much simpler since there is only a single row
8512 ** of output.
8514 assert( p->pGroupBy==0 );
8515 resetAccumulator(pParse, pAggInfo);
8517 /* If this query is a candidate for the min/max optimization, then
8518 ** minMaxFlag will have been previously set to either
8519 ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
8520 ** be an appropriate ORDER BY expression for the optimization.
8522 assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
8523 assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
8525 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8526 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
8527 pDistinct, p, minMaxFlag|distFlag, 0);
8528 if( pWInfo==0 ){
8529 goto select_end;
8531 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8532 eDist = sqlite3WhereIsDistinct(pWInfo);
8533 updateAccumulator(pParse, regAcc, pAggInfo, eDist);
8534 if( eDist!=WHERE_DISTINCT_NOOP ){
8535 struct AggInfo_func *pF = pAggInfo->aFunc;
8536 if( pF ){
8537 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
8541 if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
8542 if( minMaxFlag ){
8543 sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
8545 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8546 sqlite3WhereEnd(pWInfo);
8547 finalizeAggFunctions(pParse, pAggInfo);
8550 sSort.pOrderBy = 0;
8551 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
8552 selectInnerLoop(pParse, p, -1, 0, 0,
8553 pDest, addrEnd, addrEnd);
8555 sqlite3VdbeResolveLabel(v, addrEnd);
8557 } /* endif aggregate query */
8559 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
8560 explainTempTable(pParse, "DISTINCT");
8563 /* If there is an ORDER BY clause, then we need to sort the results
8564 ** and send them to the callback one by one.
8566 if( sSort.pOrderBy ){
8567 assert( p->pEList==pEList );
8568 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
8571 /* Jump here to skip this query
8573 sqlite3VdbeResolveLabel(v, iEnd);
8575 /* The SELECT has been coded. If there is an error in the Parse structure,
8576 ** set the return code to 1. Otherwise 0. */
8577 rc = (pParse->nErr>0);
8579 /* Control jumps to here if an error is encountered above, or upon
8580 ** successful coding of the SELECT.
8582 select_end:
8583 assert( db->mallocFailed==0 || db->mallocFailed==1 );
8584 assert( db->mallocFailed==0 || pParse->nErr!=0 );
8585 sqlite3ExprListDelete(db, pMinMaxOrderBy);
8586 #ifdef SQLITE_DEBUG
8587 if( pAggInfo && !db->mallocFailed ){
8588 #if TREETRACE_ENABLED
8589 if( sqlite3TreeTrace & 0x20 ){
8590 TREETRACE(0x20,pParse,p,("Finished with AggInfo\n"));
8591 printAggInfo(pAggInfo);
8593 #endif
8594 for(i=0; i<pAggInfo->nColumn; i++){
8595 Expr *pExpr = pAggInfo->aCol[i].pCExpr;
8596 if( pExpr==0 ) continue;
8597 assert( pExpr->pAggInfo==pAggInfo );
8598 assert( pExpr->iAgg==i );
8600 for(i=0; i<pAggInfo->nFunc; i++){
8601 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
8602 assert( pExpr!=0 );
8603 assert( pExpr->pAggInfo==pAggInfo );
8604 assert( pExpr->iAgg==i );
8607 #endif
8609 #if TREETRACE_ENABLED
8610 TREETRACE(0x1,pParse,p,("end processing\n"));
8611 if( (sqlite3TreeTrace & 0x40000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
8612 sqlite3TreeViewSelect(0, p, 0);
8614 #endif
8615 ExplainQueryPlanPop(pParse);
8616 return rc;