interplane.Get Omega
Read in your language

sqlite

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

Brought by drakestapleton

branch master Branches Tags History

sqlite / src / select.c

9303 lines · 346326 bytes Raw Blame History
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.
10**
11*************************************************************************
12** This file contains C code routines that are called by the parser
13** to handle SELECT statements in SQLite.
14*/
15#include "sqliteInt.h"
16
17/*
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.
21*/
22typedef struct DistinctCtx DistinctCtx;
23struct DistinctCtx {
24 u8 isTnct; /* 0: Not distinct. 1: DISTINCT 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 */
28};
29
30/*
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.
33**
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:
37**
38** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10;
39**
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.
43**
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.
47*/
48typedef struct SortCtx SortCtx;
49struct 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
72};
73#define SORTFLAG_UseSorter 0x01 /* Use SorterOpen instead of OpenEphemeral */
74
75/*
76** Delete all the content of a Select structure. Deallocate the structure
77** itself depending on the value of bFree
78**
79** If bFree==1, call sqlite3DbFree() on the p object.
80** If bFree==0, Leave the first Select object unfreed
81*/
82static 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);
97 }
98 while( p->pWin ){
99 assert( p->pWin->ppThis==&p->pWin );
100 sqlite3WindowUnlinkFromSelect(p->pWin);
101 }
102#endif
103 if( bFree ) sqlite3DbNNFreeNN(db, p);
104 p = pPrior;
105 bFree = 1;
106 }
107}
108
109/*
110** Initialize a SelectDest structure.
111*/
112void 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;
119}
120
121
122/*
123** Allocate a new Select structure and return a pointer to that
124** structure.
125*/
126Select *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 */
136){
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;
143 }
144 if( pEList==0 ){
145 pEList = sqlite3ExprListAppend(pParse, 0,
146 sqlite3Expr(pParse->db,TK_ASTERISK,0));
147 }
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->nSelectRow = 0;
155 if( pSrc==0 ) pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);
156 pNew->pSrc = pSrc;
157 pNew->pWhere = pWhere;
158 pNew->pGroupBy = pGroupBy;
159 pNew->pHaving = pHaving;
160 pNew->pOrderBy = pOrderBy;
161 pNew->pPrior = 0;
162 pNew->pNext = 0;
163 pNew->pLimit = pLimit;
164 pNew->pWith = 0;
165#ifndef SQLITE_OMIT_WINDOWFUNC
166 pNew->pWin = 0;
167 pNew->pWinDefn = 0;
168#endif
169 if( pParse->db->mallocFailed ) {
170 clearSelect(pParse->db, pNew, pNew!=&standin);
171 pAllocated = 0;
172 }else{
173 assert( pNew->pSrc!=0 || pParse->nErr>0 );
174 }
175 return pAllocated;
176}
177
178
179/*
180** Delete the given Select structure and all of its substructures.
181*/
182void sqlite3SelectDelete(sqlite3 *db, Select *p){
183 if( OK_IF_ALWAYS_TRUE(p) ) clearSelect(db, p, 1);
184}
185void sqlite3SelectDeleteGeneric(sqlite3 *db, void *p){
186 if( ALWAYS(p) ) clearSelect(db, (Select*)p, 1);
187}
188
189/*
190** Return a pointer to the right-most SELECT statement in a compound.
191*/
192static Select *findRightmost(Select *p){
193 while( p->pNext ) p = p->pNext;
194 return p;
195}
196
197/*
198** Given 1 to 3 identifiers preceding the JOIN keyword, determine the
199** type of join. Return an integer constant that expresses that type
200** in terms of the following bit values:
201**
202** JT_INNER
203** JT_CROSS
204** JT_OUTER
205** JT_NATURAL
206** JT_LEFT
207** JT_RIGHT
208**
209** A full outer join is the combination of JT_LEFT and JT_RIGHT.
210**
211** If an illegal or unsupported join type is seen, then still return
212** a join type, but put an error in the pParse structure.
213**
214** These are the valid join types:
215**
216**
217** pA pB pC Return Value
218** ------- ----- ----- ------------
219** CROSS - - JT_CROSS
220** INNER - - JT_INNER
221** LEFT - - JT_LEFT|JT_OUTER
222** LEFT OUTER - JT_LEFT|JT_OUTER
223** RIGHT - - JT_RIGHT|JT_OUTER
224** RIGHT OUTER - JT_RIGHT|JT_OUTER
225** FULL - - JT_LEFT|JT_RIGHT|JT_OUTER
226** FULL OUTER - JT_LEFT|JT_RIGHT|JT_OUTER
227** NATURAL INNER - JT_NATURAL|JT_INNER
228** NATURAL LEFT - JT_NATURAL|JT_LEFT|JT_OUTER
229** NATURAL LEFT OUTER JT_NATURAL|JT_LEFT|JT_OUTER
230** NATURAL RIGHT - JT_NATURAL|JT_RIGHT|JT_OUTER
231** NATURAL RIGHT OUTER JT_NATURAL|JT_RIGHT|JT_OUTER
232** NATURAL FULL - JT_NATURAL|JT_LEFT|JT_RIGHT
233** NATURAL FULL OUTER JT_NATRUAL|JT_LEFT|JT_RIGHT
234**
235** To preserve historical compatibly, SQLite also accepts a variety
236** of other non-standard and in many cases nonsensical join types.
237** This routine makes as much sense at it can from the nonsense join
238** type and returns a result. Examples of accepted nonsense join types
239** include but are not limited to:
240**
241** INNER CROSS JOIN -> same as JOIN
242** NATURAL CROSS JOIN -> same as NATURAL JOIN
243** OUTER LEFT JOIN -> same as LEFT JOIN
244** LEFT NATURAL JOIN -> same as NATURAL LEFT JOIN
245** LEFT RIGHT JOIN -> same as FULL JOIN
246** RIGHT OUTER FULL JOIN -> same as FULL JOIN
247** CROSS CROSS CROSS JOIN -> same as JOIN
248**
249** The only restrictions on the join type name are:
250**
251** * "INNER" cannot appear together with "OUTER", "LEFT", "RIGHT",
252** or "FULL".
253**
254** * "CROSS" cannot appear together with "OUTER", "LEFT", "RIGHT,
255** or "FULL".
256**
257** * If "OUTER" is present then there must also be one of
258** "LEFT", "RIGHT", or "FULL"
259*/
260int sqlite3JoinType(Parse *pParse, Token *pA, Token *pB, Token *pC){
261 int jointype = 0;
262 Token *apAll[3];
263 Token *p;
264 /* 0123456789 123456789 123456789 123 */
265 static const char zKeyText[] = "naturaleftouterightfullinnercross";
266 static const struct {
267 u8 i; /* Beginning of keyword text in zKeyText[] */
268 u8 nChar; /* Length of the keyword in characters */
269 u8 code; /* Join type mask */
270 } aKeyword[] = {
271 /* (0) natural */ { 0, 7, JT_NATURAL },
272 /* (1) left */ { 6, 4, JT_LEFT|JT_OUTER },
273 /* (2) outer */ { 10, 5, JT_OUTER },
274 /* (3) right */ { 14, 5, JT_RIGHT|JT_OUTER },
275 /* (4) full */ { 19, 4, JT_LEFT|JT_RIGHT|JT_OUTER },
276 /* (5) inner */ { 23, 5, JT_INNER },
277 /* (6) cross */ { 28, 5, JT_INNER|JT_CROSS },
278 };
279 int i, j;
280 apAll[0] = pA;
281 apAll[1] = pB;
282 apAll[2] = pC;
283 for(i=0; i<3 && apAll[i]; i++){
284 p = apAll[i];
285 for(j=0; j<ArraySize(aKeyword); j++){
286 if( p->n==aKeyword[j].nChar
287 && sqlite3StrNICmp((char*)p->z, &zKeyText[aKeyword[j].i], p->n)==0 ){
288 jointype |= aKeyword[j].code;
289 break;
290 }
291 }
292 testcase( j==0 || j==1 || j==2 || j==3 || j==4 || j==5 || j==6 );
293 if( j>=ArraySize(aKeyword) ){
294 jointype |= JT_ERROR;
295 break;
296 }
297 }
298 if(
299 (jointype & (JT_INNER|JT_OUTER))==(JT_INNER|JT_OUTER) ||
300 (jointype & JT_ERROR)!=0 ||
301 (jointype & (JT_OUTER|JT_LEFT|JT_RIGHT))==JT_OUTER
302 ){
303 const char *zSp1 = " ";
304 const char *zSp2 = " ";
305 if( pB==0 ){ zSp1++; }
306 if( pC==0 ){ zSp2++; }
307 sqlite3ErrorMsg(pParse, "unknown join type: "
308 "%T%s%T%s%T", pA, zSp1, pB, zSp2, pC);
309 jointype = JT_INNER;
310 }
311 return jointype;
312}
313
314/*
315** Return the index of a column in a table. Return -1 if the column
316** is not contained in the table.
317*/
318int sqlite3ColumnIndex(Table *pTab, const char *zCol){
319 int i;
320 u8 h;
321 const Column *aCol;
322 int nCol;
323
324 h = sqlite3StrIHash(zCol);
325 aCol = pTab->aCol;
326 nCol = pTab->nCol;
327
328 /* See if the aHx gives us a lucky match */
329 i = pTab->aHx[h % sizeof(pTab->aHx)];
330 assert( i<nCol );
331 if( aCol[i].hName==h
332 && sqlite3StrICmp(aCol[i].zCnName, zCol)==0
333 ){
334 return i;
335 }
336
337 /* No lucky match from the hash table. Do a full search. */
338 i = 0;
339 while( 1 /*exit-by-break*/ ){
340 if( aCol[i].hName==h
341 && sqlite3StrICmp(aCol[i].zCnName, zCol)==0
342 ){
343 return i;
344 }
345 i++;
346 if( i>=nCol ) break;
347 }
348 return -1;
349}
350
351/*
352** Mark a subquery result column as having been used.
353*/
354void sqlite3SrcItemColumnUsed(SrcItem *pItem, int iCol){
355 assert( pItem!=0 );
356 assert( (int)pItem->fg.isNestedFrom == IsNestedFrom(pItem) );
357 if( pItem->fg.isNestedFrom ){
358 ExprList *pResults;
359 assert( pItem->fg.isSubquery );
360 assert( pItem->u4.pSubq!=0 );
361 assert( pItem->u4.pSubq->pSelect!=0 );
362 pResults = pItem->u4.pSubq->pSelect->pEList;
363 assert( pResults!=0 );
364 assert( iCol>=0 && iCol<pResults->nExpr );
365 pResults->a[iCol].fg.bUsed = 1;
366 }
367}
368
369/*
370** Search the tables iStart..iEnd (inclusive) in pSrc, looking for a
371** table that has a column named zCol. The search is left-to-right.
372** The first match found is returned.
373**
374** When found, set *piTab and *piCol to the table index and column index
375** of the matching column and return TRUE.
376**
377** If not found, return FALSE.
378*/
379static int tableAndColumnIndex(
380 SrcList *pSrc, /* Array of tables to search */
381 int iStart, /* First member of pSrc->a[] to check */
382 int iEnd, /* Last member of pSrc->a[] to check */
383 const char *zCol, /* Name of the column we are looking for */
384 int *piTab, /* Write index of pSrc->a[] here */
385 int *piCol, /* Write index of pSrc->a[*piTab].pSTab->aCol[] here */
386 int bIgnoreHidden /* Ignore hidden columns */
387){
388 int i; /* For looping over tables in pSrc */
389 int iCol; /* Index of column matching zCol */
390
391 assert( iEnd<pSrc->nSrc );
392 assert( iStart>=0 );
393 assert( (piTab==0)==(piCol==0) ); /* Both or neither are NULL */
394
395 for(i=iStart; i<=iEnd; i++){
396 iCol = sqlite3ColumnIndex(pSrc->a[i].pSTab, zCol);
397 if( iCol>=0
398 && (bIgnoreHidden==0 || IsHiddenColumn(&pSrc->a[i].pSTab->aCol[iCol])==0)
399 ){
400 if( piTab ){
401 sqlite3SrcItemColumnUsed(&pSrc->a[i], iCol);
402 *piTab = i;
403 *piCol = iCol;
404 }
405 return 1;
406 }
407 }
408 return 0;
409}
410
411/*
412** Set the EP_OuterON property on all terms of the given expression.
413** And set the Expr.w.iJoin to iTable for every term in the
414** expression.
415**
416** The EP_OuterON property is used on terms of an expression to tell
417** the OUTER JOIN processing logic that this term is part of the
418** join restriction specified in the ON or USING clause and not a part
419** of the more general WHERE clause. These terms are moved over to the
420** WHERE clause during join processing but we need to remember that they
421** originated in the ON or USING clause.
422**
423** The Expr.w.iJoin tells the WHERE clause processing that the
424** expression depends on table w.iJoin even if that table is not
425** explicitly mentioned in the expression. That information is needed
426** for cases like this:
427**
428** SELECT * FROM t1 LEFT JOIN t2 ON t1.a=t2.b AND t1.x=5
429**
430** The where clause needs to defer the handling of the t1.x=5
431** term until after the t2 loop of the join. In that way, a
432** NULL t2 row will be inserted whenever t1.x!=5. If we do not
433** defer the handling of t1.x=5, it will be processed immediately
434** after the t1 loop and rows with t1.x!=5 will never appear in
435** the output, which is incorrect.
436*/
437void sqlite3SetJoinExpr(Expr *p, int iTable, u32 joinFlag){
438 assert( joinFlag==EP_OuterON || joinFlag==EP_InnerON );
439 while( p ){
440 ExprSetProperty(p, joinFlag);
441 assert( !ExprHasProperty(p, EP_TokenOnly|EP_Reduced) );
442 ExprSetVVAProperty(p, EP_NoReduce);
443 p->w.iJoin = iTable;
444 if( ExprUseXList(p) ){
445 if( p->x.pList ){
446 int i;
447 for(i=0; i<p->x.pList->nExpr; i++){
448 sqlite3SetJoinExpr(p->x.pList->a[i].pExpr, iTable, joinFlag);
449 }
450 }
451 }
452 sqlite3SetJoinExpr(p->pLeft, iTable, joinFlag);
453 p = p->pRight;
454 }
455}
456
457/* Undo the work of sqlite3SetJoinExpr(). This is used when a LEFT JOIN
458** is simplified into an ordinary JOIN, and when an ON expression is
459** "pushed down" into the WHERE clause of a subquery.
460**
461** Convert every term that is marked with EP_OuterON and w.iJoin==iTable into
462** an ordinary term that omits the EP_OuterON mark. Or if iTable<0, then
463** just clear every EP_OuterON and EP_InnerON mark from the expression tree.
464**
465** If nullable is true, that means that Expr p might evaluate to NULL even
466** if it is a reference to a NOT NULL column. This can happen, for example,
467** if the table that p references is on the left side of a RIGHT JOIN.
468** If nullable is true, then take care to not remove the EP_CanBeNull bit.
469** See forum thread https://sqlite.org/forum/forumpost/b40696f50145d21c
470*/
471static void unsetJoinExpr(Expr *p, int iTable, int nullable){
472 while( p ){
473 if( iTable<0 || (ExprHasProperty(p, EP_OuterON) && p->w.iJoin==iTable) ){
474 ExprClearProperty(p, EP_OuterON|EP_InnerON);
475 if( iTable>=0 ) ExprSetProperty(p, EP_InnerON);
476 }
477 if( p->op==TK_COLUMN && p->iTable==iTable && !nullable ){
478 ExprClearProperty(p, EP_CanBeNull);
479 }
480 if( p->op==TK_FUNCTION ){
481 assert( ExprUseXList(p) );
482 assert( p->pLeft==0 );
483 if( p->x.pList ){
484 int i;
485 for(i=0; i<p->x.pList->nExpr; i++){
486 unsetJoinExpr(p->x.pList->a[i].pExpr, iTable, nullable);
487 }
488 }
489 }
490 unsetJoinExpr(p->pLeft, iTable, nullable);
491 p = p->pRight;
492 }
493}
494
495/*
496** Tree walker expression callback for clearOuterOnExpr().
497**
498** If the Expr node is marked as coming from an outer join for
499** table pWalker->u.iCur, then clear its join markers completely.
500*/
501static int clearOuterOnExprCb(Walker *pWalker, Expr *p){
502 if( ExprHasProperty(p, EP_OuterON) && p->w.iJoin==pWalker->u.iCur ){
503 ExprClearProperty(p, EP_OuterON|EP_InnerON);
504 }
505 return WRC_Continue;
506}
507
508/*
509** Remove the EP_OuterON mark, without substituting EP_InnerON, from every
510** term of the expression tree p that is marked EP_OuterON with w.iJoin==iTable.
511** The resulting terms are ordinary WHERE-clause terms.
512**
513** This is used when table iTable was marked as an outer-join table only
514** because it was the left operand of a RIGHT JOIN (JT_LTORJ) and that
515** status has been removed by OUTER JOIN strength reduction.
516*/
517static void clearOuterOnExpr(Expr *p, int iTable){
518 Walker w;
519 memset(&w, 0, sizeof(w));
520 w.u.iCur = iTable;
521 w.xExprCallback = clearOuterOnExprCb;
522 w.xSelectCallback = 0;
523 sqlite3WalkExpr(&w,p);
524}
525
526/*
527** This routine processes the join information for a SELECT statement.
528**
529** * A NATURAL join is converted into a USING join. After that, we
530** do not need to be concerned with NATURAL joins and we only have
531** think about USING joins.
532**
533** * ON and USING clauses result in extra terms being added to the
534** WHERE clause to enforce the specified constraints. The extra
535** WHERE clause terms will be tagged with EP_OuterON or
536** EP_InnerON so that we know that they originated in ON/USING.
537**
538** The terms of a FROM clause are contained in the Select.pSrc structure.
539** The left most table is the first entry in Select.pSrc. The right-most
540** table is the last entry. The join operator is held in the entry to
541** the right. Thus entry 1 contains the join operator for the join between
542** entries 0 and 1. Any ON or USING clauses associated with the join are
543** also attached to the right entry.
544**
545** This routine returns the number of errors encountered.
546*/
547static int sqlite3ProcessJoin(Parse *pParse, Select *p){
548 SrcList *pSrc; /* All tables in the FROM clause */
549 int i, j; /* Loop counters */
550 SrcItem *pLeft; /* Left table being joined */
551 SrcItem *pRight; /* Right table being joined */
552 int bSeenTFunc = 0; /* True if have seen table-valued function */
553
554 pSrc = p->pSrc;
555 if( pSrc->nSrc<=1 ) return 0;
556 pLeft = &pSrc->a[0];
557 pRight = &pLeft[1];
558 for(i=0; i<pSrc->nSrc-1; i++, pRight++, pLeft++){
559 Table *pRightTab = pRight->pSTab;
560 u32 joinType;
561
562 if( NEVER(pLeft->pSTab==0 || pRightTab==0) ) continue;
563 joinType = (pRight->fg.jointype & JT_OUTER)!=0 ? EP_OuterON : EP_InnerON;
564
565 /* If this is a NATURAL join, synthesize an appropriate USING clause
566 ** to specify which columns should be joined.
567 */
568 if( pRight->fg.jointype & JT_NATURAL ){
569 IdList *pUsing = 0;
570 if( pRight->fg.isUsing || pRight->u3.pOn ){
571 sqlite3ErrorMsg(pParse, "a NATURAL join may not have "
572 "an ON or USING clause", 0);
573 return 1;
574 }
575 for(j=0; j<pRightTab->nCol; j++){
576 char *zName; /* Name of column in the right table */
577
578 if( IsHiddenColumn(&pRightTab->aCol[j]) ) continue;
579 zName = pRightTab->aCol[j].zCnName;
580 if( tableAndColumnIndex(pSrc, 0, i, zName, 0, 0, 1) ){
581 pUsing = sqlite3IdListAppend(pParse, pUsing, 0);
582 if( pUsing ){
583 assert( pUsing->nId>0 );
584 assert( pUsing->a[pUsing->nId-1].zName==0 );
585 pUsing->a[pUsing->nId-1].zName = sqlite3DbStrDup(pParse->db, zName);
586 }
587 }
588 }
589 if( pUsing ){
590 pRight->fg.isUsing = 1;
591 pRight->fg.isSynthUsing = 1;
592 pRight->u3.pUsing = pUsing;
593 }
594 if( pParse->nErr ) return 1;
595 }
596
597 /* Create extra terms on the WHERE clause for each column named
598 ** in the USING clause. Example: If the two tables to be joined are
599 ** A and B and the USING clause names X, Y, and Z, then add this
600 ** to the WHERE clause: A.X=B.X AND A.Y=B.Y AND A.Z=B.Z
601 ** Report an error if any column mentioned in the USING clause is
602 ** not contained in both tables to be joined.
603 */
604 if( pRight->fg.isUsing ){
605 IdList *pList = pRight->u3.pUsing;
606 sqlite3 *db = pParse->db;
607 assert( pList!=0 );
608 for(j=0; j<pList->nId; j++){
609 char *zName; /* Name of the term in the USING clause */
610 int iLeft; /* Table on the left with matching column name */
611 int iLeftCol; /* Column number of matching column on the left */
612 int iRightCol; /* Column number of matching column on the right */
613 Expr *pE1; /* Reference to the column on the LEFT of the join */
614 Expr *pE2; /* Reference to the column on the RIGHT of the join */
615 Expr *pEq; /* Equality constraint. pE1 == pE2 */
616
617 zName = pList->a[j].zName;
618 iRightCol = sqlite3ColumnIndex(pRightTab, zName);
619 if( iRightCol<0
620 || tableAndColumnIndex(pSrc, 0, i, zName, &iLeft, &iLeftCol,
621 pRight->fg.isSynthUsing)==0
622 ){
623 sqlite3ErrorMsg(pParse, "cannot join using column %s - column "
624 "not present in both tables", zName);
625 return 1;
626 }
627 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
628 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
629 if( (pSrc->a[0].fg.jointype & JT_LTORJ)!=0 && pParse->nErr==0 ){
630 /* This branch runs if the query contains one or more RIGHT or FULL
631 ** JOINs. If only a single table on the left side of this join
632 ** contains the zName column, then this branch is a no-op.
633 ** But if there are two or more tables on the left side
634 ** of the join, construct a coalesce() function that gathers all
635 ** such tables. Raise an error if more than one of those references
636 ** to zName is not also within a prior USING clause.
637 **
638 ** We really ought to raise an error if there are two or more
639 ** non-USING references to zName on the left of an INNER or LEFT
640 ** JOIN. But older versions of SQLite do not do that, so we avoid
641 ** adding a new error so as to not break legacy applications.
642 */
643 ExprList *pFuncArgs = 0; /* Arguments to the coalesce() */
644 static const Token tkCoalesce = { "coalesce", 8 };
645 assert( pE1!=0 );
646 ExprSetProperty(pE1, EP_CanBeNull);
647 while( tableAndColumnIndex(pSrc, iLeft+1, i, zName, &iLeft, &iLeftCol,
648 pRight->fg.isSynthUsing)!=0 ){
649 if( pSrc->a[iLeft].fg.isUsing==0
650 || sqlite3IdListIndex(pSrc->a[iLeft].u3.pUsing, zName)<0
651 ){
652 sqlite3ErrorMsg(pParse, "ambiguous reference to %s in USING()",
653 zName);
654 break;
655 }
656 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
657 pE1 = sqlite3CreateColumnExpr(db, pSrc, iLeft, iLeftCol);
658 sqlite3SrcItemColumnUsed(&pSrc->a[iLeft], iLeftCol);
659 }
660 if( pFuncArgs ){
661 pFuncArgs = sqlite3ExprListAppend(pParse, pFuncArgs, pE1);
662 pE1 = sqlite3ExprFunction(pParse, pFuncArgs, &tkCoalesce, 0);
663 if( pE1 ){
664 pE1->affExpr = SQLITE_AFF_DEFER;
665 }
666 }
667 }else if( (pSrc->a[i+1].fg.jointype & JT_LEFT)!=0 && pParse->nErr==0 ){
668 assert( pE1!=0 );
669 ExprSetProperty(pE1, EP_CanBeNull);
670 }
671 pE2 = sqlite3CreateColumnExpr(db, pSrc, i+1, iRightCol);
672 sqlite3SrcItemColumnUsed(pRight, iRightCol);
673 pEq = sqlite3PExpr(pParse, TK_EQ, pE1, pE2);
674 assert( pE2!=0 || pEq==0 );
675 if( pEq ){
676 ExprSetProperty(pEq, joinType);
677 assert( !ExprHasProperty(pEq, EP_TokenOnly|EP_Reduced) );
678 ExprSetVVAProperty(pEq, EP_NoReduce);
679 pEq->w.iJoin = pE2->iTable;
680 }
681 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pEq);
682 }
683 }
684
685 /* Add the ON clause to the end of the WHERE clause, connected by
686 ** an AND operator.
687 */
688 else if( pRight->u3.pOn ){
689 sqlite3SetJoinExpr(pRight->u3.pOn, pRight->iCursor, joinType);
690 p->pWhere = sqlite3ExprAnd(pParse, p->pWhere, pRight->u3.pOn);
691 pRight->u3.pOn = 0;
692 pRight->fg.isOn = 1;
693 p->selFlags |= SF_OnToWhere;
694 }
695
696 if( bSeenTFunc==0 ){
697 bSeenTFunc = (pLeft->fg.isTabFunc && pLeft->u1.pFuncArg);
698 }
699
700 /* We also need to call sqlite3SelectCheckOnClauses() to verify that
701 ** table-valued function arguments do not illegally refer to any tables to
702 ** their right. This test is required if either (a) there is a RIGHT JOIN
703 ** in the SrcList, or (b) there is a LEFT JOIN to the right of a
704 ** table-valued function. */
705 if( (pRight->fg.isTabFunc && joinType==EP_OuterON && pRight->u1.pFuncArg)
706 || (bSeenTFunc && joinType==EP_OuterON)
707 ){
708 p->selFlags |= SF_OnToWhere;
709 }
710 }
711 return 0;
712}
713
714/*
715** An instance of this object holds information (beyond pParse and pSelect)
716** needed to load the next result row that is to be added to the sorter.
717*/
718typedef struct RowLoadInfo RowLoadInfo;
719struct RowLoadInfo {
720 int regResult; /* Store results in array of registers here */
721 u8 ecelFlags; /* Flag argument to ExprCodeExprList() */
722#ifdef SQLITE_ENABLE_SORTER_REFERENCES
723 ExprList *pExtra; /* Extra columns needed by sorter refs */
724 int regExtraResult; /* Where to load the extra columns */
725#endif
726};
727
728/*
729** This routine does the work of loading query data into an array of
730** registers so that it can be added to the sorter.
731*/
732static void innerLoopLoadRow(
733 Parse *pParse, /* Statement under construction */
734 Select *pSelect, /* The query being coded */
735 RowLoadInfo *pInfo /* Info needed to complete the row load */
736){
737 sqlite3ExprCodeExprList(pParse, pSelect->pEList, pInfo->regResult,
738 0, pInfo->ecelFlags);
739#ifdef SQLITE_ENABLE_SORTER_REFERENCES
740 if( pInfo->pExtra ){
741 sqlite3ExprCodeExprList(pParse, pInfo->pExtra, pInfo->regExtraResult, 0, 0);
742 sqlite3ExprListDelete(pParse->db, pInfo->pExtra);
743 }
744#endif
745}
746
747/*
748** Code the OP_MakeRecord instruction that generates the entry to be
749** added into the sorter.
750**
751** Return the register in which the result is stored.
752*/
753static int makeSorterRecord(
754 Parse *pParse,
755 SortCtx *pSort,
756 Select *pSelect,
757 int regBase,
758 int nBase
759){
760 int nOBSat = pSort->nOBSat;
761 Vdbe *v = pParse->pVdbe;
762 int regOut = ++pParse->nMem;
763 if( pSort->pDeferredRowLoad ){
764 innerLoopLoadRow(pParse, pSelect, pSort->pDeferredRowLoad);
765 }
766 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase+nOBSat, nBase-nOBSat, regOut);
767 return regOut;
768}
769
770/*
771** Generate code that will push the record in registers regData
772** through regData+nData-1 onto the sorter.
773*/
774static void pushOntoSorter(
775 Parse *pParse, /* Parser context */
776 SortCtx *pSort, /* Information about the ORDER BY clause */
777 Select *pSelect, /* The whole SELECT statement */
778 int regData, /* First register holding data to be sorted */
779 int regOrigData, /* First register holding data before packing */
780 int nData, /* Number of elements in the regData data array */
781 int nPrefixReg /* No. of reg prior to regData available for use */
782){
783 Vdbe *v = pParse->pVdbe; /* Stmt under construction */
784 int bSeq = ((pSort->sortFlags & SORTFLAG_UseSorter)==0);
785 int nExpr = pSort->pOrderBy->nExpr; /* No. of ORDER BY terms */
786 int nBase = nExpr + bSeq + nData; /* Fields in sorter record */
787 int regBase; /* Regs for sorter record */
788 int regRecord = 0; /* Assembled sorter record */
789 int nOBSat = pSort->nOBSat; /* ORDER BY terms to skip */
790 int op; /* Opcode to add sorter record to sorter */
791 int iLimit; /* LIMIT counter */
792 int iSkip = 0; /* End of the sorter insert loop */
793
794 assert( bSeq==0 || bSeq==1 );
795
796 /* Three cases:
797 ** (1) The data to be sorted has already been packed into a Record
798 ** by a prior OP_MakeRecord. In this case nData==1 and regData
799 ** will be completely unrelated to regOrigData.
800 ** (2) All output columns are included in the sort record. In that
801 ** case regData==regOrigData.
802 ** (3) Some output columns are omitted from the sort record due to
803 ** the SQLITE_ENABLE_SORTER_REFERENCES optimization, or due to the
804 ** SQLITE_ECEL_OMITREF optimization, or due to the
805 ** SortCtx.pDeferredRowLoad optimization. In any of these cases
806 ** regOrigData is 0 to prevent this routine from trying to copy
807 ** values that might not yet exist.
808 */
809 assert( nData==1 || regData==regOrigData || regOrigData==0 );
810
811#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
812 pSort->addrPush = sqlite3VdbeCurrentAddr(v);
813#endif
814
815 if( nPrefixReg ){
816 assert( nPrefixReg==nExpr+bSeq );
817 regBase = regData - nPrefixReg;
818 }else{
819 regBase = pParse->nMem + 1;
820 pParse->nMem += nBase;
821 }
822 assert( pSelect->iOffset==0 || pSelect->iLimit!=0 );
823 iLimit = pSelect->iOffset ? pSelect->iOffset+1 : pSelect->iLimit;
824 pSort->labelDone = sqlite3VdbeMakeLabel(pParse);
825 sqlite3ExprCodeExprList(pParse, pSort->pOrderBy, regBase, regOrigData,
826 SQLITE_ECEL_DUP | (regOrigData? SQLITE_ECEL_REF : 0));
827 if( bSeq ){
828 sqlite3VdbeAddOp2(v, OP_Sequence, pSort->iECursor, regBase+nExpr);
829 }
830 if( nPrefixReg==0 && nData>0 ){
831 sqlite3ExprCodeMove(pParse, regData, regBase+nExpr+bSeq, nData);
832 }
833 if( nOBSat>0 ){
834 int regPrevKey; /* The first nOBSat columns of the previous row */
835 int addrFirst; /* Address of the OP_IfNot opcode */
836 int addrJmp; /* Address of the OP_Jump opcode */
837 VdbeOp *pOp; /* Opcode that opens the sorter */
838 int nKey; /* Number of sorting key columns, including OP_Sequence */
839 KeyInfo *pKI; /* Original KeyInfo on the sorter table */
840
841 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
842 regPrevKey = pParse->nMem+1;
843 pParse->nMem += pSort->nOBSat;
844 nKey = nExpr - pSort->nOBSat + bSeq;
845 if( bSeq ){
846 addrFirst = sqlite3VdbeAddOp1(v, OP_IfNot, regBase+nExpr);
847 }else{
848 addrFirst = sqlite3VdbeAddOp1(v, OP_SequenceTest, pSort->iECursor);
849 }
850 VdbeCoverage(v);
851 sqlite3VdbeAddOp3(v, OP_Compare, regPrevKey, regBase, pSort->nOBSat);
852 pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
853 if( pParse->db->mallocFailed ) return;
854 pOp->p2 = nKey + nData;
855 pKI = pOp->p4.pKeyInfo;
856 memset(pKI->aSortFlags, 0, pKI->nKeyField); /* Makes OP_Jump testable */
857 sqlite3VdbeChangeP4(v, -1, (char*)pKI, P4_KEYINFO);
858 testcase( pKI->nAllField > pKI->nKeyField+2 );
859 pOp->p4.pKeyInfo = sqlite3KeyInfoFromExprList(pParse,pSort->pOrderBy,nOBSat,
860 pKI->nAllField-pKI->nKeyField-1);
861 pOp = 0; /* Ensure pOp not used after sqlite3VdbeAddOp3() */
862 addrJmp = sqlite3VdbeCurrentAddr(v);
863 sqlite3VdbeAddOp3(v, OP_Jump, addrJmp+1, 0, addrJmp+1); VdbeCoverage(v);
864 pSort->labelBkOut = sqlite3VdbeMakeLabel(pParse);
865 pSort->regReturn = ++pParse->nMem;
866 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
867 sqlite3VdbeAddOp1(v, OP_ResetSorter, pSort->iECursor);
868 if( iLimit ){
869 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, pSort->labelDone);
870 VdbeCoverage(v);
871 }
872 sqlite3VdbeJumpHere(v, addrFirst);
873 sqlite3ExprCodeMove(pParse, regBase, regPrevKey, pSort->nOBSat);
874 sqlite3VdbeJumpHere(v, addrJmp);
875 }
876 if( iLimit ){
877 /* At this point the values for the new sorter entry are stored
878 ** in an array of registers. They need to be composed into a record
879 ** and inserted into the sorter if either (a) there are currently
880 ** less than LIMIT+OFFSET items or (b) the new record is smaller than
881 ** the largest record currently in the sorter. If (b) is true and there
882 ** are already LIMIT+OFFSET items in the sorter, delete the largest
883 ** entry before inserting the new one. This way there are never more
884 ** than LIMIT+OFFSET items in the sorter.
885 **
886 ** If the new record does not need to be inserted into the sorter,
887 ** jump to the next iteration of the loop. If the pSort->labelOBLopt
888 ** value is not zero, then it is a label of where to jump. Otherwise,
889 ** just bypass the row insert logic. See the header comment on the
890 ** sqlite3WhereOrderByLimitOptLabel() function for additional info.
891 */
892 int iCsr = pSort->iECursor;
893 sqlite3VdbeAddOp2(v, OP_IfNotZero, iLimit, sqlite3VdbeCurrentAddr(v)+4);
894 VdbeCoverage(v);
895 sqlite3VdbeAddOp2(v, OP_Last, iCsr, 0);
896 iSkip = sqlite3VdbeAddOp4Int(v, OP_IdxLE,
897 iCsr, 0, regBase+nOBSat, nExpr-nOBSat);
898 VdbeCoverage(v);
899 sqlite3VdbeAddOp1(v, OP_Delete, iCsr);
900 }
901 if( regRecord==0 ){
902 regRecord = makeSorterRecord(pParse, pSort, pSelect, regBase, nBase);
903 }
904 if( pSort->sortFlags & SORTFLAG_UseSorter ){
905 op = OP_SorterInsert;
906 }else{
907 op = OP_IdxInsert;
908 }
909 sqlite3VdbeAddOp4Int(v, op, pSort->iECursor, regRecord,
910 regBase+nOBSat, nBase-nOBSat);
911 if( iSkip ){
912 sqlite3VdbeChangeP2(v, iSkip,
913 pSort->labelOBLopt ? pSort->labelOBLopt : sqlite3VdbeCurrentAddr(v));
914 }
915#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
916 pSort->addrPushEnd = sqlite3VdbeCurrentAddr(v)-1;
917#endif
918}
919
920/*
921** Add code to implement the OFFSET
922*/
923static void codeOffset(
924 Vdbe *v, /* Generate code into this VM */
925 int iOffset, /* Register holding the offset counter */
926 int iContinue /* Jump here to skip the current record */
927){
928 if( iOffset>0 ){
929 sqlite3VdbeAddOp3(v, OP_IfPos, iOffset, iContinue, 1); VdbeCoverage(v);
930 VdbeComment((v, "OFFSET"));
931 }
932}
933
934/*
935** Add code that will check to make sure the array of registers starting at
936** iMem form a distinct entry. This is used by both "SELECT DISTINCT ..." and
937** distinct aggregates ("SELECT count(DISTINCT <expr>) ..."). Three strategies
938** are available. Which is used depends on the value of parameter eTnctType,
939** as follows:
940**
941** WHERE_DISTINCT_UNORDERED/WHERE_DISTINCT_NOOP:
942** Build an ephemeral table that contains all entries seen before and
943** skip entries which have been seen before.
944**
945** Parameter iTab is the cursor number of an ephemeral table that must
946** be opened before the VM code generated by this routine is executed.
947** The ephemeral cursor table is queried for a record identical to the
948** record formed by the current array of registers. If one is found,
949** jump to VM address addrRepeat. Otherwise, insert a new record into
950** the ephemeral cursor and proceed.
951**
952** The returned value in this case is a copy of parameter iTab.
953**
954** WHERE_DISTINCT_ORDERED:
955** In this case rows are being delivered sorted order. The ephemeral
956** table is not required. Instead, the current set of values
957** is compared against previous row. If they match, the new row
958** is not distinct and control jumps to VM address addrRepeat. Otherwise,
959** the VM program proceeds with processing the new row.
960**
961** The returned value in this case is the register number of the first
962** in an array of registers used to store the previous result row so that
963** it can be compared to the next. The caller must ensure that this
964** register is initialized to NULL. (The fixDistinctOpenEph() routine
965** will take care of this initialization.)
966**
967** WHERE_DISTINCT_UNIQUE:
968** In this case it has already been determined that the rows are distinct.
969** No special action is required. The return value is zero.
970**
971** Parameter pEList is the list of expressions used to generated the
972** contents of each row. It is used by this routine to determine (a)
973** how many elements there are in the array of registers and (b) the
974** collation sequences that should be used for the comparisons if
975** eTnctType is WHERE_DISTINCT_ORDERED.
976*/
977static int codeDistinct(
978 Parse *pParse, /* Parsing and code generating context */
979 int eTnctType, /* WHERE_DISTINCT_* value */
980 int iTab, /* A sorting index used to test for distinctness */
981 int addrRepeat, /* Jump to here if not distinct */
982 ExprList *pEList, /* Expression for each element */
983 int regElem /* First element */
984){
985 int iRet = 0;
986 int nResultCol = pEList->nExpr;
987 Vdbe *v = pParse->pVdbe;
988
989 switch( eTnctType ){
990 case WHERE_DISTINCT_ORDERED: {
991 int i;
992 int iJump; /* Jump destination */
993 int regPrev; /* Previous row content */
994
995 /* Allocate space for the previous row */
996 iRet = regPrev = pParse->nMem+1;
997 pParse->nMem += nResultCol;
998
999 iJump = sqlite3VdbeCurrentAddr(v) + nResultCol;
1000 for(i=0; i<nResultCol; i++){
1001 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pEList->a[i].pExpr);
1002 if( i<nResultCol-1 ){
1003 sqlite3VdbeAddOp3(v, OP_Ne, regElem+i, iJump, regPrev+i);
1004 VdbeCoverage(v);
1005 }else{
1006 sqlite3VdbeAddOp3(v, OP_Eq, regElem+i, addrRepeat, regPrev+i);
1007 VdbeCoverage(v);
1008 }
1009 sqlite3VdbeChangeP4(v, -1, (const char *)pColl, P4_COLLSEQ);
1010 sqlite3VdbeChangeP5(v, SQLITE_NULLEQ);
1011 }
1012 assert( sqlite3VdbeCurrentAddr(v)==iJump || pParse->db->mallocFailed );
1013 sqlite3VdbeAddOp3(v, OP_Copy, regElem, regPrev, nResultCol-1);
1014 break;
1015 }
1016
1017 case WHERE_DISTINCT_UNIQUE: {
1018 /* nothing to do */
1019 break;
1020 }
1021
1022 default: {
1023 int r1 = sqlite3GetTempReg(pParse);
1024 sqlite3VdbeAddOp4Int(v, OP_Found, iTab, addrRepeat, regElem, nResultCol);
1025 VdbeCoverage(v);
1026 sqlite3VdbeAddOp3(v, OP_MakeRecord, regElem, nResultCol, r1);
1027 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iTab, r1, regElem, nResultCol);
1028 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1029 sqlite3ReleaseTempReg(pParse, r1);
1030 iRet = iTab;
1031 break;
1032 }
1033 }
1034
1035 return iRet;
1036}
1037
1038/*
1039** This routine runs after codeDistinct(). It makes necessary
1040** adjustments to the OP_OpenEphemeral opcode that the codeDistinct()
1041** routine made use of. This processing must be done separately since
1042** sometimes codeDistinct is called before the OP_OpenEphemeral is actually
1043** laid down.
1044**
1045** WHERE_DISTINCT_NOOP:
1046** WHERE_DISTINCT_UNORDERED:
1047**
1048** No adjustments necessary. This function is a no-op.
1049**
1050** WHERE_DISTINCT_UNIQUE:
1051**
1052** The ephemeral table is not needed. So change the
1053** OP_OpenEphemeral opcode into an OP_Noop.
1054**
1055** WHERE_DISTINCT_ORDERED:
1056**
1057** The ephemeral table is not needed. But we do need register
1058** iVal to be initialized to NULL. So change the OP_OpenEphemeral
1059** into an OP_Null on the iVal register.
1060*/
1061static void fixDistinctOpenEph(
1062 Parse *pParse, /* Parsing and code generating context */
1063 int eTnctType, /* WHERE_DISTINCT_* value */
1064 int iVal, /* Value returned by codeDistinct() */
1065 int iOpenEphAddr /* Address of OP_OpenEphemeral instruction for iTab */
1066){
1067 if( pParse->nErr==0
1068 && (eTnctType==WHERE_DISTINCT_UNIQUE || eTnctType==WHERE_DISTINCT_ORDERED)
1069 ){
1070 Vdbe *v = pParse->pVdbe;
1071 sqlite3VdbeChangeToNoop(v, iOpenEphAddr);
1072 if( sqlite3VdbeGetOp(v, iOpenEphAddr+1)->opcode==OP_Explain ){
1073 sqlite3VdbeChangeToNoop(v, iOpenEphAddr+1);
1074 }
1075 if( eTnctType==WHERE_DISTINCT_ORDERED ){
1076 /* Change the OP_OpenEphemeral to an OP_Null that sets the MEM_Cleared
1077 ** bit on the first register of the previous value. This will cause the
1078 ** OP_Ne added in codeDistinct() to always fail on the first iteration of
1079 ** the loop even if the first row is all NULLs. */
1080 VdbeOp *pOp = sqlite3VdbeGetOp(v, iOpenEphAddr);
1081 pOp->opcode = OP_Null;
1082 pOp->p1 = 1;
1083 pOp->p2 = iVal;
1084 }
1085 }
1086}
1087
1088#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1089/*
1090** This function is called as part of inner-loop generation for a SELECT
1091** statement with an ORDER BY that is not optimized by an index. It
1092** determines the expressions, if any, that the sorter-reference
1093** optimization should be used for. The sorter-reference optimization
1094** is used for SELECT queries like:
1095**
1096** SELECT a, bigblob FROM t1 ORDER BY a LIMIT 10
1097**
1098** If the optimization is used for expression "bigblob", then instead of
1099** storing values read from that column in the sorter records, the PK of
1100** the row from table t1 is stored instead. Then, as records are extracted from
1101** the sorter to return to the user, the required value of bigblob is
1102** retrieved directly from table t1. If the values are very large, this
1103** can be more efficient than storing them directly in the sorter records.
1104**
1105** The ExprList_item.fg.bSorterRef flag is set for each expression in pEList
1106** for which the sorter-reference optimization should be enabled.
1107** Additionally, the pSort->aDefer[] array is populated with entries
1108** for all cursors required to evaluate all selected expressions. Finally.
1109** output variable (*ppExtra) is set to an expression list containing
1110** expressions for all extra PK values that should be stored in the
1111** sorter records.
1112*/
1113static void selectExprDefer(
1114 Parse *pParse, /* Leave any error here */
1115 SortCtx *pSort, /* Sorter context */
1116 ExprList *pEList, /* Expressions destined for sorter */
1117 ExprList **ppExtra /* Expressions to append to sorter record */
1118){
1119 int i;
1120 int nDefer = 0;
1121 ExprList *pExtra = 0;
1122 for(i=0; i<pEList->nExpr; i++){
1123 struct ExprList_item *pItem = &pEList->a[i];
1124 if( pItem->u.x.iOrderByCol==0 ){
1125 Expr *pExpr = pItem->pExpr;
1126 Table *pTab;
1127 if( pExpr->op==TK_COLUMN
1128 && pExpr->iColumn>=0
1129 && ALWAYS( ExprUseYTab(pExpr) )
1130 && (pTab = pExpr->y.pTab)!=0
1131 && IsOrdinaryTable(pTab)
1132 && (pTab->aCol[pExpr->iColumn].colFlags & COLFLAG_SORTERREF)!=0
1133 ){
1134 int j;
1135 for(j=0; j<nDefer; j++){
1136 if( pSort->aDefer[j].iCsr==pExpr->iTable ) break;
1137 }
1138 if( j==nDefer ){
1139 if( nDefer==ArraySize(pSort->aDefer) ){
1140 continue;
1141 }else{
1142 int nKey = 1;
1143 int k;
1144 Index *pPk = 0;
1145 if( !HasRowid(pTab) ){
1146 pPk = sqlite3PrimaryKeyIndex(pTab);
1147 nKey = pPk->nKeyCol;
1148 }
1149 for(k=0; k<nKey; k++){
1150 Expr *pNew = sqlite3PExpr(pParse, TK_COLUMN, 0, 0);
1151 if( pNew ){
1152 pNew->iTable = pExpr->iTable;
1153 assert( ExprUseYTab(pNew) );
1154 pNew->y.pTab = pExpr->y.pTab;
1155 pNew->iColumn = pPk ? pPk->aiColumn[k] : -1;
1156 pExtra = sqlite3ExprListAppend(pParse, pExtra, pNew);
1157 }
1158 }
1159 pSort->aDefer[nDefer].pTab = pExpr->y.pTab;
1160 pSort->aDefer[nDefer].iCsr = pExpr->iTable;
1161 pSort->aDefer[nDefer].nKey = nKey;
1162 nDefer++;
1163 }
1164 }
1165 pItem->fg.bSorterRef = 1;
1166 }
1167 }
1168 }
1169 pSort->nDefer = (u8)nDefer;
1170 *ppExtra = pExtra;
1171}
1172#endif
1173
1174#ifdef SQLITE_DEBUG
1175/*
1176** This is a byte-code validation check that only runs when SQLITE_DEBUG
1177** is defined. This routine looks backwards through the bytecode
1178** for the definition of cursor with index iCur. It extracts the KeyInfo from
1179** that cursor (it must be an index cursor) and verifies that the cursor
1180** does not use any collating seqeuences other than BINARY for its first
1181** nCol columns.
1182**
1183** This routine is used inside of an assert(). So it should return true
1184** on success and false if the invariant is not satisfied.
1185**
1186** tag-202607231411
1187*/
1188static int sqlite3CursorBloomable(Parse *pParse, int iCur, int nCol){
1189 int i,k;
1190 Vdbe *v = pParse->pVdbe;
1191 if( pParse->nErr ) return 1;
1192 assert( v );
1193 for(k=sqlite3VdbeCurrentAddr(v)-1; k>0; k--){
1194 const VdbeOp *pOp = sqlite3VdbeGetOp(v, k);
1195 const KeyInfo *pKeyInfo;
1196 if( pOp->p1!=iCur ) continue;
1197 if( pOp->opcode!=OP_OpenRead
1198 && pOp->opcode!=OP_OpenWrite
1199 && pOp->opcode!=OP_OpenEphemeral
1200 ){
1201 continue;
1202 }
1203 assert( pOp->p4type==P4_KEYINFO );
1204 pKeyInfo = (const KeyInfo*)pOp->p4.pKeyInfo;
1205 assert( pKeyInfo!=0 );
1206 for(i=0; i<nCol; i++){
1207 assert( sqlite3IsBinary(pKeyInfo->aColl[i]) );
1208 }
1209 return 1;
1210 }
1211 return 0;
1212}
1213#endif /* SQLITE_DEBUG */
1214
1215
1216/*
1217** This routine generates the code for the inside of the inner loop
1218** of a SELECT.
1219**
1220** If srcTab is negative, then the p->pEList expressions
1221** are evaluated in order to get the data for this row. If srcTab is
1222** zero or more, then data is pulled from srcTab and p->pEList is used only
1223** to get the number of columns and the collation sequence for each column.
1224*/
1225static void selectInnerLoop(
1226 Parse *pParse, /* The parser context */
1227 Select *p, /* The complete select statement being coded */
1228 int srcTab, /* Pull data from this table if non-negative */
1229 SortCtx *pSort, /* If not NULL, info on how to process ORDER BY */
1230 DistinctCtx *pDistinct, /* If not NULL, info on how to process DISTINCT */
1231 SelectDest *pDest, /* How to dispose of the results */
1232 int iContinue, /* Jump here to continue with next row */
1233 int iBreak /* Jump here to break out of the inner loop */
1234){
1235 Vdbe *v = pParse->pVdbe;
1236 int i;
1237 int hasDistinct; /* True if the DISTINCT keyword is present */
1238 int eDest = pDest->eDest; /* How to dispose of results */
1239 int iParm = pDest->iSDParm; /* First argument to disposal method */
1240 int nResultCol; /* Number of result columns */
1241 int nPrefixReg = 0; /* Number of extra registers before regResult */
1242 RowLoadInfo sRowLoadInfo; /* Info for deferred row loading */
1243
1244 /* Usually, regResult is the first cell in an array of memory cells
1245 ** containing the current result row. In this case regOrig is set to the
1246 ** same value. However, if the results are being sent to the sorter, the
1247 ** values for any expressions that are also part of the sort-key are omitted
1248 ** from this array. In this case regOrig is set to zero. */
1249 int regResult; /* Start of memory holding current results */
1250 int regOrig; /* Start of memory holding full result (or 0) */
1251
1252 assert( v );
1253 assert( p->pEList!=0 );
1254 hasDistinct = pDistinct ? pDistinct->eTnctType : WHERE_DISTINCT_NOOP;
1255 if( pSort && pSort->pOrderBy==0 ) pSort = 0;
1256 if( pSort==0 && !hasDistinct ){
1257 assert( iContinue!=0 );
1258 codeOffset(v, p->iOffset, iContinue);
1259 }
1260
1261 /* Pull the requested columns.
1262 */
1263 nResultCol = p->pEList->nExpr;
1264
1265 if( pDest->iSdst==0 ){
1266 if( pSort ){
1267 nPrefixReg = pSort->pOrderBy->nExpr;
1268 if( !(pSort->sortFlags & SORTFLAG_UseSorter) ) nPrefixReg++;
1269 pParse->nMem += nPrefixReg;
1270 }
1271 pDest->iSdst = pParse->nMem+1;
1272 pParse->nMem += nResultCol;
1273 }else if( pDest->iSdst+nResultCol > pParse->nMem ){
1274 /* This is an error condition that can result, for example, when a SELECT
1275 ** on the right-hand side of an INSERT contains more result columns than
1276 ** there are columns in the table on the left. The error will be caught
1277 ** and reported later. But we need to make sure enough memory is allocated
1278 ** to avoid other spurious errors in the meantime. */
1279 pParse->nMem += nResultCol;
1280 }
1281 pDest->nSdst = nResultCol;
1282 regOrig = regResult = pDest->iSdst;
1283 if( srcTab>=0 ){
1284 for(i=0; i<nResultCol; i++){
1285 sqlite3VdbeAddOp3(v, OP_Column, srcTab, i, regResult+i);
1286 VdbeComment((v, "%s", p->pEList->a[i].zEName));
1287 }
1288 }else if( eDest!=SRT_Exists || hasDistinct ){
1289 /* If the destination is an EXISTS(...) expression, the actual
1290 ** values returned by the SELECT are only required if the query is
1291 ** DISTINCT. */
1292#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1293 ExprList *pExtra = 0;
1294#endif
1295 u8 ecelFlags; /* "ecel" is an abbreviation of "ExprCodeExprList" */
1296 ExprList *pEList;
1297 if( eDest==SRT_Mem || eDest==SRT_Output || eDest==SRT_Coroutine ){
1298 ecelFlags = SQLITE_ECEL_DUP;
1299 }else{
1300 ecelFlags = 0;
1301 }
1302 if( pSort && hasDistinct==0 && eDest!=SRT_EphemTab && eDest!=SRT_Table ){
1303 /* For each expression in p->pEList that is a copy of an expression in
1304 ** the ORDER BY clause (pSort->pOrderBy), set the associated
1305 ** iOrderByCol value to one more than the index of the ORDER BY
1306 ** expression within the sort-key that pushOntoSorter() will generate.
1307 ** This allows the p->pEList field to be omitted from the sorted record,
1308 ** saving space and CPU cycles. */
1309 ecelFlags |= (SQLITE_ECEL_OMITREF|SQLITE_ECEL_REF);
1310
1311 for(i=pSort->nOBSat; i<pSort->pOrderBy->nExpr; i++){
1312 int j;
1313 if( (j = pSort->pOrderBy->a[i].u.x.iOrderByCol)>0 ){
1314 p->pEList->a[j-1].u.x.iOrderByCol = i+1-pSort->nOBSat;
1315 }
1316 }
1317#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1318 selectExprDefer(pParse, pSort, p->pEList, &pExtra);
1319 if( pExtra && pParse->db->mallocFailed==0 ){
1320 /* If there are any extra PK columns to add to the sorter records,
1321 ** allocate extra memory cells and adjust the OpenEphemeral
1322 ** instruction to account for the larger records. This is only
1323 ** required if there are one or more WITHOUT ROWID tables with
1324 ** composite primary keys in the SortCtx.aDefer[] array. */
1325 VdbeOp *pOp = sqlite3VdbeGetOp(v, pSort->addrSortIndex);
1326 pOp->p2 += (pExtra->nExpr - pSort->nDefer);
1327 pOp->p4.pKeyInfo->nAllField += (pExtra->nExpr - pSort->nDefer);
1328 pParse->nMem += pExtra->nExpr;
1329 }
1330#endif
1331
1332 /* Adjust nResultCol to account for columns that are omitted
1333 ** from the sorter by the optimizations in this branch */
1334 pEList = p->pEList;
1335 for(i=0; i<pEList->nExpr; i++){
1336 if( pEList->a[i].u.x.iOrderByCol>0
1337#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1338 || pEList->a[i].fg.bSorterRef
1339#endif
1340 ){
1341 nResultCol--;
1342 regOrig = 0;
1343 }
1344 }
1345
1346 testcase( regOrig );
1347 testcase( eDest==SRT_Set );
1348 testcase( eDest==SRT_Mem );
1349 testcase( eDest==SRT_Coroutine );
1350 testcase( eDest==SRT_Output );
1351 assert( eDest==SRT_Set || eDest==SRT_Mem
1352 || eDest==SRT_Coroutine || eDest==SRT_Output
1353 || eDest==SRT_Upfrom );
1354 }
1355 sRowLoadInfo.regResult = regResult;
1356 sRowLoadInfo.ecelFlags = ecelFlags;
1357#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1358 sRowLoadInfo.pExtra = pExtra;
1359 sRowLoadInfo.regExtraResult = regResult + nResultCol;
1360 if( pExtra ) nResultCol += pExtra->nExpr;
1361#endif
1362 if( p->iLimit
1363 && (ecelFlags & SQLITE_ECEL_OMITREF)!=0
1364 && nPrefixReg>0
1365 ){
1366 assert( pSort!=0 );
1367 assert( hasDistinct==0 );
1368 pSort->pDeferredRowLoad = &sRowLoadInfo;
1369 regOrig = 0;
1370 }else{
1371 innerLoopLoadRow(pParse, p, &sRowLoadInfo);
1372 }
1373 }
1374
1375 /* If the DISTINCT keyword was present on the SELECT statement
1376 ** and this row has been seen before, then do not make this row
1377 ** part of the result.
1378 */
1379 if( hasDistinct ){
1380 int eType = pDistinct->eTnctType;
1381 int iTab = pDistinct->tabTnct;
1382 assert( nResultCol==p->pEList->nExpr );
1383 iTab = codeDistinct(pParse, eType, iTab, iContinue, p->pEList, regResult);
1384 fixDistinctOpenEph(pParse, eType, iTab, pDistinct->addrTnct);
1385 if( pSort==0 ){
1386 codeOffset(v, p->iOffset, iContinue);
1387 }
1388 }
1389
1390 switch( eDest ){
1391 /* Store the result as data using a unique key.
1392 */
1393 case SRT_Fifo:
1394 case SRT_DistFifo:
1395 case SRT_Table:
1396 case SRT_EphemTab: {
1397 int r1 = sqlite3GetTempRange(pParse, nPrefixReg+1);
1398 testcase( eDest==SRT_Table );
1399 testcase( eDest==SRT_EphemTab );
1400 testcase( eDest==SRT_Fifo );
1401 testcase( eDest==SRT_DistFifo );
1402 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r1+nPrefixReg);
1403#if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
1404 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
1405 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
1406 ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
1407 ** This does not affect operation in any way - it just allows MakeRecord
1408 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
1409 if( eDest==SRT_Table && pDest->iSDParm2 ){
1410 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
1411 }
1412#endif
1413#ifndef SQLITE_OMIT_CTE
1414 if( eDest==SRT_DistFifo ){
1415 /* If the destination is DistFifo, then cursor (iParm+1) is open
1416 ** on an ephemeral index. If the current row is already present
1417 ** in the index, do not write it to the output. If not, add the
1418 ** current row to the index and proceed with writing it to the
1419 ** output table as well. */
1420 int addr = sqlite3VdbeCurrentAddr(v) + 4;
1421 sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, addr, r1, 0);
1422 VdbeCoverage(v);
1423 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,regResult,nResultCol);
1424 assert( pSort==0 );
1425 }
1426#endif
1427 if( pSort ){
1428 assert( regResult==regOrig );
1429 pushOntoSorter(pParse, pSort, p, r1+nPrefixReg, regOrig, 1, nPrefixReg);
1430 }else{
1431 int r2 = sqlite3GetTempReg(pParse);
1432 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
1433 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
1434 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1435 sqlite3ReleaseTempReg(pParse, r2);
1436 }
1437 sqlite3ReleaseTempRange(pParse, r1, nPrefixReg+1);
1438 break;
1439 }
1440
1441 case SRT_Upfrom: {
1442 if( pSort ){
1443 pushOntoSorter(
1444 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1445 }else{
1446 int i2 = pDest->iSDParm2;
1447 int r1 = sqlite3GetTempReg(pParse);
1448
1449 /* If the UPDATE FROM join is an aggregate that matches no rows, it
1450 ** might still be trying to return one row, because that is what
1451 ** aggregates do. Don't record that empty row in the output table. */
1452 sqlite3VdbeAddOp2(v, OP_IsNull, regResult, iBreak); VdbeCoverage(v);
1453
1454 sqlite3VdbeAddOp3(v, OP_MakeRecord,
1455 regResult+(i2<0), nResultCol-(i2<0), r1);
1456 if( i2<0 ){
1457 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regResult);
1458 }else{
1459 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, i2);
1460 }
1461 }
1462 break;
1463 }
1464
1465#ifndef SQLITE_OMIT_SUBQUERY
1466 /* If we are creating a set for an "expr IN (SELECT ...)" construct,
1467 ** then there should be a single item on the stack. Write this
1468 ** item into the set table with bogus data.
1469 */
1470 case SRT_Set: {
1471 if( pSort ){
1472 /* At first glance you would think we could optimize out the
1473 ** ORDER BY in this case since the order of entries in the set
1474 ** does not matter. But there might be a LIMIT clause, in which
1475 ** case the order does matter */
1476 pushOntoSorter(
1477 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1478 pDest->iSDParm2 = 0; /* Signal that any Bloom filter is unpopulated */
1479 }else{
1480 int r1 = sqlite3GetTempReg(pParse);
1481 assert( sqlite3Strlen30(pDest->zAffSdst)==nResultCol );
1482 sqlite3VdbeAddOp4(v, OP_MakeRecord, regResult, nResultCol,
1483 r1, pDest->zAffSdst, nResultCol);
1484 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regResult, nResultCol);
1485 if( pDest->iSDParm2 ){
1486 assert( sqlite3CursorBloomable(pParse,iParm,nResultCol) );
1487 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
1488 regResult, nResultCol);
1489 ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
1490 }
1491 sqlite3ReleaseTempReg(pParse, r1);
1492 }
1493 break;
1494 }
1495
1496
1497 /* If any row exist in the result set, record that fact and abort.
1498 */
1499 case SRT_Exists: {
1500 sqlite3VdbeAddOp2(v, OP_Integer, 1, iParm);
1501 /* The LIMIT clause will terminate the loop for us */
1502 break;
1503 }
1504
1505 /* If this is a scalar select that is part of an expression, then
1506 ** store the results in the appropriate memory cell or array of
1507 ** memory cells and break out of the scan loop.
1508 */
1509 case SRT_Mem: {
1510 if( pSort ){
1511 assert( nResultCol<=pDest->nSdst );
1512 pushOntoSorter(
1513 pParse, pSort, p, regResult, regOrig, nResultCol, nPrefixReg);
1514 pDest->iSDParm = regResult;
1515 }else{
1516 assert( nResultCol==pDest->nSdst );
1517 if( regResult!=iParm ){
1518 /* This occurs in cases where the SELECT had both a DISTINCT and
1519 ** an OFFSET clause. */
1520 sqlite3VdbeAddOp3(v, OP_Copy, regResult, iParm, nResultCol-1);
1521 }
1522 /* The LIMIT clause will jump out of the loop for us */
1523 }
1524 break;
1525 }
1526#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
1527
1528 case SRT_Coroutine: /* Send data to a co-routine */
1529 case SRT_Output: { /* Return the results */
1530 testcase( eDest==SRT_Coroutine );
1531 testcase( eDest==SRT_Output );
1532 if( pSort ){
1533 pushOntoSorter(pParse, pSort, p, regResult, regOrig, nResultCol,
1534 nPrefixReg);
1535 }else if( eDest==SRT_Coroutine ){
1536 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1537 }else{
1538 sqlite3VdbeAddOp2(v, OP_ResultRow, regResult, nResultCol);
1539 }
1540 break;
1541 }
1542
1543#ifndef SQLITE_OMIT_CTE
1544 /* Write the results into a priority queue that is order according to
1545 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
1546 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
1547 ** pSO->nExpr columns, then make sure all keys are unique by adding a
1548 ** final OP_Sequence column. The last column is the record as a blob.
1549 */
1550 case SRT_DistQueue:
1551 case SRT_Queue: {
1552 int nKey;
1553 int r1, r2, r3;
1554 int addrTest = 0;
1555 ExprList *pSO;
1556 pSO = pDest->pOrderBy;
1557 assert( pSO );
1558 nKey = pSO->nExpr;
1559 r1 = sqlite3GetTempReg(pParse);
1560 r2 = sqlite3GetTempRange(pParse, nKey+2);
1561 r3 = r2+nKey+1;
1562 if( eDest==SRT_DistQueue ){
1563 /* If the destination is DistQueue, then cursor (iParm+1) is open
1564 ** on a second ephemeral index that holds all values every previously
1565 ** added to the queue. */
1566 addrTest = sqlite3VdbeAddOp4Int(v, OP_Found, iParm+1, 0,
1567 regResult, nResultCol);
1568 VdbeCoverage(v);
1569 }
1570 sqlite3VdbeAddOp3(v, OP_MakeRecord, regResult, nResultCol, r3);
1571 if( eDest==SRT_DistQueue ){
1572 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
1573 sqlite3VdbeChangeP5(v, OPFLAG_USESEEKRESULT);
1574 }
1575 for(i=0; i<nKey; i++){
1576 sqlite3VdbeAddOp2(v, OP_SCopy,
1577 regResult + pSO->a[i].u.x.iOrderByCol - 1,
1578 r2+i);
1579 }
1580 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
1581 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
1582 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
1583 if( addrTest ) sqlite3VdbeJumpHere(v, addrTest);
1584 sqlite3ReleaseTempReg(pParse, r1);
1585 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
1586 break;
1587 }
1588#endif /* SQLITE_OMIT_CTE */
1589
1590
1591
1592#if !defined(SQLITE_OMIT_TRIGGER)
1593 /* Discard the results. This is used for SELECT statements inside
1594 ** the body of a TRIGGER. The purpose of such selects is to call
1595 ** user-defined functions that have side effects. We do not care
1596 ** about the actual results of the select.
1597 */
1598 default: {
1599 assert( eDest==SRT_Discard );
1600 break;
1601 }
1602#endif
1603 }
1604
1605 /* Jump to the end of the loop if the LIMIT is reached. Except, if
1606 ** there is a sorter, in which case the sorter has already limited
1607 ** the output for us.
1608 */
1609 if( pSort==0 && p->iLimit ){
1610 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
1611 }
1612}
1613
1614/*
1615** Allocate a KeyInfo object sufficient for an index of N key columns and
1616** X extra columns.
1617*/
1618KeyInfo *sqlite3KeyInfoAlloc(sqlite3 *db, int N, int X){
1619 int nExtra = (N+X)*(sizeof(CollSeq*)+1);
1620 KeyInfo *p;
1621 assert( X>=0 );
1622 if( NEVER(N+X>0xffff) ) return (KeyInfo*)sqlite3OomFault(db);
1623 p = sqlite3DbMallocRawNN(db, SZ_KEYINFO(0) + nExtra);
1624 if( p ){
1625 p->aSortFlags = (u8*)&p->aColl[N+X];
1626 p->nKeyField = (u16)N;
1627 p->nAllField = (u16)(N+X);
1628 p->enc = ENC(db);
1629 p->db = db;
1630 p->nRef = 1;
1631 memset(p->aColl, 0, nExtra);
1632 }else{
1633 return (KeyInfo*)sqlite3OomFault(db);
1634 }
1635 return p;
1636}
1637
1638/*
1639** Deallocate a KeyInfo object
1640*/
1641void sqlite3KeyInfoUnref(KeyInfo *p){
1642 if( p ){
1643 assert( p->db!=0 );
1644 assert( p->nRef>0 );
1645 p->nRef--;
1646 if( p->nRef==0 ) sqlite3DbNNFreeNN(p->db, p);
1647 }
1648}
1649
1650/*
1651** Make a new pointer to a KeyInfo object
1652*/
1653KeyInfo *sqlite3KeyInfoRef(KeyInfo *p){
1654 if( p ){
1655 assert( p->nRef>0 );
1656 p->nRef++;
1657 }
1658 return p;
1659}
1660
1661#ifdef SQLITE_DEBUG
1662/*
1663** Return TRUE if a KeyInfo object can be change. The KeyInfo object
1664** can only be changed if this is just a single reference to the object.
1665**
1666** This routine is used only inside of assert() statements.
1667*/
1668int sqlite3KeyInfoIsWriteable(KeyInfo *p){ return p->nRef==1; }
1669#endif /* SQLITE_DEBUG */
1670
1671/*
1672** Given an expression list, generate a KeyInfo structure that records
1673** the collating sequence for each expression in that expression list.
1674**
1675** If the ExprList is an ORDER BY or GROUP BY clause then the resulting
1676** KeyInfo structure is appropriate for initializing a virtual index to
1677** implement that clause. If the ExprList is the result set of a SELECT
1678** then the KeyInfo structure is appropriate for initializing a virtual
1679** index to implement a DISTINCT test.
1680**
1681** Space to hold the KeyInfo structure is obtained from malloc. The calling
1682** function is responsible for seeing that this structure is eventually
1683** freed.
1684*/
1685KeyInfo *sqlite3KeyInfoFromExprList(
1686 Parse *pParse, /* Parsing context */
1687 ExprList *pList, /* Form the KeyInfo object from this ExprList */
1688 int iStart, /* Begin with this column of pList */
1689 int nExtra /* Add this many extra columns to the end */
1690){
1691 int nExpr;
1692 KeyInfo *pInfo;
1693 struct ExprList_item *pItem;
1694 sqlite3 *db = pParse->db;
1695 int i;
1696
1697 nExpr = pList->nExpr;
1698 pInfo = sqlite3KeyInfoAlloc(db, nExpr-iStart, nExtra+1);
1699 if( pInfo ){
1700 assert( sqlite3KeyInfoIsWriteable(pInfo) );
1701 for(i=iStart, pItem=pList->a+iStart; i<nExpr; i++, pItem++){
1702 pInfo->aColl[i-iStart] = sqlite3ExprNNCollSeq(pParse, pItem->pExpr);
1703 pInfo->aSortFlags[i-iStart] = pItem->fg.sortFlags;
1704 }
1705 }
1706 return pInfo;
1707}
1708
1709/*
1710** Name of the connection operator, used for error messages.
1711*/
1712const char *sqlite3SelectOpName(int id){
1713 char *z;
1714 switch( id ){
1715 case TK_ALL: z = "UNION ALL"; break;
1716 case TK_INTERSECT: z = "INTERSECT"; break;
1717 case TK_EXCEPT: z = "EXCEPT"; break;
1718 default: z = "UNION"; break;
1719 }
1720 return z;
1721}
1722
1723#ifndef SQLITE_OMIT_EXPLAIN
1724/*
1725** Unless an "EXPLAIN QUERY PLAN" command is being processed, this function
1726** is a no-op. Otherwise, it adds a single row of output to the EQP result,
1727** where the caption is of the form:
1728**
1729** "USE TEMP B-TREE FOR xxx"
1730**
1731** where xxx is one of "DISTINCT", "ORDER BY" or "GROUP BY". Exactly which
1732** is determined by the zUsage argument.
1733*/
1734static void explainTempTable(Parse *pParse, const char *zUsage){
1735 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s", zUsage));
1736}
1737
1738/*
1739** Assign expression b to lvalue a. A second, no-op, version of this macro
1740** is provided when SQLITE_OMIT_EXPLAIN is defined. This allows the code
1741** in sqlite3Select() to assign values to structure member variables that
1742** only exist if SQLITE_OMIT_EXPLAIN is not defined without polluting the
1743** code with #ifndef directives.
1744*/
1745# define explainSetInteger(a, b) a = b
1746
1747#else
1748/* No-op versions of the explainXXX() functions and macros. */
1749# define explainTempTable(y,z)
1750# define explainSetInteger(y,z)
1751#endif
1752
1753
1754/*
1755** If the inner loop was generated using a non-null pOrderBy argument,
1756** then the results were placed in a sorter. After the loop is terminated
1757** we need to run the sorter and output the results. The following
1758** routine generates the code needed to do that.
1759*/
1760static void generateSortTail(
1761 Parse *pParse, /* Parsing context */
1762 Select *p, /* The SELECT statement */
1763 SortCtx *pSort, /* Information on the ORDER BY clause */
1764 int nColumn, /* Number of columns of data */
1765 SelectDest *pDest /* Write the sorted results here */
1766){
1767 Vdbe *v = pParse->pVdbe; /* The prepared statement */
1768 int addrBreak = pSort->labelDone; /* Jump here to exit loop */
1769 int addrContinue = sqlite3VdbeMakeLabel(pParse);/* Jump here for next cycle */
1770 int addr; /* Top of output loop. Jump for Next. */
1771 int addrOnce = 0;
1772 int iTab;
1773 ExprList *pOrderBy = pSort->pOrderBy;
1774 int eDest = pDest->eDest;
1775 int iParm = pDest->iSDParm;
1776 int regRow;
1777 int regRowid;
1778 int iCol;
1779 int nKey; /* Number of key columns in sorter record */
1780 int iSortTab; /* Sorter cursor to read from */
1781 int i;
1782 int bSeq; /* True if sorter record includes seq. no. */
1783 int nRefKey = 0;
1784 struct ExprList_item *aOutEx = p->pEList->a;
1785#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
1786 int addrExplain; /* Address of OP_Explain instruction */
1787#endif
1788
1789 nKey = pOrderBy->nExpr - pSort->nOBSat;
1790 if( pSort->nOBSat==0 || nKey==1 ){
1791 ExplainQueryPlan2(addrExplain, (pParse, 0,
1792 "USE TEMP B-TREE FOR %sORDER BY", pSort->nOBSat?"LAST TERM OF ":""
1793 ));
1794 }else{
1795 ExplainQueryPlan2(addrExplain, (pParse, 0,
1796 "USE TEMP B-TREE FOR LAST %d TERMS OF ORDER BY", nKey
1797 ));
1798 }
1799 sqlite3VdbeScanStatusRange(v, addrExplain,pSort->addrPush,pSort->addrPushEnd);
1800 sqlite3VdbeScanStatusCounters(v, addrExplain, addrExplain, pSort->addrPush);
1801
1802
1803 assert( addrBreak<0 );
1804 if( pSort->labelBkOut ){
1805 sqlite3VdbeAddOp2(v, OP_Gosub, pSort->regReturn, pSort->labelBkOut);
1806 sqlite3VdbeGoto(v, addrBreak);
1807 sqlite3VdbeResolveLabel(v, pSort->labelBkOut);
1808 }
1809
1810#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1811 /* Open any cursors needed for sorter-reference expressions */
1812 for(i=0; i<pSort->nDefer; i++){
1813 Table *pTab = pSort->aDefer[i].pTab;
1814 int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
1815 sqlite3OpenTable(pParse, pSort->aDefer[i].iCsr, iDb, pTab, OP_OpenRead);
1816 sqlite3VdbeAddOp2(v, OP_Rewind, pSort->aDefer[i].iCsr,
1817 sqlite3VdbeCurrentAddr(v)+1);
1818 VdbeCoverage(v);
1819 nRefKey = MAX(nRefKey, pSort->aDefer[i].nKey);
1820 }
1821#endif
1822
1823 iTab = pSort->iECursor;
1824 if( eDest==SRT_Output || eDest==SRT_Coroutine || eDest==SRT_Mem ){
1825 if( eDest==SRT_Mem && p->iOffset ){
1826 sqlite3VdbeAddOp2(v, OP_Null, 0, pDest->iSdst);
1827 }
1828 regRowid = 0;
1829 regRow = pDest->iSdst;
1830 }else{
1831 regRowid = sqlite3GetTempReg(pParse);
1832 if( eDest==SRT_EphemTab || eDest==SRT_Table ){
1833 regRow = sqlite3GetTempReg(pParse);
1834 nColumn = 0;
1835 }else{
1836 regRow = sqlite3GetTempRange(pParse, nColumn);
1837 }
1838 }
1839 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1840 int regSortOut = ++pParse->nMem;
1841 iSortTab = pParse->nTab++;
1842 if( pSort->labelBkOut ){
1843 addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
1844 }
1845 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iSortTab, regSortOut,
1846 nKey+1+nColumn+nRefKey);
1847 if( addrOnce ) sqlite3VdbeJumpHere(v, addrOnce);
1848 addr = 1 + sqlite3VdbeAddOp2(v, OP_SorterSort, iTab, addrBreak);
1849 VdbeCoverage(v);
1850 assert( p->iLimit==0 && p->iOffset==0 );
1851 sqlite3VdbeAddOp3(v, OP_SorterData, iTab, regSortOut, iSortTab);
1852 bSeq = 0;
1853 }else{
1854 addr = 1 + sqlite3VdbeAddOp2(v, OP_Sort, iTab, addrBreak); VdbeCoverage(v);
1855 codeOffset(v, p->iOffset, addrContinue);
1856 iSortTab = iTab;
1857 bSeq = 1;
1858 if( p->iOffset>0 ){
1859 sqlite3VdbeAddOp2(v, OP_AddImm, p->iLimit, -1);
1860 }
1861 }
1862 for(i=0, iCol=nKey+bSeq-1; i<nColumn; i++){
1863#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1864 if( aOutEx[i].fg.bSorterRef ) continue;
1865#endif
1866 if( aOutEx[i].u.x.iOrderByCol==0 ) iCol++;
1867 }
1868#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1869 if( pSort->nDefer ){
1870 int iKey = iCol+1;
1871 int regKey = sqlite3GetTempRange(pParse, nRefKey);
1872
1873 for(i=0; i<pSort->nDefer; i++){
1874 int iCsr = pSort->aDefer[i].iCsr;
1875 Table *pTab = pSort->aDefer[i].pTab;
1876 int nKey = pSort->aDefer[i].nKey;
1877
1878 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1879 if( HasRowid(pTab) ){
1880 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey);
1881 sqlite3VdbeAddOp3(v, OP_SeekRowid, iCsr,
1882 sqlite3VdbeCurrentAddr(v)+1, regKey);
1883 }else{
1884 int k;
1885 int iJmp;
1886 assert( sqlite3PrimaryKeyIndex(pTab)->nKeyCol==nKey );
1887 for(k=0; k<nKey; k++){
1888 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iKey++, regKey+k);
1889 }
1890 iJmp = sqlite3VdbeCurrentAddr(v);
1891 sqlite3VdbeAddOp4Int(v, OP_SeekGE, iCsr, iJmp+2, regKey, nKey);
1892 sqlite3VdbeAddOp4Int(v, OP_IdxLE, iCsr, iJmp+3, regKey, nKey);
1893 sqlite3VdbeAddOp1(v, OP_NullRow, iCsr);
1894 }
1895 }
1896 sqlite3ReleaseTempRange(pParse, regKey, nRefKey);
1897 }
1898#endif
1899 for(i=nColumn-1; i>=0; i--){
1900#ifdef SQLITE_ENABLE_SORTER_REFERENCES
1901 if( aOutEx[i].fg.bSorterRef ){
1902 sqlite3ExprCode(pParse, aOutEx[i].pExpr, regRow+i);
1903 }else
1904#endif
1905 {
1906 int iRead;
1907 if( aOutEx[i].u.x.iOrderByCol ){
1908 iRead = aOutEx[i].u.x.iOrderByCol-1;
1909 }else{
1910 iRead = iCol--;
1911 }
1912 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, iRead, regRow+i);
1913 VdbeComment((v, "%s", aOutEx[i].zEName));
1914 }
1915 }
1916 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
1917 switch( eDest ){
1918 case SRT_Table:
1919 case SRT_EphemTab: {
1920 sqlite3VdbeAddOp3(v, OP_Column, iSortTab, nKey+bSeq, regRow);
1921 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, regRowid);
1922 sqlite3VdbeAddOp3(v, OP_Insert, iParm, regRow, regRowid);
1923 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
1924 break;
1925 }
1926#ifndef SQLITE_OMIT_SUBQUERY
1927 case SRT_Set: {
1928 assert( nColumn==sqlite3Strlen30(pDest->zAffSdst) );
1929 sqlite3VdbeAddOp4(v, OP_MakeRecord, regRow, nColumn, regRowid,
1930 pDest->zAffSdst, nColumn);
1931 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, regRowid, regRow, nColumn);
1932 break;
1933 }
1934 case SRT_Mem: {
1935 /* The LIMIT clause will terminate the loop for us */
1936 break;
1937 }
1938#endif
1939 case SRT_Upfrom: {
1940 int i2 = pDest->iSDParm2;
1941 int r1 = sqlite3GetTempReg(pParse);
1942 sqlite3VdbeAddOp3(v, OP_MakeRecord,regRow+(i2<0),nColumn-(i2<0),r1);
1943 if( i2<0 ){
1944 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, regRow);
1945 }else{
1946 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, regRow, i2);
1947 }
1948 break;
1949 }
1950 default: {
1951 assert( eDest==SRT_Output || eDest==SRT_Coroutine );
1952 testcase( eDest==SRT_Output );
1953 testcase( eDest==SRT_Coroutine );
1954 if( eDest==SRT_Output ){
1955 sqlite3VdbeAddOp2(v, OP_ResultRow, pDest->iSdst, nColumn);
1956 }else{
1957 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
1958 }
1959 break;
1960 }
1961 }
1962 if( regRowid ){
1963 if( eDest==SRT_Set ){
1964 sqlite3ReleaseTempRange(pParse, regRow, nColumn);
1965 }else{
1966 sqlite3ReleaseTempReg(pParse, regRow);
1967 }
1968 sqlite3ReleaseTempReg(pParse, regRowid);
1969 }
1970 /* The bottom of the loop
1971 */
1972 sqlite3VdbeResolveLabel(v, addrContinue);
1973 if( pSort->sortFlags & SORTFLAG_UseSorter ){
1974 sqlite3VdbeAddOp2(v, OP_SorterNext, iTab, addr); VdbeCoverage(v);
1975 }else{
1976 sqlite3VdbeAddOp2(v, OP_Next, iTab, addr); VdbeCoverage(v);
1977 }
1978 sqlite3VdbeScanStatusRange(v, addrExplain, sqlite3VdbeCurrentAddr(v)-1, -1);
1979 if( pSort->regReturn ) sqlite3VdbeAddOp1(v, OP_Return, pSort->regReturn);
1980 sqlite3VdbeResolveLabel(v, addrBreak);
1981}
1982
1983/*
1984** Return a pointer to a string containing the 'declaration type' of the
1985** expression pExpr. The string may be treated as static by the caller.
1986**
1987** The declaration type is the exact datatype definition extracted from the
1988** original CREATE TABLE statement if the expression is a column. The
1989** declaration type for a ROWID field is INTEGER. Exactly when an expression
1990** is considered a column can be complex in the presence of subqueries. The
1991** result-set expression in all of the following SELECT statements is
1992** considered a column by this function.
1993**
1994** SELECT col FROM tbl;
1995** SELECT (SELECT col FROM tbl;
1996** SELECT (SELECT col FROM tbl);
1997** SELECT abc FROM (SELECT col AS abc FROM tbl);
1998**
1999** The declaration type for any expression other than a column is NULL.
2000**
2001** This routine has either 3 or 6 parameters depending on whether or not
2002** the SQLITE_ENABLE_COLUMN_METADATA compile-time option is used.
2003*/
2004#ifdef SQLITE_ENABLE_COLUMN_METADATA
2005# define columnType(A,B,C,D,E) columnTypeImpl(A,B,C,D,E)
2006#else /* if !defined(SQLITE_ENABLE_COLUMN_METADATA) */
2007# define columnType(A,B,C,D,E) columnTypeImpl(A,B)
2008#endif
2009static const char *columnTypeImpl(
2010 NameContext *pNC,
2011#ifndef SQLITE_ENABLE_COLUMN_METADATA
2012 Expr *pExpr
2013#else
2014 Expr *pExpr,
2015 const char **pzOrigDb,
2016 const char **pzOrigTab,
2017 const char **pzOrigCol
2018#endif
2019){
2020 char const *zType = 0;
2021 int j;
2022#ifdef SQLITE_ENABLE_COLUMN_METADATA
2023 char const *zOrigDb = 0;
2024 char const *zOrigTab = 0;
2025 char const *zOrigCol = 0;
2026#endif
2027
2028 assert( pExpr!=0 );
2029 assert( pNC->pSrcList!=0 );
2030 switch( pExpr->op ){
2031 case TK_COLUMN: {
2032 /* The expression is a column. Locate the table the column is being
2033 ** extracted from in NameContext.pSrcList. This table may be real
2034 ** database table or a subquery.
2035 */
2036 Table *pTab = 0; /* Table structure column is extracted from */
2037 Select *pS = 0; /* Select the column is extracted from */
2038 int iCol = pExpr->iColumn; /* Index of column in pTab */
2039 while( pNC && !pTab ){
2040 SrcList *pTabList = pNC->pSrcList;
2041 for(j=0;j<pTabList->nSrc && pTabList->a[j].iCursor!=pExpr->iTable;j++);
2042 if( j<pTabList->nSrc ){
2043 pTab = pTabList->a[j].pSTab;
2044 if( pTabList->a[j].fg.isSubquery ){
2045 pS = pTabList->a[j].u4.pSubq->pSelect;
2046 }else{
2047 pS = 0;
2048 }
2049 }else{
2050 pNC = pNC->pNext;
2051 }
2052 }
2053
2054 if( pTab==0 ){
2055 /* At one time, code such as "SELECT new.x" within a trigger would
2056 ** cause this condition to run. Since then, we have restructured how
2057 ** trigger code is generated and so this condition is no longer
2058 ** possible. However, it can still be true for statements like
2059 ** the following:
2060 **
2061 ** CREATE TABLE t1(col INTEGER);
2062 ** SELECT (SELECT t1.col) FROM FROM t1;
2063 **
2064 ** when columnType() is called on the expression "t1.col" in the
2065 ** sub-select. In this case, set the column type to NULL, even
2066 ** though it should really be "INTEGER".
2067 **
2068 ** This is not a problem, as the column type of "t1.col" is never
2069 ** used. When columnType() is called on the expression
2070 ** "(SELECT t1.col)", the correct type is returned (see the TK_SELECT
2071 ** branch below. */
2072 break;
2073 }
2074
2075 assert( pTab && ExprUseYTab(pExpr) && pExpr->y.pTab==pTab );
2076 if( pS ){
2077 /* The "table" is actually a sub-select or a view in the FROM clause
2078 ** of the SELECT statement. Return the declaration type and origin
2079 ** data for the result-set column of the sub-select.
2080 */
2081 if( iCol<pS->pEList->nExpr
2082 && (!ViewCanHaveRowid || iCol>=0)
2083 ){
2084 /* If iCol is less than zero, then the expression requests the
2085 ** rowid of the sub-select or view. This expression is legal (see
2086 ** test case misc2.2.2) - it always evaluates to NULL.
2087 */
2088 NameContext sNC;
2089 Expr *p = pS->pEList->a[iCol].pExpr;
2090 sNC.pSrcList = pS->pSrc;
2091 sNC.pNext = pNC;
2092 sNC.pParse = pNC->pParse;
2093 zType = columnType(&sNC, p,&zOrigDb,&zOrigTab,&zOrigCol);
2094 }
2095 }else{
2096 /* A real table or a CTE table */
2097 assert( !pS );
2098#ifdef SQLITE_ENABLE_COLUMN_METADATA
2099 if( iCol<0 ) iCol = pTab->iPKey;
2100 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
2101 if( iCol<0 ){
2102 zType = "INTEGER";
2103 zOrigCol = "rowid";
2104 }else{
2105 zOrigCol = pTab->aCol[iCol].zCnName;
2106 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
2107 }
2108 zOrigTab = pTab->zName;
2109 if( pNC->pParse && pTab->pSchema ){
2110 int iDb = sqlite3SchemaToIndex(pNC->pParse->db, pTab->pSchema);
2111 zOrigDb = pNC->pParse->db->aDb[iDb].zDbSName;
2112 }
2113#else
2114 assert( iCol==XN_ROWID || (iCol>=0 && iCol<pTab->nCol) );
2115 if( iCol<0 ){
2116 zType = "INTEGER";
2117 }else{
2118 zType = sqlite3ColumnType(&pTab->aCol[iCol],0);
2119 }
2120#endif
2121 }
2122 break;
2123 }
2124#ifndef SQLITE_OMIT_SUBQUERY
2125 case TK_SELECT: {
2126 /* The expression is a sub-select. Return the declaration type and
2127 ** origin info for the single column in the result set of the SELECT
2128 ** statement.
2129 */
2130 NameContext sNC;
2131 Select *pS;
2132 Expr *p;
2133 assert( ExprUseXSelect(pExpr) );
2134 pS = pExpr->x.pSelect;
2135 p = pS->pEList->a[0].pExpr;
2136 sNC.pSrcList = pS->pSrc;
2137 sNC.pNext = pNC;
2138 sNC.pParse = pNC->pParse;
2139 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2140 break;
2141 }
2142#endif
2143 }
2144
2145#ifdef SQLITE_ENABLE_COLUMN_METADATA
2146 if( pzOrigDb ){
2147 assert( pzOrigTab && pzOrigCol );
2148 *pzOrigDb = zOrigDb;
2149 *pzOrigTab = zOrigTab;
2150 *pzOrigCol = zOrigCol;
2151 }
2152#endif
2153 return zType;
2154}
2155
2156/*
2157** Generate code that will tell the VDBE the declaration types of columns
2158** in the result set.
2159*/
2160static void generateColumnTypes(
2161 Parse *pParse, /* Parser context */
2162 SrcList *pTabList, /* List of tables */
2163 ExprList *pEList /* Expressions defining the result set */
2164){
2165#ifndef SQLITE_OMIT_DECLTYPE
2166 Vdbe *v = pParse->pVdbe;
2167 int i;
2168 NameContext sNC;
2169 sNC.pSrcList = pTabList;
2170 sNC.pParse = pParse;
2171 sNC.pNext = 0;
2172 for(i=0; i<pEList->nExpr; i++){
2173 Expr *p = pEList->a[i].pExpr;
2174 const char *zType;
2175#ifdef SQLITE_ENABLE_COLUMN_METADATA
2176 const char *zOrigDb = 0;
2177 const char *zOrigTab = 0;
2178 const char *zOrigCol = 0;
2179 zType = columnType(&sNC, p, &zOrigDb, &zOrigTab, &zOrigCol);
2180
2181 /* The vdbe must make its own copy of the column-type and other
2182 ** column specific strings, in case the schema is reset before this
2183 ** virtual machine is deleted.
2184 */
2185 sqlite3VdbeSetColName(v, i, COLNAME_DATABASE, zOrigDb, SQLITE_TRANSIENT);
2186 sqlite3VdbeSetColName(v, i, COLNAME_TABLE, zOrigTab, SQLITE_TRANSIENT);
2187 sqlite3VdbeSetColName(v, i, COLNAME_COLUMN, zOrigCol, SQLITE_TRANSIENT);
2188#else
2189 zType = columnType(&sNC, p, 0, 0, 0);
2190#endif
2191 sqlite3VdbeSetColName(v, i, COLNAME_DECLTYPE, zType, SQLITE_TRANSIENT);
2192 }
2193#else
2194 UNUSED_PARAMETER(pParse);
2195 UNUSED_PARAMETER(pTabList);
2196 UNUSED_PARAMETER(pEList);
2197#endif /* !defined(SQLITE_OMIT_DECLTYPE) */
2198}
2199
2200
2201/*
2202** Compute the column names for a SELECT statement.
2203**
2204** The only guarantee that SQLite makes about column names is that if the
2205** column has an AS clause assigning it a name, that will be the name used.
2206** That is the only documented guarantee. However, countless applications
2207** developed over the years have made baseless assumptions about column names
2208** and will break if those assumptions changes. Hence, use extreme caution
2209** when modifying this routine to avoid breaking legacy.
2210**
2211** See Also: sqlite3ColumnsFromExprList()
2212**
2213** The PRAGMA short_column_names and PRAGMA full_column_names settings are
2214** deprecated. The default setting is short=ON, full=OFF. 99.9% of all
2215** applications should operate this way. Nevertheless, we need to support the
2216** other modes for legacy:
2217**
2218** short=OFF, full=OFF: Column name is the text of the expression has it
2219** originally appears in the SELECT statement. In
2220** other words, the zSpan of the result expression.
2221**
2222** short=ON, full=OFF: (This is the default setting). If the result
2223** refers directly to a table column, then the
2224** result column name is just the table column
2225** name: COLUMN. Otherwise use zSpan.
2226**
2227** full=ON, short=ANY: If the result refers directly to a table column,
2228** then the result column name with the table name
2229** prefix, ex: TABLE.COLUMN. Otherwise use zSpan.
2230*/
2231void sqlite3GenerateColumnNames(
2232 Parse *pParse, /* Parser context */
2233 Select *pSelect /* Generate column names for this SELECT statement */
2234){
2235 Vdbe *v = pParse->pVdbe;
2236 int i;
2237 Table *pTab;
2238 SrcList *pTabList;
2239 ExprList *pEList;
2240 sqlite3 *db = pParse->db;
2241 int fullName; /* TABLE.COLUMN if no AS clause and is a direct table ref */
2242 int srcName; /* COLUMN or TABLE.COLUMN if no AS clause and is direct */
2243
2244 if( pParse->colNamesSet ) return;
2245 /* Column names are determined by the left-most term of a compound select */
2246 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2247 TREETRACE(0x80,pParse,pSelect,("generating column names\n"));
2248 pTabList = pSelect->pSrc;
2249 pEList = pSelect->pEList;
2250 assert( v!=0 );
2251 assert( pTabList!=0 );
2252 pParse->colNamesSet = 1;
2253 fullName = (db->flags & SQLITE_FullColNames)!=0;
2254 srcName = (db->flags & SQLITE_ShortColNames)!=0 || fullName;
2255 sqlite3VdbeSetNumCols(v, pEList->nExpr);
2256 for(i=0; i<pEList->nExpr; i++){
2257 Expr *p = pEList->a[i].pExpr;
2258
2259 assert( p!=0 );
2260 assert( p->op!=TK_AGG_COLUMN ); /* Agg processing has not run yet */
2261 assert( p->op!=TK_COLUMN
2262 || (ExprUseYTab(p) && p->y.pTab!=0) ); /* Covering idx not yet coded */
2263 if( pEList->a[i].zEName && pEList->a[i].fg.eEName==ENAME_NAME ){
2264 /* An AS clause always takes first priority */
2265 char *zName = pEList->a[i].zEName;
2266 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_TRANSIENT);
2267 }else if( srcName && p->op==TK_COLUMN ){
2268 char *zCol;
2269 int iCol = p->iColumn;
2270 pTab = p->y.pTab;
2271 assert( pTab!=0 );
2272 if( iCol<0 ) iCol = pTab->iPKey;
2273 assert( iCol==-1 || (iCol>=0 && iCol<pTab->nCol) );
2274 if( iCol<0 ){
2275 zCol = "rowid";
2276 }else{
2277 zCol = pTab->aCol[iCol].zCnName;
2278 }
2279 if( fullName ){
2280 char *zName = 0;
2281 zName = sqlite3MPrintf(db, "%s.%s", pTab->zName, zCol);
2282 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zName, SQLITE_DYNAMIC);
2283 }else{
2284 sqlite3VdbeSetColName(v, i, COLNAME_NAME, zCol, SQLITE_TRANSIENT);
2285 }
2286 }else{
2287 const char *z = pEList->a[i].zEName;
2288 z = z==0 ? sqlite3MPrintf(db, "column%d", i+1) : sqlite3DbStrDup(db, z);
2289 sqlite3VdbeSetColName(v, i, COLNAME_NAME, z, SQLITE_DYNAMIC);
2290 }
2291 }
2292 generateColumnTypes(pParse, pTabList, pEList);
2293}
2294
2295/*
2296** Given an expression list (which is really the list of expressions
2297** that form the result set of a SELECT statement) compute appropriate
2298** column names for a table that would hold the expression list.
2299**
2300** All column names will be unique.
2301**
2302** Only the column names are computed. Column.zType, Column.zColl,
2303** and other fields of Column are zeroed.
2304**
2305** Return SQLITE_OK on success. If a memory allocation error occurs,
2306** store NULL in *paCol and 0 in *pnCol and return SQLITE_NOMEM.
2307**
2308** The only guarantee that SQLite makes about column names is that if the
2309** column has an AS clause assigning it a name, that will be the name used.
2310** That is the only documented guarantee. However, countless applications
2311** developed over the years have made baseless assumptions about column names
2312** and will break if those assumptions changes. Hence, use extreme caution
2313** when modifying this routine to avoid breaking legacy.
2314**
2315** See Also: sqlite3GenerateColumnNames()
2316*/
2317int sqlite3ColumnsFromExprList(
2318 Parse *pParse, /* Parsing context */
2319 ExprList *pEList, /* Expr list from which to derive column names */
2320 i16 *pnCol, /* Write the number of columns here */
2321 Column **paCol /* Write the new column list here */
2322){
2323 sqlite3 *db = pParse->db; /* Database connection */
2324 int i, j; /* Loop counters */
2325 u32 cnt; /* Index added to make the name unique */
2326 Column *aCol, *pCol; /* For looping over result columns */
2327 int nCol; /* Number of columns in the result set */
2328 char *zName; /* Column name */
2329 int nName; /* Size of name in zName[] */
2330 Hash ht; /* Hash table of column names */
2331 Table *pTab;
2332
2333 sqlite3HashInit(&ht);
2334 if( pEList ){
2335 nCol = pEList->nExpr;
2336 aCol = sqlite3DbMallocZero(db, sizeof(aCol[0])*nCol);
2337 testcase( aCol==0 );
2338 if( nCol>32767 ) nCol = 32767;
2339 }else{
2340 nCol = 0;
2341 aCol = 0;
2342 }
2343 assert( nCol==(i16)nCol );
2344 *pnCol = nCol;
2345 *paCol = aCol;
2346
2347 for(i=0, pCol=aCol; i<nCol && !pParse->nErr; i++, pCol++){
2348 struct ExprList_item *pX = &pEList->a[i];
2349 struct ExprList_item *pCollide;
2350 /* Get an appropriate name for the column
2351 */
2352 if( (zName = pX->zEName)!=0 && pX->fg.eEName==ENAME_NAME ){
2353 /* If the column contains an "AS <name>" phrase, use <name> as the name */
2354 }else{
2355 Expr *pColExpr = sqlite3ExprSkipCollateAndLikely(pX->pExpr);
2356 while( ALWAYS(pColExpr!=0) && pColExpr->op==TK_DOT ){
2357 pColExpr = pColExpr->pRight;
2358 assert( pColExpr!=0 );
2359 }
2360 if( pColExpr->op==TK_COLUMN
2361 && ALWAYS( ExprUseYTab(pColExpr) )
2362 && ALWAYS( pColExpr->y.pTab!=0 )
2363 ){
2364 /* For columns use the column name name */
2365 int iCol = pColExpr->iColumn;
2366 pTab = pColExpr->y.pTab;
2367 if( iCol<0 ) iCol = pTab->iPKey;
2368 zName = iCol>=0 ? pTab->aCol[iCol].zCnName : "rowid";
2369 }else if( pColExpr->op==TK_ID ){
2370 assert( !ExprHasProperty(pColExpr, EP_IntValue) );
2371 zName = pColExpr->u.zToken;
2372 }else{
2373 /* Use the original text of the column expression as its name */
2374 assert( zName==pX->zEName ); /* pointer comparison intended */
2375 }
2376 }
2377 if( zName && !sqlite3IsTrueOrFalse(zName) ){
2378 zName = sqlite3DbStrDup(db, zName);
2379 }else{
2380 zName = sqlite3MPrintf(db,"column%d",i+1);
2381 }
2382
2383 /* Make sure the column name is unique. If the name is not unique,
2384 ** append an integer to the name so that it becomes unique.
2385 */
2386 cnt = 0;
2387 while( zName && (pCollide = sqlite3HashFind(&ht, zName))!=0 ){
2388 if( pCollide->fg.bUsingTerm ){
2389 pCol->colFlags |= COLFLAG_NOEXPAND;
2390 }
2391 nName = sqlite3Strlen30(zName);
2392 if( nName>0 ){
2393 for(j=nName-1; j>0 && sqlite3Isdigit(zName[j]); j--){}
2394 if( zName[j]==':' ) nName = j;
2395 }
2396 zName = sqlite3MPrintf(db, "%.*z:%u", nName, zName, ++cnt);
2397 sqlite3ProgressCheck(pParse);
2398 if( cnt>3 ){
2399 sqlite3_randomness(sizeof(cnt), &cnt);
2400 }
2401 }
2402 pCol->zCnName = zName;
2403 pCol->hName = sqlite3StrIHash(zName);
2404 if( pX->fg.bNoExpand ){
2405 pCol->colFlags |= COLFLAG_NOEXPAND;
2406 }
2407 sqlite3ColumnPropertiesFromName(0, pCol);
2408 if( zName && sqlite3HashInsert(&ht, zName, pX)==pX ){
2409 sqlite3OomFault(db);
2410 }
2411 }
2412 sqlite3HashClear(&ht);
2413 if( pParse->nErr ){
2414 for(j=0; j<i; j++){
2415 sqlite3DbFree(db, aCol[j].zCnName);
2416 }
2417 sqlite3DbFree(db, aCol);
2418 *paCol = 0;
2419 *pnCol = 0;
2420 return pParse->rc;
2421 }
2422 return SQLITE_OK;
2423}
2424
2425/*
2426** pTab is a transient Table object that represents a subquery of some
2427** kind (maybe a parenthesized subquery in the FROM clause of a larger
2428** query, or a VIEW, or a CTE). This routine computes type information
2429** for that Table object based on the Select object that implements the
2430** subquery. For the purposes of this routine, "type information" means:
2431**
2432** * The datatype name, as it might appear in a CREATE TABLE statement
2433** * Which collating sequence to use for the column
2434** * The affinity of the column
2435*/
2436void sqlite3SubqueryColumnTypes(
2437 Parse *pParse, /* Parsing contexts */
2438 Table *pTab, /* Add column type information to this table */
2439 Select *pSelect, /* SELECT used to determine types and collations */
2440 char aff /* Default affinity. */
2441){
2442 sqlite3 *db = pParse->db;
2443 Column *pCol;
2444 CollSeq *pColl;
2445 int i,j;
2446 Expr *p;
2447 struct ExprList_item *a;
2448 NameContext sNC;
2449
2450 assert( pSelect!=0 );
2451 assert( (pSelect->selFlags & SF_Resolved)!=0 );
2452 assert( pTab->nCol==pSelect->pEList->nExpr || pParse->nErr>0 );
2453 assert( aff==SQLITE_AFF_NONE || aff==SQLITE_AFF_BLOB );
2454 if( db->mallocFailed || IN_RENAME_OBJECT ) return;
2455 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2456 a = pSelect->pEList->a;
2457 memset(&sNC, 0, sizeof(sNC));
2458 sNC.pSrcList = pSelect->pSrc;
2459 for(i=0, pCol=pTab->aCol; i<pTab->nCol; i++, pCol++){
2460 const char *zType;
2461 i64 n;
2462 int m = 0;
2463 Select *pS2 = pSelect;
2464 pTab->tabFlags |= (pCol->colFlags & COLFLAG_NOINSERT);
2465 p = a[i].pExpr;
2466 /* pCol->szEst = ... // Column size est for SELECT tables never used */
2467 pCol->affinity = sqlite3ExprAffinity(p);
2468 while( pCol->affinity<=SQLITE_AFF_NONE && pS2->pNext!=0 ){
2469 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
2470 pS2 = pS2->pNext;
2471 pCol->affinity = sqlite3ExprAffinity(pS2->pEList->a[i].pExpr);
2472 }
2473 if( pCol->affinity<=SQLITE_AFF_NONE ){
2474 pCol->affinity = aff;
2475 }
2476 if( pCol->affinity>=SQLITE_AFF_TEXT && (pS2->pNext || pS2!=pSelect) ){
2477 for(pS2=pS2->pNext; pS2; pS2=pS2->pNext){
2478 m |= sqlite3ExprDataType(pS2->pEList->a[i].pExpr);
2479 }
2480 if( pCol->affinity==SQLITE_AFF_TEXT && (m&0x01)!=0 ){
2481 pCol->affinity = SQLITE_AFF_BLOB;
2482 }else
2483 if( pCol->affinity>=SQLITE_AFF_NUMERIC && (m&0x02)!=0 ){
2484 pCol->affinity = SQLITE_AFF_BLOB;
2485 }
2486 if( pCol->affinity>=SQLITE_AFF_NUMERIC && p->op==TK_CAST ){
2487 pCol->affinity = SQLITE_AFF_FLEXNUM;
2488 }
2489 }
2490 zType = columnType(&sNC, p, 0, 0, 0);
2491 if( zType==0 || pCol->affinity!=sqlite3AffinityType(zType, 0) ){
2492 if( pCol->affinity==SQLITE_AFF_NUMERIC
2493 || pCol->affinity==SQLITE_AFF_FLEXNUM
2494 ){
2495 zType = "NUM";
2496 }else{
2497 zType = 0;
2498 for(j=1; j<SQLITE_N_STDTYPE; j++){
2499 if( sqlite3StdTypeAffinity[j]==pCol->affinity ){
2500 zType = sqlite3StdType[j];
2501 break;
2502 }
2503 }
2504 }
2505 }
2506 if( zType ){
2507 const i64 k = strlen(zType);
2508 n = strlen(pCol->zCnName);
2509 pCol->zCnName = sqlite3DbReallocOrFree(db, pCol->zCnName, n+k+2);
2510 pCol->colFlags &= ~(COLFLAG_HASTYPE|COLFLAG_HASCOLL);
2511 if( pCol->zCnName ){
2512 memcpy(&pCol->zCnName[n+1], zType, k+1);
2513 pCol->colFlags |= COLFLAG_HASTYPE;
2514 }
2515 }
2516 pColl = sqlite3ExprCollSeq(pParse, p);
2517 if( pColl ){
2518 assert( pTab->pIndex==0 );
2519 sqlite3ColumnSetColl(db, pCol, pColl->zName);
2520 }
2521 }
2522 pTab->szTabRow = 1; /* Any non-zero value works */
2523}
2524
2525/*
2526** Check the current subquery nesting depth. Return true and set an
2527** error if it has gone too deep.
2528*/
2529static int checkSubqueryNestingDepth(Parse *pParse){
2530#if SQLITE_MAX_EXPR_DEPTH>0
2531 if( pParse->nNestSel >= pParse->db->aLimit[SQLITE_LIMIT_EXPR_DEPTH] ){
2532 sqlite3ErrorMsg(pParse, "VIEWs and/or subqueries nested too deep");
2533 return 1;
2534 }
2535#endif
2536 return 0;
2537}
2538
2539/*
2540** Given a SELECT statement, generate a Table structure that describes
2541** the result set of that SELECT.
2542*/
2543Table *sqlite3ResultSetOfSelect(Parse *pParse, Select *pSelect, char aff){
2544 Table *pTab;
2545 sqlite3 *db = pParse->db;
2546 u64 savedFlags;
2547
2548 pParse->nNestSel++;
2549 if( checkSubqueryNestingDepth(pParse) ) return 0;
2550 savedFlags = db->flags;
2551 db->flags &= ~(u64)SQLITE_FullColNames;
2552 db->flags |= SQLITE_ShortColNames;
2553 sqlite3SelectPrep(pParse, pSelect, 0);
2554 db->flags = savedFlags;
2555 if( pParse->nErr ) return 0;
2556 while( pSelect->pPrior ) pSelect = pSelect->pPrior;
2557 pTab = sqlite3DbMallocZero(db, sizeof(Table) );
2558 if( pTab==0 ){
2559 return 0;
2560 }
2561 pTab->nTabRef = 1;
2562 pTab->zName = 0;
2563 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
2564 sqlite3ColumnsFromExprList(pParse, pSelect->pEList, &pTab->nCol, &pTab->aCol);
2565 sqlite3SubqueryColumnTypes(pParse, pTab, pSelect, aff);
2566 pTab->iPKey = -1;
2567 if( db->mallocFailed ){
2568 sqlite3DeleteTable(db, pTab);
2569 return 0;
2570 }
2571 pParse->nNestSel--;
2572 assert( pParse->nNestSel>=0 );
2573 return pTab;
2574}
2575
2576/*
2577** Get a VDBE for the given parser context. Create a new one if necessary.
2578** If an error occurs, return NULL and leave a message in pParse.
2579*/
2580Vdbe *sqlite3GetVdbe(Parse *pParse){
2581 if( pParse->pVdbe ){
2582 return pParse->pVdbe;
2583 }
2584 if( pParse->pToplevel==0 ){
2585 pParse->okConstFactor = 1;
2586 }
2587 return sqlite3VdbeCreate(pParse);
2588}
2589
2590
2591/*
2592** Compute the iLimit and iOffset fields of the SELECT based on the
2593** pLimit expressions. pLimit->pLeft and pLimit->pRight hold the expressions
2594** that appear in the original SQL statement after the LIMIT and OFFSET
2595** keywords. Or NULL if those keywords are omitted. iLimit and iOffset
2596** are the integer memory register numbers for counters used to compute
2597** the limit and offset. If there is no limit and/or offset, then
2598** iLimit and iOffset are negative.
2599**
2600** This routine changes the values of iLimit and iOffset only if
2601** a limit or offset is defined by pLimit->pLeft and pLimit->pRight. iLimit
2602** and iOffset should have been preset to appropriate default values (zero)
2603** prior to calling this routine.
2604**
2605** The iOffset register (if it exists) is initialized to the value
2606** of the OFFSET. The iLimit register is initialized to LIMIT. Register
2607** iOffset+1 is initialized to LIMIT+OFFSET.
2608**
2609** Only if pLimit->pLeft!=0 do the limit registers get
2610** redefined. The UNION ALL operator uses this property to force
2611** the reuse of the same limit and offset registers across multiple
2612** SELECT statements.
2613*/
2614static void computeLimitRegisters(Parse *pParse, Select *p, int iBreak){
2615 Vdbe *v = 0;
2616 int iLimit = 0;
2617 int iOffset;
2618 int n;
2619 Expr *pLimit = p->pLimit;
2620
2621 if( p->iLimit ) return;
2622
2623 /*
2624 ** "LIMIT -1" always shows all rows. There is some
2625 ** controversy about what the correct behavior should be.
2626 ** The current implementation interprets "LIMIT 0" to mean
2627 ** no rows.
2628 */
2629 if( pLimit ){
2630 assert( pLimit->op==TK_LIMIT );
2631 assert( pLimit->pLeft!=0 );
2632 p->iLimit = iLimit = ++pParse->nMem;
2633 v = sqlite3GetVdbe(pParse);
2634 assert( v!=0 );
2635 if( sqlite3ExprIsInteger(pLimit->pLeft, &n, pParse, 0) ){
2636 sqlite3VdbeAddOp2(v, OP_Integer, n, iLimit);
2637 VdbeComment((v, "LIMIT counter"));
2638 if( n==0 ){
2639 sqlite3VdbeGoto(v, iBreak);
2640 }else if( n>=0 && p->nSelectRow>sqlite3LogEst((u64)n) ){
2641 p->nSelectRow = sqlite3LogEst((u64)n);
2642 p->selFlags |= SF_FixedLimit;
2643 }
2644 }else{
2645 sqlite3ExprCode(pParse, pLimit->pLeft, iLimit);
2646 sqlite3VdbeAddOp1(v, OP_MustBeInt, iLimit); VdbeCoverage(v);
2647 VdbeComment((v, "LIMIT counter"));
2648 sqlite3MayAbort(pParse);
2649 sqlite3VdbeAddOp2(v, OP_IfNot, iLimit, iBreak); VdbeCoverage(v);
2650 }
2651 if( pLimit->pRight ){
2652 p->iOffset = iOffset = ++pParse->nMem;
2653 pParse->nMem++; /* Allocate an extra register for limit+offset */
2654 sqlite3ExprCode(pParse, pLimit->pRight, iOffset);
2655 sqlite3VdbeAddOp1(v, OP_MustBeInt, iOffset); VdbeCoverage(v);
2656 sqlite3MayAbort(pParse);
2657 VdbeComment((v, "OFFSET counter"));
2658 sqlite3VdbeAddOp3(v, OP_OffsetLimit, iLimit, iOffset+1, iOffset);
2659 VdbeComment((v, "LIMIT+OFFSET"));
2660 }
2661 }
2662}
2663
2664#ifndef SQLITE_OMIT_COMPOUND_SELECT
2665/*
2666** Return the appropriate collating sequence for the iCol-th column of
2667** the result set for the compound-select statement "p". Return NULL if
2668** the column has no default collating sequence.
2669**
2670** The collating sequence for the compound select is taken from the
2671** left-most term of the select that has a collating sequence.
2672*/
2673static CollSeq *multiSelectCollSeq(Parse *pParse, Select *p, int iCol){
2674 CollSeq *pRet;
2675 if( p->pPrior ){
2676 pRet = multiSelectCollSeq(pParse, p->pPrior, iCol);
2677 }else{
2678 pRet = 0;
2679 }
2680 assert( iCol>=0 );
2681 /* iCol must be less than p->pEList->nExpr. Otherwise an error would
2682 ** have been thrown during name resolution and we would not have gotten
2683 ** this far. If p is really a multi-row VALUES statement, it is guaranteed
2684 ** not to have any collation sequences. So leave pRet set to 0 in this case */
2685 if( pRet==0 && ALWAYS(iCol<p->pEList->nExpr)
2686 && ((p->selFlags & SF_Values)==0 || p->pSrc->nSrc==0) /* multi-row VALUES */
2687 ){
2688 pRet = sqlite3ExprCollSeq(pParse, p->pEList->a[iCol].pExpr);
2689 }
2690
2691 return pRet;
2692}
2693
2694/*
2695** The select statement passed as the second parameter is a compound SELECT
2696** with an ORDER BY clause. This function allocates and returns a KeyInfo
2697** structure suitable for implementing the ORDER BY.
2698**
2699** Space to hold the KeyInfo structure is obtained from malloc. The calling
2700** function is responsible for ensuring that this structure is eventually
2701** freed.
2702*/
2703static KeyInfo *multiSelectByMergeKeyInfo(Parse *pParse, Select *p, int nExtra){
2704 ExprList *pOrderBy = p->pOrderBy;
2705 int nOrderBy = (pOrderBy!=0) ? pOrderBy->nExpr : 0;
2706 sqlite3 *db = pParse->db;
2707 KeyInfo *pRet = sqlite3KeyInfoAlloc(db, nOrderBy+nExtra, 1);
2708 if( pRet ){
2709 int i;
2710 for(i=0; i<nOrderBy; i++){
2711 struct ExprList_item *pItem = &pOrderBy->a[i];
2712 Expr *pTerm = pItem->pExpr;
2713 CollSeq *pColl;
2714
2715 if( pTerm->flags & EP_Collate ){
2716 pColl = sqlite3ExprCollSeq(pParse, pTerm);
2717 }else{
2718 pColl = multiSelectCollSeq(pParse, p, pItem->u.x.iOrderByCol-1);
2719 if( pColl==0 ) pColl = db->pDfltColl;
2720 pOrderBy->a[i].pExpr =
2721 sqlite3ExprAddCollateString(pParse, pTerm, pColl->zName);
2722 }
2723 assert( sqlite3KeyInfoIsWriteable(pRet) );
2724 pRet->aColl[i] = pColl;
2725 pRet->aSortFlags[i] = pOrderBy->a[i].fg.sortFlags;
2726 }
2727 }
2728
2729 return pRet;
2730}
2731
2732#ifndef SQLITE_OMIT_CTE
2733/*
2734** This routine generates VDBE code to compute the content of a WITH RECURSIVE
2735** query of the form:
2736**
2737** <recursive-table> AS (<setup-query> UNION [ALL] <recursive-query>)
2738** \___________/ \_______________/
2739** p->pPrior p
2740**
2741**
2742** There is exactly one reference to the recursive-table in the FROM clause
2743** of recursive-query, marked with the SrcList->a[].fg.isRecursive flag.
2744**
2745** The setup-query runs once to generate an initial set of rows that go
2746** into a Queue table. Rows are extracted from the Queue table one by
2747** one. Each row extracted from Queue is output to pDest. Then the single
2748** extracted row (now in the iCurrent table) becomes the content of the
2749** recursive-table for a recursive-query run. The output of the recursive-query
2750** is added back into the Queue table. Then another row is extracted from Queue
2751** and the iteration continues until the Queue table is empty.
2752**
2753** If the compound query operator is UNION then no duplicate rows are ever
2754** inserted into the Queue table. The iDistinct table keeps a copy of all rows
2755** that have ever been inserted into Queue and causes duplicates to be
2756** discarded. If the operator is UNION ALL, then duplicates are allowed.
2757**
2758** If the query has an ORDER BY, then entries in the Queue table are kept in
2759** ORDER BY order and the first entry is extracted for each cycle. Without
2760** an ORDER BY, the Queue table is just a FIFO.
2761**
2762** If a LIMIT clause is provided, then the iteration stops after LIMIT rows
2763** have been output to pDest. A LIMIT of zero means to output no rows and a
2764** negative LIMIT means to output all rows. If there is also an OFFSET clause
2765** with a positive value, then the first OFFSET outputs are discarded rather
2766** than being sent to pDest. The LIMIT count does not begin until after OFFSET
2767** rows have been skipped.
2768*/
2769static void generateWithRecursiveQuery(
2770 Parse *pParse, /* Parsing context */
2771 Select *p, /* The recursive SELECT to be coded */
2772 SelectDest *pDest /* What to do with query results */
2773){
2774 SrcList *pSrc = p->pSrc; /* The FROM clause of the recursive query */
2775 int nCol = p->pEList->nExpr; /* Number of columns in the recursive table */
2776 Vdbe *v = pParse->pVdbe; /* The prepared statement under construction */
2777 Select *pSetup; /* The setup query */
2778 Select *pFirstRec; /* Left-most recursive term */
2779 int addrTop; /* Top of the loop */
2780 int addrCont, addrBreak; /* CONTINUE and BREAK addresses */
2781 int iCurrent = 0; /* The Current table */
2782 int regCurrent; /* Register holding Current table */
2783 int iQueue; /* The Queue table */
2784 int iDistinct = 0; /* To ensure unique results if UNION */
2785 int eDest = SRT_Fifo; /* How to write to Queue */
2786 SelectDest destQueue; /* SelectDest targeting the Queue table */
2787 int i; /* Loop counter */
2788 int rc; /* Result code */
2789 ExprList *pOrderBy; /* The ORDER BY clause */
2790 Expr *pLimit; /* Saved LIMIT and OFFSET */
2791 int regLimit, regOffset; /* Registers used by LIMIT and OFFSET */
2792
2793#ifndef SQLITE_OMIT_WINDOWFUNC
2794 if( p->pWin ){
2795 sqlite3ErrorMsg(pParse, "cannot use window functions in recursive queries");
2796 return;
2797 }
2798#endif
2799
2800 /* Obtain authorization to do a recursive query */
2801 if( sqlite3AuthCheck(pParse, SQLITE_RECURSIVE, 0, 0, 0) ) return;
2802
2803 /* Process the LIMIT and OFFSET clauses, if they exist */
2804 addrBreak = sqlite3VdbeMakeLabel(pParse);
2805 p->nSelectRow = 320; /* 4 billion rows */
2806 computeLimitRegisters(pParse, p, addrBreak);
2807 pLimit = p->pLimit;
2808 regLimit = p->iLimit;
2809 regOffset = p->iOffset;
2810 p->pLimit = 0;
2811 p->iLimit = p->iOffset = 0;
2812 pOrderBy = p->pOrderBy;
2813
2814 /* Locate the cursor number of the Current table */
2815 for(i=0; ALWAYS(i<pSrc->nSrc); i++){
2816 if( pSrc->a[i].fg.isRecursive ){
2817 iCurrent = pSrc->a[i].iCursor;
2818 break;
2819 }
2820 }
2821
2822 /* Allocate cursors numbers for Queue and Distinct. The cursor number for
2823 ** the Distinct table must be exactly one greater than Queue in order
2824 ** for the SRT_DistFifo and SRT_DistQueue destinations to work. */
2825 iQueue = pParse->nTab++;
2826 if( p->op==TK_UNION ){
2827 eDest = pOrderBy ? SRT_DistQueue : SRT_DistFifo;
2828 iDistinct = pParse->nTab++;
2829 }else{
2830 eDest = pOrderBy ? SRT_Queue : SRT_Fifo;
2831 }
2832 sqlite3SelectDestInit(&destQueue, eDest, iQueue);
2833
2834 /* Allocate cursors for Current, Queue, and Distinct. */
2835 regCurrent = ++pParse->nMem;
2836 sqlite3VdbeAddOp3(v, OP_OpenPseudo, iCurrent, regCurrent, nCol);
2837 if( pOrderBy ){
2838 KeyInfo *pKeyInfo = multiSelectByMergeKeyInfo(pParse, p, 1);
2839 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iQueue, pOrderBy->nExpr+2, 0,
2840 (char*)pKeyInfo, P4_KEYINFO);
2841 destQueue.pOrderBy = pOrderBy;
2842 }else{
2843 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, iQueue, nCol);
2844 }
2845 VdbeComment((v, "Queue table"));
2846 if( iDistinct ){
2847 /* Generate an ephemeral table used to enforce distinctness on the
2848 ** output of the recursive part of the CTE.
2849 */
2850 KeyInfo *pKeyInfo; /* Collating sequence for the result set */
2851 CollSeq **apColl; /* For looping through pKeyInfo->aColl[] */
2852
2853 assert( p->pNext==0 );
2854 assert( p->pEList!=0 );
2855 nCol = p->pEList->nExpr;
2856 pKeyInfo = sqlite3KeyInfoAlloc(pParse->db, nCol, 1);
2857 if( pKeyInfo ){
2858 for(i=0, apColl=pKeyInfo->aColl; i<nCol; i++, apColl++){
2859 *apColl = multiSelectCollSeq(pParse, p, i);
2860 if( 0==*apColl ){
2861 *apColl = pParse->db->pDfltColl;
2862 }
2863 }
2864 sqlite3VdbeAddOp4(v, OP_OpenEphemeral, iDistinct, nCol, 0,
2865 (void*)pKeyInfo, P4_KEYINFO);
2866 }else{
2867 assert( pParse->nErr>0 );
2868 }
2869 }
2870
2871 /* Detach the ORDER BY clause from the compound SELECT */
2872 p->pOrderBy = 0;
2873
2874 /* Figure out how many elements of the compound SELECT are part of the
2875 ** recursive query. Make sure no recursive elements use aggregate
2876 ** functions. Mark the recursive elements as UNION ALL even if they
2877 ** are really UNION because the distinctness will be enforced by the
2878 ** iDistinct table. pFirstRec is left pointing to the left-most
2879 ** recursive term of the CTE.
2880 */
2881 for(pFirstRec=p; ALWAYS(pFirstRec!=0); pFirstRec=pFirstRec->pPrior){
2882 if( pFirstRec->selFlags & SF_Aggregate ){
2883 sqlite3ErrorMsg(pParse, "recursive aggregate queries not supported");
2884 goto end_of_recursive_query;
2885 }
2886 pFirstRec->op = TK_ALL;
2887 if( (pFirstRec->pPrior->selFlags & SF_Recursive)==0 ) break;
2888 }
2889
2890 /* Store the results of the setup-query in Queue. */
2891 pSetup = pFirstRec->pPrior;
2892 pSetup->pNext = 0;
2893 ExplainQueryPlan((pParse, 1, "SETUP"));
2894 rc = sqlite3Select(pParse, pSetup, &destQueue);
2895 pSetup->pNext = p;
2896 if( rc ) goto end_of_recursive_query;
2897
2898 /* Find the next row in the Queue and output that row */
2899 addrTop = sqlite3VdbeAddOp2(v, OP_Rewind, iQueue, addrBreak); VdbeCoverage(v);
2900
2901 /* Transfer the next row in Queue over to Current */
2902 sqlite3VdbeAddOp1(v, OP_Stale, iCurrent); /* To reset column cache */
2903 if( pOrderBy ){
2904 sqlite3VdbeAddOp3(v, OP_Column, iQueue, pOrderBy->nExpr+1, regCurrent);
2905 }else{
2906 sqlite3VdbeAddOp2(v, OP_RowData, iQueue, regCurrent);
2907 }
2908 sqlite3VdbeAddOp1(v, OP_Delete, iQueue);
2909
2910 /* Output the single row in Current */
2911 addrCont = sqlite3VdbeMakeLabel(pParse);
2912 codeOffset(v, regOffset, addrCont);
2913 selectInnerLoop(pParse, p, iCurrent,
2914 0, 0, pDest, addrCont, addrBreak);
2915 if( regLimit ){
2916 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, regLimit, addrBreak);
2917 VdbeCoverage(v);
2918 }
2919 sqlite3VdbeResolveLabel(v, addrCont);
2920
2921 /* Execute the recursive SELECT taking the single row in Current as
2922 ** the value for the recursive-table. Store the results in the Queue.
2923 */
2924 pFirstRec->pPrior = 0;
2925 ExplainQueryPlan((pParse, 1, "RECURSIVE STEP"));
2926 sqlite3Select(pParse, p, &destQueue);
2927 assert( pFirstRec->pPrior==0 );
2928 pFirstRec->pPrior = pSetup;
2929
2930 /* Keep running the loop until the Queue is empty */
2931 sqlite3VdbeGoto(v, addrTop);
2932 sqlite3VdbeResolveLabel(v, addrBreak);
2933
2934end_of_recursive_query:
2935 sqlite3ExprListDelete(pParse->db, p->pOrderBy);
2936 p->pOrderBy = pOrderBy;
2937 p->pLimit = pLimit;
2938 return;
2939}
2940#endif /* SQLITE_OMIT_CTE */
2941
2942/* Forward references */
2943static int multiSelectByMerge(
2944 Parse *pParse, /* Parsing context */
2945 Select *p, /* The right-most of SELECTs to be coded */
2946 SelectDest *pDest /* What to do with query results */
2947);
2948
2949/*
2950** Handle the special case of a compound-select that originates from a
2951** VALUES clause. By handling this as a special case, we avoid deep
2952** recursion, and thus do not need to enforce the SQLITE_LIMIT_COMPOUND_SELECT
2953** on a VALUES clause.
2954**
2955** Because the Select object originates from a VALUES clause:
2956** (1) There is no LIMIT or OFFSET or else there is a LIMIT of exactly 1
2957** (2) All terms are UNION ALL
2958** (3) There is no ORDER BY clause
2959**
2960** The "LIMIT of exactly 1" case of condition (1) comes about when a VALUES
2961** clause occurs within scalar expression (ex: "SELECT (VALUES(1),(2),(3))").
2962** The sqlite3CodeSubselect will have added the LIMIT 1 clause in tht case.
2963** Since the limit is exactly 1, we only need to evaluate the left-most VALUES.
2964*/
2965static int multiSelectValues(
2966 Parse *pParse, /* Parsing context */
2967 Select *p, /* The right-most of SELECTs to be coded */
2968 SelectDest *pDest /* What to do with query results */
2969){
2970 int nRow = 1;
2971 int rc = 0;
2972 int bShowAll = p->pLimit==0;
2973 assert( p->selFlags & SF_MultiValue );
2974 do{
2975 assert( p->selFlags & SF_Values );
2976 assert( p->op==TK_ALL || (p->op==TK_SELECT && p->pPrior==0) );
2977 assert( p->pNext==0 || p->pEList->nExpr==p->pNext->pEList->nExpr );
2978#ifndef SQLITE_OMIT_WINDOWFUNC
2979 if( p->pWin ) return -1;
2980#endif
2981 if( p->pPrior==0 ) break;
2982 assert( p->pPrior->pNext==p );
2983 p = p->pPrior;
2984 nRow += bShowAll;
2985 }while(1);
2986 ExplainQueryPlan((pParse, 0, "SCAN %d CONSTANT ROW%s", nRow,
2987 nRow==1 ? "" : "S"));
2988 while( p ){
2989 selectInnerLoop(pParse, p, -1, 0, 0, pDest, 1, 1);
2990 if( !bShowAll ) break;
2991 p->nSelectRow = nRow;
2992 p = p->pNext;
2993 }
2994 return rc;
2995}
2996
2997/*
2998** Return true if the SELECT statement which is known to be the recursive
2999** part of a recursive CTE still has its anchor terms attached. If the
3000** anchor terms have already been removed, then return false.
3001*/
3002static int hasAnchor(Select *p){
3003 while( p && (p->selFlags & SF_Recursive)!=0 ){ p = p->pPrior; }
3004 return p!=0;
3005}
3006
3007/*
3008** Return TRUE if every compound operator in the compound SELECT that
3009** ends with p is UNION ALL.
3010*/
3011static int selectIsUnionAll(Select *p){
3012 for(; p->pPrior; p=p->pPrior){
3013 if( p->op!=TK_ALL ) return 0;
3014 }
3015 return 1;
3016}
3017
3018/*
3019** Return TRUE if p is a UNION with a LIMIT of exactly 1 and no OFFSET
3020** clause. This is a precondition for a couple of related optimizations.
3021**
3022** False negatives are harmless (apart from resulting in a slower query).
3023** False positives can result in incorrect answers, however. To provoke
3024** false negatives for testing purposes, disable the SQLITE_UnionLimit
3025** optimization.
3026*/
3027static int unionWithLimitOne(sqlite3 *db, Select *p){
3028 int v;
3029 if( p->op!=TK_UNION ) return 0;
3030 if( p->pLimit==0 ) return 0;
3031 if( p->pLimit->pRight ) return 0; /* No OFFSET */
3032 v = 0;
3033 assert( p->pLimit->pLeft!=0 );
3034 if( sqlite3ExprIsInteger(p->pLimit->pLeft, &v, 0, 0)==0 ) return 0;
3035 if( v!=1 ) return 0;
3036 if( OptimizationDisabled(db, SQLITE_UnionLimit) ) return 0;
3037 return 1;
3038}
3039
3040/*
3041** This routine is called to process a compound query formed from
3042** two or more separate queries using UNION, UNION ALL, EXCEPT, or
3043** INTERSECT
3044**
3045** "p" points to the right-most of the two queries. The query on the
3046** left is p->pPrior. The left query could also be a compound query
3047** in which case this routine will be called recursively.
3048**
3049** The results of the total query are to be written into a destination
3050** of type eDest with parameter iParm.
3051**
3052** Example 1: Consider a three-way compound SQL statement.
3053**
3054** SELECT a FROM t1 UNION SELECT b FROM t2 UNION SELECT c FROM t3
3055**
3056** This statement is parsed up as follows:
3057**
3058** SELECT c FROM t3
3059** |
3060** `-----> SELECT b FROM t2
3061** |
3062** `------> SELECT a FROM t1
3063**
3064** The arrows in the diagram above represent the Select.pPrior pointer.
3065** So if this routine is called with p equal to the t3 query, then
3066** pPrior will be the t2 query. p->op will be TK_UNION in this case.
3067**
3068** Notice that because of the way SQLite parses compound SELECTs, the
3069** individual selects always group from left to right.
3070*/
3071static int multiSelect(
3072 Parse *pParse, /* Parsing context */
3073 Select *p, /* The right-most of SELECTs to be coded */
3074 SelectDest *pDest /* What to do with query results */
3075){
3076 int rc = SQLITE_OK; /* Success code from a subroutine */
3077 Select *pPrior; /* Another SELECT immediately to our left */
3078 Vdbe *v; /* Generate code to this VDBE */
3079 SelectDest dest; /* Alternative data destination */
3080 Select *pDelete = 0; /* Chain of simple selects to delete */
3081 sqlite3 *db; /* Database connection */
3082
3083 /* Make sure there is no ORDER BY or LIMIT clause on prior SELECTs. Only
3084 ** the last (right-most) SELECT in the series may have an ORDER BY or LIMIT.
3085 */
3086 assert( p && p->pPrior ); /* Calling function guarantees this much */
3087 assert( (p->selFlags & SF_Recursive)==0 || p->op==TK_ALL || p->op==TK_UNION );
3088 assert( p->selFlags & SF_Compound );
3089 db = pParse->db;
3090 pPrior = p->pPrior;
3091 dest = *pDest;
3092 assert( pPrior->pOrderBy==0 );
3093 assert( pPrior->pLimit==0 );
3094
3095 v = sqlite3GetVdbe(pParse);
3096 assert( v!=0 ); /* The VDBE already created by calling function */
3097
3098 /* Create the destination temporary table if necessary
3099 */
3100 if( dest.eDest==SRT_EphemTab ){
3101 assert( p->pEList );
3102 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, dest.iSDParm, p->pEList->nExpr);
3103 dest.eDest = SRT_Table;
3104 }
3105
3106 /* Special handling for a compound-select that originates as a VALUES clause.
3107 */
3108 if( p->selFlags & SF_MultiValue ){
3109 rc = multiSelectValues(pParse, p, &dest);
3110 if( rc>=0 ) goto multi_select_end;
3111 rc = SQLITE_OK;
3112 }
3113
3114 /* Make sure all SELECTs in the statement have the same number of elements
3115 ** in their result sets.
3116 */
3117 assert( p->pEList && pPrior->pEList );
3118 assert( p->pEList->nExpr==pPrior->pEList->nExpr );
3119
3120#ifndef SQLITE_OMIT_CTE
3121 if( (p->selFlags & SF_Recursive)!=0 && hasAnchor(p) ){
3122 generateWithRecursiveQuery(pParse, p, &dest);
3123 }else
3124#endif
3125 if( p->pOrderBy ){
3126 /* If the compound has an ORDER BY clause, then always use the merge
3127 ** algorithm. */
3128 return multiSelectByMerge(pParse, p, pDest);
3129 }else if( !selectIsUnionAll(p) && !unionWithLimitOne(db,p) ){
3130 /* If the compound is EXCEPT, INTERSECT, or UNION (anything other than
3131 ** UNION ALL) then also always use the merge algorithm. However, the
3132 ** multiSelectByMerge() routine requires that the compound have an
3133 ** ORDER BY clause, and it doesn't right now. So invent one first. */
3134 Expr *pOne = sqlite3ExprInt32(db, 1);
3135 p->pOrderBy = sqlite3ExprListAppend(pParse, 0, pOne);
3136 if( pParse->nErr ) goto multi_select_end;
3137 assert( p->pOrderBy!=0 );
3138 p->pOrderBy->a[0].u.x.iOrderByCol = 1;
3139 return multiSelectByMerge(pParse, p, pDest);
3140 }else{
3141 /* For a UNION ALL compound without ORDER BY, or for a UNION with a
3142 ** LIMIT of exactly 1 and no OFFSET and no ORDER BY, simply run the left
3143 ** query, then run the right query */
3144 int addr = 0;
3145 int nLimit = 0; /* Initialize to suppress harmless compiler warning */
3146
3147#ifndef SQLITE_OMIT_EXPLAIN
3148 if( pPrior->pPrior==0 ){
3149 ExplainQueryPlan((pParse, 1, "COMPOUND QUERY"));
3150 ExplainQueryPlan((pParse, 1, "LEFT-MOST SUBQUERY"));
3151 }
3152#endif
3153 assert( !pPrior->pLimit );
3154 pPrior->iLimit = p->iLimit;
3155 pPrior->iOffset = p->iOffset;
3156 pPrior->pLimit = sqlite3ExprDup(db, p->pLimit, 0);
3157 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL left...\n"));
3158 rc = sqlite3Select(pParse, pPrior, &dest);
3159 sqlite3ExprDelete(db, pPrior->pLimit);
3160 pPrior->pLimit = 0;
3161 if( rc ){
3162 goto multi_select_end;
3163 }
3164 p->pPrior = 0;
3165 p->iLimit = pPrior->iLimit;
3166 p->iOffset = pPrior->iOffset;
3167 if( p->iLimit ){
3168 addr = sqlite3VdbeAddOp1(v, OP_IfNot, p->iLimit); VdbeCoverage(v);
3169 VdbeComment((v, "Jump ahead if LIMIT reached"));
3170 if( p->iOffset ){
3171 sqlite3VdbeAddOp3(v, OP_OffsetLimit,
3172 p->iLimit, p->iOffset+1, p->iOffset);
3173 }
3174 }
3175 ExplainQueryPlan((pParse, 1, "UNION ALL"));
3176 TREETRACE(0x200, pParse, p, ("multiSelect UNION ALL right...\n"));
3177 rc = sqlite3Select(pParse, p, &dest);
3178 testcase( rc!=SQLITE_OK );
3179 pDelete = p->pPrior;
3180 p->pPrior = pPrior;
3181 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3182 if( p->pLimit
3183 && sqlite3ExprIsInteger(p->pLimit->pLeft, &nLimit, pParse, 0)
3184 && nLimit>0 && p->nSelectRow > sqlite3LogEst((u64)nLimit)
3185 ){
3186 p->nSelectRow = sqlite3LogEst((u64)nLimit);
3187 }
3188 if( addr ){
3189 sqlite3VdbeJumpHere(v, addr);
3190 }
3191#ifndef SQLITE_OMIT_EXPLAIN
3192 if( p->pNext==0 ){
3193 ExplainQueryPlanPop(pParse);
3194 }
3195#endif
3196 }
3197
3198multi_select_end:
3199 pDest->iSdst = dest.iSdst;
3200 pDest->nSdst = dest.nSdst;
3201 pDest->iSDParm2 = dest.iSDParm2;
3202 if( pDelete ){
3203 sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pDelete);
3204 }
3205 return rc;
3206}
3207#endif /* SQLITE_OMIT_COMPOUND_SELECT */
3208
3209/*
3210** Error message for when two or more terms of a compound select have different
3211** size result sets.
3212*/
3213void sqlite3SelectWrongNumTermsError(Parse *pParse, Select *p){
3214 if( p->selFlags & SF_Values ){
3215 sqlite3ErrorMsg(pParse, "all VALUES must have the same number of terms");
3216 }else{
3217 sqlite3ErrorMsg(pParse, "SELECTs to the left and right of %s"
3218 " do not have the same number of result columns",
3219 sqlite3SelectOpName(p->op));
3220 }
3221}
3222
3223/*
3224** Code an output subroutine for a coroutine implementation of a
3225** SELECT statement.
3226**
3227** The data to be output is contained in an array of pIn->nSdst registers
3228** starting at register pIn->iSdst. pDest is where the output should
3229** be sent.
3230**
3231** regReturn is the number of the register holding the subroutine
3232** return address.
3233**
3234** If regPrev>0 then it is the first register in a vector that
3235** records the previous output. mem[regPrev] is a flag that is false
3236** if there has been no previous output. If regPrev>0 then code is
3237** generated to suppress duplicates. pKeyInfo is used for comparing
3238** keys.
3239**
3240** If the LIMIT found in p->iLimit is reached, jump immediately to
3241** iBreak.
3242*/
3243static int generateOutputSubroutine(
3244 Parse *pParse, /* Parsing context */
3245 Select *p, /* The SELECT statement */
3246 SelectDest *pIn, /* Coroutine supplying data */
3247 SelectDest *pDest, /* Where to send the data */
3248 int regReturn, /* The return address register */
3249 int regPrev, /* Previous result register. No uniqueness if 0 */
3250 KeyInfo *pKeyInfo, /* For comparing with previous entry */
3251 int iBreak /* Jump here if we hit the LIMIT */
3252){
3253 Vdbe *v = pParse->pVdbe;
3254 int iContinue;
3255 int addr;
3256
3257 assert( pIn->eDest==SRT_Coroutine );
3258
3259 addr = sqlite3VdbeCurrentAddr(v);
3260 iContinue = sqlite3VdbeMakeLabel(pParse);
3261
3262 /* Suppress duplicates for UNION, EXCEPT, and INTERSECT
3263 */
3264 if( regPrev ){
3265 int addr1, addr2;
3266 addr1 = sqlite3VdbeAddOp1(v, OP_IfNot, regPrev); VdbeCoverage(v);
3267 addr2 = sqlite3VdbeAddOp4(v, OP_Compare, pIn->iSdst, regPrev+1, pIn->nSdst,
3268 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
3269 sqlite3VdbeAddOp3(v, OP_Jump, addr2+2, iContinue, addr2+2); VdbeCoverage(v);
3270 sqlite3VdbeJumpHere(v, addr1);
3271 sqlite3VdbeAddOp3(v, OP_Copy, pIn->iSdst, regPrev+1, pIn->nSdst-1);
3272 sqlite3VdbeAddOp2(v, OP_Integer, 1, regPrev);
3273 }
3274 if( pParse->db->mallocFailed ) return 0;
3275
3276 /* Suppress the first OFFSET entries if there is an OFFSET clause
3277 */
3278 codeOffset(v, p->iOffset, iContinue);
3279
3280 switch( pDest->eDest ){
3281 /* Store the result as data using a unique key.
3282 */
3283 case SRT_Fifo:
3284 case SRT_DistFifo:
3285#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
3286 case SRT_Table:
3287#endif
3288 case SRT_EphemTab: {
3289 int r1 = sqlite3GetTempReg(pParse);
3290 int r2 = sqlite3GetTempReg(pParse);
3291 int iParm = pDest->iSDParm;
3292 testcase( pDest->eDest==SRT_EphemTab );
3293 testcase( pDest->eDest==SRT_Fifo );
3294 testcase( pDest->eDest==SRT_DistFifo );
3295 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r1);
3296#ifdef SQLITE_ENABLE_UPDATE_DELETE_LIMIT
3297 testcase( pDest->eDest==SRT_Table );
3298#if !defined(SQLITE_ENABLE_NULL_TRIM) && defined(SQLITE_DEBUG)
3299 /* A destination of SRT_Table and a non-zero iSDParm2 parameter means
3300 ** that this is an "UPDATE ... FROM" on a virtual table or view. In this
3301 ** case set the p5 parameter of the OP_MakeRecord to OPFLAG_NOCHNG_MAGIC.
3302 ** This does not affect operation in any way - it just allows MakeRecord
3303 ** to process OPFLAG_NOCHANGE values without an assert() failing. */
3304 if( pDest->eDest==SRT_Table && pDest->iSDParm2 ){
3305 sqlite3VdbeChangeP5(v, OPFLAG_NOCHNG_MAGIC);
3306 }
3307#endif /* !ENABLE_NULL_TRIM && DEBUG */
3308#endif /* UPDATE_DELETE_LIMIT */
3309#ifndef SQLITE_OMIT_CTE
3310 if( pDest->eDest==SRT_DistFifo ){
3311 /* If the destination is DistFifo, then cursor (iParm+1) is open
3312 ** on an ephemeral index that is used to enforce uniqueness on the
3313 ** total result. At this point, we are processing the setup portion
3314 ** of the recursive CTE using the merge algorithm, so the results are
3315 ** guaranteed to be unique anyhow. But we still need to populate the
3316 ** (iParm+1) cursor for use by the subsequent recursive phase.
3317 */
3318 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm+1, r1,
3319 pIn->iSdst, pIn->nSdst);
3320 }
3321#endif
3322 sqlite3VdbeAddOp2(v, OP_NewRowid, iParm, r2);
3323 sqlite3VdbeAddOp3(v, OP_Insert, iParm, r1, r2);
3324 sqlite3VdbeChangeP5(v, OPFLAG_APPEND);
3325 sqlite3ReleaseTempReg(pParse, r2);
3326 sqlite3ReleaseTempReg(pParse, r1);
3327 break;
3328 }
3329
3330 /* If any row exist in the result set, record that fact and abort.
3331 */
3332 case SRT_Exists: {
3333 sqlite3VdbeAddOp2(v, OP_Integer, 1, pDest->iSDParm);
3334 /* The LIMIT clause will terminate the loop for us */
3335 break;
3336 }
3337
3338#ifndef SQLITE_OMIT_SUBQUERY
3339 /* If we are creating a set for an "expr IN (SELECT ...)".
3340 */
3341 case SRT_Set: {
3342 int r1;
3343 testcase( pIn->nSdst>1 );
3344 r1 = sqlite3GetTempReg(pParse);
3345 sqlite3VdbeAddOp4(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst,
3346 r1, pDest->zAffSdst, pIn->nSdst);
3347 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pDest->iSDParm, r1,
3348 pIn->iSdst, pIn->nSdst);
3349 if( pDest->iSDParm2>0 ){
3350 assert( sqlite3CursorBloomable(pParse, pDest->iSDParm, pIn->nSdst) );
3351 sqlite3VdbeAddOp4Int(v, OP_FilterAdd, pDest->iSDParm2, 0,
3352 pIn->iSdst, pIn->nSdst);
3353 ExplainQueryPlan((pParse, 0, "CREATE BLOOM FILTER"));
3354 }
3355 sqlite3ReleaseTempReg(pParse, r1);
3356 break;
3357 }
3358
3359 /* If this is a scalar select that is part of an expression, then
3360 ** store the results in the appropriate memory cell and break out
3361 ** of the scan loop. Note that the select might return multiple columns
3362 ** if it is the RHS of a row-value IN operator.
3363 */
3364 case SRT_Mem: {
3365 testcase( pIn->nSdst>1 );
3366 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSDParm, pIn->nSdst);
3367 /* The LIMIT clause will jump out of the loop for us */
3368 break;
3369 }
3370#endif /* #ifndef SQLITE_OMIT_SUBQUERY */
3371
3372 /* The results are stored in a sequence of registers
3373 ** starting at pDest->iSdst. Then the co-routine yields.
3374 */
3375 case SRT_Coroutine: {
3376 if( pDest->iSdst==0 ){
3377 pDest->iSdst = sqlite3GetTempRange(pParse, pIn->nSdst);
3378 pDest->nSdst = pIn->nSdst;
3379 }
3380 sqlite3ExprCodeMove(pParse, pIn->iSdst, pDest->iSdst, pIn->nSdst);
3381 sqlite3VdbeAddOp1(v, OP_Yield, pDest->iSDParm);
3382 break;
3383 }
3384
3385#ifndef SQLITE_OMIT_CTE
3386 /* Write the results into a priority queue that is order according to
3387 ** pDest->pOrderBy (in pSO). pDest->iSDParm (in iParm) is the cursor for an
3388 ** index with pSO->nExpr+2 columns. Build a key using pSO for the first
3389 ** pSO->nExpr columns, then make sure all keys are unique by adding a
3390 ** final OP_Sequence column. The last column is the record as a blob.
3391 */
3392 case SRT_DistQueue:
3393 case SRT_Queue: {
3394 int nKey;
3395 int r1, r2, r3, ii;
3396 ExprList *pSO;
3397 int iParm = pDest->iSDParm;
3398 pSO = pDest->pOrderBy;
3399 assert( pSO );
3400 nKey = pSO->nExpr;
3401 r1 = sqlite3GetTempReg(pParse);
3402 r2 = sqlite3GetTempRange(pParse, nKey+2);
3403 r3 = r2+nKey+1;
3404
3405 sqlite3VdbeAddOp3(v, OP_MakeRecord, pIn->iSdst, pIn->nSdst, r3);
3406 if( pDest->eDest==SRT_DistQueue ){
3407 sqlite3VdbeAddOp2(v, OP_IdxInsert, iParm+1, r3);
3408 }
3409 for(ii=0; ii<nKey; ii++){
3410 sqlite3VdbeAddOp2(v, OP_SCopy,
3411 pIn->iSdst + pSO->a[ii].u.x.iOrderByCol - 1,
3412 r2+ii);
3413 }
3414 sqlite3VdbeAddOp2(v, OP_Sequence, iParm, r2+nKey);
3415 sqlite3VdbeAddOp3(v, OP_MakeRecord, r2, nKey+2, r1);
3416 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, iParm, r1, r2, nKey+2);
3417 sqlite3ReleaseTempReg(pParse, r1);
3418 sqlite3ReleaseTempRange(pParse, r2, nKey+2);
3419 break;
3420 }
3421#endif /* SQLITE_OMIT_CTE */
3422
3423 /* Ignore the output */
3424 case SRT_Discard: {
3425 break;
3426 }
3427
3428 /* If none of the above, then the result destination must be
3429 ** SRT_Output.
3430 **
3431 ** For SRT_Output, results are stored in a sequence of registers.
3432 ** Then the OP_ResultRow opcode is used to cause sqlite3_step() to
3433 ** return the next row of result.
3434 */
3435 default: {
3436 assert( pDest->eDest==SRT_Output );
3437 sqlite3VdbeAddOp2(v, OP_ResultRow, pIn->iSdst, pIn->nSdst);
3438 break;
3439 }
3440 }
3441
3442 /* Jump to the end of the loop if the LIMIT is reached.
3443 */
3444 if( p->iLimit ){
3445 sqlite3VdbeAddOp2(v, OP_DecrJumpZero, p->iLimit, iBreak); VdbeCoverage(v);
3446 }
3447
3448 /* Generate the subroutine return
3449 */
3450 sqlite3VdbeResolveLabel(v, iContinue);
3451 sqlite3VdbeAddOp1(v, OP_Return, regReturn);
3452
3453 return addr;
3454}
3455
3456/*
3457** Generate code for a compound SELECT statement using a merge
3458** algorithm. The compound must have an ORDER BY clause for this
3459** to work.
3460**
3461** We assume a query of the following form:
3462**
3463** <selectA> <operator> <selectB> ORDER BY <orderbylist>
3464**
3465** <operator> is one of UNION ALL, UNION, EXCEPT, or INTERSECT. The idea
3466** is to code both <selectA> and <selectB> with the ORDER BY clause as
3467** co-routines. Then run the co-routines in parallel and merge the results
3468** into the output. In addition to the two coroutines (called selectA and
3469** selectB) there are 7 subroutines:
3470**
3471** outA: Move the output of the selectA coroutine into the output
3472** of the compound query.
3473**
3474** outB: Move the output of the selectB coroutine into the output
3475** of the compound query. (Only generated for UNION and
3476** UNION ALL. EXCEPT and INTERSECT never output a row that
3477** appears only in B.)
3478**
3479** AltB: Called when there is data from both coroutines and A<B.
3480**
3481** AeqB: Called when there is data from both coroutines and A==B.
3482**
3483** AgtB: Called when there is data from both coroutines and A>B.
3484**
3485** EofA: Called when data is exhausted from selectA.
3486**
3487** EofB: Called when data is exhausted from selectB.
3488**
3489** The implementation of the latter five subroutines depend on which
3490** <operator> is used:
3491**
3492**
3493** UNION ALL UNION EXCEPT INTERSECT
3494** ------------- ----------------- -------------- -----------------
3495** AltB: outA, nextA outA, nextA outA, nextA nextA
3496**
3497** AeqB: outA, nextA nextA nextA outA, nextA
3498**
3499** AgtB: outB, nextB outB, nextB nextB nextB
3500**
3501** EofA: outB, nextB outB, nextB halt halt
3502**
3503** EofB: outA, nextA outA, nextA outA, nextA halt
3504**
3505** In the AltB, AeqB, and AgtB subroutines, an EOF on A following nextA
3506** causes an immediate jump to EofA and an EOF on B following nextB causes
3507** an immediate jump to EofB. Within EofA and EofB, and EOF on entry or
3508** following nextX causes a jump to the end of the select processing.
3509**
3510** Duplicate removal in the UNION, EXCEPT, and INTERSECT cases is handled
3511** within the output subroutine. The regPrev register set holds the previously
3512** output value. A comparison is made against this value and the output
3513** is skipped if the next results would be the same as the previous.
3514**
3515** The implementation plan is to implement the two coroutines and seven
3516** subroutines first, then put the control logic at the bottom. Like this:
3517**
3518** goto Init
3519** coA: coroutine for left query (A)
3520** coB: coroutine for right query (B)
3521** outA: output one row of A
3522** outB: output one row of B (UNION and UNION ALL only)
3523** EofA: ...
3524** EofB: ...
3525** AltB: ...
3526** AeqB: ...
3527** AgtB: ...
3528** Init: initialize coroutine registers
3529** yield coA, on eof goto EofA
3530** yield coB, on eof goto EofB
3531** Cmpr: Compare A, B
3532** Jump AltB, AeqB, AgtB
3533** End: ...
3534**
3535** We call AltB, AeqB, AgtB, EofA, and EofB "subroutines" but they are not
3536** actually called using Gosub and they do not Return. EofA and EofB loop
3537** until all data is exhausted then jump to the "end" label. AltB, AeqB,
3538** and AgtB jump to either Cmpr or to one of EofA or EofB.
3539*/
3540#ifndef SQLITE_OMIT_COMPOUND_SELECT
3541static int multiSelectByMerge(
3542 Parse *pParse, /* Parsing context */
3543 Select *p, /* The right-most of SELECTs to be coded */
3544 SelectDest *pDest /* What to do with query results */
3545){
3546 int i, j; /* Loop counters */
3547 Select *pPrior; /* Another SELECT immediately to our left */
3548 Select *pSplit; /* Left-most SELECT in the right-hand group */
3549 int nSelect; /* Number of SELECT statements in the compound */
3550 Vdbe *v; /* Generate code to this VDBE */
3551 SelectDest destA; /* Destination for coroutine A */
3552 SelectDest destB; /* Destination for coroutine B */
3553 int regAddrA; /* Address register for select-A coroutine */
3554 int regAddrB; /* Address register for select-B coroutine */
3555 int addrSelectA; /* Address of the select-A coroutine */
3556 int addrSelectB; /* Address of the select-B coroutine */
3557 int regOutA; /* Address register for the output-A subroutine */
3558 int regOutB; /* Address register for the output-B subroutine */
3559 int addrOutA; /* Address of the output-A subroutine */
3560 int addrOutB = 0; /* Address of the output-B subroutine */
3561 int addrEofA; /* Address of the select-A-exhausted subroutine */
3562 int addrEofA_noB; /* Alternate addrEofA if B is uninitialized */
3563 int addrEofB; /* Address of the select-B-exhausted subroutine */
3564 int addrAltB; /* Address of the A<B subroutine */
3565 int addrAeqB; /* Address of the A==B subroutine */
3566 int addrAgtB; /* Address of the A>B subroutine */
3567 int regLimitA; /* Limit register for select-A */
3568 int regLimitB; /* Limit register for select-A */
3569 int regPrev; /* A range of registers to hold previous output */
3570 int savedLimit; /* Saved value of p->iLimit */
3571 int savedOffset; /* Saved value of p->iOffset */
3572 int labelCmpr; /* Label for the start of the merge algorithm */
3573 int labelEnd; /* Label for the end of the overall SELECT stmt */
3574 int addr1; /* Jump instructions that get retargeted */
3575 int op; /* One of TK_ALL, TK_UNION, TK_EXCEPT, TK_INTERSECT */
3576 KeyInfo *pKeyDup = 0; /* Comparison information for duplicate removal */
3577 KeyInfo *pKeyMerge; /* Comparison information for merging rows */
3578 sqlite3 *db; /* Database connection */
3579 ExprList *pOrderBy; /* The ORDER BY clause */
3580 int nOrderBy; /* Number of terms in the ORDER BY clause */
3581 u32 *aPermute; /* Mapping from ORDER BY terms to result set columns */
3582
3583 assert( p->pOrderBy!=0 );
3584 assert( pKeyDup==0 ); /* "Managed" code needs this. Ticket #3382. */
3585 db = pParse->db;
3586 v = pParse->pVdbe;
3587 assert( v!=0 ); /* Already thrown the error if VDBE alloc failed */
3588 labelEnd = sqlite3VdbeMakeLabel(pParse);
3589 labelCmpr = sqlite3VdbeMakeLabel(pParse);
3590
3591
3592 /* Patch up the ORDER BY clause
3593 */
3594 op = p->op;
3595 assert( p->pPrior->pOrderBy==0 );
3596 pOrderBy = p->pOrderBy;
3597 assert( pOrderBy );
3598 nOrderBy = pOrderBy->nExpr;
3599
3600 /* For operators other than UNION ALL we have to make sure that
3601 ** the ORDER BY clause covers every term of the result set. Add
3602 ** terms to the ORDER BY clause as necessary. Do the same for UNION ALL
3603 ** if any operator to the left is not UNION ALL, so that the ORDER BY
3604 ** carries the collation of every column into that sub-compound.
3605 */
3606 for(pPrior=p; pPrior && pPrior->op==TK_ALL; pPrior=pPrior->pPrior){}
3607 if( pPrior && pPrior->pPrior ){
3608 for(i=1; db->mallocFailed==0 && i<=p->pEList->nExpr; i++){
3609 struct ExprList_item *pItem;
3610 for(j=0, pItem=pOrderBy->a; j<nOrderBy; j++, pItem++){
3611 assert( pItem!=0 );
3612 assert( pItem->u.x.iOrderByCol>0 );
3613 if( pItem->u.x.iOrderByCol==i ) break;
3614 }
3615 if( j==nOrderBy ){
3616 Expr *pNew = sqlite3ExprInt32(db, i);
3617 if( pNew==0 ) return SQLITE_NOMEM_BKPT;
3618 p->pOrderBy = pOrderBy = sqlite3ExprListAppend(pParse, pOrderBy, pNew);
3619 if( pOrderBy ) pOrderBy->a[nOrderBy++].u.x.iOrderByCol = (u16)i;
3620 }
3621 }
3622 }
3623
3624 /* Compute the comparison permutation and keyinfo that is used with
3625 ** the permutation to determine if the next row of results comes
3626 ** from selectA or selectB. Also add literal collations to the
3627 ** ORDER BY clause terms so that when selectA and selectB are
3628 ** evaluated, they use the correct collation.
3629 */
3630 aPermute = sqlite3DbMallocRawNN(db, sizeof(u32)*(nOrderBy + 1));
3631 if( aPermute ){
3632 struct ExprList_item *pItem;
3633 int bKeep = 0;
3634 aPermute[0] = nOrderBy;
3635 for(i=1, pItem=pOrderBy->a; i<=nOrderBy; i++, pItem++){
3636 assert( pItem!=0 );
3637 assert( pItem->u.x.iOrderByCol>0 );
3638 assert( pItem->u.x.iOrderByCol<=p->pEList->nExpr );
3639 aPermute[i] = pItem->u.x.iOrderByCol - 1;
3640 if( aPermute[i]!=(u32)i-1 ) bKeep = 1;
3641 }
3642 if( bKeep==0 ){
3643 sqlite3DbFreeNN(db, aPermute);
3644 aPermute = 0;
3645 }
3646 }
3647 pKeyMerge = multiSelectByMergeKeyInfo(pParse, p, 1);
3648
3649 /* Allocate a range of temporary registers and the KeyInfo needed
3650 ** for the logic that removes duplicate result rows when the
3651 ** operator is UNION, EXCEPT, or INTERSECT (but not UNION ALL).
3652 */
3653 if( op==TK_ALL ){
3654 regPrev = 0;
3655 }else{
3656 int nExpr = p->pEList->nExpr;
3657 assert( nOrderBy>=nExpr || db->mallocFailed );
3658 regPrev = pParse->nMem+1;
3659 pParse->nMem += nExpr+1;
3660 sqlite3VdbeAddOp2(v, OP_Integer, 0, regPrev);
3661 pKeyDup = sqlite3KeyInfoAlloc(db, nExpr, 1);
3662 if( pKeyDup ){
3663 assert( sqlite3KeyInfoIsWriteable(pKeyDup) );
3664 /* Use the ORDER BY collations, not multiSelectCollSeq(p), because
3665 ** p might be just one part of a larger compound, in which case
3666 ** the ORDER BY carries the COLLATE of the larger compound. */
3667 for(i=0; ALWAYS(pKeyMerge) && i<nOrderBy; i++){
3668 pKeyDup->aColl[pOrderBy->a[i].u.x.iOrderByCol-1] = pKeyMerge->aColl[i];
3669 }
3670 }
3671 }
3672
3673 /* Separate the left and the right query from one another
3674 */
3675 nSelect = 1;
3676 if( (op==TK_ALL || op==TK_UNION)
3677 && OptimizationEnabled(db, SQLITE_BalancedMerge)
3678 ){
3679 for(pSplit=p; pSplit->pPrior!=0 && pSplit->op==op; pSplit=pSplit->pPrior){
3680 nSelect++;
3681 assert( pSplit->pPrior->pNext==pSplit );
3682 }
3683 }
3684 if( nSelect<=3 ){
3685 pSplit = p;
3686 }else{
3687 pSplit = p;
3688 for(i=2; i<nSelect; i+=2){ pSplit = pSplit->pPrior; }
3689 }
3690 pPrior = pSplit->pPrior;
3691 assert( pPrior!=0 );
3692 pSplit->pPrior = 0;
3693 pPrior->pNext = 0;
3694 assert( p->pOrderBy == pOrderBy );
3695 assert( pOrderBy!=0 || db->mallocFailed );
3696 pPrior->pOrderBy = sqlite3ExprListDup(pParse->db, pOrderBy, 0);
3697 sqlite3ResolveOrderGroupBy(pParse, p, p->pOrderBy, "ORDER");
3698 sqlite3ResolveOrderGroupBy(pParse, pPrior, pPrior->pOrderBy, "ORDER");
3699
3700 /* Compute the limit registers */
3701 computeLimitRegisters(pParse, p, labelEnd);
3702 if( p->iLimit && (op==TK_ALL || unionWithLimitOne(db,p)) ){
3703 regLimitA = ++pParse->nMem;
3704 regLimitB = ++pParse->nMem;
3705 sqlite3VdbeAddOp2(v, OP_Copy, p->iOffset ? p->iOffset+1 : p->iLimit,
3706 regLimitA);
3707 sqlite3VdbeAddOp2(v, OP_Copy, regLimitA, regLimitB);
3708 }else{
3709 regLimitA = regLimitB = 0;
3710 }
3711 sqlite3ExprDelete(db, p->pLimit);
3712 p->pLimit = 0;
3713
3714 regAddrA = ++pParse->nMem;
3715 regAddrB = ++pParse->nMem;
3716 regOutA = ++pParse->nMem;
3717 regOutB = ++pParse->nMem;
3718 sqlite3SelectDestInit(&destA, SRT_Coroutine, regAddrA);
3719 sqlite3SelectDestInit(&destB, SRT_Coroutine, regAddrB);
3720
3721 ExplainQueryPlan((pParse, 1, "MERGE (%s)", sqlite3SelectOpName(p->op)));
3722
3723 /* Generate a coroutine to evaluate the SELECT statement to the
3724 ** left of the compound operator - the "A" select.
3725 */
3726 addrSelectA = sqlite3VdbeCurrentAddr(v) + 1;
3727 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrA, 0, addrSelectA);
3728 VdbeComment((v, "SUBR: next-A"));
3729 pPrior->iLimit = regLimitA;
3730 ExplainQueryPlan((pParse, 1, "LEFT"));
3731 sqlite3Select(pParse, pPrior, &destA);
3732 sqlite3VdbeEndCoroutine(v, regAddrA);
3733 sqlite3VdbeJumpHere(v, addr1);
3734
3735 /* Generate a coroutine to evaluate the SELECT statement on
3736 ** the right - the "B" select
3737 */
3738 addrSelectB = sqlite3VdbeCurrentAddr(v) + 1;
3739 addr1 = sqlite3VdbeAddOp3(v, OP_InitCoroutine, regAddrB, 0, addrSelectB);
3740 VdbeComment((v, "SUBR: next-B"));
3741 savedLimit = p->iLimit;
3742 savedOffset = p->iOffset;
3743 p->iLimit = regLimitB;
3744 p->iOffset = 0;
3745 ExplainQueryPlan((pParse, 1, "RIGHT"));
3746 sqlite3Select(pParse, p, &destB);
3747 p->iLimit = savedLimit;
3748 p->iOffset = savedOffset;
3749 sqlite3VdbeEndCoroutine(v, regAddrB);
3750
3751 /* Generate a subroutine that outputs the current row of the A
3752 ** select as the next output row of the compound select.
3753 */
3754 VdbeNoopComment((v, "SUBR: out-A"));
3755 addrOutA = generateOutputSubroutine(pParse,
3756 p, &destA, pDest, regOutA,
3757 regPrev, pKeyDup, labelEnd);
3758
3759 /* Generate a subroutine that outputs the current row of the B
3760 ** select as the next output row of the compound select.
3761 */
3762 if( op==TK_ALL || op==TK_UNION ){
3763 VdbeNoopComment((v, "SUBR: out-B"));
3764 addrOutB = generateOutputSubroutine(pParse,
3765 p, &destB, pDest, regOutB,
3766 regPrev, pKeyDup, labelEnd);
3767 }
3768 sqlite3KeyInfoUnref(pKeyDup);
3769
3770 /* Generate a subroutine to run when the results from select A
3771 ** are exhausted and only data in select B remains.
3772 */
3773 if( op==TK_EXCEPT || op==TK_INTERSECT ){
3774 addrEofA_noB = addrEofA = labelEnd;
3775 }else{
3776 VdbeNoopComment((v, "SUBR: eof-A"));
3777 addrEofA = sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3778 VdbeComment((v, "out-B"));
3779 addrEofA_noB = sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, labelEnd);
3780 VdbeCoverage(v);
3781 VdbeComment((v, "next-B"));
3782 sqlite3VdbeGoto(v, addrEofA);
3783 p->nSelectRow = sqlite3LogEstAdd(p->nSelectRow, pPrior->nSelectRow);
3784 }
3785
3786 /* Generate a subroutine to run when the results from select B
3787 ** are exhausted and only data in select A remains.
3788 */
3789 if( op==TK_INTERSECT ){
3790 addrEofB = addrEofA;
3791 if( p->nSelectRow > pPrior->nSelectRow ) p->nSelectRow = pPrior->nSelectRow;
3792 }else{
3793 VdbeNoopComment((v, "SUBR: eof-B"));
3794 addrEofB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3795 VdbeComment((v, "out-A"));
3796 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, labelEnd); VdbeCoverage(v);
3797 VdbeComment((v, "next-A"));
3798 sqlite3VdbeGoto(v, addrEofB);
3799 }
3800
3801 /* Generate code to handle the case of A<B
3802 */
3803 addrAltB = sqlite3VdbeAddOp2(v, OP_Gosub, regOutA, addrOutA);
3804 VdbeComment((v, "out-A"));
3805 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA); VdbeCoverage(v);
3806 VdbeComment((v, "next-A"));
3807 sqlite3VdbeGoto(v, labelCmpr);
3808
3809 /* Generate code to handle the case of A==B
3810 */
3811 if( op==TK_ALL ){
3812 addrAeqB = addrAltB;
3813 }else if( op==TK_INTERSECT ){
3814 addrAeqB = addrAltB;
3815 addrAltB++;
3816 }else{
3817 addrAeqB = addrAltB + 1;
3818 }
3819
3820 /* Generate code to handle the case of A>B
3821 */
3822 addrAgtB = sqlite3VdbeCurrentAddr(v);
3823 if( op==TK_ALL || op==TK_UNION ){
3824 sqlite3VdbeAddOp2(v, OP_Gosub, regOutB, addrOutB);
3825 VdbeComment((v, "out-B"));
3826 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3827 VdbeComment((v, "next-B"));
3828 sqlite3VdbeGoto(v, labelCmpr);
3829 }else{
3830 addrAgtB++; /* Just do next-B. Might as well use the next-B call
3831 ** in the next code block */
3832 }
3833
3834 /* This code runs once to initialize everything.
3835 */
3836 sqlite3VdbeJumpHere(v, addr1);
3837 sqlite3VdbeAddOp2(v, OP_Yield, regAddrA, addrEofA_noB); VdbeCoverage(v);
3838 VdbeComment((v, "next-A"));
3839 /* v--- Also the A>B case for EXCEPT and INTERSECT */
3840 sqlite3VdbeAddOp2(v, OP_Yield, regAddrB, addrEofB); VdbeCoverage(v);
3841 VdbeComment((v, "next-B"));
3842
3843 /* Implement the main merge loop
3844 */
3845 if( aPermute!=0 ){
3846 sqlite3VdbeAddOp4(v, OP_Permutation, 0, 0, 0, (char*)aPermute, P4_INTARRAY);
3847 }
3848 sqlite3VdbeResolveLabel(v, labelCmpr);
3849 sqlite3VdbeAddOp4(v, OP_Compare, destA.iSdst, destB.iSdst, nOrderBy,
3850 (char*)pKeyMerge, P4_KEYINFO);
3851 if( aPermute!=0 ){
3852 sqlite3VdbeChangeP5(v, OPFLAG_PERMUTE);
3853 }
3854 sqlite3VdbeAddOp3(v, OP_Jump, addrAltB, addrAeqB, addrAgtB);
3855 VdbeCoverageIf(v, op==TK_ALL);
3856 VdbeCoverageIf(v, op==TK_UNION);
3857 VdbeCoverageIf(v, op==TK_EXCEPT);
3858 VdbeCoverageIf(v, op==TK_INTERSECT);
3859
3860 /* Jump to the this point in order to terminate the query.
3861 */
3862 sqlite3VdbeResolveLabel(v, labelEnd);
3863
3864 /* Make arrangements to free the 2nd and subsequent arms of the compound
3865 ** after the parse has finished */
3866 if( pSplit->pPrior ){
3867 sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSplit->pPrior);
3868 }
3869 pSplit->pPrior = pPrior;
3870 pPrior->pNext = pSplit;
3871 sqlite3ExprListDelete(db, pPrior->pOrderBy);
3872 pPrior->pOrderBy = 0;
3873
3874 /*** TBD: Insert subroutine calls to close cursors on incomplete
3875 **** subqueries ****/
3876 ExplainQueryPlanPop(pParse);
3877 return pParse->nErr!=0;
3878}
3879#endif
3880
3881#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
3882
3883/* An instance of the SubstContext object describes an substitution edit
3884** to be performed on a parse tree.
3885**
3886** All references to columns in table iTable are to be replaced by corresponding
3887** expressions in pEList.
3888**
3889** ## About "isOuterJoin":
3890**
3891** The isOuterJoin column indicates that the replacement will occur into a
3892** position in the parent that is NULL-able due to an OUTER JOIN. Either the
3893** target slot in the parent is the right operand of a LEFT JOIN, or one of
3894** the left operands of a RIGHT JOIN. In either case, we need to potentially
3895** bypass the substituted expression with OP_IfNullRow.
3896**
3897** Suppose the original expression is an integer constant. Even though the table
3898** has the nullRow flag set, because the expression is an integer constant,
3899** it will not be NULLed out. So instead, we insert an OP_IfNullRow opcode
3900** that checks to see if the nullRow flag is set on the table. If the nullRow
3901** flag is set, then the value in the register is set to NULL and the original
3902** expression is bypassed. If the nullRow flag is not set, then the original
3903** expression runs to populate the register.
3904**
3905** Example where this is needed:
3906**
3907** CREATE TABLE t1(a INTEGER PRIMARY KEY, b INT);
3908** CREATE TABLE t2(x INT UNIQUE);
3909**
3910** SELECT a,b,m,x FROM t1 LEFT JOIN (SELECT 59 AS m,x FROM t2) ON b=x;
3911**
3912** When the subquery on the right side of the LEFT JOIN is flattened, we
3913** have to add OP_IfNullRow in front of the OP_Integer that implements the
3914** "m" value of the subquery so that a NULL will be loaded instead of 59
3915** when processing a non-matched row of the left.
3916**
3917** ## Unwrap mode:
3918**
3919** If pEList is NULL, then the SubstContext is being used by
3920** unwrapIfNullRow() to remove TK_IF_NULL_ROW wrappers instead of to
3921** substitute column references. In that mode, only the TK_IF_NULL_ROW
3922** nodes with iTable==iTable are touched, each one being replaced by its
3923** operand. Column references are left alone and iNewTable must equal
3924** iTable.
3925*/
3926typedef struct SubstContext {
3927 Parse *pParse; /* The parsing context */
3928 int iTable; /* Replace references to this table */
3929 int iNewTable; /* New table number */
3930 int isOuterJoin; /* Add TK_IF_NULL_ROW opcodes on each replacement */
3931 int nSelDepth; /* Depth of sub-query recursion. Top==1 */
3932 ExprList *pEList; /* Replacement expressions */
3933 ExprList *pCList; /* Collation sequences for replacement expr */
3934} SubstContext;
3935
3936/* Forward Declarations */
3937static void substExprList(SubstContext*, ExprList*);
3938static void substSelect(SubstContext*, Select*, int);
3939
3940/*
3941** Scan through the expression pExpr. Replace every reference to
3942** a column in table number iTable with a copy of the iColumn-th
3943** entry in pEList. (But leave references to the ROWID column
3944** unchanged.)
3945**
3946** This routine is part of the flattening procedure. A subquery
3947** whose result set is defined by pEList appears as entry in the
3948** FROM clause of a SELECT such that the VDBE cursor assigned to that
3949** FORM clause entry is iTable. This routine makes the necessary
3950** changes to pExpr so that it refers directly to the source table
3951** of the subquery rather the result set of the subquery.
3952*/
3953static Expr *substExpr(
3954 SubstContext *pSubst, /* Description of the substitution */
3955 Expr *pExpr /* Expr in which substitution occurs */
3956){
3957 if( pExpr==0 ) return 0;
3958 if( ExprHasProperty(pExpr, EP_OuterON|EP_InnerON)
3959 && pExpr->w.iJoin==pSubst->iTable
3960 ){
3961 testcase( ExprHasProperty(pExpr, EP_InnerON) );
3962 pExpr->w.iJoin = pSubst->iNewTable;
3963 }
3964 if( pExpr->op==TK_COLUMN
3965 && pExpr->iTable==pSubst->iTable
3966 && pSubst->pEList!=0
3967 && !ExprHasProperty(pExpr, EP_FixedCol)
3968 ){
3969#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
3970 if( pExpr->iColumn<0 ){
3971 pExpr->op = TK_NULL;
3972 }else
3973#endif
3974 {
3975 Expr *pNew;
3976 int iColumn;
3977 Expr *pCopy;
3978 Expr ifNullRow;
3979 iColumn = pExpr->iColumn;
3980 assert( iColumn>=0 );
3981 assert( pSubst->pEList!=0 && iColumn<pSubst->pEList->nExpr );
3982 assert( pExpr->pRight==0 );
3983 pCopy = pSubst->pEList->a[iColumn].pExpr;
3984 if( sqlite3ExprIsVector(pCopy) ){
3985 sqlite3VectorErrorMsg(pSubst->pParse, pCopy);
3986 }else{
3987 sqlite3 *db = pSubst->pParse->db;
3988 if( pSubst->isOuterJoin
3989 && (pCopy->op!=TK_COLUMN || pCopy->iTable!=pSubst->iNewTable)
3990 ){
3991 memset(&ifNullRow, 0, sizeof(ifNullRow));
3992 ifNullRow.op = TK_IF_NULL_ROW;
3993 ifNullRow.pLeft = pCopy;
3994 ifNullRow.iTable = pSubst->iNewTable;
3995 ifNullRow.iColumn = -99;
3996 ifNullRow.flags = EP_IfNullRow;
3997 pCopy = &ifNullRow;
3998 }
3999 testcase( ExprHasProperty(pCopy, EP_Subquery) );
4000 pNew = sqlite3ExprDup(db, pCopy, 0);
4001 if( db->mallocFailed ){
4002 sqlite3ExprDelete(db, pNew);
4003 return pExpr;
4004 }
4005 if( pSubst->isOuterJoin ){
4006 ExprSetProperty(pNew, EP_CanBeNull);
4007 }
4008 if( pNew->op==TK_TRUEFALSE ){
4009 pNew->u.iValue = sqlite3ExprTruthValue(pNew);
4010 pNew->op = TK_INTEGER;
4011 ExprSetProperty(pNew, EP_IntValue);
4012 }
4013
4014 /* Ensure that the expression now has an implicit collation sequence,
4015 ** just as it did when it was a column of a view or sub-query. */
4016 {
4017 CollSeq *pNat = sqlite3ExprCollSeq(pSubst->pParse, pNew);
4018 CollSeq *pColl = sqlite3ExprCollSeq(pSubst->pParse,
4019 pSubst->pCList->a[iColumn].pExpr
4020 );
4021 if( pNat!=pColl || (pNew->op!=TK_COLUMN && pNew->op!=TK_COLLATE) ){
4022 pNew = sqlite3ExprAddCollateString(pSubst->pParse, pNew,
4023 (pColl ? pColl->zName : "BINARY")
4024 );
4025 }
4026 }
4027 ExprClearProperty(pNew, EP_Collate);
4028 if( ExprHasProperty(pExpr,EP_OuterON|EP_InnerON) ){
4029 sqlite3SetJoinExpr(pNew, pExpr->w.iJoin,
4030 pExpr->flags & (EP_OuterON|EP_InnerON));
4031 }
4032 sqlite3ExprDelete(db, pExpr);
4033 pExpr = pNew;
4034 }
4035 }
4036 }else{
4037 if( pExpr->op==TK_IF_NULL_ROW && pExpr->iTable==pSubst->iTable ){
4038 if( pSubst->pEList==0 ){
4039 /* Unwrap mode. See unwrapIfNullRow(). */
4040 Expr *pInner = pExpr->pLeft;
4041 pExpr->pLeft = 0;
4042 sqlite3ExprDelete(pSubst->pParse->db, pExpr);
4043 return substExpr(pSubst, pInner);
4044 }
4045 pExpr->iTable = pSubst->iNewTable;
4046 }
4047 if( pExpr->op==TK_AGG_FUNCTION
4048 && pSubst->pEList!=0
4049 && pExpr->op2>=pSubst->nSelDepth
4050 ){
4051 pExpr->op2--;
4052 }
4053 pExpr->pLeft = substExpr(pSubst, pExpr->pLeft);
4054 pExpr->pRight = substExpr(pSubst, pExpr->pRight);
4055 if( ExprUseXSelect(pExpr) ){
4056 substSelect(pSubst, pExpr->x.pSelect, 1);
4057 }else{
4058 substExprList(pSubst, pExpr->x.pList);
4059 }
4060#ifndef SQLITE_OMIT_WINDOWFUNC
4061 if( ExprHasProperty(pExpr, EP_WinFunc) ){
4062 Window *pWin = pExpr->y.pWin;
4063 pWin->pFilter = substExpr(pSubst, pWin->pFilter);
4064 substExprList(pSubst, pWin->pPartition);
4065 substExprList(pSubst, pWin->pOrderBy);
4066 }
4067#endif
4068 }
4069 return pExpr;
4070}
4071static void substExprList(
4072 SubstContext *pSubst, /* Description of the substitution */
4073 ExprList *pList /* List to scan and in which to make substitutes */
4074){
4075 int i;
4076 if( pList==0 ) return;
4077 for(i=0; i<pList->nExpr; i++){
4078 pList->a[i].pExpr = substExpr(pSubst, pList->a[i].pExpr);
4079 }
4080}
4081static void substSelect(
4082 SubstContext *pSubst, /* Description of the substitution */
4083 Select *p, /* SELECT statement in which to make substitutions */
4084 int doPrior /* Do substitutes on p->pPrior too */
4085){
4086 SrcList *pSrc;
4087 SrcItem *pItem;
4088 int i;
4089 if( !p ) return;
4090 pSubst->nSelDepth++;
4091 do{
4092 substExprList(pSubst, p->pEList);
4093 substExprList(pSubst, p->pGroupBy);
4094 substExprList(pSubst, p->pOrderBy);
4095 p->pHaving = substExpr(pSubst, p->pHaving);
4096 p->pWhere = substExpr(pSubst, p->pWhere);
4097 pSrc = p->pSrc;
4098 assert( pSrc!=0 );
4099 for(i=pSrc->nSrc, pItem=pSrc->a; i>0; i--, pItem++){
4100 if( pItem->fg.isSubquery ){
4101 substSelect(pSubst, pItem->u4.pSubq->pSelect, 1);
4102 }
4103 if( pItem->fg.isTabFunc ){
4104 substExprList(pSubst, pItem->u1.pFuncArg);
4105 }
4106 }
4107 }while( doPrior && (p = p->pPrior)!=0 );
4108 pSubst->nSelDepth--;
4109}
4110
4111/*
4112** The flattener wraps each substituted expression in a TK_IF_NULL_ROW
4113** operator when the subquery being flattened is on the NULL-able side of
4114** an outer join. The wrapper is keyed to the cursor iCur of the
4115** (single-table) subquery.
4116**
4117** If OUTER JOIN strength reduction later determines that the table with
4118** cursor iCur can no longer be a NULL row, then those wrappers are
4119** unnecessary. Worse, they are harmful if the FROM-clause term for iCur
4120** is itself a subquery that is flattened later. The flattener would
4121** then renumber the wrappers to refer to the first table of that
4122** subquery, and that table might legitimately be a NULL row (for example,
4123** if it is the left operand of a FULL JOIN inside the subquery). The
4124** substituted expressions would then be incorrectly forced to NULL.
4125**
4126** So when strength reduction removes the NULL-able status from the
4127** table at iCur, remove all of the TK_IF_NULL_ROW wrappers for iCur from
4128** the entire SELECT statement p.
4129*/
4130static void unwrapIfNullRow(Parse *pParse, Select *p, int iCur){
4131 SubstContext x;
4132 memset(&x, 0, sizeof(x));
4133 x.pParse = pParse;
4134 x.iTable = iCur;
4135 x.iNewTable = iCur;
4136 substSelect(&x, p, 0);
4137}
4138#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4139
4140#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4141/*
4142** pSelect is a SELECT statement and pSrcItem is one item in the FROM
4143** clause of that SELECT.
4144**
4145** This routine scans the entire SELECT statement and recomputes the
4146** pSrcItem->colUsed mask.
4147*/
4148static int recomputeColumnsUsedExpr(Walker *pWalker, Expr *pExpr){
4149 SrcItem *pItem;
4150 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
4151 pItem = pWalker->u.pSrcItem;
4152 if( pItem->iCursor!=pExpr->iTable ) return WRC_Continue;
4153 if( pExpr->iColumn<0 ) return WRC_Continue;
4154 pItem->colUsed |= sqlite3ExprColUsed(pExpr);
4155 return WRC_Continue;
4156}
4157static void recomputeColumnsUsed(
4158 Select *pSelect, /* The complete SELECT statement */
4159 SrcItem *pSrcItem /* Which FROM clause item to recompute */
4160){
4161 Walker w;
4162 if( NEVER(pSrcItem->pSTab==0) ) return;
4163 memset(&w, 0, sizeof(w));
4164 w.xExprCallback = recomputeColumnsUsedExpr;
4165 w.xSelectCallback = sqlite3SelectWalkNoop;
4166 w.u.pSrcItem = pSrcItem;
4167 pSrcItem->colUsed = 0;
4168 sqlite3WalkSelect(&w, pSelect);
4169}
4170#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4171
4172#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4173/*
4174** Assign new cursor numbers to each of the items in pSrc. For each
4175** new cursor number assigned, set an entry in the aCsrMap[] array
4176** to map the old cursor number to the new:
4177**
4178** aCsrMap[iOld+1] = iNew;
4179**
4180** The array is guaranteed by the caller to be large enough for all
4181** existing cursor numbers in pSrc. aCsrMap[0] is the array size.
4182**
4183** If pSrc contains any sub-selects, call this routine recursively
4184** on the FROM clause of each such sub-select, with iExcept set to -1.
4185*/
4186static void srclistRenumberCursors(
4187 Parse *pParse, /* Parse context */
4188 int *aCsrMap, /* Array to store cursor mappings in */
4189 SrcList *pSrc, /* FROM clause to renumber */
4190 int iExcept /* FROM clause item to skip */
4191){
4192 int i;
4193 SrcItem *pItem;
4194 for(i=0, pItem=pSrc->a; i<pSrc->nSrc; i++, pItem++){
4195 if( i!=iExcept ){
4196 Select *p;
4197 assert( pItem->iCursor < aCsrMap[0] );
4198 if( !pItem->fg.isRecursive || aCsrMap[pItem->iCursor+1]==0 ){
4199 aCsrMap[pItem->iCursor+1] = pParse->nTab++;
4200 }
4201 pItem->iCursor = aCsrMap[pItem->iCursor+1];
4202 if( pItem->fg.isSubquery ){
4203 for(p=pItem->u4.pSubq->pSelect; p; p=p->pPrior){
4204 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, -1);
4205 }
4206 }
4207 }
4208 }
4209}
4210
4211/*
4212** *piCursor is a cursor number. Change it if it needs to be mapped.
4213*/
4214static void renumberCursorDoMapping(Walker *pWalker, int *piCursor){
4215 int *aCsrMap = pWalker->u.aiCol;
4216 int iCsr = *piCursor;
4217 if( iCsr < aCsrMap[0] && aCsrMap[iCsr+1]>0 ){
4218 *piCursor = aCsrMap[iCsr+1];
4219 }
4220}
4221
4222/*
4223** Expression walker callback used by renumberCursors() to update
4224** Expr objects to match newly assigned cursor numbers.
4225*/
4226static int renumberCursorsCb(Walker *pWalker, Expr *pExpr){
4227 int op = pExpr->op;
4228 if( op==TK_COLUMN || op==TK_IF_NULL_ROW ){
4229 renumberCursorDoMapping(pWalker, &pExpr->iTable);
4230 }
4231 if( ExprHasProperty(pExpr, (EP_OuterON|EP_InnerON)) ){
4232 testcase( ExprHasProperty(pExpr, EP_OuterON) );
4233 testcase( ExprHasProperty(pExpr, EP_InnerON) );
4234 renumberCursorDoMapping(pWalker, &pExpr->w.iJoin);
4235 }
4236 return WRC_Continue;
4237}
4238
4239/*
4240** Assign a new cursor number to each cursor in the FROM clause (Select.pSrc)
4241** of the SELECT statement passed as the second argument, and to each
4242** cursor in the FROM clause of any FROM clause sub-selects, recursively.
4243** Except, do not assign a new cursor number to the iExcept'th element in
4244** the FROM clause of (*p). Update all expressions and other references
4245** to refer to the new cursor numbers.
4246**
4247** Argument aCsrMap is an array that may be used for temporary working
4248** space. Two guarantees are made by the caller:
4249**
4250** * the array is larger than the largest cursor number used within the
4251** select statement passed as an argument, and
4252**
4253** * the array entries for all cursor numbers that do *not* appear in
4254** FROM clauses of the select statement as described above are
4255** initialized to zero.
4256*/
4257static void renumberCursors(
4258 Parse *pParse, /* Parse context */
4259 Select *p, /* Select to renumber cursors within */
4260 int iExcept, /* FROM clause item to skip */
4261 int *aCsrMap /* Working space */
4262){
4263 Walker w;
4264 srclistRenumberCursors(pParse, aCsrMap, p->pSrc, iExcept);
4265 memset(&w, 0, sizeof(w));
4266 w.u.aiCol = aCsrMap;
4267 w.xExprCallback = renumberCursorsCb;
4268 w.xSelectCallback = sqlite3SelectWalkNoop;
4269 sqlite3WalkSelect(&w, p);
4270}
4271#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4272
4273/*
4274** If pSel is not part of a compound SELECT, return a pointer to its
4275** expression list. Otherwise, return a pointer to the expression list
4276** of the leftmost SELECT in the compound.
4277*/
4278static ExprList *findLeftmostExprlist(Select *pSel){
4279 while( pSel->pPrior ){
4280 pSel = pSel->pPrior;
4281 }
4282 return pSel->pEList;
4283}
4284
4285/*
4286** Return true if any of the result-set columns in the compound query
4287** have incompatible affinities on one or more arms of the compound.
4288*/
4289static int compoundHasDifferentAffinities(Select *p){
4290 int ii;
4291 ExprList *pList;
4292 assert( p!=0 );
4293 assert( p->pEList!=0 );
4294 assert( p->pPrior!=0 );
4295 pList = p->pEList;
4296 for(ii=0; ii<pList->nExpr; ii++){
4297 char aff;
4298 Select *pSub1;
4299 assert( pList->a[ii].pExpr!=0 );
4300 aff = sqlite3ExprAffinity(pList->a[ii].pExpr);
4301 for(pSub1=p->pPrior; pSub1; pSub1=pSub1->pPrior){
4302 assert( pSub1->pEList!=0 );
4303 assert( pSub1->pEList->nExpr>ii );
4304 assert( pSub1->pEList->a[ii].pExpr!=0 );
4305 if( sqlite3ExprAffinity(pSub1->pEList->a[ii].pExpr)!=aff ){
4306 return 1;
4307 }
4308 }
4309 }
4310 return 0;
4311}
4312
4313#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
4314/*
4315** Return true if the FROM clause pSrc, other than item iExcept, contains
4316** a subquery implemented using a co-routine. Such co-routines may have
4317** been coded while the SQL text was being parsed, before query planning.
4318*/
4319static int srcListHasCoroutine(const SrcList *pSrc, int iExcept){
4320 int i;
4321 for(i=0; i<pSrc->nSrc; i++){
4322 const SrcItem *pItem = &pSrc->a[i];
4323 if( i==iExcept ) continue;
4324 if( pItem->fg.viaCoroutine ) return 1;
4325 if( pItem->fg.isSubquery ){
4326 Select *pSelect;
4327 for(pSelect=pItem->u4.pSubq->pSelect;
4328 pSelect;
4329 pSelect=pSelect->pPrior
4330 ){
4331 if( srcListHasCoroutine(pSelect->pSrc, -1) ) return 1;
4332 }
4333 }
4334 }
4335 return 0;
4336}
4337
4338/*
4339** This routine attempts to flatten subqueries as a performance optimization.
4340** This routine returns 1 if it makes changes and 0 if no flattening occurs.
4341**
4342** To understand the concept of flattening, consider the following
4343** query:
4344**
4345** SELECT a FROM (SELECT x+y AS a FROM t1 WHERE z<100) WHERE a>5
4346**
4347** The default way of implementing this query is to execute the
4348** subquery first and store the results in a temporary table, then
4349** run the outer query on that temporary table. This requires two
4350** passes over the data. Furthermore, because the temporary table
4351** has no indices, the WHERE clause on the outer query cannot be
4352** optimized.
4353**
4354** This routine attempts to rewrite queries such as the above into
4355** a single flat select, like this:
4356**
4357** SELECT x+y AS a FROM t1 WHERE z<100 AND a>5
4358**
4359** The code generated for this simplification gives the same result
4360** but only has to scan the data once. And because indices might
4361** exist on the table t1, a complete scan of the data might be
4362** avoided.
4363**
4364** Flattening is subject to the following constraints:
4365**
4366** (**) We no longer attempt to flatten aggregate subqueries. Was:
4367** The subquery and the outer query cannot both be aggregates.
4368**
4369** (**) We no longer attempt to flatten aggregate subqueries. Was:
4370** (2) If the subquery is an aggregate then
4371** (2a) the outer query must not be a join and
4372** (2b) the outer query must not use subqueries
4373** other than the one FROM-clause subquery that is a candidate
4374** for flattening. (This is due to ticket [2f7170d73bf9abf80]
4375** from 2015-02-09.)
4376**
4377** (3) If the subquery is the right operand of a LEFT JOIN then
4378** (3a) the subquery may not be a join
4379** (**) Was (3b): "the FROM clause of the subquery may not contain
4380** a virtual table"
4381** (**) Was: "The outer query may not have a GROUP BY." This case
4382** is now managed correctly
4383** (3d) the outer query may not be DISTINCT.
4384** See also (26) for restrictions on RIGHT JOIN.
4385**
4386** (4) The subquery can not be DISTINCT.
4387**
4388** (**) At one point restrictions (4) and (5) defined a subset of DISTINCT
4389** sub-queries that were excluded from this optimization. Restriction
4390** (4) has since been expanded to exclude all DISTINCT subqueries.
4391**
4392** (**) We no longer attempt to flatten aggregate subqueries. Was:
4393** If the subquery is aggregate, the outer query may not be DISTINCT.
4394**
4395** (7) The subquery must have a FROM clause. TODO: For subqueries without
4396** A FROM clause, consider adding a FROM clause with the special
4397** table sqlite_once that consists of a single row containing a
4398** single NULL.
4399**
4400** (8) If the subquery uses LIMIT then the outer query may not be a join.
4401**
4402** (9) If the subquery uses LIMIT then the outer query may not be aggregate.
4403**
4404** (**) Restriction (10) was removed from the code on 2005-02-05 but we
4405** accidentally carried the comment forward until 2014-09-15. Original
4406** constraint: "If the subquery is aggregate then the outer query
4407** may not use LIMIT."
4408**
4409** (11) The subquery and the outer query may not both have ORDER BY clauses.
4410**
4411** (**) Not implemented. Subsumed into restriction (3). Was previously
4412** a separate restriction deriving from ticket #350.
4413**
4414** (13) The subquery and outer query may not both use LIMIT.
4415**
4416** (14) The subquery may not use OFFSET.
4417**
4418** (15) If the outer query is part of a compound select, then the
4419** subquery may not use LIMIT.
4420** (See ticket #2339 and ticket [02a8e81d44]).
4421**
4422** (16) If the outer query is aggregate, then the subquery may not
4423** use ORDER BY. (Ticket #2942) This used to not matter
4424** until we introduced the group_concat() function.
4425**
4426** (17) If the subquery is a compound select, then
4427** (17a) all compound operators must be a UNION ALL, and
4428** (17b) no terms within the subquery compound may be aggregate
4429** or DISTINCT, and
4430** (17c) every term within the subquery compound must have a FROM clause
4431** (17d) the outer query may not be
4432** (17d1) aggregate, or
4433** (17d2) DISTINCT
4434** (17e) the subquery may not contain window functions, and
4435** (17f) the subquery must not be the RHS of a LEFT JOIN.
4436** (17g) either the subquery is the first element of the outer
4437** query or there are no RIGHT or FULL JOINs in any arm
4438** of the subquery. (This is a duplicate of condition (27b).)
4439** (17h) The corresponding result set expressions in all arms of the
4440** compound must have the same affinity.
4441**
4442** The parent and sub-query may contain WHERE clauses. Subject to
4443** rules (11), (13) and (14), they may also contain ORDER BY,
4444** LIMIT and OFFSET clauses. The subquery cannot use any compound
4445** operator other than UNION ALL because all the other compound
4446** operators have an implied DISTINCT which is disallowed by
4447** restriction (4).
4448**
4449** Also, each component of the sub-query must return the same number
4450** of result columns. This is actually a requirement for any compound
4451** SELECT statement, but all the code here does is make sure that no
4452** such (illegal) sub-query is flattened. The caller will detect the
4453** syntax error and return a detailed message.
4454**
4455** (18) If the sub-query is a compound select, then all terms of the
4456** ORDER BY clause of the parent must be copies of a term returned
4457** by the parent query.
4458**
4459** (19) If the subquery uses LIMIT then the outer query may not
4460** have a WHERE clause.
4461**
4462** (20) If the sub-query is a compound select, then it must not use
4463** an ORDER BY clause. Ticket #3773. We could relax this constraint
4464** somewhat by saying that the terms of the ORDER BY clause must
4465** appear as unmodified result columns in the outer query. But we
4466** have other optimizations in mind to deal with that case.
4467**
4468** (21) If the subquery uses LIMIT then the outer query may not be
4469** DISTINCT. (See ticket [752e1646fc]).
4470**
4471** (22) The subquery may not be a recursive CTE.
4472**
4473** (23) If the outer query is a recursive CTE, then the sub-query may not be
4474** a compound query. This restriction is because transforming the
4475** parent to a compound query confuses the code that handles
4476** recursive queries in multiSelect().
4477**
4478** (**) We no longer attempt to flatten aggregate subqueries. Was:
4479** The subquery may not be an aggregate that uses the built-in min() or
4480** or max() functions. (Without this restriction, a query like:
4481** "SELECT x FROM (SELECT max(y), x FROM t1)" would not necessarily
4482** return the value X for which Y was maximal.)
4483**
4484** (25) If either the subquery or the parent query contains a window
4485** function in the select list or ORDER BY clause, flattening
4486** is not attempted.
4487**
4488** (26) The subquery may not be the right operand of a RIGHT JOIN.
4489** See also (3) for restrictions on LEFT JOIN.
4490**
4491** (27) The subquery may not contain a FULL or RIGHT JOIN unless it
4492** is the first element of the parent query. Two subcases:
4493** (27a) the subquery is not a compound query.
4494** (27b) the subquery is a compound query and the RIGHT JOIN occurs
4495** in any arm of the compound query. (See also (17g).)
4496**
4497** (28) The subquery is not a MATERIALIZED CTE. (This is handled
4498** in the caller before ever reaching this routine.)
4499**
4500**
4501** In this routine, the "p" parameter is a pointer to the outer query.
4502** The subquery is p->pSrc->a[iFrom]. isAgg is true if the outer query
4503** uses aggregates.
4504**
4505** If flattening is not attempted, this routine is a no-op and returns 0.
4506** If flattening is attempted this routine returns 1.
4507**
4508** All of the expression analysis must occur on both the outer query and
4509** the subquery before this routine runs.
4510*/
4511static int flattenSubquery(
4512 Parse *pParse, /* Parsing context */
4513 Select *p, /* The parent or outer SELECT statement */
4514 int iFrom, /* Index in p->pSrc->a[] of the inner subquery */
4515 int isAgg /* True if outer SELECT uses aggregate functions */
4516){
4517 const char *zSavedAuthContext = pParse->zAuthContext;
4518 Select *pParent; /* Current UNION ALL term of the other query */
4519 Select *pSub; /* The inner query or "subquery" */
4520 Select *pSub1; /* Pointer to the rightmost select in sub-query */
4521 SrcList *pSrc; /* The FROM clause of the outer query */
4522 SrcList *pSubSrc; /* The FROM clause of the subquery */
4523 int iParent; /* VDBE cursor number of the pSub result set temp table */
4524 int iNewParent = -1;/* Replacement table for iParent */
4525 int isOuterJoin = 0; /* True if pSub is the right side of a LEFT JOIN */
4526 int i; /* Loop counter */
4527 Expr *pWhere; /* The WHERE clause */
4528 SrcItem *pSubitem; /* The subquery */
4529 sqlite3 *db = pParse->db;
4530 Walker w; /* Walker to persist agginfo data */
4531 int *aCsrMap = 0;
4532
4533 /* Check to see if flattening is permitted. Return 0 if not.
4534 */
4535 assert( p!=0 );
4536 assert( p->pPrior==0 );
4537 if( OptimizationDisabled(db, SQLITE_QueryFlattener) ) return 0;
4538 pSrc = p->pSrc;
4539 assert( pSrc && iFrom>=0 && iFrom<pSrc->nSrc );
4540 pSubitem = &pSrc->a[iFrom];
4541 iParent = pSubitem->iCursor;
4542 assert( pSubitem->fg.isSubquery );
4543 pSub = pSubitem->u4.pSubq->pSelect;
4544 assert( pSub!=0 );
4545
4546#ifndef SQLITE_OMIT_WINDOWFUNC
4547 if( p->pWin || pSub->pWin ) return 0; /* Restriction (25) */
4548#endif
4549
4550 pSubSrc = pSub->pSrc;
4551 assert( pSubSrc );
4552 /* Prior to version 3.1.2, when LIMIT and OFFSET had to be simple constants,
4553 ** not arbitrary expressions, we allowed some combining of LIMIT and OFFSET
4554 ** because they could be computed at compile-time. But when LIMIT and OFFSET
4555 ** became arbitrary expressions, we were forced to add restrictions (13)
4556 ** and (14). */
4557 if( pSub->pLimit && p->pLimit ) return 0; /* Restriction (13) */
4558 if( pSub->pLimit && pSub->pLimit->pRight ) return 0; /* Restriction (14) */
4559 if( (p->selFlags & SF_Compound)!=0 && pSub->pLimit ){
4560 return 0; /* Restriction (15) */
4561 }
4562 if( pSubSrc->nSrc==0 ) return 0; /* Restriction (7) */
4563 if( pSub->selFlags & SF_Distinct ) return 0; /* Restriction (4) */
4564 if( pSub->pLimit && (pSrc->nSrc>1 || isAgg) ){
4565 return 0; /* Restrictions (8)(9) */
4566 }
4567 if( p->pOrderBy && pSub->pOrderBy ){
4568 return 0; /* Restriction (11) */
4569 }
4570 if( isAgg && pSub->pOrderBy ) return 0; /* Restriction (16) */
4571 if( pSub->pLimit && p->pWhere ) return 0; /* Restriction (19) */
4572 if( pSub->pLimit && (p->selFlags & SF_Distinct)!=0 ){
4573 return 0; /* Restriction (21) */
4574 }
4575 if( pSub->selFlags & (SF_Recursive) ){
4576 return 0; /* Restrictions (22) */
4577 }
4578
4579 /*
4580 ** If the subquery is the right operand of a LEFT JOIN, then the
4581 ** subquery may not be a join itself (3a). Example of why this is not
4582 ** allowed:
4583 **
4584 ** t1 LEFT OUTER JOIN (t2 JOIN t3)
4585 **
4586 ** If we flatten the above, we would get
4587 **
4588 ** (t1 LEFT OUTER JOIN t2) JOIN t3
4589 **
4590 ** which is not at all the same thing.
4591 **
4592 ** See also tickets #306, #350, and #3300.
4593 */
4594 if( (pSubitem->fg.jointype & (JT_OUTER|JT_LTORJ))!=0 ){
4595 if( pSubSrc->nSrc>1 /* (3a) */
4596 /**** || IsVirtual(pSubSrc->a[0].pSTab) (3b)-omitted */
4597 || (p->selFlags & SF_Distinct)!=0 /* (3d) */
4598 || (pSubitem->fg.jointype & JT_RIGHT)!=0 /* (26) */
4599 ){
4600 return 0;
4601 }
4602 isOuterJoin = 1;
4603 }
4604
4605 assert( pSubSrc->nSrc>0 ); /* True by restriction (7) */
4606 if( iFrom>0 && (pSubSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4607 return 0; /* Restriction (27a) */
4608 }
4609
4610 /* Condition (28) is blocked by the caller */
4611 assert( !pSubitem->fg.isCte || pSubitem->u2.pCteUse->eM10d!=M10d_Yes );
4612
4613 /* Restriction (17): If the sub-query is a compound SELECT, then it must
4614 ** use only the UNION ALL operator. And none of the simple select queries
4615 ** that make up the compound SELECT are allowed to be aggregate or distinct
4616 ** queries.
4617 */
4618 if( pSub->pPrior ){
4619 int ii;
4620 if( pSub->pOrderBy ){
4621 return 0; /* Restriction (20) */
4622 }
4623 if( isAgg || (p->selFlags & SF_Distinct)!=0 || isOuterJoin>0 ){
4624 return 0; /* (17d1), (17d2), or (17f) */
4625 }
4626 for(pSub1=pSub; pSub1; pSub1=pSub1->pPrior){
4627 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct );
4628 testcase( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))==SF_Aggregate );
4629 assert( pSub->pSrc!=0 );
4630 assert( (pSub->selFlags & SF_Recursive)==0 );
4631 assert( pSub->pEList->nExpr==pSub1->pEList->nExpr );
4632 if( (pSub1->selFlags & (SF_Distinct|SF_Aggregate))!=0 /* (17b) */
4633 || (pSub1->pPrior && pSub1->op!=TK_ALL) /* (17a) */
4634 || pSub1->pSrc->nSrc<1 /* (17c) */
4635#ifndef SQLITE_OMIT_WINDOWFUNC
4636 || pSub1->pWin /* (17e) */
4637#endif
4638 ){
4639 return 0;
4640 }
4641 if( iFrom>0 && (pSub1->pSrc->a[0].fg.jointype & JT_LTORJ)!=0 ){
4642 /* Without this restriction, the JT_LTORJ flag would end up being
4643 ** omitted on left-hand tables of the right join that is being
4644 ** flattened. */
4645 return 0; /* Restrictions (17g), (27b) */
4646 }
4647 testcase( pSub1->pSrc->nSrc>1 );
4648 }
4649
4650 /* Restriction (18). */
4651 if( p->pOrderBy ){
4652 for(ii=0; ii<p->pOrderBy->nExpr; ii++){
4653 if( p->pOrderBy->a[ii].u.x.iOrderByCol==0 ) return 0;
4654 }
4655 }
4656
4657 /* Restriction (23) */
4658 if( (p->selFlags & SF_Recursive) ) return 0;
4659
4660 /* Restriction (17h) */
4661 if( compoundHasDifferentAffinities(pSub) ) return 0;
4662
4663 if( pSrc->nSrc>1 ){
4664 if( pParse->nSelect>500 ) return 0;
4665 if( OptimizationDisabled(db, SQLITE_FlttnUnionAll) ) return 0;
4666 if( p->pOrderBy && srcListHasCoroutine(pSrc, iFrom) ) return 0;
4667 aCsrMap = sqlite3DbMallocZero(db, ((i64)pParse->nTab+1)*sizeof(int));
4668 if( aCsrMap ) aCsrMap[0] = pParse->nTab;
4669 }
4670 }
4671
4672 /***** If we reach this point, flattening is permitted. *****/
4673 TREETRACE(0x4,pParse,p,("flatten %u.%p from term %d\n",
4674 pSub->selId, pSub, iFrom));
4675
4676 /* Authorize the subquery */
4677 pParse->zAuthContext = pSubitem->zName;
4678 TESTONLY(i =) sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0);
4679 testcase( i==SQLITE_DENY );
4680 pParse->zAuthContext = zSavedAuthContext;
4681
4682 /* Delete the transient structures associated with the subquery */
4683
4684 if( ALWAYS(pSubitem->fg.isSubquery) ){
4685 pSub1 = sqlite3SubqueryDetach(db, pSubitem);
4686 }else{
4687 pSub1 = 0;
4688 }
4689 assert( pSubitem->fg.isSubquery==0 );
4690 assert( pSubitem->fg.fixedSchema==0 );
4691 sqlite3DbFree(db, pSubitem->zName);
4692 sqlite3DbFree(db, pSubitem->zAlias);
4693 pSubitem->zName = 0;
4694 pSubitem->zAlias = 0;
4695 assert( pSubitem->fg.isUsing!=0 || pSubitem->u3.pOn==0 );
4696
4697 /* If the sub-query is a compound SELECT statement, then (by restrictions
4698 ** 17 and 18 above) it must be a UNION ALL and the parent query must
4699 ** be of the form:
4700 **
4701 ** SELECT <expr-list> FROM (<sub-query>) <where-clause>
4702 **
4703 ** followed by any ORDER BY, LIMIT and/or OFFSET clauses. This block
4704 ** creates N-1 copies of the parent query without any ORDER BY, LIMIT or
4705 ** OFFSET clauses and joins them to the left-hand-side of the original
4706 ** using UNION ALL operators. In this case N is the number of simple
4707 ** select statements in the compound sub-query.
4708 **
4709 ** Example:
4710 **
4711 ** SELECT a+1 FROM (
4712 ** SELECT x FROM tab
4713 ** UNION ALL
4714 ** SELECT y FROM tab
4715 ** UNION ALL
4716 ** SELECT abs(z*2) FROM tab2
4717 ** ) WHERE a!=5 ORDER BY 1
4718 **
4719 ** Transformed into:
4720 **
4721 ** SELECT x+1 FROM tab WHERE x+1!=5
4722 ** UNION ALL
4723 ** SELECT y+1 FROM tab WHERE y+1!=5
4724 ** UNION ALL
4725 ** SELECT abs(z*2)+1 FROM tab2 WHERE abs(z*2)+1!=5
4726 ** ORDER BY 1
4727 **
4728 ** We call this the "compound-subquery flattening".
4729 */
4730 for(pSub=pSub->pPrior; pSub; pSub=pSub->pPrior){
4731 Select *pNew;
4732 ExprList *pOrderBy = p->pOrderBy;
4733 Expr *pLimit = p->pLimit;
4734 Select *pPrior = p->pPrior;
4735 Table *pItemTab = pSubitem->pSTab;
4736 pSubitem->pSTab = 0;
4737 p->pOrderBy = 0;
4738 p->pPrior = 0;
4739 p->pLimit = 0;
4740 pNew = sqlite3SelectDup(db, p, 0);
4741 p->pLimit = pLimit;
4742 p->pOrderBy = pOrderBy;
4743 p->op = TK_ALL;
4744 pSubitem->pSTab = pItemTab;
4745 if( pNew==0 ){
4746 p->pPrior = pPrior;
4747 }else{
4748 pNew->selId = ++pParse->nSelect;
4749 if( aCsrMap && ALWAYS(db->mallocFailed==0) ){
4750 renumberCursors(pParse, pNew, iFrom, aCsrMap);
4751 }
4752 pNew->pPrior = pPrior;
4753 if( pPrior ) pPrior->pNext = pNew;
4754 pNew->pNext = p;
4755 p->pPrior = pNew;
4756 TREETRACE(0x4,pParse,p,("compound-subquery flattener"
4757 " creates %u as peer\n",pNew->selId));
4758 }
4759 assert( pSubitem->fg.isSubquery==0 );
4760 }
4761 sqlite3DbFree(db, aCsrMap);
4762 if( db->mallocFailed ){
4763 assert( pSubitem->fg.fixedSchema==0 );
4764 assert( pSubitem->fg.isSubquery==0 );
4765 assert( pSubitem->u4.zDatabase==0 );
4766 sqlite3SrcItemAttachSubquery(pParse, pSubitem, pSub1, 0);
4767 return 1;
4768 }
4769
4770 /* Defer deleting the Table object associated with the
4771 ** subquery until code generation is
4772 ** complete, since there may still exist Expr.pTab entries that
4773 ** refer to the subquery even after flattening. Ticket #3346.
4774 **
4775 ** pSubitem->pSTab is always non-NULL by test restrictions and tests above.
4776 */
4777 if( ALWAYS(pSubitem->pSTab!=0) ){
4778 Table *pTabToDel = pSubitem->pSTab;
4779 if( pTabToDel->nTabRef==1 ){
4780 Parse *pToplevel = sqlite3ParseToplevel(pParse);
4781 sqlite3ParserAddCleanup(pToplevel, sqlite3DeleteTableGeneric, pTabToDel);
4782 testcase( pToplevel->earlyCleanup );
4783 }else{
4784 pTabToDel->nTabRef--;
4785 }
4786 pSubitem->pSTab = 0;
4787 }
4788
4789 /* The following loop runs once for each term in a compound-subquery
4790 ** flattening (as described above). If we are doing a different kind
4791 ** of flattening - a flattening other than a compound-subquery flattening -
4792 ** then this loop only runs once.
4793 **
4794 ** This loop moves all of the FROM elements of the subquery into the
4795 ** the FROM clause of the outer query. Before doing this, remember
4796 ** the cursor number for the original outer query FROM element in
4797 ** iParent. The iParent cursor will never be used. Subsequent code
4798 ** will scan expressions looking for iParent references and replace
4799 ** those references with expressions that resolve to the subquery FROM
4800 ** elements we are now copying in.
4801 */
4802 pSub = pSub1;
4803 for(pParent=p; pParent; pParent=pParent->pPrior, pSub=pSub->pPrior){
4804 int nSubSrc;
4805 u8 jointype = pParent->pSrc->a[iFrom].fg.jointype;
4806 assert( pSub!=0 );
4807 pSubSrc = pSub->pSrc; /* FROM clause of subquery */
4808 nSubSrc = pSubSrc->nSrc; /* Number of terms in subquery FROM clause */
4809 pSrc = pParent->pSrc; /* FROM clause of the outer query */
4810
4811 /* The subquery uses a single slot of the FROM clause of the outer
4812 ** query. If the subquery has more than one element in its FROM clause,
4813 ** then expand the outer query to make space for it to hold all elements
4814 ** of the subquery.
4815 **
4816 ** Example:
4817 **
4818 ** SELECT * FROM tabA, (SELECT * FROM sub1, sub2), tabB;
4819 **
4820 ** The outer query has 3 slots in its FROM clause. One slot of the
4821 ** outer query (the middle slot) is used by the subquery. The next
4822 ** block of code will expand the outer query FROM clause to 4 slots.
4823 ** The middle slot is expanded to two slots in order to make space
4824 ** for the two elements in the FROM clause of the subquery.
4825 */
4826 if( nSubSrc>1 ){
4827 pSrc = sqlite3SrcListEnlarge(pParse, pSrc, nSubSrc-1,iFrom+1);
4828 if( pSrc==0 ) break;
4829 pParent->pSrc = pSrc;
4830 }
4831
4832 /* Transfer the FROM clause terms from the subquery into the
4833 ** outer query.
4834 */
4835 iNewParent = pSubSrc->a[0].iCursor;
4836 for(i=0; i<nSubSrc; i++){
4837 SrcItem *pItem = &pSrc->a[i+iFrom];
4838 assert( pItem->fg.isTabFunc==0 );
4839 assert( pItem->fg.isSubquery
4840 || pItem->fg.fixedSchema
4841 || pItem->u4.zDatabase==0 );
4842 if( pItem->fg.isUsing ) sqlite3IdListDelete(db, pItem->u3.pUsing);
4843 *pItem = pSubSrc->a[i];
4844 pItem->fg.jointype |= (jointype & JT_LTORJ);
4845 memset(&pSubSrc->a[i], 0, sizeof(pSubSrc->a[i]));
4846 }
4847 pSrc->a[iFrom].fg.jointype |= jointype;
4848
4849 /* Begin substituting subquery result set expressions for
4850 ** references to the iParent in the outer query.
4851 **
4852 ** Example:
4853 **
4854 ** SELECT a+5, b*10 FROM (SELECT x*3 AS a, y+10 AS b FROM t1) WHERE a>b;
4855 ** \ \_____________ subquery __________/ /
4856 ** \_____________________ outer query ______________________________/
4857 **
4858 ** We look at every expression in the outer query and every place we see
4859 ** "a" we substitute "x*3" and every place we see "b" we substitute "y+10".
4860 */
4861 if( pSub->pOrderBy ){
4862 /* At this point, any non-zero iOrderByCol values indicate that the
4863 ** ORDER BY column expression is identical to the iOrderByCol'th
4864 ** expression returned by SELECT statement pSub. Since these values
4865 ** do not necessarily correspond to columns in SELECT statement pParent,
4866 ** zero them before transferring the ORDER BY clause.
4867 **
4868 ** Not doing this may cause an error if a subsequent call to this
4869 ** function attempts to flatten a compound sub-query into pParent.
4870 ** See ticket [d11a6e908f].
4871 */
4872 ExprList *pOrderBy = pSub->pOrderBy;
4873 for(i=0; i<pOrderBy->nExpr; i++){
4874 pOrderBy->a[i].u.x.iOrderByCol = 0;
4875 }
4876 assert( pParent->pOrderBy==0 );
4877 pParent->pOrderBy = pOrderBy;
4878 pSub->pOrderBy = 0;
4879 }
4880 pWhere = pSub->pWhere;
4881 pSub->pWhere = 0;
4882 if( isOuterJoin>0 ){
4883 assert( pSubSrc->nSrc==1 );
4884 sqlite3SetJoinExpr(pWhere, iNewParent, EP_OuterON);
4885 }
4886 if( pWhere ){
4887 if( pParent->pWhere ){
4888 pParent->pWhere = sqlite3PExpr(pParse, TK_AND, pWhere, pParent->pWhere);
4889 }else{
4890 pParent->pWhere = pWhere;
4891 }
4892 }
4893 if( db->mallocFailed==0 ){
4894 SubstContext x;
4895 x.pParse = pParse;
4896 x.iTable = iParent;
4897 x.iNewTable = iNewParent;
4898 x.isOuterJoin = isOuterJoin;
4899 x.nSelDepth = 0;
4900 x.pEList = pSub->pEList;
4901 x.pCList = findLeftmostExprlist(pSub);
4902 substSelect(&x, pParent, 0);
4903 }
4904
4905 /* The flattened query is a compound if either the inner or the
4906 ** outer query is a compound. */
4907 pParent->selFlags |= pSub->selFlags & SF_Compound;
4908 assert( (pSub->selFlags & SF_Distinct)==0 ); /* restriction (17b) */
4909
4910 /*
4911 ** SELECT ... FROM (SELECT ... LIMIT a OFFSET b) LIMIT x OFFSET y;
4912 **
4913 ** One is tempted to try to add a and b to combine the limits. But this
4914 ** does not work if either limit is negative.
4915 */
4916 if( pSub->pLimit ){
4917 pParent->pLimit = pSub->pLimit;
4918 pSub->pLimit = 0;
4919 }
4920
4921 /* Recompute the SrcItem.colUsed masks for the flattened
4922 ** tables. */
4923 for(i=0; i<nSubSrc; i++){
4924 recomputeColumnsUsed(pParent, &pSrc->a[i+iFrom]);
4925 }
4926 }
4927
4928 /* Finally, delete what is left of the subquery and return success.
4929 */
4930 sqlite3AggInfoPersistWalkerInit(&w, pParse);
4931 sqlite3WalkSelect(&w,pSub1);
4932 sqlite3SelectDelete(db, pSub1);
4933
4934#if TREETRACE_ENABLED
4935 if( sqlite3TreeTrace & 0x4 ){
4936 TREETRACE(0x4,pParse,p,("After flattening:\n"));
4937 sqlite3TreeViewSelect(0, p, 0);
4938 }
4939#endif
4940
4941 return 1;
4942}
4943#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
4944
4945/*
4946** A structure to keep track of all of the column values that are fixed to
4947** a known value due to WHERE clause constraints of the form COLUMN=VALUE.
4948*/
4949typedef struct WhereConst WhereConst;
4950struct WhereConst {
4951 Parse *pParse; /* Parsing context */
4952 u8 *pOomFault; /* Pointer to pParse->db->mallocFailed */
4953 int nConst; /* Number for COLUMN=CONSTANT terms */
4954 int nChng; /* Number of times a constant is propagated */
4955 int bHasAffBlob; /* A column in apExpr[] has affinity NONE or BLOB */
4956 u32 mExcludeOn; /* Which ON expressions to exclude from considertion.
4957 ** Either EP_OuterON or EP_InnerON|EP_OuterON */
4958 Expr **apExpr; /* [i*2] is COLUMN and [i*2+1] is VALUE */
4959};
4960
4961/*
4962** Add a new entry to the pConst object, if appropriate.
4963**
4964** * Do not add if pValue is not constant. (This is enforced by
4965** the caller)
4966**
4967** * Do not add duplicate pColumn entries
4968**
4969** * Do not add if pValue has an affinity
4970**
4971** * Do not add if the comparison uses a collating sequence other
4972** than binary.
4973**
4974** * Do not add if pValue is a function that might return a subtype
4975**
4976** The caller guarantees the pColumn is a column.
4977*/
4978static void constInsert(
4979 WhereConst *pConst, /* The WhereConst into which we are inserting */
4980 Expr *pColumn, /* The COLUMN part of the constraint */
4981 Expr *pValue, /* The VALUE part of the constraint */
4982 Expr *pExpr /* Overall expression: COLUMN=VALUE or VALUE=COLUMN */
4983){
4984 int i;
4985 assert( pColumn->op==TK_COLUMN );
4986 assert( sqlite3ExprIsConstant(pConst->pParse, pValue) );
4987 if( ExprHasProperty(pColumn, EP_FixedCol) ) return;
4988 if( sqlite3ExprAffinity(pValue)!=0 ) return;
4989 if( !sqlite3IsBinary(sqlite3ExprCompareCollSeq(pConst->pParse,pExpr)) ){
4990 return;
4991 }
4992 if( sqlite3ExprCanReturnSubtype(pConst->pParse, pValue) ) return;
4993
4994 /* 2018-10-25 ticket [cf5ed20f]
4995 ** Make sure the same pColumn is not inserted more than once */
4996 for(i=0; i<pConst->nConst; i++){
4997 const Expr *pE2 = pConst->apExpr[i*2];
4998 assert( pE2->op==TK_COLUMN );
4999 if( pE2->iTable==pColumn->iTable
5000 && pE2->iColumn==pColumn->iColumn
5001 ){
5002 return; /* Already present. Return without doing anything. */
5003 }
5004 }
5005 assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
5006 if( sqlite3ExprAffinity(pColumn)<=SQLITE_AFF_BLOB ){
5007 pConst->bHasAffBlob = 1;
5008 }
5009
5010 pConst->nConst++;
5011 pConst->apExpr = sqlite3DbReallocOrFree(pConst->pParse->db, pConst->apExpr,
5012 pConst->nConst*2*sizeof(Expr*));
5013 if( pConst->apExpr==0 ){
5014 pConst->nConst = 0;
5015 }else{
5016 pConst->apExpr[pConst->nConst*2-2] = pColumn;
5017 pConst->apExpr[pConst->nConst*2-1] = pValue;
5018 }
5019}
5020
5021/*
5022** Find all terms of COLUMN=VALUE or VALUE=COLUMN in pExpr where VALUE
5023** is a constant expression and where the term must be true because it
5024** is part of the AND-connected terms of the expression. For each term
5025** found, add it to the pConst structure.
5026*/
5027static void findConstInWhere(WhereConst *pConst, Expr *pExpr){
5028 Expr *pRight, *pLeft;
5029 if( NEVER(pExpr==0) ) return;
5030 if( ExprHasProperty(pExpr, pConst->mExcludeOn) ){
5031 testcase( ExprHasProperty(pExpr, EP_OuterON) );
5032 testcase( ExprHasProperty(pExpr, EP_InnerON) );
5033 return;
5034 }
5035 if( pExpr->op==TK_AND ){
5036 findConstInWhere(pConst, pExpr->pRight);
5037 findConstInWhere(pConst, pExpr->pLeft);
5038 return;
5039 }
5040 if( pExpr->op!=TK_EQ ) return;
5041 pRight = pExpr->pRight;
5042 pLeft = pExpr->pLeft;
5043 assert( pRight!=0 );
5044 assert( pLeft!=0 );
5045 if( pRight->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pLeft) ){
5046 constInsert(pConst,pRight,pLeft,pExpr);
5047 }
5048 if( pLeft->op==TK_COLUMN && sqlite3ExprIsConstant(pConst->pParse, pRight) ){
5049 constInsert(pConst,pLeft,pRight,pExpr);
5050 }
5051}
5052
5053/*
5054** This is a helper function for Walker callback propagateConstantExprRewrite().
5055**
5056** Argument pExpr is a candidate expression to be replaced by a value. If
5057** pExpr is equivalent to one of the columns named in pWalker->u.pConst,
5058** then overwrite it with the corresponding value. Except, do not do so
5059** if argument bIgnoreAffBlob is non-zero and the affinity of pExpr
5060** is SQLITE_AFF_BLOB.
5061*/
5062static int propagateConstantExprRewriteOne(
5063 WhereConst *pConst,
5064 Expr *pExpr,
5065 int bIgnoreAffBlob
5066){
5067 int i;
5068 if( pConst->pOomFault[0] ) return WRC_Prune;
5069 if( pExpr->op!=TK_COLUMN ) return WRC_Continue;
5070 if( ExprHasProperty(pExpr, EP_FixedCol|pConst->mExcludeOn) ){
5071 testcase( ExprHasProperty(pExpr, EP_FixedCol) );
5072 testcase( ExprHasProperty(pExpr, EP_OuterON) );
5073 testcase( ExprHasProperty(pExpr, EP_InnerON) );
5074 return WRC_Continue;
5075 }
5076 for(i=0; i<pConst->nConst; i++){
5077 Expr *pColumn = pConst->apExpr[i*2];
5078 if( pColumn==pExpr ) continue;
5079 if( pColumn->iTable!=pExpr->iTable ) continue;
5080 if( pColumn->iColumn!=pExpr->iColumn ) continue;
5081 assert( SQLITE_AFF_NONE<SQLITE_AFF_BLOB );
5082 if( bIgnoreAffBlob && sqlite3ExprAffinity(pColumn)<=SQLITE_AFF_BLOB ){
5083 break;
5084 }
5085 /* A match is found. Add the EP_FixedCol property */
5086 pConst->nChng++;
5087 ExprClearProperty(pExpr, EP_Leaf);
5088 ExprSetProperty(pExpr, EP_FixedCol);
5089 assert( pExpr->pLeft==0 );
5090 pExpr->pLeft = sqlite3ExprDup(pConst->pParse->db, pConst->apExpr[i*2+1], 0);
5091 if( pConst->pParse->db->mallocFailed ) return WRC_Prune;
5092 break;
5093 }
5094 return WRC_Prune;
5095}
5096
5097/*
5098** This is a Walker expression callback. pExpr is a node from the WHERE
5099** clause of a SELECT statement. This function examines pExpr to see if
5100** any substitutions based on the contents of pWalker->u.pConst should
5101** be made to pExpr or its immediate children.
5102**
5103** A substitution is made if:
5104**
5105** + pExpr is a column with an affinity other than BLOB that matches
5106** one of the columns in pWalker->u.pConst, or
5107**
5108** + pExpr is a binary comparison operator (=, <=, >=, <, >) that
5109** uses an affinity other than TEXT and one of its immediate
5110** children is a column that matches one of the columns in
5111** pWalker->u.pConst.
5112*/
5113static int propagateConstantExprRewrite(Walker *pWalker, Expr *pExpr){
5114 WhereConst *pConst = pWalker->u.pConst;
5115 assert( TK_GT==TK_EQ+1 );
5116 assert( TK_LE==TK_EQ+2 );
5117 assert( TK_LT==TK_EQ+3 );
5118 assert( TK_GE==TK_EQ+4 );
5119 if( pConst->bHasAffBlob ){
5120 if( (pExpr->op>=TK_EQ && pExpr->op<=TK_GE)
5121 || pExpr->op==TK_IS
5122 ){
5123 if( sqlite3ExprAffinity(pExpr->pRight)!=SQLITE_AFF_TEXT ){
5124 propagateConstantExprRewriteOne(pConst, pExpr->pLeft, 0);
5125 }
5126 if( sqlite3ExprAffinity(pExpr->pLeft)!=SQLITE_AFF_TEXT ){
5127 propagateConstantExprRewriteOne(pConst, pExpr->pRight, 0);
5128 }
5129 }
5130 }
5131 return propagateConstantExprRewriteOne(pConst, pExpr, pConst->bHasAffBlob);
5132}
5133
5134/*
5135** The WHERE-clause constant propagation optimization.
5136**
5137** If the WHERE clause contains terms of the form COLUMN=CONSTANT or
5138** CONSTANT=COLUMN that are top-level AND-connected terms that are not
5139** part of a ON clause from an OUTER JOIN, then throughout the query
5140** replace all other occurrences of COLUMN with CONSTANT.
5141**
5142** For example, the query:
5143**
5144** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=t1.a AND t3.c=t2.b
5145**
5146** Is transformed into
5147**
5148** SELECT * FROM t1, t2, t3 WHERE t1.a=39 AND t2.b=39 AND t3.c=39
5149**
5150** Return true if any transformations where made and false if not.
5151**
5152** Implementation note: Constant propagation is tricky due to affinity
5153** and collating sequence interactions. Consider this example:
5154**
5155** CREATE TABLE t1(a INT,b TEXT);
5156** INSERT INTO t1 VALUES(123,'0123');
5157** SELECT * FROM t1 WHERE a=123 AND b=a;
5158** SELECT * FROM t1 WHERE a=123 AND b=123;
5159**
5160** The two SELECT statements above should return different answers. b=a
5161** is always true because the comparison uses numeric affinity, but b=123
5162** is false because it uses text affinity and '0123' is not the same as '123'.
5163** To work around this, the expression tree is not actually changed from
5164** "b=a" to "b=123" but rather the "a" in "b=a" is tagged with EP_FixedCol
5165** and the "123" value is hung off of the pLeft pointer. Code generator
5166** routines know to generate the constant "123" instead of looking up the
5167** column value. Also, to avoid collation problems, this optimization is
5168** only attempted if the "a=123" term uses the default BINARY collation.
5169**
5170** 2021-05-25 forum post 6a06202608: Another troublesome case is...
5171**
5172** CREATE TABLE t1(x);
5173** INSERT INTO t1 VALUES(10.0);
5174** SELECT 1 FROM t1 WHERE x=10 AND x LIKE 10;
5175**
5176** The query should return no rows, because the t1.x value is '10.0' not '10'
5177** and '10.0' is not LIKE '10'. But if we are not careful, the first WHERE
5178** term "x=10" will cause the second WHERE term to become "10 LIKE 10",
5179** resulting in a false positive. To avoid this, constant propagation for
5180** columns with BLOB affinity is only allowed if the constant is used with
5181** operators ==, <=, <, >=, >, or IS in a way that will cause the correct
5182** type conversions to occur. See logic associated with the bHasAffBlob flag
5183** for details.
5184*/
5185static int propagateConstants(
5186 Parse *pParse, /* The parsing context */
5187 Select *p /* The query in which to propagate constants */
5188){
5189 WhereConst x;
5190 Walker w;
5191 int nChng = 0;
5192 x.pParse = pParse;
5193 x.pOomFault = &pParse->db->mallocFailed;
5194 do{
5195 x.nConst = 0;
5196 x.nChng = 0;
5197 x.apExpr = 0;
5198 x.bHasAffBlob = 0;
5199 if( ALWAYS(p->pSrc!=0)
5200 && p->pSrc->nSrc>0
5201 && (p->pSrc->a[0].fg.jointype & JT_LTORJ)!=0
5202 ){
5203 /* Do not propagate constants on any ON clause if there is a
5204 ** RIGHT JOIN anywhere in the query */
5205 x.mExcludeOn = EP_InnerON | EP_OuterON;
5206 }else{
5207 /* Do not propagate constants through the ON clause of a LEFT JOIN */
5208 x.mExcludeOn = EP_OuterON;
5209 }
5210 findConstInWhere(&x, p->pWhere);
5211 if( x.nConst ){
5212 memset(&w, 0, sizeof(w));
5213 w.pParse = pParse;
5214 w.xExprCallback = propagateConstantExprRewrite;
5215 w.xSelectCallback = sqlite3SelectWalkNoop;
5216 w.xSelectCallback2 = 0;
5217 w.walkerDepth = 0;
5218 w.u.pConst = &x;
5219 sqlite3WalkExpr(&w, p->pWhere);
5220 sqlite3DbFree(x.pParse->db, x.apExpr);
5221 nChng += x.nChng;
5222 }
5223 }while( x.nChng );
5224 return nChng;
5225}
5226
5227#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5228# if !defined(SQLITE_OMIT_WINDOWFUNC)
5229/*
5230** This function is called to determine whether or not it is safe to
5231** push WHERE clause expression pExpr down to FROM clause sub-query
5232** pSubq, which contains at least one window function. Return 1
5233** if it is safe and the expression should be pushed down, or 0
5234** otherwise.
5235**
5236** It is only safe to push the expression down if it consists only
5237** of constants and copies of expressions that appear in the PARTITION
5238** BY clause of all window function used by the sub-query. It is safe
5239** to filter out entire partitions, but not rows within partitions, as
5240** this may change the results of the window functions.
5241**
5242** At the time this function is called it is guaranteed that
5243**
5244** * the sub-query uses only one distinct window frame, and
5245** * that the window frame has a PARTITION BY clause.
5246*/
5247static int pushDownWindowCheck(Parse *pParse, Select *pSubq, Expr *pExpr){
5248 assert( pSubq->pWin->pPartition );
5249 assert( (pSubq->selFlags & SF_MultiPart)==0 );
5250 assert( pSubq->pPrior==0 );
5251 return sqlite3ExprIsConstantOrGroupBy(pParse, pExpr, pSubq->pWin->pPartition);
5252}
5253# endif /* SQLITE_OMIT_WINDOWFUNC */
5254#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5255
5256#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
5257/*
5258** Make copies of relevant WHERE clause terms of the outer query into
5259** the WHERE clause of subquery. Example:
5260**
5261** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1) WHERE x=5 AND y=10;
5262**
5263** Transformed into:
5264**
5265** SELECT * FROM (SELECT a AS x, c-d AS y FROM t1 WHERE a=5 AND c-d=10)
5266** WHERE x=5 AND y=10;
5267**
5268** The hope is that the terms added to the inner query will make it more
5269** efficient.
5270**
5271** NAME AMBIGUITY
5272**
5273** This optimization is called the "WHERE-clause push-down optimization"
5274** or sometimes the "predicate push-down optimization".
5275**
5276** Do not confuse this optimization with another unrelated optimization
5277** with a similar name: The "MySQL push-down optimization" causes WHERE
5278** clause terms that can be evaluated using only the index and without
5279** reference to the table are run first, so that if they are false,
5280** unnecessary table seeks are avoided.
5281**
5282** RULES
5283**
5284** Do not attempt this optimization if:
5285**
5286** (1) (** This restriction was removed on 2017-09-29. We used to
5287** disallow this optimization for aggregate subqueries, but now
5288** it is allowed by putting the extra terms on the HAVING clause.
5289** The added HAVING clause is pointless if the subquery lacks
5290** a GROUP BY clause. But such a HAVING clause is also harmless
5291** so there does not appear to be any reason to add extra logic
5292** to suppress it. **)
5293**
5294** (2) The inner query is the recursive part of a common table expression.
5295**
5296** (3) The inner query has a LIMIT clause (since the changes to the WHERE
5297** clause would change the meaning of the LIMIT).
5298**
5299** (4) The inner query is the right operand of a LEFT JOIN and the
5300** expression to be pushed down does not come from the ON clause
5301** on that LEFT JOIN.
5302**
5303** (5) The WHERE clause expression originates in the ON or USING clause
5304** of a LEFT JOIN where iCursor is not the right-hand table of that
5305** left join. An example:
5306**
5307** SELECT *
5308** FROM (SELECT 1 AS a1 UNION ALL SELECT 2) AS aa
5309** JOIN (SELECT 1 AS b2 UNION ALL SELECT 2) AS bb ON (a1=b2)
5310** LEFT JOIN (SELECT 8 AS c3 UNION ALL SELECT 9) AS cc ON (b2=2);
5311**
5312** The correct answer is three rows: (1,1,NULL),(2,2,8),(2,2,9).
5313** But if the (b2=2) term were to be pushed down into the bb subquery,
5314** then the (1,1,NULL) row would be suppressed.
5315**
5316** (6) Window functions make things tricky as changes to the WHERE clause
5317** of the inner query could change the window over which window
5318** functions are calculated. Therefore, do not attempt the optimization
5319** if:
5320**
5321** (6a) The inner query uses multiple incompatible window partitions.
5322**
5323** (6b) The inner query is a compound and uses window-functions.
5324**
5325** (6c) The WHERE clause does not consist entirely of constants and
5326** copies of expressions found in the PARTITION BY clause of
5327** all window-functions used by the sub-query. It is safe to
5328** filter out entire partitions, as this does not change the
5329** window over which any window-function is calculated.
5330**
5331** (7) The inner query is a Common Table Expression (CTE) that should
5332** be materialized. (This restriction is implemented in the calling
5333** routine.)
5334**
5335** (8) If the subquery is a compound that uses UNION, INTERSECT,
5336** or EXCEPT, then all of the result set columns for all arms of
5337** the compound must use the BINARY collating sequence.
5338**
5339** (9) All three of the following are true:
5340**
5341** (9a) The WHERE clause expression originates in the ON or USING clause
5342** of a join (either an INNER or an OUTER join), and
5343**
5344** (9b) The subquery is to the right of the ON/USING clause
5345**
5346** (9c) There is a RIGHT JOIN (or FULL JOIN) in between the ON/USING
5347** clause and the subquery.
5348**
5349** Without this restriction, the WHERE-clause push-down optimization
5350** might move the ON/USING filter expression from the left side of a
5351** RIGHT JOIN over to the right side, which leads to incorrect answers.
5352** See also restriction (6) in sqlite3ExprIsSingleTableConstraint().
5353**
5354** (10) The inner query is not the right-hand table of a RIGHT JOIN.
5355**
5356** (11) The subquery is not a VALUES clause
5357**
5358** (12) The WHERE clause is not "rowid ISNULL" or the equivalent. This
5359** case only comes up if SQLite is compiled using
5360** SQLITE_ALLOW_ROWID_IN_VIEW.
5361**
5362** Return 0 if no changes are made and non-zero if one or more WHERE clause
5363** terms are duplicated into the subquery.
5364*/
5365static int pushDownWhereTerms(
5366 Parse *pParse, /* Parse context (for malloc() and error reporting) */
5367 Select *pSubq, /* The subquery whose WHERE clause is to be augmented */
5368 Expr *pWhere, /* The WHERE clause of the outer query */
5369 SrcList *pSrcList, /* The complete from clause of the outer query */
5370 int iSrc /* Which FROM clause term to try to push into */
5371){
5372 Expr *pNew;
5373 SrcItem *pSrc; /* The subquery FROM term into which WHERE is pushed */
5374 int nChng = 0;
5375 pSrc = &pSrcList->a[iSrc];
5376 if( pWhere==0 ) return 0;
5377 if( pSubq->selFlags & (SF_Recursive|SF_MultiPart) ){
5378 return 0; /* restrictions (2) and (11) */
5379 }
5380 if( pSrc->fg.jointype & (JT_LTORJ|JT_RIGHT) ){
5381 return 0; /* restrictions (10) */
5382 }
5383
5384 if( pSubq->pPrior ){
5385 Select *pSel;
5386 int notUnionAll = 0;
5387 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5388 u8 op = pSel->op;
5389 assert( op==TK_ALL || op==TK_SELECT
5390 || op==TK_UNION || op==TK_INTERSECT || op==TK_EXCEPT );
5391 if( op!=TK_ALL && op!=TK_SELECT ){
5392 notUnionAll = 1;
5393 }
5394#ifndef SQLITE_OMIT_WINDOWFUNC
5395 if( pSel->pWin ) return 0; /* restriction (6b) */
5396#endif
5397 }
5398 if( notUnionAll ){
5399 /* If any of the compound arms are connected using UNION, INTERSECT,
5400 ** or EXCEPT, then we must ensure that none of the columns use a
5401 ** non-BINARY collating sequence. */
5402 for(pSel=pSubq; pSel; pSel=pSel->pPrior){
5403 int ii;
5404 const ExprList *pList = pSel->pEList;
5405 assert( pList!=0 );
5406 for(ii=0; ii<pList->nExpr; ii++){
5407 CollSeq *pColl = sqlite3ExprCollSeq(pParse, pList->a[ii].pExpr);
5408 if( !sqlite3IsBinary(pColl) ){
5409 return 0; /* Restriction (8) */
5410 }
5411 }
5412 }
5413 }
5414 }else{
5415#ifndef SQLITE_OMIT_WINDOWFUNC
5416 if( pSubq->pWin && pSubq->pWin->pPartition==0 ) return 0;
5417#endif
5418 }
5419
5420#ifdef SQLITE_DEBUG
5421 /* Only the first term of a compound can have a WITH clause. But make
5422 ** sure no other terms are marked SF_Recursive in case something changes
5423 ** in the future.
5424 */
5425 {
5426 Select *pX;
5427 for(pX=pSubq; pX; pX=pX->pPrior){
5428 assert( (pX->selFlags & (SF_Recursive))==0 );
5429 }
5430 }
5431#endif
5432
5433 if( pSubq->pLimit!=0 ){
5434 return 0; /* restriction (3) */
5435 }
5436 while( pWhere->op==TK_AND ){
5437 nChng += pushDownWhereTerms(pParse, pSubq, pWhere->pRight, pSrcList, iSrc);
5438 pWhere = pWhere->pLeft;
5439 }
5440
5441#if 0 /* These checks now done by sqlite3ExprIsSingleTableConstraint() */
5442 if( ExprHasProperty(pWhere, EP_OuterON|EP_InnerON) /* (9a) */
5443 && (pSrcList->a[0].fg.jointype & JT_LTORJ)!=0 /* Fast pre-test of (9c) */
5444 ){
5445 int jj;
5446 for(jj=0; jj<iSrc; jj++){
5447 if( pWhere->w.iJoin==pSrcList->a[jj].iCursor ){
5448 /* If we reach this point, both (9a) and (9b) are satisfied.
5449 ** The following loop checks (9c):
5450 */
5451 for(jj++; jj<iSrc; jj++){
5452 if( (pSrcList->a[jj].fg.jointype & JT_RIGHT)!=0 ){
5453 return 0; /* restriction (9) */
5454 }
5455 }
5456 }
5457 }
5458 }
5459 if( isLeftJoin
5460 && (ExprHasProperty(pWhere,EP_OuterON)==0
5461 || pWhere->w.iJoin!=iCursor)
5462 ){
5463 return 0; /* restriction (4) */
5464 }
5465 if( ExprHasProperty(pWhere,EP_OuterON)
5466 && pWhere->w.iJoin!=iCursor
5467 ){
5468 return 0; /* restriction (5) */
5469 }
5470#endif
5471
5472#ifdef SQLITE_ALLOW_ROWID_IN_VIEW
5473 if( ViewCanHaveRowid && (pWhere->op==TK_ISNULL || pWhere->op==TK_NOTNULL) ){
5474 Expr *pLeft = pWhere->pLeft;
5475 if( ALWAYS(pLeft)
5476 && pLeft->op==TK_COLUMN
5477 && pLeft->iColumn < 0
5478 ){
5479 return 0; /* Restriction (12) */
5480 }
5481 }
5482#endif
5483
5484 if( sqlite3ExprIsSingleTableConstraint(pWhere, pSrcList, iSrc, 1) ){
5485 nChng++;
5486 pSubq->selFlags |= SF_PushDown;
5487 while( pSubq ){
5488 SubstContext x;
5489 pNew = sqlite3ExprDup(pParse->db, pWhere, 0);
5490 unsetJoinExpr(pNew, -1, 1);
5491 x.pParse = pParse;
5492 x.iTable = pSrc->iCursor;
5493 x.iNewTable = pSrc->iCursor;
5494 x.isOuterJoin = 0;
5495 x.nSelDepth = 0;
5496 x.pEList = pSubq->pEList;
5497 x.pCList = findLeftmostExprlist(pSubq);
5498 pNew = substExpr(&x, pNew);
5499 assert( pNew!=0 || pParse->nErr!=0 );
5500 if( pParse->nErr==0 && pNew->op==TK_IN && ExprUseXSelect(pNew) ){
5501 assert( pNew->x.pSelect!=0 );
5502 pNew->x.pSelect->selFlags |= SF_ClonedRhsIn;
5503 assert( pWhere!=0 );
5504 assert( pWhere->op==TK_IN );
5505 assert( ExprUseXSelect(pWhere) );
5506 assert( pWhere->x.pSelect!=0 );
5507 pWhere->x.pSelect->selFlags |= SF_ClonedRhsIn;
5508 }
5509#ifndef SQLITE_OMIT_WINDOWFUNC
5510 if( pSubq->pWin && 0==pushDownWindowCheck(pParse, pSubq, pNew) ){
5511 /* Restriction 6c has prevented push-down in this case */
5512 sqlite3ExprDelete(pParse->db, pNew);
5513 nChng--;
5514 break;
5515 }
5516#endif
5517 if( pSubq->selFlags & SF_Aggregate ){
5518 pSubq->pHaving = sqlite3ExprAnd(pParse, pSubq->pHaving, pNew);
5519 }else{
5520 pSubq->pWhere = sqlite3ExprAnd(pParse, pSubq->pWhere, pNew);
5521 }
5522 pSubq = pSubq->pPrior;
5523 }
5524 }
5525 return nChng;
5526}
5527#endif /* !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW) */
5528
5529/*
5530** Check to see if a subquery contains result-set columns that are
5531** never used. If it does, change the value of those result-set columns
5532** to NULL so that they do not cause unnecessary work to compute.
5533**
5534** Return the number of column that were changed to NULL.
5535*/
5536static int disableUnusedSubqueryResultColumns(SrcItem *pItem){
5537 int nCol;
5538 Select *pSub; /* The subquery to be simplified */
5539 Select *pX; /* For looping over compound elements of pSub */
5540 Table *pTab; /* The table that describes the subquery */
5541 int j; /* Column number */
5542 int nChng = 0; /* Number of columns converted to NULL */
5543 Bitmask colUsed; /* Columns that may not be NULLed out */
5544
5545 assert( pItem!=0 );
5546 if( pItem->fg.isCorrelated || pItem->fg.isCte ){
5547 return 0;
5548 }
5549 assert( pItem->pSTab!=0 );
5550 pTab = pItem->pSTab;
5551 assert( pItem->fg.isSubquery );
5552 pSub = pItem->u4.pSubq->pSelect;
5553 assert( pSub->pEList->nExpr==pTab->nCol );
5554 for(pX=pSub; pX; pX=pX->pPrior){
5555 if( (pX->selFlags & (SF_Distinct|SF_Aggregate))!=0 ){
5556 testcase( pX->selFlags & SF_Distinct );
5557 testcase( pX->selFlags & SF_Aggregate );
5558 return 0;
5559 }
5560 if( pX->pPrior && pX->op!=TK_ALL ){
5561 /* This optimization does not work for compound subqueries that
5562 ** use UNION, INTERSECT, or EXCEPT. Only UNION ALL is allowed. */
5563 return 0;
5564 }
5565#ifndef SQLITE_OMIT_WINDOWFUNC
5566 if( pX->pWin ){
5567 /* This optimization does not work for subqueries that use window
5568 ** functions. */
5569 return 0;
5570 }
5571#endif
5572 }
5573 colUsed = pItem->colUsed;
5574 if( pSub->pOrderBy ){
5575 ExprList *pList = pSub->pOrderBy;
5576 for(j=0; j<pList->nExpr; j++){
5577 u16 iCol = pList->a[j].u.x.iOrderByCol;
5578 if( iCol>0 ){
5579 iCol--;
5580 colUsed |= ((Bitmask)1)<<(iCol>=BMS ? BMS-1 : iCol);
5581 }
5582 }
5583 }
5584 nCol = pTab->nCol;
5585 for(j=0; j<nCol; j++){
5586 Bitmask m = j<BMS-1 ? MASKBIT(j) : TOPBIT;
5587 if( (m & colUsed)!=0 ) continue;
5588 for(pX=pSub; pX; pX=pX->pPrior) {
5589 Expr *pY = pX->pEList->a[j].pExpr;
5590 if( pY->op==TK_NULL ) continue;
5591 pY->op = TK_NULL;
5592 ExprClearProperty(pY, EP_Skip|EP_Unlikely);
5593 pX->selFlags |= SF_PushDown;
5594 nChng++;
5595 }
5596 }
5597 return nChng;
5598}
5599
5600
5601/*
5602** The pFunc is the only aggregate function in the query. Check to see
5603** if the query is a candidate for the min/max optimization.
5604**
5605** If the query is a candidate for the min/max optimization, then set
5606** *ppMinMax to be an ORDER BY clause to be used for the optimization
5607** and return either WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX depending on
5608** whether pFunc is a min() or max() function.
5609**
5610** If the query is not a candidate for the min/max optimization, return
5611** WHERE_ORDERBY_NORMAL (which must be zero).
5612**
5613** This routine must be called after aggregate functions have been
5614** located but before their arguments have been subjected to aggregate
5615** analysis.
5616*/
5617static u8 minMaxQuery(sqlite3 *db, Expr *pFunc, ExprList **ppMinMax){
5618 int eRet = WHERE_ORDERBY_NORMAL; /* Return value */
5619 ExprList *pEList; /* Arguments to agg function */
5620 const char *zFunc; /* Name of aggregate function pFunc */
5621 ExprList *pOrderBy;
5622 u8 sortFlags = 0;
5623
5624 assert( *ppMinMax==0 );
5625 assert( pFunc->op==TK_AGG_FUNCTION );
5626 assert( !IsWindowFunc(pFunc) );
5627 assert( ExprUseXList(pFunc) );
5628 pEList = pFunc->x.pList;
5629 if( pEList==0
5630 || pEList->nExpr!=1
5631 || ExprHasProperty(pFunc, EP_WinFunc)
5632 || OptimizationDisabled(db, SQLITE_MinMaxOpt)
5633 ){
5634 return eRet;
5635 }
5636 assert( !ExprHasProperty(pFunc, EP_IntValue) );
5637 zFunc = pFunc->u.zToken;
5638 if( sqlite3StrICmp(zFunc, "min")==0 ){
5639 eRet = WHERE_ORDERBY_MIN;
5640 if( sqlite3ExprCanBeNull(pEList->a[0].pExpr) ){
5641 sortFlags = KEYINFO_ORDER_BIGNULL;
5642 }
5643 }else if( sqlite3StrICmp(zFunc, "max")==0 ){
5644 eRet = WHERE_ORDERBY_MAX;
5645 sortFlags = KEYINFO_ORDER_DESC;
5646 }else{
5647 return eRet;
5648 }
5649 *ppMinMax = pOrderBy = sqlite3ExprListDup(db, pEList, 0);
5650 assert( pOrderBy!=0 || db->mallocFailed );
5651 if( pOrderBy ) pOrderBy->a[0].fg.sortFlags = sortFlags;
5652 return eRet;
5653}
5654
5655/*
5656** The select statement passed as the first argument is an aggregate query.
5657** The second argument is the associated aggregate-info object. This
5658** function tests if the SELECT is of the form:
5659**
5660** SELECT count(*) FROM <tbl>
5661**
5662** where table is a database table, not a sub-select or view. If the query
5663** does match this pattern, then a pointer to the Table object representing
5664** <tbl> is returned. Otherwise, NULL is returned.
5665**
5666** This routine checks to see if it is safe to use the count optimization.
5667** A correct answer is still obtained (though perhaps more slowly) if
5668** this routine returns NULL when it could have returned a table pointer.
5669** But returning the pointer when NULL should have been returned can
5670** result in incorrect answers and/or crashes. So, when in doubt, return NULL.
5671*/
5672static Table *isSimpleCount(Select *p, AggInfo *pAggInfo){
5673 Table *pTab;
5674 Expr *pExpr;
5675
5676 assert( !p->pGroupBy );
5677
5678 if( p->pWhere
5679 || p->pEList->nExpr!=1
5680 || p->pSrc->nSrc!=1
5681 || p->pSrc->a[0].fg.isSubquery
5682 || pAggInfo->nFunc!=1
5683 || p->pHaving
5684 ){
5685 return 0;
5686 }
5687 pTab = p->pSrc->a[0].pSTab;
5688 assert( pTab!=0 );
5689 assert( !IsView(pTab) );
5690 if( !IsOrdinaryTable(pTab) ) return 0;
5691 pExpr = p->pEList->a[0].pExpr;
5692 assert( pExpr!=0 );
5693 if( pExpr->op!=TK_AGG_FUNCTION ) return 0;
5694 if( pExpr->pAggInfo!=pAggInfo ) return 0;
5695 if( (pAggInfo->aFunc[0].pFunc->funcFlags&SQLITE_FUNC_COUNT)==0 ) return 0;
5696 assert( pAggInfo->aFunc[0].pFExpr==pExpr );
5697 testcase( ExprHasProperty(pExpr, EP_Distinct) );
5698 testcase( ExprHasProperty(pExpr, EP_WinFunc) );
5699 if( ExprHasProperty(pExpr, EP_Distinct|EP_WinFunc) ) return 0;
5700
5701 return pTab;
5702}
5703
5704/*
5705** If the source-list item passed as an argument was augmented with an
5706** INDEXED BY clause, then try to locate the specified index. If there
5707** was such a clause and the named index cannot be found, return
5708** SQLITE_ERROR and leave an error in pParse. Otherwise, populate
5709** pFrom->pIndex and return SQLITE_OK.
5710*/
5711int sqlite3IndexedByLookup(Parse *pParse, SrcItem *pFrom){
5712 Table *pTab = pFrom->pSTab;
5713 char *zIndexedBy = pFrom->u1.zIndexedBy;
5714 Index *pIdx;
5715 assert( pTab!=0 );
5716 assert( pFrom->fg.isIndexedBy!=0 );
5717
5718 for(pIdx=pTab->pIndex;
5719 pIdx && sqlite3StrICmp(pIdx->zName, zIndexedBy);
5720 pIdx=pIdx->pNext
5721 );
5722 if( !pIdx ){
5723 sqlite3ErrorMsg(pParse, "no such index: %s", zIndexedBy, 0);
5724 pParse->checkSchema = 1;
5725 return SQLITE_ERROR;
5726 }
5727 assert( pFrom->fg.isCte==0 );
5728 pFrom->u2.pIBIndex = pIdx;
5729 return SQLITE_OK;
5730}
5731
5732/*
5733** Detect compound SELECT statements that use an ORDER BY clause with
5734** an alternative collating sequence.
5735**
5736** SELECT ... FROM t1 EXCEPT SELECT ... FROM t2 ORDER BY .. COLLATE ...
5737**
5738** These are rewritten as a subquery:
5739**
5740** SELECT * FROM (SELECT ... FROM t1 EXCEPT SELECT ... FROM t2)
5741** ORDER BY ... COLLATE ...
5742**
5743** This transformation is necessary because the multiSelectByMerge() routine
5744** above that generates the code for a compound SELECT with an ORDER BY clause
5745** uses a merge algorithm that requires the same collating sequence on the
5746** result columns as on the ORDER BY clause. See ticket
5747** http://sqlite.org/src/info/6709574d2a
5748**
5749** This transformation is only needed for EXCEPT, INTERSECT, and UNION.
5750** The UNION ALL operator works fine with multiSelectByMerge() even when
5751** there are COLLATE terms in the ORDER BY.
5752*/
5753static int convertCompoundSelectToSubquery(Walker *pWalker, Select *p){
5754 int i;
5755 Select *pNew;
5756 Select *pX;
5757 sqlite3 *db;
5758 struct ExprList_item *a;
5759 SrcList *pNewSrc;
5760 Parse *pParse;
5761 Token dummy;
5762
5763 if( p->pPrior==0 ) return WRC_Continue;
5764 if( p->pOrderBy==0 ) return WRC_Continue;
5765 for(pX=p; pX && (pX->op==TK_ALL || pX->op==TK_SELECT); pX=pX->pPrior){}
5766 if( pX==0 ) return WRC_Continue;
5767 a = p->pOrderBy->a;
5768#ifndef SQLITE_OMIT_WINDOWFUNC
5769 /* If iOrderByCol is already non-zero, then it has already been matched
5770 ** to a result column of the SELECT statement. This occurs when the
5771 ** SELECT is rewritten for window-functions processing and then passed
5772 ** to sqlite3SelectPrep() and similar a second time. The rewriting done
5773 ** by this function is not required in this case. */
5774 if( a[0].u.x.iOrderByCol ) return WRC_Continue;
5775#endif
5776 for(i=p->pOrderBy->nExpr-1; i>=0; i--){
5777 if( a[i].pExpr->flags & EP_Collate ) break;
5778 }
5779 if( i<0 ) return WRC_Continue;
5780
5781 /* If we reach this point, that means the transformation is required. */
5782
5783 pParse = pWalker->pParse;
5784 db = pParse->db;
5785 pNew = sqlite3DbMallocZero(db, sizeof(*pNew) );
5786 if( pNew==0 ) return WRC_Abort;
5787 memset(&dummy, 0, sizeof(dummy));
5788 pNewSrc = sqlite3SrcListAppendFromTerm(pParse,0,0,0,&dummy,pNew,0);
5789 assert( pNewSrc!=0 || pParse->nErr );
5790 if( pParse->nErr ){
5791 sqlite3SrcListDelete(db, pNewSrc);
5792 return WRC_Abort;
5793 }
5794 *pNew = *p;
5795 p->pSrc = pNewSrc;
5796 p->pEList = sqlite3ExprListAppend(pParse, 0, sqlite3Expr(db, TK_ASTERISK, 0));
5797 p->op = TK_SELECT;
5798 p->pWhere = 0;
5799 p->pGroupBy = 0;
5800 p->pHaving = 0;
5801 pNew->pOrderBy = 0;
5802 p->pPrior = 0;
5803 p->pNext = 0;
5804 p->pWith = 0;
5805#ifndef SQLITE_OMIT_WINDOWFUNC
5806 p->pWinDefn = 0;
5807#endif
5808 p->selFlags &= ~(u32)(SF_Compound|SF_Distinct);
5809 assert( (p->selFlags & SF_Converted)==0 );
5810 p->selFlags |= SF_Converted;
5811 assert( pNew->pPrior!=0 );
5812 pNew->pPrior->pNext = pNew;
5813 pNew->pLimit = 0;
5814 return WRC_Continue;
5815}
5816
5817/*
5818** Check to see if the FROM clause term pFrom has table-valued function
5819** arguments. If it does, leave an error message in pParse and return
5820** non-zero, since pFrom is not allowed to be a table-valued function.
5821*/
5822static int cannotBeFunction(Parse *pParse, SrcItem *pFrom){
5823 if( pFrom->fg.isTabFunc ){
5824 sqlite3ErrorMsg(pParse, "'%s' is not a function", pFrom->zName);
5825 return 1;
5826 }
5827 return 0;
5828}
5829
5830#ifndef SQLITE_OMIT_CTE
5831/*
5832** Argument pWith (which may be NULL) points to a linked list of nested
5833** WITH contexts, from inner to outermost. If the table identified by
5834** FROM clause element pItem is really a common-table-expression (CTE)
5835** then return a pointer to the CTE definition for that table. Otherwise
5836** return NULL.
5837**
5838** If a non-NULL value is returned, set *ppContext to point to the With
5839** object that the returned CTE belongs to.
5840*/
5841static struct Cte *searchWith(
5842 With *pWith, /* Current innermost WITH clause */
5843 SrcItem *pItem, /* FROM clause element to resolve */
5844 With **ppContext /* OUT: WITH clause return value belongs to */
5845){
5846 const char *zName = pItem->zName;
5847 With *p;
5848 assert( pItem->fg.fixedSchema || pItem->u4.zDatabase==0 );
5849 assert( zName!=0 );
5850 for(p=pWith; p; p=p->pOuter){
5851 int i;
5852 for(i=0; i<p->nCte; i++){
5853 if( sqlite3StrICmp(zName, p->a[i].zName)==0 ){
5854 *ppContext = p;
5855 return &p->a[i];
5856 }
5857 }
5858 if( p->bView ) break;
5859 }
5860 return 0;
5861}
5862
5863/* The code generator maintains a stack of active WITH clauses
5864** with the inner-most WITH clause being at the top of the stack.
5865**
5866** This routine pushes the WITH clause passed as the second argument
5867** onto the top of the stack. If argument bFree is true, then this
5868** WITH clause will never be popped from the stack but should instead
5869** be freed along with the Parse object. In other cases, when
5870** bFree==0, the With object will be freed along with the SELECT
5871** statement with which it is associated.
5872**
5873** This routine returns a copy of pWith. Or, if bFree is true and
5874** the pWith object is destroyed immediately due to an OOM condition,
5875** then this routine return NULL.
5876**
5877** If bFree is true, do not continue to use the pWith pointer after
5878** calling this routine, Instead, use only the return value.
5879*/
5880With *sqlite3WithPush(Parse *pParse, With *pWith, u8 bFree){
5881 if( pWith ){
5882 if( bFree ){
5883 pWith = (With*)sqlite3ParserAddCleanup(pParse, sqlite3WithDeleteGeneric,
5884 pWith);
5885 if( pWith==0 ) return 0;
5886 }
5887 if( pParse->nErr==0 ){
5888 assert( pParse->pWith!=pWith );
5889 pWith->pOuter = pParse->pWith;
5890 pParse->pWith = pWith;
5891 }
5892 }
5893 return pWith;
5894}
5895
5896static int selectExpanderWalk(Walker*, Select*);
5897
5898/*
5899** This function checks to see if argument pFrom refers to a CTE declared by
5900** a WITH clause on the stack currently maintained by the parser (on the
5901** pParse->pWith linked list). And if currently processing a CTE expression,
5902** it also checks to see if the reference is a recursive reference to the CTE.
5903**
5904** If pFrom matches a CTE, pFrom->pSTab and other fields are populated
5905** accordingly.
5906**
5907** Return 0 if no match is found.
5908** Return 1 if a match is found.
5909** Return 2 if an error condition is detected.
5910*/
5911static int resolveFromTermToCte(
5912 Parse *pParse, /* The parsing context */
5913 Walker *pWalker, /* Current tree walker */
5914 SrcItem *pFrom /* The FROM clause term to check */
5915){
5916 Cte *pCte; /* Matched CTE (or NULL if no match) */
5917 With *pWith; /* The matching WITH */
5918
5919 assert( pFrom->pSTab==0 );
5920 if( pParse->pWith==0 ){
5921 /* There are no WITH clauses in the stack. No match is possible */
5922 return 0;
5923 }
5924 if( pParse->nErr ){
5925 /* Prior errors might have left pParse->pWith in a goofy state, so
5926 ** go no further. */
5927 return 0;
5928 }
5929 assert( pFrom->fg.hadSchema==0 || pFrom->fg.notCte!=0 );
5930 if( pFrom->fg.fixedSchema==0 && pFrom->u4.zDatabase!=0 ){
5931 /* The FROM term contains a schema qualifier (ex: main.t1) and so
5932 ** it cannot possibly be a CTE reference. */
5933 return 0;
5934 }
5935 if( pFrom->fg.notCte ){
5936 /* The FROM term is specifically excluded from matching a CTE.
5937 ** (1) It is part of a trigger that used to have zDatabase but had
5938 ** zDatabase removed by sqlite3FixTriggerStep().
5939 ** (2) This is the first term in the FROM clause of an UPDATE.
5940 */
5941 return 0;
5942 }
5943 pCte = searchWith(pParse->pWith, pFrom, &pWith);
5944 if( pCte ){
5945 sqlite3 *db = pParse->db;
5946 Table *pTab;
5947 ExprList *pEList;
5948 Select *pSel;
5949 Select *pLeft; /* Left-most SELECT statement */
5950 Select *pRecTerm; /* Left-most recursive term */
5951 int bMayRecursive; /* True if compound joined by UNION [ALL] */
5952 With *pSavedWith; /* Initial value of pParse->pWith */
5953 int iRecTab = -1; /* Cursor for recursive table */
5954 CteUse *pCteUse;
5955
5956 /* If pCte->zCteErr is non-NULL at this point, then this is an illegal
5957 ** recursive reference to CTE pCte. Leave an error in pParse and return
5958 ** early. If pCte->zCteErr is NULL, then this is not a recursive reference.
5959 ** In this case, proceed. */
5960 if( pCte->zCteErr ){
5961 sqlite3ErrorMsg(pParse, pCte->zCteErr, pCte->zName);
5962 return 2;
5963 }
5964 if( cannotBeFunction(pParse, pFrom) ) return 2;
5965
5966 assert( pFrom->pSTab==0 );
5967 pTab = sqlite3DbMallocZero(db, sizeof(Table));
5968 if( pTab==0 ) return 2;
5969 pCteUse = pCte->pUse;
5970 if( pCteUse==0 ){
5971 pCte->pUse = pCteUse = sqlite3DbMallocZero(db, sizeof(pCteUse[0]));
5972 if( pCteUse==0
5973 || sqlite3ParserAddCleanup(pParse,sqlite3DbFree,pCteUse)==0
5974 ){
5975 sqlite3DbFree(db, pTab);
5976 return 2;
5977 }
5978 pCteUse->eM10d = pCte->eM10d;
5979 }
5980 pFrom->pSTab = pTab;
5981 pTab->nTabRef = 1;
5982 pTab->zName = sqlite3DbStrDup(db, pCte->zName);
5983 pTab->iPKey = -1;
5984 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
5985 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
5986 sqlite3SrcItemAttachSubquery(pParse, pFrom, pCte->pSelect, 1);
5987 if( db->mallocFailed ) return 2;
5988 assert( pFrom->fg.isSubquery && pFrom->u4.pSubq );
5989 pSel = pFrom->u4.pSubq->pSelect;
5990 assert( pSel!=0 );
5991 pSel->selFlags |= SF_CopyCte;
5992 if( pFrom->fg.isIndexedBy ){
5993 sqlite3ErrorMsg(pParse, "no such index: \"%s\"", pFrom->u1.zIndexedBy);
5994 return 2;
5995 }
5996 assert( !pFrom->fg.isIndexedBy );
5997 pFrom->fg.isCte = 1;
5998 pFrom->u2.pCteUse = pCteUse;
5999 pCteUse->nUse++;
6000
6001 /* Check if this is a recursive CTE. */
6002 pRecTerm = pSel;
6003 bMayRecursive = ( pSel->op==TK_ALL || pSel->op==TK_UNION );
6004 while( bMayRecursive && pRecTerm->op==pSel->op ){
6005 int i;
6006 SrcList *pSrc = pRecTerm->pSrc;
6007 assert( pRecTerm->pPrior!=0 );
6008 for(i=0; i<pSrc->nSrc; i++){
6009 SrcItem *pItem = &pSrc->a[i];
6010 if( pItem->zName!=0
6011 && !pItem->fg.hadSchema
6012 && ALWAYS( !pItem->fg.isSubquery )
6013 && (pItem->fg.fixedSchema || pItem->u4.zDatabase==0)
6014 && 0==sqlite3StrICmp(pItem->zName, pCte->zName)
6015 ){
6016 pItem->pSTab = pTab;
6017 pTab->nTabRef++;
6018 pItem->fg.isRecursive = 1;
6019 if( pRecTerm->selFlags & SF_Recursive ){
6020 sqlite3ErrorMsg(pParse,
6021 "multiple references to recursive table: %s", pCte->zName
6022 );
6023 return 2;
6024 }
6025 pRecTerm->selFlags |= SF_Recursive;
6026 if( iRecTab<0 ) iRecTab = pParse->nTab++;
6027 pItem->iCursor = iRecTab;
6028 }
6029 }
6030 if( (pRecTerm->selFlags & SF_Recursive)==0 ) break;
6031 pRecTerm = pRecTerm->pPrior;
6032 }
6033
6034 if( pParse->nTab >= db->aLimit[SQLITE_LIMIT_CTES]
6035 && db->aLimit[SQLITE_LIMIT_CTES]>0
6036 ){
6037 sqlite3ErrorMsg(pParse, "too many CTEs");
6038 return 2;
6039 }
6040#if SQLITE_MAX_EXPR_DEPTH>0
6041 pParse->nNestSel++;
6042 if( checkSubqueryNestingDepth(pParse) ) return 2;
6043#endif
6044 pCte->zCteErr = "circular reference: %s";
6045 pSavedWith = pParse->pWith;
6046 pParse->pWith = pWith;
6047 if( pSel->selFlags & SF_Recursive ){
6048 int rc;
6049 assert( pRecTerm!=0 );
6050 assert( (pRecTerm->selFlags & SF_Recursive)==0 );
6051 assert( pRecTerm->pNext!=0 );
6052 assert( (pRecTerm->pNext->selFlags & SF_Recursive)!=0 );
6053 assert( pRecTerm->pWith==0 );
6054 pRecTerm->pWith = pSel->pWith;
6055 rc = sqlite3WalkSelect(pWalker, pRecTerm);
6056 pRecTerm->pWith = 0;
6057 if( rc ){
6058 pParse->pWith = pSavedWith;
6059 return 2;
6060 }
6061 }else{
6062 if( selectExpanderWalk(pWalker, pSel) ){
6063 pParse->pWith = pSavedWith;
6064 return 2;
6065 }
6066 }
6067 pParse->pWith = pWith;
6068#if SQLITE_MAX_EXPR_DEPTH>0
6069 pParse->nNestSel--;
6070 assert( pParse->nNestSel>=0 );
6071#endif
6072
6073 for(pLeft=pSel; pLeft->pPrior; pLeft=pLeft->pPrior);
6074 pEList = pLeft->pEList;
6075 if( pCte->pCols ){
6076 if( pEList && pEList->nExpr!=pCte->pCols->nExpr ){
6077 sqlite3ErrorMsg(pParse, "table %s has %d values for %d columns",
6078 pCte->zName, pEList->nExpr, pCte->pCols->nExpr
6079 );
6080 pParse->pWith = pSavedWith;
6081 return 2;
6082 }
6083 pEList = pCte->pCols;
6084 }
6085
6086 sqlite3ColumnsFromExprList(pParse, pEList, &pTab->nCol, &pTab->aCol);
6087 if( bMayRecursive ){
6088 if( pSel->selFlags & SF_Recursive ){
6089 pCte->zCteErr = "multiple recursive references: %s";
6090 }else{
6091 pCte->zCteErr = "recursive reference in a subquery: %s";
6092 }
6093 sqlite3WalkSelect(pWalker, pSel);
6094 }
6095 pCte->zCteErr = 0;
6096 pParse->pWith = pSavedWith;
6097 return 1; /* Success */
6098 }
6099 return 0; /* No match */
6100}
6101#endif
6102
6103#ifndef SQLITE_OMIT_CTE
6104/*
6105** If the SELECT passed as the second argument has an associated WITH
6106** clause, pop it from the stack stored as part of the Parse object.
6107**
6108** This function is used as the xSelectCallback2() callback by
6109** sqlite3SelectExpand() when walking a SELECT tree to resolve table
6110** names and other FROM clause elements.
6111*/
6112void sqlite3SelectPopWith(Walker *pWalker, Select *p){
6113 Parse *pParse = pWalker->pParse;
6114 if( OK_IF_ALWAYS_TRUE(pParse->pWith) && p->pPrior==0 ){
6115 With *pWith = findRightmost(p)->pWith;
6116 if( pWith!=0 ){
6117 assert( pParse->pWith==pWith || pParse->nErr );
6118 pParse->pWith = pWith->pOuter;
6119 }
6120 }
6121}
6122#endif
6123
6124/*
6125** The SrcItem structure passed as the second argument represents a
6126** sub-query in the FROM clause of a SELECT statement. This function
6127** allocates and populates the SrcItem.pTab object. If successful,
6128** SQLITE_OK is returned. Otherwise, if an OOM error is encountered,
6129** SQLITE_NOMEM.
6130*/
6131int sqlite3ExpandSubquery(Parse *pParse, SrcItem *pFrom){
6132 Select *pSel;
6133 Table *pTab;
6134
6135 assert( pFrom->fg.isSubquery );
6136 assert( pFrom->u4.pSubq!=0 );
6137 pSel = pFrom->u4.pSubq->pSelect;
6138 assert( pSel );
6139 pFrom->pSTab = pTab = sqlite3DbMallocZero(pParse->db, sizeof(Table));
6140 if( pTab==0 ) return SQLITE_NOMEM;
6141 pTab->nTabRef = 1;
6142 if( pFrom->zAlias ){
6143 pTab->zName = sqlite3DbStrDup(pParse->db, pFrom->zAlias);
6144 }else{
6145 pTab->zName = sqlite3MPrintf(pParse->db, "%!S", pFrom);
6146 }
6147 while( pSel->pPrior ){ pSel = pSel->pPrior; }
6148 sqlite3ColumnsFromExprList(pParse, pSel->pEList,&pTab->nCol,&pTab->aCol);
6149 pTab->iPKey = -1;
6150 pTab->eTabType = TABTYP_VIEW;
6151 pTab->nRowLogEst = 200; assert( 200==sqlite3LogEst(1048576) );
6152#ifndef SQLITE_ALLOW_ROWID_IN_VIEW
6153 /* The usual case - do not allow ROWID on a subquery */
6154 pTab->tabFlags |= TF_Ephemeral | TF_NoVisibleRowid;
6155#else
6156 /* Legacy compatibility mode */
6157 pTab->tabFlags |= TF_Ephemeral | sqlite3Config.mNoVisibleRowid;
6158#endif
6159 return pParse->nErr ? SQLITE_ERROR : SQLITE_OK;
6160}
6161
6162
6163/*
6164** Check the N SrcItem objects to the right of pBase. (N might be zero!)
6165** If any of those SrcItem objects have a USING clause containing zName
6166** then return true.
6167**
6168** If N is zero, or none of the N SrcItem objects to the right of pBase
6169** contains a USING clause, or if none of the USING clauses contain zName,
6170** then return false.
6171*/
6172static int inAnyUsingClause(
6173 const char *zName, /* Name we are looking for */
6174 SrcItem *pBase, /* The base SrcItem. Looking at pBase[1] and following */
6175 int N /* How many SrcItems to check */
6176){
6177 while( N>0 ){
6178 N--;
6179 pBase++;
6180 if( pBase->fg.isUsing==0 ) continue;
6181 if( NEVER(pBase->u3.pUsing==0) ) continue;
6182 if( sqlite3IdListIndex(pBase->u3.pUsing, zName)>=0 ) return 1;
6183 }
6184 return 0;
6185}
6186
6187
6188/*
6189** This routine is a Walker callback for "expanding" a SELECT statement.
6190** "Expanding" means to do the following:
6191**
6192** (1) Make sure VDBE cursor numbers have been assigned to every
6193** element of the FROM clause.
6194**
6195** (2) Fill in the pTabList->a[].pTab fields in the SrcList that
6196** defines FROM clause. When views appear in the FROM clause,
6197** fill pTabList->a[].pSelect with a copy of the SELECT statement
6198** that implements the view. A copy is made of the view's SELECT
6199** statement so that we can freely modify or delete that statement
6200** without worrying about messing up the persistent representation
6201** of the view.
6202**
6203** (3) Add terms to the WHERE clause to accommodate the NATURAL keyword
6204** on joins and the ON and USING clause of joins.
6205**
6206** (4) Scan the list of columns in the result set (pEList) looking
6207** for instances of the "*" operator or the TABLE.* operator.
6208** If found, expand each "*" to be every column in every table
6209** and TABLE.* to be every column in TABLE.
6210**
6211*/
6212static int selectExpander(Walker *pWalker, Select *p){
6213 Parse *pParse = pWalker->pParse;
6214 int i, j, k, rc;
6215 SrcList *pTabList;
6216 ExprList *pEList;
6217 SrcItem *pFrom;
6218 sqlite3 *db = pParse->db;
6219 Expr *pE, *pRight, *pExpr;
6220 u16 selFlags = p->selFlags;
6221 u32 elistFlags = 0;
6222
6223 p->selFlags |= SF_Expanded;
6224 if( db->mallocFailed ){
6225 return WRC_Abort;
6226 }
6227 assert( p->pSrc!=0 );
6228 if( (selFlags & SF_Expanded)!=0 ){
6229 return WRC_Prune;
6230 }
6231 if( pWalker->eCode ){
6232 /* Renumber selId because it has been copied from a view */
6233 p->selId = ++pParse->nSelect;
6234 }
6235 pTabList = p->pSrc;
6236 pEList = p->pEList;
6237 if( pParse->pWith && (p->selFlags & SF_View) ){
6238 if( p->pWith==0 ){
6239 p->pWith = (With*)sqlite3DbMallocZero(db, SZ_WITH(1) );
6240 if( p->pWith==0 ){
6241 return WRC_Abort;
6242 }
6243 }
6244 p->pWith->bView = 1;
6245 }
6246 sqlite3WithPush(pParse, p->pWith, 0);
6247
6248 /* Make sure cursor numbers have been assigned to all entries in
6249 ** the FROM clause of the SELECT statement.
6250 */
6251 sqlite3SrcListAssignCursors(pParse, pTabList);
6252
6253 /* Look up every table named in the FROM clause of the select. If
6254 ** an entry of the FROM clause is a subquery instead of a table or view,
6255 ** then create a transient table structure to describe the subquery.
6256 */
6257 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6258 Table *pTab;
6259 assert( pFrom->fg.isRecursive==0 || pFrom->pSTab!=0 );
6260 if( pFrom->pSTab ) continue;
6261 assert( pFrom->fg.isRecursive==0 );
6262 if( pFrom->zName==0 ){
6263#ifndef SQLITE_OMIT_SUBQUERY
6264 Select *pSel;
6265 assert( pFrom->fg.isSubquery && pFrom->u4.pSubq!=0 );
6266 pSel = pFrom->u4.pSubq->pSelect;
6267 /* A sub-query in the FROM clause of a SELECT */
6268 assert( pSel!=0 );
6269 assert( pFrom->pSTab==0 );
6270 if( sqlite3WalkSelect(pWalker, pSel) ) return WRC_Abort;
6271 if( sqlite3ExpandSubquery(pParse, pFrom) ) return WRC_Abort;
6272#endif
6273#ifndef SQLITE_OMIT_CTE
6274 }else if( (rc = resolveFromTermToCte(pParse, pWalker, pFrom))!=0 ){
6275 if( rc>1 ) return WRC_Abort;
6276 pTab = pFrom->pSTab;
6277 assert( pTab!=0 );
6278#endif
6279 }else{
6280 /* An ordinary table or view name in the FROM clause */
6281 assert( pFrom->pSTab==0 );
6282 pFrom->pSTab = pTab = sqlite3LocateTableItem(pParse, 0, pFrom);
6283 if( pTab==0 ) return WRC_Abort;
6284 if( pTab->nTabRef>=0xffff ){
6285 sqlite3ErrorMsg(pParse, "too many references to \"%s\": max 65535",
6286 pTab->zName);
6287 pFrom->pSTab = 0;
6288 return WRC_Abort;
6289 }
6290 pTab->nTabRef++;
6291 if( !IsVirtual(pTab) && cannotBeFunction(pParse, pFrom) ){
6292 return WRC_Abort;
6293 }
6294#if !defined(SQLITE_OMIT_VIEW) || !defined(SQLITE_OMIT_VIRTUALTABLE)
6295 if( !IsOrdinaryTable(pTab) ){
6296 i16 nCol;
6297 u8 eCodeOrig = pWalker->eCode;
6298 if( sqlite3ViewGetColumnNames(pParse, pTab) ) return WRC_Abort;
6299 assert( pFrom->fg.isSubquery==0 );
6300 if( IsView(pTab) ){
6301 if( (db->flags & SQLITE_EnableView)==0
6302 && pTab->pSchema!=db->aDb[1].pSchema
6303 ){
6304 sqlite3ErrorMsg(pParse, "access to view \"%s\" prohibited",
6305 pTab->zName);
6306 }
6307 sqlite3SrcItemAttachSubquery(pParse, pFrom, pTab->u.view.pSelect, 1);
6308 }
6309#ifndef SQLITE_OMIT_VIRTUALTABLE
6310 else if( ALWAYS(IsVirtual(pTab))
6311 && (pFrom->fg.fromDDL || (pParse->prepFlags & SQLITE_PREPARE_FROM_DDL))
6312 && ALWAYS(pTab->u.vtab.p!=0)
6313 && pTab->u.vtab.p->eVtabRisk > ((db->flags & SQLITE_TrustedSchema)!=0)
6314 ){
6315 sqlite3ErrorMsg(pParse, "unsafe use of virtual table \"%s\"",
6316 pTab->zName);
6317 }
6318 assert( SQLITE_VTABRISK_Normal==1 && SQLITE_VTABRISK_High==2 );
6319#endif
6320 nCol = pTab->nCol;
6321 pTab->nCol = -1;
6322 pWalker->eCode = 1; /* Turn on Select.selId renumbering */
6323 if( pFrom->fg.isSubquery ){
6324 bft hasCompound = pParse->hasCompound;
6325 pParse->hasCompound = 1;
6326 selectExpanderWalk(pWalker, pFrom->u4.pSubq->pSelect);
6327 pParse->hasCompound = hasCompound;
6328 }
6329 pWalker->eCode = eCodeOrig;
6330 pTab->nCol = nCol;
6331 }
6332#endif
6333 }
6334
6335 /* Locate the index named by the INDEXED BY clause, if any. */
6336 if( pFrom->fg.isIndexedBy && sqlite3IndexedByLookup(pParse, pFrom) ){
6337 return WRC_Abort;
6338 }
6339 }
6340
6341 /* Process NATURAL keywords, and ON and USING clauses of joins.
6342 */
6343 assert( db->mallocFailed==0 || pParse->nErr!=0 );
6344 if( pParse->nErr || sqlite3ProcessJoin(pParse, p) ){
6345 return WRC_Abort;
6346 }
6347
6348 /* For every "*" that occurs in the column list, insert the names of
6349 ** all columns in all tables. And for every TABLE.* insert the names
6350 ** of all columns in TABLE. The parser inserted a special expression
6351 ** with the TK_ASTERISK operator for each "*" that it found in the column
6352 ** list. The following code just has to locate the TK_ASTERISK
6353 ** expressions and expand each one to the list of all columns in
6354 ** all tables.
6355 **
6356 ** The first loop just checks to see if there are any "*" operators
6357 ** that need expanding.
6358 */
6359 for(k=0; k<pEList->nExpr; k++){
6360 pE = pEList->a[k].pExpr;
6361 if( pE->op==TK_ASTERISK ) break;
6362 assert( pE->op!=TK_DOT || pE->pRight!=0 );
6363 assert( pE->op!=TK_DOT || (pE->pLeft!=0 && pE->pLeft->op==TK_ID) );
6364 if( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK ) break;
6365 elistFlags |= pE->flags;
6366 }
6367 if( k<pEList->nExpr ){
6368 /*
6369 ** If we get here it means the result set contains one or more "*"
6370 ** operators that need to be expanded. Loop through each expression
6371 ** in the result set and expand them one by one.
6372 */
6373 struct ExprList_item *a = pEList->a;
6374 ExprList *pNew = 0;
6375 int flags = pParse->db->flags;
6376 int longNames = (flags & SQLITE_FullColNames)!=0
6377 && (flags & SQLITE_ShortColNames)==0;
6378
6379 for(k=0; k<pEList->nExpr; k++){
6380 pE = a[k].pExpr;
6381 elistFlags |= pE->flags;
6382 pRight = pE->pRight;
6383 assert( pE->op!=TK_DOT || pRight!=0 );
6384 if( pE->op!=TK_ASTERISK
6385 && (pE->op!=TK_DOT || pRight->op!=TK_ASTERISK)
6386 ){
6387 /* This particular expression does not need to be expanded.
6388 */
6389 pNew = sqlite3ExprListAppend(pParse, pNew, a[k].pExpr);
6390 if( pNew ){
6391 pNew->a[pNew->nExpr-1].zEName = a[k].zEName;
6392 pNew->a[pNew->nExpr-1].fg.eEName = a[k].fg.eEName;
6393 a[k].zEName = 0;
6394 }
6395 a[k].pExpr = 0;
6396 }else{
6397 /* This expression is a "*" or a "TABLE.*" and needs to be
6398 ** expanded. */
6399 int tableSeen = 0; /* Set to 1 when TABLE matches */
6400 char *zTName = 0; /* text of name of TABLE */
6401 int iErrOfst;
6402 if( pE->op==TK_DOT ){
6403 assert( (selFlags & SF_NestedFrom)==0 );
6404 assert( pE->pLeft!=0 );
6405 assert( !ExprHasProperty(pE->pLeft, EP_IntValue) );
6406 zTName = pE->pLeft->u.zToken;
6407 assert( ExprUseWOfst(pE->pLeft) );
6408 iErrOfst = pE->pRight->w.iOfst;
6409 }else{
6410 assert( pE->pLeft==0 );
6411 assert( ExprUseWOfst(pE) );
6412 iErrOfst = pE->w.iOfst;
6413 }
6414 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6415 int nAdd; /* Number of cols including rowid */
6416 Table *pTab = pFrom->pSTab; /* Table for this data source */
6417 ExprList *pNestedFrom; /* Result-set of a nested FROM clause */
6418 char *zTabName; /* AS name for this data source */
6419 const char *zSchemaName = 0; /* Schema name for this data source */
6420 int iDb; /* Schema index for this data src */
6421 IdList *pUsing; /* USING clause for pFrom[1] */
6422
6423 if( (zTabName = pFrom->zAlias)==0 ){
6424 zTabName = pTab->zName;
6425 }
6426 if( db->mallocFailed ) break;
6427 assert( (int)pFrom->fg.isNestedFrom == IsNestedFrom(pFrom) );
6428 if( pFrom->fg.isNestedFrom ){
6429 assert( pFrom->fg.isSubquery && pFrom->u4.pSubq );
6430 assert( pFrom->u4.pSubq->pSelect!=0 );
6431 pNestedFrom = pFrom->u4.pSubq->pSelect->pEList;
6432 assert( pNestedFrom!=0 );
6433 assert( pNestedFrom->nExpr==pTab->nCol );
6434 assert( VisibleRowid(pTab)==0 || ViewCanHaveRowid );
6435 }else{
6436 if( zTName && sqlite3StrICmp(zTName, zTabName)!=0 ){
6437 continue;
6438 }
6439 pNestedFrom = 0;
6440 iDb = sqlite3SchemaToIndex(db, pTab->pSchema);
6441 zSchemaName = iDb>=0 ? db->aDb[iDb].zDbSName : "*";
6442 }
6443 if( i+1<pTabList->nSrc
6444 && pFrom[1].fg.isUsing
6445 && (selFlags & SF_NestedFrom)!=0
6446 ){
6447 int ii;
6448 pUsing = pFrom[1].u3.pUsing;
6449 for(ii=0; ii<pUsing->nId; ii++){
6450 const char *zUName = pUsing->a[ii].zName;
6451 pRight = sqlite3Expr(db, TK_ID, zUName);
6452 sqlite3ExprSetErrorOffset(pRight, iErrOfst);
6453 pNew = sqlite3ExprListAppend(pParse, pNew, pRight);
6454 if( pNew ){
6455 struct ExprList_item *pX = &pNew->a[pNew->nExpr-1];
6456 assert( pX->zEName==0 );
6457 pX->zEName = sqlite3MPrintf(db,"..%s", zUName);
6458 pX->fg.eEName = ENAME_TAB;
6459 pX->fg.bUsingTerm = 1;
6460 }
6461 }
6462 }else{
6463 pUsing = 0;
6464 }
6465
6466 nAdd = pTab->nCol;
6467 if( VisibleRowid(pTab) && (selFlags & SF_NestedFrom)!=0 ) nAdd++;
6468 for(j=0; j<nAdd; j++){
6469 const char *zName;
6470 struct ExprList_item *pX; /* Newly added ExprList term */
6471
6472 if( j==pTab->nCol ){
6473 zName = sqlite3RowidAlias(pTab);
6474 if( zName==0 ) continue;
6475 }else{
6476 zName = pTab->aCol[j].zCnName;
6477
6478 /* If pTab is actually an SF_NestedFrom sub-select, do not
6479 ** expand any ENAME_ROWID columns. */
6480 if( pNestedFrom && pNestedFrom->a[j].fg.eEName==ENAME_ROWID ){
6481 continue;
6482 }
6483
6484 if( zTName
6485 && pNestedFrom
6486 && sqlite3MatchEName(&pNestedFrom->a[j], 0, zTName, 0, 0)==0
6487 ){
6488 continue;
6489 }
6490
6491 /* If a column is marked as 'hidden', omit it from the expanded
6492 ** result-set list unless the SELECT has the SF_IncludeHidden
6493 ** bit set.
6494 */
6495 if( (p->selFlags & SF_IncludeHidden)==0
6496 && IsHiddenColumn(&pTab->aCol[j])
6497 ){
6498 continue;
6499 }
6500 if( (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND)!=0
6501 && zTName==0
6502 && (selFlags & (SF_NestedFrom))==0
6503 ){
6504 continue;
6505 }
6506 }
6507 assert( zName );
6508 tableSeen = 1;
6509
6510 if( i>0 && zTName==0 && (selFlags & SF_NestedFrom)==0 ){
6511 if( pFrom->fg.isUsing
6512 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0
6513 ){
6514 /* In a join with a USING clause, omit columns in the
6515 ** using clause from the table on the right. */
6516 continue;
6517 }
6518 }
6519 pRight = sqlite3Expr(db, TK_ID, zName);
6520 if( (pTabList->nSrc>1
6521 && ( (pFrom->fg.jointype & JT_LTORJ)==0
6522 || zTName!=0
6523 || (selFlags & SF_NestedFrom)!=0
6524 || !inAnyUsingClause(zName,pFrom,pTabList->nSrc-i-1)
6525 )
6526 )
6527 || IN_RENAME_OBJECT
6528 ){
6529 Expr *pLeft;
6530 pLeft = sqlite3Expr(db, TK_ID, zTabName);
6531 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pRight);
6532 if( IN_RENAME_OBJECT && pE->pLeft ){
6533 assert( pE->op==TK_DOT && pE->pRight->op==TK_ASTERISK );
6534 sqlite3RenameTokenRemap(pParse, pLeft, pE->pLeft);
6535 }
6536 if( zSchemaName ){
6537 pLeft = sqlite3Expr(db, TK_ID, zSchemaName);
6538 pExpr = sqlite3PExpr(pParse, TK_DOT, pLeft, pExpr);
6539 }
6540 }else{
6541 pExpr = pRight;
6542 }
6543 sqlite3ExprSetErrorOffset(pExpr, iErrOfst);
6544 pNew = sqlite3ExprListAppend(pParse, pNew, pExpr);
6545 if( pNew==0 ){
6546 break; /* OOM */
6547 }
6548 pX = &pNew->a[pNew->nExpr-1];
6549 assert( pX->zEName==0 );
6550 if( (selFlags & SF_NestedFrom)!=0 && !IN_RENAME_OBJECT ){
6551 if( pNestedFrom && (!ViewCanHaveRowid || j<pNestedFrom->nExpr) ){
6552 assert( j<pNestedFrom->nExpr );
6553 pX->zEName = sqlite3DbStrDup(db, pNestedFrom->a[j].zEName);
6554 testcase( pX->zEName==0 );
6555 }else{
6556 pX->zEName = sqlite3MPrintf(db, "%s.%s.%s",
6557 zSchemaName, zTabName, zName);
6558 testcase( pX->zEName==0 );
6559 }
6560 pX->fg.eEName = (j==pTab->nCol ? ENAME_ROWID : ENAME_TAB);
6561 if( (pFrom->fg.isUsing
6562 && sqlite3IdListIndex(pFrom->u3.pUsing, zName)>=0)
6563 || (pUsing && sqlite3IdListIndex(pUsing, zName)>=0)
6564 || (j<pTab->nCol && (pTab->aCol[j].colFlags & COLFLAG_NOEXPAND))
6565 ){
6566 pX->fg.bNoExpand = 1;
6567 }
6568 }else if( longNames ){
6569 pX->zEName = sqlite3MPrintf(db, "%s.%s", zTabName, zName);
6570 pX->fg.eEName = ENAME_NAME;
6571 }else{
6572 pX->zEName = sqlite3DbStrDup(db, zName);
6573 pX->fg.eEName = ENAME_NAME;
6574 if( IN_RENAME_OBJECT ) pX->fg.bStarName = 1;
6575 }
6576 }
6577 }
6578 if( !tableSeen ){
6579 if( zTName ){
6580 sqlite3ErrorMsg(pParse, "no such table: %s", zTName);
6581 }else{
6582 sqlite3ErrorMsg(pParse, "no tables specified");
6583 }
6584 }
6585 }
6586 }
6587 sqlite3ExprListDelete(db, pEList);
6588 p->pEList = pNew;
6589 }
6590 if( p->pEList ){
6591 if( p->pEList->nExpr>db->aLimit[SQLITE_LIMIT_COLUMN] ){
6592 sqlite3ErrorMsg(pParse, "too many columns in result set");
6593 return WRC_Abort;
6594 }
6595 if( (elistFlags & (EP_HasFunc|EP_Subquery))!=0 ){
6596 p->selFlags |= SF_ComplexResult;
6597 }
6598 }
6599#if TREETRACE_ENABLED
6600 if( sqlite3TreeTrace & 0x8 ){
6601 TREETRACE(0x8,pParse,p,("After result-set wildcard expansion:\n"));
6602 sqlite3TreeViewSelect(0, p, 0);
6603 }
6604#endif
6605 return WRC_Continue;
6606}
6607
6608#if SQLITE_DEBUG
6609/*
6610** Always assert. This xSelectCallback2 implementation proves that the
6611** xSelectCallback2 is never invoked.
6612*/
6613void sqlite3SelectWalkAssert2(Walker *NotUsed, Select *NotUsed2){
6614 UNUSED_PARAMETER2(NotUsed, NotUsed2);
6615 assert( 0 );
6616}
6617#endif
6618
6619/*
6620** The first argument is a Walker object created by sqlite3SelectExpand().
6621** This function uses the walker to expand the SELECT statement passed
6622** as the second argument. If necessary, it also converts any compound
6623** SELECT statements that have COLLATE clauses on ORDER BY expressions
6624** to sub-queries. Return the return value of sqlite3WalkSelect().
6625*/
6626static int selectExpanderWalk(Walker *pWalker, Select *pSelect){
6627 assert( pWalker->xExprCallback==sqlite3ExprWalkNoop );
6628 assert( pWalker->pParse!=0 );
6629 if( OK_IF_ALWAYS_TRUE(pWalker->pParse->hasCompound) ){
6630 pWalker->xSelectCallback = convertCompoundSelectToSubquery;
6631 pWalker->xSelectCallback2 = 0;
6632 sqlite3WalkSelect(pWalker, pSelect);
6633 }
6634 pWalker->xSelectCallback = selectExpander;
6635 pWalker->xSelectCallback2 = sqlite3SelectPopWith;
6636 return sqlite3WalkSelect(pWalker, pSelect);
6637}
6638
6639/*
6640** This routine "expands" a SELECT statement and all of its subqueries.
6641** For additional information on what it means to "expand" a SELECT
6642** statement, see the comment on the selectExpand worker callback above.
6643**
6644** Expanding a SELECT statement is the first step in processing a
6645** SELECT statement. The SELECT statement must be expanded before
6646** name resolution is performed.
6647**
6648** If anything goes wrong, an error message is written into pParse.
6649** The calling function can detect the problem by looking at pParse->nErr
6650** and/or pParse->db->mallocFailed.
6651*/
6652static void sqlite3SelectExpand(Parse *pParse, Select *pSelect){
6653 Walker w;
6654 w.xExprCallback = sqlite3ExprWalkNoop;
6655 w.pParse = pParse;
6656 w.eCode = 0;
6657 selectExpanderWalk(&w, pSelect);
6658}
6659
6660
6661#ifndef SQLITE_OMIT_SUBQUERY
6662/*
6663** This is a Walker.xSelectCallback callback for the sqlite3SelectTypeInfo()
6664** interface.
6665**
6666** For each FROM-clause subquery, add Column.zType, Column.zColl, and
6667** Column.affinity information to the Table structure that represents
6668** the result set of that subquery.
6669**
6670** The Table structure that represents the result set was constructed
6671** by selectExpander() but the type and collation and affinity information
6672** was omitted at that point because identifiers had not yet been resolved.
6673** This routine is called after identifier resolution.
6674*/
6675static void selectAddSubqueryTypeInfo(Walker *pWalker, Select *p){
6676 Parse *pParse;
6677 int i;
6678 SrcList *pTabList;
6679 SrcItem *pFrom;
6680
6681 if( p->selFlags & SF_HasTypeInfo ) return;
6682 p->selFlags |= SF_HasTypeInfo;
6683 pParse = pWalker->pParse;
6684 assert( (p->selFlags & SF_Resolved) );
6685 pTabList = p->pSrc;
6686 for(i=0, pFrom=pTabList->a; i<pTabList->nSrc; i++, pFrom++){
6687 Table *pTab = pFrom->pSTab;
6688 assert( pTab!=0 );
6689 if( (pTab->tabFlags & TF_Ephemeral)!=0 && pFrom->fg.isSubquery ){
6690 /* A sub-query in the FROM clause of a SELECT */
6691 Select *pSel = pFrom->u4.pSubq->pSelect;
6692 sqlite3SubqueryColumnTypes(pParse, pTab, pSel, SQLITE_AFF_NONE);
6693 }
6694 }
6695}
6696#endif
6697
6698
6699/*
6700** This routine adds datatype and collating sequence information to
6701** the Table structures of all FROM-clause subqueries in a
6702** SELECT statement.
6703**
6704** Use this routine after name resolution.
6705*/
6706static void sqlite3SelectAddTypeInfo(Parse *pParse, Select *pSelect){
6707#ifndef SQLITE_OMIT_SUBQUERY
6708 Walker w;
6709 w.xSelectCallback = sqlite3SelectWalkNoop;
6710 w.xSelectCallback2 = selectAddSubqueryTypeInfo;
6711 w.xExprCallback = sqlite3ExprWalkNoop;
6712 w.pParse = pParse;
6713 sqlite3WalkSelect(&w, pSelect);
6714#endif
6715}
6716
6717
6718/*
6719** This routine sets up a SELECT statement for processing. The
6720** following is accomplished:
6721**
6722** * VDBE Cursor numbers are assigned to all FROM-clause terms.
6723** * Ephemeral Table objects are created for all FROM-clause subqueries.
6724** * ON and USING clauses are shifted into WHERE statements
6725** * Wildcards "*" and "TABLE.*" in result sets are expanded.
6726** * Identifiers in expression are matched to tables.
6727**
6728** This routine acts recursively on all subqueries within the SELECT.
6729*/
6730void sqlite3SelectPrep(
6731 Parse *pParse, /* The parser context */
6732 Select *p, /* The SELECT statement being coded. */
6733 NameContext *pOuterNC /* Name context for container */
6734){
6735 assert( p!=0 || pParse->db->mallocFailed );
6736 assert( pParse->db->pParse==pParse );
6737 if( pParse->db->mallocFailed ) return;
6738 if( p->selFlags & SF_HasTypeInfo ) return;
6739 sqlite3SelectExpand(pParse, p);
6740 if( pParse->nErr ) return;
6741 sqlite3ResolveSelectNames(pParse, p, pOuterNC);
6742 if( pParse->nErr ) return;
6743 sqlite3SelectAddTypeInfo(pParse, p);
6744}
6745
6746#if TREETRACE_ENABLED
6747/*
6748** Display all information about an AggInfo object
6749*/
6750static void printAggInfo(AggInfo *pAggInfo){
6751 int ii;
6752 sqlite3DebugPrintf("AggInfo %d/%p:\n",
6753 pAggInfo->selId, pAggInfo);
6754 for(ii=0; ii<pAggInfo->nColumn; ii++){
6755 struct AggInfo_col *pCol = &pAggInfo->aCol[ii];
6756 sqlite3DebugPrintf(
6757 "agg-column[%d] pTab=%s iTable=%d iColumn=%d iMem=%d"
6758 " iSorterColumn=%d %s\n",
6759 ii, pCol->pTab ? pCol->pTab->zName : "NULL",
6760 pCol->iTable, pCol->iColumn, pAggInfo->iFirstReg+ii,
6761 pCol->iSorterColumn,
6762 ii>=pAggInfo->nAccumulator ? "" : " Accumulator");
6763 sqlite3TreeViewExpr(0, pAggInfo->aCol[ii].pCExpr, 0);
6764 }
6765 for(ii=0; ii<pAggInfo->nFunc; ii++){
6766 sqlite3DebugPrintf("agg-func[%d]: iMem=%d\n",
6767 ii, pAggInfo->iFirstReg+pAggInfo->nColumn+ii);
6768 sqlite3TreeViewExpr(0, pAggInfo->aFunc[ii].pFExpr, 0);
6769 }
6770}
6771#endif /* TREETRACE_ENABLED */
6772
6773/*
6774** Analyze the arguments to aggregate functions. Create new pAggInfo->aCol[]
6775** entries for columns that are arguments to aggregate functions but which
6776** are not otherwise used.
6777**
6778** The aCol[] entries in AggInfo prior to nAccumulator are columns that
6779** are referenced outside of aggregate functions. These might be columns
6780** that are part of the GROUP by clause, for example. Other database engines
6781** would throw an error if there is a column reference that is not in the
6782** GROUP BY clause and that is not part of an aggregate function argument.
6783** But SQLite allows this.
6784**
6785** The aCol[] entries beginning with the aCol[nAccumulator] and following
6786** are column references that are used exclusively as arguments to
6787** aggregate functions. This routine is responsible for computing
6788** (or recomputing) those aCol[] entries.
6789*/
6790static void analyzeAggFuncArgs(
6791 AggInfo *pAggInfo,
6792 NameContext *pNC
6793){
6794 int i;
6795 assert( pAggInfo!=0 );
6796 assert( pAggInfo->iFirstReg==0 );
6797 pNC->ncFlags |= NC_InAggFunc;
6798 for(i=0; i<pAggInfo->nFunc; i++){
6799 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
6800 assert( pExpr->op==TK_FUNCTION || pExpr->op==TK_AGG_FUNCTION );
6801 assert( ExprUseXList(pExpr) );
6802 sqlite3ExprAnalyzeAggList(pNC, pExpr->x.pList);
6803 if( pExpr->pLeft ){
6804 assert( pExpr->pLeft->op==TK_ORDER );
6805 assert( ExprUseXList(pExpr->pLeft) );
6806 sqlite3ExprAnalyzeAggList(pNC, pExpr->pLeft->x.pList);
6807 }
6808#ifndef SQLITE_OMIT_WINDOWFUNC
6809 assert( !IsWindowFunc(pExpr) );
6810 if( ExprHasProperty(pExpr, EP_WinFunc) ){
6811 sqlite3ExprAnalyzeAggregates(pNC, pExpr->y.pWin->pFilter);
6812 }
6813#endif
6814 }
6815 pNC->ncFlags &= ~NC_InAggFunc;
6816}
6817
6818/*
6819** An index on expressions is being used in the inner loop of an
6820** aggregate query with a GROUP BY clause. This routine attempts
6821** to adjust the AggInfo object to take advantage of index and to
6822** perhaps use the index as a covering index.
6823**
6824*/
6825static void optimizeAggregateUseOfIndexedExpr(
6826 Parse *pParse, /* Parsing context */
6827 Select *pSelect, /* The SELECT statement being processed */
6828 AggInfo *pAggInfo, /* The aggregate info */
6829 NameContext *pNC /* Name context used to resolve agg-func args */
6830){
6831 assert( pAggInfo->iFirstReg==0 );
6832 assert( pSelect!=0 );
6833 assert( pSelect->pGroupBy!=0 );
6834 pAggInfo->nColumn = pAggInfo->nAccumulator;
6835 if( ALWAYS(pAggInfo->nSortingColumn>0) ){
6836 int mx = pSelect->pGroupBy->nExpr - 1;
6837 int j, k;
6838 for(j=0; j<pAggInfo->nColumn; j++){
6839 k = pAggInfo->aCol[j].iSorterColumn;
6840 if( k>mx ) mx = k;
6841 }
6842 pAggInfo->nSortingColumn = mx+1;
6843 }
6844 analyzeAggFuncArgs(pAggInfo, pNC);
6845#if TREETRACE_ENABLED
6846 if( sqlite3TreeTrace & 0x20 ){
6847 IndexedExpr *pIEpr;
6848 TREETRACE(0x20, pParse, pSelect,
6849 ("AggInfo (possibly) adjusted for Indexed Exprs\n"));
6850 sqlite3TreeViewSelect(0, pSelect, 0);
6851 for(pIEpr=pParse->pIdxEpr; pIEpr; pIEpr=pIEpr->pIENext){
6852 printf("data-cursor=%d index={%d,%d}\n",
6853 pIEpr->iDataCur, pIEpr->iIdxCur, pIEpr->iIdxCol);
6854 sqlite3TreeViewExpr(0, pIEpr->pExpr, 0);
6855 }
6856 printAggInfo(pAggInfo);
6857 }
6858#else
6859 UNUSED_PARAMETER(pSelect);
6860 UNUSED_PARAMETER(pParse);
6861#endif
6862}
6863
6864/*
6865** Walker callback for aggregateConvertIndexedExprRefToColumn().
6866*/
6867static int aggregateIdxEprRefToColCallback(Walker *pWalker, Expr *pExpr){
6868 AggInfo *pAggInfo;
6869 struct AggInfo_col *pCol;
6870 UNUSED_PARAMETER(pWalker);
6871 if( pExpr->pAggInfo==0 ) return WRC_Continue;
6872 if( pExpr->op==TK_AGG_COLUMN ) return WRC_Continue;
6873 if( pExpr->op==TK_AGG_FUNCTION ) return WRC_Continue;
6874 if( pExpr->op==TK_IF_NULL_ROW ) return WRC_Continue;
6875 pAggInfo = pExpr->pAggInfo;
6876 if( NEVER(pExpr->iAgg>=pAggInfo->nColumn) ) return WRC_Continue;
6877 assert( pExpr->iAgg>=0 );
6878 pCol = &pAggInfo->aCol[pExpr->iAgg];
6879 pExpr->op = TK_AGG_COLUMN;
6880 pExpr->iTable = pCol->iTable;
6881 pExpr->iColumn = pCol->iColumn;
6882 ExprClearProperty(pExpr, EP_Skip|EP_Collate|EP_Unlikely);
6883 return WRC_Prune;
6884}
6885
6886/*
6887** Convert every pAggInfo->aFunc[].pExpr such that any node within
6888** those expressions that has pAppInfo set is changed into a TK_AGG_COLUMN
6889** opcode.
6890*/
6891static void aggregateConvertIndexedExprRefToColumn(AggInfo *pAggInfo){
6892 int i;
6893 Walker w;
6894 memset(&w, 0, sizeof(w));
6895 w.xExprCallback = aggregateIdxEprRefToColCallback;
6896 for(i=0; i<pAggInfo->nFunc; i++){
6897 sqlite3WalkExpr(&w, pAggInfo->aFunc[i].pFExpr);
6898 }
6899}
6900
6901
6902/*
6903** Allocate a block of registers so that there is one register for each
6904** pAggInfo->aCol[] and pAggInfo->aFunc[] entry in pAggInfo. The first
6905** register in this block is stored in pAggInfo->iFirstReg.
6906**
6907** This routine may only be called once for each AggInfo object. Prior
6908** to calling this routine:
6909**
6910** * The aCol[] and aFunc[] arrays may be modified
6911** * The AggInfoColumnReg() and AggInfoFuncReg() macros may not be used
6912**
6913** After calling this routine:
6914**
6915** * The aCol[] and aFunc[] arrays are fixed
6916** * The AggInfoColumnReg() and AggInfoFuncReg() macros may be used
6917**
6918*/
6919static void assignAggregateRegisters(Parse *pParse, AggInfo *pAggInfo){
6920 assert( pAggInfo!=0 );
6921 assert( pAggInfo->iFirstReg==0 );
6922 pAggInfo->iFirstReg = pParse->nMem + 1;
6923 pParse->nMem += pAggInfo->nColumn + pAggInfo->nFunc;
6924}
6925
6926/*
6927** Reset the aggregate accumulator.
6928**
6929** The aggregate accumulator is a set of memory cells that hold
6930** intermediate results while calculating an aggregate. This
6931** routine generates code that stores NULLs in all of those memory
6932** cells.
6933*/
6934static void resetAccumulator(Parse *pParse, AggInfo *pAggInfo){
6935 Vdbe *v = pParse->pVdbe;
6936 int i;
6937 struct AggInfo_func *pFunc;
6938 int nReg = pAggInfo->nFunc + pAggInfo->nColumn;
6939 assert( pAggInfo->iFirstReg>0 );
6940 assert( pParse->db->pParse==pParse );
6941 assert( pParse->db->mallocFailed==0 || pParse->nErr!=0 );
6942 if( nReg==0 ) return;
6943 if( pParse->nErr ) return;
6944 if( pAggInfo->nFunc ){
6945 sqlite3MayAbort(pParse);
6946 }
6947 sqlite3VdbeAddOp3(v, OP_Null, 0, pAggInfo->iFirstReg,
6948 pAggInfo->iFirstReg+nReg-1);
6949 for(pFunc=pAggInfo->aFunc, i=0; i<pAggInfo->nFunc; i++, pFunc++){
6950 if( pFunc->iDistinct>=0 ){
6951 Expr *pE = pFunc->pFExpr;
6952 assert( ExprUseXList(pE) );
6953 if( pE->x.pList==0 || pE->x.pList->nExpr!=1 ){
6954 sqlite3ErrorMsg(pParse, "DISTINCT aggregates must have exactly one "
6955 "argument");
6956 pFunc->iDistinct = -1;
6957 }else{
6958 KeyInfo *pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pE->x.pList,0,0);
6959 pFunc->iDistAddr = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6960 pFunc->iDistinct, 0, 0, (char*)pKeyInfo, P4_KEYINFO);
6961 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(DISTINCT)",
6962 pFunc->pFunc->zName));
6963 }
6964 }
6965 if( pFunc->iOBTab>=0 ){
6966 ExprList *pOBList;
6967 KeyInfo *pKeyInfo;
6968 int nExtra = 0;
6969 assert( pFunc->pFExpr->pLeft!=0 );
6970 assert( pFunc->pFExpr->pLeft->op==TK_ORDER );
6971 assert( ExprUseXList(pFunc->pFExpr->pLeft) );
6972 assert( pFunc->pFunc!=0 );
6973 pOBList = pFunc->pFExpr->pLeft->x.pList;
6974 if( !pFunc->bOBUnique ){
6975 nExtra++; /* One extra column for the OP_Sequence */
6976 }
6977 if( pFunc->bOBPayload ){
6978 /* extra columns for the function arguments */
6979 assert( ExprUseXList(pFunc->pFExpr) );
6980 assert( pFunc->pFExpr->x.pList!=0 );
6981 nExtra += pFunc->pFExpr->x.pList->nExpr;
6982 }
6983 if( pFunc->bUseSubtype ){
6984 nExtra += pFunc->pFExpr->x.pList->nExpr;
6985 }
6986 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pOBList, 0, nExtra);
6987 if( !pFunc->bOBUnique && pParse->nErr==0 ){
6988 pKeyInfo->nKeyField++;
6989 }
6990 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
6991 pFunc->iOBTab, pOBList->nExpr+nExtra, 0,
6992 (char*)pKeyInfo, P4_KEYINFO);
6993 ExplainQueryPlan((pParse, 0, "USE TEMP B-TREE FOR %s(ORDER BY)",
6994 pFunc->pFunc->zName));
6995 }
6996 }
6997}
6998
6999/*
7000** Invoke the OP_AggFinalize opcode for every aggregate function
7001** in the AggInfo structure.
7002*/
7003static void finalizeAggFunctions(Parse *pParse, AggInfo *pAggInfo){
7004 Vdbe *v = pParse->pVdbe;
7005 int i;
7006 struct AggInfo_func *pF;
7007 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
7008 ExprList *pList;
7009 assert( ExprUseXList(pF->pFExpr) );
7010 if( pParse->nErr ) return;
7011 pList = pF->pFExpr->x.pList;
7012 if( pF->iOBTab>=0 ){
7013 /* For an ORDER BY aggregate, calls to OP_AggStep were deferred. Inputs
7014 ** were stored in emphermal table pF->iOBTab. Here, we extract those
7015 ** inputs (in ORDER BY order) and make all calls to OP_AggStep
7016 ** before doing the OP_AggFinal call. */
7017 int iTop; /* Start of loop for extracting columns */
7018 int nArg; /* Number of columns to extract */
7019 int nKey; /* Key columns to be skipped */
7020 int regAgg; /* Extract into this array */
7021 int j; /* Loop counter */
7022
7023 assert( pF->pFunc!=0 );
7024 nArg = pList->nExpr;
7025 regAgg = sqlite3GetTempRange(pParse, nArg);
7026
7027 if( pF->bOBPayload==0 ){
7028 nKey = 0;
7029 }else{
7030 assert( pF->pFExpr->pLeft!=0 );
7031 assert( ExprUseXList(pF->pFExpr->pLeft) );
7032 assert( pF->pFExpr->pLeft->x.pList!=0 );
7033 nKey = pF->pFExpr->pLeft->x.pList->nExpr;
7034 if( ALWAYS(!pF->bOBUnique) ) nKey++;
7035 }
7036 iTop = sqlite3VdbeAddOp1(v, OP_Rewind, pF->iOBTab); VdbeCoverage(v);
7037 for(j=nArg-1; j>=0; j--){
7038 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, nKey+j, regAgg+j);
7039 }
7040 if( pF->bUseSubtype ){
7041 int regSubtype = sqlite3GetTempReg(pParse);
7042 int iBaseCol = nKey + nArg + (pF->bOBPayload==0 && pF->bOBUnique==0);
7043 for(j=nArg-1; j>=0; j--){
7044 sqlite3VdbeAddOp3(v, OP_Column, pF->iOBTab, iBaseCol+j, regSubtype);
7045 sqlite3VdbeAddOp2(v, OP_SetSubtype, regSubtype, regAgg+j);
7046 }
7047 sqlite3ReleaseTempReg(pParse, regSubtype);
7048 }
7049 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
7050 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
7051 sqlite3VdbeChangeP5(v, (u16)nArg);
7052 sqlite3VdbeAddOp2(v, OP_Next, pF->iOBTab, iTop+1); VdbeCoverage(v);
7053 sqlite3VdbeJumpHere(v, iTop);
7054 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
7055 }
7056 sqlite3VdbeAddOp2(v, OP_AggFinal, AggInfoFuncReg(pAggInfo,i),
7057 pList ? pList->nExpr : 0);
7058 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
7059 }
7060}
7061
7062/*
7063** Generate code that will update the accumulator memory cells for an
7064** aggregate based on the current cursor position.
7065**
7066** If regAcc is non-zero and there are no min() or max() aggregates
7067** in pAggInfo, then only populate the pAggInfo->nAccumulator accumulator
7068** registers if register regAcc contains 0. The caller will take care
7069** of setting and clearing regAcc.
7070**
7071** For an ORDER BY aggregate, the actual accumulator memory cell update
7072** is deferred until after all input rows have been received, so that they
7073** can be run in the requested order. In that case, instead of invoking
7074** OP_AggStep to update the accumulator, just add the arguments that would
7075** have been passed into OP_AggStep into the sorting ephemeral table
7076** (along with the appropriate sort key).
7077*/
7078static void updateAccumulator(
7079 Parse *pParse,
7080 int regAcc,
7081 AggInfo *pAggInfo,
7082 int eDistinctType
7083){
7084 Vdbe *v = pParse->pVdbe;
7085 int i;
7086 int regHit = 0;
7087 int addrHitTest = 0;
7088 struct AggInfo_func *pF;
7089 struct AggInfo_col *pC;
7090
7091 assert( pAggInfo->iFirstReg>0 );
7092 if( pParse->nErr ) return;
7093 pAggInfo->directMode = 1;
7094 for(i=0, pF=pAggInfo->aFunc; i<pAggInfo->nFunc; i++, pF++){
7095 int nArg;
7096 int addrNext = 0;
7097 int regAgg;
7098 int regAggSz = 0;
7099 int regDistinct = 0;
7100 ExprList *pList;
7101 assert( ExprUseXList(pF->pFExpr) );
7102 assert( !IsWindowFunc(pF->pFExpr) );
7103 assert( pF->pFunc!=0 );
7104 pList = pF->pFExpr->x.pList;
7105 if( ExprHasProperty(pF->pFExpr, EP_WinFunc) ){
7106 Expr *pFilter = pF->pFExpr->y.pWin->pFilter;
7107 if( pAggInfo->nAccumulator
7108 && (pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL)
7109 && regAcc
7110 ){
7111 /* If regAcc==0, there there exists some min() or max() function
7112 ** without a FILTER clause that will ensure the magnet registers
7113 ** are populated. */
7114 if( regHit==0 ) regHit = ++pParse->nMem;
7115 /* If this is the first row of the group (regAcc contains 0), clear the
7116 ** "magnet" register regHit so that the accumulator registers
7117 ** are populated if the FILTER clause jumps over the the
7118 ** invocation of min() or max() altogether. Or, if this is not
7119 ** the first row (regAcc contains 1), set the magnet register so that
7120 ** the accumulators are not populated unless the min()/max() is invoked
7121 ** and indicates that they should be. */
7122 sqlite3VdbeAddOp2(v, OP_Copy, regAcc, regHit);
7123 }
7124 addrNext = sqlite3VdbeMakeLabel(pParse);
7125 sqlite3ExprIfFalse(pParse, pFilter, addrNext, SQLITE_JUMPIFNULL);
7126 }
7127 if( pF->iOBTab>=0 ){
7128 /* Instead of invoking AggStep, we must push the arguments that would
7129 ** have been passed to AggStep onto the sorting table. */
7130 int jj; /* Registered used so far in building the record */
7131 ExprList *pOBList; /* The ORDER BY clause */
7132 assert( pList!=0 );
7133 nArg = pList->nExpr;
7134 assert( nArg>0 );
7135 assert( pF->pFExpr->pLeft!=0 );
7136 assert( pF->pFExpr->pLeft->op==TK_ORDER );
7137 assert( ExprUseXList(pF->pFExpr->pLeft) );
7138 pOBList = pF->pFExpr->pLeft->x.pList;
7139 assert( pOBList!=0 );
7140 assert( pOBList->nExpr>0 );
7141 regAggSz = pOBList->nExpr;
7142 if( !pF->bOBUnique ){
7143 regAggSz++; /* One register for OP_Sequence */
7144 }
7145 if( pF->bOBPayload ){
7146 regAggSz += nArg;
7147 }
7148 if( pF->bUseSubtype ){
7149 regAggSz += nArg;
7150 }
7151 regAggSz++; /* One extra register to hold result of MakeRecord */
7152 regAgg = sqlite3GetTempRange(pParse, regAggSz);
7153 regDistinct = regAgg;
7154 sqlite3ExprCodeExprList(pParse, pOBList, regAgg, 0, SQLITE_ECEL_DUP);
7155 jj = pOBList->nExpr;
7156 if( !pF->bOBUnique ){
7157 sqlite3VdbeAddOp2(v, OP_Sequence, pF->iOBTab, regAgg+jj);
7158 jj++;
7159 }
7160 if( pF->bOBPayload ){
7161 regDistinct = regAgg+jj;
7162 sqlite3ExprCodeExprList(pParse, pList, regDistinct, 0, SQLITE_ECEL_DUP);
7163 jj += nArg;
7164 }
7165 if( pF->bUseSubtype ){
7166 int kk;
7167 int regBase = pF->bOBPayload ? regDistinct : regAgg;
7168 for(kk=0; kk<nArg; kk++, jj++){
7169 sqlite3VdbeAddOp2(v, OP_GetSubtype, regBase+kk, regAgg+jj);
7170 }
7171 }
7172 }else if( pList ){
7173 nArg = pList->nExpr;
7174 regAgg = sqlite3GetTempRange(pParse, nArg);
7175 regDistinct = regAgg;
7176 sqlite3ExprCodeExprList(pParse, pList, regAgg, 0, SQLITE_ECEL_DUP);
7177 }else{
7178 nArg = 0;
7179 regAgg = 0;
7180 }
7181 if( pF->iDistinct>=0 && pList ){
7182 if( addrNext==0 ){
7183 addrNext = sqlite3VdbeMakeLabel(pParse);
7184 }
7185 pF->iDistinct = codeDistinct(pParse, eDistinctType,
7186 pF->iDistinct, addrNext, pList, regDistinct);
7187 }
7188 if( pF->iOBTab>=0 ){
7189 /* Insert a new record into the ORDER BY table */
7190 sqlite3VdbeAddOp3(v, OP_MakeRecord, regAgg, regAggSz-1,
7191 regAgg+regAggSz-1);
7192 sqlite3VdbeAddOp4Int(v, OP_IdxInsert, pF->iOBTab, regAgg+regAggSz-1,
7193 regAgg, regAggSz-1);
7194 sqlite3ReleaseTempRange(pParse, regAgg, regAggSz);
7195 }else{
7196 /* Invoke the AggStep function */
7197 if( pF->pFunc->funcFlags & SQLITE_FUNC_NEEDCOLL ){
7198 CollSeq *pColl = 0;
7199 struct ExprList_item *pItem;
7200 int j;
7201 assert( pList!=0 ); /* pList!=0 if pF->pFunc has NEEDCOLL */
7202 for(j=0, pItem=pList->a; !pColl && j<nArg; j++, pItem++){
7203 pColl = sqlite3ExprCollSeq(pParse, pItem->pExpr);
7204 }
7205 if( !pColl ){
7206 pColl = pParse->db->pDfltColl;
7207 }
7208 if( regHit==0 && pAggInfo->nAccumulator ) regHit = ++pParse->nMem;
7209 sqlite3VdbeAddOp4(v, OP_CollSeq, regHit, 0, 0,
7210 (char *)pColl, P4_COLLSEQ);
7211 }
7212 sqlite3VdbeAddOp3(v, OP_AggStep, 0, regAgg, AggInfoFuncReg(pAggInfo,i));
7213 sqlite3VdbeAppendP4(v, pF->pFunc, P4_FUNCDEF);
7214 sqlite3VdbeChangeP5(v, (u16)nArg);
7215 sqlite3ReleaseTempRange(pParse, regAgg, nArg);
7216 }
7217 if( addrNext ){
7218 sqlite3VdbeResolveLabel(v, addrNext);
7219 }
7220 if( pParse->nErr ) return;
7221 }
7222 if( regHit==0 && pAggInfo->nAccumulator ){
7223 regHit = regAcc;
7224 }
7225 if( regHit ){
7226 addrHitTest = sqlite3VdbeAddOp1(v, OP_If, regHit); VdbeCoverage(v);
7227 }
7228 for(i=0, pC=pAggInfo->aCol; i<pAggInfo->nAccumulator; i++, pC++){
7229 sqlite3ExprCode(pParse, pC->pCExpr, AggInfoColumnReg(pAggInfo,i));
7230 if( pParse->nErr ) return;
7231 }
7232
7233 pAggInfo->directMode = 0;
7234 if( addrHitTest ){
7235 sqlite3VdbeJumpHereOrPopInst(v, addrHitTest);
7236 }
7237}
7238
7239/*
7240** Add a single OP_Explain instruction to the VDBE to explain a simple
7241** count(*) query ("SELECT count(*) FROM pTab").
7242*/
7243#ifndef SQLITE_OMIT_EXPLAIN
7244static void explainSimpleCount(
7245 Parse *pParse, /* Parse context */
7246 Table *pTab, /* Table being queried */
7247 Index *pIdx /* Index used to optimize scan, or NULL */
7248){
7249 if( pParse->explain==2 ){
7250 int bCover = (pIdx!=0 && (HasRowid(pTab) || !IsPrimaryKeyIndex(pIdx)));
7251 sqlite3VdbeExplain(pParse, 0, "SCAN %s%s%s",
7252 pTab->zName,
7253 bCover ? " USING COVERING INDEX " : "",
7254 bCover ? pIdx->zName : ""
7255 );
7256 }
7257}
7258#else
7259# define explainSimpleCount(a,b,c)
7260#endif
7261
7262/*
7263** sqlite3WalkExpr() callback used by havingToWhere().
7264**
7265** If the node passed to the callback is a TK_AND node, return
7266** WRC_Continue to tell sqlite3WalkExpr() to iterate through child nodes.
7267**
7268** Otherwise, return WRC_Prune. In this case, also check if the
7269** sub-expression matches the criteria for being moved to the WHERE
7270** clause. If so, add it to the WHERE clause and replace the sub-expression
7271** within the HAVING expression with a constant "1".
7272*/
7273static int havingToWhereExprCb(Walker *pWalker, Expr *pExpr){
7274 if( pExpr->op!=TK_AND ){
7275 Select *pS = pWalker->u.pSelect;
7276 /* This routine is called before the HAVING clause of the current
7277 ** SELECT is analyzed for aggregates. So if pExpr->pAggInfo is set
7278 ** here, it indicates that the expression is a correlated reference to a
7279 ** column from an outer aggregate query, or an aggregate function that
7280 ** belongs to an outer query. Do not move the expression to the WHERE
7281 ** clause in this obscure case, as doing so may corrupt the outer Select
7282 ** statements AggInfo structure. */
7283 if( sqlite3ExprIsConstantOrGroupBy(pWalker->pParse, pExpr, pS->pGroupBy)
7284 && ExprAlwaysFalse(pExpr)==0
7285 && pExpr->pAggInfo==0
7286 ){
7287 sqlite3 *db = pWalker->pParse->db;
7288 Expr *pNew = sqlite3ExprInt32(db, 1);
7289 if( pNew ){
7290 Expr *pWhere = pS->pWhere;
7291 SWAP(Expr, *pNew, *pExpr);
7292 pNew = sqlite3ExprAnd(pWalker->pParse, pWhere, pNew);
7293 pS->pWhere = pNew;
7294 pWalker->eCode = 1;
7295 }
7296 }
7297 return WRC_Prune;
7298 }
7299 return WRC_Continue;
7300}
7301
7302/*
7303** Transfer eligible terms from the HAVING clause of a query, which is
7304** processed after grouping, to the WHERE clause, which is processed before
7305** grouping. For example, the query:
7306**
7307** SELECT * FROM <tables> WHERE a=? GROUP BY b HAVING b=? AND c=?
7308**
7309** can be rewritten as:
7310**
7311** SELECT * FROM <tables> WHERE a=? AND b=? GROUP BY b HAVING c=?
7312**
7313** A term of the HAVING expression is eligible for transfer if it consists
7314** entirely of constants and expressions that are also GROUP BY terms that
7315** use the "BINARY" collation sequence.
7316*/
7317static void havingToWhere(Parse *pParse, Select *p){
7318 Walker sWalker;
7319 memset(&sWalker, 0, sizeof(sWalker));
7320 sWalker.pParse = pParse;
7321 sWalker.xExprCallback = havingToWhereExprCb;
7322 sWalker.u.pSelect = p;
7323 sqlite3WalkExpr(&sWalker, p->pHaving);
7324#if TREETRACE_ENABLED
7325 if( sWalker.eCode && (sqlite3TreeTrace & 0x100)!=0 ){
7326 TREETRACE(0x100,pParse,p,("Move HAVING terms into WHERE:\n"));
7327 sqlite3TreeViewSelect(0, p, 0);
7328 }
7329#endif
7330}
7331
7332/*
7333** Check to see if the pThis entry of pTabList is a self-join of another view.
7334** Search FROM-clause entries in the range of iFirst..iEnd, including iFirst
7335** but stopping before iEnd.
7336**
7337** If pThis is a self-join, then return the SrcItem for the first other
7338** instance of that view found. If pThis is not a self-join then return 0.
7339*/
7340static SrcItem *isSelfJoinView(
7341 SrcList *pTabList, /* Search for self-joins in this FROM clause */
7342 SrcItem *pThis, /* Search for prior reference to this subquery */
7343 int iFirst, int iEnd /* Range of FROM-clause entries to search. */
7344){
7345 SrcItem *pItem;
7346 Select *pSel;
7347 assert( pThis->fg.isSubquery );
7348 pSel = pThis->u4.pSubq->pSelect;
7349 assert( pSel!=0 );
7350 if( pSel->selFlags & SF_PushDown ) return 0;
7351 while( iFirst<iEnd ){
7352 Select *pS1;
7353 pItem = &pTabList->a[iFirst++];
7354 if( !pItem->fg.isSubquery ) continue;
7355 if( pItem->fg.viaCoroutine ) continue;
7356 if( pItem->zName==0 ) continue;
7357 assert( pItem->pSTab!=0 );
7358 assert( pThis->pSTab!=0 );
7359 if( pItem->pSTab->pSchema!=pThis->pSTab->pSchema ) continue;
7360 if( sqlite3_stricmp(pItem->zName, pThis->zName)!=0 ) continue;
7361 pS1 = pItem->u4.pSubq->pSelect;
7362 if( pItem->pSTab->pSchema==0 && pSel->selId!=pS1->selId ){
7363 /* The query flattener left two different CTE tables with identical
7364 ** names in the same FROM clause. */
7365 continue;
7366 }
7367 if( pS1->selFlags & SF_PushDown ){
7368 /* The view was modified by some other optimization such as
7369 ** pushDownWhereTerms() */
7370 continue;
7371 }
7372 return pItem;
7373 }
7374 return 0;
7375}
7376
7377/*
7378** Deallocate a single AggInfo object
7379*/
7380static void agginfoFree(sqlite3 *db, void *pArg){
7381 AggInfo *p = (AggInfo*)pArg;
7382 sqlite3DbFree(db, p->aCol);
7383 sqlite3DbFree(db, p->aFunc);
7384 sqlite3DbFreeNN(db, p);
7385}
7386
7387/*
7388** Attempt to transform a query of the form
7389**
7390** SELECT count(*) FROM (SELECT x FROM t1 UNION ALL SELECT y FROM t2)
7391**
7392** Into this:
7393**
7394** SELECT (SELECT count(*) FROM t1)+(SELECT count(*) FROM t2)
7395**
7396** The transformation only works if all of the following are true:
7397**
7398** * The subquery is a UNION ALL of two or more terms
7399** * The subquery does not have a LIMIT clause
7400** * There is no WHERE or GROUP BY or HAVING clauses on the subqueries
7401** * The outer query is a simple count(*) with no WHERE clause or other
7402** extraneous syntax.
7403** * None of the subqueries are DISTINCT (forumpost/a860f5fb2e 2025-03-10)
7404**
7405** Return TRUE if the optimization is undertaken.
7406*/
7407static int countOfViewOptimization(Parse *pParse, Select *p){
7408 Select *pSub, *pPrior;
7409 Expr *pExpr;
7410 Expr *pCount;
7411 sqlite3 *db;
7412 SrcItem *pFrom;
7413 if( (p->selFlags & SF_Aggregate)==0 ) return 0; /* This is an aggregate */
7414 if( p->pEList->nExpr!=1 ) return 0; /* Single result column */
7415 if( p->pWhere ) return 0;
7416 if( p->pHaving ) return 0;
7417 if( p->pGroupBy ) return 0;
7418 if( p->pOrderBy ) return 0;
7419 pExpr = p->pEList->a[0].pExpr;
7420 if( pExpr->op!=TK_AGG_FUNCTION ) return 0; /* Result is an aggregate */
7421 assert( ExprUseUToken(pExpr) );
7422 if( sqlite3_stricmp(pExpr->u.zToken,"count") ) return 0; /* Is count() */
7423 assert( ExprUseXList(pExpr) );
7424 if( pExpr->x.pList!=0 ) return 0; /* Must be count(*) */
7425 if( p->pSrc->nSrc!=1 ) return 0; /* One table in FROM */
7426 if( ExprHasProperty(pExpr, EP_WinFunc) ) return 0;/* Not a window function */
7427 pFrom = p->pSrc->a;
7428 if( pFrom->fg.isSubquery==0 ) return 0; /* FROM is a subquery */
7429 if( (p->selFlags & SF_Correlated)!=0 ) return 0; /* Not a correlated subq */
7430 pSub = pFrom->u4.pSubq->pSelect;
7431 if( pSub->pPrior==0 ) return 0; /* Must be a compound */
7432 if( pSub->selFlags & SF_CopyCte ) return 0; /* Not a CTE */
7433 do{
7434 if( pSub->op!=TK_ALL && pSub->pPrior ) return 0; /* Must be UNION ALL */
7435 if( pSub->pWhere ) return 0; /* No WHERE clause */
7436 if( pSub->pLimit ) return 0; /* No LIMIT clause */
7437 if( pSub->selFlags & (SF_Aggregate|SF_Distinct) ){
7438 testcase( pSub->selFlags & SF_Aggregate );
7439 testcase( pSub->selFlags & SF_Distinct );
7440 return 0; /* Not an aggregate nor DISTINCT */
7441 }
7442 assert( pSub->pHaving==0 ); /* Due to the previous */
7443 pSub = pSub->pPrior; /* Repeat over compound */
7444 }while( pSub );
7445
7446 /* If we reach this point then it is OK to perform the transformation */
7447
7448 db = pParse->db;
7449 pCount = pExpr;
7450 pExpr = 0;
7451 pSub = sqlite3SubqueryDetach(db, pFrom);
7452 sqlite3SrcListDelete(db, p->pSrc);
7453 p->pSrc = sqlite3DbMallocZero(pParse->db, SZ_SRCLIST_1);
7454 while( pSub ){
7455 Expr *pTerm;
7456 pPrior = pSub->pPrior;
7457 pSub->pPrior = 0;
7458 pSub->pNext = 0;
7459 pSub->selFlags |= SF_Aggregate;
7460 pSub->selFlags &= ~(u32)SF_Compound;
7461 pSub->nSelectRow = 0;
7462 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric, pSub->pEList);
7463 pTerm = pPrior ? sqlite3ExprDup(db, pCount, 0) : pCount;
7464 pSub->pEList = sqlite3ExprListAppend(pParse, 0, pTerm);
7465 pTerm = sqlite3PExpr(pParse, TK_SELECT, 0, 0);
7466 sqlite3PExprAddSelect(pParse, pTerm, pSub);
7467 if( pExpr==0 ){
7468 pExpr = pTerm;
7469 }else{
7470 pExpr = sqlite3PExpr(pParse, TK_PLUS, pTerm, pExpr);
7471 }
7472 if( pParse->nErr ){
7473 sqlite3ExprDelete(db, pExpr);
7474 pExpr = 0;
7475 }
7476 pSub = pPrior;
7477 }
7478 p->pEList->a[0].pExpr = pExpr;
7479 p->selFlags &= ~(u32)SF_Aggregate;
7480
7481#if TREETRACE_ENABLED
7482 if( sqlite3TreeTrace & 0x200 ){
7483 TREETRACE(0x200,pParse,p,("After count-of-view optimization:\n"));
7484 sqlite3TreeViewSelect(0, p, 0);
7485 }
7486#endif
7487 return 1;
7488}
7489
7490/*
7491** If any term of pSrc, or any SF_NestedFrom sub-query, is not the same
7492** as pSrcItem but has the same alias as p0, then return true.
7493** Otherwise return false.
7494*/
7495static int sameSrcAlias(SrcItem *p0, SrcList *pSrc){
7496 int i;
7497 for(i=0; i<pSrc->nSrc; i++){
7498 SrcItem *p1 = &pSrc->a[i];
7499 if( p1==p0 ) continue;
7500 if( p0->pSTab==p1->pSTab && 0==sqlite3_stricmp(p0->zAlias, p1->zAlias) ){
7501 return 1;
7502 }
7503 if( p1->fg.isSubquery
7504 && (p1->u4.pSubq->pSelect->selFlags & SF_NestedFrom)!=0
7505 && sameSrcAlias(p0, p1->u4.pSubq->pSelect->pSrc)
7506 ){
7507 return 1;
7508 }
7509 }
7510 return 0;
7511}
7512
7513/*
7514** Return TRUE (non-zero) if the i-th entry in the pTabList SrcList can
7515** be implemented as a co-routine. The i-th entry is guaranteed to be
7516** a subquery.
7517**
7518** The subquery is implemented as a co-routine if all of the following are
7519** true:
7520**
7521** (1) The subquery will likely be implemented in the outer loop of
7522** the query. This will be the case if any one of the following
7523** conditions hold:
7524** (a) The subquery is the only term in the FROM clause
7525** (b) The subquery is the left-most term and a CROSS JOIN or similar
7526** requires it to be the outer loop
7527** (c) All of the following are true:
7528** (i) The subquery is the left-most subquery in the FROM clause
7529** (ii) There is nothing that would prevent the subquery from
7530** being used as the outer loop if the sqlite3WhereBegin()
7531** routine nominates it to that position.
7532** (iii) The query is not a UPDATE ... FROM
7533** (2) The subquery is not a CTE that should be materialized because
7534** (a) the AS MATERIALIZED keyword is used, or
7535** (b) the CTE is used multiple times and does not have the
7536** NOT MATERIALIZED keyword
7537** (3) The subquery is not part of a left operand for a RIGHT JOIN
7538** (4) The SQLITE_Coroutine optimization disable flag is not set
7539** (5) The subquery is not self-joined
7540*/
7541static int fromClauseTermCanBeCoroutine(
7542 Parse *pParse, /* Parsing context */
7543 SrcList *pTabList, /* FROM clause */
7544 int i, /* Which term of the FROM clause holds the subquery */
7545 int selFlags /* Flags on the SELECT statement */
7546){
7547 SrcItem *pItem = &pTabList->a[i];
7548 if( pItem->fg.isCte ){
7549 const CteUse *pCteUse = pItem->u2.pCteUse;
7550 if( pCteUse->eM10d==M10d_Yes ) return 0; /* (2a) */
7551 if( pCteUse->nUse>=2 && pCteUse->eM10d!=M10d_No ) return 0; /* (2b) */
7552 }
7553 if( pTabList->a[0].fg.jointype & JT_LTORJ ) return 0; /* (3) */
7554 if( OptimizationDisabled(pParse->db, SQLITE_Coroutines) ) return 0; /* (4) */
7555 if( isSelfJoinView(pTabList, pItem, i+1, pTabList->nSrc)!=0 ){
7556 return 0; /* (5) */
7557 }
7558 if( i==0 ){
7559 if( pTabList->nSrc==1 ) return 1; /* (1a) */
7560 if( pTabList->a[1].fg.jointype & JT_CROSS ) return 1; /* (1b) */
7561 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7562 return 1;
7563 }
7564 if( selFlags & SF_UpdateFrom ) return 0; /* (1c-iii) */
7565 while( 1 /*exit-by-break*/ ){
7566 if( pItem->fg.jointype & (JT_OUTER|JT_CROSS) ) return 0; /* (1c-ii) */
7567 if( i==0 ) break;
7568 i--;
7569 pItem--;
7570 if( pItem->fg.isSubquery ) return 0; /* (1c-i) */
7571 }
7572 return 1;
7573}
7574
7575/*
7576** Argument pWhere is the WHERE clause belonging to SELECT statement p. This
7577** function attempts to transform expressions of the form:
7578**
7579** EXISTS (SELECT ...)
7580**
7581** into joins. For example, given
7582**
7583** CREATE TABLE sailors(sid INTEGER PRIMARY KEY, name TEXT);
7584** CREATE TABLE reserves(sid INT, day DATE, PRIMARY KEY(sid, day));
7585**
7586** SELECT name FROM sailors AS S WHERE EXISTS (
7587** SELECT * FROM reserves AS R WHERE S.sid = R.sid AND R.day = '2022-10-25'
7588** );
7589**
7590** the SELECT statement may be transformed as follows:
7591**
7592** SELECT name FROM sailors AS S, reserves AS R
7593** WHERE S.sid = R.sid AND R.day = '2022-10-25';
7594**
7595** **Approximately**. Really, we have to ensure that the FROM-clause term
7596** that was formerly inside the EXISTS is only executed once. This is handled
7597** by setting the SrcItem.fg.fromExists flag, which then causes code in
7598** the where.c file to exit the corresponding loop after the first successful
7599** match (if any).
7600*/
7601static SQLITE_NOINLINE void existsToJoin(
7602 Parse *pParse, /* Parsing context */
7603 Select *p, /* The SELECT statement being optimized */
7604 Expr *pWhere /* part of the WHERE clause currently being examined */
7605){
7606 if( pParse->nErr==0
7607 && pWhere!=0
7608 && !ExprHasProperty(pWhere, EP_OuterON|EP_InnerON)
7609 && ALWAYS(p->pSrc!=0)
7610 && p->pSrc->nSrc<BMS
7611 && (p->pLimit==0 || p->pLimit->pRight==0)
7612 ){
7613 if( pWhere->op==TK_AND ){
7614 Expr *pRight = pWhere->pRight;
7615 existsToJoin(pParse, p, pWhere->pLeft);
7616 existsToJoin(pParse, p, pRight);
7617 }
7618 else if( pWhere->op==TK_EXISTS ){
7619 Select *pSub = pWhere->x.pSelect;
7620 Expr *pSubWhere = pSub->pWhere;
7621 if( pSub->pSrc->nSrc==1
7622 && (pSub->selFlags & SF_Aggregate)==0
7623 && !pSub->pSrc->a[0].fg.isSubquery
7624 && pSub->pLimit==0
7625 && pSub->pPrior==0
7626 ){
7627 /* Before combining the sub-select with the parent, renumber the
7628 ** cursor used by the subselect. This is because the EXISTS expression
7629 ** might be a copy of another EXISTS expression from somewhere
7630 ** else in the tree, and in this case it is important that it use
7631 ** a unique cursor number. */
7632 sqlite3 *db = pParse->db;
7633 int *aCsrMap = sqlite3DbMallocZero(db, (pParse->nTab+2)*sizeof(int));
7634 if( aCsrMap==0 ) return;
7635 aCsrMap[0] = (pParse->nTab+1);
7636 renumberCursors(pParse, pSub, -1, aCsrMap);
7637 sqlite3DbFree(db, aCsrMap);
7638
7639 memset(pWhere, 0, sizeof(*pWhere));
7640 pWhere->op = TK_INTEGER;
7641 pWhere->u.iValue = 1;
7642 ExprSetProperty(pWhere, EP_IntValue);
7643 assert( p->pWhere!=0 );
7644 pSub->pSrc->a[0].fg.fromExists = 1;
7645 p->pSrc = sqlite3SrcListAppendList(pParse, p->pSrc, pSub->pSrc);
7646 if( pSubWhere ){
7647 p->pWhere = sqlite3PExpr(pParse, TK_AND, p->pWhere, pSubWhere);
7648 pSub->pWhere = 0;
7649 }
7650 pSub->pSrc = 0;
7651 sqlite3ParserAddCleanup(pParse, sqlite3SelectDeleteGeneric, pSub);
7652 recomputeColumnsUsed(p, &p->pSrc->a[p->pSrc->nSrc-1]);
7653#if TREETRACE_ENABLED
7654 if( sqlite3TreeTrace & 0x100000 ){
7655 TREETRACE(0x100000,pParse,p,
7656 ("After EXISTS-to-JOIN optimization:\n"));
7657 sqlite3TreeViewSelect(0, p, 0);
7658 }
7659#endif
7660 }
7661 }
7662 }
7663}
7664
7665/*
7666** Type used for Walker callbacks by selectCheckOnClauses().
7667*/
7668typedef struct CheckOnCtx CheckOnCtx;
7669struct CheckOnCtx {
7670 SrcList *pSrc; /* SrcList for this context */
7671 int iJoin; /* Cursors must be left of this one, if not negative */
7672 int bFuncArg; /* True for table-function arg */
7673 CheckOnCtx *pParent; /* Parent context */
7674};
7675
7676/*
7677** True if the SrcList passed as the only argument contains at least
7678** one RIGHT or FULL JOIN. False otherwise.
7679*/
7680#define hasRightJoin(pSrc) (((pSrc)->a[0].fg.jointype & JT_LTORJ)!=0)
7681
7682/*
7683** The xExpr callback for the search of invalid ON clause terms.
7684*/
7685static int selectCheckOnClausesExpr(Walker *pWalker, Expr *pExpr){
7686 CheckOnCtx *pCtx = pWalker->u.pCheckOnCtx;
7687
7688 /* Check if pExpr is root or near-root of an ON clause constraint that needs
7689 ** to be checked to ensure that it does not refer to tables in its FROM
7690 ** clause to the right of itself. i.e. it is either:
7691 **
7692 ** + an ON clause on an OUTER join, or
7693 ** + an ON clause on an INNER join within a FROM that features at
7694 ** least one RIGHT or FULL join.
7695 */
7696 if( (ExprHasProperty(pExpr, EP_OuterON))
7697 || (ExprHasProperty(pExpr, EP_InnerON) && hasRightJoin(pCtx->pSrc))
7698 ){
7699 /* If CheckOnCtx.iJoin is already set, then fall through and process
7700 ** this expression node as normal. Or, if CheckOnCtx.iJoin is still 0,
7701 ** set it to the cursor number of the RHS of the join to which this
7702 ** ON expression was attached and then iterate through the entire
7703 ** expression. */
7704 assert( pCtx->iJoin<0 || pCtx->iJoin==pExpr->w.iJoin );
7705 if( pCtx->iJoin<0 ){
7706 pCtx->iJoin = pExpr->w.iJoin;
7707 sqlite3WalkExprNN(pWalker, pExpr);
7708 pCtx->iJoin = -1;
7709 return WRC_Prune;
7710 }
7711 }
7712
7713 if( pExpr->op==TK_COLUMN ){
7714 /* A column expression. Find the SrcList (if any) to which it refers.
7715 ** Then, if CheckOnCtx.iJoin indicates that this expression is part of an
7716 ** ON clause from that SrcList (i.e. if iJoin is non-zero), check that it
7717 ** does not refer to a table to the right of CheckOnCtx.iJoin. */
7718 int iTab = pExpr->iTable;
7719 do {
7720 SrcList *pSrc = pCtx->pSrc;
7721 int nSrc = pSrc->nSrc;
7722 int ii;
7723 for(ii=0; ii<nSrc && pSrc->a[ii].iCursor!=iTab; ii++){}
7724 if( ii<nSrc ){
7725 /* pSrc is the FROM clause that contains iTab */
7726 if( pCtx->iJoin>=0 ){
7727 for(ii--; ii>=0 && pSrc->a[ii].iCursor!=pCtx->iJoin; ii--){}
7728 if( ii>=0 ){
7729 /* Table iJoin appears to the left of table iTab in the SrcList.
7730 ** Therefore the expression refers to a table to its right. */
7731 sqlite3ErrorMsg(pWalker->pParse,
7732 "%s references tables to its right",
7733 (pCtx->bFuncArg ? "table-function argument" : "ON clause")
7734 );
7735 return WRC_Abort;
7736 }
7737 }
7738 break;
7739 }
7740 pCtx = pCtx->pParent;
7741 }while( pCtx );
7742 }
7743 return WRC_Continue;
7744}
7745
7746/*
7747** The xSelect callback for the search of invalid ON clause terms.
7748*/
7749static int selectCheckOnClausesSelect(Walker *pWalker, Select *pSelect){
7750 CheckOnCtx *pCtx = pWalker->u.pCheckOnCtx;
7751 if( pSelect->pSrc==pCtx->pSrc || pSelect->pSrc->nSrc==0 ){
7752 return WRC_Continue;
7753 }else{
7754 CheckOnCtx sCtx;
7755 memset(&sCtx, 0, sizeof(sCtx));
7756 sCtx.pSrc = pSelect->pSrc;
7757 sCtx.pParent = pCtx;
7758 sCtx.iJoin = -1;
7759 pWalker->u.pCheckOnCtx = &sCtx;
7760 sqlite3WalkSelect(pWalker, pSelect);
7761 pWalker->u.pCheckOnCtx = pCtx;
7762 pSelect->selFlags &= ~SF_OnToWhere;
7763 return WRC_Prune;
7764 }
7765}
7766
7767/*
7768** Check all ON clauses in pSelect to verify that they do not reference
7769** columns to the right.
7770*/
7771void sqlite3SelectCheckOnClauses(Parse *pParse, Select *pSelect){
7772 Walker w;
7773 CheckOnCtx sCtx;
7774 int ii;
7775 assert( pSelect->selFlags & SF_OnToWhere );
7776 assert( pSelect->pSrc!=0 && pSelect->pSrc->nSrc>=2 );
7777 memset(&w, 0, sizeof(w));
7778 w.pParse = pParse;
7779 w.xExprCallback = selectCheckOnClausesExpr;
7780 w.xSelectCallback = selectCheckOnClausesSelect;
7781 w.u.pCheckOnCtx = &sCtx;
7782 memset(&sCtx, 0, sizeof(sCtx));
7783 sCtx.pSrc = pSelect->pSrc;
7784 sCtx.iJoin = -1;
7785 sqlite3WalkExpr(&w, pSelect->pWhere);
7786 pSelect->selFlags &= ~SF_OnToWhere;
7787
7788 /* Check for any table-function args that are attached to virtual tables
7789 ** on the RHS of an outer join. They are subject to similar constraints
7790 ** as ON clauses. Specifically:
7791 **
7792 ** * If the table-valued function is to the left of any RIGHT JOIN, or if
7793 ** it is the RHS of a RIGHT JOIN, then the table-valued function arguments
7794 ** may not refer to any tables to the right of this one.
7795 **
7796 ** * If the table-valued function is to the left of a LEFT JOIN, then it
7797 ** may not refer to any table that occurs to the right of the LEFT JOIN.
7798 */
7799 sCtx.bFuncArg = 1;
7800 for(ii=0; ii<pSelect->pSrc->nSrc; ii++){
7801 SrcItem *pItem = &pSelect->pSrc->a[ii];
7802 if( pItem->fg.isTabFunc ){
7803 sCtx.iJoin = -1;
7804 if( (pItem->fg.jointype & (JT_LTORJ|JT_RIGHT)) ){
7805 sCtx.iJoin = pItem->iCursor;
7806 }else{
7807 int jj;
7808 for(jj=ii+1; jj<pSelect->pSrc->nSrc; jj++){
7809 SrcItem *pItem2 = &pSelect->pSrc->a[jj];
7810 if( pItem2->fg.jointype & JT_OUTER ){
7811 sCtx.iJoin = pItem2[-1].iCursor;
7812 break;
7813 }
7814 }
7815 }
7816 if( sCtx.iJoin>=0 ){
7817 sqlite3WalkExprList(&w, pItem->u1.pFuncArg);
7818 }
7819 }
7820 }
7821}
7822
7823/*
7824** If p2 exists and p1 and p2 have the same number of terms, then change
7825** every term of p1 to have the same sort order as p2 and return true.
7826**
7827** If p2 is NULL or p1 and p2 are different lengths, then make no changes
7828** and return false.
7829**
7830** p1 must be non-NULL.
7831*/
7832static int sqlite3CopySortOrder(ExprList *p1, ExprList *p2){
7833 assert( p1 );
7834 if( p2 && p1->nExpr==p2->nExpr ){
7835 int ii;
7836 for(ii=0; ii<p1->nExpr; ii++){
7837 u8 sortFlags;
7838 sortFlags = p2->a[ii].fg.sortFlags & KEYINFO_ORDER_DESC;
7839 p1->a[ii].fg.sortFlags = sortFlags;
7840 }
7841 return 1;
7842 }else{
7843 return 0;
7844 }
7845}
7846
7847/*
7848** Generate byte-code for the SELECT statement given in the p argument.
7849**
7850** The results are returned according to the SelectDest structure.
7851** See comments in sqliteInt.h for further information.
7852**
7853** This routine returns the number of errors. If any errors are
7854** encountered, then an appropriate error message is left in
7855** pParse->zErrMsg.
7856**
7857** This routine does NOT free the Select structure passed in. The
7858** calling function needs to do that.
7859**
7860** This is a long function. The following is an outline of the processing
7861** steps, with tags referencing various milestones:
7862**
7863** * Resolve names and similar preparation tag-select-0100
7864** * Scan of the FROM clause tag-select-0200
7865** + OUTER JOIN strength reduction tag-select-0220
7866** + Sub-query ORDER BY removal tag-select-0230
7867** + Query flattening tag-select-0240
7868** * Separate subroutine for compound-SELECT tag-select-0300
7869** * WHERE-clause constant propagation tag-select-0330
7870** * Count()-of-VIEW optimization tag-select-0350
7871** * Scan of the FROM clause again tag-select-0400
7872** + Authorize unreferenced tables tag-select-0410
7873** + Predicate push-down optimization tag-select-0420
7874** + Omit unused subquery columns optimization tag-select-0440
7875** + Generate code to implement subqueries tag-select-0480
7876** - Co-routines tag-select-0482
7877** - Reuse previously computed CTE tag-select-0484
7878** - REuse previously computed VIEW tag-select-0486
7879** - Materialize a VIEW or CTE tag-select-0488
7880** * DISTINCT ORDER BY -> GROUP BY optimization tag-select-0500
7881** * Set up for ORDER BY tag-select-0600
7882** * Create output table tag-select-0630
7883** * Prepare registers for LIMIT tag-select-0650
7884** * Setup for DISTINCT tag-select-0680
7885** * Generate code for non-aggregate and non-GROUP BY tag-select-0700
7886** * Generate code for aggregate and/or GROUP BY tag-select-0800
7887** + GROUP BY queries tag-select-0810
7888** + non-GROUP BY queries tag-select-0820
7889** - Special case of count() w/o GROUP BY tag-select-0821
7890** - General case of non-GROUP BY aggregates tag-select-0822
7891** * Sort results, as needed tag-select-0900
7892** * Internal self-checks tag-select-1000
7893*/
7894int sqlite3Select(
7895 Parse *pParse, /* The parser context */
7896 Select *p, /* The SELECT statement being coded. */
7897 SelectDest *pDest /* What to do with the query results */
7898){
7899 int i, j; /* Loop counters */
7900 WhereInfo *pWInfo; /* Return from sqlite3WhereBegin() */
7901 Vdbe *v; /* The virtual machine under construction */
7902 int isAgg; /* True for select lists like "count(*)" */
7903 ExprList *pEList = 0; /* List of columns to extract. */
7904 SrcList *pTabList; /* List of tables to select from */
7905 Expr *pWhere; /* The WHERE clause. May be NULL */
7906 ExprList *pGroupBy; /* The GROUP BY clause. May be NULL */
7907 Expr *pHaving; /* The HAVING clause. May be NULL */
7908 AggInfo *pAggInfo = 0; /* Aggregate information */
7909 int rc = 1; /* Value to return from this function */
7910 DistinctCtx sDistinct; /* Info on how to code the DISTINCT keyword */
7911 SortCtx sSort; /* Info on how to code the ORDER BY clause */
7912 int iEnd; /* Address of the end of the query */
7913 sqlite3 *db; /* The database connection */
7914 ExprList *pMinMaxOrderBy = 0; /* Added ORDER BY for min/max queries */
7915 u8 minMaxFlag; /* Flag for min/max queries */
7916
7917 db = pParse->db;
7918 assert( pParse==db->pParse );
7919 v = sqlite3GetVdbe(pParse);
7920 if( p==0 || pParse->nErr ){
7921 return 1;
7922 }
7923 assert( db->mallocFailed==0 );
7924 if( sqlite3AuthCheck(pParse, SQLITE_SELECT, 0, 0, 0) ) return 1;
7925#if TREETRACE_ENABLED
7926 TREETRACE(0x1,pParse,p, ("begin processing:\n", pParse->addrExplain));
7927 if( sqlite3TreeTrace & 0x10000 ){
7928 if( (sqlite3TreeTrace & 0x10001)==0x10000 ){
7929 sqlite3TreeViewLine(0, "In sqlite3Select() at %s:%d",
7930 __FILE__, __LINE__);
7931 }
7932 sqlite3ShowSelect(p);
7933 }
7934#endif
7935
7936 /* tag-select-0100 */
7937 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistFifo );
7938 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Fifo );
7939 assert( p->pOrderBy==0 || pDest->eDest!=SRT_DistQueue );
7940 assert( p->pOrderBy==0 || pDest->eDest!=SRT_Queue );
7941 if( IgnorableDistinct(pDest) ){
7942 assert(pDest->eDest==SRT_Exists || pDest->eDest==SRT_Discard ||
7943 pDest->eDest==SRT_DistQueue || pDest->eDest==SRT_DistFifo );
7944 /* All of these destinations are also able to ignore the ORDER BY clause */
7945 if( p->pOrderBy ){
7946#if TREETRACE_ENABLED
7947 TREETRACE(0x800,pParse,p, ("dropping superfluous ORDER BY:\n"));
7948 if( sqlite3TreeTrace & 0x800 ){
7949 sqlite3TreeViewExprList(0, p->pOrderBy, 0, "ORDERBY");
7950 }
7951#endif
7952 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
7953 p->pOrderBy);
7954 testcase( pParse->earlyCleanup );
7955 p->pOrderBy = 0;
7956 }
7957 /* Do not ignore DISTINCT for an EXISTS subquery with an OFFSET clause.
7958 ** In this case the OFFSET must be applied after duplicates are discarded,
7959 ** so the DISTINCT is required. */
7960 if( pDest->eDest!=SRT_Exists
7961 || (ALWAYS(p->pLimit!=0) && p->pLimit->pRight==0)
7962 /* ^^^^^^-- because tag-202611101908 and SRT_Exists set nowhere else */
7963 ){
7964 p->selFlags &= ~(u32)SF_Distinct;
7965 }
7966 }
7967 sqlite3SelectPrep(pParse, p, 0);
7968 if( pParse->nErr ){
7969 goto select_end;
7970 }
7971 assert( db->mallocFailed==0 );
7972 assert( p->pEList!=0 );
7973#if TREETRACE_ENABLED
7974 if( sqlite3TreeTrace & 0x10 ){
7975 TREETRACE(0x10,pParse,p, ("after name resolution:\n"));
7976 sqlite3TreeViewSelect(0, p, 0);
7977 }
7978#endif
7979
7980 /* If the SF_UFSrcCheck flag is set, then this function is being called
7981 ** as part of populating the temp table for an UPDATE...FROM statement.
7982 ** In this case, it is an error if the target object (pSrc->a[0]) name
7983 ** or alias is duplicated within FROM clause (pSrc->a[1..n]).
7984 **
7985 ** Postgres disallows this case too. The reason is that some other
7986 ** systems handle this case differently, and not all the same way,
7987 ** which is just confusing. To avoid this, we follow PG's lead and
7988 ** disallow it altogether. */
7989 if( p->selFlags & SF_UFSrcCheck ){
7990 SrcItem *p0 = &p->pSrc->a[0];
7991 if( sameSrcAlias(p0, p->pSrc) ){
7992 sqlite3ErrorMsg(pParse,
7993 "target object/alias may not appear in FROM clause: %s",
7994 p0->zAlias ? p0->zAlias : p0->pSTab->zName
7995 );
7996 goto select_end;
7997 }
7998
7999 /* Clear the SF_UFSrcCheck flag. The check has already been performed,
8000 ** and leaving this flag set can cause errors if a compound sub-query
8001 ** in p->pSrc is flattened into this query and this function called
8002 ** again as part of compound SELECT processing. */
8003 p->selFlags &= ~(u32)SF_UFSrcCheck;
8004 }
8005
8006 if( pDest->eDest==SRT_Output ){
8007 sqlite3GenerateColumnNames(pParse, p);
8008 }
8009
8010#ifndef SQLITE_OMIT_WINDOWFUNC
8011 if( sqlite3WindowRewrite(pParse, p) ){
8012 assert( pParse->nErr );
8013 goto select_end;
8014 }
8015#if TREETRACE_ENABLED
8016 if( p->pWin && (sqlite3TreeTrace & 0x40)!=0 ){
8017 TREETRACE(0x40,pParse,p, ("after window rewrite:\n"));
8018 sqlite3TreeViewSelect(0, p, 0);
8019 }
8020#endif
8021#endif /* SQLITE_OMIT_WINDOWFUNC */
8022 pTabList = p->pSrc;
8023 isAgg = (p->selFlags & SF_Aggregate)!=0;
8024 memset(&sSort, 0, sizeof(sSort));
8025 sSort.pOrderBy = p->pOrderBy;
8026
8027 /* Try to do various optimizations (flattening subqueries, and strength
8028 ** reduction of join operators) in the FROM clause up into the main query
8029 ** tag-select-0200
8030 */
8031#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
8032 for(i=0; !p->pPrior && i<pTabList->nSrc; i++){
8033 SrcItem *pItem = &pTabList->a[i];
8034 Select *pSub = pItem->fg.isSubquery ? pItem->u4.pSubq->pSelect : 0;
8035 Table *pTab = pItem->pSTab;
8036
8037 /* The expander should have already created transient Table objects
8038 ** even for FROM clause elements such as subqueries that do not correspond
8039 ** to a real table */
8040 assert( pTab!=0 );
8041
8042 /* Try to simplify joins:
8043 **
8044 ** LEFT JOIN -> JOIN
8045 ** RIGHT JOIN -> JOIN
8046 ** FULL JOIN -> RIGHT JOIN
8047 **
8048 ** If terms of the i-th table are used in the WHERE clause in such a
8049 ** way that the i-th table cannot be the NULL row of a join, then
8050 ** perform the appropriate simplification. This is called
8051 ** "OUTER JOIN strength reduction" in the SQLite documentation.
8052 ** tag-select-0220
8053 */
8054 if( (pItem->fg.jointype & (JT_LEFT|JT_LTORJ))!=0
8055 && sqlite3ExprImpliesNonNullRow(p->pWhere, pItem->iCursor,
8056 pItem->fg.jointype & JT_LTORJ)
8057 && OptimizationEnabled(db, SQLITE_SimplifyJoin)
8058 ){
8059 if( pItem->fg.jointype & JT_LEFT ){
8060 if( pItem->fg.jointype & JT_RIGHT ){
8061 TREETRACE(0x1000,pParse,p,
8062 ("FULL-JOIN simplifies to RIGHT-JOIN on term %d\n",i));
8063 pItem->fg.jointype &= ~JT_LEFT;
8064 }else{
8065 TREETRACE(0x1000,pParse,p,
8066 ("LEFT-JOIN simplifies to JOIN on term %d\n",i));
8067 pItem->fg.jointype &= ~(JT_LEFT|JT_OUTER);
8068 unsetJoinExpr(p->pWhere, pItem->iCursor, 0);
8069 }
8070 }
8071 if( pItem->fg.jointype & JT_LTORJ ){
8072 for(j=i+1; j<pTabList->nSrc; j++){
8073 SrcItem *pI2 = &pTabList->a[j];
8074 if( pI2->fg.jointype & JT_RIGHT ){
8075 if( pI2->fg.jointype & JT_LEFT ){
8076 TREETRACE(0x1000,pParse,p,
8077 ("FULL-JOIN simplifies to LEFT-JOIN on term %d\n",j));
8078 pI2->fg.jointype &= ~JT_RIGHT;
8079 }else{
8080 TREETRACE(0x1000,pParse,p,
8081 ("RIGHT-JOIN simplifies to JOIN on term %d\n",j));
8082 pI2->fg.jointype &= ~(JT_RIGHT|JT_OUTER);
8083 unsetJoinExpr(p->pWhere, pI2->iCursor, 1);
8084 }
8085 }
8086 }
8087 for(j=pTabList->nSrc-1; j>=0; j--){
8088 SrcItem *pI2 = &pTabList->a[j];
8089 pI2->fg.jointype &= ~JT_LTORJ;
8090 if( (pI2->fg.jointype & (JT_LEFT|JT_RIGHT))==0 ){
8091 clearOuterOnExpr(p->pWhere, pI2->iCursor);
8092 unwrapIfNullRow(pParse, p, pI2->iCursor);
8093 }
8094 if( pI2->fg.jointype & JT_RIGHT ) break;
8095 }
8096 }
8097 }
8098
8099 /* No further action if this term of the FROM clause is not a subquery */
8100 if( pSub==0 ) continue;
8101
8102 /* Catch mismatch in the declared columns of a view and the number of
8103 ** columns in the SELECT on the RHS */
8104 if( pTab->nCol!=pSub->pEList->nExpr ){
8105 sqlite3ErrorMsg(pParse, "expected %d columns for '%s' but got %d",
8106 pTab->nCol, pTab->zName, pSub->pEList->nExpr);
8107 goto select_end;
8108 }
8109
8110 /* Do not attempt the usual optimizations (flattening and ORDER BY
8111 ** elimination) on a MATERIALIZED common table expression because
8112 ** a MATERIALIZED common table expression is an optimization fence.
8113 */
8114 if( pItem->fg.isCte && pItem->u2.pCteUse->eM10d==M10d_Yes ){
8115 continue;
8116 }
8117
8118 /* Do not try to flatten an aggregate subquery.
8119 **
8120 ** Flattening an aggregate subquery is only possible if the outer query
8121 ** is not a join. But if the outer query is not a join, then the subquery
8122 ** will be implemented as a co-routine and there is no advantage to
8123 ** flattening in that case.
8124 */
8125 if( (pSub->selFlags & SF_Aggregate)!=0 ) continue;
8126 assert( pSub->pGroupBy==0 );
8127
8128 /* tag-select-0230:
8129 ** If a FROM-clause subquery has an ORDER BY clause that is not
8130 ** really doing anything, then delete it now so that it does not
8131 ** interfere with query flattening. See the discussion at
8132 ** https://sqlite.org/forum/forumpost/2d76f2bcf65d256a
8133 **
8134 ** Beware of these cases where the ORDER BY clause may not be safely
8135 ** omitted:
8136 **
8137 ** (1) There is also a LIMIT clause
8138 ** (2) The subquery was added to help with window-function
8139 ** processing
8140 ** (3) The subquery is in the FROM clause of an UPDATE
8141 ** (4) The outer query uses an aggregate function other than
8142 ** the built-in count(), min(), or max().
8143 ** (5) The ORDER BY isn't going to accomplish anything because
8144 ** one of:
8145 ** (a) The outer query has a different ORDER BY clause
8146 ** (b) The subquery is part of a join
8147 ** See forum post 062d576715d277c8
8148 ** (6) The subquery is not a recursive CTE. ORDER BY has a different
8149 ** meaning for recursive CTEs and this optimization does not
8150 ** apply.
8151 **
8152 ** Also retain the ORDER BY if the OmitOrderBy optimization is disabled.
8153 */
8154 if( pSub->pOrderBy!=0
8155 && (p->pOrderBy!=0 || pTabList->nSrc>1) /* Condition (5) */
8156 && pSub->pLimit==0 /* Condition (1) */
8157 && (pSub->selFlags & (SF_OrderByReqd|SF_Recursive))==0 /* (2) and (6) */
8158 && (p->selFlags & SF_OrderByReqd)==0 /* Condition (3) and (4) */
8159 && OptimizationEnabled(db, SQLITE_OmitOrderBy)
8160 ){
8161 TREETRACE(0x800,pParse,p,
8162 ("omit superfluous ORDER BY on %r FROM-clause subquery\n",i+1));
8163 sqlite3ParserAddCleanup(pParse, sqlite3ExprListDeleteGeneric,
8164 pSub->pOrderBy);
8165 pSub->pOrderBy = 0;
8166 }
8167
8168 /* If the outer query contains a "complex" result set (that is,
8169 ** if the result set of the outer query uses functions or subqueries)
8170 ** and if the subquery contains an ORDER BY clause and if
8171 ** it will be implemented as a co-routine, then do not flatten. This
8172 ** restriction allows SQL constructs like this:
8173 **
8174 ** SELECT expensive_function(x)
8175 ** FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
8176 **
8177 ** The expensive_function() is only computed on the 10 rows that
8178 ** are output, rather than every row of the table.
8179 **
8180 ** The requirement that the outer query have a complex result set
8181 ** means that flattening does occur on simpler SQL constraints without
8182 ** the expensive_function() like:
8183 **
8184 ** SELECT x FROM (SELECT x FROM tab ORDER BY y LIMIT 10);
8185 */
8186 if( pSub->pOrderBy!=0
8187 && i==0
8188 && (p->selFlags & SF_ComplexResult)!=0
8189 && (pTabList->nSrc==1
8190 || (pTabList->a[1].fg.jointype&(JT_OUTER|JT_CROSS))!=0)
8191 ){
8192 continue;
8193 }
8194
8195 /* tag-select-0240 */
8196 if( flattenSubquery(pParse, p, i, isAgg) ){
8197 if( pParse->nErr ) goto select_end;
8198 /* This subquery can be absorbed into its parent. */
8199 i = -1;
8200 }
8201 pTabList = p->pSrc;
8202 if( db->mallocFailed ) goto select_end;
8203 if( !IgnorableOrderby(pDest) ){
8204 sSort.pOrderBy = p->pOrderBy;
8205 }
8206 }
8207#endif
8208
8209#ifndef SQLITE_OMIT_COMPOUND_SELECT
8210 /* Handle compound SELECT statements using the separate multiSelect()
8211 ** procedure. tag-select-0300
8212 */
8213 if( p->pPrior ){
8214 rc = multiSelect(pParse, p, pDest);
8215#if TREETRACE_ENABLED
8216 TREETRACE(0x400,pParse,p,("end compound-select processing\n"));
8217 if( (sqlite3TreeTrace & 0x400)!=0 && ExplainQueryPlanParent(pParse)==0 ){
8218 sqlite3TreeViewSelect(0, p, 0);
8219 }
8220#endif
8221 if( p->pNext==0 ) ExplainQueryPlanPop(pParse);
8222 return rc;
8223 }
8224#endif
8225
8226 /* If there may be an "EXISTS (SELECT ...)" in the WHERE clause, attempt
8227 ** to change it into a join. */
8228 if( pParse->bHasExists && OptimizationEnabled(db,SQLITE_ExistsToJoin) ){
8229 existsToJoin(pParse, p, p->pWhere);
8230 pTabList = p->pSrc;
8231 }
8232
8233 /* Do the WHERE-clause constant propagation optimization if this is
8234 ** a join. No need to spend time on this operation for non-join queries
8235 ** as the equivalent optimization will be handled by query planner in
8236 ** sqlite3WhereBegin(). tag-select-0330
8237 */
8238 if( p->pWhere!=0
8239 && p->pWhere->op==TK_AND
8240 && OptimizationEnabled(db, SQLITE_PropagateConst)
8241 && propagateConstants(pParse, p)
8242 ){
8243#if TREETRACE_ENABLED
8244 if( sqlite3TreeTrace & 0x2000 ){
8245 TREETRACE(0x2000,pParse,p,("After constant propagation:\n"));
8246 sqlite3TreeViewSelect(0, p, 0);
8247 }
8248#endif
8249 }else{
8250 TREETRACE(0x2000,pParse,p,("Constant propagation not helpful\n"));
8251 }
8252
8253 /* tag-select-0350 */
8254 if( OptimizationEnabled(db, SQLITE_QueryFlattener|SQLITE_CountOfView)
8255 && countOfViewOptimization(pParse, p)
8256 ){
8257 if( db->mallocFailed ) goto select_end;
8258 pTabList = p->pSrc;
8259 }
8260
8261 /* Loop over all terms in the FROM clause and do two things for each term:
8262 **
8263 ** (1) Authorize unreferenced tables
8264 ** (2) Generate code for all sub-queries
8265 **
8266 ** tag-select-0400
8267 */
8268 for(i=0; i<pTabList->nSrc; i++){
8269 SrcItem *pItem = &pTabList->a[i];
8270 SrcItem *pPrior;
8271 SelectDest dest;
8272 Subquery *pSubq;
8273 Select *pSub;
8274#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
8275 const char *zSavedAuthContext;
8276#endif
8277
8278 /* Authorized unreferenced tables. tag-select-0410
8279 **
8280 ** Issue SQLITE_READ authorizations with a fake column name for any
8281 ** tables that are referenced but from which no values are extracted.
8282 ** Examples of where these kinds of null SQLITE_READ authorizations
8283 ** would occur:
8284 **
8285 ** SELECT count(*) FROM t1; -- SQLITE_READ t1.""
8286 ** SELECT t1.* FROM t1, t2; -- SQLITE_READ t2.""
8287 **
8288 ** The fake column name is an empty string. It is possible for a table to
8289 ** have a column named by the empty string, in which case there is no way to
8290 ** distinguish between an unreferenced table and an actual reference to the
8291 ** "" column. The original design was for the fake column name to be a NULL,
8292 ** which would be unambiguous. But legacy authorization callbacks might
8293 ** assume the column name is non-NULL and segfault. The use of an empty
8294 ** string for the fake column name seems safer.
8295 */
8296 if( pItem->colUsed==0 && pItem->zName!=0 ){
8297 const char *zDb;
8298 if( pItem->fg.fixedSchema ){
8299 int iDb = sqlite3SchemaToIndex(pParse->db, pItem->u4.pSchema);
8300 zDb = db->aDb[iDb].zDbSName;
8301 }else if( pItem->fg.isSubquery ){
8302 zDb = 0;
8303 }else{
8304 zDb = pItem->u4.zDatabase;
8305 }
8306 sqlite3AuthCheck(pParse, SQLITE_READ, pItem->zName, "", zDb);
8307 }
8308
8309#if !defined(SQLITE_OMIT_SUBQUERY) || !defined(SQLITE_OMIT_VIEW)
8310 /* Generate code for all sub-queries in the FROM clause
8311 */
8312 if( pItem->fg.isSubquery==0 ) continue;
8313 pSubq = pItem->u4.pSubq;
8314 assert( pSubq!=0 );
8315 pSub = pSubq->pSelect;
8316
8317 /* The code for a subquery should only be generated once. */
8318 if( pSubq->addrFillSub!=0 ) continue;
8319
8320 /* Increment Parse.nHeight by the height of the largest expression
8321 ** tree referred to by this, the parent select. The child select
8322 ** may contain expression trees of at most
8323 ** (SQLITE_MAX_EXPR_DEPTH-Parse.nHeight) height. This is a bit
8324 ** more conservative than necessary, but much easier than enforcing
8325 ** an exact limit.
8326 */
8327 pParse->nHeight += sqlite3SelectExprHeight(p);
8328
8329 /* Make copies of constant WHERE-clause terms in the outer query down
8330 ** inside the subquery. This can help the subquery to run more efficiently.
8331 ** This is the "predicate push-down optimization". tag-select-0420
8332 */
8333 if( OptimizationEnabled(db, SQLITE_PushDown)
8334 && (pItem->fg.isCte==0
8335 || (pItem->u2.pCteUse->eM10d!=M10d_Yes && pItem->u2.pCteUse->nUse<2))
8336 && pushDownWhereTerms(pParse, pSub, p->pWhere, pTabList, i)
8337 ){
8338#if TREETRACE_ENABLED
8339 if( sqlite3TreeTrace & 0x4000 ){
8340 TREETRACE(0x4000,pParse,p,
8341 ("After WHERE-clause push-down into subquery %d:\n", pSub->selId));
8342 sqlite3TreeViewSelect(0, p, 0);
8343 }
8344#endif
8345 assert( pSubq->pSelect && (pSub->selFlags & SF_PushDown)!=0 );
8346 }else{
8347 TREETRACE(0x4000,pParse,p,("WHERE-clause push-down not possible\n"));
8348 }
8349
8350 /* Convert unused result columns of the subquery into simple NULL
8351 ** expressions, to avoid unneeded searching and computation.
8352 ** tag-select-0440
8353 */
8354 if( OptimizationEnabled(db, SQLITE_NullUnusedCols)
8355 && disableUnusedSubqueryResultColumns(pItem)
8356 ){
8357#if TREETRACE_ENABLED
8358 if( sqlite3TreeTrace & 0x4000 ){
8359 TREETRACE(0x4000,pParse,p,
8360 ("Change unused result columns to NULL for subquery %d:\n",
8361 pSub->selId));
8362 sqlite3TreeViewSelect(0, p, 0);
8363 }
8364#endif
8365 }
8366
8367 zSavedAuthContext = pParse->zAuthContext;
8368 pParse->zAuthContext = pItem->zName;
8369
8370 /* Generate byte-code to implement the subquery tag-select-0480
8371 */
8372 if( fromClauseTermCanBeCoroutine(pParse, pTabList, i, p->selFlags) ){
8373 /* Implement a co-routine that will return a single row of the result
8374 ** set on each invocation. tag-select-0482
8375 */
8376 int addrTop = sqlite3VdbeCurrentAddr(v)+1;
8377
8378 pSubq->regReturn = ++pParse->nMem;
8379 sqlite3VdbeAddOp3(v, OP_InitCoroutine, pSubq->regReturn, 0, addrTop);
8380 VdbeComment((v, "%!S", pItem));
8381 pSubq->addrFillSub = addrTop;
8382 sqlite3SelectDestInit(&dest, SRT_Coroutine, pSubq->regReturn);
8383 ExplainQueryPlan((pParse, 1, "CO-ROUTINE %!S", pItem));
8384 sqlite3Select(pParse, pSub, &dest);
8385 pItem->pSTab->nRowLogEst = pSub->nSelectRow;
8386 pItem->fg.viaCoroutine = 1;
8387 pSubq->regResult = dest.iSdst;
8388 sqlite3VdbeEndCoroutine(v, pSubq->regReturn);
8389 VdbeComment((v, "end %!S", pItem));
8390 sqlite3VdbeJumpHere(v, addrTop-1);
8391 sqlite3ClearTempRegCache(pParse);
8392 }else if( pItem->fg.isCte && pItem->u2.pCteUse->addrM9e>0 ){
8393 /* This is a CTE for which materialization code has already been
8394 ** generated. Invoke the subroutine to compute the materialization,
8395 ** then make the pItem->iCursor be a copy of the ephemeral table that
8396 ** holds the result of the materialization. tag-select-0484 */
8397 CteUse *pCteUse = pItem->u2.pCteUse;
8398 /* The materialization is computed once per run of the statement or
8399 ** trigger program and does not change after that. So the subroutine
8400 ** call and the OP_OpenDup are needed on the first pass only. The
8401 ** OP_NullRow runs on every pass and leaves the duplicate cursor not
8402 ** positioned on a row, as OP_OpenDup does. */
8403 int addrOnce = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
8404 sqlite3VdbeAddOp2(v, OP_Gosub, pCteUse->regRtn, pCteUse->addrM9e);
8405 if( pItem->iCursor!=pCteUse->iCur ){
8406 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pCteUse->iCur);
8407 VdbeComment((v, "%!S", pItem));
8408 }
8409 sqlite3VdbeJumpHere(v, addrOnce);
8410 if( pItem->iCursor!=pCteUse->iCur ){
8411 sqlite3VdbeAddOp1(v, OP_NullRow, pItem->iCursor);
8412 }
8413 pSub->nSelectRow = pCteUse->nRowEst;
8414 }else if( (pPrior = isSelfJoinView(pTabList, pItem, 0, i))!=0 ){
8415 /* This view has already been materialized by a prior entry in
8416 ** this same FROM clause. Reuse it. tag-select-0486 */
8417 Subquery *pPriorSubq;
8418 assert( pPrior->fg.isSubquery );
8419 pPriorSubq = pPrior->u4.pSubq;
8420 assert( pPriorSubq!=0 );
8421 if( pPriorSubq->addrFillSub ){
8422 sqlite3VdbeAddOp2(v, OP_Gosub, pPriorSubq->regReturn,
8423 pPriorSubq->addrFillSub);
8424 }
8425 sqlite3VdbeAddOp2(v, OP_OpenDup, pItem->iCursor, pPrior->iCursor);
8426 pSub->nSelectRow = pPriorSubq->pSelect->nSelectRow;
8427 }else{
8428 /* Materialize the view. If the view is not correlated, generate a
8429 ** subroutine to do the materialization so that subsequent uses of
8430 ** the same view can reuse the materialization. tag-select-0488 */
8431 int topAddr;
8432 int onceAddr = 0;
8433#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
8434 int addrExplain;
8435#endif
8436
8437 pSubq->regReturn = ++pParse->nMem;
8438 topAddr = sqlite3VdbeAddOp0(v, OP_Goto);
8439 pSubq->addrFillSub = topAddr+1;
8440 pItem->fg.isMaterialized = 1;
8441 if( pItem->fg.isCorrelated==0 ){
8442 /* If the subquery is not correlated and if we are not inside of
8443 ** a trigger, then we only need to compute the value of the subquery
8444 ** once. */
8445 onceAddr = sqlite3VdbeAddOp0(v, OP_Once); VdbeCoverage(v);
8446 VdbeComment((v, "materialize %!S", pItem));
8447 }else{
8448 VdbeNoopComment((v, "materialize %!S", pItem));
8449 }
8450 sqlite3SelectDestInit(&dest, SRT_EphemTab, pItem->iCursor);
8451
8452 ExplainQueryPlan2(addrExplain, (pParse, 1, "MATERIALIZE %!S", pItem));
8453 sqlite3Select(pParse, pSub, &dest);
8454 pItem->pSTab->nRowLogEst = pSub->nSelectRow;
8455 if( onceAddr ) sqlite3VdbeJumpHere(v, onceAddr);
8456 sqlite3VdbeAddOp2(v, OP_Return, pSubq->regReturn, topAddr+1);
8457 VdbeComment((v, "end %!S", pItem));
8458 sqlite3VdbeScanStatusRange(v, addrExplain, addrExplain, -1);
8459 sqlite3VdbeJumpHere(v, topAddr);
8460 sqlite3ClearTempRegCache(pParse);
8461 if( pItem->fg.isCte && pItem->fg.isCorrelated==0 ){
8462 CteUse *pCteUse = pItem->u2.pCteUse;
8463 pCteUse->addrM9e = pSubq->addrFillSub;
8464 pCteUse->regRtn = pSubq->regReturn;
8465 pCteUse->iCur = pItem->iCursor;
8466 pCteUse->nRowEst = pSub->nSelectRow;
8467 }
8468 }
8469 if( db->mallocFailed ) goto select_end;
8470 pParse->nHeight -= sqlite3SelectExprHeight(p);
8471 pParse->zAuthContext = zSavedAuthContext;
8472#endif
8473 }
8474
8475 /* Various elements of the SELECT copied into local variables for
8476 ** convenience */
8477 pEList = p->pEList;
8478 pWhere = p->pWhere;
8479 pGroupBy = p->pGroupBy;
8480 pHaving = p->pHaving;
8481 sDistinct.isTnct = (p->selFlags & SF_Distinct)!=0;
8482
8483#if TREETRACE_ENABLED
8484 if( sqlite3TreeTrace & 0x8000 ){
8485 TREETRACE(0x8000,pParse,p,("After all FROM-clause analysis:\n"));
8486 sqlite3TreeViewSelect(0, p, 0);
8487 }
8488#endif
8489
8490 /* tag-select-0500
8491 **
8492 ** If the query is DISTINCT with an ORDER BY but is not an aggregate, and
8493 ** if the select-list is the same as the ORDER BY list, then this query
8494 ** can be rewritten as a GROUP BY. In other words, this:
8495 **
8496 ** SELECT DISTINCT xyz FROM ... ORDER BY xyz
8497 **
8498 ** is transformed to:
8499 **
8500 ** SELECT xyz FROM ... GROUP BY xyz ORDER BY xyz
8501 **
8502 ** The second form is preferred as a single index (or temp-table) may be
8503 ** used for both the ORDER BY and DISTINCT processing. As originally
8504 ** written the query must use a temp-table for at least one of the ORDER
8505 ** BY and DISTINCT, and an index or separate temp-table for the other.
8506 */
8507 if( (p->selFlags & (SF_Distinct|SF_Aggregate))==SF_Distinct
8508 && sqlite3CopySortOrder(pEList, sSort.pOrderBy)
8509 && sqlite3ExprListCompare(pEList, sSort.pOrderBy, -1)==0
8510 && OptimizationEnabled(db, SQLITE_GroupByOrder)
8511#ifndef SQLITE_OMIT_WINDOWFUNC
8512 && p->pWin==0
8513#endif
8514 ){
8515 p->selFlags &= ~(u32)SF_Distinct;
8516 pGroupBy = p->pGroupBy = sqlite3ExprListDup(db, pEList, 0);
8517 if( pGroupBy ){
8518 for(i=0; i<pGroupBy->nExpr; i++){
8519 pGroupBy->a[i].u.x.iOrderByCol = i+1;
8520 }
8521 }
8522 p->selFlags |= SF_Aggregate;
8523 /* Notice that even thought SF_Distinct has been cleared from p->selFlags,
8524 ** the sDistinct.isTnct is still set. Hence, isTnct represents the
8525 ** original setting of the SF_Distinct flag, not the current setting */
8526 assert( sDistinct.isTnct );
8527 sDistinct.isTnct = 2;
8528
8529#if TREETRACE_ENABLED
8530 if( sqlite3TreeTrace & 0x20000 ){
8531 TREETRACE(0x20000,pParse,p,("Transform DISTINCT into GROUP BY:\n"));
8532 sqlite3TreeViewSelect(0, p, 0);
8533 }
8534#endif
8535 }
8536
8537 /* If there is an ORDER BY clause, then create an ephemeral index to
8538 ** do the sorting. But this sorting ephemeral index might end up
8539 ** being unused if the data can be extracted in pre-sorted order.
8540 ** If that is the case, then the OP_OpenEphemeral instruction will be
8541 ** changed to an OP_Noop once we figure out that the sorting index is
8542 ** not needed. The sSort.addrSortIndex variable is used to facilitate
8543 ** that change. tag-select-0600
8544 */
8545 if( sSort.pOrderBy ){
8546 KeyInfo *pKeyInfo;
8547 pKeyInfo = sqlite3KeyInfoFromExprList(
8548 pParse, sSort.pOrderBy, 0, pEList->nExpr);
8549 sSort.iECursor = pParse->nTab++;
8550 sSort.addrSortIndex =
8551 sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
8552 sSort.iECursor, sSort.pOrderBy->nExpr+1+pEList->nExpr, 0,
8553 (char*)pKeyInfo, P4_KEYINFO
8554 );
8555 }else{
8556 sSort.addrSortIndex = -1;
8557 }
8558
8559 /* If the output is destined for a temporary table, open that table.
8560 ** tag-select-0630
8561 */
8562 if( pDest->eDest==SRT_EphemTab ){
8563 sqlite3VdbeAddOp2(v, OP_OpenEphemeral, pDest->iSDParm, pEList->nExpr);
8564 if( p->selFlags & SF_NestedFrom ){
8565 /* Delete or NULL-out result columns that will never be used */
8566 int ii;
8567 for(ii=pEList->nExpr-1; ii>0 && pEList->a[ii].fg.bUsed==0; ii--){
8568 sqlite3ExprDelete(db, pEList->a[ii].pExpr);
8569 sqlite3DbFree(db, pEList->a[ii].zEName);
8570 pEList->nExpr--;
8571 }
8572 for(ii=0; ii<pEList->nExpr; ii++){
8573 if( pEList->a[ii].fg.bUsed==0 ) pEList->a[ii].pExpr->op = TK_NULL;
8574 }
8575 }
8576 }
8577
8578 /* Set the limiter. tag-select-0650
8579 */
8580 iEnd = sqlite3VdbeMakeLabel(pParse);
8581 if( (p->selFlags & SF_FixedLimit)==0 ){
8582 p->nSelectRow = 320; /* 4 billion rows */
8583 }
8584 if( p->pLimit ) computeLimitRegisters(pParse, p, iEnd);
8585 if( p->iLimit==0 && sSort.addrSortIndex>=0 ){
8586 sqlite3VdbeChangeOpcode(v, sSort.addrSortIndex, OP_SorterOpen);
8587 sSort.sortFlags |= SORTFLAG_UseSorter;
8588 }
8589
8590 /* Open an ephemeral index to use for the distinct set. tag-select-0680
8591 */
8592 if( p->selFlags & SF_Distinct ){
8593 sDistinct.tabTnct = pParse->nTab++;
8594 sDistinct.addrTnct = sqlite3VdbeAddOp4(v, OP_OpenEphemeral,
8595 sDistinct.tabTnct, 0, 0,
8596 (char*)sqlite3KeyInfoFromExprList(pParse, p->pEList,0,0),
8597 P4_KEYINFO);
8598 sqlite3VdbeChangeP5(v, BTREE_UNORDERED);
8599 sDistinct.eTnctType = WHERE_DISTINCT_UNORDERED;
8600 }else{
8601 sDistinct.eTnctType = WHERE_DISTINCT_NOOP;
8602 }
8603
8604 if( !isAgg && pGroupBy==0 ){
8605 /* No aggregate functions and no GROUP BY clause. tag-select-0700 */
8606 u16 wctrlFlags = (sDistinct.isTnct ? WHERE_WANT_DISTINCT : 0)
8607 | (p->selFlags & SF_FixedLimit);
8608#ifndef SQLITE_OMIT_WINDOWFUNC
8609 Window *pWin = p->pWin; /* Main window object (or NULL) */
8610 if( pWin ){
8611 sqlite3WindowCodeInit(pParse, p);
8612 }
8613#endif
8614 assert( WHERE_USE_LIMIT==SF_FixedLimit );
8615
8616
8617 /* Begin the database scan. */
8618 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8619 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, sSort.pOrderBy,
8620 p->pEList, p, wctrlFlags, p->nSelectRow);
8621 if( pWInfo==0 ) goto select_end;
8622 if( sqlite3WhereOutputRowCount(pWInfo) < p->nSelectRow ){
8623 p->nSelectRow = sqlite3WhereOutputRowCount(pWInfo);
8624 if( pDest->eDest<=SRT_DistQueue && pDest->eDest>=SRT_DistFifo ){
8625 /* TUNING: For a UNION CTE, because UNION is implies DISTINCT,
8626 ** reduce the estimated output row count by 8 (LogEst 30).
8627 ** Search for tag-20250414a to see other cases */
8628 p->nSelectRow -= 30;
8629 }
8630 }
8631 if( sDistinct.isTnct && sqlite3WhereIsDistinct(pWInfo) ){
8632 sDistinct.eTnctType = sqlite3WhereIsDistinct(pWInfo);
8633 }
8634 if( sSort.pOrderBy ){
8635 sSort.nOBSat = sqlite3WhereIsOrdered(pWInfo);
8636 sSort.labelOBLopt = sqlite3WhereOrderByLimitOptLabel(pWInfo);
8637 if( sSort.nOBSat==sSort.pOrderBy->nExpr ){
8638 sSort.pOrderBy = 0;
8639 }
8640 }
8641 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8642
8643 /* If sorting index that was created by a prior OP_OpenEphemeral
8644 ** instruction ended up not being needed, then change the OP_OpenEphemeral
8645 ** into an OP_Noop.
8646 */
8647 if( sSort.addrSortIndex>=0 && sSort.pOrderBy==0 ){
8648 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
8649 }
8650
8651 assert( p->pEList==pEList );
8652#ifndef SQLITE_OMIT_WINDOWFUNC
8653 if( pWin ){
8654 int addrGosub = sqlite3VdbeMakeLabel(pParse);
8655 int iCont = sqlite3VdbeMakeLabel(pParse);
8656 int iBreak = sqlite3VdbeMakeLabel(pParse);
8657 int regGosub = ++pParse->nMem;
8658
8659 sqlite3WindowCodeStep(pParse, p, pWInfo, regGosub, addrGosub);
8660
8661 sqlite3VdbeAddOp2(v, OP_Goto, 0, iBreak);
8662 sqlite3VdbeResolveLabel(v, addrGosub);
8663 VdbeNoopComment((v, "inner-loop subroutine"));
8664 sSort.labelOBLopt = 0;
8665 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest, iCont, iBreak);
8666 sqlite3VdbeResolveLabel(v, iCont);
8667 sqlite3VdbeAddOp1(v, OP_Return, regGosub);
8668 VdbeComment((v, "end inner-loop subroutine"));
8669 sqlite3VdbeResolveLabel(v, iBreak);
8670 }else
8671#endif /* SQLITE_OMIT_WINDOWFUNC */
8672 {
8673 /* Use the standard inner loop. */
8674 selectInnerLoop(pParse, p, -1, &sSort, &sDistinct, pDest,
8675 sqlite3WhereContinueLabel(pWInfo),
8676 sqlite3WhereBreakLabel(pWInfo));
8677
8678 /* End the database scan loop.
8679 */
8680 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8681 sqlite3WhereEnd(pWInfo);
8682 }
8683 }else{
8684 /* This case is for when there exist aggregate functions or a GROUP BY
8685 ** clause or both. tag-select-0800 */
8686 NameContext sNC; /* Name context for processing aggregate information */
8687 int iAMem; /* First Mem address for storing current GROUP BY */
8688 int iBMem; /* First Mem address for previous GROUP BY */
8689 int iUseFlag; /* Mem address holding flag indicating that at least
8690 ** one row of the input to the aggregator has been
8691 ** processed */
8692 int iAbortFlag; /* Mem address which causes query abort if positive */
8693 int groupBySort; /* Rows come from source in GROUP BY order */
8694 int addrEnd; /* End of processing for this SELECT */
8695 int sortPTab = 0; /* Pseudotable used to decode sorting results */
8696 int sortOut = 0; /* Output register from the sorter */
8697 int orderByGrp = 0; /* True if the GROUP BY and ORDER BY are the same */
8698
8699 /* Remove any and all aliases between the result set and the
8700 ** GROUP BY clause.
8701 */
8702 if( pGroupBy ){
8703 int k; /* Loop counter */
8704 struct ExprList_item *pItem; /* For looping over expression in a list */
8705
8706 for(k=p->pEList->nExpr, pItem=p->pEList->a; k>0; k--, pItem++){
8707 pItem->u.x.iAlias = 0;
8708 }
8709 for(k=pGroupBy->nExpr, pItem=pGroupBy->a; k>0; k--, pItem++){
8710 pItem->u.x.iAlias = 0;
8711 }
8712 assert( 66==sqlite3LogEst(100) );
8713 if( p->nSelectRow>66 ) p->nSelectRow = 66;
8714
8715 /* If there is both a GROUP BY and an ORDER BY clause and they are
8716 ** identical, then it may be possible to disable the ORDER BY clause
8717 ** on the grounds that the GROUP BY will cause elements to come out
8718 ** in the correct order. It also may not - the GROUP BY might use a
8719 ** database index that causes rows to be grouped together as required
8720 ** but not actually sorted. Either way, record the fact that the
8721 ** ORDER BY and GROUP BY clauses are the same by setting the orderByGrp
8722 ** variable. */
8723 if( sqlite3CopySortOrder(pGroupBy, sSort.pOrderBy)
8724 && sqlite3ExprListCompare(pGroupBy, sSort.pOrderBy, -1)==0
8725 ){
8726 orderByGrp = 1;
8727 }
8728 }else{
8729 assert( 0==sqlite3LogEst(1) );
8730 p->nSelectRow = 0;
8731 }
8732
8733 /* Create a label to jump to when we want to abort the query */
8734 addrEnd = sqlite3VdbeMakeLabel(pParse);
8735
8736 /* Convert TK_COLUMN nodes into TK_AGG_COLUMN and make entries in
8737 ** sAggInfo for all TK_AGG_FUNCTION nodes in expressions of the
8738 ** SELECT statement.
8739 */
8740 pAggInfo = sqlite3DbMallocZero(db, sizeof(*pAggInfo) );
8741 if( pAggInfo ){
8742 sqlite3ParserAddCleanup(pParse, agginfoFree, pAggInfo);
8743 testcase( pParse->earlyCleanup );
8744 }
8745 if( db->mallocFailed ){
8746 goto select_end;
8747 }
8748 pAggInfo->selId = p->selId;
8749#ifdef SQLITE_DEBUG
8750 pAggInfo->pSelect = p;
8751#endif
8752 memset(&sNC, 0, sizeof(sNC));
8753 sNC.pParse = pParse;
8754 sNC.pSrcList = pTabList;
8755 sNC.uNC.pAggInfo = pAggInfo;
8756 VVA_ONLY( sNC.ncFlags = NC_UAggInfo; )
8757 pAggInfo->nSortingColumn = pGroupBy ? pGroupBy->nExpr : 0;
8758 pAggInfo->pGroupBy = pGroupBy;
8759 sqlite3ExprAnalyzeAggList(&sNC, pEList);
8760 sqlite3ExprAnalyzeAggList(&sNC, sSort.pOrderBy);
8761 if( pHaving ){
8762 if( pGroupBy && OptimizationEnabled(db, SQLITE_HavingToWhere) ){
8763 assert( pWhere==p->pWhere );
8764 assert( pHaving==p->pHaving );
8765 assert( pGroupBy==p->pGroupBy );
8766 havingToWhere(pParse, p);
8767 pWhere = p->pWhere;
8768 }
8769 sqlite3ExprAnalyzeAggregates(&sNC, pHaving);
8770 }
8771 pAggInfo->nAccumulator = pAggInfo->nColumn;
8772 if( p->pGroupBy==0 && p->pHaving==0 && pAggInfo->nFunc==1 ){
8773 minMaxFlag = minMaxQuery(db, pAggInfo->aFunc[0].pFExpr, &pMinMaxOrderBy);
8774 }else{
8775 minMaxFlag = WHERE_ORDERBY_NORMAL;
8776 }
8777 analyzeAggFuncArgs(pAggInfo, &sNC);
8778 if( db->mallocFailed ) goto select_end;
8779#if TREETRACE_ENABLED
8780 if( sqlite3TreeTrace & 0x20 ){
8781 TREETRACE(0x20,pParse,p,("After aggregate analysis %p:\n", pAggInfo));
8782 sqlite3TreeViewSelect(0, p, 0);
8783 if( minMaxFlag ){
8784 sqlite3DebugPrintf("MIN/MAX Optimization (0x%02x) adds:\n", minMaxFlag);
8785 sqlite3TreeViewExprList(0, pMinMaxOrderBy, 0, "ORDERBY");
8786 }
8787 printAggInfo(pAggInfo);
8788 }
8789#endif
8790
8791
8792 /* Processing for aggregates with GROUP BY is very different and
8793 ** much more complex than aggregates without a GROUP BY. tag-select-0810
8794 */
8795 if( pGroupBy ){
8796 KeyInfo *pKeyInfo; /* Keying information for the group by clause */
8797 int addr1; /* A-vs-B comparison jump */
8798 int addrOutputRow; /* Start of subroutine that outputs a result row */
8799 int regOutputRow; /* Return address register for output subroutine */
8800 int addrSetAbort; /* Set the abort flag and return */
8801 int addrTopOfLoop; /* Top of the input loop */
8802 int addrSortingIdx; /* The OP_OpenEphemeral for the sorting index */
8803 int addrReset; /* Subroutine for resetting the accumulator */
8804 int regReset; /* Return address register for reset subroutine */
8805 ExprList *pDistinct = 0;
8806 u16 distFlag = 0;
8807 int eDist = WHERE_DISTINCT_NOOP;
8808
8809 if( pAggInfo->nFunc==1
8810 && pAggInfo->aFunc[0].iDistinct>=0
8811 && ALWAYS(pAggInfo->aFunc[0].pFExpr!=0)
8812 && ALWAYS(ExprUseXList(pAggInfo->aFunc[0].pFExpr))
8813 && pAggInfo->aFunc[0].pFExpr->x.pList!=0
8814 ){
8815 Expr *pExpr = pAggInfo->aFunc[0].pFExpr->x.pList->a[0].pExpr;
8816 pExpr = sqlite3ExprDup(db, pExpr, 0);
8817 pDistinct = sqlite3ExprListDup(db, pGroupBy, 0);
8818 pDistinct = sqlite3ExprListAppend(pParse, pDistinct, pExpr);
8819 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
8820 }
8821
8822 /* If there is a GROUP BY clause we might need a sorting index to
8823 ** implement it. Allocate that sorting index now. If it turns out
8824 ** that we do not need it after all, the OP_SorterOpen instruction
8825 ** will be converted into a Noop.
8826 */
8827 pAggInfo->sortingIdx = pParse->nTab++;
8828 pKeyInfo = sqlite3KeyInfoFromExprList(pParse, pGroupBy,
8829 0, pAggInfo->nColumn);
8830 addrSortingIdx = sqlite3VdbeAddOp4(v, OP_SorterOpen,
8831 pAggInfo->sortingIdx, pAggInfo->nSortingColumn,
8832 0, (char*)pKeyInfo, P4_KEYINFO);
8833
8834 /* Initialize memory locations used by GROUP BY aggregate processing
8835 */
8836 iUseFlag = ++pParse->nMem;
8837 iAbortFlag = ++pParse->nMem;
8838 regOutputRow = ++pParse->nMem;
8839 addrOutputRow = sqlite3VdbeMakeLabel(pParse);
8840 regReset = ++pParse->nMem;
8841 addrReset = sqlite3VdbeMakeLabel(pParse);
8842 iAMem = pParse->nMem + 1;
8843 pParse->nMem += pGroupBy->nExpr;
8844 iBMem = pParse->nMem + 1;
8845 pParse->nMem += pGroupBy->nExpr;
8846 sqlite3VdbeAddOp2(v, OP_Integer, 0, iAbortFlag);
8847 VdbeComment((v, "clear abort flag"));
8848 sqlite3VdbeAddOp3(v, OP_Null, 0, iAMem, iAMem+pGroupBy->nExpr-1);
8849 sqlite3ExprNullRegisterRange(pParse, iAMem, pGroupBy->nExpr);
8850
8851 /* Begin a loop that will extract all source rows in GROUP BY order.
8852 ** This might involve two separate loops with an OP_Sort in between, or
8853 ** it might be a single loop that uses an index to extract information
8854 ** in the right order to begin with.
8855 */
8856 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
8857 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
8858 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pGroupBy, pDistinct,
8859 p, (sDistinct.isTnct==2 ? WHERE_DISTINCTBY : WHERE_GROUPBY)
8860 | (orderByGrp ? WHERE_SORTBYGROUP : 0) | distFlag, 0
8861 );
8862 if( pWInfo==0 ){
8863 sqlite3ExprListDelete(db, pDistinct);
8864 goto select_end;
8865 }
8866 if( pParse->pIdxEpr ){
8867 optimizeAggregateUseOfIndexedExpr(pParse, p, pAggInfo, &sNC);
8868 }
8869 assignAggregateRegisters(pParse, pAggInfo);
8870 eDist = sqlite3WhereIsDistinct(pWInfo);
8871 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
8872 if( sqlite3WhereIsOrdered(pWInfo)==pGroupBy->nExpr ){
8873 /* The optimizer is able to deliver rows in group by order so
8874 ** we do not have to sort. The OP_OpenEphemeral table will be
8875 ** cancelled later because we still need to use the pKeyInfo
8876 */
8877 groupBySort = 0;
8878 }else{
8879 /* Rows are coming out in undetermined order. We have to push
8880 ** each row into a sorting index, terminate the first loop,
8881 ** then loop over the sorting index in order to get the output
8882 ** in sorted order
8883 */
8884 int regBase;
8885 int regRecord;
8886 int nCol;
8887 int nGroupBy;
8888
8889#ifdef SQLITE_ENABLE_STMT_SCANSTATUS
8890 int addrExp; /* Address of OP_Explain instruction */
8891#endif
8892 ExplainQueryPlan2(addrExp, (pParse, 0, "USE TEMP B-TREE FOR %s",
8893 (sDistinct.isTnct && (p->selFlags&SF_Distinct)==0) ?
8894 "DISTINCT" : "GROUP BY"
8895 ));
8896
8897 groupBySort = 1;
8898 nGroupBy = pGroupBy->nExpr;
8899 nCol = nGroupBy;
8900 j = nGroupBy;
8901 for(i=0; i<pAggInfo->nColumn; i++){
8902 if( pAggInfo->aCol[i].iSorterColumn>=j ){
8903 nCol++;
8904 j++;
8905 }
8906 }
8907 regBase = sqlite3GetTempRange(pParse, nCol);
8908 sqlite3ExprCodeExprList(pParse, pGroupBy, regBase, 0, 0);
8909 j = nGroupBy;
8910 pAggInfo->directMode = 1;
8911 for(i=0; i<pAggInfo->nColumn; i++){
8912 struct AggInfo_col *pCol = &pAggInfo->aCol[i];
8913 if( pCol->iSorterColumn>=j ){
8914 sqlite3ExprCode(pParse, pCol->pCExpr, j + regBase);
8915 j++;
8916 }
8917 }
8918 pAggInfo->directMode = 0;
8919 regRecord = sqlite3GetTempReg(pParse);
8920 sqlite3VdbeScanStatusCounters(v, addrExp, 0, sqlite3VdbeCurrentAddr(v));
8921 sqlite3VdbeAddOp3(v, OP_MakeRecord, regBase, nCol, regRecord);
8922 sqlite3VdbeAddOp2(v, OP_SorterInsert, pAggInfo->sortingIdx, regRecord);
8923 sqlite3VdbeScanStatusRange(v, addrExp, sqlite3VdbeCurrentAddr(v)-2, -1);
8924 sqlite3ReleaseTempReg(pParse, regRecord);
8925 sqlite3ReleaseTempRange(pParse, regBase, nCol);
8926 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
8927 sqlite3WhereEnd(pWInfo);
8928 pAggInfo->sortingIdxPTab = sortPTab = pParse->nTab++;
8929 sortOut = sqlite3GetTempReg(pParse);
8930 sqlite3VdbeScanStatusCounters(v, addrExp, sqlite3VdbeCurrentAddr(v), 0);
8931 sqlite3VdbeAddOp3(v, OP_OpenPseudo, sortPTab, sortOut, nCol);
8932 sqlite3VdbeAddOp2(v, OP_SorterSort, pAggInfo->sortingIdx, addrEnd);
8933 VdbeComment((v, "GROUP BY sort")); VdbeCoverage(v);
8934 pAggInfo->useSortingIdx = 1;
8935 sqlite3VdbeScanStatusRange(v, addrExp, -1, sortPTab);
8936 sqlite3VdbeScanStatusRange(v, addrExp, -1, pAggInfo->sortingIdx);
8937 }
8938
8939 /* If there are entries in pAgggInfo->aFunc[] that contain subexpressions
8940 ** that are indexed (and that were previously identified and tagged
8941 ** in optimizeAggregateUseOfIndexedExpr()) then those subexpressions
8942 ** must now be converted into a TK_AGG_COLUMN node so that the value
8943 ** is correctly pulled from the index rather than being recomputed. */
8944 if( pParse->pIdxEpr ){
8945 aggregateConvertIndexedExprRefToColumn(pAggInfo);
8946#if TREETRACE_ENABLED
8947 if( sqlite3TreeTrace & 0x20 ){
8948 TREETRACE(0x20, pParse, p,
8949 ("AggInfo function expressions converted to reference index\n"));
8950 sqlite3TreeViewSelect(0, p, 0);
8951 printAggInfo(pAggInfo);
8952 }
8953#endif
8954 }
8955
8956 /* If the index or temporary table used by the GROUP BY sort
8957 ** will naturally deliver rows in the order required by the ORDER BY
8958 ** clause, cancel the ephemeral table open coded earlier.
8959 **
8960 ** This is an optimization - the correct answer should result regardless.
8961 ** Use the SQLITE_GroupByOrder flag with SQLITE_TESTCTRL_OPTIMIZER to
8962 ** disable this optimization for testing purposes. */
8963 if( orderByGrp && OptimizationEnabled(db, SQLITE_GroupByOrder)
8964 && (groupBySort || sqlite3WhereIsSorted(pWInfo))
8965 ){
8966 sSort.pOrderBy = 0;
8967 sqlite3VdbeChangeToNoop(v, sSort.addrSortIndex);
8968 }
8969
8970 /* Evaluate the current GROUP BY terms and store in b0, b1, b2...
8971 ** (b0 is memory location iBMem+0, b1 is iBMem+1, and so forth)
8972 ** Then compare the current GROUP BY terms against the GROUP BY terms
8973 ** from the previous row currently stored in a0, a1, a2...
8974 */
8975 addrTopOfLoop = sqlite3VdbeCurrentAddr(v);
8976 if( groupBySort ){
8977 sqlite3VdbeAddOp3(v, OP_SorterData, pAggInfo->sortingIdx,
8978 sortOut, sortPTab);
8979 }
8980 for(j=0; j<pGroupBy->nExpr; j++){
8981 int iOrderByCol = pGroupBy->a[j].u.x.iOrderByCol;
8982
8983 if( groupBySort ){
8984 sqlite3VdbeAddOp3(v, OP_Column, sortPTab, j, iBMem+j);
8985 }else{
8986 pAggInfo->directMode = 1;
8987 sqlite3ExprCode(pParse, pGroupBy->a[j].pExpr, iBMem+j);
8988 }
8989
8990 if( iOrderByCol ){
8991 Expr *pX = p->pEList->a[iOrderByCol-1].pExpr;
8992 Expr *pBase = sqlite3ExprSkipCollateAndLikely(pX);
8993 while( ALWAYS(pBase!=0) && pBase->op==TK_IF_NULL_ROW ){
8994 pX = pBase->pLeft;
8995 pBase = sqlite3ExprSkipCollateAndLikely(pX);
8996 }
8997 if( ALWAYS(pBase!=0)
8998 && pBase->op!=TK_AGG_COLUMN
8999 && pBase->op!=TK_REGISTER
9000 ){
9001 sqlite3ExprToRegister(pX, iAMem+j);
9002 }
9003 }
9004 }
9005 sqlite3VdbeAddOp4(v, OP_Compare, iAMem, iBMem, pGroupBy->nExpr,
9006 (char*)sqlite3KeyInfoRef(pKeyInfo), P4_KEYINFO);
9007 addr1 = sqlite3VdbeCurrentAddr(v);
9008 sqlite3VdbeAddOp3(v, OP_Jump, addr1+1, 0, addr1+1); VdbeCoverage(v);
9009
9010 /* Generate code that runs whenever the GROUP BY changes.
9011 ** Changes in the GROUP BY are detected by the previous code
9012 ** block. If there were no changes, this block is skipped.
9013 **
9014 ** This code copies current group by terms in b0,b1,b2,...
9015 ** over to a0,a1,a2. It then calls the output subroutine
9016 ** and resets the aggregate accumulator registers in preparation
9017 ** for the next GROUP BY batch.
9018 */
9019 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
9020 VdbeComment((v, "output one row of %d", p->selId));
9021 sqlite3ExprCodeMove(pParse, iBMem, iAMem, pGroupBy->nExpr);
9022 sqlite3VdbeAddOp2(v, OP_IfPos, iAbortFlag, addrEnd); VdbeCoverage(v);
9023 VdbeComment((v, "check abort flag"));
9024 sqlite3VdbeAddOp2(v, OP_Gosub, regReset, addrReset);
9025 VdbeComment((v, "reset accumulator %d", p->selId));
9026
9027 /* Update the aggregate accumulators based on the content of
9028 ** the current row
9029 */
9030 sqlite3VdbeJumpHere(v, addr1);
9031 updateAccumulator(pParse, iUseFlag, pAggInfo, eDist);
9032 sqlite3VdbeAddOp2(v, OP_Integer, 1, iUseFlag);
9033 VdbeComment((v, "indicate data in accumulator %d", p->selId));
9034
9035 /* End of the loop
9036 */
9037 if( groupBySort ){
9038 sqlite3VdbeAddOp2(v, OP_SorterNext, pAggInfo->sortingIdx,addrTopOfLoop);
9039 VdbeCoverage(v);
9040 }else{
9041 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
9042 sqlite3WhereEnd(pWInfo);
9043 sqlite3VdbeChangeToNoop(v, addrSortingIdx);
9044 }
9045 sqlite3ExprListDelete(db, pDistinct);
9046
9047 /* Output the final row of result
9048 */
9049 sqlite3VdbeAddOp2(v, OP_Gosub, regOutputRow, addrOutputRow);
9050 VdbeComment((v, "output final row of %d", p->selId));
9051
9052 /* Jump over the subroutines
9053 */
9054 sqlite3VdbeGoto(v, addrEnd);
9055
9056 /* Generate a subroutine that outputs a single row of the result
9057 ** set. This subroutine first looks at the iUseFlag. If iUseFlag
9058 ** is less than or equal to zero, the subroutine is a no-op. If
9059 ** the processing calls for the query to abort, this subroutine
9060 ** increments the iAbortFlag memory location before returning in
9061 ** order to signal the caller to abort.
9062 */
9063 addrSetAbort = sqlite3VdbeCurrentAddr(v);
9064 sqlite3VdbeAddOp2(v, OP_Integer, 1, iAbortFlag);
9065 VdbeComment((v, "set abort flag"));
9066 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
9067 sqlite3VdbeResolveLabel(v, addrOutputRow);
9068 addrOutputRow = sqlite3VdbeCurrentAddr(v);
9069 sqlite3VdbeAddOp2(v, OP_IfPos, iUseFlag, addrOutputRow+2);
9070 VdbeCoverage(v);
9071 VdbeComment((v, "Groupby result generator entry point %d", p->selId));
9072 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
9073 finalizeAggFunctions(pParse, pAggInfo);
9074 sqlite3ExprIfFalse(pParse, pHaving, addrOutputRow+1, SQLITE_JUMPIFNULL);
9075 selectInnerLoop(pParse, p, -1, &sSort,
9076 &sDistinct, pDest,
9077 addrOutputRow+1, addrSetAbort);
9078 sqlite3VdbeAddOp1(v, OP_Return, regOutputRow);
9079 VdbeComment((v, "end groupby result generator %d", p->selId));
9080
9081 /* Generate a subroutine that will reset the group-by accumulator
9082 */
9083 sqlite3VdbeResolveLabel(v, addrReset);
9084 resetAccumulator(pParse, pAggInfo);
9085 sqlite3VdbeAddOp2(v, OP_Integer, 0, iUseFlag);
9086 VdbeComment((v, "indicate accumulator %d empty", p->selId));
9087 sqlite3VdbeAddOp1(v, OP_Return, regReset);
9088
9089 if( distFlag!=0 && eDist!=WHERE_DISTINCT_NOOP ){
9090 struct AggInfo_func *pF = &pAggInfo->aFunc[0];
9091 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
9092 }
9093 } /* endif pGroupBy. Begin aggregate queries without GROUP BY: */
9094 else {
9095 /* Aggregate functions without GROUP BY. tag-select-0820 */
9096 Table *pTab;
9097 if( (pTab = isSimpleCount(p, pAggInfo))!=0 ){
9098 /* tag-select-0821
9099 **
9100 ** If isSimpleCount() returns a pointer to a Table structure, then
9101 ** the SQL statement is of the form:
9102 **
9103 ** SELECT count(*) FROM <tbl>
9104 **
9105 ** where the Table structure returned represents table <tbl>.
9106 **
9107 ** This statement is so common that it is optimized specially. The
9108 ** OP_Count instruction is executed either on the intkey table that
9109 ** contains the data for table <tbl> or on one of its indexes. It
9110 ** is better to execute the op on an index, as indexes are almost
9111 ** always spread across less pages than their corresponding tables.
9112 */
9113 const int iDb = sqlite3SchemaToIndex(pParse->db, pTab->pSchema);
9114 const int iCsr = pParse->nTab++; /* Cursor to scan b-tree */
9115 Index *pIdx; /* Iterator variable */
9116 KeyInfo *pKeyInfo = 0; /* Keyinfo for scanned index */
9117 Index *pBest = 0; /* Best index found so far */
9118 Pgno iRoot = pTab->tnum; /* Root page of scanned b-tree */
9119
9120 sqlite3CodeVerifySchema(pParse, iDb);
9121 sqlite3TableLock(pParse, iDb, pTab->tnum, 0, pTab->zName);
9122
9123 /* Search for the index that has the lowest scan cost.
9124 **
9125 ** (2011-04-15) Do not do a full scan of an unordered index.
9126 **
9127 ** (2013-10-03) Do not count the entries in a partial index.
9128 **
9129 ** In practice the KeyInfo structure will not be used. It is only
9130 ** passed to keep OP_OpenRead happy.
9131 */
9132 if( !HasRowid(pTab) ) pBest = sqlite3PrimaryKeyIndex(pTab);
9133 if( !p->pSrc->a[0].fg.notIndexed ){
9134 for(pIdx=pTab->pIndex; pIdx; pIdx=pIdx->pNext){
9135 if( pIdx->bUnordered==0
9136 && pIdx->szIdxRow<pTab->szTabRow
9137 && pIdx->pPartIdxWhere==0
9138 && (!pBest || pIdx->szIdxRow<pBest->szIdxRow)
9139 ){
9140 pBest = pIdx;
9141 }
9142 }
9143 }
9144 if( pBest ){
9145 iRoot = pBest->tnum;
9146 pKeyInfo = sqlite3KeyInfoOfIndex(pParse, pBest);
9147 }
9148
9149 /* Open a read-only cursor, execute the OP_Count, close the cursor. */
9150 sqlite3VdbeAddOp4Int(v, OP_OpenRead, iCsr, (int)iRoot, iDb, 1);
9151 if( pKeyInfo ){
9152 sqlite3VdbeChangeP4(v, -1, (char *)pKeyInfo, P4_KEYINFO);
9153 }
9154 assignAggregateRegisters(pParse, pAggInfo);
9155 sqlite3VdbeAddOp2(v, OP_Count, iCsr, AggInfoFuncReg(pAggInfo,0));
9156 sqlite3VdbeAddOp1(v, OP_Close, iCsr);
9157 explainSimpleCount(pParse, pTab, pBest);
9158 }else{
9159 /* The general case of an aggregate query without GROUP BY
9160 ** tag-select-0822 */
9161 int regAcc = 0; /* "populate accumulators" flag */
9162 ExprList *pDistinct = 0;
9163 u16 distFlag = 0;
9164 int eDist;
9165
9166 /* If there are accumulator registers but no min() or max() functions
9167 ** without FILTER clauses, allocate register regAcc. Register regAcc
9168 ** will contain 0 the first time the inner loop runs, and 1 thereafter.
9169 ** The code generated by updateAccumulator() uses this to ensure
9170 ** that the accumulator registers are (a) updated only once if
9171 ** there are no min() or max functions or (b) always updated for the
9172 ** first row visited by the aggregate, so that they are updated at
9173 ** least once even if the FILTER clause means the min() or max()
9174 ** function visits zero rows. */
9175 if( pAggInfo->nAccumulator ){
9176 for(i=0; i<pAggInfo->nFunc; i++){
9177 if( ExprHasProperty(pAggInfo->aFunc[i].pFExpr, EP_WinFunc) ){
9178 continue;
9179 }
9180 if( pAggInfo->aFunc[i].pFunc->funcFlags&SQLITE_FUNC_NEEDCOLL ){
9181 break;
9182 }
9183 }
9184 if( i==pAggInfo->nFunc ){
9185 regAcc = ++pParse->nMem;
9186 sqlite3VdbeAddOp2(v, OP_Integer, 0, regAcc);
9187 }
9188 }else if( pAggInfo->nFunc==1 && pAggInfo->aFunc[0].iDistinct>=0 ){
9189 assert( ExprUseXList(pAggInfo->aFunc[0].pFExpr) );
9190 pDistinct = pAggInfo->aFunc[0].pFExpr->x.pList;
9191 distFlag = pDistinct ? (WHERE_WANT_DISTINCT|WHERE_AGG_DISTINCT) : 0;
9192 }
9193 assignAggregateRegisters(pParse, pAggInfo);
9194
9195 /* This case runs if the aggregate has no GROUP BY clause. The
9196 ** processing is much simpler since there is only a single row
9197 ** of output.
9198 */
9199 assert( p->pGroupBy==0 );
9200 resetAccumulator(pParse, pAggInfo);
9201
9202 /* If this query is a candidate for the min/max optimization, then
9203 ** minMaxFlag will have been previously set to either
9204 ** WHERE_ORDERBY_MIN or WHERE_ORDERBY_MAX and pMinMaxOrderBy will
9205 ** be an appropriate ORDER BY expression for the optimization.
9206 */
9207 assert( minMaxFlag==WHERE_ORDERBY_NORMAL || pMinMaxOrderBy!=0 );
9208 assert( pMinMaxOrderBy==0 || pMinMaxOrderBy->nExpr==1 );
9209
9210 TREETRACE(0x2,pParse,p,("WhereBegin\n"));
9211 pWInfo = sqlite3WhereBegin(pParse, pTabList, pWhere, pMinMaxOrderBy,
9212 pDistinct, p, minMaxFlag|distFlag, 0);
9213 if( pWInfo==0 ){
9214 goto select_end;
9215 }
9216 TREETRACE(0x2,pParse,p,("WhereBegin returns\n"));
9217 eDist = sqlite3WhereIsDistinct(pWInfo);
9218 updateAccumulator(pParse, regAcc, pAggInfo, eDist);
9219 if( eDist!=WHERE_DISTINCT_NOOP ){
9220 struct AggInfo_func *pF = pAggInfo->aFunc;
9221 if( pF ){
9222 fixDistinctOpenEph(pParse, eDist, pF->iDistinct, pF->iDistAddr);
9223 }
9224 }
9225
9226 if( regAcc ) sqlite3VdbeAddOp2(v, OP_Integer, 1, regAcc);
9227 if( minMaxFlag ){
9228 sqlite3WhereMinMaxOptEarlyOut(v, pWInfo);
9229 }
9230 TREETRACE(0x2,pParse,p,("WhereEnd\n"));
9231 sqlite3WhereEnd(pWInfo);
9232 finalizeAggFunctions(pParse, pAggInfo);
9233 }
9234
9235 sSort.pOrderBy = 0;
9236 sqlite3ExprIfFalse(pParse, pHaving, addrEnd, SQLITE_JUMPIFNULL);
9237 selectInnerLoop(pParse, p, -1, 0, 0,
9238 pDest, addrEnd, addrEnd);
9239 }
9240 sqlite3VdbeResolveLabel(v, addrEnd);
9241
9242 } /* endif aggregate query */
9243
9244 if( sDistinct.eTnctType==WHERE_DISTINCT_UNORDERED ){
9245 explainTempTable(pParse, "DISTINCT");
9246 }
9247
9248 /* If there is an ORDER BY clause, then we need to sort the results
9249 ** and send them to the callback one by one. tag-select-0900
9250 */
9251 if( sSort.pOrderBy ){
9252 assert( p->pEList==pEList );
9253 generateSortTail(pParse, p, &sSort, pEList->nExpr, pDest);
9254 }
9255
9256 /* Jump here to skip this query
9257 */
9258 sqlite3VdbeResolveLabel(v, iEnd);
9259
9260 /* The SELECT has been coded. If there is an error in the Parse structure,
9261 ** set the return code to 1. Otherwise 0. */
9262 rc = (pParse->nErr>0);
9263
9264 /* Control jumps to here if an error is encountered above, or upon
9265 ** successful coding of the SELECT.
9266 */
9267select_end:
9268 assert( db->mallocFailed==0 || db->mallocFailed==1 );
9269 assert( db->mallocFailed==0 || pParse->nErr!=0 );
9270 sqlite3ExprListDelete(db, pMinMaxOrderBy);
9271#ifdef SQLITE_DEBUG
9272 /* Internal self-checks. tag-select-1000 */
9273 if( pAggInfo && !db->mallocFailed ){
9274#if TREETRACE_ENABLED
9275 if( sqlite3TreeTrace & 0x20 ){
9276 TREETRACE(0x20,pParse,p,("Finished with AggInfo\n"));
9277 printAggInfo(pAggInfo);
9278 }
9279#endif
9280 for(i=0; i<pAggInfo->nColumn; i++){
9281 Expr *pExpr = pAggInfo->aCol[i].pCExpr;
9282 if( pExpr==0 ) continue;
9283 assert( pExpr->pAggInfo==pAggInfo );
9284 assert( pExpr->iAgg==i );
9285 }
9286 for(i=0; i<pAggInfo->nFunc; i++){
9287 Expr *pExpr = pAggInfo->aFunc[i].pFExpr;
9288 assert( pExpr!=0 );
9289 assert( pExpr->pAggInfo==pAggInfo );
9290 assert( pExpr->iAgg==i );
9291 }
9292 }
9293#endif
9294
9295#if TREETRACE_ENABLED
9296 TREETRACE(0x1,pParse,p,("end processing\n"));
9297 if( (sqlite3TreeTrace & 0x40000)!=0 && ExplainQueryPlanParent(pParse)==0 ){
9298 sqlite3TreeViewSelect(0, p, 0);
9299 }
9300#endif
9301 ExplainQueryPlanPop(pParse);
9302 return rc;
9303}