Merge sqlite-release(3.44.2) into prerelease-integration
[sqlcipher.git] / src / select.c
blobe5312c7ee7e5483a8e08a33b06a61c0584ab4920
1 /*
2 ** 2001 September 15
3 **
4 ** The author disclaims copyright to this source code. In place of
5 ** a legal notice, here is a blessing:
6 **
7 ** May you do good and not evil.
8 ** May you find forgiveness for yourself and forgive others.
9 ** May you share freely, never taking more than you give.
11 *************************************************************************
12 ** This file contains C code routines that are called by the parser
13 ** to handle SELECT statements in SQLite.
15 #include "sqliteInt.h"
18 ** An instance of the following object is used to record information about
19 ** how to process the DISTINCT keyword, to simplify passing that information
20 ** into the selectInnerLoop() routine.
22 typedef struct DistinctCtx DistinctCtx;
23 struct DistinctCtx {
24 u8 isTnct; /* 0: Not distinct. 1: DISTICT 2: DISTINCT and ORDER BY */
25 u8 eTnctType; /* One of the WHERE_DISTINCT_* operators */
26 int tabTnct; /* Ephemeral table used for DISTINCT processing */
27 int addrTnct; /* Address of OP_OpenEphemeral opcode for tabTnct */
31 ** An instance of the following object is used to record information about
32 ** the ORDER BY (or GROUP BY) clause of query is being coded.
34 ** The aDefer[] array is used by the sorter-references optimization. For
35 ** example, assuming there is no index that can be used for the ORDER BY,
36 ** for the query:
38 ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
40 ** it may be more efficient to add just the "a" values to the sorter, and
41 ** retrieve the associated "bigblob" values directly from table t1 as the
42 ** 10 smallest "a" values are extracted from the sorter.
44 ** When the sorter-reference optimization is used, there is one entry in the
45 ** aDefer[] array for each database table that may be read as values are
46 ** extracted from the sorter.
48 typedef struct SortCtx SortCtx;
49 struct SortCtx {
50 ExprList *pOrderBy; /* The ORDER BY (or GROUP BY clause) */
51 int nOBSat; /* Number of ORDER BY terms satisfied by indices */
52 int iECursor; /* Cursor number for the sorter */
53 int regReturn; /* Register holding block-output return address */
54 int labelBkOut; /* Start label for the block-output subroutine */
55 int addrSortIndex; /* Address of the OP_SorterOpen or OP_OpenEphemeral */
56 int labelDone; /* Jump here when done, ex: LIMIT reached */
57 int labelOBLopt; /* Jump here when sorter is full */
58 u8 sortFlags; /* Zero or more SORTFLAG_* bits */
59 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
60 u8 nDefer; /* Number of valid entries in aDefer[] */
61 struct DeferredCsr {
62 Table *pTab; /* Table definition */
63 int iCsr; /* Cursor number for table */
64 int nKey; /* Number of PK columns for table pTab (>=1) */
65 } aDefer[4];
66 #endif
67 struct RowLoadInfo *pDeferredRowLoad; /* Deferred row loading info or NULL */
68 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
69 int addrPush; /* First instruction to push data into sorter */
70 int addrPushEnd; /* Last instruction that pushes data into sorter */
71 #endif
73 #define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
76 ** Delete all the content of a Select structure. Deallocate the structure
77 ** itself depending on the value of bFree
79 ** If bFree==1, call sqlite3DbFree() on the p object.
80 ** If bFree==0, Leave the first Select object unfreed
82 static void clearSelect(sqlite3 *db, Select *p, int bFree){
83 assert( db!=0 );
84 while( p ){
85 Select *pPrior = p->pPrior;
86 sqlite3ExprListDelete(db, p->pEList);
87 sqlite3SrcListDelete(db, p->pSrc);
88 sqlite3ExprDelete(db, p->pWhere);
89 sqlite3ExprListDelete(db, p->pGroupBy);
90 sqlite3ExprDelete(db, p->pHaving);
91 sqlite3ExprListDelete(db, p->pOrderBy);
92 sqlite3ExprDelete(db, p->pLimit);
93 if( OK_IF_ALWAYS_TRUE(p->pWith) ) sqlite3WithDelete(db, p->pWith);
94 #ifndef SQLITE_OMIT_WINDOWFUNC
95 if( OK_IF_ALWAYS_TRUE(p->pWinDefn) ){
96 sqlite3WindowListDelete(db, p->pWinDefn);
98 while( p->pWin ){
99 assert( p->pWin->ppThis==&p->pWin );
100 sqlite3WindowUnlinkFromSelect(p->pWin);
102 #endif
103 if( bFree ) sqlite3DbNNFreeNN(db, p);
104 p = pPrior;
105 bFree = 1;
110 ** Initialize a SelectDest structure.
112 void sqlite3SelectDestInit(SelectDest *pDest, int eDest, int iParm){
113 pDest->eDest = (u8)eDest;
114 pDest->iSDParm = iParm;
115 pDest->iSDParm2 = 0;
116 pDest->zAffSdst = 0;
117 pDest->iSdst = 0;
118 pDest->nSdst = 0;
123 ** Allocate a new Select structure and return a pointer to that
124 ** structure.
126 Select *sqlite3SelectNew(
127 Parse *pParse, /* Parsing context */
128 ExprList *pEList, /* which columns to include in the result */
129 SrcList *pSrc, /* the FROM clause -- which tables to scan */
130 Expr *pWhere, /* the WHERE clause */
131 ExprList *pGroupBy, /* the GROUP BY clause */
132 Expr *pHaving, /* the HAVING clause */
133 ExprList *pOrderBy, /* the ORDER BY clause */
134 u32 selFlags, /* Flag parameters, such as SF_Distinct */
135 Expr *pLimit /* LIMIT value. NULL means not used */
137 Select *pNew, *pAllocated;
138 Select standin;
139 pAllocated = pNew = sqlite3DbMallocRawNN(pParse->db, sizeof(*pNew) );
140 if( pNew==0 ){
141 assert( pParse->db->mallocFailed );
142 pNew = &standin;
144 if( pEList==0 ){
145 pEList = sqlite3ExprListAppend(pParse, 0,
146 sqlite3Expr(pParse->db,TK_ASTERISK,0));
148 pNew->pEList = pEList;
149 pNew->op = TK_SELECT;
150 pNew->selFlags = selFlags;
151 pNew->iLimit = 0;
152 pNew->iOffset = 0;
153 pNew->selId = ++pParse->nSelect;
154 pNew->addrOpenEphm[0] = -1;
155 pNew->addrOpenEphm[1] = -1;
156 pNew->nSelectRow = 0;
157 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*pSrc));
158 pNew->pSrc = pSrc;
159 pNew->pWhere = pWhere;
160 pNew->pGroupBy = pGroupBy;
161 pNew->pHaving = pHaving;
162 pNew->pOrderBy = pOrderBy;
163 pNew->pPrior = 0;
164 pNew->pNext = 0;
165 pNew->pLimit = pLimit;
166 pNew->pWith = 0;
167 #ifndef SQLITE_OMIT_WINDOWFUNC
168 pNew->pWin = 0;
169 pNew->pWinDefn = 0;
170 #endif
171 if( pParse->db->mallocFailed ) {
172 clearSelect(pParse->db, pNew, pNew!=&standin);
173 pAllocated = 0;
174 }else{
175 assert( pNew->pSrc!=0 || pParse->nErr>0 );
177 return pAllocated;
182 ** Delete the given Select structure and all of its substructures.
184 void sqlite3SelectDelete(sqlite3 *db, Select *p){
185 if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
189 ** Return a pointer to the right-most SELECT statement in a compound.
191 static Select *findRightmost(Select *p){
192 while( p->pNext ) p = p->pNext;
193 return p;
197 ** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
198 ** type of join. Return an integer constant that expresses that type
199 ** in terms of the following bit values:
201 ** JT_INNER
202 ** JT_CROSS
203 ** JT_OUTER
204 ** JT_NATURAL
205 ** JT_LEFT
206 ** JT_RIGHT
208 ** A full outer join is the combination of JT_LEFT and JT_RIGHT.
210 ** If an illegal or unsupported join type is seen, then still return
211 ** a join type, but put an error in the pParse structure.
213 ** These are the valid join types:
216 ** pA pB pC Return Value
217 ** ------- ----- ----- ------------
218 ** CROSS - - JT_CROSS
219 ** INNER - - JT_INNER
220 ** LEFT - - JT_LEFT|JT_OUTER
221 ** LEFT OUTER - JT_LEFT|JT_OUTER
222 ** RIGHT - - JT_RIGHT|JT_OUTER
223 ** RIGHT OUTER - JT_RIGHT|JT_OUTER
224 ** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER
225 ** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER
226 ** NATURAL INNER - JT_NATURAL|JT_INNER
227 ** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER
228 ** NATURAL LEFT OUTER JT_NATURAL|JT_LEFT|JT_OUTER
229 ** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER
230 ** NATURAL RIGHT OUTER JT_NATURAL|JT_RIGHT|JT_OUTER
231 ** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT
232 ** NATURAL FULL OUTER JT_NATRUAL|JT_LEFT|JT_RIGHT
234 ** To preserve historical compatibly, SQLite also accepts a variety
235 ** of other non-standard and in many cases nonsensical join types.
236 ** This routine makes as much sense at it can from the nonsense join
237 ** type and returns a result. Examples of accepted nonsense join types
238 ** include but are not limited to:
240 ** INNER CROSS JOIN -> same as JOIN
241 ** NATURAL CROSS JOIN -> same as NATURAL JOIN
242 ** OUTER LEFT JOIN -> same as LEFT JOIN
243 ** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN
244 ** LEFT RIGHT JOIN -> same as FULL JOIN
245 ** RIGHT OUTER FULL JOIN -> same as FULL JOIN
246 ** CROSS CROSS CROSS JOIN -> same as JOIN
248 ** The only restrictions on the join type name are:
250 ** * "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT",
251 ** or "FULL".
253 ** * "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT,
254 ** or "FULL".
256 ** * If "OUTER" is present then there must also be one of
257 ** "LEFT", "RIGHT", or "FULL"
259 int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
260 int jointype = 0;
261 Token *apAll[3];
262 Token *p;
263 /* 0123456789 123456789 123456789 123 */
264 static const char zKeyText[] = "naturaleftouterightfullinnercross";
265 static const struct {
266 u8 i; /* Beginning of keyword text in zKeyText[] */
267 u8 nChar; /* Length of the keyword in characters */
268 u8 code; /* Join type mask */
269 } aKeyword[] = {
270 /* (0) natural */ { 0, 7, JT_NATURAL },
271 /* (1) left */ { 6, 4, JT_LEFT|JT_OUTER },
272 /* (2) outer */ { 10, 5, JT_OUTER },
273 /* (3) right */ { 14, 5, JT_RIGHT|JT_OUTER },
274 /* (4) full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
275 /* (5) inner */ { 23, 5, JT_INNER },
276 /* (6) cross */ { 28, 5, JT_INNER|JT_CROSS },
278 int i, j;
279 apAll[0] = pA;
280 apAll[1] = pB;
281 apAll[2] = pC;
282 for(i=0; i<3 && apAll[i]; i++){
283 p = apAll[i];
284 for(j=0; j<ArraySize(aKeyword); j++){
285 if( p->n==aKeyword[j].nChar
286 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
287 jointype |= aKeyword[j].code;
288 break;
291 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
292 if( j>=ArraySize(aKeyword) ){
293 jointype |= JT_ERROR;
294 break;
298 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
299 (jointype & JT_ERROR)!=0 ||
300 (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER
302 const char *zSp1 = " ";
303 const char *zSp2 = " ";
304 if( pB==0 ){ zSp1++; }
305 if( pC==0 ){ zSp2++; }
306 sqlite3ErrorMsg(pParse, "unknown join type: "
307 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
308 jointype = JT_INNER;
310 return jointype;
314 ** Return the index of a column in a table. Return -1 if the column
315 ** is not contained in the table.
317 int sqlite3ColumnIndex(Table *pTab, const char *zCol){
318 int i;
319 u8 h = sqlite3StrIHash(zCol);
320 Column *pCol;
321 for(pCol=pTab->aCol, i=0; i<pTab->nCol; pCol++, i++){
322 if( pCol->hName==h && sqlite3StrICmp(pCol->zCnName, zCol)==0 ) return i;
324 return -1;
328 ** Mark a subquery result column as having been used.
330 void sqlite3SrcItemColumnUsed(SrcItem *pItem, int iCol){
331 assert( pItem!=0 );
332 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem->pSelect) );
333 if( pItem->fg.isNestedFrom ){
334 ExprList *pResults;
335 assert( pItem->pSelect!=0 );
336 pResults = pItem->pSelect->pEList;
337 assert( pResults!=0 );
338 assert( iCol>=0 && iCol<pResults->nExpr );
339 pResults->a[iCol].fg.bUsed = 1;
344 ** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
345 ** table that has a column named zCol. The search is left-to-right.
346 ** The first match found is returned.
348 ** When found, set *piTab and *piCol to the table index and column index
349 ** of the matching column and return TRUE.
351 ** If not found, return FALSE.
353 static int tableAndColumnIndex(
354 SrcList *pSrc, /* Array of tables to search */
355 int iStart, /* First member of pSrc->a[] to check */
356 int iEnd, /* Last member of pSrc->a[] to check */
357 const char *zCol, /* Name of the column we are looking for */
358 int *piTab, /* Write index of pSrc->a[] here */
359 int *piCol, /* Write index of pSrc->a[*piTab].pTab->aCol[] here */
360 int bIgnoreHidden /* Ignore hidden columns */
362 int i; /* For looping over tables in pSrc */
363 int iCol; /* Index of column matching zCol */
365 assert( iEnd<pSrc->nSrc );
366 assert( iStart>=0 );
367 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
369 for(i=iStart; i<=iEnd; i++){
370 iCol = sqlite3ColumnIndex(pSrc->a[i].pTab, zCol);
371 if( iCol>=0
372 && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pTab->aCol[iCol])==0)
374 if( piTab ){
375 sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
376 *piTab = i;
377 *piCol = iCol;
379 return 1;
382 return 0;
386 ** Set the EP_OuterON property on all terms of the given expression.
387 ** And set the Expr.w.iJoin to iTable for every term in the
388 ** expression.
390 ** The EP_OuterON property is used on terms of an expression to tell
391 ** the OUTER JOIN processing logic that this term is part of the
392 ** join restriction specified in the ON or USING clause and not a part
393 ** of the more general WHERE clause. These terms are moved over to the
394 ** WHERE clause during join processing but we need to remember that they
395 ** originated in the ON or USING clause.
397 ** The Expr.w.iJoin tells the WHERE clause processing that the
398 ** expression depends on table w.iJoin even if that table is not
399 ** explicitly mentioned in the expression. That information is needed
400 ** for cases like this:
402 ** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
404 ** The where clause needs to defer the handling of the t1.x=5
405 ** term until after the t2 loop of the join. In that way, a
406 ** NULL t2 row will be inserted whenever t1.x!=5. If we do not
407 ** defer the handling of t1.x=5, it will be processed immediately
408 ** after the t1 loop and rows with t1.x!=5 will never appear in
409 ** the output, which is incorrect.
411 void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){
412 assert( joinFlag==EP_OuterON || joinFlag==EP_InnerON );
413 while( p ){
414 ExprSetProperty(p, joinFlag);
415 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
416 ExprSetVVAProperty(p, EP_NoReduce);
417 p->w.iJoin = iTable;
418 if( p->op==TK_FUNCTION ){
419 assert( ExprUseXList(p) );
420 if( p->x.pList ){
421 int i;
422 for(i=0; i<p->x.pList->nExpr; i++){
423 sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
427 sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
428 p = p->pRight;
432 /* Undo the work of sqlite3SetJoinExpr(). This is used when a LEFT JOIN
433 ** is simplified into an ordinary JOIN, and when an ON expression is
434 ** "pushed down" into the WHERE clause of a subquery.
436 ** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
437 ** an ordinary term that omits the EP_OuterON mark. Or if iTable<0, then
438 ** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
440 ** If nullable is true, that means that Expr p might evaluate to NULL even
441 ** if it is a reference to a NOT NULL column. This can happen, for example,
442 ** if the table that p references is on the left side of a RIGHT JOIN.
443 ** If nullable is true, then take care to not remove the EP_CanBeNull bit.
444 ** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
446 static void unsetJoinExpr(Expr *p, int iTable, int nullable){
447 while( p ){
448 if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
449 ExprClearProperty(p, EP_OuterON|EP_InnerON);
450 if( iTable>=0 ) ExprSetProperty(p, EP_InnerON);
452 if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
453 ExprClearProperty(p, EP_CanBeNull);
455 if( p->op==TK_FUNCTION ){
456 assert( ExprUseXList(p) );
457 assert( p->pLeft==0 );
458 if( p->x.pList ){
459 int i;
460 for(i=0; i<p->x.pList->nExpr; i++){
461 unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
465 unsetJoinExpr(p->pLeft, iTable, nullable);
466 p = p->pRight;
471 ** This routine processes the join information for a SELECT statement.
473 ** * A NATURAL join is converted into a USING join. After that, we
474 ** do not need to be concerned with NATURAL joins and we only have
475 ** think about USING joins.
477 ** * ON and USING clauses result in extra terms being added to the
478 ** WHERE clause to enforce the specified constraints. The extra
479 ** WHERE clause terms will be tagged with EP_OuterON or
480 ** EP_InnerON so that we know that they originated in ON/USING.
482 ** The terms of a FROM clause are contained in the Select.pSrc structure.
483 ** The left most table is the first entry in Select.pSrc. The right-most
484 ** table is the last entry. The join operator is held in the entry to
485 ** the right. Thus entry 1 contains the join operator for the join between
486 ** entries 0 and 1. Any ON or USING clauses associated with the join are
487 ** also attached to the right entry.
489 ** This routine returns the number of errors encountered.
491 static int sqlite3ProcessJoin(Parse *pParse, Select *p){
492 SrcList *pSrc; /* All tables in the FROM clause */
493 int i, j; /* Loop counters */
494 SrcItem *pLeft; /* Left table being joined */
495 SrcItem *pRight; /* Right table being joined */
497 pSrc = p->pSrc;
498 pLeft = &pSrc->a[0];
499 pRight = &pLeft[1];
500 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
501 Table *pRightTab = pRight->pTab;
502 u32 joinType;
504 if( NEVER(pLeft->pTab==0 || pRightTab==0) ) continue;
505 joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
507 /* If this is a NATURAL join, synthesize an appropriate USING clause
508 ** to specify which columns should be joined.
510 if( pRight->fg.jointype & JT_NATURAL ){
511 IdList *pUsing = 0;
512 if( pRight->fg.isUsing || pRight->u3.pOn ){
513 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
514 "an ON or USING clause", 0);
515 return 1;
517 for(j=0; j<pRightTab->nCol; j++){
518 char *zName; /* Name of column in the right table */
520 if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
521 zName = pRightTab->aCol[j].zCnName;
522 if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){
523 pUsing = sqlite3IdListAppend(pParse, pUsing, 0);
524 if( pUsing ){
525 assert( pUsing->nId>0 );
526 assert( pUsing->a[pUsing->nId-1].zName==0 );
527 pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
531 if( pUsing ){
532 pRight->fg.isUsing = 1;
533 pRight->fg.isSynthUsing = 1;
534 pRight->u3.pUsing = pUsing;
536 if( pParse->nErr ) return 1;
539 /* Create extra terms on the WHERE clause for each column named
540 ** in the USING clause. Example: If the two tables to be joined are
541 ** A and B and the USING clause names X, Y, and Z, then add this
542 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
543 ** Report an error if any column mentioned in the USING clause is
544 ** not contained in both tables to be joined.
546 if( pRight->fg.isUsing ){
547 IdList *pList = pRight->u3.pUsing;
548 sqlite3 *db = pParse->db;
549 assert( pList!=0 );
550 for(j=0; j<pList->nId; j++){
551 char *zName; /* Name of the term in the USING clause */
552 int iLeft; /* Table on the left with matching column name */
553 int iLeftCol; /* Column number of matching column on the left */
554 int iRightCol; /* Column number of matching column on the right */
555 Expr *pE1; /* Reference to the column on the LEFT of the join */
556 Expr *pE2; /* Reference to the column on the RIGHT of the join */
557 Expr *pEq; /* Equality constraint. pE1 == pE2 */
559 zName = pList->a[j].zName;
560 iRightCol = sqlite3ColumnIndex(pRightTab, zName);
561 if( iRightCol<0
562 || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol,
563 pRight->fg.isSynthUsing)==0
565 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
566 "not present in both tables", zName);
567 return 1;
569 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
570 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
571 if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
572 /* This branch runs if the query contains one or more RIGHT or FULL
573 ** JOINs. If only a single table on the left side of this join
574 ** contains the zName column, then this branch is a no-op.
575 ** But if there are two or more tables on the left side
576 ** of the join, construct a coalesce() function that gathers all
577 ** such tables. Raise an error if more than one of those references
578 ** to zName is not also within a prior USING clause.
580 ** We really ought to raise an error if there are two or more
581 ** non-USING references to zName on the left of an INNER or LEFT
582 ** JOIN. But older versions of SQLite do not do that, so we avoid
583 ** adding a new error so as to not break legacy applications.
585 ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */
586 static const Token tkCoalesce = { "coalesce", 8 };
587 while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,
588 pRight->fg.isSynthUsing)!=0 ){
589 if( pSrc->a[iLeft].fg.isUsing==0
590 || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
592 sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()",
593 zName);
594 break;
596 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
597 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
598 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
600 if( pFuncArgs ){
601 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
602 pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);
605 pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);
606 sqlite3SrcItemColumnUsed(pRight, iRightCol);
607 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
608 assert( pE2!=0 || pEq==0 );
609 if( pEq ){
610 ExprSetProperty(pEq, joinType);
611 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
612 ExprSetVVAProperty(pEq, EP_NoReduce);
613 pEq->w.iJoin = pE2->iTable;
615 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
619 /* Add the ON clause to the end of the WHERE clause, connected by
620 ** an AND operator.
622 else if( pRight->u3.pOn ){
623 sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
624 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
625 pRight->u3.pOn = 0;
626 pRight->fg.isOn = 1;
629 return 0;
633 ** An instance of this object holds information (beyond pParse and pSelect)
634 ** needed to load the next result row that is to be added to the sorter.
636 typedef struct RowLoadInfo RowLoadInfo;
637 struct RowLoadInfo {
638 int regResult; /* Store results in array of registers here */
639 u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
640 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
641 ExprList *pExtra; /* Extra columns needed by sorter refs */
642 int regExtraResult; /* Where to load the extra columns */
643 #endif
647 ** This routine does the work of loading query data into an array of
648 ** registers so that it can be added to the sorter.
650 static void innerLoopLoadRow(
651 Parse *pParse, /* Statement under construction */
652 Select *pSelect, /* The query being coded */
653 RowLoadInfo *pInfo /* Info needed to complete the row load */
655 sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
656 0, pInfo->ecelFlags);
657 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
658 if( pInfo->pExtra ){
659 sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
660 sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
662 #endif
666 ** Code the OP_MakeRecord instruction that generates the entry to be
667 ** added into the sorter.
669 ** Return the register in which the result is stored.
671 static int makeSorterRecord(
672 Parse *pParse,
673 SortCtx *pSort,
674 Select *pSelect,
675 int regBase,
676 int nBase
678 int nOBSat = pSort->nOBSat;
679 Vdbe *v = pParse->pVdbe;
680 int regOut = ++pParse->nMem;
681 if( pSort->pDeferredRowLoad ){
682 innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
684 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
685 return regOut;
689 ** Generate code that will push the record in registers regData
690 ** through regData+nData-1 onto the sorter.
692 static void pushOntoSorter(
693 Parse *pParse, /* Parser context */
694 SortCtx *pSort, /* Information about the ORDER BY clause */
695 Select *pSelect, /* The whole SELECT statement */
696 int regData, /* First register holding data to be sorted */
697 int regOrigData, /* First register holding data before packing */
698 int nData, /* Number of elements in the regData data array */
699 int nPrefixReg /* No. of reg prior to regData available for use */
701 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
702 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
703 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
704 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
705 int regBase; /* Regs for sorter record */
706 int regRecord = 0; /* Assembled sorter record */
707 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
708 int op; /* Opcode to add sorter record to sorter */
709 int iLimit; /* LIMIT counter */
710 int iSkip = 0; /* End of the sorter insert loop */
712 assert( bSeq==0 || bSeq==1 );
714 /* Three cases:
715 ** (1) The data to be sorted has already been packed into a Record
716 ** by a prior OP_MakeRecord. In this case nData==1 and regData
717 ** will be completely unrelated to regOrigData.
718 ** (2) All output columns are included in the sort record. In that
719 ** case regData==regOrigData.
720 ** (3) Some output columns are omitted from the sort record due to
721 ** the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
722 ** SQLITE_ECEL_OMITREF optimization, or due to the
723 ** SortCtx.pDeferredRowLoad optimization. In any of these cases
724 ** regOrigData is 0 to prevent this routine from trying to copy
725 ** values that might not yet exist.
727 assert( nData==1 || regData==regOrigData || regOrigData==0 );
729 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
730 pSort->addrPush = sqlite3VdbeCurrentAddr(v);
731 #endif
733 if( nPrefixReg ){
734 assert( nPrefixReg==nExpr+bSeq );
735 regBase = regData - nPrefixReg;
736 }else{
737 regBase = pParse->nMem + 1;
738 pParse->nMem += nBase;
740 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
741 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
742 pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
743 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
744 SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
745 if( bSeq ){
746 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
748 if( nPrefixReg==0 && nData>0 ){
749 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
751 if( nOBSat>0 ){
752 int regPrevKey; /* The first nOBSat columns of the previous row */
753 int addrFirst; /* Address of the OP_IfNot opcode */
754 int addrJmp; /* Address of the OP_Jump opcode */
755 VdbeOp *pOp; /* Opcode that opens the sorter */
756 int nKey; /* Number of sorting key columns, including OP_Sequence */
757 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
759 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
760 regPrevKey = pParse->nMem+1;
761 pParse->nMem += pSort->nOBSat;
762 nKey = nExpr - pSort->nOBSat + bSeq;
763 if( bSeq ){
764 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
765 }else{
766 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
768 VdbeCoverage(v);
769 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
770 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
771 if( pParse->db->mallocFailed ) return;
772 pOp->p2 = nKey + nData;
773 pKI = pOp->p4.pKeyInfo;
774 memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
775 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
776 testcase( pKI->nAllField > pKI->nKeyField+2 );
777 pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
778 pKI->nAllField-pKI->nKeyField-1);
779 pOp = 0; /* Ensure pOp not used after sqlite3VdbeAddOp3() */
780 addrJmp = sqlite3VdbeCurrentAddr(v);
781 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
782 pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
783 pSort->regReturn = ++pParse->nMem;
784 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
785 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
786 if( iLimit ){
787 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
788 VdbeCoverage(v);
790 sqlite3VdbeJumpHere(v, addrFirst);
791 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
792 sqlite3VdbeJumpHere(v, addrJmp);
794 if( iLimit ){
795 /* At this point the values for the new sorter entry are stored
796 ** in an array of registers. They need to be composed into a record
797 ** and inserted into the sorter if either (a) there are currently
798 ** less than LIMIT+OFFSET items or (b) the new record is smaller than
799 ** the largest record currently in the sorter. If (b) is true and there
800 ** are already LIMIT+OFFSET items in the sorter, delete the largest
801 ** entry before inserting the new one. This way there are never more
802 ** than LIMIT+OFFSET items in the sorter.
804 ** If the new record does not need to be inserted into the sorter,
805 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
806 ** value is not zero, then it is a label of where to jump. Otherwise,
807 ** just bypass the row insert logic. See the header comment on the
808 ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
810 int iCsr = pSort->iECursor;
811 sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
812 VdbeCoverage(v);
813 sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
814 iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
815 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
816 VdbeCoverage(v);
817 sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
819 if( regRecord==0 ){
820 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
822 if( pSort->sortFlags & SORTFLAG_UseSorter ){
823 op = OP_SorterInsert;
824 }else{
825 op = OP_IdxInsert;
827 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
828 regBase+nOBSat, nBase-nOBSat);
829 if( iSkip ){
830 sqlite3VdbeChangeP2(v, iSkip,
831 pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
833 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
834 pSort->addrPushEnd = sqlite3VdbeCurrentAddr(v)-1;
835 #endif
839 ** Add code to implement the OFFSET
841 static void codeOffset(
842 Vdbe *v, /* Generate code into this VM */
843 int iOffset, /* Register holding the offset counter */
844 int iContinue /* Jump here to skip the current record */
846 if( iOffset>0 ){
847 sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
848 VdbeComment((v, "OFFSET"));
853 ** Add code that will check to make sure the array of registers starting at
854 ** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
855 ** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
856 ** are available. Which is used depends on the value of parameter eTnctType,
857 ** as follows:
859 ** WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
860 ** Build an ephemeral table that contains all entries seen before and
861 ** skip entries which have been seen before.
863 ** Parameter iTab is the cursor number of an ephemeral table that must
864 ** be opened before the VM code generated by this routine is executed.
865 ** The ephemeral cursor table is queried for a record identical to the
866 ** record formed by the current array of registers. If one is found,
867 ** jump to VM address addrRepeat. Otherwise, insert a new record into
868 ** the ephemeral cursor and proceed.
870 ** The returned value in this case is a copy of parameter iTab.
872 ** WHERE_DISTINCT_ORDERED:
873 ** In this case rows are being delivered sorted order. The ephemeral
874 ** table is not required. Instead, the current set of values
875 ** is compared against previous row. If they match, the new row
876 ** is not distinct and control jumps to VM address addrRepeat. Otherwise,
877 ** the VM program proceeds with processing the new row.
879 ** The returned value in this case is the register number of the first
880 ** in an array of registers used to store the previous result row so that
881 ** it can be compared to the next. The caller must ensure that this
882 ** register is initialized to NULL. (The fixDistinctOpenEph() routine
883 ** will take care of this initialization.)
885 ** WHERE_DISTINCT_UNIQUE:
886 ** In this case it has already been determined that the rows are distinct.
887 ** No special action is required. The return value is zero.
889 ** Parameter pEList is the list of expressions used to generated the
890 ** contents of each row. It is used by this routine to determine (a)
891 ** how many elements there are in the array of registers and (b) the
892 ** collation sequences that should be used for the comparisons if
893 ** eTnctType is WHERE_DISTINCT_ORDERED.
895 static int codeDistinct(
896 Parse *pParse, /* Parsing and code generating context */
897 int eTnctType, /* WHERE_DISTINCT_* value */
898 int iTab, /* A sorting index used to test for distinctness */
899 int addrRepeat, /* Jump to here if not distinct */
900 ExprList *pEList, /* Expression for each element */
901 int regElem /* First element */
903 int iRet = 0;
904 int nResultCol = pEList->nExpr;
905 Vdbe *v = pParse->pVdbe;
907 switch( eTnctType ){
908 case WHERE_DISTINCT_ORDERED: {
909 int i;
910 int iJump; /* Jump destination */
911 int regPrev; /* Previous row content */
913 /* Allocate space for the previous row */
914 iRet = regPrev = pParse->nMem+1;
915 pParse->nMem += nResultCol;
917 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
918 for(i=0; i<nResultCol; i++){
919 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
920 if( i<nResultCol-1 ){
921 sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
922 VdbeCoverage(v);
923 }else{
924 sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
925 VdbeCoverage(v);
927 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
928 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
930 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
931 sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
932 break;
935 case WHERE_DISTINCT_UNIQUE: {
936 /* nothing to do */
937 break;
940 default: {
941 int r1 = sqlite3GetTempReg(pParse);
942 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
943 VdbeCoverage(v);
944 sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
945 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
946 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
947 sqlite3ReleaseTempReg(pParse, r1);
948 iRet = iTab;
949 break;
953 return iRet;
957 ** This routine runs after codeDistinct(). It makes necessary
958 ** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
959 ** routine made use of. This processing must be done separately since
960 ** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
961 ** laid down.
963 ** WHERE_DISTINCT_NOOP:
964 ** WHERE_DISTINCT_UNORDERED:
966 ** No adjustments necessary. This function is a no-op.
968 ** WHERE_DISTINCT_UNIQUE:
970 ** The ephemeral table is not needed. So change the
971 ** OP_OpenEphemeral opcode into an OP_Noop.
973 ** WHERE_DISTINCT_ORDERED:
975 ** The ephemeral table is not needed. But we do need register
976 ** iVal to be initialized to NULL. So change the OP_OpenEphemeral
977 ** into an OP_Null on the iVal register.
979 static void fixDistinctOpenEph(
980 Parse *pParse, /* Parsing and code generating context */
981 int eTnctType, /* WHERE_DISTINCT_* value */
982 int iVal, /* Value returned by codeDistinct() */
983 int iOpenEphAddr /* Address of OP_OpenEphemeral instruction for iTab */
985 if( pParse->nErr==0
986 && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
988 Vdbe *v = pParse->pVdbe;
989 sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
990 if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
991 sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
993 if( eTnctType==WHERE_DISTINCT_ORDERED ){
994 /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
995 ** bit on the first register of the previous value. This will cause the
996 ** OP_Ne added in codeDistinct() to always fail on the first iteration of
997 ** the loop even if the first row is all NULLs. */
998 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
999 pOp->opcode = OP_Null;
1000 pOp->p1 = 1;
1001 pOp->p2 = iVal;
1006 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1008 ** This function is called as part of inner-loop generation for a SELECT
1009 ** statement with an ORDER BY that is not optimized by an index. It
1010 ** determines the expressions, if any, that the sorter-reference
1011 ** optimization should be used for. The sorter-reference optimization
1012 ** is used for SELECT queries like:
1014 ** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
1016 ** If the optimization is used for expression "bigblob", then instead of
1017 ** storing values read from that column in the sorter records, the PK of
1018 ** the row from table t1 is stored instead. Then, as records are extracted from
1019 ** the sorter to return to the user, the required value of bigblob is
1020 ** retrieved directly from table t1. If the values are very large, this
1021 ** can be more efficient than storing them directly in the sorter records.
1023 ** The ExprList_item.fg.bSorterRef flag is set for each expression in pEList
1024 ** for which the sorter-reference optimization should be enabled.
1025 ** Additionally, the pSort->aDefer[] array is populated with entries
1026 ** for all cursors required to evaluate all selected expressions. Finally.
1027 ** output variable (*ppExtra) is set to an expression list containing
1028 ** expressions for all extra PK values that should be stored in the
1029 ** sorter records.
1031 static void selectExprDefer(
1032 Parse *pParse, /* Leave any error here */
1033 SortCtx *pSort, /* Sorter context */
1034 ExprList *pEList, /* Expressions destined for sorter */
1035 ExprList **ppExtra /* Expressions to append to sorter record */
1037 int i;
1038 int nDefer = 0;
1039 ExprList *pExtra = 0;
1040 for(i=0; i<pEList->nExpr; i++){
1041 struct ExprList_item *pItem = &pEList->a[i];
1042 if( pItem->u.x.iOrderByCol==0 ){
1043 Expr *pExpr = pItem->pExpr;
1044 Table *pTab;
1045 if( pExpr->op==TK_COLUMN
1046 && pExpr->iColumn>=0
1047 && ALWAYS( ExprUseYTab(pExpr) )
1048 && (pTab = pExpr->y.pTab)!=0
1049 && IsOrdinaryTable(pTab)
1050 && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
1052 int j;
1053 for(j=0; j<nDefer; j++){
1054 if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
1056 if( j==nDefer ){
1057 if( nDefer==ArraySize(pSort->aDefer) ){
1058 continue;
1059 }else{
1060 int nKey = 1;
1061 int k;
1062 Index *pPk = 0;
1063 if( !HasRowid(pTab) ){
1064 pPk = sqlite3PrimaryKeyIndex(pTab);
1065 nKey = pPk->nKeyCol;
1067 for(k=0; k<nKey; k++){
1068 Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
1069 if( pNew ){
1070 pNew->iTable = pExpr->iTable;
1071 assert( ExprUseYTab(pNew) );
1072 pNew->y.pTab = pExpr->y.pTab;
1073 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
1074 pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
1077 pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
1078 pSort->aDefer[nDefer].iCsr = pExpr->iTable;
1079 pSort->aDefer[nDefer].nKey = nKey;
1080 nDefer++;
1083 pItem->fg.bSorterRef = 1;
1087 pSort->nDefer = (u8)nDefer;
1088 *ppExtra = pExtra;
1090 #endif
1093 ** This routine generates the code for the inside of the inner loop
1094 ** of a SELECT.
1096 ** If srcTab is negative, then the p->pEList expressions
1097 ** are evaluated in order to get the data for this row. If srcTab is
1098 ** zero or more, then data is pulled from srcTab and p->pEList is used only
1099 ** to get the number of columns and the collation sequence for each column.
1101 static void selectInnerLoop(
1102 Parse *pParse, /* The parser context */
1103 Select *p, /* The complete select statement being coded */
1104 int srcTab, /* Pull data from this table if non-negative */
1105 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
1106 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
1107 SelectDest *pDest, /* How to dispose of the results */
1108 int iContinue, /* Jump here to continue with next row */
1109 int iBreak /* Jump here to break out of the inner loop */
1111 Vdbe *v = pParse->pVdbe;
1112 int i;
1113 int hasDistinct; /* True if the DISTINCT keyword is present */
1114 int eDest = pDest->eDest; /* How to dispose of results */
1115 int iParm = pDest->iSDParm; /* First argument to disposal method */
1116 int nResultCol; /* Number of result columns */
1117 int nPrefixReg = 0; /* Number of extra registers before regResult */
1118 RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
1120 /* Usually, regResult is the first cell in an array of memory cells
1121 ** containing the current result row. In this case regOrig is set to the
1122 ** same value. However, if the results are being sent to the sorter, the
1123 ** values for any expressions that are also part of the sort-key are omitted
1124 ** from this array. In this case regOrig is set to zero. */
1125 int regResult; /* Start of memory holding current results */
1126 int regOrig; /* Start of memory holding full result (or 0) */
1128 assert( v );
1129 assert( p->pEList!=0 );
1130 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
1131 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
1132 if( pSort==0 && !hasDistinct ){
1133 assert( iContinue!=0 );
1134 codeOffset(v, p->iOffset, iContinue);
1137 /* Pull the requested columns.
1139 nResultCol = p->pEList->nExpr;
1141 if( pDest->iSdst==0 ){
1142 if( pSort ){
1143 nPrefixReg = pSort->pOrderBy->nExpr;
1144 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
1145 pParse->nMem += nPrefixReg;
1147 pDest->iSdst = pParse->nMem+1;
1148 pParse->nMem += nResultCol;
1149 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
1150 /* This is an error condition that can result, for example, when a SELECT
1151 ** on the right-hand side of an INSERT contains more result columns than
1152 ** there are columns in the table on the left. The error will be caught
1153 ** and reported later. But we need to make sure enough memory is allocated
1154 ** to avoid other spurious errors in the meantime. */
1155 pParse->nMem += nResultCol;
1157 pDest->nSdst = nResultCol;
1158 regOrig = regResult = pDest->iSdst;
1159 if( srcTab>=0 ){
1160 for(i=0; i<nResultCol; i++){
1161 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
1162 VdbeComment((v, "%s", p->pEList->a[i].zEName));
1164 }else if( eDest!=SRT_Exists ){
1165 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1166 ExprList *pExtra = 0;
1167 #endif
1168 /* If the destination is an EXISTS(...) expression, the actual
1169 ** values returned by the SELECT are not required.
1171 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
1172 ExprList *pEList;
1173 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
1174 ecelFlags = SQLITE_ECEL_DUP;
1175 }else{
1176 ecelFlags = 0;
1178 if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
1179 /* For each expression in p->pEList that is a copy of an expression in
1180 ** the ORDER BY clause (pSort->pOrderBy), set the associated
1181 ** iOrderByCol value to one more than the index of the ORDER BY
1182 ** expression within the sort-key that pushOntoSorter() will generate.
1183 ** This allows the p->pEList field to be omitted from the sorted record,
1184 ** saving space and CPU cycles. */
1185 ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
1187 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
1188 int j;
1189 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
1190 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
1193 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1194 selectExprDefer(pParse, pSort, p->pEList, &pExtra);
1195 if( pExtra && pParse->db->mallocFailed==0 ){
1196 /* If there are any extra PK columns to add to the sorter records,
1197 ** allocate extra memory cells and adjust the OpenEphemeral
1198 ** instruction to account for the larger records. This is only
1199 ** required if there are one or more WITHOUT ROWID tables with
1200 ** composite primary keys in the SortCtx.aDefer[] array. */
1201 VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
1202 pOp->p2 += (pExtra->nExpr - pSort->nDefer);
1203 pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
1204 pParse->nMem += pExtra->nExpr;
1206 #endif
1208 /* Adjust nResultCol to account for columns that are omitted
1209 ** from the sorter by the optimizations in this branch */
1210 pEList = p->pEList;
1211 for(i=0; i<pEList->nExpr; i++){
1212 if( pEList->a[i].u.x.iOrderByCol>0
1213 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1214 || pEList->a[i].fg.bSorterRef
1215 #endif
1217 nResultCol--;
1218 regOrig = 0;
1222 testcase( regOrig );
1223 testcase( eDest==SRT_Set );
1224 testcase( eDest==SRT_Mem );
1225 testcase( eDest==SRT_Coroutine );
1226 testcase( eDest==SRT_Output );
1227 assert( eDest==SRT_Set || eDest==SRT_Mem
1228 || eDest==SRT_Coroutine || eDest==SRT_Output
1229 || eDest==SRT_Upfrom );
1231 sRowLoadInfo.regResult = regResult;
1232 sRowLoadInfo.ecelFlags = ecelFlags;
1233 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1234 sRowLoadInfo.pExtra = pExtra;
1235 sRowLoadInfo.regExtraResult = regResult + nResultCol;
1236 if( pExtra ) nResultCol += pExtra->nExpr;
1237 #endif
1238 if( p->iLimit
1239 && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
1240 && nPrefixReg>0
1242 assert( pSort!=0 );
1243 assert( hasDistinct==0 );
1244 pSort->pDeferredRowLoad = &sRowLoadInfo;
1245 regOrig = 0;
1246 }else{
1247 innerLoopLoadRow(pParse, p, &sRowLoadInfo);
1251 /* If the DISTINCT keyword was present on the SELECT statement
1252 ** and this row has been seen before, then do not make this row
1253 ** part of the result.
1255 if( hasDistinct ){
1256 int eType = pDistinct->eTnctType;
1257 int iTab = pDistinct->tabTnct;
1258 assert( nResultCol==p->pEList->nExpr );
1259 iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
1260 fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
1261 if( pSort==0 ){
1262 codeOffset(v, p->iOffset, iContinue);
1266 switch( eDest ){
1267 /* In this mode, write each query result to the key of the temporary
1268 ** table iParm.
1270 #ifndef SQLITE_OMIT_COMPOUND_SELECT
1271 case SRT_Union: {
1272 int r1;
1273 r1 = sqlite3GetTempReg(pParse);
1274 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1);
1275 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1276 sqlite3ReleaseTempReg(pParse, r1);
1277 break;
1280 /* Construct a record from the query result, but instead of
1281 ** saving that record, use it as a key to delete elements from
1282 ** the temporary table iParm.
1284 case SRT_Except: {
1285 sqlite3VdbeAddOp3(v, OP_IdxDelete, iParm, regResult, nResultCol);
1286 break;
1288 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
1290 /* Store the result as data using a unique key.
1292 case SRT_Fifo:
1293 case SRT_DistFifo:
1294 case SRT_Table:
1295 case SRT_EphemTab: {
1296 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
1297 testcase( eDest==SRT_Table );
1298 testcase( eDest==SRT_EphemTab );
1299 testcase( eDest==SRT_Fifo );
1300 testcase( eDest==SRT_DistFifo );
1301 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
1302 #if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
1303 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
1304 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
1305 ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
1306 ** This does not affect operation in any way - it just allows MakeRecord
1307 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
1308 if( eDest==SRT_Table && pDest->iSDParm2 ){
1309 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
1311 #endif
1312 #ifndef SQLITE_OMIT_CTE
1313 if( eDest==SRT_DistFifo ){
1314 /* If the destination is DistFifo, then cursor (iParm+1) is open
1315 ** on an ephemeral index. If the current row is already present
1316 ** in the index, do not write it to the output. If not, add the
1317 ** current row to the index and proceed with writing it to the
1318 ** output table as well. */
1319 int addr = sqlite3VdbeCurrentAddr(v) + 4;
1320 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
1321 VdbeCoverage(v);
1322 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
1323 assert( pSort==0 );
1325 #endif
1326 if( pSort ){
1327 assert( regResult==regOrig );
1328 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
1329 }else{
1330 int r2 = sqlite3GetTempReg(pParse);
1331 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
1332 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
1333 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1334 sqlite3ReleaseTempReg(pParse, r2);
1336 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
1337 break;
1340 case SRT_Upfrom: {
1341 if( pSort ){
1342 pushOntoSorter(
1343 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1344 }else{
1345 int i2 = pDest->iSDParm2;
1346 int r1 = sqlite3GetTempReg(pParse);
1348 /* If the UPDATE FROM join is an aggregate that matches no rows, it
1349 ** might still be trying to return one row, because that is what
1350 ** aggregates do. Don't record that empty row in the output table. */
1351 sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
1353 sqlite3VdbeAddOp3(v, OP_MakeRecord,
1354 regResult+(i2<0), nResultCol-(i2<0), r1);
1355 if( i2<0 ){
1356 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
1357 }else{
1358 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
1361 break;
1364 #ifndef SQLITE_OMIT_SUBQUERY
1365 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1366 ** then there should be a single item on the stack. Write this
1367 ** item into the set table with bogus data.
1369 case SRT_Set: {
1370 if( pSort ){
1371 /* At first glance you would think we could optimize out the
1372 ** ORDER BY in this case since the order of entries in the set
1373 ** does not matter. But there might be a LIMIT clause, in which
1374 ** case the order does matter */
1375 pushOntoSorter(
1376 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1377 }else{
1378 int r1 = sqlite3GetTempReg(pParse);
1379 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
1380 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
1381 r1, pDest->zAffSdst, nResultCol);
1382 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1383 sqlite3ReleaseTempReg(pParse, r1);
1385 break;
1389 /* If any row exist in the result set, record that fact and abort.
1391 case SRT_Exists: {
1392 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
1393 /* The LIMIT clause will terminate the loop for us */
1394 break;
1397 /* If this is a scalar select that is part of an expression, then
1398 ** store the results in the appropriate memory cell or array of
1399 ** memory cells and break out of the scan loop.
1401 case SRT_Mem: {
1402 if( pSort ){
1403 assert( nResultCol<=pDest->nSdst );
1404 pushOntoSorter(
1405 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1406 }else{
1407 assert( nResultCol==pDest->nSdst );
1408 assert( regResult==iParm );
1409 /* The LIMIT clause will jump out of the loop for us */
1411 break;
1413 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1415 case SRT_Coroutine: /* Send data to a co-routine */
1416 case SRT_Output: { /* Return the results */
1417 testcase( eDest==SRT_Coroutine );
1418 testcase( eDest==SRT_Output );
1419 if( pSort ){
1420 pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
1421 nPrefixReg);
1422 }else if( eDest==SRT_Coroutine ){
1423 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1424 }else{
1425 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
1427 break;
1430 #ifndef SQLITE_OMIT_CTE
1431 /* Write the results into a priority queue that is order according to
1432 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
1433 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
1434 ** pSO->nExpr columns, then make sure all keys are unique by adding a
1435 ** final OP_Sequence column. The last column is the record as a blob.
1437 case SRT_DistQueue:
1438 case SRT_Queue: {
1439 int nKey;
1440 int r1, r2, r3;
1441 int addrTest = 0;
1442 ExprList *pSO;
1443 pSO = pDest->pOrderBy;
1444 assert( pSO );
1445 nKey = pSO->nExpr;
1446 r1 = sqlite3GetTempReg(pParse);
1447 r2 = sqlite3GetTempRange(pParse, nKey+2);
1448 r3 = r2+nKey+1;
1449 if( eDest==SRT_DistQueue ){
1450 /* If the destination is DistQueue, then cursor (iParm+1) is open
1451 ** on a second ephemeral index that holds all values every previously
1452 ** added to the queue. */
1453 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
1454 regResult, nResultCol);
1455 VdbeCoverage(v);
1457 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
1458 if( eDest==SRT_DistQueue ){
1459 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
1460 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1462 for(i=0; i<nKey; i++){
1463 sqlite3VdbeAddOp2(v, OP_SCopy,
1464 regResult + pSO->a[i].u.x.iOrderByCol - 1,
1465 r2+i);
1467 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
1468 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
1469 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
1470 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1471 sqlite3ReleaseTempReg(pParse, r1);
1472 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1473 break;
1475 #endif /* SQLITE_OMIT_CTE */
1479 #if !defined(SQLITE_OMIT_TRIGGER)
1480 /* Discard the results. This is used for SELECT statements inside
1481 ** the body of a TRIGGER. The purpose of such selects is to call
1482 ** user-defined functions that have side effects. We do not care
1483 ** about the actual results of the select.
1485 default: {
1486 assert( eDest==SRT_Discard );
1487 break;
1489 #endif
1492 /* Jump to the end of the loop if the LIMIT is reached. Except, if
1493 ** there is a sorter, in which case the sorter has already limited
1494 ** the output for us.
1496 if( pSort==0 && p->iLimit ){
1497 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1502 ** Allocate a KeyInfo object sufficient for an index of N key columns and
1503 ** X extra columns.
1505 KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1506 int nExtra = (N+X)*(sizeof(CollSeq*)+1) - sizeof(CollSeq*);
1507 KeyInfo *p = sqlite3DbMallocRawNN(db, sizeof(KeyInfo) + nExtra);
1508 if( p ){
1509 p->aSortFlags = (u8*)&p->aColl[N+X];
1510 p->nKeyField = (u16)N;
1511 p->nAllField = (u16)(N+X);
1512 p->enc = ENC(db);
1513 p->db = db;
1514 p->nRef = 1;
1515 memset(&p[1], 0, nExtra);
1516 }else{
1517 return (KeyInfo*)sqlite3OomFault(db);
1519 return p;
1523 ** Deallocate a KeyInfo object
1525 void sqlite3KeyInfoUnref(KeyInfo *p){
1526 if( p ){
1527 assert( p->db!=0 );
1528 assert( p->nRef>0 );
1529 p->nRef--;
1530 if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
1535 ** Make a new pointer to a KeyInfo object
1537 KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
1538 if( p ){
1539 assert( p->nRef>0 );
1540 p->nRef++;
1542 return p;
1545 #ifdef SQLITE_DEBUG
1547 ** Return TRUE if a KeyInfo object can be change. The KeyInfo object
1548 ** can only be changed if this is just a single reference to the object.
1550 ** This routine is used only inside of assert() statements.
1552 int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
1553 #endif /* SQLITE_DEBUG */
1556 ** Given an expression list, generate a KeyInfo structure that records
1557 ** the collating sequence for each expression in that expression list.
1559 ** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
1560 ** KeyInfo structure is appropriate for initializing a virtual index to
1561 ** implement that clause. If the ExprList is the result set of a SELECT
1562 ** then the KeyInfo structure is appropriate for initializing a virtual
1563 ** index to implement a DISTINCT test.
1565 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
1566 ** function is responsible for seeing that this structure is eventually
1567 ** freed.
1569 KeyInfo *sqlite3KeyInfoFromExprList(
1570 Parse *pParse, /* Parsing context */
1571 ExprList *pList, /* Form the KeyInfo object from this ExprList */
1572 int iStart, /* Begin with this column of pList */
1573 int nExtra /* Add this many extra columns to the end */
1575 int nExpr;
1576 KeyInfo *pInfo;
1577 struct ExprList_item *pItem;
1578 sqlite3 *db = pParse->db;
1579 int i;
1581 nExpr = pList->nExpr;
1582 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1583 if( pInfo ){
1584 assert( sqlite3KeyInfoIsWriteable(pInfo) );
1585 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1586 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
1587 pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
1590 return pInfo;
1594 ** Name of the connection operator, used for error messages.
1596 const char *sqlite3SelectOpName(int id){
1597 char *z;
1598 switch( id ){
1599 case TK_ALL: z = "UNION ALL"; break;
1600 case TK_INTERSECT: z = "INTERSECT"; break;
1601 case TK_EXCEPT: z = "EXCEPT"; break;
1602 default: z = "UNION"; break;
1604 return z;
1607 #ifndef SQLITE_OMIT_EXPLAIN
1609 ** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1610 ** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1611 ** where the caption is of the form:
1613 ** "USE TEMP B-TREE FOR xxx"
1615 ** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
1616 ** is determined by the zUsage argument.
1618 static void explainTempTable(Parse *pParse, const char *zUsage){
1619 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
1623 ** Assign expression b to lvalue a. A second, no-op, version of this macro
1624 ** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1625 ** in sqlite3Select() to assign values to structure member variables that
1626 ** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1627 ** code with #ifndef directives.
1629 # define explainSetInteger(a, b) a = b
1631 #else
1632 /* No-op versions of the explainXXX() functions and macros. */
1633 # define explainTempTable(y,z)
1634 # define explainSetInteger(y,z)
1635 #endif
1639 ** If the inner loop was generated using a non-null pOrderBy argument,
1640 ** then the results were placed in a sorter. After the loop is terminated
1641 ** we need to run the sorter and output the results. The following
1642 ** routine generates the code needed to do that.
1644 static void generateSortTail(
1645 Parse *pParse, /* Parsing context */
1646 Select *p, /* The SELECT statement */
1647 SortCtx *pSort, /* Information on the ORDER BY clause */
1648 int nColumn, /* Number of columns of data */
1649 SelectDest *pDest /* Write the sorted results here */
1651 Vdbe *v = pParse->pVdbe; /* The prepared statement */
1652 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
1653 int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
1654 int addr; /* Top of output loop. Jump for Next. */
1655 int addrOnce = 0;
1656 int iTab;
1657 ExprList *pOrderBy = pSort->pOrderBy;
1658 int eDest = pDest->eDest;
1659 int iParm = pDest->iSDParm;
1660 int regRow;
1661 int regRowid;
1662 int iCol;
1663 int nKey; /* Number of key columns in sorter record */
1664 int iSortTab; /* Sorter cursor to read from */
1665 int i;
1666 int bSeq; /* True if sorter record includes seq. no. */
1667 int nRefKey = 0;
1668 struct ExprList_item *aOutEx = p->pEList->a;
1669 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1670 int addrExplain; /* Address of OP_Explain instruction */
1671 #endif
1673 ExplainQueryPlan2(addrExplain, (pParse, 0,
1674 "USE TEMP B-TREE FOR %sORDER BY", pSort->nOBSat>0?"RIGHT PART OF ":"")
1676 sqlite3VdbeScanStatusRange(v, addrExplain,pSort->addrPush,pSort->addrPushEnd);
1677 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, pSort->addrPush);
1680 assert( addrBreak<0 );
1681 if( pSort->labelBkOut ){
1682 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1683 sqlite3VdbeGoto(v, addrBreak);
1684 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1687 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1688 /* Open any cursors needed for sorter-reference expressions */
1689 for(i=0; i<pSort->nDefer; i++){
1690 Table *pTab = pSort->aDefer[i].pTab;
1691 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1692 sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
1693 nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
1695 #endif
1697 iTab = pSort->iECursor;
1698 if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
1699 if( eDest==SRT_Mem && p->iOffset ){
1700 sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
1702 regRowid = 0;
1703 regRow = pDest->iSdst;
1704 }else{
1705 regRowid = sqlite3GetTempReg(pParse);
1706 if( eDest==SRT_EphemTab || eDest==SRT_Table ){
1707 regRow = sqlite3GetTempReg(pParse);
1708 nColumn = 0;
1709 }else{
1710 regRow = sqlite3GetTempRange(pParse, nColumn);
1713 nKey = pOrderBy->nExpr - pSort->nOBSat;
1714 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1715 int regSortOut = ++pParse->nMem;
1716 iSortTab = pParse->nTab++;
1717 if( pSort->labelBkOut ){
1718 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1720 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
1721 nKey+1+nColumn+nRefKey);
1722 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1723 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1724 VdbeCoverage(v);
1725 assert( p->iLimit==0 && p->iOffset==0 );
1726 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
1727 bSeq = 0;
1728 }else{
1729 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1730 codeOffset(v, p->iOffset, addrContinue);
1731 iSortTab = iTab;
1732 bSeq = 1;
1733 if( p->iOffset>0 ){
1734 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1737 for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
1738 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1739 if( aOutEx[i].fg.bSorterRef ) continue;
1740 #endif
1741 if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
1743 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1744 if( pSort->nDefer ){
1745 int iKey = iCol+1;
1746 int regKey = sqlite3GetTempRange(pParse, nRefKey);
1748 for(i=0; i<pSort->nDefer; i++){
1749 int iCsr = pSort->aDefer[i].iCsr;
1750 Table *pTab = pSort->aDefer[i].pTab;
1751 int nKey = pSort->aDefer[i].nKey;
1753 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1754 if( HasRowid(pTab) ){
1755 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
1756 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
1757 sqlite3VdbeCurrentAddr(v)+1, regKey);
1758 }else{
1759 int k;
1760 int iJmp;
1761 assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
1762 for(k=0; k<nKey; k++){
1763 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
1765 iJmp = sqlite3VdbeCurrentAddr(v);
1766 sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
1767 sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
1768 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1771 sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
1773 #endif
1774 for(i=nColumn-1; i>=0; i--){
1775 #ifdef SQLITE_ENABLE_SORTER_REFERENCES
1776 if( aOutEx[i].fg.bSorterRef ){
1777 sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
1778 }else
1779 #endif
1781 int iRead;
1782 if( aOutEx[i].u.x.iOrderByCol ){
1783 iRead = aOutEx[i].u.x.iOrderByCol-1;
1784 }else{
1785 iRead = iCol--;
1787 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
1788 VdbeComment((v, "%s", aOutEx[i].zEName));
1791 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
1792 switch( eDest ){
1793 case SRT_Table:
1794 case SRT_EphemTab: {
1795 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
1796 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1797 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1798 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1799 break;
1801 #ifndef SQLITE_OMIT_SUBQUERY
1802 case SRT_Set: {
1803 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
1804 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
1805 pDest->zAffSdst, nColumn);
1806 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
1807 break;
1809 case SRT_Mem: {
1810 /* The LIMIT clause will terminate the loop for us */
1811 break;
1813 #endif
1814 case SRT_Upfrom: {
1815 int i2 = pDest->iSDParm2;
1816 int r1 = sqlite3GetTempReg(pParse);
1817 sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
1818 if( i2<0 ){
1819 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
1820 }else{
1821 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
1823 break;
1825 default: {
1826 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
1827 testcase( eDest==SRT_Output );
1828 testcase( eDest==SRT_Coroutine );
1829 if( eDest==SRT_Output ){
1830 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1831 }else{
1832 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1834 break;
1837 if( regRowid ){
1838 if( eDest==SRT_Set ){
1839 sqlite3ReleaseTempRange(pParse, regRow, nColumn);
1840 }else{
1841 sqlite3ReleaseTempReg(pParse, regRow);
1843 sqlite3ReleaseTempReg(pParse, regRowid);
1845 /* The bottom of the loop
1847 sqlite3VdbeResolveLabel(v, addrContinue);
1848 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1849 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1850 }else{
1851 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1853 sqlite3VdbeScanStatusRange(v, addrExplain, sqlite3VdbeCurrentAddr(v)-1, -1);
1854 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1855 sqlite3VdbeResolveLabel(v, addrBreak);
1859 ** Return a pointer to a string containing the 'declaration type' of the
1860 ** expression pExpr. The string may be treated as static by the caller.
1862 ** The declaration type is the exact datatype definition extracted from the
1863 ** original CREATE TABLE statement if the expression is a column. The
1864 ** declaration type for a ROWID field is INTEGER. Exactly when an expression
1865 ** is considered a column can be complex in the presence of subqueries. The
1866 ** result-set expression in all of the following SELECT statements is
1867 ** considered a column by this function.
1869 ** SELECT col FROM tbl;
1870 ** SELECT (SELECT col FROM tbl;
1871 ** SELECT (SELECT col FROM tbl);
1872 ** SELECT abc FROM (SELECT col AS abc FROM tbl);
1874 ** The declaration type for any expression other than a column is NULL.
1876 ** This routine has either 3 or 6 parameters depending on whether or not
1877 ** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
1879 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1880 # define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
1881 #else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
1882 # define columnType(A,B,C,D,E) columnTypeImpl(A,B)
1883 #endif
1884 static const char *columnTypeImpl(
1885 NameContext *pNC,
1886 #ifndef SQLITE_ENABLE_COLUMN_METADATA
1887 Expr *pExpr
1888 #else
1889 Expr *pExpr,
1890 const char **pzOrigDb,
1891 const char **pzOrigTab,
1892 const char **pzOrigCol
1893 #endif
1895 char const *zType = 0;
1896 int j;
1897 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1898 char const *zOrigDb = 0;
1899 char const *zOrigTab = 0;
1900 char const *zOrigCol = 0;
1901 #endif
1903 assert( pExpr!=0 );
1904 assert( pNC->pSrcList!=0 );
1905 switch( pExpr->op ){
1906 case TK_COLUMN: {
1907 /* The expression is a column. Locate the table the column is being
1908 ** extracted from in NameContext.pSrcList. This table may be real
1909 ** database table or a subquery.
1911 Table *pTab = 0; /* Table structure column is extracted from */
1912 Select *pS = 0; /* Select the column is extracted from */
1913 int iCol = pExpr->iColumn; /* Index of column in pTab */
1914 while( pNC && !pTab ){
1915 SrcList *pTabList = pNC->pSrcList;
1916 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
1917 if( j<pTabList->nSrc ){
1918 pTab = pTabList->a[j].pTab;
1919 pS = pTabList->a[j].pSelect;
1920 }else{
1921 pNC = pNC->pNext;
1925 if( pTab==0 ){
1926 /* At one time, code such as "SELECT new.x" within a trigger would
1927 ** cause this condition to run. Since then, we have restructured how
1928 ** trigger code is generated and so this condition is no longer
1929 ** possible. However, it can still be true for statements like
1930 ** the following:
1932 ** CREATE TABLE t1(col INTEGER);
1933 ** SELECT (SELECT t1.col) FROM FROM t1;
1935 ** when columnType() is called on the expression "t1.col" in the
1936 ** sub-select. In this case, set the column type to NULL, even
1937 ** though it should really be "INTEGER".
1939 ** This is not a problem, as the column type of "t1.col" is never
1940 ** used. When columnType() is called on the expression
1941 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
1942 ** branch below. */
1943 break;
1946 assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
1947 if( pS ){
1948 /* The "table" is actually a sub-select or a view in the FROM clause
1949 ** of the SELECT statement. Return the declaration type and origin
1950 ** data for the result-set column of the sub-select.
1952 if( iCol<pS->pEList->nExpr
1953 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
1954 && iCol>=0
1955 #else
1956 && ALWAYS(iCol>=0)
1957 #endif
1959 /* If iCol is less than zero, then the expression requests the
1960 ** rowid of the sub-select or view. This expression is legal (see
1961 ** test case misc2.2.2) - it always evaluates to NULL.
1963 NameContext sNC;
1964 Expr *p = pS->pEList->a[iCol].pExpr;
1965 sNC.pSrcList = pS->pSrc;
1966 sNC.pNext = pNC;
1967 sNC.pParse = pNC->pParse;
1968 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
1970 }else{
1971 /* A real table or a CTE table */
1972 assert( !pS );
1973 #ifdef SQLITE_ENABLE_COLUMN_METADATA
1974 if( iCol<0 ) iCol = pTab->iPKey;
1975 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1976 if( iCol<0 ){
1977 zType = "INTEGER";
1978 zOrigCol = "rowid";
1979 }else{
1980 zOrigCol = pTab->aCol[iCol].zCnName;
1981 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
1983 zOrigTab = pTab->zName;
1984 if( pNC->pParse && pTab->pSchema ){
1985 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
1986 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
1988 #else
1989 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
1990 if( iCol<0 ){
1991 zType = "INTEGER";
1992 }else{
1993 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
1995 #endif
1997 break;
1999 #ifndef SQLITE_OMIT_SUBQUERY
2000 case TK_SELECT: {
2001 /* The expression is a sub-select. Return the declaration type and
2002 ** origin info for the single column in the result set of the SELECT
2003 ** statement.
2005 NameContext sNC;
2006 Select *pS;
2007 Expr *p;
2008 assert( ExprUseXSelect(pExpr) );
2009 pS = pExpr->x.pSelect;
2010 p = pS->pEList->a[0].pExpr;
2011 sNC.pSrcList = pS->pSrc;
2012 sNC.pNext = pNC;
2013 sNC.pParse = pNC->pParse;
2014 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2015 break;
2017 #endif
2020 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2021 if( pzOrigDb ){
2022 assert( pzOrigTab && pzOrigCol );
2023 *pzOrigDb = zOrigDb;
2024 *pzOrigTab = zOrigTab;
2025 *pzOrigCol = zOrigCol;
2027 #endif
2028 return zType;
2032 ** Generate code that will tell the VDBE the declaration types of columns
2033 ** in the result set.
2035 static void generateColumnTypes(
2036 Parse *pParse, /* Parser context */
2037 SrcList *pTabList, /* List of tables */
2038 ExprList *pEList /* Expressions defining the result set */
2040 #ifndef SQLITE_OMIT_DECLTYPE
2041 Vdbe *v = pParse->pVdbe;
2042 int i;
2043 NameContext sNC;
2044 sNC.pSrcList = pTabList;
2045 sNC.pParse = pParse;
2046 sNC.pNext = 0;
2047 for(i=0; i<pEList->nExpr; i++){
2048 Expr *p = pEList->a[i].pExpr;
2049 const char *zType;
2050 #ifdef SQLITE_ENABLE_COLUMN_METADATA
2051 const char *zOrigDb = 0;
2052 const char *zOrigTab = 0;
2053 const char *zOrigCol = 0;
2054 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2056 /* The vdbe must make its own copy of the column-type and other
2057 ** column specific strings, in case the schema is reset before this
2058 ** virtual machine is deleted.
2060 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
2061 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
2062 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
2063 #else
2064 zType = columnType(&sNC, p, 0, 0, 0);
2065 #endif
2066 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
2068 #endif /* !defined(SQLITE_OMIT_DECLTYPE) */
2073 ** Compute the column names for a SELECT statement.
2075 ** The only guarantee that SQLite makes about column names is that if the
2076 ** column has an AS clause assigning it a name, that will be the name used.
2077 ** That is the only documented guarantee. However, countless applications
2078 ** developed over the years have made baseless assumptions about column names
2079 ** and will break if those assumptions changes. Hence, use extreme caution
2080 ** when modifying this routine to avoid breaking legacy.
2082 ** See Also: sqlite3ColumnsFromExprList()
2084 ** The PRAGMA short_column_names and PRAGMA full_column_names settings are
2085 ** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
2086 ** applications should operate this way. Nevertheless, we need to support the
2087 ** other modes for legacy:
2089 ** short=OFF, full=OFF: Column name is the text of the expression has it
2090 ** originally appears in the SELECT statement. In
2091 ** other words, the zSpan of the result expression.
2093 ** short=ON, full=OFF: (This is the default setting). If the result
2094 ** refers directly to a table column, then the
2095 ** result column name is just the table column
2096 ** name: COLUMN. Otherwise use zSpan.
2098 ** full=ON, short=ANY: If the result refers directly to a table column,
2099 ** then the result column name with the table name
2100 ** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
2102 void sqlite3GenerateColumnNames(
2103 Parse *pParse, /* Parser context */
2104 Select *pSelect /* Generate column names for this SELECT statement */
2106 Vdbe *v = pParse->pVdbe;
2107 int i;
2108 Table *pTab;
2109 SrcList *pTabList;
2110 ExprList *pEList;
2111 sqlite3 *db = pParse->db;
2112 int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
2113 int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
2115 if( pParse->colNamesSet ) return;
2116 /* Column names are determined by the left-most term of a compound select */
2117 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2118 TREETRACE(0x80,pParse,pSelect,("generating column names\n"));
2119 pTabList = pSelect->pSrc;
2120 pEList = pSelect->pEList;
2121 assert( v!=0 );
2122 assert( pTabList!=0 );
2123 pParse->colNamesSet = 1;
2124 fullName = (db->flags & SQLITE_FullColNames)!=0;
2125 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
2126 sqlite3VdbeSetNumCols(v, pEList->nExpr);
2127 for(i=0; i<pEList->nExpr; i++){
2128 Expr *p = pEList->a[i].pExpr;
2130 assert( p!=0 );
2131 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
2132 assert( p->op!=TK_COLUMN
2133 || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
2134 if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
2135 /* An AS clause always takes first priority */
2136 char *zName = pEList->a[i].zEName;
2137 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
2138 }else if( srcName && p->op==TK_COLUMN ){
2139 char *zCol;
2140 int iCol = p->iColumn;
2141 pTab = p->y.pTab;
2142 assert( pTab!=0 );
2143 if( iCol<0 ) iCol = pTab->iPKey;
2144 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
2145 if( iCol<0 ){
2146 zCol = "rowid";
2147 }else{
2148 zCol = pTab->aCol[iCol].zCnName;
2150 if( fullName ){
2151 char *zName = 0;
2152 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
2153 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
2154 }else{
2155 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
2157 }else{
2158 const char *z = pEList->a[i].zEName;
2159 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
2160 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
2163 generateColumnTypes(pParse, pTabList, pEList);
2167 ** Given an expression list (which is really the list of expressions
2168 ** that form the result set of a SELECT statement) compute appropriate
2169 ** column names for a table that would hold the expression list.
2171 ** All column names will be unique.
2173 ** Only the column names are computed. Column.zType, Column.zColl,
2174 ** and other fields of Column are zeroed.
2176 ** Return SQLITE_OK on success. If a memory allocation error occurs,
2177 ** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
2179 ** The only guarantee that SQLite makes about column names is that if the
2180 ** column has an AS clause assigning it a name, that will be the name used.
2181 ** That is the only documented guarantee. However, countless applications
2182 ** developed over the years have made baseless assumptions about column names
2183 ** and will break if those assumptions changes. Hence, use extreme caution
2184 ** when modifying this routine to avoid breaking legacy.
2186 ** See Also: sqlite3GenerateColumnNames()
2188 int sqlite3ColumnsFromExprList(
2189 Parse *pParse, /* Parsing context */
2190 ExprList *pEList, /* Expr list from which to derive column names */
2191 i16 *pnCol, /* Write the number of columns here */
2192 Column **paCol /* Write the new column list here */
2194 sqlite3 *db = pParse->db; /* Database connection */
2195 int i, j; /* Loop counters */
2196 u32 cnt; /* Index added to make the name unique */
2197 Column *aCol, *pCol; /* For looping over result columns */
2198 int nCol; /* Number of columns in the result set */
2199 char *zName; /* Column name */
2200 int nName; /* Size of name in zName[] */
2201 Hash ht; /* Hash table of column names */
2202 Table *pTab;
2204 sqlite3HashInit(&ht);
2205 if( pEList ){
2206 nCol = pEList->nExpr;
2207 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
2208 testcase( aCol==0 );
2209 if( NEVER(nCol>32767) ) nCol = 32767;
2210 }else{
2211 nCol = 0;
2212 aCol = 0;
2214 assert( nCol==(i16)nCol );
2215 *pnCol = nCol;
2216 *paCol = aCol;
2218 for(i=0, pCol=aCol; i<nCol && !pParse->nErr; i++, pCol++){
2219 struct ExprList_item *pX = &pEList->a[i];
2220 struct ExprList_item *pCollide;
2221 /* Get an appropriate name for the column
2223 if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
2224 /* If the column contains an "AS <name>" phrase, use <name> as the name */
2225 }else{
2226 Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
2227 while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
2228 pColExpr = pColExpr->pRight;
2229 assert( pColExpr!=0 );
2231 if( pColExpr->op==TK_COLUMN
2232 && ALWAYS( ExprUseYTab(pColExpr) )
2233 && ALWAYS( pColExpr->y.pTab!=0 )
2235 /* For columns use the column name name */
2236 int iCol = pColExpr->iColumn;
2237 pTab = pColExpr->y.pTab;
2238 if( iCol<0 ) iCol = pTab->iPKey;
2239 zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
2240 }else if( pColExpr->op==TK_ID ){
2241 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
2242 zName = pColExpr->u.zToken;
2243 }else{
2244 /* Use the original text of the column expression as its name */
2245 assert( zName==pX->zEName ); /* pointer comparison intended */
2248 if( zName && !sqlite3IsTrueOrFalse(zName) ){
2249 zName = sqlite3DbStrDup(db, zName);
2250 }else{
2251 zName = sqlite3MPrintf(db,"column%d",i+1);
2254 /* Make sure the column name is unique. If the name is not unique,
2255 ** append an integer to the name so that it becomes unique.
2257 cnt = 0;
2258 while( zName && (pCollide = sqlite3HashFind(&ht, zName))!=0 ){
2259 if( pCollide->fg.bUsingTerm ){
2260 pCol->colFlags |= COLFLAG_NOEXPAND;
2262 nName = sqlite3Strlen30(zName);
2263 if( nName>0 ){
2264 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
2265 if( zName[j]==':' ) nName = j;
2267 zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
2268 sqlite3ProgressCheck(pParse);
2269 if( cnt>3 ){
2270 sqlite3_randomness(sizeof(cnt), &cnt);
2273 pCol->zCnName = zName;
2274 pCol->hName = sqlite3StrIHash(zName);
2275 if( pX->fg.bNoExpand ){
2276 pCol->colFlags |= COLFLAG_NOEXPAND;
2278 sqlite3ColumnPropertiesFromName(0, pCol);
2279 if( zName && sqlite3HashInsert(&ht, zName, pX)==pX ){
2280 sqlite3OomFault(db);
2283 sqlite3HashClear(&ht);
2284 if( pParse->nErr ){
2285 for(j=0; j<i; j++){
2286 sqlite3DbFree(db, aCol[j].zCnName);
2288 sqlite3DbFree(db, aCol);
2289 *paCol = 0;
2290 *pnCol = 0;
2291 return pParse->rc;
2293 return SQLITE_OK;
2297 ** pTab is a transient Table object that represents a subquery of some
2298 ** kind (maybe a parenthesized subquery in the FROM clause of a larger
2299 ** query, or a VIEW, or a CTE). This routine computes type information
2300 ** for that Table object based on the Select object that implements the
2301 ** subquery. For the purposes of this routine, "type information" means:
2303 ** * The datatype name, as it might appear in a CREATE TABLE statement
2304 ** * Which collating sequence to use for the column
2305 ** * The affinity of the column
2307 void sqlite3SubqueryColumnTypes(
2308 Parse *pParse, /* Parsing contexts */
2309 Table *pTab, /* Add column type information to this table */
2310 Select *pSelect, /* SELECT used to determine types and collations */
2311 char aff /* Default affinity. */
2313 sqlite3 *db = pParse->db;
2314 Column *pCol;
2315 CollSeq *pColl;
2316 int i,j;
2317 Expr *p;
2318 struct ExprList_item *a;
2319 NameContext sNC;
2321 assert( pSelect!=0 );
2322 testcase( (pSelect->selFlags & SF_Resolved)==0 );
2323 assert( (pSelect->selFlags & SF_Resolved)!=0 || IN_RENAME_OBJECT );
2324 assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
2325 assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
2326 if( db->mallocFailed || IN_RENAME_OBJECT ) return;
2327 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2328 a = pSelect->pEList->a;
2329 memset(&sNC, 0, sizeof(sNC));
2330 sNC.pSrcList = pSelect->pSrc;
2331 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
2332 const char *zType;
2333 i64 n;
2334 pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
2335 p = a[i].pExpr;
2336 /* pCol->szEst = ... // Column size est for SELECT tables never used */
2337 pCol->affinity = sqlite3ExprAffinity(p);
2338 if( pCol->affinity<=SQLITE_AFF_NONE ){
2339 pCol->affinity = aff;
2341 if( pCol->affinity>=SQLITE_AFF_TEXT && pSelect->pNext ){
2342 int m = 0;
2343 Select *pS2;
2344 for(m=0, pS2=pSelect->pNext; pS2; pS2=pS2->pNext){
2345 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
2347 if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
2348 pCol->affinity = SQLITE_AFF_BLOB;
2349 }else
2350 if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
2351 pCol->affinity = SQLITE_AFF_BLOB;
2353 if( pCol->affinity>=SQLITE_AFF_NUMERIC && p->op==TK_CAST ){
2354 pCol->affinity = SQLITE_AFF_FLEXNUM;
2357 zType = columnType(&sNC, p, 0, 0, 0);
2358 if( zType==0 || pCol->affinity!=sqlite3AffinityType(zType, 0) ){
2359 if( pCol->affinity==SQLITE_AFF_NUMERIC
2360 || pCol->affinity==SQLITE_AFF_FLEXNUM
2362 zType = "NUM";
2363 }else{
2364 zType = 0;
2365 for(j=1; j<SQLITE_N_STDTYPE; j++){
2366 if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
2367 zType = sqlite3StdType[j];
2368 break;
2373 if( zType ){
2374 i64 m = sqlite3Strlen30(zType);
2375 n = sqlite3Strlen30(pCol->zCnName);
2376 pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+m+2);
2377 pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
2378 if( pCol->zCnName ){
2379 memcpy(&pCol->zCnName[n+1], zType, m+1);
2380 pCol->colFlags |= COLFLAG_HASTYPE;
2383 pColl = sqlite3ExprCollSeq(pParse, p);
2384 if( pColl ){
2385 assert( pTab->pIndex==0 );
2386 sqlite3ColumnSetColl(db, pCol, pColl->zName);
2389 pTab->szTabRow = 1; /* Any non-zero value works */
2393 ** Given a SELECT statement, generate a Table structure that describes
2394 ** the result set of that SELECT.
2396 Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
2397 Table *pTab;
2398 sqlite3 *db = pParse->db;
2399 u64 savedFlags;
2401 savedFlags = db->flags;
2402 db->flags &= ~(u64)SQLITE_FullColNames;
2403 db->flags |= SQLITE_ShortColNames;
2404 sqlite3SelectPrep(pParse, pSelect, 0);
2405 db->flags = savedFlags;
2406 if( pParse->nErr ) return 0;
2407 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2408 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
2409 if( pTab==0 ){
2410 return 0;
2412 pTab->nTabRef = 1;
2413 pTab->zName = 0;
2414 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
2415 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
2416 sqlite3SubqueryColumnTypes(pParse, pTab, pSelect, aff);
2417 pTab->iPKey = -1;
2418 if( db->mallocFailed ){
2419 sqlite3DeleteTable(db, pTab);
2420 return 0;
2422 return pTab;
2426 ** Get a VDBE for the given parser context. Create a new one if necessary.
2427 ** If an error occurs, return NULL and leave a message in pParse.
2429 Vdbe *sqlite3GetVdbe(Parse *pParse){
2430 if( pParse->pVdbe ){
2431 return pParse->pVdbe;
2433 if( pParse->pToplevel==0
2434 && OptimizationEnabled(pParse->db,SQLITE_FactorOutConst)
2436 pParse->okConstFactor = 1;
2438 return sqlite3VdbeCreate(pParse);
2443 ** Compute the iLimit and iOffset fields of the SELECT based on the
2444 ** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
2445 ** that appear in the original SQL statement after the LIMIT and OFFSET
2446 ** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
2447 ** are the integer memory register numbers for counters used to compute
2448 ** the limit and offset. If there is no limit and/or offset, then
2449 ** iLimit and iOffset are negative.
2451 ** This routine changes the values of iLimit and iOffset only if
2452 ** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
2453 ** and iOffset should have been preset to appropriate default values (zero)
2454 ** prior to calling this routine.
2456 ** The iOffset register (if it exists) is initialized to the value
2457 ** of the OFFSET. The iLimit register is initialized to LIMIT. Register
2458 ** iOffset+1 is initialized to LIMIT+OFFSET.
2460 ** Only if pLimit->pLeft!=0 do the limit registers get
2461 ** redefined. The UNION ALL operator uses this property to force
2462 ** the reuse of the same limit and offset registers across multiple
2463 ** SELECT statements.
2465 static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
2466 Vdbe *v = 0;
2467 int iLimit = 0;
2468 int iOffset;
2469 int n;
2470 Expr *pLimit = p->pLimit;
2472 if( p->iLimit ) return;
2475 ** "LIMIT -1" always shows all rows. There is some
2476 ** controversy about what the correct behavior should be.
2477 ** The current implementation interprets "LIMIT 0" to mean
2478 ** no rows.
2480 if( pLimit ){
2481 assert( pLimit->op==TK_LIMIT );
2482 assert( pLimit->pLeft!=0 );
2483 p->iLimit = iLimit = ++pParse->nMem;
2484 v = sqlite3GetVdbe(pParse);
2485 assert( v!=0 );
2486 if( sqlite3ExprIsInteger(pLimit->pLeft, &n) ){
2487 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
2488 VdbeComment((v, "LIMIT counter"));
2489 if( n==0 ){
2490 sqlite3VdbeGoto(v, iBreak);
2491 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
2492 p->nSelectRow = sqlite3LogEst((u64)n);
2493 p->selFlags |= SF_FixedLimit;
2495 }else{
2496 sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
2497 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
2498 VdbeComment((v, "LIMIT counter"));
2499 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
2501 if( pLimit->pRight ){
2502 p->iOffset = iOffset = ++pParse->nMem;
2503 pParse->nMem++; /* Allocate an extra register for limit+offset */
2504 sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
2505 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
2506 VdbeComment((v, "OFFSET counter"));
2507 sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
2508 VdbeComment((v, "LIMIT+OFFSET"));
2513 #ifndef SQLITE_OMIT_COMPOUND_SELECT
2515 ** Return the appropriate collating sequence for the iCol-th column of
2516 ** the result set for the compound-select statement "p". Return NULL if
2517 ** the column has no default collating sequence.
2519 ** The collating sequence for the compound select is taken from the
2520 ** left-most term of the select that has a collating sequence.
2522 static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
2523 CollSeq *pRet;
2524 if( p->pPrior ){
2525 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
2526 }else{
2527 pRet = 0;
2529 assert( iCol>=0 );
2530 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
2531 ** have been thrown during name resolution and we would not have gotten
2532 ** this far */
2533 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr) ){
2534 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
2536 return pRet;
2540 ** The select statement passed as the second parameter is a compound SELECT
2541 ** with an ORDER BY clause. This function allocates and returns a KeyInfo
2542 ** structure suitable for implementing the ORDER BY.
2544 ** Space to hold the KeyInfo structure is obtained from malloc. The calling
2545 ** function is responsible for ensuring that this structure is eventually
2546 ** freed.
2548 static KeyInfo *multiSelectOrderByKeyInfo(Parse *pParse, Select *p, int nExtra){
2549 ExprList *pOrderBy = p->pOrderBy;
2550 int nOrderBy = ALWAYS(pOrderBy!=0) ? pOrderBy->nExpr : 0;
2551 sqlite3 *db = pParse->db;
2552 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
2553 if( pRet ){
2554 int i;
2555 for(i=0; i<nOrderBy; i++){
2556 struct ExprList_item *pItem = &pOrderBy->a[i];
2557 Expr *pTerm = pItem->pExpr;
2558 CollSeq *pColl;
2560 if( pTerm->flags & EP_Collate ){
2561 pColl = sqlite3ExprCollSeq(pParse, pTerm);
2562 }else{
2563 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
2564 if( pColl==0 ) pColl = db->pDfltColl;
2565 pOrderBy->a[i].pExpr =
2566 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
2568 assert( sqlite3KeyInfoIsWriteable(pRet) );
2569 pRet->aColl[i] = pColl;
2570 pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
2574 return pRet;
2577 #ifndef SQLITE_OMIT_CTE
2579 ** This routine generates VDBE code to compute the content of a WITH RECURSIVE
2580 ** query of the form:
2582 ** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
2583 ** \___________/ \_______________/
2584 ** p->pPrior p
2587 ** There is exactly one reference to the recursive-table in the FROM clause
2588 ** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
2590 ** The setup-query runs once to generate an initial set of rows that go
2591 ** into a Queue table. Rows are extracted from the Queue table one by
2592 ** one. Each row extracted from Queue is output to pDest. Then the single
2593 ** extracted row (now in the iCurrent table) becomes the content of the
2594 ** recursive-table for a recursive-query run. The output of the recursive-query
2595 ** is added back into the Queue table. Then another row is extracted from Queue
2596 ** and the iteration continues until the Queue table is empty.
2598 ** If the compound query operator is UNION then no duplicate rows are ever
2599 ** inserted into the Queue table. The iDistinct table keeps a copy of all rows
2600 ** that have ever been inserted into Queue and causes duplicates to be
2601 ** discarded. If the operator is UNION ALL, then duplicates are allowed.
2603 ** If the query has an ORDER BY, then entries in the Queue table are kept in
2604 ** ORDER BY order and the first entry is extracted for each cycle. Without
2605 ** an ORDER BY, the Queue table is just a FIFO.
2607 ** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
2608 ** have been output to pDest. A LIMIT of zero means to output no rows and a
2609 ** negative LIMIT means to output all rows. If there is also an OFFSET clause
2610 ** with a positive value, then the first OFFSET outputs are discarded rather
2611 ** than being sent to pDest. The LIMIT count does not begin until after OFFSET
2612 ** rows have been skipped.
2614 static void generateWithRecursiveQuery(
2615 Parse *pParse, /* Parsing context */
2616 Select *p, /* The recursive SELECT to be coded */
2617 SelectDest *pDest /* What to do with query results */
2619 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
2620 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
2621 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
2622 Select *pSetup; /* The setup query */
2623 Select *pFirstRec; /* Left-most recursive term */
2624 int addrTop; /* Top of the loop */
2625 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
2626 int iCurrent = 0; /* The Current table */
2627 int regCurrent; /* Register holding Current table */
2628 int iQueue; /* The Queue table */
2629 int iDistinct = 0; /* To ensure unique results if UNION */
2630 int eDest = SRT_Fifo; /* How to write to Queue */
2631 SelectDest destQueue; /* SelectDest targeting the Queue table */
2632 int i; /* Loop counter */
2633 int rc; /* Result code */
2634 ExprList *pOrderBy; /* The ORDER BY clause */
2635 Expr *pLimit; /* Saved LIMIT and OFFSET */
2636 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
2638 #ifndef SQLITE_OMIT_WINDOWFUNC
2639 if( p->pWin ){
2640 sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
2641 return;
2643 #endif
2645 /* Obtain authorization to do a recursive query */
2646 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2648 /* Process the LIMIT and OFFSET clauses, if they exist */
2649 addrBreak = sqlite3VdbeMakeLabel(pParse);
2650 p->nSelectRow = 320; /* 4 billion rows */
2651 computeLimitRegisters(pParse, p, addrBreak);
2652 pLimit = p->pLimit;
2653 regLimit = p->iLimit;
2654 regOffset = p->iOffset;
2655 p->pLimit = 0;
2656 p->iLimit = p->iOffset = 0;
2657 pOrderBy = p->pOrderBy;
2659 /* Locate the cursor number of the Current table */
2660 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
2661 if( pSrc->a[i].fg.isRecursive ){
2662 iCurrent = pSrc->a[i].iCursor;
2663 break;
2667 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
2668 ** the Distinct table must be exactly one greater than Queue in order
2669 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2670 iQueue = pParse->nTab++;
2671 if( p->op==TK_UNION ){
2672 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2673 iDistinct = pParse->nTab++;
2674 }else{
2675 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2677 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2679 /* Allocate cursors for Current, Queue, and Distinct. */
2680 regCurrent = ++pParse->nMem;
2681 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2682 if( pOrderBy ){
2683 KeyInfo *pKeyInfo = multiSelectOrderByKeyInfo(pParse, p, 1);
2684 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2685 (char*)pKeyInfo, P4_KEYINFO);
2686 destQueue.pOrderBy = pOrderBy;
2687 }else{
2688 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2690 VdbeComment((v, "Queue table"));
2691 if( iDistinct ){
2692 p->addrOpenEphm[0] = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iDistinct, 0);
2693 p->selFlags |= SF_UsesEphemeral;
2696 /* Detach the ORDER BY clause from the compound SELECT */
2697 p->pOrderBy = 0;
2699 /* Figure out how many elements of the compound SELECT are part of the
2700 ** recursive query. Make sure no recursive elements use aggregate
2701 ** functions. Mark the recursive elements as UNION ALL even if they
2702 ** are really UNION because the distinctness will be enforced by the
2703 ** iDistinct table. pFirstRec is left pointing to the left-most
2704 ** recursive term of the CTE.
2706 for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
2707 if( pFirstRec->selFlags & SF_Aggregate ){
2708 sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2709 goto end_of_recursive_query;
2711 pFirstRec->op = TK_ALL;
2712 if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
2715 /* Store the results of the setup-query in Queue. */
2716 pSetup = pFirstRec->pPrior;
2717 pSetup->pNext = 0;
2718 ExplainQueryPlan((pParse, 1, "SETUP"));
2719 rc = sqlite3Select(pParse, pSetup, &destQueue);
2720 pSetup->pNext = p;
2721 if( rc ) goto end_of_recursive_query;
2723 /* Find the next row in the Queue and output that row */
2724 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2726 /* Transfer the next row in Queue over to Current */
2727 sqlite3VdbeAddOp1(v, OP_NullRow, iCurrent); /* To reset column cache */
2728 if( pOrderBy ){
2729 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2730 }else{
2731 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2733 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2735 /* Output the single row in Current */
2736 addrCont = sqlite3VdbeMakeLabel(pParse);
2737 codeOffset(v, regOffset, addrCont);
2738 selectInnerLoop(pParse, p, iCurrent,
2739 0, 0, pDest, addrCont, addrBreak);
2740 if( regLimit ){
2741 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2742 VdbeCoverage(v);
2744 sqlite3VdbeResolveLabel(v, addrCont);
2746 /* Execute the recursive SELECT taking the single row in Current as
2747 ** the value for the recursive-table. Store the results in the Queue.
2749 pFirstRec->pPrior = 0;
2750 ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
2751 sqlite3Select(pParse, p, &destQueue);
2752 assert( pFirstRec->pPrior==0 );
2753 pFirstRec->pPrior = pSetup;
2755 /* Keep running the loop until the Queue is empty */
2756 sqlite3VdbeGoto(v, addrTop);
2757 sqlite3VdbeResolveLabel(v, addrBreak);
2759 end_of_recursive_query:
2760 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2761 p->pOrderBy = pOrderBy;
2762 p->pLimit = pLimit;
2763 return;
2765 #endif /* SQLITE_OMIT_CTE */
2767 /* Forward references */
2768 static int multiSelectOrderBy(
2769 Parse *pParse, /* Parsing context */
2770 Select *p, /* The right-most of SELECTs to be coded */
2771 SelectDest *pDest /* What to do with query results */
2775 ** Handle the special case of a compound-select that originates from a
2776 ** VALUES clause. By handling this as a special case, we avoid deep
2777 ** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
2778 ** on a VALUES clause.
2780 ** Because the Select object originates from a VALUES clause:
2781 ** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
2782 ** (2) All terms are UNION ALL
2783 ** (3) There is no ORDER BY clause
2785 ** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
2786 ** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
2787 ** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
2788 ** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
2790 static int multiSelectValues(
2791 Parse *pParse, /* Parsing context */
2792 Select *p, /* The right-most of SELECTs to be coded */
2793 SelectDest *pDest /* What to do with query results */
2795 int nRow = 1;
2796 int rc = 0;
2797 int bShowAll = p->pLimit==0;
2798 assert( p->selFlags & SF_MultiValue );
2800 assert( p->selFlags & SF_Values );
2801 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
2802 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
2803 #ifndef SQLITE_OMIT_WINDOWFUNC
2804 if( p->pWin ) return -1;
2805 #endif
2806 if( p->pPrior==0 ) break;
2807 assert( p->pPrior->pNext==p );
2808 p = p->pPrior;
2809 nRow += bShowAll;
2810 }while(1);
2811 ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
2812 nRow==1 ? "" : "S"));
2813 while( p ){
2814 selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
2815 if( !bShowAll ) break;
2816 p->nSelectRow = nRow;
2817 p = p->pNext;
2819 return rc;
2823 ** Return true if the SELECT statement which is known to be the recursive
2824 ** part of a recursive CTE still has its anchor terms attached. If the
2825 ** anchor terms have already been removed, then return false.
2827 static int hasAnchor(Select *p){
2828 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
2829 return p!=0;
2833 ** This routine is called to process a compound query form from
2834 ** two or more separate queries using UNION, UNION ALL, EXCEPT, or
2835 ** INTERSECT
2837 ** "p" points to the right-most of the two queries. the query on the
2838 ** left is p->pPrior. The left query could also be a compound query
2839 ** in which case this routine will be called recursively.
2841 ** The results of the total query are to be written into a destination
2842 ** of type eDest with parameter iParm.
2844 ** Example 1: Consider a three-way compound SQL statement.
2846 ** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
2848 ** This statement is parsed up as follows:
2850 ** SELECT c FROM t3
2851 ** |
2852 ** `-----> SELECT b FROM t2
2853 ** |
2854 ** `------> SELECT a FROM t1
2856 ** The arrows in the diagram above represent the Select.pPrior pointer.
2857 ** So if this routine is called with p equal to the t3 query, then
2858 ** pPrior will be the t2 query. p->op will be TK_UNION in this case.
2860 ** Notice that because of the way SQLite parses compound SELECTs, the
2861 ** individual selects always group from left to right.
2863 static int multiSelect(
2864 Parse *pParse, /* Parsing context */
2865 Select *p, /* The right-most of SELECTs to be coded */
2866 SelectDest *pDest /* What to do with query results */
2868 int rc = SQLITE_OK; /* Success code from a subroutine */
2869 Select *pPrior; /* Another SELECT immediately to our left */
2870 Vdbe *v; /* Generate code to this VDBE */
2871 SelectDest dest; /* Alternative data destination */
2872 Select *pDelete = 0; /* Chain of simple selects to delete */
2873 sqlite3 *db; /* Database connection */
2875 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
2876 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
2878 assert( p && p->pPrior ); /* Calling function guarantees this much */
2879 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
2880 assert( p->selFlags & SF_Compound );
2881 db = pParse->db;
2882 pPrior = p->pPrior;
2883 dest = *pDest;
2884 assert( pPrior->pOrderBy==0 );
2885 assert( pPrior->pLimit==0 );
2887 v = sqlite3GetVdbe(pParse);
2888 assert( v!=0 ); /* The VDBE already created by calling function */
2890 /* Create the destination temporary table if necessary
2892 if( dest.eDest==SRT_EphemTab ){
2893 assert( p->pEList );
2894 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
2895 dest.eDest = SRT_Table;
2898 /* Special handling for a compound-select that originates as a VALUES clause.
2900 if( p->selFlags & SF_MultiValue ){
2901 rc = multiSelectValues(pParse, p, &dest);
2902 if( rc>=0 ) goto multi_select_end;
2903 rc = SQLITE_OK;
2906 /* Make sure all SELECTs in the statement have the same number of elements
2907 ** in their result sets.
2909 assert( p->pEList && pPrior->pEList );
2910 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
2912 #ifndef SQLITE_OMIT_CTE
2913 if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
2914 generateWithRecursiveQuery(pParse, p, &dest);
2915 }else
2916 #endif
2918 /* Compound SELECTs that have an ORDER BY clause are handled separately.
2920 if( p->pOrderBy ){
2921 return multiSelectOrderBy(pParse, p, pDest);
2922 }else{
2924 #ifndef SQLITE_OMIT_EXPLAIN
2925 if( pPrior->pPrior==0 ){
2926 ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
2927 ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
2929 #endif
2931 /* Generate code for the left and right SELECT statements.
2933 switch( p->op ){
2934 case TK_ALL: {
2935 int addr = 0;
2936 int nLimit = 0; /* Initialize to suppress harmless compiler warning */
2937 assert( !pPrior->pLimit );
2938 pPrior->iLimit = p->iLimit;
2939 pPrior->iOffset = p->iOffset;
2940 pPrior->pLimit = p->pLimit;
2941 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
2942 rc = sqlite3Select(pParse, pPrior, &dest);
2943 pPrior->pLimit = 0;
2944 if( rc ){
2945 goto multi_select_end;
2947 p->pPrior = 0;
2948 p->iLimit = pPrior->iLimit;
2949 p->iOffset = pPrior->iOffset;
2950 if( p->iLimit ){
2951 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
2952 VdbeComment((v, "Jump ahead if LIMIT reached"));
2953 if( p->iOffset ){
2954 sqlite3VdbeAddOp3(v, OP_OffsetLimit,
2955 p->iLimit, p->iOffset+1, p->iOffset);
2958 ExplainQueryPlan((pParse, 1, "UNION ALL"));
2959 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
2960 rc = sqlite3Select(pParse, p, &dest);
2961 testcase( rc!=SQLITE_OK );
2962 pDelete = p->pPrior;
2963 p->pPrior = pPrior;
2964 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
2965 if( p->pLimit
2966 && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit)
2967 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
2969 p->nSelectRow = sqlite3LogEst((u64)nLimit);
2971 if( addr ){
2972 sqlite3VdbeJumpHere(v, addr);
2974 break;
2976 case TK_EXCEPT:
2977 case TK_UNION: {
2978 int unionTab; /* Cursor number of the temp table holding result */
2979 u8 op = 0; /* One of the SRT_ operations to apply to self */
2980 int priorOp; /* The SRT_ operation to apply to prior selects */
2981 Expr *pLimit; /* Saved values of p->nLimit */
2982 int addr;
2983 SelectDest uniondest;
2985 testcase( p->op==TK_EXCEPT );
2986 testcase( p->op==TK_UNION );
2987 priorOp = SRT_Union;
2988 if( dest.eDest==priorOp ){
2989 /* We can reuse a temporary table generated by a SELECT to our
2990 ** right.
2992 assert( p->pLimit==0 ); /* Not allowed on leftward elements */
2993 unionTab = dest.iSDParm;
2994 }else{
2995 /* We will need to create our own temporary table to hold the
2996 ** intermediate results.
2998 unionTab = pParse->nTab++;
2999 assert( p->pOrderBy==0 );
3000 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, unionTab, 0);
3001 assert( p->addrOpenEphm[0] == -1 );
3002 p->addrOpenEphm[0] = addr;
3003 findRightmost(p)->selFlags |= SF_UsesEphemeral;
3004 assert( p->pEList );
3008 /* Code the SELECT statements to our left
3010 assert( !pPrior->pOrderBy );
3011 sqlite3SelectDestInit(&uniondest, priorOp, unionTab);
3012 TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION left...\n"));
3013 rc = sqlite3Select(pParse, pPrior, &uniondest);
3014 if( rc ){
3015 goto multi_select_end;
3018 /* Code the current SELECT statement
3020 if( p->op==TK_EXCEPT ){
3021 op = SRT_Except;
3022 }else{
3023 assert( p->op==TK_UNION );
3024 op = SRT_Union;
3026 p->pPrior = 0;
3027 pLimit = p->pLimit;
3028 p->pLimit = 0;
3029 uniondest.eDest = op;
3030 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3031 sqlite3SelectOpName(p->op)));
3032 TREETRACE(0x200, pParse, p, ("multiSelect EXCEPT/UNION right...\n"));
3033 rc = sqlite3Select(pParse, p, &uniondest);
3034 testcase( rc!=SQLITE_OK );
3035 assert( p->pOrderBy==0 );
3036 pDelete = p->pPrior;
3037 p->pPrior = pPrior;
3038 p->pOrderBy = 0;
3039 if( p->op==TK_UNION ){
3040 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3042 sqlite3ExprDelete(db, p->pLimit);
3043 p->pLimit = pLimit;
3044 p->iLimit = 0;
3045 p->iOffset = 0;
3047 /* Convert the data in the temporary table into whatever form
3048 ** it is that we currently need.
3050 assert( unionTab==dest.iSDParm || dest.eDest!=priorOp );
3051 assert( p->pEList || db->mallocFailed );
3052 if( dest.eDest!=priorOp && db->mallocFailed==0 ){
3053 int iCont, iBreak, iStart;
3054 iBreak = sqlite3VdbeMakeLabel(pParse);
3055 iCont = sqlite3VdbeMakeLabel(pParse);
3056 computeLimitRegisters(pParse, p, iBreak);
3057 sqlite3VdbeAddOp2(v, OP_Rewind, unionTab, iBreak); VdbeCoverage(v);
3058 iStart = sqlite3VdbeCurrentAddr(v);
3059 selectInnerLoop(pParse, p, unionTab,
3060 0, 0, &dest, iCont, iBreak);
3061 sqlite3VdbeResolveLabel(v, iCont);
3062 sqlite3VdbeAddOp2(v, OP_Next, unionTab, iStart); VdbeCoverage(v);
3063 sqlite3VdbeResolveLabel(v, iBreak);
3064 sqlite3VdbeAddOp2(v, OP_Close, unionTab, 0);
3066 break;
3068 default: assert( p->op==TK_INTERSECT ); {
3069 int tab1, tab2;
3070 int iCont, iBreak, iStart;
3071 Expr *pLimit;
3072 int addr;
3073 SelectDest intersectdest;
3074 int r1;
3076 /* INTERSECT is different from the others since it requires
3077 ** two temporary tables. Hence it has its own case. Begin
3078 ** by allocating the tables we will need.
3080 tab1 = pParse->nTab++;
3081 tab2 = pParse->nTab++;
3082 assert( p->pOrderBy==0 );
3084 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab1, 0);
3085 assert( p->addrOpenEphm[0] == -1 );
3086 p->addrOpenEphm[0] = addr;
3087 findRightmost(p)->selFlags |= SF_UsesEphemeral;
3088 assert( p->pEList );
3090 /* Code the SELECTs to our left into temporary table "tab1".
3092 sqlite3SelectDestInit(&intersectdest, SRT_Union, tab1);
3093 TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT left...\n"));
3094 rc = sqlite3Select(pParse, pPrior, &intersectdest);
3095 if( rc ){
3096 goto multi_select_end;
3099 /* Code the current SELECT into temporary table "tab2"
3101 addr = sqlite3VdbeAddOp2(v, OP_OpenEphemeral, tab2, 0);
3102 assert( p->addrOpenEphm[1] == -1 );
3103 p->addrOpenEphm[1] = addr;
3104 p->pPrior = 0;
3105 pLimit = p->pLimit;
3106 p->pLimit = 0;
3107 intersectdest.iSDParm = tab2;
3108 ExplainQueryPlan((pParse, 1, "%s USING TEMP B-TREE",
3109 sqlite3SelectOpName(p->op)));
3110 TREETRACE(0x400, pParse, p, ("multiSelect INTERSECT right...\n"));
3111 rc = sqlite3Select(pParse, p, &intersectdest);
3112 testcase( rc!=SQLITE_OK );
3113 pDelete = p->pPrior;
3114 p->pPrior = pPrior;
3115 if( p->nSelectRow>pPrior->nSelectRow ){
3116 p->nSelectRow = pPrior->nSelectRow;
3118 sqlite3ExprDelete(db, p->pLimit);
3119 p->pLimit = pLimit;
3121 /* Generate code to take the intersection of the two temporary
3122 ** tables.
3124 if( rc ) break;
3125 assert( p->pEList );
3126 iBreak = sqlite3VdbeMakeLabel(pParse);
3127 iCont = sqlite3VdbeMakeLabel(pParse);
3128 computeLimitRegisters(pParse, p, iBreak);
3129 sqlite3VdbeAddOp2(v, OP_Rewind, tab1, iBreak); VdbeCoverage(v);
3130 r1 = sqlite3GetTempReg(pParse);
3131 iStart = sqlite3VdbeAddOp2(v, OP_RowData, tab1, r1);
3132 sqlite3VdbeAddOp4Int(v, OP_NotFound, tab2, iCont, r1, 0);
3133 VdbeCoverage(v);
3134 sqlite3ReleaseTempReg(pParse, r1);
3135 selectInnerLoop(pParse, p, tab1,
3136 0, 0, &dest, iCont, iBreak);
3137 sqlite3VdbeResolveLabel(v, iCont);
3138 sqlite3VdbeAddOp2(v, OP_Next, tab1, iStart); VdbeCoverage(v);
3139 sqlite3VdbeResolveLabel(v, iBreak);
3140 sqlite3VdbeAddOp2(v, OP_Close, tab2, 0);
3141 sqlite3VdbeAddOp2(v, OP_Close, tab1, 0);
3142 break;
3146 #ifndef SQLITE_OMIT_EXPLAIN
3147 if( p->pNext==0 ){
3148 ExplainQueryPlanPop(pParse);
3150 #endif
3152 if( pParse->nErr ) goto multi_select_end;
3154 /* Compute collating sequences used by
3155 ** temporary tables needed to implement the compound select.
3156 ** Attach the KeyInfo structure to all temporary tables.
3158 ** This section is run by the right-most SELECT statement only.
3159 ** SELECT statements to the left always skip this part. The right-most
3160 ** SELECT might also skip this part if it has no ORDER BY clause and
3161 ** no temp tables are required.
3163 if( p->selFlags & SF_UsesEphemeral ){
3164 int i; /* Loop counter */
3165 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
3166 Select *pLoop; /* For looping through SELECT statements */
3167 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
3168 int nCol; /* Number of columns in result set */
3170 assert( p->pNext==0 );
3171 assert( p->pEList!=0 );
3172 nCol = p->pEList->nExpr;
3173 pKeyInfo = sqlite3KeyInfoAlloc(db, nCol, 1);
3174 if( !pKeyInfo ){
3175 rc = SQLITE_NOMEM_BKPT;
3176 goto multi_select_end;
3178 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
3179 *apColl = multiSelectCollSeq(pParse, p, i);
3180 if( 0==*apColl ){
3181 *apColl = db->pDfltColl;
3185 for(pLoop=p; pLoop; pLoop=pLoop->pPrior){
3186 for(i=0; i<2; i++){
3187 int addr = pLoop->addrOpenEphm[i];
3188 if( addr<0 ){
3189 /* If [0] is unused then [1] is also unused. So we can
3190 ** always safely abort as soon as the first unused slot is found */
3191 assert( pLoop->addrOpenEphm[1]<0 );
3192 break;
3194 sqlite3VdbeChangeP2(v, addr, nCol);
3195 sqlite3VdbeChangeP4(v, addr, (char*)sqlite3KeyInfoRef(pKeyInfo),
3196 P4_KEYINFO);
3197 pLoop->addrOpenEphm[i] = -1;
3200 sqlite3KeyInfoUnref(pKeyInfo);
3203 multi_select_end:
3204 pDest->iSdst = dest.iSdst;
3205 pDest->nSdst = dest.nSdst;
3206 if( pDelete ){
3207 sqlite3ParserAddCleanup(pParse,
3208 (void(*)(sqlite3*,void*))sqlite3SelectDelete,
3209 pDelete);
3211 return rc;
3213 #endif /* SQLITE_OMIT_COMPOUND_SELECT */
3216 ** Error message for when two or more terms of a compound select have different
3217 ** size result sets.
3219 void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
3220 if( p->selFlags & SF_Values ){
3221 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
3222 }else{
3223 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
3224 " do not have the same number of result columns",
3225 sqlite3SelectOpName(p->op));
3230 ** Code an output subroutine for a coroutine implementation of a
3231 ** SELECT statement.
3233 ** The data to be output is contained in pIn->iSdst. There are
3234 ** pIn->nSdst columns to be output. pDest is where the output should
3235 ** be sent.
3237 ** regReturn is the number of the register holding the subroutine
3238 ** return address.
3240 ** If regPrev>0 then it is the first register in a vector that
3241 ** records the previous output. mem[regPrev] is a flag that is false
3242 ** if there has been no previous output. If regPrev>0 then code is
3243 ** generated to suppress duplicates. pKeyInfo is used for comparing
3244 ** keys.
3246 ** If the LIMIT found in p->iLimit is reached, jump immediately to
3247 ** iBreak.
3249 static int generateOutputSubroutine(
3250 Parse *pParse, /* Parsing context */
3251 Select *p, /* The SELECT statement */
3252 SelectDest *pIn, /* Coroutine supplying data */
3253 SelectDest *pDest, /* Where to send the data */
3254 int regReturn, /* The return address register */
3255 int regPrev, /* Previous result register. No uniqueness if 0 */
3256 KeyInfo *pKeyInfo, /* For comparing with previous entry */
3257 int iBreak /* Jump here if we hit the LIMIT */
3259 Vdbe *v = pParse->pVdbe;
3260 int iContinue;
3261 int addr;
3263 addr = sqlite3VdbeCurrentAddr(v);
3264 iContinue = sqlite3VdbeMakeLabel(pParse);
3266 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
3268 if( regPrev ){
3269 int addr1, addr2;
3270 addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
3271 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
3272 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
3273 sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
3274 sqlite3VdbeJumpHere(v, addr1);
3275 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
3276 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
3278 if( pParse->db->mallocFailed ) return 0;
3280 /* Suppress the first OFFSET entries if there is an OFFSET clause
3282 codeOffset(v, p->iOffset, iContinue);
3284 assert( pDest->eDest!=SRT_Exists );
3285 assert( pDest->eDest!=SRT_Table );
3286 switch( pDest->eDest ){
3287 /* Store the result as data using a unique key.
3289 case SRT_EphemTab: {
3290 int r1 = sqlite3GetTempReg(pParse);
3291 int r2 = sqlite3GetTempReg(pParse);
3292 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
3293 sqlite3VdbeAddOp2(v, OP_NewRowid, pDest->iSDParm, r2);
3294 sqlite3VdbeAddOp3(v, OP_Insert, pDest->iSDParm, r1, r2);
3295 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3296 sqlite3ReleaseTempReg(pParse, r2);
3297 sqlite3ReleaseTempReg(pParse, r1);
3298 break;
3301 #ifndef SQLITE_OMIT_SUBQUERY
3302 /* If we are creating a set for an "expr IN (SELECT ...)".
3304 case SRT_Set: {
3305 int r1;
3306 testcase( pIn->nSdst>1 );
3307 r1 = sqlite3GetTempReg(pParse);
3308 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
3309 r1, pDest->zAffSdst, pIn->nSdst);
3310 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
3311 pIn->iSdst, pIn->nSdst);
3312 sqlite3ReleaseTempReg(pParse, r1);
3313 break;
3316 /* If this is a scalar select that is part of an expression, then
3317 ** store the results in the appropriate memory cell and break out
3318 ** of the scan loop. Note that the select might return multiple columns
3319 ** if it is the RHS of a row-value IN operator.
3321 case SRT_Mem: {
3322 testcase( pIn->nSdst>1 );
3323 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
3324 /* The LIMIT clause will jump out of the loop for us */
3325 break;
3327 #endif /* #ifndef SQLITE_OMIT_SUBQUERY */
3329 /* The results are stored in a sequence of registers
3330 ** starting at pDest->iSdst. Then the co-routine yields.
3332 case SRT_Coroutine: {
3333 if( pDest->iSdst==0 ){
3334 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
3335 pDest->nSdst = pIn->nSdst;
3337 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
3338 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
3339 break;
3342 /* If none of the above, then the result destination must be
3343 ** SRT_Output. This routine is never called with any other
3344 ** destination other than the ones handled above or SRT_Output.
3346 ** For SRT_Output, results are stored in a sequence of registers.
3347 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
3348 ** return the next row of result.
3350 default: {
3351 assert( pDest->eDest==SRT_Output );
3352 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
3353 break;
3357 /* Jump to the end of the loop if the LIMIT is reached.
3359 if( p->iLimit ){
3360 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
3363 /* Generate the subroutine return
3365 sqlite3VdbeResolveLabel(v, iContinue);
3366 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
3368 return addr;
3372 ** Alternative compound select code generator for cases when there
3373 ** is an ORDER BY clause.
3375 ** We assume a query of the following form:
3377 ** <selectA> <operator> <selectB> ORDER BY <orderbylist>
3379 ** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
3380 ** is to code both <selectA> and <selectB> with the ORDER BY clause as
3381 ** co-routines. Then run the co-routines in parallel and merge the results
3382 ** into the output. In addition to the two coroutines (called selectA and
3383 ** selectB) there are 7 subroutines:
3385 ** outA: Move the output of the selectA coroutine into the output
3386 ** of the compound query.
3388 ** outB: Move the output of the selectB coroutine into the output
3389 ** of the compound query. (Only generated for UNION and
3390 ** UNION ALL. EXCEPT and INSERTSECT never output a row that
3391 ** appears only in B.)
3393 ** AltB: Called when there is data from both coroutines and A<B.
3395 ** AeqB: Called when there is data from both coroutines and A==B.
3397 ** AgtB: Called when there is data from both coroutines and A>B.
3399 ** EofA: Called when data is exhausted from selectA.
3401 ** EofB: Called when data is exhausted from selectB.
3403 ** The implementation of the latter five subroutines depend on which
3404 ** <operator> is used:
3407 ** UNION ALL UNION EXCEPT INTERSECT
3408 ** ------------- ----------------- -------------- -----------------
3409 ** AltB: outA, nextA outA, nextA outA, nextA nextA
3411 ** AeqB: outA, nextA nextA nextA outA, nextA
3413 ** AgtB: outB, nextB outB, nextB nextB nextB
3415 ** EofA: outB, nextB outB, nextB halt halt
3417 ** EofB: outA, nextA outA, nextA outA, nextA halt
3419 ** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
3420 ** causes an immediate jump to EofA and an EOF on B following nextB causes
3421 ** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
3422 ** following nextX causes a jump to the end of the select processing.
3424 ** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
3425 ** within the output subroutine. The regPrev register set holds the previously
3426 ** output value. A comparison is made against this value and the output
3427 ** is skipped if the next results would be the same as the previous.
3429 ** The implementation plan is to implement the two coroutines and seven
3430 ** subroutines first, then put the control logic at the bottom. Like this:
3432 ** goto Init
3433 ** coA: coroutine for left query (A)
3434 ** coB: coroutine for right query (B)
3435 ** outA: output one row of A
3436 ** outB: output one row of B (UNION and UNION ALL only)
3437 ** EofA: ...
3438 ** EofB: ...
3439 ** AltB: ...
3440 ** AeqB: ...
3441 ** AgtB: ...
3442 ** Init: initialize coroutine registers
3443 ** yield coA
3444 ** if eof(A) goto EofA
3445 ** yield coB
3446 ** if eof(B) goto EofB
3447 ** Cmpr: Compare A, B
3448 ** Jump AltB, AeqB, AgtB
3449 ** End: ...
3451 ** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
3452 ** actually called using Gosub and they do not Return. EofA and EofB loop
3453 ** until all data is exhausted then jump to the "end" label. AltB, AeqB,
3454 ** and AgtB jump to either L2 or to one of EofA or EofB.
3456 #ifndef SQLITE_OMIT_COMPOUND_SELECT
3457 static int multiSelectOrderBy(
3458 Parse *pParse, /* Parsing context */
3459 Select *p, /* The right-most of SELECTs to be coded */
3460 SelectDest *pDest /* What to do with query results */
3462 int i, j; /* Loop counters */
3463 Select *pPrior; /* Another SELECT immediately to our left */
3464 Select *pSplit; /* Left-most SELECT in the right-hand group */
3465 int nSelect; /* Number of SELECT statements in the compound */
3466 Vdbe *v; /* Generate code to this VDBE */
3467 SelectDest destA; /* Destination for coroutine A */
3468 SelectDest destB; /* Destination for coroutine B */
3469 int regAddrA; /* Address register for select-A coroutine */
3470 int regAddrB; /* Address register for select-B coroutine */
3471 int addrSelectA; /* Address of the select-A coroutine */
3472 int addrSelectB; /* Address of the select-B coroutine */
3473 int regOutA; /* Address register for the output-A subroutine */
3474 int regOutB; /* Address register for the output-B subroutine */
3475 int addrOutA; /* Address of the output-A subroutine */
3476 int addrOutB = 0; /* Address of the output-B subroutine */
3477 int addrEofA; /* Address of the select-A-exhausted subroutine */
3478 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
3479 int addrEofB; /* Address of the select-B-exhausted subroutine */
3480 int addrAltB; /* Address of the A<B subroutine */
3481 int addrAeqB; /* Address of the A==B subroutine */
3482 int addrAgtB; /* Address of the A>B subroutine */
3483 int regLimitA; /* Limit register for select-A */
3484 int regLimitB; /* Limit register for select-A */
3485 int regPrev; /* A range of registers to hold previous output */
3486 int savedLimit; /* Saved value of p->iLimit */
3487 int savedOffset; /* Saved value of p->iOffset */
3488 int labelCmpr; /* Label for the start of the merge algorithm */
3489 int labelEnd; /* Label for the end of the overall SELECT stmt */
3490 int addr1; /* Jump instructions that get retargeted */
3491 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
3492 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
3493 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
3494 sqlite3 *db; /* Database connection */
3495 ExprList *pOrderBy; /* The ORDER BY clause */
3496 int nOrderBy; /* Number of terms in the ORDER BY clause */
3497 u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */
3499 assert( p->pOrderBy!=0 );
3500 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
3501 db = pParse->db;
3502 v = pParse->pVdbe;
3503 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
3504 labelEnd = sqlite3VdbeMakeLabel(pParse);
3505 labelCmpr = sqlite3VdbeMakeLabel(pParse);
3508 /* Patch up the ORDER BY clause
3510 op = p->op;
3511 assert( p->pPrior->pOrderBy==0 );
3512 pOrderBy = p->pOrderBy;
3513 assert( pOrderBy );
3514 nOrderBy = pOrderBy->nExpr;
3516 /* For operators other than UNION ALL we have to make sure that
3517 ** the ORDER BY clause covers every term of the result set. Add
3518 ** terms to the ORDER BY clause as necessary.
3520 if( op!=TK_ALL ){
3521 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
3522 struct ExprList_item *pItem;
3523 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
3524 assert( pItem!=0 );
3525 assert( pItem->u.x.iOrderByCol>0 );
3526 if( pItem->u.x.iOrderByCol==i ) break;
3528 if( j==nOrderBy ){
3529 Expr *pNew = sqlite3Expr(db, TK_INTEGER, 0);
3530 if( pNew==0 ) return SQLITE_NOMEM_BKPT;
3531 pNew->flags |= EP_IntValue;
3532 pNew->u.iValue = i;
3533 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
3534 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
3539 /* Compute the comparison permutation and keyinfo that is used with
3540 ** the permutation used to determine if the next
3541 ** row of results comes from selectA or selectB. Also add explicit
3542 ** collations to the ORDER BY clause terms so that when the subqueries
3543 ** to the right and the left are evaluated, they use the correct
3544 ** collation.
3546 aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
3547 if( aPermute ){
3548 struct ExprList_item *pItem;
3549 aPermute[0] = nOrderBy;
3550 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
3551 assert( pItem!=0 );
3552 assert( pItem->u.x.iOrderByCol>0 );
3553 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
3554 aPermute[i] = pItem->u.x.iOrderByCol - 1;
3556 pKeyMerge = multiSelectOrderByKeyInfo(pParse, p, 1);
3557 }else{
3558 pKeyMerge = 0;
3561 /* Allocate a range of temporary registers and the KeyInfo needed
3562 ** for the logic that removes duplicate result rows when the
3563 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
3565 if( op==TK_ALL ){
3566 regPrev = 0;
3567 }else{
3568 int nExpr = p->pEList->nExpr;
3569 assert( nOrderBy>=nExpr || db->mallocFailed );
3570 regPrev = pParse->nMem+1;
3571 pParse->nMem += nExpr+1;
3572 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
3573 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
3574 if( pKeyDup ){
3575 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
3576 for(i=0; i<nExpr; i++){
3577 pKeyDup->aColl[i] = multiSelectCollSeq(pParse, p, i);
3578 pKeyDup->aSortFlags[i] = 0;
3583 /* Separate the left and the right query from one another
3585 nSelect = 1;
3586 if( (op==TK_ALL || op==TK_UNION)
3587 && OptimizationEnabled(db, SQLITE_BalancedMerge)
3589 for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
3590 nSelect++;
3591 assert( pSplit->pPrior->pNext==pSplit );
3594 if( nSelect<=3 ){
3595 pSplit = p;
3596 }else{
3597 pSplit = p;
3598 for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
3600 pPrior = pSplit->pPrior;
3601 assert( pPrior!=0 );
3602 pSplit->pPrior = 0;
3603 pPrior->pNext = 0;
3604 assert( p->pOrderBy == pOrderBy );
3605 assert( pOrderBy!=0 || db->mallocFailed );
3606 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
3607 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
3608 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
3610 /* Compute the limit registers */
3611 computeLimitRegisters(pParse, p, labelEnd);
3612 if( p->iLimit && op==TK_ALL ){
3613 regLimitA = ++pParse->nMem;
3614 regLimitB = ++pParse->nMem;
3615 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
3616 regLimitA);
3617 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
3618 }else{
3619 regLimitA = regLimitB = 0;
3621 sqlite3ExprDelete(db, p->pLimit);
3622 p->pLimit = 0;
3624 regAddrA = ++pParse->nMem;
3625 regAddrB = ++pParse->nMem;
3626 regOutA = ++pParse->nMem;
3627 regOutB = ++pParse->nMem;
3628 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
3629 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
3631 ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
3633 /* Generate a coroutine to evaluate the SELECT statement to the
3634 ** left of the compound operator - the "A" select.
3636 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
3637 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
3638 VdbeComment((v, "left SELECT"));
3639 pPrior->iLimit = regLimitA;
3640 ExplainQueryPlan((pParse, 1, "LEFT"));
3641 sqlite3Select(pParse, pPrior, &destA);
3642 sqlite3VdbeEndCoroutine(v, regAddrA);
3643 sqlite3VdbeJumpHere(v, addr1);
3645 /* Generate a coroutine to evaluate the SELECT statement on
3646 ** the right - the "B" select
3648 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
3649 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
3650 VdbeComment((v, "right SELECT"));
3651 savedLimit = p->iLimit;
3652 savedOffset = p->iOffset;
3653 p->iLimit = regLimitB;
3654 p->iOffset = 0;
3655 ExplainQueryPlan((pParse, 1, "RIGHT"));
3656 sqlite3Select(pParse, p, &destB);
3657 p->iLimit = savedLimit;
3658 p->iOffset = savedOffset;
3659 sqlite3VdbeEndCoroutine(v, regAddrB);
3661 /* Generate a subroutine that outputs the current row of the A
3662 ** select as the next output row of the compound select.
3664 VdbeNoopComment((v, "Output routine for A"));
3665 addrOutA = generateOutputSubroutine(pParse,
3666 p, &destA, pDest, regOutA,
3667 regPrev, pKeyDup, labelEnd);
3669 /* Generate a subroutine that outputs the current row of the B
3670 ** select as the next output row of the compound select.
3672 if( op==TK_ALL || op==TK_UNION ){
3673 VdbeNoopComment((v, "Output routine for B"));
3674 addrOutB = generateOutputSubroutine(pParse,
3675 p, &destB, pDest, regOutB,
3676 regPrev, pKeyDup, labelEnd);
3678 sqlite3KeyInfoUnref(pKeyDup);
3680 /* Generate a subroutine to run when the results from select A
3681 ** are exhausted and only data in select B remains.
3683 if( op==TK_EXCEPT || op==TK_INTERSECT ){
3684 addrEofA_noB = addrEofA = labelEnd;
3685 }else{
3686 VdbeNoopComment((v, "eof-A subroutine"));
3687 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3688 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3689 VdbeCoverage(v);
3690 sqlite3VdbeGoto(v, addrEofA);
3691 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3694 /* Generate a subroutine to run when the results from select B
3695 ** are exhausted and only data in select A remains.
3697 if( op==TK_INTERSECT ){
3698 addrEofB = addrEofA;
3699 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3700 }else{
3701 VdbeNoopComment((v, "eof-B subroutine"));
3702 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3703 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3704 sqlite3VdbeGoto(v, addrEofB);
3707 /* Generate code to handle the case of A<B
3709 VdbeNoopComment((v, "A-lt-B subroutine"));
3710 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3711 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3712 sqlite3VdbeGoto(v, labelCmpr);
3714 /* Generate code to handle the case of A==B
3716 if( op==TK_ALL ){
3717 addrAeqB = addrAltB;
3718 }else if( op==TK_INTERSECT ){
3719 addrAeqB = addrAltB;
3720 addrAltB++;
3721 }else{
3722 VdbeNoopComment((v, "A-eq-B subroutine"));
3723 addrAeqB =
3724 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3725 sqlite3VdbeGoto(v, labelCmpr);
3728 /* Generate code to handle the case of A>B
3730 VdbeNoopComment((v, "A-gt-B subroutine"));
3731 addrAgtB = sqlite3VdbeCurrentAddr(v);
3732 if( op==TK_ALL || op==TK_UNION ){
3733 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3735 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3736 sqlite3VdbeGoto(v, labelCmpr);
3738 /* This code runs once to initialize everything.
3740 sqlite3VdbeJumpHere(v, addr1);
3741 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3742 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3744 /* Implement the main merge loop
3746 sqlite3VdbeResolveLabel(v, labelCmpr);
3747 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
3748 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
3749 (char*)pKeyMerge, P4_KEYINFO);
3750 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3751 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB); VdbeCoverage(v);
3753 /* Jump to the this point in order to terminate the query.
3755 sqlite3VdbeResolveLabel(v, labelEnd);
3757 /* Make arrangements to free the 2nd and subsequent arms of the compound
3758 ** after the parse has finished */
3759 if( pSplit->pPrior ){
3760 sqlite3ParserAddCleanup(pParse,
3761 (void(*)(sqlite3*,void*))sqlite3SelectDelete, pSplit->pPrior);
3763 pSplit->pPrior = pPrior;
3764 pPrior->pNext = pSplit;
3765 sqlite3ExprListDelete(db, pPrior->pOrderBy);
3766 pPrior->pOrderBy = 0;
3768 /*** TBD: Insert subroutine calls to close cursors on incomplete
3769 **** subqueries ****/
3770 ExplainQueryPlanPop(pParse);
3771 return pParse->nErr!=0;
3773 #endif
3775 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3777 /* An instance of the SubstContext object describes an substitution edit
3778 ** to be performed on a parse tree.
3780 ** All references to columns in table iTable are to be replaced by corresponding
3781 ** expressions in pEList.
3783 ** ## About "isOuterJoin":
3785 ** The isOuterJoin column indicates that the replacement will occur into a
3786 ** position in the parent that NULL-able due to an OUTER JOIN. Either the
3787 ** target slot in the parent is the right operand of a LEFT JOIN, or one of
3788 ** the left operands of a RIGHT JOIN. In either case, we need to potentially
3789 ** bypass the substituted expression with OP_IfNullRow.
3791 ** Suppose the original expression is an integer constant. Even though the table
3792 ** has the nullRow flag set, because the expression is an integer constant,
3793 ** it will not be NULLed out. So instead, we insert an OP_IfNullRow opcode
3794 ** that checks to see if the nullRow flag is set on the table. If the nullRow
3795 ** flag is set, then the value in the register is set to NULL and the original
3796 ** expression is bypassed. If the nullRow flag is not set, then the original
3797 ** expression runs to populate the register.
3799 ** Example where this is needed:
3801 ** CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
3802 ** CREATE TABLE t2(x INT UNIQUE);
3804 ** SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x;
3806 ** When the subquery on the right side of the LEFT JOIN is flattened, we
3807 ** have to add OP_IfNullRow in front of the OP_Integer that implements the
3808 ** "m" value of the subquery so that a NULL will be loaded instead of 59
3809 ** when processing a non-matched row of the left.
3811 typedef struct SubstContext {
3812 Parse *pParse; /* The parsing context */
3813 int iTable; /* Replace references to this table */
3814 int iNewTable; /* New table number */
3815 int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
3816 ExprList *pEList; /* Replacement expressions */
3817 ExprList *pCList; /* Collation sequences for replacement expr */
3818 } SubstContext;
3820 /* Forward Declarations */
3821 static void substExprList(SubstContext*, ExprList*);
3822 static void substSelect(SubstContext*, Select*, int);
3825 ** Scan through the expression pExpr. Replace every reference to
3826 ** a column in table number iTable with a copy of the iColumn-th
3827 ** entry in pEList. (But leave references to the ROWID column
3828 ** unchanged.)
3830 ** This routine is part of the flattening procedure. A subquery
3831 ** whose result set is defined by pEList appears as entry in the
3832 ** FROM clause of a SELECT such that the VDBE cursor assigned to that
3833 ** FORM clause entry is iTable. This routine makes the necessary
3834 ** changes to pExpr so that it refers directly to the source table
3835 ** of the subquery rather the result set of the subquery.
3837 static Expr *substExpr(
3838 SubstContext *pSubst, /* Description of the substitution */
3839 Expr *pExpr /* Expr in which substitution occurs */
3841 if( pExpr==0 ) return 0;
3842 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)
3843 && pExpr->w.iJoin==pSubst->iTable
3845 testcase( ExprHasProperty(pExpr, EP_InnerON) );
3846 pExpr->w.iJoin = pSubst->iNewTable;
3848 if( pExpr->op==TK_COLUMN
3849 && pExpr->iTable==pSubst->iTable
3850 && !ExprHasProperty(pExpr, EP_FixedCol)
3852 #ifdef SQLITE_ALLOW_ROWID_IN_VIEW
3853 if( pExpr->iColumn<0 ){
3854 pExpr->op = TK_NULL;
3855 }else
3856 #endif
3858 Expr *pNew;
3859 int iColumn;
3860 Expr *pCopy;
3861 Expr ifNullRow;
3862 iColumn = pExpr->iColumn;
3863 assert( iColumn>=0 );
3864 assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
3865 assert( pExpr->pRight==0 );
3866 pCopy = pSubst->pEList->a[iColumn].pExpr;
3867 if( sqlite3ExprIsVector(pCopy) ){
3868 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
3869 }else{
3870 sqlite3 *db = pSubst->pParse->db;
3871 if( pSubst->isOuterJoin
3872 && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
3874 memset(&ifNullRow, 0, sizeof(ifNullRow));
3875 ifNullRow.op = TK_IF_NULL_ROW;
3876 ifNullRow.pLeft = pCopy;
3877 ifNullRow.iTable = pSubst->iNewTable;
3878 ifNullRow.iColumn = -99;
3879 ifNullRow.flags = EP_IfNullRow;
3880 pCopy = &ifNullRow;
3882 testcase( ExprHasProperty(pCopy, EP_Subquery) );
3883 pNew = sqlite3ExprDup(db, pCopy, 0);
3884 if( db->mallocFailed ){
3885 sqlite3ExprDelete(db, pNew);
3886 return pExpr;
3888 if( pSubst->isOuterJoin ){
3889 ExprSetProperty(pNew, EP_CanBeNull);
3891 if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){
3892 sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
3893 pExpr->flags & (EP_OuterON|EP_InnerON));
3895 sqlite3ExprDelete(db, pExpr);
3896 pExpr = pNew;
3897 if( pExpr->op==TK_TRUEFALSE ){
3898 pExpr->u.iValue = sqlite3ExprTruthValue(pExpr);
3899 pExpr->op = TK_INTEGER;
3900 ExprSetProperty(pExpr, EP_IntValue);
3903 /* Ensure that the expression now has an implicit collation sequence,
3904 ** just as it did when it was a column of a view or sub-query. */
3906 CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pExpr);
3907 CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
3908 pSubst->pCList->a[iColumn].pExpr
3910 if( pNat!=pColl || (pExpr->op!=TK_COLUMN && pExpr->op!=TK_COLLATE) ){
3911 pExpr = sqlite3ExprAddCollateString(pSubst->pParse, pExpr,
3912 (pColl ? pColl->zName : "BINARY")
3916 ExprClearProperty(pExpr, EP_Collate);
3919 }else{
3920 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
3921 pExpr->iTable = pSubst->iNewTable;
3923 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
3924 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
3925 if( ExprUseXSelect(pExpr) ){
3926 substSelect(pSubst, pExpr->x.pSelect, 1);
3927 }else{
3928 substExprList(pSubst, pExpr->x.pList);
3930 #ifndef SQLITE_OMIT_WINDOWFUNC
3931 if( ExprHasProperty(pExpr, EP_WinFunc) ){
3932 Window *pWin = pExpr->y.pWin;
3933 pWin->pFilter = substExpr(pSubst, pWin->pFilter);
3934 substExprList(pSubst, pWin->pPartition);
3935 substExprList(pSubst, pWin->pOrderBy);
3937 #endif
3939 return pExpr;
3941 static void substExprList(
3942 SubstContext *pSubst, /* Description of the substitution */
3943 ExprList *pList /* List to scan and in which to make substitutes */
3945 int i;
3946 if( pList==0 ) return;
3947 for(i=0; i<pList->nExpr; i++){
3948 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
3951 static void substSelect(
3952 SubstContext *pSubst, /* Description of the substitution */
3953 Select *p, /* SELECT statement in which to make substitutions */
3954 int doPrior /* Do substitutes on p->pPrior too */
3956 SrcList *pSrc;
3957 SrcItem *pItem;
3958 int i;
3959 if( !p ) return;
3961 substExprList(pSubst, p->pEList);
3962 substExprList(pSubst, p->pGroupBy);
3963 substExprList(pSubst, p->pOrderBy);
3964 p->pHaving = substExpr(pSubst, p->pHaving);
3965 p->pWhere = substExpr(pSubst, p->pWhere);
3966 pSrc = p->pSrc;
3967 assert( pSrc!=0 );
3968 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
3969 substSelect(pSubst, pItem->pSelect, 1);
3970 if( pItem->fg.isTabFunc ){
3971 substExprList(pSubst, pItem->u1.pFuncArg);
3974 }while( doPrior && (p = p->pPrior)!=0 );
3976 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
3978 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3980 ** pSelect is a SELECT statement and pSrcItem is one item in the FROM
3981 ** clause of that SELECT.
3983 ** This routine scans the entire SELECT statement and recomputes the
3984 ** pSrcItem->colUsed mask.
3986 static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
3987 SrcItem *pItem;
3988 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
3989 pItem = pWalker->u.pSrcItem;
3990 if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
3991 if( pExpr->iColumn<0 ) return WRC_Continue;
3992 pItem->colUsed |= sqlite3ExprColUsed(pExpr);
3993 return WRC_Continue;
3995 static void recomputeColumnsUsed(
3996 Select *pSelect, /* The complete SELECT statement */
3997 SrcItem *pSrcItem /* Which FROM clause item to recompute */
3999 Walker w;
4000 if( NEVER(pSrcItem->pTab==0) ) return;
4001 memset(&w, 0, sizeof(w));
4002 w.xExprCallback = recomputeColumnsUsedExpr;
4003 w.xSelectCallback = sqlite3SelectWalkNoop;
4004 w.u.pSrcItem = pSrcItem;
4005 pSrcItem->colUsed = 0;
4006 sqlite3WalkSelect(&w, pSelect);
4008 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4010 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4012 ** Assign new cursor numbers to each of the items in pSrc. For each
4013 ** new cursor number assigned, set an entry in the aCsrMap[] array
4014 ** to map the old cursor number to the new:
4016 ** aCsrMap[iOld+1] = iNew;
4018 ** The array is guaranteed by the caller to be large enough for all
4019 ** existing cursor numbers in pSrc. aCsrMap[0] is the array size.
4021 ** If pSrc contains any sub-selects, call this routine recursively
4022 ** on the FROM clause of each such sub-select, with iExcept set to -1.
4024 static void srclistRenumberCursors(
4025 Parse *pParse, /* Parse context */
4026 int *aCsrMap, /* Array to store cursor mappings in */
4027 SrcList *pSrc, /* FROM clause to renumber */
4028 int iExcept /* FROM clause item to skip */
4030 int i;
4031 SrcItem *pItem;
4032 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
4033 if( i!=iExcept ){
4034 Select *p;
4035 assert( pItem->iCursor < aCsrMap[0] );
4036 if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
4037 aCsrMap[pItem->iCursor+1] = pParse->nTab++;
4039 pItem->iCursor = aCsrMap[pItem->iCursor+1];
4040 for(p=pItem->pSelect; p; p=p->pPrior){
4041 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
4048 ** *piCursor is a cursor number. Change it if it needs to be mapped.
4050 static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
4051 int *aCsrMap = pWalker->u.aiCol;
4052 int iCsr = *piCursor;
4053 if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
4054 *piCursor = aCsrMap[iCsr+1];
4059 ** Expression walker callback used by renumberCursors() to update
4060 ** Expr objects to match newly assigned cursor numbers.
4062 static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
4063 int op = pExpr->op;
4064 if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
4065 renumberCursorDoMapping(pWalker, &pExpr->iTable);
4067 if( ExprHasProperty(pExpr, EP_OuterON) ){
4068 renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
4070 return WRC_Continue;
4074 ** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
4075 ** of the SELECT statement passed as the second argument, and to each
4076 ** cursor in the FROM clause of any FROM clause sub-selects, recursively.
4077 ** Except, do not assign a new cursor number to the iExcept'th element in
4078 ** the FROM clause of (*p). Update all expressions and other references
4079 ** to refer to the new cursor numbers.
4081 ** Argument aCsrMap is an array that may be used for temporary working
4082 ** space. Two guarantees are made by the caller:
4084 ** * the array is larger than the largest cursor number used within the
4085 ** select statement passed as an argument, and
4087 ** * the array entries for all cursor numbers that do *not* appear in
4088 ** FROM clauses of the select statement as described above are
4089 ** initialized to zero.
4091 static void renumberCursors(
4092 Parse *pParse, /* Parse context */
4093 Select *p, /* Select to renumber cursors within */
4094 int iExcept, /* FROM clause item to skip */
4095 int *aCsrMap /* Working space */
4097 Walker w;
4098 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
4099 memset(&w, 0, sizeof(w));
4100 w.u.aiCol = aCsrMap;
4101 w.xExprCallback = renumberCursorsCb;
4102 w.xSelectCallback = sqlite3SelectWalkNoop;
4103 sqlite3WalkSelect(&w, p);
4105 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4108 ** If pSel is not part of a compound SELECT, return a pointer to its
4109 ** expression list. Otherwise, return a pointer to the expression list
4110 ** of the leftmost SELECT in the compound.
4112 static ExprList *findLeftmostExprlist(Select *pSel){
4113 while( pSel->pPrior ){
4114 pSel = pSel->pPrior;
4116 return pSel->pEList;
4120 ** Return true if any of the result-set columns in the compound query
4121 ** have incompatible affinities on one or more arms of the compound.
4123 static int compoundHasDifferentAffinities(Select *p){
4124 int ii;
4125 ExprList *pList;
4126 assert( p!=0 );
4127 assert( p->pEList!=0 );
4128 assert( p->pPrior!=0 );
4129 pList = p->pEList;
4130 for(ii=0; ii<pList->nExpr; ii++){
4131 char aff;
4132 Select *pSub1;
4133 assert( pList->a[ii].pExpr!=0 );
4134 aff = sqlite3ExprAffinity(pList->a[ii].pExpr);
4135 for(pSub1=p->pPrior; pSub1; pSub1=pSub1->pPrior){
4136 assert( pSub1->pEList!=0 );
4137 assert( pSub1->pEList->nExpr>ii );
4138 assert( pSub1->pEList->a[ii].pExpr!=0 );
4139 if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
4140 return 1;
4144 return 0;
4147 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4149 ** This routine attempts to flatten subqueries as a performance optimization.
4150 ** This routine returns 1 if it makes changes and 0 if no flattening occurs.
4152 ** To understand the concept of flattening, consider the following
4153 ** query:
4155 ** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
4157 ** The default way of implementing this query is to execute the
4158 ** subquery first and store the results in a temporary table, then
4159 ** run the outer query on that temporary table. This requires two
4160 ** passes over the data. Furthermore, because the temporary table
4161 ** has no indices, the WHERE clause on the outer query cannot be
4162 ** optimized.
4164 ** This routine attempts to rewrite queries such as the above into
4165 ** a single flat select, like this:
4167 ** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
4169 ** The code generated for this simplification gives the same result
4170 ** but only has to scan the data once. And because indices might
4171 ** exist on the table t1, a complete scan of the data might be
4172 ** avoided.
4174 ** Flattening is subject to the following constraints:
4176 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4177 ** The subquery and the outer query cannot both be aggregates.
4179 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4180 ** (2) If the subquery is an aggregate then
4181 ** (2a) the outer query must not be a join and
4182 ** (2b) the outer query must not use subqueries
4183 ** other than the one FROM-clause subquery that is a candidate
4184 ** for flattening. (This is due to ticket [2f7170d73bf9abf80]
4185 ** from 2015-02-09.)
4187 ** (3) If the subquery is the right operand of a LEFT JOIN then
4188 ** (3a) the subquery may not be a join and
4189 ** (3b) the FROM clause of the subquery may not contain a virtual
4190 ** table and
4191 ** (**) Was: "The outer query may not have a GROUP BY." This case
4192 ** is now managed correctly
4193 ** (3d) the outer query may not be DISTINCT.
4194 ** See also (26) for restrictions on RIGHT JOIN.
4196 ** (4) The subquery can not be DISTINCT.
4198 ** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
4199 ** sub-queries that were excluded from this optimization. Restriction
4200 ** (4) has since been expanded to exclude all DISTINCT subqueries.
4202 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4203 ** If the subquery is aggregate, the outer query may not be DISTINCT.
4205 ** (7) The subquery must have a FROM clause. TODO: For subqueries without
4206 ** A FROM clause, consider adding a FROM clause with the special
4207 ** table sqlite_once that consists of a single row containing a
4208 ** single NULL.
4210 ** (8) If the subquery uses LIMIT then the outer query may not be a join.
4212 ** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
4214 ** (**) Restriction (10) was removed from the code on 2005-02-05 but we
4215 ** accidentally carried the comment forward until 2014-09-15. Original
4216 ** constraint: "If the subquery is aggregate then the outer query
4217 ** may not use LIMIT."
4219 ** (11) The subquery and the outer query may not both have ORDER BY clauses.
4221 ** (**) Not implemented. Subsumed into restriction (3). Was previously
4222 ** a separate restriction deriving from ticket #350.
4224 ** (13) The subquery and outer query may not both use LIMIT.
4226 ** (14) The subquery may not use OFFSET.
4228 ** (15) If the outer query is part of a compound select, then the
4229 ** subquery may not use LIMIT.
4230 ** (See ticket #2339 and ticket [02a8e81d44]).
4232 ** (16) If the outer query is aggregate, then the subquery may not
4233 ** use ORDER BY. (Ticket #2942) This used to not matter
4234 ** until we introduced the group_concat() function.
4236 ** (17) If the subquery is a compound select, then
4237 ** (17a) all compound operators must be a UNION ALL, and
4238 ** (17b) no terms within the subquery compound may be aggregate
4239 ** or DISTINCT, and
4240 ** (17c) every term within the subquery compound must have a FROM clause
4241 ** (17d) the outer query may not be
4242 ** (17d1) aggregate, or
4243 ** (17d2) DISTINCT
4244 ** (17e) the subquery may not contain window functions, and
4245 ** (17f) the subquery must not be the RHS of a LEFT JOIN.
4246 ** (17g) either the subquery is the first element of the outer
4247 ** query or there are no RIGHT or FULL JOINs in any arm
4248 ** of the subquery. (This is a duplicate of condition (27b).)
4249 ** (17h) The corresponding result set expressions in all arms of the
4250 ** compound must have the same affinity.
4252 ** The parent and sub-query may contain WHERE clauses. Subject to
4253 ** rules (11), (13) and (14), they may also contain ORDER BY,
4254 ** LIMIT and OFFSET clauses. The subquery cannot use any compound
4255 ** operator other than UNION ALL because all the other compound
4256 ** operators have an implied DISTINCT which is disallowed by
4257 ** restriction (4).
4259 ** Also, each component of the sub-query must return the same number
4260 ** of result columns. This is actually a requirement for any compound
4261 ** SELECT statement, but all the code here does is make sure that no
4262 ** such (illegal) sub-query is flattened. The caller will detect the
4263 ** syntax error and return a detailed message.
4265 ** (18) If the sub-query is a compound select, then all terms of the
4266 ** ORDER BY clause of the parent must be copies of a term returned
4267 ** by the parent query.
4269 ** (19) If the subquery uses LIMIT then the outer query may not
4270 ** have a WHERE clause.
4272 ** (20) If the sub-query is a compound select, then it must not use
4273 ** an ORDER BY clause. Ticket #3773. We could relax this constraint
4274 ** somewhat by saying that the terms of the ORDER BY clause must
4275 ** appear as unmodified result columns in the outer query. But we
4276 ** have other optimizations in mind to deal with that case.
4278 ** (21) If the subquery uses LIMIT then the outer query may not be
4279 ** DISTINCT. (See ticket [752e1646fc]).
4281 ** (22) The subquery may not be a recursive CTE.
4283 ** (23) If the outer query is a recursive CTE, then the sub-query may not be
4284 ** a compound query. This restriction is because transforming the
4285 ** parent to a compound query confuses the code that handles
4286 ** recursive queries in multiSelect().
4288 ** (**) We no longer attempt to flatten aggregate subqueries. Was:
4289 ** The subquery may not be an aggregate that uses the built-in min() or
4290 ** or max() functions. (Without this restriction, a query like:
4291 ** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
4292 ** return the value X for which Y was maximal.)
4294 ** (25) If either the subquery or the parent query contains a window
4295 ** function in the select list or ORDER BY clause, flattening
4296 ** is not attempted.
4298 ** (26) The subquery may not be the right operand of a RIGHT JOIN.
4299 ** See also (3) for restrictions on LEFT JOIN.
4301 ** (27) The subquery may not contain a FULL or RIGHT JOIN unless it
4302 ** is the first element of the parent query. Two subcases:
4303 ** (27a) the subquery is not a compound query.
4304 ** (27b) the subquery is a compound query and the RIGHT JOIN occurs
4305 ** in any arm of the compound query. (See also (17g).)
4307 ** (28) The subquery is not a MATERIALIZED CTE. (This is handled
4308 ** in the caller before ever reaching this routine.)
4311 ** In this routine, the "p" parameter is a pointer to the outer query.
4312 ** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
4313 ** uses aggregates.
4315 ** If flattening is not attempted, this routine is a no-op and returns 0.
4316 ** If flattening is attempted this routine returns 1.
4318 ** All of the expression analysis must occur on both the outer query and
4319 ** the subquery before this routine runs.
4321 static int flattenSubquery(
4322 Parse *pParse, /* Parsing context */
4323 Select *p, /* The parent or outer SELECT statement */
4324 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
4325 int isAgg /* True if outer SELECT uses aggregate functions */
4327 const char *zSavedAuthContext = pParse->zAuthContext;
4328 Select *pParent; /* Current UNION ALL term of the other query */
4329 Select *pSub; /* The inner query or "subquery" */
4330 Select *pSub1; /* Pointer to the rightmost select in sub-query */
4331 SrcList *pSrc; /* The FROM clause of the outer query */
4332 SrcList *pSubSrc; /* The FROM clause of the subquery */
4333 int iParent; /* VDBE cursor number of the pSub result set temp table */
4334 int iNewParent = -1;/* Replacement table for iParent */
4335 int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
4336 int i; /* Loop counter */
4337 Expr *pWhere; /* The WHERE clause */
4338 SrcItem *pSubitem; /* The subquery */
4339 sqlite3 *db = pParse->db;
4340 Walker w; /* Walker to persist agginfo data */
4341 int *aCsrMap = 0;
4343 /* Check to see if flattening is permitted. Return 0 if not.
4345 assert( p!=0 );
4346 assert( p->pPrior==0 );
4347 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
4348 pSrc = p->pSrc;
4349 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
4350 pSubitem = &pSrc->a[iFrom];
4351 iParent = pSubitem->iCursor;
4352 pSub = pSubitem->pSelect;
4353 assert( pSub!=0 );
4355 #ifndef SQLITE_OMIT_WINDOWFUNC
4356 if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
4357 #endif
4359 pSubSrc = pSub->pSrc;
4360 assert( pSubSrc );
4361 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
4362 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
4363 ** because they could be computed at compile-time. But when LIMIT and OFFSET
4364 ** became arbitrary expressions, we were forced to add restrictions (13)
4365 ** and (14). */
4366 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
4367 if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
4368 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
4369 return 0; /* Restriction (15) */
4371 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
4372 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
4373 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
4374 return 0; /* Restrictions (8)(9) */
4376 if( p->pOrderBy && pSub->pOrderBy ){
4377 return 0; /* Restriction (11) */
4379 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
4380 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
4381 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
4382 return 0; /* Restriction (21) */
4384 if( pSub->selFlags & (SF_Recursive) ){
4385 return 0; /* Restrictions (22) */
4389 ** If the subquery is the right operand of a LEFT JOIN, then the
4390 ** subquery may not be a join itself (3a). Example of why this is not
4391 ** allowed:
4393 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
4395 ** If we flatten the above, we would get
4397 ** (t1 LEFT OUTER JOIN t2) JOIN t3
4399 ** which is not at all the same thing.
4401 ** See also tickets #306, #350, and #3300.
4403 if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
4404 if( pSubSrc->nSrc>1 /* (3a) */
4405 || IsVirtual(pSubSrc->a[0].pTab) /* (3b) */
4406 || (p->selFlags & SF_Distinct)!=0 /* (3d) */
4407 || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */
4409 return 0;
4411 isOuterJoin = 1;
4414 assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */
4415 if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4416 return 0; /* Restriction (27a) */
4419 /* Condition (28) is blocked by the caller */
4420 assert( !pSubitem->fg.isCte || pSubitem->u2.pCteUse->eM10d!=M10d_Yes );
4422 /* Restriction (17): If the sub-query is a compound SELECT, then it must
4423 ** use only the UNION ALL operator. And none of the simple select queries
4424 ** that make up the compound SELECT are allowed to be aggregate or distinct
4425 ** queries.
4427 if( pSub->pPrior ){
4428 int ii;
4429 if( pSub->pOrderBy ){
4430 return 0; /* Restriction (20) */
4432 if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
4433 return 0; /* (17d1), (17d2), or (17f) */
4435 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
4436 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
4437 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
4438 assert( pSub->pSrc!=0 );
4439 assert( (pSub->selFlags & SF_Recursive)==0 );
4440 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
4441 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
4442 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
4443 || pSub1->pSrc->nSrc<1 /* (17c) */
4444 #ifndef SQLITE_OMIT_WINDOWFUNC
4445 || pSub1->pWin /* (17e) */
4446 #endif
4448 return 0;
4450 if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4451 /* Without this restriction, the JT_LTORJ flag would end up being
4452 ** omitted on left-hand tables of the right join that is being
4453 ** flattened. */
4454 return 0; /* Restrictions (17g), (27b) */
4456 testcase( pSub1->pSrc->nSrc>1 );
4459 /* Restriction (18). */
4460 if( p->pOrderBy ){
4461 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
4462 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
4466 /* Restriction (23) */
4467 if( (p->selFlags & SF_Recursive) ) return 0;
4469 /* Restriction (17h) */
4470 if( compoundHasDifferentAffinities(pSub) ) return 0;
4472 if( pSrc->nSrc>1 ){
4473 if( pParse->nSelect>500 ) return 0;
4474 if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
4475 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
4476 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
4480 /***** If we reach this point, flattening is permitted. *****/
4481 TREETRACE(0x4,pParse,p,("flatten %u.%p from term %d\n",
4482 pSub->selId, pSub, iFrom));
4484 /* Authorize the subquery */
4485 pParse->zAuthContext = pSubitem->zName;
4486 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
4487 testcase( i==SQLITE_DENY );
4488 pParse->zAuthContext = zSavedAuthContext;
4490 /* Delete the transient structures associated with the subquery */
4491 pSub1 = pSubitem->pSelect;
4492 sqlite3DbFree(db, pSubitem->zDatabase);
4493 sqlite3DbFree(db, pSubitem->zName);
4494 sqlite3DbFree(db, pSubitem->zAlias);
4495 pSubitem->zDatabase = 0;
4496 pSubitem->zName = 0;
4497 pSubitem->zAlias = 0;
4498 pSubitem->pSelect = 0;
4499 assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
4501 /* If the sub-query is a compound SELECT statement, then (by restrictions
4502 ** 17 and 18 above) it must be a UNION ALL and the parent query must
4503 ** be of the form:
4505 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
4507 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
4508 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
4509 ** OFFSET clauses and joins them to the left-hand-side of the original
4510 ** using UNION ALL operators. In this case N is the number of simple
4511 ** select statements in the compound sub-query.
4513 ** Example:
4515 ** SELECT a+1 FROM (
4516 ** SELECT x FROM tab
4517 ** UNION ALL
4518 ** SELECT y FROM tab
4519 ** UNION ALL
4520 ** SELECT abs(z*2) FROM tab2
4521 ** ) WHERE a!=5 ORDER BY 1
4523 ** Transformed into:
4525 ** SELECT x+1 FROM tab WHERE x+1!=5
4526 ** UNION ALL
4527 ** SELECT y+1 FROM tab WHERE y+1!=5
4528 ** UNION ALL
4529 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
4530 ** ORDER BY 1
4532 ** We call this the "compound-subquery flattening".
4534 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
4535 Select *pNew;
4536 ExprList *pOrderBy = p->pOrderBy;
4537 Expr *pLimit = p->pLimit;
4538 Select *pPrior = p->pPrior;
4539 Table *pItemTab = pSubitem->pTab;
4540 pSubitem->pTab = 0;
4541 p->pOrderBy = 0;
4542 p->pPrior = 0;
4543 p->pLimit = 0;
4544 pNew = sqlite3SelectDup(db, p, 0);
4545 p->pLimit = pLimit;
4546 p->pOrderBy = pOrderBy;
4547 p->op = TK_ALL;
4548 pSubitem->pTab = pItemTab;
4549 if( pNew==0 ){
4550 p->pPrior = pPrior;
4551 }else{
4552 pNew->selId = ++pParse->nSelect;
4553 if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
4554 renumberCursors(pParse, pNew, iFrom, aCsrMap);
4556 pNew->pPrior = pPrior;
4557 if( pPrior ) pPrior->pNext = pNew;
4558 pNew->pNext = p;
4559 p->pPrior = pNew;
4560 TREETRACE(0x4,pParse,p,("compound-subquery flattener"
4561 " creates %u as peer\n",pNew->selId));
4563 assert( pSubitem->pSelect==0 );
4565 sqlite3DbFree(db, aCsrMap);
4566 if( db->mallocFailed ){
4567 pSubitem->pSelect = pSub1;
4568 return 1;
4571 /* Defer deleting the Table object associated with the
4572 ** subquery until code generation is
4573 ** complete, since there may still exist Expr.pTab entries that
4574 ** refer to the subquery even after flattening. Ticket #3346.
4576 ** pSubitem->pTab is always non-NULL by test restrictions and tests above.
4578 if( ALWAYS(pSubitem->pTab!=0) ){
4579 Table *pTabToDel = pSubitem->pTab;
4580 if( pTabToDel->nTabRef==1 ){
4581 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4582 sqlite3ParserAddCleanup(pToplevel,
4583 (void(*)(sqlite3*,void*))sqlite3DeleteTable,
4584 pTabToDel);
4585 testcase( pToplevel->earlyCleanup );
4586 }else{
4587 pTabToDel->nTabRef--;
4589 pSubitem->pTab = 0;
4592 /* The following loop runs once for each term in a compound-subquery
4593 ** flattening (as described above). If we are doing a different kind
4594 ** of flattening - a flattening other than a compound-subquery flattening -
4595 ** then this loop only runs once.
4597 ** This loop moves all of the FROM elements of the subquery into the
4598 ** the FROM clause of the outer query. Before doing this, remember
4599 ** the cursor number for the original outer query FROM element in
4600 ** iParent. The iParent cursor will never be used. Subsequent code
4601 ** will scan expressions looking for iParent references and replace
4602 ** those references with expressions that resolve to the subquery FROM
4603 ** elements we are now copying in.
4605 pSub = pSub1;
4606 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
4607 int nSubSrc;
4608 u8 jointype = 0;
4609 u8 ltorj = pSrc->a[iFrom].fg.jointype & JT_LTORJ;
4610 assert( pSub!=0 );
4611 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
4612 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
4613 pSrc = pParent->pSrc; /* FROM clause of the outer query */
4615 if( pParent==p ){
4616 jointype = pSubitem->fg.jointype; /* First time through the loop */
4619 /* The subquery uses a single slot of the FROM clause of the outer
4620 ** query. If the subquery has more than one element in its FROM clause,
4621 ** then expand the outer query to make space for it to hold all elements
4622 ** of the subquery.
4624 ** Example:
4626 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
4628 ** The outer query has 3 slots in its FROM clause. One slot of the
4629 ** outer query (the middle slot) is used by the subquery. The next
4630 ** block of code will expand the outer query FROM clause to 4 slots.
4631 ** The middle slot is expanded to two slots in order to make space
4632 ** for the two elements in the FROM clause of the subquery.
4634 if( nSubSrc>1 ){
4635 pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
4636 if( pSrc==0 ) break;
4637 pParent->pSrc = pSrc;
4640 /* Transfer the FROM clause terms from the subquery into the
4641 ** outer query.
4643 for(i=0; i<nSubSrc; i++){
4644 SrcItem *pItem = &pSrc->a[i+iFrom];
4645 if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
4646 assert( pItem->fg.isTabFunc==0 );
4647 *pItem = pSubSrc->a[i];
4648 pItem->fg.jointype |= ltorj;
4649 iNewParent = pSubSrc->a[i].iCursor;
4650 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
4652 pSrc->a[iFrom].fg.jointype &= JT_LTORJ;
4653 pSrc->a[iFrom].fg.jointype |= jointype | ltorj;
4655 /* Now begin substituting subquery result set expressions for
4656 ** references to the iParent in the outer query.
4658 ** Example:
4660 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
4661 ** \ \_____________ subquery __________/ /
4662 ** \_____________________ outer query ______________________________/
4664 ** We look at every expression in the outer query and every place we see
4665 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
4667 if( pSub->pOrderBy && (pParent->selFlags & SF_NoopOrderBy)==0 ){
4668 /* At this point, any non-zero iOrderByCol values indicate that the
4669 ** ORDER BY column expression is identical to the iOrderByCol'th
4670 ** expression returned by SELECT statement pSub. Since these values
4671 ** do not necessarily correspond to columns in SELECT statement pParent,
4672 ** zero them before transferring the ORDER BY clause.
4674 ** Not doing this may cause an error if a subsequent call to this
4675 ** function attempts to flatten a compound sub-query into pParent
4676 ** (the only way this can happen is if the compound sub-query is
4677 ** currently part of pSub->pSrc). See ticket [d11a6e908f]. */
4678 ExprList *pOrderBy = pSub->pOrderBy;
4679 for(i=0; i<pOrderBy->nExpr; i++){
4680 pOrderBy->a[i].u.x.iOrderByCol = 0;
4682 assert( pParent->pOrderBy==0 );
4683 pParent->pOrderBy = pOrderBy;
4684 pSub->pOrderBy = 0;
4686 pWhere = pSub->pWhere;
4687 pSub->pWhere = 0;
4688 if( isOuterJoin>0 ){
4689 sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON);
4691 if( pWhere ){
4692 if( pParent->pWhere ){
4693 pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
4694 }else{
4695 pParent->pWhere = pWhere;
4698 if( db->mallocFailed==0 ){
4699 SubstContext x;
4700 x.pParse = pParse;
4701 x.iTable = iParent;
4702 x.iNewTable = iNewParent;
4703 x.isOuterJoin = isOuterJoin;
4704 x.pEList = pSub->pEList;
4705 x.pCList = findLeftmostExprlist(pSub);
4706 substSelect(&x, pParent, 0);
4709 /* The flattened query is a compound if either the inner or the
4710 ** outer query is a compound. */
4711 pParent->selFlags |= pSub->selFlags & SF_Compound;
4712 assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
4715 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
4717 ** One is tempted to try to add a and b to combine the limits. But this
4718 ** does not work if either limit is negative.
4720 if( pSub->pLimit ){
4721 pParent->pLimit = pSub->pLimit;
4722 pSub->pLimit = 0;
4725 /* Recompute the SrcItem.colUsed masks for the flattened
4726 ** tables. */
4727 for(i=0; i<nSubSrc; i++){
4728 recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
4732 /* Finally, delete what is left of the subquery and return success.
4734 sqlite3AggInfoPersistWalkerInit(&w, pParse);
4735 sqlite3WalkSelect(&w,pSub1);
4736 sqlite3SelectDelete(db, pSub1);
4738 #if TREETRACE_ENABLED
4739 if( sqlite3TreeTrace & 0x4 ){
4740 TREETRACE(0x4,pParse,p,("After flattening:\n"));
4741 sqlite3TreeViewSelect(0, p, 0);
4743 #endif
4745 return 1;
4747 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4750 ** A structure to keep track of all of the column values that are fixed to
4751 ** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
4753 typedef struct WhereConst WhereConst;
4754 struct WhereConst {
4755 Parse *pParse; /* Parsing context */
4756 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
4757 int nConst; /* Number for COLUMN=CONSTANT terms */
4758 int nChng; /* Number of times a constant is propagated */
4759 int bHasAffBlob; /* At least one column in apExpr[] as affinity BLOB */
4760 u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
4761 ** Either EP_OuterON or EP_InnerON|EP_OuterON */
4762 Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
4766 ** Add a new entry to the pConst object. Except, do not add duplicate
4767 ** pColumn entries. Also, do not add if doing so would not be appropriate.
4769 ** The caller guarantees the pColumn is a column and pValue is a constant.
4770 ** This routine has to do some additional checks before completing the
4771 ** insert.
4773 static void constInsert(
4774 WhereConst *pConst, /* The WhereConst into which we are inserting */
4775 Expr *pColumn, /* The COLUMN part of the constraint */
4776 Expr *pValue, /* The VALUE part of the constraint */
4777 Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
4779 int i;
4780 assert( pColumn->op==TK_COLUMN );
4781 assert( sqlite3ExprIsConstant(pValue) );
4783 if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
4784 if( sqlite3ExprAffinity(pValue)!=0 ) return;
4785 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
4786 return;
4789 /* 2018-10-25 ticket [cf5ed20f]
4790 ** Make sure the same pColumn is not inserted more than once */
4791 for(i=0; i<pConst->nConst; i++){
4792 const Expr *pE2 = pConst->apExpr[i*2];
4793 assert( pE2->op==TK_COLUMN );
4794 if( pE2->iTable==pColumn->iTable
4795 && pE2->iColumn==pColumn->iColumn
4797 return; /* Already present. Return without doing anything. */
4800 if( sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4801 pConst->bHasAffBlob = 1;
4804 pConst->nConst++;
4805 pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
4806 pConst->nConst*2*sizeof(Expr*));
4807 if( pConst->apExpr==0 ){
4808 pConst->nConst = 0;
4809 }else{
4810 pConst->apExpr[pConst->nConst*2-2] = pColumn;
4811 pConst->apExpr[pConst->nConst*2-1] = pValue;
4816 ** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
4817 ** is a constant expression and where the term must be true because it
4818 ** is part of the AND-connected terms of the expression. For each term
4819 ** found, add it to the pConst structure.
4821 static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
4822 Expr *pRight, *pLeft;
4823 if( NEVER(pExpr==0) ) return;
4824 if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
4825 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4826 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4827 return;
4829 if( pExpr->op==TK_AND ){
4830 findConstInWhere(pConst, pExpr->pRight);
4831 findConstInWhere(pConst, pExpr->pLeft);
4832 return;
4834 if( pExpr->op!=TK_EQ ) return;
4835 pRight = pExpr->pRight;
4836 pLeft = pExpr->pLeft;
4837 assert( pRight!=0 );
4838 assert( pLeft!=0 );
4839 if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pLeft) ){
4840 constInsert(pConst,pRight,pLeft,pExpr);
4842 if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pRight) ){
4843 constInsert(pConst,pLeft,pRight,pExpr);
4848 ** This is a helper function for Walker callback propagateConstantExprRewrite().
4850 ** Argument pExpr is a candidate expression to be replaced by a value. If
4851 ** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
4852 ** then overwrite it with the corresponding value. Except, do not do so
4853 ** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
4854 ** is SQLITE_AFF_BLOB.
4856 static int propagateConstantExprRewriteOne(
4857 WhereConst *pConst,
4858 Expr *pExpr,
4859 int bIgnoreAffBlob
4861 int i;
4862 if( pConst->pOomFault[0] ) return WRC_Prune;
4863 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
4864 if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
4865 testcase( ExprHasProperty(pExpr, EP_FixedCol) );
4866 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4867 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4868 return WRC_Continue;
4870 for(i=0; i<pConst->nConst; i++){
4871 Expr *pColumn = pConst->apExpr[i*2];
4872 if( pColumn==pExpr ) continue;
4873 if( pColumn->iTable!=pExpr->iTable ) continue;
4874 if( pColumn->iColumn!=pExpr->iColumn ) continue;
4875 if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)==SQLITE_AFF_BLOB ){
4876 break;
4878 /* A match is found. Add the EP_FixedCol property */
4879 pConst->nChng++;
4880 ExprClearProperty(pExpr, EP_Leaf);
4881 ExprSetProperty(pExpr, EP_FixedCol);
4882 assert( pExpr->pLeft==0 );
4883 pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
4884 if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
4885 break;
4887 return WRC_Prune;
4891 ** This is a Walker expression callback. pExpr is a node from the WHERE
4892 ** clause of a SELECT statement. This function examines pExpr to see if
4893 ** any substitutions based on the contents of pWalker->u.pConst should
4894 ** be made to pExpr or its immediate children.
4896 ** A substitution is made if:
4898 ** + pExpr is a column with an affinity other than BLOB that matches
4899 ** one of the columns in pWalker->u.pConst, or
4901 ** + pExpr is a binary comparison operator (=, <=, >=, <, >) that
4902 ** uses an affinity other than TEXT and one of its immediate
4903 ** children is a column that matches one of the columns in
4904 ** pWalker->u.pConst.
4906 static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
4907 WhereConst *pConst = pWalker->u.pConst;
4908 assert( TK_GT==TK_EQ+1 );
4909 assert( TK_LE==TK_EQ+2 );
4910 assert( TK_LT==TK_EQ+3 );
4911 assert( TK_GE==TK_EQ+4 );
4912 if( pConst->bHasAffBlob ){
4913 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
4914 || pExpr->op==TK_IS
4916 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
4917 if( pConst->pOomFault[0] ) return WRC_Prune;
4918 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
4919 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
4923 return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
4927 ** The WHERE-clause constant propagation optimization.
4929 ** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
4930 ** CONSTANT=COLUMN that are top-level AND-connected terms that are not
4931 ** part of a ON clause from a LEFT JOIN, then throughout the query
4932 ** replace all other occurrences of COLUMN with CONSTANT.
4934 ** For example, the query:
4936 ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
4938 ** Is transformed into
4940 ** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
4942 ** Return true if any transformations where made and false if not.
4944 ** Implementation note: Constant propagation is tricky due to affinity
4945 ** and collating sequence interactions. Consider this example:
4947 ** CREATE TABLE t1(a INT,b TEXT);
4948 ** INSERT INTO t1 VALUES(123,'0123');
4949 ** SELECT * FROM t1 WHERE a=123 AND b=a;
4950 ** SELECT * FROM t1 WHERE a=123 AND b=123;
4952 ** The two SELECT statements above should return different answers. b=a
4953 ** is always true because the comparison uses numeric affinity, but b=123
4954 ** is false because it uses text affinity and '0123' is not the same as '123'.
4955 ** To work around this, the expression tree is not actually changed from
4956 ** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
4957 ** and the "123" value is hung off of the pLeft pointer. Code generator
4958 ** routines know to generate the constant "123" instead of looking up the
4959 ** column value. Also, to avoid collation problems, this optimization is
4960 ** only attempted if the "a=123" term uses the default BINARY collation.
4962 ** 2021-05-25 forum post 6a06202608: Another troublesome case is...
4964 ** CREATE TABLE t1(x);
4965 ** INSERT INTO t1 VALUES(10.0);
4966 ** SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
4968 ** The query should return no rows, because the t1.x value is '10.0' not '10'
4969 ** and '10.0' is not LIKE '10'. But if we are not careful, the first WHERE
4970 ** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
4971 ** resulting in a false positive. To avoid this, constant propagation for
4972 ** columns with BLOB affinity is only allowed if the constant is used with
4973 ** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
4974 ** type conversions to occur. See logic associated with the bHasAffBlob flag
4975 ** for details.
4977 static int propagateConstants(
4978 Parse *pParse, /* The parsing context */
4979 Select *p /* The query in which to propagate constants */
4981 WhereConst x;
4982 Walker w;
4983 int nChng = 0;
4984 x.pParse = pParse;
4985 x.pOomFault = &pParse->db->mallocFailed;
4987 x.nConst = 0;
4988 x.nChng = 0;
4989 x.apExpr = 0;
4990 x.bHasAffBlob = 0;
4991 if( ALWAYS(p->pSrc!=0)
4992 && p->pSrc->nSrc>0
4993 && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
4995 /* Do not propagate constants on any ON clause if there is a
4996 ** RIGHT JOIN anywhere in the query */
4997 x.mExcludeOn = EP_InnerON | EP_OuterON;
4998 }else{
4999 /* Do not propagate constants through the ON clause of a LEFT JOIN */
5000 x.mExcludeOn = EP_OuterON;
5002 findConstInWhere(&x, p->pWhere);
5003 if( x.nConst ){
5004 memset(&w, 0, sizeof(w));
5005 w.pParse = pParse;
5006 w.xExprCallback = propagateConstantExprRewrite;
5007 w.xSelectCallback = sqlite3SelectWalkNoop;
5008 w.xSelectCallback2 = 0;
5009 w.walkerDepth = 0;
5010 w.u.pConst = &x;
5011 sqlite3WalkExpr(&w, p->pWhere);
5012 sqlite3DbFree(x.pParse->db, x.apExpr);
5013 nChng += x.nChng;
5015 }while( x.nChng );
5016 return nChng;
5019 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5020 # if !defined(SQLITE_OMIT_WINDOWFUNC)
5022 ** This function is called to determine whether or not it is safe to
5023 ** push WHERE clause expression pExpr down to FROM clause sub-query
5024 ** pSubq, which contains at least one window function. Return 1
5025 ** if it is safe and the expression should be pushed down, or 0
5026 ** otherwise.
5028 ** It is only safe to push the expression down if it consists only
5029 ** of constants and copies of expressions that appear in the PARTITION
5030 ** BY clause of all window function used by the sub-query. It is safe
5031 ** to filter out entire partitions, but not rows within partitions, as
5032 ** this may change the results of the window functions.
5034 ** At the time this function is called it is guaranteed that
5036 ** * the sub-query uses only one distinct window frame, and
5037 ** * that the window frame has a PARTITION BY clause.
5039 static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
5040 assert( pSubq->pWin->pPartition );
5041 assert( (pSubq->selFlags & SF_MultiPart)==0 );
5042 assert( pSubq->pPrior==0 );
5043 return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
5045 # endif /* SQLITE_OMIT_WINDOWFUNC */
5046 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5048 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5050 ** Make copies of relevant WHERE clause terms of the outer query into
5051 ** the WHERE clause of subquery. Example:
5053 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
5055 ** Transformed into:
5057 ** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
5058 ** WHERE x=5 AND y=10;
5060 ** The hope is that the terms added to the inner query will make it more
5061 ** efficient.
5063 ** Do not attempt this optimization if:
5065 ** (1) (** This restriction was removed on 2017-09-29. We used to
5066 ** disallow this optimization for aggregate subqueries, but now
5067 ** it is allowed by putting the extra terms on the HAVING clause.
5068 ** The added HAVING clause is pointless if the subquery lacks
5069 ** a GROUP BY clause. But such a HAVING clause is also harmless
5070 ** so there does not appear to be any reason to add extra logic
5071 ** to suppress it. **)
5073 ** (2) The inner query is the recursive part of a common table expression.
5075 ** (3) The inner query has a LIMIT clause (since the changes to the WHERE
5076 ** clause would change the meaning of the LIMIT).
5078 ** (4) The inner query is the right operand of a LEFT JOIN and the
5079 ** expression to be pushed down does not come from the ON clause
5080 ** on that LEFT JOIN.
5082 ** (5) The WHERE clause expression originates in the ON or USING clause
5083 ** of a LEFT JOIN where iCursor is not the right-hand table of that
5084 ** left join. An example:
5086 ** SELECT *
5087 ** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
5088 ** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
5089 ** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
5091 ** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
5092 ** But if the (b2=2) term were to be pushed down into the bb subquery,
5093 ** then the (1,1,NULL) row would be suppressed.
5095 ** (6) Window functions make things tricky as changes to the WHERE clause
5096 ** of the inner query could change the window over which window
5097 ** functions are calculated. Therefore, do not attempt the optimization
5098 ** if:
5100 ** (6a) The inner query uses multiple incompatible window partitions.
5102 ** (6b) The inner query is a compound and uses window-functions.
5104 ** (6c) The WHERE clause does not consist entirely of constants and
5105 ** copies of expressions found in the PARTITION BY clause of
5106 ** all window-functions used by the sub-query. It is safe to
5107 ** filter out entire partitions, as this does not change the
5108 ** window over which any window-function is calculated.
5110 ** (7) The inner query is a Common Table Expression (CTE) that should
5111 ** be materialized. (This restriction is implemented in the calling
5112 ** routine.)
5114 ** (8) If the subquery is a compound that uses UNION, INTERSECT,
5115 ** or EXCEPT, then all of the result set columns for all arms of
5116 ** the compound must use the BINARY collating sequence.
5118 ** (9) All three of the following are true:
5120 ** (9a) The WHERE clause expression originates in the ON or USING clause
5121 ** of a join (either an INNER or an OUTER join), and
5123 ** (9b) The subquery is to the right of the ON/USING clause
5125 ** (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
5126 ** clause and the subquery.
5128 ** Without this restriction, the push-down optimization might move
5129 ** the ON/USING filter expression from the left side of a RIGHT JOIN
5130 ** over to the right side, which leads to incorrect answers. See
5131 ** also restriction (6) in sqlite3ExprIsSingleTableConstraint().
5133 ** (10) The inner query is not the right-hand table of a RIGHT JOIN.
5135 ** (11) The subquery is not a VALUES clause
5137 ** Return 0 if no changes are made and non-zero if one or more WHERE clause
5138 ** terms are duplicated into the subquery.
5140 static int pushDownWhereTerms(
5141 Parse *pParse, /* Parse context (for malloc() and error reporting) */
5142 Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
5143 Expr *pWhere, /* The WHERE clause of the outer query */
5144 SrcList *pSrcList, /* The complete from clause of the outer query */
5145 int iSrc /* Which FROM clause term to try to push into */
5147 Expr *pNew;
5148 SrcItem *pSrc; /* The subquery FROM term into which WHERE is pushed */
5149 int nChng = 0;
5150 pSrc = &pSrcList->a[iSrc];
5151 if( pWhere==0 ) return 0;
5152 if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
5153 return 0; /* restrictions (2) and (11) */
5155 if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
5156 return 0; /* restrictions (10) */
5159 if( pSubq->pPrior ){
5160 Select *pSel;
5161 int notUnionAll = 0;
5162 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5163 u8 op = pSel->op;
5164 assert( op==TK_ALL || op==TK_SELECT
5165 || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
5166 if( op!=TK_ALL && op!=TK_SELECT ){
5167 notUnionAll = 1;
5169 #ifndef SQLITE_OMIT_WINDOWFUNC
5170 if( pSel->pWin ) return 0; /* restriction (6b) */
5171 #endif
5173 if( notUnionAll ){
5174 /* If any of the compound arms are connected using UNION, INTERSECT,
5175 ** or EXCEPT, then we must ensure that none of the columns use a
5176 ** non-BINARY collating sequence. */
5177 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5178 int ii;
5179 const ExprList *pList = pSel->pEList;
5180 assert( pList!=0 );
5181 for(ii=0; ii<pList->nExpr; ii++){
5182 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[ii].pExpr);
5183 if( !sqlite3IsBinary(pColl) ){
5184 return 0; /* Restriction (8) */
5189 }else{
5190 #ifndef SQLITE_OMIT_WINDOWFUNC
5191 if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
5192 #endif
5195 #ifdef SQLITE_DEBUG
5196 /* Only the first term of a compound can have a WITH clause. But make
5197 ** sure no other terms are marked SF_Recursive in case something changes
5198 ** in the future.
5201 Select *pX;
5202 for(pX=pSubq; pX; pX=pX->pPrior){
5203 assert( (pX->selFlags & (SF_Recursive))==0 );
5206 #endif
5208 if( pSubq->pLimit!=0 ){
5209 return 0; /* restriction (3) */
5211 while( pWhere->op==TK_AND ){
5212 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
5213 pWhere = pWhere->pLeft;
5216 #if 0 /* These checks now done by sqlite3ExprIsSingleTableConstraint() */
5217 if( ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) /* (9a) */
5218 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (9c) */
5220 int jj;
5221 for(jj=0; jj<iSrc; jj++){
5222 if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
5223 /* If we reach this point, both (9a) and (9b) are satisfied.
5224 ** The following loop checks (9c):
5226 for(jj++; jj<iSrc; jj++){
5227 if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
5228 return 0; /* restriction (9) */
5234 if( isLeftJoin
5235 && (ExprHasProperty(pWhere,EP_OuterON)==0
5236 || pWhere->w.iJoin!=iCursor)
5238 return 0; /* restriction (4) */
5240 if( ExprHasProperty(pWhere,EP_OuterON)
5241 && pWhere->w.iJoin!=iCursor
5243 return 0; /* restriction (5) */
5245 #endif
5247 if( sqlite3ExprIsSingleTableConstraint(pWhere, pSrcList, iSrc) ){
5248 nChng++;
5249 pSubq->selFlags |= SF_PushDown;
5250 while( pSubq ){
5251 SubstContext x;
5252 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
5253 unsetJoinExpr(pNew, -1, 1);
5254 x.pParse = pParse;
5255 x.iTable = pSrc->iCursor;
5256 x.iNewTable = pSrc->iCursor;
5257 x.isOuterJoin = 0;
5258 x.pEList = pSubq->pEList;
5259 x.pCList = findLeftmostExprlist(pSubq);
5260 pNew = substExpr(&x, pNew);
5261 #ifndef SQLITE_OMIT_WINDOWFUNC
5262 if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
5263 /* Restriction 6c has prevented push-down in this case */
5264 sqlite3ExprDelete(pParse->db, pNew);
5265 nChng--;
5266 break;
5268 #endif
5269 if( pSubq->selFlags & SF_Aggregate ){
5270 pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
5271 }else{
5272 pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
5274 pSubq = pSubq->pPrior;
5277 return nChng;
5279 #endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5282 ** Check to see if a subquery contains result-set columns that are
5283 ** never used. If it does, change the value of those result-set columns
5284 ** to NULL so that they do not cause unnecessary work to compute.
5286 ** Return the number of column that were changed to NULL.
5288 static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
5289 int nCol;
5290 Select *pSub; /* The subquery to be simplified */
5291 Select *pX; /* For looping over compound elements of pSub */
5292 Table *pTab; /* The table that describes the subquery */
5293 int j; /* Column number */
5294 int nChng = 0; /* Number of columns converted to NULL */
5295 Bitmask colUsed; /* Columns that may not be NULLed out */
5297 assert( pItem!=0 );
5298 if( pItem->fg.isCorrelated || pItem->fg.isCte ){
5299 return 0;
5301 assert( pItem->pTab!=0 );
5302 pTab = pItem->pTab;
5303 assert( pItem->pSelect!=0 );
5304 pSub = pItem->pSelect;
5305 assert( pSub->pEList->nExpr==pTab->nCol );
5306 for(pX=pSub; pX; pX=pX->pPrior){
5307 if( (pX->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
5308 testcase( pX->selFlags & SF_Distinct );
5309 testcase( pX->selFlags & SF_Aggregate );
5310 return 0;
5312 if( pX->pPrior && pX->op!=TK_ALL ){
5313 /* This optimization does not work for compound subqueries that
5314 ** use UNION, INTERSECT, or EXCEPT. Only UNION ALL is allowed. */
5315 return 0;
5317 #ifndef SQLITE_OMIT_WINDOWFUNC
5318 if( pX->pWin ){
5319 /* This optimization does not work for subqueries that use window
5320 ** functions. */
5321 return 0;
5323 #endif
5325 colUsed = pItem->colUsed;
5326 if( pSub->pOrderBy ){
5327 ExprList *pList = pSub->pOrderBy;
5328 for(j=0; j<pList->nExpr; j++){
5329 u16 iCol = pList->a[j].u.x.iOrderByCol;
5330 if( iCol>0 ){
5331 iCol--;
5332 colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
5336 nCol = pTab->nCol;
5337 for(j=0; j<nCol; j++){
5338 Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
5339 if( (m & colUsed)!=0 ) continue;
5340 for(pX=pSub; pX; pX=pX->pPrior) {
5341 Expr *pY = pX->pEList->a[j].pExpr;
5342 if( pY->op==TK_NULL ) continue;
5343 pY->op = TK_NULL;
5344 ExprClearProperty(pY, EP_Skip|EP_Unlikely);
5345 pX->selFlags |= SF_PushDown;
5346 nChng++;
5349 return nChng;
5354 ** The pFunc is the only aggregate function in the query. Check to see
5355 ** if the query is a candidate for the min/max optimization.
5357 ** If the query is a candidate for the min/max optimization, then set
5358 ** *ppMinMax to be an ORDER BY clause to be used for the optimization
5359 ** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
5360 ** whether pFunc is a min() or max() function.
5362 ** If the query is not a candidate for the min/max optimization, return
5363 ** WHERE_ORDERBY_NORMAL (which must be zero).
5365 ** This routine must be called after aggregate functions have been
5366 ** located but before their arguments have been subjected to aggregate
5367 ** analysis.
5369 static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
5370 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
5371 ExprList *pEList; /* Arguments to agg function */
5372 const char *zFunc; /* Name of aggregate function pFunc */
5373 ExprList *pOrderBy;
5374 u8 sortFlags = 0;
5376 assert( *ppMinMax==0 );
5377 assert( pFunc->op==TK_AGG_FUNCTION );
5378 assert( !IsWindowFunc(pFunc) );
5379 assert( ExprUseXList(pFunc) );
5380 pEList = pFunc->x.pList;
5381 if( pEList==0
5382 || pEList->nExpr!=1
5383 || ExprHasProperty(pFunc, EP_WinFunc)
5384 || OptimizationDisabled(db, SQLITE_MinMaxOpt)
5386 return eRet;
5388 assert( !ExprHasProperty(pFunc, EP_IntValue) );
5389 zFunc = pFunc->u.zToken;
5390 if( sqlite3StrICmp(zFunc, "min")==0 ){
5391 eRet = WHERE_ORDERBY_MIN;
5392 if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
5393 sortFlags = KEYINFO_ORDER_BIGNULL;
5395 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
5396 eRet = WHERE_ORDERBY_MAX;
5397 sortFlags = KEYINFO_ORDER_DESC;
5398 }else{
5399 return eRet;
5401 *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
5402 assert( pOrderBy!=0 || db->mallocFailed );
5403 if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
5404 return eRet;
5408 ** The select statement passed as the first argument is an aggregate query.
5409 ** The second argument is the associated aggregate-info object. This
5410 ** function tests if the SELECT is of the form:
5412 ** SELECT count(*) FROM <tbl>
5414 ** where table is a database table, not a sub-select or view. If the query
5415 ** does match this pattern, then a pointer to the Table object representing
5416 ** <tbl> is returned. Otherwise, NULL is returned.
5418 ** This routine checks to see if it is safe to use the count optimization.
5419 ** A correct answer is still obtained (though perhaps more slowly) if
5420 ** this routine returns NULL when it could have returned a table pointer.
5421 ** But returning the pointer when NULL should have been returned can
5422 ** result in incorrect answers and/or crashes. So, when in doubt, return NULL.
5424 static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
5425 Table *pTab;
5426 Expr *pExpr;
5428 assert( !p->pGroupBy );
5430 if( p->pWhere
5431 || p->pEList->nExpr!=1
5432 || p->pSrc->nSrc!=1
5433 || p->pSrc->a[0].pSelect
5434 || pAggInfo->nFunc!=1
5435 || p->pHaving
5437 return 0;
5439 pTab = p->pSrc->a[0].pTab;
5440 assert( pTab!=0 );
5441 assert( !IsView(pTab) );
5442 if( !IsOrdinaryTable(pTab) ) return 0;
5443 pExpr = p->pEList->a[0].pExpr;
5444 assert( pExpr!=0 );
5445 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
5446 if( pExpr->pAggInfo!=pAggInfo ) return 0;
5447 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
5448 assert( pAggInfo->aFunc[0].pFExpr==pExpr );
5449 testcase( ExprHasProperty(pExpr, EP_Distinct) );
5450 testcase( ExprHasProperty(pExpr, EP_WinFunc) );
5451 if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
5453 return pTab;
5457 ** If the source-list item passed as an argument was augmented with an
5458 ** INDEXED BY clause, then try to locate the specified index. If there
5459 ** was such a clause and the named index cannot be found, return
5460 ** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
5461 ** pFrom->pIndex and return SQLITE_OK.
5463 int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
5464 Table *pTab = pFrom->pTab;
5465 char *zIndexedBy = pFrom->u1.zIndexedBy;
5466 Index *pIdx;
5467 assert( pTab!=0 );
5468 assert( pFrom->fg.isIndexedBy!=0 );
5470 for(pIdx=pTab->pIndex;
5471 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
5472 pIdx=pIdx->pNext
5474 if( !pIdx ){
5475 sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
5476 pParse->checkSchema = 1;
5477 return SQLITE_ERROR;
5479 assert( pFrom->fg.isCte==0 );
5480 pFrom->u2.pIBIndex = pIdx;
5481 return SQLITE_OK;
5485 ** Detect compound SELECT statements that use an ORDER BY clause with
5486 ** an alternative collating sequence.
5488 ** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
5490 ** These are rewritten as a subquery:
5492 ** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
5493 ** ORDER BY ... COLLATE ...
5495 ** This transformation is necessary because the multiSelectOrderBy() routine
5496 ** above that generates the code for a compound SELECT with an ORDER BY clause
5497 ** uses a merge algorithm that requires the same collating sequence on the
5498 ** result columns as on the ORDER BY clause. See ticket
5499 ** http://www.sqlite.org/src/info/6709574d2a
5501 ** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
5502 ** The UNION ALL operator works fine with multiSelectOrderBy() even when
5503 ** there are COLLATE terms in the ORDER BY.
5505 static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
5506 int i;
5507 Select *pNew;
5508 Select *pX;
5509 sqlite3 *db;
5510 struct ExprList_item *a;
5511 SrcList *pNewSrc;
5512 Parse *pParse;
5513 Token dummy;
5515 if( p->pPrior==0 ) return WRC_Continue;
5516 if( p->pOrderBy==0 ) return WRC_Continue;
5517 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
5518 if( pX==0 ) return WRC_Continue;
5519 a = p->pOrderBy->a;
5520 #ifndef SQLITE_OMIT_WINDOWFUNC
5521 /* If iOrderByCol is already non-zero, then it has already been matched
5522 ** to a result column of the SELECT statement. This occurs when the
5523 ** SELECT is rewritten for window-functions processing and then passed
5524 ** to sqlite3SelectPrep() and similar a second time. The rewriting done
5525 ** by this function is not required in this case. */
5526 if( a[0].u.x.iOrderByCol ) return WRC_Continue;
5527 #endif
5528 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
5529 if( a[i].pExpr->flags & EP_Collate ) break;
5531 if( i<0 ) return WRC_Continue;
5533 /* If we reach this point, that means the transformation is required. */
5535 pParse = pWalker->pParse;
5536 db = pParse->db;
5537 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
5538 if( pNew==0 ) return WRC_Abort;
5539 memset(&dummy, 0, sizeof(dummy));
5540 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
5541 if( pNewSrc==0 ) return WRC_Abort;
5542 *pNew = *p;
5543 p->pSrc = pNewSrc;
5544 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
5545 p->op = TK_SELECT;
5546 p->pWhere = 0;
5547 pNew->pGroupBy = 0;
5548 pNew->pHaving = 0;
5549 pNew->pOrderBy = 0;
5550 p->pPrior = 0;
5551 p->pNext = 0;
5552 p->pWith = 0;
5553 #ifndef SQLITE_OMIT_WINDOWFUNC
5554 p->pWinDefn = 0;
5555 #endif
5556 p->selFlags &= ~SF_Compound;
5557 assert( (p->selFlags & SF_Converted)==0 );
5558 p->selFlags |= SF_Converted;
5559 assert( pNew->pPrior!=0 );
5560 pNew->pPrior->pNext = pNew;
5561 pNew->pLimit = 0;
5562 return WRC_Continue;
5566 ** Check to see if the FROM clause term pFrom has table-valued function
5567 ** arguments. If it does, leave an error message in pParse and return
5568 ** non-zero, since pFrom is not allowed to be a table-valued function.
5570 static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
5571 if( pFrom->fg.isTabFunc ){
5572 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
5573 return 1;
5575 return 0;
5578 #ifndef SQLITE_OMIT_CTE
5580 ** Argument pWith (which may be NULL) points to a linked list of nested
5581 ** WITH contexts, from inner to outermost. If the table identified by
5582 ** FROM clause element pItem is really a common-table-expression (CTE)
5583 ** then return a pointer to the CTE definition for that table. Otherwise
5584 ** return NULL.
5586 ** If a non-NULL value is returned, set *ppContext to point to the With
5587 ** object that the returned CTE belongs to.
5589 static struct Cte *searchWith(
5590 With *pWith, /* Current innermost WITH clause */
5591 SrcItem *pItem, /* FROM clause element to resolve */
5592 With **ppContext /* OUT: WITH clause return value belongs to */
5594 const char *zName = pItem->zName;
5595 With *p;
5596 assert( pItem->zDatabase==0 );
5597 assert( zName!=0 );
5598 for(p=pWith; p; p=p->pOuter){
5599 int i;
5600 for(i=0; i<p->nCte; i++){
5601 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
5602 *ppContext = p;
5603 return &p->a[i];
5606 if( p->bView ) break;
5608 return 0;
5611 /* The code generator maintains a stack of active WITH clauses
5612 ** with the inner-most WITH clause being at the top of the stack.
5614 ** This routine pushes the WITH clause passed as the second argument
5615 ** onto the top of the stack. If argument bFree is true, then this
5616 ** WITH clause will never be popped from the stack but should instead
5617 ** be freed along with the Parse object. In other cases, when
5618 ** bFree==0, the With object will be freed along with the SELECT
5619 ** statement with which it is associated.
5621 ** This routine returns a copy of pWith. Or, if bFree is true and
5622 ** the pWith object is destroyed immediately due to an OOM condition,
5623 ** then this routine return NULL.
5625 ** If bFree is true, do not continue to use the pWith pointer after
5626 ** calling this routine, Instead, use only the return value.
5628 With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
5629 if( pWith ){
5630 if( bFree ){
5631 pWith = (With*)sqlite3ParserAddCleanup(pParse,
5632 (void(*)(sqlite3*,void*))sqlite3WithDelete,
5633 pWith);
5634 if( pWith==0 ) return 0;
5636 if( pParse->nErr==0 ){
5637 assert( pParse->pWith!=pWith );
5638 pWith->pOuter = pParse->pWith;
5639 pParse->pWith = pWith;
5642 return pWith;
5646 ** This function checks if argument pFrom refers to a CTE declared by
5647 ** a WITH clause on the stack currently maintained by the parser (on the
5648 ** pParse->pWith linked list). And if currently processing a CTE
5649 ** CTE expression, through routine checks to see if the reference is
5650 ** a recursive reference to the CTE.
5652 ** If pFrom matches a CTE according to either of these two above, pFrom->pTab
5653 ** and other fields are populated accordingly.
5655 ** Return 0 if no match is found.
5656 ** Return 1 if a match is found.
5657 ** Return 2 if an error condition is detected.
5659 static int resolveFromTermToCte(
5660 Parse *pParse, /* The parsing context */
5661 Walker *pWalker, /* Current tree walker */
5662 SrcItem *pFrom /* The FROM clause term to check */
5664 Cte *pCte; /* Matched CTE (or NULL if no match) */
5665 With *pWith; /* The matching WITH */
5667 assert( pFrom->pTab==0 );
5668 if( pParse->pWith==0 ){
5669 /* There are no WITH clauses in the stack. No match is possible */
5670 return 0;
5672 if( pParse->nErr ){
5673 /* Prior errors might have left pParse->pWith in a goofy state, so
5674 ** go no further. */
5675 return 0;
5677 if( pFrom->zDatabase!=0 ){
5678 /* The FROM term contains a schema qualifier (ex: main.t1) and so
5679 ** it cannot possibly be a CTE reference. */
5680 return 0;
5682 if( pFrom->fg.notCte ){
5683 /* The FROM term is specifically excluded from matching a CTE.
5684 ** (1) It is part of a trigger that used to have zDatabase but had
5685 ** zDatabase removed by sqlite3FixTriggerStep().
5686 ** (2) This is the first term in the FROM clause of an UPDATE.
5688 return 0;
5690 pCte = searchWith(pParse->pWith, pFrom, &pWith);
5691 if( pCte ){
5692 sqlite3 *db = pParse->db;
5693 Table *pTab;
5694 ExprList *pEList;
5695 Select *pSel;
5696 Select *pLeft; /* Left-most SELECT statement */
5697 Select *pRecTerm; /* Left-most recursive term */
5698 int bMayRecursive; /* True if compound joined by UNION [ALL] */
5699 With *pSavedWith; /* Initial value of pParse->pWith */
5700 int iRecTab = -1; /* Cursor for recursive table */
5701 CteUse *pCteUse;
5703 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
5704 ** recursive reference to CTE pCte. Leave an error in pParse and return
5705 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
5706 ** In this case, proceed. */
5707 if( pCte->zCteErr ){
5708 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
5709 return 2;
5711 if( cannotBeFunction(pParse, pFrom) ) return 2;
5713 assert( pFrom->pTab==0 );
5714 pTab = sqlite3DbMallocZero(db, sizeof(Table));
5715 if( pTab==0 ) return 2;
5716 pCteUse = pCte->pUse;
5717 if( pCteUse==0 ){
5718 pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
5719 if( pCteUse==0
5720 || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
5722 sqlite3DbFree(db, pTab);
5723 return 2;
5725 pCteUse->eM10d = pCte->eM10d;
5727 pFrom->pTab = pTab;
5728 pTab->nTabRef = 1;
5729 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
5730 pTab->iPKey = -1;
5731 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5732 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5733 pFrom->pSelect = sqlite3SelectDup(db, pCte->pSelect, 0);
5734 if( db->mallocFailed ) return 2;
5735 pFrom->pSelect->selFlags |= SF_CopyCte;
5736 assert( pFrom->pSelect );
5737 if( pFrom->fg.isIndexedBy ){
5738 sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
5739 return 2;
5741 pFrom->fg.isCte = 1;
5742 pFrom->u2.pCteUse = pCteUse;
5743 pCteUse->nUse++;
5745 /* Check if this is a recursive CTE. */
5746 pRecTerm = pSel = pFrom->pSelect;
5747 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
5748 while( bMayRecursive && pRecTerm->op==pSel->op ){
5749 int i;
5750 SrcList *pSrc = pRecTerm->pSrc;
5751 assert( pRecTerm->pPrior!=0 );
5752 for(i=0; i<pSrc->nSrc; i++){
5753 SrcItem *pItem = &pSrc->a[i];
5754 if( pItem->zDatabase==0
5755 && pItem->zName!=0
5756 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
5758 pItem->pTab = pTab;
5759 pTab->nTabRef++;
5760 pItem->fg.isRecursive = 1;
5761 if( pRecTerm->selFlags & SF_Recursive ){
5762 sqlite3ErrorMsg(pParse,
5763 "multiple references to recursive table: %s", pCte->zName
5765 return 2;
5767 pRecTerm->selFlags |= SF_Recursive;
5768 if( iRecTab<0 ) iRecTab = pParse->nTab++;
5769 pItem->iCursor = iRecTab;
5772 if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
5773 pRecTerm = pRecTerm->pPrior;
5776 pCte->zCteErr = "circular reference: %s";
5777 pSavedWith = pParse->pWith;
5778 pParse->pWith = pWith;
5779 if( pSel->selFlags & SF_Recursive ){
5780 int rc;
5781 assert( pRecTerm!=0 );
5782 assert( (pRecTerm->selFlags & SF_Recursive)==0 );
5783 assert( pRecTerm->pNext!=0 );
5784 assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
5785 assert( pRecTerm->pWith==0 );
5786 pRecTerm->pWith = pSel->pWith;
5787 rc = sqlite3WalkSelect(pWalker, pRecTerm);
5788 pRecTerm->pWith = 0;
5789 if( rc ){
5790 pParse->pWith = pSavedWith;
5791 return 2;
5793 }else{
5794 if( sqlite3WalkSelect(pWalker, pSel) ){
5795 pParse->pWith = pSavedWith;
5796 return 2;
5799 pParse->pWith = pWith;
5801 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
5802 pEList = pLeft->pEList;
5803 if( pCte->pCols ){
5804 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
5805 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
5806 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
5808 pParse->pWith = pSavedWith;
5809 return 2;
5811 pEList = pCte->pCols;
5814 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
5815 if( bMayRecursive ){
5816 if( pSel->selFlags & SF_Recursive ){
5817 pCte->zCteErr = "multiple recursive references: %s";
5818 }else{
5819 pCte->zCteErr = "recursive reference in a subquery: %s";
5821 sqlite3WalkSelect(pWalker, pSel);
5823 pCte->zCteErr = 0;
5824 pParse->pWith = pSavedWith;
5825 return 1; /* Success */
5827 return 0; /* No match */
5829 #endif
5831 #ifndef SQLITE_OMIT_CTE
5833 ** If the SELECT passed as the second argument has an associated WITH
5834 ** clause, pop it from the stack stored as part of the Parse object.
5836 ** This function is used as the xSelectCallback2() callback by
5837 ** sqlite3SelectExpand() when walking a SELECT tree to resolve table
5838 ** names and other FROM clause elements.
5840 void sqlite3SelectPopWith(Walker *pWalker, Select *p){
5841 Parse *pParse = pWalker->pParse;
5842 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
5843 With *pWith = findRightmost(p)->pWith;
5844 if( pWith!=0 ){
5845 assert( pParse->pWith==pWith || pParse->nErr );
5846 pParse->pWith = pWith->pOuter;
5850 #endif
5853 ** The SrcItem structure passed as the second argument represents a
5854 ** sub-query in the FROM clause of a SELECT statement. This function
5855 ** allocates and populates the SrcItem.pTab object. If successful,
5856 ** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
5857 ** SQLITE_NOMEM.
5859 int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
5860 Select *pSel = pFrom->pSelect;
5861 Table *pTab;
5863 assert( pSel );
5864 pFrom->pTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
5865 if( pTab==0 ) return SQLITE_NOMEM;
5866 pTab->nTabRef = 1;
5867 if( pFrom->zAlias ){
5868 pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
5869 }else{
5870 pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
5872 while( pSel->pPrior ){ pSel = pSel->pPrior; }
5873 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
5874 pTab->iPKey = -1;
5875 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5876 #ifndef SQLITE_ALLOW_ROWID_IN_VIEW
5877 /* The usual case - do not allow ROWID on a subquery */
5878 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5879 #else
5880 pTab->tabFlags |= TF_Ephemeral; /* Legacy compatibility mode */
5881 #endif
5882 return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
5887 ** Check the N SrcItem objects to the right of pBase. (N might be zero!)
5888 ** If any of those SrcItem objects have a USING clause containing zName
5889 ** then return true.
5891 ** If N is zero, or none of the N SrcItem objects to the right of pBase
5892 ** contains a USING clause, or if none of the USING clauses contain zName,
5893 ** then return false.
5895 static int inAnyUsingClause(
5896 const char *zName, /* Name we are looking for */
5897 SrcItem *pBase, /* The base SrcItem. Looking at pBase[1] and following */
5898 int N /* How many SrcItems to check */
5900 while( N>0 ){
5901 N--;
5902 pBase++;
5903 if( pBase->fg.isUsing==0 ) continue;
5904 if( NEVER(pBase->u3.pUsing==0) ) continue;
5905 if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
5907 return 0;
5912 ** This routine is a Walker callback for "expanding" a SELECT statement.
5913 ** "Expanding" means to do the following:
5915 ** (1) Make sure VDBE cursor numbers have been assigned to every
5916 ** element of the FROM clause.
5918 ** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
5919 ** defines FROM clause. When views appear in the FROM clause,
5920 ** fill pTabList->a[].pSelect with a copy of the SELECT statement
5921 ** that implements the view. A copy is made of the view's SELECT
5922 ** statement so that we can freely modify or delete that statement
5923 ** without worrying about messing up the persistent representation
5924 ** of the view.
5926 ** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
5927 ** on joins and the ON and USING clause of joins.
5929 ** (4) Scan the list of columns in the result set (pEList) looking
5930 ** for instances of the "*" operator or the TABLE.* operator.
5931 ** If found, expand each "*" to be every column in every table
5932 ** and TABLE.* to be every column in TABLE.
5935 static int selectExpander(Walker *pWalker, Select *p){
5936 Parse *pParse = pWalker->pParse;
5937 int i, j, k, rc;
5938 SrcList *pTabList;
5939 ExprList *pEList;
5940 SrcItem *pFrom;
5941 sqlite3 *db = pParse->db;
5942 Expr *pE, *pRight, *pExpr;
5943 u16 selFlags = p->selFlags;
5944 u32 elistFlags = 0;
5946 p->selFlags |= SF_Expanded;
5947 if( db->mallocFailed ){
5948 return WRC_Abort;
5950 assert( p->pSrc!=0 );
5951 if( (selFlags & SF_Expanded)!=0 ){
5952 return WRC_Prune;
5954 if( pWalker->eCode ){
5955 /* Renumber selId because it has been copied from a view */
5956 p->selId = ++pParse->nSelect;
5958 pTabList = p->pSrc;
5959 pEList = p->pEList;
5960 if( pParse->pWith && (p->selFlags & SF_View) ){
5961 if( p->pWith==0 ){
5962 p->pWith = (With*)sqlite3DbMallocZero(db, sizeof(With));
5963 if( p->pWith==0 ){
5964 return WRC_Abort;
5967 p->pWith->bView = 1;
5969 sqlite3WithPush(pParse, p->pWith, 0);
5971 /* Make sure cursor numbers have been assigned to all entries in
5972 ** the FROM clause of the SELECT statement.
5974 sqlite3SrcListAssignCursors(pParse, pTabList);
5976 /* Look up every table named in the FROM clause of the select. If
5977 ** an entry of the FROM clause is a subquery instead of a table or view,
5978 ** then create a transient table structure to describe the subquery.
5980 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
5981 Table *pTab;
5982 assert( pFrom->fg.isRecursive==0 || pFrom->pTab!=0 );
5983 if( pFrom->pTab ) continue;
5984 assert( pFrom->fg.isRecursive==0 );
5985 if( pFrom->zName==0 ){
5986 #ifndef SQLITE_OMIT_SUBQUERY
5987 Select *pSel = pFrom->pSelect;
5988 /* A sub-query in the FROM clause of a SELECT */
5989 assert( pSel!=0 );
5990 assert( pFrom->pTab==0 );
5991 if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
5992 if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
5993 #endif
5994 #ifndef SQLITE_OMIT_CTE
5995 }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
5996 if( rc>1 ) return WRC_Abort;
5997 pTab = pFrom->pTab;
5998 assert( pTab!=0 );
5999 #endif
6000 }else{
6001 /* An ordinary table or view name in the FROM clause */
6002 assert( pFrom->pTab==0 );
6003 pFrom->pTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
6004 if( pTab==0 ) return WRC_Abort;
6005 if( pTab->nTabRef>=0xffff ){
6006 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
6007 pTab->zName);
6008 pFrom->pTab = 0;
6009 return WRC_Abort;
6011 pTab->nTabRef++;
6012 if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
6013 return WRC_Abort;
6015 #if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
6016 if( !IsOrdinaryTable(pTab) ){
6017 i16 nCol;
6018 u8 eCodeOrig = pWalker->eCode;
6019 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
6020 assert( pFrom->pSelect==0 );
6021 if( IsView(pTab) ){
6022 if( (db->flags & SQLITE_EnableView)==0
6023 && pTab->pSchema!=db->aDb[1].pSchema
6025 sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
6026 pTab->zName);
6028 pFrom->pSelect = sqlite3SelectDup(db, pTab->u.view.pSelect, 0);
6030 #ifndef SQLITE_OMIT_VIRTUALTABLE
6031 else if( ALWAYS(IsVirtual(pTab))
6032 && pFrom->fg.fromDDL
6033 && ALWAYS(pTab->u.vtab.p!=0)
6034 && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
6036 sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
6037 pTab->zName);
6039 assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
6040 #endif
6041 nCol = pTab->nCol;
6042 pTab->nCol = -1;
6043 pWalker->eCode = 1; /* Turn on Select.selId renumbering */
6044 sqlite3WalkSelect(pWalker, pFrom->pSelect);
6045 pWalker->eCode = eCodeOrig;
6046 pTab->nCol = nCol;
6048 #endif
6051 /* Locate the index named by the INDEXED BY clause, if any. */
6052 if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
6053 return WRC_Abort;
6057 /* Process NATURAL keywords, and ON and USING clauses of joins.
6059 assert( db->mallocFailed==0 || pParse->nErr!=0 );
6060 if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
6061 return WRC_Abort;
6064 /* For every "*" that occurs in the column list, insert the names of
6065 ** all columns in all tables. And for every TABLE.* insert the names
6066 ** of all columns in TABLE. The parser inserted a special expression
6067 ** with the TK_ASTERISK operator for each "*" that it found in the column
6068 ** list. The following code just has to locate the TK_ASTERISK
6069 ** expressions and expand each one to the list of all columns in
6070 ** all tables.
6072 ** The first loop just checks to see if there are any "*" operators
6073 ** that need expanding.
6075 for(k=0; k<pEList->nExpr; k++){
6076 pE = pEList->a[k].pExpr;
6077 if( pE->op==TK_ASTERISK ) break;
6078 assert( pE->op!=TK_DOT || pE->pRight!=0 );
6079 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
6080 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
6081 elistFlags |= pE->flags;
6083 if( k<pEList->nExpr ){
6085 ** If we get here it means the result set contains one or more "*"
6086 ** operators that need to be expanded. Loop through each expression
6087 ** in the result set and expand them one by one.
6089 struct ExprList_item *a = pEList->a;
6090 ExprList *pNew = 0;
6091 int flags = pParse->db->flags;
6092 int longNames = (flags & SQLITE_FullColNames)!=0
6093 && (flags & SQLITE_ShortColNames)==0;
6095 for(k=0; k<pEList->nExpr; k++){
6096 pE = a[k].pExpr;
6097 elistFlags |= pE->flags;
6098 pRight = pE->pRight;
6099 assert( pE->op!=TK_DOT || pRight!=0 );
6100 if( pE->op!=TK_ASTERISK
6101 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
6103 /* This particular expression does not need to be expanded.
6105 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
6106 if( pNew ){
6107 pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
6108 pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
6109 a[k].zEName = 0;
6111 a[k].pExpr = 0;
6112 }else{
6113 /* This expression is a "*" or a "TABLE.*" and needs to be
6114 ** expanded. */
6115 int tableSeen = 0; /* Set to 1 when TABLE matches */
6116 char *zTName = 0; /* text of name of TABLE */
6117 int iErrOfst;
6118 if( pE->op==TK_DOT ){
6119 assert( (selFlags & SF_NestedFrom)==0 );
6120 assert( pE->pLeft!=0 );
6121 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
6122 zTName = pE->pLeft->u.zToken;
6123 assert( ExprUseWOfst(pE->pLeft) );
6124 iErrOfst = pE->pRight->w.iOfst;
6125 }else{
6126 assert( ExprUseWOfst(pE) );
6127 iErrOfst = pE->w.iOfst;
6129 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6130 int nAdd; /* Number of cols including rowid */
6131 Table *pTab = pFrom->pTab; /* Table for this data source */
6132 ExprList *pNestedFrom; /* Result-set of a nested FROM clause */
6133 char *zTabName; /* AS name for this data source */
6134 const char *zSchemaName = 0; /* Schema name for this data source */
6135 int iDb; /* Schema index for this data src */
6136 IdList *pUsing; /* USING clause for pFrom[1] */
6138 if( (zTabName = pFrom->zAlias)==0 ){
6139 zTabName = pTab->zName;
6141 if( db->mallocFailed ) break;
6142 assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom->pSelect) );
6143 if( pFrom->fg.isNestedFrom ){
6144 assert( pFrom->pSelect!=0 );
6145 pNestedFrom = pFrom->pSelect->pEList;
6146 assert( pNestedFrom!=0 );
6147 assert( pNestedFrom->nExpr==pTab->nCol );
6148 assert( VisibleRowid(pTab)==0 );
6149 }else{
6150 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
6151 continue;
6153 pNestedFrom = 0;
6154 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6155 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
6157 if( i+1<pTabList->nSrc
6158 && pFrom[1].fg.isUsing
6159 && (selFlags & SF_NestedFrom)!=0
6161 int ii;
6162 pUsing = pFrom[1].u3.pUsing;
6163 for(ii=0; ii<pUsing->nId; ii++){
6164 const char *zUName = pUsing->a[ii].zName;
6165 pRight = sqlite3Expr(db, TK_ID, zUName);
6166 sqlite3ExprSetErrorOffset(pRight, iErrOfst);
6167 pNew = sqlite3ExprListAppend(pParse, pNew, pRight);
6168 if( pNew ){
6169 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
6170 assert( pX->zEName==0 );
6171 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
6172 pX->fg.eEName = ENAME_TAB;
6173 pX->fg.bUsingTerm = 1;
6176 }else{
6177 pUsing = 0;
6180 nAdd = pTab->nCol + (VisibleRowid(pTab) && (selFlags&SF_NestedFrom));
6181 for(j=0; j<nAdd; j++){
6182 const char *zName;
6183 struct ExprList_item *pX; /* Newly added ExprList term */
6185 if( j==pTab->nCol ){
6186 zName = sqlite3RowidAlias(pTab);
6187 if( zName==0 ) continue;
6188 }else{
6189 zName = pTab->aCol[j].zCnName;
6191 /* If pTab is actually an SF_NestedFrom sub-select, do not
6192 ** expand any ENAME_ROWID columns. */
6193 if( pNestedFrom && pNestedFrom->a[j].fg.eEName==ENAME_ROWID ){
6194 continue;
6197 if( zTName
6198 && pNestedFrom
6199 && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0, 0)==0
6201 continue;
6204 /* If a column is marked as 'hidden', omit it from the expanded
6205 ** result-set list unless the SELECT has the SF_IncludeHidden
6206 ** bit set.
6208 if( (p->selFlags & SF_IncludeHidden)==0
6209 && IsHiddenColumn(&pTab->aCol[j])
6211 continue;
6213 if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
6214 && zTName==0
6215 && (selFlags & (SF_NestedFrom))==0
6217 continue;
6220 assert( zName );
6221 tableSeen = 1;
6223 if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
6224 if( pFrom->fg.isUsing
6225 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
6227 /* In a join with a USING clause, omit columns in the
6228 ** using clause from the table on the right. */
6229 continue;
6232 pRight = sqlite3Expr(db, TK_ID, zName);
6233 if( (pTabList->nSrc>1
6234 && ( (pFrom->fg.jointype & JT_LTORJ)==0
6235 || (selFlags & SF_NestedFrom)!=0
6236 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
6239 || IN_RENAME_OBJECT
6241 Expr *pLeft;
6242 pLeft = sqlite3Expr(db, TK_ID, zTabName);
6243 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
6244 if( IN_RENAME_OBJECT && pE->pLeft ){
6245 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
6247 if( zSchemaName ){
6248 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
6249 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
6251 }else{
6252 pExpr = pRight;
6254 sqlite3ExprSetErrorOffset(pExpr, iErrOfst);
6255 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
6256 if( pNew==0 ){
6257 break; /* OOM */
6259 pX = &pNew->a[pNew->nExpr-1];
6260 assert( pX->zEName==0 );
6261 if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
6262 if( pNestedFrom ){
6263 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
6264 testcase( pX->zEName==0 );
6265 }else{
6266 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
6267 zSchemaName, zTabName, zName);
6268 testcase( pX->zEName==0 );
6270 pX->fg.eEName = (j==pTab->nCol ? ENAME_ROWID : ENAME_TAB);
6271 if( (pFrom->fg.isUsing
6272 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
6273 || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
6274 || (j<pTab->nCol && (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND))
6276 pX->fg.bNoExpand = 1;
6278 }else if( longNames ){
6279 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
6280 pX->fg.eEName = ENAME_NAME;
6281 }else{
6282 pX->zEName = sqlite3DbStrDup(db, zName);
6283 pX->fg.eEName = ENAME_NAME;
6287 if( !tableSeen ){
6288 if( zTName ){
6289 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
6290 }else{
6291 sqlite3ErrorMsg(pParse, "no tables specified");
6296 sqlite3ExprListDelete(db, pEList);
6297 p->pEList = pNew;
6299 if( p->pEList ){
6300 if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
6301 sqlite3ErrorMsg(pParse, "too many columns in result set");
6302 return WRC_Abort;
6304 if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
6305 p->selFlags |= SF_ComplexResult;
6308 #if TREETRACE_ENABLED
6309 if( sqlite3TreeTrace & 0x8 ){
6310 TREETRACE(0x8,pParse,p,("After result-set wildcard expansion:\n"));
6311 sqlite3TreeViewSelect(0, p, 0);
6313 #endif
6314 return WRC_Continue;
6317 #if SQLITE_DEBUG
6319 ** Always assert. This xSelectCallback2 implementation proves that the
6320 ** xSelectCallback2 is never invoked.
6322 void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
6323 UNUSED_PARAMETER2(NotUsed, NotUsed2);
6324 assert( 0 );
6326 #endif
6328 ** This routine "expands" a SELECT statement and all of its subqueries.
6329 ** For additional information on what it means to "expand" a SELECT
6330 ** statement, see the comment on the selectExpand worker callback above.
6332 ** Expanding a SELECT statement is the first step in processing a
6333 ** SELECT statement. The SELECT statement must be expanded before
6334 ** name resolution is performed.
6336 ** If anything goes wrong, an error message is written into pParse.
6337 ** The calling function can detect the problem by looking at pParse->nErr
6338 ** and/or pParse->db->mallocFailed.
6340 static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
6341 Walker w;
6342 w.xExprCallback = sqlite3ExprWalkNoop;
6343 w.pParse = pParse;
6344 if( OK_IF_ALWAYS_TRUE(pParse->hasCompound) ){
6345 w.xSelectCallback = convertCompoundSelectToSubquery;
6346 w.xSelectCallback2 = 0;
6347 sqlite3WalkSelect(&w, pSelect);
6349 w.xSelectCallback = selectExpander;
6350 w.xSelectCallback2 = sqlite3SelectPopWith;
6351 w.eCode = 0;
6352 sqlite3WalkSelect(&w, pSelect);
6356 #ifndef SQLITE_OMIT_SUBQUERY
6358 ** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
6359 ** interface.
6361 ** For each FROM-clause subquery, add Column.zType, Column.zColl, and
6362 ** Column.affinity information to the Table structure that represents
6363 ** the result set of that subquery.
6365 ** The Table structure that represents the result set was constructed
6366 ** by selectExpander() but the type and collation and affinity information
6367 ** was omitted at that point because identifiers had not yet been resolved.
6368 ** This routine is called after identifier resolution.
6370 static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
6371 Parse *pParse;
6372 int i;
6373 SrcList *pTabList;
6374 SrcItem *pFrom;
6376 if( p->selFlags & SF_HasTypeInfo ) return;
6377 p->selFlags |= SF_HasTypeInfo;
6378 pParse = pWalker->pParse;
6379 testcase( (p->selFlags & SF_Resolved)==0 );
6380 assert( (p->selFlags & SF_Resolved) || IN_RENAME_OBJECT );
6381 pTabList = p->pSrc;
6382 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6383 Table *pTab = pFrom->pTab;
6384 assert( pTab!=0 );
6385 if( (pTab->tabFlags & TF_Ephemeral)!=0 ){
6386 /* A sub-query in the FROM clause of a SELECT */
6387 Select *pSel = pFrom->pSelect;
6388 if( pSel ){
6389 sqlite3SubqueryColumnTypes(pParse, pTab, pSel, SQLITE_AFF_NONE);
6394 #endif
6398 ** This routine adds datatype and collating sequence information to
6399 ** the Table structures of all FROM-clause subqueries in a
6400 ** SELECT statement.
6402 ** Use this routine after name resolution.
6404 static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
6405 #ifndef SQLITE_OMIT_SUBQUERY
6406 Walker w;
6407 w.xSelectCallback = sqlite3SelectWalkNoop;
6408 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
6409 w.xExprCallback = sqlite3ExprWalkNoop;
6410 w.pParse = pParse;
6411 sqlite3WalkSelect(&w, pSelect);
6412 #endif
6417 ** This routine sets up a SELECT statement for processing. The
6418 ** following is accomplished:
6420 ** * VDBE Cursor numbers are assigned to all FROM-clause terms.
6421 ** * Ephemeral Table objects are created for all FROM-clause subqueries.
6422 ** * ON and USING clauses are shifted into WHERE statements
6423 ** * Wildcards "*" and "TABLE.*" in result sets are expanded.
6424 ** * Identifiers in expression are matched to tables.
6426 ** This routine acts recursively on all subqueries within the SELECT.
6428 void sqlite3SelectPrep(
6429 Parse *pParse, /* The parser context */
6430 Select *p, /* The SELECT statement being coded. */
6431 NameContext *pOuterNC /* Name context for container */
6433 assert( p!=0 || pParse->db->mallocFailed );
6434 assert( pParse->db->pParse==pParse );
6435 if( pParse->db->mallocFailed ) return;
6436 if( p->selFlags & SF_HasTypeInfo ) return;
6437 sqlite3SelectExpand(pParse, p);
6438 if( pParse->nErr ) return;
6439 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
6440 if( pParse->nErr ) return;
6441 sqlite3SelectAddTypeInfo(pParse, p);
6444 #if TREETRACE_ENABLED
6446 ** Display all information about an AggInfo object
6448 static void printAggInfo(AggInfo *pAggInfo){
6449 int ii;
6450 for(ii=0; ii<pAggInfo->nColumn; ii++){
6451 struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
6452 sqlite3DebugPrintf(
6453 "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
6454 " iSorterColumn=%d %s\n",
6455 ii, pCol->pTab ? pCol->pTab->zName : "NULL",
6456 pCol->iTable, pCol->iColumn, pAggInfo->iFirstReg+ii,
6457 pCol->iSorterColumn,
6458 ii>=pAggInfo->nAccumulator ? "" : " Accumulator");
6459 sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
6461 for(ii=0; ii<pAggInfo->nFunc; ii++){
6462 sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
6463 ii, pAggInfo->iFirstReg+pAggInfo->nColumn+ii);
6464 sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
6467 #endif /* TREETRACE_ENABLED */
6470 ** Analyze the arguments to aggregate functions. Create new pAggInfo->aCol[]
6471 ** entries for columns that are arguments to aggregate functions but which
6472 ** are not otherwise used.
6474 ** The aCol[] entries in AggInfo prior to nAccumulator are columns that
6475 ** are referenced outside of aggregate functions. These might be columns
6476 ** that are part of the GROUP by clause, for example. Other database engines
6477 ** would throw an error if there is a column reference that is not in the
6478 ** GROUP BY clause and that is not part of an aggregate function argument.
6479 ** But SQLite allows this.
6481 ** The aCol[] entries beginning with the aCol[nAccumulator] and following
6482 ** are column references that are used exclusively as arguments to
6483 ** aggregate functions. This routine is responsible for computing
6484 ** (or recomputing) those aCol[] entries.
6486 static void analyzeAggFuncArgs(
6487 AggInfo *pAggInfo,
6488 NameContext *pNC
6490 int i;
6491 assert( pAggInfo!=0 );
6492 assert( pAggInfo->iFirstReg==0 );
6493 pNC->ncFlags |= NC_InAggFunc;
6494 for(i=0; i<pAggInfo->nFunc; i++){
6495 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
6496 assert( pExpr->op==TK_FUNCTION || pExpr->op==TK_AGG_FUNCTION );
6497 assert( ExprUseXList(pExpr) );
6498 sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
6499 if( pExpr->pLeft ){
6500 assert( pExpr->pLeft->op==TK_ORDER );
6501 assert( ExprUseXList(pExpr->pLeft) );
6502 sqlite3ExprAnalyzeAggList(pNC, pExpr->pLeft->x.pList);
6504 #ifndef SQLITE_OMIT_WINDOWFUNC
6505 assert( !IsWindowFunc(pExpr) );
6506 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6507 sqlite3ExprAnalyzeAggregates(pNC, pExpr->y.pWin->pFilter);
6509 #endif
6511 pNC->ncFlags &= ~NC_InAggFunc;
6515 ** An index on expressions is being used in the inner loop of an
6516 ** aggregate query with a GROUP BY clause. This routine attempts
6517 ** to adjust the AggInfo object to take advantage of index and to
6518 ** perhaps use the index as a covering index.
6521 static void optimizeAggregateUseOfIndexedExpr(
6522 Parse *pParse, /* Parsing context */
6523 Select *pSelect, /* The SELECT statement being processed */
6524 AggInfo *pAggInfo, /* The aggregate info */
6525 NameContext *pNC /* Name context used to resolve agg-func args */
6527 assert( pAggInfo->iFirstReg==0 );
6528 assert( pSelect!=0 );
6529 assert( pSelect->pGroupBy!=0 );
6530 pAggInfo->nColumn = pAggInfo->nAccumulator;
6531 if( ALWAYS(pAggInfo->nSortingColumn>0) ){
6532 int mx = pSelect->pGroupBy->nExpr - 1;
6533 int j, k;
6534 for(j=0; j<pAggInfo->nColumn; j++){
6535 k = pAggInfo->aCol[j].iSorterColumn;
6536 if( k>mx ) mx = k;
6538 pAggInfo->nSortingColumn = mx+1;
6540 analyzeAggFuncArgs(pAggInfo, pNC);
6541 #if TREETRACE_ENABLED
6542 if( sqlite3TreeTrace & 0x20 ){
6543 IndexedExpr *pIEpr;
6544 TREETRACE(0x20, pParse, pSelect,
6545 ("AggInfo (possibly) adjusted for Indexed Exprs\n"));
6546 sqlite3TreeViewSelect(0, pSelect, 0);
6547 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6548 printf("data-cursor=%d index={%d,%d}\n",
6549 pIEpr->iDataCur, pIEpr->iIdxCur, pIEpr->iIdxCol);
6550 sqlite3TreeViewExpr(0, pIEpr->pExpr, 0);
6552 printAggInfo(pAggInfo);
6554 #else
6555 UNUSED_PARAMETER(pSelect);
6556 UNUSED_PARAMETER(pParse);
6557 #endif
6561 ** Walker callback for aggregateConvertIndexedExprRefToColumn().
6563 static int aggregateIdxEprRefToColCallback(Walker *pWalker, Expr *pExpr){
6564 AggInfo *pAggInfo;
6565 struct AggInfo_col *pCol;
6566 UNUSED_PARAMETER(pWalker);
6567 if( pExpr->pAggInfo==0 ) return WRC_Continue;
6568 if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
6569 if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
6570 if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
6571 pAggInfo = pExpr->pAggInfo;
6572 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
6573 assert( pExpr->iAgg>=0 );
6574 pCol = &pAggInfo->aCol[pExpr->iAgg];
6575 pExpr->op = TK_AGG_COLUMN;
6576 pExpr->iTable = pCol->iTable;
6577 pExpr->iColumn = pCol->iColumn;
6578 ExprClearProperty(pExpr, EP_Skip|EP_Collate|EP_Unlikely);
6579 return WRC_Prune;
6583 ** Convert every pAggInfo->aFunc[].pExpr such that any node within
6584 ** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
6585 ** opcode.
6587 static void aggregateConvertIndexedExprRefToColumn(AggInfo *pAggInfo){
6588 int i;
6589 Walker w;
6590 memset(&w, 0, sizeof(w));
6591 w.xExprCallback = aggregateIdxEprRefToColCallback;
6592 for(i=0; i<pAggInfo->nFunc; i++){
6593 sqlite3WalkExpr(&w, pAggInfo->aFunc[i].pFExpr);
6599 ** Allocate a block of registers so that there is one register for each
6600 ** pAggInfo->aCol[] and pAggInfo->aFunc[] entry in pAggInfo. The first
6601 ** register in this block is stored in pAggInfo->iFirstReg.
6603 ** This routine may only be called once for each AggInfo object. Prior
6604 ** to calling this routine:
6606 ** * The aCol[] and aFunc[] arrays may be modified
6607 ** * The AggInfoColumnReg() and AggInfoFuncReg() macros may not be used
6609 ** After calling this routine:
6611 ** * The aCol[] and aFunc[] arrays are fixed
6612 ** * The AggInfoColumnReg() and AggInfoFuncReg() macros may be used
6615 static void assignAggregateRegisters(Parse *pParse, AggInfo *pAggInfo){
6616 assert( pAggInfo!=0 );
6617 assert( pAggInfo->iFirstReg==0 );
6618 pAggInfo->iFirstReg = pParse->nMem + 1;
6619 pParse->nMem += pAggInfo->nColumn + pAggInfo->nFunc;
6623 ** Reset the aggregate accumulator.
6625 ** The aggregate accumulator is a set of memory cells that hold
6626 ** intermediate results while calculating an aggregate. This
6627 ** routine generates code that stores NULLs in all of those memory
6628 ** cells.
6630 static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
6631 Vdbe *v = pParse->pVdbe;
6632 int i;
6633 struct AggInfo_func *pFunc;
6634 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
6635 assert( pAggInfo->iFirstReg>0 );
6636 assert( pParse->db->pParse==pParse );
6637 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
6638 if( nReg==0 ) return;
6639 if( pParse->nErr ) return;
6640 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
6641 pAggInfo->iFirstReg+nReg-1);
6642 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
6643 if( pFunc->iDistinct>=0 ){
6644 Expr *pE = pFunc->pFExpr;
6645 assert( ExprUseXList(pE) );
6646 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
6647 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
6648 "argument");
6649 pFunc->iDistinct = -1;
6650 }else{
6651 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
6652 pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6653 pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
6654 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
6655 pFunc->pFunc->zName));
6658 if( pFunc->iOBTab>=0 ){
6659 ExprList *pOBList;
6660 KeyInfo *pKeyInfo;
6661 int nExtra = 0;
6662 assert( pFunc->pFExpr->pLeft!=0 );
6663 assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
6664 assert( ExprUseXList(pFunc->pFExpr->pLeft) );
6665 pOBList = pFunc->pFExpr->pLeft->x.pList;
6666 if( !pFunc->bOBUnique ){
6667 nExtra++; /* One extra column for the OP_Sequence */
6669 if( pFunc->bOBPayload ){
6670 /* extra columns for the function arguments */
6671 assert( ExprUseXList(pFunc->pFExpr) );
6672 nExtra += pFunc->pFExpr->x.pList->nExpr;
6674 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOBList, 0, nExtra);
6675 if( !pFunc->bOBUnique && pParse->nErr==0 ){
6676 pKeyInfo->nKeyField++;
6678 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6679 pFunc->iOBTab, pOBList->nExpr+nExtra, 0,
6680 (char*)pKeyInfo, P4_KEYINFO);
6681 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(ORDER BY)",
6682 pFunc->pFunc->zName));
6688 ** Invoke the OP_AggFinalize opcode for every aggregate function
6689 ** in the AggInfo structure.
6691 static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
6692 Vdbe *v = pParse->pVdbe;
6693 int i;
6694 struct AggInfo_func *pF;
6695 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6696 ExprList *pList;
6697 assert( ExprUseXList(pF->pFExpr) );
6698 pList = pF->pFExpr->x.pList;
6699 if( pF->iOBTab>=0 ){
6700 /* For an ORDER BY aggregate, calls to OP_AggStep where deferred and
6701 ** all content was stored in emphermal table pF->iOBTab. Extract that
6702 ** content now (in ORDER BY order) and make all calls to OP_AggStep
6703 ** before doing the OP_AggFinal call. */
6704 int iTop; /* Start of loop for extracting columns */
6705 int nArg; /* Number of columns to extract */
6706 int nKey; /* Key columns to be skipped */
6707 int regAgg; /* Extract into this array */
6708 int j; /* Loop counter */
6710 nArg = pList->nExpr;
6711 regAgg = sqlite3GetTempRange(pParse, nArg);
6713 if( pF->bOBPayload==0 ){
6714 nKey = 0;
6715 }else{
6716 assert( pF->pFExpr->pLeft!=0 );
6717 assert( ExprUseXList(pF->pFExpr->pLeft) );
6718 assert( pF->pFExpr->pLeft->x.pList!=0 );
6719 nKey = pF->pFExpr->pLeft->x.pList->nExpr;
6720 if( ALWAYS(!pF->bOBUnique) ) nKey++;
6722 iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
6723 for(j=nArg-1; j>=0; j--){
6724 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
6726 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
6727 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6728 sqlite3VdbeChangeP5(v, (u8)nArg);
6729 sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
6730 sqlite3VdbeJumpHere(v, iTop);
6731 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6733 sqlite3VdbeAddOp2(v, OP_AggFinal, AggInfoFuncReg(pAggInfo,i),
6734 pList ? pList->nExpr : 0);
6735 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6740 ** Generate code that will update the accumulator memory cells for an
6741 ** aggregate based on the current cursor position.
6743 ** If regAcc is non-zero and there are no min() or max() aggregates
6744 ** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
6745 ** registers if register regAcc contains 0. The caller will take care
6746 ** of setting and clearing regAcc.
6748 ** For an ORDER BY aggregate, the actual accumulator memory cell update
6749 ** is deferred until after all input rows have been received, so that they
6750 ** can be run in the requested order. In that case, instead of invoking
6751 ** OP_AggStep to update the accumulator, just add the arguments that would
6752 ** have been passed into OP_AggStep into the sorting ephemeral table
6753 ** (along with the appropriate sort key).
6755 static void updateAccumulator(
6756 Parse *pParse,
6757 int regAcc,
6758 AggInfo *pAggInfo,
6759 int eDistinctType
6761 Vdbe *v = pParse->pVdbe;
6762 int i;
6763 int regHit = 0;
6764 int addrHitTest = 0;
6765 struct AggInfo_func *pF;
6766 struct AggInfo_col *pC;
6768 assert( pAggInfo->iFirstReg>0 );
6769 if( pParse->nErr ) return;
6770 pAggInfo->directMode = 1;
6771 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
6772 int nArg;
6773 int addrNext = 0;
6774 int regAgg;
6775 int regAggSz = 0;
6776 int regDistinct = 0;
6777 ExprList *pList;
6778 assert( ExprUseXList(pF->pFExpr) );
6779 assert( !IsWindowFunc(pF->pFExpr) );
6780 pList = pF->pFExpr->x.pList;
6781 if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
6782 Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
6783 if( pAggInfo->nAccumulator
6784 && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
6785 && regAcc
6787 /* If regAcc==0, there there exists some min() or max() function
6788 ** without a FILTER clause that will ensure the magnet registers
6789 ** are populated. */
6790 if( regHit==0 ) regHit = ++pParse->nMem;
6791 /* If this is the first row of the group (regAcc contains 0), clear the
6792 ** "magnet" register regHit so that the accumulator registers
6793 ** are populated if the FILTER clause jumps over the the
6794 ** invocation of min() or max() altogether. Or, if this is not
6795 ** the first row (regAcc contains 1), set the magnet register so that
6796 ** the accumulators are not populated unless the min()/max() is invoked
6797 ** and indicates that they should be. */
6798 sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
6800 addrNext = sqlite3VdbeMakeLabel(pParse);
6801 sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
6803 if( pF->iOBTab>=0 ){
6804 /* Instead of invoking AggStep, we must push the arguments that would
6805 ** have been passed to AggStep onto the sorting table. */
6806 int jj; /* Registered used so far in building the record */
6807 ExprList *pOBList; /* The ORDER BY clause */
6808 assert( pList!=0 );
6809 nArg = pList->nExpr;
6810 assert( nArg>0 );
6811 assert( pF->pFExpr->pLeft!=0 );
6812 assert( pF->pFExpr->pLeft->op==TK_ORDER );
6813 assert( ExprUseXList(pF->pFExpr->pLeft) );
6814 pOBList = pF->pFExpr->pLeft->x.pList;
6815 assert( pOBList!=0 );
6816 assert( pOBList->nExpr>0 );
6817 regAggSz = pOBList->nExpr;
6818 if( !pF->bOBUnique ){
6819 regAggSz++; /* One register for OP_Sequence */
6821 if( pF->bOBPayload ){
6822 regAggSz += nArg;
6824 regAggSz++; /* One extra register to hold result of MakeRecord */
6825 regAgg = sqlite3GetTempRange(pParse, regAggSz);
6826 regDistinct = regAgg;
6827 sqlite3ExprCodeExprList(pParse, pOBList, regAgg, 0, SQLITE_ECEL_DUP);
6828 jj = pOBList->nExpr;
6829 if( !pF->bOBUnique ){
6830 sqlite3VdbeAddOp2(v, OP_Sequence, pF->iOBTab, regAgg+jj);
6831 jj++;
6833 if( pF->bOBPayload ){
6834 regDistinct = regAgg+jj;
6835 sqlite3ExprCodeExprList(pParse, pList, regDistinct, 0, SQLITE_ECEL_DUP);
6837 }else if( pList ){
6838 nArg = pList->nExpr;
6839 regAgg = sqlite3GetTempRange(pParse, nArg);
6840 regDistinct = regAgg;
6841 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
6842 }else{
6843 nArg = 0;
6844 regAgg = 0;
6846 if( pF->iDistinct>=0 && pList ){
6847 if( addrNext==0 ){
6848 addrNext = sqlite3VdbeMakeLabel(pParse);
6850 pF->iDistinct = codeDistinct(pParse, eDistinctType,
6851 pF->iDistinct, addrNext, pList, regDistinct);
6853 if( pF->iOBTab>=0 ){
6854 /* Insert a new record into the ORDER BY table */
6855 sqlite3VdbeAddOp3(v, OP_MakeRecord, regAgg, regAggSz-1,
6856 regAgg+regAggSz-1);
6857 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pF->iOBTab, regAgg+regAggSz-1,
6858 regAgg, regAggSz-1);
6859 sqlite3ReleaseTempRange(pParse, regAgg, regAggSz);
6860 }else{
6861 /* Invoke the AggStep function */
6862 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
6863 CollSeq *pColl = 0;
6864 struct ExprList_item *pItem;
6865 int j;
6866 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
6867 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
6868 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
6870 if( !pColl ){
6871 pColl = pParse->db->pDfltColl;
6873 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
6874 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0,
6875 (char *)pColl, P4_COLLSEQ);
6877 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
6878 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
6879 sqlite3VdbeChangeP5(v, (u8)nArg);
6880 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
6882 if( addrNext ){
6883 sqlite3VdbeResolveLabel(v, addrNext);
6886 if( regHit==0 && pAggInfo->nAccumulator ){
6887 regHit = regAcc;
6889 if( regHit ){
6890 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
6892 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
6893 sqlite3ExprCode(pParse, pC->pCExpr, AggInfoColumnReg(pAggInfo,i));
6896 pAggInfo->directMode = 0;
6897 if( addrHitTest ){
6898 sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
6903 ** Add a single OP_Explain instruction to the VDBE to explain a simple
6904 ** count(*) query ("SELECT count(*) FROM pTab").
6906 #ifndef SQLITE_OMIT_EXPLAIN
6907 static void explainSimpleCount(
6908 Parse *pParse, /* Parse context */
6909 Table *pTab, /* Table being queried */
6910 Index *pIdx /* Index used to optimize scan, or NULL */
6912 if( pParse->explain==2 ){
6913 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
6914 sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
6915 pTab->zName,
6916 bCover ? " USING COVERING INDEX " : "",
6917 bCover ? pIdx->zName : ""
6921 #else
6922 # define explainSimpleCount(a,b,c)
6923 #endif
6926 ** sqlite3WalkExpr() callback used by havingToWhere().
6928 ** If the node passed to the callback is a TK_AND node, return
6929 ** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
6931 ** Otherwise, return WRC_Prune. In this case, also check if the
6932 ** sub-expression matches the criteria for being moved to the WHERE
6933 ** clause. If so, add it to the WHERE clause and replace the sub-expression
6934 ** within the HAVING expression with a constant "1".
6936 static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
6937 if( pExpr->op!=TK_AND ){
6938 Select *pS = pWalker->u.pSelect;
6939 /* This routine is called before the HAVING clause of the current
6940 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
6941 ** here, it indicates that the expression is a correlated reference to a
6942 ** column from an outer aggregate query, or an aggregate function that
6943 ** belongs to an outer query. Do not move the expression to the WHERE
6944 ** clause in this obscure case, as doing so may corrupt the outer Select
6945 ** statements AggInfo structure. */
6946 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
6947 && ExprAlwaysFalse(pExpr)==0
6948 && pExpr->pAggInfo==0
6950 sqlite3 *db = pWalker->pParse->db;
6951 Expr *pNew = sqlite3Expr(db, TK_INTEGER, "1");
6952 if( pNew ){
6953 Expr *pWhere = pS->pWhere;
6954 SWAP(Expr, *pNew, *pExpr);
6955 pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
6956 pS->pWhere = pNew;
6957 pWalker->eCode = 1;
6960 return WRC_Prune;
6962 return WRC_Continue;
6966 ** Transfer eligible terms from the HAVING clause of a query, which is
6967 ** processed after grouping, to the WHERE clause, which is processed before
6968 ** grouping. For example, the query:
6970 ** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
6972 ** can be rewritten as:
6974 ** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
6976 ** A term of the HAVING expression is eligible for transfer if it consists
6977 ** entirely of constants and expressions that are also GROUP BY terms that
6978 ** use the "BINARY" collation sequence.
6980 static void havingToWhere(Parse *pParse, Select *p){
6981 Walker sWalker;
6982 memset(&sWalker, 0, sizeof(sWalker));
6983 sWalker.pParse = pParse;
6984 sWalker.xExprCallback = havingToWhereExprCb;
6985 sWalker.u.pSelect = p;
6986 sqlite3WalkExpr(&sWalker, p->pHaving);
6987 #if TREETRACE_ENABLED
6988 if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
6989 TREETRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
6990 sqlite3TreeViewSelect(0, p, 0);
6992 #endif
6996 ** Check to see if the pThis entry of pTabList is a self-join of another view.
6997 ** Search FROM-clause entries in the range of iFirst..iEnd, including iFirst
6998 ** but stopping before iEnd.
7000 ** If pThis is a self-join, then return the SrcItem for the first other
7001 ** instance of that view found. If pThis is not a self-join then return 0.
7003 static SrcItem *isSelfJoinView(
7004 SrcList *pTabList, /* Search for self-joins in this FROM clause */
7005 SrcItem *pThis, /* Search for prior reference to this subquery */
7006 int iFirst, int iEnd /* Range of FROM-clause entries to search. */
7008 SrcItem *pItem;
7009 assert( pThis->pSelect!=0 );
7010 if( pThis->pSelect->selFlags & SF_PushDown ) return 0;
7011 while( iFirst<iEnd ){
7012 Select *pS1;
7013 pItem = &pTabList->a[iFirst++];
7014 if( pItem->pSelect==0 ) continue;
7015 if( pItem->fg.viaCoroutine ) continue;
7016 if( pItem->zName==0 ) continue;
7017 assert( pItem->pTab!=0 );
7018 assert( pThis->pTab!=0 );
7019 if( pItem->pTab->pSchema!=pThis->pTab->pSchema ) continue;
7020 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
7021 pS1 = pItem->pSelect;
7022 if( pItem->pTab->pSchema==0 && pThis->pSelect->selId!=pS1->selId ){
7023 /* The query flattener left two different CTE tables with identical
7024 ** names in the same FROM clause. */
7025 continue;
7027 if( pItem->pSelect->selFlags & SF_PushDown ){
7028 /* The view was modified by some other optimization such as
7029 ** pushDownWhereTerms() */
7030 continue;
7032 return pItem;
7034 return 0;
7038 ** Deallocate a single AggInfo object
7040 static void agginfoFree(sqlite3 *db, AggInfo *p){
7041 sqlite3DbFree(db, p->aCol);
7042 sqlite3DbFree(db, p->aFunc);
7043 sqlite3DbFreeNN(db, p);
7047 ** Attempt to transform a query of the form
7049 ** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
7051 ** Into this:
7053 ** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
7055 ** The transformation only works if all of the following are true:
7057 ** * The subquery is a UNION ALL of two or more terms
7058 ** * The subquery does not have a LIMIT clause
7059 ** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
7060 ** * The outer query is a simple count(*) with no WHERE clause or other
7061 ** extraneous syntax.
7063 ** Return TRUE if the optimization is undertaken.
7065 static int countOfViewOptimization(Parse *pParse, Select *p){
7066 Select *pSub, *pPrior;
7067 Expr *pExpr;
7068 Expr *pCount;
7069 sqlite3 *db;
7070 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
7071 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
7072 if( p->pWhere ) return 0;
7073 if( p->pHaving ) return 0;
7074 if( p->pGroupBy ) return 0;
7075 if( p->pOrderBy ) return 0;
7076 pExpr = p->pEList->a[0].pExpr;
7077 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
7078 assert( ExprUseUToken(pExpr) );
7079 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
7080 assert( ExprUseXList(pExpr) );
7081 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
7082 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
7083 if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
7084 pSub = p->pSrc->a[0].pSelect;
7085 if( pSub==0 ) return 0; /* The FROM is a subquery */
7086 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
7087 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
7089 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
7090 if( pSub->pWhere ) return 0; /* No WHERE clause */
7091 if( pSub->pLimit ) return 0; /* No LIMIT clause */
7092 if( pSub->selFlags & SF_Aggregate ) return 0; /* Not an aggregate */
7093 assert( pSub->pHaving==0 ); /* Due to the previous */
7094 pSub = pSub->pPrior; /* Repeat over compound */
7095 }while( pSub );
7097 /* If we reach this point then it is OK to perform the transformation */
7099 db = pParse->db;
7100 pCount = pExpr;
7101 pExpr = 0;
7102 pSub = p->pSrc->a[0].pSelect;
7103 p->pSrc->a[0].pSelect = 0;
7104 sqlite3SrcListDelete(db, p->pSrc);
7105 p->pSrc = sqlite3DbMallocZero(pParse->db, sizeof(*p->pSrc));
7106 while( pSub ){
7107 Expr *pTerm;
7108 pPrior = pSub->pPrior;
7109 pSub->pPrior = 0;
7110 pSub->pNext = 0;
7111 pSub->selFlags |= SF_Aggregate;
7112 pSub->selFlags &= ~SF_Compound;
7113 pSub->nSelectRow = 0;
7114 sqlite3ExprListDelete(db, pSub->pEList);
7115 pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
7116 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
7117 pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
7118 sqlite3PExprAddSelect(pParse, pTerm, pSub);
7119 if( pExpr==0 ){
7120 pExpr = pTerm;
7121 }else{
7122 pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
7124 pSub = pPrior;
7126 p->pEList->a[0].pExpr = pExpr;
7127 p->selFlags &= ~SF_Aggregate;
7129 #if TREETRACE_ENABLED
7130 if( sqlite3TreeTrace & 0x200 ){
7131 TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
7132 sqlite3TreeViewSelect(0, p, 0);
7134 #endif
7135 return 1;
7139 ** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
7140 ** as pSrcItem but has the same alias as p0, then return true.
7141 ** Otherwise return false.
7143 static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
7144 int i;
7145 for(i=0; i<pSrc->nSrc; i++){
7146 SrcItem *p1 = &pSrc->a[i];
7147 if( p1==p0 ) continue;
7148 if( p0->pTab==p1->pTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
7149 return 1;
7151 if( p1->pSelect
7152 && (p1->pSelect->selFlags & SF_NestedFrom)!=0
7153 && sameSrcAlias(p0, p1->pSelect->pSrc)
7155 return 1;
7158 return 0;
7162 ** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
7163 ** be implemented as a co-routine. The i-th entry is guaranteed to be
7164 ** a subquery.
7166 ** The subquery is implemented as a co-routine if all of the following are
7167 ** true:
7169 ** (1) The subquery will likely be implemented in the outer loop of
7170 ** the query. This will be the case if any one of the following
7171 ** conditions hold:
7172 ** (a) The subquery is the only term in the FROM clause
7173 ** (b) The subquery is the left-most term and a CROSS JOIN or similar
7174 ** requires it to be the outer loop
7175 ** (c) All of the following are true:
7176 ** (i) The subquery is the left-most subquery in the FROM clause
7177 ** (ii) There is nothing that would prevent the subquery from
7178 ** being used as the outer loop if the sqlite3WhereBegin()
7179 ** routine nominates it to that position.
7180 ** (iii) The query is not a UPDATE ... FROM
7181 ** (2) The subquery is not a CTE that should be materialized because
7182 ** (a) the AS MATERIALIZED keyword is used, or
7183 ** (b) the CTE is used multiple times and does not have the
7184 ** NOT MATERIALIZED keyword
7185 ** (3) The subquery is not part of a left operand for a RIGHT JOIN
7186 ** (4) The SQLITE_Coroutine optimization disable flag is not set
7187 ** (5) The subquery is not self-joined
7189 static int fromClauseTermCanBeCoroutine(
7190 Parse *pParse, /* Parsing context */
7191 SrcList *pTabList, /* FROM clause */
7192 int i, /* Which term of the FROM clause holds the subquery */
7193 int selFlags /* Flags on the SELECT statement */
7195 SrcItem *pItem = &pTabList->a[i];
7196 if( pItem->fg.isCte ){
7197 const CteUse *pCteUse = pItem->u2.pCteUse;
7198 if( pCteUse->eM10d==M10d_Yes ) return 0; /* (2a) */
7199 if( pCteUse->nUse>=2 && pCteUse->eM10d!=M10d_No ) return 0; /* (2b) */
7201 if( pTabList->a[0].fg.jointype & JT_LTORJ ) return 0; /* (3) */
7202 if( OptimizationDisabled(pParse->db, SQLITE_Coroutines) ) return 0; /* (4) */
7203 if( isSelfJoinView(pTabList, pItem, i+1, pTabList->nSrc)!=0 ){
7204 return 0; /* (5) */
7206 if( i==0 ){
7207 if( pTabList->nSrc==1 ) return 1; /* (1a) */
7208 if( pTabList->a[1].fg.jointype & JT_CROSS ) return 1; /* (1b) */
7209 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7210 return 1;
7212 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7213 while( 1 /*exit-by-break*/ ){
7214 if( pItem->fg.jointype & (JT_OUTER|JT_CROSS) ) return 0; /* (1c-ii) */
7215 if( i==0 ) break;
7216 i--;
7217 pItem--;
7218 if( pItem->pSelect!=0 ) return 0; /* (1c-i) */
7220 return 1;
7224 ** Generate code for the SELECT statement given in the p argument.
7226 ** The results are returned according to the SelectDest structure.
7227 ** See comments in sqliteInt.h for further information.
7229 ** This routine returns the number of errors. If any errors are
7230 ** encountered, then an appropriate error message is left in
7231 ** pParse->zErrMsg.
7233 ** This routine does NOT free the Select structure passed in. The
7234 ** calling function needs to do that.
7236 int sqlite3Select(
7237 Parse *pParse, /* The parser context */
7238 Select *p, /* The SELECT statement being coded. */
7239 SelectDest *pDest /* What to do with the query results */
7241 int i, j; /* Loop counters */
7242 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
7243 Vdbe *v; /* The virtual machine under construction */
7244 int isAgg; /* True for select lists like "count(*)" */
7245 ExprList *pEList = 0; /* List of columns to extract. */
7246 SrcList *pTabList; /* List of tables to select from */
7247 Expr *pWhere; /* The WHERE clause. May be NULL */
7248 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
7249 Expr *pHaving; /* The HAVING clause. May be NULL */
7250 AggInfo *pAggInfo = 0; /* Aggregate information */
7251 int rc = 1; /* Value to return from this function */
7252 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
7253 SortCtx sSort; /* Info on how to code the ORDER BY clause */
7254 int iEnd; /* Address of the end of the query */
7255 sqlite3 *db; /* The database connection */
7256 ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
7257 u8 minMaxFlag; /* Flag for min/max queries */
7259 db = pParse->db;
7260 assert( pParse==db->pParse );
7261 v = sqlite3GetVdbe(pParse);
7262 if( p==0 || pParse->nErr ){
7263 return 1;
7265 assert( db->mallocFailed==0 );
7266 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
7267 #if TREETRACE_ENABLED
7268 TREETRACE(0x1,pParse,p, ("begin processing:\n", pParse->addrExplain));
7269 if( sqlite3TreeTrace & 0x10000 ){
7270 if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
7271 sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
7272 __FILE__, __LINE__);
7274 sqlite3ShowSelect(p);
7276 #endif
7278 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
7279 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
7280 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
7281 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
7282 if( IgnorableDistinct(pDest) ){
7283 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Union ||
7284 pDest->eDest==SRT_Except || pDest->eDest==SRT_Discard ||
7285 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
7286 /* All of these destinations are also able to ignore the ORDER BY clause */
7287 if( p->pOrderBy ){
7288 #if TREETRACE_ENABLED
7289 TREETRACE(0x800,pParse,p, ("dropping superfluous ORDER BY:\n"));
7290 if( sqlite3TreeTrace & 0x800 ){
7291 sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
7293 #endif
7294 sqlite3ParserAddCleanup(pParse,
7295 (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
7296 p->pOrderBy);
7297 testcase( pParse->earlyCleanup );
7298 p->pOrderBy = 0;
7300 p->selFlags &= ~SF_Distinct;
7301 p->selFlags |= SF_NoopOrderBy;
7303 sqlite3SelectPrep(pParse, p, 0);
7304 if( pParse->nErr ){
7305 goto select_end;
7307 assert( db->mallocFailed==0 );
7308 assert( p->pEList!=0 );
7309 #if TREETRACE_ENABLED
7310 if( sqlite3TreeTrace & 0x10 ){
7311 TREETRACE(0x10,pParse,p, ("after name resolution:\n"));
7312 sqlite3TreeViewSelect(0, p, 0);
7314 #endif
7316 /* If the SF_UFSrcCheck flag is set, then this function is being called
7317 ** as part of populating the temp table for an UPDATE...FROM statement.
7318 ** In this case, it is an error if the target object (pSrc->a[0]) name
7319 ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
7321 ** Postgres disallows this case too. The reason is that some other
7322 ** systems handle this case differently, and not all the same way,
7323 ** which is just confusing. To avoid this, we follow PG's lead and
7324 ** disallow it altogether. */
7325 if( p->selFlags & SF_UFSrcCheck ){
7326 SrcItem *p0 = &p->pSrc->a[0];
7327 if( sameSrcAlias(p0, p->pSrc) ){
7328 sqlite3ErrorMsg(pParse,
7329 "target object/alias may not appear in FROM clause: %s",
7330 p0->zAlias ? p0->zAlias : p0->pTab->zName
7332 goto select_end;
7335 /* Clear the SF_UFSrcCheck flag. The check has already been performed,
7336 ** and leaving this flag set can cause errors if a compound sub-query
7337 ** in p->pSrc is flattened into this query and this function called
7338 ** again as part of compound SELECT processing. */
7339 p->selFlags &= ~SF_UFSrcCheck;
7342 if( pDest->eDest==SRT_Output ){
7343 sqlite3GenerateColumnNames(pParse, p);
7346 #ifndef SQLITE_OMIT_WINDOWFUNC
7347 if( sqlite3WindowRewrite(pParse, p) ){
7348 assert( pParse->nErr );
7349 goto select_end;
7351 #if TREETRACE_ENABLED
7352 if( p->pWin && (sqlite3TreeTrace & 0x40)!=0 ){
7353 TREETRACE(0x40,pParse,p, ("after window rewrite:\n"));
7354 sqlite3TreeViewSelect(0, p, 0);
7356 #endif
7357 #endif /* SQLITE_OMIT_WINDOWFUNC */
7358 pTabList = p->pSrc;
7359 isAgg = (p->selFlags & SF_Aggregate)!=0;
7360 memset(&sSort, 0, sizeof(sSort));
7361 sSort.pOrderBy = p->pOrderBy;
7363 /* Try to do various optimizations (flattening subqueries, and strength
7364 ** reduction of join operators) in the FROM clause up into the main query
7366 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7367 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
7368 SrcItem *pItem = &pTabList->a[i];
7369 Select *pSub = pItem->pSelect;
7370 Table *pTab = pItem->pTab;
7372 /* The expander should have already created transient Table objects
7373 ** even for FROM clause elements such as subqueries that do not correspond
7374 ** to a real table */
7375 assert( pTab!=0 );
7377 /* Try to simplify joins:
7379 ** LEFT JOIN -> JOIN
7380 ** RIGHT JOIN -> JOIN
7381 ** FULL JOIN -> RIGHT JOIN
7383 ** If terms of the i-th table are used in the WHERE clause in such a
7384 ** way that the i-th table cannot be the NULL row of a join, then
7385 ** perform the appropriate simplification. This is called
7386 ** "OUTER JOIN strength reduction" in the SQLite documentation.
7388 if( (pItem->fg.jointype & (JT_LEFT|JT_LTORJ))!=0
7389 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor,
7390 pItem->fg.jointype & JT_LTORJ)
7391 && OptimizationEnabled(db, SQLITE_SimplifyJoin)
7393 if( pItem->fg.jointype & JT_LEFT ){
7394 if( pItem->fg.jointype & JT_RIGHT ){
7395 TREETRACE(0x1000,pParse,p,
7396 ("FULL-JOIN simplifies to RIGHT-JOIN on term %d\n",i));
7397 pItem->fg.jointype &= ~JT_LEFT;
7398 }else{
7399 TREETRACE(0x1000,pParse,p,
7400 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
7401 pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
7402 unsetJoinExpr(p->pWhere, pItem->iCursor, 0);
7405 if( pItem->fg.jointype & JT_LTORJ ){
7406 for(j=i+1; j<pTabList->nSrc; j++){
7407 SrcItem *pI2 = &pTabList->a[j];
7408 if( pI2->fg.jointype & JT_RIGHT ){
7409 if( pI2->fg.jointype & JT_LEFT ){
7410 TREETRACE(0x1000,pParse,p,
7411 ("FULL-JOIN simplifies to LEFT-JOIN on term %d\n",j));
7412 pI2->fg.jointype &= ~JT_RIGHT;
7413 }else{
7414 TREETRACE(0x1000,pParse,p,
7415 ("RIGHT-JOIN simplifies to JOIN on term %d\n",j));
7416 pI2->fg.jointype &= ~(JT_RIGHT|JT_OUTER);
7417 unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
7421 for(j=pTabList->nSrc-1; j>=0; j--){
7422 pTabList->a[j].fg.jointype &= ~JT_LTORJ;
7423 if( pTabList->a[j].fg.jointype & JT_RIGHT ) break;
7428 /* No further action if this term of the FROM clause is not a subquery */
7429 if( pSub==0 ) continue;
7431 /* Catch mismatch in the declared columns of a view and the number of
7432 ** columns in the SELECT on the RHS */
7433 if( pTab->nCol!=pSub->pEList->nExpr ){
7434 sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
7435 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
7436 goto select_end;
7439 /* Do not attempt the usual optimizations (flattening and ORDER BY
7440 ** elimination) on a MATERIALIZED common table expression because
7441 ** a MATERIALIZED common table expression is an optimization fence.
7443 if( pItem->fg.isCte && pItem->u2.pCteUse->eM10d==M10d_Yes ){
7444 continue;
7447 /* Do not try to flatten an aggregate subquery.
7449 ** Flattening an aggregate subquery is only possible if the outer query
7450 ** is not a join. But if the outer query is not a join, then the subquery
7451 ** will be implemented as a co-routine and there is no advantage to
7452 ** flattening in that case.
7454 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
7455 assert( pSub->pGroupBy==0 );
7457 /* If a FROM-clause subquery has an ORDER BY clause that is not
7458 ** really doing anything, then delete it now so that it does not
7459 ** interfere with query flattening. See the discussion at
7460 ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
7462 ** Beware of these cases where the ORDER BY clause may not be safely
7463 ** omitted:
7465 ** (1) There is also a LIMIT clause
7466 ** (2) The subquery was added to help with window-function
7467 ** processing
7468 ** (3) The subquery is in the FROM clause of an UPDATE
7469 ** (4) The outer query uses an aggregate function other than
7470 ** the built-in count(), min(), or max().
7471 ** (5) The ORDER BY isn't going to accomplish anything because
7472 ** one of:
7473 ** (a) The outer query has a different ORDER BY clause
7474 ** (b) The subquery is part of a join
7475 ** See forum post 062d576715d277c8
7477 ** Also retain the ORDER BY if the OmitOrderBy optimization is disabled.
7479 if( pSub->pOrderBy!=0
7480 && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */
7481 && pSub->pLimit==0 /* Condition (1) */
7482 && (pSub->selFlags & SF_OrderByReqd)==0 /* Condition (2) */
7483 && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
7484 && OptimizationEnabled(db, SQLITE_OmitOrderBy)
7486 TREETRACE(0x800,pParse,p,
7487 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
7488 sqlite3ParserAddCleanup(pParse,
7489 (void(*)(sqlite3*,void*))sqlite3ExprListDelete,
7490 pSub->pOrderBy);
7491 pSub->pOrderBy = 0;
7494 /* If the outer query contains a "complex" result set (that is,
7495 ** if the result set of the outer query uses functions or subqueries)
7496 ** and if the subquery contains an ORDER BY clause and if
7497 ** it will be implemented as a co-routine, then do not flatten. This
7498 ** restriction allows SQL constructs like this:
7500 ** SELECT expensive_function(x)
7501 ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
7503 ** The expensive_function() is only computed on the 10 rows that
7504 ** are output, rather than every row of the table.
7506 ** The requirement that the outer query have a complex result set
7507 ** means that flattening does occur on simpler SQL constraints without
7508 ** the expensive_function() like:
7510 ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
7512 if( pSub->pOrderBy!=0
7513 && i==0
7514 && (p->selFlags & SF_ComplexResult)!=0
7515 && (pTabList->nSrc==1
7516 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
7518 continue;
7521 if( flattenSubquery(pParse, p, i, isAgg) ){
7522 if( pParse->nErr ) goto select_end;
7523 /* This subquery can be absorbed into its parent. */
7524 i = -1;
7526 pTabList = p->pSrc;
7527 if( db->mallocFailed ) goto select_end;
7528 if( !IgnorableOrderby(pDest) ){
7529 sSort.pOrderBy = p->pOrderBy;
7532 #endif
7534 #ifndef SQLITE_OMIT_COMPOUND_SELECT
7535 /* Handle compound SELECT statements using the separate multiSelect()
7536 ** procedure.
7538 if( p->pPrior ){
7539 rc = multiSelect(pParse, p, pDest);
7540 #if TREETRACE_ENABLED
7541 TREETRACE(0x400,pParse,p,("end compound-select processing\n"));
7542 if( (sqlite3TreeTrace & 0x400)!=0 && ExplainQueryPlanParent(pParse)==0 ){
7543 sqlite3TreeViewSelect(0, p, 0);
7545 #endif
7546 if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
7547 return rc;
7549 #endif
7551 /* Do the WHERE-clause constant propagation optimization if this is
7552 ** a join. No need to speed time on this operation for non-join queries
7553 ** as the equivalent optimization will be handled by query planner in
7554 ** sqlite3WhereBegin().
7556 if( p->pWhere!=0
7557 && p->pWhere->op==TK_AND
7558 && OptimizationEnabled(db, SQLITE_PropagateConst)
7559 && propagateConstants(pParse, p)
7561 #if TREETRACE_ENABLED
7562 if( sqlite3TreeTrace & 0x2000 ){
7563 TREETRACE(0x2000,pParse,p,("After constant propagation:\n"));
7564 sqlite3TreeViewSelect(0, p, 0);
7566 #endif
7567 }else{
7568 TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
7571 if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
7572 && countOfViewOptimization(pParse, p)
7574 if( db->mallocFailed ) goto select_end;
7575 pTabList = p->pSrc;
7578 /* For each term in the FROM clause, do two things:
7579 ** (1) Authorized unreferenced tables
7580 ** (2) Generate code for all sub-queries
7582 for(i=0; i<pTabList->nSrc; i++){
7583 SrcItem *pItem = &pTabList->a[i];
7584 SrcItem *pPrior;
7585 SelectDest dest;
7586 Select *pSub;
7587 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7588 const char *zSavedAuthContext;
7589 #endif
7591 /* Issue SQLITE_READ authorizations with a fake column name for any
7592 ** tables that are referenced but from which no values are extracted.
7593 ** Examples of where these kinds of null SQLITE_READ authorizations
7594 ** would occur:
7596 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
7597 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
7599 ** The fake column name is an empty string. It is possible for a table to
7600 ** have a column named by the empty string, in which case there is no way to
7601 ** distinguish between an unreferenced table and an actual reference to the
7602 ** "" column. The original design was for the fake column name to be a NULL,
7603 ** which would be unambiguous. But legacy authorization callbacks might
7604 ** assume the column name is non-NULL and segfault. The use of an empty
7605 ** string for the fake column name seems safer.
7607 if( pItem->colUsed==0 && pItem->zName!=0 ){
7608 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", pItem->zDatabase);
7611 #if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
7612 /* Generate code for all sub-queries in the FROM clause
7614 pSub = pItem->pSelect;
7615 if( pSub==0 ) continue;
7617 /* The code for a subquery should only be generated once. */
7618 assert( pItem->addrFillSub==0 );
7620 /* Increment Parse.nHeight by the height of the largest expression
7621 ** tree referred to by this, the parent select. The child select
7622 ** may contain expression trees of at most
7623 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
7624 ** more conservative than necessary, but much easier than enforcing
7625 ** an exact limit.
7627 pParse->nHeight += sqlite3SelectExprHeight(p);
7629 /* Make copies of constant WHERE-clause terms in the outer query down
7630 ** inside the subquery. This can help the subquery to run more efficiently.
7632 if( OptimizationEnabled(db, SQLITE_PushDown)
7633 && (pItem->fg.isCte==0
7634 || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
7635 && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
7637 #if TREETRACE_ENABLED
7638 if( sqlite3TreeTrace & 0x4000 ){
7639 TREETRACE(0x4000,pParse,p,
7640 ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
7641 sqlite3TreeViewSelect(0, p, 0);
7643 #endif
7644 assert( pItem->pSelect && (pItem->pSelect->selFlags & SF_PushDown)!=0 );
7645 }else{
7646 TREETRACE(0x4000,pParse,p,("Push-down not possible\n"));
7649 /* Convert unused result columns of the subquery into simple NULL
7650 ** expressions, to avoid unneeded searching and computation.
7652 if( OptimizationEnabled(db, SQLITE_NullUnusedCols)
7653 && disableUnusedSubqueryResultColumns(pItem)
7655 #if TREETRACE_ENABLED
7656 if( sqlite3TreeTrace & 0x4000 ){
7657 TREETRACE(0x4000,pParse,p,
7658 ("Change unused result columns to NULL for subquery %d:\n",
7659 pSub->selId));
7660 sqlite3TreeViewSelect(0, p, 0);
7662 #endif
7665 zSavedAuthContext = pParse->zAuthContext;
7666 pParse->zAuthContext = pItem->zName;
7668 /* Generate code to implement the subquery
7670 if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
7671 /* Implement a co-routine that will return a single row of the result
7672 ** set on each invocation.
7674 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
7676 pItem->regReturn = ++pParse->nMem;
7677 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pItem->regReturn, 0, addrTop);
7678 VdbeComment((v, "%!S", pItem));
7679 pItem->addrFillSub = addrTop;
7680 sqlite3SelectDestInit(&dest, SRT_Coroutine, pItem->regReturn);
7681 ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
7682 sqlite3Select(pParse, pSub, &dest);
7683 pItem->pTab->nRowLogEst = pSub->nSelectRow;
7684 pItem->fg.viaCoroutine = 1;
7685 pItem->regResult = dest.iSdst;
7686 sqlite3VdbeEndCoroutine(v, pItem->regReturn);
7687 sqlite3VdbeJumpHere(v, addrTop-1);
7688 sqlite3ClearTempRegCache(pParse);
7689 }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
7690 /* This is a CTE for which materialization code has already been
7691 ** generated. Invoke the subroutine to compute the materialization,
7692 ** the make the pItem->iCursor be a copy of the ephemeral table that
7693 ** holds the result of the materialization. */
7694 CteUse *pCteUse = pItem->u2.pCteUse;
7695 sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
7696 if( pItem->iCursor!=pCteUse->iCur ){
7697 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
7698 VdbeComment((v, "%!S", pItem));
7700 pSub->nSelectRow = pCteUse->nRowEst;
7701 }else if( (pPrior = isSelfJoinView(pTabList, pItem, 0, i))!=0 ){
7702 /* This view has already been materialized by a prior entry in
7703 ** this same FROM clause. Reuse it. */
7704 if( pPrior->addrFillSub ){
7705 sqlite3VdbeAddOp2(v, OP_Gosub, pPrior->regReturn, pPrior->addrFillSub);
7707 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
7708 pSub->nSelectRow = pPrior->pSelect->nSelectRow;
7709 }else{
7710 /* Materialize the view. If the view is not correlated, generate a
7711 ** subroutine to do the materialization so that subsequent uses of
7712 ** the same view can reuse the materialization. */
7713 int topAddr;
7714 int onceAddr = 0;
7715 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
7716 int addrExplain;
7717 #endif
7719 pItem->regReturn = ++pParse->nMem;
7720 topAddr = sqlite3VdbeAddOp0(v, OP_Goto);
7721 pItem->addrFillSub = topAddr+1;
7722 pItem->fg.isMaterialized = 1;
7723 if( pItem->fg.isCorrelated==0 ){
7724 /* If the subquery is not correlated and if we are not inside of
7725 ** a trigger, then we only need to compute the value of the subquery
7726 ** once. */
7727 onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
7728 VdbeComment((v, "materialize %!S", pItem));
7729 }else{
7730 VdbeNoopComment((v, "materialize %!S", pItem));
7732 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
7734 ExplainQueryPlan2(addrExplain, (pParse, 1, "MATERIALIZE %!S", pItem));
7735 sqlite3Select(pParse, pSub, &dest);
7736 pItem->pTab->nRowLogEst = pSub->nSelectRow;
7737 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
7738 sqlite3VdbeAddOp2(v, OP_Return, pItem->regReturn, topAddr+1);
7739 VdbeComment((v, "end %!S", pItem));
7740 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
7741 sqlite3VdbeJumpHere(v, topAddr);
7742 sqlite3ClearTempRegCache(pParse);
7743 if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
7744 CteUse *pCteUse = pItem->u2.pCteUse;
7745 pCteUse->addrM9e = pItem->addrFillSub;
7746 pCteUse->regRtn = pItem->regReturn;
7747 pCteUse->iCur = pItem->iCursor;
7748 pCteUse->nRowEst = pSub->nSelectRow;
7751 if( db->mallocFailed ) goto select_end;
7752 pParse->nHeight -= sqlite3SelectExprHeight(p);
7753 pParse->zAuthContext = zSavedAuthContext;
7754 #endif
7757 /* Various elements of the SELECT copied into local variables for
7758 ** convenience */
7759 pEList = p->pEList;
7760 pWhere = p->pWhere;
7761 pGroupBy = p->pGroupBy;
7762 pHaving = p->pHaving;
7763 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
7765 #if TREETRACE_ENABLED
7766 if( sqlite3TreeTrace & 0x8000 ){
7767 TREETRACE(0x8000,pParse,p,("After all FROM-clause analysis:\n"));
7768 sqlite3TreeViewSelect(0, p, 0);
7770 #endif
7772 /* If the query is DISTINCT with an ORDER BY but is not an aggregate, and
7773 ** if the select-list is the same as the ORDER BY list, then this query
7774 ** can be rewritten as a GROUP BY. In other words, this:
7776 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
7778 ** is transformed to:
7780 ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
7782 ** The second form is preferred as a single index (or temp-table) may be
7783 ** used for both the ORDER BY and DISTINCT processing. As originally
7784 ** written the query must use a temp-table for at least one of the ORDER
7785 ** BY and DISTINCT, and an index or separate temp-table for the other.
7787 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
7788 && sqlite3ExprListCompare(sSort.pOrderBy, pEList, -1)==0
7789 #ifndef SQLITE_OMIT_WINDOWFUNC
7790 && p->pWin==0
7791 #endif
7793 p->selFlags &= ~SF_Distinct;
7794 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
7795 p->selFlags |= SF_Aggregate;
7796 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
7797 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
7798 ** original setting of the SF_Distinct flag, not the current setting */
7799 assert( sDistinct.isTnct );
7800 sDistinct.isTnct = 2;
7802 #if TREETRACE_ENABLED
7803 if( sqlite3TreeTrace & 0x20000 ){
7804 TREETRACE(0x20000,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
7805 sqlite3TreeViewSelect(0, p, 0);
7807 #endif
7810 /* If there is an ORDER BY clause, then create an ephemeral index to
7811 ** do the sorting. But this sorting ephemeral index might end up
7812 ** being unused if the data can be extracted in pre-sorted order.
7813 ** If that is the case, then the OP_OpenEphemeral instruction will be
7814 ** changed to an OP_Noop once we figure out that the sorting index is
7815 ** not needed. The sSort.addrSortIndex variable is used to facilitate
7816 ** that change.
7818 if( sSort.pOrderBy ){
7819 KeyInfo *pKeyInfo;
7820 pKeyInfo = sqlite3KeyInfoFromExprList(
7821 pParse, sSort.pOrderBy, 0, pEList->nExpr);
7822 sSort.iECursor = pParse->nTab++;
7823 sSort.addrSortIndex =
7824 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7825 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
7826 (char*)pKeyInfo, P4_KEYINFO
7828 }else{
7829 sSort.addrSortIndex = -1;
7832 /* If the output is destined for a temporary table, open that table.
7834 if( pDest->eDest==SRT_EphemTab ){
7835 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
7836 if( p->selFlags & SF_NestedFrom ){
7837 /* Delete or NULL-out result columns that will never be used */
7838 int ii;
7839 for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
7840 sqlite3ExprDelete(db, pEList->a[ii].pExpr);
7841 sqlite3DbFree(db, pEList->a[ii].zEName);
7842 pEList->nExpr--;
7844 for(ii=0; ii<pEList->nExpr; ii++){
7845 if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
7850 /* Set the limiter.
7852 iEnd = sqlite3VdbeMakeLabel(pParse);
7853 if( (p->selFlags & SF_FixedLimit)==0 ){
7854 p->nSelectRow = 320; /* 4 billion rows */
7856 if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
7857 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
7858 sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
7859 sSort.sortFlags |= SORTFLAG_UseSorter;
7862 /* Open an ephemeral index to use for the distinct set.
7864 if( p->selFlags & SF_Distinct ){
7865 sDistinct.tabTnct = pParse->nTab++;
7866 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
7867 sDistinct.tabTnct, 0, 0,
7868 (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
7869 P4_KEYINFO);
7870 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
7871 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
7872 }else{
7873 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
7876 if( !isAgg && pGroupBy==0 ){
7877 /* No aggregate functions and no GROUP BY clause */
7878 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
7879 | (p->selFlags & SF_FixedLimit);
7880 #ifndef SQLITE_OMIT_WINDOWFUNC
7881 Window *pWin = p->pWin; /* Main window object (or NULL) */
7882 if( pWin ){
7883 sqlite3WindowCodeInit(pParse, p);
7885 #endif
7886 assert( WHERE_USE_LIMIT==SF_FixedLimit );
7889 /* Begin the database scan. */
7890 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
7891 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
7892 p->pEList, p, wctrlFlags, p->nSelectRow);
7893 if( pWInfo==0 ) goto select_end;
7894 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
7895 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
7897 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
7898 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
7900 if( sSort.pOrderBy ){
7901 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
7902 sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
7903 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
7904 sSort.pOrderBy = 0;
7907 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
7909 /* If sorting index that was created by a prior OP_OpenEphemeral
7910 ** instruction ended up not being needed, then change the OP_OpenEphemeral
7911 ** into an OP_Noop.
7913 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
7914 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
7917 assert( p->pEList==pEList );
7918 #ifndef SQLITE_OMIT_WINDOWFUNC
7919 if( pWin ){
7920 int addrGosub = sqlite3VdbeMakeLabel(pParse);
7921 int iCont = sqlite3VdbeMakeLabel(pParse);
7922 int iBreak = sqlite3VdbeMakeLabel(pParse);
7923 int regGosub = ++pParse->nMem;
7925 sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
7927 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
7928 sqlite3VdbeResolveLabel(v, addrGosub);
7929 VdbeNoopComment((v, "inner-loop subroutine"));
7930 sSort.labelOBLopt = 0;
7931 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
7932 sqlite3VdbeResolveLabel(v, iCont);
7933 sqlite3VdbeAddOp1(v, OP_Return, regGosub);
7934 VdbeComment((v, "end inner-loop subroutine"));
7935 sqlite3VdbeResolveLabel(v, iBreak);
7936 }else
7937 #endif /* SQLITE_OMIT_WINDOWFUNC */
7939 /* Use the standard inner loop. */
7940 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
7941 sqlite3WhereContinueLabel(pWInfo),
7942 sqlite3WhereBreakLabel(pWInfo));
7944 /* End the database scan loop.
7946 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
7947 sqlite3WhereEnd(pWInfo);
7949 }else{
7950 /* This case when there exist aggregate functions or a GROUP BY clause
7951 ** or both */
7952 NameContext sNC; /* Name context for processing aggregate information */
7953 int iAMem; /* First Mem address for storing current GROUP BY */
7954 int iBMem; /* First Mem address for previous GROUP BY */
7955 int iUseFlag; /* Mem address holding flag indicating that at least
7956 ** one row of the input to the aggregator has been
7957 ** processed */
7958 int iAbortFlag; /* Mem address which causes query abort if positive */
7959 int groupBySort; /* Rows come from source in GROUP BY order */
7960 int addrEnd; /* End of processing for this SELECT */
7961 int sortPTab = 0; /* Pseudotable used to decode sorting results */
7962 int sortOut = 0; /* Output register from the sorter */
7963 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
7965 /* Remove any and all aliases between the result set and the
7966 ** GROUP BY clause.
7968 if( pGroupBy ){
7969 int k; /* Loop counter */
7970 struct ExprList_item *pItem; /* For looping over expression in a list */
7972 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
7973 pItem->u.x.iAlias = 0;
7975 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
7976 pItem->u.x.iAlias = 0;
7978 assert( 66==sqlite3LogEst(100) );
7979 if( p->nSelectRow>66 ) p->nSelectRow = 66;
7981 /* If there is both a GROUP BY and an ORDER BY clause and they are
7982 ** identical, then it may be possible to disable the ORDER BY clause
7983 ** on the grounds that the GROUP BY will cause elements to come out
7984 ** in the correct order. It also may not - the GROUP BY might use a
7985 ** database index that causes rows to be grouped together as required
7986 ** but not actually sorted. Either way, record the fact that the
7987 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
7988 ** variable. */
7989 if( sSort.pOrderBy && pGroupBy->nExpr==sSort.pOrderBy->nExpr ){
7990 int ii;
7991 /* The GROUP BY processing doesn't care whether rows are delivered in
7992 ** ASC or DESC order - only that each group is returned contiguously.
7993 ** So set the ASC/DESC flags in the GROUP BY to match those in the
7994 ** ORDER BY to maximize the chances of rows being delivered in an
7995 ** order that makes the ORDER BY redundant. */
7996 for(ii=0; ii<pGroupBy->nExpr; ii++){
7997 u8 sortFlags;
7998 sortFlags = sSort.pOrderBy->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
7999 pGroupBy->a[ii].fg.sortFlags = sortFlags;
8001 if( sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0 ){
8002 orderByGrp = 1;
8005 }else{
8006 assert( 0==sqlite3LogEst(1) );
8007 p->nSelectRow = 0;
8010 /* Create a label to jump to when we want to abort the query */
8011 addrEnd = sqlite3VdbeMakeLabel(pParse);
8013 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
8014 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
8015 ** SELECT statement.
8017 pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
8018 if( pAggInfo ){
8019 sqlite3ParserAddCleanup(pParse,
8020 (void(*)(sqlite3*,void*))agginfoFree, pAggInfo);
8021 testcase( pParse->earlyCleanup );
8023 if( db->mallocFailed ){
8024 goto select_end;
8026 pAggInfo->selId = p->selId;
8027 #ifdef SQLITE_DEBUG
8028 pAggInfo->pSelect = p;
8029 #endif
8030 memset(&sNC, 0, sizeof(sNC));
8031 sNC.pParse = pParse;
8032 sNC.pSrcList = pTabList;
8033 sNC.uNC.pAggInfo = pAggInfo;
8034 VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
8035 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
8036 pAggInfo->pGroupBy = pGroupBy;
8037 sqlite3ExprAnalyzeAggList(&sNC, pEList);
8038 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
8039 if( pHaving ){
8040 if( pGroupBy ){
8041 assert( pWhere==p->pWhere );
8042 assert( pHaving==p->pHaving );
8043 assert( pGroupBy==p->pGroupBy );
8044 havingToWhere(pParse, p);
8045 pWhere = p->pWhere;
8047 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
8049 pAggInfo->nAccumulator = pAggInfo->nColumn;
8050 if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
8051 minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
8052 }else{
8053 minMaxFlag = WHERE_ORDERBY_NORMAL;
8055 analyzeAggFuncArgs(pAggInfo, &sNC);
8056 if( db->mallocFailed ) goto select_end;
8057 #if TREETRACE_ENABLED
8058 if( sqlite3TreeTrace & 0x20 ){
8059 TREETRACE(0x20,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
8060 sqlite3TreeViewSelect(0, p, 0);
8061 if( minMaxFlag ){
8062 sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
8063 sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
8065 printAggInfo(pAggInfo);
8067 #endif
8070 /* Processing for aggregates with GROUP BY is very different and
8071 ** much more complex than aggregates without a GROUP BY.
8073 if( pGroupBy ){
8074 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
8075 int addr1; /* A-vs-B comparison jump */
8076 int addrOutputRow; /* Start of subroutine that outputs a result row */
8077 int regOutputRow; /* Return address register for output subroutine */
8078 int addrSetAbort; /* Set the abort flag and return */
8079 int addrTopOfLoop; /* Top of the input loop */
8080 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
8081 int addrReset; /* Subroutine for resetting the accumulator */
8082 int regReset; /* Return address register for reset subroutine */
8083 ExprList *pDistinct = 0;
8084 u16 distFlag = 0;
8085 int eDist = WHERE_DISTINCT_NOOP;
8087 if( pAggInfo->nFunc==1
8088 && pAggInfo->aFunc[0].iDistinct>=0
8089 && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
8090 && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
8091 && pAggInfo->aFunc[0].pFExpr->x.pList!=0
8093 Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
8094 pExpr = sqlite3ExprDup(db, pExpr, 0);
8095 pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
8096 pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
8097 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
8100 /* If there is a GROUP BY clause we might need a sorting index to
8101 ** implement it. Allocate that sorting index now. If it turns out
8102 ** that we do not need it after all, the OP_SorterOpen instruction
8103 ** will be converted into a Noop.
8105 pAggInfo->sortingIdx = pParse->nTab++;
8106 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
8107 0, pAggInfo->nColumn);
8108 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
8109 pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
8110 0, (char*)pKeyInfo, P4_KEYINFO);
8112 /* Initialize memory locations used by GROUP BY aggregate processing
8114 iUseFlag = ++pParse->nMem;
8115 iAbortFlag = ++pParse->nMem;
8116 regOutputRow = ++pParse->nMem;
8117 addrOutputRow = sqlite3VdbeMakeLabel(pParse);
8118 regReset = ++pParse->nMem;
8119 addrReset = sqlite3VdbeMakeLabel(pParse);
8120 iAMem = pParse->nMem + 1;
8121 pParse->nMem += pGroupBy->nExpr;
8122 iBMem = pParse->nMem + 1;
8123 pParse->nMem += pGroupBy->nExpr;
8124 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
8125 VdbeComment((v, "clear abort flag"));
8126 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
8128 /* Begin a loop that will extract all source rows in GROUP BY order.
8129 ** This might involve two separate loops with an OP_Sort in between, or
8130 ** it might be a single loop that uses an index to extract information
8131 ** in the right order to begin with.
8133 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
8134 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8135 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
8136 p, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
8137 | (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
8139 if( pWInfo==0 ){
8140 sqlite3ExprListDelete(db, pDistinct);
8141 goto select_end;
8143 if( pParse->pIdxEpr ){
8144 optimizeAggregateUseOfIndexedExpr(pParse, p, pAggInfo, &sNC);
8146 assignAggregateRegisters(pParse, pAggInfo);
8147 eDist = sqlite3WhereIsDistinct(pWInfo);
8148 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8149 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
8150 /* The optimizer is able to deliver rows in group by order so
8151 ** we do not have to sort. The OP_OpenEphemeral table will be
8152 ** cancelled later because we still need to use the pKeyInfo
8154 groupBySort = 0;
8155 }else{
8156 /* Rows are coming out in undetermined order. We have to push
8157 ** each row into a sorting index, terminate the first loop,
8158 ** then loop over the sorting index in order to get the output
8159 ** in sorted order
8161 int regBase;
8162 int regRecord;
8163 int nCol;
8164 int nGroupBy;
8166 #ifdef SQLITE_ENABLE_STMT_SCANSTATUS
8167 int addrExp; /* Address of OP_Explain instruction */
8168 #endif
8169 ExplainQueryPlan2(addrExp, (pParse, 0, "USE TEMP B-TREE FOR %s",
8170 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
8171 "DISTINCT" : "GROUP BY"
8174 groupBySort = 1;
8175 nGroupBy = pGroupBy->nExpr;
8176 nCol = nGroupBy;
8177 j = nGroupBy;
8178 for(i=0; i<pAggInfo->nColumn; i++){
8179 if( pAggInfo->aCol[i].iSorterColumn>=j ){
8180 nCol++;
8181 j++;
8184 regBase = sqlite3GetTempRange(pParse, nCol);
8185 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
8186 j = nGroupBy;
8187 pAggInfo->directMode = 1;
8188 for(i=0; i<pAggInfo->nColumn; i++){
8189 struct AggInfo_col *pCol = &pAggInfo->aCol[i];
8190 if( pCol->iSorterColumn>=j ){
8191 sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
8192 j++;
8195 pAggInfo->directMode = 0;
8196 regRecord = sqlite3GetTempReg(pParse);
8197 sqlite3VdbeScanStatusCounters(v, addrExp, 0, sqlite3VdbeCurrentAddr(v));
8198 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
8199 sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
8200 sqlite3VdbeScanStatusRange(v, addrExp, sqlite3VdbeCurrentAddr(v)-2, -1);
8201 sqlite3ReleaseTempReg(pParse, regRecord);
8202 sqlite3ReleaseTempRange(pParse, regBase, nCol);
8203 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8204 sqlite3WhereEnd(pWInfo);
8205 pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
8206 sortOut = sqlite3GetTempReg(pParse);
8207 sqlite3VdbeScanStatusCounters(v, addrExp, sqlite3VdbeCurrentAddr(v), 0);
8208 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
8209 sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
8210 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
8211 pAggInfo->useSortingIdx = 1;
8212 sqlite3VdbeScanStatusRange(v, addrExp, -1, sortPTab);
8213 sqlite3VdbeScanStatusRange(v, addrExp, -1, pAggInfo->sortingIdx);
8216 /* If there are entries in pAgggInfo->aFunc[] that contain subexpressions
8217 ** that are indexed (and that were previously identified and tagged
8218 ** in optimizeAggregateUseOfIndexedExpr()) then those subexpressions
8219 ** must now be converted into a TK_AGG_COLUMN node so that the value
8220 ** is correctly pulled from the index rather than being recomputed. */
8221 if( pParse->pIdxEpr ){
8222 aggregateConvertIndexedExprRefToColumn(pAggInfo);
8223 #if TREETRACE_ENABLED
8224 if( sqlite3TreeTrace & 0x20 ){
8225 TREETRACE(0x20, pParse, p,
8226 ("AggInfo function expressions converted to reference index\n"));
8227 sqlite3TreeViewSelect(0, p, 0);
8228 printAggInfo(pAggInfo);
8230 #endif
8233 /* If the index or temporary table used by the GROUP BY sort
8234 ** will naturally deliver rows in the order required by the ORDER BY
8235 ** clause, cancel the ephemeral table open coded earlier.
8237 ** This is an optimization - the correct answer should result regardless.
8238 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
8239 ** disable this optimization for testing purposes. */
8240 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
8241 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
8243 sSort.pOrderBy = 0;
8244 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
8247 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
8248 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
8249 ** Then compare the current GROUP BY terms against the GROUP BY terms
8250 ** from the previous row currently stored in a0, a1, a2...
8252 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
8253 if( groupBySort ){
8254 sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
8255 sortOut, sortPTab);
8257 for(j=0; j<pGroupBy->nExpr; j++){
8258 if( groupBySort ){
8259 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
8260 }else{
8261 pAggInfo->directMode = 1;
8262 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
8265 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
8266 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
8267 addr1 = sqlite3VdbeCurrentAddr(v);
8268 sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
8270 /* Generate code that runs whenever the GROUP BY changes.
8271 ** Changes in the GROUP BY are detected by the previous code
8272 ** block. If there were no changes, this block is skipped.
8274 ** This code copies current group by terms in b0,b1,b2,...
8275 ** over to a0,a1,a2. It then calls the output subroutine
8276 ** and resets the aggregate accumulator registers in preparation
8277 ** for the next GROUP BY batch.
8279 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
8280 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
8281 VdbeComment((v, "output one row"));
8282 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
8283 VdbeComment((v, "check abort flag"));
8284 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
8285 VdbeComment((v, "reset accumulator"));
8287 /* Update the aggregate accumulators based on the content of
8288 ** the current row
8290 sqlite3VdbeJumpHere(v, addr1);
8291 updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
8292 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
8293 VdbeComment((v, "indicate data in accumulator"));
8295 /* End of the loop
8297 if( groupBySort ){
8298 sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
8299 VdbeCoverage(v);
8300 }else{
8301 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8302 sqlite3WhereEnd(pWInfo);
8303 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
8305 sqlite3ExprListDelete(db, pDistinct);
8307 /* Output the final row of result
8309 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
8310 VdbeComment((v, "output final row"));
8312 /* Jump over the subroutines
8314 sqlite3VdbeGoto(v, addrEnd);
8316 /* Generate a subroutine that outputs a single row of the result
8317 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
8318 ** is less than or equal to zero, the subroutine is a no-op. If
8319 ** the processing calls for the query to abort, this subroutine
8320 ** increments the iAbortFlag memory location before returning in
8321 ** order to signal the caller to abort.
8323 addrSetAbort = sqlite3VdbeCurrentAddr(v);
8324 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
8325 VdbeComment((v, "set abort flag"));
8326 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8327 sqlite3VdbeResolveLabel(v, addrOutputRow);
8328 addrOutputRow = sqlite3VdbeCurrentAddr(v);
8329 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
8330 VdbeCoverage(v);
8331 VdbeComment((v, "Groupby result generator entry point"));
8332 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8333 finalizeAggFunctions(pParse, pAggInfo);
8334 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
8335 selectInnerLoop(pParse, p, -1, &sSort,
8336 &sDistinct, pDest,
8337 addrOutputRow+1, addrSetAbort);
8338 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
8339 VdbeComment((v, "end groupby result generator"));
8341 /* Generate a subroutine that will reset the group-by accumulator
8343 sqlite3VdbeResolveLabel(v, addrReset);
8344 resetAccumulator(pParse, pAggInfo);
8345 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
8346 VdbeComment((v, "indicate accumulator empty"));
8347 sqlite3VdbeAddOp1(v, OP_Return, regReset);
8349 if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
8350 struct AggInfo_func *pF = &pAggInfo->aFunc[0];
8351 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
8353 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
8354 else {
8355 Table *pTab;
8356 if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
8357 /* If isSimpleCount() returns a pointer to a Table structure, then
8358 ** the SQL statement is of the form:
8360 ** SELECT count(*) FROM <tbl>
8362 ** where the Table structure returned represents table <tbl>.
8364 ** This statement is so common that it is optimized specially. The
8365 ** OP_Count instruction is executed either on the intkey table that
8366 ** contains the data for table <tbl> or on one of its indexes. It
8367 ** is better to execute the op on an index, as indexes are almost
8368 ** always spread across less pages than their corresponding tables.
8370 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
8371 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
8372 Index *pIdx; /* Iterator variable */
8373 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
8374 Index *pBest = 0; /* Best index found so far */
8375 Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
8377 sqlite3CodeVerifySchema(pParse, iDb);
8378 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
8380 /* Search for the index that has the lowest scan cost.
8382 ** (2011-04-15) Do not do a full scan of an unordered index.
8384 ** (2013-10-03) Do not count the entries in a partial index.
8386 ** In practice the KeyInfo structure will not be used. It is only
8387 ** passed to keep OP_OpenRead happy.
8389 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
8390 if( !p->pSrc->a[0].fg.notIndexed ){
8391 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
8392 if( pIdx->bUnordered==0
8393 && pIdx->szIdxRow<pTab->szTabRow
8394 && pIdx->pPartIdxWhere==0
8395 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
8397 pBest = pIdx;
8401 if( pBest ){
8402 iRoot = pBest->tnum;
8403 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
8406 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
8407 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
8408 if( pKeyInfo ){
8409 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
8411 assignAggregateRegisters(pParse, pAggInfo);
8412 sqlite3VdbeAddOp2(v, OP_Count, iCsr, AggInfoFuncReg(pAggInfo,0));
8413 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
8414 explainSimpleCount(pParse, pTab, pBest);
8415 }else{
8416 int regAcc = 0; /* "populate accumulators" flag */
8417 ExprList *pDistinct = 0;
8418 u16 distFlag = 0;
8419 int eDist;
8421 /* If there are accumulator registers but no min() or max() functions
8422 ** without FILTER clauses, allocate register regAcc. Register regAcc
8423 ** will contain 0 the first time the inner loop runs, and 1 thereafter.
8424 ** The code generated by updateAccumulator() uses this to ensure
8425 ** that the accumulator registers are (a) updated only once if
8426 ** there are no min() or max functions or (b) always updated for the
8427 ** first row visited by the aggregate, so that they are updated at
8428 ** least once even if the FILTER clause means the min() or max()
8429 ** function visits zero rows. */
8430 if( pAggInfo->nAccumulator ){
8431 for(i=0; i<pAggInfo->nFunc; i++){
8432 if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
8433 continue;
8435 if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
8436 break;
8439 if( i==pAggInfo->nFunc ){
8440 regAcc = ++pParse->nMem;
8441 sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
8443 }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
8444 assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
8445 pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
8446 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
8448 assignAggregateRegisters(pParse, pAggInfo);
8450 /* This case runs if the aggregate has no GROUP BY clause. The
8451 ** processing is much simpler since there is only a single row
8452 ** of output.
8454 assert( p->pGroupBy==0 );
8455 resetAccumulator(pParse, pAggInfo);
8457 /* If this query is a candidate for the min/max optimization, then
8458 ** minMaxFlag will have been previously set to either
8459 ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
8460 ** be an appropriate ORDER BY expression for the optimization.
8462 assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
8463 assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
8465 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8466 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
8467 pDistinct, p, minMaxFlag|distFlag, 0);
8468 if( pWInfo==0 ){
8469 goto select_end;
8471 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8472 eDist = sqlite3WhereIsDistinct(pWInfo);
8473 updateAccumulator(pParse, regAcc, pAggInfo, eDist);
8474 if( eDist!=WHERE_DISTINCT_NOOP ){
8475 struct AggInfo_func *pF = pAggInfo->aFunc;
8476 if( pF ){
8477 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
8481 if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
8482 if( minMaxFlag ){
8483 sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
8485 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8486 sqlite3WhereEnd(pWInfo);
8487 finalizeAggFunctions(pParse, pAggInfo);
8490 sSort.pOrderBy = 0;
8491 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
8492 selectInnerLoop(pParse, p, -1, 0, 0,
8493 pDest, addrEnd, addrEnd);
8495 sqlite3VdbeResolveLabel(v, addrEnd);
8497 } /* endif aggregate query */
8499 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
8500 explainTempTable(pParse, "DISTINCT");
8503 /* If there is an ORDER BY clause, then we need to sort the results
8504 ** and send them to the callback one by one.
8506 if( sSort.pOrderBy ){
8507 assert( p->pEList==pEList );
8508 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
8511 /* Jump here to skip this query
8513 sqlite3VdbeResolveLabel(v, iEnd);
8515 /* The SELECT has been coded. If there is an error in the Parse structure,
8516 ** set the return code to 1. Otherwise 0. */
8517 rc = (pParse->nErr>0);
8519 /* Control jumps to here if an error is encountered above, or upon
8520 ** successful coding of the SELECT.
8522 select_end:
8523 assert( db->mallocFailed==0 || db->mallocFailed==1 );
8524 assert( db->mallocFailed==0 || pParse->nErr!=0 );
8525 sqlite3ExprListDelete(db, pMinMaxOrderBy);
8526 #ifdef SQLITE_DEBUG
8527 if( pAggInfo && !db->mallocFailed ){
8528 for(i=0; i<pAggInfo->nColumn; i++){
8529 Expr *pExpr = pAggInfo->aCol[i].pCExpr;
8530 if( pExpr==0 ) continue;
8531 assert( pExpr->pAggInfo==pAggInfo );
8532 assert( pExpr->iAgg==i );
8534 for(i=0; i<pAggInfo->nFunc; i++){
8535 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
8536 assert( pExpr!=0 );
8537 assert( pExpr->pAggInfo==pAggInfo );
8538 assert( pExpr->iAgg==i );
8541 #endif
8543 #if TREETRACE_ENABLED
8544 TREETRACE(0x1,pParse,p,("end processing\n"));
8545 if( (sqlite3TreeTrace & 0x40000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
8546 sqlite3TreeViewSelect(0, p, 0);
8548 #endif
8549 ExplainQueryPlanPop(pParse);
8550 return rc;